From 7dab2b31d99fd114239690dfbebaa20cc917e7fa Mon Sep 17 00:00:00 2001 From: Karan Date: Wed, 7 Oct 2026 23:27:36 -0400 Subject: [PATCH 01/25] docs: add AI-agent documentation (AGENTS.md, CLAUDE.md, docs/agents) Verified against 654d822 (situation-v1): an index, overview, repo map, glossary, playbooks and 15 subsystem docs, each fact-checked against the code, plus a root AGENTS.md with ground rules, verified commands and a definition of done. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 192 +++ CLAUDE.md | 3 + docs/agents/README.md | 185 +++ docs/agents/demos.md | 540 +++++++++ docs/agents/extension-and-benchmarks.md | 559 +++++++++ docs/agents/genclass-model-lineage.md | 534 +++++++++ docs/agents/glossary.md | 445 +++++++ docs/agents/model-io-contract.md | 685 +++++++++++ docs/agents/overview.md | 418 +++++++ docs/agents/playbooks.md | 774 ++++++++++++ docs/agents/repo-map.md | 856 +++++++++++++ docs/agents/runtime/build-test-release.md | 550 +++++++++ docs/agents/runtime/decide-policy-actions.md | 724 +++++++++++ docs/agents/runtime/devtools.md | 712 +++++++++++ docs/agents/runtime/learn-situation-triage.md | 1056 +++++++++++++++++ docs/agents/runtime/model-host.md | 670 +++++++++++ docs/agents/runtime/observe-and-trace.md | 791 ++++++++++++ .../runtime/public-api-and-lifecycle.md | 641 ++++++++++ docs/agents/runtime/state-and-adapters.md | 653 ++++++++++ docs/agents/sim.md | 823 +++++++++++++ docs/agents/status-and-known-issues.md | 642 ++++++++++ docs/agents/training.md | 523 ++++++++ 22 files changed, 12976 insertions(+) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 docs/agents/README.md create mode 100644 docs/agents/demos.md create mode 100644 docs/agents/extension-and-benchmarks.md create mode 100644 docs/agents/genclass-model-lineage.md create mode 100644 docs/agents/glossary.md create mode 100644 docs/agents/model-io-contract.md create mode 100644 docs/agents/overview.md create mode 100644 docs/agents/playbooks.md create mode 100644 docs/agents/repo-map.md create mode 100644 docs/agents/runtime/build-test-release.md create mode 100644 docs/agents/runtime/decide-policy-actions.md create mode 100644 docs/agents/runtime/devtools.md create mode 100644 docs/agents/runtime/learn-situation-triage.md create mode 100644 docs/agents/runtime/model-host.md create mode 100644 docs/agents/runtime/observe-and-trace.md create mode 100644 docs/agents/runtime/public-api-and-lifecycle.md create mode 100644 docs/agents/runtime/state-and-adapters.md create mode 100644 docs/agents/sim.md create mode 100644 docs/agents/status-and-known-issues.md create mode 100644 docs/agents/training.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..44d92c88 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,192 @@ +# AGENTS.md + +Root entry point for AI coding agents in GenClass-lib. Verified against commit 654d822 (2026-10-07). +The code is the source of truth: if this file or any other doc disagrees with it, the code wins. + +## 1. What this repo is + +- `@genclass/runtime` (`packages/runtime/`) is an npm library for self-healing web apps. It observes a running app + (fetch/XHR/WebSocket, user actions, timers, state stores, errors, causality) and computes generic facts. +- For salient situations a small local model (ONNX in a Web Worker, WebGPU or WASM) chooses a diagnosis and an action. + Actions are minimal (only `discard`, a late revert, `rollback` and custom actions with `onUndo` can be undone), and they + pass a precision-first policy gate. Without a model the runtime only observes. +- `sim/` generates training data by driving the real runtime. `training/` trains and exports the model, and `demos/` holds six evaluation apps. +- `jev_local/`, `extension/`, `bench/`, `results/` and the legacy `docs/*.md` are the older GenClass model, Chrome extension and benchmarks that the runtime builds on. +- npm workspaces: `packages/*`, `sim`, `demos`. Branches `main`, `origin/main` and `origin/runtime` all point at 654d822. + +Read next: [docs/agents/README.md](docs/agents/README.md) (index: which doc answers which question), then +[docs/agents/overview.md](docs/agents/overview.md) (how the parts fit together). Also: +[repo-map](docs/agents/repo-map.md), [glossary](docs/agents/glossary.md), [playbooks](docs/agents/playbooks.md), and +[status-and-known-issues](docs/agents/status-and-known-issues.md) before you change anything. + +## 2. Status in brief + +- `@genclass/runtime@0.1.0-alpha.0` is on npm (per `OPEN_TASKS.md`; git tag `v0.1.0-alpha.0` = 654d822). **It only observes.** + `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which is + not published yet (`packages/runtime-model/` holds only `MODEL_CARD.md`). So a default `GenClass.init()` ends with model status `error` and + prints `[GenClass] Model unavailable (...); observing only.` From then on it never holds a write or takes an action. +- The runtime source is frozen at tag `situation-v1` (1a77558): `git diff situation-v1 HEAD -- packages/runtime/src` is + empty. SIM phase A (600,676 rows) came from that code. Final training round 1 was launched, and the repo has no results from it. +- Next (`OPEN_TASKS.md`): choose the shipping model (R17 and/or R32), publish `@genclass/runtime-model@0.1.0` and its GitHub + release, publish `@genclass/runtime@0.1.0`, add CI, then re-run the demos with the trained model. +- The repo has no CI (no `.github/`) and no committed root `package-lock.json`. Demo results so far use the v0.1 GenClass model + (a general classifier, not trained for runtime decisions). +- `demos/src/server/data/cities.ts` is not in git (root `.gitignore` rule `data/`), so a fresh clone cannot build or typecheck the demos. +- Open product risks (`demos/NEEDS.md` §1, §2, §5, all still open in code): held writes can land after a newer user write, holds add + latency, and `retry` is offered for non-idempotent requests. Details: [status doc](docs/agents/status-and-known-issues.md). + +## 3. Ground rules (binding; `docs/runtime/CONTRACT.md` §0 and §0.5) + +CONTRACT: "If something here is wrong, tell the lead; do not silently diverge." The workstream roles in the docs +(lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule says "ask the lead", ask the user. + +1. **No hardcoded bug rules in the runtime (§0 rule 1).** The runtime may compute generic, uniform facts and may triage, which means + deciding whether a situation is worth asking the model about. It must never map a fact pattern to a diagnosis or an action with an if/then. Diagnoses and + actions come from the model. In code, triage is `facts.every((f) => f.neutral)` in `packages/runtime/src/runtime.ts` -> + `RuntimeImpl.trigger`. Actions are chosen only by `packages/runtime/src/decide/policy.ts` -> `gate` from model probabilities. + `packages/runtime/src/situation/build.ts` -> `builtinApplicable` says only whether an action *can* run. +2. **Train/runtime parity (§0 rule 2).** There is exactly one implementation of situation building and serialization: + `packages/runtime/src/situation/*`. The sim drives the real runtime (`sim/src/run/rt.ts` -> `realRuntimeFactory`), and + `training/curriculum/rt.py` is a Python port of it. The situation format is frozen at tag `situation-v1`. **Any change to + situation text, facts, questions, action/diagnosis wording, `packages/runtime/src/util.ts` formatting or op/event names + invalidates the SIM data and the trained model.** Do not make such a change without the user's explicit go-ahead. +3. **Determinism (§0 rule 3).** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly, and never + schedules with the global `setTimeout`. It uses the injected `Clock` (`packages/runtime/src/clock.ts` -> `browserClock` + captures the real timers at module load). IDs come from counters (e.g. `OpRegistry` `nextId`, action ids `a`). + Same inputs give byte-identical situations. Known exceptions, none of which touch situation text: + `packages/runtime/src/model/engine.ts` defaults `now` to `performance.now()` (timing only), + `packages/runtime/src/model/host.ts` -> `scheduleIdle` uses `requestIdleCallback`, and + `packages/runtime/src/devtools/index.ts` captures the global `requestAnimationFrame` and `setTimeout` at module load + (`rawRaf`, `rawSetTimeout`: render flushes, the Copy-button reset and the no-plugin timer fallback). +4. **Honest-evaluation separation (§0 rule 4).** `sim/` and `demos/` never read or model each other. The sim never models a + demo. Demos contain nothing beyond a normal integration: stores, optional resync handlers, and custom actions or questions only in + the extensibility demo. Do not copy code, scenarios or knowledge between the two. +5. **Precision first, fail open (§0 rule 1, §0.5 principle 1, §8, §11).** The default mode (`guard`) takes only minimal guard-tier + actions (`discard`, `defer`, `coalesce`, `delay`; only `discard` has an undo, so CONTRACT's "reversible" is drift: + [decide-policy-actions](docs/agents/runtime/decide-policy-actions.md) Drift 10). An action runs only when the summed calibrated + probability of the permitted non-passive actions reaches the candidate action's tier threshold (guard-tier 0.9, heal-tier 0.8; + `packages/runtime/src/decide/policy.ts` -> `gate`), and the model's top diagnosis is not `expected`. If the model is unavailable, loading, late or erroring, the runtime takes the passive action. Held writes and + requests are released when the hold budget expires. False interventions on clean runs are a first-class metric. +6. **Dependencies (§0 rule 6).** `onnxruntime-web` is the only runtime `dependency` (`packages/runtime/package.json`). Do not + add another runtime dependency without asking. React, Redux and Zustand are optional peers. +7. **TypeScript strict, ESM only (§0 rule 6).** `tsconfig.base.json` sets `strict`, `verbatimModuleSyntax` and `isolatedModules`. + The package is ESM-only (no `require` export). `packages/runtime/tsconfig.json` has `types: []`, so `src/` must not use Node APIs. +8. **Leave legacy content alone (§1).** "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is." This + covers the pre-runtime GenClass content: `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, the legacy `docs/*.md`, + `docs/benchmax-research/` and the legacy scripts in `scripts/`. It does not cover `docs/runtime/`, `docs/agents/` or + `scripts/vm.sh`. Edit legacy content only when the user asks ([playbooks](docs/agents/playbooks.md) recipe 27). +9. **REVIEW tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make them pass. Fix `src/` instead. + +## 4. Where to run things + +- **The team's rule (CONTRACT §0 rule 5).** "The Mac only edits files." Every build, test, browser and model run went to the Azure `train` VM through + `scripts/vm.sh` in a per-workstream slot, because the original author's Mac has 8 GB RAM. `vm.sh` needs + `~/.jev-local/azure_hosts`, `~/.ssh/jev_azure` and GNU `timeout`, none of which are in the repo. +- **Policy for agents (set when these docs were written, 2026-10-07).** On other machines, `npm install`, typecheck, build and unit tests are + light and were verified locally (macOS, 16 GB RAM, Node v25.6.0, npm 11.8.0). You may run the verified commands in §5. +- **Ask the user first** before running any of these: the sim (generation, `sim/scripts/*`), training (`training/*.sh`, any Python training or eval), + Playwright (`npm run test:browser`, the UI spec, `test/smoke/smoke.sh`), model downloads (`genclass-runtime fetch-model`, + `demos/scripts/fetch-model.sh`), the demos' eval (`npm run eval` in `demos/`, `demos/scripts/vm-eval.sh`), or any script that touches Azure + (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). +- **Side effects of `npm install` at the root.** It creates an untracked root `package-lock.json` (never committed; whether to commit + one is the user's decision). It also chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, which git reports as a mode change + (committed mode is 644). Revert it with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. + +## 5. Commands + +Verified when these docs were written, 2026-10-07 (Node v25.6.0). "Dir" is where to run the command from. + +| command | dir | result / notes | +|---|---|---| +| `npm install` | repo root | OK in 18 s, 134 packages. One EBADENGINE warning: vitest 5.0.3 wants Node `^22.12.0 \|\| ^24.0.0 \|\| >=26.0.0` (Node 25 works). Side effects: see §4 | +| `npx tsc -p tsconfig.json --noEmit` | `packages/runtime` | clean, ~1.6 s. Checks `src/` only: test files are never type-checked | +| `npx tsup` | `packages/runtime` | ~2.5 s. Cleans `dist/` first. 6 entries: `index`, `adapters/{react,redux,zustand}`, `devtools/index`, `worker`; `.d.ts` for all but `worker`; ~1.6 MB with maps | +| `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` | `packages/runtime` | ~2.4 s. Files 36 passed, 1 skipped (37). Tests 286 passed, 14 skipped (300). The 14 skips are model-parity tests that need model files at `GENCLASS_MODEL_DIR` (default `/.cache-model`): `test/model/packer.test.ts` (all 10), `engine.test.ts` (3 of 4), `calibrate.test.ts` (1 of 8). With a model dir, all 300 pass | + +Not verified when these docs were written (taken from [build-test-release.md](docs/agents/runtime/build-test-release.md)): + +| command | dir | notes | +|---|---|---| +| `npm run build` / `npm test` | repo root | run only in `@genclass/runtime` (`tsup` / `vitest run`). `vitest.config.ts` already excludes `test/browser/**` | +| `npm run typecheck` | repo root | every workspace. The demos typecheck needs `packages/runtime/dist/*.d.ts`, so build first; it also needs the missing `demos/src/server/data/cities.ts` (see [demos.md](docs/agents/demos.md)). Until that file is recreated, the demos typecheck, and so the root typecheck, fails (inferred from the imports; not run) | +| `npx vitest run test/atoms.test.ts -t "late discard"` | `packages/runtime` | one file or one test | +| `npm run test:browser` | `packages/runtime` | **ask first.** Playwright, rebuilds `dist/`, needs Chromium for `@playwright/test` 1.63.0 and a model dir, overwrites the committed UI screenshots | +| `npx playwright test --config test/browser/ui/playwright.config.ts` | `packages/runtime` | **ask first.** Devtools UI spec, writes 18 screenshots | +| `bash test/smoke/smoke.sh` | `packages/runtime` | **ask first.** `npm pack` into a temp Vite 8 app (registry access), then headless Chromium; leaves the `.tgz` and the temp dir | +| `npm run build && cd sim && SIM_RUNTIME=real npx vitest run` | repo root | **ask first** (sim). Sim tests against the real runtime; without `SIM_RUNTIME=real` they use a fake runtime | +| `node packages/runtime/bin/genclass-runtime.mjs fetch-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | repo root | **ask first** (download). Fetches the v0.1 model for the model tests (`GENCLASS_MODEL_DIR=`). The default `--from` is an unpublished release | +| `scripts/vm.sh run\|exec ''` | repo root | **ask first** (Azure). The original team's path for every command above | + +## 6. Top-level layout + +| path | what it is | doc | +|---|---|---| +| `packages/` | `runtime/`: the `@genclass/runtime` library (`src/`, `test/`, `bin/genclass-runtime.mjs` CLI, `STATUS.md`, `UI-NEEDS.md`). `runtime-model/`: only `MODEL_CARD.md` of the unpublished model package | [docs/agents/runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle, [build-test-release](docs/agents/runtime/build-test-release.md)) and [model-io-contract](docs/agents/model-io-contract.md) | +| `sim/` | `@genclass/sim`: training-data simulator driving the real runtime (private, Node 22 ESM) | [sim.md](docs/agents/sim.md) | +| `training/` | Python training, eval and export of the runtime model (R17/R32), plus Azure scripts | [training.md](docs/agents/training.md) | +| `demos/` | `@genclass/demos`: six Vite demo apps, Service Worker chaos backend, Playwright trial harness | [demos.md](docs/agents/demos.md) | +| `docs/` | `runtime/` (`CONTRACT.md`, which is binding, plus `API.md` and `ARCHITECTURE.md`; all three drift from the code), `agents/` (these docs), legacy `*.md` and `benchmax-research/` (do not edit) | [status-and-known-issues](docs/agents/status-and-known-issues.md) (drift tables) | +| `jev_local/` | legacy Python predecessor (`jev-local`): the model the runtime's `src/model` was ported from, the trainer `training/` drives, server and harness | [genclass-model-lineage.md](docs/agents/genclass-model-lineage.md) | +| `tests/` | Python tests for `jev_local` (the 20 `test_data_*.py` files fail at collection: `jev_local/data` is gitignored) | [genclass-model-lineage.md](docs/agents/genclass-model-lineage.md) | +| `extension/` | legacy GenClass 0.1.0 MV3 voice-control Chrome extension, the JS ancestor of `src/model` | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) | +| `bench/`, `results/` | benchmark pre-registrations and published results (jevbench, benchmax, CU head-to-head) | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) | +| `scripts/` | ops and benchmark scripts; for the runtime: `vm.sh` (VM build/test), `azvm.sh` and `launch_run.sh` (called by `training/*.sh`), and `genclass_export.py` (its `ExportModel` is imported by `training/export_runtime.py`) | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) (one row per script) | +| root files | `package.json` (workspaces), `tsconfig.base.json`, `pyproject.toml` (`jev-local`), `OPEN_TASKS.md`, `README.md`, `BENCHMARKS.md`, `LICENSE` (Apache-2.0) | [status-and-known-issues](docs/agents/status-and-known-issues.md) | + +## 7. Conventions + +**Code (observed in `packages/runtime/src`; there is no formatter or linter config).** +- Every module opens with a `//` header comment that states its role and invariants. Many cite the CONTRACT section they implement + (e.g. `// Policy gate for non-passive actions (CONTRACT §8)`). Most `packages/runtime/src/model/*` headers name the + `jev_local` Python file or extension code they port. +- Comments are sparse: about 4-10% of lines in the large modules. Use `/** */` JSDoc on exported symbols and non-obvious fields. Inline + comments mostly explain why, or state an invariant. +- Naming: PascalCase classes and types (`RuntimeImpl`, `StoreHub`, `OpRegistry`), camelCase functions, UPPER_SNAKE module constants + (`LATE_REVERT_MS`, `CACHE_MAX`), short locals. Named exports only. The one default export is + `packages/runtime/src/index.ts` -> `GenClass`. +- Imports: relative paths with `.js` extensions; `import type` for types (`verbatimModuleSyntax`). Style: 2-space indent, + double quotes, semicolons, lines mostly at most 120 chars. +- Errors: never throw into the host app. Hooks, plugins, listeners and callbacks run in `try/catch` with a comment + (`/* hooks never break the app */`, `/* listeners never break tracing */`). `ask()`/`decide()` reject with + `GenClassUnavailableError` and a `reason` (`packages/runtime/src/errors.ts`); with `timeoutMs` set, a failed model load + rejects with the provider's own error instead. A failing action controller throws a plain `Error` with an English + message: the runtime records `ok: false` plus `error` on the `ActionRecord` and runs the passive action instead. +- Every user-visible or model-visible string (facts, reports, `changed` sentences) is plain English. Model-visible text is frozen (rule 2). + +**Tests (`packages/runtime/test/`, vitest).** +- One `.test.ts` per area (`test/model/` for model code). Use `test/helpers.ts`: `setup()` returns `{ clock, server, g, decider, rt, fetch }` + and builds a `FakeClock`, a `FakeServer`, an instrumented global and a `ScriptedDecider` around `createRuntime`. There is no real time, network or model. +- Drive time with `clock.advance(ms)` / `clock.flush()`. Control answers with `defaultScript({ : { diagnosis, action } })`, + or with `ManualDecider` plus `answer()`. Force consultation with `triage: "always"`. Assert on `decider.calls[i].state`, `rt.decisions()`, + `rt.interventions()`, `server.hits`. +- Name the CONTRACT section in the `describe` (e.g. `"atoms and the mutation pipeline (CONTRACT §4)"`). DOM tests start with + `// @vitest-environment happy-dom`. Never use real timers or `Date.now` in tests except where noted in the build doc. + +**Coordination files (the original team's protocol; keep using it).** +- `OPEN_TASKS.md` (lead): project status in Done / In progress / Next / Needs the user / Known risks. +- `packages/runtime/STATUS.md` (CORE): test state, batch changes, headless recipe, trigger table, example situations, + **Deviations from the contract (and why)**, **Open issues**. +- `NEEDS.md` files live in the *requester's* directory: `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and + (an exception) `packages/runtime/UI-NEEDS.md`. `sim/NEEDS.md` and `training/NEEDS.md` mark items OPEN (needed) / ASK (would help) / + DONE (landed and verified by the requester), and training/NEEDS also uses INFO. `UI-NEEDS.md` uses Open / Nice to have / Done + sections. `demos/NEEDS.md` uses numbered sections addressed to an owner. Owners may add answers to a requester's file + (training/NEEDS has "CORE → TRAIN" and "MODEL → TRAIN (from MODEL, ...)" sections); only the requester closes an item. +- `docs/runtime/CONTRACT.md` (lead): the binding spec. An approved change is appended to §13, and an accepted divergence goes into STATUS + "Deviations". A deviation without a STATUS entry is a bug. CONTRACT, STATUS, API.md and the NEEDS files are stale in places + (CONTRACT was last edited before batch 3): check the drift tables in the status doc before relying on them. + +## 8. Definition of done + +1. If you touched `packages/runtime/src`: `npx tsc -p tsconfig.json --noEmit` is clean, and `npx tsup` still builds when you changed + entries, exports or the worker. Keep tsup entries as literal `"src/...ts"` strings, and keep the worker URL and ORT `import()` literals. +2. Unit tests pass: 286 passed and 14 skipped without a model dir (all 300 with one), plus new tests in house style for new + behaviour. No `review-*.test.ts` was edited. For sim or demos changes, name the checks you could not run and why. +3. No model-visible text changed (rule 2), unless the user explicitly approved it. If it was approved, also update the exact-text + tests and the STATUS example situations, and flag that SIM data and training must be regenerated. +4. Update the affected `docs/agents/` doc(s) (see [docs/agents/README.md](docs/agents/README.md)) and set its header line + `Verified against commit ()` to the commit you re-checked it against. A public-surface change also updates + `docs/runtime/API.md` and the JSDoc in `packages/runtime/src/types.ts`. +5. If behaviour changed: update `packages/runtime/STATUS.md` (Updated line, batch section, Deviations, Open issues) and move the item + in `OPEN_TASKS.md`. Add or answer the relevant `NEEDS.md` item. +6. Leave no `npm install` side effects in the diff: revert the `bin/genclass-runtime.mjs` mode change and do not commit the root + `package-lock.json` unless the user decided to. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..f26a7604 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +GenClass-lib: monorepo for @genclass/runtime, a self-healing web-app runtime with a local ONNX model, plus its training-data simulator (sim/), model training (training/) and demos (demos/). Agent instructions live in AGENTS.md, imported below. + +@AGENTS.md diff --git a/docs/agents/README.md b/docs/agents/README.md new file mode 100644 index 00000000..44015fdb --- /dev/null +++ b/docs/agents/README.md @@ -0,0 +1,185 @@ +# Agent docs: index and router + +> **Scope:** every doc in `docs/agents/`, the root entry points `AGENTS.md` and `CLAUDE.md`, and how these docs relate to the human docs in `docs/runtime/`. +> **Read this when:** you need the right doc for a task, want to know what a doc covers, or must update the docs after changing code. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## Purpose and reading order + +These docs are for AI coding agents that arrive in this repo with no context. Each subsystem doc describes one area as the code stands at a stated commit, with `file -> symbol` pointers so you can go straight to the source. They are not product documentation. For that, see `README.md`, `packages/runtime/README.md` and `docs/runtime/*.md`. + +Read them in this order: + +1. [`../../AGENTS.md`](../../AGENTS.md): ground rules, what you may run locally, and what needs the user's OK first. +2. [overview.md](overview.md): what the product is and how runtime, sim, training, model and demos fit together. +3. The subsystem doc for your task (see the [routing table](#routing-table)). Read its TL;DR first, then "Invariants and gotchas" and "How to change it safely" before you edit anything. +4. [playbooks.md](playbooks.md): procedures for tasks that span several subsystems. + +Keep three docs open for reference: [repo-map.md](repo-map.md) (where things live), [glossary.md](glossary.md) (terms) and [status-and-known-issues.md](status-and-known-issues.md) (what is shipped, frozen, open and stale). + +Three facts change how you should read every other doc: + +- **The situation format is frozen** at tag `situation-v1` (1a77558). `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Any change to text the model reads needs the user's go-ahead (ask the user; the workstream roles belonged to the original team), regenerated sim data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). +- **The published alpha only observes.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which has not been published (OPEN_TASKS item 8; the CDN was not checked live). A default `GenClass.init()` ends in model status `error` and never acts. See [runtime/model-host.md](runtime/model-host.md). +- **The subsystem docs still state the original run rule:** everything on the Azure VM via `scripts/vm.sh`, never locally (CONTRACT §0 rule 5, written for an 8 GB Mac). The current policy for agents is in `AGENTS.md`: + - You may run `npm install`, typecheck, the tsup build and the vitest unit tests locally. The lead checked all four on 2026-10-07. + - Ask the user before you run the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). + +## Routing table + +Each row names the doc to read, and then any further docs to check. "Ask first" means you must get the user's OK before you run anything for that task. + +### Orientation and process + +| If your task is ... | Read | Then | +|---|---|---| +| Learn what is shipped, frozen or in flight, and who owns what | [status-and-known-issues.md](status-and-known-issues.md) | [overview.md](overview.md) | +| Find where a file, package or script lives | [repo-map.md](repo-map.md) | the "Files" table of the subsystem doc | +| Look up a term (situation, trigger, tier, settled point, hold budget, FIR, R17/R32) | [glossary.md](glossary.md) | the doc's "Concepts and data structures" | +| Decide whether a change forces new sim data and retraining | [model-io-contract.md](model-io-contract.md) ("Versioning: what invalidates the trained model") | [status-and-known-issues.md](status-and-known-issues.md) ("Change anything the model reads") | +| Record status after a change (STATUS.md, NEEDS files, OPEN_TASKS.md) or file a cross-workstream request | [status-and-known-issues.md](status-and-known-issues.md) ("How to change it safely") | — | +| Handle a human doc (API.md, CONTRACT.md, a README, STATUS.md) that disagrees with the code | [status-and-known-issues.md](status-and-known-issues.md) ("Drift and open issues", "Fix doc drift") | the subsystem doc's "Drift and open issues" | + +### Runtime: public API, observers, state + +| If your task is ... | Read | Then | +|---|---|---| +| Add or change an init/`createRuntime` option or a default (mode, thresholds, `settleMs`, `historySize`) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [sim.md](sim.md) (`sim/src/run/rt.ts` -> `createOptions`) if it reaches situations or decisions | +| Add a `Runtime` method or event | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/devtools.md](runtime/devtools.md) (`MockRuntime`), [demos.md](demos.md) (runtime shim) | +| Change `GenClass.init`, the kill switch or `destroy()` | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (how globals are restored) | +| Write a plugin, custom action or standing question | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (plugin API) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [model-io-contract.md](model-io-contract.md) (no retrain; quality unmeasured) | +| Add code that depends on time (timers, timestamps, ids) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`Clock` rules) | [runtime/build-test-release.md](runtime/build-test-release.md) (`FakeClock` tests) | +| Add an observer (`EventSource`, `BroadcastChannel`, ...) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) if you add an `OpKind` | +| Debug how fetch/XHR requests are held, coalesced, retried, hedged or served from cache | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Change op signatures, request identity or volatile headers | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [model-io-contract.md](model-io-contract.md) (op names reach the model) | +| Carry the ambient op across a new async boundary | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (`LazyOp` timer pattern) | — | +| Change DOM user-action recording or `data-genclass-ignore` | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/devtools.md](runtime/devtools.md) | +| Integrate another state library through `runtime.adapter` | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (subpath export) | +| Change the React hooks, Redux enhancer or Zustand middleware | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [demos.md](demos.md) (a demo exercises each adapter) | +| Debug why a write was held, applied, dropped or not reverted | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (hold budget, late revert) | +| Add or tune an invariant template; debug a missing or spurious `inconsistency` trigger | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | +| Fix held writes landing after a newer user write (`demos/NEEDS.md` §1) | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [status-and-known-issues.md](status-and-known-issues.md), [demos.md](demos.md) | + +### Runtime: situation, decisions, model host, devtools + +| If your task is ... | Read | Then | +|---|---|---| +| Find out why a trigger did or did not reach the model (triage) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Change fact wording or timeline/state/stats lines, or add a fact | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md) | +| Change the situation budget or section limits | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [model-io-contract.md](model-io-contract.md), [training.md](training.md) (`rt.py` must match) | +| Change redaction (`isSensitiveName`), latency/error baselines or transition profiles | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`util.ts` helpers) | +| Add a trigger kind | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`Controller`), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md) | +| Change the policy gate, thresholds, hold budget or rate limit | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [training.md](training.md) (`eval_runtime.py` mirrors the gate) | +| Change a built-in action's mechanics or its `changed` sentence | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (request/failure/stall controllers) | +| Add a built-in action or a diagnosis label | [model-io-contract.md](model-io-contract.md) ("Recipes") | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [sim.md](sim.md), [training.md](training.md) | +| Change console report wording, `explain()` or undo | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/devtools.md](runtime/devtools.md) (the overlay mirrors report templates) | +| Change the decider queue (priorities, deadlines, timeout, answer cache) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/model-host.md](runtime/model-host.md) | +| Debug "Model unavailable (...); observing only.", a stuck load or slow decisions | [runtime/model-host.md](runtime/model-host.md) | [status-and-known-issues.md](status-and-known-issues.md) | +| Point at a published model, bump the model version, or self-host model files (`genclass-runtime fetch-model`) | [runtime/model-host.md](runtime/model-host.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (publishing the model package) | +| Change WebGPU/WASM plan order, the worker protocol, a model error class or the onnxruntime-web version | [runtime/model-host.md](runtime/model-host.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (externals, browser specs) | +| Change the TS serializer, tokenizer, packer or calibration | [model-io-contract.md](model-io-contract.md) | [runtime/model-host.md](runtime/model-host.md), [genclass-model-lineage.md](genclass-model-lineage.md) (Python side), [runtime/build-test-release.md](runtime/build-test-release.md) (fixtures) | +| Mount the devtools overlay, or change a view, option, card, theme or keyboard handling | [runtime/devtools.md](runtime/devtools.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (events it subscribes to) | +| Update the overlay's Playwright spec or its screenshots (ask first) | [runtime/devtools.md](runtime/devtools.md) | [runtime/build-test-release.md](runtime/build-test-release.md) | +| Investigate a false intervention or unexpected behaviour reported by a user | [playbooks.md](playbooks.md#25-investigate-a-false-intervention-reported-by-a-user) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | + +### Build, test and release + +| If your task is ... | Read | Then | +|---|---|---| +| Build, typecheck or run the unit tests | [runtime/build-test-release.md](runtime/build-test-release.md) | [`../../AGENTS.md`](../../AGENTS.md) (what may run locally) | +| Write a unit test in house style (`setup()`, `FakeClock`, `ManualDecider`) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`defaultScript`) | +| Add a public entry point (subpath export) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | +| Run the Playwright specs or the npm-pack smoke test (ask first) | [runtime/build-test-release.md](runtime/build-test-release.md) | — | +| Cut a release, publish `@genclass/runtime-model`, or add CI (there is no `.github/`) | [runtime/build-test-release.md](runtime/build-test-release.md) | [playbooks.md](playbooks.md#19-publish-genclassruntime) recipes 19–21, [status-and-known-issues.md](status-and-known-issues.md) | + +### Sim, training and demos + +| If your task is ... | Read | Then | +|---|---|---| +| Generate or regenerate training data (ask first) | [sim.md](sim.md) | [model-io-contract.md](model-io-contract.md) | +| Add a feature combinator, domain, chaos behaviour or ask-question generator | [sim.md](sim.md) | — | +| Change cost weights or label parameters | [sim.md](sim.md) | [model-io-contract.md](model-io-contract.md) (how the sim labels rows) | +| Debug a dropped trajectory, a `prefix-mismatch` or an odd label | [sim.md](sim.md) | — | +| Change the runtime options the sim passes (`createOptions`) | [sim.md](sim.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | +| Mirror a runtime wording change into `training/curriculum/rt.py` | [training.md](training.md) | [model-io-contract.md](model-io-contract.md) | +| Regenerate the curriculum, change a mixture or launch a training round (Azure; ask first) | [training.md](training.md) | [genclass-model-lineage.md](genclass-model-lineage.md) (the `jev_local` trainer) | +| Evaluate a checkpoint, fit calibration or read EVAL.md numbers | [training.md](training.md) | [model-io-contract.md](model-io-contract.md) ("Re-calibrate only") | +| Export and validate a model directory; choose between R17 and R32 | [training.md](training.md) | [runtime/model-host.md](runtime/model-host.md) (card format), [status-and-known-issues.md](status-and-known-issues.md) | +| Change the tokenizer vocabulary | [training.md](training.md) | [genclass-model-lineage.md](genclass-model-lineage.md) | +| Build the demos from a fresh clone (`demos/src/server/data/cities.ts` is missing) | [demos.md](demos.md) | — | +| Add a demo, or change a scenario, oracle, chaos knob or mock route | [demos.md](demos.md) | — | +| Use a new runtime API from the demos (runtime shim) | [demos.md](demos.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | +| Evaluate a model in the demos (`demos/scripts/vm-eval.sh`; ask first) | [demos.md](demos.md) | [runtime/model-host.md](runtime/model-host.md) | +| Investigate a regression caused by holds (`e2e/eval.ts --trace`) | [demos.md](demos.md) | [runtime/state-and-adapters.md](runtime/state-and-adapters.md), [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | + +### Legacy GenClass, extension and benchmarks + +| If your task is ... | Read | Then | +|---|---|---| +| Change `jev_local` serialization, packing, calibration or answer math | [genclass-model-lineage.md](genclass-model-lineage.md) | [model-io-contract.md](model-io-contract.md), [runtime/model-host.md](runtime/model-host.md) | +| Work on the Jev-compatible server, the macOS voice harness or the Python tests | [genclass-model-lineage.md](genclass-model-lineage.md) | — | +| Change the Chrome extension | [extension-and-benchmarks.md](extension-and-benchmarks.md) | [genclass-model-lineage.md](genclass-model-lineage.md) (harness parity) | +| Fix an engine/packer/tokenizer bug that the extension also has | [runtime/model-host.md](runtime/model-host.md) (the runtime copy is the maintained one) | [extension-and-benchmarks.md](extension-and-benchmarks.md) | +| Run, extend or quote a benchmark (jevbench, benchmax, the computer-use head-to-head); paid calls need the user's OK | [extension-and-benchmarks.md](extension-and-benchmarks.md) | — | +| Find out what a script in `scripts/` does and whether it touches Azure, money or secrets | [extension-and-benchmarks.md](extension-and-benchmarks.md) (scripts table) | [runtime/build-test-release.md](runtime/build-test-release.md) (`scripts/vm.sh`) | + +## Catalogue + +Line counts were taken with `wc -l` and are approximate. + +| Path | Scope | Read when | Lines | +|---|---|---|---| +| [`../../AGENTS.md`](../../AGENTS.md) | Entry point: what the repo is, status, ground rules, where to run things, commands, conventions, definition of done | First, always | ~190 | +| [`../../CLAUDE.md`](../../CLAUDE.md) | Claude Code entry point: one-line repo summary that imports `AGENTS.md` (`@AGENTS.md`) | Loaded for you by Claude Code | 3 | +| [README.md](README.md) | This index: routing, catalogue, conventions, maintenance | Finding a doc; updating docs | ~185 | +| [overview.md](overview.md) | The mental model: component map, runtime data flow, offline loops (sim -> training -> model), modes, fail-open behaviour | Second, after AGENTS.md | ~415 | +| [repo-map.md](repo-map.md) | Every tracked path, plus generated and ignored paths in a working copy | Finding where a file, symbol, constant, CLI command, env var or config key lives | ~855 | +| [glossary.md](glossary.md) | Terms used across the docs | When a term is unclear | ~445 | +| [playbooks.md](playbooks.md) | End-to-end procedures across subsystems | Before a multi-subsystem change | ~775 | +| [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | `index.ts`, `runtime.ts` wiring, `types.ts`, errors, `Clock`, `util.ts`, `package.json` | Options, `Runtime` methods, events, plugins, init/destroy, kill switch | ~640 | +| [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | `observe/*`, `trace/*`, observer install/route code in `runtime.ts` | Patching fetch/XHR/WS/timers/DOM/history/Storage; ops, identity, causality | ~790 | +| [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | `state/*`, `adapters/*`, store code in `runtime.ts` | Holds, patches, reverts, snapshots, invariants, React/Redux/Zustand | ~650 | +| [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | `learn/*`, `situation/*`, triage in `runtime.ts` | Any model-visible text, triage, budgets, redaction, baselines | ~1050 | +| [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | `decide/*`, action controllers, `explain`, undo | Queue, policy gate, built-in actions, reports | ~720 | +| [runtime/model-host.md](runtime/model-host.md) | `model/*`, worker, CLI `bin/genclass-runtime.mjs`, `packages/runtime-model/` | Model loading, caching, WebGPU/WASM, packer, calibration, CLI | ~670 | +| [runtime/devtools.md](runtime/devtools.md) | `devtools/*`, `UI-NEEDS.md`, devtools tests and UI spec | The overlay, its views, theming, screenshots | ~710 | +| [runtime/build-test-release.md](runtime/build-test-release.md) | Workspace config, tsup/vitest/Playwright, fixtures, smoke, `scripts/vm.sh`, publishing | Build, test, fixtures, release, CI | ~550 | +| [model-io-contract.md](model-io-contract.md) | Situation text -> packed request -> heads -> calibrated answers, across runtime, sim and training | Any change the model can see; shipping a model directory | ~690 | +| [sim.md](sim.md) | `sim/**` | Training data generation, labels, splits, budgets | ~820 | +| [training.md](training.md) | `training/**` and the `jev_local` parts it calls | Curriculum, training rounds, eval, calibration, export | ~520 | +| [demos.md](demos.md) | `demos/**` | Demo apps, mock server, chaos, Playwright eval, results | ~540 | +| [genclass-model-lineage.md](genclass-model-lineage.md) | `jev_local/**` (except bench), Python tests, legacy `docs/*.md` | Python reference for parity; trainer; legacy server and harness | ~530 | +| [extension-and-benchmarks.md](extension-and-benchmarks.md) | `extension/**`, `bench/**`, `jev_local/bench/**`, `results/**`, `scripts/**` | Chrome extension, benchmarks, ops scripts | ~560 | +| [status-and-known-issues.md](status-and-known-issues.md) | OPEN_TASKS, STATUS, NEEDS files, `docs/runtime/*`, git history | Status, ground rules, owners, open issues, cross-doc drift | ~625 | + +## Conventions used in these docs + +- **Header block.** Every subsystem doc opens with three lines: **Scope** (the files it covers), **Read this when** and **Source of truth**. The last line reads "Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins." +- **Fixed sections.** All 15 subsystem docs use the same sections in the same order: TL;DR, Files, Concepts and data structures, How it works, Configuration and constants, Invariants and gotchas, How to change it safely, Tests, Drift and open issues, Related docs. Jump straight to the one you need. +- **Code pointers** look like `path/from/repo/root.ts` -> `symbolName`, for example `packages/runtime/src/decide/policy.ts` -> `gate`. They never give line numbers; find a symbol with `rg -n "symbolName" `. Some runtime docs shorten paths to `src/…` and `test/…`, relative to `packages/runtime/`. [status-and-known-issues.md](status-and-known-issues.md) states its own path convention at the top of its TL;DR. +- **Code wins.** A doc describes the code at its verified commit. If a doc disagrees with the code, trust the code, then fix the doc. This applies to the human docs too: CONTRACT.md, API.md, the READMEs, STATUS.md, the NEEDS files and MODEL_CARD.md all have stale items. +- **Drift sections.** "Drift and open issues" lists two things: + - where docs or code comments disagree with the code, and what the code really does; + - open questions, and findings that came only from reading the code, with no test behind them. + + Check this section before you rely on a human doc. [status-and-known-issues.md](status-and-known-issues.md) holds the cross-cutting drift tables (human docs vs the runtime code). Subsystem-specific drift is only in each doc's own Drift section. +- **"(unverified)"** marks a claim that nobody could confirm from the code or a run at the verified commit. Typical cases are live URLs, browser behaviour, VM state and results that are not in the repo. Treat such a claim as a hypothesis. "Inferred" and "code reading only" mean the claim was derived from the source and no test asserts it. + +## Keeping the docs current + +1. **Update the doc in the same change as the code.** If you change code under a doc's Scope, edit the affected sections in that doc (Files, constants, How it works, Tests). Remove Drift entries your change resolves, and add any mismatch it creates. +2. **Update the commit line.** Set "Verified against commit … (date)" to the commit you checked the doc against. If you re-checked only part of the doc, name those sections in that line. +3. **Fix every copy of a repeated fact.** Several facts appear in more than one doc: the unpublished default model, the `situation-v1` freeze, the default hold budget, test counts. Before you finish, search for the symbol or value you changed and fix every hit, for example `rg -n "DEFAULT_MODEL_BASE_URL" docs/agents`. +4. **Model-visible changes cascade.** A change to situation text, questions, labels or budgets touches [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md) and [status-and-known-issues.md](status-and-known-issues.md) (freeze tag). +5. **New docs.** A new subsystem doc keeps the same header block and ten sections. Add it to the catalogue and the routing table here, and to [repo-map.md](repo-map.md). Refresh the line counts with `wc -l docs/agents/*.md docs/agents/runtime/*.md` when a doc grows or shrinks a lot. +6. **Mark what you could not check.** Write "(unverified)" next to anything you could not confirm. Never add line numbers. + +### How these docs relate to the human docs + +The agent docs are derived from the code. They cite the human docs mainly to record drift, and they do not replace them: + +- `docs/runtime/CONTRACT.md` is the binding build contract. The lead owns it. It holds the §0 ground rules, the spec, and the approved additions in §13. To change it, write a NEEDS item or ask the user (who now stands in for the lead); an approved deviation goes into CONTRACT §13 or STATUS "Deviations from the contract (and why)". +- `docs/runtime/API.md` is the public API reference for library users. If you change the public surface, update API.md and the JSDoc in `packages/runtime/src/types.ts` in the same change, then the agent doc. +- `docs/runtime/ARCHITECTURE.md` is the design overview for humans. Its known drift is listed in [status-and-known-issues.md](status-and-known-issues.md). +- The workstream status files (`packages/runtime/STATUS.md`, `packages/runtime/UI-NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, `OPEN_TASKS.md`) are how the team coordinates. Follow the process in [status-and-known-issues.md](status-and-known-issues.md), and do not close or rewrite another workstream's items: the requester flips an item to DONE after verifying (owners may add answers under their own heading, as MODEL did in `training/NEEDS.md`). +- The legacy jev-local docs (`docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`) and `docs/benchmax-research/` are not the runtime contract. CONTRACT §1 says this earlier GenClass content "stays as is". They are summarised in [genclass-model-lineage.md](genclass-model-lineage.md) and [extension-and-benchmarks.md](extension-and-benchmarks.md). diff --git a/docs/agents/demos.md b/docs/agents/demos.md new file mode 100644 index 00000000..1add95d8 --- /dev/null +++ b/docs/agents/demos.md @@ -0,0 +1,540 @@ +# demos/: six demo apps, chaos backend and trial harness + +> **Scope:** `demos/` (`README.md`, `NEEDS.md`, `results.md`, `results*.json`, `package.json`, `vite.config.ts`, `tsconfig*.json`, `scripts/**`, `e2e/**`, `src/**`, `index.html`, `*/index.html`). +> **Read this when:** you change a demo app, its scenario or oracle; touch the Service Worker mock server or chaos model; run or change the Playwright eval; read or regenerate `results.*`; update the runtime API the demos use (shim); or work on a `demos/NEEDS.md` item. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- `@genclass/demos` (private workspace) is a Vite multi-page static site: a landing page plus six small apps (`search`, `editor`, `checkout`, `status`, `board`, `decisions`), each with a deliberate, realistic latent bug that only shows under network chaos. +- The backend is a **mock API inside a Service Worker** (`src/server/`): real `fetch` and a real `EventSource` from the page's point of view. Each page or trial gets its own server session (**world**). The page controls the server only via `postMessage`, never `fetch`, so GenClass never observes test traffic. +- GenClass is created in exactly one place, `src/shared/genclass.ts` -> `startGenClass`. Demo **Off** = `GenClass.init({ mode: "observe", model: false })` (the baseline; nothing is held or decided). **Guard** / **Heal** = `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. App code is identical in all three. +- A **trial** = seeded scenario (scripted user steps + chaos + server params + intent) run in a fresh page, then scored by the demo's **oracle** (test code that reads only the DOM and the mock server's truth). **Chaos** trials measure bug rate; **clean** trials (calm network, calm user, app is correct) count **false interventions** (any non-passive action that ran). +- Two drivers run the same steps: the in-page "Run trials" panel (iframes, synthetic DOM events, `src/shared/driver.ts`) and the headless eval (`e2e/eval.ts`, Playwright, real keyboard and mouse). +- Fairness devices: **common random numbers** (the n-th identical request/event gets the same latency and failure draws in every mode) and **native timers** captured before `GenClass.init` for all test code. Known gap: scripted world activity is timed from world creation, which precedes the Guard/Heal model wait (`gc.loadMs` 0.67–2.08 s in the shipped run), see [Invariants](#invariants-and-gotchas). +- Shipped results (`results.md`, 810 trials, the v0.1 GenClass model, which was not trained for runtime decisions, q8 WASM): no executed action lowered a bug rate (the only drop, status under Guard 100% -> 93%, came with zero actions executed), 0 false interventions (mostly because decisions missed thresholds or the hold budget), and holding writes cost latency (search) and introduced bugs (board, 9 of 30 seeds under both Guard and Heal). +- Open runtime work for CORE is in `demos/NEEDS.md`; at HEAD §1 (held write lands after a newer user write), §2 (holds cost latency), §5 (`retry` offered for non-idempotent requests) and §6 (no EventSource observer) are still open in code. +- **Blocking gotcha:** `demos/src/server/data/cities.ts` is imported by the search world, scenario and oracle but is **not in git** (the root `.gitignore` line `data/` ignores it). A fresh clone cannot build the Service Worker or the search page until it is recreated. See [Drift](#drift-and-open-issues). +- Ground rules: the original team ran every build, browser and model run on the `train` VM through `scripts/vm.sh` (slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([../../AGENTS.md](../../AGENTS.md) §4), ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`), model downloads (`npm run fetch-model`) or anything on Azure. Demos and `sim/` must not read each other, and oracles are never passed to GenClass. + +## Files + +| Path | Role | Key exports / entry points | +|---|---|---| +| `demos/package.json` | workspace `@genclass/demos` (private, ESM). Deps: `@genclass/runtime` `*` (workspace), `react`/`react-dom` ^19.3.0, `redux` ^5.0.1, `zustand` ^5.0.15, `@fontsource-variable/{inter,jetbrains-mono}`. Dev: `@playwright/test` 1.63.0, `vite` ^8.3.3, `@vitejs/plugin-react` ^6.1.2, TS ~5.9.3 | scripts `dev`, `build`, `preview`, `typecheck`, `typecheck:shim`, `fetch-model`, `eval`, `eval:fast`, `shots` | +| `demos/vite.config.ts` | multi-page build (`base: "./"`), shim aliasing, dev Service Worker middleware, defines | `PAGES`, plugin `genclass-demo-dev-sw`, defines `__BUILD_ID__`, `__RUNTIME_KIND__` | +| `demos/tsconfig.json` | app code (`src`, excludes `src/server/sw.ts` and the shim) | | +| `demos/tsconfig.sw.json` | Service Worker code (`lib: WebWorker`): `src/server/**`, `src/shared/{chaos,rng,protocol}.ts` | | +| `demos/tsconfig.node.json` | `e2e/**/*.ts`, `vite.config.ts` | | +| `demos/tsconfig.shim.json` | like `tsconfig.json` with `paths` mapping `@genclass/runtime*` to the shim | | +| `demos/.gitignore` | ignores `node_modules/`, `dist/`, `public/genclass-model/`, `test-results/`, `playwright-report/`, `e2e/.out/` | | +| `demos/public/favicon.svg` | site icon (copied to `dist/` by the site build) | | +| `demos/index.html`, `demos//index.html` | pages; `` is `./` (landing) or `../` (demos); inline theme bootstrap from `localStorage["gc-demo-theme"]` | `src/site/landing.ts`, `src/demos//main.ts` | +| `demos/scripts/build.mjs` | builds the site, then `dist/sw.js` as one classic IIFE (`name: "GenClassDemoServer"`) with the same `BUILD_ID`; copies `results-summary.json`; writes `dist/build.json`, `dist/.nojekyll` | | +| `demos/scripts/fetch-model.sh` | downloads a model directory (runtime CLI `packages/runtime/bin/genclass-runtime.mjs fetch-model`, curl fallback) | args `[dir] [baseUrl] [variant]` | +| `demos/scripts/vm-eval.sh` | full VM pipeline: install, build runtime, model, build demos, typecheck, eval | env `GENCLASS_MODEL_FROM/DIR/URL/VARIANT`, `ALLOW_BROKEN_RUNTIME`, `SKIP_EVAL` | +| `demos/e2e/eval.ts` | headless Playwright eval: trials, reports, screenshots | CLI options (see Configuration) | +| `demos/e2e/serve.ts` | static server for `dist/` under a sub-path, with extra mounts | `serveStatic(rootDir, base, port, mounts)` | +| `demos/e2e/trace-report.ts` | analyses `--trace` runs (held writes, apply order); prints Markdown to stdout. Sections: "Board: what holding writes does" (per mode/kind: writes, held = waited > 2 ms, median hold, held writes applied after a newer user write to the same card), A/A flips (with the optional 2nd file), per-seed card timelines for seeds clean in Off but buggy in Guard/Heal plus "mechanism counts"; "Search: where the latency goes" (held response writes, decision latency, holds released before their decision arrived) | `node --experimental-strip-types e2e/trace-report.ts [traces.json (default e2e/.out/traces.json)] [offB.json]` | +| `demos/src/shared/genclass.ts` | the only place the runtime is created; session stats | `startGenClass`, `collectStats`, `statusText`, `RUNTIME_KIND`, `GcSession` | +| `demos/src/shared/settings.ts` | URL params and localStorage | `getMode`, `setMode`, `modelBaseUrl`, `trialParams` (`TrialParams { seed, kind, mode, run }`), `traceOn`, `holdBudget`, `sessionId`, `loadChaos`, `saveChaos`, `siteRoot`, `getTheme`/`setTheme`, `urlParams` | +| `demos/src/shared/chaos.ts` | chaos model (shared by page and Service Worker) | `RouteChaos`, `Chaos`, `CALM`, `PresetId` (`calm\|busy\|flaky\|storm\|outage`), `PRESETS`, `withPreset`, `matchPreset`, `mergeChaos`, `resolveChaos`, `Timing { up, down, spike }`, `sampleTiming`, `sampleEventDelay`, `describeChaos` | +| `demos/src/shared/protocol.ts` | page <-> Service Worker control protocol | `DemoId`, `ControlMessage`, `ControlReply`, `LogEntry`, `EventEntry`, `ServerInfo` (exported, unused) | +| `demos/src/shared/server.ts` | page side of the mock server | `ensureServiceWorker`, `ServerLink`, `ServerTruth`, `ServerError`, `epochNow`, `wait` | +| `demos/src/shared/native.ts` | timers captured at module load, before `GenClass.init` wraps globals | `nativeSetTimeout`, `nativeClearTimeout`, `nativeSetInterval`, `nativeClearInterval`, `sleep` | +| `demos/src/shared/rng.ts` | seeded PRNG (sfc32, seeded from a number or `hashString` of a string, 12 warm-up draws) and distributions | `Rng` (`float`, `range`, `int`, `chance`, `pick`, `weighted`, `normal`, `lognormal(median, sigma)`, `exp(mean)`, `shuffle`, `fork` (unused)), `hashString` (FNV-1a 32-bit), `clamp` | +| `demos/src/shared/scenario-kit.ts` | human typing rhythm with typos, chaos sampling | `TypingStyle { median, sigma, typoRate, pauseRate, pauseMs }`, `typeSteps(rng, sel, text, style)`, `keyDelay`, `CALM_TYPIST`, `FAST_TYPIST`, `ChaosRanges`, `sampleChaos(rng, ranges, extra)` (uniform per key, rounded to 3 decimals), `CLEAN_CHAOS` | +| `demos/src/shared/types.ts` | trial types | `GcMode`, `MODES`, `TrialKind`, `Step`, `Scenario`, `Score`, `GcStats`, `InterventionSummary`, `TrialResult` | +| `demos/src/shared/demo-def.ts` | demo contract | `DemoDefinition`, `AppContext`, `OracleContext`, `Oracle` | +| `demos/src/shared/driver.ts` | synthetic in-page user (dispatches keyboard/input/pointer/mouse events) | `runSteps`, `DriverHooks` | +| `demos/src/shared/harness.ts` | trial harness inside a trial page (`bootTrial` assigns it to `window.__trial`; this file declares the `__trial`/`__trialReady`/`__trialError` globals) | `TrialHarness` | +| `demos/src/shared/aggregate.ts` | aggregation (no DOM; used by panel and eval) | `wilson`, `quantile`, `summarizeMode`, `summarizeDemo`, `ModeSummary`, `DemoSummary`, `Rate` | +| `demos/src/shared/trace.ts` | investigation tracing (`?trace=1`) via `hooks.mutationProposed` and runtime events | `newTrace`, `traceHooks`, `attachTrace`, `Trace` | +| `demos/src/shared/demos.ts` | copy for landing/topbar/explain cards | `DEMOS`, `DEMO_BY_ID`, `REPO_URL`, `DemoInfo` | +| `demos/src/shared/api.ts` | API base URL (`api/`) | `api(path)` | +| `demos/src/server/sw.ts` | Service Worker: sessions, control messages, `/api/*` routing, COOP/COEP headers, GC of worlds | listeners `install`, `activate`, `message`, `fetch` | +| `demos/src/server/core.ts` | world (session) class: router, chaos/latency pipeline, SSE streams, request log, quiescence | `World`, `WorldDef`, `Route`, `Req`, `Res`, `json`, `now`, `sleep` | +| `demos/src/server/worlds/.ts` | one server world per demo (state, routes, scripted activity, snapshot) | `searchWorld`, `editorWorld` (`ServerNote`), `checkoutWorld` (`PRODUCTS`, `ServerOrder`), `statusWorld` (`SERVICES`, `truthAt`, `Incident`, `Health`), `boardWorld` (`COLUMNS`, `BOARD_SEED`, `TEAMMATES`, `teammateMove`, `Card`), `decisionsWorld` (`BACKUP_MS`, `JournalVersion`) | +| `demos/src/server/data/cities.ts` | **missing from git** (ignored by root `.gitignore` `data/`); must export `searchCities(q)` and `TYPED_TARGETS` | used by `worlds/search.ts`, `demos/search/{scenario,oracle}.ts` | +| `demos/src/demos//main.ts` | `bootDemo({...})` with the demo's `DemoDefinition` | | +| `demos/src/demos//app.ts(x)`, `store.ts` | the app (with its latent bug) and its store wiring | `mountSearch`, `mountEditor`/`createNotesStore`, `mountCheckout`, `mountStatus`, `mountBoard`/`createBoardStore`, `mountDecisions` | +| `demos/src/demos//scenario.ts` | seeded scenario generator | `Scenario(seed, kind)` | +| `demos/src/demos//oracle.ts` | scorer (test code only) | `Oracle(ctx)` | +| `demos/src/demos/decisions/{plugin,jobs}.ts` | custom plugin; background job controller | `backgroundWorkPlugin`, `BackgroundJobs`, `jobs` | +| `demos/src/site/demo-page.ts` | boots an interactive demo page or a bare trial page | `bootDemo` | +| `demos/src/site/activity.ts` | "GenClass activity" panel (reports, evidence via `gc.explain`, Undo, banner) | `mountActivity(gc, mode, overlayHost)` -> `ActivityPanel { el, counts: { prevented, flagged } }` | +| `demos/src/site/chaos-panel.ts` | chaos presets, sliders, toggles, demo extras | `mountChaosPanel(demo, link, initial, extras)` -> `ChaosPanel { el, get(), set(c) }`; `SLIDERS` (module-private) | +| `demos/src/site/trials-panel.ts` | in-page trial runner (iframes) | `mountTrials` | +| `demos/src/site/netlane.ts` | live waterfall of the server log (last 10 s) | `mountNetLane` | +| `demos/src/site/landing.ts` | landing page (hero, modes, demo cards, results table from `results-summary.json`) | module side effects | +| `demos/src/site/{chrome,dom,icons,art,highlight}.ts` | top bar (brand, demo nav, theme toggle that dispatches the `gc-theme` window event, GitHub link) and theme; DOM helpers; SVG icons; per-demo card art; tiny TS/JS syntax highlighter for the `code` snippets | `renderTopbar(active)`, `applyTheme`; `h(tag, attrs, ...children)` (`class`, `html`, `style`, `on*` keys), `append`, `esc`, `ago`, `fmtMs`, `pct`, `toast(msg, ms = 3200)`, `svg` (unused); `icon(name, attrs)`, `BRAND_MARK`, `IconName`; `ART: Record`; `highlight(code)` | +| `demos/src/styles/{system,site}.css` | design tokens (light/dark, `--mode-off/guard/heal`) and site chrome | | +| `demos/src/dev/runtime-shim/*.ts` | observe-only stand-in for `@genclass/runtime`, `/react`, `/redux`, `/zustand`, `/devtools`; re-exports all types from `packages/runtime/src/types.ts` by relative path | `index.ts`: `GenClass` (singleton `init`, `runtime` getter, `destroy`), `createRuntime`, `GenClassUnavailableError` (no `reason` field); `react.ts`: `useGenClass`, `useAtom`, `useGenClassState`; `redux.ts`: `genclassEnhancer` (identity); `zustand.ts`: `genclass` (identity); `devtools.ts`: `mountDevtools` (no-op handle), `DevtoolsOptions` | +| `demos/README.md` | human README (run, URL params, oracles table, latest results, honesty rules) | | +| `demos/NEEDS.md` | what DEMOS needs from CORE/MODEL, with evidence | | +| `demos/results.md`, `results.json`, `results-summary.json` | latest measurements (raw trials only in `results.json`); summary ships with the site | | +| `demos/screenshots/*.png` | captured by the eval's screenshot tour | | + +## Concepts and data structures + +Additional terms used in this doc (repo-wide terms such as op, trigger, situation, hold, mode, tier, late revert, budget follow the glossary): + +| Term | Meaning here | +|---|---| +| demo mode | `GcMode = "off" \| "guard" \| "heal"` (`src/shared/types.ts`). Demo **Off** maps to runtime mode `observe` with `model: false`. Do not confuse demo Off with `?genclass=off` (the runtime's kill switch, which installs nothing). | +| world | one mock-server session (`src/server/core.ts` -> `World`), keyed by a session id (`sid`): `live--` for an interactive page (sessionStorage `gc-demo-sid-`), `trial--` for a trial. Owns state, chaos, request log, event log, SSE streams, timers. | +| chaos | `RouteChaos` (global knobs) + `Chaos.routes` per-route overrides. Environment only, never app logic. | +| route key | string naming a route for chaos rules and logs, e.g. `search`, `notes/item`, `status/payments`, `board/events`. `resolveChaos` applies global, then each prefix (`status`), then the exact key. | +| common random numbers (CRN) | `World.rngFor(key)`: the n-th occurrence of the same logical request (`" "`) or live event gets `new Rng(hashString("\|\|"))`, so timing/failure draws do not shift when GenClass changes timing. | +| freeze | control action `world` / `"freeze"`: sets `World.frozen`, stopping scripted activity (`World.script` timers: teammates, random incidents); deliveries continue. | +| quiet | `World.quiet(idleMs, timeoutMs, ignoreStreams)`: no request in flight and (unless ignored) no pending SSE delivery for `idleMs`. | +| scenario | `Scenario { seed, kind, chaos, params, steps, intent, label }`; `intent` is read only by the oracle. | +| step | `Step` union discriminated by **`k`**: `{k:"type", sel, text, delays[]}` (one delay per char), `{k:"key", sel, key: "Backspace"\|"Enter"\|"Escape"\|"Tab"\|"ArrowLeft"\|"ArrowRight", delays[]}` (one press per delay), `{k:"click", sel, count?, gap?, unless?}` (`unless` = oracle condition that skips the click), `{k:"focus", sel}`, `{k:"caret", sel, pos: "end"\|"start"\|number}`, `{k:"wait", ms}`, `{k:"until", cond, timeout}` (named oracle condition), `{k:"chaos", patch}`, `{k:"server", action, args?}` (world action), `{k:"mark", name}` (epoch timestamp in `OracleContext.marks`). | +| world clock | scripted world activity (status incidents at `w.created + at`, board teammates, random incidents) is timed from world creation (`hello`), not from the session start `t0`. See the fairness gotcha in [Invariants](#invariants-and-gotchas). | +| demo host | `DemoDefinition.host`, the fake address in the app's window chrome: search `wander.example/search`, editor `notes.example/workspace`, checkout `fieldsupply.example/cart`, status `status.acme.example`, board `tasks.example/sprint-14`, decisions `journal.example/day-3`. | +| oracle | `Oracle { start?(), check?(cond), finish(): Promise }` built from `OracleContext { link, doc, el, scenario, marks, t0, tEnd }`. Samples the DOM with native timers; reads truth via `ServerLink.truth()` / `.log()`. Never given to GenClass or the app. | +| `Score` | `{ bug, reasons[], metrics: Record, details? }`. `metrics.latencyMs` is the demo's user-visible latency metric. | +| `TrialResult` | `Score` + `{ demo, mode, kind, seed, label, durationMs, gc: GcStats, driver: "synthetic"\|"playwright", error?, trace? }`. | +| `GcStats` | `{ runtime: "real"\|"shim", isolated?, status, model?, device?, variant?, loadMs?, decisions, detections, notExecuted, interventions: InterventionSummary[], decisionLatencyMs[], diagnoses }`. `notExecuted` keys are `Decision.reason` with digits replaced by `#`. | +| false intervention | one `act` event (an executed non-passive action, including failed attempts and late reverts) on a clean trial. | +| fixed / introduced | paired with Off on the same chaos seed: Off bug -> mode ok / Off ok -> mode bug (`summarizeMode`). | +| A/A noise | flips between two Off runs of the same seeds; the floor for reading fixed/introduced (board: 1 of 30 after CRN, per `NEEDS.md` §4). | +| jump-back | board oracle metric: a card the user moved shows its previous column again 400 ms–5 s after the server accepted the move, before any newer move of that card. | +| trace run | `?trace=1` / `eval.ts --trace`: records every proposed write (`hooks.mutationProposed`), each `state` event (applied write), ops and decisions into `window.__gcTrace`. Off by default; never in published results. | +| runtime shim | `src/dev/runtime-shim/`: observe-only stand-in aliased when `packages/runtime/dist/index.js` is missing or `GENCLASS_SHIM=1`; results then say `runtime: "shim"`. | +| COI | cross-origin isolation: the Service Worker adds COOP/COEP/CORP headers so `crossOriginIsolated` is true and WASM threads are available to the model. | + +Key types (abridged; field names exact): + +```ts +// src/shared/demo-def.ts +interface DemoDefinition { + id: DemoId; host: string; // fake address in the window chrome + mount(ctx: AppContext): void | Promise; // AppContext { gc: Runtime; el; mode: GcMode; embed: boolean } + scenario(seed: number, kind: TrialKind): Scenario; + oracle(ctx: OracleContext): Oracle; + chaosExtras?(link: ServerLink): HTMLElement; // demo-specific server controls + code: string; // highlighted integration snippet (HTML) + plugins?(): Plugin[]; + settle?: { idleMs: number; timeoutMs: number; ignoreStreams?: boolean } | false; // default { idleMs: 700, timeoutMs: 20000 } + serverParams?: Record; // world params for the interactive page + loaded?: string; // oracle condition awaited before the session +} + +// src/shared/protocol.ts (page -> Service Worker, each with a MessagePort for the reply) +type ControlMessage = + | { type: "hello"; sid; demo; reset?; seed?; chaos?; params? } | { type: "ping"; sid? } + | { type: "chaos"; sid; patch; replace? } | { type: "state"; sid } | { type: "log"; sid; since? } + | { type: "quiet"; sid; idleMs; timeoutMs; ignoreStreams? } | { type: "world"; sid; action; args? } | { type: "bye"; sid }; +// plus the untyped { type: "claim" } used by ensureServiceWorker +interface LogEntry { id; method; path; query; route; t0; tHandled?; tEnd?; status?; + outcome: "pending" | "ok" | "client-error" | "rejected" | "lost" | "network"; effect?; aborted?; spike?; body? } +``` + +`LogEntry.outcome`: `rejected` = 5xx before handling (or outage 503), `lost` = handled then 502/504 (side effects stay), `network` = offline (`Response.error()`), `client-error` = handler returned ≥ 400 or 404 route. All times (`t0`, `tHandled`, `tEnd`, `EventEntry.t`, `deliveredAt[]`) are epoch ms = `performance.timeOrigin + performance.now()` of the Service Worker (`core.ts` -> `now`); the page side uses the same formula (`server.ts` -> `epochNow`). + +Control messages and their replies (`src/server/sw.ts` -> `control`; every reply has `ok`, failures `ok: false, error`; `ServerLink.send` throws `ServerError` when `ok` is false and `error` is set): + +| `type` | Effect | Reply fields | +|---|---|---| +| `claim` | `clients.claim()` (sent by `ensureServiceWorker` to an uncontrolled page) | `{ ok: true }` | +| `ping` | binds client id -> `sid` if given | `buildId`, `epoch` (random per worker instance), `known` (world exists) | +| `hello` | creates a world when none exists, `reset` is set, or the existing world is for another demo (old one disposed); binds client | `buildId`, `epoch`, `created`, `chaos`, `t` | +| `chaos` | `World.setChaos(patch, replace)` | `chaos` | +| `state` | `WorldDef.snapshot(w)` | `t`, `created`, `state`, `chaos`, `events` (count) | +| `log` | request log entries with `id > since`, all events | `t`, `log`, `events` | +| `quiet` | `World.quiet(idleMs, timeoutMs, ignoreStreams)` | `quiet`, `waited` | +| `world` | `"freeze"` sets `frozen`; other names go to `WorldDef.action` | `result` (`ok` is false when the action returned `undefined`) | +| `bye` | disposes `trial-*` worlds only; unbinds this client | `{ ok: true }` | + +Page side (`src/shared/server.ts` -> `ServerLink(sid, demo)`): `send(msg, timeoutMs = 10000)` (waits up to 5 s for a controller), `hello(opts)` (remembers opts for re-binding), `startHeartbeat()` (ping every 5 s with a 4 s timeout; re-`hello`s with the remembered opts and `reset: false` in three cases: on `{type:"identify"}` (re-hello only, never `onRestart`), on `controllerchange` (`onRestart` if the reply says `created`), or when `ping` says `known: false` (`onRestart` always)), `stop()`, `setChaos(patch, replace = false)`, `truth()` -> `ServerTruth { t, created, state: S, chaos, events }`, `log(since = 0)`, `quiet(idleMs, timeoutMs, ignoreStreams = false)` (control timeout `timeoutMs + 5000`), `world(action, args)` -> `result`, `bye()` (2 s timeout, errors ignored). + +World API (`src/server/core.ts`): + +| Member | Meaning | +|---|---| +| `WorldDef { demo, create(rng, params), routes, snapshot(w), start?(w), action?(w, name, args) }` | one per demo in `src/server/worlds/`; registered in `sw.ts` -> `DEFS` | +| `Route { method, pattern: RegExp, key(m), handle?(w, req), stream? }` | `pattern` matches the path after `api` (e.g. `/notes/n1`); capture groups become `req.params` | +| `Req { method, path, query: URLSearchParams, body, raw, headers, params, entry }` / `Res { status, json?, headers?, work?, effect? }` | `body` is parsed JSON (or the raw string); `work` = extra server ms (× `spikeFactor` on a spike); `effect` is logged | +| `rng` / `scriptRng` / `rngFor(key)` | handler RNG (per request: `new Rng(handlerSeed)`; outside requests the base RNG `Rng(seed ^ 0x5eed)`); script RNG `Rng(seed ^ 0xc0ffee)`; CRN generator | +| `after(ms, fn)`, `every(ms, fn)` (unused), `script(ms, fn)` | world-owned timers (cleared on `dispose`); `script` skips when `frozen` | +| `publish(type, data, key?)`, `openStream(clientId)`, `openStreams` (unused) | SSE | +| `inflight`, `pendingDeliveries`, `lastActivity`, `frozen`, `disposed`, `created`, `log`, `events`, `state`, `chaos`, `params`, `seed`, `sid` | bookkeeping read by `quiet`, `sw.ts` and snapshots | + +Aggregation output (`src/shared/aggregate.ts`): `Rate { n, k, rate, lo, hi }`; `ModeSummary { mode, chaos: Rate, clean: Rate, falseInterventions, cleanTrialsWithIntervention, cleanTrials, interventionsPerChaosTrial, decisionsPerTrial, detectionsPerTrial, latencyMs, latencyChaosMs, decisionP50, decisionP95, fixed, introduced, paired, notExecuted, actions, errors, runtime, modelStatus, metrics }`; `DemoSummary { demo, modes: Partial>, trials }`. `results*.json` `demos.` is `DemoSummary.modes`. + +Trace shape (`src/shared/trace.ts`, stored in `window.__gcTrace` and `TrialResult.trace`): `Trace { origin (performance.timeOrigin), proposals: TraceProposal[], applies: TraceApply[], decisions: TraceDecision[], ops: Record }`. `TraceProposal { id, t, store, paths (≤ 12), cause?, changes (≤ 12, values shortened to 60/160 chars) }` from `hooks.mutationProposed`; `TraceApply { t, mutation, store, paths, user, op?, summary }` from `event` kind `state`; `TraceOp { kind, name, t, cause? }` from the first `op.start`/`user` event per op; `TraceDecision { id, trigger, subject (≤ 160 chars), at, latencyMs, action, candidate?, mass?, executed, reason?, diagnosis, mutation?, op? }` from `decide` (`mutation`/`op` from `Decision.subjectRef`). Times `t` are page `performance.now()`. + +## How it works + +### 1. Page boot (`src/site/demo-page.ts` -> `bootDemo`) + +1. `applyTheme()`; `trialParams()` decides the page kind (`?embed=trial` -> trial page). +2. `ensureServiceWorker(siteRoot())` (`src/shared/server.ts`): registers `sw.js` (`type: "module"` in dev, `"classic"` in prod, `scope: root.pathname`, `updateViaCache: "none"`); up to 3 attempts to get control (posts `{type:"claim"}`, waits for `controllerchange` 3 s / 5 s); if still uncontrolled, reloads once (sessionStorage `gc-demo-sw-reload`) then throws. If the top-level page is not `crossOriginIsolated` and `?coi=0` is absent, reloads once (`gc-demo-coi-reload`). If the controller's `buildId` differs from `__BUILD_ID__` (non-dev), calls `reg.update()` and waits up to 6 s. +3. **Interactive page** (`bootInteractive`): `ServerLink(sessionId(demo))`, `hello({ chaos: loadChaos(demo), params: def.serverParams, seed: 7 })` (re-applies saved chaos with `replace` if the world already existed), `startHeartbeat()`; `link.onRestart` = toast "The mock server restarted and its data was reset" then `location.reload()` after 1,500 ms; `pagehide` -> `link.stop()`; `startGenClass(getMode(), { baseUrl: modelBaseUrl(root), plugins: def.plugins?.(), holdBudgetMs: holdBudget() })`; renders top bar, hero, mode card (segmented Off/Guard/Heal + model status), app frame + net lane, explain cards (`DEMO_BY_ID[id].wrong/scored` + `def.code`), Try it, Activity, Chaos panel, Trials; `await def.mount(...)`; exposes `window.__demo = { scenario, setChaos, world }` for the screenshot tour; mounts `mountDevtools(gc, { collapsed: ?devtools !== "open", theme, position: "bottom-right" })` (`theme` = forced `data-theme` or `"auto"`; mount errors only `console.warn`) and remounts it collapsed on the `gc-theme` event. The mode card (`modeCard`) shows `MODE_HINT[mode]`, or a kill-switch hint when `?genclass=` is present, or the `?budget` experiment; the model status line repaints on `gc.on("status")` and every 400 ms while loading ("Model ready · wasm · q8 · threads|1 thread · loaded in N s", "Model unavailable … · acting passively", "No model · observing only", or "Development stand-in runtime · no model" for the shim). +4. **Trial page** (`bootTrial`): `body.embed`; `scenario = def.scenario(seed, kind)`; `ServerLink("trial--")`, `hello({ reset: true, seed, chaos: scenario.chaos, params: scenario.params })`; `startHeartbeat()` (no `onRestart` handler on trial pages); `pagehide` -> `link.bye()`; `startGenClass(mode, { ..., trace: traceOn() })`; for Guard/Heal waits for `gc.ready` (max 120 s; a rejected `ready` is ignored) **before mounting the app** (the world, and its clock, already exist at this point); mounts; creates `TrialHarness`; waits for `def.loaded` (`harness.check`, max 15 s) or `link.quiet(250, 10000, true)`; `harness.start()` (oracle starts sampling); sets `window.__trial`. `window.__trialReady` resolves to it; failures set `window.__trialError`. +5. Boot failures on either page kind (no Service Worker support, the worker never takes control, any exception) go to `fatal`: an error card ("This demo could not start") replaces the page and `window.__trialError` is set, which the in-page runner and the eval turn into an error result. + +### 2. Mock server request path (`src/server/sw.ts` + `src/server/core.ts` -> `World.handle`) + +1. `fetch` listener: same origin only. Paths under `api/` are API calls; other `GET`s with destination `document|iframe|worker|sharedworker` are re-fetched and get `Cross-Origin-Opener-Policy: same-origin`, `Cross-Origin-Embedder-Policy: require-corp`, `Cross-Origin-Resource-Policy: same-origin` unless `?coi=0` (document URL, or referrer for workers). +2. `resolveSid(clientId)`: the binding from `hello`/`ping`; unknown clients get `{type:"identify"}` and up to 5 s for the page to re-`hello`. No world -> `503 "The demo server lost this session. Reload the page."` +3. `World.handle`: route match by method + regex; log entry (`route` = route key or `"unknown"`; 404 for no route). `c = resolveChaos(chaos, entry.route)`. +4. Stream routes (`stream: true`): offline -> `Response.error()`; outage -> 503; else `openStream` (SSE, first chunk `retry: 1000`, keep-alive comment every 15 s). +5. Normal routes: read body; draw everything up front from `rngFor(" ")`: timing `sampleTiming`, `fail`, `failCode` ∈ {500, 502, 503}, `commitFail`, `commitCode` ∈ {502, 504}, `hang`, `handlerSeed`. +6. Order: offline -> wait `min(up, 150)` -> network error. Wait `up`. Outage -> wait `down` -> 503. `fail < failRate` -> wait `down` -> 5xx, **no side effects**. Run the handler (world `rng` = `new Rng(handlerSeed)` during the call; exceptions -> 500). `down += res.work × (spikeFactor if spike)`. If `status < 400` and `commitFail < commitFailRate` -> 504 after `max(down, hangMs × 0.5)` or 502 after `down`, outcome `lost`, **side effects stay**. If `hang < timeoutRate` -> `down += hangMs`. Wait `down`, respond JSON (`cache-control: no-store`). +7. `World.publish(type, data, key?)` (live events): one `rngFor("event ")` per logical event (`key` defaults to `JSON.stringify(data)`); each open stream gets an independent delay `sampleEventDelay(erng, resolveChaos(chaos, "/events"))`, so events can overtake each other. Payload `id: \ndata: {"seq","type",...data}`. +8. Housekeeping: log capped at 6,000 entries, events at 2,000; every 10 s, worlds with no live bound client are disposed once `lastSeen` (last `hello`/`ping`/API call) is more than 15 s (`trial-*`) or 120 s (live) old. `bye` disposes only `trial-*` worlds. +9. Worker lifecycle: `install` -> `skipWaiting()`, `activate` -> `clients.claim()`. Worlds, bindings and `lastSeen` live only in the worker's memory; if the browser stops and restarts the worker, every world is gone. Whichever comes first decides what the page does: a heartbeat `ping` gets `known: false`, the page re-`hello`s (fresh world) and the interactive page reloads via `onRestart`; an API call triggers `identify`, the page re-`hello`s and gets a fresh world silently (no `onRestart`, and the next ping then says `known: true`). A stream route (`board/events`) is logged as `ok` the moment the stream opens. + +### 3. Chaos timing model (`src/shared/chaos.ts`) + +1. `sampleTiming(rng, c)`: `median = max(1, latency)`, `sigma = ln(1 + jitter / median)`, `total = clamp(lognormal(median, sigma), 2, 30000)`; spike with probability `spikeRate` multiplies `total` by `max(1, spikeFactor)`; `up = total × U(0.25, 0.5)`, `down = total − up`; if `reorder > 0`, `up += Exp(reorder × max(median, 40))`, `down += Exp(that × 0.5)`. +2. `sampleEventDelay(rng, c)`: `median = max(4, latency × 0.4)`, `sigma = ln(1 + jitter / max(1, latency))`, `clamp(lognormal, 1, 20000)`, plus `Exp(reorder × max(latency, 40))` when `reorder > 0`. +3. Interactive chaos is changed by `mountChaosPanel` (debounced 120 ms; `setChaos(chaos, true)` and `saveChaos` to `localStorage["gc-demo-chaos-"]`). Preset buttons apply `withPreset(id)` but keep the current `routes`; "Reset" goes back to `{ ...CALM, routes: {} }`; the pressed preset is `matchPreset(chaos)` (compares every global key, ignores routes); the summary line is `describeChaos`. `hangMs` has no slider (the "Hangs (6–8 s)" label assumes the preset/CALM values). Trials set chaos in `hello` and may patch it mid-session with `chaos` steps. +4. Merge semantics (`mergeChaos(base, patch)`): global keys are shallow-replaced; `patch.routes[k]` is merged into the existing rule for `k`; `patch.routes[k] = null` deletes that rule. `World.setChaos(patch, replace)` merges into the current chaos, or into a fresh `CALM` when `replace` is true. + +### 4. Trial lifecycle (`src/shared/harness.ts` -> `TrialHarness`) + +1. Driver calls `begin()` (sets `ctx.t0`), then runs `steps` (synthetic: `runSynthetic()` -> `runSteps(document, steps, hooks)`; Playwright: `e2e/eval.ts` -> `runSteps(page, steps, true)` calling `__trial.check/mark/chaos/server` through `page.evaluate`). `until` timeouts are recorded as `metrics.untilTimeouts`. +2. `finish(driver)`: `tEnd`; `link.world("freeze")`; if `settle !== false`, `link.quiet(idleMs, timeoutMs, ignoreStreams)` (default `{ idleMs: 700, timeoutMs: 20000 }`); then waits **2,500 ms** (350 ms when `settle === false`) so held writes and late reverts land; `oracle.finish()`; oracle exceptions become `{ bug: false, reasons: ["oracle failed"] }` with `error` set (excluded from rates). +3. Returns `TrialResult` with `gc: collectStats(gcs)` and, in trace runs, `trace`. + +### 5. Drivers + +- **Synthetic** (`src/shared/driver.ts` -> `runSteps`): per typed char `keydown` (`code` `KeyX`/`DigitN`/`Space`), `keypress`, `beforeinput` + `setRangeText` + `input` (`insertText`; `\n` -> Enter), `keyup`; Backspace -> `deleteContentBackward`; Enter in `` -> `form.requestSubmit()`; clicks fire `pointerover/enter`, `mouseover`, `pointerdown`, `mousedown`, focus, `pointerup`, `mouseup`, `click` (+ `dblclick` when `count === 2 && gap < 300`); clicks on disabled controls do nothing; selectors are awaited up to 5 s (clicks 4 s). All waits use native timers. The runtime's DOM observer keeps untrusted events when no app op is running (`packages/runtime/src/observe/dom-user.ts` -> `programmatic`). +- **Playwright** (`e2e/eval.ts` -> `runSteps`): `page.keyboard.type/press` (one char at a time after its delay; missing delays default to 90 ms in both drivers), `locator.click` (click waits up to 1,500 ms for an enabled, visible element on the first click, 200 ms on repeats; `click` timeout 2,000 ms, errors ignored), `waitForFunction` for `until` (polling 25 ms); `wait` is `page.waitForTimeout` (Node side, invisible to the runtime). With `harness = false` (screenshot tour on the interactive page) `mark` is skipped, `chaos`/`server` go through `window.__demo`, `until` just waits `min(1500, timeout)` and `unless` is never true. +- `TrialHarness.check(cond)` returns `false` when the oracle has no `check` or throws, so a broken condition makes `until` steps time out (counted in `metrics.untilTimeouts`) instead of failing the trial. + +### 6. In-page trial runner (`src/site/trials-panel.ts` -> `mountTrials`) + +1. Plan: `n` chaos seeds `1000..1000+n−1` and `clean = max(2, ceil(n/2))` clean seeds `1500..` (checkbox can disable clean), each × Off/Guard/Heal; `n` ∈ {3, 6, 10, 20, 30}, default 6. +2. Each job loads `?embed=trial&mode&kind&seed&run` in one iframe (keeps `budget`, `model`, `coi` from the page URL), polls every 50 ms for `__trialReady`, calls `harness.runSynthetic()`; 150 s timeout per trial; errors are recorded as error results. +3. Job order: every chaos seed with Off, Guard, Heal in turn, then every clean seed; one iframe at a time. "Stop" finishes the current trial first. Errored trials get a placeholder result (`label: "–"`, `gc.runtime: "real"`, `gc.status: "error"`). +4. Table via `summarizeMode` (columns: bug rate with meter, false interventions / clean runs, clean bugs, fixed / new, clean latency p50 with delta to Off, model decision p50) plus a per-trial log; "Copy JSON" copies raw results. The placeholder asks to keep the tab visible while trials run (background tabs throttle timers). + +### 7. Headless eval (`e2e/eval.ts`) + +1. Requires `dist/index.html` (exit 2 otherwise). Model: `--model` default `genclass-model/` when `dist/genclass-model/model.json` or `<--model-dir|GENCLASS_MODEL_DIR>/model.json` exists, else `cdn`. +2. `serveStatic(dist, "/genclass/", 4173, { "genclass-model": MODEL_DIR })` (the mount only when `MODEL_DIR` is set; with `--model genclass-model/` and no local model it logs a warning and Guard/Heal run without a model); Chromium headless. Before the trials it records `servedCard()` (the served `model.json` name/version/variants, or `{ source }` for `cdn` / unreachable URLs) and `runtimeBuild()`; `IS_V01` (card name `genclass-model`, version `0.1*`) adds the "general classifier, not trained for runtime decisions" sentence to the results note. +3. `planJobs()`: for `i < max(N, CLEAN)`, for each demo: chaos seed `SEED_BASE + i` (if `i < N`) and clean seed `SEED_BASE + 500 + i` (if `i < CLEAN`), each × modes. `WORKERS` browser contexts (1280×900) pull from one queue; each context first `warmUp` (opens `search/?mode=off`, waits for `crossOriginIsolated` and a mounted app, 30 s). +4. `runTrial`: new page at the trial URL (`embed=trial`, `mode`, `kind`, `seed`, random `run`, `model=`, plus `budget`/`trace=1` when set; `goto` 60 s), wait for `__trial` or `__trialError` (150 s), `begin`, real-input steps, `__trial.finish("playwright")`; adds `metrics.untilTimeouts` and `metrics.pageErrors`; whole trial capped at `--trial-timeout` (180 s); any failure becomes an error result (`failed`). Partial results every 12 trials to `e2e/.out/partial.json`. Results are written to `--out` (default `demos/`); `e2e/.out/` is always under `demos/`. The run then prints the first 16 lines of `results.md`. +5. `writeReports`: `results.json` (summaries + `raw`), `results-summary.json` (no raw; copied to `dist/` only when `SUFFIX` is empty, i.e. no `--tag` and no `--budget`), `results.md`; with `--trace`, `e2e/.out/traces.json`. Records `model.card` (served `model.json`), `runtimeBuild` (`packages/runtime` version + sha256 of `dist/**/*.js`, 12 hex), `policy`, seeds, definitions. JSON top-level keys: `generatedAt`, `runtime`, `model { name, note, status, baseUrl, card, tag? }`, `runtimeBuild`, `driver`, `policy` (`"runtime defaults"` or `{ holdBudgetMs, note }`), `trials { chaos, clean }`, `modes`, `seeds { chaos: "a..b", clean: "a..b" }`, `definitions`, `demos` (`` -> `DemoSummary.modes`), `raw` (`TrialResult[]` without `trace`). `results.md` = header (runtime, model note), driver line, summary table (`mdTable`), one section per demo (`mdDemo`: per-mode sentence with Wilson CI, false interventions, fixed/introduced, actions and "chosen but not run" reasons; a table of mean metrics `chaos.*`/`clean.*` per mode; the top 5 Off bug reasons with digits masked as `#`), then "How to reproduce". +6. Screenshot tour (unless `--no-shots`; `--shots-only` skips the trials): light and dark contexts (1440×1000): `index.png` / `index-dark.png` (+ `index-full.png` light), `.png` / `-dark.png` (Guard, devtools open, waits up to 90 s for the model status to leave `loading`, clicks the preset button named by `SHOT_PRESET` = search/editor/board/decisions `Busy`, checkout/status `Flaky`, then the first 40 steps of `scenario(1003, "chaos")` via `window.__demo`), light only: `-page.png` and `-full.png` (devtools collapsed; viewport / full page), `decisions-heal.png` (Heal, Storm), `search-trials.png` (in-page runner with 3 chaos + 2 clean seeds per mode; skip with `--no-trials-ui`); mobile 390×844: `index-mobile.png`, `search-mobile.png`. + +### 8. Aggregation (`src/shared/aggregate.ts` -> `summarizeMode`) + +1. Bug rate: `wilson(k, n)` (z = 1.96) over non-error chaos trials; clean bug rate likewise. +2. `falseInterventions` = sum of `gc.interventions.length` on clean trials; `cleanTrialsWithIntervention`. +3. Paired fixed/introduced vs Off on the same chaos seed (skips pairs with errors). +4. `latencyMs` / `latencyChaosMs` = median (`quantile(…, 0.5)`, linear interpolation) of `metrics.latencyMs` over clean / chaos trials; `decisionP50`/`P95` over all `decisionLatencyMs`; `metrics` = mean of each metric key, prefixed `chaos.` / `clean.`. + +### 9. GenClass wiring (`src/shared/genclass.ts` -> `startGenClass`) + +1. `policy = holdBudgetMs ? { holdBudgetMs } : undefined` (`?budget=`). +2. Trace runs pass `hooks: traceHooks(trace)` (cast through `Partial`; `GenClass.init` spreads options into `createRuntime`) and `attachTrace` subscribes to `event` (`state`, `op.start`, `user`) and `decide`. +3. Off: `GenClass.init({ mode: "observe", model: false, plugins, policy })`. Guard/Heal: `GenClass.init({ mode, model: { baseUrl?, preload: "eager" }, plugins, debug, policy })`. +4. Session arrays fed by `gc.on("decide" | "detect" | "act" | "report")`; `readyAt` from `gc.ready`. +5. `collectStats(session)` -> `GcStats`: `runtime` = `RUNTIME_KIND` (from the `__RUNTIME_KIND__` define), `isolated` = `crossOriginIsolated`, `status`/`model`/`device`/`variant` from `gc.status`, `loadMs` = `status.loadMs` or `readyAt − initAt`, `diagnoses` counted over all decisions, `notExecuted` over decisions with `!executed && reason`, `interventions` = every `act` record (`{ action, tier, trigger, changed, at }`), `decisionLatencyMs` rounded to 0.1 ms. `statusText(gc)` formats `gc.status` for compact display. + +### 10. The six demos + +Common: each `main.ts` calls `bootDemo` with `host`, `mount`, `scenario`, `oracle`, `code` and optional `loaded`, `settle`, `chaosExtras`, `serverParams`, `plugins`. Scenario RNG: `new Rng("::")`; server world RNG: the numeric trial seed (`state` from `Rng(seed)`, request handlers from CRN, scripts from `Rng(seed ^ 0xc0ffee)`). Clean chaos is always `CLEAN_CHAOS` (45 ± 15 ms, no failures, no spikes, no reorder). + +#### search: city typeahead (`src/demos/search/`) + +| Aspect | Detail | +|---|---| +| App | `app.ts` -> `mountSearch`: input -> atom `input`/`loading`, 150 ms debounce (`setTimeout`), `GET /api/search?q=` -> `search.set({ query, items, total })`. | +| Latent bug | no ordering guard (no AbortController, no request id): an older, slower answer can overwrite newer results. | +| Store | `gc.atom("search", { input, query, items, total, loading, error })`. | +| Server | `worlds/search.ts`: route `GET /search` (key `search`), `searchCities(q)` from the missing `data/cities.ts`; `work = 20 + min(total, 60) × 9` ms (short prefixes slower). | +| Scenario | 1 round, or 2 with P 0.45 (chaos) / 0.3 (clean); city from `TYPED_TARGETS`, 70% lowercased, 50% typed in full else stopped at 4..len (min 3); round 2 clears with one Backspace per char (40–90 ms); chaos: 60% "glance" pause after 2–3 chars if > 4 chars; marks `typed`, `lastKey`; waits 1.6–2.6 s. Intent `{ finalQuery, queries }`. Typist: clean `CALM_TYPIST`, chaos `FAST_TYPIST` with median 110–210 ms. Chaos ranges: latency 120–650, jitter 80–550, reorder 0–0.7, spikeRate 0–0.12, failRate 0–0.04, spikeFactor 4. Settle: default. | +| Oracle | samples every 20 ms; `ok` = shown ids equal `searchCities(input).items` ids. Bug if final list wrong, or `staleMs ≥ STALE_BUG_MS` (400) where stale time counts only while an answer for the current text (sent since the text changed) arrived ≥ `GRACE_MS` (350) earlier. Metrics `finalWrong`, `staleMs`, `wrongVisibleMs`, `staleShare`, `latencyMs` (last keystroke -> list correct and stays correct), `requests`. Condition `settled`. | + +#### editor: notes autosave (`src/demos/editor/`) + +| Aspect | Detail | +|---|---| +| App | `app.ts` -> `mountEditor`: `DEBOUNCE_MS` 700, `MAX_WAIT_MS` 3000 (save immediately if the first unsaved edit is ≥ 3 s old), `TYPING_GUARD_MS` 300, `REFRESH_MS` 5000 background refresh (skipped unless status `saved`/`idle` and no key in 2 s), retry after a failed save 2000 ms. | +| Latent bugs | saves not serialised (overlap, out-of-order at server); echo applied unless a key was pressed in the last 300 ms (`applyBody`); any success shows "Saved"; refresh checks local edits when it starts, not when it answers. | +| Store | Redux `legacy_createStore(reducer, initial, genclassEnhancer(gc, { name: "notes" }))` (`store.ts` -> `createNotesStore`). Actions `notes/listed`, `note/loaded`, `note/selected`, `note/edited`, `save/started`, `save/succeeded {note, applyBody}`, `save/failed`. `SaveStatus = "idle" \| "dirty" \| "saving" \| "saved" \| "error"` is rendered as `save-status[data-state]`; `save/succeeded` with `applyBody: false` keeps the local body but takes the server's `version`. | +| Server | `worlds/editor.ts`: `GET /notes` (`notes`), `GET /notes/:id`, `PUT /notes/:id` (both `notes/item`); PUT bumps `version`, appends `history` (cap 400, keeps entry 0), `work = 15 + body.length × 0.02`. Seed notes `n1` Launch checklist, `n2`, `n3`. | +| Scenario | click body, caret end, 2–4 bursts of sentences (first prefixed `\n`); pauses clean 0.9–2.6 s, chaos 0.25–2.2 s; mark `lastKey`; wait 1.2–2.0 s. Chaos typist `FAST_TYPIST` median 120–200, typoRate 0.04. Chaos: latency 100–900, jitter 60–700, reorder 0–0.8, failRate 0–0.1, spikeRate 0–0.1, spikeFactor 4. `loaded: "loaded"`, settle `{ idleMs: 900, timeoutMs: 25000 }`. Intent `{ noteId: "n1", typed }`. | +| Oracle | samples text + `data-state` every 25 ms. Bug if editor text ≠ seed body + typed (`lostLocal`), server body ≠ editor (`lostServer`), final "saved"/"idle" while server differs (`finalLie`), else a "Saved" lie run > `LIE_BUG_MS` (1500). Metrics `lieMs`, `maxLieMs`, `reverts` (text shrank to a prefix by > 1 char), `saves`, `latencyMs` (last key -> saved and true). | + +#### checkout: cart and checkout (`src/demos/checkout/`) + +| Aspect | Detail | +|---|---| +| App | React 19 `app.tsx` -> `Store`: optimistic add/qty/remove with `fetchWithTimeout` 4,000 ms; `placeOrder` posts `{ lines, total }` with 5,000 ms timeout, retries 5xx/timeouts/network up to 3 attempts with `600 × attempt` ms backoff (a 4xx shows the server's error and stops). `place-order` is disabled only when the cart is empty and no order is placing (class `busy` while placing); `add-`/`inc-` disable at stock; in-app toast 3,500 ms. Test ids: `add-`, `inc-`, `dec-`, `remove-`, `cart`, `cart-count`, `cart-line[data-sku]`, `line-qty`, `line-price`, `cart-total`, `place-order`, `order-error`, `order-confirmation`, `placed-order`, `app-toast`. | +| Latent bugs | Place order stays clickable while placing; retries without an idempotency key; total maintained incrementally (failed changes revert the line but not the total; a revert restores the quantity captured at click time). | +| Store | `useGenClassState("cart", EMPTY, { resync: () => reloadCart() })`, `useGenClassState("orders", …)`; products in plain `useState`. No provider (adapter falls back to `GenClass.runtime`). | +| Server | `worlds/checkout.ts`: `PRODUCTS` (mug 1800¢ stock 8, tee 2900/5, cap 2400/3, tote 1600/10, notebook 1200/6, stickers 600/4); `GET /products`, `GET /cart`, `POST /cart/lines` and `PATCH\|DELETE /cart/lines/:sku` (key `cart/lines`, clamp to stock), `POST /orders` (key `orders`, 201, id `A-1041…`, `work` 120, total taken from the client, clears cart), `GET /orders` (`orders/list`). Snapshot includes `cartHistory`. | +| Scenario | until `loaded`; 2–4 products (chaos: 25% double add); 1–3 `+` clicks on 1–2 lines; 30% one `−`; mark `order`; click style clean `once`, chaos weighted double 0.35 (gap 70–180 ms) / impatient 0.3 (re-click after 1.2–2.6 s `unless: "orderDone"`) / once 0.35; until `orderDone` (20 s); wait 900 ms. Intent `{ orders: 1, qty }`. Conditions: `loaded` (any `add-` button), `orderDone` (confirmation or error shown and not placing). Chaos: latency 150–700, jitter 100–500, failRate 0.03–0.2, commitFailRate 0.02–0.12, timeoutRate 0–0.06, spikeRate 0–0.1, hangMs 6500, spikeFactor 5. Settle `{ 900, 25000 }`. | +| Oracle | samples every 30 ms. Bug if orders > intended (1), "Order placed" without an order, error shown but order placed, still placing, any order whose `total ≠ Σ qty × price` (wrong charge), displayed total ≠ sum of displayed lines at the end or for > `DRIFT_BUG_MS` (1000), or (no order) screen cart ≠ server cart. Metrics `ordersCreated`, `duplicates`, `wrongCharges`, `driftMs`, `maxDriftMs`, `errorsShown`, `latencyMs` (`order` mark -> first confirmation). | + +#### status: service status dashboard (`src/demos/status/`) + +| Aspect | Detail | +|---|---| +| App | `app.ts` -> `mountStatus`: `POLL_MS` 2000 `setInterval(refreshAll)` (never waits), per-service `GET /api/status/:id` with 4,000 ms timeout, up to 3 attempts with no backoff, then status `unreachable` + banner (last 3 kept); render every 1 s; Refresh button. | +| Latent bugs | overlapping poll rounds; immediate retries (retry storm); one failed poll = "Unreachable" + error banner. | +| Store | the app's own `createStore` handed over with `gc.guard("services", raw, { resync: () => refreshAll() })`. | +| Server | `worlds/status.ts`: `SERVICES` api, auth, payments, search, notify, cdn; route `GET /status/:id`, key `status/`; `truthAt(incidents, svc, t)`; reply `latencyMs` 35–95 (operational), 400–1200 (degraded), null (down); `work` 4. Random incidents (interactive): first after 6–15 s, then every 20–45 s, 35% down, 8–20 s. Actions `incident {svc, status, dur}`, `resolveAll`. Extras panel: "Real incidents (12 s)". | +| Scenario | params `{ incidents, randomIncidents: false }`: 1–2 incidents (40% down) at 3–9 s for 3.5–7 s. Clean: Refresh once, wait 9–12 s. Chaos: 1–3 routes with `failRate` 0.25–0.6, one route `spikeRate` 0.15–0.4 × 5–9; global latency 80–320, jitter 50–260, failRate 0–0.06, timeoutRate 0.02, hangMs 6000; Refresh 1–3× (gap 150–450 ms); 70%: one route `outage: true` for 4–8 s (the status API is down, the service is fine). Both kinds start with `until loaded` (10 s) then wait 2–3.5 s. `loaded: "loaded"` (no card shows `unknown`), `settle: false`, interactive `serverParams: { randomIncidents: true }`. Note: a status route keeps answering **200** while the service is `down`; only chaos produces HTTP failures. | +| Oracle | samples every 50 ms, ignores the first `GRACE_MS` (3500) after t0. A card may show any truth from `[t − 3500, t]`. Bug if `falseAlarmMs > 1500` (red while no red allowed), `missedMs > 1500` (true `down` not shown), `otherMs > 3000` (including `unknown`), any banner, or requests > 1.5 × ideal (`6 × (session / 2000 + refresh clicks)`, counting `status/*` requests between `t0` and `tEnd`). Metrics `falseAlarmMs`, `missedMs`, `otherWrongMs`, `banners`, `requests`, `requestRatio`, `latencyMs` (mean delay from a true transition inside `[t0, tEnd − 3500]` to the card first showing it). | + +#### board: team kanban (`src/demos/board/`) + +| Aspect | Detail | +|---|---| +| App | React 19 + Zustand; `EventSource(api("board/events"))` -> `applyEvent`; optimistic `move` with `pending: true` ("syncing"), confirmation replaces the card; failure restores the whole `before` snapshot + notice (auto-dismiss 4 s). `applyEvent` replaces the card with the event's copy and sets `pending: false`, so any echo ends "syncing". Arrow buttons `mv-left-`/`mv-right-`, drag and drop; `live` indicator from `EventSource.onopen/onerror`. | +| Latent bugs | events applied with no version check; echo of your own move can land after your next move; whole-board rollback discards updates that arrived meanwhile. | +| Store | `create()(genclass(gc, "board", { resync })(creator))` (`store.ts` -> `createBoardStore`); `resync` calls the store's own `load()`. | +| Server | `worlds/board.ts`: `COLUMNS` backlog/doing/review/done; `BOARD_SEED` c1–c10; `GET /board` (`board`, work 20), `POST /cards/:id/move` (`board/move`), SSE `GET /board/events` (`board/events`). Every move bumps `version` and publishes `card.moved` with CRN key `:v::`. Teammates (Ana, Kofi, Mei) move a card every `Exp(teamEveryMs) + 1500` ms (first `+3000`), to a column ≤ 2 away. Action `teammateMove {card?, column?, recent?}` (`recent` = the card the user last moved). Interactive `teamEveryMs` 9000 (`≤ 0` disables teammates); the extras panel has "Teammate moves a card" and "…the one you just moved". Snapshot: `cards` (`{ column, version, updatedBy }` per id) and `moves[]` (`{ t, card, column, by, version }`, `by: "you"` for user moves). | +| Scenario | until `loaded`; 2–3 focus cards (60% of moves); clean 4–6 moves, waits 0.9–1.6 s, `teamEveryMs` 7000; chaos 6–10 moves, 35% immediate re-move (110–260 ms), 30% simultaneous `teammateMove` of the same card, waits 0.15–0.9 s, `teamEveryMs` 2000–4000; mark `lastMove`, wait 1.5 s. Chaos: latency 150–600, jitter 100–500, reorder 0.3–0.9, failRate 0.03–0.15, spikeRate 0–0.08, spikeFactor 4. Settle `{ 800, 25000 }`. | +| Oracle | samples columns and `data-pending` every 50 ms. Allowed column at t: server column at `t ± WINDOW_MS` (1500) or any move in that window. Bug if any card's final column ≠ server, else a divergence run > 2000 ms; plus cards still pending at the end. Metrics `finalMismatches`, `divergedMs`, `maxDivergedMs`, `jumpBacks`, `userMoves`, `teammateMoves`, `latencyMs` (last move -> board equals server). `details` carries mismatched cards for `trace-report.ts`. | + +#### decisions: field journal (`src/demos/decisions/`) + +| Aspect | Detail | +|---|---| +| App | `app.ts` -> `mountDecisions`: four typed questions with `{ timeoutMs: 2500 }`, each falling back to an app default on rejection: backup `gc.ask({ type: "noul", … })` (`noul ≥ 0.5` -> start; default start now; a postponed click retries once after 6 s); photo quality `gc.decide(…, { full, reduced, thumbnails })` (default `full`); leave `gc.ask noul` (default: the `dirty` flag, cleared when a save starts); connection health `gc.ask({ type: "score", criteria: failing…excellent })` rounded to a level (default `good` if `navigator.onLine`). Journal autosave 800 ms after typing; heartbeat `GET /api/ping` every 2,500 ms. Decisions log rendered as `[data-testid="decision"]` with `data-q/answer/source/asked-at/ms`. | +| Latent bug | the fixed defaults are wrong exactly when it matters (typing, struggling network, failed save). | +| Store | `gc.atom("journal", …)`, `gc.atom("gallery", …)`; plugin `backgroundWorkPlugin(jobs)` passed through `plugins()`. | +| Plugin | `plugin.ts`: `setup` listens to `visibilitychange`, `online`/`offline`, Battery API, and `jobs` events; records the backup as an op `api.recordOp("task", "background photo backup", …)` / `endOp`; `facts()` (backup progress, background tab, offline, battery < 20% discharging); action `pause_background` (`on: ["failure", "stall"]`, tier `heal`, risk `low`, `applicable` while a job runs, `ctx.describe(...)`, `ctx.onUndo` resumes). Plugin name `background-work`; custom events via `api.emit`: `page.visibility`, `network.online`, `network.offline`, `battery`, `backup.paused`, `backup.resumed`. | +| Jobs | `jobs.ts` -> `BackgroundJobs extends EventTarget` (singleton `jobs`): `start()` (`POST /api/backup`, then polls `GET /api/backup` every 1,000 ms), `pause()`/`resume()` (`POST /api/backup/pause\|resume`), `running()`, `current: JobInfo \| null` (`{ id, name, startedAt, progress, paused }`); dispatches `start`, `progress`, `end`, `pause`, `resume`, each followed by `change`. | +| Server | `worlds/decisions.ts`: `GET/PUT /journal` (`journal`, `journal/save`), `GET /photos?quality=` (`photos`; bytes full 2.4 MB / reduced 380 KB / thumbnails 24 KB; work 420/150/30 ms), `POST /backup` (`backup`, 202, `BACKUP_MS` 8000), `POST /backup/(pause\|resume)` (`backup/control`), `GET /backup` (`backup/status`), `GET /ping` (`ping`). While an unpaused backup runs (`backupActive`), `journal`, `journal/save` (base work 20), `photos`, `backup/status` get +350 ms `work` and `ping` +175 ms; `POST /backup` (work 40) and `backup/control` get none. Pause/resume with no running job -> 409; resume extends `endsAt` by the paused time. Snapshot: `body`, `version`, `history`, `backups`, `photoLoads`. | +| Scenario | until `loaded`, wait 2.5–4 s. Chaos condition uniform over healthy (latency 50–140, jitter 10–60), slow (650–1300, 150–450, spikeRate 0.05–0.15 × 3), flaky (150–400, 80–250, failRate 0.25–0.45), failing (200–500, 100–300, failRate 0.6–0.85). Moments: clean 3 of {backup-idle, photos, health, leave-saved}; chaos 3–4 of those plus backup-busy, leave-inflight (leave 850–1050 ms after typing, while the save is in flight), leave-failed (`journal/save` failRate 1 during the moment). Leave moments sorted last; a leave moment clicks Leave, waits `until leaveAnswered` (6 s), then clicks Stay `unless: "noConfirm"` and Reopen `unless: "notClosed"`. Typist: clean `CALM_TYPIST`, chaos `FAST_TYPIST` with typoRate 0.02. Intent `{ condition, moments }`. `loaded: "loaded"`, settle `{ 600, 15000, ignoreStreams: true }`. | +| Oracle | recomputes the right answer at each `askedAt` from keys (keydown/input), sampled text, server log and history. Backup = "start now" only if no key in 2.5 s, no `journal/save` in flight, no failure in 8 s and median ok latency over 10 s < 600 ms. Quality over 15 s: failRate ≥ 0.25 -> thumbnails, median ≥ 450 -> reduced, else full. Leave = "warn" if text ≠ stored body or a save in flight. Health over 15 s: level 3 if no requests; failRate ≥ 0.5 -> 0; ≥ 0.2 or median ≥ 900 -> 1; > 0 or ≥ 350 -> 2; ≥ 120 -> 3; else 4; correct within ±1. The backup's own `backup`/`backup/control` routes are excluded. Bug if any decision is wrong. Metrics `decisions`, `wrong`, `accuracy`, `answeredByGenClass`, `latencyMs` (mean ask time), `.n`, `.ok`. Conditions: `loaded` (journal text non-empty), `leaveAnswered`, `noConfirm`, `notClosed`. "Failure" = outcome `rejected`, `lost` or `network`; latency = `tEnd − t0` of `ok` requests. | + +### 11. Site shell (`src/site/`) + +1. **Landing** (`index.html` -> `src/site/landing.ts`, module side effects, no GenClass runtime on this page): `applyTheme()`, then replaces `#page` with `renderTopbar("home")` and sections `hero` (install snippet with Copy; the three "[GenClass]" console lines are **illustrative copy, not real output**), `modes` (Observe / Guard (default) / Heal adoption path), `demos` (cards from `DEMOS` + `ART`, links `/`), `results` (fetches `results-summary.json` with `cache: "no-store"`; reads `demos...chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`; shows "No measurements ship with this build yet" when absent), `how`, `observability`, footer (Apache-2.0, `REPO_URL`). +2. **Demo page layout** (`bootInteractive`): top bar; hero (`DEMO_BY_ID[id]` `n`, `tagline`, `title`, `summary`, `stack` badges) + mode card; main column = app frame (`.app-frame` with fake window chrome, `def.host`, mode chip, `.app-body` where the app mounts) + net lane + explain cards (`wrong`, `scored`, `def.code`); side column = Try it (`tryIt` HTML), Activity, Network chaos; then Run trials; footer. +3. **Activity panel** (`activity.ts` -> `mountActivity`): one row per `gc.on("report")` (`kind: "intervene"` counts as "prevented", anything else non-status as "flagged"; `kind: "status"` updates one status row in place). Titles from `ACTION_TITLE` (`discard`, `defer`, `coalesce`, `delay`, `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`) and `DIAG_TITLE` (`stale`, `conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, `transient`, `overload`, `unusual`). "Evidence" calls `gc.explain(id)` and shows `changed`, `facts`, diagnosis and action probability bars, `timeline`, and a toggle for `situationText`. "Undo" calls `ActionRecord.undo()`. Each intervention flashes the app frame (`gc-flash` class) and adds a shield toast over it (max 3, auto-close 7 s). A "Model consulted N× (median …)" line classifies every `decide`: executed with a non-passive tier -> acted, executed passive -> "chose to let it be", otherwise by `reason` substring (`"hold budget"` -> late, `"below the"` -> low confidence, `"expected"` -> judged expected, else not allowed in this mode); an "Observed …" line counts `event`s (`op.start` named like an HTTP method = request, `state` = write, `user`). +4. **Net lane** (`netlane.ts` -> `mountNetLane(link)`): polls `link.log(since)` every 300 ms (re-polling from the oldest pending entry; paused while the tab is hidden) and renders a 10 s waterfall on `requestAnimationFrame` (every ≥ 70 ms): 8 rows of 12 px, label `METHOD path?query` (≤ 34 chars), labels dropped when > 22 bars are visible, class per `LogEntry.outcome` and `spike`, tooltip with status, duration, `effect` and "aborted by the page". +5. **Chaos panel extras**: `DemoDefinition.chaosExtras(link)` renders demo-specific server controls under the sliders: status "Real incidents (12 s)" (service select, Degrade / Start outage -> `world("incident", { svc, status, dur: 12000 })`, Resolve all -> `world("resolveAll")`); board teammate buttons (see the board table). + +### 12. Build, dev server and scripts + +1. `npm run dev` -> Vite dev server (port 5173, `host: true`); plugin `genclass-demo-dev-sw` (`apply: "serve"`) answers any URL ending in `/sw.js` with `server.transformRequest("/src/server/sw.ts")` (headers `Service-Worker-Allowed: /`, `Cache-Control: no-store`); `ensureServiceWorker` registers it as `type: "module"` because `import.meta.env.DEV`. +2. `npm run build` -> `scripts/build.mjs`: sets `BUILD_ID` (env or `Date.now().toString(36)`), (a) `vite build` with `vite.config.ts` (`base: "./"`, `outDir: "dist"`, `emptyOutDir: true`, `target: "es2022"`, `sourcemap: true`, `chunkSizeWarningLimit: 1500`, `rolldownOptions.input` = `index.html` + each `PAGES` entry whose `/index.html` exists, `worker.format: "es"`), (b) a second `build` (`configFile: false`) of `src/server/sw.ts` as a minified IIFE library (`name: "GenClassDemoServer"`, `fileName: "sw.js"`, `emptyOutDir: false`, `copyPublicDir: false`, only `__BUILD_ID__` defined), then copies `results-summary.json`, writes `dist/build.json` (`{ buildId, at }`) and `dist/.nojekyll`. +3. `npm run preview` -> `e2e/serve.ts`: binds `127.0.0.1`; `/` and the bare base redirect (302) to the base; paths outside the base 404; `mounts` map a sub-path to another directory (eval: `genclass-model/` -> `MODEL_DIR`); path traversal -> 403; directories -> 301 with a trailing slash; `Cache-Control: no-cache` for `sw.js` and `.html`, else `public, max-age=600`; content types include `.wasm` and `.onnx`; **no COOP/COEP headers** (isolation comes from the Service Worker). +4. `npm run fetch-model` -> `scripts/fetch-model.sh public/genclass-model` (args `[dir] [baseUrl] [variant]`, defaults `public/genclass-model`, `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, `q8`): runs `node ../packages/runtime/bin/genclass-runtime.mjs fetch-model --from --variant ` then `info `; if the CLI is missing or fails, curl downloads `model.json` and every file it lists (`variants` matching the variant or `all`, `files`, `bundled`; else `tokenizer.json`, `calibration.json`, `meta.json`), skipping non-empty existing files. +5. `scripts/vm-eval.sh [eval.ts args]` (run from a `scripts/vm.sh` slot, `cd` to the repo root): `npm install` -> `npm run build -w @genclass/runtime` (failure prints `RUNTIME_BUILD_FAILED` and exits unless `ALLOW_BROKEN_RUNTIME=1`) -> model (`GENCLASS_MODEL_URL` set: pass `--model ` and download nothing; else download `GENCLASS_MODEL_FROM` (default v0.1 release) into `GENCLASS_MODEL_DIR` (default `~/gcl/models/genclass-v0.1`, or `~/gcl/models/` for another source) unless `model.json` exists, variant `GENCLASS_MODEL_VARIANT` default `q8`) -> `npm run build` -> `npm run typecheck` (failure only prints `TYPECHECK_FAILED`) -> `eval.ts` with `GENCLASS_MODEL_DIR` (skipped when `SKIP_EVAL=1`). + +## Configuration and constants + +### URL parameters and storage (`src/shared/settings.ts`, `src/site/*`) + +| Name | Type | Default | Defined in | Effect | +|---|---|---|---|---| +| `?mode=` | `off\|guard\|heal` | localStorage `gc-demo-mode`, else `guard` | `getMode` | demo mode; `setMode` stores it and reloads without the param | +| `?model=` | URL or `cdn` | `VITE_GENCLASS_MODEL_URL`, else `genclass-model/` (relative to site root) | `modelBaseUrl` | model directory; `cdn`/empty -> runtime default `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`) | +| `?embed=trial&kind=&seed=&mode=&run=` | | `kind` chaos, `seed` 1, `mode` guard, `run` random | `trialParams` | bare trial page | +| `?trace=1` | flag | off | `traceOn` | trace instrumentation on trial pages | +| `?budget=` | number > 0 | unset (runtime default) | `holdBudget` | `policy.holdBudgetMs` experiment | +| `?coi=0` | flag | isolation on | `server.ts`, `sw.ts` | no COOP/COEP; no isolation reload | +| `?devtools=open` | flag | collapsed | `demo-page.ts` | devtools overlay starts open (Alt+Shift+G toggles, per README) | +| `?genclass=` | `off\|observe\|guard\|heal` | none | runtime (`killSwitch`) | runtime kill switch / mode override; the mode card shows a hint | +| localStorage | `gc-demo-mode`, `gc-demo-chaos-`, `gc-demo-theme` | | `settings.ts` | per-browser settings | +| sessionStorage | `gc-demo-sid-`, `gc-demo-sw-reload`, `gc-demo-coi-reload` | | `settings.ts`, `server.ts` | live session id; one-shot reload guards | + +### Chaos (`src/shared/chaos.ts`) + +| Name | Value | Effect | +|---|---|---| +| `CALM` | latency 45, jitter 15, all rates 0, hangMs 8000, spikeFactor 5, reorder 0, outage/offline false | base for every world (`mergeChaos({...CALM, routes: {}}, patch)`) | +| `PRESETS.busy` | latency 350, jitter 320, spikeRate 0.08, spikeFactor 5, reorder 0.35 | slow, jittery, reordering | +| `PRESETS.flaky` | latency 160, jitter 120, failRate 0.15, commitFailRate 0.04, spikeRate 0.06, spikeFactor 6 | random 5xx, lost responses | +| `PRESETS.storm` | latency 450, jitter 450, failRate 0.2, commitFailRate 0.05, timeoutRate 0.04, hangMs 6000, spikeRate 0.12, spikeFactor 6, reorder 0.6 | everything | +| `PRESETS.outage` | `outage: true` | 503 for everything | +| `CLEAN_CHAOS` (`scenario-kit.ts`) | latency 45, jitter 15, rates 0, reorder 0 | clean trials | +| Slider ranges (`chaos-panel.ts` -> `SLIDERS`) | latency 5–2000, jitter 0–1500, failures 0–60%, lost 0–30%, slowdowns 0–40%, factor 2–12, reorder 0–100%, hangs 0–20% | interactive controls (push debounced 120 ms) | + +### Typing and scenario kit (`src/shared/scenario-kit.ts`) + +| Name | Value | +|---|---| +| `CALM_TYPIST` | median 210 ms, sigma 0.28, typoRate 0.03, pauseRate 0.04, pauseMs 500–1100 | +| `FAST_TYPIST` | median 120 ms, sigma 0.4, typoRate 0.06, pauseRate 0.05, pauseMs 400–1200 | +| `keyDelay` | `clamp(lognormal(median, sigma), 35, 900)` | +| `typeSteps` | per char: `keyDelay`, plus a `pauseMs` pause with P `pauseRate` (or P `3 × pauseRate` on a space); typo (letters only, P `typoRate`) = a `NEIGHBOURS` key, then a Backspace `key` step after 160–420 ms, then the right char with a fresh `keyDelay` | + +### Harness, eval and server + +| Name | Value | Defined in | Effect | +|---|---|---|---| +| default settle | `{ idleMs: 700, timeoutMs: 20000 }` | `harness.ts` -> `finish` | quiescence before scoring | +| post-settle wait | 2500 ms (350 ms when `settle === false`) | `harness.ts` -> `finish` | lets held writes (hold budget up to 800 ms) and late reverts (~2 s) land | +| trial page `gc.ready` wait | 120,000 ms | `demo-page.ts` -> `bootTrial` | Guard/Heal mount after the model is ready | +| `loaded` wait | 15,000 ms (else `quiet(250, 10000, true)`) | `bootTrial` | | +| interactive world seed | 7 | `bootInteractive` | | +| ServerLink heartbeat | ping every 5,000 ms (4,000 ms timeout); control timeout 10,000 ms | `server.ts` | re-`hello` when the worker forgot the session | +| world GC | every 10 s; a world with no live bound client is disposed when its `lastSeen` (last `hello`/`ping`/API call) is older than 15 s (`trial-*`) or 120 s (live) | `sw.ts` | | +| log caps | 6,000 requests, 2,000 events; body logged up to 400 chars | `core.ts` | | +| SSE | `retry: 1000`; keep-alive every 15,000 ms | `core.ts` -> `openStream` | | +| `--n` | 30 (`--fast`: 4) | `eval.ts` | chaos trials per mode per demo | +| `--clean` | `ceil(N / 2)` (`--fast`: 2) | `eval.ts` | clean trials per mode per demo | +| `--demos`, `--modes`, `--kinds` | all six; `off,guard,heal`; `chaos,clean` | `eval.ts` | | +| `--workers` | 8 | `eval.ts` | parallel browser contexts | +| `--seed-base` | 1000 (clean = base + 500) | `eval.ts` | | +| `--base`, `--port` | `/genclass/`, 4173 | `eval.ts` | static server sub-path and port | +| `--trial-timeout` | 180,000 ms | `eval.ts` | | +| `--model`, `--model-dir` | `genclass-model/` if a local model exists else `cdn`; `GENCLASS_MODEL_DIR` | `eval.ts` | | +| `--tag`, `--budget` | none | `eval.ts` | `SUFFIX` = `-` and/or `-budget`; writes `results.*` (not copied to `dist/`); `--budget` also adds `budget=` to trial URLs | +| `--trace`, `--out`, `--no-shots`, `--shots-only`, `--no-trials-ui` | flags; `--out` default `demos/` | `eval.ts` | `--trace` adds `trace=1` to trial URLs and writes `e2e/.out/traces.json`; `--out` = directory for `results.*` | +| eval exit / warm-up | exit code 2 when `dist/index.html` is missing; warm-up 30 s (`crossOriginIsolated` and `.app-body > *`) | `eval.ts` | a failed warm-up is only logged | +| trial runner (in-page) | `n` ∈ {3, 6, 10, 20, 30}, default 6; clean `max(2, ceil(n/2))`; seeds 1000.. / 1500..; poll 50 ms; 150,000 ms per trial | `trials-panel.ts` | | +| net lane | window 10,000 ms, 8 rows × 12 px, poll 300 ms, render ≥ 70 ms apart, labels off above 22 bars | `netlane.ts` | | +| activity | shield toasts max 3, auto-close 7,000 ms; row "fresh" highlight 2,500 ms; prevented/flagged badges update on each report; "Model consulted" and "Observed" lines repaint every 500 ms; relative times every 5,000 ms | `activity.ts` | | +| site toast | 3,200 ms default | `dom.ts` -> `toast` | | +| `onRestart` reload delay | 1,500 ms | `demo-page.ts` | | +| `npm run dev` / `build` / `preview` | `vite` / `node scripts/build.mjs` / `node --experimental-strip-types e2e/serve.ts dist --base /genclass/ --port 4173` | `package.json` | see [How it works §12](#12-build-dev-server-and-scripts) | +| `npm run typecheck` / `typecheck:shim` | `tsc --noEmit` over `tsconfig.json` (or `tsconfig.shim.json`), `tsconfig.sw.json`, `tsconfig.node.json` | `package.json` | the root `npm run typecheck` (`--workspaces --if-present`) also runs the demos' one | +| `npm run fetch-model` / `eval` / `eval:fast` / `shots` | `bash scripts/fetch-model.sh public/genclass-model` / `e2e/eval.ts` / `e2e/eval.ts --fast` / `e2e/eval.ts --shots-only` (the three eval scripts via `node --experimental-strip-types`) | `package.json` | | +| `VITE_GENCLASS_MODEL_URL` | build-time env, unset by default | `settings.ts` -> `modelBaseUrl` | default model directory when `?model=` is absent | +| dev server | port 5173, `host: true` | `vite.config.ts` | | +| `GENCLASS_SHIM` | `1` force shim, `0` force real; default shim iff `packages/runtime/dist/index.js` missing | `vite.config.ts` | | +| `BUILD_ID` | env or `Date.now().toString(36)` | `vite.config.ts`, `build.mjs` | page/worker version match | +| `vm-eval.sh` model | default `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` -> `~/gcl/models/genclass-v0.1`, variant `q8` | `scripts/vm-eval.sh` | `GENCLASS_MODEL_FROM`, `GENCLASS_MODEL_DIR`, `GENCLASS_MODEL_URL` (pass `--model`, serve nothing), `GENCLASS_MODEL_VARIANT` | +| runtime policy defaults (not demos code) | thresholds report 0.6 / guard 0.9 / heal 0.8; `holdBudgetMs: "auto"` = clamp(1.5 × median latency, 150, 800), 300 when unknown | `packages/runtime/src/decide/policy.ts` -> `policyConfig`, `holdBudget` | explains `notExecuted` reasons | + +## Invariants and gotchas + +- **Test code must use native timers.** The six oracles, `driver.ts`, `server.ts` (whose `wait` the harness uses) and the site files `activity.ts`, `chaos-panel.ts`, `demo-page.ts`, `dom.ts` (`toast`), `netlane.ts`, `trials-panel.ts` import from `src/shared/native.ts`. Using `setInterval`/`setTimeout` there makes the runtime's timer observer see test ops (e.g. "interval 0.05s") that can become the cause of app writes (`NEEDS.md` §4). App code must keep using the normal globals. +- **Control traffic never goes through `fetch`.** Everything test-side (chaos, truth, log, quiet, world actions) uses `ServerLink.send` (`postMessage` + `MessagePort`). Adding a test-side `fetch` makes GenClass observe it. +- **CRN keys must be run-independent.** `rngFor` keys include method, path, query and raw body; event keys exclude timestamps (board uses `:v::`). Putting a timestamp or random id in a request body or event key re-rolls the network per mode and breaks paired comparisons (the board's "9 introduced" was partly this before CRN, per `NEEDS.md` §4). +- **World scripts use `scriptRng` and `World.script`**, so request timing does not shift teammates/incidents, and `freeze` stops them before scoring. +- **Same wait in every mode.** The 2.5 s post-settle wait applies to Off too; do not make it mode-dependent. +- **Oracles read only the DOM and server truth.** They rely on `data-testid` and `data-*` attributes (`search-results [data-id]`, `note-body`, `save-status[data-state]`, `cart-line[data-sku]`, `line-qty`, `line-price`, `cart-total`, `placed-order`, `order-error`, `place-order.busy`, `svc-[data-state]`, `banner`, `col-`, `[data-card][data-pending]`, `decision[data-q][data-answer][data-asked-at]`, `leave-confirm`, `closed`). Renaming any of these silently changes scores. +- **Latent bugs are the point.** Do not fix app bugs (ordering guards, idempotency keys, version checks) and do not tune apps for GenClass; that invalidates the evaluation (`docs/runtime/CONTRACT.md` §0 rule 4 and §12). +- **Honesty rule:** demos never import or read `sim/` and vice versa (verified: no code references either way; `sim/README.md` mentions `demos/` only to say it was not read). Allowed hints are stores via runtime/adapters, `resync` where the app already has a loader (cart, board, status), and the decisions demo's plugin and questions. +- **Trial pages wait for the model** in Guard/Heal before mounting; Off mounts immediately. Decision latency includes queueing: the model host answers one request at a time, and 8 parallel eval workers share the VM's CPU (impact on latency unmeasured). +- **Clean trials of a seed differ from chaos trials of the same seed** (scenario RNG includes `kind`); clean seeds also start at base + 500. +- **Status uses `settle: false`** because polling never stops; it gets only 350 ms after freeze. +- **The world clock starts before the model wait (fairness risk, inferred from code; impact unmeasured).** `bootTrial` sends `hello` (world created, `WorldDef.start` runs) and only then waits for `gc.ready` in Guard/Heal, while Off mounts at once. Status incidents (`from = w.created + at`, at 3–9 s), board teammate moves (`Exp(teamEveryMs) + 3000` ms after start) and anything else scheduled with `World.script`/`after` therefore happen earlier relative to the session `t0` in Guard/Heal, by roughly the model load time (`gc.loadMs` 672–2,077 ms over the 540 Guard/Heal trials in `results.json`, median ~834 ms). Per-request CRN draws are unaffected. Moving `hello` after the model wait, or scheduling scripts from a `start` world action sent at `begin()`, would remove the offset; either changes every seed's results. +- **Clocks across contexts.** Oracles compare page `epochNow()` with Service Worker log times (both `performance.timeOrigin + performance.now()`, but of different globals); the decisions app stamps `askedAt` with `Date.now()`. These agree to within clock skew, which matters only for windows close to the boundary (e.g. "no key in 2.5 s"). +- **The activity panel parses runtime reason strings** (`"hold budget"`, `"below the"`, `"expected"`) to classify decisions; rewording `Decision.reason` in the runtime silently moves counts between buckets (the same applies to `notExecuted` keys in results). +- **Mock-server state is in worker memory only.** A Service Worker restart loses every world. The interactive page reloads (`onRestart`) only if its heartbeat `ping` notices first (`known: false`); if an app request arrives first, `identify` makes it re-`hello` into a fresh, reset world without reloading. A trial in flight gets a fresh, empty world the same way and will usually be scored as a bug or fail its `until` steps. +- **Isolation needs the worker.** `e2e/serve.ts` and the Vite dev server send no COOP/COEP; the first visit is not isolated and reloads once (`gc-demo-coi-reload`); iframes (`window.top !== window`) never reload, they rely on the worker adding headers to `iframe` requests. +- **`hello` for an existing `sid` with a different `demo` replaces the world** (disposes the old one). Session ids are per demo (`live--…`, `trial--…`), so this only happens if ids are reused by hand. +- **The landing page's three "[GenClass]" console lines are hand-written examples** in `landing.ts` -> `hero`, not captured runtime output. (Its "x-genclass header" claim does match the runtime, which sets `x-genclass` on responses it synthesises, e.g. `packages/runtime/src/observe/xhr.ts` blocked responses.) +- **`react-dom` hoisting:** `packages/runtime/UI-NEEDS.md` notes that the runtime's React adapter tests resolve `react-dom/client` only because the `demos` workspace hoists it; removing `react`/`react-dom` from `demos/package.json` can break runtime tests. +- **Unused helpers** (safe to delete or use): `World.every`, `World.openStreams`, `Rng.fork`, `dom.ts` -> `svg`, `icons.ts` -> `IconName`, `protocol.ts` -> `ServerInfo`. +- **The Service Worker build is separate.** `scripts/build.mjs` builds `dist/sw.js` as a classic IIFE; in dev, `vite.config.ts` serves `/src/server/sw.ts` at any `*/sw.js` as a module worker. `tsconfig.sw.json` includes only `src/server/**` and `src/shared/{chaos,rng,protocol}.ts`: the worker must not import DOM code. +- **`build.mjs` uses `emptyOutDir: false` for the worker** and copies `public/` (including a fetched `public/genclass-model/`) into `dist/`, so a self-hosted model ships with the site. +- **`vm-eval.sh` refuses to measure a half-built runtime** (tsup cleans `dist/` first) unless `ALLOW_BROKEN_RUNTIME=1`; typecheck failures only print `TYPECHECK_FAILED`. +- **Two Off notions:** demo Off (`observe`, `model: false`, stats still collected) vs `?genclass=off` (runtime kill switch: nothing installed). +- **`act` counts as an intervention** even when the action failed (`ok: false`) or was a late revert; `notExecuted` is keyed by the runtime's reason string with numbers masked, so changing reason wording in the runtime changes report keys. +- **Off has `ask`/`decide` reject immediately** (`GenClassUnavailableError` reason `off`), so decisions latency is 0 ms in Off. The decisions app labels every `GenClassUnavailableError` (including the runtime's `"timeout"` reason) as "no model: app default"; any other rejection is labelled "no answer in time: app default". +- **Redaction:** the runtime's default redactor drops any path segment that is a secret word (`packages/runtime/src/util.ts` -> `isSensitiveName`, `SECRET_WORDS` includes `auth`). The status store keys services by id, so `services.services.auth.*` is redacted from situations (inferred from code; not observed in a trace). + +## How to change it safely + +The original team ran all builds, browsers and model runs on the `train` VM (`scripts/vm.sh`, slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things)), ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`), model downloads (`npm run fetch-model`) or anything on Azure. + +1. **Recreate the missing city data (prerequisite for any build).** Add `demos/src/server/data/cities.ts` exporting `searchCities(q: string): { total: number; items: { id: number; name: string; country: string; population: number }[] }` (deterministic, short prefixes match more) and `TYPED_TARGETS: string[]`. Either rename the directory or add a negation (`!demos/src/server/data/`) to the root `.gitignore`, otherwise it will be ignored again. The UI copy says 340 cities. +2. **Add a demo.** Add `DemoId` in `src/shared/protocol.ts`; a world `src/server/worlds/.ts` and register it in `sw.ts` -> `DEFS`; `src/demos//{main,app,scenario,oracle}.ts` + `app.css`; `/index.html` (copy one, `gc-root` `../`); add to `PAGES` (`vite.config.ts`), `ALL_DEMOS`/`TITLES`/`SHOT_PRESET` (`e2e/eval.ts`), `DEMOS` (`src/shared/demos.ts`: `n`, `title`, `tagline`, `stack`, `summary`, `wrong`, `scored`, `failure`, `tryIt`), `ART` (`src/site/art.ts`). `DEFS`, `ART`, `TITLES` and `SHOT_PRESET` are `Record` literals, so `tsc` flags a missing entry there; it does **not** flag `DEMOS` (an array; `DEMO_BY_ID` is built from it with a cast), `PAGES` or `ALL_DEMOS`, so add those by hand. Keep oracles on native timers and `data-testid`s. Run `npm run typecheck`, `npm run build`, `npm run eval:fast -- --demos ` (ask first). +3. **Change a scenario or oracle threshold.** Edit `scenario.ts` / `oracle.ts`; keep the scenario RNG label `"::"` stable (changing it changes every seed). Update `src/shared/demos.ts` (`scored` copy) and the README oracle table. Results are not comparable to older `results.*`: re-run all modes. +4. **Add a chaos knob.** Add the field to `RouteChaos` and `CALM`; apply it in `World.handle` (draw any randomness from the request's `rrng` up front, not lazily); add a slider in `chaos-panel.ts` -> `SLIDERS` and text in `describeChaos`; include it in `ChaosRanges` usage in scenarios. Typecheck both `tsconfig.json` and `tsconfig.sw.json`. +5. **Add a server route or world action.** Add a `Route` with a stable `key` (chaos rules and oracles use it); use `w.rng` inside handlers and `w.scriptRng` / `w.script` for scripted activity; add oracle-relevant data to `snapshot`. World actions return `undefined` for unknown names (the control reply is then `ok: false`). +6. **The demos need a new runtime API.** Use only the public API (`@genclass/runtime`, `/react`, `/redux`, `/zustand`, `/devtools`). Mirror it in `src/dev/runtime-shim/*` (and `tsconfig.shim.json` paths / `vite.config.ts` aliases for new entry points), then run `npm run typecheck:shim`. +7. **Evaluate a new model (ask first).** `GENCLASS_MODEL_FROM= bash demos/scripts/vm-eval.sh --tag ` (or `GENCLASS_MODEL_URL=|cdn`). Tagged runs write `results-.*` and do not replace the shipped results; untagged runs replace `results.json/.md/-summary.json` and the landing page numbers. Check `model.card` and `runtimeBuild` in the JSON. +8. **Investigate a hold-induced regression (ask first).** Run `eval.ts --trace --demos board --modes off,guard,heal --tag ` (and a second Off-only run for A/A), then `node --experimental-strip-types e2e/trace-report.ts e2e/.out/traces-.json [e2e/.out/traces-.json]`. It reports held writes, median holds, held writes applied after a newer user write, and per-card timelines for introduced bugs. +9. **Change the GenClass init.** Only edit `src/shared/genclass.ts` -> `startGenClass`; the mode mapping must stay identical for every demo and app code must not branch on mode. +10. **Change the results schema or aggregation.** `ModeSummary` feeds three consumers: `trials-panel.ts` -> `renderTable`, `eval.ts` -> `mdTable`/`mdDemo`/`writeReports`, and `landing.ts` -> `results` (its local `ResultsFile` type reads `demos...chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`). Keep those fields or update all three; an old `results-summary.json` keeps shipping until an untagged eval replaces it. +11. **Change the activity panel or devtools wiring.** Use only `Report`, `Decision`, `ActionRecord`, `Explanation` fields from the public types; if you add a decision bucket, match on `Decision.reason` text from `packages/runtime/src/decide/` and expect it to drift. Theme changes must dispatch `gc-theme` so the devtools overlay remounts. +12. **Fix the world-clock offset (if wanted).** Either move `link.hello(...)` in `bootTrial` after the `gc.ready` wait, or start scripted activity from a world action sent at `TrialHarness.begin()`. Then re-run all modes and both kinds; numbers are not comparable with the shipped `results.*`. + +## Tests + +There are no unit tests under `demos/`. The oracles and the eval are the tests; type checking covers the rest. + +| Test / check | What it asserts | +|---|---| +| `src/demos/search/oracle.ts` | final list equals results for the final text; stale results not visible ≥ 400 ms after the right answer (350 ms grace) | +| `src/demos/editor/oracle.ts` | no lost keystrokes; server copy equals editor; "Saved" never untrue at the end or for > 1.5 s | +| `src/demos/checkout/oracle.ts` | orders = intended; truthful confirmation/error; charged total = sum of lines; displayed total = sum of displayed lines (≤ 1 s drift); cart matches server | +| `src/demos/status/oracle.ts` | no false alarm > 1.5 s, no missed outage > 1.5 s, no other wrong status > 3 s, no banners, ≤ 1.5× steady request volume | +| `src/demos/board/oracle.ts` | final board equals server; no divergence run > 2 s (1.5 s window); no card stuck syncing | +| `src/demos/decisions/oracle.ts` | every answer equals the ground truth recomputed at ask time (health within ±1 level) | +| `e2e/eval.ts` | runs every oracle with real input in all modes; warm-up checks that pages reach cross-origin isolation (a failure is only logged, the run continues); screenshot tour exercises the interactive pages and the in-page runner | +| `npm run typecheck` | `tsc` over `tsconfig.json`, `tsconfig.sw.json`, `tsconfig.node.json` (needs `packages/runtime/dist/*.d.ts` and the missing `src/server/data/cities.ts`) | +| `npm run typecheck:shim` | the same against the shim | +| `e2e/eval.ts` -> `shootTrialsUI` | the in-page runner (iframes, synthetic events) on `search`, Guard page, selector set to 3 (3 chaos + 2 clean seeds per mode, 15 trials) finishes within 900 s; logs row and error counts (not a pass/fail gate: a timeout is caught and logged) | +| `e2e/trace-report.ts` | diagnostic only: quantifies held writes and write reordering on traced board/search runs | +| `scripts/vm-eval.sh` | end-to-end gate: refuses to evaluate when `@genclass/runtime` does not build (unless `ALLOW_BROKEN_RUNTIME=1`) | + +### Results so far (v0.1 model, not trained for runtime decisions) + +Source: `demos/results.md` / `results-summary.json`, generated 2026-10-07T19:30:09Z, 810 trials (6 demos × 3 modes × (30 chaos + 15 clean)), seeds chaos 1000–1029, clean 1500–1514, Playwright real input, model "GenClass v0.1 (self-hosted copy)" on WASM q8, all 540 Guard/Heal runs cross-origin isolated, 0 errored trials. + +| Demo | Bug rate Off | Guard | Heal | False interventions Guard / Heal | Fixed/introduced Guard; Heal | User latency p50 clean Off / Guard / Heal | Decision p50 Guard / Heal | +|---|---|---|---|---|---|---|---| +| search | 13% (4/30) | 13% | 13% | 0 / 0 | 0/0; 0/0 | 14 ms / 125 ms / 126 ms | 481 / 495 ms | +| editor | 83% (25/30) | 83% | 87% | 0 / 0 | 1/1; 0/1 | 779 / 775 / 783 ms | 333 / 340 ms | +| checkout | 83% (25/30) | 90% | 90% | 0 / 0 | 0/2; 0/2 | 205 / 204 / 206 ms | 363 / 366 ms | +| status | 100% (30/30) | 93% | 100% | 0 / 0 | 2/0; 0/0 | 1.33 / 1.26 / 1.28 s | 1.20 / 1.25 s | +| board | 50% (15/30) | 77% | 73% | 0 / 0 | 1/9; 2/9 | 19 / 31 / 33 ms | 346 / 360 ms | +| decisions | 83% (25/30) | 90% | 93% | 0 / 0 | 3/5; 2/5 | 0 / 151 / 157 ms | 308 / 304 ms | + +How to read it (aggregated from `results.json` `raw`): + +- Off is bug-free on all clean runs and fails often under chaos: the latent bugs are real. +- Chosen but not run (all modes): below a threshold 958 (reason "below the guard threshold" 730 + "below the heal threshold" 228), arrived after the hold budget 663, "guard mode does not allow heal-tier actions" 277. Diagnoses: `unusual` 6,328, `inconsistent` 58, never `expected`, so the "diagnosis ≠ expected" gate never blocked. +- Guard executed nothing. Heal executed 92 actions: `retry` 30 (decisions 10, board 9, editor 8, checkout 3), `block` 62 (60 of the decisions heartbeat `GET /api/ping`, 2 editor autosaves `PUT /api/notes/:id`). No Heal bug rate dropped below Off. +- Status Guard 100% -> 93% came without any action; the README's explanation (held requests spaced out the immediate retries) is a hypothesis, not traced. +- Holds cost latency (search clean p50 14 -> 125 ms) and introduced board bugs (9/30); `NEEDS.md` §1 attributes the board effect to the write-ordering issue using traced runs from a later runtime (batch 3), not this run. +- Decisions: accuracy under chaos 0.42 (defaults) -> 0.62 (Guard) / 0.59 (Heal); on clean runs 1.00 -> 0.27 (Guard and Heal clean bug rate 15/15): v0.1 answers as if something were always wrong. +- Fixed/introduced are noisy: read them against A/A flips (1/30 on the board after CRN). Wilson 95% intervals are in `results.md`. +- These numbers measure the runtime, integration and harness, not the runtime-specialist model; re-run with the trained model is `OPEN_TASKS.md` item 6. + +## Drift and open issues + +Doc-vs-code mismatches: + +1. **`demos/src/server/data/cities.ts` is missing from the repo.** Imported by `src/server/worlds/search.ts`, `src/demos/search/scenario.ts`, `src/demos/search/oracle.ts`; `git check-ignore -v` attributes it to the root `.gitignore` pattern `data/`; it never appears in `git log --all`. The SW bundle (imports all worlds) and the search page cannot build from a clean clone. +2. **Hold budget "300 ms".** `demos/README.md` (results text and "Model decision p50" bullet), `src/shared/settings.ts` -> `holdBudget` comment and `e2e/eval.ts` (`policy.note`, results header) say the default is 300 ms. HEAD runtime default is `"auto"` = clamp(1.5 × median, 150, 800) with 300 only as fallback (`packages/runtime/src/decide/policy.ts`). The shipped results were measured when the default was a fixed 300 ms (commit 353b0a4 `holdBudgetMs ?? 300`); `NEEDS.md` and `harness.ts` already assume the 800 ms ceiling. +3. **Shipped results predate the current eval and runtime.** `results.json` has no `model.card` or `runtimeBuild` (README says the card is recorded there); `results.md` "How to reproduce" differs from what `eval.ts` writes now; `screenshots/` lacks `decisions-heal.png`. Results were generated 19:30Z, before commits a53dd38 and 1a77558 (batch 3); `NEEDS.md`'s traced numbers (board Guard 19/30) come from a different, later run than `results.md` (23/30). +4. README says the harness waits for quiet + 2.5 s; for `status` (`settle: false`) there is no quiet wait and only 350 ms. +5. UI copy in `src/shared/demos.ts`: board "beyond a 1 s grace" (code: 1.5 s window, bug at > 2 s); status "beyond one poll of grace" (code: 3.5 s grace); decisions "Bug rate = share of wrong decisions" (code: a trial is a bug when any one decision is wrong, so bug rate is the share of trials with at least one wrong decision; per-decision accuracy is the `accuracy` metric). Its header also claims it is imported by `vite.config.ts` and injected at build time; it is not. +6. `src/demos/status/scenario.ts` comment says incidents are the same in clean and chaos runs of a seed; the RNG label includes `kind`, so they differ. +7. `eval.ts` options `--trace`, `--kinds`, `--base`, `--port`, `--trial-timeout`, `--out` are not listed in the README or the file header. +8. The runtime shim is behind the `Runtime` interface: `ShimRuntime implements Runtime` lacks `adapter()`, `holdBudgetMs()` and `situationBudget()` (`packages/runtime/src/types.ts` -> `Runtime`), so `npm run typecheck:shim` likely fails (unverified). The shim's `GenClassUnavailableError(message)` also lacks the real class's `reason` field (`"off" | "error" | "timeout" | "destroyed"`, `packages/runtime/src/errors.ts`). +9. README example `GENCLASS_MODEL_URL=https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/` lacks the `files/` suffix of the runtime's `DEFAULT_MODEL_BASE_URL`; the model package is not published yet (`OPEN_TASKS.md` item 8), so `?model=cdn` currently cannot load a model. +10. README results table shows decisions latency "–"; `results.md` has 0 / 151 / 157 ms. +11. README ("Latest results") says the default redaction hides the board's `cards` from the model "(§2)". In `NEEDS.md` redaction is §3 and is marked resolved in batch 3; the README sentence describes the pre-batch-3 measured run and points at the wrong section. +12. README "Files" block and the `eval.ts` header omit `e2e/trace-report.ts`. +13. Not drift but an open risk found while reviewing: the world-clock offset between Off and Guard/Heal trials (see [Invariants](#invariants-and-gotchas)); none of `README.md`, `NEEDS.md` or `results.md` mention it. + +Open `NEEDS.md` items for CORE (checked against HEAD): + +| § | Item | State at 654d822 | +|---|---|---| +| 1 | A held write lands after the user's newer write (board jump-backs +56%, 9 introduced bugs) | **open**: `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` still commits user-sync bypass writes immediately while earlier writes wait in `s.queue`; see [state-and-adapters](runtime/state-and-adapters.md) | +| 2 | Holds cost interactive latency while the model is slower than the budget; decision requests queue | **open**: holds depend only on `mayHold` (`consultable() && mode !== "observe"`), no latency-based skip or superseded-request drop | +| 3 | Redaction of ordinary fields (`board.cards`) | resolved in batch 3 (word-level `isSensitiveName`); note the new `auth` segment case above | +| 4 | Demos-side fixes (CRN, native timers) | done, for the record | +| 5 | `retry` offered for non-idempotent requests | **open**: `packages/runtime/src/situation/build.ts` -> `builtinApplicable` offers `retry` for any replayable fetch with `attempt < 4`; idempotency is only a fact | +| 6 | Observe EventSource (and BroadcastChannel) messages as ops | **open**: no EventSource observer in `packages/runtime/src/observe/` | +| 7 | Keep observing synthetic DOM events | satisfied: `observe/dom-user.ts` keeps untrusted events unless an app op is running | +| 8 | Notes on the v0.1 model | informational | + +Other open items: `OPEN_TASKS.md` item 2 (demos in progress), item 6 (re-evaluate with the trained model; investigate hold-induced harm and triage sensitivity on typeahead, salient about 6 times per clean trial), and "Needs the user: public demo hosting (GitHub Pages) OK to publish?". + +## Related docs + +- [demos/README.md](../../demos/README.md), [demos/NEEDS.md](../../demos/NEEDS.md), [demos/results.md](../../demos/results.md) +- [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) (§0 ground rules, §12 demos, §13 hooks) +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `GenClass.init`, options, kill switch +- [runtime/state-and-adapters.md](runtime/state-and-adapters.md): holds, `propose` ordering risk, React/Redux/Zustand adapters, redaction +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): policy gate, thresholds, hold budget, `retry`/`block`, late revert +- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): DOM/fetch/timer observers, ops +- [runtime/model-host.md](runtime/model-host.md): model loading, `fetch-model` CLI, WASM threads +- [runtime/devtools.md](runtime/devtools.md): the overlay mounted by the demo page +- [runtime/build-test-release.md](runtime/build-test-release.md): workspace build order, `scripts/vm.sh` +- [sim.md](sim.md) (independent from demos by rule), [model-io-contract.md](model-io-contract.md), [training.md](training.md) +- [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [playbooks.md](playbooks.md), [repo-map.md](repo-map.md), [overview.md](overview.md), [../../AGENTS.md](../../AGENTS.md) diff --git a/docs/agents/extension-and-benchmarks.md b/docs/agents/extension-and-benchmarks.md new file mode 100644 index 00000000..f2848609 --- /dev/null +++ b/docs/agents/extension-and-benchmarks.md @@ -0,0 +1,559 @@ +# Chrome extension, benchmarks and ops scripts (adjacent to the runtime library) + +> **Scope:** `extension/**`, `bench/**`, `jev_local/bench/**`, `BENCHMARKS.md`, `results/**`, `scripts/**`, `docs/benchmax-research/**` (summarised). +> **Read this when:** you touch the GenClass voice-control Chrome extension; you need to know where the runtime's model engine/packer/tokenizer came from and how parity was proven; you run, extend or quote a benchmark (jevbench, benchmax, the computer-use head-to-head); you need to know what a script in `scripts/` does and whether it touches Azure, money or secrets. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- **This whole area is adjacent/legacy relative to `@genclass/runtime`.** It is the pre-runtime GenClass project (the "jev-local" era): a voice-controlled MV3 Chrome extension (GenClass 0.1.0), the Python benchmark harnesses that compared the model with TypeSafe's hosted Jev, and the Azure/Mac ops scripts. `docs/runtime/CONTRACT.md` says "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." +- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh` and the `training/README.md` recipes to start multi-node torchrun jobs) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the `runtime-model-v0.1.0` release of GenClass-lib; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. +- **Extension architecture:** service worker (`src/background/sw.js`: tabs, navigation, feature plumbing) + offscreen document "brain" (`src/offscreen/offscreen.js`: model, speech, decision loop) + content script (`src/content/content.js`: page observation, in-page actions, ad hiding) + side panel (`src/sidepanel/panel.js`: view + settings). Pure-JS decision logic lives in `src/core/`: `types`, `catalog`, `questions`, `state`, `spans`, `stream`, `policy`, `safety` and `controller` port the Python macOS harness `jev_local/harness/*`; `tokenizer`, `packer` and `engine` port `jev_local/engine/encoder/{tokenize_pack,engine,calibrate}.py` plus `jev_local/confidence.py`; `serialize` ports `jev_local/serialize.py`; `features`, `sites` and the numbered-pick/rescue code are GenClass-only additions. +- **The model is asked typed questions** (choice / noul / score) about a `state` object (screen, focused element, recent actions, pending, transcript). Questions are block-isolated in the attention mask, so the extension asks in two exact stages (intent/complete/is_command/destructive first, then only the argument question the intent needs). +- **Mid-sentence acting is safe** because of a consumed-prefix transcript cursor (`core/stream.js` -> `Stream`), stability gates (`core/policy.js` -> `evaluatePolicy`), deterministic safety rules plus spoken confirmation (`core/safety.js` -> `gate`), and a 3 actions/s rate limit. +- **Benchmarks** come in three generations: the computer-use head-to-head vs Jev (`results/genclass-vs-jev-computer-use.md`, summarised in `BENCHMARKS.md`); **jevbench v1** (25 public datasets, pre-registered in `bench/PREREG-jevbench.md`, release read M0 in `results/jevbench-m0.md`, Jev pass blocked by billing); **benchmax** (549 published Jev numbers, 154 counted; 19 publisher-harness adapter specs; pre-registered draft in `bench/PREREG-benchmax.md`; no test-split scoreboard exists in the repo). +- **Headline numbers:** v1 32M model beats Jev on mid-sentence intent (90.4% vs 66.4%, n=664) and typed span (94.9% vs 75.5%, n=98); Jev wins on held-out generic questions (94.7% vs 80.5%, n=451) and AG News (0.882 vs 0.315). jevbench M0 skill index for v1 = 10.1 [9.7, 10.7]. +- **Rules that bind anyone touching this area:** the original team rule (CONTRACT §0 rule 5) was that the Mac only edits files. Under the current agent policy ([../../AGENTS.md](../../AGENTS.md) §4), nothing in this area runs without the user's OK (extension `npm ci`/`npm test`/e2e, Python tests, benchmarks, `scripts/*`); Jev outputs are evaluation-only; OpenRouter/Jev calls cost real money (lifetime cap $5 per the benchmax PLAN) and need the user's OK; benchmark test splits are read once per release. + +## Files + +### Extension (`extension/`, GenClass 0.1.0, not an npm workspace) + +| path | role | key exports / entry points | +|---|---|---| +| `extension/README.md`, `MODEL_CARD.md`, `RELEASE.md`, `NOTICE`, `LICENSE` | product docs, model card, manual release checklist, third-party notices, Apache-2.0 text | — | +| `extension/package.json` (+ own `package-lock.json`) | scripts `build`, `package`, `test`, `test:e2e`; deps `onnxruntime-web ^1.31.0-dev.20260914-8d85527a0`, `@huggingface/transformers ^4.3.0`; dev `@playwright/test ^1.63.0`, `esbuild ^0.28.2` | not in root `package.json` `workspaces` | +| `extension/static/manifest.json` | MV3 manifest; `minimum_chrome_version` 116; permissions `sidePanel offscreen storage scripting alarms system.memory`; host ``; `content.js` declared as a content script for `http://*/*` and `https://*/*` at `document_idle` (tabs opened before install get it via `sw.js` -> `ensureContent`); commands `toggle-listening` (Alt+Shift+G), `kill-switch` (Alt+Shift+K); CSP `script-src 'self' 'wasm-unsafe-eval'`; COEP `require-corp`, COOP `same-origin` | — | +| `extension/static/{panel.html,panel.css,offscreen.html,welcome.html,audio-worklet.js,icons/}` | pages, styles, mic AudioWorklet (`genclass-capture`, posts 1600-sample = 100 ms chunks) | — | +| `extension/src/background/sw.js` | service worker: side panel, offscreen lifecycle, observe/execute routing, tab ops, content filter rules, focus/RAM plumbing | module-internal (nothing exported): `ensureBrain`, `observe`, `execute`, `tabOp`, `filterBlocks`, `ramTick`, `RESTRICTED_RE`, `DENY_SITE_RE`, `DEFAULT_FEATURES` | +| `extension/src/offscreen/offscreen.js` | "brain": model download/cache/load, speech, `Controller` wiring, message handlers | module-internal (nothing exported): `loadEngine`, `fetchCached`, `observer`, `executor`, `buildController`, `textCommand`, `benchModel`, `benchSpeech`, `playAudio`, `CACHE` | +| `extension/src/offscreen/speech.js` | speech sources: local ASR (transformers.js, energy VAD, re-decoded partials) and Web Speech | `SPEECH_ENGINES`, `speechPlan`, `gpuInfo`, `LocalAsr`, `LocalSpeechSource`, `WebSpeechSource`, `summarizeStats` | +| `extension/src/offscreen/features_rt.js` | model-backed content filter, focus mode, tab relevance | `Features` | +| `extension/src/content/content.js` | page observation (numbered elements), in-page actions, overlays/badges, content-block hiding, Esc kill switch | IIFE; message types `observe execute badges listening ping page_info filter_set filter_unhide_all` | +| `extension/src/sidepanel/{panel.js,welcome.js}` | panel view + settings; welcome/mic-permission page | `DEFAULTS`, `FEAT_DEFAULTS` | +| `extension/src/core/types.js` | shapes, `Kind`, `Risk`, thresholds, default config | `Kind`, `KINDS`, `Risk`, `DEFAULT_THRESHOLDS`, `defaultConfig`, `makeAction`, `describeAction` | +| `extension/src/core/catalog.js` | closed vocabularies (model input, do not edit) | `INTENTS`, `BROWSER_EXTRA_INTENTS`, `KEYS`, `FOLDERS`, `SCROLL_LEVELS`, `RISK_WORDS`, `RISK_RE`, `DENY_APP_*`, `SECURE_FIELD_RE`, `FILLERS`, `CHAIN_WORDS` | +| `extension/src/core/questions.js` | fixed question schema per transcript update | `buildQuestions`, `elementLine`, `rankApps`, `INSTR`, `Q_*` ids | +| `extension/src/core/state.js` | the `state` object | `buildState` | +| `extension/src/core/spans.js` | verbatim text/URL candidates, numbered picks, word consumption | `extractTextCandidates`, `extractUrlCandidates`, `parseCandidatePick`, `consumedFor`, `endsSentence` | +| `extension/src/core/stream.js` | consumed-prefix transcript cursor | `Stream`, `matchPrefix`, `coreWords` | +| `extension/src/core/policy.js` | answers -> verdict (pure) | `evaluatePolicy`, `ARG_QUESTIONS`, `pickOf`, `newPolicyContext` | +| `extension/src/core/safety.js` | deny / risk / confirm gating, rate limit | `gate`, `classifyRisk`, `denyReason`, `confirmationAllowed`, `RateLimiter`, `CONFIRM_REACTION_S` | +| `extension/src/core/controller.js` | incremental decision loop | `Controller`, `rescueTarget`, `silenceGatesFor`, `MAX_LOOPS`, `MAX_DEBOUNCE_MS` | +| `extension/src/core/{tokenizer,packer,engine,serialize,pyutil}.js` | model engine (ancestor of the runtime's `src/model`) | `Tokenizer`, `Packer`, `planInputs`, `unpackLogits`, `Engine`, `calibrateLogits`, `buildAnswer`, `headerKey`, `stateSegments`, `questionBlock`, `pyRound` | +| `extension/src/core/{features,sites,fuzz}.js` | feature questions/verdicts; tab/site catalogue for `app`; rapidfuzz `partial_ratio` port | `filterRequest`, `focusRequest`, `focusVerdict`, `protectedTab`, `discardOrder`, `appCatalog`, `SITES`, `extract` | +| `extension/src/model/{model.json,tokenizer.json,calibration.json,meta.json}` | model card (URLs, sha256) + bundled small files | — | +| `extension/release-assets/{tokenizer,calibration,meta,parity}.json` | export outputs: `tokenizer/calibration/meta.json` are byte-identical to `src/model/` (checked with `cmp`), plus `parity.json`; there is no `model.json` here; `*.onnx` are gitignored and absent | — | +| `extension/scripts/build.mjs` | esbuild bundle -> `dist/genclass/`; `--zip`, `--bundle-model`, `--release`, `--dev` | — | +| `extension/scripts/{make_icons.mjs,compose_screens.mjs}` | icon PNGs (no image libs); 1280x800 store screenshots from e2e raw shots | — | +| `extension/scripts/make_py_fixtures.py` | regenerates `test/fixtures/{spans,questions,policy,stream}_py.json` from `jev_local.harness` | — | +| `extension/tools/genclass_export.py` | PyTorch -> ONNX export (fp32/fp16/q8), parity, `pack_fixtures.json`, `torch_fixtures.json` (VM, torch) | `ExportModel`, `make_q8`, `plan_inputs`, `unpack` | +| `extension/test/unit/*.test.mjs`, `test/e2e/*.spec.mjs`, `test/eval/*` | see [Tests](#tests) | — | +| `extension/test/unit/helpers.mjs` | `ROOT`, `FIX`, `ASSETS`, `readJson`, `questionsFromJson` (rebuilds choice criteria as `Map`s in Python label order, because `JSON.parse` reorders integer-like keys) | — | +| `extension/test/e2e/fixtures.mjs` | Playwright launcher: persistent Chromium context with the unpacked extension (`GENCLASS_EXT`, default `dist/genclass`), the local server, the panel as a page; `say()` waits 700 ms before each command (the `Stream` treats an identical command within 350 ms of a final as a recognizer duplicate) | `launch`, `setSettings`, `shot`, `EXT`, `SHOTS` | +| `extension/test/e2e/server.mjs` | static server with COEP-compatible headers (`cross-origin-resource-policy: cross-origin`, `access-control-allow-origin: *`); mounts `/site/` (test pages), `/assets/` (`release-assets/`), `/audio/`, `/fixtures/`, `/shots/`; standalone `node test/e2e/server.mjs [port]` defaults to port 8737 | `startServer` | +| `extension/test/e2e/playwright.config.mjs` | `testMatch` `*.spec.mjs`, `timeout` 600000 ms, `workers` 1, reporter `list` | — | +| `extension/test/e2e/site/{shop,notes,recipes}.html` | local test pages: `shop` = voice commands and marked ads; `notes` = an on-task tab (laptop battery notes); `recipes` = the off-task tab in the focus test; both also serve as idle tabs in the RAM test | — | +| `extension/test/fixtures/{requests50,pack_fixtures,torch_fixtures}.json` | the 50 harness requests (with `gold`, `screen_type`) and the export's Python/PyTorch parity outputs | — | +| `extension/test/fixtures/{spans,questions,policy,stream}_py.json` | Python-harness parity fixtures (from `extension/scripts/make_py_fixtures.py`, not the runtime's `packages/runtime/test/fixtures/model/make_py_fixtures.py`) | — | +| `extension/test/fixtures/audio/{click,scroll,type}.wav` | 16 kHz mono 16-bit speech clips; `speech.spec.mjs` uses `scroll.wav` (`bench_speech`) and `click.wav` (`play_audio`); `type.wav` is not referenced by any test or script | — | +| `extension/.gitignore` | ignores `node_modules/`, `dist/`, `release-assets/*.onnx`, `test-results/`, `playwright-report/`, `.DS_Store` | — | +| `extension/store/{listing,permissions,privacy}.md`, `store/screenshots/*.png` (01–09, 1280x800), `store/icon-128.png` | Chrome Web Store material; `permissions.md` justifies each manifest permission and lists what is **not** requested (`tabs`, `debugger`, `history`, `cookies`, `webRequest`, `clipboardRead`) | — | +| `extension/static/icons/store-icon-128.png` | store icon; `build.mjs` deletes it from `dist/genclass/icons/` | — | + +### Benchmarks + +| path | role | key exports / entry points | +|---|---|---| +| `BENCHMARKS.md` | public summary: CU head-to-head, speed/cost, wire compatibility, order robustness, where Jev wins, caveats | — | +| `results/genclass-vs-jev-computer-use.md` | full CU head-to-head table (1,280 examples) | — | +| `results/jevbench-m0.md` | jevbench v1 release read M0 report | — | +| `results/z68m-dev-notes.md` | Z-68m (benchmax zero-shot retrain) dev check and calibration-transfer finding | — | +| `bench/PREREG-jevbench.md` | jevbench v1 pre-registration (sha256 `a35004c6…6fe457`, matches the hash M0 quotes) | — | +| `bench/PREREG-benchmax.md` | benchmax phase-0 freeze (DRAFT, local only) | — | +| `bench/public/targets.json` | 549 targets, schema `benchmax-targets/1` | `targets[]` | +| `bench/public/jev_published.json` | 549 published Jev numbers (list of rows) | — | +| `bench/public/exclusions.json` | registry manifest, schema `benchmax-exclusions/1` | — | +| `jev_local/bench/registry.py` | jevbench datasets + training-exclusion rules (decontamination stage 1), stdlib only | `TEST`, `DEV`, `REF`, `RETIRED_DEV`, `exclusion_reason`, `is_excluded`, `s_allow_reason`, `exclusion_manifest`, `manifest_sha256` | +| `jev_local/bench/templates.py` | dataset row -> Jev request mappers, variants | `m_`, `MAPPERS`, `bare`, `shuffled`, `validate_request`, `TEMPLATE_VERSION`, `FIN_TOPIC_NAMES` | +| `jev_local/bench/build.py` | download, pin, sample, render jevbench files (VM) | `build_dataset`, `sample_items`, `main` | +| `jev_local/bench/metrics.py` | scoring, indices, bootstrap, decision rule (numpy) | `collect`, `score_dataset`, `index`, `decision_rule`, `flip_rate`, `skill`, `decision_score` | +| `jev_local/bench/ours.py` | run a FastEngine checkpoint with exact option/question chunking (VM, torch) | `OursRunner` | +| `jev_local/bench/baselines.py` | open-baseline adapter contract; only the HTTP adapter is implemented | `SystemOneHTTP`, `BASELINES`, `run_rows` | +| `jev_local/bench/benchmax/__init__.py` | spec registry | `Spec`, `register`, `load_specs`, `get_spec`, `runner_adapter_class` | +| `jev_local/bench/benchmax/{specs_a,specs_b}.py` | the 19 registered specs (4 group A + 15 group B) | `DEUSSER`, `DECISION_INDEX`, `TYPED_DECISIONS`, `JEVBENCH_HF`, `SPECS_B` | +| `jev_local/bench/benchmax/runner.py` | engine clients, wire answers W1–W3, refusals W4, overflow W5, `run.json`, determinism W11 | `LocalClient`, `HttpClient`, `HeuristicClient`, `wire_answers`, `refusal_body`, `RunContext`, `Session`, `check_model_id` | +| `jev_local/bench/benchmax/bridge_b.py` | wraps group-B adapters into the runner contract | `bridge_class`, `is_group_b_class` | +| `jev_local/bench/benchmax/adapters_a/*.py` | Deußer, Decision Index, typed-decisions, jev-bench (HF) | `DeusserAdapter`, `DecisionIndexAdapter`, `TypedDecisionsAdapter`, `JevbenchHfAdapter` | +| `jev_local/bench/benchmax/adapters_b/.py` (15 modules, see [the spec table](#benchmax-spec-registry-19-specs)) | group-B suites | module-level `SPEC_ID`, `TARGETS` (target row ids like `"T308"`), usually `TASKS`; class `Adapter(AdapterB)` constructed as `Adapter(spec, args)` (`args.work`, `args.limit`, `args.tasks`) with class attributes `SPLITS`, `TASKS`, `EVAL_SPLIT` and methods `prepare(split)`, `items(split, limit, tasks)`, `score(items, answers, split, thresholds)`, optional `fit(items, answers)` (registered as `":Adapter"` in `specs_b.py`) | +| `jev_local/bench/benchmax/adapters_b/common.py` | shared `Item` record, `AdapterB` base class, pinned fetching (commit/revision + sha256), HF parquet reading, publisher metrics (F1, ECE, nDCG, Wilson CIs, bootstrap) | `Item`, `AdapterB`, `work_dir`, `repos_dir`, `hf_home`, `DEFAULT_WORK`, `MODEL_ID`, `VENDOR` | +| `jev_local/bench/benchmax/adapters_b/driver.py` | group-B standalone CLI (`python -m jev_local.bench.benchmax.adapters_b.driver prepare\|items\|run\|score\|fit\|selfcheck`); writes `items.jsonl`, `answers.jsonl`, `scores.json`, a lighter `run.json`; `selfcheck` refuses the test split | — | +| `jev_local/bench/benchmax/adapters_b/engine_client.py` | answerers: `HttpAnswerer` (POST `/v1/systemone`), `LocalAnswerer` (VM; `OursRunner` + `jev_local.confidence.build_answer` at 12 digits), resumable `run_items` | `HttpAnswerer`, `LocalAnswerer`, `run_items`, `AnswerError` | +| `jev_local/bench/benchmax/adapters_b/vendor/` | pinned upstream label/prompt/policy files per publisher (11 directories; each carries the upstream `LICENSE` except `dmb/`, whose repo has no licence); `UPSTREAM_SHA256.txt` lists 34 sha256 lines for upstream caches/candidate files | — | +| `jev_local/bench/__init__.py`, `benchmax/adapters_a/__init__.py`, `adapters_b/__init__.py` | package markers (`adapters_b/__init__.py` documents a module-level function contract that the adapters no longer follow; the real contract is in `specs_b.py`'s docstring and `common.py` -> `AdapterB`, see Drift) | — | + +### Research notes (`docs/benchmax-research/`, read-only background; all reference their old home `docs/research/benchmax/`) + +| file | lines | what it holds | +|---|---|---| +| `PLAN.md` | 971 | the binding benchmax plan (2026-10-03): 154 counted benchmarks, two tracks, test hygiene (§2), data acquisition, model ladder 68m/150m/400m/1b, compute budget (≈ $2.9–5.1k Azure, 12x F80as_v7 + D64), harness per suite (§6), predicted outcome, decisions for the user. $5 lifetime cap on Jev, $0 planned. | +| `feasibility-targets.md` | 876 | rev 2: per-benchmark W/T/L verdicts by size and track, significance bar formula (§1.2), the §3 verdict table parsed by `scripts/benchmax_build_targets.py` | +| `jev-published.md` | 2206 | census of every published Jev number (549 rows in `bench/public/jev_published.json`), tiers A/B/C/X and `protocol=zero-shot\|uses-train-data` notes | +| `suite-reproduction-specs.md` | 768 | how to reproduce each of the 9 suites byte-exactly, pinned commits, engine requirements W1–W11 (§1.2), the contamination-audit pattern list that fed the registry's sibling/`public_jev` rules (§1.5) | +| `train-data-and-supervised-ceilings.md` | 936 | train splits, licences, supervised ceilings and contamination traps (§7) per dataset; feeds the S allow-list | + +### Scripts (`scripts/`): one row per script + +"Azure" = needs an Azure VM / the `az` CLI / the private 10.0.0.x network. "Mac-only" = needs macOS/MLX/the 8 GB Mac. Nothing here should be run by an agent without the user's go-ahead; anything marked **$** spends money. + +| script | purpose | where it runs | Azure? | notes | +|---|---|---|---|---| +| `azvm.sh` | `azvm.sh HOST 'cmd'` (ssh), `--put LOCAL REMOTE` (single-file scp), `--get REMOTE LOCAL` (recursive scp), `--sync` (rsync `--delete` of `jev_local scripts tests pyproject.toml` to `~/jev/`) for a named VM from `~/.jev-local/azure_hosts` (user `azureuser`, key `~/.ssh/jev_azure`) | Mac | yes | used by most other ops scripts and by `training/*.sh`; **no timeout of its own** (a `TIMEOUT=` prefix is ignored); `--sync` does **not** copy `bench/` or `docs/` | +| `vm.sh` | subcommands `sync SLOT`, `run SLOT 'cmd'` (sync then run), `exec SLOT 'cmd'` (no sync), `get SLOT REMOTE LOCAL`: rsync `-az --delete` of this repo to `~/gcl/SLOT` on VM `train` (host from `azure_hosts`), run commands in it with `$HOME/node/bin` on PATH; SLOT must match `[a-zA-Z0-9_-]+` | Mac | yes | **the runtime build/test path**; `TIMEOUT` default 1800 s per remote command (sync: 300 s mkdir + 600 s rsync; `get`: 600 s); rsync excludes `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, **`/extension/`**, `/sim/out/`, `.cache-model/`; `--delete` removes slot files that are not in your local working copy unless they are under an excluded path; model dirs under `.cache-model/` or `/models/` survive | +| `cluster_up.sh` | `cluster_up.sh NAME:SIZE …`: `az vm create` training nodes `vm-jev-` (Ubuntu 24.04, resource group `rg-jev-train`, 256 GB Premium disk, proximity group `ppg-jev`), appends `NAME PUBLIC_IP PRIVATE_IP SIZE` to `azure_hosts`, auto-shutdown 18:00 UTC | Mac | yes **$** | serial `az` only | +| `vm_bootstrap.sh` | one-time Ubuntu 24.04 VM setup: venv, CPU torch, data tooling | on a VM | yes | | +| `node_setup.sh` | on a fresh node: bootstrap + pull `v2_bundle.tar` from data VM `10.0.0.5:8797` | on a VM | yes | | +| `launch_run.sh` | `launch_run.sh RUN MASTER_PRIV_IP NPROC THREADS "node1 node2 …" -- `: detached (`setsid nohup nice -n 5`) multi-node `torch.distributed.run -m jev_local.train.train --ddp` over `azvm.sh`, master port 29500, env `OMP_NUM_THREADS=THREADS GLOO_SOCKET_IFNAME=eth0 JEV_ENCODER=banded TOKENIZERS_PARALLELISM=false HF_HUB_OFFLINE=1` | Mac | yes **$** | logs `~/jev/runs//rank.out`; calls `scripts/azvm.sh` by a relative path, so run it from the repo root; reads no `TIMEOUT`; **also used by the runtime model training** (`training/launch_s2.sh`, `training/launch_final1.sh`, `training/README.md`) and by `launch_z68m.sh` / `stage1_speedtest.sh` | +| `launch_z68m.sh` | phase-2 benchmax Z-68m retrain: sync, distribute Z bundle (sha256 `a333fd88…`), launch 8 nodes x 4 ranks x 20 threads | Mac | yes **$** | expects `bench/public/mix_z_run.json` (not in repo) | +| `stage1_speedtest.sh` | PLAN-excel stage 1: 20-step 8-node DDP timing runs, copies timing logs to `runs/stage1//` | Mac | yes **$** | | +| `watch_runs.sh` | `watch_runs.sh INTERVAL_S "run:node …"`: poll rank-0 logs, print step/loss/tok/s, exit with `EVENT:` on DONE/ERROR/STOPPED | Mac | yes | | +| `phase3_eval.sh` | benchmax phase 3: start VM `train`, pull checkpoint from `c01`, dev eval + global calibration, write `~/phase3_run_all.sh` that runs every spec | Mac | yes **$** | prints manual steps; fitting the calibration is manual; the generated `phase3_run_all.sh` (`--threads 48`) skips a spec only if `run.json` contains `"complete": true`, which `RunContext` never writes (it writes `"status": "complete"`), so a second pass re-runs every spec and trips `benchmax.py`'s `--rerun-reason` guard (see Drift) | +| `benchmax.py` | benchmax CLI: `list`, `verify --spec`, `run --spec` (writes `runs/benchmax///run.json`) | `list`/`--help` anywhere; `verify`/`run` on VM `train` | yes (run) | default `--model-id genclass-68m`, `--threads 8`, `--determinism 20` | +| `benchmax/stage0_validation.sh` | `stage0_validation.sh CKPT OUT [MODEL_ID=genclass-68m] [THREADS=32]`: PLAN-excel stage 0, every adapter on NON-evaluated splits, `/summary.tsv`; skips runs whose `run.json` is finished | VM `train` (launched via `azvm.sh train`) | yes | never passes `--allow-test`; `LIMIT` default 1000, per-run timeout 3600 s, `--determinism 5`; the skip test is `grep -q '"finished"'`, which matches **any** existing `run.json` (the key is always written, as `null` until the end), so failed/incomplete runs are skipped too (see Drift) | +| `benchmax/dry_pass_validation.sh` | `dry_pass_validation.sh [CKPT=~/jev/models/jev-local-fast-v2] [OUT] [THREADS=16]`: bm-integrate dry pass of all 19 specs on non-evaluated items | VM `train` | yes | eval-only suites get `verify` only | +| `benchmax/engine_determinism.py` | W11 determinism report on synthetic requests (in-process and optional live uvicorn) | VM | yes | loads torch | +| `benchmax_build_targets.py` | regenerate `targets.json` + `exclusions.json` from `jev_published.json` and the feasibility note; `--write-registry`, `--check` | anywhere (stdlib) | no | reads `docs/research/benchmax/feasibility-targets.md` (path moved, see Drift) | +| `jevbench.py` | jevbench CLI with subcommands `build`, `run-ours`, `run-jev`, `score`, `report` | `build`/`run-ours`/`score` on VM; `run-jev` on Mac; `report` anywhere | yes (VM steps) | `run-jev` calls OpenRouter **$** with key `~/.jev-local/secrets/openrouter.key` | +| `compare_jev.py` | CU head-to-head behind `results/genclass-vs-jev-computer-use.md`: Jev via OpenRouter vs `models/jev-local-fast` on `data/cu`, `data/gen` test samples; flags `--n-cu` 1000, `--n-gen` 300, `--seed` 7, `--workers` 6, `--skip-local`, `--jev-only`, `--local-only`; Jev cache `runs/compare/jev.jsonl`, ours `runs/compare/ours.json` | Mac (local CPU torch) | no | **$** OpenRouter; data/models not in repo | +| `openrouter_key.sh` | `set` (hidden prompt) / `check` balance of the OpenRouter key | Mac | no | handles a secret: never run on an agent's own initiative | +| `dev_to_calib.py` | jevbench clean-dev request files -> calibration-fitter rows (`CLEAN_DEV` 10 keys) | anywhere | no | needs `bench/jevbench/dev` files (VM) | +| `genclass_export.py` | **older** export variant: fp32/fp16 + dynamic **int8** (`genclass-int8.onnx`) | VM (torch) | yes | superseded for the extension's q8 export by `extension/tools/genclass_export.py`, but still imported by `training/export_runtime.py` | +| `bench_encoder.py` | FastEngine inference regimes (first/uncached/partials/warm) + training step benchmark; `runs/bench_encoder.json` | Mac (mps/cpu) | no | | +| `bench_decoder.py` | MLX decoder engine (`jev-local-general`) latency/accuracy; `runs/bench_decoder.json` | Mac-only (MLX) | no | | +| `bench_laya.py` | zero-shot Laya (`convaiinnovations/laya`) on the 20 harness cases | Mac | no | | +| `overnight.py` | memory-gated overnight job runner for the 8 GB Mac (`--daemon`, `--check`, `--status`, `--ignore-window`); control files in `~/.jev-local/overnight/` (`PAUSE`, `STOP`, `HOLD` expiring after 2 h, `status.json`) | Mac-only | no | start only if all hold for 60 s: swap < 3 GB, RAM free ≥ peak + 2 GB, swap-ins < 100/s, disk ≥ 4 GB, inside 23:00–09:30; stop if RAM free < 12 %, swap-ins ≥ 1000/s on 2 samples, or disk < 2.5 GB; SIGKILL at < 8 % free or ≥ 3000 swap-ins/s; tested by `tests/test_overnight.py` | +| `demo.py` | entry for the macOS voice computer-use demo (`jev_local.demo.main`; `--live`, `--text`, `--say`) | Mac-only | no | | +| `demo_proof.sh` | offline mid-sentence proof with the real model, gated by `overnight.py --check` (RAM free ≥ 2.5 GB, swap-ins < 300/s); env `MODEL` (`v1` default, `v2`), `ENGINE` (`fast` default, `rule` = no-weights check) | Mac-only | no | writes `docs/build/demo-proof/` | + +## Concepts and data structures + +The runtime terms (op, trigger, facts, situation, mode, tier, hold, …) do **not** apply to the extension; it predates the runtime. Its closest analogues: the extension's `state` object plays the role of the runtime's **situation**, and `Engine` plays the role of the runtime's **model host**/decider. New terms used in this doc: + +| term | definition | +|---|---| +| harness | the extension's decision loop and its Python original `jev_local/harness/*` (macOS voice computer-use) | +| `Element` | `{eid, role, label, value?, context?, focused?, enabled?, secure?, submits?, inForm?, searchForm?}`; `eid` is `e01…` in screen order (`content.js` -> `observe`) | +| `Snapshot` | `{id, appName:"Google Chrome", windowTitle, url, browser:true, elements[], focusedEid, walkMs, takenAt}` plus `tabId`, `deniedSite`, `restricted`, `error` added by `sw.js` -> `observe` | +| `Tail` | the unconsumed transcript: `{vid, text, words[], cursor, isFinal, silentMs, uid, joined}` (`Stream.current`) | +| `vid` | virtual utterance id `"+"`; `gen` increments on every consume | +| `Action` | `{kind, sourceVid, confidence, targetEid, targetLabel, app, text, key, url, folder, amount, consumedWords}` (`types.js` -> `makeAction`) | +| `Decision` | `{verdict, action, reason, seq, retryInMs, answers, latencyMs, risk}`; verdicts `act wait ignore clarify confirm deny need_args` | +| `Kind` | `open_app quit_app click type_text search_web open_url press_key scroll_down scroll_up open_folder go_back go_forward new_tab close_tab undo confirm cancel` | +| `Risk` | `LOW 0, MEDIUM 1, HIGH 2, DENY 3` | +| question ids | `intent complete is_command destructive target app key folder text_span url_span scroll_amount`; `folder` omitted in browser mode; `target` only with elements; `text_span`/`url_span` only with candidates | +| staged evaluation | pass 1 = `STAGE1` (`intent complete is_command destructive`); if policy returns `need_args`, pass 2 asks only `ARG_QUESTIONS[intent]` | +| consumed prefix | words already acted on; later partials must still start with them (fillers/chain words ignored) or the stream freezes (`revised_after_act`) | +| rescue | `controller.js` -> `rescueTarget`: for intent `click`, if the target answer is `none`/weak and exactly one on-screen label (≥ 3 chars) occurs verbatim, overwrite the answer (p 0.9) and log `rescue` | +| numbered pick | after "which element?", top-3 candidates get page badges; "number two"/"the second one" within 10 s and ≤ 5 words clicks it without a model call (still through `gate`) | +| pending | a risky action waiting for spoken "confirm" (`Controller.propose`), expires after `confirm_timeout_ms` | +| header key | `sha1(header)[:12]`, the calibration `by_header` key (`engine.js` -> `headerKey`) | +| jevbench | v1 benchmark: 25 test datasets in 7 areas (A Topic … G Multi-question), dev and reference rows (`registry.py` -> `TEST`, `DEV`, `REF`) | +| variant | jevbench request flavour: `main` (counted), `shuffle` (option-order rotation), `bare` (no descriptions), `choice` (SST-2 only) | +| skill | `clip((m − c)/(1 − c), 0, 1)` for primary metric `m` and chance `c` (`metrics.py` -> `skill`) | +| Decision Score | `clip(1 − mean Brier / mean Brier_prior, −1, 1)` per dataset (`metrics.py` -> `decision_score`) | +| benchmax | campaign to beat every published Jev number through each publisher's own harness | +| target row | `targets.json` `targets[]` entry, fields: `id, row, suite, dataset, hf_id, config, split, n, metric, higher_is_better, jev_score, jev_model, jev_protocol, tier, date, source_url, raw_outputs_url, raw_outputs_use, group, category, benchmark_key, role, counted, bar_z, bar_s, bar_source, s_bar_rows, verdict{S:{68m,150m,400m,1b}, Z:{…}, source}, track{Z,S}, train_sources, z_contamination_flags, spec_id, spec_status, note` | +| role | `headline` (154, counted), `s_bar` (10), `secondary` (58), `context` (300), `composite` (4), `diagnostic` (23) | +| track Z / S | Z = zero-shot (no benchmark data of any split); S = supervised (official train splits allowed, disclosed) | +| `Spec` | `{id, suite, adapter, harness, verification, counted_rows, description, owner}`; `id` equals a `targets.json` `spec_id` byte for byte | +| W1–W11 | engine/wire requirements from `suite-reproduction-specs.md` §1.2 (choice argmax of unrounded p, confidence formula, precision, refusal bodies, overflow, …, W10 model id, W11 determinism) | +| `run.json` | per-run record, schema `benchmax-run/1` (`runner.py` -> `RunContext`) | +| decontamination stage 1 | name-level exclusion of training sources (`registry.py` -> `is_excluded(name, track)`) | +| meharsjev / genclass- | model ids used for benchmax runs; `jev-*` and `typesafe/*` are rejected (`runner.py` -> `check_model_id`) | +| CU / GEN | in the head-to-head: CU = synthetic computer-use harness examples (the extension's domain); GEN = generic questions from task families held out of training | +| `jev-local-fast` (v1) / v2-68m / Z-68m | v1 = the 32M Ettin computer-use checkpoint the extension ships (`jev-local-fast-0.1.0`); v2-68m = `jev-local-fast-v2` (68m checkpoint whose training mix contains public-Jev train splits, so no S or Z model may be initialised from it, PLAN §2.3 item 5, and it cannot back a Z claim on about 25 counted rows, PLAN §0); Z-68m = `meharsjev-68m-z`, the clean zero-shot benchmax retrain | +| release read (M0) | one pre-registered scoring of jevbench test splits for a release tag (`--release m0`); test splits are read once per release | +| group A / group B | benchmax adapter families: A (4 specs, `adapters_a`, own `add_arguments/verify/run`), B (15 specs, `adapters_b`, `prepare/items/score/fit`, wrapped by `bridge_b`). "Eval-only" B suites (`asevlad_injection`, `mbburabak_safety`) have no non-test split, so dry passes only `verify` them | + +Message routing in the extension: every `chrome.runtime.sendMessage` carries `{to: "sw"|"brain"|"panel"|"content", type, …}`. + +| receiver | message types | +|---|---| +| `sw` (`sw.js`) | `ensure_brain observe execute tabs badges listening filter_enabled_for filter_blocks filter_count filter_site tab_list_full tab_get page_info tab_op ram_tick active_host open_mic_page` | +| `brain` (`offscreen.js`, two listeners) | `init settings start stop toggle kill text confirm cancel status log bench_speech bench_model play_audio clear_cache`; features: `filter_classify focus_config tab_event focus_keep focus_state relevance` | +| `panel` (`panel.js`) | `status progress ui{event}` with events `transcript decision executed pending picks error info denied killed` (the controller also emits `halted`, which the panel ignores; the brain refreshes `status` instead); `lists_changed focus` | +| `content` (`content.js`) | `observe execute badges listening ping page_info filter_set filter_unhide_all` | + +Storage (`chrome.storage.local`): `settings` (panel `DEFAULTS` + `filter/focus/ram`), `parked` and `ramFreed` undo lists (max 50 via `sw.js` -> `pushList`), `ramStatus`. Cache Storage: `genclass-models-v1` (decision model) and transformers.js caches (speech models). `brain clear_cache` deletes `genclass-models-v1` and every cache whose name starts with `transformers`. + +### Extension model I/O (v0.1 ONNX graph) + +Defined by `extension/tools/genclass_export.py` (docstring) and `src/model/meta.json` `inputs`/`outputs`; fed by `core/engine.js` -> `Engine.feeds`. Batch is always 1, no padding; all inputs `int64`. + +| tensor | shape | meaning | +|---|---|---| +| `input_ids`, `position_ids`, `q_group`, `i_group` | `[1, L]` | packed sequence; `q_group` = -1 for state else question ordinal; `i_group` = -1 for state and header tokens else item ordinal (`core/packer.js` -> `Packer.layout`) | +| `choice_q` `[G]`, `choice_items` `[G, K]` | | flat index of each choice question's `[Q]` marker and its `[O]` item markers (padded with 0) | +| `score_q` `[S]`, `score_items` `[S, K2]` | | `[Q]` and `[L]` markers | +| `noul_q`, `noul_t`, `noul_f` | `[M]` | `[Q]`, `[T]`, `[F]` markers | +| outputs `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` | fp32 | raw logits at temperature 1; padding columns are garbage (`unpackLogits` slices to `labels.length`). An absent kind is fed a dummy `[0]` | + +Calibration and answers (`core/engine.js`, mirrors `jev_local/engine/encoder/calibrate.py` and `jev_local/confidence.py`): + +1. Temperature for choice/score: `by_header[headerKey]` -> `by_bucket[":"]` -> `tau_k` (`a + b·ln(max(K,2))`, clamped to `bucket_clamp` default `[0.5, 5.0]`) -> the kind's scalar (`choice` 0.6835, `score` 0.8572 in v0.1) -> 1.0. +2. Noul: `sigmoid(a·logit + b)` with `a = 1/by_header[hk]`, else `noul_platt {a, b}`, else `a = 1/noul` (1.468 in v0.1), `b = 0`. +3. Choice answer: `choice` = argmax of the unrounded p (first wins ties); `confidence = clip01((K·pmax − 1)/(K − 1))`; probabilities rounded to 2 dp (`pyRound`, half-even). +4. Score answer: `score = Σ i·pᵢ`; `confidence = max(0, 1 − Σ pᵢ·|i − mode| / MAD_uniform(K))`. + +Tokenizer (`src/model/tokenizer.json`): byte-level BPE, 50,280 vocab entries, 121 added tokens (12 special: `<|padding|>`, `<|endoftext|>`, `[UNK]`, `[CLS]`, `[SEP]`, `[PAD]`, `[MASK]`, `[Q]`, `[O]`, `[L]`, `[T]`, `[F]`; 109 non-special: `|||IP_ADDRESS|||`-style placeholders, `[unusedN]`, space runs of 2–24). + +### Extension feature questions (`core/features.js`) + +| feature | request | answer -> verdict | +|---|---|---| +| content filter | one `choice` per block (`b`), instruction "What kind of page block is this? Block: \"\"", criteria `BLOCK_KINDS` = `ad`, `sponsored`, `clickbait`, `off_topic` (only when a focus task is set), `normal`; state `{site, page, task}` | `filterResults`: hide when choice ≠ `normal` and p ≥ `minP` 0.6. Presets skip the model: iframe host matches `AD_HOST_RE` (doubleclick, googlesyndication, taboola, outbrain, criteo, …) -> `ad`; a ≤ 24-char leaf label matching `LABEL_RE` (`sponsored`, `promoted`, `advertisement`, `ad`, `ads`, `paid partnership`, `anzeige`, `publicité`) -> `sponsored` | +| focus mode | one `noul` per tab (`t`), "Does this browser tab help with \`task\`? Tab: \"\" (<host>) - <description ≤ 140>", criteria `RELEVANT`; state `{task ≤ 200 chars}` | `focusVerdict`: on-task if p ≥ `FOCUS_MODEL_MIN` 0.04 or `keywordOverlap` > 0 (content words ≥ 4 chars, not in `STOP`, first 6 letters) | +| RAM relevance | same as focus (`Features.relevance`, chunks of 16) | `discardOrder`: relevance (default 0.5) ascending when the gap > 0.15, else `lastAccessed` ascending | + +### jevbench v1.1 datasets (`jev_local/bench/registry.py`) + +| role | keys (area letter) | +|---|---| +| `TEST` (25, counted; index runs over the 24 built) | A Topic: `ag_news`, `yahoo_topics`, `fin_topic`; B Sentiment: `sst2`, `fin_phrasebank`, `sst5`, `yelp5`; C Emotion: `dair_emotion`, `tweeteval_emotion`, `go_emotions`; D Intent: `banking77`, `clinc150`, `massive`; E Inference: `boolq`, `rte`, `anli`, `paws`, `stsb`; F Fact & safety: `llm_aggrefact` (gated, not built), `climate_fever`, `toxic_chat`, `openai_moderation`; G Multi-question: `typed_decisions`, `unfair_tos`, `helpsteer2` | +| `DEV` (10, clean set `clean-2026-10-03`; selection and calibration only) | `newsgroups20`, `tweeteval_sentiment`, `atis`, `snips`, `mrpc`, `scitail`, `cb`, `tweeteval_offensive`, `scifact`, `tasksource_heldout` (same list as `scripts/dev_to_calib.py` -> `CLEAN_DEV`) | +| `RETIRED_DEV` (5, moved to `public_jev`) | `tweet_topic`, `app_reviews`, `hwu64`, `toxigen`, `prompt_injections` | +| `REF` (area `K`, shown, not counted) | `hellaswag`, `winogrande`, `mmlu_pro`, `bbh` (M0 reports the first three) | + +Exclusion categories (`registry.py` -> `exclusion_reason(name, track)`, Z precedence in `_z_reason`; first match wins, in this order): exact ids (`EXCLUDED_DATASET_IDS`), then the rule families `test:<key>`, `dev:<key>`, `sibling:<key>`, `jev_labelled`, then `public_jev:<key>` (hand rules, then the generated hf-id / repo-segment / key-token tables; sources of the 549 published rows), then `reserved:<key>` (external typed-decision suites), then held-out tasksource dev families. On track S, `s_allow_reason` (the S allow-list: train-split targets and their `train_sources`) waives `test`/`sibling`/`public_jev` matches; `jev_labelled`, `reserved`, `S_DENY_RULES` (reported as `s_deny:<rule> (<reason>)`), `dev:tasksource_heldout` and the clean dev sets are never waived (a clean dev set is waived only when that dataset is itself a train-split target). + +### benchmax spec registry (19 specs) + +`Spec.id` equals `targets.json` `spec_id`. "Headline rows" = `role == "headline"` rows of `targets.json` carrying that `spec_id` (132 of 154 in total). + +| spec id | group / module | suite | headline rows | +|---|---|---|---| +| `deusser_exact@6bbdeb33` | A / `adapters_a/deusser.py` -> `DeusserAdapter` | Deußer, Sparrenberg & Sifa 2026 (37 tasks; CI bootstrap 500, seed 0; overflow truncate) | 37 | +| `decision_index_0.2.1@87d4650b` | A / `adapters_a/decision_index.py` -> `DecisionIndexAdapter` | Decision Index 0.2.1 kit (overflow refuse; unrounded p) | 41 | +| `typed_decisions_card@d0e2f0c4` | A / `adapters_a/typed_decisions.py` -> `TypedDecisionsAdapter` | LocalLLaMA/typed-decisions (400 cases; scorer pinned by Prior/Uniform rows) | 1 | +| `jevbench_hf_praveenrajus_v0.1.1` | A / `adapters_a/jevbench_hf.py` -> `JevbenchHfAdapter` | Praveenrajus/jev-bench v0.1.1 (22 configs) | 13 | +| `chepyle_lexglue_systemone_v1` | B / `chepyle_lexglue` | LexGLUE 7 tasks + BANKING77 + CLINC150 | 7 | +| `mbburabak_safety` | B / `mbburabak_safety` (eval-only) | HateCheck, ToxicChat, Aegis v1/v2, WildGuardTest, HarmBench | 7 | +| `dmb_expanded@eabd88b0` | B / `dmb_expanded` | DMB expanded: BANKING77, CLINC150+OOS, NLU++ | 1 | +| `rerank_scripts` | B / `rerank_scripts` | rerank scripts: denser-org (BEIR SciFact/NFCorpus), hev (SciFact/NFCorpus/FiQA), anessbelbati (8 sets + NevIR) | 4 | +| `elcronos_plain` | B / `elcronos` | emotion, TweetTopic, fin topic, DailyDialog | 3 | +| `zhuyansen_batch20` | B / `zhuyansen` (multi-stage) | 20 texts per call: AG News, SST-2, BANKING77, TweetEval emotion, PAWS, arXiv | 2 | +| `thisisandreeeee` | B / `thisisandreeeee` | BANKING77, CLINC150, HWU64, SST-2 noul, STS-B score | 1 | +| `asevlad_injection` | B / `asevlad_injection` (eval-only) | combined prompt-injection corpus (11,900 rows) | 1 | +| `stperic_medhallu` | B / `stperic_medhallu` | MedHallu 1,000 items | 1 | +| `goya_rm_eval` | B / `goya_rm` | RewardBench 1/2, RM-Bench, RubricBench, PPE, ProcessBench, PRMBench | 8 | +| `study:earino_zero_shot_complaint_benchmark_cfpb_113_cl` | B / `study_cfpb` | CFPB complaints, 113 issues | 1 | +| `study:do_system_one_decisions_add_up_arxiv_2609_33971` | B / `study_trec50` | TREC-50 | 1 | +| `study:jev_for_network_traffic_classification_arxiv_261` | B / `study_cesnet` | CESNET-QUICEXT-25 | 1 | +| `study:koa_action_arxiv_2609_36115` | B / `study_amazon_polarity` | SST-2, Amazon Reviews Polarity | 1 | +| `study:jev_ids_arxiv_2610_01079` | B / `study_nslkdd` | NSL-KDD | 1 | + +Win rule (`bench/PREREG-benchmax.md` §1): Win iff `ours − jev_score > bar`, with `bar = bar_z` (Z) or `bar_s` (S) from `targets.json`; the bar is √2 x the publisher's CI half-width where one is published (the 37 Deußer rows), else `1.96·√(2p(1−p)/n)`; for `higher_is_better: false` metrics the inequality is reversed. The S bar uses `max(Jev zero-shot, Jev given train data) + margin` where a `s_bar` row exists. Where publishers disagree on Jev's value, the stricter one is used. + +## How it works + +### 1. Extension boot and model load + +1. Panel opens -> `panel.js` loads `settings`, sends `{to:"sw", type:"ensure_brain"}`; `sw.js` -> `ensureBrain` creates `offscreen.html` (reasons `USER_MEDIA`, `WORKERS`). +2. Panel sends `brain init` -> `offscreen.js` -> `init` runs `loadEngine` and (unless `speechEngine === "chrome"` or `preloadSpeech === false`) `loadSpeech` in parallel. +3. `loadEngine`: reads `model/{model.json,tokenizer.json,calibration.json,meta.json}`; `gpuInfo()`; plan list: if `settings.compute !== "wasm"` and WebGPU is available -> `["fp16","webgpu"]` when `shader-f16` else `["q8","webgpu"]`; `["q8","wasm"]` is always the last plan (the only one when `compute === "wasm"` or there is no WebGPU). +4. Per plan: bundled `model/genclass-<v>.onnx` if present (HEAD probe) else download `settings.modelBaseUrl || card.default_base_url` + file via `fetchCached` (Cache `genclass-models-v1`, size check on hits, sha256 check on download, progress to panel). +5. `ort.InferenceSession.create(buf, {executionProviders:[provider], graphOptimizationLevel:"all"})` -> `new Engine(...)` -> two warm-up `evaluate` calls on a realistic request; `B.engineInfo = {variant, provider, threads, loadMs, warmMs}`. First failing plan falls through to the next. +6. `buildController()` wires `Controller` with `observer` (snapshot via `sw observe`, 1200 ms cache), `executor` (`sw execute`, undo stack of 20), `appsFor` (`sites.js` -> `appCatalog`), `ui` and `log` (ring of 2000 entries). + +### 2. Spoken (or typed) command -> action + +1. Speech source emits `{kind: speech_start|partial|final|speech_end|error, uid, text}`. Local engines (`LocalSpeechSource`): energy VAD (voiced if RMS > max(0.012, noise x 3.5)), 300 ms pre-roll, the whole open utterance is re-transcribed roughly every `stepMs` (a `tick` timer at max(50, stepMs/2) ms decodes once ≥ 0.8·stepMs of new audio has arrived; `cadenceMs` = max(stepMs, last decode ms)); utterance ends after 600 ms of silence or 25 s. Panel text input (`brain text`) streams one partial per word every 230 ms, then a final after 350 ms (`textCommand`). +2. `offscreen.js` -> `onSpeech` sets `controller.cadenceMs` from the local source; `Controller.onEvent` -> `Stream.update(ev, now)` returns the unconsumed tail (or null if frozen/dropped/too short). +3. Final -> immediate `request("final")`; partial -> `debounceRequest` (120 ms, capped at 300 ms since the first pending partial; 0 ms once `cadenceMs` is set). `armSilence` schedules re-decisions at `payload_silence_ms` and `silence_complete_ms` (+15 ms). +4. One decision in flight; newer requests coalesce into one `want` (`drainWants`). `decide` loops `decideOnce` up to `MAX_LOOPS` = 4 times after actions (`post_action`). +5. `decideOnce`: absorb leftover words of the last action (`absorbLeftovers`), skip if the key `[vid, cursor, text, isFinal, silenceBucket, pendingId]` repeats, snapshot, `buildState` + `buildQuestions(..., {browser:true})`, numbered pick shortcut, then `ask()` (staged by default). +6. Stale check: if the stream's `vid`/`cursor` changed during inference -> `stale_dropped`; if only the text grew -> `stale: true` (closed-set commands may still act; payload and silence gates are treated as not met). +7. `rescueTarget`, then `policy.js` -> `evaluatePolicy` (gate order: pending confirm/cancel; `is_command` < 0.5 -> ignore; intent `none`/`wait`/low -> ignore/wait; `complete` < 0.65 unless final or ≥ 900 ms silence -> wait; `type_text`/`search_web` wait for final or ≥ 600 ms silence; `open_url` also waits unless the address is closed by "and/then"; argument gates; stability: on an unsettled partial a closed-set act needs `complete` ≥ 0.85 or the same pick twice). +8. `safety.js` -> `gate(decision, snap, cfg, said)`: deny rules -> `deny`; HIGH risk -> `confirm` if intent p ≥ 0.85 and (for clicks) target p ≥ 0.75 else `clarify`; `destructive` ≥ 0.5 -> `confirm`. +9. `Controller.apply`: `wait`/`ignore` may skip leftover words; `clarify` on "which element"/"not sure enough" offers numbered picks; duplicates are suppressed by the fired-key set `[vid, cursor, n]` and `stream.matches`; `deny` drops the utterance; `confirm` -> `propose` + drop utterance; `act` -> rate limit (3 per 1.0 s) -> consume words -> `execute`. +10. `executor.run` -> `sw.js` -> `execute`: tab-level kinds (`new_tab close_tab go_back go_forward open_url search_web open_app quit_app undo`, `press_key cmd+r`/`cmd+n`) run in the SW; everything else is forwarded to the content script (`content.js` -> `execute`: click, type into focused/best field via `execCommand("insertText")`, key emulation, scroll). Dry run (`settings.dryRun`, default **true**) executes nothing: click/type targets are highlighted, every other kind only returns a "dry run: would …" detail. +11. Page observation (`content.js` -> `observe`, called via `sw.js` -> `observe`, which injects the content script on demand with `ensureContent` and short-circuits restricted URLs to `{restricted: true}`): collects `SELECTOR` matches (links, buttons, inputs, selects, textareas, summaries, ARIA widgets, contenteditable, `[onclick]`); drops invisible/occluded ones, controls nested in an already-collected control, and secure inputs unless focused (their `value` is never sent). Over the `max` cap (default 60) it keeps the highest score: focused +100, each label word (> 2 chars) the speaker used +10, in viewport +1. Elements are sorted by top (8 px tolerance) then left, numbered `e01…`, and repeated `role|label` pairs get " (k of n)". The last 5 snapshots' eid -> node maps are kept for `execute`. +12. Undo (`sw.js` -> `execute`, case `undo`, on the last entry of the brain's undo stack): a tab it opened is closed (`undo.closeTab`); a navigation goes back (`undo.back`); a scroll scrolls the other way by the same amount; typing runs `execCommand("undo")` in the page (`undo_type`); anything else sends `cmd+z`. `open_folder` always fails in the browser. `open_app` switches to a matching tab (`sites.js` -> `appCatalog` resolve) or opens the site URL, reusing an empty/new-tab page; `quit_app` closes the matching tab. +13. Lifecycle: on install `sw.js` sets `openPanelOnActionClick` and opens `welcome.html` (mic permission page; `open_mic_page` reopens it at `#mic`); `chrome.commands` `toggle-listening` -> `ensureBrain` + `brain toggle`, `kill-switch` -> `brain kill {from:"shortcut"}`. + +### 3. Confirmation and kill switch + +1. `propose` stores `pending`, `pendingMark = [uid, heardWords, now]`, starts an 8 s timer, shows the panel card. +2. A later tail with intent `confirm` passes only if `confirmationAllowed` (different `vid`, not `joined`, same-uid tails must start after the mark and be heard ≥ `CONFIRM_REACTION_S` = 0.8 s after it), `AFFIRM_RE` matches, intent p ≥ 0.8, and the phrase is settled or `complete` ≥ 0.85. Intent `cancel` with p ≥ `CANCEL_TOP_P` (0.5), or a `NEGATE_RE` match while the intent is `cancel`/`confirm`/`none`/`wait`, drops it (`policy.js` -> `pendingDecision`). The panel's Confirm button counts as an explicit yes (`confirmFromUi`). +3. Kill: Esc on a page while listening (trusted event), panel "Stop all", or Alt+Shift+K -> `brain kill` -> `Controller.halt()` (cancels everything, drops pending, skips stream to end) + stop listening + abort a streaming text command. `resume()` on the next start. + +### 4. Opt-in features (all off by default) + +- **Content filter:** content script `collectBlocks` (≤ 30 blocks, ≥ 120x30 px, ≥ 25 chars unless ad marker, outside nav/header/footer/form) -> `sw filter_blocks` -> `filterRequest` presets: ad-network iframe hosts -> `ad`, small labels like "Sponsored"/"Promoted" -> `sponsored`, known ad selectors -> `ad`; only if `filter.model` is on are the rest sent to the brain (`classifyBlocks`, chunks of 10, hide non-`normal` picks with p ≥ 0.6). Hidden blocks get a "show" link; the badge counts them; per-site toggle `filter.sites[host] = false`. `content.js` -> `runFilter` is debounced (`scheduleFilter`): 600 ms after load when enabled, 1200 ms after scroll, 1500 ms after DOM mutations (`MutationObserver`), 100 ms after `filter_set`; blocks already sent once (`classified`) are not re-sent. Settings changes are pushed by `sw.js` `storage.onChanged` (`setFilterForAll`, `configureAlarms`, `brain focus_config`). +- **Focus mode:** `focusRequest` asks one noul per tab ("Does this browser tab help with `task`?"), chunks of 16; `focusVerdict` = on-task if p ≥ `FOCUS_MODEL_MIN` (0.04) **or** any shared content word (≥ 4 chars, first 6 letters). Off-task tabs are discarded/closed after `graceMin` (default 5 min; `features_rt.js` floors it at 0.25 min, the panel input at 1 min) unless used during the session, opened from an on-task tab, or protected (`protectedTab`: pinned, audible, active, unsaved input, browser pages). +- **RAM manager:** alarm `genclass-ram` every 1 min -> `ramTick` reads `chrome.system.memory`; below `minFreePct` (15%) it discards up to `maxPerRound` (3) idle (> `idleMin` 10 min) unprotected http(s) tabs in `discardOrder` (lowest focus relevance first when relevance differs by > 0.15, default 0.5, then least recently used; relevance is only computed while focus mode is on with a task). + +### 5. Model lineage and parity (extension -> runtime) + +1. The model is the v1 32M checkpoint `jev-local-fast-0.1.0` (Ettin-32m, 10 layers, hidden 384, layer pattern full, then (sliding, sliding, full) x 3; `meta.json`). Python reference: `jev_local/engine/encoder/{tokenize_pack,engine,calibrate}.py` (see [genclass-model-lineage.md](genclass-model-lineage.md)). +2. `extension/tools/genclass_export.py` (VM, torch) exports `ExportModel` with the block attention mask built in-graph from `q_group`/`i_group`/`position_ids` (sliding layers also need `|pos_q − pos_k| ≤ window` = 64), writes fp32/fp16/q8 ONNX, `parity.json`, `pack_fixtures.json`, `torch_fixtures.json`, `tokenizer.json`, `calibration.json`, `meta.json`. +3. `release-assets/parity.json` (50 requests, 353 choice/score + 150 noul answers): fp32 max |Δlogit| 2.05e-5, 353/353 + 150/150; fp16 0.0177, 353/353 + 150/150; q8 0.365, 352/353 + 150/150. Tokens per request min 1065, median 1274, max 1661. ORT CPU p50 at 8 threads: fp32 126.9 ms, fp16 157.4 ms, q8 136.2 ms (PyTorch banded 152.4 ms); file sizes 134.2 / 67.2 / 56.9 MB. q8 = `MatMulNBits` 8-bit weight-only, block 32, symmetric, fp16 embedding table (`genclass_export.py` -> `make_q8`); export opset default 17. +4. Extension JS (`tokenizer.js`, `packer.js`, `engine.js`) is checked against these fixtures by `test/unit/pack_parity.test.mjs` and `engine_parity.test.mjs`. +5. `packages/runtime/src/model/*.ts` was ported from the extension JS and is tested against the **same** fixtures (`packages/runtime/test/fixtures/model/{pack_fixtures,torch_fixtures}.json` hold the same JSON values as the extension's, re-serialised without whitespace, so `cmp` differs but a parsed comparison is equal; `requests50.json` is the same 50 requests minus the `gold`/`screen_type` keys). Differences in the port: heap-based BPE merges and tokenizer options read from the file (pruned vocabularies work), markers/ids from `meta.json`, graph inputs built from `meta.json` `inputs`, typed errors, default precision `"exact"` (the extension always rounds to 2 dp, `round2`). See [runtime/model-host.md](runtime/model-host.md) and [model-io-contract.md](model-io-contract.md). +6. The runtime's loader still accepts the v0.1 extension card (`bundled`, `default_base_url`, no `files`): `packages/runtime/src/model/loader.ts` -> `parseCard` falls back to `tokenizer.json`/`calibration.json`/`meta.json` without hashes (cache-keyed by `name@version`). + +### 6. Building and releasing the extension + +1. `npm ci` in `extension/` (own lockfile; not a root workspace). +2. `node scripts/build.mjs`: esbuild bundles `sw.js` (esm), `content.js` (iife), `panel.js`, `welcome.js`, `offscreen.js` (conditions `onnxruntime-web-use-extern-wasm`) for `chrome116`, minified unless `--dev`; rewrites transformers.js' jsDelivr ORT wasm path to `/ort/` and **throws if any `cdn.jsdelivr.net` URL remains** (MV3: no remote code); copies `static/`, sets `manifest.version` from `package.json`, copies `ort-wasm-simd-threaded.asyncify.{mjs,wasm}` into `ort/`, copies `src/model/*` small files; `--bundle-model` also copies `release-assets/genclass-{q8,fp16}.onnx`. +3. `--zip` (also `npm run package`) -> `dist/genclass-<version>.zip` (uses the system `zip`); `--release` implies the zip, verifies each `release-assets/<variant>.onnx` sha256 against `src/model/model.json` (throws on mismatch, warns if missing), writes `dist/release/` (ONNX files, the four model JSONs, the zip, `ASSETS.json` with names/bytes/sha256 plus the Hugging Face speech files fetched at runtime) and `dist/store/` (copy of `store/` + `privacy.html` rendered by the built-in `mdToHtml`). Every build also copies `LICENSE` and `NOTICE` into `dist/genclass/`. +4. Load for development: `chrome://extensions` -> Developer mode -> Load unpacked -> `dist/genclass/`. Screenshots: run the e2e specs (they write raw shots to `dist/store/screenshots/raw/`), then `node scripts/compose_screens.mjs` (Playwright Chromium) composes the 1280x800 store images; `node scripts/make_icons.mjs` regenerates `static/icons/*.png`. +5. Manual publication steps are in `extension/RELEASE.md` (GitHub release `v0.1.0` asset names must match exactly; q8 must be 56,931,453 bytes; Web Store: upload the zip, declare no remote code). + +### 7. jevbench v1 pipeline (`scripts/jevbench.py`) + +1. `build` (VM): `jev_local/bench/build.py` downloads pinned HF revisions, samples with seed 20261001 (`build.py` -> `sample_items`: `all`, `random`, or `strat` / `strat_by_source` with largest-remainder proportional quotas), renders `templates.py` mappers, writes `bench/jevbench/<role>/<key>__<variant>.jsonl` rows `{id, dataset, variant, item, stratum, request, gold, meta}` and `manifest.json`. +2. `run-ours` (VM): `ours.py` -> `OursRunner.answer` packs with exact chunking (options and questions are attention-isolated, so splitting a request into passes that repeat the state and concatenating raw logits is exact), truncates the longest state field only if the state + one unit cannot fit. +3. `run-jev` (Mac, OpenRouter `https://openrouter.ai/api/alpha/decisions`, model `typesafe/jev-1.13`): ≤ 6 workers, 6 attempts, retries on 408/409/425/429/5xx, aborts on 401/402/403, append-only cache, `--max-cost` 8.0 $. +4. `score` (VM): `metrics.py` aligns probabilities to canonical labels, rounds to 2 dp, failures = wrong/uniform, paired item-clustered stratified bootstrap B = 2000; `report` renders `REPORT.md`. +5. Claim rule (pre-registered): (a) CI lower bound of index(ours) − index(Jev) > 0 for both indices, (b) strictly higher primary metric on ≥ 13 datasets, (c) no area trails by > 10 skill points. +6. File layout (`scripts/jevbench.py` docstring and constants `BENCH`, `RUNS`): requests `bench/jevbench/<role>/<key>__<variant>.jsonl[.gz]` (VM; the Mac copy for `run-jev` is `runs/jevbench/requests/`); results `runs/jevbench/<release>/{jev.jsonl, ours__<name>.jsonl, scores.json, REPORT.md}`. Request files are read variant-major (`main`, `choice`, `shuffle`, `bare`) so the primary pass completes first. None of these are in the repo. + +| subcommand | flags (defaults) | +|---|---| +| `build` | `--out bench/jevbench`, `--keys ""`, `--roles test,dev,ref` | +| `run-ours` | `--ckpt` (required), `--release` (required), `--name ""`, `--requests bench/jevbench`, `--roles test,ref`, `--variants main,choice,shuffle,bare`, `--keys`, `--workers 8`, `--threads 2`, `--chunk 64`, `--max-tokens 0` | +| `run-jev` | `--release` (required), `--requests runs/jevbench/requests`, `--roles test`, `--variants main,choice,shuffle,bare`, `--keys`, `--workers 6`, `--attempts 6`, `--limit-per-file 0`, `--max-cost 8.0` | +| `score` | `--release` (required), `--requests bench/jevbench`, `--ours`, `--jev`, `--roles test,ref`, `-B 2000`, `--seed 20261001`, `--out scores.json` | +| `report` | `--release` (required), `--scores scores.json`, `--note` (repeatable release-note bullet) | + +### 8. benchmax pipeline + +1. `scripts/benchmax_build_targets.py` builds `targets.json` (549 rows) from `jev_published.json` + the feasibility verdict tables, derives the registry's `public_jev` family and writes `exclusions.json`; `--write-registry` rewrites the generated block in `registry.py`; `--check` exits 1 when anything is stale. +2. `PREREG-benchmax.md` freezes the hashes of those files plus the research notes (decision rules: Win only if `ours − jev_score > bar_z|bar_s`; Ahead (n.s.), Tie (< 1 pt), Behind; Z and S scoreboards never merged; no Jev output ever enters training/selection/calibration). +3. `scripts/benchmax.py run --spec <id> (--ckpt | --base-url | --engine heuristic)` loads the spec (`load_specs`), wraps group-B classes with `bridge_b.bridge_class`, builds a client (`runner.build_client`), runs, writes `run.json`, replays the first N requests for W11. Group-B test splits need `--allow-test`; reruns into a complete `--out` need `--rerun-reason`. +4. `scripts/phase3_eval.sh` is the runbook for a finished checkpoint: global calibration on the clean dev set (no `by_header`), then every spec serially on VM `train`. +5. Validation passes before any test read: `scripts/benchmax/stage0_validation.sh` (non-evaluated splits, `summary.tsv`) and `scripts/benchmax/dry_pass_validation.sh` (all 19 specs; DI uses synthetic smoke rows since it has no non-test split); `scripts/benchmax/engine_determinism.py` reports W11 on synthetic requests only. +6. Group-B adapters can also be driven without the shared runner via `python -m jev_local.bench.benchmax.adapters_b.driver prepare|items|run|score|fit|selfcheck --spec <id> --split <split>` (`--engine local|http`, `--ckpt` default `$JEV_LOCAL_FAST_CKPT`, `--url` default `http://127.0.0.1:8765`, `--threads 8`, `--allow-test`, `--no-resume`, `--rebuild-items`); `selfcheck` refuses the test split. Its `run.json` is lighter than `benchmax-run/1`. + +`scripts/benchmax.py run` flags (`_common`, `_engine`): + +| flag | default | meaning | +|---|---|---| +| `--spec` | required | spec id (`list` prints them) | +| `--out` | `runs/benchmax/<ckpt>/<spec>/` | run directory | +| `--model-id` | `genclass-68m` | W10 wire model id (checked by `check_model_id`) | +| `--threads` | 8 | torch threads for the local engine | +| `--ckpt` / `--base-url` / `--engine local\|http\|heuristic` | local if `--ckpt`, http if `--base-url` | engine client | +| `--wire-model` | — | model id put on the wire for `--base-url` (disclosed) | +| `--calib` | checkpoint's file | W9 calibration override | +| `--max-tokens` | engine limit | context override | +| `--overflow refuse\|truncate` | the spec's rule | W5 | +| `--precision unrounded\|2dp` | `unrounded` | W3 | +| `--refusal-status 400\|422` | 400 | W4 HTTP status of in-process refusals | +| `--determinism N` | 20 | W11: re-send the first N requests at the end | +| `--trace` | off | write every request/response to `<out>/trace.jsonl` | +| `--rerun-reason` | — | required when `<out>/run.json` is already complete (old one kept as `run.<timestamp>.json`) | +| `--track Z\|S` | `Z` | recorded only | +| group-B extras (`bridge_b`) | — | `--split`, `--limit`, `--tasks`, `--work`, `--thresholds`, `--fit`, `--allow-test`, `--skip-prepare`, `--resume` | + +### 9. Headline results (what may be quoted, with caveats) + +All are documents in the repo; none can be reproduced from the repo alone (the data, models and run directories live on the VMs). + +| source | result | +|---|---| +| `results/genclass-vs-jev-computer-use.md` (1,280 examples: 1,000 CU + 300 GEN sampled, seed 7; Jev = `typesafe/jev-1.13` via OpenRouter; ours = `jev-local-fast` v1 32M) | fair rows: intent complete 91.4 % vs 92.0 % (tie, n=336); intent mid-sentence 66.4 % vs **90.4 %** (n=664); target real element **86.6 %** vs 82.4 % (n=119, ±7 pts); text span real payload 75.5 % vs **94.9 %** (n=98); GEN held-out families **94.7 %** vs 80.5 % (n=451). Latency p50/p95: Jev 177/311 ms (incl. network), ours 187/204 ms (Azure EPYC CPU, 4 threads). Jev cost $0.1049 for 2,498,287 input tokens. 20 GEN examples excluded (OpenRouter 400 on object criteria). | +| same file, wire conformance vs 1,280 real Jev responses | choice confidence 6,239/6,244 within 0.02; score confidence 1,053/1,053 within 0.03; score value 1,051/1,053 within 0.02 | +| `BENCHMARKS.md` | public summary of the above plus per-question rows (is_command 82.4 vs 96.1, complete 72.7 vs 93.3, destructive 94.1 vs 99.4, app 96.5 vs 99.0, key 89.4 vs 98.7, URL 81.6 vs 100 (n=49), scroll 59.3 vs 98.1 (n=54)); order robustness (GenClass 0 flips by construction; Jev 10.3 % / 13 % per third-party tests); AG News 0.882 (Jev) vs 0.315 | +| `results/jevbench-m0.md` (release read M0, 2026-10-02) | `jev-local-fast` v1: skill index **10.1** [9.7, 10.7], Decision-Score index **−27.9** [−28.6, −27.1]; 0 option-order flips on 11 choice datasets; noul polarity broken on general yes/no (SST-2 noul 0.491 vs 0.735 as a 2-option choice; BoolQ 0.384). Jev valid only on AG News (0.882) and Yahoo (0.743) after HTTP 402; no claim evaluated. `llm_aggrefact` not built (gated), so indices span 24 datasets. Harness sanity: AG News 0.882 vs Deußer's 0.885 (n=7,600). | +| `results/z68m-dev-notes.md` | Z-68m (clean zero-shot 68m retrain) final step 2010: clean-dev skill 40.2, decision-score 5.6, mean of 7 shared dev sets 0.602 vs v2-68m 0.604 (parity); fitted calibration does not transfer (split-half 0.023 -> 0.029), so ship identity calibration | +| `bench/public/targets.json` `counts` (predictions, not results) | 549 rows, 154 counted (groups A 37, B 41, C 7, E-A 33, E-B 13, G 23). Predicted W/T/L of 154: S-68m 21/31/102, S-150m 29/37/88, S-400m 37/48/69, S-1b 43/55/56; Z-68m 0/14/138 (+2 n/a), Z-1b 2/42/108 (+2 n/a). No benchmax test-split result exists in the repo. | +| `extension/README.md` (not re-measured) | commands eval 16/18; Moonshine first partial 149 ms, RTF 0.08, Whisper base.en 1238 ms, RTF 0.48 (CPU-only Linux VM, WASM x4); decision latency WASM x4: staged pass 1 212 ms p50, full fan-out 713 ms, 251 ms p50 end-to-end; WebGPU not measured | + +## Configuration and constants + +### Extension + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `DEFAULT_THRESHOLDS.is_command` | number | 0.5 | `core/types.js` | below -> `ignore` | +| `.intent_conf` / `.intent_top_p` | number | 0.45 / 0.55 | `core/types.js` | below -> `wait` | +| `.complete` / `.stable_complete` | number | 0.65 / 0.85 | `core/types.js` | completeness gate / act on a partial without a second agreeing pick | +| `.target_conf` / `.target_top_p` | number | 0.45 / 0.35 | `core/types.js` | click target gates | +| `.span_top_p` / `.app_top_p` / `.key_top_p` / `.folder_top_p` | number | 0.35 / 0.5 / 0.6 / 0.5 | `core/types.js` | argument gates | +| `.destructive` | number | 0.5 | `core/types.js` | ≥ -> confirm | +| `.high_risk_intent_p` / `.high_risk_target_p` | number | 0.85 / 0.75 | `core/types.js` | HIGH risk below these -> clarify | +| `.confirm_p` | number | 0.8 | `core/types.js` | min intent p for a spoken confirm | +| `.silence_complete_ms` / `.payload_silence_ms` | ms | 900 / 600 | `core/types.js` | silence gates (raised for local ASR, below) | +| `.debounce_ms` / `.confirm_timeout_ms` | ms | 120 / 8000 | `core/types.js` | partial debounce; pending expiry | +| `defaultConfig()` | object | `dryRun:true, searchUrl:"https://www.google.com/search?q={q}", allowApps:[], maxElements:60, maxApps:24` | `core/types.js` | controller config | +| `silenceGatesFor(c)` | fn | payload = round(2c + 150), complete = max(payload, 900) | `core/controller.js` | applied when `cadenceMs` is set; also forces `debounce_ms` 0 | +| `MAX_LOOPS` / `MAX_DEBOUNCE_MS` / `SILENCE_MARGIN_MS` | int | 4 / 300 / 15 | `core/controller.js` | re-decide loops; debounce cap; silence timer margin | +| `RATE_MAX` / `RATE_WINDOW_S` | int / s | 3 / 1.0 | `core/controller.js` | executions per window | +| numbered pick window | s / words | 10 / ≤ 5, top 3 | `core/controller.js` -> `numberedPick`, `offerPicks` | badge picks | +| `CONFIRM_REACTION_S` | s | 0.8 | `core/safety.js` | min delay between prompt and "yes" | +| `CANCEL_TOP_P` | number | 0.5 | `core/policy.js` | cancel pending | +| `Stream` echo / dup windows | s | 2.0 / 0.35; closed-uid memory 64 | `core/stream.js` | uid echo inheritance | +| `Packer` options | int | `maxPositions` 1536 (from `meta.max_len`), `maxTotal` 8192, `cacheSize` 8192 | `core/packer.js`, `core/engine.js` | `max_tokens_exceeded` | +| `MAX_ARRAY_SEGMENTS` | int | 64 | `core/serialize.js` | array state segments | +| `K_BUCKETS` / `BUCKET_CLAMP` | consts | `[[2,2],[3,5],[6,10],[11,30],[31,100],[101,255]]` / `[0.5, 5.0]` | `core/engine.js` | calibration lookup | +| `calibration.json` | temps | noul 1.468, choice 0.6835, score 0.8572, 11 `by_header` entries | `src/model/calibration.json` | answer calibration | +| `meta.json` | model meta | `max_len` 1536, `window` 64, `hidden_size` 384, markers `[Q]` 50368 … `[F]` 50372, cls 50281, sep 50282, pad 50283 | `src/model/meta.json` | packer/engine | +| model variants | card | fp16 67,154,907 B (webgpu, needs shader-f16); q8 56,931,453 B (wasm); base `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | `src/model/model.json` | download + sha256 | +| `CACHE` | string | `genclass-models-v1` | `offscreen/offscreen.js` | model cache name | +| ORT threads | int | `min(4, hardwareConcurrency)` if `crossOriginIsolated` else 1 | `offscreen/offscreen.js` | WASM speed | +| snapshot cache | ms | 1200 | `offscreen/offscreen.js` -> `observer` | observe calls | +| `SPEECH_ENGINES` | table | moonshine stepMs 250 (WebGPU 154 MB / WASM 63 MB); whisper-base 500 (206 / 77 MB); whisper-turbo 900, WebGPU only (q4 759 MB / q4f16 564 MB); chrome (cloud) | `offscreen/speech.js` | speech choice | +| `LocalSpeechSource` | opts | `endSilenceMs` 600, `maxUtteranceS` 25, `preRollMs` 300, noise init 0.004, threshold max(0.012, 3.5 x noise) | `offscreen/speech.js` | VAD | +| panel `DEFAULTS` | object | `speechEngine "moonshine", dryRun true, compute "auto", searchUrl "https://www.google.com/search?q={q}", maxElements 60 (clamped 10–100), staged true, modelBaseUrl "", lang "en-US"` | `sidepanel/panel.js` | settings | +| brain-only settings | keys | `targetTabId` (act on a fixed tab instead of the active one; set by e2e), `preloadSpeech` (`false` skips speech load in `init`) | `offscreen/offscreen.js` | not in the panel UI | +| `DEFAULT_FEATURES` | object | filter `{enabled:false, hide:{ad:true, sponsored:true, clickbait:false, off_topic:false}, sites:{}, model:false}`; focus `{enabled:false, task:"", action:"discard", graceMin:5}`; ram `{enabled:false, minFreePct:15, idleMin:10, maxPerRound:3}` | `background/sw.js` (copy in `panel.js` `FEAT_DEFAULTS`) | features | +| RAM alarm | string / min | `genclass-ram`, `periodInMinutes` 1 | `background/sw.js` -> `configureAlarms` | created only while `ram.enabled` | +| `Engine` defaults | ctor | `provider "wasm"`, `variant "int8"` (name `genclass-<variant>`; the brain always passes `q8`/`fp16`), packer `maxPositions = meta.max_len` | `core/engine.js` | `model` field of answers | +| `textCommand` pacing | ms | `wordMs` 230, `finalAfterMs` 350 | `offscreen/offscreen.js` | typed commands streamed as partials | +| undo stack / brain log | entries | 20 / 2000 (spliced by 500) | `offscreen/offscreen.js` | `executor`, `brain log` | +| e2e/test env vars | env | `GENCLASS_EXT` (unpacked dir, default `dist/genclass`), `HEADED` (headed Chromium), `SWIFTSHADER` (software WebGPU flags), `GENCLASS_COMPUTE` (default `auto`), `ENGINES` (speech bench, default `moonshine,whisper-base,whisper-turbo`), `CMD` (`\|`-separated, default `click the laptops link`), `LIVE`, `LIVE_AFTER` (debug spec); unit: `GENCLASS_VARIANTS` (default `q8`), `GENCLASS_THREADS` (default 1) | `test/e2e/*.mjs`, `test/unit/engine_parity.test.mjs` | test behaviour | +| `FOCUS_MODEL_MIN` / filter `minP` | number | 0.04 / 0.6 | `core/features.js` | focus and filter verdicts | +| `MAX_LABEL` / snapshots kept | int | 60 chars / last 5 | `content/content.js` | observation | +| scroll amounts | px | level 0 = 160; 1 = 0.85 x viewport; 2 = full height | `content/content.js` -> `scroll` | `scroll_*` | +| `RESTRICTED_RE`, `DENY_SITE_RE` | regex | chrome/extension/devtools/about/file/data/javascript schemes, Web Store; banks, payments, crypto, password managers, Google/Apple/Microsoft account pages | `background/sw.js` | never act inside | + +### Benchmarks + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `SEED` | int | 20261001 | `jev_local/bench/registry.py` | every sample/shuffle/bootstrap | +| `REGISTRY_VERSION` / `DEV_SET_VERSION` | string | `jevbench-v1.1` / `clean-2026-10-03` | `registry.py` | manifest identity | +| `TEMPLATE_VERSION` | string | `jevbench-v1-t1` | `templates.py` | request rendering | +| `DEUSSER_COMMIT` / `BTZSC_REVISION` | sha | `6bbdeb33…` / `fef2a2ac…` | `templates.py` | label-text sources | +| `DEV_PER_FAMILY` | int | 200 | `build.py` | held-out tasksource rows per family | +| `NLL_FLOOR` / `SUM_TOL` | float | 0.005 / 0.02 | `metrics.py` | scoring | +| bootstrap B | int | 2000 | `scripts/jevbench.py score -B` | CIs | +| `run-jev` limits | — | workers 6, attempts 6, `--max-cost` 8.0 | `scripts/jevbench.py` | Jev spend | +| `KBUCKETS` | tuple | `(2,2),(3,5),(6,10),(11,30),(31,100),(101,255)` | `baselines.py` | baseline refit buckets | +| `MAX_CHOICE_OPTIONS` | int | 255 | `benchmax/runner.py` | option cap refusal | +| `MODEL_ID_RE` | regex | `^(?:genclass\|meharsjev)-[a-z0-9][A-Za-z0-9._-]*$` | `benchmax/runner.py` | W10 | +| `PRECISIONS` / `OVERFLOWS` | tuple | `unrounded, 2dp` / `refuse, truncate` | `benchmax/runner.py` | W3 / W5 | +| `DEFAULT_WORK` | path | `$BENCHMAX_WORK` or `~/bench_work` (group B: `~/bench_work_b`) | `runner.py`, `adapters_b/common.py` | harness checkouts | +| `MODEL_ID` (group B) | string | `$BENCHMAX_MODEL` or `genclass-68m` | `adapters_b/common.py` | wire model id | +| `RUN_SCHEMA` / `TARGETS_PATH` | string / path | `benchmax-run/1` / `<repo>/bench/public/targets.json` | `benchmax/runner.py` | `run.json` schema; adapters read targets at run time | +| `RETRY_HTTP` | tuple | `408 409 425 429 500 502 503 504 520 522 524 529` | `benchmax/runner.py` (same list as `scripts/jevbench.py` `RETRY_STATUS`) | retried HTTP statuses | +| `CAPACITY_MARKERS` | tuple | `options per choice`, `a choice needs at least two options`, `a score takes 2 to 10 levels`, `the canvas holds`, `maximum context length`, … | `benchmax/runner.py` | W4 refusal texts the publishers' harnesses recognise as `unsupported` | +| other benchmax env vars | env | `BENCHMAX_REPOS` (default `<work>/repos`), `BENCHMAX_HF_HOME` (default `<work>/hf`), `BENCHMAX_API_KEY` (bearer for `HttpClient`), `JEV_LOCAL_API_KEY` / `JEV_LOCAL_FAST_CKPT` (group-B driver), `BENCHMAX_DMB_INSTRUCTIONS`, `BENCHMAX_HARMBENCH_COMMIT`, `HF_TOKEN` / `JSB_HF_TOKEN` (gated safety sets); `JEV_CACHE_DB` is **set** by the Deußer adapter for the upstream code | `benchmax/**` | — | +| jevbench Jev endpoint | consts | `URL https://openrouter.ai/api/alpha/decisions`, `MODEL typesafe/jev-1.13`, `KEY_PATH ~/.jev-local/secrets/openrouter.key`, `ACCOUNT_STATUS (401, 402, 403)` abort the run (retried on the next run) | `scripts/jevbench.py` | **$** | +| `TASKSOURCE_JEV` / `_REV` | string | `tasksource/tasksource-jev-typed-decisions` @ `8173a06c…` | `jev_local/bench/build.py` | held-out dev family source | +| `SEP` | string | `"\x1f"` (`<qid>\x1f<chunk>` sub-block ids) | `jev_local/bench/ours.py` | exact chunking | +| baseline adapters | — | only `SystemOneHTTP` works; `GLiNER2Adapter`, `NLIZeroShotAdapter`, `QwenRerankerAdapter` are stubs | `jev_local/bench/baselines.py` | open-baseline comparisons | + +## Invariants and gotchas + +- **Catalog strings are model input.** `catalog.js` `INTENTS`, `KEYS`, `FOLDERS`, `SCROLL_LEVELS`, `questions.js` `INSTR` and criteria texts are what the model was trained on; editing a word changes predictions. `BROWSER_EXTRA_INTENTS` (`go_forward`) is appended rather than trained; it is safe only because options are scored in isolation (it changes the softmax total, not other options' logits). +- **Python parity is the contract for `src/core`.** `spans.js`, `questions.js`, `state.js`, `policy.js`, `safety.js`, `stream.js` must reproduce `jev_local/harness/*` exactly, including reason strings (asserted for 700 synthetic policy cases). Python-semantics helpers: `pyutil.js` (`pyRound` half-even, `split`/`split1` = `str.split`, `strip`/`rstrip`, `isAlnum`, `clip01`) and `serialize.js` (`pyRepr` = `repr`, `pyJson` = `json.dumps(ensure_ascii=False, separators=(", ", ": "))`). Choice criteria must be `Map`s: plain objects reorder integer-like labels. +- **Staged evaluation is exact only because of the block mask.** If a future model shares attention across questions, stage 1 + stage 2 answers would differ from a single pass. +- **Special tokens are never matched in text** (`tokenizer.js`): a user saying "[Q]" cannot forge a marker; non-special added tokens (space runs of 2–24, `|||EMAIL_ADDRESS|||`) are split out leftmost-longest. +- **Positions restart per question branch**, so `max_len` (1536) bounds state + longest branch, not the whole sequence; total length is bounded by `maxTotal` (8192). The model card's "128-token local window" is `window` = 64 on each side. +- **One inference at a time per session** (`Engine.busy` chain). The comment in `features_rt.js` ("voice always wins") is not enforced: feature requests and voice requests share the engine FIFO. +- **v0.1 q8 on WebGPU:** the q8 export keeps an fp16 embedding table, which per `packages/runtime/src/model/README.md` needs `shader-f16` on onnxruntime's WebGPU provider; the extension card does not declare `needs` for q8, so on an adapter without `shader-f16` the extension tries `webgpu+q8`, fails at warm-up, and falls back to `wasm+q8`. +- **MV3 rules:** no remotely hosted code (build guard on jsDelivr URLs); COEP `require-corp` means every fetched model/asset needs CORP/CORS-compatible headers (the e2e server sets `cross-origin-resource-policy: cross-origin`). +- **Safety layers are deterministic first:** never type/paste into secure fields (`SECURE_FIELD_RE`, `autocomplete` password/cc/OTP), never act on restricted or denied sites, `close_tab`/`quit_app` always HIGH, submit buttons and Return in non-search forms HIGH. Do not move a check behind a model probability. +- **Words are consumed once.** Any change to `consumedFor`, `Stream.consume` or the fired-key set can make an action run twice or swallow the next command. +- **Fixture regeneration:** `pack_fixtures.json`/`torch_fixtures.json` come from an exporter run (`extension/tools/genclass_export.py` or the older `scripts/genclass_export.py`, whose fixture-writing code is identical; which one produced the committed files is not recorded) (torch, VM); the `*_py.json` fixtures from `extension/scripts/make_py_fixtures.py` (torch-free; it also reads `tests/fixtures/harness_cases.json` and `requests50.json`). Do not hand-edit them. +- **Cache names differ:** extension `genclass-models-v1`, runtime `genclass-runtime-v1`. They never share entries. +- **Mac safety:** `scripts/vm.sh` excludes `/extension/` from its rsync, so the standard runtime VM path cannot build or test the extension; there is no script for it (see Drift). +- **`vm.sh` mirrors with `rsync --delete`.** Anything you create only on the VM in `~/gcl/<SLOT>` (outside the excluded paths) is deleted on the next `sync`/`run`; that is why `demos/` keeps model directories outside the synced tree. +- **`azvm.sh` has no timeout.** Unlike `vm.sh`, it never reads `TIMEOUT`; the `TIMEOUT=… "$JEV/scripts/azvm.sh" …` prefixes in `training/{deliver_final,import_sim}.sh` and the `TIMEOUT=300 scripts/launch_run.sh …` prefixes in `training/{launch_s2,launch_final1}.sh` have no effect (`launch_run.sh` reads no `TIMEOUT` either; `training/node.sh`, default 900 s, and `vm.sh`, default 1800 s, do honour it). A hung ssh blocks until the connection drops (`ServerAliveInterval=30`, `ServerAliveCountMax=6`). +- **`azvm.sh --sync` copies only `jev_local scripts tests pyproject.toml`** to `~/jev/`. The benchmax adapters read `bench/public/targets.json` at run time (`runner.py` -> `TARGETS_PATH`, used by `deusser.py`, `jevbench_hf.py`, `bridge_b.py`), so the VM needs that file from some other copy (how it got there is unverified). +- **Extension state lives in the offscreen document.** The undo stack (`B.undo`, max 20), the decision log and the loaded engine are module state in `offscreen.js`; if Chrome closes the offscreen document they are gone and `ensure_brain` recreates a fresh one. Only settings, `parked`, `ramFreed` and `ramStatus` persist in `chrome.storage.local`. +- **The model is not a general classifier.** `MODEL_CARD.md` and `test/eval/features_eval_q8.json` (4/18 exact) show zero-shot ad/clickbait classification near chance; that is why `filter.model` is off by default and deterministic markers decide ads. Focus mode leans on keyword overlap and session use for the same reason. +- **Jev hygiene:** Jev outputs are evaluation-only (never train, select, calibrate, filter); Jev is never run on dev; raw Jev outputs are not republished; Deußer's Zenodo `responses.db` (per-item Jev outputs) is never downloaded or used (the Deußer adapter's own `cache/responses.<model_id>.db`, set through `JEV_CACHE_DB`, holds our answers only). +- **Money:** `jevbench.py run-jev` and `compare_jev.py` call OpenRouter (paid). The benchmax PLAN sets a $5 lifetime cap on Jev; M0 already used $0.217 lifetime per `results/jevbench-m0.md`. Azure scripts marked $ create or run billed VMs. +- **Test splits are read once per release.** benchmax: group-B `--allow-test`, `--rerun-reason`; adapters are debugged on validation/dev/train items only. +- **Pre-registration hashes:** editing any frozen file (`targets.json`, `jev_published.json`, `exclusions.json`, `registry.py`, `benchmax_build_targets.py`, and four of the five `docs/benchmax-research/*.md` notes: `PLAN.md`, `suite-reproduction-specs.md`, `feasibility-targets.md`, `train-data-and-supervised-ceilings.md`; `jev-published.md` is not in the frozen table) invalidates the benchmax freeze; jevbench registered code hashes for `registry.py`, `templates.py`, `build.py`, `metrics.py`, `scripts/jevbench.py` already differ (only `ours.py` still matches), so a new jevbench read needs a new pre-registration or a release note re-scoring earlier reads. +- **Model ids:** never `jev-*` or `typesafe/*` for our runs (`check_model_id`). + +## How to change it safely + +1. **Change harness logic in the extension (`policy`, `safety`, `spans`, `stream`, `questions`, `state`).** Change `jev_local/harness/*.py` the same way first (the Python is the reference), regenerate `extension/test/fixtures/*_py.json` with `extension/scripts/make_py_fixtures.py` (fix its `ROOT`/`OUT` paths first, see Drift), then run `npm test` in `extension/` on the VM. Browser-only rules (things guarded by `snap.browser`) need no Python change but must not alter Mac-harness verdicts (the parity fixtures have no `browser` flag). +2. **Add a browser-only intent.** Add it to `catalog.js` `BROWSER_EXTRA_INTENTS`, `types.js` `Kind`, `spans.js` `NO_ARG_INTENTS` (if argument-free), `controller.js` `LEFTOVER_WORDS`, `safety.js` `IN_APP_KINDS`/risk sets as appropriate, `policy.js` `ARG_QUESTIONS` (if it reads an argument), and an executor branch in `sw.js` -> `execute` or `content.js` -> `execute`. Add an eval row to `test/eval/commands_eval.mjs`. +3. **Ship a new model in the extension.** Export on the VM with `tools/genclass_export.py --ckpt … --requests test/fixtures/requests50.json --out …`; copy `tokenizer/calibration/meta.json` into `src/model/` and `release-assets/`; update `src/model/model.json` bytes/sha256 (and `needs` if any fp16 tensor remains); copy `pack_fixtures.json`/`torch_fixtures.json` into `test/fixtures/`; run `GENCLASS_VARIANTS=q8,fp16 npm test`; then `node scripts/build.mjs --release` (it re-verifies sha256). +4. **Fix an engine/packer/tokenizer bug.** The runtime copy (`packages/runtime/src/model/`) is the maintained one; fix it there with its tests ([runtime/model-host.md](runtime/model-host.md)). Port to the extension only if the extension is still being released, and re-run `pack_parity` + `engine_parity`. +5. **Build and test the extension.** On the VM (never the Mac): get `extension/` onto the VM yourself (not covered by `scripts/vm.sh`), `npm ci`, `npm test` (unit; ONNX-dependent tests skip without `release-assets/genclass-*.onnx`), put `genclass-q8.onnx` (and `-fp16.onnx` for WebGPU) into `release-assets/` (from the v0.1.0 GitHub release, or `packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` and copy the `.onnx` files over), `npm run build`, `npm run test:e2e` (Playwright Chromium with the unpacked extension; `SWIFTSHADER=1` for software WebGPU; `speech.spec.mjs` needs network to Hugging Face). +6. **Add a benchmax spec.** Use the exact `spec_id` string from `targets.json`; group A: a class with `add_arguments`/`verify`/`run` (subclass of `runner.py` -> `Adapter`, with `default_overflow`/`allow_truncate`) registered in `specs_a.py`; group B: a module `adapters_b/<suite>.py` with `SPEC_ID`, `TARGETS` and a class `Adapter(AdapterB)` implementing `prepare(split)`, `items(split, limit, tasks)`, `score(...)` and optionally `fit(...)`, registered in `specs_b.py` -> `SPECS_B` as `"<module>:Adapter"` (bridged automatically because `bridge_b.is_group_b_class` sees `prepare/items/score` and no `verify/run/add_arguments`). Pin every upstream commit/revision and sha256. Add pure-Python tests (`tests/test_bm_adapters_*.py`), then `scripts/benchmax.py verify --spec <id>` and a validation-split `run` on the VM. +7. **Update targets or the published-Jev list.** Edit `bench/public/jev_published.json`, run `scripts/benchmax_build_targets.py --write-registry` then `--check` (fix the feasibility-note path first), run `tests/test_bench_registry.py`; this changes frozen hashes, so write a new freeze before any test read. +8. **Score a new checkpoint on jevbench.** `scripts/jevbench.py run-ours --ckpt … --release <r>` then `score` and `report` on the VM; do not run `run-jev` without the user's OK (cost) and a funded key. +9. **Re-measure the extension's model-backed behaviour.** On the VM with `release-assets/genclass-q8.onnx` present: `node test/eval/commands_eval.mjs`, `node test/eval/features_eval.mjs`, `node test/eval/focus_heldout.mjs` (each rewrites its JSON: `commands_eval.json`, `features_eval_<variant>.json`, `focus_heldout.json`). If a threshold such as `FOCUS_MODEL_MIN` or filter `minP` changes, update the eval JSON and the README numbers together. +10. **Touch an ops script.** Keep `vm.sh`'s rsync exclusions (`/extension/`, `/models/`, `/runs/`, `/data/`, `/sim/out/`, `.cache-model/`) and `--delete` semantics in mind: every workstream depends on them. Do not change `launch_run.sh`'s argument order (`RUN MASTER NPROC THREADS "nodes" -- args`): `training/launch_s2.sh` and `training/launch_final1.sh` call it positionally. Anything that calls `az vm create/start` or OpenRouter needs the user's go-ahead. + +## Tests + +| test file | what it asserts | needs | +|---|---|---| +| `extension/test/unit/pack_parity.test.mjs` | JS tokenizer + `Packer` reproduce Python `Packer` ids, positions, `q_group`, `i_group`, `n_state`, question order, marker positions on 50 requests (> 50k tokens); "[Q]" in text is not the marker; space-run and `EMAIL_ADDRESS` (pipe-delimited) added tokens; non-ASCII encodes | `release-assets/tokenizer.json` (committed) | +| `extension/test/unit/engine_parity.test.mjs` | `headerKey` = Python `sha1[:12]`; JS calibration of PyTorch logits = PyTorch probs (< 1e-9); per variant (`GENCLASS_VARIANTS`, default `q8`): ONNX via onnxruntime-web WASM vs PyTorch (fp32 max logit < 1e-3; fp16/q8 decision agreement ≥ 0.99) | ONNX tests skip without `release-assets/genclass-<v>.onnx` | +| `extension/test/unit/harness_parity.test.mjs` | spans (> 100 fixtures), questions + state + `rankApps`, policy + gate on exactly 700 synthetic responses (verdict, reason, retry, action, pick, gate verdict/reason/risk), stream records | `*_py.json` fixtures | +| `extension/test/unit/controller_model.test.mjs` | real q8 model, streamed text: scroll fires once before the last word then search runs once with a verbatim span; "click buy now" waits for a later "confirm"; side talk ignored; "no cancel that" drops pending | `genclass-q8.onnx` (skips otherwise) | +| `extension/test/unit/rescue.test.mjs` | `rescueTarget`: verbatim label rescues `none`; confident answer kept; ordinal among "(k of n)" duplicates and longest label wins; ambiguous duplicates not guessed; only for `click` | — | +| `extension/test/e2e/voice.spec.mjs` | unpacked extension in Chromium on the local shop page: model loads from `modelBaseUrl` and is cached; dry run does nothing; live click/type/scroll and mid-sentence chain `[click, scroll_down]`; risky click waits for confirm, cancel drops; never types into password field; kill switch; never acts on `chrome://` | built `dist/genclass`, `release-assets/*.onnx` | +| `extension/test/e2e/features.spec.mjs` | content filter hides 2 marked ads, badge "2", per-site off restores; focus mode closes the off-task recipes tab after 0.25 min and restores it; RAM manager preview never picks pinned/active tabs | same | +| `extension/test/e2e/speech.spec.mjs` | speech benchmark on `scroll.wav` (Moonshine final contains "scroll down"); `click.wav` through Moonshine clicks the laptops link | network (Hugging Face) | +| `extension/test/e2e/{webgpu,wasm_bench}.spec.mjs` | `bench_model` latency on 8 requests per provider + one click executes (titles over-claim, see Drift) | same | +| `extension/test/e2e/debug.spec.mjs` | dev helper: run `CMD` commands and print the brain log | — | +| `extension/test/eval/commands_eval.mjs` (+ `.json`) | 18 everyday commands with the shipped q8: **16/18** (misses: "open github" -> wait; "click the first result") | model | +| `extension/test/eval/features_eval.mjs` (+ `features_eval_q8.json`) | zero-shot filter: 4/18 exact, 11/18 hide-vs-keep; focus: 8/14 at 0.5, AUC 0.938 | model | +| `extension/test/eval/focus_heldout.mjs` (+ `.json`) | `focusVerdict` on 36 held-out tabs / 3 tasks: on-task kept 11/17, off-task flagged 18/19, model-only at 0.04: 22/36 | model | +| `extension/test/eval/phrasing_probe.mjs` | dev tool: alternative feature-question phrasings | model | +| `packages/runtime/test/model/*.test.ts` | the runtime port against the same pack/torch fixtures (see [runtime/build-test-release.md](runtime/build-test-release.md)) | `GENCLASS_MODEL_DIR` for model-file tests | +| `tests/test_bench_registry.py` (15) | registry v1.1 invariants, clean dev set, stage-1 exclusion on Z and S, generated `public_jev` family vs `targets.json`, manifest | pure Python | +| `tests/test_bench_templates.py` (9), `test_bench_build_dev_v11.py` (8) | mappers produce valid string-only requests; variants; ATIS/SciFact dev mappers | pure Python | +| `tests/test_bench_metrics.py` (6), `test_bench_cli.py` (2), `test_bench_baselines.py` (3) | scorer primitives, failures, indices, bootstrap; jevbench cache semantics and file order; baseline option mapping | numpy | +| `tests/test_bench_ours.py` (4) | `OursRunner` equals `FastEngine.evaluate`; chunking exact | weights, VM | +| `tests/test_bm_engine.py` (34), `test_bm_engine_vm.py` (10) | W1–W11 on stub/heuristic engines; on the real v2 checkpoint | VM for `_vm` | +| `tests/test_bm_adapters_a_runner.py` (22), `_a_suites.py` (14), `_a_typed_decisions.py` (9), `_b.py` (19), `_b_goya.py` (3), `test_bm_integrate.py` (9) | runner plumbing, group-A adapters, typed-decisions scorer pinning, group-B adapters, bridge + CLI for every spec, `run.json` fields | pure Python | +| `tests/test_data_bm_eval_suites.py` (13), `test_data_bm_z.py` (6) | benchmax eval-suite fetch and Z mixture accounting | import `jev_local.data`, which is not in this repo | +| `tests/test_overnight.py` (7) | `scripts/overnight.py` gate logic against the 2026-09-27 crash readings | pure Python (loads the script by path) | +| `tests/test_mlx_scorer.py` (24) | the MLX decoder engine; borrows prompt helpers from `scripts/bench_decoder.py` | mlx tiers need Apple Silicon; real-model tier marked `model`/`slow` | + +Run commands: extension unit tests `npm test` = `node --test --test-concurrency=1 test/unit/*.test.mjs`; e2e `npm run test:e2e` = `playwright test --config test/e2e/playwright.config.mjs` (needs `npm run build` first); Python tests with `pytest tests/test_bench_*.py tests/test_bm_*.py` (on the VM per the contract; the counts above are `def test_` occurrences). + +## Drift and open issues + +1. `docs/runtime/CONTRACT.md` §10 cites the extension engine at `extension/genclass/src/core/{engine,packer,tokenizer,serialize,pyutil,runtime}.js` "in the parent jev repo" (read-only reference `/Users/meharkhanna/jev/extension/genclass/src/`) and the card at `extension/genclass/src/model/model.json`. In this repo the path is `extension/src/core/` and there is no `runtime.js`. +2. `extension/package.json` says `"license": "MIT"`; `extension/README.md`, `LICENSE`, `NOTICE` and the store listing say Apache-2.0. +3. `extension/scripts/make_py_fixtures.py` assumes the old `extension/genclass/` layout: `ROOT = parents[3]` resolves to the directory above the repo and `OUT` is `extension/genclass/test/fixtures`. `extension/tools/genclass_export.py` usage text and `RELEASE.md` ("push the contents of `extension/genclass/`") have the same stale path. +4. `scripts/vm.sh` excludes `/extension/` from its rsync, while `extension/README.md` documents `npm ci` / `npm test` / `npm run test:e2e` and the runtime contract forbids running them on the Mac. There is no supported way to build or test the extension. +5. `extension/README.md` lists q8 for "WASM, and WebGPU without f16". The runtime's WebGPU notes (`packages/runtime/src/model/README.md`) found that the v0.1 q8 needs `shader-f16` on WebGPU; `src/model/model.json` declares no `needs` for q8. +6. `extension/README.md` says a closed-set command acts "as soon as the model says the command is complete and two partials agree". The code (`policy.js` -> `evaluatePolicy`) acts on a partial when `complete` ≥ 0.65 and (`complete` ≥ 0.85 **or** the same pick twice), or once the phrase is settled. For local ASR the 600 ms payload gate is raised to `round(2 x cadence + 150)` ms (`controller.js` -> `silenceGatesFor`), where cadence = max(`stepMs`, last decode ms), so at least 650 ms for Moonshine (`stepMs` 250). +7. `features_rt.js` -> `Features.run` says "voice always wins"; nothing gives voice priority over feature requests on the shared engine queue. +8. `test/e2e/webgpu.spec.mjs` is titled "agrees with the WASM run and parity fixtures" and `wasm_bench.spec.mjs` "with the WASM run and parity fixtures". Neither compares answers: they record `bench_model` latency and check that one click executes. +9. `extension/README.md` says `release-assets/` model files are "not committed"; the JSON files (`tokenizer`, `calibration`, `meta`, `parity`) are committed and only `*.onnx` is ignored. +10. `scripts/genclass_export.py` is an older export (dynamic int8 `genclass-int8.onnx`). The shipped model and `extension/tools/genclass_export.py` use q8 (MatMulNBits, block 32, fp16 embeddings). The `extension/tools/genclass_export.py` -> `make_q8` docstring explains why: dynamic int8 lost 7% argmax agreement (activation outliers); q8 keeps 99.8%. +11. `bench/PREREG-benchmax.md` cites `bench/public/PREREG.sha256`, which is missing, and `docs/research/benchmax/*.md`, which is now `docs/benchmax-research/*.md`. The frozen sha256 of every moved file still matches (checked with `shasum`): `targets.json`, `jev_published.json`, `exclusions.json`, `registry.py`, PLAN, specs, feasibility, train-data, `benchmax_build_targets.py`. +12. `scripts/benchmax_build_targets.py` reads `FEAS = docs/research/benchmax/feasibility-targets.md`, which does not exist here; the script opens it unconditionally, so regeneration (and `--check`) would fail with a missing-file error (from the code; unverified). Its docstring says "131 counted benchmarks"; `targets.json` `counts.counted` is 154. +13. `bench/PREREG-jevbench.md`, `results/jevbench-m0.md`, the `metrics.py` docstring and `scripts/jevbench.py` -> `_prereg_check` expect `bench/jevbench/PREREG.md`. The file is now `bench/PREREG-jevbench.md` (hash unchanged), so `_prereg_check` would report "No PREREG.md found." The `bench/jevbench/` request files, manifest and `runs/` are not in the repo; they live on the VM. +14. jevbench §11 registered hashes: `registry.py`, `templates.py`, `build.py`, `metrics.py` and `scripts/jevbench.py` now differ from the registered values; only `ours.py` matches. The M0 release notes cover only `metrics.py` and `scripts/jevbench.py`. The `registry.py` change is the v1.1 clean-dev-set + `public_jev` change (its `REGISTRY_VERSION` comment says so); that the `templates.py`/`build.py` changes are only the new dev mappers is likely but unverified hunk by hunk. +15. Model id naming: `PREREG-benchmax.md` and `docs/benchmax-research` say `meharsjev-<size>`. `runner.py` -> `MODEL_ID_RE` accepts `genclass-` or `meharsjev-`, and `scripts/benchmax.py` and `adapters_b/common.py` default to `genclass-68m`. +16. `scripts/launch_z68m.sh` needs `bench/public/mix_z_run.json`, which is not in the repo. +17. `jev_local/data/` is absent, but `tests/test_data_bm_eval_suites.py` and `tests/test_data_bm_z.py` import it and `registry.py` mentions `jev_local.data.v2.decontam`. Those tests cannot import here. +18. `BENCHMARKS.md` points to "`runs/compare/report.md` in the development repo", which is not here. It also promises that in-browser WebGPU latency "will be published with the first extension release". The extension README says WebGPU is not measured (no GPU in CI). Still open. +19. jevbench M0 is incomplete. OpenRouter returned 402 after 4,420 Jev responses, so Jev is valid only on AG News and Yahoo, and no claim was evaluated. Finishing it needs about $4.50 of credit, which is a user action (`results/jevbench-m0.md`). +20. The benchmax freeze is DRAFT and its hash is unpublished (user decision). No test-split scoreboard exists in the repo. 132 of the 154 headline rows have a registered spec; 22 rows (16 `study:*` spec ids) have no adapter. Z-68m trained and converged at v2's dev level. Its calibration does not transfer, so it ships with identity calibration (`results/z68m-dev-notes.md`). +21. `training/{deliver_final,import_sim,import_final,node}.sh` set `JEV="$(cd "$HERE/../.." && pwd)"` with `HERE` = `training/`, i.e. the directory **above** this repo (the parent-repo layout; `node.sh` comments it as `/Users/meharkhanna/jev`). The first three then call `$JEV/scripts/azvm.sh`; `node.sh` rsyncs `$JEV/jev_local`, `$JEV/scripts` and `$JEV/pyproject.toml` to the node. In this standalone checkout those paths are outside the repo; whether a jev checkout exists there is machine-dependent (see [training.md](training.md)). The same applies to `scripts/launch_run.sh`: `training/launch_s2.sh` and `training/launch_final1.sh` `cd "$(dirname "$0")/../.."` (commented `/Users/meharkhanna/jev`) and then call `scripts/launch_run.sh` relative to that directory. +22. `training/{deliver_final,import_sim}.sh` prefix `azvm.sh` calls with `TIMEOUT=<s>`, but `scripts/azvm.sh` never reads `TIMEOUT` (it has no timeout wrapper), so those calls are unbounded. The same holds for `TIMEOUT=300 scripts/launch_run.sh …` in `training/{launch_s2,launch_final1}.sh`. `training/import_final.sh` uses coreutils `timeout 120` instead, which does work. +23. Docstrings point at research paths that are not in this repo: `jev_local/bench/__init__.py` and `scripts/jevbench.py` cite `docs/research/v2/PLAN.md`; `jev_local/bench/benchmax/__init__.py`, `scripts/benchmax_build_targets.py` (as a real input path, item 12), `bench/PREREG-*.md`, `bench/public/targets.json` and the `docs/benchmax-research/*.md` notes cite `docs/research/benchmax/*` or `docs/research/v2/*` (the benchmax notes now live in `docs/benchmax-research/`; the v2 notes are absent). There is no `docs/research/` directory. +24. `docs/GENCLASS.md` (outside this scope) says both that the extension zip and weights "are in the v0.1.0 release" and, further down, that they "are coming in the first release". `extension/README.md` and `RELEASE.md` treat v0.1.0 as released; whether the GitHub release exists cannot be checked from the repo (unverified). +25. `jev_local/bench/benchmax/adapters_b/__init__.py` documents a **module-level** function contract (`prepare(work, split)`, `items(work, split, limit, tasks)`, `SPLITS` at module level). The 15 adapters actually expose module-level `SPEC_ID`/`TARGETS` plus a class `Adapter(AdapterB)` whose methods take no `work` argument (`args.work` is passed to the constructor), as `specs_b.py`'s docstring and `common.py` -> `AdapterB` describe. Follow the class contract. +26. `scripts/benchmax/stage0_validation.sh` says it "Skips a run whose run.json is already complete", but it tests `grep -q '"finished"'`. `runner.py` -> `RunContext.to_dict` always writes a `finished` key (`null` until `finish()`), and `benchmax.py run` writes `run.json` before the adapter runs, so any existing `run.json`, including a failed or interrupted one, is skipped on a rerun. +27. `scripts/phase3_eval.sh` writes a `phase3_run_all.sh` that skips specs whose `run.json` contains `"complete": true`. `RunContext` writes `"status": "complete"` instead, so nothing is ever skipped: a second pass re-runs every spec into a complete `--out`, `benchmax.py` exits with "a rerun needs --rerun-reason", and the loop logs `FAILED <spec>`. +28. `extension/test/fixtures/audio/type.wav` is committed but unused. + +## Related docs + +- [README.md](README.md), [overview.md](overview.md), [repo-map.md](repo-map.md), [glossary.md](glossary.md), [playbooks.md](playbooks.md), root [AGENTS.md](../../AGENTS.md) +- [runtime/model-host.md](runtime/model-host.md): the maintained TS port of the extension engine +- [model-io-contract.md](model-io-contract.md): situation text -> packed request -> heads -> calibrated answers +- [genclass-model-lineage.md](genclass-model-lineage.md): `jev_local` (Python model, server, macOS harness, training) +- [training.md](training.md): curriculum, R17/R32, export (`training/export_runtime.py`) +- [runtime/build-test-release.md](runtime/build-test-release.md): `scripts/vm.sh` usage, runtime tests and release +- [status-and-known-issues.md](status-and-known-issues.md) +- Sources: [extension/README.md](../../extension/README.md), [extension/MODEL_CARD.md](../../extension/MODEL_CARD.md), [extension/RELEASE.md](../../extension/RELEASE.md), [BENCHMARKS.md](../../BENCHMARKS.md), [bench/PREREG-jevbench.md](../../bench/PREREG-jevbench.md), [bench/PREREG-benchmax.md](../../bench/PREREG-benchmax.md), [results/jevbench-m0.md](../../results/jevbench-m0.md), [results/genclass-vs-jev-computer-use.md](../../results/genclass-vs-jev-computer-use.md), [docs/benchmax-research/PLAN.md](../benchmax-research/PLAN.md), [packages/runtime/src/model/README.md](../../packages/runtime/src/model/README.md), [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) diff --git a/docs/agents/genclass-model-lineage.md b/docs/agents/genclass-model-lineage.md new file mode 100644 index 00000000..e8a7a492 --- /dev/null +++ b/docs/agents/genclass-model-lineage.md @@ -0,0 +1,534 @@ +# GenClass model lineage: jev_local (Python model, server, harness, training) and legacy docs + +> **Scope:** `jev_local/**` except `jev_local/bench/**` (`api.py`, `schema.py`, `serialize.py`, `confidence.py`, `validate.py`, `cli.py`, `demo.py`, `engine/**`, `harness/**`, `server/**`, `train/**`), `pyproject.toml`, `tests/**` (Python), and the legacy design docs `docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`. +> **Read this when:** you touch anything that changes the text the model reads or the numbers it returns (serialization, packing, markers, heads, calibration, answer math); you need to know what `packages/runtime/src/model` was ported from and how parity is checked; you run or change the Python trainer that `training/` drives; you need the Jev-compatible HTTP server or the macOS voice harness; you want to know which Python is legacy and safe to ignore for the self-healing runtime. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- `jev_local` (pip package `jev-local` 0.1.0) is the **predecessor project** of `@genclass/runtime`: a local, open re-implementation of TypeSafe's "Jev" *System One* typed-decision API (not affiliated). It contains the model, a Jev-wire-compatible HTTP server, a macOS voice computer-use harness, and the multi-node CPU trainer. +- A **typed decision** is `{state, model, questions}` in, `{model, answers, usage}` out. Three question kinds: `choice` (2–255 labels, softmax), `noul` (absolute P(true), sigmoid), `score` (2–10 ordered levels, softmax, value = Σ i·pᵢ). Wire models: `jev_local/schema.py`. +- The model (`FastEngine`, "jev-local-fast") is an **ettin/ModernBERT encoder** with **typed heads over marker tokens** `[Q] [O] [L] [T] [F]`. One packed sequence holds the state once plus every question; a block attention mask makes each option see only the state, its own header and itself, so answers are **exactly invariant to option order and to other questions**. +- Raw logits are turned into probabilities by **post-hoc calibration** (`calibration.json`: per kind, per header hash, per (kind, K-bucket), τ(K), noul Platt), then into Jev answers by `confidence.build_answer`. +- **The runtime model is a direct descendant.** `packages/runtime/src/model` is a TypeScript port of `serialize.py`, the HF tokenizer call, `tokenize_pack.Packer` (single-pass subset), `calibrate.py` lookup and `confidence.py`. The network itself is exported to ONNX by `scripts/genclass_export.py` (graph) / `training/export_runtime.py` (q8/fp16 + card). Parity is pinned by Python-generated fixtures in `packages/runtime/test/fixtures/model/`. +- **R32** (runtime candidate) is initialised from the v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers) with a pruned 16,364-token vocabulary; **R17** starts from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers per `training/README.md`; fresh `DecisionHeads(enc.hidden_size)`), also pruned to 16,364 tokens. Both are trained with `jev_local/train/train.py` (stream mode, DDP) launched from `training/`. Caveat: `training/node.sh sync` copies `jev_local/` from the **parent jev repo** (`$HERE/../..`), not from this repo's root (see Drift). +- Python entry points: console script `jev-local` (`cli.py`), and `python -m` on `jev_local.server.app`, `jev_local.train.train`, `jev_local.train.eval`, `jev_local.train.stream`, `jev_local.engine.encoder.calibrate`, `jev_local.harness.observe`, `jev_local.demo` (table in Files). +- **Changing `serialize.py`, `tokenize_pack.py`, marker ids, `heads.py`, `calibrate.py` lookup or `confidence.py` breaks train/runtime parity** unless the TS port, fixtures and model are changed together. +- Legacy for the runtime library (safe to ignore unless asked): `api.py` routing and benchmax `ServeConfig`, `validate.py`, `server/app.py`, `engine/registry.py`, `engine/heuristic.py`, `engine/decoder/mlx_scorer.py`, all of `harness/**`, `demo.py`, `cli.py`, and the legacy docs listed in Scope. +- `jev_local/data/**` (the v1/v2 data generators) is **not in this repo**: the root `.gitignore` rule `data/` also matches `jev_local/data/`. The 20 `tests/test_data_*.py` files import it and fail at collection. +- Python tests live in `tests/` (71 files); heavy ones are marked `model` / `slow` / `macos`. Per `docs/CONTRACT-v2.md`, torch/model work runs on the Azure VMs, never on the 8 GB Mac. + +## Files + +### Package core + +| path | role | key exports / entry points | +|---|---|---| +| `pyproject.toml` | package `jev-local` 0.1.0, Python `>=3.12,<3.14`, setuptools; console script `jev-local = jev_local.cli:main`; extras `general` (mlx, mlx-lm), `dev` (pytest, jsonschema, typesafe-sdk); pytest `testpaths=["tests"]`, markers `macos`, `model`, `slow` | — | +| `jev_local/__init__.py` | version string | `__version__ = "0.1.0"` | +| `jev_local/schema.py` | Jev wire models (pydantic v2, `extra="ignore"`) | `Entry`, `NoulCriteria`, `NoulQuestion`, `ChoiceQuestion`, `ScoreQuestion`, `Question`, `SystemOneRequest`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `Answer`, `Usage`, `SystemOneResponse`, `question_from_json`, `question_to_json` | +| `jev_local/serialize.py` | canonical text of state and questions, shared by every engine and the trainer | `entry_text`, `Segment` (+ `.digest`: blake2b-12 of key/text), `state_segments`, `state_text`, `QBlock`, `question_block`, `MAX_ARRAY_SEGMENTS`, `DEFAULT_NOUL_INSTR` / `DEFAULT_CHOICE_INSTR` / `DEFAULT_SCORE_INSTR` (values in Constants) | +| `jev_local/confidence.py` | raw distribution -> Jev answer (the only place answers are built) | `choice_confidence`, `score_value`, `score_center`, `score_confidence`, `mad_uniform`, `normalize`, `largest_remainder`, `round_probs`, `build_answer`, `Precision` | +| `jev_local/validate.py` | count limits the schema cannot express | `validate_limits`, `OptionCapExceeded`, `option_cap_message`, `RefusalStyle`, `OPTION_CAP_MARKER`, `MIN/MAX_CHOICE_OPTIONS`, `MIN/MAX_SCORE_LEVELS` | +| `jev_local/api.py` | validate -> normalise -> route -> evaluate -> answers; benchmax run config; determinism report | `ServeConfig` (+ `.preset`, `.rounding`, `.to_dict`), `PRESETS`, `parse_precision`, `resolve_model_id`, `public_model_id`, `route`, `route_key`, `Candidate`, `serve_request`, `Served`, `system_one`, `system_one_json`, `serve_json`, `normalize_request`, `output_tokens`, `too_long_message`, `is_too_long`, `refusal_kind`, `determinism_report`, `hardware_info`, `sha256_file`, `AUTO_IDS`, `AUTO_ORDER`, `EXPLICIT_PREFIXES`, `MAX_TOKENS_EXCEEDED` | +| `jev_local/cli.py` | `jev-local demo ...` and `jev-local serve [--port]` only | `main` | +| `jev_local/demo.py` | voice demo entry (`scripts/demo.py` wraps it); RAM guards `NEED_ENGINE_GB` 1.5, `NEED_WHISPER_GB` 0.6, `NEED_MARGIN_GB` 0.4; checkpoints `CKPTS = {"v1": models/jev-local-fast, "v2": runs/v2/jev-local-fast-v2}` | `main`, `parse_args`, `amain`, `SessionTap`, `required_free_gb` | +| `jev_local/{engine/encoder,engine/decoder,harness,server,train}/__init__.py` | empty package markers; `jev_local/engine/` itself has **no** `__init__.py` (implicit namespace package) | — | + +### Engines + +| path | role | key exports | +|---|---|---| +| `jev_local/engine/base.py` | engine protocol (no `__init__.py` in `engine/`: implicit namespace package) | `Engine`, `RawDist`, `EngineResult`, `EngineError`, `Kind` | +| `jev_local/engine/registry.py` | lazy construction of `fast` / `general` / `heuristic` | `Registry(fast_ckpt=None, general_repo=None, load_general="lazy", *, load_fast=True, fast_options=None)` with `.engines()`, `.ready`, `.warm()`, `.status()`, `.describe()`, `.unload()`, `.notes`; `default_fast_ckpt`, `general_model_cached`, `is_loaded`, `checkpoint_sha256` (sha256 of `heads.safetensors`, `backbone/model.safetensors`, `calibration.json`, `meta.json`), `DEFAULT_FAST_CKPT`, `FAST_CKPT_ENV`, `DEFAULT_GENERAL_REPO`, `LoadMode` (`lazy`/`eager`/`off`) | +| `jev_local/engine/heuristic.py` | model-free fuzzy-matching fallback | `HeuristicEngine` (`name = NAME = "jev-local-heuristic-0.1.0"`), `reference_text` | +| `jev_local/engine/encoder/tokenize_pack.py` | sequence layout, dense masks, tree layout | `MARKERS`, `BUCKETS`, `MAX_LEN`, `STATE`, `PAD`, `Packer` (`encode`, `segment_text`, `count`, `pack`, `pack_split`, `collate`, `_state_ids`, `_block_parts`, `_layout`), `Packed`, `QIndex`, `Batch`, `build_masks`, `TreeBatch`, `collate_tree`, `add_marker_tokens`, `bucket_for`, `ITEM_CHUNK` | +| `jev_local/engine/encoder/model.py` | ModernBERT forward with arbitrary block mask (reuses the HF submodules `embeddings`, `attn.Wqkv`, `attn.Wo`, `mlp`, norms, `rotary_emb`; re-implements the per-layer attention: RoPE rotated in fp32, SDPA with a per-layer-type boolean mask) | `MaskedEncoder` (`from_pretrained`, `forward`, `forward_raw`, `forward_tree`, `.grad_ckpt`), `BASE_MODEL`, `init_marker_embeddings` | +| `jev_local/engine/encoder/heads.py` | decision heads over marker states; parameter names `norm`, `choice_mlp`, `score_mlp`, `noul_mlp` (the `heads.safetensors` keys) | `DecisionHeads(d=384)`, `MLP`, `build_plan`, `HeadPlan`, `GroupIdx`, `NoulIdx`, `HeadOut`, `QRef`, `probabilities`, `temperature_vector` | +| `jev_local/engine/encoder/calibrate.py` | calibration fit + lookup; CLI | `fit_calibration`, `fit_tau`, `fit_tau_k`, `fit_platt`, `nll`, `tau_for`, `noul_affine`, `calibrate_logits`, `calibrated_probs`, `apply_calibration`, `apply_tau`, `load_calibration`, `describe_calibration`, `header_key`, `k_bucket`, `bucket_key`, `CalibRecord`, `DEFAULT_CALIBRATION`, `main` | +| `jev_local/engine/encoder/engine.py` | `FastEngine`, checkpoint I/O, fast exact encoder | `FastEngine` (`supports`, `count_tokens`, `positions_needed`, `fit_state`, `evaluate`, `evaluate_logits`, `warmup`, `unload`, `calibration_info`, `last_passes`), `BandedEncoder`, `ENCODERS`, `encoder_class`, `init_model`, `load_tokenizer`, `write_checkpoint`, `load_checkpoint`, `plan_passes`, `Fragment`, `pick_device`, `ENGINE_NAME`, `MAX_CHOICE_OPTIONS` (255), `MAX_POSITIONS`, `ENGINE_BUCKETS`, `MARKER_SEEDS` | +| `jev_local/engine/decoder/mlx_scorer.py` | zero-shot Qwen3-1.7B 4-bit prefill-only scorer (macOS/MLX) | `GeneralEngine` (`name = "jev-local-general-0.1.0"`, `available`, `load`, `unload`), `prefix_text`, `choice_suffix`, `score_suffix`, `noul_suffix`, `SYSTEM_PROMPT`, `combine_pages`, `paginate`, `pick_finalists`, `presentation_order`, `neutralizer`, `fork_cache`, `common_prefix_len` | + +### Server, training + +| path | role | key exports | +|---|---|---| +| `jev_local/server/app.py` | FastAPI app; `python -m jev_local.server.app` CLI | `create_app`, `serve`, `main`, `build_parser`, `config_from_args`, `registry_from_args`, `Counters` (`FIELDS`), `new_request_id`, `rss_mb`, `Overloaded`, `_Gate`, `_Guard`, header names `REQUEST_ID_HEADER`, `ENGINE_HEADER`, `LATENCY_HEADER`, `TRUNCATED_HEADER`, `ENGINE_DESCRIPTIONS`, `ALIASES`, `PUBLIC_DESCRIPTION` | +| `jev_local/train/train.py` | trainer (index mode v1, stream mode v2, DDP) | `train`, `main`, `build_parser`, `encode_example`, `example_tokens`, `parse_target`, `QTarget`, `Row`, `DataStats`, `make_batches`, `prepare_batch`, `build_targets`, `train_buckets`, `JsonlIndex`, `IndexSource`, `StreamSource`, `Prefetch`, `param_groups`, `amp_dtype`, `loss_config`, `parse_curriculum`, `save_state`, `load_state`, `load_weights`, `lr_factor`, `LONG_BUCKETS`, `MAX_TRAIN_LEN` | +| `jev_local/train/stream.py` | torch-free (numpy) indexed mixture reader for `*.jsonl(.zst)` shards; CLI prints the mixture plan | `Corpus` (`.open`, `.summary`), `Mixture` (`.iterate`, `.plan_summary`), `MixConfig` (`.from_json`, `.to_json`), `PassPlan`, `FileIndex`, `build_file_index`, `discover`, `main`, `DEFAULT_BUCKET_WEIGHTS`, `OTHER_BUCKET_WEIGHT`, `SPLITS`, `LICENSES`, `INDEX_VERSION` | +| `jev_local/train/losses.py` | proper-scoring losses + consistency pairs | `LossConfig` (`.v2()`, `.sigma(progress)`), `Targets`, `compute_loss`, `consistency_terms`, term functions `softmax_ce`, `softmax_brier`, `rps`, `spherical`, `coral`, `noul_bce`, `noul_brier`, `entropy`, `smooth`, `NEG_FILL` (-1e4) | +| `jev_local/train/ddp.py` | torchrun/gloo (NCCL on CUDA) helpers, one all-reduce per step | `Dist`, `init_from_env`, `destroy`, `barrier`, `any_flag`, `LaggedFlag`, `GradReducer`, `broadcast_object`, `broadcast_tensors`, `broadcast_optimizer`, `module_tensors` | +| `jev_local/train/eval.py` | per-qid / per-K-bucket metrics; logit collection; CLI | `collect`, `collect_from_model`, `Collected`, `RecMeta`, `metrics_from`, `ece`, `auroc`, `StreamExamples`, `example_source`, `main`, `N_BINS` | +| `jev_local/train/fixture.py` | tiny procedural harness examples for tests (goes through `build_state` / `build_questions` / span extractors) | `make_examples`, `write_splits` | + +### Voice computer-use harness (`jev_local/harness/`, summary level; legacy for the runtime) + +| module | role | +|---|---| +| `types.py` | `TranscriptEvent`, `Element`, `Snapshot`, `Tail`, `ActionKind`, `RiskLevel`, `Action`, `Decision`, `ExecResult`, `ActionRecord`, `Thresholds`, `HarnessConfig` | +| `catalog.py` | closed vocabularies shown to the model: `INTENTS` (18), `KEYS`, `FOLDERS`, `SCROLL_LEVELS`, `RISK_RE`, deny lists, `SECURE_FIELD_RE`, `CHAIN_WORDS` | +| `questions.py`, `state.py`, `spans.py` | the fixed question schema (`build_questions`, `rank_apps`, `element_line`), `build_state`, verbatim span candidates (`extract_text_candidates`, `extract_url_candidates`, `consumed_for`) | +| `stream.py` | `Stream`: consumed-prefix cursor, virtual utterances `<uid>+<gen>`, fired set | +| `policy.py` | `evaluate_policy`: ordered gates -> `act/wait/ignore/confirm/clarify` | +| `safety.py` | `gate`, `classify_risk`, `deny_reason`, `confirmation_allowed`, `RateLimiter` | +| `controller.py` | `Controller`: asyncio loop (debounce, coalescing, stale rule, execute, consume, re-decide), `halt()` kill switch | +| `client.py` | `DecisionClient` backends `inproc` (calls `api.system_one`), `http`, `hosted` | +| `observe.py`, `execute.py`, `apps.py` | macOS Accessibility snapshots (`Observer`), execution (`Executor`, `MacUI`; dry-run by default), app index | +| `whisper_source.py` | whisper.cpp `whisper-stream` / `whisper-cli` speech sources and utterance tracker | +| `log.py`, `hud.py`, `killswitch.py`, `replay.py`, `simworld.py`, `fakes.py` | audit JSONL (`AuditLog`, default dir `~/.jev-local/log`, `TOP_K = 3` probabilities kept per choice), console HUD (`ConsoleHud`), ⌃⌥⎋ switch (`KillSwitch`), word-timed replay in virtual time (`VirtualTimeLoop`, `run_replay`, `load_script`), simulated screen (`SimWorld`, `SimExecutor`), test fakes (`RuleModel`, `ScriptedEngine`, `FakeObserver`, `FakeExecutor`, `SlowClient`) | + +The harness's pure modules (`catalog`, `controller`, `policy`, `questions`, `safety`, `spans`, `state`, `stream`, `types`) were ported to the GenClass Chrome extension's JS core (`extension/src/core/*.js`; e.g. `controller.js` says it is a port of `controller.py`), and `extension/scripts/make_py_fixtures.py` imports `catalog`, `policy`, `questions`, `safety`, `spans`, `state`, `stream`, `types` (not `controller`) plus `jev_local.schema` to generate the extension's parity fixtures. So `harness/**` is legacy for `@genclass/runtime` but is still the reference for the extension (see [extension-and-benchmarks.md](extension-and-benchmarks.md)). + +### Entry points + +| command | defined in | what it does | +|---|---|---| +| `jev-local demo [...]` / `jev-local serve [--port 8765]` | `pyproject.toml` `[project.scripts]` -> `jev_local/cli.py` -> `main` | demo -> `jev_local.demo.main`; serve -> `server.app.serve(port=...)` with `ServeConfig()` (= `compat`); any other subcommand exits 2 | +| `python -m jev_local.server.app [flags]` | `server/app.py` -> `main` | benchmax server (default `--preset jev`); flags in Constants | +| `python -m jev_local.train.train [flags]` | `train/train.py` -> `main` | trainer (index or stream mode, `--ddp` under torchrun) | +| `python -m jev_local.train.eval --ckpt DIR (--data DIR \| --stream ROOTS) [--split dev] [--out PATH] [--no-calib]` | `train/eval.py` -> `main` | metrics JSON (default `runs/<ckpt name>/eval_<split>.json`) | +| `python -m jev_local.train.stream ROOTS [--cache runs/stream_cache] [--mixture m.json] [--workers 4] [--out PATH]` | `train/stream.py` -> `main` | index shards and print the mixture plan | +| `python -m jev_local.engine.encoder.calibrate --ckpt DIR ...` | `engine/encoder/calibrate.py` -> `main` | fit and **overwrite** `<ckpt>/calibration.json` | +| `python -m jev_local.harness.observe [--app NAME] [--runs 1] [--max-elements 60] [--quiet]` | `harness/observe.py` -> `main` | print a read-only AX snapshot (macOS) | +| `python -m jev_local.demo [...]` or `python scripts/demo.py` | `demo.py` -> `main` | voice demo (dry-run unless `--live`); walkthrough in [`docs/DEMO.md`](../DEMO.md) | + +### Tests support files and legacy design docs + +| path | role | +|---|---| +| `tests/conftest.py` | `pytest_collection_modifyitems`: skips `macos`-marked tests when `sys.platform != "darwin"` | +| `tests/fixtures/official_examples.json` | Jev documentation examples (server + SDK shape tests) | +| `tests/fixtures/harness_cases.json` | harness decision cases (`test_mlx_scorer.py`; also read by `scripts/bench_{decoder,encoder,laya}.py`) | +| `docs/SPEC.md` | 2026-09-22 rebuild spec: what Jev is (endpoints, wire schema, answer math), how voice computer-use demos work, encoder/decoder design, runtime, data. Many designs differ from code (Drift) | +| `docs/CONTRACT.md` | v0.1 build contract per workstream A–H (API, encoder, decoder, data, harness, macOS I/O, speech, integration); defines the CONTRACT-D training row format still used by `training/` and `sim/` | +| `docs/CONTRACT-v2.md` | v2 mechanics: Mac safety rules (8 GB M1: pure-Python tests only), Azure VM data layout `~/jev/data/v2/`, ownership, lead status notes | +| `docs/DEMO.md` | voice demo setup, commands, what to say, safety, latency, troubleshooting | +| `docs/GENCLASS.md` | public README for GenClass (browser extension + 32M model, Apache-2.0) | +| `docs/COMPARISON.md` | 2026-10-02 meharsjev vs Jev results (computer control, jevbench, compatibility check) | +| `docs/PLAN-excel.md` | 2026-10-03 staged plan to improve the benchmark model (speed fix, specialist, teacher/distil) | + +## Concepts and data structures + +Terms not in the shared terminology list: + +- **System One / Jev wire format.** TypeSafe's typed-decision API shape (`POST /v1/systemone`). `jev_local` reproduces its request/response shapes, limits and answer math (checked against 1,280 real Jev responses per `docs/COMPARISON.md` §3); the runtime's model host uses the same question/answer shape internally. +- **Request** (`SystemOneRequest`): `state: Entry`, `model: str`, `questions: dict[str, Question]` with `min_length=1` (empty `questions` is a pydantic 422). `Question` is a union discriminated by `type` (`"noul" | "choice" | "score"`); unknown fields are ignored everywhere. +- **Question kinds** (`schema.py`). `ChoiceQuestion.criteria: dict[label, Entry | None]` (order = probability order; `None`, `""` or a description equal to the label all mean "read the label by its name alone"). `ScoreQuestion.criteria: list[Entry]` (index = level). `NoulQuestion.criteria: NoulCriteria(true, false) | None`. `instructions` is optional everywhere. `Entry = str | dict | list`. +- **Answers.** `NoulAnswer{noul}` (no confidence field), `ChoiceAnswer{choice, confidence, probabilities}`, `ScoreAnswer{score, confidence, legend, probabilities}` (keys `"0".."n-1"`, legend echoes criteria verbatim). `Usage{input_tokens, output_tokens}`. +- **RawDist** (`engine/base.py`). Unrounded per-question distribution `RawDist(kind, probs, labels)`: noul `probs=(p_true,)`, `labels=()`; choice per label in request order; score per level, labels `"0".."K-1"`. **EngineResult** = `dists`, `input_tokens`, `output_tokens`, `engine` (versioned id), `cached_tokens`, `timings_ms`. **Engine** protocol = `name`, `max_tokens`, `supports(req)`, `count_tokens(req)`, `evaluate(state, questions)`; optional duck-typed `positions_needed(req)` and `fit_state(state, questions)`. **EngineError(detail, status=400)** carries the HTTP status. +- **Segment / QBlock** (`serialize.py`). State -> ordered `Segment(key, text)`: a string state is one segment with key `""`; a dict gives one segment per top-level key; a list gives `"[i]"` segments for the first `MAX_ARRAY_SEGMENTS = 64` items plus one `"[64:]"` tail segment. A question -> `QBlock(qid, kind, header, items, labels)`: header = rendered instructions or a default; choice items `"label: desc"` or bare `"label"`; score items = level texts, labels `"0".."K-1"`; noul items `(true_text or "yes", false_text or "no")`, labels `("true","false")`. **Question ids are never shown to the model.** +- **entry_text rules** (what text the model sees): `None` -> `""`; `str` -> `strip()`; list of strings -> `"; "`-joined non-empty items; other lists -> `json.dumps(..., separators=(", ", ": "))`; dict -> `" | "`-joined `"k: v"` with nested dicts / non-string lists JSON-dumped; anything else -> `str(x)` (so Python renders `True`, `25.0`, `1e-05`). In a dict state, a list-of-strings value is newline-joined. +- **Markers.** `MARKERS = ("[Q]", "[O]", "[L]", "[T]", "[F]")`, added as special tokens. `[Q]` starts a question header, `[O]` a choice option, `[L]` a score level, `[T]`/`[F]` the noul true/false criteria. Heads read hidden states **at marker positions recorded at pack time**; user text is tokenized with `encode_special_tokens = True`, so a label like `"[O] Delete all"` cannot forge a marker. v0.1 ids: `[Q]..[F]` = 50368–50372, `[CLS]` 50281, `[SEP]` 50282, `[PAD]` 50283 (`extension/release-assets/meta.json`); pruned R17/R32 tokenizers: 16359–16363 (`packages/runtime-model/MODEL_CARD.md`). +- **Packed sequence** (`Packed`): `[CLS] seg0 [SEP] seg1 [SEP] ... | [Q] header0 | [O] item00 | [O] item01 | ... | [Q] header1 | ...`, with per-token `input_ids`, `position_ids`, `q_group` (`STATE = -1` for `[CLS]`/state, else question ordinal; `PAD = -2` for padding) and `i_group` (`-1` for state and header tokens, else item ordinal). `QIndex(qid, kind, header, labels, q_pos, item_pos)` records marker positions. State segment text is `"key: text"` (or `text` when key is `""`). +- **Branch.** One question header plus one of its items. Attention rule: a token attends to key *k* iff *k* is a state token, or *k* is in the same question and is a header token or in the same item. Positions restart per branch: header at `S..`, every item at `S+len(header)..`. So `max_tokens` bounds **positions** (state + header + longest item), not the total sequence. +- **Dense vs tree layout.** `build_masks` builds the reference `[B,1,L,L]` boolean masks (`full_attention` and `sliding_attention`, the latter ANDed with `|pos_q - pos_k| <= window`, window = `config.sliding_window` = 64 for ettin). `collate_tree` computes the same attention as three small problems per layer: trunk (state), head (header + its row's state), item chunks (whole items of one question packed into chunks of ≤ `ITEM_CHUNK = 64` tokens, a single longer item gets a wider chunk; keys = its row's state + its header + same-item tokens). **BandedEncoder** (`engine.py`) is a faster exact version of the tree forward (slot gathers, banded local layers); `JEV_ENCODER=reference` selects `MaskedEncoder`. +- **Fragment / pass** (`engine.py`). Each pass holds the state plus at most `max_flat_tokens − state` question tokens. `plan_passes` splits a choice/score question whose header + items exceed that room into contiguous **fragments** (header repeated), then first-fit packs questions and fragments in request order into **passes**, each repeating the state; never two fragments of one qid in a pass; noul is never split. Raw logits of a question's fragments are concatenated and calibrated with **one** softmax over all K options, so the result equals a single pass. +- **Heads** (`heads.py`, d = 384 for ettin-32m). A shared `LayerNorm(d)` normalises gathered marker states, then: choice `z_i = MLP_c([h_Q; h_Oi; h_Q*h_Oi])`; score `z_k = MLP_s([h_Q; h_Lk; h_Q*h_Lk])`; noul `z = MLP_n([h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F])` (absolute, sigmoid). `MLP` = Linear(in -> d) -> GELU -> Linear(d -> 1), last layer `N(0, 0.02)`, bias 0. A `HeadPlan` gathers all questions of a batch into dense `[G, Kmax]` index tensors (padding logits `-inf`). +- **K-bucket.** Option-count bucket for calibration: `2`, `3-5`, `6-10`, `11-30`, `31-100`, `101-255` (`calibrate.K_BUCKETS`); bucket key `"choice:3-5"` etc., `"noul"` for nouls. +- **calibration.json.** v1 keys `{"noul": τ, "choice": τ, "score": τ, "by_header": {sha1(header)[:12]: τ}}`; v2 adds `"version": 2`, `"by_bucket"`, `"tau_k": {"choice": [a, b], "score": [a, b]}` (τ(K) = a + b·ln K), `"noul_platt": {"a", "b"}`, `"bucket_clamp"`, `"_fit"` (stats, ignored at inference). +- **Fast checkpoint dir.** `backbone/` (HF `save_pretrained` of the ModernBertModel + tokenizer with markers), `heads.safetensors`, `calibration.json`, `meta.json` (`name`, `base`, `markers`, `max_len`, `buckets`, `hidden_size`, `written_at`, plus trainer fields `run`, `trained`, `step`, `final`). +- **CONTRACT-D row** (training example, one JSON per line): `{id, split, family, state, questions, labels, meta}`; v2 adds provenance `bucket, source, license_use, variant, group_id`. Labels: choice `{"type":"choice","label":L}` or `{"dist":{L:p}}`; score `{"level":k}` or `{"dist":[...]}`; noul `{"p":x}`. A qid absent from `labels` is unsupervised. `meta.prefix` (harness), `meta.pairs` (consistency), `meta.cap_key|subsource|task` (mixture grouping). +- **Consistency pair** (`meta.pairs`, v2 loss): `{"kind":"neg","a":q,"b":q}` (p(Q)+p(¬Q) = 1), `{"kind":"noul_choice","noul":q,"choice":q,"yes":L}`, `{"kind":"score_choice","score":q,"choice":q,"map":[L per level]}`. +- **Trainer records** (`train/train.py`). `QTarget(dist, hard)` (choice/score: distribution over labels; noul: `[p]`; `hard` = one-hot or p ∈ {0, 1}; `losses.smooth` applies label smoothing only to hard choice/score targets, never to nouls). `Row(pack: Packed, targets: dict[qid, QTarget], example_id, meta)` = one packed sequence. `DataStats(examples, rows, dropped_qids, bad_labels, unsupervised_examples)`. `losses.Targets` = the batch's supervised targets as index tensors aligned with `HeadPlan` groups (`choice_idx/choice/choice_hard`, `score_*`, `noul_idx/noul`, consistency `neg_*`, `nc_*`, `sc_*`). +- **CalibRecord** (`calibrate.py`): `(qid, kind, header, logits, target)` where `header` is already `header_key(...)`, `logits` are raw (τ = 1), choice/score `[K]`, noul `[1]`; `.k` = 2 for noul. `train.eval.collect` returns `Collected(records, metas: list[RecMeta(example_id, prefix, labels, source)], calib, n_examples, dropped_qids)`; `training/eval_runtime.py` consumes exactly this. +- **ServeConfig / preset / W1–W11.** Per-run serving options for the benchmark ("benchmax") effort, chosen once at server start and never per request; W-numbers are requirement ids from `docs/benchmax-research/suite-reproduction-specs.md` (W1 argmax ties, W3 precision, W4 refusals, W5 truncation, W8 label alias, W9 calibration by run config, W10 public id, W11 determinism). +- **Model lineage names.** *jev-local-fast v1* (`models/jev-local-fast`, ettin-32m) = **GenClass 0.1** (`genclass-model-0.1.0`, ONNX in the Chrome extension) = the R32 initialisation. *v2* (`jev-local-fast-v2`, ettin-68m) = public id `meharsjev-68m`, renamed `genclass-<size>`; not used by `training/`. *R32 / R17* = runtime model candidates (see [glossary.md](glossary.md)). + +## How it works + +### 1. One request through the HTTP server + +1. `jev_local/server/app.py` -> `_Guard` (pure ASGI): assigns `x-typesafe-request-id` (`req_` + 12 hex ms + 16 random hex), rejects a Host not in `LOCAL_HOSTS` (400 `Invalid host header`), and, when an API key is set, requires `Authorization: Bearer <key>` on `/v1/*` (401). +2. `create_app` -> `systemone`: pydantic parses `SystemOneRequest` (schema errors -> 422); unknown top-level fields are logged once per distinct set (`_log_extra_fields`, max 256 sets). +3. `_Gate.slot()`: one evaluation at a time (asyncio lock); if busy and `waiting >= max_queue` -> 529 `{"detail":"Overloaded"}`, `retry-after: 1`. Evaluation runs in a threadpool under a second `threading.Lock`. +4. `api.serve_request`: `validate.validate_limits` (count limits, option-cap refusal per `ServeConfig`), then `normalize_request` when `label_alias` (description == key -> `None`), then `_candidates` (flow 2 below). +5. `cand.engine.evaluate(state, questions)` -> `EngineResult`. A too-long error from an engine whose estimate undershot moves auto mode to the next engine; explicit mode raises it in the canonical shape `{"detail":[{"type":"max_tokens_exceeded","msg":...}]}`. +6. `confidence.build_answer` per question (precision and centre from `ServeConfig`), `usage.input_tokens` = engine count, `usage.output_tokens` = Σ (items + 1) (`api.output_tokens`), `model` = `api.public_model_id`. +7. Response headers: `x-jev-local-engine` (`fast|general|heuristic`), `x-jev-local-latency-ms`, and `x-jev-local-truncated` when state tokens were cut. `Counters` record served / refused / truncated for `/healthz` and `/x/v1/run`. + +#### HTTP API reference (`server/app.py` -> `create_app`) + +| method, path | auth | 200 body | notes | +|---|---|---|---| +| `POST /v1/systemone` | bearer if a key is set | `SystemOneResponse` `{model, answers: {qid: Answer}, usage: {input_tokens, output_tokens}}` | headers `x-jev-local-engine`, `x-jev-local-latency-ms` (1 dp), `x-jev-local-truncated` (only when state tokens were cut) | +| `GET /v1/models` | bearer if a key is set | `{"models": [{name, description, release_date}]}` | configured `model_id` first (only if set and a `fast` engine was built), then every engine's versioned name, then aliases `jev-local`, `jev-latest`; `release_date` = `RELEASE_DATE` | +| `GET /healthz` | none | `{ok, version, engines: {fast, general, heuristic: loaded\|lazy\|off\|missing\|error}, queue: {waiting, max}, rss_mb, benchmax: {config, counters, started_at}}` | not a Jev route | +| `GET /x/v1/run` | none | `{config, counters, started_at, registry: Registry.describe(), hardware: hardware_info(), version}` | not a Jev route | + +FastAPI's own `/openapi.json` and `/docs` are also served (`test_server.py` checks the OpenAPI document). Every response, errors included, carries `x-typesafe-request-id`. + +| status | body | when | +|---|---|---| +| 400 | `{"detail": "Invalid host header"}` | Host not in `LOCAL_HOSTS` (unless `allow_remote`) | +| 400 | `{"detail": "<message>"}` | count limits, `No local engine supports this request`, `Model <name> does not support this request` | +| 400 / 413 / 422 | `{"detail": [{"type": "max_tokens_exceeded", "msg": ...}]}` or the option-cap message | capacity refusals; status = `ServeConfig.refusal_status` | +| 401 | `{"detail": "Missing API key"}` / `{"detail": "Invalid API key"}` + `www-authenticate: Bearer` | `/v1/*` only | +| 404 | `{"detail": "Model not found: <id>"}` | unknown id, or engine not installed | +| 422 | FastAPI validation shape | schema errors; empty score `criteria` (raised by `validate_limits` in the same shape) | +| 500 | `{"detail": "Internal server error"}` | unexpected exception (logged with the request id) | +| 503 | `{"detail": "No decision engine is available"}` | registry has no engines (not reachable in practice: heuristic is always built) | +| 529 | `{"detail": "Overloaded"}` + `retry-after: 1` | `max_queue` waiters already queued | + +Illustrative request and response (numbers made up but consistent with the answer math; `compat` rounding): + +```json +{"model": "jev-local", "state": {"transcript": "open safari"}, + "questions": {"intent": {"type": "choice", "instructions": "Which action?", "criteria": {"open_app": "open an app", "none": null}}, + "done": {"type": "noul", "instructions": "Is the command complete?"}, + "urgency": {"type": "score", "criteria": ["low", "high"]}}} +``` + +```json +{"model": "jev-local-fast-0.1.0", + "answers": {"intent": {"type": "choice", "choice": "open_app", "confidence": 0.9, "probabilities": {"open_app": 0.95, "none": 0.05}}, + "done": {"type": "noul", "noul": 0.97}, + "urgency": {"type": "score", "score": 0.3, "confidence": 0.4, "legend": {"0": "low", "1": "high"}, "probabilities": {"0": 0.7, "1": 0.3}}}, + "usage": {"input_tokens": 41, "output_tokens": 9}} +``` + +`output_tokens` = (2 + 1) + (2 + 1) + (2 + 1) = 9; `model` is the engine's versioned name because `jev-local` is an auto alias and no public `model_id` is configured. + +### 2. Model-id resolution and routing (`api.py`) + +1. Strip a vendor prefix `typesafe/`. `AUTO_IDS` (`jev-local`, `jev`, `jev-latest`, `jev-preview`, `jev-1.13`, `jev-1.13.0`) -> auto. Prefixes `jev-local-fast|general|heuristic` -> that engine. `genclass-*` / legacy `meharsjev-*` -> `fast` (if `ServeConfig.model_id` is set, only that exact id). Anything else -> 404 `Model not found: <id>`. +2. Explicit engine: missing -> 404; `_prepare` (truncate mode: `engine.fit_state`); length check `_needed` (`positions_needed` if the engine has it, else `count_tokens`) **before** `supports`, so a too-long request is always a capacity refusal; then `supports` (400 if false). +3. Auto: try `AUTO_ORDER = ("fast", "general", "heuristic")` lazily; skip engines that are too long or do not support the request. If something was too long -> that refusal; no engines at all -> 503; else 400 `No local engine supports this request`. + +### 3. `FastEngine.evaluate` (`engine/encoder/engine.py`) + +1. `serialize.state_segments(state)` and `question_block` per question. +2. `_forward`: `Packer._state_ids` (`[CLS]` + segments with `[SEP]`), `Packer._block_parts` (markers + cached token ids), `plan_passes(n_state, blocks, parts, max_tokens, max_flat_tokens)`; raises `EngineError` 400 `max_tokens_exceeded` if any branch exceeds `max_tokens` positions or the state alone leaves no room. +3. Per pass: `Packer._layout` -> `collate_tree(..., buckets=ENGINE_BUCKETS)` -> `build_plan` -> `heads(enc(batch), plan)`; one host sync per pass. (`attn="dense"` uses `Packer.collate` + `build_masks` instead.) +4. Concatenate each question's fragment logits in option order; `calibrate.calibrate_logits(kind, header_key(header), logits, calib)` in float64 numpy -> `RawDist`. +5. `EngineResult.input_tokens` = state + all header and item tokens counted once (repeated state across passes not counted); `timings_ms` has `serialize`, `pack`, `forward`, `heads`, `total`, `passes`. + +### 4. Calibration lookup (`calibrate.tau_for`, `calibrate.noul_affine`, `calibrate.calibrate_logits`) + +1. `by_header[sha1(header)[:12]]` wins for every kind (fixed-instruction questions keep their own temperature). +2. noul: `noul_platt` (p = sigmoid(a·z + b)) else per-kind τ (p = sigmoid(z/τ)). +3. choice/score: `by_bucket["<kind>:<K-bucket>"]` else `tau_k` (clamped to `bucket_clamp`, default [0.5, 5.0]) else per-kind τ; then softmax(z/τ) with K = full option count. +4. `FastEngine(calibration=...)` **replaces** (never merges with) the checkpoint file (W9); `drop_header_calibration=True` empties `by_header`. + +### 5. Answer math (`confidence.build_answer`) + +1. Choice: reorder engine probs to request label order (`_ordered_probs`), `normalize` (clip, drop NaN/inf, renormalise; all-zero -> uniform), `choice` = argmax of the **unrounded** probs, ties -> first label (W1); `confidence = (K·pmax − 1)/(K − 1)` clipped to [0, 1]. +2. Score: `score = Σ i·pᵢ`; `confidence = max(0, 1 − Σ pᵢ|i − c| / MAD_uniform(K))`, `c` = mode (default; first index on ties) or median; `legend` echoes criteria. +3. Noul: `p` clipped to [0, 1]; NaN/inf -> 0.5. No range clamp beyond [0, 1]. +4. Precision: `round` (each number to N dp, default 2), `lr` (largest-remainder rounding so Σp = 1.00 exactly; scalars still from unrounded probs), `exact` (no rounding). `+ 0.0` everywhere removes `-0.0`. + +### 6. Decoder and heuristic engines (legacy, summary) + +1. `GeneralEngine` (`mlx_scorer.py`): prefix = `SYSTEM_PROMPT` + `<document>{state_text}</document>` in Qwen3 ChatML, prefilled once in chunks of 512 and reused across requests by longest common prefix. Each question is a branch suffix ending with the assistant header and an empty `<think>` block; the answer is read from **next-token logits only**: letters `A..Z` (choice), digits `0..9` (score), `sigmoid(logit("Yes") − logit("No"))` (noul). >26 options are paginated (pages of 25, top ≤3 per page to a final round, merged by `combine_pages`). Control-token strings in user text are broken by `neutralizer`. Branches are batched (≤ 8 rows, ≤ 1024 padded tokens). Never downloads unless `allow_download=True`; missing weights -> 503. +2. `HeuristicEngine`: picks a reference text (state segment named by a backticked path in the instructions, else a transcript-like key, else the whole state), scores options by IDF- and field-weighted word matches (exact, rapidfuzz ≥ 80, 5-letter stem), softmax with scale `(1 + ln K)/0.6`; nouls from criteria similarity or keyword cues (0.5 with no cues, 0.4 when cues are absent from the text). Always present in the registry, < 5 ms target. + +### 7. Training (`train/train.py`) + +1. `init_model(base)`: tokenizer + markers (`add_marker_tokens`), backbone via `encoder_class(...).from_pretrained` (HF cache only, `local_files_only`), embeddings resized and marker rows seeded by `init_marker_embeddings` (0.5·(mean of seed-word embeddings + `[CLS]` embedding); seeds `MARKER_SEEDS`), fresh `DecisionHeads`. `--init-only` writes a servable checkpoint with random heads. +2. Data source: **index mode** (`--data`/`--extra` dirs with `train.jsonl`; `JsonlIndex` byte offsets; `make_batches` length-bucketed by line bytes) or **stream mode** (`--stream` roots; `stream.Corpus` decompresses `.zst` once into `--stream-cache` and indexes per-row offset, split, licence, group, #decisions, class key, layout sizes; `stream.Mixture` filters by split/licence/bucket, caps per group/class, allocates tokens by bucket weight and `n_decisions^alpha` with water-filled repeat limits, shuffles, cuts token-budget micro-batches, optional length curriculum). +3. `encode_example`: `question_from_json` -> `question_block` -> `parse_target` -> `Packer.pack_split` (an over-long example becomes several rows, each repeating the state; questions too long even alone are dropped and counted). +4. `prepare_batch`: `collate_tree` (default `--attn tree`) + `build_plan` + `build_targets` (+ `_pair_refs` for consistency pairs). +5. Forward under optional autocast (`--amp`: fp16 on MPS, bf16 on CPU / bf16 CUDA), `losses.compute_loss`, backward with `/grad_accum`; AdamW (betas 0.9/0.98, eps 1e-6, decay 0.01 except norms/embeddings/biases; heads at `--head-lr`), warmup + cosine (`lr_factor`), grad-norm clip. +6. DDP (`--ddp` under torchrun): no DDP wrapper; `ddp.GradReducer` all-reduces one flat buffer (grads + counters + has-grad flags) per optimizer step; data cursor counts global micro-batches so resume works on a different world size; SIGTERM handled by `LaggedFlag` (non-blocking flag read one micro-batch later; `--stop-check micro` = blocking `any_flag` per micro-batch). +7. Checkpointing: trainer state in `runs/<run>/ckpt/` (`model.safetensors`, `optim.pt`, `trainer.json`, atomic swap) and the servable export in `--out` via `write_checkpoint` (fp32 on CPU, atomic swap; meta gets `base`, `max_len` = `--max-len`, `run`, `trained`, `step`, `final`), every `--ckpt-every` steps and at the end; first SIGINT/SIGTERM finishes the step (DDP: all ranks drop the partial step), checkpoints and exits **130**. Logs: `runs/<run>/log.jsonl`, `mixture_plan.json`, optional `timing/rank<r>.jsonl`. +8. `train/eval.py` collects raw logits (`collect`), computes accuracy / NLL / Brier / ECE (15 bins) / AUROC per qid, kind, K-bucket and source; `calibrate.py main` fits and writes `calibration.json` into the checkpoint. + +### 8. Voice harness (legacy, summary) + +`whisper-stream` -> `WhisperSource` (parser + `UtteranceTracker`) -> `Controller.on_event` -> `Stream.update` (tail after the consumed prefix) -> debounce -> `build_state` + `build_questions` (one request with every question: speculative fan-out) -> `DecisionClient.system_one` -> stale check -> `policy.evaluate_policy` -> `safety.gate` -> `Executor.run` on a worker thread (dry-run by default) -> `Stream.consume` -> re-decide on the rest (≤ `MAX_LOOPS = 4`). Typed text is always a verbatim transcript span chosen by a choice question. Walkthrough and safety rules: [`docs/DEMO.md`](../DEMO.md). + +### 9. From a Python checkpoint to the runtime's model (lineage) + +1. Train with `jev_local/train/train.py` (stream mode) from `training/` launchers (`scripts/launch_run.sh` runs `python -m torch.distributed.run ... -m jev_local.train.train --ddp` on each node); R32 starts from v1 `jev-local-fast` (v1 heads) after `training/prune_vocab.py` keeps the first 16,000 BPE merges (16,364 tokens) into `models/r32-v16k` (launched with `--base .../r32-v16k/backbone`); R17 from the pruned `ettin-17m-v16k` base with fresh heads; stage 1c `--init-from` the stage-1 trainer state (`runs/<model>-s1/ckpt`); the stage-2 pilot and final round 1 both `--init-from` the stage-1c state (`runs/<model>-s1c/ckpt`), not the pilot (`training/launch_s2.sh`, `training/launch_final1.sh`). +2. Evaluate / fit temperatures with `training/eval_runtime.py` (uses `jev_local.train.eval.collect` for raw logits; its own `fit_calibration` fits per-kind, `action`/`diagnosis` group and `by_header` (≥ 300 records) temperatures; `--write-calibration` writes only `noul`/`choice`/`score`, `by_header` (only with `--header-calibration`, else `{}`) and `_fit`: the group temperatures are evaluation-only). +3. Export: `training/export_runtime.py` imports `scripts/genclass_export.py`'s `ExportModel` (dense block mask built in-graph, raw logits at τ = 1) over `load_checkpoint(..., encoder="reference")`, writes `<name>-q8.onnx` / `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`, `model.json`, plus `parity.json`, `pack_fixtures.json`, `torch_fixtures.json`, `requests.json` computed with the Python `Packer` and `calibrate_logits`. +4. In the browser, `packages/runtime/src/model` re-implements packing and calibration in TypeScript and runs the ONNX graph with onnxruntime-web; its tests compare against those fixtures (port table below). Details: [runtime/model-host.md](runtime/model-host.md), [model-io-contract.md](model-io-contract.md). + +### Port map: Python -> TypeScript (`packages/runtime/src/model`) + +The port went Python -> the GenClass extension's JS core (`extension/src/core/{serialize,packer,tokenizer,pyutil,engine}.js`) -> TypeScript. + +| Python (`jev_local/...`) | TypeScript (`packages/runtime/src/model/...`) | notes | +|---|---|---| +| `serialize.py` -> `entry_text`, `state_segments`, `question_block`, `state_text` | `serialize.ts` -> `entryText`, `stateSegments`, `questionBlock`, `stateText` (+ `pyutil.ts` -> `pyNumber`, `pyStrip`) | renders values exactly as Python does **after a JSON round trip** (int vs float text, `str.strip` whitespace set, `True`/`False`) | +| HF `tokenizers` `encode_batch(..., add_special_tokens=False)` with `encode_special_tokens=True` (`Packer.__init__`, `Packer.encode`) | `tokenizer.ts` | byte-level BPE from `tokenizer.json`; special tokens never matched in text | +| `engine/encoder/tokenize_pack.py` -> `Packer._state_ids`, `_block_parts`, `_layout`, `MARKERS`, `STATE` | `packer.ts` -> `Packer.stateIds`, `blockParts` / `layout` (private), `pack`, `measure`, `MARKERS`, `STATE` | **single pass only**: throws `MaxTokensExceededError` when state + longest branch > `maxPositions` (default 1536, meta `max_len`) or total > `maxTotal` (default 8192, meta `max_total`); no `plan_passes`, no `fit_state` | +| `scripts/genclass_export.py` -> `plan_inputs`, `unpack` | `packer.ts` -> `planInputs`, `unpackLogits` | ONNX feed: `input_ids, position_ids, q_group, i_group, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f` -> `choice_logits, score_logits, noul_logits` | +| `engine/encoder/model.py` `MaskedEncoder` + `heads.py` `DecisionHeads` | the ONNX graph, run by `engine.ts` / `backend.ts` | dense reference mask in-graph (batch 1, no padding) | +| `engine/encoder/calibrate.py` -> `header_key`, `k_bucket`, `tau_for`, `noul_affine`, `calibrate_logits`, `K_BUCKETS`, `BUCKET_CLAMP` | `calibrate.ts` -> `headerKey`, `kBucket`, `tauFor`, `noulAffine`, `calibrateLogits`, `K_BUCKETS`, `BUCKET_CLAMP` | identical lookup order; fitting is not ported | +| `confidence.py` -> `normalize`, `choice_confidence`, `score_confidence(center="mode")`, `build_answer` | `calibrate.ts` -> `normalizeProbs`, `choiceConfidence`, `scoreConfidence`, `buildAnswer` | TS precision is `"exact"` (default) or `"round"` (2 dp); no `lr`, no median centre; runtime `ScoreAnswer` has **no `legend`** | +| not ported | — | `validate.py`, `api.py` routing/`ServeConfig`, multi-pass option batching, truncate mode, heuristic and decoder engines | + +Fixtures (all in `packages/runtime/test/fixtures/model/`): `py_fixtures.json` (sections `serialize`, `tokenize`, `pruned`, `calibrate`, `confidence`; regenerate with `packages/runtime/test/fixtures/model/make_py_fixtures.py`, not to be confused with the extension's `extension/scripts/make_py_fixtures.py`; it imports `jev_local.serialize`, `jev_local.schema`, `jev_local.engine.encoder.calibrate`, `jev_local.confidence`), `requests50.json`, `pack_fixtures.json`, `torch_fixtures.json` (50 each; from the v0.1 export flow). Tests prefer `requests.json` / `pack_fixtures.json` / `torch_fixtures.json` from the model directory (`GENCLASS_MODEL_DIR`) when present (`packages/runtime/test/model/helpers.ts`). Reported results (unverified): packing identical on all 50 v0.1 fixtures, q8 decisions 79/80 vs PyTorch (`OPEN_TASKS.md`); R32 export q8 450/454, fp16 453/454, bit-exact packing on 89/90 requests (`packages/runtime/src/model/README.md`). + +### What `training/` reuses vs what is legacy + +| `jev_local` part | used by `training/` / runtime pipeline? | how | +|---|---|---| +| `train/train.py`, `train/stream.py`, `train/losses.py`, `train/ddp.py` | **yes** | the trainer for R17/R32 (stream mode, DDP, `--balance`, `--init-from`; the `training/` launchers pass no `--loss`, so the v1 loss default applies) | +| `train/eval.py` | **yes** | `collect` used by `training/eval_runtime.py`; `train.parse_target` used by `training/curriculum/generate.py` to validate labels | +| `engine/encoder/{tokenize_pack,model,heads,engine}.py` | **yes** | `init_model`, `load_checkpoint`, `write_checkpoint`, `Packer`, `collate_tree`, `build_plan`, `FastEngine` (export, prune tests) | +| `engine/encoder/calibrate.py` | lookup **yes** (export parity); fitting/CLI no (TRAIN fits in `eval_runtime.py`) | `calibrate_logits`, `header_key` | +| `schema.py`, `serialize.py` | **yes** | `question_from_json`, `question_block`, `state_segments` (curriculum validation, export, pruning) | +| `confidence.py` | parity only | TS port + `packages/runtime/test/fixtures/model/make_py_fixtures.py` | +| `api.py`, `validate.py`, `server/**`, `engine/registry.py`, `engine/heuristic.py`, `engine/decoder/**` | no | Jev-compatible server and benchmarks (legacy) | +| `harness/**`, `demo.py`, `cli.py`, `train/fixture.py` | no | voice computer-use product and its tests (legacy for the runtime; `harness/**` remains the parity source for the Chrome extension's `extension/src/core/*.js` via `extension/scripts/make_py_fixtures.py`) | + +Two exporter copies exist: `scripts/genclass_export.py` (imported by `training/export_runtime.py`, which inserts `~/jev` and `~/jev/scripts` into `sys.path`, i.e. the VM copy synced by `training/node.sh`) and `extension/tools/genclass_export.py` (the extension's copy; the files differ). Change the one `training/` imports. + +## Configuration and constants + +### Serialization and answer math (`serialize.py`, `confidence.py`): model-input constants + +These strings are model input; the TS port copies them verbatim (`packages/runtime/src/model/serialize.ts`). Changing any of them is a parity break (see Invariants). + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `DEFAULT_NOUL_INSTR` | str | `"Is the statement true of the state?"` | `serialize.py` | noul header when `instructions` renders empty | +| `DEFAULT_CHOICE_INSTR` | str | `"Which option best fits the state?"` | `serialize.py` | choice header default | +| `DEFAULT_SCORE_INSTR` | str | `"Which level best describes the state?"` | `serialize.py` | score header default | +| noul item defaults | str | `"yes"` / `"no"` | `serialize.question_block` | `[T]` / `[F]` item text when criteria sides are absent or empty | +| `MAX_ARRAY_SEGMENTS` | int | 64 | `serialize.py` | list states: items 0..63 one segment each, the rest newline-joined into `"[64:]"` | +| segment text | format | `"key: text"` (bare `text` when key is `""`) | `tokenize_pack.Packer.segment_text` | each followed by `[SEP]` | +| `state_text` | format | `"key:\ntext"` blocks joined by `"\n\n"` | `serialize.state_text` | decoder engine only | +| `build_answer` defaults | kwargs | `round_digits=2`, `center="mode"`, `precision="round"` | `confidence.py` | `serve_request` passes values from `ServeConfig` | +| score median centre | rule | first index with cumulative p ≥ 0.5 − 1e-12 | `confidence.score_center` | only with `center="median"` | + +### Wire limits and serving (`validate.py`, `api.py`, `server/app.py`) + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `MIN_CHOICE_OPTIONS` / `MAX_CHOICE_OPTIONS` | int | 2 / 255 | `validate.py` | 400 outside; >255 is `OptionCapExceeded` with `ServeConfig.refusal_status` | +| `MIN_SCORE_LEVELS` / `MAX_SCORE_LEVELS` | int | 2 / 10 | `validate.py` | 400 outside; **0 levels is a 422** in FastAPI's error shape | +| `OPTION_CAP_MARKER` / `CONTEXT_MARKER` | str | `"options per choice"` / `"maximum context length"` | `validate.py` / `api.py` | capacity markers in `refusal_style="jev"` wording | +| `AUTO_IDS`, `AUTO_ORDER` | set / tuple | see How it works 2; order `fast, general, heuristic` | `api.py` | auto routing | +| `PUBLIC_PREFIX`, `PUBLIC_PREFIXES` | str / tuple | `"genclass-"`; `("genclass-", "meharsjev-")` | `api.py` | public ids route to `fast` | +| `ServeConfig()` defaults | dataclass | `precision="round2"`, `overflow="refuse"`, `refusal_status=400`, `refusal_style="local"`, `model_id=None`, `label_alias=True`, `center="mode"`, `name="compat"` | `api.py` | v1 server behaviour | +| `ServeConfig` validation | `__post_init__` | `precision` ∈ `exact` \| `round<N>` \| `lr<N>` (N = 1–2 digits, default 2; `parse_precision`); `overflow` ∈ refuse/truncate; `refusal_status` ∈ {400, 413, 422}; `refusal_style` ∈ local/jev; `model_id` matches `^(?:genclass\|meharsjev)-[a-z0-9][a-z0-9.\-]*$` | `api.py` | `ValueError` at start-up | +| `PRESETS` | dict | `compat`; `jev` (+jev wording); `di` (exact, refuse, 400, jev); `jevbench` (exact, refuse, 422, jev); `deusser` (exact, truncate, 400, jev); `paired2dp` (lr2, truncate, 400, jev) | `api.py` | `--preset` | +| `DEFAULT_HOST` / `DEFAULT_PORT` | str / int | `127.0.0.1` / 8765 | `server/app.py` | `serve` refuses other hosts unless `allow_remote` | +| `MAX_QUEUE` | int | 32 | `server/app.py` | waiters before 529 | +| `API_KEY_ENV` | env | `JEV_LOCAL_API_KEY` | `server/app.py` | optional bearer auth on `/v1/*` | +| `LOCAL_HOSTS` | set | `127.0.0.1`, `localhost`, `::1`, `testserver` | `server/app.py` | DNS-rebinding Host check | +| `RELEASE_DATE` | str | `"2026-09-24"` | `server/app.py` | `/v1/models` | +| server CLI defaults | args | `--preset jev`, `--threads 16`; general engine off when `--no-general` or not macOS | `server/app.py` -> `build_parser`, `registry_from_args` | note `jev-local serve` (cli.py) uses `ServeConfig()` = `compat`, not `jev` | +| `Counters.FIELDS` | tuple | `requests`, `served`, `truncated_requests`, `truncated_tokens`, `refused_context`, `refused_options`, `errors_4xx`, `errors_5xx`, `overloaded` | `server/app.py` | `/healthz` `benchmax.counters`, `/x/v1/run` | +| request id | format | `req_` + 12 hex digits of epoch ms + 16 random hex | `server/app.py` -> `new_request_id` | `x-typesafe-request-id` | +| unknown-field log | int | ≤ 256 distinct field sets remembered | `server/app.py` -> `_log_extra_fields` | logs once per set | + +`python -m jev_local.server.app` flags (`build_parser`; `None` = keep the preset's / engine's own value): `--preset {compat,jev,di,jevbench,deusser,paired2dp}` (jev), `--precision`, `--overflow {refuse,truncate}`, `--refusal-status {400,413,422}`, `--refusal-style {local,jev}`, `--model-id`, `--no-label-alias`, `--ckpt PATH` (default `$JEV_LOCAL_FAST_CKPT` or `models/jev-local-fast`), `--calib PATH` (replaces the checkpoint's calibration, W9), `--global-calibration-only` (drop `by_header`), `--max-tokens`, `--max-flat`, `--device` (free text, help says `cpu | mps`; unset = `FastEngine`'s `mps`, falling back to cpu), `--threads 16`, `--no-general`, `--host 127.0.0.1`, `--allow-remote` (disables the Host check), `--port 8765`, `--max-queue 32`, `--api-key`, `--log-level info`, `--print-config` (print `{config, fast_options}` JSON and exit). `config_from_args` applies the overrides on top of `ServeConfig.preset(...)`; `registry_from_args` turns the engine flags into `Registry(fast_options=...)`. + +### Environment variables + +| variable | read by | effect | +|---|---|---| +| `JEV_LOCAL_API_KEY` | `server/app.py` -> `create_app` (`API_KEY_ENV`); `harness/client.py` (http backend) | enables / sends bearer auth on `/v1/*`; empty = no auth | +| `JEV_LOCAL_FAST_CKPT` | `engine/registry.py` -> `default_fast_ckpt`; `tests/test_bm_engine_vm.py` (default `~/jev/models/jev-local-fast-v2`); `tests/test_bench_ours.py` (default `~/jev/models/jev-local-fast`) | fast checkpoint dir (default `<repo>/models/jev-local-fast`) | +| `JEV_ENCODER` | `engine/encoder/engine.py` -> `encoder_class` | forces `reference` or `banded` for every constructor | +| `TYPESAFE_API_KEY` | `harness/client.py` (`API_KEY_ENV`, hosted backend at `https://api.typesafe.ai`) | hosted Jev key (constructor `api_key` or this variable); without one the hosted backend raises `DecisionError` before opening a connection | +| `RANK`, `WORLD_SIZE`, `MASTER_ADDR`, `MASTER_PORT` (required), `LOCAL_RANK`, `LOCAL_WORLD_SIZE` | `train/ddp.py` -> `init_from_env` | torchrun process group (`--ddp`) | +| `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, `TORCH_NUM_THREADS` | `api.hardware_info` (reported only) | recorded in determinism reports and `/x/v1/run` | +| `NO_COLOR` | `harness/hud.py` | disables HUD colours | + +Routes, response shapes and error statuses: see "HTTP API reference" under How it works 1. + +### Encoder, packing, engine (`engine/encoder/*`, `engine/registry.py`) + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `BASE_MODEL` | str | `jhu-clsp/ettin-encoder-32m` | `model.py` | default backbone: d 384, 10 layers, global attention at layers 0/3/6/9, sliding window 64 (per the v0.1 `meta.json`; layer types and window are read from the HF config at load time) | +| `MARKERS` | tuple | `[Q] [O] [L] [T] [F]` | `tokenize_pack.py` | special tokens | +| `BUCKETS` | tuple | 256, 384, 512, 768, 1024, 1536, 2048 | `tokenize_pack.py` | padded lengths (MPS shape stability); beyond: round up to 64 | +| `MAX_LEN` | int | 2048 | `tokenize_pack.py` | `Packer` default; `meta.json` fallback | +| `ITEM_CHUNK` | int | 64 | `tokenize_pack.py` | item tokens per tree chunk | +| `Packer.cache_size` | int | 8192 | `tokenize_pack.py` | token cache entries (cleared when full) | +| `ENGINE_NAME` | str | `jev-local-fast-0.1.0` | `engine.py` | response `model` / engine id | +| `MAX_POSITIONS` | int | 8192 | `engine.py` | hard cap on `max_tokens` | +| `ENGINE_BUCKETS` | tuple | `BUCKETS` + 3072, 4096, 6144, 8192, 12288, 16384 | `engine.py` | flat tree lengths | +| `MARKER_SEEDS` | dict | `" question"`, `" option"`, `" level"`, `" true"`, `" false"` | `engine.py` | marker embedding init | +| `FastEngine(...)` defaults | ctor | `device="mps"` (falls back to cpu), `dtype=float16` (forced to fp32 on CPU), `max_tokens=None` (-> `meta.max_len`, else 2048, ≤ 8192), `attn="tree"`, `max_flat_tokens=None` (-> `max(max_tokens, 8192)`; dense: `max_tokens`), `encoder="banded"`, `calibration=None`, `drop_header_calibration=False`, `threads=None` | `engine.py` | | +| `FastEngine.warmup` lengths | tuple | 256, 512, 768, 1024, 1536 | `engine.py` | MPS kernel warm-up | +| `fit_state` | kwargs | `margin=8`, `min_keep=16`, `max_rounds=12` | `engine.py` | truncate mode | +| `JEV_ENCODER` | env | `reference` / `banded` | `engine.py` -> `encoder_class` | overrides encoder choice | +| default `encoder` | str | `"reference"` for `encoder_class`, `init_model`, `load_checkpoint`; `"banded"` for `FastEngine`, `train --encoder`, eval | `engine.py`, `train.py` | exports use `load_checkpoint(..., encoder="reference")` | +| `MAX_CHOICE_OPTIONS` | int | 255 | `engine.py` | `FastEngine.supports` is False above it (independent of `validate.py`'s identical cap) | +| `write_checkpoint` meta defaults | dict | `name=ENGINE_NAME`, `base=BASE_MODEL`, `markers`, `max_len=MAX_LEN` (2048), `buckets=BUCKETS`, `hidden_size`, `written_at`; trainer `meta=` overrides | `engine.py` | `FastEngine.max_tokens` comes from `max_len` | +| `JEV_LOCAL_FAST_CKPT` | env | path | `registry.py` | fast checkpoint dir (default `<repo>/models/jev-local-fast`) | +| `DEFAULT_GENERAL_REPO` | str | `mlx-community/Qwen3-1.7B-4bit` | `registry.py` | never downloaded by the registry | + +### Calibration (`engine/encoder/calibrate.py`) + +| name | value | effect | +|---|---|---| +| `DEFAULT_CALIBRATION` | `{"noul":1.0,"choice":1.0,"score":1.0,"by_header":{}}` | base of every loaded file | +| `TAU_MIN, TAU_MAX` | 0.05, 20.0 | per-kind / per-header fit range | +| `BUCKET_CLAMP` | (0.5, 5.0) | bucket τ and τ(K) clamp | +| `K_BUCKETS` | (2,2) (3,5) (6,10) (11,30) (31,100) (101,255) | K-buckets | +| `min_per_header`, `min_per_bucket` | 50, 50 | samples needed to fit a header / bucket / Platt | +| `fit_tau_k` | needs ≥ 20 records and ≥ 2 distinct K; subsample 20,000 (seed 0) | τ(K) fit | +| `fit_platt` | Newton, 50 iters; `a` clamped to [0.2, 2.0], `b` to [−5, 5] | noul Platt | +| `fit_tau` | golden-section on log β = log(1/τ), 60 iterations, range `[TAU_MIN, TAU_MAX]` (or the bucket clamp) | per-kind / header / bucket τ | +| `tau_k` lookup | τ = clamp(a + b·ln(max(K, 2)), `calib["bucket_clamp"]` or `BUCKET_CLAMP`) | `tau_for` | +| `k_bucket(K)` for K > 255 | `"101-255"` | the last bucket absorbs everything above | +| rounding of fitted values | 4 dp | every τ, `tau_k` pair and Platt `(a, b)` in the written file | + +Calibrate CLI (`calibrate.main`): `--ckpt` (required), `--data`, `--extra`, `--stream ROOTS`, `--stream-cache runs/stream_cache`, `--split dev`, `--limit`, `--batch 8`, `--device`, `--max-len`, `--min-per-header 50`, `--min-per-bucket 50`, `--bucket-clamp 0.5,5.0`, `--no-platt`, `--no-buckets` (v1 file). It writes `<ckpt>/calibration.json` and prints ECE before/after per kind and per K-bucket. + +### Decoder and heuristic (legacy) + +| name | value | defined in | +|---|---|---| +| `MAX_TOKENS` (GeneralEngine) | 8192 (prefix + all branches, and prefix + longest branch) | `mlx_scorer.py` | +| `PAGE_SIZE`, `MAX_FINALISTS_PER_PAGE`, `PREFILL_CHUNK`, `CACHE_LIMIT_MB` | 25, 3, 512, 256 | `mlx_scorer.py` | +| `GeneralEngine` ctor | `order_samples=1`, `batch_tokens=1024`, `max_batch=8`, temperatures 1.0, `allow_download=False` | `mlx_scorer.py` | +| `HeuristicEngine.max_tokens` | 65536 | `heuristic.py` | +| `CHOICE_TEMP`, `SCORE_TEMP`, `NONE_BASELINE`, `FUZZY_CUTOFF`, `STEM_LEN`, `NOUL_SLOPE` | 0.6, 0.6, 0.45, 80.0, 5, 8.0 | `heuristic.py` | + +### Training (`train/train.py`, `train/losses.py`, `train/stream.py`) + +| name | value | effect | +|---|---|---| +| CLI defaults | `--data data/cu`, `--out models/jev-local-fast`, `--runs-dir runs` (`--run-name` defaults to the basename of `--out`), `--base jhu-clsp/ettin-encoder-32m`, `--batch 4`, `--grad-accum 4`, `--max-len 1536` (≤ `MAX_TRAIN_LEN` 8192), `--lr 5e-5`, `--head-lr 1e-3`, `--weight-decay 0.01`, `--warmup 0.03`, `--clip 1.0`, `--log-every 20`, `--ckpt-every 500`, `--empty-cache-every 200`, `--seed 0`, `--encoder banded`, `--attn tree`, `--grad-ckpt` on, `--loss v1`, `--prefetch` 2 (stream) / 0 (index), `--calibrate-lengths 64`, `--index-workers 4`, `--ddp-timeout 1800`, `--stop-check lagged` | `build_parser` | +| other trainer flags | `--init-from PATH` (weights only, fresh optimizer/schedule; servable ckpt or trainer state dir, `load_weights`), `--init-only`, `--resume`, `--epochs`, `--max-steps`, `--limit`, `--device` (free text: mps / cpu / cuda; default mps when available), `--amp`, `--threads`; loss overrides `--smoothing`, `--brier`, `--rps`, `--kl/--no-kl`, `--spherical`, `--coral`, `--noise-sigma start,end`, `--noise-samples`, `--noise-weight`, `--consistency`; stream group `--stream ROOTS`, `--stream-cache runs/stream_cache`, `--mixture JSON`, `--batch-tokens`, `--batch-rows`, `--source-cap`, `--class-cap`, `--alpha`, `--passes`, `--pool`, `--batch-layout {tree,dense}`, `--balance/--no-balance`, `--curriculum 'p:max,...'`, `--license`, `--buckets`, `--splits`; DDP group `--ddp`, `--ddp-compress bf16`, `--stop-check {lagged,micro}`, `--timing-log`; hidden `--stop-at K` (tests) | `build_parser`, `loss_config`, `build_stream` | +| `LONG_BUCKETS` | 3072, 4096, 6144, 8192 | `train_buckets` | +| `LossConfig()` (v1) | smoothing 0.02, rps 0.25 (score), brier 0, kl False, spherical 0, coral 0, noise off, consistency 0 | `losses.py` | +| `LossConfig.v2()` | smoothing 0.02, rps 1.0, kl True, spherical 0.5, coral 0.25, consistency 0.1 | `losses.py` | +| `MixConfig()` | `seed=0`, `splits=("train",)`, `licenses=None`, `buckets=None`, `bucket_weights=DEFAULT_BUCKET_WEIGHTS`, `weight_unit="tokens"`, `alpha=0.5`, `source_cap=None`, `class_cap=None`, `max_repeat=2.0`, `pass_tokens=None` (one capped epoch), `passes=1.0`, `pool=4096`, `batch_tokens=16384`, `layout="tree"`, `batch_rows=None`, `max_len=8192`, `curriculum=()`, `balance=False` | `stream.py` | +| `DEFAULT_BUCKET_WEIGHTS` | `b1_tasksource_jev` 0.36, `b2_label_semantics` 0.10, `b3_nli` 0.05, `b4_procedural` 0.08, `b5_open_jev` 0.04, `b6_synthetic` 0.14, `b7_laurer` 0.06, `b8_extractive` 0.04, `b9_cu` 0.12, `s0_families` 0.14; any other bucket `OTHER_BUCKET_WEIGHT` 0.04 (renormalised over buckets present) | `stream.py` | +| `SPLITS`, `LICENSES` | `("train", "dev_mix", "dev_family", "dev", "test")`, `("commercial", "research", "unknown")` | `stream.py` | +| AdamW | betas (0.9, 0.98), eps 1e-6; groups: decayed backbone, no-decay backbone (ndim < 2, `norm`, `embeddings`), heads at `--head-lr` with no decay | `train.py` -> `param_groups` | +| `lr_factor` | linear warmup over `max(1, round(total·warmup))` steps, then cosine to `floor` (0.0) | `train.py` | +| `amp_dtype` | MPS fp16; CPU bf16; CUDA bf16 if supported else `None` (no autocast) | `train.py` | +| `DEFAULT_TOKENS_PER_BYTE`, `INDEX_VERSION` | 0.27, 2 | `stream.py` | +| `N_BINS` | 15 | `train/eval.py` (ECE) | + +### Harness (legacy, `harness/types.py` -> `Thresholds`, `controller.py`, `safety.py`) + +`Thresholds`: `is_command` 0.5, `intent_conf` 0.45, `intent_top_p` 0.55, `complete` 0.65, `stable_complete` 0.85, `target_conf` 0.45, `target_top_p` 0.35, `span_top_p` 0.35, `app_top_p` 0.50, `key_top_p` 0.60, `folder_top_p` 0.50, `destructive` 0.5, `high_risk_intent_p` 0.85, `high_risk_target_p` 0.75, `confirm_p` 0.8, `silence_complete_ms` 900, `payload_silence_ms` 600, `debounce_ms` 120, `confirm_timeout_ms` 8000. `HarnessConfig`: `dry_run=True`, `backend="inproc"`, `base_url="http://127.0.0.1:8765"`, `model="jev-local"`, `search_url="https://www.google.com/search?q={q}"`, `allow_apps=()`, `max_elements=60`, `max_apps=24`, `log_redact=True`, `thresholds=Thresholds()`. Controller: `MAX_LOOPS` 4, `MAX_DEBOUNCE_MS` 300, `SILENCE_MARGIN_MS` 15, `RATE_MAX, RATE_WINDOW_S` = 3, 1.0, `UNDO_DEPTH` 20, `DEFAULT_APPS` (18 names, deny-listed apps included on purpose); `silence_gates_for(cadence)` = (2·cadence + 150, max(that, 900)). Safety: `CONFIRM_REACTION_S` 0.8. Policy: `CANCEL_TOP_P` 0.5. `DecisionClient` timeout 1.2 s; hosted base URL `https://api.typesafe.ai`. Whisper (`whisper_source.py`): models in `~/.jev-local/models/whisper` (default `base.en`), `DEFAULT_STEP_MS` 500, `DEFAULT_LENGTH_MS` 8000, `DEFAULT_KEEP_MS` 200, `SAMPLE_RATE` 16000; binaries `whisper-stream` / `whisper-cli` from `PATH` else `/opt/homebrew/bin`. Question ids sent every update (`questions.py`): `intent`, `complete`, `is_command`, `destructive`, `target` (only with a snapshot), `app`, `key`, `folder`, `text_span` / `url_span` (only with candidates), `scroll_amount`; state keys (`state.build_state`): `screen`, `focused`, `recent_actions` (last 3), `pending`, `transcript`. + +## Invariants and gotchas + +- **Text parity is the contract with the runtime.** The trained weights only work on text produced exactly as `serialize.py` + `Packer` produce it. Any change to `entry_text`, `state_segments`, default instructions, item rendering (`"label: desc"` vs bare label), `[SEP]`/`[CLS]` placement, marker set or order, or position numbering silently degrades every existing model and breaks `packages/runtime/test/model/*` parity. +- **Python number rendering leaks into the text.** `str(25.0)` is `"25.0"` but JS can only produce `25`; rows with integral floats train on text the runtime never sends (`training/NEEDS.md` item 8: write integral floats as ints). Booleans render `True`/`False`, `None` as `""` in dicts. +- **Isolation is exact, not approximate.** Option order and unrelated questions cannot change an answer (tests: `test_encoder_engine.py` -> `test_permuting_options_is_exact`, `test_unrelated_question_is_exact`). Do not add cross-question or cross-option attention; it would break this and the multi-pass equivalence. +- **`max_tokens` is a positions budget.** It bounds state + header + longest item; the whole request may be far longer (multi-pass). The router compares `positions_needed`, not `count_tokens`. The TS port has **no** multi-pass and also enforces a total (`maxTotal`), so the runtime must keep situations inside its budgets. +- **Three different length checks.** `Packer.pack` (used by `scripts/genclass_export.py` and `training/export_runtime.py` to build parity fixtures) bounds the **total** sequence by `max_len` (`EngineError` 400 `{"detail": "max_tokens_exceeded", "tokens", "max_tokens"}`); `FastEngine` bounds **positions** via `plan_passes` and splits the rest into passes; `FastEngine.count_tokens` (= `Packer.count`) is the total and is what `usage.input_tokens` reports, while routing uses `positions_needed`. The TS packer checks both positions (`maxPositions`) and total (`maxTotal`). Both exporters build fixtures with `Packer(tok, max_len=8192)`, so fixture totals stay ≤ 8192 (= TS `maxTotal` default), but `Packer.pack` does not bound positions; `training/export_runtime.py` -> `requests_from_rows` only samples data rows whose total is ≤ 1500 tokens, which keeps them under `maxPositions` 1536. Requests passed with `--requests` get no such filter. +- **Packer token cache** is cleared wholesale when `cache_size` (8192) would be exceeded, and the current call's texts are then re-encoded; `test_encoder_pack.py` -> `test_encode_cache_eviction_keeps_this_calls_hits` pins that fix. +- **Joint softmax over fragments.** Calibration must see all K logits of a question at once (bucket by the full K). Never calibrate per fragment. +- **`by_header` keys are sha1 of the rendered header** (`header_key(question_block(...).header)`), i.e. of the instructions text or the default instruction, not of the qid. Renaming or rewording standing-question instructions silently drops their per-header temperature. +- **`heads.probabilities` is v1-only** (per kind + by_header, torch). `FastEngine` uses `calibrate.calibrate_logits` (numpy, float64, v2 keys). `calibrate.calibrated_probs` is the v2 torch equivalent. +- **Answer math.** `choice` is the argmax of unrounded probabilities with ties to the first label; confidence is computed before rounding; `round` precision can make Σp ≠ 1 for many options (use `lr` or `exact` when sums are checked). +- **Marker forgery is blocked** only because `Packer.__init__` sets `tok.backend_tokenizer.encode_special_tokens = True` (this mutates the shared tokenizer object). The TS tokenizer must keep "special tokens are never matched in text". +- **Checkpoints are written atomically** (sibling `.tmp-<pid>` then swap); `write_checkpoint` stores fp32 on CPU. `meta.json["max_len"]` becomes `FastEngine.max_tokens`; an `--init-only` checkpoint has `max_len` 2048. +- **Engines are not thread-safe.** The server serialises evaluations (asyncio gate + lock); `DecisionClient` inproc uses a lock. +- **`BandedEncoder` == `MaskedEncoder.forward_tree` == dense mask** in float64 (outputs and gradients), pinned by `test_train_v2_banded.py` and `test_encoder_model.py`. Change all three together or not at all. +- **Padding rows must stay finite**: padding queries attend to themselves / key 0 (`build_masks`, `_only_first_key`); a NaN would leak into real rows through 0·NaN in backward. +- **Determinism.** Same request bytes -> same response bytes is measured (not enforced) by `api.determinism_report` (W11; asserted in `test_bm_engine.py` and `test_bm_engine_vm.py`). Training data order is a pure function of seed, pass and cursor (`stream._rng`); DDP replicas stay bit-identical through identical reduced gradients. +- **Never download.** `load_tokenizer` / `init_model` use `local_files_only` for bare repo ids; the registry never fetches the decoder; `GeneralEngine` returns 503 when weights are absent. +- **Mac safety** (`docs/CONTRACT-v2.md`): on the 8 GB M1 run only pure-Python tests; torch, models, datasets, training and benchmarks run on Azure VMs. The executor defaults to dry-run; live actions only by the user. +- **`pyproject.toml` lists pyobjc unconditionally** and lacks `zstandard`, `onnx`, `onnxruntime`; installing on Linux VMs may need manual handling (unverified). +- **Which `jev_local` the VMs run.** `training/node.sh sync` rsyncs `${HERE}/../..` + `/jev_local`, `/scripts`, `/pyproject.toml` (comment: "parent repo with jev_local") to `~/jev/` on the node, and commands run with `PYTHONPATH=~/jev:~/gcl-train/training`. Edits to this repo's `jev_local/` reach the cluster only if that parent copy is the same tree; check before assuming a Python change is live in training. +- **Collection errors abort pytest.** The 20 `tests/test_data_*.py` files import the absent `jev_local.data`; a plain `pytest tests` stops at collection. Ignore them (see Tests). + +## How to change it safely + +1. **Change serialization, packing, markers or position rules** (affects every model): + - Edit `jev_local/serialize.py` / `engine/encoder/tokenize_pack.py` **and** `packages/runtime/src/model/{serialize,packer,pyutil,tokenizer}.ts` in the same change. + - Regenerate `py_fixtures.json` (`packages/runtime/test/fixtures/model/make_py_fixtures.py`, on a VM with the jev venv) and re-export a model so `pack_fixtures.json` / `torch_fixtures.json` / `parity.json` reflect the new layout; retrain (the change invalidates trained weights). + - Run `tests/test_encoder_pack.py`, `test_encoder_model.py`, `test_encoder_engine.py`, `test_train_v2_banded.py`, `test_train_v2_engine.py`, `test_serialize_w8.py`, and `packages/runtime/test/model/*.test.ts`. Coordinate with MODEL and TRAIN (see [model-io-contract.md](model-io-contract.md)). +2. **Change calibration lookup or file format**: edit `calibrate.tau_for` / `noul_affine` / `calibrate_logits` and `calibrate.ts` together; keep v1 files loadable (`test_train_v2_engine.py` checks backward compatibility); update the calibrate section of `packages/runtime/test/fixtures/model/make_py_fixtures.py`; run `test_encoder_heads.py`, `test_train_v2_engine.py`, `test_bm_engine.py` (`test_load_calibration_replaces_and_describes`), TS `calibrate.test.ts`. +3. **Change answer math** (`confidence.py`): keep the documented Jev rows within ±0.01 (`test_confidence.py`), keep W1 ties and precision modes (`test_bm_engine.py`); mirror in `calibrate.ts` `buildAnswer` if the runtime should follow. +4. **Add a server option / preset**: add a `ServeConfig` field with validation in `__post_init__`, add it to `PRESETS` if needed, wire a flag in `server/app.py` -> `build_parser` / `config_from_args`; never decide from request content. Tests: `test_bm_engine.py`, `test_server.py`. +5. **Change training losses**: add a `LossConfig` field defaulting to off so the v1 path stays bit-identical (`test_train_v2_losses.py` -> `test_v1_default_is_bit_identical`); expose a CLI flag in `build_parser` and `loss_config`. Every new term must be a proper scoring rule (zero gradient at p = t). +6. **Change the mixture / data reader**: `stream.py` is numpy-only; keep determinism and world-size-independent cursors (`test_train_v2_stream.py`). Bump `INDEX_VERSION` if the per-row index layout changes (old caches are rebuilt by manifest key). +7. **Change harness vocabularies** (`harness/catalog.py`, `questions.py` instructions): these strings are model input, so a change requires regenerating data and retraining the computer-use model; run `test_policy.py`, `test_safety.py`, `test_controller.py`, `test_heuristic.py`. The extension's JS core mirrors these modules, so its parity fixtures (`extension/scripts/make_py_fixtures.py`) change too (see [extension-and-benchmarks.md](extension-and-benchmarks.md)). +8. **Ship a `jev_local` change to training runs**: `training/` imports `jev_local` from `~/jev` on the VMs (`training/node.sh sync` source is `$HERE/../..`, see Invariants); make sure the copy that gets synced contains your change, then re-run `training/tests/` on a VM (see [training.md](training.md)). Keep trainer flags that the `training/` launchers and `scripts/launch_run.sh` pass (`--ddp`, `--threads`, `--run-name`, `--stream`, `--stream-cache`, `--mixture`, `--runs-dir`, `--max-len`, `--batch-tokens`, `--balance`, `--amp`, `--no-grad-ckpt`, `--device`, `--base`, `--init-from`, `--out`, `--lr`, `--head-lr`, `--grad-accum`, `--resume`, ...) backward compatible; note `scripts/launch_run.sh` also exports `JEV_ENCODER=banded`. +9. **Add a Python test**: put it in `tests/test_<module>.py`; mark `@pytest.mark.model` (needs downloaded weights), `@pytest.mark.slow` (> 10 s), `@pytest.mark.macos` (AX/AppKit; auto-skipped off macOS by `tests/conftest.py`). + +## Tests + +How to run (from the repo root, inside the jev venv; per [`docs/CONTRACT-v2.md`](../CONTRACT-v2.md) torch/model tests run on the VM): + +```sh +.venv/bin/pip install -e ".[dev]" # once (pyobjc deps: see gotchas) +.venv/bin/python -m pytest -q tests --ignore-glob='tests/test_data_*.py' -m "not model and not slow" # pure-ish +.venv/bin/python -m pytest -q tests --ignore-glob='tests/test_data_*.py' # VM: everything else +JEV_LOCAL_FAST_CKPT=~/jev/models/jev-local-fast-v2 .venv/bin/python -m pytest -q tests/test_bm_engine_vm.py +``` + +`model` tests need `jhu-clsp/ettin-encoder-32m` in the Hugging Face cache (encoder/train tests) or `mlx-community/Qwen3-1.7B-4bit` (decoder); `test_server.py` / `test_sdk_roundtrip.py` skip without the `dev` extra; `test_train_v2.py` needs `zstandard` and spawns 2 local gloo ranks. `test_encoder_heads.py`, `test_train_v2_losses.py` and `test_train_v2_engine.py` (its first three tests are unmarked) import torch at module level without a file-wide `model` marker, so `-m "not model"` is not torch-free; on the Mac, select files explicitly. Instead of `--ignore-glob`, `--continue-on-collection-errors` also works. `training/tests/` is not under `testpaths` (see [training.md](training.md)). + +| test file | area | needs | what it asserts | +|---|---|---|---| +| `test_confidence.py` | answer math | pure | documented Jev confidence rows within ±0.01; mode vs median; MAD; normalise; label reordering, ties, legend echo, noul clip without range clamp | +| `test_validate.py` | limits | pure | 2..255 options, 2..10 levels, empty score = 422, nouls unlimited | +| `test_api.py` | routing | pure | auto prefers fast, falls back; explicit ids; 404/400/503; too-long normalisation; auto retry after an engine under-estimate; output_tokens | +| `test_bm_engine.py` | benchmax W1–W11 | pure | largest-remainder, presets, public ids, refusal wording/status, length-before-supports, multi-pass via `positions_needed`, truncate mode + headers/counters, label alias, 255 options over HTTP, determinism report, calibration replace, CLI print-config, no torch import | +| `test_bm_engine_vm.py` | benchmax on real ckpt | torch + ckpt, VM only (skips on darwin) | 8k states, 255 long options in exact passes, refuse vs truncate on 12k state, calibration by run config, byte determinism and order invariance | +| `test_server.py` | HTTP | dev extra | official examples' shape vs SDK models + jsonschema, request ids, extra fields, models/healthz/openapi, 422/400/404, auth + env key, Host check, engine header, 529 + no overlap, 500 with request id, latency header | +| `test_sdk_roundtrip.py` | client compat | dev extra, live uvicorn | `typesafe-sdk` sync/async round trips, errors, auth, base URL | +| `test_registry.py` | registry | pure | lazy build, missing/erroring engines non-fatal, env override, general cached/lazy/eager, warm, importing does not import torch/mlx | +| `test_heuristic.py` | heuristic | pure | protocol, determinism, min < 5 ms (median < 15 ms) on a 61-option target request, sane harness answers, permutation invariance, backticked path | +| `test_serialize_w8.py` | serialization | pure | `null`, `""`, desc == label render identically | +| `test_encoder_pack.py` | packing | `model` (tokenizer) | markers added once, layout/positions/groups, marker forgery blocked, max tokens, `pack_split`, buckets, mask rules, cache-eviction regression | +| `test_encoder_model.py` | masked forward | `model` | config matches contract, all-attend == HF forward, tree == dense, padding/batching invariance, tree backward + grad checkpoint | +| `test_encoder_heads.py` | heads/losses/calib/eval | torch | plan shapes, temperatures, permutation equivariance, losses decrease, RPS ordinal, `parse_target`, batching, LR schedule, τ fits, ECE/AUROC | +| `test_encoder_engine.py` | FastEngine | `model` (+ MPS and `slow` for one test) | protocol + checkpoint round trip, exact option-permutation and unrelated-question invariance, tree == dense engine, max tokens, >255 unsupported, calibration, api end to end, MPS fp16 ≈ CPU fp32 | +| `test_train_v2_engine.py` | FastEngine v2 | torch import; K-bucket/fit/clamp tests unmarked (numpy), the rest `model` | K-buckets, bucket/Platt fit recovery, clamp, multi-pass == single pass, 255 ok / 256 not, states to 8192, `evaluate_logits`, calibrate CLI writes v2 file | +| `test_train_v2_banded.py` | BandedEncoder | `model` | hidden states and gradients equal the reference (padding, many option chunks, long states, checkpointing) | +| `test_train.py` | trainer v1 | `model`, `slow` | 20-step smoke loss decreases, servable ckpt, resume == uninterrupted, init-only, eval + calibrate CLI | +| `test_train_v2.py` | trainer v2 | `model`, `slow`, zstandard | stream smoke with v2 losses, resume, token budget + `--init-from`, DDP == single-process accumulation, SIGTERM on all ranks + resume | +| `test_train_v2_losses.py` | losses | torch | v1 default bit-identical, KL/spherical/CORAL proper, noise schedule, consistency pairs, NaN-free padding | +| `test_train_v2_stream.py` | mixture | numpy | index + cache, filters, bucket shares + sqrt sampling, caps/repeat water-fill, determinism, token budgets, DDP sharding/resume, cycling, curriculum, cost balancing | +| `test_mlx_scorer.py` | decoder | pure helpers; mlx for mechanics; `model`+`slow` for Qwen3 | prompt text, pagination math, neutralizer, forked-prefix == full forward, batching, prefix reuse, no writes to shared cache, doc example -> billing | +| `test_stream.py`, `test_policy.py`, `test_safety.py`, `test_controller.py`, `test_client.py`, `test_log.py`, `test_replay.py`, `test_fakes.py`, `test_hud.py` | harness core | pure (`test_replay.py` has a `slow` test) | consumed-prefix/dedup, gate order, red-team list never executes unconfirmed, mid-sentence replays (42 controller tests), client backends (hosted needs an explicit key), redaction, virtual-time replay == real-time replay | +| `test_execute.py` | macOS execution | pure (fake UI; one `slow` test) | key map covers every catalog key, URL builder accepts/refuses, dry-run is the default and never touches the UI, live-path fallbacks (AXPress, keystrokes), secure-field and deny-list refusals, undo | +| `test_observe.py`, `test_apps.py` | macOS observation | pure helpers + `macos` live tests | role humanising, ranking, permission/locked-screen handling; read-only live Finder / frontmost snapshots; app index scan | +| `test_whisper_source.py`, `test_demo.py`, `test_demo_midsentence.py`, `test_demo_safety_review.py` | voice demo | pure (`test_demo.py` has `macos` tests, e.g. the kill switch) | whisper parser/tracker over a fake binary, demo args/memory guards, adversarial mid-sentence and safety reviews (docstrings say written to fail before fixes; current pass status unverified) | +| `test_overnight.py`, `test_bench_*.py`, `test_bm_adapters_*.py`, `test_bm_integrate.py` | scripts / benchmarks | pure, except `test_bench_ours.py` (`model`, skips on darwin and without a checkpoint) | out of scope: see [extension-and-benchmarks.md](extension-and-benchmarks.md) | +| `test_data_*.py` (20 files) | data generators | `jev_local.data` | **cannot run in this repo**: the package is not in it | + +Fixtures: `tests/fixtures/official_examples.json` (Jev doc examples, server + SDK tests), `tests/fixtures/harness_cases.json` (decoder cases, `test_mlx_scorer.py`). `tests/conftest.py` only skips `macos` tests off macOS; there are no shared fixtures. + +## Drift and open issues + +Code wins in every row. + +| # | doc says | code does | +|---|---|---| +| 1 | `docs/CONTRACT.md` H: subcommands `serve`, `run`, `replay`, `doctor`, `bench`, `data`, `train`, `eval`, `calibrate`, `snapshot` | `jev_local/cli.py` -> `main` has only `demo` and `serve [--port]` | +| 2 | `docs/CONTRACT.md` G, `docs/SPEC.md` §4.1–4.2: Swift `helpers/JevHear` + `harness/stt_client.py` (SpeechAnalyzer over a Unix socket) | no `helpers/`, no `stt_client.py`; speech comes from whisper.cpp via `harness/whisper_source.py` | +| 3 | `docs/CONTRACT.md` D, `docs/SPEC.md` §6.1, `docs/GENCLASS.md` ("data pipelines ... `jev_local/data/`"), `train/stream.py` docstring (`jev_local.data.v2.render`) | `jev_local/data/` absent: root `.gitignore` `data/` matches it; 20 `tests/test_data_*.py` fail to import | +| 4 | `docs/SPEC.md` §3.3: segment-causal state attention, segment KV cache (`engine/encoder/cache.py`), span head, `<s:...>` segment tags, buckets 256/512/768/1024/2048 (§6.2 `pack` signature: up to 4096), packed ≤ 4096 (v0) / 8192 | full bidirectional state attention, no cache, no span head, `"key: text" [SEP]` segments, `BUCKETS` to 2048 (`ENGINE_BUCKETS` to 16384), positions ≤ `meta.max_len` (fallback 2048, cap 8192) with multi-pass | +| 5 | `docs/SPEC.md` §3.3 noul head `[h_Q; h_T; h_F]` | 5-way `[h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F]` (matches CONTRACT B); plus a shared `LayerNorm` on gathered states (in neither doc) | +| 6 | `docs/SPEC.md` §3.4 / CONTRACT C: noul tokens `" Yes"`/`" No"`, suffix ends `Answer:` | single tokens `"Yes"`/`"No"`; ChatML assistant header with empty `<think>` block, `CHOICE_ASK`/`SCORE_ASK`/`NOUL_ASK` lines | +| 7 | `docs/CONTRACT.md` A: every count limit is a 400 | empty score criteria -> 422 (FastAPI shape); option cap status 400/413/422 and wording per `ServeConfig` | +| 8 | `docs/CONTRACT.md` B training losses: CE + smoothing 0.02, optional Brier | v1 default also adds RPS 0.25 on score; `--loss v2` = KL + 0.5 spherical + 1.0 RPS + 0.25 CORAL + 0.1 consistency | +| 9 | `docs/SPEC.md` §4.3–4.4 thresholds (`intent_conf` 0.60, `app_conf` 0.60, `key_conf` 0.70, `correction`, `ends_dictation`), intents `switch_app`, `click_element`, `menu_item`, `WAIT`, dictation mode | `Thresholds` as in Constants; 18 `catalog.INTENTS` (`click`, `wait`, no `switch_app`/`menu_item`); no dictation, `is_correction` or `ends_dictation` | +| 10 | `docs/SPEC.md` §5.1: `POST /x/v1/spans`, release date 2026-10-01; §5.2: too-long message "7,680 tokens" | no spans route; `GET /x/v1/run`; `RELEASE_DATE` 2026-09-24; message from `api.too_long_message` | +| 11 | code docstrings cite `docs/research/SPEC.md`, `docs/research/benchmax/...`, `docs/build/stage1-speed.md` (and `jev_local/bench/` cites `docs/research/v2/PLAN.md`); `docs/CONTRACT.md` and `docs/CONTRACT-v2.md` also point at `docs/research/...` | in this repo: `docs/SPEC.md`, `docs/benchmax-research/*`; `docs/research/` and `docs/build/` do not exist | +| 12 | `api.py` module docstring, `server/app.py` `--model-id` help and `PUBLIC_DESCRIPTION`: `meharsjev-<size>` | `PUBLIC_PREFIX = "genclass-"`; `meharsjev-*` still accepted | +| 13 | `docs/runtime/CONTRACT.md` §10: port of `extension/genclass/src/core/...` in the parent jev repo | in this repo the JS core is `extension/src/core/` | +| 14 | `docs/DEMO.md`, `docs/CONTRACT.md`: project at `/Users/meharkhanna/jev`; `models/`, `runs/`, `data/` present | this repo has `jev_local` at the root and none of those (gitignored) | +| 15 | `docs/SPEC.md` §6.2 signatures (`Packed.attn_mask`, `FastEngine.spans`, `Controller(speech, ..., T, safety)`), `docs/CONTRACT.md` `Registry(...)`, `build_answer(q, d, round_digits)` | code signatures differ (additive `load_fast`, `fast_options`, `center`, `precision`; no `spans`) | +| 16 | `docs/CONTRACT.md` A heuristic nouls "default to 0.5" | 0.5 only when instructions have no content words; 0.4 when cues are not found | +| 17 | `test_demo_midsentence.py` docstring: every test "FAILS on the reviewed code"; `test_demo_safety_review.py` docstring: tests "are expected to FAIL until the corresponding issue is fixed" | the fixes they name appear in code (`silence_gates_for`, terminal/code-editor deny lists, `joined` confirmation rule); pass status (unverified) | +| 18 | `tests/conftest.py` docstring: the full suite (`pytest -q tests`) is runnable on the Linux VMs | in this repo the 20 `test_data_*.py` files fail at collection (no `jev_local/data`), so a plain `pytest -q tests` errors out; use `--ignore-glob` (see Tests) | +| 19 | `training/node.sh` / `training/README.md`: `jev_local/` comes from the parent jev repo at `$HERE/../..` | in this repo `jev_local/` sits at the repo root (`$HERE/..`); `node.sh sync` would copy `<parent of repo>/jev_local`, not this tree | +| 20 | `engine/encoder/heads.py` docstring: noul `p = sigmoid(z / tau)`; `engine/encoder/engine.py` docstring lists only the v1 `calibration.json` keys | `FastEngine` applies `calibrate.calibrate_logits`: `by_header` τ, else `noul_platt` `sigmoid(a·z + b)`, else per-kind τ; v2 keys `by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp` are honoured | +| 21 | `engine/base.py` docstring: answers are built "in `jev_local.api.build_answer`" | defined in `jev_local/confidence.py` -> `build_answer`; `api.py` only imports it | + +Open issues relevant to this scope: + +- `training/NEEDS.md` item 8: curriculum rows contain Python-only float literals (`25.0`), so Python-packed text differs from runtime text on those rows (one of 90 parity requests). +- TS port intentionally lacks multi-pass option batching and `lr`/median answer modes; the runtime must stay within `maxPositions` / `maxTotal`. +- `docs/GENCLASS.md` / `docs/COMPARISON.md` / `docs/PLAN-excel.md` numbers (90.4% vs 66.4%, v2 skill 36.8, staged budgets) describe the computer-use and benchmark lineage, not the runtime model; do not quote them as runtime results. + +## Related docs + +- [runtime/model-host.md](runtime/model-host.md) — the TypeScript model host built from this engine. +- [model-io-contract.md](model-io-contract.md) — situation text -> packed request -> heads -> calibrated answers across runtime, sim and training. +- [training.md](training.md) — `training/` (curriculum, prune, export, eval) that drives `jev_local/train`. +- [sim.md](sim.md) — the simulator that writes CONTRACT-D rows for the stage-2 pilot and the final rounds. +- [extension-and-benchmarks.md](extension-and-benchmarks.md) — Chrome extension (JS core between Python and TS), `jev_local/bench`, scripts. +- [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [repo-map.md](repo-map.md). +- Legacy sources: [SPEC](../SPEC.md), [CONTRACT](../CONTRACT.md), [CONTRACT-v2](../CONTRACT-v2.md), [DEMO](../DEMO.md), [GENCLASS](../GENCLASS.md), [COMPARISON](../COMPARISON.md), [PLAN-excel](../PLAN-excel.md); runtime contract [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md); port notes [packages/runtime/src/model/README.md](../../packages/runtime/src/model/README.md). diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md new file mode 100644 index 00000000..8cc07f81 --- /dev/null +++ b/docs/agents/glossary.md @@ -0,0 +1,445 @@ +# Glossary + +> **Scope:** every term defined in the subsystem docs under `docs/agents/`, the shared runtime vocabulary (op, trigger, situation, hold, tier, ...) and project jargon (workstreams, datasets, training stages, hosts, model names, benchmark names). One alphabetical list. A qualifier in parentheses separates words that mean different things in different subsystems, e.g. *chaos (demos)* vs *chaos (sim)*, *Decision (runtime)* vs *Decision (extension)*. +> **Read this when:** a doc, a status file or the code uses a word you do not know, or two docs seem to use one word differently. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this glossary, a subsystem doc and the code disagree, the code wins. + +Conventions: **Code:** `path/from/repo/root` -> `symbol` (a method is written `Class.method`). **Doc:** the subsystem doc with the full detail. "See *x*" points to another entry of this glossary. Runtime numbers (thresholds, budgets, sizes) are the defaults at 654d822. + +Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](#g) · [H](#h) · [I](#i) · [J](#j) · [K](#k) · [L](#l) · [M](#m) · [N](#n) · [O](#o) · [P](#p) · [Q](#q) · [R](#r) · [S](#s) · [T](#t) · [U](#u) · [V](#v) · [W](#w) · [X](#x) · [Z](#z) + +## A + +- **A/A noise (demos)**: Bug-verdict flips between two Off runs of the same seeds; the noise floor against which *fixed / introduced* counts are read (board demo: 1 of 30 after common random numbers). Doc: [demos](demos.md). +- **action**: The model's answer to the `action` question: one of the actions offered for the trigger, built-ins first (passive first, then the applicable guard/heal actions), then applicable custom actions. The `action` question is asked only when at least 2 actions apply; with one, the runtime treats the answer as `{ <passive>: 1 }`. See *built-in actions*. Code: `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS`, `buildQuestions`; `packages/runtime/src/situation/build.ts` -> `builtinApplicable`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **actionLabel (sim)**: The sim's soft `action` label from counterfactual costs: each action's per-future cost gets a tier premium (or the tie rule), then `p_a ∝ exp(−gap_a / τ_a)`, where `gap_a` is the mean paired cost difference to the best action and `τ_a = 0.10 + 1.0 × SE` of that difference. Code: `sim/src/oracle/cost.ts` -> `actionLabel`, `LABEL`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). +- **ActionRecord**: The record `a<n>` of one non-passive action attempt (built-in, custom or late revert), kept also when it failed (`ok: false`): `decisionId, action, tier, trigger, subject, at, ok, error?, changed, undo?, late?`. Fires the `act` event; `rt.interventions()` returns the last 200. Also called an *intervention*. Code: `packages/runtime/src/types.ts` -> `ActionRecord`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **adapter (store kind)**: A store whose value lives in a state library; writes commit through the proposal's `commit(next)`, and GenClass may write directly (rollback, revert) only when `AdapterIO.set` exists (`writable`). The Redux enhancer and the Zustand middleware create adapter stores. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.adapter`; `packages/runtime/src/types.ts` -> `AdapterIO`, `AdapterHandle`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **adapters (framework)**: Subpath exports owned by UI: `@genclass/runtime/react` (`GenClassProvider`, `useGenClass`, `useGenClassState`, which registers an atom, plus decision/status hooks), `@genclass/runtime/redux` (`genclassEnhancer`) and `@genclass/runtime/zustand` (`genclass` middleware). Code: `packages/runtime/src/adapters/react.ts` -> `useGenClassState`; `packages/runtime/src/adapters/redux.ts` -> `genclassEnhancer`; `packages/runtime/src/adapters/zustand.ts` -> `genclass`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **ambient op**: The op whose work is running now (`Context.cur`). `startOp` uses it as the `cause` of new ops and the hub records it as the writer of state writes. `Context.run` sets it synchronously, `Context.stick` until the end of the macrotask; GenClass does not propagate it through arbitrary promises. Code: `packages/runtime/src/trace/context.ts` -> `Context`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **answer cache**: The `DeciderQueue` cache of provider answers keyed by `fnv1a(trigger + state + questions)` (subject and priority excluded): 64 entries, 30 s TTL, served only while the provider is `ready`, with no latency sample. Code: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **apply (action)**: Passive action of the `mutation` trigger: let the write update the state now (or when the store's queue drains). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **ask (trigger)**: The developer-question trigger. `rt.ask(question, { about, timeoutMs })`, `rt.decide(question, options)` and `rt.situation()` build an `ask` situation about now, an op id or a store outside `trigger()`: no triage, no gate, no `Decision`, queue priority 1. `rt.ask` replaces the questions with `{ answer: q }`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.ask`, `RuntimeImpl.decide`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **ask row / ask probe (sim)**: At `scenario.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records it; `askQuestions` attaches 1–3 programmatic questions with exact labels (`q_*` qids). Code: `sim/src/ask/questions.ts` -> `askQuestions`. Doc: [sim](sim.md). +- **atom (store kind)**: A store whose value GenClass owns (`StoreRec.value`), created by `rt.atom(name, initial, opts)` and by the React hook `useGenClassState`; always writable. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.atom`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **attempt (model load)**: `LoadAttempt { variant, device, error }`: a load plan that failed, listed in `status.attempts`. Code: `packages/runtime/src/model/errors.ts` -> `LoadAttempt`. Doc: [model-host](runtime/model-host.md). +- **auto budget**: See *situation budget*. + +## B + +- **backfill (devtools)**: At mount the overlay replays `decisions(200)`, `interventions(200)` and `history(400)`, and re-derives detections with the literal 0.6 threshold; report sentences are not available for these items. Code: `packages/runtime/src/devtools/index.ts` -> `mountDevtools`. Doc: [devtools](runtime/devtools.md). +- **BandedEncoder**: See *tree layout / BandedEncoder*. +- **base run (sim)**: The scenario run with the real runtime, a recording decider, exploration (ε of 0, 0.08 or 0.2, weighted 4/3/2; ε where the sim sees a problem, ε/4 elsewhere) and ask probes. Its recorded decisions are the candidate decision points. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md). +- **baseline**: Online statistics per op signature, for fetch/XHR ops only (not synthetic, not GenClass): last 64 non-failure latencies (nearest-rank median/p95, need ≥ 5 samples), last 20 outcomes, failure streak, an EWMA error rate (computed but never read), last 128 start times (recent vs usual rate), and per request identity an EWMA gap between identical requests. Memory only; feeds facts, stats lines, the stall timer and `delay` backoff. Code: `packages/runtime/src/learn/baselines.ts` -> `Baselines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **batch (CORE)**: A numbered CORE release of fixes. Batch 1 = SIM requests 1–5; batch 2 = situation budget, `sectionLimits`, auto hold budget, late revert, provider errors fail open; batch 3 = REVIEW's 34 findings, SIM a–f, summed-mass gate, `transient`, compact questions (commit 1a77558, tagged `situation-v1`). Doc: [status-and-known-issues](status-and-known-issues.md). +- **benchmax**: Campaign to beat every published Jev number through each publisher's own harness: 549 targets (154 headline/counted), tracks Z and S, 19 registered adapter specs; no test-split scoreboard exists in the repo. Code: `jev_local/bench/benchmax/__init__.py` -> `Spec`; `scripts/benchmax.py`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **block (action)**: Heal-tier `request` action: do not send; answer with a 503 `Response` (statusText `Blocked by GenClass`, header `x-genclass: blocked`) and end the op `blocked` (XHR: a faked 503). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `blockedResponse`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **branch (packing)**: State + one question header + one of its items. Positions restart per branch (header at `S..`, every item at `S + len(header)..`). In the runtime TS packer `meta.max_len` (default 1536) bounds the state plus the longest branch and `meta.max_total` (8192) the whole sequence; `FastEngine` also bounds positions and splits the rest into passes. The Python `Packer.pack` bounds the total sequence by `max_len` (default 2048) and the trainer's `Packer.pack_split` bounds state + whole question blocks per sequence. Code: `packages/runtime/src/model/packer.ts` -> `Packer`; `jev_local/engine/encoder/tokenize_pack.py` -> `Packer.pack`, `Packer.pack_split`; `jev_local/engine/encoder/engine.py` -> `plan_passes`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **browserClock**: The default `Clock`: `performance.now()` (or a counter), with `setTimeout`, `clearTimeout`, `setImmediate`, `MessageChannel` and `performance` captured at module load so the runtime's own timers never pass through its timers observer; `afterTask` runs via `setImmediate` (Node) or `MessageChannel`. Code: `packages/runtime/src/clock.ts` -> `browserClock`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **bucket (training mixture)**: A mixture group named after the parent directory of a shard file (`data/s3/simA/shard07.jsonl` -> `simA`). Weights in `mix_*.json` are renormalised over the buckets present, so a missing bucket is silently dropped. Code: `jev_local/train/stream.py` -> `_names`, `MixConfig`. Doc: [training](training.md). +- **budget**: Overloaded word; check which one is meant: *situation budget* (characters of situation text), *hold budget* (ms a subject may be held), *budget scale* (shrink factor of the auto situation budget), the packer's token limits `max_len` / `max_total` (see *max_tokens_exceeded*), *pass / pass_tokens* (training tokens per mixture draw) and *budget (sim)*. +- **budget (sim)**: The `situation.budget` the sim passes to the runtime per scenario: 3200, 2000 or 1000 characters (weights 40/30/30), recorded in `meta.budget`. Code: `sim/src/world/scenario.ts` -> `buildScenario`. Doc: [sim](sim.md). +- **budget scale**: `RuntimeImpl.budgetScale`: starts at 1 and is multiplied by 0.8 (floor 0.5, never restored) each time the provider fails with `max_tokens_exceeded`; it applies only to the automatic situation budget. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **built-in actions**: The 15 generic actions in `BUILTIN_ACTIONS` (name, tier, model-facing description), offered per trigger by `TRIGGER_ACTIONS` and applicability: passive `apply`, `send`, `deliver`, `wait`, `ignore`; guard `discard`, `defer`, `coalesce`, `delay`; heal `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`. Each has its own entry here. Code: `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **bypass write**: A write applied at once in the caller's stack without gating: user-sync writes, writes from GenClass ops, stores registered with `hold: false`, writes while gating is off (paused or destroyed), no-op writes and unholdable writes. Errors propagate to the caller. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). + +## C + +- **c01 / c02–c11**: Azure hosts used by TRAIN: `c01` (10.0.0.6) is the workbench and data hub (prune, generate, eval, export); `c02`–`c11` are F80 training nodes (`c02` is R32 rank 0, `c09` is R17 rank 0). The host table lives in `~/.jev-local/azure_hosts` (not in the repo). See *train VM*. Doc: [training](training.md). +- **calibration / calibration.json**: Post-hoc temperature scaling of raw logits read from `calibration.json`: τ by header key, else by `(kind, K-bucket)`, else `τ(K) = a + b·ln K` clamped to `[0.5, 5.0]`, else per kind; a noul uses its header temperature, else a Platt affine, else the per-kind temperature. Trained checkpoints ship all-1.0 temperatures; the real file comes from `training/eval_runtime.py --write-calibration`. Code: `packages/runtime/src/model/calibrate.ts` -> `tauFor`, `noulAffine`, `calibrateLogits`; `jev_local/engine/encoder/calibrate.py` -> `tau_for`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). +- **candidate**: See *permitted set / candidate / mass*. +- **cause / root (op)**: `OpRec.cause` is the id of the op that was ambient (or passed explicitly) when the op started; `root` is the cause's root, or the op's own id when it has no cause. User ops and WS messages are always roots; a retry or hedge op names the original op as its cause. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **chain**: An op and its causal descendants (ops sharing its `root`). In facts, "same chain" means one op is an ancestor-or-self of the other; "the op's chain wrote" (`RuntimeImpl.chainWrites`) means fields written by the op's root chain since the root started. Code: `packages/runtime/src/situation/facts.ts` -> `computeFacts`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.chainWrites`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **chain keys (normalised)**: Keys of `OpRec.chain`: field paths passed through `normalizeFieldPath`, which turns every segment after the store name that is id-like or contains a digit into `:id` (`chat.byId.m21` -> `chat.byId.:id`). Transition shapes, involved fields and transition `SubjectRef.paths` use them. Code: `packages/runtime/src/util.ts` -> `normalizeFieldPath`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **chain revert**: The `rollback` implementation for `transition` and `error` triggers: restore exactly the fields the op's root chain wrote (not overwritten since, with a known earlier value, in a writable store) to their values before the chain's first write; undo restores the replaced values. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.revertChain`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **chain write**: `ChainWrite { kind, len0, len1 }`, accumulated per normalised path in `OpRec.chain` of profiled ops (the writer plus up to 8 ancestors) by `RuntimeImpl.onApplied`; the input to transition profiles. `ChainWriteInfo` (`SitEnv.chainWrites`) is the real-path view used by facts and rollback applicability. Code: `packages/runtime/src/trace/ops.ts` -> `ChainWrite`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **chaos (demos)**: `RouteChaos` knobs (latency, jitter, failRate, commitFailRate, timeoutRate, hangMs, spikeRate, spikeFactor, reorder, outage, offline) plus per-route overrides, applied by the Service Worker mock server; environment only, never app logic. Clean trials use `CLEAN_CHAOS` (45 ± 15 ms, no failures). Code: `demos/src/shared/chaos.ts` -> `RouteChaos`, `resolveChaos`; `demos/src/shared/scenario-kit.ts` -> `CLEAN_CHAOS`. Doc: [demos](demos.md). +- **chaos (sim)**: Per-scenario network regime `calm | normal | flaky | degraded | storm` (weights 2/3/3/3/1) that `makeNet` turns into latency multipliers, transient and network-error rates, outages, slow periods, capacity, rate limits, replica lag and server bugs. Code: `sim/src/world/scenario.ts` -> `buildScenario`, `makeNet`. Doc: [sim](sim.md). +- **chaos trial / clean trial (demos)**: A chaos trial randomises chaos and stresses the simulated user, and measures bug rate; a clean trial uses a calm network and a calm user on which the app is correct, so any executed non-passive action is a *false intervention*. Doc: [demos](demos.md). +- **choice (question kind)**: A typed question answered by a softmax over 2–255 labels (`criteria`: label -> description or `null`); the answer is `{ choice, confidence, probabilities }` with probabilities in criteria order. `diagnosis` and `action` are choice questions; `rt.decide()` is a choice shortcut. Code: `packages/runtime/src/types.ts` -> `Question`, `ChoiceAnswer`; `jev_local/schema.py` -> `ChoiceQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **CI**: There is none: the repo has no `.github/` directory; adding CI is open work in `OPEN_TASKS.md`. Doc: [build-test-release](runtime/build-test-release.md). +- **classify (sim)**: A feature-provided closure on a sim op or sim write, evaluated at decision time, that returns a diagnosis (`stale`, `conflict`, `duplicate`, `expected`) from content bookkeeping; a returned label takes precedence in `diagnose`. Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [sim](sim.md). +- **clear (devtools)**: Overlay-only removal of cards and rows; runtime buffers are untouched and a remount backfills them again. Doc: [devtools](runtime/devtools.md). +- **Clock**: The injected time interface `{ now(), setTimeout(fn, ms), clearTimeout(h), afterTask(fn) }` through which all runtime time and scheduling go. Runtime code never calls `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`, which keeps the sim deterministic. Defaults to `browserClock`; tests use `FakeClock`, the sim its `VirtualLoop` clock. Code: `packages/runtime/src/types.ts` -> `Clock`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **coalesce (action)**: Guard-tier `request` action, fetch only: do not send; wait (≤ 8 s) for the buffered response of an identical request that is in flight or settled ≤ 2 s ago, and answer a copy marked `x-genclass: coalesced`. Offered only when `ResponseCache.shareable` finds such a request. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `ResponseCache`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **COI (demos)**: Cross-origin isolation: the demos' Service Worker adds COOP `same-origin`, COEP `require-corp` and CORP `same-origin` headers so `crossOriginIsolated` is true and WASM threads are available to the model (`?coi=0` disables it). Doc: [demos](demos.md). +- **common random numbers (CRN)**: Pairing device that gives compared runs the same random draws. In the sim, counterfactual futures share one salt across all actions; in the demos, `World.rngFor(key)` gives the n-th occurrence of the same logical request or live event the same RNG in every mode, so Off/Guard/Heal comparisons measure GenClass rather than re-rolled network. Code: `sim/src/gen/trajectory.ts` -> `pointCosts`; `demos/src/server/core.ts` -> `World.rngFor`. Doc: [sim](sim.md), [demos](demos.md). +- **compact questions**: At a situation budget ≤ 1400 characters (`COMPACT_QUESTIONS_BUDGET`) every option description becomes `null` (bare labels), except vocabulary overrides of ≤ 24 characters; custom-action and plugin-label descriptions are dropped too. Instructions are unchanged. Code: `packages/runtime/src/situation/questions.ts` -> `buildQuestions`, `COMPACT_QUESTIONS_BUDGET`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). +- **COMPACT_BUDGET vs COMPACT_QUESTIONS_BUDGET**: Two distinct constants. `COMPACT_BUDGET` (1100, `serialize.ts`, exported from the root) is the budget at and below which section limits are smallest; `COMPACT_QUESTIONS_BUDGET` (1400, `questions.ts`, not exported from the root) is the threshold for compact questions. Code: `packages/runtime/src/situation/serialize.ts` -> `COMPACT_BUDGET`; `packages/runtime/src/situation/questions.ts` -> `COMPACT_QUESTIONS_BUDGET`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md). +- **consistency pair**: A `meta.pairs` entry (`neg`, `noul_choice`, `score_choice`) that the v2 training loss penalises to keep related answers coherent. Code: `jev_local/train/losses.py` -> `consistency_terms`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **consistent snapshot**: A deep clone of all stores taken at a settled point where no violation newly broke (lingering ones allowed); `RuntimeImpl.snaps` keeps the last 8. Inconsistency `rollback` writes the last one back. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`, `RuntimeImpl.rollback`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **consultable**: `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists and its `status.state` is `"ready"` or `"off"`. When false, every trigger runs its passive action without building a situation and no write is held; a default install today reaches this state because the unpublished model ends in status `error`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.consultable`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [status-and-known-issues](status-and-known-issues.md). +- **consumed prefix (extension)**: Transcript words already acted on; later partials must still start with them (fillers and chain words ignored) or the stream freezes (`revised_after_act`), so an action never runs twice. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **CONTRACT (legacy)**: `docs/CONTRACT.md` (the jev-local v0.1 build contract per workstream A–H, whose section D defines the CONTRACT-D row format), with `docs/CONTRACT-v2.md`, `docs/SPEC.md` and the other jev-local design docs. Legacy: runtime CONTRACT §1 says not to edit them. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **CONTRACT (runtime)**: `docs/runtime/CONTRACT.md`, the binding build contract owned by the lead: §0 ground rules (no hardcoded bug rules, one situation implementation shared with the sim, determinism through the injected `Clock`, sim and demos never read each other, no runtime dependency besides `onnxruntime-web`, builds on the VM), §0.5 product principles, §1 layout and owners, §2–§12 spec (§8 = the policy gate), §13 approved additions. Last edited in a53dd38, before batch 3, so it lags the code. Doc: [status-and-known-issues](status-and-known-issues.md). +- **CONTRACT-D row**: One JSONL training example `{id, split, family, state, questions, labels, meta}` (legacy CONTRACT section D, referenced by runtime CONTRACT §11), written by the sim and the curriculum and read by the trainer. Labels: choice `{label}` or `{dist}`, noul `{p}`, score `{level}` or `{dist}`; a qid without a label is packed but unsupervised. Code: `sim/src/types.ts` -> `Row`, `Label`; `jev_local/train/train.py` -> `parse_target`. Doc: [model-io-contract](model-io-contract.md), [sim](sim.md), [training](training.md). +- **Controller (extension)**: The extension's incremental voice decision loop (debounce, coalescing, stale rule, execute, consume, re-decide), a port of `jev_local/harness/controller.py`. See *harness (extension)*. Code: `extension/src/core/controller.js` -> `Controller`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **Controller (runtime)**: The seam between the decision flow and one trigger subject: `passive()` lets the subject proceed unchanged; `run(action)` performs a built-in action and returns `ActionEffect { changed, undo? }`, or throws/rejects, after which the passive action runs and the attempt is recorded `ok: false`. Held mutations also have `revertable()` / `revert()` for a late revert. Code: `packages/runtime/src/decide/exec.ts` -> `Controller`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **CORE (workstream)**: Owns `packages/runtime/**` except `packages/runtime/src/{model,devtools,adapters}/**`, including the situation wording and `packages/runtime/src/types.ts`; writes `packages/runtime/STATUS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). +- **cost (sim)**: `runCost`, a run's cost relative to the ideal run: 1.0 × D(t) integrated over the 10 s after the decision + 4.0 × final client divergence + server damage (25 per extra/missing item, 6 per differing field or counter unit) + 0.8 × relation-violation seconds + 2.0 × relations still violated at the end + 1.5 × shown errors + 1.0 × uncaught errors + 0.08 × extra requests + 0.25 × pending seconds; "final" is decision + 15 s. Code: `sim/src/oracle/cost.ts` -> `runCost`, `W`. Doc: [sim](sim.md). +- **counterfactual run / counterfactual cost (sim)**: A sim re-run with a forced map (explored choices before decision `k`, action `a` at `k`, passive after), stopped at `t_k + 15 s` and required to reproduce the base run's fingerprints up to `k`; its `runCost` against the ideal run is the counterfactual cost of `a` at `k`. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `pointCosts`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). +- **createRuntime**: The headless entry point (tests, sim, SSR): builds a `RuntimeImpl`, creating and owning a model host only when `decider` is `undefined` and `model` is an object. It can throw on malformed options and never sets `GenClass.runtime`. Code: `packages/runtime/src/index.ts` -> `createRuntime`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **CU / GEN**: The two sets of the GenClass-vs-Jev head-to-head: CU = synthetic computer-use harness examples (the extension's domain), GEN = generic questions from task families held out of training. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **cur1 / cur2 / cur3 / cur4**: Curriculum datasets from `training/curriculum/generate.py`: `cur1` 800k train rows, all varied style (seed 1); `cur2` 400k, `--p-runtime 0.6` with the pre-freeze `rt.py` (seed 2); `cur3` 300k stage-2 replay, `--p-runtime 0.8`, pre-freeze wording (seed 4); `cur4` 300k final replay in the frozen `situation-v1` wording, `--p-runtime 0.8` (seed 5). `--p-runtime` is the share of decision rows rendered runtime-exact. Doc: [training](training.md). +- **custom action**: An `ActionDef` added with `rt.action(def)`, a plugin's `actions` or the `plugins` option. Offered when `def.on` includes the trigger, the name is new and `applicable(draft)` is true; gated at its own tier (default `heal`); runs inside a GenClass op; `ctx.builtin(name)` may run an offered built-in (re-checked for mode, deny/allow, pause and rate limit, not thresholds); if no built-in took over, the passive action runs afterwards. Code: `packages/runtime/src/types.ts` -> `ActionDef`, `ActionContext`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). + +## D + +- **D(t) (sim)**: Weighted client divergence of a run's stores from the ideal run's at the same time: each field contributes `w × d` with `d ∈ [0, 1]`, lists compared as multisets of item content. Integrated over the 10 s after a decision in the cost. Code: `sim/src/oracle/cost.ts` -> `clientDist`, `divergenceArea`. Doc: [sim](sim.md). +- **data-genclass-ignore**: Attribute that makes the DOM user observer skip events from inside the marked subtree, crossing shadow roots; the devtools host carries it. Code: `packages/runtime/src/observe/dom-user.ts` -> `ignoredEvent`. Doc: [devtools](runtime/devtools.md), [observe-and-trace](runtime/observe-and-trace.md). +- **DeciderQueue**: The single-flight priority queue in front of the `DecisionProvider`: highest priority then oldest first; ≤ 32 queued (overflow drops the lowest-priority, oldest item); deadlines; a 10 s runtime-side timeout when there is no deadline; the answer cache; the last 20 provider latencies for the auto hold budget. Every fail-open path resolves `null`, never rejects. Code: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **Decision (extension)**: The extension controller's per-update result `{verdict, action, reason, seq, retryInMs, answers, latencyMs, risk}`. See *verdict (extension)*. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **Decision (runtime)**: The record `d<n>` made for every model answer to a trigger that reaches `onDecision` (never for `ask`/`decide`, while loading, for triage-skipped triggers or for failed queue items): diagnosis and its probabilities, `action` (the action that ran, else the model's top choice), `ran` (what actually executed, passive included), `executed`, `reason`, `candidate`, `mass`, facts (≤ 12), `answers`, `subjectRef`. `Detection` is a type alias. Code: `packages/runtime/src/types.ts` -> `Decision`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **decision point (sim)**: `DecisionRec`: one `evaluate` call recorded in the base run (`k` = 0-based index, `t`, `trigger`, `state`, `questions`, `actions`, `chosen`, `explored`, `diagnosis`, `subject`, `fp`); a trajectory labels up to `maxPoints` of them. Code: `sim/src/run/runner.ts` -> `DecisionRec`. Doc: [sim](sim.md). +- **Decision Score (jevbench)**: `clip(1 − mean Brier / mean prior Brier, −1, 1)` per dataset. Code: `jev_local/bench/metrics.py` -> `decision_score`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **DecisionProvider**: The only seam between the runtime and a model: `{ status, ready(), evaluate(req), onStatus?(fn), dispose?() }`. Implemented by the model host, the test deciders, the sim's recording decider and `failedProvider`; passed as `options.decider`, which wins over `options.model` (`null` = no model). `evaluate` receives `EvaluateRequest { trigger, state, questions, priority?, subject?, timeoutMs? }`. Code: `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [model-io-contract](model-io-contract.md). +- **decontamination stage 1 (benchmax)**: Name-level exclusion of training sources per track. Code: `jev_local/bench/registry.py` -> `is_excluded`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS item 8; no `runtime-model-v0.1.0` tag in the repo; the URL was not checked), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published at 654d822, so a default `GenClass.init()` ends with model status `error` and only observes. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **defer (action)**: Guard-tier `mutation` action, offered while the write was deferred fewer than 2 times: wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **delay (action)**: Guard-tier `request` action (fetch and XHR): wait `min(250 × 2^failStreak, 8000)` ms, where `failStreak` is the signature's current failure streak, then send. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **deliver (action)**: Passive action of the `failure` trigger: hand the original `Response` or rejection to the app. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **delta signature**: `deltaOf` output that is equal for "the same change applied again": `n:<diff>` (numbers), `a:+added|-removed` (array multiset diff), `o:<hash>` (pure reorder), `c:+k/~k/-k` (collections), `v:<hash>` (anything else), `x:removed`. Feeds `RecentChange.key` and the repetition facts. Code: `packages/runtime/src/state/fields.ts` -> `deltaOf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **demo mode**: `GcMode = "off" | "guard" | "heal"`. Off = `GenClass.init({ mode: "observe", model: false })`, the baseline; Guard and Heal init with that mode and `model: { baseUrl, preload: "eager" }`. Not the same as `?genclass=off`, the runtime kill switch that installs nothing. Code: `demos/src/shared/types.ts` -> `GcMode`; `demos/src/shared/genclass.ts` -> `startGenClass`. Doc: [demos](demos.md). +- **DEMOS (workstream)**: Owns `demos/`; writes `demos/NEEDS.md`, `demos/README.md` and `demos/results*.{md,json}`. Doc: [status-and-known-issues](status-and-known-issues.md), [demos](demos.md). +- **describeElement**: Public helper returning `role "name"` for a DOM element (e.g. `button "Place order"`); the name comes from aria-label, labelledby, labels, text, placeholder, title, name, button value or id (≤ 40 chars), never from a typed value. Code: `packages/runtime/src/observe/dom-user.ts` -> `describeElement`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **detached preview / unholdable**: When a guarded functional updater mutated the stored value in place, the hub clones the result and restores the live value (`restoreInPlace`) so the write can still be held; if that fails the write is *unholdable* and applies at once. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **detection**: A `Decision` whose diagnosis is not `expected` and whose diagnosis probability is ≥ `thresholds.report` (0.6), whether or not an action ran. Fires the `detect` event, and a `[GenClass] Flagged …` report when no action ran. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **detection card (devtools)**: `article.card.det`, keyed by decision id, for a detection that did not run a non-passive action; it moves to Interventions when an `act` arrives for that decision. Doc: [devtools](runtime/devtools.md). +- **diagnosis**: The `diagnosis` question (choice, header "What is happening here?") asked on every trigger except `ask`, over the diagnosis vocabulary: by default `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`, `expected` always first. The policy gate requires the top diagnosis to differ from `expected` (`requireDiagnosis`). In sim rows the label is a hard label from the sim's own knowledge. Code: `packages/runtime/src/situation/questions.ts` -> `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). +- **diagnosis-only row (sim)**: A decision with fewer than 2 applicable actions (so no `action` question): the row carries only a `diagnosis` label and no counterfactuals; at most 3 per trajectory. Doc: [sim](sim.md). +- **discard (action)**: Guard-tier `mutation` action: drop the held write and keep the current state (the `set` caller is not notified); undo applies the write on top of the current value. Also the action behind a late revert. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **draft (SituationDraft)**: The structured view of a situation handed to plugin `facts()` and `ActionDef.applicable()`: trigger, subject, now, op, root, stores, mutation/request/failure/error/invariant details, facts, in-flight ops. Code: `packages/runtime/src/types.ts` -> `SituationDraft`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). + +## E + +- **Engine**: In the runtime, `Engine` (`engine.ts`) = `Packer` + an ORT session + calibration -> typed answers, building exactly the inputs `meta.json` declares. In `jev_local`, `Engine` is the Python engine protocol (`name`, `max_tokens`, `supports`, `count_tokens`, `evaluate` -> `EngineResult` of unrounded `RawDist`s) that `FastEngine` implements. Code: `packages/runtime/src/model/engine.ts` -> `Engine`; `jev_local/engine/base.py` -> `Engine`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). +- **episode / muted**: The episode is the set of violation ids at the previous settled point; only violations not in it are fresh, so an inconsistency is raised once per episode. Muted ids are violations whose rollback was undone; they are not raised again until they hold once more. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **error (trigger)**: Raised by `rt.reportError` (also by the errors observer, and by app errors the hub catches while applying a held write); not held, priority 0; actions `ignore` (passive) and `rollback` (a chain revert, offered only when an ambient op existed). Fact E1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.reportError`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **ettin**: The `jhu-clsp/ettin-encoder-*` family of ModernBERT-architecture encoders (MIT) behind every model here: 17m (d 256, 7 layers) for R17; 32m (d 384, 10 layers) for GenClass 0.1 and R32; 68m for the v2 benchmax models. Doc: [training](training.md), [genclass-model-lineage](genclass-model-lineage.md). +- **EventLog / RtEvent**: Ring buffer of `RtEvent { seq, t, kind, name, op?, cause?, data? }`, size `max(16, historySize ?? 500)`; kinds `user, op.start, op.end, state, error, nav, perf, storage, custom, decision, action`. `rt.history(n)` reads it and situation timelines are rendered from it; `touch()` re-notifies after a typing burst updates an event in place. Code: `packages/runtime/src/trace/events.ts` -> `EventLog`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **events (runtime)**: `rt.on(type, fn)` types: `decide` (every runtime Decision), `detect` (detections), `act` (every non-passive action attempt), `event` (every RtEvent), `status` (model status changes and every `setMode` call), `report` (every report, even with `report: "silent"`). Listener exceptions are swallowed. Code: `packages/runtime/src/types.ts` -> `RuntimeEvents`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **evidence (devtools)**: The expandable block of a card, built from `runtime.explain(id)` with a fallback to the `Decision`: facts, model answers (top 6 bars per question), timeline, the exact situation text, metadata and a deny hint. Doc: [devtools](runtime/devtools.md). +- **expected**: The "nothing is wrong" diagnosis label; see *diagnosis*. +- **expired**: The hold-budget timer fired before the decision arrived, so the passive action already ran; a later gate-passing `discard` on a held write may still late-revert it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **explain**: `rt.explain(id)` with a decision id `d<n>` or an action id `a<n>`: returns the message, decision, exact situation text, facts, timeline, answers and, if an action ran, the action and its `changed` sentence; `null` for unknown or evicted ids. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.explain`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). + +## F + +- **F80**: The Azure VM size of the TRAIN nodes (`c01`, `c02`–`c11`), about $5.46/h per node (`training/LOG.md`); training runs use 8 ranks × 10 threads per node. Doc: [training](training.md). +- **facade**: `GenClass` (named and default export), the browser singleton around `createRuntime`. `GenClass.init(options)` never throws (it falls back to an inert runtime), is idempotent (a second call returns the first runtime and ignores its options), applies the kill switch and loads the local model by default; `GenClass.runtime` and `GenClass.destroy()` complete it. Code: `packages/runtime/src/index.ts` -> `GenClass`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **fact**: `Fact { text, kind, neutral }`: a uniform English sentence computed per trigger by `computeFacts`; `neutral: false` makes the situation salient. Ordered non-neutral first, then by kind rank (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), capped at 12 (`MAX_FACTS`). Plugin facts are always neutral. Code: `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **fail open**: The universal fallback: no provider, provider not ready, any provider error, queue overflow, an expired deadline, hold-budget expiry or a throwing action all run the passive action, so a missing or slow model never blocks the app. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [model-host](runtime/model-host.md). +- **failure (baseline)**: A completion whose `EndOpts.failure` is set: network error, timeout, HTTP 5xx, 429 or 408 (a 404 is not a failure). Failures feed fail streaks and outcomes, never latency samples. Code: `packages/runtime/src/observe/fetch.ts` -> `FAILURE_STATUS`; `packages/runtime/src/learn/baselines.ts` -> `Baselines.end`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **failure (trigger)**: Raised when a request fails (see *failure (baseline)*) before the app sees the failure. Fetch failures go through the holdable failure gate (priority 2 when held), but are held only when a non-passive failure action is permitted: `retry` and `serve_cached` are heal tier, so in the default `guard` mode (and in `observe`) the failure is delivered at once and decided in the background (priority 1, 5 s deadline) unless a guard-tier custom action applies. XHR failures are never held (priority 1) and are detection-only. Actions `deliver` (passive), `retry`, `serve_cached`; fact F1 makes it always salient. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **fake runtime (sim)**: `createFakeRuntime`, a crude test double of the runtime used by default in the sim's vitest suites (`SIM_RUNTIME=real` switches to the real one). Its rows are marked `meta.runtime: "fake"`; `gen.js` uses it only with `--allow-fake`. Code: `sim/src/run/fake-runtime.ts` -> `createFakeRuntime`. Doc: [sim](sim.md). +- **FakeClock / FakeServer**: Runtime test kit: `FakeClock` is a virtual clock starting at `t = 1000` with `advance(ms)`, `flush()` and `runAll(maxMs = 120000)`; `FakeServer` is a virtual HTTP server exposed as `fetch` (routes keyed `METHOD pathname`, default latency 50 ms, unknown routes 404) that records hits. Code: `packages/runtime/test/helpers.ts` -> `FakeClock`, `FakeServer`. Doc: [build-test-release](runtime/build-test-release.md). +- **false intervention (demos)**: One `act` event (an executed non-passive action, including failed attempts and late reverts) on a clean trial. A different metric from TRAIN's *FIR*. Doc: [demos](demos.md). +- **family (sim)**: Program family = the sorted feature kinds joined by `+` (e.g. `cart+search`); a sim row's `family` is `<program family>/<trigger>`, and families whose hash falls in the first 17% go to test. Curriculum rows use `cur/<trigger>/<case>` families instead. Code: `sim/src/world/scenario.ts` -> `familyHeldOut`, `splitOf`. Doc: [sim](sim.md), [training](training.md). +- **FastEngine**: The Python model engine ("jev-local-fast"): an ettin encoder with typed heads over marker tokens and one packed sequence per request with block attention, so answers are exactly invariant to option order and to other questions. Checkpoints are `backbone/`, `heads.safetensors`, `calibration.json`, `meta.json`. Code: `jev_local/engine/encoder/engine.py` -> `FastEngine`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **feature combinator (sim)**: A `FeatureDef` (`make`, `pattern`, `server`, `client`, `session`, optional `external`, `relations`) from which scenarios build random apps; 15 kinds: search, editor, form, cart, toggle, counter, poll, board, chat, settings, nav, list, bulk, auth, benign. Code: `sim/src/app/feature.ts` -> `FeatureDef`; `sim/src/app/features/index.ts` -> `FEATURES`. Doc: [sim](sim.md). +- **feed pause (devtools)**: Overlay-only freeze of list, activity and Now rendering; intake and counters continue and "N new" is counted. Unrelated to `runtime.pause()`. Doc: [devtools](runtime/devtools.md). +- **field / path / leaf**: A store value is flattened into dotted fields `store.k1.k2` (at most 4 key levels). Arrays, plain objects with more than 32 keys or none, and non-plain objects are one leaf each; a store has a soft cap of 200 fields. `Leaf { value, hash, kind, len, elems?, keys?, khash?, src? }`. Code: `packages/runtime/src/state/fields.ts` -> `flatten`, `Leaf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **FieldState / FieldHist / LogEntry**: Per-field bookkeeping in the hub: version `v`, writer op, `t` and `seq`; the last 16 writes with before/after values (history); the last 512 writes as compact entries (log). Facts read field versions from them. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **final round 1 / 2**: TRAIN's final training of R17 and R32 on frozen-format data. Round 1 = SIM phase A plus `cur4`/`cur1`/`gen` replay (`mix_final1`), launched 2026-10-08 00:06–00:12 UTC, with no results in the repo; round 2 = phase A + B with longer schedules, planned. Doc: [training](training.md), [status-and-known-issues](status-and-known-issues.md). +- **FIR**: False-intervention rate in TRAIN's evaluation: gate fires on passive-best rows ÷ passive-best rows, per mode (guard, heal), with the runtime's policy gate mirrored in Python. Code: `training/eval_runtime.py` -> `decision_metrics`. Doc: [training](training.md). +- **fixed / introduced (demos)**: Paired with Off on the same chaos seed: *fixed* = Off had the bug and the mode did not; *introduced* = Off was fine and the mode had the bug. Read against A/A noise. Code: `demos/src/shared/aggregate.ts` -> `summarizeMode`. Doc: [demos](demos.md). +- **FIXTURES_FROM_MODEL**: Flag in the model test helpers, true when `requests.json`, `pack_fixtures.json` and `torch_fixtures.json` exist in the model directory (written by `training/export_runtime.py`); the unit parity tests then use them instead of the v0.1 fixture set (browser specs never do). Code: `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL`. Doc: [build-test-release](runtime/build-test-release.md). +- **forced**: `BuiltSituation.forced`: a standing question with `always: true` is registered for the trigger, so the model is consulted even when no fact is salient. Not model input. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **fp (fingerprint, sim)**: `JSON.stringify([trigger, state, questions])` of a decision. A counterfactual run must reproduce the base run's fp for every decision up to `k`; otherwise the point is dropped as `prefix-mismatch`. Doc: [sim](sim.md). +- **fragment / pass (FastEngine)**: When a choice/score question's header and items exceed the room left after the state, `plan_passes` splits it into contiguous option fragments (header repeated) packed into passes that each repeat the state; fragment logits are concatenated and calibrated with one softmax, so the result equals a single pass. Python only: the runtime packer is single-pass. Code: `jev_local/engine/encoder/engine.py` -> `plan_passes`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **freeze / quiet / settle (demos)**: After a trial's steps the harness freezes scripted world activity, waits for quiet (no request in flight and no pending SSE delivery for `idleMs`, default 700 ms, timeout 20,000 ms) unless the demo sets `settle: false`, then waits 2,500 ms (350 ms with `settle: false`) so held writes and late reverts land before the oracle scores. Code: `demos/src/server/core.ts` -> `World.quiet`. Doc: [demos](demos.md). +- **frozen runtime**: `packages/runtime/src` unchanged since tag `situation-v1`. Changing anything that reaches model input needs the lead, SIM and TRAIN; only the runtime source is frozen (sim, training and demos changed after the tag). Doc: [status-and-known-issues](status-and-known-issues.md). +- **future (sim)**: One re-seeded continuation after a decision point. Future 0 keeps the base run's draws; futures 1..K−1 re-seed network, push, model-latency and external-event draws after the decision with a salt shared by all actions (common random numbers). K = 3, but futures beyond 0 run only when some non-passive action beats passive by more than 0.05 in future 0. Code: `sim/src/gen/trajectory.ts` -> `pointCosts`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). + +## G + +- **gated (`NetHost.gated`)**: `!paused && !destroyed && !op.genclass`. Only gated fetch/XHR ops raise request, failure or stall triggers, are held or are stall-watched. Code: `packages/runtime/src/decide/exec.ts` -> `NetHost`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **gen / cu (buckets)**: GenClass 0.1 (v1) synthetic training data (`data/gen`, a slice of `data/cu`: generic and computer-use examples) mixed into runtime-model training as replay only. Doc: [training](training.md). +- **GenClass**: Project name: the GenClass 0.1 model and Chrome extension of the jev-local era, and now `@genclass/runtime`. In code, the facade object `GenClass` exported by the runtime. See *facade*, *GenClass 0.1*. +- **GenClass 0.1 (v0.1 model)**: The v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers, unpruned vocabulary) exported as ONNX `genclass-model-0.1.0` for the Chrome extension and published at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. A general typed-decision classifier, not trained for runtime decisions; the demos and model tests use it and R32 is initialised from it. Doc: [genclass-model-lineage](genclass-model-lineage.md), [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **GenClass op**: An instant op of kind `genclass` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause `null`) for undo, revert, rollback, resync and custom actions. Writes and requests inside it are never gated and are excluded from baselines and profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runAsGenClass`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **genclass-<size> / meharsjev-<size>**: Model ids allowed for benchmax runs (`genclass-<size>`, legacy `meharsjev-<size>`); `jev-*` and `typesafe/*` ids are rejected (W10). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **genclass-runtime (CLI)**: The package's bin: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info <dir>` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`. Doc: [model-host](runtime/model-host.md). +- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`); `0.1.0-alpha.0` is published (per `OPEN_TASKS.md`). Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md). +- **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0. Only `packages/runtime-model/MODEL_CARD.md` exists. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). +- **`@genclass/sim` / `@genclass/demos`**: The private workspaces `sim/` and `demos/`. Both depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first. Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). +- **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `<repo>/.cache-model`, filled with `genclass-runtime fetch-model <dir> --from <v0.1 release URL>` (ask first; the default `--from` is unpublished)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). +- **GENCLASS_REPLACE**: `"@@genclass/REPLACE"`, the Redux action the enhancer uses for GenClass's whole-state writes (rollback, revert); it never reaches the app reducer. Code: `packages/runtime/src/adapters/redux.ts` -> `GENCLASS_REPLACE`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **GenClassUnavailableError**: The error `rt.ask()` / `rt.decide()` reject with when no model can answer; `reason` is `destroyed`, `off`, `timeout` or `error` (with `timeoutMs` set, a raw provider load error can escape instead). Provider errors never escape a trigger. Code: `packages/runtime/src/errors.ts` -> `GenClassUnavailableError`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **guard (store kind)**: A store whose value the app owns behind `get` / `set` / `subscribe` (`rt.guard(name, io, opts)`); external changes arrive through `subscribe` and are recorded, never held; always writable. Not the same as the guard mode or tier (see *mode*, *tier*). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.guard`; `packages/runtime/src/types.ts` -> `StoreIO`. Doc: [state-and-adapters](runtime/state-and-adapters.md). + +## H + +- **harness (extension)**: The extension's incremental voice decision loop (`extension/src/core/controller.js` with the policy, safety, stream and spans modules) and its Python original `jev_local/harness/*` (macOS voice computer use); the JS core is parity-tested against fixtures generated from the Python. Code: `extension/src/core/controller.js` -> `Controller`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). +- **header / item**: A question's header is its `instructions` text (a default when missing); its items are the options (choice: `label` or `label: desc`), the levels (score) or the true/false criteria (noul). Question ids are never shown to the model. Code: `packages/runtime/src/model/serialize.ts` -> `questionBlock`. Doc: [model-io-contract](model-io-contract.md). +- **header key**: `sha1(header)[:12]`, the key of `calibration.json` `by_header` (e.g. `041ccfa6318c` = "What is happening here?"). Code: `packages/runtime/src/model/calibrate.ts` -> `headerKey`. Doc: [model-io-contract](model-io-contract.md). +- **heads**: The graph outputs `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` (raw, τ = 1), computed from marker hidden states: choice and score MLPs over `[h_Q; h_item; h_Q*h_item]`, noul over `[h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F]` with a sigmoid. Code: `jev_local/engine/encoder/heads.py` -> `DecisionHeads`; `packages/runtime/src/model/engine.ts` -> `Engine`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). +- **hedge (action)**: Heal-tier `stall` action for an idempotent, replayable fetch GET: send a second identical request (op detail `(hedge)`, cause = the original); the first good answer reaches the app. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **held-out domains / templates (curriculum)**: Curriculum test rows use only the 13 held-out app domains of 62 (`TEST_DOMAINS`), and the trailing `max(1, round(0.2 n))` entries of every template list with at least 4 entries appear only in test rows. See *split (sim)* for the sim's hold-outs. Code: `training/curriculum/vocab.py` -> `TEST_DOMAINS`; `training/curriculum/fmt.py` -> `pick_from`, `held_count`. Doc: [training](training.md). +- **hold / held**: Making a subject wait for the model's decision: a store write (`mutation`), a fetch/XHR request (`request`) or a fetch failure (`failure`). A trigger holds only when it is holdable, the runtime is consultable, the situation is salient, the model is ready and the mode/policy permits at least one non-passive action (see *waits*); when the hold budget expires the subject proceeds with the passive action. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **hold budget**: The longest a held subject waits for the decision (after a gate-passing answer the action itself may keep it waiting: `delay`/`coalesce` ≤ 8 s, `retry` backoff ≤ 5 s, custom actions unbounded): `policy.holdBudgetMs`, default `"auto"` = `clamp(round(1.5 × median of the last 20 provider latencies, or the model's warmupMs before any), 150, 800)` ms, and 300 ms when neither is known; a number is used as `max(0, n)`. `rt.holdBudgetMs()` returns the current value. Code: `packages/runtime/src/decide/policy.ts` -> `holdBudget`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **holdable**: A trigger raised with `TriggerOpts.hold: true` (mutation, fetch and async-XHR request, fetch failure); it is actually held only when it *waits*. Not to be confused with an *unholdable* write. See *hold / held*, *waits*. Code: `packages/runtime/src/decide/exec.ts` -> `TriggerOpts`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **hooks (RuntimeHooks)**: `createRuntime({ hooks })`: `opCreated(op)` (sync, in `startOp`) and `mutationProposed({ id, store, paths, cause?, changes })` (sync, before gating); exceptions are swallowed. The sim uses them for subject correlation and the demos' trace run for proposals. Code: `packages/runtime/src/types.ts` -> `RuntimeHooks`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). + +## I + +- **ideal run (sim)**: `runScenario(scn, { ideal: true })`: no runtime, `IDEAL_PROFILE` network (0 latency, no failures or chaos), accidental and conditional steps skipped, app duplicates share the original's result. It is the intended outcome every cost is measured against. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/net/network.ts` -> `IDEAL_PROFILE`. Doc: [sim](sim.md). +- **ignore (action)**: Passive action of `inconsistency`, `transition` and `error`: leave the state as it is. Code: `packages/runtime/src/situation/questions.ts` -> `PASSIVE`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **in_flight (section)**: The situation section listing in-flight ops other than user ops and the subject op, same signature first, then same root, then by start time: `<opPhrase> (#id) <secs> so far[, by #cause]`. Code: `packages/runtime/src/situation/build.ts` -> `inFlightLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **inconsistency (trigger)**: Raised at a settled point for fresh violations of learned or developer invariants (once per episode); not held, priority 1; actions `ignore`, `rollback` (to the last consistent snapshot), `resync`. Fact I1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseInconsistency`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **inert runtime**: A `RuntimeImpl` with every observer off (`ALL_OFF`), no decider, `report: "silent"`, mode `observe`, produced by the `off` kill switch and by `GenClass.init`'s fallback after a throw. Stores, `op`, `emit` and `user` still record; nothing is held or asked. Code: `packages/runtime/src/index.ts` -> `GenClass`, `initUnsafe`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **instant op**: An op created already ended (`end = start`, status `ok`) and never in flight: user actions, timer ticks, WS messages and sends, GenClass actions. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **intent (sim)**: `Intent` in `Knowledge`: one user step with the slot (`key`) it targets, `mode` `replace` (a newer replace-intent on the same key supersedes older ones, making them stale) or `accumulate`, and an `accidental` flag (double click, impatient re-click) with `repeatOf`. Code: `sim/src/oracle/knowledge.ts` -> `Intent`. Doc: [sim](sim.md). +- **intervention**: A non-passive action that ran (or was attempted); see *ActionRecord*. +- **intervention card (devtools)**: `article.card.act`, keyed by `ActionRecord.id`: shows the `changed` note, an Undo button when `ActionRecord.undo` exists, and evidence. Doc: [devtools](runtime/devtools.md). +- **invariant**: A relation over store fields checked at settled points. Developer invariants come from `rt.expect(name, predicate)`; learned invariants are mined from 9 templates (`type, nonnull, nonneg, eq, len, sum, sumprod, in, unique`) over non-dynamic paths, learned after 3 involved, non-trivial settled points (6 for `nonnull`) and dropped for good if falsified while learning. A freshly broken invariant raises `inconsistency`. Code: `packages/runtime/src/state/invariants.ts` -> `InvariantMiner`, `LEARN_AFTER`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **involved stores**: The registered stores a situation is about: mutation -> its store; inconsistency -> stores of violated fields; transition -> stores of chain keys; error -> stores changed since the op started; request/failure/stall -> stores this signature's chains wrote (`storeWriters`); ask -> the asked store. They select state lines and timeline relevance and decide rollback/resync applicability. Code: `packages/runtime/src/situation/build.ts` -> `involvedStores`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). + +## J + +- **Jev**: TypeSafe's hosted typed-decision model and API ("System One", `POST /v1/systemone`): `{state, model, questions}` in, `{model, answers, usage}` out, with `choice`, `noul` and `score` questions. This repo is not affiliated: `jev_local` re-implements the wire format, the runtime keeps its shape (`JevState`, `Question`, `Answer`), and the benchmarks compare against it. Doc: [genclass-model-lineage](genclass-model-lineage.md), [extension-and-benchmarks](extension-and-benchmarks.md). +- **jev-local / jev_local**: The predecessor Python project (pip package `jev-local` 0.1.0 in `jev_local/`): FastEngine model, Jev-wire-compatible HTTP server, macOS voice harness, benchmarks and the trainer that `training/` still drives (`jev_local/train/train.py`). Its serializer, packer, calibration and answer math are the reference that `packages/runtime/src/model` ports. `~/.jev-local/` on the original Mac holds the Azure host table. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **jevbench**: Pre-registered v1 benchmark: 25 public test datasets in 7 areas plus clean dev and reference rows, scored with the skill and Decision Score indices and a 3-part claim rule; test splits are read once per release (see *M0*). Code: `jev_local/bench/registry.py`; `scripts/jevbench.py`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **JevState**: The situation state object the model reads, `Record<string, unknown>`. Runtime situations use 7 keys in fixed order `app, trigger, facts, in_flight, timeline, state, stats`, each a string or a string array (one line each), empty arrays as `"none"`. Code: `packages/runtime/src/types.ts` -> `JevState`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`. Doc: [model-io-contract](model-io-contract.md). +- **jump-back (demos)**: Board-demo metric: a card the user moved shows its previous column again 400 ms–5 s after the server accepted the move, before any newer move of that card. Doc: [demos](demos.md). + +## K + +- **K-bucket**: Option-count bucket for calibration: `2`, `3-5`, `6-10`, `11-30`, `31-100`, `101-255`; bucket keys look like `choice:3-5`. Code: `packages/runtime/src/model/calibrate.ts` -> `kBucket`, `K_BUCKETS`; `jev_local/engine/encoder/calibrate.py` -> `K_BUCKETS`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **kill switch**: URL parameter `genclass` (wins) or `localStorage.genclass`, read by `GenClass.init`: `off` gives an inert runtime and drops every option; `observe`, `guard` or `heal` overrides `options.mode`. `createRuntime` and `new RuntimeImpl` ignore it. Code: `packages/runtime/src/index.ts` -> `killSwitch`, `initUnsafe`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **Knowledge (sim)**: The sim's ground-truth bookkeeping during a run: intents, app ops (`SimOp`), writes (`SimWrite`), error tags; `diagnose` reads it to label diagnoses. Code: `sim/src/oracle/knowledge.ts` -> `Knowledge`. Doc: [sim](sim.md). + +## L + +- **late revert**: When a held write applied because its hold budget expired, a gate-passing `discard` that arrives within `LATE_REVERT_MS` (2,000 ms) reverts exactly that write if `StoreHub.revertable` allows it (store writable, none of its fields changed since, no later write from the same root chain). The `ActionRecord` gets `late: true` and the report lead `Reverted`; undo re-applies the write. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; `packages/runtime/src/state/hub.ts` -> `StoreHub.revertable`, `StoreHub.revert`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **lazy preload**: When a salient trigger finds the provider in state `off`, the runtime reads `rt.ready` (calling `decider.ready()` once, which starts loading) and fails open for that trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **LazyOp (lazy timer op)**: Created for each wrapped timer callback; it becomes a real instant `timer` op only when something calls `ctx.op()`. Its parent is always a real op or `null` (`LazyOp.nearest`), so recursive timer loops never build a chain. Code: `packages/runtime/src/trace/context.ts` -> `LazyOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **lead**: The coordinator workstream: owns `docs/runtime/CONTRACT.md`, `packages/runtime-model/` and (per CONTRACT §1) `training/`; approves contract additions (§13) and new dependencies, relays NEEDS items, publishes. Doc: [status-and-known-issues](status-and-known-issues.md). +- **learned invariant**: See *invariant*. + +## M + +- **M0 (release read)**: One pre-registered scoring of the jevbench test splits for a release tag (`--release m0`); the v1 model's M0 skill index is 10.1. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **ManualDecider**: See *ScriptedDecider / ManualDecider / defaultScript*. +- **marker tokens**: Special tokens `[Q]` (question header), `[O]` (choice option), `[L]` (score level), `[T]` / `[F]` (noul criteria) whose hidden states feed the heads. Their positions are recorded at pack time and text is encoded with `encode_special_tokens = True`, so user text cannot forge them. Ids 16359–16363 in the pruned vocabulary (50368–50372 in v0.1), read from `tokenizer.json` / `meta.json`. Code: `packages/runtime/src/model/packer.ts` -> `MARKERS`; `jev_local/engine/encoder/tokenize_pack.py` -> `MARKERS`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **mass**: See *permitted set / candidate / mass*. +- **max_tokens_exceeded**: The packer's limit error (`MaxTokensExceededError`): state + longest question branch > `meta.max_len` (default 1536), or the whole sequence > `meta.max_total` (default 8192). The runtime reacts by multiplying its budget scale by 0.8 (floor 0.5). Code: `packages/runtime/src/model/errors.ts` -> `MaxTokensExceededError`; `packages/runtime/src/model/packer.ts` -> `Packer`. Doc: [model-host](runtime/model-host.md). +- **meharsjev**: See *genclass-<size> / meharsjev-<size>*. +- **mix_* (mixture config)**: `training/configs/mix_{s1,s1b,s1c,s2,final1}.json`: bucket weights for a training round, read as `MixConfig`; `mix_final1` = simA 0.85, cur4 0.12, cur1 0.02, gen 0.01. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). +- **MockRuntime / loadScenario / runStoreSession**: The devtools and adapter UI test harness: `MockRuntime` is a scripted `Runtime`; `loadScenario` scripts a store story with 3 interventions and 3 detections; `runStoreSession` drives the real `createRuntime` with a virtual clock, a fake backend and the rule-based `SessionDecider`. Code: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`; `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario`; `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession`. Doc: [devtools](runtime/devtools.md). +- **mode**: `observe | guard | heal` (default `guard`): which action tiers may run. `observe` permits passive only (never holds, but still decides in the background so detections and reports work); `guard` adds guard-tier actions; `heal` adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`. Code: `packages/runtime/src/types.ts` -> `Mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **MODEL (workstream)**: Owns `packages/runtime/src/model/**` and `packages/runtime/bin/genclass-runtime.mjs`, and co-owns the "model seam" section of `packages/runtime/src/types.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). +- **model card**: `model.json` in format `genclass-runtime-model/1`: `name`, `version`, `variants` (`q8`, `fp16`: file, bytes, sha256, provider, needs) and `files` (`tokenizer`, `calibration`, `meta`). `parseCard` also accepts the v0.1 extension card. Code: `packages/runtime/src/model/loader.ts` -> `parseCard`, `CARD_FORMAT`. Doc: [model-host](runtime/model-host.md). +- **model directory**: A folder or URL holding `model.json` plus the ONNX variants, `tokenizer.json`, `calibration.json` and `meta.json`; produced by `training/export_runtime.py`, fetched with `genclass-runtime fetch-model`, passed as `model: { baseUrl }`, read by tests from `GENCLASS_MODEL_DIR`. Downloads are cached in Cache Storage `genclass-runtime-v1`. Doc: [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md). +- **model host (ModelHost)**: `ModelHost` from `createModelHost`: the main-thread `DecisionProvider` that owns the worker or inline transport, preload scheduling (`eager | idle | lazy`, default `idle`), a priority queue, timeouts (10 s), status and one WASM-only retry after a failed WebGPU load. `evaluate()` rejects at once unless `ready` (fail open, never wait). `GenClass.init` creates one by default in a browser; `createRuntime` only with `model: {...}`. Code: `packages/runtime/src/model/host.ts` -> `createModelHost`. Doc: [model-host](runtime/model-host.md). +- **model status**: `rt.status` (`ModelStatus`; the host's `ModelHostStatus` adds detail): `state` `off` (not started, or no decider) -> `loading` (phases `card`, `download`, `runtime`, `session`, `warmup`) -> `ready` or `error`; `dispose()` returns it to `off`. The runtime consults the model in `ready` (and in `off`, which starts the lazy load); `loading` and `error` fail open at once. Code: `packages/runtime/src/types.ts` -> `ModelStatus`; `packages/runtime/src/model/backend.ts` -> `ModelHostStatus`. Doc: [model-host](runtime/model-host.md). +- **ModelBackend**: The load-and-evaluate wrapper that runs in the worker or inline: fetches the card, computes plans, imports ORT, downloads files, creates sessions, warms up, then evaluates; it emits a `ModelHostStatus` on every change. Code: `packages/runtime/src/model/backend.ts` -> `ModelBackend`. Doc: [model-host](runtime/model-host.md). +- **mutation (trigger)**: Raised through the hub's gate hook for a queued (non-bypassed) store write; holdable, priority 2; actions `apply` (passive), `discard`, `defer`. Salient through facts M2, M5, M6, M8, M10 or M12. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **MutationRec (proposal)**: One proposed write: changes, cause, base, preview, optional `fn` / `commit`, `userSync`, `genclass`, `defers`, state `queued | held | resolved | done`, verdict `apply | discard | defer`, outcome `applied | discarded | deferred | failed`, `appliedAt` / `appliedSeq`. Code: `packages/runtime/src/state/hub.ts` -> `MutationRec`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **muted**: See *episode / muted*. + +## N + +- **native timers (demos)**: Timers captured before `GenClass.init` wraps the globals; all test code (driver, oracle) uses them, so the runtime never sees test ops. Code: `demos/src/shared/native.ts`. Doc: [demos](demos.md). +- **NATIVE_FETCH**: `globalThis.fetch` captured when `index.ts` is evaluated; an owned model host downloads with it, so GenClass never observes its own model download. Code: `packages/runtime/src/index.ts` -> `NATIVE_FETCH`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exception `packages/runtime/UI-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). +- **NetCause (sim)**: Why a simulated request ended (`NetEntry.cause`): `ok, transient, outage, overload, ratelimit, spike, slow-period, gateway-timeout, bug, replica-lag, neterr, aborted, notfound`; diagnoses read it. Code: `sim/src/net/network.ts` -> `NetCause`. Doc: [sim](sim.md). +- **noul**: A typed question asking for the absolute probability that a statement is true (sigmoid head; `criteria` optional `{ true?, false? }`); the answer is `{ noul: P(true) }`, with no confidence field. Code: `packages/runtime/src/types.ts` -> `NoulAnswer`; `jev_local/schema.py` -> `NoulQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **Now view (devtools)**: Renders `runtime.situation()` (an "ask about now" situation) and `inflight()`, refreshed every second while visible. Doc: [devtools](runtime/devtools.md). +- **numbered pick (extension)**: After "which element?", the top-3 candidates get page badges; "number two" within 10 s and ≤ 5 words clicks it without a model call (still through the safety gate). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). + +## O + +- **observers**: `ObserverName` = `fetch, xhr, user, errors, nav, storage, perf, websocket, timers`, installed by `RuntimeImpl.installObservers`, each in try/catch (`timers` is on by default only when a `document` exists). fetch is the only fully controllable transport; XHR supports send/delay/block/serve_cached and its failures and stalls are detection-only; nav, perf and storage only record events. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **op / OpRec**: Anything the app does asynchronously, recorded in `OpRegistry`: kind `user | fetch | xhr | ws | task | timer | genclass`, a sequential `id` per runtime, `name` (the op signature), optional `detail`, start/end, status (`ok | error | aborted | blocked`), `code`, `cause` / `root`, `attempt`, `identity`. User actions, timer ticks, WS messages and sends, and GenClass actions are instant ops. Code: `packages/runtime/src/trace/ops.ts` -> `OpRec`, `OpRegistry`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **op signature**: `OpRec.name`, the key ops are grouped by. For fetch/XHR it is `METHOD normalisedPath` (`requestSignature`: path only, host + path when cross-origin, no query or fragment, id-like segments -> `:id`, e.g. `GET /api/items/:id`); other kinds use their own names (`click button "Add to cart"`, `WS message <path>`, `timer 300ms`, a task name). It keys baselines, transition profiles (user ops as `user <name>`) and `storeWriters`. Code: `packages/runtime/src/util.ts` -> `requestSignature`, `normalizePath`, `isIdSegment`. Doc: [observe-and-trace](runtime/observe-and-trace.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **OPEN_TASKS.md**: Repo-root project status maintained by the lead: Done / In progress / Next / Needs the user / Known risks. Doc: [status-and-known-issues](status-and-known-issues.md). +- **opLabel / opPhrase**: How ops are worded in model text: `opPhrase` gives `<signature><detail>` for requests (e.g. `GET /api/search?q=re`), the user phrase for user ops, `task <name>` and `GenClass <name>`; `opLabel` = `<opPhrase truncated to 90> (#id)`, or `an earlier operation` when the op is unknown. Also used in `ActionEffect.changed` sentences. Code: `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `opLabel`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **oracle (demos)**: Per-demo scorer (`start`, `check`, `finish` -> `Score { bug, reasons, metrics }`) that samples the DOM with native timers and reads the mock server's truth and log; never passed to GenClass or the app. Code: `demos/src/shared/demo-def.ts` -> `Oracle`. Doc: [demos](demos.md). +- **ORT / ORT build**: ORT = onnxruntime-web, the runtime's only dependency. The ORT build is the bundle the backend imports: `webgpu` (`onnxruntime-web/webgpu`, asyncify wasm, WebGPU and WASM execution providers) when any WebGPU plan exists, else `wasm` (`onnxruntime-web/wasm`, CPU only); reported as `status.ortBuild`. Doc: [model-host](runtime/model-host.md). +- **outcome (baseline)**: The string recorded per completion in `SigStats.outcomes` (last 20): HTTP code, `timeout`, `network` or an op status, with a `!` prefix for failures; `aborted` is never recorded. Code: `packages/runtime/src/learn/baselines.ts` -> `Baselines`, `outcomeLabel`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **overlay / host (devtools)**: The `<genclass-devtools data-genclass-devtools data-genclass-ignore>` element plus its open shadow root, mounted by `mountDevtools(runtime, options)`; inline style `all:initial; position:fixed; z-index:2147483646`. It uses only the public `Runtime` API. Code: `packages/runtime/src/devtools/index.ts` -> `mountDevtools`. Doc: [devtools](runtime/devtools.md). +- **owned decider**: A model host that `createRuntime` created itself (`ownsDecider: true`); only owned deciders are disposed by `destroy()`, a caller-supplied decider never is. Code: `packages/runtime/src/index.ts` -> `createRuntime`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). + +## P + +- **package build vs model-entries build**: The two library builds of the Playwright setup. When every tsup entry file exists, `buildLibrary` runs `npx tsup` and uses `packages/runtime/dist` if its `index.js` mentions `createModelHost` ("package" mode); otherwise, or if that build fails, it bundles only `packages/runtime/src/model/{index,worker}.ts` into `packages/runtime/test/browser/.build/dist` ("model-entries" mode). Code: `packages/runtime/test/browser/build.mjs` -> `buildLibrary`. Doc: [build-test-release](runtime/build-test-release.md). +- **Packer**: The TypeScript port of `jev_local`'s `tokenize_pack.Packer` (single-pass subset): turns a wire request into `[CLS] key: text [SEP] … | [Q] header [O] item …` token ids, with positions restarting per branch and `q_group` / `i_group` for block attention; throws `MaxTokensExceededError` past `max_len` / `max_total`. Code: `packages/runtime/src/model/packer.ts` -> `Packer`. Doc: [model-io-contract](model-io-contract.md), [model-host](runtime/model-host.md). +- **parity**: The hard invariant that the TypeScript model path (serializer, tokenizer, packer, calibration, engine) reproduces the Python reference (`jev_local`, `scripts/genclass_export.py`) the model was trained with, and that `training/curriculum/rt.py` renders situations exactly like the runtime. Checked against Python-generated fixtures. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **parity fixtures**: Python-generated files the runtime's model tests compare against: the v0.1 set in `packages/runtime/test/fixtures/model/` (`requests50.json`, `pack_fixtures.json`, `torch_fixtures.json`, plus `py_fixtures.json`) and the model-dir set (`requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, `parity.json`) that `training/export_runtime.py` writes next to an export. Doc: [build-test-release](runtime/build-test-release.md), [model-io-contract](model-io-contract.md). +- **parts (SituationParts)**: The unbudgeted section lines `{ app, trigger, facts[], in_flight[], timeline[], state[], stats[] }` that `toJevState` shapes to the budget. Code: `packages/runtime/src/situation/serialize.ts` -> `SituationParts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **parts mode (sim)**: `gen.js --parts`: resumable fixed seed chunks (default 100 seeds) written as `parts/part-NNNNNN.<split>.jsonl` with a `.json` marker; finished parts are skipped on restart. Used for phase B. Code: `sim/src/gen.ts` -> `main`, `mergeParts`. Doc: [sim](sim.md). +- **pass / pass_tokens (training)**: One draw of the training mixture; each bucket's token budget per pass is weight × `pass_tokens`, and `--passes` may be fractional. Not the FastEngine *fragment / pass*. Doc: [training](training.md). +- **passive (action)**: The action that lets the subject proceed unchanged, per trigger (`PASSIVE`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. It is offered first, permitted in every mode and runs on every fail-open path. Code: `packages/runtime/src/situation/questions.ts` -> `PASSIVE`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **patch (patchValue)**: Re-applies a set of field changes on top of the current store value (removals first, never removing a path that has a set beneath it, copy-on-write); used for queued value writes, revert, reapply and restoreFields, so newer input in other fields survives. Code: `packages/runtime/src/state/fields.ts` -> `patchValue`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **pattern (sim)**: Variant tag a feature's `pattern(spec)` returns, prefixed with the kind (e.g. `search/guard:none`); held-out patterns (`TEST_PATTERNS`) go to test. Code: `sim/src/world/scenario.ts` -> `TEST_PATTERNS`. Doc: [sim](sim.md). +- **pause / resume**: `rt.pause()` stops triggers, holds and request gating (`hub.gating = false`) while tracing continues; decisions already queued still produce a `Decision` but never run; `ask()` still works. `rt.resume()` undoes it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.pause`, `RuntimeImpl.resume`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **pending (extension)**: A risky action waiting for a spoken confirmation from a later utterance; it expires after `confirm_timeout_ms` (default 8,000 ms). Code: `extension/src/core/controller.js` -> `Controller`; `extension/src/core/safety.js` -> `confirmationAllowed`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **permitted set / candidate / mass**: In the policy gate, A = the offered non-passive actions whose tier the mode permits, minus `policy.deny` (or only `policy.allow` when set); the candidate is the action with the highest probability in A; the mass is Σ p over A, compared with the candidate tier's threshold. Recorded as `Decision.candidate` / `mass`. Code: `packages/runtime/src/decide/policy.ts` -> `permittedActions`, `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **phase (model load)**: The load step in progress, `status.phase`: `card | download | runtime | session | warmup`. Doc: [model-host](runtime/model-host.md). +- **phase A / phase B (SIM)**: The final SIM datasets from the frozen runtime (`sim/scripts/final.sh`). Phase A = 600,676 rows (train 448,420 / dev 14,613 / test 137,643), seeds from 10,000,000, in `sim/out/final-a`; phase B = 1.4M more rows from seeds 50,000,000 upward as resumable parts in `sim/out/final-b`, in progress at 654d822. Doc: [sim](sim.md), [status-and-known-issues](status-and-known-issues.md). +- **pill (devtools)**: The collapsed overlay button: mode, intervention and detection counters, a model-status dot and a load progress bar; it pulses on new items. Doc: [devtools](runtime/devtools.md). +- **plan (model load)**: A `{ variant, device }` pair the backend tries in order: `webgpu+fp16` (needs `shader-f16`) -> `webgpu+q8` -> `wasm+q8` (`wasm+fp16` when there is no q8 variant); the first plan that passes its warm-up wins. Code: `packages/runtime/src/model/loader.ts` -> `planOrder`. Doc: [model-host](runtime/model-host.md). +- **plugin**: `Plugin { name, setup?(api), facts?(draft), actions?, questions?, diagnoses? }`, installed with `rt.use(plugin)` or the `plugins` option. Plugin facts are always neutral (they cannot make a trigger salient), plugin actions default to the heal tier, plugin diagnosis labels are appended if new. `PluginApi` offers `runtime`, `clock`, `emit`, `recordOp` / `endOp` / `runInOp`, `user`, `reportError`, `on`, `stores`. Code: `packages/runtime/src/types.ts` -> `Plugin`, `PluginApi`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.use`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **policy gate**: The final check between the model's answer and an action (runtime CONTRACT §8, the "summed-mass gate"): an action runs only if the runtime is not paused, the permitted set's mass ≥ the candidate tier's threshold (guard 0.9, heal 0.8), the top diagnosis is not `expected` (`requireDiagnosis`), fewer than `maxActionsPerMinute` (60) actions ran in the last minute, and, for holdable triggers only (mutation, request, fetch failure), the subject is still held (otherwise late-revert rules apply). It only filters what the model chose; `training/eval_runtime.py` mirrors it. Code: `packages/runtime/src/decide/policy.ts` -> `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [training](training.md). +- **prefix-mismatch**: See *fp (fingerprint, sim)*. +- **primitive question (curriculum)**: An exact-label question about the curriculum trace (qid prefixes `t_` temporal, `c_` causal, `v_` versions, `i_` identity, `o_` outcomes, `b_` baselines, `f_` failure, `j_` JSON, `h_` HTTP, `js_` JS errors, plus `decide` and scenario-specific ids). Code: `training/curriculum/prims.py`; `training/curriculum/standalone.py`. Doc: [training](training.md). +- **programmatic event**: A DOM event the user observer drops: dispatched while a non-user op is running (`ctx.running`), or untrusted while a non-user op is ambient. Code: `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **proposal**: See *MutationRec (proposal)*. +- **pruned vocabulary**: The shipped tokenizer: 245 base ids + the first 16,000 BPE merges of the ettin tokenizer + 119 added tokens = 16,364 tokens, markers at 16359–16363; R17 and R32 share it. Code: `training/prune_vocab.py` -> `prune_tokenizer_json`. Doc: [training](training.md). + +## Q + +- **q8**: The int8 ONNX variant (`<name>-q8.onnx`): MatMulNBits 8-bit (block 32) on every MatMul (Gemm rewritten to MatMul) and int8 row-wise embeddings with fp32 scales, with no fp16 tensor or cast (the export refuses one), so it runs on WASM and on WebGPU without `shader-f16`. Stage-1c sizes: R17 9.58 MB, R32 22.47 MB. Code: `training/export_runtime.py` -> `make_q8`. Doc: [training](training.md), [model-host](runtime/model-host.md). +- **QBlock**: One question rendered for packing: `{ qid, kind: noul | choice | score, header, items, labels }` (choice labels in criteria order; score `"0".."n-1"`; noul `["true", "false"]`). Code: `packages/runtime/src/model/serialize.ts` -> `QBlock`, `questionBlock`; `jev_local/serialize.py` -> `QBlock`. Doc: [model-io-contract](model-io-contract.md). +- **questions**: The typed questions sent with a situation, `Record<qid, Question>`: `diagnosis` (every trigger except `ask`), `action` (when at least 2 actions apply) and registered standing questions by id; `rt.ask()` replaces them with `{ answer: q }`. Qids are never shown to the model. Code: `packages/runtime/src/situation/questions.ts` -> `buildQuestions`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). +- **quiet (demos)**: See *freeze / quiet / settle (demos)*. + +## R + +- **R17**: Runtime model candidate initialised from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers, fresh heads) with the pruned 16,364-token vocabulary: 8.1M + 0.7M head parameters, q8 9.6 MB, fp16 13.6 MB. Planned WASM default. Doc: [training](training.md), [model-host](runtime/model-host.md). +- **r300k**: The pre-freeze SIM run used for the stage-2 pilot, imported as bucket `sim1`. Doc: [training](training.md). +- **R32**: Runtime model candidate initialised from GenClass 0.1 `jev-local-fast` (ettin-32m, d 384, 10 layers, v1 heads) with the pruned 16,364-token vocabulary: 18.8M + 1.6M head parameters, q8 22.5 MB, fp16 34.8 MB. Planned for WebGPU only if clearly more accurate than R17. Doc: [training](training.md), [model-host](runtime/model-host.md). +- **rate limit**: `policy.maxActionsPerMinute` (default 60): a sliding 60 s window of non-passive actions. When full, the gate refuses with `rate limit: …`, and a status line is emitted at most once a minute. Code: `packages/runtime/src/decide/policy.ts` -> `RateLimiter`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **raw logits**: Head outputs at τ = 1 (`choice_logits`, `score_logits`, `noul_logits`) before calibration; what PyTorch parity fixtures and calibration fitting use. Doc: [model-io-contract](model-io-contract.md). +- **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when any path segment names a secret by meaning (`isSensitiveName`: password, token, card number, api key, ...), not by substring. Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitiveName`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **relation (sim)**: An app-declared executable invariant (`Relation { fields, desc, check(stores) }`, e.g. count = len(items), total = Σ price × qty, badge = cart count); ground truth for the `inconsistent` diagnosis and a cost term. Code: `sim/src/app/feature.ts` -> `Relation`. Doc: [sim](sim.md). +- **render bits (devtools)**: Dirty flags `STATUS=1, MODE=2, LISTS=4, EVENTS=8` (ALL=15) OR'ed by `mark()` and flushed once per animation frame; LISTS and EVENTS are deferred while the panel is closed or paused. Doc: [devtools](runtime/devtools.md). +- **repeat folding (devtools)**: Detections with the same `repeatKey` (trigger, diagnosis, action and subject, digits normalised) within 60 s of a card's latest repeat fold into one card with a `×N` badge. Code: `packages/runtime/src/devtools/ui.ts` -> `repeatKey`. Doc: [devtools](runtime/devtools.md). +- **replay (training)**: Curriculum (`cur1`–`cur4`) and GenClass 0.1 (`gen`, `cu`) buckets mixed into SIM-based rounds. Doc: [training](training.md). +- **report / Reporter**: The runtime's one-line console sentences: `[GenClass] Flagged …` per detection without action, `[GenClass] <lead> …` per intervention (`Prevented`, `Held back`, `Slowed down`, `Stopped`, `Recovered from`, `Worked around`, `Repaired`, `Reverted`, `Handled`), plus status lines. Sink `report: "console" | "silent" | fn` (console output deduplicated per 60 s window); every report also fires the `report` event. Code: `packages/runtime/src/decide/report.ts` -> `Reporter`, `interventionLine`, `detectionLine`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **report sentence (devtools)**: `Report.message` from `on("report")`, split by `splitReport` into card title and body; unavailable for items recorded before mount, which use *templates*. Code: `packages/runtime/src/devtools/ui.ts` -> `splitReport`. Doc: [devtools](runtime/devtools.md). +- **request (trigger)**: Raised by the fetch and async-XHR request gates before a gated request is sent; holdable, priority 2; actions `send` (passive), `coalesce`, `delay`, `block`, `serve_cached`. Keepalive fetches and synchronous XHRs raise none. Salient through facts R3 (a close identical request), R5 (fail streak ≥ 2) or R7 (hot request rate). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [observe-and-trace](runtime/observe-and-trace.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **request identity**: The hash that defines "identical requests": FNV-1a of method + absolute URL + non-volatile headers (tracing headers and `x-genclass` excluded) + a body content key. Bodies that cannot be read cheaply get a unique `uniq:N` key and never match; the identity is `""` while a body is still being read (≤ 100 ms). Ops with the same identity started in the last 10 s or still in flight are the identical requests behind repetition facts and `coalesce`. Code: `packages/runtime/src/observe/fetch.ts` -> `parseRequest`, `bodyInfo`, `headersKey`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **rescue (extension)**: `rescueTarget`: for a click whose target answer is `none` or weak, use the unique on-screen label (≥ 3 chars) that occurs verbatim in the transcript; logged as `rescue`. Code: `extension/src/core/controller.js` -> `rescueTarget`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **ResponseCache**: Two response stores used by `coalesce` and `serve_cached`: an LRU GET cache of the last good 2xx body per identity (≤ 256 KB each, ≤ 64 entries) and a coalescing table of in-flight or ≤ 2 s-settled requests (≤ 8 per identity, ≤ 64 entries, ≤ 4 MiB). Bodies are buffered from clones; the app always reads its own `Response`. Code: `packages/runtime/src/observe/cache.ts` -> `ResponseCache`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **resync (action)**: Heal-tier action for `inconsistency` and `transition`, offered when an involved store has a `StoreOptions.resync` handler: call each such handler inside a GenClass op. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.resync`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **retry (action)**: Heal-tier `failure` action for a replayable fetch with `attempt < 4`: after `min(200 × 2^(attempt−1), 5000)` ms start a new fetch op (`attempt + 1`, cause = the failed op); the app receives that attempt's result, which passes through the failure gate again. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **REVIEW / review tests**: The workstream that filed 34 findings (all fixed in batch 3); its bug-demonstration tests `packages/runtime/test/review-*.test.ts` must pass unmodified. Doc: [status-and-known-issues](status-and-known-issues.md), [build-test-release](runtime/build-test-release.md). +- **rollback (action)**: Heal-tier action. For `inconsistency` it writes the last consistent snapshot back to the involved writable stores (undo restores the pre-rollback values and mutes those violations); for `transition` and `error` it is a *chain revert*. Its model-facing description always says "last consistent snapshot". Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.rollback`, `RuntimeImpl.revertChain`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **root**: See *cause / root (op)*. +- **route key (demos)**: A stable string naming a mock-server route (e.g. `search`, `notes/item`, `status/<id>`, `board/events`), used for per-route chaos (`resolveChaos`: global, then prefix, then exact key) and in the request log. Code: `demos/src/shared/chaos.ts` -> `resolveChaos`. Doc: [demos](demos.md). +- **rt1**: Runtime-style curriculum evaluation and calibration set (6k dev / 12k test, of which 6,583 test decision rows) generated with `--p-runtime 1.0` by the pre-freeze `rt.py` port, so it measures the old situation format; source of the stage-1c headline numbers and stage-1 temperatures. Doc: [training](training.md). +- **run.json (benchmax)**: Per-run record, schema `benchmax-run/1`, written by `RunContext` at start and end. Code: `jev_local/bench/benchmax/runner.py` -> `RunContext`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **running op**: `Context.running`, set only while `Context.run(op, fn)` executes `fn` synchronously; the DOM observer uses it to drop programmatic events. Code: `packages/runtime/src/trace/context.ts` -> `Context`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **runtime shim (demos)**: `demos/src/dev/runtime-shim/`, an observe-only stand-in aliased when `packages/runtime/dist/index.js` is missing or `GENCLASS_SHIM=1`; results then say `runtime: "shim"`. Doc: [demos](demos.md). +- **runtime-exact row / varied style (curriculum)**: A runtime-exact row is rendered by `rt.py` exactly as the runtime builds situations and questions (`meta.style = "runtime"`); other rows use the varied `Style` surface (op-ref formats, 6 time formats, 4 timeline line formats, key-name variants, paraphrased descriptions, renamed or distractor actions, bare labels). Code: `training/curriculum/rt.py` -> `render`; `training/curriculum/fmt.py` -> `Style`. Doc: [training](training.md). +- **RuntimeImpl**: The class behind every runtime (implements `Runtime`): wires trace, state, learn, situation, decide and observers; exported publicly for advanced use. Its constructor never reads `options.model` and ignores the kill switch, so use `createRuntime` unless you resolve the decider yourself. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **RuntimeInternals**: The `rt.internals` getter on `RuntimeImpl`: `{ hub, ops, events, base, profiles, miner, ctx, clock }` for tests and tooling. Code: `packages/runtime/src/runtime.ts` -> `RuntimeInternals`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). + +## S + +- **salient**: `BuiltSituation.salient` / `Situation.salient`: `triage === "always"`, or the trigger is `ask`, or at least one fact is non-neutral. Failure, stall, inconsistency, transition and error situations are always salient (facts F1, S1, I1, T1, E1); mutation and request only through specific facts. Not model input. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **Scen / case (curriculum)**: A curriculum scenario result (`Scen`: trigger, case, subject, facts, actions, action, diag, prims, trace, spec, ...); `case` is `"<builder>/<case>"` (e.g. `typeahead/stale`), and the row family drops the builder (`cur/mutation/stale`). Code: `training/curriculum/scenarios.py` -> `Scen`. Doc: [training](training.md). +- **scenario (demos)**: Seeded `Scenario { seed, kind, chaos, params, steps, intent, label }`; `steps` is a union discriminated by `k` (`type`, `key`, `click`, `focus`, `caret`, `wait`, `until`, `chaos`, `server`, `mark`); `intent` is read only by the oracle. Code: `demos/src/shared/demo-def.ts` -> `DemoDefinition`. Doc: [demos](demos.md). +- **scenario (sim)**: `Scenario` from `buildScenario(seed)`: a program (domain, 1–3 features plus optional `benign`, naming, API style, id style), a user session, a network profile and chaos, external events, timing, ask times, vocabulary overrides, model latency and situation budget, all determined by the seed. Code: `sim/src/world/scenario.ts` -> `buildScenario`. Doc: [sim](sim.md). +- **score (question kind)**: A typed question over 2–10 ordered levels (`criteria` = level texts): softmax over the levels, answer `{ score, confidence, probabilities }` with `score = Σ i·p_i`. Code: `packages/runtime/src/types.ts` -> `ScoreAnswer`; `jev_local/confidence.py` -> `score_value`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **ScriptedDecider / ManualDecider / defaultScript**: Test `DecisionProvider`s: `ScriptedDecider` answers at once from a script and records calls; `ManualDecider` queues requests until `answer()`; `defaultScript(pick)` answers each trigger's diagnosis/action from `pick` at p = 0.97, otherwise `expected` and the first (passive) action. Code: `packages/runtime/test/helpers.ts` -> `ScriptedDecider`, `ManualDecider`, `defaultScript`. Doc: [build-test-release](runtime/build-test-release.md). +- **segment**: One `key: text` unit of the packed state: one per top-level key of an object state (string-array values joined with `\n`), `[i]` per item of an array state (first 64, then a `[64:]` tail), or one keyless segment for a string state; segments are separated by `[SEP]`. Code: `packages/runtime/src/model/serialize.ts` -> `stateSegments`, `Segment`; `jev_local/serialize.py` -> `state_segments`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **send (action)**: Passive action of the `request` trigger: send the request now. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **servable checkpoint vs trainer state**: `models/<M>/` (`backbone/`, `heads.safetensors`, `calibration.json` with all-1.0 temperatures, `meta.json` with a `final` flag) is what eval and export read; `runs/<run>/ckpt` holds weights plus optimizer for `--resume` and `--init-from`. Doc: [training](training.md). +- **serve_cached (action)**: Heal-tier action for `request`, `failure` and `stall` on a GET with a cached good response (fetch only for failure and stall): answer with the last good 2xx body for that identity (≤ 256 KB), marked `x-genclass: cached`; on a stall the original request continues in the background. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `ResponseCache`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **ServeConfig / preset**: Per-run serving options of the `jev_local` HTTP server for benchmax (precision, overflow refuse/truncate, refusal status/style, public model id, label alias), chosen once at server start, never per request. Code: `jev_local/api.py` -> `ServeConfig`, `PRESETS`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **settle (demos)**: See *freeze / quiet / settle (demos)*. +- **settled point**: `RuntimeImpl.settled()`, run `settleMs` (default 60 ms) after the last op end, applied write or discarded write. It does nothing while an op younger than 10 s is in flight or a write is pending (the next op end or write schedules it again); otherwise it runs the invariant miner, takes consistent snapshots, learns transition profiles and raises `inconsistency` / `transition` triggers. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [state-and-adapters](runtime/state-and-adapters.md). +- **setup() (tests)**: The runtime test factory: `createRuntime` with a `FakeClock`, a global whose `fetch` is a `FakeServer` (location `http://app.test/search`), a `ScriptedDecider`, `report: "silent"` and only the fetch observer; returns `{ clock, server, g, decider, rt, fetch }`. Options you pass override these defaults, so keep your own reference to a custom decider. Code: `packages/runtime/test/helpers.ts` -> `setup`. Doc: [build-test-release](runtime/build-test-release.md). +- **shape / Unusual**: See *transition profile*. +- **SIM (workstream)**: Owns `sim/`; writes `sim/NEEDS.md`, `sim/README.md` and the training data under `sim/out/` (gitignored). Doc: [status-and-known-issues](status-and-known-issues.md), [sim](sim.md). +- **sim op / sim write**: The sim's app-level ground-truth records, not runtime ops: `SimOp` (a request with role, intent, key, idempotent, attempt, `retryOf`, `dupOf`, `classify()`, linked runtime op id) and `SimWrite` (a store write with role, op, intent, key, changed fields, anomaly, `classify()`, linked runtime mutation). Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`. Doc: [sim](sim.md). +- **simA / sim1 (buckets)**: Training buckets of SIM data: `simA` = phase A (`final-a`, frozen format; 448,420 / 14,613 / 137,643 rows), `sim1` = the pre-freeze run `r300k` (224,051 / 7,426 / 68,790). `simAe` (8k dev / 20k test) and `sim1e` (20k test) are random eval subsets; `simsample` is the 200-row `sim/samples/sample.jsonl`. Doc: [training](training.md). +- **SitEnv**: The read-only view of the runtime that situation code receives (ops, hub, baselines, profiles, events, redactor, cache peek, identical requests, consistent snapshots, `storeWriters`, `chainWrites`, ...), implemented by `RuntimeImpl.makeEnv`. Code: `packages/runtime/src/situation/env.ts` -> `SitEnv`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **situation**: The model input for one trigger: a `JevState` with seven keys in fixed order, `app`, `trigger` (the subject sentence), `facts`, `in_flight`, `timeline`, `state` (store field lines), `stats` (signature baselines), shaped to the situation budget, plus the typed `questions`. The `Situation` object (`rt.situation()`, `buildSituation`) also carries `trigger, subject, actions, salient, facts, compact, budget`, which the model does not read. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). +- **situation budget**: The situation's size in characters as measured by `stateChars`: `STATE_CHAR_BUDGET` 3200 (full), `COMPACT_BUDGET` 1100 (smallest section limits), floor `MIN_BUDGET` 500, linear in between (`sectionLimits`). `situation.budget: "auto"` (default) gives 3200 for WebGPU or an unknown device and `1000 + round((threads − 1) × 1000 / 3)` for WASM with 1–4 threads, times the budget scale; a number is used as is. Over budget, `toJevState` drops timeline lines (oldest first), then state, facts (keeping ≥ 1), in-flight and stats lines, then shortens facts and the trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **situation-v1**: Annotated git tag on commit 1a77558 ("Frozen runtime situation format for model training"). SIM phase A/B and TRAIN's final rounds use this format; `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Any change to text the model reads (situation code, `util.ts` formatters, `changeText`, questions, vocabulary, budgets) needs regenerated SIM data, a matching change to the `training/curriculum/rt.py` port and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference the model was trained with. Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). +- **skill (jevbench)**: `clip((m − c) / (1 − c), 0, 1)` for primary metric `m` and chance level `c`. Code: `jev_local/bench/metrics.py` -> `skill`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **slot (VM slot)**: A per-workstream directory `~/gcl/<SLOT>` on the Azure `train` VM used by `scripts/vm.sh` (names `[a-zA-Z0-9_-]+`, conventionally `core`, `model`, `sim`, `demos`). `sync` uses `rsync --delete`, so files created in a slot outside the excluded paths are removed on the next sync. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). +- **smoke test**: `packages/runtime/test/smoke/smoke.sh`: build, `npm pack`, install the tarball into a temporary Vite 8 app, build it and load it in headless Chromium (Playwright) on port 4191, requiring no errors, a devtools element and ≥ 3 history events; runs with `model: false`. Doc: [build-test-release](runtime/build-test-release.md). +- **Spec (benchmax)**: Registry entry `{ id, suite, adapter, harness, verification, counted_rows, description, owner }` whose `id` equals a `targets.json` `spec_id` byte for byte; 19 are registered (4 group A, 15 group B). Code: `jev_local/bench/benchmax/__init__.py` -> `Spec`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **split (sim)**: Decided per scenario: test = one of 10 held-out domains, a held-out family hash (first 17%) or a held-out pattern; dev = 3% of the remaining families; only 33% of test trajectories are kept (`--test-keep`). All rows of a trajectory share its split. Code: `sim/src/world/scenario.ts` -> `splitOf`. Doc: [sim](sim.md). +- **stage 1 / 1c / 2 (training)**: Training rounds before the freeze: s1 = curriculum `cur1` + `gen`/`cu` replay (`mix_s1`); s1c = continuation with runtime-exact `cur2` (`mix_s1c`), the current best checkpoints (`rt1` action ≈ 98%, FIR 0%); s2 = pilot on the pre-freeze SIM run `r300k` (`mix_s2`), precise but with heal recall ≈ 1.3%. Final rounds restart from the s1c weights. Doc: [training](training.md). +- **staged evaluation (extension)**: The extension first asks the `STAGE1` questions (intent, complete, is_command, destructive) and, only when the policy returns `need_args`, the argument question the intent needs (`ARG_QUESTIONS[intent]`); exact because questions are block-isolated in the attention mask. Code: `extension/src/core/policy.js` -> `evaluatePolicy`, `ARG_QUESTIONS`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **stall (trigger)**: Raised once per gated fetch or async XHR by `RuntimeImpl.watchStall` at `max(4 × median, 2 × p95, 500 ms)` after sending, only when the signature has a latency baseline (≥ 5 samples); not held, priority 1; actions `wait` (passive), `hedge`, `serve_cached` (XHR: passive only). Fact S1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.watchStall`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **stall watch (model host)**: A host timer re-armed by every worker status while loading (180 s); silence means a stuck worker, which leads to the one WASM retry if WebGPU was involved, otherwise to status `error`. Code: `packages/runtime/src/model/host.ts` -> `LOAD_STALL_MS`. Doc: [model-host](runtime/model-host.md). +- **standing question**: `StandingQuestion { id, on, question, always?, onAnswer? }`, registered with `rt.question` or a plugin: asked next to `diagnosis` / `action` on its triggers; `always: true` makes the trigger *forced* (bypasses triage); `onAnswer` receives the answer after the decide/detect events, before any action. Docs also call the built-in `diagnosis` and `action` questions "standing questions". Code: `packages/runtime/src/types.ts` -> `StandingQuestion`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **state (section)**: The `state` key inside a situation, not the whole `JevState`: lines `<path> = <value> (v<version>[, by #writer] <secs> ago)` for the involved fields first, then fields of all involved stores, most recent write first; a store registered with `describe` contributes one line instead. Code: `packages/runtime/src/situation/build.ts` -> `stateLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **stats (section)**: The situation section of baseline lines for the subject op's signature and every in-flight fetch/XHR signature: `<sig>: <count> done[, median <secs>, p95 <secs>], <failed> of last <of> failed, <recent> in last 10s[ (usual <n>)]`. Code: `packages/runtime/src/situation/build.ts` -> `statsLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **STATUS.md**: `packages/runtime/STATUS.md`, CORE's status file read by SIM, DEMOS, UI and MODEL: test state, batch changes, the headless recipe, the trigger table, example situations, "Deviations from the contract (and why)" and "Open issues". Last changed at 1a77558. Doc: [status-and-known-issues](status-and-known-issues.md). +- **stick**: `Context.stick(op)`: makes `op` ambient until `clock.afterTask` clears it at the end of the macrotask (only if it is still that op); done when a fetch/XHR/Response body settles, a user action is recorded, a timer fires, a WS message arrives or `rt.op` settles. Code: `packages/runtime/src/trace/context.ts` -> `Context.stick`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **store / StoreHub**: Every store registered with a runtime lives in one `StoreHub`, keyed by a store name that is global per runtime. The hub holds the three store kinds (*atom*, *guard*, *adapter*), the mutation pipeline, per-field versions and logs, recent changes, late-revert primitives and snapshots. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **storeWriters**: `Map<signature, Map<store, count>>` learned in `RuntimeImpl.onApplied` (the writer plus up to 8 ancestors; ≤ 1000 signatures): how often each signature's chain wrote each store. Used for involved stores, timeline relevance, concurrency facts and `defer`'s related ops. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **subject / SubjectSpec / SubjectRef**: What a trigger is about. `SubjectSpec` is the rich internal description (one variant per trigger: the `MutationRec`, the op and `ReqMeta`, the violations, ...); `SubjectRef` is the public id-only reference (`{ kind, op?, mutation?, store?, paths?, cause?, error?, invariant? }`) passed as `EvaluateRequest.subject` and `Decision.subjectRef` and never serialised into model input. The short `Situation.subject` string is for reports and devtools. Code: `packages/runtime/src/situation/env.ts` -> `SubjectSpec`; `packages/runtime/src/types.ts` -> `SubjectRef`; `packages/runtime/src/situation/build.ts` -> `subjectOf`, `subjectRef`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **subject correlation (sim)**: How the sim maps `EvaluateRequest.subject` (runtime op/mutation ids) to its own knowledge, via `hooks.opCreated` / `mutationProposed` and the `x-request-id` header; recorded as `how` (`subject`, `sync`, `chain`, `delivered`, `last`, `text`, `none`). An unknown subject gets no diagnosis label. Code: `sim/src/run/runner.ts` -> `runScenario`. Doc: [sim](sim.md). +- **subject op**: The op a situation centres on: the cause op for `mutation`, the request op for request/failure/stall/transition, the ambient op for `error`, the asked op for `ask`, none for `inconsistency`. Code: `packages/runtime/src/situation/build.ts` -> `subjectOp`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **summed-mass gate**: See *policy gate*. +- **sync verdict**: For mutations only: the verdict `gateMutation` sees while `trigger()` is still on the stack. `apply` there (triage-neutral, not salient, provider `off`, nothing permitted) means the write is not held at all and applies in the caller's stack. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **synthetic end**: `endOp(..., { synthetic: true })`: the op was answered by GenClass (block, cache, coalesce); excluded from latency baselines and transition profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **System One**: Jev's typed-decision endpoint (`POST /v1/systemone`) and wire format, reproduced by `jev_local/schema.py` and served by `jev_local/server/app.py`. See *Jev*. Code: `jev_local/schema.py` -> `SystemOneRequest`. Doc: [genclass-model-lineage](genclass-model-lineage.md). + +## T + +- **Tail / vid (extension)**: `Tail` is the unconsumed transcript `{ vid, text, words, cursor, isFinal, silentMs, uid, joined }`; `vid` is the virtual utterance id `"<uid>+<gen>"`, where `gen` increments on every consume. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). +- **templates (devtools)**: `actTitle`, `diagTitle` and `phrase`: card titles used when no report sentence is known; they approximate the wording of `packages/runtime/src/decide/report.ts`. Code: `packages/runtime/src/devtools/ui.ts` -> `actTitle`, `diagTitle`, `phrase`. Doc: [devtools](runtime/devtools.md). +- **tier**: The mode an action needs: `passive` (always allowed), `guard` (withhold, deduplicate or slow down: `discard`, `defer`, `coalesce`, `delay`) or `heal` (change what the app receives or restore state: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`; custom actions by default). The policy gate compares the mode with the tier and uses the tier's threshold (guard 0.9, heal 0.8). Code: `packages/runtime/src/types.ts` -> `Tier`; `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **tier premium / tie rule (sim)**: Label-time adjustments that favour passive: each action's per-future cost gets +0 (passive), +0.25 (guard) or +0.5 (heal); a non-passive action whose mean raw cost is within 0.05 of passive's is a practical tie and its cost becomes passive's cost + 1.5. Code: `sim/src/oracle/cost.ts` -> `LABEL`, `actionLabel`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). +- **timeline (section)**: The situation section built from the last 96 events: relevant lines first (user, error, action and nav events always; state events of involved stores; op events of the subject, its ancestors, its signature, its root chain or signatures that wrote an involved store), topped up with recent other lines, in event order. Past GenClass actions appear as `GenClass <changed>`; decision events never appear. Code: `packages/runtime/src/situation/build.ts` -> `timelineLines`; `packages/runtime/src/situation/describe.ts` -> `eventLine`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **Tokenizer**: Byte-level BPE over a Hugging Face `tokenizer.json` with `encode_special_tokens = True` semantics (text cannot produce special tokens); the shipped one is the *pruned vocabulary*. Code: `packages/runtime/src/model/tokenizer.ts` -> `Tokenizer`. Doc: [model-io-contract](model-io-contract.md). +- **Trace (curriculum)**: The explicit curriculum world model (ops, writes with versions, extra events, baselines) from which every curriculum label is computed; labels never come from rendered text. Code: `training/curriculum/world.py` -> `Trace`. Doc: [training](training.md). +- **trace run (demos)**: `?trace=1` or `eval.ts --trace`: records proposed writes (`hooks.mutationProposed`), applied state events, ops and decisions into `window.__gcTrace`, analysed by `demos/e2e/trace-report.ts`; off by default and never in published results. Doc: [demos](demos.md). +- **track Z / S (benchmax)**: Z = zero-shot (no benchmark data of any split in training); S = supervised (official train splits allowed and disclosed). Their scoreboards are never merged. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **TRAIN (workstream)**: Owns `training/` (`training/README.md` says "Owner: TRAIN"; runtime CONTRACT §1 lists the lead); writes `training/NEEDS.md`, `training/LOG.md` and `training/EVAL.md`. Doc: [status-and-known-issues](status-and-known-issues.md), [training](training.md). +- **train VM**: The Azure VM named `train` (10.0.0.4): the team's build/test host for every workstream slot (`scripts/vm.sh`), where SIM generates data and exported models are delivered and validated; it has a 03:00 UTC auto-shutdown. Doc: [build-test-release](runtime/build-test-release.md), [training](training.md), [sim](sim.md). +- **trajectory (sim)**: One scenario processed by `generateTrajectory`: ideal run + base run + counterfactual runs for up to `maxPoints` decision points -> decision rows, diagnosis-only rows and ask rows, all in one split. Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md). +- **transform variant (sim)**: Per-row post-processing of the recorded `action` question (`meta.transform`): `default`, `shuffle`, `drop:<action>` or `drop:<action>,shuffle`, with the label distribution adjusted to match. Code: `sim/src/run/transform.ts` -> `transformQuestions`. Doc: [sim](sim.md). +- **transition (trigger)**: Raised at a settled point for an op whose completion is unusual for its signature (see *transition profile*); the most specific flagged op wins and each op is raised at most once; not held, priority 0; actions `ignore`, `rollback` (chain revert), `resync`. Fact T1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseTransition`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **transition profile**: `Profiles`: per op signature (user ops as `user <name>`), counts over completions of the written-field set (normalised chain keys), each field's value kind (arrays only empty/non-empty), the status class, a write-count bucket and a duration bucket. At a settled point `Profiles.check` returns `Unusual` items for a set, kind, status or write count seen in < 1% of ≥ 20 previous completions (duration is never checked), which raises `transition`. Persisted to `localStorage` only with `learn: { persist: true }`. Code: `packages/runtime/src/learn/profiles.ts` -> `Profiles`, `shapeOf`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **transport (model host)**: How the host reaches its `ModelBackend`: `WorkerTransport` (a module Worker running `dist/worker.js`) or `InlineTransport` (same realm, via a microtask), used when the Worker cannot start, errors before `hello`, sends no `hello` within 15 s, or `worker: false`. Both speak `ToWorker` / `FromWorker`, which carry only `state` and `questions`. Code: `packages/runtime/src/model/host.ts` -> `WorkerTransport`, `InlineTransport`; `packages/runtime/src/model/protocol.ts` -> `ToWorker`. Doc: [model-host](runtime/model-host.md). +- **tree layout / BandedEncoder**: Python attention implementations: `collate_tree` computes the block-mask attention as trunk (state), head (header) and item-chunk sub-problems; `BandedEncoder` is a faster exact version (`JEV_ENCODER=reference` selects `MaskedEncoder`). Code: `jev_local/engine/encoder/tokenize_pack.py` -> `collate_tree`; `jev_local/engine/encoder/engine.py` -> `BandedEncoder`. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **triage**: The cost filter before a model call: with `triage: "salient"` (default) the model is consulted only if some fact is non-neutral, a standing question with `always: true` covers the trigger, or the trigger is `ask`; otherwise the passive action runs with no model call and no `Decision`. `"always"` consults on every consultable trigger. Triage never picks a diagnosis or action, but it shapes the sim's training distribution (the sim runs with `"salient"`). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`; `packages/runtime/src/situation/facts.ts` -> `computeFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **trial (demos)**: A seeded scenario run in a fresh page (in-page "Run trials" driver or the Playwright eval `demos/e2e/eval.ts`) and scored by the demo's oracle; chaos trials measure bug rate, clean trials count false interventions. Doc: [demos](demos.md). +- **trigger**: A `TriggerKind` event that asks "should the runtime intervene here?": `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, plus `ask` for developer questions. Each has a `SubjectSpec`, a passive action, offered actions, a hold flag and a queue priority (held mutation/request/fetch failure 2; stall, inconsistency, XHR failure, ask 1; transition, error 0). Observers and settled points call `RuntimeImpl.trigger(spec, controller, opts)`. Code: `packages/runtime/src/types.ts` -> `TriggerKind`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **typed decision**: One forward pass that answers typed questions (`choice`, `noul`, `score`) about a state object, with calibrated probabilities; the Jev request shape and the model family used throughout this repo. See *Jev*. Doc: [genclass-model-lineage](genclass-model-lineage.md). +- **TypeSafe**: The company behind Jev; see *Jev*. + +## U + +- **UI (workstream)**: Owns `packages/runtime/src/devtools/**` and `packages/runtime/src/adapters/**` (CONTRACT §13; §1's table still says CORE); writes `packages/runtime/UI-NEEDS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). +- **undo**: `ActionRecord.undo()`, present only for reversible effects (discard, late revert, rollback, chain revert, custom `onUndo`): idempotent, runs inside a GenClass op named `undo`, never gated, pushes an `action` event `undid <action> (<id>)`, and fires no `act` event or report. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **unholdable**: See *detached preview / unholdable*. +- **user model (sim)**: `UserModel`: think times (`max(120, lognormal)` ms), per-keystroke typing with typos and backspaces, accidental double clicks and impatient re-clicks guarded by `when` conditions; accidental steps carry `repeatOf`. Code: `sim/src/app/feature.ts` -> `UserModel`. Doc: [sim](sim.md). +- **user-sync write**: A write whose cause is the current task's user op or shares its root (`Context.isUserSync`); it bypasses gating and is never held unless `policy.holdUserWrites` is true. Code: `packages/runtime/src/trace/context.ts` -> `Context.isUserSync`. Doc: [state-and-adapters](runtime/state-and-adapters.md). + +## V + +- **v0.1 fixture set**: `packages/runtime/test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests with the Python packer output and PyTorch logits of the v0.1 GenClass model. Doc: [build-test-release](runtime/build-test-release.md). +- **v0.1 model**: See *GenClass 0.1 (v0.1 model)*. +- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0` (published per `OPEN_TASKS.md`; the registry was not re-checked). Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). +- **variant (jevbench)**: Request flavour per item: `main` (the only one counted), `shuffle` (option-order rotation), `bare` (no descriptions), `choice` (SST-2 only). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **variant (model)**: One ONNX file of a model, keyed in `card.variants`: `q8` (meant for WASM) or `fp16` (meant for WebGPU with `shader-f16`). See *q8*, *plan*. Doc: [model-host](runtime/model-host.md). +- **varied style**: See *runtime-exact row / varied style (curriculum)*. +- **verdict (extension)**: `Decision.verdict`: `act | wait | ignore | clarify | confirm | deny | need_args`, from `evaluatePolicy` then the safety `gate`. Code: `extension/src/core/policy.js` -> `evaluatePolicy`; `extension/src/core/safety.js` -> `gate`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). +- **verdict (mutation)**: `Verdict = "apply" | "discard" | "defer"`, what a held mutation's promise resolves to. Code: `packages/runtime/src/state/hub.ts` -> `Verdict`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **virtual utterance**: See *Tail / vid (extension)*. +- **VirtualLoop (sim)**: The sim's deterministic virtual event loop and clock (`schedule`, `afterTask`, `clockFor`, `settle`, `runUntil`); with keyed RNG forks it makes every seed reproducible. Code: `sim/src/loop.ts` -> `VirtualLoop`. Doc: [sim](sim.md). +- **vm.sh**: `scripts/vm.sh sync|run|exec|get <SLOT> ...`: rsync this repo to `~/gcl/<SLOT>` on the `train` VM and run commands there (default timeout 1800 s); it needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are not in the repo. The original team ran every build and test this way because the author's Mac has 8 GB RAM (CONTRACT §0 rule 5). Current agent policy: install, typecheck, build and unit tests run locally; ask the user before running the sim, training, Playwright, model downloads, the demos' eval or any script that touches Azure. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). +- **Vocabulary**: The `vocabulary` option `{ diagnoses?, actions? }`: `diagnoses` replaces the default label set (`expected` re-added first, plugin labels appended), `actions[name]` overrides the description of a built-in or custom action. It changes model input wording; the sim randomises it per scenario. Code: `packages/runtime/src/types.ts` -> `Vocabulary`; `packages/runtime/src/situation/questions.ts` -> `diagnosisVocabulary`, `actionDescription`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). + +## W + +- **W1–W11**: Engine and wire requirements for benchmax runs from `docs/benchmax-research/suite-reproduction-specs.md` §1.2 (e.g. W1 choice = argmax of unrounded probabilities with ties to the first key, W2 score fields, W3 precision, W4 refusal bodies, W5 overflow refuse/truncate, W9 one global calibration file, W10 model id never `jev-*`, W11 determinism). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`; `jev_local/api.py` -> `ServeConfig`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). +- **wait (action)**: Passive action of the `stall` trigger: keep waiting for the response. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **waits**: In `RuntimeImpl.trigger`, `opts.hold && permittedActions(policy, mode, actions).length > 0 && !paused`: whether the subject is actually held. A holdable trigger with nothing permitted runs its passive action at once and is decided in the background (detection only, 5 s deadline). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **warm-up**: One forward pass (two on WebGPU) over `WARMUP_STATE` / `WARMUP_QUESTIONS` before a plan is accepted; it sets `status.warmupMs` (which seeds the auto hold budget) and seeds `status.latency`. Code: `packages/runtime/src/model/backend.ts` -> `ModelBackend`, `WARMUP_STATE`. Doc: [model-host](runtime/model-host.md). +- **wire request**: `{ state, questions }`, the only part of `EvaluateRequest` the model host uses; `trigger`, `subject`, `priority` and `timeoutMs` are scheduling and test metadata that never reach the packer. Code: `packages/runtime/src/model/protocol.ts` -> `ToWorker`. Doc: [model-io-contract](model-io-contract.md). +- **worker URL pattern**: The literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `defaultWorkerFactory` (and the literal `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` calls beside it) that app bundlers recognise; the browser-test build asserts they survive bundling. Code: `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory`. Doc: [build-test-release](runtime/build-test-release.md). +- **workstream**: A team role that owns paths (runtime CONTRACT §1 and §13): lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW. They communicate through `packages/runtime/STATUS.md` and per-requester NEEDS files; each has its own entry here. Doc: [status-and-known-issues](status-and-known-issues.md). +- **world (demos)**: One mock-server session in the demos' Service Worker, keyed by `live-<demo>-<rand>` or `trial-<demo>-<run>`; it owns state, chaos, request and event logs, SSE streams and timers. The page controls it only via `postMessage`, so GenClass never observes test traffic. Code: `demos/src/server/core.ts` -> `World`. Doc: [demos](demos.md). + +## X + +- **x-genclass**: Response header on responses GenClass synthesises: `blocked` (503), `cached`, `coalesced` (opaque responses shared by coalescing are unmarked clones). It is also a volatile request header, excluded from request identity. Code: `packages/runtime/src/observe/cache.ts` -> `makeResponse`, `blockedResponse`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **x-request-id (sim)**: The header (`SIM_OP_HEADER`) the sim's app code puts on requests so subject correlation can map runtime ops to sim ops. Code: `sim/src/net/network.ts` -> `SIM_OP_HEADER`. Doc: [sim](sim.md). + +## Z + +- **Z-68m**: `meharsjev-68m-z`, the clean zero-shot (track Z) benchmax retrain of the 68m model. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). diff --git a/docs/agents/model-io-contract.md b/docs/agents/model-io-contract.md new file mode 100644 index 00000000..f8632605 --- /dev/null +++ b/docs/agents/model-io-contract.md @@ -0,0 +1,685 @@ +# Model I/O contract: situation text -> packed request -> model heads -> calibrated answers (runtime, sim and training) + +> **Scope:** `packages/runtime/src/situation/{serialize,questions,build,describe,env}.ts`, `packages/runtime/src/model/{packer,serialize,tokenizer,calibrate,engine,protocol,loader}.ts` (+ `pyutil.ts`), the model seam of `packages/runtime/src/types.ts`, `sim/src/ask/questions.ts`, `sim/src/gen.ts`, `sim/src/gen/*.ts`, `sim/src/oracle/cost.ts` (+ `sim/src/run/transform.ts`, `sim/src/run/rt.ts`), `training/export_runtime.py`, `training/eval_runtime.py`, `training/curriculum/{fmt,rows}.py` (+ `rt.py`), `packages/runtime-model/MODEL_CARD.md`, the example situations in `packages/runtime/STATUS.md`. Python reference counterparts in `jev_local/` and `scripts/genclass_export.py` are cited where they define the other side of the contract. +> **Read this when:** you change any text the model reads (facts, subject sentences, timeline/state/stats lines, question instructions, option descriptions, diagnosis labels, budgets); you change the packer, tokenizer, feeds, heads or calibration; you change how the sim labels rows or how training reads them; you export or ship a model directory; you need to know whether a change forces regenerating data and retraining. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- One pipeline, three consumers. The **runtime** builds a situation (`JevState` + typed questions). The **model host** packs it into token ids, runs the ONNX graph and calibrates the logits into answers. The **sim** records the same `state`/`questions` verbatim from the real runtime, attaches labels, and **training** packs them with the Python reference (`jev_local`). Every step on the TypeScript side is a byte-exact port of the Python step. That makes train/serve parity a hard invariant. +- The **situation** is a 7-key object in fixed order: `app, trigger, facts, in_flight, timeline, state, stats`. Each value is a string or an array of strings (one line each). Empty arrays become `"none"`. It is sized by a **character budget** (`STATE_CHAR_BUDGET` 3,200; compact 1,100; floor 500) and shrunk deterministically (`toJevState`). +- **Questions** are Jev-wire objects `{type, instructions, criteria}` of kind `choice | noul | score`. Standing qids are `diagnosis` (always, except on `ask`) and `action` (only when ≥ 2 actions apply). Qids are never shown to the model. At budgets ≤ 1,400 chars, options are bare labels (`null` descriptions, called **compact questions**). +- **Diagnosis labels (10, in order):** `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`. **Actions:** 15 built-ins, 7 trigger kinds, passive first: `apply|send|deliver|wait|ignore` are passive. +- **Packing:** `[CLS] key: text [SEP] … | [Q] header [O] item … | [Q] …`. Positions restart per question branch and per item. `q_group`/`i_group` drive block attention, so options and questions are isolated: option order and unrelated questions cannot change an answer. Limits: positions (state + longest single branch) ≤ `meta.max_len` (default 1536), total ≤ `meta.max_total` (default 8192). +- **Heads → answers:** raw logits (τ = 1) per question → calibration (`calibration.json`: by-header, then by-bucket, then τ(K), then per-kind temperature; or Platt for noul) → `Answer` (`choice`, `confidence`, `probabilities` in criteria order). The runtime gate reads only `probabilities` and the diagnosis `choice`. +- **SIM labels:** `action` is a soft distribution from **counterfactual costs**. The sim re-runs the scenario with each action forced, over up to 3 paired futures, adds a tier premium and a tie rule, then takes `p ∝ exp(−gap/τ)`. `diagnosis` is a hard label from the sim's own knowledge. `ask` rows get exact noul/score/choice labels. +- **Model directory** (`export_runtime.py`): `model.json` (card `genclass-runtime-model/1`, bytes + sha256), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU + `shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, and parity fixtures. +- **Freeze:** tag `situation-v1` (commit 1a77558) froze the situation format. `git diff situation-v1 HEAD -- packages/runtime/src jev_local scripts/genclass_export.py` is empty at 654d822. Any change to text, questions, vocabulary, budgets, packing, tokenizer or labels needs regenerated SIM data (and the `rt.py` port) plus retraining. + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `packages/runtime/src/situation/build.ts` | Assembles a situation: subject sentence, facts, in-flight, timeline, state, stats, applicable actions, standing questions, triage flag | `buildSituation`, `subjectOf`, `subjectRef`, `isTrigger`, `BuildOptions`, `BuiltSituation`, `ActionOption` | +| `packages/runtime/src/situation/serialize.ts` | Budget-shaped `JevState` (key order, section and line limits, shrink order) | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `SituationParts`, `SectionLimits` | +| `packages/runtime/src/situation/questions.ts` | Action catalogue, per-trigger actions/passive/instructions, diagnosis vocabulary, standing-question builder | `BUILTIN_ACTIONS`, `BuiltinAction`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | +| `packages/runtime/src/situation/describe.ts` | How ops/events are named in subject sentences, facts and timeline lines | `opPhrase`, `opLabel`, `userPhrase`, `statusText`, `eventLine` | +| `packages/runtime/src/situation/env.ts` | Read-only view of the runtime used by situation building; subject specs per trigger | `SitEnv`, `SubjectSpec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo` | +| `packages/runtime/src/situation/facts.ts` | (out of scope, see [learn-situation-triage.md](runtime/learn-situation-triage.md)) fact computation and ordering | `computeFacts`, `orderFacts`, `MAX_FACTS` | +| `packages/runtime/src/util.ts` | Formatting helpers that appear in the text (`secs`, `rel`, `fmtNum`, `truncate`, `describe`, redaction) | `secs`, `rel`, `truncate`, `describe` | +| `packages/runtime/src/types.ts` | Model seam types (CORE + MODEL change together; the file's "model seam" section) plus the situation/plugin types the text depends on | `JevState`, `Question`, `Answer`, `AnswerOf`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `TriggerKind`, `ModelStatus`, `EvaluateRequest`, `DecisionProvider`, `SubjectRef`, `Situation`, `SituationDraft`, `Fact`, `FactKind`, `Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier` | +| `packages/runtime/src/model/serialize.ts` | Port of `jev_local/serialize.py`: state segments and question blocks with Python-after-JSON value semantics | `stateSegments`, `segmentText`, `questionBlock`, `questionEntries`, `entryText`, `toJsonValue`, `pyJson`, `criteriaEntries`, `stateText`, `MAX_ARRAY_SEGMENTS`, `DEFAULT_NOUL_INSTR`, `DEFAULT_CHOICE_INSTR`, `DEFAULT_SCORE_INSTR`, `QBlock`, `Segment`, `BlockKind`, `WireQuestion` | +| `packages/runtime/src/model/pyutil.ts` | Python formatting semantics (`str.strip`, float `repr`, `round`) | `pyStrip`, `pyNumber`, `pyFloatRepr`, `pyRound`, `clip01` | +| `packages/runtime/src/model/tokenizer.ts` | Byte-level BPE over a HF `tokenizer.json` (`encode_special_tokens = True` semantics) | `Tokenizer`, `bytesToUnicode`, `TokenizerJson` | +| `packages/runtime/src/model/packer.ts` | Port of `jev_local/engine/encoder/tokenize_pack.Packer` (FastEngine length semantics) + ONNX feed plan | `Packer` (`pack`, `measure`, `encode`, `stateIds`), `PackerOptions`, `MARKERS`, `Marker`, `STATE` (= −1), `Packed`, `PackedQuestion`, `planInputs`, `unpackLogits`, `FeedPlan`, `HeadOutput` | +| `packages/runtime/src/model/engine.ts` | Packer + ORT session + calibration → answers; builds exactly the inputs `meta.json` declares | `Engine` (`evaluate`, `logits`, `release`), `EngineOptions`, `FEEDS`, `ModelMeta`, `EngineResult`, `tensorFloats`, `OrtLike`, `OrtSessionLike`, `OrtTensorLike` | +| `packages/runtime/src/model/calibrate.ts` | Port of `jev_local/engine/encoder/calibrate.py` lookup and `jev_local/confidence.py` answer math | `Calibration`, `parseCalibration`, `headerKey`, `kBucket`, `tauFor`, `noulAffine`, `calibrateLogits`, `buildAnswer`, `Precision`, `normalizeProbs`, `choiceConfidence`, `scoreConfidence`, `K_BUCKETS`, `BUCKET_CLAMP` | +| `packages/runtime/src/model/protocol.ts` | Main thread ↔ worker messages (`state`, `questions` only; trigger/subject never cross). `evaluate` and `measure` requests; one `result` per id | `ToWorker`, `FromWorker`, `EvaluateOk` | +| `packages/runtime/src/model/loader.ts` | Model card parsing, plan order, downloads with sha256 | `parseCard`, `CARD_FORMAT`, `DEFAULT_CACHE_NAME`, `cardId`, `planOrder`, `fetchFile`, `fetchCard`, `ModelCard`, `FileSpec`, `VariantSpec`, `FileRole`, `Plan` | +| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample` | `main`, `mergeParts` | +| `sim/src/gen/trajectory.ts` | One scenario → decision rows, diagnosis-only rows, ask rows; counterfactual costs | `generateTrajectory`, `pointCosts`, `GenOptions`, `PointStat`, `TrajectoryOut` | +| `sim/src/gen/worker.ts` | Worker thread: writes `shards/<split>.w<id>.jsonl` or `parts/part-NNNNNN.<split>.jsonl` | (module) | +| `sim/src/gen/examples.ts` | `sim/samples/EXAMPLES.md` renderer | `renderExamples` | +| `sim/src/oracle/cost.ts` | Run cost vs the ideal run; soft action label | `W`, `LABEL`, `TIER`, `runCost`, `actionLabel`, `clientDist`, `serverDist`, `valueDist`, `divergenceArea`, `relationViolation`, `CostBreakdown`, `ActionLabel` | +| `sim/src/oracle/diagnose.ts` | (detail in [sim.md](sim.md)) hard `diagnosis` label from the sim's knowledge | `diagnose`, `diagnoseFailure` | +| `sim/src/world/scenario.ts` | (detail in [sim.md](sim.md)) scenario seed → domain, budget, ask times, vocabulary paraphrases, split | `buildScenario`, `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `DEFAULT_DIAGNOSES` | +| `sim/src/ask/questions.ts` | Programmatic `ask` questions with exact labels | `askQuestions`, `AskQ` | +| `sim/src/run/transform.ts` | Post-transform of recorded questions (shuffle/drop action options); action paraphrases | `transformQuestions`, `ACTION_PARA` | +| `sim/src/run/rt.ts` | Options the sim passes to `createRuntime` | `createOptions`, `realRuntimeFactory` | +| `sim/src/types.ts` | Sim mirror of the seam + row schema | `Row`, `Label`, `PASSIVE`, `DIAGNOSES` | +| `training/curriculum/rows.py` | Stage-1 curriculum rows (decision / ask), varied style or runtime-exact | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `RENAMES` | +| `training/curriculum/fmt.py` | Surface variation (key names, time formats, paraphrase templates with held-out tails), vocab copies | `Style`, `TEMPLATES`, `ACTION_DESC`, `DIAG_DESC`, `TRIGGER_ACTIONS`, `TIER`, `DISTRACTOR_ACTIONS`, `js_numbers`, `pick_from` | +| `training/curriculum/rt.py` | Python port of the runtime's situation text (frozen wording) for runtime-exact curriculum rows | `render`, `to_state`, `section_limits`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR` | +| `training/curriculum/generate.py` | (detail in [training.md](training.md)) curriculum CLI: row ids, `js_numbers`, validation through the trainer's own parser | `make_row`, `_validate`, `work`, `main` (`--p-runtime` → env `GC_P_RUNTIME`) | +| `training/prune_vocab.py` | (detail in [training.md](training.md)) prunes the ettin tokenizer to the shipped `tokenizer.json` (16,000 merges) | — | +| `training/eval_runtime.py` | Accuracy, calibration fit (`calibration.json`), §8 gate metrics | `fit_calibration`, `decision_metrics`, `question_metrics`, `main` | +| `training/export_runtime.py` | Checkpoint → ONNX q8/fp16 + model directory + parity fixtures | `make_q8`, `make_fp16`, `quantize_embedding`, `gemm_to_matmul`, `requests_from_rows`, `main` | +| `jev_local/serialize.py`, `jev_local/engine/encoder/tokenize_pack.py`, `jev_local/engine/encoder/calibrate.py`, `jev_local/engine/encoder/heads.py`, `jev_local/train/train.py` | Python reference: serialization, packing, calibration, heads, label → target | `state_segments`, `question_block`, `Packer.pack`/`pack_split`, `header_key`, `DecisionHeads`, `parse_target`, `encode_example` | +| `scripts/genclass_export.py` | ONNX graph definition and feed plan (imported by `export_runtime.py`) | `ExportModel`, `plan_inputs`, `unpack` | +| `packages/runtime-model/MODEL_CARD.md` | Model card (only file in that package today) | — | +| `packages/runtime/test/fixtures/model/` | Parity fixtures for the TS ports: `py_fixtures.json` (made by `make_py_fixtures.py`: `serialize`, `tokenize`, `pruned`, `calibrate`, `confidence` sections), v0.1 `requests50.json` / `pack_fixtures.json` / `torch_fixtures.json`, `make_webgpu_variants.py` (WebGPU embedding-encoding variants) | read by `test/model/helpers.ts` | +| `packages/runtime/STATUS.md` ("Example situations") | Real rendered situations: the same stale write at 1,000 chars (998, compact questions) and 2,000 chars (1,494); one full-budget situation per trigger (mutation, request, failure, stall, inconsistency, transition, error) | copied from `test/budget.test.ts` / `test/situation.test.ts` | + +## Concepts and data structures + +Terms used here beyond the shared terminology (see [glossary.md](glossary.md)): + +- **Wire request**: `{state, questions}`, the only thing the model host uses. `EvaluateRequest.trigger`, `subject`, `priority` and `timeoutMs` are scheduling/test metadata and never reach the packer (`protocol.ts` -> `ToWorker` carries only `state`, `questions`). +- **Segment**: one `key: text` unit of the state (`model/serialize.ts` -> `Segment`). **QBlock**: one question rendered as `header` + `items` + `labels`. +- **Header**: the question's `instructions` text. **Item**: one option (choice), level (score), or the true/false criterion (noul). +- **Marker**: special token `[Q] [O] [L] [T] [F]` whose hidden state feeds a head. **Branch**: state + one question's header + one of its items (what `max_len` bounds). +- **Raw logits**: head outputs at τ = 1. **Header key**: `sha1(header)[:12]`, the key of `calibration.json.by_header`. +- **Compact questions**: options with `null` descriptions when the situation budget ≤ `COMPACT_QUESTIONS_BUDGET` (1,400). +- **CONTRACT-D row**: one JSONL training example `{id, split, family, state, questions, labels, meta}`. +- **Counterfactual cost**: cost of a re-run with one action forced at a decision point, measured against the ideal run (`sim/src/oracle/cost.ts` -> `runCost`). **Future**: one re-seeded continuation after the decision (common random numbers across actions). +- **Tier premium / tie rule**: label-time adjustments that favour passive (`LABEL` in `cost.ts`). + +### Seam types (`packages/runtime/src/types.ts`) + +```ts +type JevState = Record<string, unknown>; +type Question = + | { type: "noul"; instructions: string; criteria?: { true?: string; false?: string } } + | { type: "choice"; instructions: string; criteria: Record<string, string | null> } + | { type: "score"; instructions: string; criteria: string[] }; +interface NoulAnswer { type: "noul"; noul: number } // calibrated P(true) +interface ChoiceAnswer { type: "choice"; choice: L; confidence: number; probabilities: Record<L, number> } +interface ScoreAnswer { type: "score"; score: number; confidence: number; probabilities: Record<string, number> } +interface EvaluateRequest { trigger: TriggerKind; state: JevState; questions: Record<string, Question>; + priority?: number; subject?: SubjectRef; timeoutMs?: number } +interface DecisionProvider { readonly status: ModelStatus; ready(): Promise<void>; + evaluate(req: EvaluateRequest): Promise<Record<string, Answer>>; onStatus?(fn): () => void; dispose?(): void } +``` + +`Situation` (returned by `runtime.situation()`, built in `build.ts`): `trigger, subject, state, questions, actions` (passive first), `salient`, `facts` (all ordered facts, ≤ 12, **not** budget-trimmed), `compact`, `budget`. The model reads `state.facts`, which may be shorter. + +Other `types.ts` shapes on the model path (`Vocabulary`, `StandingQuestion.question` and `ActionDef.description` change the text the model reads): + +```ts +interface Vocabulary { diagnoses?: Record<string, string>; // replaces the default label set (expected re-added, plugin labels appended) + actions?: Partial<Record<string, string>> } // per-action description override +interface StandingQuestion { id: string; on: TriggerKind[]; question: Question; + always?: boolean /* consult even when not salient */; onAnswer?(a, ctx): void } +interface ActionDef { name; description; on: TriggerKind[]; tier?: "guard" | "heal" /* default heal */; + risk?; applicable?(sit: SituationDraft): boolean; run(ctx) } +type AnswerOf<Q> = /* noul → NoulAnswer; choice → ChoiceAnswer<keyof criteria>; score → ScoreAnswer */ +``` + +- **salient** (`build.ts` -> `buildSituation`): `triage === "always" || trigger === "ask" || facts.some(f => !f.neutral)`. **forced**: some standing question for this trigger has `always: true`. Neither is model input. +- **`SubjectRef`** (`build.ts` -> `subjectRef`; never serialized, the model host ignores it): mutation `{mutation, store, paths, cause?}`; request/failure/stall `{op}`; transition `{op, paths, store?}`; inconsistency `{paths, store?, invariant?}` (first violation's text); error `{error: raw, op?}`; ask `{op?}` or `{store?}`. +- **`EvaluateRequest.priority`** is queue order only (`types.ts` comment: held writes/requests 2, background 0); see [decide-policy-actions.md](runtime/decide-policy-actions.md). + +### Model-side structures (`packages/runtime/src/model/`) + +| type | fields | +|---|---| +| `Segment` | `key` (`""` for a string state, object key, or `[i]`), `text` | +| `QBlock` | `qid`, `kind: "noul" \| "choice" \| "score"`, `header`, `items`, `labels` (choice labels in criteria order; score `"0".."n-1"`; noul `["true","false"]`) | +| `Packed` | `inputIds`, `positionIds`, `qGroup`, `iGroup`, `nState`, `qIndex: Map<qid, PackedQuestion>` | +| `PackedQuestion` | `kind`, `header`, `labels`, `qPos` (index of `[Q]`), `itemPos` (index of each `[O]`/`[L]`, or `[T]`,`[F]`) | +| `FeedPlan` | `choice {q, items, k}`, `score {q, items, k}`, `noul {q, t, f}` | +| `ModelMeta` (keys read) | `max_len`, `max_total`, `markers`, `cls_id`, `sep_id`, `inputs`, `outputs`; `name` only as the `Engine` fallback when no `name` option is passed (the backend always passes one); `pad_id` declared but unused | +| `Calibration` | `noul`, `choice`, `score` (τ > 0, default 1.0), `by_header`, optional `by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp`, `version` | +| `ModelCard` | `format`, `name`, `version`, `license?`, `variants{name: {file, bytes?, sha256?, provider?, needs?}}`, `files{tokenizer, calibration, meta}` | + +### Diagnosis vocabulary (`questions.ts` -> `DEFAULT_DIAGNOSES`, order is the option order) + +| label | description (what the model reads at full budget) | +|---|---| +| `expected` | normal behaviour, nothing is wrong | +| `stale` | outdated data or an older operation is about to replace newer state | +| `conflict` | concurrent operations are competing over the same state or resource | +| `duplicate` | the same change or request is happening again without a new intent | +| `inconsistent` | the state contradicts itself or relationships it normally keeps | +| `failing` | an operation keeps failing or its failures follow a pattern | +| `slow` | an operation is far slower than usual | +| `overload` | work is being triggered far more often than usual | +| `unusual` | this differs from how the same operation normally behaves | +| `transient` | a one-off failure that is likely to succeed if tried again | + +`diagnosisVocabulary(vocab, pluginLabels)`: `vocab.diagnoses` replaces the defaults. `expected` is always kept and moved first. Plugin labels are appended if their names are new. The header is always `DIAGNOSIS_INSTRUCTIONS` = `"What is happening here?"`. + +### Actions per trigger (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `BUILTIN_ACTIONS`; applicability in `build.ts` -> `builtinApplicable`) + +| trigger | action header (exact) | actions, passive first | offered only when | +|---|---|---|---| +| `mutation` | What should the runtime do with this write? | `apply`, `discard`, `defer` | `defer`: the mutation was deferred < 2 times | +| `request` | What should the runtime do with this request? | `send`, `coalesce`, `delay`, `block`, `serve_cached` | `coalesce`: fetch and `env.canCoalesce`; `serve_cached`: GET and a cached response | +| `failure` | What should the runtime do with this failed request? | `deliver`, `retry`, `serve_cached` | `retry`: replayable, attempt < 4, fetch; `serve_cached`: GET, cached, fetch | +| `stall` | What should the runtime do with this slow request? | `wait`, `hedge`, `serve_cached` | `hedge`: idempotent GET, replayable, fetch; `serve_cached`: GET, cached, fetch | +| `inconsistency` | What should the runtime do about this inconsistent state? | `ignore`, `rollback`, `resync` | `rollback`: a consistent snapshot and a writable store; `resync`: a store with a resync handler | +| `transition` | What should the runtime do about this unusual state change? | `ignore`, `rollback`, `resync` | `rollback`: the op chain's writes are revertable; `resync`: a chain store is resyncable | +| `error` | What should the runtime do about this error? | `ignore`, `rollback` | `rollback`: the ambient op's chain wrote revertable state | +| `ask` | (none) | (none) | — | + +Built-in descriptions and tiers (`BUILTIN_ACTIONS`; the sim's `TIER`, curriculum `fmt.TIER` and `eval_runtime.TIER` are copies): + +| action | tier | description | +|---|---|---| +| `apply` | passive | let this write update the state now | +| `discard` | guard | drop this write and keep the current state | +| `defer` | guard | hold this write until the related in-flight operations finish, then decide again | +| `send` | passive | send the request now | +| `coalesce` | guard | do not send; reuse the result of the identical request that is in flight or just finished | +| `delay` | guard | wait before sending, backing off so the service can recover | +| `block` | heal | do not send; fail this request immediately | +| `serve_cached` | heal | answer with the last successful response for this request instead | +| `deliver` | passive | pass the failure to the application as it is | +| `retry` | heal | retry the request after a short backoff | +| `wait` | passive | keep waiting for the request | +| `hedge` | heal | send a second identical request and use whichever answers first | +| `ignore` | passive | leave the state as it is | +| `rollback` | heal | restore the affected state to its last consistent snapshot | +| `resync` | heal | reload the affected state from its source | + +Custom (plugin) actions are appended after the built-ins when `def.on` includes the trigger, the name is new, and `def.applicable(draft)` is truthy (no `applicable` = applicable; a throw counts as false). Their tier defaults to `heal`, and their description comes from `actionDescription` (vocabulary override, then `def.description`, then the built-in text, then the name). + +### Training row (`sim/src/types.ts` -> `Row`, `Label`; same schema as docs/CONTRACT.md §D) + +```ts +interface Row { id: string; split: "train" | "dev" | "test"; family: string; state: JevState; + questions: Record<string, Question>; labels: Record<string, Label>; meta: Record<string, unknown> } +type Label = { type: "choice"; label: string } | { type: "choice"; dist: Record<string, number> } + | { type: "noul"; p: number } | { type: "score"; level: number } | { type: "score"; dist: number[] }; +``` + +A qid without a label is packed but unsupervised. + +## How it works + +### 1. Situation text (`build.ts` -> `buildSituation`, `serialize.ts` -> `toJevState`) + +1. `subjectOf(env, spec)` writes the `trigger` sentence (model input) and `Situation.subject` (reports only, never model input). `opLabel(op)` = `` `${truncate(opPhrase(op), 90)} (#${op.id})` `` (`"an earlier operation"` when the op is unknown). + | trigger | sentence template (`state.trigger`) | `Situation.subject` | + |---|---|---| + | mutation | `A write to <p1, p2, p3[ and N more] \| store>[ from <opLabel(cause)>] is about to be applied.` | `write to <paths>[ from <opLabel>]` | + | request | `<opLabel> is about to be sent.` | `<opLabel>` | + | failure | `<opLabel> failed (<HTTP 503 \| timed out \| network error>) and the app has not seen the failure yet.` | `<opLabel> (<failure>)` | + | stall | `<opLabel> has been waiting <secs> for a response.` | `<opLabel>, waiting <secs>` | + | inconsistency | `The relation <text \| ?>[ (and N more)] no longer holds now that the app is settled.` | `relation <text>[ (and N more)]` | + | transition | `<opLabel> completed with a state change unlike its usual ones.` | `<opLabel> state change` | + | error | `An uncaught <Name> was thrown: <message, truncated to 120>` | `<Name>: <message ≤ 80>` | + | ask | `The developer asks about <opLabel>.` / `The developer asks about the store <name>.` / `The developer asks about the app right now.` | `question about <opLabel \| name \| the app>` | + + `opPhrase` by op kind (`describe.ts`): user → `userPhrase` (`user clicked <target>`, `user typed <value>[ into <target>]`, `user changed …`, `user submitted …`, `user pressed <key>…`, `user navigated to …`); fetch/xhr → `<op.name><op.detail>` where `name` is the op signature and `detail` the query string plus, for non-GET/HEAD, a redacted body summary (`observe/fetch.ts`; e.g. `GET /api/search?q=rea`, `POST /api/orders {items: [1], cardNumber: [redacted]}`); timer/ws → name; task → `task <name>[ <detail>]`; genclass → `GenClass <name>`. Time and number formats come from `util.ts`: `secs(ms)` = 2 dp below 10 s (`0.42s`), 1 dp below 1,000 s (`12.3s`), else integer; `rel(ms)` = signed timeline stamp (`-1.24s`, `+…` for future); `fmtNum` = integers as is, else 1/2/4 dp by magnitude (≥ 100 / ≥ 1 / < 1); `truncate(s, n)` = first `n−1` UTF-16 code units + `…`. +2. Facts: `computeFacts` (or precomputed facts from triage), plus plugin facts (each truncated to 240, `kind: "plugin"`, neutral). Then `orderFacts` (non-neutral first, then kind rank, stable) and `.slice(0, MAX_FACTS = 12)`. +3. Section lines (details in [learn-situation-triage.md](runtime/learn-situation-triage.md)): + - `app`: `` `${title} — ${route}` ``, or whichever exists, else `unknown`. + - `in_flight`: non-user in-flight ops except the subject, same signature first, then same root, then by start: `<opPhrase≤80> (#id) <secs> so far[, by #cause]`. + - `timeline`: from the last 96 events, the relevant ones (≤ section limit), topped up with the most recent irrelevant ones and sorted by `seq`. Lines come from `describe.ts` -> `eventLine`, for example `-0.90s start GET /api/search?q=rea (#6, by #5)`, `-0.00s end … (#6): 200 in 0.90s`, `-0.69s write search.results: 0 items → 2 items […] (by #8)`, `-1.05s user typed "reac" into input "Search" (4 keystrokes, #1–#7)`, `… error <msg≤100> (during #2)`, `… navigate <route≤60>`, `… GenClass <text≤100>`. `decision` events are never shown. + - `state`: involved fields first, then other fields of the involved stores by most recent write: `path = value (vN, by #writer <secs> ago)` or `(v0)`. A store with a `describe` option renders `store = <describe≤110> (vN)`. + - `stats`: `<sig>: N done[, median Xs, p95 Ys], F of last N failed, R in last 10s[ (usual U)]`. +4. `toJevState(parts, budget)`: + 1. `b = max(MIN_BUDGET 500, round(budget))`; `L = sectionLimits(b)`, with `r = clamp((b − 1100) / 2100, 0, 1)` and every limit `Math.round(a + (b − a)·r)` (half-up). + 2. Cap each section: facts/in_flight/state/stats keep the first N, timeline keeps the **last** N. Each line is truncated to its line limit with `…` (`util.truncate`: first `n−1` chars + `…`). + 3. Build the object in key order `app, trigger, facts, in_flight, timeline, state, stats`. An empty array becomes the string `"none"`. + 4. Size = `stateChars` = Σ over keys of `len(key) + 2 + len(value joined by "\n") + 1`. While size > `b`, shrink in this order: timeline (drop oldest, floor 0), state (drop last, floor 0), facts (drop last, **floor 1**), in_flight (drop last), stats (drop last). + 5. If still over (`over = size − b`): shorten every fact to `max(60, len − over)`. If still over, shorten the trigger to `max(60, len − remaining excess)` (the excess is recomputed after the fact shortening). +5. The situation is deterministic: the same inputs and clock give byte-identical output (`test/situation.test.ts`, `test/budget.test.ts`). +6. The budget comes from `RuntimeImpl.situationBudget` (`src/runtime.ts`). A numeric `situation.budget` is used as is. With `"auto"`: webgpu or an unknown device gives 3,200; wasm gives `1000 + round((threads − 1)·1000/3)` with threads clamped to 1..4 (1,000 / 1,333 / 1,667 / 2,000). The result is multiplied by `budgetScale`, which starts at 1 and becomes `max(0.5, ×0.8)` after each `max_tokens_exceeded` (auto only). + +### 2. Standing questions (`questions.ts` -> `buildQuestions`) + +1. `compact = budget <= COMPACT_QUESTIONS_BUDGET` (1,400). This is a different constant from `COMPACT_BUDGET` 1,100. +2. `ask` trigger: only standing questions (from `rt.question` or a plugin) for `ask`. `runtime.ask(q)` sends its own `{answer: q}` (`runtime.ts` -> `ask`). +3. Otherwise `diagnosis = {type: "choice", instructions: "What is happening here?", criteria}`, where `criteria[label]` is the description. In compact mode it is `null`, unless a `vocabulary.diagnoses` override of ≤ 24 chars (`COMPACT_DESC_MAX`) exists for that label. +4. `action` is added only if more than one action applies, with `criteria[name]` = the description (compact: `null` unless a `vocabulary.actions` override ≤ 24 chars). The header is `ACTION_INSTRUCTIONS[trigger]` and is fixed per trigger (no subject interpolation). +5. Standing questions (from `rt.question` or a plugin) follow, by their `id`, only if the id is not already in the object (`if (!(k in qs))`). So an id `diagnosis` is always skipped, but an id `action` is **inserted** when the built-in `action` question is absent (≤ 1 applicable action). Insertion order is `diagnosis, action, <standing qids>`. For `ask` the result is `{...extra}` (standing questions for `ask` only, nothing skipped). + +### 3. Wire → segments and blocks (`model/serialize.ts`, port of `jev_local/serialize.py`) + +1. The host calls `toJsonValue(req.state)` (`host.ts` -> `evaluateDetailed`; questions are passed as given and converted per value inside `questionBlock`). This is the value Python sees after `json.loads(JSON.stringify(v))`: `undefined` keys vanish, NaN/±Infinity become `null`, Dates become strings, Maps are kept as ordered maps (entries whose value is `undefined`, a function or a symbol are dropped). BigInt and cyclic values throw `ModelInputError`. `pyJson` is `json.dumps(v, ensure_ascii=False, separators=(", ", ": "))`: non-ASCII characters stay raw, numbers go through `pyNumber`. +2. `stateSegments(state)`: + - object: one segment per top-level key, `text = valueText(v)`: an array of strings is joined with `"\n"` (not stripped); anything else goes through `entryText`. + - array: up to 64 (`MAX_ARRAY_SEGMENTS`) `[i]` segments plus one `[64:]` remainder. + - string: one segment with key `""` (stripped). + - `null` → `None`; booleans → `True`/`False`; numbers → Python repr. +3. `entryText`: + - `null` → `""`. + - string → `pyStrip` (Python whitespace set). + - all-string array → items joined with `"; "`, skipping empties. + - other array → `json.dumps(…, separators=(", ", ": "))`. + - object → `k: v | k: v` (nested objects and non-string arrays as JSON). + - number → `pyNumber`: JSON integers print as ints; others print as Python `repr(float)`, with an exponent form outside `[1e-4, 1e16)`. +4. `segmentText` = `` `${key}: ${text}` `` (or `text` when the key is empty). The model therefore reads `facts: <fact1>\n<fact2>`. The indented `facts:\n <fact1>` rendering in STATUS.md and `explain()` comes from `situation/serialize.ts` -> `stateText` and is display only. (`model/serialize.ts` -> `stateText` is a different helper: `key:\ntext` blocks joined by blank lines, also display only.) +5. `questionBlock(qid, q)`: + - header = `entryText(instructions)` or the default (`Is the statement true of the state?` / `Which option best fits the state?` / `Which level best describes the state?`). + - choice: items `label` when the description is `null`, `""`, or equal to the label after strip; otherwise `label: <entryText(desc)>`. Labels are in criteria order (a Map keeps integer-like labels in order; a plain object moves them first). Empty criteria → `ModelInputError`. + - score: items = level texts, labels `"0".."n-1"`. Empty criteria → `ModelInputError`. + - noul: items `[true || "yes", false || "no"]`, labels `["true","false"]`. + - Any other type → `ModelInputError`. +6. `questionEntries(questions)`: request order (`Object.entries`, or Map order). + +### 4. Packing (`packer.ts` -> `Packer.pack`) + +``` +[CLS] seg_0 [SEP] seg_1 [SEP] … seg_n [SEP] | [Q] header_0 | [O] item_00 | [O] item_01 … | [Q] header_1 | [L] lvl_10 … | [Q] header_2 | [T] true | [F] false +``` + +1. Each text is tokenized on its own with no special tokens (`Packer.encode` -> `Tokenizer.encode`, cached by text, 8,192 entries). Special added tokens (`[CLS]`, `[Q]`, …) are **never** matched inside text, so user text cannot forge a marker. In code order (`Tokenizer.encode`): the file's normalizer runs on the whole text first (NFC for the shipped file; `NFC/NFD/NFKC/NFKD/Lowercase/Sequence` supported), then non-special added tokens (whitespace runs, `|||…|||`, `[unusedN]`) are split out leftmost-longest and keep their own ids, then each remaining piece goes ByteLevel regex → BPE merges (heap, `Word::merge_all` order). +2. State ids: `[CLS]`, then each segment's ids followed by `[SEP]`. `nState = S` is the count. +3. Per question `qn`: header = `[Q]` + header ids. Each item = its marker + item ids. Markers: `[O]` choice, `[L]` score, `[T]`/`[F]` noul. +4. `position_ids`: state `0..S−1`. Header tokens `S..S+h−1`. Every item **restarts** at `S+h`. +5. `q_group`: −1 for state, `qn` for header and items. `i_group`: −1 for state and header tokens, the item ordinal for item tokens. The graph builds the block mask from these: a token sees the state plus its own header and its own item. ModernBERT local (`sliding_attention`) layers also require `|pos_q − pos_k| ≤ window`; the window is a graph constant (`ExportModel.window`), recorded as `meta.json` `window` but not read by the host. +6. Limits: `positions = S + max over questions(len(header) + longest item)` must be ≤ `maxPositions` (`meta.max_len`, default 1536), and `total = S + Σ(header + all items)` ≤ `maxTotal` (`meta.max_total`, default 8192). Otherwise `MaxTokensExceededError` (`code: "max_tokens_exceeded"`) is thrown. There is no truncation inside the model host: the situation budget is the only size control. +7. Marker, `[CLS]` and `[SEP]` ids come from `meta.json` when given and must equal the tokenizer's ids, otherwise `ModelUnsupportedError`. Nothing is hardcoded. The pruned runtime tokenizer has markers at ids 16359–16363 (MODEL_CARD). +8. `Packer.measure(state, questions?)` returns `{stateTokens, positions, total}` with the same arithmetic as `pack` but never throws `MaxTokensExceededError` (host `measure`, worker message `measure`; the runtime itself does not call it, see [model-host.md](runtime/model-host.md)). +9. Tokenizer constraints (`tokenizer.ts` -> `Tokenizer` constructor, all `ModelUnsupportedError`): model type must be `BPE`; no dropout; no `continuing_subword_prefix`/`end_of_word_suffix`; pre-tokenizer must be `ByteLevel` (or a one-element `Sequence` of it); normalizer one of `NFC/NFD/NFKC/NFKD/Lowercase/Sequence` or none; non-special added tokens may not use `lstrip`/`rstrip`/`single_word`; every byte that can occur in UTF-8 needs its byte-level token; every merge must refer to vocab tokens; every id < `ID_SPACE` (2^26, module-private). The pre-tokenizer regex spells `\s` as `\p{White_Space}` to match Rust/Oniguruma. + +### 5. Feeds, graph and heads (`engine.ts`, `packer.ts` -> `planInputs`/`unpackLogits`; graph `scripts/genclass_export.py` -> `ExportModel`) + +1. `planInputs` groups questions by kind in request order: + - `choice_q [G]`, `choice_items [G, K]` (padded with 0); + - `score_q [S]`, `score_items [S, K2]`; + - `noul_q/noul_t/noul_f [M]`. + A kind with no question gets one dummy row pointing at token 0. +2. `Engine` feeds exactly `meta.inputs`. The set must equal the session's input names, and every name must be in `FEEDS`: `input_ids, position_ids, q_group, i_group, attention_mask, token_type_ids, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f`. All feeds are int64, and token rows are `[1, L]`. Shipped exports declare the 11 inputs without `attention_mask`/`token_type_ids`. +3. Outputs map by name: `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` (fp16 outputs are converted to numbers). +4. Heads (`jev_local/engine/encoder/heads.py`): + - choice: `z_i = MLP([h_Q; h_Oi; h_Q*h_Oi])`; + - score: `z_k = MLP([h_Q; h_Lk; h_Q*h_Lk])`; + - noul: `z = MLP([h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F])`, an absolute sigmoid rather than a 2-way softmax. + MLP = Linear → GELU → Linear(d → 1). Every `h_*` is first passed through the heads' shared LayerNorm (`DecisionHeads.norm`; `pairwise`/`n` in `ExportModel.forward`). +5. `unpackLogits` returns raw logits per qid in request order, taking the first `labels.length` columns. `Engine.logits` serializes forward passes (one at a time per session). +6. `Engine` constructor checks (all `ModelUnsupportedError`): the session's input names must equal `meta.inputs` as a set (if `meta.inputs` is absent, the session's names are used); every input must be a `FEEDS` key; every `meta.outputs` name must be a graph output; outputs are filtered to `choice_logits`/`score_logits`/`noul_logits` and at least one must remain. A question whose kind has no head fails at `logits` time. Output tensors of type float16 (`Uint16Array`) are decoded by `tensorFloats`; float32/float64 pass through; any other type throws. The reported model id comes from the backend: `name: "<card.name>@<card.version>"` (`backend.ts` -> `createEngine`); `meta.name` is only a fallback when no name is passed. + +### 6. Logits → calibrated probabilities → answers (`calibrate.ts`) + +0. `parseCalibration(json)` (backend load) fills missing `noul`/`choice`/`score` with 1.0 and `by_header` with `{}`, then throws `ModelUnsupportedError` if the file is not an object, any of the three is not a number > 0, or `by_header` is not an object. Other keys (`by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp`, `version`, and an unknown `_fit`) are passed through unchecked. +1. `hk = headerKey(header)` = `sha1(header)[:12]` (UTF-8). Example keys: `041ccfa6318c` = "What is happening here?", `bb11f7f0f3a7` = "What should the runtime do with this write?", `61d7c396157f` (request), `3616530c70a5` (failure), `94978d9e82be` (stall), `1b36f88322a0` (inconsistency), `6a2432a6e7de` (transition), `3f494eb3a731` (error). +2. choice/score: `tauFor(calib, kind, hk, K)` takes the first that applies: + 1. `by_header[hk]`; + 2. `by_bucket["<kind>:<bucket(K)>"]`, with buckets `2 | 3-5 | 6-10 | 11-30 | 31-100 | 101-255` (K > 255 → `101-255`); + 3. `tau_k[kind] = [a, b]` → `clamp(a + b·ln max(K, 2), bucket_clamp)` (default `[0.5, 5.0]`); + 4. `calib[kind]`. + Then `softmax(z / τ)` (max-subtracted, float64). +3. noul: `noulAffine` gives `[1/by_header[hk], 0]`, else `noul_platt (a, b)`, else `[1/calib.noul, 0]`. Then `p = sigmoid(a·z + b)`. +4. `buildAnswer(q, probs, precision = "exact", labels)`: + - choice: `normalizeProbs` (non-finite or ≤ 0 → 0, renormalize; all zero → uniform). `choice` = argmax (first label wins ties). `confidence = clip01((K·pmax − 1)/(K − 1))`. `probabilities` is a plain object in criteria order. + - score: `score = Σ i·p_i`. `confidence = max(0, 1 − Σ p_i·|i − mode| / MAD_uniform(K))`, with mode = first argmax and `MAD_uniform(K) = mean_i |i − (K−1)/2|`. `probabilities` is keyed `"0".."K−1"` (not the level texts). K ≤ 1 gives confidence 1 for both choice and score. + - noul: `noul = clip01(p)` (0.5 if p is not finite). + - `precision: "round"` rounds every number to 2 dp, half-even (`pyRound`), like the Jev server. +5. `EngineResult`: `{model: "<card.name>@<card.version>", answers, usage: {input_tokens, positions: max(position_id)+1}, timings}`. + +### 7. How the runtime consumes answers (detail in [decide-policy-actions.md](runtime/decide-policy-actions.md)) + +`runtime.ts` -> `onDecision`: + +- It reads `answers.action.probabilities`, or `{<passive>: 1}` when there is no `action` question. The top action is `answers.action.choice`, or the passive action if that choice is not offered. +- It reads `answers.diagnosis.choice`, or `expected`. +- `decide/policy.ts` -> `gate`: A = the permitted non-passive actions; the candidate is the argmax over A. The candidate runs iff `Σ_{a∈A} p(a)` ≥ the candidate tier's threshold (defaults guard 0.9, heal 0.8) and the diagnosis is not `expected` (unless `requireDiagnosis: false`). +- `Answer.confidence` is **not** used by the gate. `Decision.confidence` = `probabilities[action]`. + +### 8. Annotated example (real SIM row `sim-1071-d17` from `sim/samples/sample.jsonl`, budget 1,000) + +`state`/`questions` are exactly what the runtime handed its decider (843 chars by `stateChars`): + +```jsonc +{ "app": "Snapvault — /albums", // title — route, ≤ 60 chars at this budget + "trigger": "A write to routeData.model.photos, routeData.model.owners, routeData.model.activity and 2 more from GET /v1/photos/photos (#73) is about to be applied.", + "facts": [ // compact limit 6; 2 remain (the shrink loop never drops the last one); each ≤ 220 chars ("…") + "routeData.model.photos was written once by other operations since this write's cause (#73) started (version 7 → 8), last 0.16s ago by user navigated to link \"Albums\" (#87), which started 2.07s after #73, from a later us…", + "routeData.model.owners was written once by other operations since this write's cause (#73) started (version 8 → 9), last 0.16s ago by user navigated to link \"Albums\" (#87), which started 2.07s after #73, from a later us…" ], + "in_flight": [ "GET /v1/albums/photos (#88) 0.16s so far, by #87", "GET /v1/albums/albums (#89) 0.16s so far, by #87" ], + "timeline": "none", // emptied by the shrink loop (dropped first) + "state": "none", // emptied by the shrink loop, or no state lines to begin with + "stats": [ "GET /v1/photos/photos: 4 done, 0 of last 4 failed, 1 in last 10s" ] } +``` + +```json +{ "diagnosis": { "type": "choice", "instructions": "What is happening here?", + "criteria": { "expected": null, "stale": null, "conflict": null, "duplicate": null, "inconsistent": null, + "failing": null, "slow": null, "overload": null, "unusual": null, "transient": null } }, + "action": { "type": "choice", "instructions": "What should the runtime do with this write?", + "criteria": { "apply": null, "discard": null, "defer": null } } } +``` + +At budgets > 1,400 the same criteria carry descriptions (for example `"discard": "drop this write and keep the current state"`), and the item text becomes `discard: drop this write and keep the current state`. + +Packed (schematic): `[CLS] "app: Snapvault — /albums" [SEP] "trigger: A write to …" [SEP] "facts: <f1>\n<f2>" [SEP] "in_flight: <l1>\n<l2>" [SEP] "timeline: none" [SEP] "state: none" [SEP] "stats: GET /v1/photos/photos: …" [SEP] [Q] "What is happening here?" [O] "expected" … [O] "transient" [Q] "What should the runtime do with this write?" [O] "apply" [O] "discard" [O] "defer"`. + +- `q_group`: −1 for the state, 0 for diagnosis, 1 for action. +- Feed plan: `choice_q = [qPos_diag, qPos_action]`, `choice_items` is `[2, 10]` (the action row is padded with 0 after 3), and score/noul get dummy rows. +- `choice_logits [2, 10]` → diagnosis uses 10 values, action the first 3. +- Calibration: `by_header["041ccfa6318c"]` / `["bb11f7f0f3a7"]` if present, else `choice:6-10` / `choice:3-5` buckets, else `tau_k`, else `choice`. + +Labels and the cost evidence in `meta`: + +```json +"labels": { "action": { "type": "choice", "dist": { "apply": 0, "discard": 1, "defer": 0 } }, + "diagnosis": { "type": "choice", "label": "stale" } } +"meta": { "trigger": "mutation", "budget": 1000, "best": "discard", "passive_best": false, + "costs": { "apply": 69.2888, "discard": 64.6921, "defer": 67.9801 }, + "adjusted": { "apply": 4.347, "discard": 0, "defer": 3.288 }, "se": { "apply": 0.004, "discard": 0, "defer": 0.012 }, + "futures": 3, "non_passive_mass": 1, "transform": "default", "diagnosis": "stale", … } +``` + +How the label falls out of `actionLabel`: + +- Adjusted costs: apply = 69.29 + 0 (passive premium), discard = 64.69 + 0.25, defer = 67.98 + 0.25. No tie with passive, since the gaps exceed 0.05. +- Best = discard. gap_apply = 4.347 and gap_defer = 3.288, with τ ≈ 0.10–0.11. +- `exp(−gap/τ)` ≈ 0, so the distribution is one-hot on `discard`. + +#### Reading the STATUS.md examples + +`packages/runtime/STATUS.md` ("Example situations") prints situations with `stateText` (indented list items) and a display-only `questions:` footer; the model reads `key: line1\nline2` segments and the question blocks of section 3. What they show: + +- **Compact vs full** (`test/budget.test.ts`): the same stale write at budget 1,000 (998 chars) and 2,000 (1,494 chars). Limits at 1,000 are facts 6 / timeline 3, and the shrink loop leaves 1 timeline line; at 2,000, `r = 900/2100`, so timeline = `round(3 + 13r)` = 9 lines. At 1,000 the questions are bare labels (≤ 1,400); at 2,000 they carry descriptions. +- **One per trigger at 3,200** (`test/situation.test.ts`): mutation, request (redacted body `cardNumber: [redacted]`, `serve_cached` absent because the request is a POST and `serve_cached` needs a GET with a cached response, `state: none`, `stats: none`), failure, stall, inconsistency, transition, error. These strings are what `rt.py` must reproduce and what a wording change must update. + +### 9. SIM rows (`sim/src/gen/trajectory.ts` -> `generateTrajectory`) + +1. `buildScenario(seed)` fixes the domain, features, chaos, wording and `budget` (weighted 3,200:40 / 2,000:30 / 1,000:30). The split comes from `splitOf`: test if the domain is in `TEST_DOMAINS` (10 of 55), the family hash is in the held-out 17% (`"family-split-v1"`), or a pattern is in `TEST_PATTERNS`; dev if `hash("dev-split-v1", family) % 100 < 3`; else train. Test trajectories are kept with probability `testKeep` (CLI default 0.33). +2. **Ideal run** (no runtime, zero latency, exactly-once), then the **base run** on the real `createRuntime`. Options come from `sim/src/run/rt.ts` -> `createOptions`: `mode: "heal"`, `triage: "salient"`, `model: false`, `report: "silent"`, thresholds `{report 0, guard 0.5, heal 0.5}`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`, `historySize: 500`, observers fetch + timers + websocket only (xhr, user, errors, nav, storage, perf off; user actions and errors enter through `runtime.user()`/`reportError()`), `situation: {budget}`, `vocabulary` when paraphrased. The runtime module is `process.env.GENCLASS_RUNTIME ?? "@genclass/runtime"` (`realRuntimeFactory`), which also passes the sim's own `DEFAULT_DIAGNOSES` if the runtime's default vocabulary lacks any contract label. `--allow-fake` uses `sim/src/run/fake-runtime.ts` instead (`meta.runtime: "fake"`; tests only). + - The recording decider (`sim/src/run/runner.ts`) records `{state, questions}` verbatim, answers with probability 1 on the chosen action, and adds a lognormal virtual latency (median 6–25 ms, σ 0.35). + - Exploration ε ∈ {0, 0.08, 0.2} (weights 4:3:2) × `exploreScale`, used fully where the sim sees a problem and at ε/4 elsewhere. +3. Decision points (`pickPoints`): decisions with ≥ 2 actions, up to `maxPoints` (CLI default 6). They are weighted by `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2), ×1.5 when the sim's diagnosis is not `expected`. +4. `pointCosts`: for each action and each future j < K (default 3), re-run with the base run's explored choices before k, the action at k and passive after k. Each run stops at `t_k + W.finalMs` (15 s). + - Futures 1..K−1 re-seed everything after the decision with a salt `hashAll("future", seed, k, j)` shared across actions (common random numbers). When the scenario has external events after `t_k`, the ideal run is re-run with the same salt for that future. + - Adaptive: futures 1+ run only if some non-passive action beats passive by > 0.05 in future 0. `meta.futures` = the number of futures actually run (1 or K). + - Any prefix fingerprint mismatch, internal error or exception drops the point (`prefix-mismatch`, `cf-internal-error`, `cf-exception`). +5. `runCost(real, ideal, from, tEnd)`, with `stop = min(tEnd, from + 15 s, real.tStop)`, sums: + - `area`: ∫ client divergence over [from, min(stop, from + 10 s)]; + - 4.0 × final client divergence at `stop` + the server divergence `serverDist` vs the ideal server state at `stop`: per collection `25 × min(5, extra/missing items) + 6 × min(5, changed items)`; per document `6 × min(3, differing fields)`; per counter `6 × min(3, |difference|)` (counters ending in `beats` ignored); + - 1.5 × extra shown-error episodes + 1.0 × extra uncaught errors (counts in [from, stop] beyond the ideal run's); + - 0.08 × requests beyond the ideal run per signature (requests that arrived at the server in [from, stop], `NetEntry.ta`); + - 0.25 × seconds non-background ops were pending inside [from, stop]; + - 0.8 × ∫ violated app relations over [from, min(stop, from + 10 s)] + 2.0 × relations still violated at `stop`. + Client divergence `clientDist` = Σ over store fields of `weight × valueDist` (weights from the app, default 1; the first field (`fields[0]`) of every violated app relation counts its full weight even if it equals the ideal value, and is then skipped in the per-field comparison). `valueDist` ∈ [0, 1]: lists compare as multisets of content with volatile keys (`id, version, rev, revision, etag, updatedAt, updated_at, clientId, pending, seq`) ignored; objects recurse to depth 3 averaging over non-volatile keys; numbers equal within 1e-9. +6. `actionLabel(futures, passive)`: + 1. Premium per action tier: passive 0, guard 0.25, heal 0.5. + 2. A non-passive action whose mean cost is within 0.05 of passive's is a tie and is pinned to passive's costs + 1.5. + 3. Best = lowest mean adjusted cost (passive wins exact ties). + 4. `p_a ∝ exp(−max(0, mean(adj_a − adj_best)) / (0.1 + 1.0·SE_a))`, rounded to 1e-4. `SE_a` = sample SD of the paired per-future differences / √K (0 with one future). Futures are paired by index and truncated to the shortest list. + 5. `meta.costs` = per-action mean raw cost (1e-4); `meta.cost_futures` = the raw per-future costs (1e-4); `meta.adjusted` = gap to best (1e-3), `meta.se` (1e-3), `meta.non_passive_mass` (1e-4). +7. `transformQuestions`, with an independent RNG per row: + - 50%: unchanged. + - Otherwise, for `action` only: with p 0.12, if there are ≥ 3 options, drop one option that is neither passive nor best and renormalize the distribution. With p 0.5, shuffle the options. + - `meta.transform` records the variant (`default`, `drop:<a>`, `shuffle` or `drop:<a>,shuffle`). + - Instructions and descriptions are never changed. Wording variation comes from the runtime's `vocabulary`, per trajectory: + - diagnoses: 50% default; otherwise each label is paraphrased with p 0.6, and with p 0.3 one or two of `conflict, slow, overload, unusual, inconsistent, duplicate, transient` are dropped; + - actions: 50% default; otherwise each action is paraphrased with p 0.6 (`ACTION_PARA`). +8. Labels written: `labels.action = {type: "choice", dist}` always. `labels.diagnosis = {type: "choice", label: diag}` only if the sim's diagnosis is in the row's criteria and the subject correlated; otherwise the row is still emitted, counting drops `diagnosis-not-in-vocab` / `diagnosis-uncorrelated`. + - The diagnosis is **not** derived from costs or from the runtime's text: `sim/src/oracle/diagnose.ts` -> `diagnose(trigger, subject, ctx)` maps the sim's ground truth (superseded intent → `stale`, competing intents → `conflict`, repeated intent → `duplicate`, broken app relation → `inconsistent`, failure streak/outage → `failing`, isolated 5xx/network/timeout → `transient`, latency anomaly → `slow`, rate anomaly → `overload`, genuine shape anomaly/server bug → `unusual`, else `expected`). Exact rules per trigger: [sim.md](sim.md) flow 8. +9. Other row kinds: + - **Diagnosis-only** rows (`sim-<seed>-s<k>`): up to 3 per trajectory, sampled from decisions with < 2 actions, a diagnosis and a correlated subject; questions = the recorded `questions` **untransformed** (normally just `{diagnosis}`); meta `{…scenario meta, trigger, decision, t, diagnosis, diagnosis_only: true, subject}`. + - **Ask** rows (`sim-<seed>-a<i>`, family `<scenario family>/ask`): `runtime.situation("ask")` (always about `"now"`, so `trigger` = `The developer asks about the app right now.`) at 1–3 probe times (`scenario.askTimes`), with 1–3 questions from `askQuestions` (generators tried in shuffled order, each may return null). Labels are exact. The generators that name things (`last_failed`, `route`, `slowest`) check that their evidence appears in `JSON.stringify(state)`; the timing generators skip borderline values (table below). Meta `{…scenario meta, trigger: "ask", t, kinds}`. + + | qid | type | options (criteria) | label | skipped when | + |---|---|---|---|---| + | `q_write_inflight` | noul | true `yes, a write is in flight` / false `no write is in flight` | a POST/PUT/PATCH/DELETE in flight | never | + | `q_any_inflight` | noul | default (`yes`/`no`) | any request in flight | never | + | `q_pending` | score | `none, one, two, three or more` or `0 requests, 1 request, 2 requests, 3+ requests` | `min(3, in-flight count)` | > 6 in flight | + | `q_last_failed` | choice | `e1..e3` = endpoint signatures, `none` = a "none" phrase | id of the last failing signature (≥ 400 or network error, last 12 s), else `none` | < 2 known signatures; its path tail not in the text | + | `q_recent_failure` | noul | default | a failure in the last 5 or 10 s | a failure within 1 s of the window edge | + | `q_fail_count` | score | `none, one, two, three or more` | `min(3, failures in last 10 s)` | counts at 9 s and 11 s differ | + | `q_user_waiting` | noul | default | user-initiated wait > N s (N ∈ 1, 2, 3, 5) | within 400 ms of N s | + | `q_user_recent` | noul | default | user input within N s (N ∈ 1, 2, 3) | within 300 ms of N s | + | `q_last_save` | noul | true `the last save succeeded` / false `the last save failed` | last save ok | no save yet | + | `q_route` | choice | `r1..r3` = the route + 2 from a fixed list (`/settings`, `/home`, …) | id of the current route | route not in the text | + | `q_slowest` | choice | `o1..o4` = in-flight signatures | id of the oldest in-flight request | < 2 in flight; top two within 300 ms or same signature; a path tail missing from the text | +10. Ids, family and meta: + - Ids: `sim-<seed>-d<k>` (decision), `-s<k>`, `-a<i>`. `family` = `<scenario family>/<trigger>`. + - Decision meta: `seed, domain, family, chaos, budget, runtime, features, patterns, trigger, decision, t, explored_before, best, passive_best, costs, cost_futures, futures, adjusted, se, non_passive_mass, cost_parts{area, final_client, final_server, relation_s, relation_final, errors, uncaught, wasted, latency_s}, tiers, diagnosis, subject{kind, how, ref?}, transform, fake_diagnosis?`. + - Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/part-NNNNNN.<split>.jsonl`, written as `.tmp` and renamed when the part completes, with a `part-NNNNNN.json` marker; `--merge-only` concatenates them). `stats.json` `token_estimate` is `(len(JSON state) + len(JSON questions)) / 3.6`, not real tokens. + - `--sample`: target 900 rows, `testKeep` 1, then a stratified 200 rows (round-robin over `trigger|diagnosis|act-or-passive`) to `sim/samples/sample.jsonl`, plus `EXAMPLES.md` (`renderExamples`) and `sample-stats.json`. Full CLI: [sim.md](sim.md). + +### 10. Training consumes rows (`jev_local/train/train.py` -> `encode_example`, `parse_target`) + +1. Every question goes through `question_from_json` → `question_block`, and the state through `state_segments`. This is the Python original of `model/serialize.ts`, so SIM rows (written by `JSON.stringify`) render identically on both sides. +2. `parse_target(block, label)`: + - noul `p` → `[p]` (hard if 0/1). + - choice `label` → one-hot over `block.labels` (rejected if not an option). + - choice `dist` → values aligned to `block.labels` (missing → 0), renormalized; always `hard=False`, **even when one-hot**, so label smoothing never applies to SIM action labels (they are always `dist`). A dist summing to 0 is rejected. + - score `level` → one-hot (rejected outside `0..K−1`); score `dist` (length must equal K) → renormalized, soft. + - A type mismatch or bad label makes the question unsupervised (`bad_labels`); a label for a qid that has no question is ignored by the trainer (the curriculum's `_validate` rejects such rows). +3. `Packer.pack_split(segments, blocks, --max-len)`: questions are isolated, so an over-long example splits into several sequences that repeat the state (greedy, in request order). A question whose state + whole block exceeds `max_len` is dropped (`dropped_qids`); a state that alone exceeds `max_len` therefore drops every question. +4. Losses (`jev_local/train/losses.py`): proper scoring rules. Defaults reproduce v1 (CE, label smoothing 0.02 on hard labels, RPS 0.25 on score). See [training.md](training.md) for the configs actually used. +5. Final round 1 (`training/launch_final1.sh`, `training/configs/mix_final1.json`): `--max-len 2048`, `--batch-tokens 8192`, mixture `simA 0.85, cur4 0.12, cur1 0.02, gen 0.01`, `pass_tokens` 500,000,000, `max_repeat` `{"*": 2.0, "simA": 1.3}`. +6. Curriculum rows (`rows.py`; full detail in [training.md](training.md)): + - `decision_row` emits either runtime-exact text (`rt.render`, style `runtime`, share `--p-runtime` = env `GC_P_RUNTIME`, default 0; `cur4` used 0.8) or varied text (style `varied`; also the fallback when `rt.render` returns `None`, e.g. a scenario with no `spec` or `no_runtime`). Runtime-style rows get the runtime's exact questions plus 0–2 primitive questions (choice of `(0, 0, 1, 2)`); `action` is labelled only if `rt.render` produced an `action` question. + - Varied text: renamed keys (`KEY_VARIANTS`), op/time/duration formats (`Style.make`), facts ≤ 12 shuffled (25%), one of `in_flight`/`stats`/`state` dropped (15%), key order shuffled (10%), state ≤ 8 lines, timeline ≤ 16; action labels renamed (10%, each with p 0.5, `RENAMES`), 1–2 `DISTRACTOR_ACTIONS` inserted (15%), options shuffled (50%), descriptions = canonical (50%) or a paraphrase; diagnosis subset of gold + `expected` + 2–5 others (20%), shuffled (50%); bare `null` criteria (10% per question); question order swapped (15%); 0–3 primitives (choice of `(0, 1, 2, 2, 3)`). Headers come from `fmt.ACTION_INSTR[trigger]` (some with `{subj}`) and `fmt.DIAG_INSTR`; these lists do **not** contain `What is happening here?` nor the runtime's exact failure/inconsistency/transition headers, so those four strings appear only in `rt.render` rows (the runtime's mutation, request, stall and error action headers are also among the varied choices). + - `ask_row`: varied state with an ask trigger sentence (`facts` dropped 30%), 2–5 primitive questions, meta `{kind: "ask", trigger: "ask", source_trigger, case, domain, prims}`, family `cur/ask/<trigger>`. + - Decision meta: `kind, trigger, case, domain, passive_best, action_gold, action_canonical, passive, diag_gold, action_names, prims, heldout_templates_possible, soft_action, style`; family `cur/<trigger>/<case tail>`. `meta.action_names` maps canonical → shown names (`eval_runtime.canonical` reverses it). + - `generate.py` writes ids `cur-<split>-<chunk:05d>-<i:06d>`, applies `js_numbers` to `state` and `questions` (integral floats → ints, as JS prints them; labels and meta untouched), and drops rows that fail `_validate` (jev_local `state_segments`/`question_block`/`parse_target`, no unknown qids, ≥ 1 label). + +### 11. Evaluation and calibration fit (`training/eval_runtime.py`) + +CLI: `--ckpt` (required), `--data DIR` (required; reads `DIR/<split>.jsonl`), `--split` (default `test`), `--fit-split`, `--limit`, `--batch` (16), `--threads` (32), `--out report.json`, `--write-calibration`, `--calibration` (evaluate with a given file; reads only `noul`, `choice`, `score`, `by_header`, so v2 keys are ignored), `--records-dir` (cache raw logits as `<ckpt>__<data>__<split>.jsonl`), `--header-calibration`. + +1. Raw logits per supervised question come from `jev_local.train.eval.collect`. `header` is the header key (`sha1(header)[:12]`, computed in `jev_local/train/eval.py`). +2. `fit_calibration` (on `--fit-split`): + - noul τ on a 61-point log grid in [0.2, 5]; + - choice τ by golden section on log τ in [0.2, 5] (40 iterations) over all choice questions, `action` and `diagnosis` included; + - score τ the same way; + - `action` and `diagnosis` also get their own τ (used by the `group` metric mode, never written); + - `by_header` (sha1 keys) only for standing questions with ≥ 300 examples. + - Split-half check: refit on fit-split records with even `crc32(id)`, evaluate on odd ones (`report.split_half`). + - Metric modes: `raw` (τ 1), `kind` (per-kind τ, what the runtime does with a v1 file), `group`, `header`; the report has `questions_<mode>` (acc, NLL, Brier, ECE 15 bins) and `decisions_<mode>` for each, plus `primitive_acc`. Rows are bucketed by `meta.budget` (else by state chars `≤1100` / `≤2100` / `>2100`) for `by_budget`. +3. `--write-calibration` writes `{noul, choice, score, by_header, _fit}`. `by_header` stays `{}` unless `--header-calibration` is passed, and `final_post.sh` (which runs the eval through `training/eval_sim.sh`) does not pass it. Shipped files are therefore v1 per-kind temperatures; the runtime ignores `_fit`. +4. Decision metrics re-implement the runtime §8 gate (summed mass, `THRESH` guard 0.9 / heal 0.8, top diagnosis ≠ `expected`; unknown actions count as heal). Reports per trigger/case/style/budget: FIR, precision, recall, mean counterfactual cost vs always-passive vs oracle (SIM rows with `meta.costs`), plus a threshold sweep. + +### 12. Export → model directory (`training/export_runtime.py` -> `main`) + +Run by `training/final_post.sh` after the eval (`eval_sim.sh simAe <M>`): `--calibration out/cal/<M>-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 --threads 24`; it then tars the export without `ref/` for `pull_on_train.sh`. + +CLI defaults: `--ckpt`, `--out` (required), `--name genclass-runtime`, `--version 0.1.0`, `--requests` (a JSON list) or `--data-rows a.jsonl,b.jsonl`, `--n-per-file 40`, `--calibration` (default: the checkpoint's), `--opset 17`, `--threads 16`, `--block 32`. It imports `jev_local` and `genclass_export` from `~/jev` and `~/jev/scripts` (VM layout). Steps: + +1. `load_checkpoint(ckpt, "cpu", float32, encoder="reference")`; `ExportModel(enc, heads)`; parity requests sampled per file (random permutation, seed 0) keeping those that pack to ≤ 1,500 tokens with the Python `Packer(tok, max_len=8192)`. +2. `torch.onnx.export` fp32 and fp16 references into `ref/` with dynamic axes `L` (tokens), `G/K` (choice), `S/K2` (score), `M` (noul). +3. `make_q8`: `gemm_to_matmul` (Gemm with transA 0, alpha = beta = 1 and an initializer weight → MatMul [+ Add]), `MatMulNBitsQuantizer` (8-bit, block 32, symmetric, axis 0), then `quantize_embedding` (per-row `scale = max|row| / 127`, zero rows scale 1, `q = clip(rint(w/scale), −127, 127)`); refuses any fp16 initializer or Cast-to-fp16. `make_fp16`: the fp16 reference with the same int8 embedding, scale stored fp16. +4. Parity on CPU (ORT `CPUExecutionProvider` with `--threads` intra-op threads for fp32/fp16/q8, plus a 1-thread session for fp16/q8 only) vs `FastEngine(…, encoder="banded")` logits, both calibrated with the shipped calibration → `parity.json`. +5. Copy tokenizer, write calibration, `meta.json`, then `model.json` with byte sizes and sha256 of every file. + +| file | content | +|---|---| +| `model.json` | `{format: "genclass-runtime-model/1", name, version, license: "Apache-2.0", variants: {q8: {file, bytes, sha256, provider: "wasm"}, fp16: {file, bytes, sha256, provider: "webgpu", needs: "shader-f16"}}, files: {tokenizer, calibration, meta: {file, bytes, sha256}}}` | +| `<name>-q8.onnx` | MatMulNBits 8-bit, block 32, symmetric, on every MatMul (Gemm rewritten first) + int8 row-wise token embedding (Gather int8 → Cast fp32 → Mul per-row scale); must contain no fp16 tensor | +| `<name>-fp16.onnx` | fp16 weights/compute, fp32 I/O, int8 embedding (Cast fp16) | +| `tokenizer.json` | copied from `<ckpt>/backbone/tokenizer.json` (pruned: 16,000 merges, 16,364 tokens) | +| `calibration.json` | `--calibration` file, else the checkpoint's | +| `meta.json` | `name` (`<name>-<version>`), `source_checkpoint`, `max_len` (checkpoint meta, else 1536; 2048 for final round 1), `max_total: 8192`, `window`, `hidden_size`, `layer_types`, `markers`, `cls_id`, `sep_id`, `pad_id`, `vocab_size`, `merges_kept`, `inputs`, `outputs: ["choice_logits","score_logits","noul_logits"]`, `embedding_quant`, `matmul_quant`, `license` | +| `requests.json` | `[{id, state, questions, tokens}]`: parity requests (≤ 1,500 tokens, `--n-per-file` per data file) | +| `pack_fixtures.json` | per request `{id, input_ids, position_ids, q_group, i_group, n_state, q_index: {qid: {kind, header, labels, q_pos, item_pos}}}` from the Python packer | +| `torch_fixtures.json` | per request `{id, logits: {qid: [...]}, probs: {qid: [...]}, header_key: {qid: hk}}` (PyTorch, calibrated with the shipped file) | +| `parity.json` | per variant `fp32`/`fp16`/`q8`: `max_abs_logit`, `max_abs_prob`, `argmax_agree`/`argmax_total`/`argmax_rate`, `noul_side_agree`/`noul_total`/`noul_side_rate`, `gate08_agree`/`gate09_agree`/`gate_total`/`gate08_rate`/`gate09_rate` (same argmax and same side of pmax ≥ 0.8 / 0.9 on choice questions), `ort_cpu_ms_p50`, `ort_cpu_1thread_ms_p50` (fp16, q8), `file_mb`; plus `n_requests`, `tokens{min, median, max}`, `embedding_q8`, `embedding_fp16` (quantization error stats) | +| `ref/` | `<name>-fp32.onnx`, `<name>-fp16-fullemb.onnx` references (not in the card; excluded from the served tar) | + +Shipped candidates (MODEL_CARD, measured at stage 1c): R17 `genclass-runtime-r17` (ettin-encoder-17m, d 256, 7 layers, 8.1M + 0.7M heads) q8 9.6 MB / fp16 13.6 MB; R32 `genclass-runtime-r32` (ettin-encoder-32m, d 384, 10 layers, 18.8M + 1.6M heads) q8 22.5 MB / fp16 34.8 MB; both vocab 16,364. + +The runtime reads `model.json` (`loader.ts` -> `parseCard`; missing `files` default to `tokenizer.json`/`calibration.json`/`meta.json`; `files` entries may be bare file names; file names must be relative with no scheme, leading slash, `..` or empty segment; `sha256` may carry a `sha256:` prefix; `format` defaults to `CARD_FORMAT` and is **not** checked; `name`/`version` default to `genclass-model`/`0.0.0`), then the `meta.json` keys listed in Concepts and every `calibration.json` key listed in step 6. Load plans (`planOrder`): webgpu+fp16 (needs `shader-f16`) → webgpu+q8 → wasm+q8 (wasm+fp16 if the card has no q8; only when the card has neither `q8` nor `fp16` are its other variant names tried on WASM in card order). `device: "auto"` skips WebGPU on a software (fallback) adapter; `"wasm"` never touches the GPU. The default base URL is `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`host.ts` -> `DEFAULT_MODEL_BASE_URL`), and that package is not published yet. More in [model-host.md](runtime/model-host.md). + +## Configuration and constants + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `STATE_CHAR_BUDGET` | number | 3200 | `situation/serialize.ts` | full section sizes; default budget | +| `COMPACT_BUDGET` | number | 1100 | `situation/serialize.ts` | budget at or below which section limits are minimal | +| `MIN_BUDGET` | number | 500 | `situation/serialize.ts` | smallest budget honoured | +| `LIMITS` (full) | object | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | lines per section at ≥ 3,200 | +| compact section limits | — | facts 6, in_flight 2, timeline 3, state 3, stats 1 | `serialize.ts` -> `sectionLimits` | lines per section at ≤ 1,100 | +| line limits compact→full | — | app 60→120, trigger 180→240, facts 220→260, in_flight 90→120, timeline 100→140, state 100→150, stats 110→140 | `serialize.ts` -> `sectionLimits` | per-line truncation | +| last-resort fact/trigger floor | — | 60 chars | `serialize.ts` -> `toJevState` | pathological over-budget case | +| `COMPACT_QUESTIONS_BUDGET` | number | 1400 | `situation/questions.ts` | bare labels/names at or below | +| `COMPACT_DESC_MAX` | number | 24 | `situation/questions.ts` (private) | vocabulary override kept in compact mode | +| `MAX_FACTS` | number | 12 | `situation/facts.ts` | facts kept before budgeting | +| plugin fact length | — | 240 | `build.ts` -> `buildSituation` | plugin fact truncation | +| phrase truncations (before line limits) | chars | `opLabel` phrase 90; in-flight phrase 80; error trigger message 120 (`Situation.subject` 80); timeline start/end phrase 80, write summary 110, error 100, navigate 60, GenClass action 100, custom name/summary 60/60, storage key 40; state value 90 (`describe`), store-level `describe` 110 | `describe.ts`, `build.ts` | text shape | +| timeline candidates | — | last 96 events | `build.ts` -> `timelineLines` | events considered | +| auto budget | — | webgpu/unknown 3,200; wasm `1000 + round((t−1)·1000/3)`, t ∈ 1..4 | `runtime.ts` -> `situationBudget` | device-sized situations | +| `budgetScale` | number | 1, ×0.8 per `max_tokens_exceeded`, floor 0.5 | `runtime.ts` | shrinks auto budgets only | +| `MAX_ARRAY_SEGMENTS` | number | 64 | `model/serialize.ts` | array states | +| `DEFAULT_NOUL/CHOICE/SCORE_INSTR` | string | see step 3.5 | `model/serialize.ts` | empty instructions | +| `Packer.maxPositions` | number | `meta.max_len` ?? 1536 | `packer.ts`, `engine.ts` | positions limit | +| `Packer.maxTotal` | number | `meta.max_total` ?? 8192 | `packer.ts`, `engine.ts` | whole-sequence limit | +| packer text cache / tokenizer word cache | number | 8192 / 20000 | `packer.ts` / `tokenizer.ts` | cleared when full | +| `MARKERS` | tuple | `[Q] [O] [L] [T] [F]` | `packer.ts` (= `tokenize_pack.MARKERS`) | head read points | +| `ID_SPACE` | number | 2^26 | `tokenizer.ts` | max token id | +| `K_BUCKETS` | list | 2, 3-5, 6-10, 11-30, 31-100, 101-255 | `calibrate.ts` | `by_bucket` keys | +| `BUCKET_CLAMP` | pair | [0.5, 5.0] | `calibrate.ts` | τ(K) clamp | +| calibration defaults | number | `noul`/`choice`/`score` 1.0, `by_header` `{}` | `calibrate.ts` -> `parseCalibration` | missing keys | +| header-key cache | number | 4096 | `calibrate.ts` -> `headerKey` | — | +| `Precision` default | string | `"exact"` | `engine.ts` | `"round"` = 2 dp half-even | +| policy thresholds | number | report 0.6, guard 0.9, heal 0.8 | `decide/policy.ts` | gate on calibrated probabilities | +| `W` | object | area 1.0, horizonMs 10000, finalMs 15000, finalClient 4.0, serverItem 25.0, serverField 6.0, shownError 1.5, uncaught 1.0, relation 0.8, relationFinal 2.0, wasted 0.08, latency 0.25 | `sim/src/oracle/cost.ts` | run cost | +| `LABEL` | object | tier {passive 0, guard 0.25, heal 0.5}, exactTie 1.5, tieEps 0.05, tau0 0.1, seMul 1.0 | `sim/src/oracle/cost.ts` | soft action label | +| futures K / adaptive gain | number | 3 / > 0.05 | `trajectory.ts` -> `pointCosts` | label sharpness | +| `TRIGGER_W` | object | see step 9.3 | `trajectory.ts` | decision point sampling | +| sim CLI defaults | — | rows 1000, seed 1, workers 4, max-points 6, test-keep 0.33, explore 1, ask on | `sim/src/gen.ts` -> `parse` | generation | +| scenario budgets | weights | 3200:40, 2000:30, 1000:30 | `sim/src/world/scenario.ts` | `meta.budget` | +| transform | prob | unchanged 0.5; drop 0.12 (≥ 3 options); shuffle 0.5 | `sim/src/run/transform.ts` | option order/subsets | +| sim gate thresholds | number | report 0, guard 0.5, heal 0.5; `requireDiagnosis: false` | `sim/src/run/rt.ts` | forced action runs exactly | +| eval `THRESH` | number | guard 0.9, heal 0.8 | `training/eval_runtime.py` | must mirror the runtime | +| eval calibration fit | — | τ ∈ [0.2, 5]; noul grid 61; by_header ≥ 300 examples; ECE 15 bins | `training/eval_runtime.py` | `calibration.json` | +| export | — | opset 17, block 32, `max_total` 8192, parity requests ≤ 1,500 tokens, `--n-per-file` 40 | `training/export_runtime.py` | model directory | +| `CARD_FORMAT` | string | `genclass-runtime-model/1` | `loader.ts`, `export_runtime.py` | card format (written, not validated on read) | +| `DEFAULT_CACHE_NAME` | string | `genclass-runtime-v1` | `loader.ts` | Cache Storage bucket for model files | +| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | where the card is fetched (package unpublished) | +| export `OUTPUTS` | list | `choice_logits, score_logits, noul_logits` | `export_runtime.py` | `meta.outputs` | +| export CLI | — | `--name genclass-runtime`, `--version 0.1.0`, `--n-per-file 40`, `--opset 17`, `--threads 16`, `--block 32` | `export_runtime.py` -> `main` | model directory | +| eval CLI | — | `--split test`, `--batch 16`, `--threads 32`; `N_BINS` 15 | `eval_runtime.py` -> `main` | report / calibration | +| `--p-runtime` / `GC_P_RUNTIME` | float | 0.0 (`cur4`: 0.8) | `training/curriculum/generate.py` | share of runtime-exact decision rows | +| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` -> `realRuntimeFactory` | runtime module the sim imports | +| `GENCLASS_MODEL_DIR` | env | `<repo>/.cache-model` | `packages/runtime/test/model/helpers.ts` | model directory for parity tests; fixtures come from it when it ships `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, else from `test/fixtures/model/` (v0.1) | +| sim runtime options | — | `historySize` 500, `holdBudgetMs` 1e9, `maxActionsPerMinute` 1e9, `report: "silent"` | `sim/src/run/rt.ts` -> `createOptions` | no time/rate limits on forced actions | + +## Invariants and gotchas + +- **Parity chain:** runtime text → `JSON.stringify` (sim row) → Python `serialize.py` → `tokenize_pack.Packer` → PyTorch. On the serving side: runtime text → `toJsonValue` → `model/serialize.ts` → `Packer` (TS) → ORT. Both sides must produce identical token ids. Do not "improve" `pyStrip`, `pyNumber`, `entryText`, the item `label: desc` rule or marker placement on one side only. +- **JS numbers vs Python floats:** JS can only print `25`, never `25.0`. Rows produced in Python must write integral floats as ints (`fmt.js_numbers`). Otherwise the model trains on text the runtime never sends. `test/model/helpers.ts` -> `pythonOnlyFloatRequests` skips such fixtures. +- **Two different compact constants:** `COMPACT_BUDGET` (1,100) shapes sections, while `COMPACT_QUESTIONS_BUDGET` (1,400) bares the questions. Budgets in (1,100, 1,400] get almost-minimal sections plus bare questions. +- **`facts` floor is 1:** the shrink loop never removes the last fact, so the trigger sentence plus one fact (when there was any) always survive; in the pathological case both may be shortened to 60 chars. +- **Display ≠ model text:** `stateText` (STATUS.md, `explain()`, devtools) indents list items. The model reads `key: line1\nline2`. +- **Qids are invisible to the model:** only headers and items are tokenized. Renaming a qid changes nothing for the model but breaks `answers.action`/`answers.diagnosis` lookups. A header change, by contrast, changes the text *and* the `by_header` key. +- **Option order is irrelevant to the model** (isolation), but it decides the order of `probabilities` and the tie-break of `choice`. Plain-object criteria with integer-like labels are reordered by JS. Pass a `Map` to keep the order. +- **Question order:** `diagnosis` comes before `action` in runtime situations. The curriculum swaps it in 15% of varied rows. Answers do not depend on it. +- **`action` is absent when only one action applies:** consumers must treat a missing `answers.action` as passive (`onDecision` does). +- **The runtime never truncates inside the model host:** a situation that does not fit throws `max_tokens_exceeded`, the decision fails open, and auto budgets shrink by 20% (to ≥ 50%). Training drops (does not truncate) questions whose block does not fit `--max-len`. +- **Length semantics differ:** the runtime bounds state + longest branch (`max_len`). The trainer's `pack_split` bounds state + the whole question block per sequence. A many-option question can be valid at runtime yet never have been trained. +- **Markers and specials are read from files:** a re-pruned tokenizer moves ids, and `meta.json` must agree with `tokenizer.json` or loading fails (`ModelUnsupportedError`). +- **Calibration keys are text-sensitive:** any change to an instruction string orphans its `by_header` entry. Shipped files have `by_header: {}`, so this matters only if `--header-calibration` is used. +- **The gate uses probabilities, not `confidence`:** recalibrating changes intervention rates. Re-run `eval_runtime.py` with the new file and compare FIR/precision before shipping. +- **The sim needs thresholds 0.5:** the decider answers with probability 1 on the forced action, so the permitted mass is 1 or 0. A threshold of 0 would run the argmax non-passive action even when passive is forced (comment in `sim/src/run/rt.ts`). +- **Sim determinism:** the counterfactual prefix check compares `JSON.stringify([trigger, state, questions])` for every decision up to k. Any nondeterminism in situation building (time, random ids, iteration order) shows up as `prefix-mismatch` drops. `situation()` must stay side-effect free. +- **`x-request-id` is the sim's correlation header:** the runtime excludes it from request identity and never serializes it. `sim/test/rows.test.ts` asserts it never appears in a state. +- **Description vs effect:** the `rollback` description says "last consistent snapshot", but transition/error rollback restores only the op chain's own writes. Changing the text is a model-input change. +- **SIM action labels are never label-smoothed:** they are always `{type: "choice", dist}`, which `parse_target` marks soft even when one-hot. Converting them to `label` would change the loss. +- **`budgetScale` only shrinks:** each `max_tokens_exceeded` multiplies it by 0.8 (floor 0.5) and nothing resets it for the life of the runtime (`runtime.ts`). Numeric `situation.budget` values are never scaled. +- **Standing question id `action`:** it is skipped only when the built-in `action` question exists. With ≤ 1 applicable action (only the passive one, which is always applicable) it is inserted, and `onDecision` copies its `probabilities` into the decision as if they were action probabilities. The gate still runs nothing (no non-passive action is offered), but reports are misleading. Avoid standing-question ids `action`/`diagnosis`. +- **`situation()` is almost side-effect free:** `env.ts` notes it caches field versions in `op.reads`. Anything more breaks the sim's prefix fingerprints. +- **Varied curriculum headers ≠ runtime headers:** `fmt.ACTION_INSTR`/`DIAG_INSTR` never produce `What is happening here?` or the runtime's failure/inconsistency/transition headers. If `--p-runtime` is 0, the model never sees those exact strings from the curriculum (SIM rows still carry them). +- **Python vs JS number text in `rt.py`:** Python `f"{x:.2f}"` rounds exact binary ties half-even, while JS `toFixed(2)` rounds them up (125 ms → Python `0.12s`, JS `0.13s`; 12.25 s → `12.2s` vs `12.3s`). `rt.py`'s `secs`, `rel` and `fmt_num` therefore differ from `util.ts` on such values. `secs` ≥ 1000 s and `ratio` ≥ 10× also use Python `round()` (banker's) where `util.ts` uses `Math.round`. This affects runtime-exact curriculum rows only; SIM rows record the runtime's own text. +- **Truncation units:** `util.truncate` counts UTF-16 code units, `rt.py.truncate` counts code points. They differ only for astral-plane characters (emoji), and the TS cut can split a surrogate pair (behaviour downstream of a lone surrogate is unverified). + +## How to change it safely + +### Versioning: what invalidates the trained model + +`situation-v1` is a git tag on commit 1a77558 ("Runtime fix batch 3", 2026-10-07). It freezes the text the SIM final data (phase A: train 448,420 / dev 14,613 / test 137,643, per `training/LOG.md`) and the final training round were built on. At 654d822, `packages/runtime/src`, `jev_local/` and `scripts/genclass_export.py` are unchanged since the tag. The sim changed after the tag in 59c213f: correlation header `x-sim-op` → `x-request-id` (excluded from request identity), sim thresholds 0 → 0.5, 1-thread budget 1100 → 1000, resumable parts. Phase A rows carry budgets 1000/2000/3200 (`training/LOG.md`), so at least the budget change was in effect. Whether the other changes were in effect when phase A was generated is (unverified). The same commit changed the training side: `training/curriculum/rt.py` was re-ported to the frozen `situation-v1` wording (relation phrasing such as "started 0.09s after #6", "pending local change" fact, error-rate text, slug-id signatures, budget-shaped sections via `section_limits`/`to_state`; compact questions and `transient` were already in `rt.py` before the tag, at a53dd38), `fmt.js_numbers` was added and applied in `generate.py`, and `eval_runtime.py` gained `by_budget`. `cur4` (300k rows, seed 5, 80% runtime-exact) was generated with that wording (`training/LOG.md`). Curriculum sets made earlier (`cur1`, `cur2`, `cur3`) predate it. + +| change in … | invalidates | required follow-up | +|---|---|---| +| `situation/{build,facts,describe,serialize,questions}.ts`, `util.ts` formatting/redaction, `state/hub.ts` change summaries, signature normalization, baselines/profiles numbers that appear in text | model input text | regenerate SIM data, re-port `training/curriculum/rt.py`, retrain, re-eval, re-export; new freeze tag | +| `DEFAULT_DIAGNOSES`, `BUILTIN_ACTIONS` descriptions, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `TRIGGER_ACTIONS` membership/order, compact thresholds | model input text and label space (and `by_header` keys) | same as above; also update copies in `sim/src/types.ts` (`PASSIVE`, `DIAGNOSES`), `sim/src/world/scenario.ts` (`DEFAULT_DIAGNOSES`, `DIAG_PARA`), `sim/src/run/transform.ts` (`ACTION_PARA`), `sim/src/oracle/cost.ts` (`TIER`), `fmt.py`, `rt.py`, `eval_runtime.py` (`TIER`, `PASSIVE`) | +| `sectionLimits`, `STATE_CHAR_BUDGET`, auto budget mapping, scenario budget weights | situation length distribution | regenerate data, retrain; check token percentiles vs `max_len` | +| triage / trigger conditions (`learn`, `runtime.ts`) | which situations get recorded (distribution), not text | regenerate data; retrain recommended | +| `model/serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts`, `FEEDS` | token ids | change `jev_local` in lockstep, re-run parity tests; retrain if the Python side changed | +| `tokenizer.json` (pruning), heads, graph inputs/outputs | the model | retrain/re-export; `meta.json` `inputs`/`outputs`/`markers` | +| `calibrate.ts` math or `calibration.json` | answers, not text | re-run `eval_runtime.py`; check `calibrate.test.ts` parity | +| `sim/src/oracle/{cost,diagnose}.ts`, `trajectory.ts`, `transform.ts`, `ask/questions.ts`, `scenario.ts` splits/vocab | labels/targets | regenerate data, retrain (`meta.cost_futures` lets you re-derive action labels offline without re-simulating) | +| `training/curriculum/{rt,fmt,rows}.py`, scenario modules | curriculum text/labels (training distribution, not runtime text) | regenerate the curriculum set (e.g. a new `curN`), update the mixture, retrain; `rt.py` must still equal the runtime's text | +| `eval_runtime.py` metrics, `export_runtime.py` graph surgery/quantization | evaluation numbers / the ONNX files, not the trained weights | re-eval or re-export; re-run `test_export_runtime.py`, `ortweb/validate.mjs`, the runtime parity tests | +| `decide/policy.ts` thresholds, host/loader/worker, `EvaluateRequest.subject/priority/timeoutMs` | nothing the model sees | mirror the gate in `eval_runtime.py` if the gate changes | + +### Recipes + +1. **Change wording the model reads** (a fact, sentence, description or instruction): + 1. Edit `packages/runtime/src/situation/*`. + 2. Update `test/situation.test.ts`/`test/budget.test.ts` expectations and the STATUS.md examples. + 3. Mirror the change in `training/curriculum/rt.py`. + 4. Regenerate SIM data (`bash sim/scripts/final.sh a`) (ask the user first). + 5. Retrain, then run `final_post.sh` (eval → calibration → export). + 6. Tag a new freeze. Coordinate with SIM and TRAIN first (`training/NEEDS.md` item 5). +2. **Add a diagnosis label:** + 1. Add it to `DEFAULT_DIAGNOSES` (order = option order; `expected` stays first). + 2. Teach the sim to emit it (`sim/src/oracle/diagnose.ts`). + 3. Add it to `sim/src/types.ts` -> `DIAGNOSES`, `scenario.ts` -> `DEFAULT_DIAGNOSES`/`DIAG_PARA`, `fmt.py` -> `DIAG_DESC` (`fmt.DIAGNOSES` is derived from it), `rt.py` -> `DIAGNOSES`. + 4. Regenerate data and retrain. Without retraining the model never picks it reliably. +3. **Add a built-in action:** + 1. Add it to `BUILTIN_ACTIONS` + `TRIGGER_ACTIONS` + `builtinApplicable` + the executor ([decide-policy-actions.md](runtime/decide-policy-actions.md)). + 2. Add its tier to `cost.ts` `TIER`, `fmt.TIER`, `eval_runtime.TIER`, `ACTION_PARA`, `fmt.ACTION_DESC`, `fmt.TRIGGER_ACTIONS`, `rt.py` `ACTIONS`/`TRIGGER_ACTIONS`, `eval_runtime.PASSIVE` and `sim/src/types.ts` -> `PASSIVE` (passive actions), and `sim/src/run/fake-runtime.ts` (`ACTIONS`/`DESC`, tests only). + 3. Make the sim able to force it, then regenerate and retrain. +4. **Standing questions (from `rt.question` or a plugin) or custom actions** need no retrain to run: the model reads the description. Quality is unmeasured, though. Check with `runtime.ask`/the demos. +5. **Change budgets or limits:** keep `rt.py` `section_limits`/`to_state` identical, including JS half-up rounding. Check token lengths: TRAIN measured about 2.4 chars/token (`training/NEEDS.md` 6a), so 3,200 chars ≈ 1,300+ tokens. +6. **Re-calibrate only:** `eval_runtime.py --fit-split dev --write-calibration cal.json`, then `export_runtime.py --calibration cal.json`. No retrain. The text does not change, so the freeze is unaffected. +7. **Change `max_len`:** train with `--max-len N`. The export copies it into `meta.json`, so the runtime positions limit follows automatically. +8. **Tests to run** (runtime vitest runs locally under the run policy in AGENTS.md; ask the user before the sim tests, training pytest, `validate.mjs` and anything that needs a model download; see [where to run things](runtime/build-test-release.md#where-to-run-things)): + - `packages/runtime`: `vitest run test/situation.test.ts test/budget.test.ts test/model/` (model parity tests read `GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`, filled by `genclass-runtime fetch-model`; with a new export, its own `requests.json`/`pack_fixtures.json`/`torch_fixtures.json` replace the v0.1 fixtures automatically). + - `sim`: `vitest run test/rows.test.ts test/determinism.test.ts test/oracle.test.ts`. + - `training/tests/test_curriculum.py`, `training/tests/test_export_runtime.py`. + - `training/ortweb/validate.mjs <export dir> q8`. + +## Tests + +| test file | what it asserts | +|---|---| +| `packages/runtime/test/situation.test.ts` | one situation per trigger (mutation, request, failure, stall, inconsistency, transition, error): key order, section caps (facts ≤ 12, timeline ≤ 16, state ≤ 8), `stateChars` ≤ 3,200, a `diagnosis` question, and regexes on selected facts (not the whole text; the full text is printed with `console.log`, which is where the STATUS.md examples come from); `ask`: `situation()` is side-effect free (same state twice, no new ops or events) and has trigger `ask`; serializer: an over-budget input stays ≤ 3,200 chars with `timeline: "none"`, an under-budget one keeps all 16 timeline lines and gives `"none"` for its empty sections; same scripted inputs → identical situations | +| `packages/runtime/test/budget.test.ts` | section limits compact 1,100 / full 3,200 / linear; every budget shapes sections and keeps top facts; compact questions keep ≤ 24-char overrides; determinism; auto budget 3,200 / 1,000–2,000; `max_tokens_exceeded` shrinks auto budgets | +| `packages/runtime/test/model/serialize.test.ts` | `state_segments`/`question_block` on edge cases vs Python fixtures; Python number printing; `json.dumps` separators; `str.strip` whitespace; JSON-round-trip semantics; situation-shaped states; `round` half-even | +| `packages/runtime/test/model/packer.test.ts` | identical ids/positions/groups/marker positions/question order vs the Python packer on the parity requests; plain-object criteria = Python-ordered Maps; special tokens stay text; marker ids from files, meta must agree; typed `max_tokens_exceeded` (positions vs total); Map label order, empty choices rejected; feed plan + unpack; HF tokenizer edge cases (full and pruned vocab); speed | +| `packages/runtime/test/model/calibrate.test.ts` | sha1 header keys = Python; reproduces PyTorch calibrated probabilities (< 1e-9); v1 and v2 files; confidence/score math; answer shapes and tie-break | +| `packages/runtime/test/model/engine.test.ts` | end-to-end TS packer → ORT (onnxruntime-node CPU, and onnxruntime-web 1.30 WASM single thread) → TS calibration vs PyTorch fixtures: within the export's own `parity.json` (agreement ≥ its count − 1, max logit diff < its value + 0.05) when the model directory has one, else ≥ 99% agreement and max logit diff < 1.0 (q8) / 0.1 (fp16); feeds exactly `meta.inputs` and rejects unknown ones | +| `packages/runtime/test/model/loader.test.ts`, `host.test.ts` | card parsing, plans, sha256 cache; host queueing/fail-open (see [model-host.md](runtime/model-host.md)) | +| `packages/runtime/test/browser/model.spec.ts`, `model-webgpu.spec.ts` (Playwright) | the model loads over WASM in a module worker and matches PyTorch, Cache Storage reuse, inline fallback, preload modes, WebGPU fallbacks (no adapter, no `shader-f16`, software adapter), latency at ~300–1,000 state tokens | +| `packages/runtime/test/fixtures/model/make_py_fixtures.py` | (generator, run on the VM) writes `py_fixtures.json` from jev_local `serialize`, HF `tokenizers`, `calibrate_logits` (v1 and v2 files) and `confidence` | +| `sim/test/rows.test.ts` | 40 trajectories produce valid CONTRACT-D rows: labels reference real options, dists sum to 1 (±0.01), noul p ∈ {0, 1}, score level in range, no `x-request-id` in states, passive-best share > 0.2, 0 prefix mismatches; splits hold out domains/families; transform renormalizes | +| `sim/test/determinism.test.ts` | same seed → identical rows and final states; forced replays reproduce every prefix | +| `sim/test/oracle.test.ts` | stale overwrite → discard best; single-point credit; intentional double add → passive/expected; duplicate POST → block/coalesce; outage → delay/serve_cached; benign concurrency → apply; sharp vs soft labels; exact ties favour passive | +| `training/tests/test_curriculum.py` | rows valid against the trainer's label parser and deterministic; held-out domains/templates only in test; label consistency; version semantics | +| `training/tests/test_export_runtime.py` | int8 embedding close and valid (zero rows survive); Gemm→MatMul rewrite preserves outputs; end to end: card bytes/sha256 match, meta markers/`cls_id`/`sep_id` = tokenizer added tokens, fp32 parity < 1e-3, R17 q8 < 12 MB | +| `training/tests/test_prune_vocab.py` | the pruned tokenizer's layout matches ettin, encodes every sample, and gives identical model outputs where tokenization is unchanged (needs the v1 checkpoint: `GC_V1_CKPT`, `GC_BASE_32M`) | +| `training/ortweb/validate.mjs` | (script: `node validate.mjs <export dir> [variant=q8] [maxRequests=60]`) onnxruntime-web WASM + node on the export, feeds from `pack_fixtures.json`, vs `torch_fixtures.json`; writes `<export dir>/ortweb_report_<variant>.json` (e.g. `ortweb_report_q8.json`; the script's header comment still says `ortweb_report.json`) | + +## Drift and open issues + +- **MODEL_CARD.md** (`packages/runtime-model/MODEL_CARD.md`): + - It lists 9 diagnoses (no `transient`); the code has 10. + - It says the runtime acts when "`p(action) ≥ 0.9` (guard) / `0.8` (heal)". The code gates on the **summed** probability of the permitted non-passive actions (`decide/policy.ts` -> `gate`, mirrored in `eval_runtime.py`). + - Accuracy numbers are stage 1c; the shipping model is the final-round model ([EVAL.md](../../training/EVAL.md) "Final round 1" is "(in progress)"). +- **training/README.md**: + - §2 says "diagnosis (9 labels …)"; `fmt.DIAG_DESC` has 10. + - §4 says the gate is "non-passive top action, p ≥ 0.9 guard / 0.8 heal"; `eval_runtime.py` implements the summed-mass gate. +- **docs/runtime/CONTRACT.md §6**: + - It says the action instructions are "What should the runtime do with <subject>?". The code uses fixed per-trigger sentences without the subject (`ACTION_INSTRUCTIONS`). + - It gives the budget as "≤ 1,000 tokens; truncate timeline first, then state, then facts". The code uses characters (3,200 default, device-sized) and the 5-step shrink plus fact/trigger shortening. + - Its `runtime.situation()` shape omits `salient`, `facts`, `compact`, `budget`. +- **`types.ts` -> `InitOptions.situation` comment**: says "wasm 1,100 + 300 per extra thread … 2,000". The code gives 1,000 / 1,333 / 1,667 / 2,000 (`situationBudget`). STATUS.md and the tests match the code. +- **`serialize.ts` header comment**: assumes ≈ 3.2 chars/token. TRAIN measured 2.4 chars/token on SIM states (mean 963, p95 1,340, max 1,569 state tokens), so 3,200 chars ≈ 1.3–1.4× the intended 1,000 tokens (`training/NEEDS.md` 6a, open ASK). +- **sim/NEEDS.md preamble and STATUS.md "How to drive it headless"** show `thresholds {guard: 0, heal: 0}`. `sim/src/run/rt.ts` uses 0.5 (changed after the tag; see the gotcha). sim/NEEDS.md's note that `transient` is missing from `DEFAULT_DIAGNOSES` is stale. +- **`training/curriculum/rt.py` -> `to_state`**: the last-resort fact shortening floor is 40 chars (runtime 60), and the trigger is never shortened. This only matters when a single fact or the trigger exceeds the budget. +- **`rollback` description vs effect** (see gotchas): fixing it is a model-input change. +- **`docs/runtime/ARCHITECTURE.md`** lists diagnoses with `transient` before `slow`. The code order puts it last. Order affects only answer key order and tie-breaks. +- **Not published:** `@genclass/runtime-model@0.1.0`. The package directory holds only `MODEL_CARD.md`, so the default base URL cannot serve a model until OPEN_TASKS item 8 lands. OPEN_TASKS says the alpha takes no actions until then. +- **Open (OPEN_TASKS.md / training/NEEDS.md):** + - final training round 1 on phase A, then round 2 on A + B; + - choose R17 (WASM) vs R32 (WebGPU); + - device-based model selection in the card; + - clean-run rows (`meta.clean`) requested by TRAIN (ASK); + - thin `conflict`/`transition` classes; + - label noise on benign request rows (OPEN_TASKS: 66% of passive-best request rows put ≥ 0.9 on passive; phase A `sim/samples/stats-final-a.json` `label_sharpness.request.passive_mass_ge_0_9` = 0.676). +- **`meta.json.name`** is `<name>-<version>`, while the runtime reports `<card.name>@<card.version>` and ignores `pad_id` and, in practice, `meta.name` (an `Engine` fallback only; `backend.ts` -> `createEngine` always passes a name). This is harmless but confusing. +- **`training/curriculum/rt.py` vs `util.ts` number formatting** (see gotchas): half-even vs half-up on exact binary ties in `secs`/`rel`/`fmt_num`, so runtime-exact curriculum rows are not always byte-identical to the runtime. `rt.py.to_state` also uses Python `round(budget)` where the runtime uses `Math.round` (irrelevant for integer budgets). +- **`model/tokenizer.ts` header comment** says non-special added tokens are split out first and the normalizer runs on the rest; `Tokenizer.encode` normalizes the whole text first, then splits added tokens. Likely equivalent for the shipped NFC normalizer and ASCII added tokens (unverified; OPEN_TASKS.md reports packing identical to Python on all 50 v0.1 fixtures); it would matter for a normalizer that rewrites added-token text (e.g. `Lowercase` and `[unusedN]`). +- **`export_runtime.py` parity `gate08`/`gate09`** compare the max choice probability per question, not the runtime's summed non-passive mass gate. They are a proxy, not the product gate. +- **docs/runtime/CONTRACT.md §11** says option order/subsets and diagnosis paraphrases/subsets are randomised "per row". In code, order/drop is per row (`transformQuestions`) but description wording and diagnosis subsets are per trajectory (runtime `vocabulary` from `scenario.ts`). +- **MODEL_CARD.md status line** ("stage 1c final, stage 2 piloted on pre-freeze SIM data"; "`calibration.json` (per-kind temperatures)") predates final round 1; the per-kind part still matches what `final_post.sh` writes. + +## Related docs + +- [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): facts catalogue, triage salience, section line details, redaction +- [runtime/model-host.md](runtime/model-host.md): worker/inline host, loader, backends, CLI, errors +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): queue, gate, action execution, reports +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `vocabulary`, `situation.budget`, `ask`/`decide`, plugins +- [runtime/build-test-release.md](runtime/build-test-release.md): where and how tests run +- [sim.md](sim.md), [training.md](training.md), [genclass-model-lineage.md](genclass-model-lineage.md) (jev_local Python reference), [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md) +- Source docs: [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) §5–§8, §10, §11; [docs/CONTRACT.md](../CONTRACT.md) §B (packing, heads) and §D (row format); [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md) (example situations); [sim/README.md](../../sim/README.md); [training/README.md](../../training/README.md); [training/NEEDS.md](../../training/NEEDS.md); [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md) diff --git a/docs/agents/overview.md b/docs/agents/overview.md new file mode 100644 index 00000000..b2bd8e6b --- /dev/null +++ b/docs/agents/overview.md @@ -0,0 +1,418 @@ +# GenClass-lib system overview: the mental model + +> **Scope:** the whole monorepo at the level of one mental model: `@genclass/runtime` (`packages/runtime/src/**`), +> the unpublished model package (`packages/runtime-model/`), `sim/`, `training/`, `demos/`, and the legacy GenClass +> content it builds on (`jev_local/`, `extension/`, `bench/`, `results/`, `scripts/`, legacy `docs/*.md`). Detail lives +> in the subsystem docs linked from every section; this doc names the stages and the seams between them. +> **Read this when:** you land in the repo cold and need to know what the parts are, how one runtime decision flows +> from an observed event to an action, how the offline loops (sim -> training -> model package, demos evaluation) +> connect to it, what each mode allows, what happens without a model, who owns what, and where the project stands. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +Path convention: every code pointer is `path/from/repo/root` -> `symbol`. Runtime source is under +`packages/runtime/src/`. + +## TL;DR + +- `@genclass/runtime` is a browser library for self-healing web apps. It instruments the page (fetch, XHR, + WebSocket, timers, DOM user events, errors, navigation, storage, long tasks) and the app's state stores, keeps a + causal trace, learns baselines, invariants and transition profiles, and turns a suspicious moment (a *trigger*) into + a plain-English *situation*. A small local model (ONNX in a Web Worker, WebGPU or WASM) answers two typed questions + about it (diagnosis, action). A policy gate runs a minimal action (undoable only for `discard`, late reverts, + `rollback` and custom `onUndo`) only at high calibrated confidence; otherwise the passive action (let it happen) runs. +- The runtime never maps a fact pattern to a diagnosis or action with an if/then (CONTRACT §0 rule 1). Facts are + generic; triage only decides whether the model is worth asking; the model decides; the gate filters. +- One situation implementation (`packages/runtime/src/situation/*`) is shared by the runtime and by the sim, which + drives the real runtime to produce training rows. Its text is frozen at git tag `situation-v1` (1a77558); + `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. +- Modes: `observe` (never changes execution), `guard` (default; guard-tier actions such as `discard`, `coalesce`), + `heal` (adds heal-tier actions such as `retry`, `serve_cached`, `rollback`). Kill switch: `?genclass=off`. +- Fail open everywhere: no model, a loading or failed model, a timeout or any error means the passive action runs; a + held write or request never waits for the model longer than the hold budget (at most 800 ms with the default + `"auto"`); an action that then runs can add its own wait (`delay` and `coalesce` ≤ 8 s, `retry` backoff ≤ 5 s, + `defer` ≤ 10 s per deferral before the write is re-decided, custom actions unbounded). +- **Where it stands:** `@genclass/runtime@0.1.0-alpha.0` is on npm, but the trained model package + (`@genclass/runtime-model@0.1.0`, the default model URL) is not published, so a default install observes and learns + but never decides or acts. SIM phase A data (600,676 rows) exists; final training round 1 was launched with no + results in the repo; the demos have only been run with the v0.1 model (not trained for runtime decisions). + +## 1. The problem and the product principles + +Web apps fail at runtime in ways their code does not handle: an older response overwrites newer state (stale write), +the same request is sent twice from one intent (duplicate), a request keeps failing, a request hangs, a store ends up +contradicting a relation it normally keeps, an operation makes a state change unlike its usual ones. CONTRACT §0.5 +states the claim: *install one library; find and prevent runtime failures automatically, with low false positives.* + +Binding principles (`docs/runtime/CONTRACT.md` §0 and §0.5; restated with code locations in +[status-and-known-issues](status-and-known-issues.md#ground-rules-binding-contract-0-and-05-restated)): + +| principle | what it means in code | +|---|---| +| Precision first | Default mode `guard` allows only guard-tier actions. The gate needs Σ p(permitted actions) ≥ 0.9 (guard) / 0.8 (heal) and a top diagnosis other than `expected` (`packages/runtime/src/decide/policy.ts` -> `gate`, `policyConfig`). The sim labels favour passive (tier premiums, tie rule). The false-intervention rate on clean runs is the headline metric in training eval and demos. | +| Cheap by default | Facts and baselines always run and are cheap; the model is consulted only for *salient* situations (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`), runs in a Worker, loads at idle or lazily, and is cached. Target model size ≤ 25 MB q8 (R17 q8 9.58 MB, R32 q8 22.47 MB). | +| Observable | One console line per detection/intervention with collapsible evidence (`packages/runtime/src/decide/report.ts` -> `Reporter`), `explain(id)`, `undo()` for reversible actions, the `x-genclass` response header on synthetic answers (`blocked`, `cached`, `coalesced`), devtools overlay, kill switch. | +| No hardcoded bugs | Facts (`packages/runtime/src/situation/facts.ts` -> `computeFacts`) are uniform sentences with a `neutral` flag; applicability (`packages/runtime/src/situation/build.ts` -> `buildSituation`, internal `builtinApplicable`) only says whether an action *can* run. Only the model's probabilities choose. Without a model the runtime observes only. | +| Determinism and parity | Runtime code reads time only from the injected `Clock` (no `Math.random`, `Date.now`, global timers), so the sim can replay it byte for byte. The sim drives the same code; `training/curriculum/rt.py` is a Python port of the situation text. | +| Honest evaluation | `sim/` and `demos/` are built by different people who do not read each other's code (CONTRACT §0 rule 4). | + +Adoption path: `observe` -> `guard` -> `heal`. + +## 2. Component map + +```text + ONLINE: inside the app's page packages/runtime (npm: @genclass/runtime) + +------------------------------------------------------------------------------------------------+ + | app code: fetch / XHR / WebSocket / timers / DOM events / store writes (atoms, Redux, Zustand) | + | | | | + | v v | + | observe/* --ops, events--> trace/* state/* StoreHub --writes--> InvariantMiner | + | (patched globals) (OpRegistry, Context, EventLog) learn/* Baselines, Profiles | + | | request / failure / stall | mutation | settled point: inconsistency, | + | | triggers | trigger | transition triggers; error | + | +---------------------------------+--------------------+ | + | v | + | runtime.ts RuntimeImpl.trigger: facts -> triage -> situation + questions (situation/*) | + | | EvaluateRequest { state, questions } | + | v | + | decide/decider.ts DeciderQueue --> DecisionProvider (default: model/* ModelHost) | + | Worker: ModelBackend -> Engine -> onnxruntime-web | + | | calibrated Answers (diagnosis, action) | + | v | + | decide/policy.ts gate --> Controller.run(action) or passive() | + | v | + | Decision / ActionRecord --> report.ts console lines, explain(), undo(), rt.on() events | + | --> devtools/* overlay, adapters/* hooks | + +------------------------------------------------------------------------------------------------+ + ^ model directory: model.json, *-q8.onnx, *-fp16.onnx, + | tokenizer.json, calibration.json, meta.json + OFFLINE | (planned home: @genclass/runtime-model, unpublished) + sim/ --drives the real createRuntime--> rows {state, questions, labels} + | + training/ curriculum + jev_local/train --> eval_runtime.py --> export_runtime.py --> model directory + demos/ GenClass.init Off / Guard / Heal --> seeded trials + oracles --> demos/results.md + legacy: jev_local/ (Python model, packer, trainer), extension/ (v0.1 model card), bench/, results/ +``` + +| component | path | role | state at 654d822 | doc | +|---|---|---|---|---| +| Public API and wiring | `packages/runtime/src/index.ts` (`GenClass`, `createRuntime`), `packages/runtime/src/runtime.ts` (`RuntimeImpl`), `types.ts`, `clock.ts`, `util.ts` | facade, construction, modes, kill switch, events, plugins, settled points | done, frozen | [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md) | +| Observers and trace | `packages/runtime/src/observe/*`, `packages/runtime/src/trace/*` | patch globals, ops with causes, ambient context, event log, fetch/XHR action controllers | done, frozen | [observe-and-trace](runtime/observe-and-trace.md) | +| State | `packages/runtime/src/state/*`, `packages/runtime/src/adapters/*` | `StoreHub` (atom/guard/adapter stores), mutation pipeline and holds, invariant miner, snapshots; React/Redux/Zustand adapters | done, frozen | [state-and-adapters](runtime/state-and-adapters.md) | +| Learn, situation, triage | `packages/runtime/src/learn/*`, `packages/runtime/src/situation/*` | baselines, transition profiles, facts, triage, situation text and questions (model input) | done, frozen at `situation-v1` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Decide | `packages/runtime/src/decide/*` | queue, hold budget, policy gate, actions, reports, explain, undo | done, frozen | [decide-policy-actions](runtime/decide-policy-actions.md) | +| Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | done, frozen | [model-host](runtime/model-host.md) | +| Devtools | `packages/runtime/src/devtools/*` | shadow-DOM overlay on the public API | done, frozen | [devtools](runtime/devtools.md) | +| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}` | tsup ESM build (6 entries), vitest, Playwright, smoke test | alpha published; no CI | [build-test-release](runtime/build-test-release.md) | +| Model I/O contract | runtime `situation/*` + `model/*`, `sim/`, `training/` | situation text -> packed request -> heads -> calibrated answers | frozen | [model-io-contract](model-io-contract.md) | +| Model package | `packages/runtime-model/` | planned home of the published model directory | only `MODEL_CARD.md`; package not created | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | +| Sim | `sim/` (`@genclass/sim`) | training-data generator driving the real runtime in a virtual world | phase A done (600,676 rows); phase B in progress at commit time | [sim](sim.md) | +| Training | `training/` | curriculum, R17/R32 training, eval, ONNX export | final round 1 launched, no results in repo | [training](training.md) | +| Demos | `demos/` (`@genclass/demos`) | six demo apps, Service Worker chaos backend, trial harness | built; results only with v0.1 model | [demos](demos.md) | +| GenClass model lineage | `jev_local/`, `scripts/genclass_export.py`, `tests/` | Python predecessor: model, packer, calibration, trainer; reference for parity | legacy except trainer, export graph, parity reference | [genclass-model-lineage](genclass-model-lineage.md) | +| Extension, benchmarks, ops scripts | `extension/`, `bench/`, `results/`, `BENCHMARKS.md`, `scripts/` | GenClass 0.1 Chrome extension, Jev benchmarks, Azure/VM scripts | legacy; `scripts/vm.sh`, `scripts/azvm.sh`, `scripts/launch_run.sh` still used | [extension-and-benchmarks](extension-and-benchmarks.md) | +| Status and team files | `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `*/NEEDS.md`, `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md` | plan, status, requests, binding contract | drift documented | [status-and-known-issues](status-and-known-issues.md) | + +Paths and per-directory detail: [repo-map](repo-map.md). Terms: [glossary](glossary.md). + +## 3. Runtime data flow end to end + +Every stage below runs inside `RuntimeImpl` (constructed by `GenClass.init` or `createRuntime`). The first four stages +always run, model or not; stages 5 onward run only while the runtime is *consultable* (not paused, not destroyed, a +`DecisionProvider` exists, and its `status.state` is `ready` or `off`). + +| # | stage | what happens | code (file -> symbol) | doc | +|---|---|---|---|---| +| 1 | Observers | Constructor installs, in order, timers, fetch, xhr, websocket, user (DOM), errors, nav, storage, perf; each in try/catch; each patched global becomes a pass-through after `destroy()` (WebSocket instances and timer callbacks created before `destroy()` keep tracing; see [observe-and-trace](runtime/observe-and-trace.md), 'After destroy: what still runs'). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | +| 2 | Trace, ops, causality | Every async unit is an `OpRec` (id, kind, signature name such as `GET /api/search`, detail such as `?q=rea`, cause, root). The ambient op (set by `run`, `stick`, `stickUser`) becomes the cause of new ops and the writer of state writes. Events go to a ring buffer (default 500). | `packages/runtime/src/trace/ops.ts` -> `OpRegistry`; `packages/runtime/src/trace/context.ts` -> `Context`, `LazyOp`; `packages/runtime/src/trace/events.ts` -> `EventLog`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`, `RuntimeImpl.user` | [observe-and-trace](runtime/observe-and-trace.md) | +| 3 | Stores | Store values are flattened into versioned dotted fields with writer ops and history. Each `set`/`dispatch` becomes a `MutationRec`: user-sync, GenClass, paused, `hold: false`, no-op and unholdable writes bypass; the rest go through the hub's `gate` hook in per-store FIFO order. | `packages/runtime/src/state/hub.ts` -> `StoreHub.propose`, `StoreHub.commit`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.onApplied` | [state-and-adapters](runtime/state-and-adapters.md) | +| 4 | Learned baselines, invariants, profiles | Fetch/XHR latency (≥ 5 samples), outcomes, failure streaks and rates per signature; at *settled points* (60 ms after the last op end or write, nothing younger than 10 s in flight and no held or queued write) the invariant miner checks 9 generic templates and transition profiles flag rare state changes (< 1% of ≥ 20 completions). | `packages/runtime/src/learn/baselines.ts` -> `Baselines`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner.observe`; `packages/runtime/src/learn/profiles.ts` -> `Profiles`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled` | [learn-situation-triage](runtime/learn-situation-triage.md), [state-and-adapters](runtime/state-and-adapters.md) | +| 5 | Trigger | A raise site calls `trigger(spec, controller, { hold, priority })`. Kinds: `mutation` (held), `request` (held), `failure` (fetch: holdable, held only when a failure action is permitted, i.e. in heal mode or with a guard-tier custom failure action), `stall`, `inconsistency`, `transition`, `error`; `ask` comes from `rt.ask`/`rt.situation`. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `gateMutation`, `watchStall`, `raiseInconsistency`, `raiseTransition`, `reportError`; `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `runRequest`, `failureGate`) | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 6 | Facts | Uniform English sentences per trigger, each with a kind and a `neutral` flag; ordered non-neutral first; at most 12. | `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| 7 | Triage | With `triage: "salient"` (default) the model is asked only if some fact is non-neutral, a standing question has `always: true`, or the trigger is `ask`. Otherwise the passive action runs with no model call and no record. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| 8 | Situation + questions | 7-key `JevState` (`app, trigger, facts, in_flight, timeline, state, stats`) sized by a character budget (3,200 full; auto 1,000-2,000 on WASM); `diagnosis` question (10 labels) and `action` question (applicable actions, passive first, only when ≥ 2 apply); bare labels at ≤ 1,400 chars. | `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`; `packages/runtime/src/situation/questions.ts` -> `buildQuestions`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget` | [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md) | +| 9 | Hold or not | The subject is held only if the trigger is holdable and the mode and policy permit at least one non-passive action; the wait for the decision lasts at most the hold budget (`"auto"`: clamp(round(1.5 × median of the last 20 provider latencies, or the model's `warmupMs` before any), 150, 800) ms; 300 ms when neither is known). Otherwise the passive action runs now and the decision continues in the background (detection only). | `packages/runtime/src/decide/policy.ts` -> `permittedActions`, `holdBudget` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 10 | Decision queue | Single-flight priority queue (32 items, 30 s answer cache, deadlines, 10 s runtime-side timeout); every miss, error or timeout resolves `null` -> passive. | `packages/runtime/src/decide/decider.ts` -> `DeciderQueue.submit` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 11 | Model host | `evaluate` rejects at once unless `ready`. In the Worker (inline fallback), the packer renders the state and questions with Python-parity serialization, tokenizes, packs `[CLS] key: text [SEP] ... [Q] header [O] item ...` with block attention, and runs one ONNX forward pass (heads `choice_logits`, `score_logits`, `noul_logits`). | `packages/runtime/src/model/host.ts` -> `createModelHost`, `ModelHost.evaluate`; `packages/runtime/src/model/backend.ts` -> `ModelBackend.evaluate`; `packages/runtime/src/model/engine.ts` -> `Engine.evaluate`; `packages/runtime/src/model/packer.ts` -> `Packer.pack` | [model-host](runtime/model-host.md), [model-io-contract](model-io-contract.md) | +| 12 | Calibrated answers | Per-question temperature (by header, bucket or kind) or Platt scaling turns logits into `Answer`s (`choice`, `confidence`, `probabilities`). The gate reads only `probabilities` and the diagnosis `choice`. | `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer` | [model-io-contract](model-io-contract.md) | +| 13 | Policy gate | A = applicable non-passive actions the mode allows minus `deny`; candidate = argmax over A; runs iff not paused, Σ p(A) ≥ the candidate tier's threshold, top diagnosis ≠ `expected`, < 60 actions in the last minute, and, for holdable triggers (mutation, request, fetch failure), the answer arrived while the subject was still held (else late-revert rules; non-holdable triggers skip this check). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`; `packages/runtime/src/decide/policy.ts` -> `gate` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 14 | Action or passive | The subject's `Controller` performs the action (`run`) or lets it through (`passive`). A throw runs passive. | `packages/runtime/src/decide/exec.ts` -> `Controller`; controllers in `packages/runtime/src/runtime.ts` -> `gateMutation`, `RuntimeImpl.rollback`, `RuntimeImpl.revertChain`, `RuntimeImpl.resync` and `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `reqCtl`, `failureGate`, `stallController`) | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 15 | Report, explain, undo, events | Every model answer to a trigger is a `Decision` (`d<n>`); every non-passive attempt an `ActionRecord` (`a<n>`, exact `changed` sentence, optional idempotent `undo`); console lines deduped per 60 s; events `decide`, `detect`, `act`, `report`, `status`, `event`; past actions reappear in later timelines as `GenClass <changed>`. | `packages/runtime/src/decide/report.ts` -> `Reporter`, `interventionLine`, `detectionLine`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.explain`, `RuntimeImpl.on`; `packages/runtime/src/devtools/index.ts` -> `mountDevtools` | [decide-policy-actions](runtime/decide-policy-actions.md), [devtools](runtime/devtools.md) | + +## 4. Walkthrough: a typeahead stale write + +The canonical bug. The user types into a search box; each keystroke sends `GET /api/search?q=...`; an older, slower +response arrives after a newer one and is about to overwrite newer results. The situation text below is Example A +from [learn-situation-triage](runtime/learn-situation-triage.md#12-annotated-examples-copied-from-packagesruntimestatusmd-produced-by-the-tests), +produced by `packages/runtime/test/budget.test.ts` -> `typeahead` at a 1,000-char budget. That test registers +`rt.atom("search", { query: "", results: [] })`, types `r`, `re`, `rea`, `reac` through `rt.user(...)`, and serves +`q=rea` with 900 ms latency and every other query with 120 ms. Op ids: `#5` user typed `rea`, `#6` `GET +/api/search?q=rea`, `#7` user typed `reac`, `#8` `GET /api/search?q=reac` (`#1`-`#4` are the `r` and `re` prefixes). +The steps assume a `ready` model and the default `guard` mode; the table after them covers the other cases. + +1. **Keystroke -> user op.** In a browser, the capture-phase `input` listener (`packages/runtime/src/observe/dom-user.ts` + -> `installDomUser`) calls the sink with `{ kind: "type", target: 'input "Search"', value }`, which is + `RuntimeImpl.user`. It starts an instant `user` op, merges keystrokes on the same target into one typing event, and + calls `Context.stickUser`, so the app's own listener in the same task runs with that op as ambient (the test calls + `rt.user(action, handler)` directly, which runs the handler inside `Context.run`). +2. **Query write bypasses.** The handler's `search.set(v => ({ ...v, query: q }))` reaches `StoreHub.propose`. Its cause + is the task's user op, so it is *user-sync* and bypasses the gate (`policy.holdUserWrites` is false): applied at once, + `search.query` gets a new version with writer `#5`. +3. **Request -> fetch op.** `fetch("/api/search?q=rea")` hits the wrapper from `installFetch`: `startOp("fetch", "GET + /api/search")` with detail `?q=rea` and cause `#5` (`#6`); `Baselines.start` records the start; `registerIdentity` + records the request identity. The request gate raises a `request` trigger (hold, priority 2). Its salient facts + would be R3 (an *identical* request close by), R5 (≥ 2 failures in a row) or R7 (hot rate); `q=rea` and `q=reac` + have different identities, nothing failed, and no usual rate is learned yet, so every fact is neutral and the + request is sent at once with no model call. The same happens 90 ms later for `#7` -> `#8`. +4. **The newer response lands first.** `#8` answers after 120 ms. `endOp` records latency and outcome; the fetch op is + stuck as ambient while the app reads the body (`instrumentResponse`), so `search.set(... results ...)` is a write + with cause `#8`. `gateMutation` -> `trigger({ trigger: "mutation", m })` computes facts: no other chain wrote the + written fields since `#8` started, and the only other in-flight `GET /api/search` (`#6`) is older, so nothing is + salient; the controller's `passive()` runs synchronously and the write applies in the caller's stack. + `search.results` goes to version 1, writer `#8`. +5. **The older response arrives.** `#6` answers at 900 ms; its write proposes `results: ["rea-1", "rea-2"]` with cause + `#6`. Now `computeFacts` (`mutationFacts`) finds M2 (salient: `search.results` was written by another chain since + `#6` started) and M5 (salient: `search.query`, same store, changed by another chain since then), plus neutral + provenance (M1) and delta (M15). Triage passes. `buildSituation` builds the situation; `toJevState` shapes it to the + budget (the test fixes 1,000 chars, which is also the auto budget on single-threaded WASM): + +```text +app: /search +trigger: A write to search.results from GET /api/search?q=rea (#6) is about to be applied. +facts: + search.results was written once by other operations since this write's cause (#6) started (version 0 → 1), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). + search.query changed since this write's cause (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. + This write comes from GET /api/search?q=rea (#6), started 0.90s ago, ended 0.00s ago with 200; its chain began with user typed "rea" into input "Search" (#5). + This write would change search.results: 2 items ["reac-1", "reac-2"] → 2 items ["rea-1", "rea-2"]. +in_flight: none +timeline: + -0.00s end GET /api/search?q=rea (#6): 200 in 0.90s +state: + search.results = 2 items ["reac-1", "reac-2"] (v1, by #8 0.69s ago) + search.query = "reac" (v4, by #7 0.81s ago) +stats: + GET /api/search: 4 done, 0 of last 4 failed, 4 in last 10s +questions: + diagnosis: What is happening here? expected | stale | conflict | duplicate | inconsistent | failing | slow | overload | unusual | transient + action: What should the runtime do with this write? apply | discard | defer +``` + + This is `stateText` of the `JevState` plus the test's printout of the questions. The model receives the `state` + object and a `questions` object of two `choice` questions whose `criteria` are all `null` (compact questions at + ≤ 1,400 chars). At the full 3,200-char budget the same write carries a 16-line timeline and described options; that + version is in `packages/runtime/STATUS.md` ("Example situations: full budget"). Its timeline also shows that in this + test the `#2` and `#4` writes were themselves dropped (`GenClass Dropped the write to search.results from GET + /api/search?q=re (#4); search stays at version 3.`), which is why `search.results` was still at version 0 when `#6` + started. +6. **Hold.** In `guard` mode the permitted set is `discard` and `defer` (guard tier; `defer` is offered while + `m.defers < 2`), so `waits` is true: `gateMutation` returns `{ held }` and the hub keeps the write queued. A budget + timer is armed (`RuntimeImpl.holdBudgetMs`), and `DeciderQueue.submit` gets priority 2 and deadline + `t0 + budget + 2000` (the extra 2 s is the late-revert window, since mutation controllers can revert). +7. **Model.** `ModelHost.evaluate` -> Worker -> `ModelBackend.evaluate` -> `Engine.evaluate`: `Packer.pack`, one forward + pass, `unpackLogits`, `calibrateLogits` and `buildAnswer` per question. The result is `{ diagnosis: ChoiceAnswer, + action: ChoiceAnswer }`, each with `probabilities` in criteria order. +8. **Gate.** `RuntimeImpl.onDecision` -> `gate`: A = {`discard`, `defer`}; candidate = the more probable of the two; it + runs iff p(discard) + p(defer) ≥ 0.9, the top diagnosis is not `expected`, the rate limiter has room, and the subject + is still held. A `Decision` is recorded either way; `decide` fires, and `detect` fires when the diagnosis is not + `expected` with p ≥ 0.6. +9. **Action.** If `discard` passes: `rate.take`, then the mutation controller's `run("discard")` settles the verdict + `discard`; the hub drops the write and the app is never notified, so `search.results` keeps the `reac` results. The + `ActionRecord` has `changed` = `Dropped the write to search.results from GET /api/search?q=rea (#6); search stays at + version <v>.` and an `undo` that commits the original write as a GenClass write. An `action` event is pushed, so + later situations show `GenClass Dropped the write ...` in their timeline. +10. **Report.** With diagnosis `stale`, `interventionLine` prints `[GenClass] Prevented a stale write: <first + non-provenance fact> <changed> (stale, <p>; discard <p>)`, here led by the M2 fact. The console groups the facts, + timeline, exact situation text and answers under it, plus an undo hint and a deny hint. `rt.explain("<id>")` + returns the same evidence; the devtools Interventions card offers Undo. + +Other outcomes of the same trigger: + +| condition | result | +|---|---| +| gate fails (mass < 0.9, top diagnosis `expected`, rate limit) | `apply` runs when the answer arrives; the stale results show; if the diagnosis is `stale` with p ≥ 0.6, a `Flagged a stale write: ...` detection line prints (with a `Not acted on (...)` clause when the gate recorded a reason) | +| model slower than the hold budget | the budget timer applies the write (fail open); a gate-passing `discard` within 2 s can still revert it if nothing changed those fields since (`Reverted a stale write: ...`, `ActionRecord.late`) | +| `mode: "observe"` | nothing is permitted, so the write applies at step 6 with no hold; the decision is made in the background (deadline 5 s) and can only flag | +| model loading, failed or absent (the alpha default once the card fetch fails) | `consultable()` is false; `gateMutation` returns no hold, no facts are computed, nothing is recorded; the stale write applies exactly as without GenClass | +| model status `off` (lazy preload not started) | facts and triage run; this salient write starts the model load and applies at once (fail open) | + +Known product risks on exactly this path (open in code, `demos/NEEDS.md`): holds add latency to typeahead-like apps +(§2; search clean p50 14 -> 125 ms with v0.1), and a held write can land after a newer user-sync write to the same +store (§1). Store names must not contain `.` (for example `search.results` as a store name): nothing enforces it, +and the version facts that detect this bug then always say the field "has not changed" +([state-and-adapters](runtime/state-and-adapters.md)). + +## 5. Offline loops + +### 5.1 Training-data loop (sim) + +```text +seed -> buildScenario (domain, features, net, budget, split) -> ideal run + base run (real runtime, recording decider) + -> sampled decision points k -> one counterfactual run per applicable action x up to K=3 paired futures + -> runCost vs ideal -> actionLabel (soft action distribution) + diagnose (hard diagnosis label) + -> CONTRACT-D rows {id, split, family, state, questions, labels, meta} -> <out>/{train,dev,test}.jsonl + stats.json +``` + +- CLI and workers: `sim/src/gen.ts` -> `main`; one trajectory: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, + `pointCosts`; one run: `sim/src/run/runner.ts` -> `runScenario` on a `VirtualLoop` (`sim/src/loop.ts`). +- The real runtime is loaded by `sim/src/run/rt.ts` -> `realRuntimeFactory` with `createOptions`: `model: false`, the + sim's recording decider, `mode: "heal"`, `triage: "salient"`, a fixed `situation.budget` (3200/2000/1000), observers + `fetch`, `timers`, `websocket` only, gate thresholds 0.5 with `requireDiagnosis: false` so exactly the forced action + runs. The decider stores every `EvaluateRequest`'s `state` and `questions` verbatim: the sim never writes situation + text, which is what keeps train/runtime parity. +- Labels: `sim/src/oracle/cost.ts` -> `runCost`, `actionLabel` (tier premium 0/0.25/0.5, ties within 0.05 pinned to + passive); `sim/src/oracle/diagnose.ts` -> `diagnose`. Plus diagnosis-only rows and `ask` rows with exact labels. +- Output so far: phase A on the frozen runtime, 600,676 rows (`sim/samples/stats-final-a.json`). Detail: [sim](sim.md). + +### 5.2 Training and export loop + +```text +prune_vocab.py (16,000 merges -> 16,364 tokens) + -> stage 1 / 1c: synthetic curriculum (curriculum/generate.py; cur1 varied style in s1, cur2 adds rt.py runtime-exact rows in s1c) + -> stage 2 / final rounds: jev_local/train/train.py on SIM rows + curriculum replay (configs/mix_*.json, Azure nodes) + -> eval_runtime.py (FIR, precision, recall, cost regret, ECE; --write-calibration -> calibration.json) + -> export_runtime.py (<name>-q8.onnx: 8-bit MatMulNBits + int8 embeddings; <name>-fp16.onnx; tokenizer.json, + calibration.json, meta.json, model.json card "genclass-runtime-model/1"; parity fixtures) + -> ortweb/validate.mjs (onnxruntime-web WASM vs torch logits) + -> [planned] publish as @genclass/runtime-model@0.1.0 (jsDelivr serves files/ = DEFAULT_MODEL_BASE_URL) + + GitHub release runtime-model-v0.1.0 (the CLI's default --from) + -> runtime: model/loader.ts fetchCard -> parseCard -> planOrder -> fetchFile (size + sha256, Cache Storage) + -> ModelBackend.load -> Engine (graph-contract check, warm-up) -> status "ready" +``` + +- Candidates: R17 (ettin-encoder-17m, d 256 × 7 layers, intended for WASM) and R32 (GenClass 0.1 `jev-local-fast`, + ettin-32m, d 384 × 10 layers, WebGPU only if clearly better; OPEN_TASKS item 5). +- Code: `training/curriculum/generate.py`, `training/curriculum/rt.py` -> `render`, `to_state`; + `jev_local/train/train.py`; `training/eval_runtime.py` -> `fit_calibration`, `decision_metrics`; + `training/export_runtime.py` -> `main` (graph from `scripts/genclass_export.py`); + `packages/runtime/src/model/loader.ts` -> `fetchCard`, `parseCard`, `planOrder`, `fetchFile`. +- Results so far: stage 1c held-out `rt1` action/diagnosis about 98% with 0% FIR; the stage-2 pilot (pre-freeze data) + was precise but rarely acted (heal recall about 1.3%); final round 1 has no results in the repo. Detail: + [training](training.md), [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). + +### 5.3 Evaluation loop (demos) + +- Six apps (`search`, `editor`, `checkout`, `status`, `board`, `decisions`), each with a deliberate latent bug, on a + Service Worker mock API with seeded chaos. GenClass is created only in `demos/src/shared/genclass.ts` -> + `startGenClass`: **Off** = `GenClass.init({ mode: "observe", model: false })` (installed, never decides), + **Guard** / **Heal** = `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. App code is identical. +- A trial is a seeded scenario run in a fresh page by `demos/src/shared/harness.ts` -> `TrialHarness` with the + synthetic driver (`demos/src/shared/driver.ts` -> `runSteps`) or Playwright (`demos/e2e/eval.ts`), scored by the + demo's oracle (DOM + server truth only). `demos/src/shared/aggregate.ts` -> `summarizeMode` reports Wilson bug + rates on chaos trials, false interventions on clean trials, fixed/introduced vs Off, and latency medians. +- Shipped `demos/results.md` (810 trials, v0.1 model (not trained for runtime decisions), WASM q8): no executed action lowered a bug rate, + 0 false interventions, holds added latency (search) and introduced board bugs. Detail: [demos](demos.md). + +### 5.4 How a runtime change reaches the shipped model + +CORE changes text the model reads -> the lead freezes it with a tag -> SIM regenerates rows from that exact runtime -> +TRAIN mirrors the wording in `training/curriculum/rt.py`, trains, calibrates, evaluates, exports -> MODEL checks TS +packer/engine parity against the export's fixtures -> the lead publishes the model package, then the runtime. Any +change to facts, timeline/state/stats lines, question wording, diagnosis labels, budgets, `util.ts` formatters, op or +event names, the packer, tokenizer or calibration lookup is a model-format change +([model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md)). + +## 6. Modes and what each allows + +Mode-tier rule: `packages/runtime/src/decide/policy.ts` -> `modeAllows`. Thresholds from `policyConfig`: report 0.6, +guard 0.9, heal 0.8. + +| mode | how to get it | actions that can run | holds | decisions and reports | +|---|---|---|---|---| +| off (kill switch) | `?genclass=off` or `localStorage.genclass = "off"` (URL wins), read by `packages/runtime/src/index.ts` -> `killSwitch` | none | never | inert runtime: every observer off, no decider, `report: "silent"`; all caller options dropped | +| `observe` | `mode: "observe"`, `?genclass=observe`, `setMode` | passive only | never | with a ready model, salient triggers are still decided in the background and recorded; detections print `Flagged ...` | +| `guard` (default) | `mode` default | passive + guard tier: `discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions | when a guard action is permitted for that trigger | decisions, detections, interventions | +| `heal` | `mode: "heal"` | guard + heal tier: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (default tier heal) | when any non-passive action is permitted | decisions, detections, interventions | + +Also: `policy.allow` / `policy.deny` narrow the permitted set; `pause()` stops gating and triggers while tracing +continues; `setMode` applies to the next gate. Passive actions per trigger: mutation `apply`, request `send`, +failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. Details: +[public-api-and-lifecycle](runtime/public-api-and-lifecycle.md#modes-and-tiers), +[decide-policy-actions](runtime/decide-policy-actions.md). + +## 7. With no model: fail open, observe only + +`consultable()` (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.consultable`) is true only when a provider exists +and its state is `ready` or `off`. Consequences: + +| provider state | what triggers do | +|---|---| +| no provider (`createRuntime` without `decider`/`model`, `GenClass.init` outside a browser without a `decider`, `model: false`, kill switch) | nothing is computed or held; every subject proceeds; no `Decision` ever | +| `off` (idle preload not started yet) | facts and triage run; the first salient situation starts the load (`void this.ready`) and fails open | +| `loading` | skipped entirely: no facts, no holds, no records | +| `error` | same as `loading`, permanently: `ready` is memoised and nothing retries the load | +| `ready` | full pipeline | + +What a default `GenClass.init()` does at 654d822 (verified by code reading only; no test covers it): it creates a +model host for `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` +(`packages/runtime/src/model/host.ts`), the idle preload fetches `model.json` from a package that does not exist, +the status becomes `error`, the console prints `[GenClass] Model unavailable (...); observing only.`, and from then on +no situation is built and nothing is held or acted on. Tracing, field versions, baselines, invariants and profiles keep +learning; `rt.situation()` still works; `rt.ask()` rejects with `GenClassUnavailableError` (or the raw provider error +when `timeoutMs` is set). To exercise the decision +pipeline today, self-host the v0.1 GenClass model (`npx genclass-runtime fetch-model <dir> --from +https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, then `model: { baseUrl }`); v0.1 is a general +classifier, not trained for runtime decisions, and answers `unusual` almost always. Full sequence: +[status-and-known-issues](status-and-known-issues.md#1-what-a-default-install-does-today-model-unpublished). + +## 8. Workstreams and ownership + +The project was built by parallel workstreams coordinated by a lead, communicating through status and NEEDS files +(detail, conventions and drift: [status-and-known-issues](status-and-known-issues.md#workstreams-and-ownership)). + +| workstream | owns | writes | +|---|---|---| +| lead | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`, `OPEN_TASKS.md` (inferred); approvals, merges, publishing; `training/` per CONTRACT §1 | contract additions (CONTRACT §13) | +| CORE | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; situation wording; `src/types.ts` | `packages/runtime/STATUS.md` (with "Deviations from the contract") | +| MODEL | `packages/runtime/src/model/**`, `packages/runtime/bin/genclass-runtime.mjs`; co-owns the model-seam section of `types.ts` | `packages/runtime/src/model/README.md`, MODEL -> TRAIN notes in `training/NEEDS.md` | +| UI | `packages/runtime/src/devtools/**`, `packages/runtime/src/adapters/**` (CONTRACT §13) | `packages/runtime/UI-NEEDS.md` | +| SIM | `sim/` | `sim/NEEDS.md`, `sim/README.md` | +| DEMOS | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*.{md,json}` | +| TRAIN | `training/` (per `training/README.md`; CONTRACT §1 lists the lead as owner) | `training/NEEDS.md`, `training/LOG.md`, `training/EVAL.md` | +| REVIEW | `packages/runtime/test/review-*.test.ts` (a contract: fix code, not these tests) | findings fixed in batch 3 | + +NEEDS items carry OPEN / ASK / DONE (plus INFO in `training/NEEDS.md`); contract changes go through the lead; SIM and +DEMOS must not read each other's code. For an agent working alone, these files are the record of intent: update the +relevant STATUS/NEEDS entry when you change behaviour they describe. + +## 9. Where the project stands (654d822) + +| item | state | +|---|---| +| Runtime core, model host, devtools, adapters | done; source frozen at `situation-v1` | +| npm | `@genclass/runtime@0.1.0-alpha.0` published (per `OPEN_TASKS.md`; tag `v0.1.0-alpha.0`); it takes no actions until the model package exists | +| Model package | `@genclass/runtime-model@0.1.0` not created (`packages/runtime-model/` has only `MODEL_CARD.md`); no `runtime-model-v0.1.0` tag exists for the planned GitHub release | +| SIM data | phase A done (600,676 rows); phase B (1.4M rows) in progress at commit time | +| Training | stage 1c done; stage-2 pilot done; final round 1 (R17, R32 on phase A) launched, no results in the repo | +| Demos | built; results only with the v0.1 model (not trained for runtime decisions); `demos/src/server/data/cities.ts` is missing from git (root `.gitignore` rule `data/`), which blocks building the search demo from a fresh clone | +| Next (`OPEN_TASKS.md`) | choose R17/R32, publish the model package and release, then `@genclass/runtime@0.1.0`; add CI; re-run demos with the trained model; investigate hold-induced harm and typeahead triage sensitivity (salient about 6 times per clean trial) | +| Open runtime issues | `demos/NEEDS.md` §1 (held write lands after a newer user write), §2 (hold latency), §5 (`retry` offered for non-idempotent requests), §6 (no EventSource observer) | +| Infrastructure | no `.github/` (no CI); no committed root `package-lock.json`; test files are not type-checked; `jev_local/data/` is missing (gitignored), so 20 legacy Python test files fail at collection | + +**Local verification when these docs were written (2026-10-07; macOS, 16 GB RAM, Node v25.6.0, npm 11.8.0).** `npm install` at the +root succeeds in about 18 s (one EBADENGINE warning for vitest 5.0.3 on Node 25; it creates an untracked root +`package-lock.json` and chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, revert with `git checkout -- +packages/runtime/bin/genclass-runtime.mjs`). In `packages/runtime`: `npx tsc -p tsconfig.json --noEmit` is clean; +`npx tsup` builds in about 2.5 s; `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` gives +286 passed and 14 skipped (the model-parity tests that need `GENCLASS_MODEL_DIR`). Not run: Playwright, the smoke +test, sim, training, demos, Python tests, model downloads, anything on Azure. + +**Working rule for agents (set when these docs were written).** CONTRACT §0 rule 5 ("the Mac only edits files"; everything on the +Azure `train` VM through `scripts/vm.sh`) existed because the original author's Mac had 8 GB RAM. On other machines, +`npm install`, typecheck, build and unit tests are light and verified to work locally. Ask the user before running the +sim, training, Playwright, model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, +`training/*.sh`, `sim/scripts/*`). Do not change situation text without a plan for regenerating data and retraining. + +## Related docs + +- [README](README.md) (index of agent docs), [repo-map](repo-map.md), [glossary](glossary.md), + [playbooks](playbooks.md). +- Runtime: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), + [observe-and-trace](runtime/observe-and-trace.md), [state-and-adapters](runtime/state-and-adapters.md), + [learn-situation-triage](runtime/learn-situation-triage.md), + [decide-policy-actions](runtime/decide-policy-actions.md), [model-host](runtime/model-host.md), + [devtools](runtime/devtools.md), [build-test-release](runtime/build-test-release.md). +- Cross-cutting: [model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md). +- Offline and legacy: [sim](sim.md), [training](training.md), [demos](demos.md), + [genclass-model-lineage](genclass-model-lineage.md), [extension-and-benchmarks](extension-and-benchmarks.md). +- Human docs (drift documented in status-and-known-issues): [CONTRACT.md](../runtime/CONTRACT.md), + [API.md](../runtime/API.md), [ARCHITECTURE.md](../runtime/ARCHITECTURE.md), + [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md), [OPEN_TASKS.md](../../OPEN_TASKS.md). diff --git a/docs/agents/playbooks.md b/docs/agents/playbooks.md new file mode 100644 index 00000000..aa8d68f7 --- /dev/null +++ b/docs/agents/playbooks.md @@ -0,0 +1,774 @@ +# Playbooks: recipes for common changes + +> **Scope:** step-by-step recipes for the edits agents are most often asked to make in this monorepo: the runtime (`packages/runtime`), its model host and devtools, the adapters, `sim/`, `training/`, `demos/`, releases, test runs, debugging a reported intervention, and these docs. Each recipe merges and deduplicates the "How to change it safely" sections of the subsystem docs. +> **Read this when:** you have a concrete change to make and need the full checklist: files and symbols to touch, tests to add and run, parity / retrain / release consequences, and the traps. +> **Source of truth:** the code. Pointers verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. If this doc and a subsystem doc disagree, check the code and fix whichever is wrong (recipe 26). + +Conventions used below: + +- Code pointers are `path/from/repo/root.ts` -> `symbol`. A method is written `Class.method`. +- In "Tests" lines, test files are listed after their directory, e.g. `packages/runtime/test/`: `atoms.test.ts`, `policy.test.ts`. +- **[ask first]** marks a step that runs something the run policy in AGENTS.md reserves for the user's approval (see [Where to run things](#3-where-to-run-things)). +- **Model input** means any byte that reaches `EvaluateRequest.state` or `EvaluateRequest.questions` (situation text, question headers, option descriptions, diagnosis labels), plus the token ids derived from it. +- Recipes say "the lead", "SIM" or "TRAIN" where the original workstream protocol required their sign-off. In an agent session, stop and get the user's decision at those points; record it the way the protocol describes (recipe 26). + +## Before you start + +### 1. Ground rules (binding: `docs/runtime/CONTRACT.md` §0 and §0.5) + +- **No rules in the runtime.** The runtime computes generic facts and decides whether to ask the model (triage); it never maps a fact pattern to a diagnosis or action with an if/then. The model chooses; `packages/runtime/src/decide/policy.ts` -> `gate` only filters. This also holds when you fix a false intervention (recipe 25). +- **One situation implementation.** `packages/runtime/src/situation/*` is the only code that builds situation text. The sim runs it unchanged (`sim/src/run/rt.ts` -> `realRuntimeFactory`), and `training/curriculum/rt.py` is a hand port of it. +- **Determinism.** Inside `packages/runtime/src`, never call `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`/`setInterval`. Use the injected `Clock` (`this.clock` in `RuntimeImpl`, `api.clock` in plugins), take ids from counters, and clear every timer you arm in `RuntimeImpl.destroy` (or make it harmless when it fires later). Sim world code uses keyed `Rng` forks only (`sim/src/rng.ts` -> `Rng.fork`). +- **Fail open.** Every path that has no usable answer runs the controller's passive action. Never make the app wait on the model. +- **`GenClass.init` never throws.** Observers install inside `tryAdd` in `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; plugin `setup` errors are swallowed. +- **Honest evaluation.** `sim/` and `demos/` never import or read each other. Do not fix the demo apps' latent bugs or tune them for GenClass. +- **Dependencies.** No new runtime dependency besides `onnxruntime-web` without the lead. TypeScript strict, ESM only. +- **Legacy content stays as is** (CONTRACT §1): `jev_local/`, `extension/` and the jev-era `docs/*.md`. This does not cover `docs/runtime/` or `docs/agents/`. +- **Review tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make it pass; fix `src/`. +- **Code wins over docs.** `docs/runtime/CONTRACT.md` was last edited in a53dd38, before batch 3. STATUS, the READMEs, `UI-NEEDS.md`, `sim/NEEDS.md` and `training/NEEDS.md` have stale items. Check the drift tables in [status-and-known-issues.md](status-and-known-issues.md#drift-and-open-issues) before trusting them. + +### 2. The `situation-v1` freeze + +Tag `situation-v1` is commit 1a77558. `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. SIM phase A (600,676 rows) and TRAIN final round 1 were built on that exact text. Before editing, classify your change (condensed from [model-io-contract.md](model-io-contract.md#versioning-what-invalidates-the-trained-model)): + +| class | what you touch | consequence | +|---|---|---| +| **A. Model input text or label space** | `packages/runtime/src/situation/{facts,describe,build,serialize,questions}.ts`; `packages/runtime/src/util.ts` formatters, redaction and signature normalisation; `packages/runtime/src/state/fields.ts` -> `changeText`; `ActionEffect.changed` sentences (`packages/runtime/src/runtime.ts`, `packages/runtime/src/observe/fetch.ts`, `packages/runtime/src/observe/xhr.ts`); observer op names, details and event `data` keys; which actions are offered (`packages/runtime/src/situation/build.ts` -> `builtinApplicable`) | user approval, SIM regeneration, `training/curriculum/rt.py` re-port, retrain, re-eval, re-export, a new freeze tag (recipe 6) | +| **B. Distribution only** | `neutral` flags and thresholds in `packages/runtime/src/situation/facts.ts`, trigger conditions, baseline/profile estimators, invariant learning, hold/bypass rules | regenerate SIM data; retrain recommended | +| **C. Token ids** | `packages/runtime/src/model/{serialize,pyutil,tokenizer,packer}.ts`, `packages/runtime/src/model/engine.ts` -> `FEEDS` | change `jev_local/` in lockstep, regenerate fixtures, retrain if the Python side changed (recipe 13) | +| **D. Answers only** | `packages/runtime/src/model/calibrate.ts`, `calibration.json` | re-run `training/eval_runtime.py`; no retrain | +| **E. Nothing the model sees** | `packages/runtime/src/decide/policy.ts` defaults, host/loader/worker, devtools, adapters, report wording | runtime tests only; mirror gate changes in `training/eval_runtime.py` | + +Class A and C changes need the user's go-ahead **before** you edit. + +### 3. Where to run things + +Run policy (set when these docs were written, 2026-10-07): the original team ran every build and test on an Azure VM through `scripts/vm.sh`, because the original author's Mac has 8 GB RAM (CONTRACT §0 rule 5; the subsystem docs repeat "VM only"). On other machines the light steps below are verified to work locally and may be run without asking. Everything else needs the user's approval first. + +| task | run locally? | command | verified result (macOS, 16 GB, 10 CPUs, Node v25.6.0, npm 11.8.0) | +|---|---|---|---| +| install | yes | `npm install` at the repo root | 18 s, 134 packages. One `EBADENGINE` warning (vitest@5.0.3 wants node `^22.12.0 \|\| ^24.0.0 \|\| >=26.0.0`; Node 25 works). Side effects: an untracked root `package-lock.json` (never committed; do not commit it without the user's decision) and a mode change on `packages/runtime/bin/genclass-runtime.mjs` (committed 644, npm sets 755): revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | +| runtime typecheck | yes | `cd packages/runtime && npx tsc -p tsconfig.json --noEmit` | clean, ~1.6 s. Covers `src/` only: tests are never type-checked | +| runtime build | yes | `cd packages/runtime && npx tsup` | ~2.5 s; entries `index`, `adapters/{react,redux,zustand}`, `devtools/index`, `worker`; `.d.ts` for all but `worker`; `dist/` ~1.6 MB with maps | +| runtime unit tests | yes | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` | Test Files 36 passed, 1 skipped (37); Tests 286 passed, 14 skipped (300); ~2.4 s | +| the 14 skipped model-parity tests | **[ask first]** (model download) | same command with `GENCLASS_MODEL_DIR=<model dir>` (default `<repo>/.cache-model`) | skipped files/tests: `test/model/packer.test.ts` (10 of 10), `engine.test.ts` (3 of 4), `calibrate.test.ts` (1 of 8). With a model directory all 300 pass (per STATUS) | +| Playwright (model specs, devtools UI spec), `packages/runtime/test/smoke/smoke.sh` | **[ask first]** | see recipe 23 | not run when these docs were written | +| sim (tests, smoke, generation), training, demos eval, Python tests, model downloads | **[ask first]** | see recipes 17, 18, 22, 23 | not run when these docs were written | +| anything that touches Azure: `scripts/*.sh`, `training/*.sh`, `sim/scripts/*` | **[ask first]** | | `scripts/vm.sh` also needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are not in the repo | + +There is **no CI** (no `.github/` directory). Your local typecheck and unit-test run is the only gate before review. + +### 4. Read these first + +| file | why | +|---|---| +| [status-and-known-issues.md](status-and-known-issues.md) | what is shipped, frozen, in flight; ownership; open product risks; drift tables | +| the subsystem doc for your area (index below) | "Invariants and gotchas", "How to change it safely", "Tests" | +| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | the lead's task list (Next / In progress / Done / Needs the user) | +| [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md) | CORE's state, example situations per trigger, "Deviations from the contract", "Open issues" | +| [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md) | binding rules (§0, §0.5), workstream layout (§1), additions (§13). Stale in places | +| [`docs/runtime/API.md`](../runtime/API.md) | human API reference; update it with any public-surface change | +| NEEDS files: [`demos/NEEDS.md`](../../demos/NEEDS.md), [`sim/NEEDS.md`](../../sim/NEEDS.md), [`training/NEEDS.md`](../../training/NEEDS.md), [`packages/runtime/UI-NEEDS.md`](../../packages/runtime/UI-NEEDS.md) | open cross-workstream requests (OPEN / ASK / DONE); `demos/NEEDS.md` §1, §2, §5, §6 are open in runtime code | +| [`training/LOG.md`](../../training/LOG.md), [`training/EVAL.md`](../../training/EVAL.md) | before any training or eval work | + +Ownership (CONTRACT §1 and §13): CORE owns `packages/runtime/src` except `model/` (MODEL) and `adapters/` + `devtools/` (UI); SIM owns `sim/`, TRAIN `training/` (CONTRACT §1 lists the lead), DEMOS `demos/`, REVIEW the `review-*` tests. + +### 5. Recipe index + +| # | recipe | area | can change model input? | needs **[ask first]** runs to finish? | +|---|---|---|---|---| +| 1 | [Add or change an observer](#1-add-or-change-an-observer) | runtime | yes (op names, details, events) | no | +| 2 | [Add or change a generic fact](#2-add-or-change-a-generic-fact) | runtime | yes | for the parity follow-up | +| 3 | [Add a trigger kind](#3-add-a-trigger-kind) | runtime + sim + training | yes | yes | +| 4 | [Add or change a built-in action](#4-add-or-change-a-built-in-action) | runtime (+ sim, training) | yes | for a new action | +| 5 | [Change a policy threshold or default](#5-change-a-policy-threshold-or-default) | runtime | no (distribution for triage) | no | +| 6 | [Change situation text, serialiser, budgets or questions](#6-change-situation-text-serialiser-budgets-or-questions) | runtime + sim + training | yes | yes | +| 7 | [Change the state pipeline or invariants](#7-change-the-state-pipeline-or-invariants) | runtime | sometimes | no | +| 8 | [Add or change a framework adapter](#8-add-or-change-a-framework-adapter) | runtime (UI) | no | smoke test only | +| 9 | [Add a public API method, option, event or subpath export](#9-add-a-public-api-method-option-event-or-subpath-export) | runtime | only if it alters situations | smoke test only | +| 10 | [Add a custom action, standing question or plugin (app side)](#10-add-a-custom-action-standing-question-or-plugin-app-side) | app code | no retrain needed | no | +| 11 | [Add or change a devtools view](#11-add-or-change-a-devtools-view) | runtime (UI) | no | Playwright for screenshots | +| 12 | [Change model loading or backends](#12-change-model-loading-or-backends) | model host | no | browser specs | +| 13 | [Change the packer, tokenizer, serializer or calibration](#13-change-the-packer-tokenizer-serializer-or-calibration) | model host + `jev_local` | yes (token ids) | yes | +| 14 | [Regenerate model parity fixtures](#14-regenerate-model-parity-fixtures) | model tests | no | yes | +| 15 | [Add a sim feature module](#15-add-a-sim-feature-module) | sim | data only | yes | +| 16 | [Change sim oracle, labelling, ask questions or splits](#16-change-sim-oracle-labelling-ask-questions-or-splits) | sim | labels only | yes | +| 17 | [Generate a data set](#17-generate-a-data-set) | sim | n/a | yes | +| 18 | [Train, evaluate and export a model](#18-train-evaluate-and-export-a-model) | training | n/a | yes | +| 19 | [Publish @genclass/runtime](#19-publish-genclassruntime) | release | n/a | yes (user publishes) | +| 20 | [Publish @genclass/runtime-model and point the runtime at it](#20-publish-genclassruntime-model-and-point-the-runtime-at-it) | release | n/a | yes | +| 21 | [Add a CI workflow](#21-add-a-ci-workflow) | repo | no | no | +| 22 | [Add or change a demo and re-run trials](#22-add-or-change-a-demo-and-re-run-trials) | demos | no | yes | +| 23 | [Run each test suite](#23-run-each-test-suite) | all | n/a | some | +| 24 | [Write a runtime unit test](#24-write-a-runtime-unit-test) | runtime tests | n/a | no | +| 25 | [Investigate a false intervention reported by a user](#25-investigate-a-false-intervention-reported-by-a-user) | runtime | depends on the fix | no | +| 26 | [Update these docs after a code change](#26-update-these-docs-after-a-code-change) | docs | n/a | no | +| 27 | [Touch legacy code: jev_local, extension, benchmarks, ops scripts](#27-touch-legacy-code-jev_local-extension-benchmarks-ops-scripts) | legacy | possibly | yes | + +## Definition of done + +A change is done when all of these hold. Say explicitly in your final report which ones you could not meet. + +1. **Typecheck clean:** `cd packages/runtime && npx tsc -p tsconfig.json --noEmit`. If you touched `sim/src` types, also `npm run typecheck -w @genclass/sim` (light; not run when these docs were written). +2. **Unit tests pass:** the full runtime suite (command in [Where to run things](#3-where-to-run-things)). Without a model directory the baseline is 286 passed / 14 skipped in 36 + 1 files; your new tests add to "passed" and nothing new is skipped. No `review-*.test.ts` was edited. +3. **New behaviour has a test** in house style (recipe 24), including a "benign stays quiet" test for anything that can make a situation salient. +4. **Build passes** (`npx tsup`) if you touched `package.json` exports, `tsup.config.ts`, the worker, dynamic imports or anything bundling-related. +5. **Mirrors updated by hand** (the runtime's `tsc` checks none of them; the sim loads the runtime by module name, so a mismatch shows up only at sim run time): `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`, `demos/src/dev/runtime-shim/*` (`ShimRuntime`), `sim/src/run/rt.ts` -> `RuntimeLike` / `createOptions`, `sim/src/types.ts`, `training/curriculum/rt.py`, the devtools copies of report wording (`packages/runtime/src/devtools/ui.ts` -> `LEAD`, `NOUN`). +6. **Freeze respected:** `git diff situation-v1 -- packages/runtime/src` shows no class A/B/C change, or the user approved it and your report lists the follow-ups (SIM regeneration, `training/curriculum/rt.py` re-port, retrain, re-export, new freeze tag). Do not create freeze tags yourself. +7. **Docs updated** (recipe 26): `packages/runtime/src/types.ts` JSDoc, `docs/runtime/API.md`, `packages/runtime/README.md` for public surface; `packages/runtime/STATUS.md`; the matching `docs/agents/*.md`; `OPEN_TASKS.md` when a listed item moves. +8. **Workspace clean:** no root `package-lock.json` committed (unless the user decided to), the bin file mode reverted, no `dist/`, `*.tgz` or regenerated screenshots committed by accident. +9. **Nothing irreversible without the user:** no `npm publish`, `git push`, tag, GitHub release, Azure VM start or paid API call unless the user explicitly asked for that action. +10. **Report** lists the commands you ran with their results, and the **[ask first]** suites you did not run (Playwright, smoke, sim, model tests, training). + +## Recipes: runtime core + +### 1. Add or change an observer + +**Goal.** Trace a new async source (e.g. `EventSource`, requested in `demos/NEEDS.md` §6, or `BroadcastChannel`), or change how an existing observer records ops and events. + +**Steps.** +1. Decide whether you need core code. App-specific sources can stay in a plugin: `PluginApi.recordOp` / `endOp` / `runInOp` (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.pluginApi`), with no core or parity impact (recipe 10). +2. Create `packages/runtime/src/observe/<name>.ts` exporting `install<Name>(...)` that returns an uninstall function, or `null` when the global is missing. Follow `packages/runtime/src/observe/fetch.ts` -> `installFetch`: a `disabled` flag so the wrapper becomes a pass-through after `destroy()`, restore the global only if it still holds your wrapper, wrap all tracing in try/catch, use the host's clock. +3. Register it in `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers` with `if (on("<name>")) tryAdd("<name>", () => install<Name>(...))`. `on(k)` defaults to true; pass a second argument (as `timers` does with `browserLike`) to make the default conditional. +4. Add the name to `packages/runtime/src/types.ts` -> `ObserverName`; TypeScript then forces it into `packages/runtime/src/index.ts` -> `ALL_OFF`. +5. Add the key to every explicit observe map: `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts` (`OBSERVE`), the `ONLY_*` constants in `review-fetch.test.ts` / `review-timers.test.ts`, `const OFF` in `dom.test.ts`, and `sim/src/run/rt.ts` -> `createOptions` (set it to `false` unless SIM wants it). +6. Reuse an existing `packages/runtime/src/types.ts` -> `OpKind` if you can. A new kind also touches `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `packages/runtime/src/runtime.ts` -> `PROFILED`, and situation text (class A). +7. To carry causality across a new async boundary (`requestAnimationFrame`, `queueMicrotask`, `MessagePort`), copy `packages/runtime/src/observe/timers.ts` -> `installTimers`: capture `ctx.peek()` at schedule time, resolve a `LazyOp` to `.nearest`, call `ctx.stick(lazyTimer(parent, label))` in the callback. Never give a `LazyOp` a `LazyOp` parent. +8. Changing DOM recording (`packages/runtime/src/observe/dom-user.ts` -> `installDomUser`): keep the `ignoredEvent(e) || programmatic(e)` guard and the rule that sensitive fields record `""`. If `describeElement` output changes, the sim's synthetic targets must follow. +9. Adding a volatile header: add it to both `packages/runtime/src/observe/fetch.ts` -> `VOLATILE_HEADERS` and `packages/runtime/src/observe/xhr.ts` -> `VOLATILE`, so identities match across transports. + +**Tests.** `packages/runtime/test/`: install and record; `destroy()` restores the global (next to `dom.test.ts` "browser globals are restored by destroy()"); pass-through after destroy (`review-fetch.test.ts` pattern); a read-only global does not throw (`batch3.test.ts`, `review-misc.test.ts` patterns). For context changes run `context.test.ts` and `review-timers.test.ts` with `NODE_OPTIONS=--expose-gc` (otherwise the gc test logs a skip and passes). For DOM changes run `dom.test.ts`, `review-dom.test.ts`. + +**Parity / retrain / release.** A new observer that the sim leaves off adds no training rows, but its ops, op names, `detail` strings and event `data` keys appear in timelines and facts at runtime: they are class A for any trigger the sim does produce. Renaming existing op names, details or event keys (`packages/runtime/src/situation/describe.ts` -> `eventLine` reads `count`, `first`, `route`, `key`, `duration`, `summary`, `message`) is class A. Signature normalisation (`packages/runtime/src/util.ts` -> `isIdSegment`, `isSlugId`) also keys baselines and the persisted profiles under `genclass.profiles.v1`. + +**Gotchas.** Captured natives (`packages/runtime/src/clock.ts` -> `browserClock` timers, `packages/runtime/src/index.ts` -> `NATIVE_FETCH`) must stay at module top level, or the runtime observes its own timers and model download. Two runtimes on one page double-wrap every global. WebSocket instances and timer callbacks created before `destroy()` keep tracing. Sync XHR and keepalive fetch raise no request trigger. Nav routes are not redacted. + +**See.** [observe-and-trace.md](runtime/observe-and-trace.md#how-to-change-it-safely), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely). + +### 2. Add or change a generic fact + +**Goal.** Add a new uniform fact, reword one, change whether it is `neutral` (triage), or change a triage threshold such as the M8 latency ratio. + +**Steps.** +1. Get the user's go-ahead: every variant is class A (wording) or class B (neutral flag, threshold). +2. Edit the per-trigger function in `packages/runtime/src/situation/facts.ts`: `mutationFacts`, `requestCommon` (shared by request/failure/stall), `failureFacts`, `stallFacts`, `inconsistencyFacts`, `transitionFacts`, `errorFacts`, `askFacts`; all dispatched by `computeFacts`. Build facts with the module's `fact(text, kind, neutral)` helper. State relations and numbers explicitly ("after", "newer", "in a row"); never phrase a verdict ("this is a bug"). +3. Data comes only from `SitEnv` (`packages/runtime/src/situation/env.ts`), implemented by `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Add a read-only member there if needed. Read time only from `env.now()`. No ops, events or store writes (the single allowed write is the `op.reads` cache in `mutationFacts`). +4. Pick `kind` deliberately: `packages/runtime/src/situation/facts.ts` -> `RANK` decides which facts survive the budget. A new kind needs `packages/runtime/src/types.ts` -> `FactKind`, an entry in `RANK` (typed `Record<FactKind, number>`, so the compiler forces it) and `RANK` in `training/curriculum/rt.py`. +5. Pick `neutral` deliberately: `false` makes the trigger salient, which means a model call and possibly a hold of the user's write or request. Triage is per trigger (the same repetition fact is salient on `request`, neutral on `failure`/`stall`). +6. Keep ordering deterministic: `orderFacts` sorts non-neutral first, then by rank, stable; `MAX_FACTS` = 12. +7. Check wording consumers: `packages/runtime/src/decide/report.ts` -> `topFact` and `packages/runtime/src/devtools/ui.ts` skip provenance with the regex `^This (write|request) (comes from|has no known cause)`; keep it matching. +8. Mirror the computation and ordering in `training/curriculum/rt.py` (`mutation_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`, `order`). +9. Variant, the numbers behind facts: baseline estimators live in `packages/runtime/src/learn/baselines.ts` -> `Baselines` (latency needs ≥ 5 samples, 64-sample window, failure streak, 10 s rate), transition rarity in `packages/runtime/src/learn/profiles.ts` -> `Profiles` (`MIN_COMPLETIONS`, `RARE`). Stall timing (`RuntimeImpl.watchStall`) and several request facts read them. Tests: `learn.test.ts`, `review-precision.test.ts`, `situation.test.ts`. Class B (class A where a number is printed). + +**Tests.** Add a positive test (the situation reaches `decider.calls`) and a benign test (nothing salient; pattern: `packages/runtime/test/review-precision.test.ts`). Update exact-text assertions found with `grep -rn "<old sentence>" packages/runtime/test`: typically `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `learn.test.ts`. If a `review-*` assertion must change, raise it with the user instead of rewriting it. Paste the situations printed by `situation.test.ts` and `budget.test.ts` into the example blocks of `packages/runtime/STATUS.md`. + +**Parity / retrain / release.** Follow recipe 6, "Parity" (SIM regeneration, `training/curriculum/rt.py`, retrain, new freeze tag). A threshold change alters which situations become rows even when no sentence changes. + +**Gotchas.** Plugin facts are always neutral and rank last. `rt.situation()` with no argument builds an `ask` situation, which is always salient, so the devtools Now view cannot tell you whether a trigger would be salient. Facts are computed only while the runtime is consultable. Making facts non-neutral increases holds: OPEN_TASKS lists hold-induced latency (search clean p50 14 -> 125 ms with v0.1) and typeahead being salient about 6 times per clean trial. + +**See.** [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes). + +### 3. Add a trigger kind + +**Goal.** Add a new kind of moment at which the model is consulted (alongside `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, `ask`). + +**Steps.** +1. Get the user's go-ahead: this adds a new question family to the model's input and needs data and retraining. +2. `packages/runtime/src/types.ts` -> `TriggerKind`. The compiler then flags every `Record<TriggerKind, …>`: `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS` (passive first), `PASSIVE`, `ACTION_INSTRUCTIONS`; `packages/runtime/src/decide/report.ts` -> `NOUN`. `packages/runtime/src/devtools/ui.ts` -> `NOUN` is a `Record<string, string>` and must be updated by hand. +3. `packages/runtime/src/situation/env.ts` -> `SubjectSpec` (the subject's shape), then `packages/runtime/src/situation/build.ts` -> `subjectOf`, `subjectOp`, `involvedStores`, `involvedFields`, `builtinApplicable`, `subjectRef` (`isTrigger` derives from `TRIGGER_ACTIONS`). +4. `packages/runtime/src/situation/facts.ts` -> a new facts function wired into `computeFacts` (recipe 2). +5. A raise site: implement `Controller` (`packages/runtime/src/decide/exec.ts`) and call `RuntimeImpl.trigger(spec, ctl, { hold, priority })` from `packages/runtime/src/runtime.ts` or an observer. Add `revertable`/`revert` only if the subject can be reverted exactly (a `revert` extends the queue deadline by `LATE_REVERT_MS`). +6. Mirrors: `sim/src/types.ts` (`TriggerKind`, `PASSIVE`), sim scenarios that can produce it and the oracle (`sim/src/oracle/diagnose.ts`, `sim/src/oracle/cost.ts`), `training/curriculum/rt.py` (`TRIGGER_ACTIONS`, `ACTION_INSTR`, a facts port), `training/curriculum/fmt.py` -> `TRIGGER_ACTIONS`, `training/eval_runtime.py` -> `PASSIVE`, devtools labels. + +**Tests.** `packages/runtime/test/`: a `situation.test.ts` case (key order, section caps, first fact), a controller test in the style of `atoms.test.ts` / `fetch.test.ts` (hold, fail-open at the budget, passive on every exit), `report.test.ts` for the report noun, `devtools.test.ts` if the overlay labels it. + +**Parity / retrain / release.** Class A plus a new label space: recipe 6 "Parity" in full, and the sim must be able to force every action of the new trigger. + +**Gotchas.** Controllers must tolerate a second `passive()` call (`runCustom` calls it outside the guard). Priority 2 is used only for held subjects; non-held ones are capped at 1. + +**See.** [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [decide-policy-actions.md](runtime/decide-policy-actions.md#how-to-change-it-safely). + +### 4. Add or change a built-in action + +**Goal.** (a) Change what an existing built-in action does or the `changed` sentence it reports; or (b) add a new built-in action. + +**Steps for (a), mechanics.** +1. Find the controller: mutation -> `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; inconsistency, transition and error -> `RuntimeImpl.raiseInconsistency`, `raiseTransition`, `reportError`, whose `rollback` runs `RuntimeImpl.rollback` (inconsistency: last consistent snapshot) or `RuntimeImpl.revertChain` (transition, error: the chain's own writes) and whose `resync` runs `RuntimeImpl.resync`; request, failure and stall -> `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `reqCtl`, `failureGate`, `stallController`) and `packages/runtime/src/observe/xhr.ts` -> `installXHR` (request gate only; XHR failures and stalls are passive-only). +2. Keep the controller contract: throw when the action cannot run (the passive action then runs); return an exact `changed` sentence; provide `undo` only if the effect is truly reversible and idempotent; mark answers GenClass synthesises with `synthetic: true` and an `x-genclass` header; tolerate repeated `passive()` calls. +3. Applicability (whether it is offered) lives in `packages/runtime/src/situation/build.ts` -> `builtinApplicable`. Example open issue: `retry` is offered for any replayable fetch with `attempt < 4`, including non-idempotent POSTs (`demos/NEEDS.md` §5). + +**Steps for (b), a new action.** Do not do this in the runtime alone. +1. Get the user's go-ahead (class A, new label). +2. `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS` (name, tier `guard` or `heal`, model-facing description) and `TRIGGER_ACTIONS` (passive stays first). +3. `packages/runtime/src/situation/build.ts` -> `builtinApplicable`; the controller's `run()` for that trigger (step a1). +4. `packages/runtime/src/decide/report.ts` -> `LEAD` and `packages/runtime/src/devtools/ui.ts` -> `LEAD`. +5. Sim: `sim/src/oracle/cost.ts` -> `TIER`, `sim/src/run/transform.ts` -> `ACTION_PARA`, the test double `sim/src/run/fake-runtime.ts`, and a scenario in which forcing it is meaningful. +6. Training: `training/curriculum/fmt.py` -> `ACTION_DESC` (canonical description first), `TRIGGER_ACTIONS`, `TIER`; `training/curriculum/rt.py` -> `ACTIONS`, `TRIGGER_ACTIONS`; `training/eval_runtime.py` -> `TIER` (unknown actions default to heal tier in eval). + +**Tests.** `packages/runtime/test/`: `fetch.test.ts`, `xhr.test.ts`, `atoms.test.ts`, `review-fetch.test.ts`, `review-xhr.test.ts` (mechanics and `changed` text); `policy.test.ts` (tiers); `report.test.ts`, `devtools.test.ts`, `devtools-runtime.test.ts` (lead words); for a new action also `situation.test.ts` (options offered). + +**Parity / retrain / release.** `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` membership/order, applicability and `ActionEffect.changed` (it reappears in later timelines) are all model input: recipe 6 "Parity". A pure mechanics change with the same `changed` text and the same applicability is class E. + +**Gotchas.** The rate limiter takes its slot before the effect, so failed attempts count; a custom action calling `ctx.builtin` takes two. `coalesce` (≤ 8 s), `delay` (≤ 8 s), `retry` backoff (≤ 5 s) keep the subject waiting after the hold budget timer is cleared. Only `discard` (and a late revert), `rollback` and custom actions with `onUndo` have an undo. The known `rollback` description mismatch (it says "last consistent snapshot" but transition/error rollback restores only the chain's writes) can only be fixed as a model-input change. + +**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes), [sim.md](sim.md#how-to-change-it-safely), [training.md](training.md#how-to-change-it-safely). + +### 5. Change a policy threshold or default + +**Goal.** Change a default such as a gate threshold, the hold budget, the rate limit, the default mode, `settleMs` or `historySize`, or change the gate logic itself. + +**Where defaults live.** + +| default | value | defined in | +|---|---|---| +| `mode` | `"guard"` | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor | +| `settleMs`, `historySize` | 60, 500 | same constructor | +| `policy.thresholds` report / guard / heal | 0.6 / 0.9 / 0.8 | `packages/runtime/src/decide/policy.ts` -> `policyConfig` | +| `policy.holdBudgetMs` | `"auto"`: clamp(1.5 × median latency, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 with no data | `policyConfig`, `holdBudget` | +| `maxActionsPerMinute`, `requireDiagnosis`, `holdUserWrites` | 60, true, false | `policyConfig` | +| queue: `MAX_QUEUE`, `CACHE_MAX`, `CACHE_TTL`, `LATENCY_SAMPLES`, `PROVIDER_TIMEOUT_MS` | 32, 64, 30 s, 20, 10 s | `packages/runtime/src/decide/decider.ts` | +| `LATE_REVERT_MS`, `BACKGROUND_DEADLINE_MS` | 2,000 ms, 5,000 ms | `packages/runtime/src/runtime.ts` | +| response cache and coalescing: `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS`; `COALESCE_MAX_WAIT_MS` | 256 KB, 64, 2,000 ms, 1,000 ms; 8,000 ms | `packages/runtime/src/observe/cache.ts`; `packages/runtime/src/observe/fetch.ts` | +| situation budgets | 3,200 / 1,100 / 500 chars | recipe 6 (model input) | + +**Steps.** +1. Change the value where it is defined (table). Options are read once in the constructor (`o.x ?? default`); only `setMode` changes behaviour live. +2. Update the JSDoc in `packages/runtime/src/types.ts` (`PolicyOptions`, `InitOptions`), `docs/runtime/API.md` ("Options", "Policy"), `packages/runtime/README.md`. +3. Gate logic: edit only `packages/runtime/src/decide/policy.ts` -> `gate`. Keep the reason strings verbatim: `policy.test.ts` and `report.test.ts` assert them, the console report prints them, devtools shows them, `demos/src/site/activity.ts` classifies decisions by the substrings `"hold budget"`, `"below the"` and `"expected"`, and the demos' results key `notExecuted` by the reason text. +4. Check the sim's forced-action contract in `sim/src/run/rt.ts` -> `createOptions` (`thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `requireDiagnosis: false`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`); it must still be able to force any action. +5. Mirror gate semantics or thresholds in `training/eval_runtime.py` (`THRESH`, `decision_metrics`) and the "Runtime gate" definition in `training/EVAL.md`. + +**Tests.** `packages/runtime/test/`: `policy.test.ts` (thresholds, reasons, tiers, rate limit), `budget.test.ts` (hold budget 300 / 150 / 800 / adaptive; `timeoutMs` = budget + 2,000 for held writes; expired queued items never computed), `fetch.test.ts` (request and failure gates fail open at 300 ms; it imports `MAX_BODY` / `MAX_ENTRIES`), `review-fetch.test.ts` (64 × 256 KB buffer bound), `atoms.test.ts` (provider error codes fail open at once), `report.test.ts`, `batch3.test.ts` and `review-misc.test.ts` (a provider that never answers). Cache limits also appear in `docs/runtime/API.md` (`serve_cached` row) and CONTRACT §7. + +**Parity / retrain / release.** Class E for the model. Thresholds and budgets change eval comparability (tell TRAIN) and demo comparability. Triage thresholds are not policy: they are `neutral` expressions in `packages/runtime/src/situation/facts.ts` (recipe 2). + +**Gotchas.** The threshold applies to the summed probability of all permitted actions, at the candidate's tier. Thresholds of 0 run the first permitted action even at probability 0 (why the sim uses 0.5). The console hint "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" does nothing on a page where `GenClass.init` already ran. The auto hold budget is seeded from `status.warmupMs` until real latency samples exist. Several docs still say the hold budget default is 300 ms (CONTRACT §8, `demos/README.md`); the code default is `"auto"`. + +**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md#configuration-and-constants), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely). + +### 6. Change situation text, serialiser, budgets or questions + +**Goal.** Change anything the model reads: fact or timeline wording, state/stats/in-flight lines, section limits or character budgets, question headers, option descriptions, diagnosis labels, formatting or redaction helpers. + +**Steps.** +1. Get the user's go-ahead first. Any such change invalidates SIM phase A/B data and the final training rounds (`situation-v1`). +2. Edit only `packages/runtime/src/situation/*` plus helpers in `packages/runtime/src/util.ts`; text that reaches the model from elsewhere: `packages/runtime/src/state/fields.ts` -> `changeText`, `ActionEffect.changed` strings, observer op details (recipe 1). +3. Find the code by section: + +| what | runtime | Python port (`training/curriculum/rt.py`) | +|---|---|---| +| facts | `packages/runtime/src/situation/facts.ts` (recipe 2) | `*_facts`, `request_common`, `order` | +| subject sentence | `packages/runtime/src/situation/build.ts` -> `subjectOf` | `subject_sentence` | +| timeline lines | `packages/runtime/src/situation/describe.ts` -> `eventLine`, `opPhrase`; `packages/runtime/src/situation/build.ts` -> `timelineLines` | `event_lines`, `phrase` | +| state / stats / in-flight lines | `packages/runtime/src/situation/build.ts` -> `stateLines`, `statsLines`, `inFlightLines` | `state_lines`, `stats_lines`, `in_flight_lines` | +| budgets and shrink order | `packages/runtime/src/situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `sectionLimits`, `toJevState`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget` | `STATE_CHAR_BUDGET`, `LIMITS`, `section_limits`, `to_state`, `BUDGETS` | +| questions | `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `buildQuestions` | `ACTIONS`, `ACTION_INSTR`, `DIAG_INSTR`, `DIAGNOSES` | +| formatters | `packages/runtime/src/util.ts` -> `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe` | `secs`, `rel`, `fmt_num`, `ratio`, `truncate` | +| signatures | `packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`, `isSlugId` | `signature`, `is_id` | +| redaction | `packages/runtime/src/util.ts` -> `isSensitiveName`, `SECRET_WORDS`, `SECRET_PAIRS`, `defaultRedact` | | + + +4. Diagnosis labels: keep `expected` first and `transient` last (`batch3.test.ts` asserts `unusual`, `transient` are last). Also update `sim/src/types.ts` -> `DIAGNOSES`, `sim/src/world/scenario.ts` -> `DEFAULT_DIAGNOSES` and `DIAG_PARA`, `sim/src/oracle/diagnose.ts` (so the sim can emit the label), `training/curriculum/fmt.py` -> `DIAG_DESC` (canonical first). +5. Action descriptions and instructions: also `sim/src/run/transform.ts` -> `ACTION_PARA`, `training/curriculum/fmt.py` -> `ACTION_DESC` canonical first entries. Per-header calibration keys are `sha1(instructions)[:12]`, so a changed header orphans its `by_header` entry. +6. Budgets: also `sim/src/world/scenario.ts` -> `buildScenario` budget weights (3200/2000/1000 at 40/30/30), the JSDoc of `InitOptions.situation` in `packages/runtime/src/types.ts` (currently drifted), `docs/runtime/API.md`, and check token lengths against the model's `meta.max_len` (TRAIN measured about 2.4 chars/token). +7. Redaction: also `docs/runtime/API.md` "Privacy". + +**Tests.** `packages/runtime/test/`: `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `learn.test.ts`, `review-redaction.test.ts` (for redaction), `report.test.ts` / `atoms.test.ts` / `fetch.test.ts` (for `changed` text); then the full suite. Update the STATUS.md example blocks from the printed situations. **[ask first]** `sim/test/rows.test.ts`, `determinism.test.ts`, `oracle.test.ts` with `SIM_RUNTIME=real`; `training/tests/test_curriculum.py` both with and without `GC_P_RUNTIME=1` (the default run never exercises `rt.py`). + +**Parity / retrain / release (the full follow-up for any class A change).** +1. Re-port `training/curriculum/rt.py` and render a few rows per budget against `sim/samples/sample.jsonl`. +2. **[ask first]** Rebuild the runtime and regenerate SIM data (recipe 17) and `sim/samples/*`. +3. **[ask first]** Regenerate a curriculum replay set with `--p-runtime 0.8`, retrain, then evaluate, calibrate and export (recipe 18). +4. The lead tags a new freeze (the `situation-v1` convention; no v2 exists). Re-run the demos with the new model (recipe 22). + +**Gotchas.** `packages/runtime/src/situation/serialize.ts` -> `stateText` (public; `explain()`, devtools, STATUS) indents list items and is not the token text; the packer uses `packages/runtime/src/model/serialize.ts` -> `segmentText`. `COMPACT_BUDGET` (1,100, section sizes) and `COMPACT_QUESTIONS_BUDGET` (1,400, bare labels) are different constants; keep both. Situation building must stay deterministic and side-effect free, or the sim's prefix check drops trajectories. Python rows must print integral floats as ints (`training/curriculum/fmt.py` -> `js_numbers`). Known `rt.py` gaps: fact shortening floor 40 vs 60 chars, half-even vs half-up rounding on exact ties. Avoid plugin question ids `action` and `diagnosis`. + +**See.** [model-io-contract.md](model-io-contract.md#how-to-change-it-safely), [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [status-and-known-issues.md](status-and-known-issues.md#how-to-change-it-safely), [training.md](training.md#how-to-change-it-safely). + +### 7. Change the state pipeline or invariants + +**Goal.** Change how writes are proposed, held, applied, patched or reverted; fix the open user-write ordering risk (`demos/NEEDS.md` §1); add an invariant template; change flattening caps; handle dotted store names. + +**Steps.** +1. **Bypass, hold and late-revert rules:** `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` (the `bypass` expression: user-sync writes unless `policy.holdUserWrites`, GenClass writes, stores with `hold: false`, and any write while paused or destroyed), `StoreHub.revertable`, and `packages/runtime/src/runtime.ts` -> `LATE_REVERT_MS`. These are policy-visible: update `docs/runtime/API.md` "State". +2. **User-write ordering fix (`demos/NEEDS.md` §1, open):** in `StoreHub.propose`, when a bypass write targets a store whose `queue` is non-empty, either apply the pending writes first in proposal order, or mark the overlapping held writes superseded and re-gate them. Add the regression test demos suggests (hold a functional write to `s.x`, make a user-sync write to `s.x`, release with `apply`, expect the user's value) and update `atoms.test.ts` "functional updates re-run against the value at apply time", which asserts the current order. +3. **Invariant template:** `packages/runtime/src/state/invariants.ts` -> extend `Tpl`, implement it in `InvariantMiner.holds` (null when not applicable), `nonTrivial`, `valuesText` and `propose` with a deterministic id and readable text; put per-array work in `ArrayStats` so it runs once per array version. +4. **Flattening caps or hashing:** `packages/runtime/src/state/fields.ts` -> `MAX_DEPTH`, `MAX_KEYS_EXPAND`, `MAX_FIELDS_PER_STORE`, and the sampling and hashing helpers. +5. **Patch semantics:** `packages/runtime/src/state/fields.ts` -> `patchValue`; keep "removals first; never remove a path with a set beneath it". +6. **Dotted store names:** nothing enforces "no `.` in store names", and every path lookup splits on `.`. Either validate in `RuntimeImpl.atom` / `guard` / `adapter` (prefer a console warning and a sanitised name; throwing breaks apps) or pass the store explicitly instead of `path.split(".")[0]`. Fix the `packages/runtime/README.md` and `packages/runtime/src/adapters/react.ts` header examples (`"search.results"`). +7. **Settled points and snapshots:** `RuntimeImpl.settled`, `RuntimeImpl.busy`. + +**Tests.** `packages/runtime/test/`: `atoms.test.ts`, `review-hub.test.ts`, `invariants.test.ts`, `adapter-seam.test.ts`, `adapters-react.test.ts`, `adapters-redux.test.ts`, `adapters-zustand.test.ts`, `review-perf.test.ts`, `review-precision.test.ts`, `situation.test.ts`, `batch3.test.ts`, `policy.test.ts`, `learn.test.ts`, `review-actions.test.ts`; then the full suite. A new template needs a learning test and a precision test (no false `inconsistency` on benign behaviour). + +**Parity / retrain / release.** Template text, flattening and `changeText` output appear verbatim in situations: class A. Bypass/hold/ordering fixes change no text but change sim dynamics (class B): tell SIM and TRAIN. Re-run the demos' board trials to measure §1 (recipe 22). + +**Gotchas.** `review-perf.test.ts` asserts wall-clock budgets on 5,000-item stores (< 1 ms per keystroke write, < 16 ms per settled point); any O(n) per-write work (hashing, cloning, `JSON.stringify`) breaks them, and they can flake on a loaded machine. Updaters may run several times and must be pure. Rollback for `inconsistency` restores whole stores; error/transition rollback is field-precise. + +**See.** [state-and-adapters.md](runtime/state-and-adapters.md#how-to-change-it-safely). + +### 8. Add or change a framework adapter + +**Goal.** Integrate another state library (MobX, Jotai, Valtio, …) through `runtime.adapter`, or change the React, Redux or Zustand adapter. + +**Steps.** +1. Add `packages/runtime/src/adapters/<lib>.ts`. Call `runtime.adapter(name, { get, set?, subscribe? }, opts)` once per store (`packages/runtime/src/types.ts` -> `Runtime.adapter`, `AdapterIO`, `AdapterHandle`). +2. Route every app write through `handle.propose({ fn | value, commit })`. `commit(next)` must write to the library store synchronously; it runs later for held writes and never for discarded ones. Provide `set` if GenClass may write whole states (rollback, resync); without it the store is not writable. +3. Build and package: `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry` (keep the literal `"src/...ts"` strings: `packages/runtime/test/browser/build.mjs` finds them with a regex), the library in `external`; `packages/runtime/package.json` -> an `exports` subpath (`types` + `import`), an optional `peerDependencies` entry plus `peerDependenciesMeta`, and the library as a devDependency for tests. +4. If the demos use it: a shim in `demos/src/dev/runtime-shim/`, an alias in `demos/vite.config.ts`, a path in `demos/tsconfig.shim.json`. +5. Changing an existing adapter: keep its contracts (commit exactly once on apply, never on discard; Redux reducer once per applied dispatch and inner enhancers see the original action; Zustand commits with `replace = true` and forwards extra `set()` arguments; React: one atom per (runtime, name), plain `useState` fallback without a runtime). Update the file's header comment and API.md "Adapters and devtools". + +**Tests.** Model the new file on `packages/runtime/test/adapters-zustand.test.ts`: `MockRuntime` (`holdWrites`, `flushHeld`, `dropHeld`, `genclassWrite`) plus one test against the real runtime with `ManualDecider`. Run `adapter-seam.test.ts`, the `adapters-*.test.ts` files and `review-perf.test.ts`. Build with `npx tsup`. **[ask first]** `cd packages/runtime && bash test/smoke/smoke.sh` after adding an import of the new subpath to the `src/main.js` that `packages/runtime/test/smoke/smoke.sh` generates. + +**Parity / retrain / release.** Class E. A new subpath is a public-surface change: update API.md, the package README and the "Extra public surface" bullet under STATUS "Deviations from the contract (and why)". + +**Gotchas.** Redux and Zustand capture `runtime` when the store is created, so `genclass(GenClass.runtime, …)` evaluated before `GenClass.init()` gets `null` and is never guarded. Store names are global per runtime across kinds: reusing a name re-registers the store and orphans old handles. A library listener that throws inside `commit` looks like a failed setter. + +**See.** [state-and-adapters.md](runtime/state-and-adapters.md#how-to-change-it-safely), [build-test-release.md](runtime/build-test-release.md#add-a-public-entry-point-new-subpath-export). + +### 9. Add a public API method, option, event or subpath export + +**Goal.** Extend the public surface of `@genclass/runtime`. + +**Steps.** +1. **Init option:** add the field with a JSDoc default to `packages/runtime/src/types.ts` -> `InitOptions` (or `CreateOptions` if headless-only); read it once in the `RuntimeImpl` constructor with an explicit default; check the four creation paths in `packages/runtime/src/index.ts` -> `initUnsafe` (browser, non-browser, kill-switch `off`) and the `GenClass.init` fallback, and decide whether the option survives each. Host-only model options: recipe 12. +2. **`Runtime` method:** add it to `packages/runtime/src/types.ts` -> `Runtime` and implement it in `packages/runtime/src/runtime.ts` -> `RuntimeImpl`. Update every other implementer by hand: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime` and `demos/src/dev/runtime-shim/index.ts` -> `ShimRuntime` (which already lacks `adapter`, `holdBudgetMs`, `situationBudget`). Add it to `sim/src/run/rt.ts` -> `RuntimeLike` only if the sim calls it. Keep it non-throwing if devtools will call it (devtools wraps calls in `safe()`). +3. **Changing an existing method or option:** find callers outside `src/`: the sim (loaded by module name via `GENCLASS_RUNTIME`, so a break shows only at sim run time), `MockRuntime`, `ShimRuntime`, `packages/runtime/src/devtools/index.ts`, `packages/runtime/src/adapters/react.ts` -> `useRuntimeList`. +4. **Event type:** add the key and payload to `packages/runtime/src/types.ts` -> `RuntimeEvents`, add a `Set` for it in `RuntimeImpl`'s `listeners` initializer (otherwise `on(newType)` throws), fire it with `RuntimeImpl.fire`. Update `packages/runtime/src/devtools/index.ts` -> `subscribe` and its unmount test list if the overlay should react. +5. **Error class:** runtime-level errors live in `packages/runtime/src/errors.ts`; model errors in recipe 12. Re-export from `packages/runtime/src/index.ts`. +6. **Subpath export:** `packages/runtime/package.json` -> `exports` (`"./<name>": { "types": "./dist/<name>.d.ts", "import": "./dist/<name>.js" }`), `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry`, externalise any new peer library; demos shim and aliases if demos use it (recipe 8 step 4). +7. Time-dependent behaviour uses `this.clock.now()` / `this.clock.setTimeout` / `this.clock.afterTask`; store the handle and clear it in `RuntimeImpl.destroy`. +8. **Kill switch or init paths:** `packages/runtime/src/index.ts` -> `killSwitch`, `initUnsafe`; keep everything inside the try/catch of `GenClass.init`. **`destroy()`:** `RuntimeImpl.destroy` must stay idempotent, clear every new timer, uninstall observers in reverse order and dispose only a decider it created (`createRuntime` with `model: {...}` and no `decider`). +9. Docs: JSDoc in `packages/runtime/src/types.ts`, `docs/runtime/API.md`, `packages/runtime/README.md`, `packages/runtime/STATUS.md` ("Deviations" lists the public surface beyond CONTRACT §2), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). + +**Tests.** A test using `setup({ ...option })` from `packages/runtime/test/helpers.ts`. Lifecycle changes: `report.test.ts` ("GenClass.init and the kill switch"), `batch3.test.ts` ("lifecycle"), `dom.test.ts` / `fetch.test.ts` / `xhr.test.ts` (destroy restores globals), `review-misc.test.ts`. Build with `npx tsup` for export changes; **[ask first]** `cd packages/runtime && bash test/smoke/smoke.sh`. + +**Parity / retrain / release.** Only if the option alters situation text or decisions: then coordinate with SIM (`sim/src/run/rt.ts` -> `createOptions`) and treat it as class A/B. Public-surface changes go into the next release notes (recipe 19). + +**Gotchas.** `GenClass.init` is idempotent: later calls ignore their options. `createRuntime` can throw on malformed options; `GenClass.init` never does (inert fallback). Any non-`undefined` `decider` (including `null`) disables model creation. `on("status")` also fires on `setMode`. `decisions(0)` returns the whole buffer. + +**See.** [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely), [build-test-release.md](runtime/build-test-release.md#add-a-public-entry-point-new-subpath-export). + +### 10. Add a custom action, standing question or plugin (app side) + +**Goal.** Extend GenClass from application code, without changing the runtime: an app capability the model may choose, an extra question per trigger, extra facts or an app-specific signal source. + +**Steps.** +1. Write a `Plugin` (`packages/runtime/src/types.ts` -> `Plugin`: `name`, `setup?(api)`, `facts?(sit)`, `actions?`, `questions?`, `diagnoses?`) and pass it as `GenClass.init({ plugins: [p] })` or `rt.use(p)`. Single pieces: `rt.action(def)`, `rt.question(def)`. Reference app: `demos/src/demos/decisions/plugin.ts` -> `backgroundWorkPlugin`. +2. **Custom action** (`ActionDef`): `name`, `description` (the model reads it), `on: TriggerKind[]`, `tier` (default `"heal"`), optional `applicable(sit)`, `run(ctx)`. In `run`, call `ctx.describe(changed)` with exactly what changed, `ctx.onUndo(fn)` if reversible, and `ctx.builtin("<name>")` to delegate to a built-in (re-checked against mode, policy and rate, not thresholds). The passive action runs afterwards unless a built-in took over. +3. **Standing question** (`StandingQuestion`): `id`, `on`, `question` (`{ type: "noul" | "choice" | "score", instructions, criteria }`), `always?` (ask even when triage finds nothing salient), `onAnswer(answer, ctx)` (runs before any action). +4. **Facts and signals:** `facts(sit)` returns strings (always neutral, ranked last, cut first by the budget). In `setup(api)`, use `api.clock`, `api.emit`, `api.recordOp` / `api.endOp` / `api.runInOp` for app ops, and return a cleanup function. +5. One-off questions: `rt.ask(question, { about, timeoutMs })` and `rt.decide(question, options)`. +6. Changing the plugin API itself (runtime side, CORE): `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`, `action`, `question`, `use`, `pluginApi`; offering in `packages/runtime/src/situation/build.ts` -> `buildSituation`. Tests: `plugins.test.ts`, `batch3.test.ts`, `review-misc.test.ts`. + +**Tests.** Pattern: `packages/runtime/test/plugins.test.ts` (custom action runs then passive, `ctx.builtin`, default heal tier, `applicable`, standing questions and `onAnswer`, `setup` cleanup, vocabulary overrides). In an app, verify with `rt.explain(id)` and the devtools overlay. + +**Parity / retrain / release.** No retrain is needed: the model reads the description at runtime. Answer quality on custom actions and questions is unmeasured. + +**Gotchas.** Custom actions are gated at their own tier (default heal, so guard mode never runs them). At budgets ≤ 1,400 characters (`COMPACT_QUESTIONS_BUDGET`), custom descriptions are sent as `null` unless a `vocabulary.actions` override of ≤ 24 characters exists, so the model sees only the name. Avoid question ids `action` and `diagnosis`. A non-iterable `plugins`, `actions` or `questions` throws inside the constructor after observers were installed (`GenClass.init` then returns an inert runtime). Custom actions can hold a subject indefinitely. Nothing acts until a model is loaded (see recipe 25 step 1). + +**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), [`docs/runtime/API.md`](../runtime/API.md) "Plugins". + +### 11. Add or change a devtools view + +**Goal.** Change the overlay (`@genclass/runtime/devtools`): add a tab, show a new `Decision` / `ActionRecord` field, change report wording, add a mount option, change styling. + +**Steps.** +1. **New tab:** `packages/runtime/src/devtools/index.ts` -> extend `DevtoolsTab` and `TABS` (keep `interventions` and `detections` first: the counters read `tabBtns[0]` and `tabBtns[1]`), add a pane in the constructor's `panes` record. If it polls the runtime, gate it like `renderNow` (open, tab selected, not paused, not dead) and refresh it from `startTicking`. Widen the `tab` union in `demos/src/dev/runtime-shim/devtools.ts`. +2. **New field on cards or evidence:** render it in `card()` or `evidence()` with `h()` and `text` (no `innerHTML`). Add the field to `makeDecision` / `makeAction` in `packages/runtime/test/browser/ui/mock-runtime.ts` and set it in `packages/runtime/test/browser/ui/scenario.ts`. +3. **Mount option:** `DevtoolsOptions` with a JSDoc default, read in the `Devtools` constructor; mirror it in `demos/src/dev/runtime-shim/devtools.ts`. +4. **Report wording:** runtime sentences come from `packages/runtime/src/decide/report.ts` -> `interventionLine`, `detectionLine`. Keep `packages/runtime/src/devtools/ui.ts` -> `splitReport` regexes able to strip the `[GenClass]` prefix, the `(diag, p; action p)` tail, `Not acted on (…): …` and the `(×N …)` suffix; keep `packages/runtime/src/devtools/ui.ts` -> `LEAD` / `NOUN` aligned where the same wording is intended. +5. **Activity kinds and filters:** `packages/runtime/src/devtools/ui.ts` -> `KIND_LABEL`, `OP_LABEL`, `eventText`, `groupOf`; `packages/runtime/src/devtools/index.ts` -> `FILTERS`; badge rules in `packages/runtime/src/devtools/css.ts`. +6. **Styling:** edit `packages/runtime/src/devtools/css.ts` only; add tokens to both `LIGHT` and `DARK`; never add selectors for `html`, `body` or `:root`. +7. **New runtime event:** `packages/runtime/src/types.ts` -> `RuntimeEvents` (CORE), then `packages/runtime/src/devtools/index.ts` -> `subscribe` through the local `on()` wrapper; update the unmount test's listener list. +8. **Cards recorded before mount** (`packages/runtime/UI-NEEDS.md` item 3): in `card()`, when the report sentence is missing, fall back to `this.rt.explain(id)?.message` inside `safe()`; then update the "reports emitted before mounting are not replayed" assertion in `devtools.test.ts`, the `.cx` body expectations in `devtools-runtime.test.ts`, and add `message` to the explanations built in `packages/runtime/test/browser/ui/scenario.ts`. +9. **Runtime-side report wording** changes (`packages/runtime/src/decide/report.ts`) also need `report.test.ts`, `atoms.test.ts` (late-revert line) and `review-misc.test.ts` updated. + +**Tests.** `packages/runtime/test/`: `devtools.test.ts` (against `MockRuntime` + `loadScenario`) and `devtools-runtime.test.ts` (real runtime via `runStoreSession`); `dom.test.ts` if you touch the ignore attribute; the `adapters-*.test.ts` files if you touch `mock-runtime.ts`. **[ask first]** `npx playwright test --config test/browser/ui/playwright.config.ts` from `packages/runtime` regenerates the 18 PNGs in `test/browser/ui/screenshots/` (written, never compared); review and commit them only if intended. + +**Parity / retrain / release.** Class E, unless the field comes from a CORE change that alters situations. Bundle size matters (devtools ~68 KB unminified in the local build). + +**Gotchas.** The overlay uses only the public `Runtime` API; it must not import runtime internals. Tests are not type-checked, so `MockRuntime` drifts silently. `npm run test:browser` also runs the UI spec with different viewport settings and overwrites the screenshots: use the UI config. + +**See.** [devtools.md](runtime/devtools.md#how-to-change-it-safely). + +## Recipes: model host and parity + +### 12. Change model loading or backends + +**Goal.** Change how the model is fetched, cached, verified or run: host options, WebGPU/WASM plan order, worker protocol, model errors, onnxruntime-web version, the `genclass-runtime` CLI, or self-hosting. + +**Steps.** +1. **Host option:** `packages/runtime/src/model/host.ts` -> `ModelHostOptions`; if it must reach the worker, also `packages/runtime/src/model/backend.ts` -> `BackendLoadOptions` (structured-cloneable values only) and the `Host` constructor's `loadOptions`; if apps set it through `GenClass.init`, also `packages/runtime/src/types.ts` -> `ModelOptions` and API.md. +2. **Plan order or device semantics:** `packages/runtime/src/model/loader.ts` -> `planOrder` (the ORT build choice follows). Keep `wasm` as the last plan for `"webgpu"`. +3. **Worker protocol message:** `packages/runtime/src/model/protocol.ts`, the switch in `packages/runtime/src/model/worker.ts`, `packages/runtime/src/model/host.ts` -> `InlineTransport` (keep both transports identical) and the host's message handler. Every request gets exactly one `result`. +4. **Model error:** `packages/runtime/src/model/errors.ts` -> `ModelErrorCode`, the class, the `deserializeError` switch (otherwise it crosses the worker boundary as a plain `Error`); re-export from `packages/runtime/src/index.ts` and `packages/runtime/src/model/index.ts`. Special runtime handling: see the `max_tokens_exceeded` handler in the `RuntimeImpl` constructor. +5. **New graph input or head:** `packages/runtime/src/model/engine.ts` -> `FEEDS`, `OUTPUT_KIND`; `packages/runtime/src/model/packer.ts` -> `planInputs`, `unpackLogits`; `packages/runtime/src/model/serialize.ts` -> `BlockKind`, `questionBlock`; `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer`; the `Question` / `Answer` types in `packages/runtime/src/types.ts` (the CORE/MODEL seam, mirrored by `sim/src/types.ts`). This is also a training change (recipe 13). +6. **onnxruntime-web upgrade:** `packages/runtime/package.json` (`^1.30.0`), `packages/runtime/src/model/backend.ts` -> `ORT_FALLBACK_VERSION`, check `ORT_WASM_FILES` names exist in the new `dist/`, keep the externals, update the browser-test regex expecting `onnxruntime-web@1.30.x` and the pinned `onnxruntime-node` devDependency. +7. **CLI:** `packages/runtime/bin/genclass-runtime.mjs` (`fetch-model`, `info`); keep its `parseCard` in sync with `packages/runtime/src/model/loader.ts` -> `parseCard`. There are no automated CLI tests. +8. **Default model URL:** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` (recipe 20). Shipping a different architecture (R17 vs R32, a new export) needs no code change when the export follows the card format and `meta.json` declares `inputs`, `outputs`, `markers`, `cls_id`, `sep_id`, `max_len`, `max_total`; device-based model selection (OPEN_TASKS item 5) is not implemented and would need card support plus a `planOrder` change. +9. **Self-hosting (app integration):** `npx genclass-runtime fetch-model public/genclass-model --from <dir URL with model.json>` **[ask first]** (download); copy both `ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` from `node_modules/onnxruntime-web/dist/`; `GenClass.init({ model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`; serve COOP/COEP for WASM threads. + +**Tests.** Local, no model files needed: `packages/runtime/test/model/`: `host.test.ts` (fake worker: queue, timeouts, crash, WASM retry, inline fallback, errors across the boundary), `loader.test.ts` (card parsing, `planOrder` matrix, cache and sha256), `engine.test.ts` graph-contract test. **[ask first]** `npm run test:browser` (needs a model directory and Playwright Chromium; rebuilds `dist/`). + +**Parity / retrain / release.** Loading and transport changes are class E. Graph inputs and heads require a new export and retraining. + +**Gotchas.** `evaluate()` never waits: before `ready` it rejects at once with `ModelNotReadyError`, and while the host is `loading` or `error` the runtime builds no situations. Keep `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` and the two `import("onnxruntime-web/webgpu")` / `import("onnxruntime-web/wasm")` literals verbatim: bundlers split on them and `packages/runtime/test/browser/build.mjs` fails without them. `packages/runtime/src/model/worker.ts` must stay inert in ORT's own worker threads (`em-pthread`, `ort-wasm-proxy-worker`). Downloads use the native fetch (`NATIVE_FETCH` or the worker realm), never the instrumented one. One inference at a time; a hung forward pass blocks the host (no watchdog). The WASM retry happens once per host lifetime. + +**See.** [model-host.md](runtime/model-host.md#how-to-change-it-safely). + +### 13. Change the packer, tokenizer, serializer or calibration + +**Goal.** Change how a situation becomes token ids or how logits become calibrated answers. These TypeScript files are byte-exact ports of Python in `jev_local/`. + +**Steps.** +1. Get the user's go-ahead (class C or D; class C requires retraining when the Python side changes). +2. Change both sides in the same change: `packages/runtime/src/model/{serialize,pyutil,tokenizer,packer}.ts` with `jev_local/serialize.py` and `jev_local/engine/encoder/tokenize_pack.py`; `packages/runtime/src/model/calibrate.ts` with `jev_local/engine/encoder/calibrate.py` and `jev_local/confidence.py`. +3. Keep v1 calibration files loadable; keep the documented Jev answer rows within ±0.01 (`jev_local/confidence.py`; tested by `tests/test_confidence.py`). +4. Regenerate the fixtures (recipe 14) and, for a token-id change, re-export a model so the export's own fixtures and `parity.json` reflect the new layout. +5. Recalibration only (no code change): `$PY training/eval_runtime.py --ckpt … --data … --fit-split dev --write-calibration cal.json`, then `$PY training/export_runtime.py … --calibration cal.json` **[ask first]** (recipe 18). + +**Tests.** Local (fixtures committed): `packages/runtime/test/model/`: `serialize.test.ts`, `calibrate.test.ts` (7 of 8 run without model files), `packer.test.ts` and `engine.test.ts` parity need a model directory **[ask first]**. Python: `tests/test_encoder_pack.py`, `test_encoder_model.py`, `test_encoder_engine.py`, `test_serialize_w8.py`, `test_confidence.py`, `test_train_v2_engine.py` **[ask first]** (Python environment with torch). + +**Parity / retrain / release.** Token-id changes invalidate trained weights: retrain and re-export (recipe 18), new freeze. Calibration changes alter intervention rates: re-run `training/eval_runtime.py` and compare FIR/precision before shipping. + +**Gotchas.** JavaScript cannot print `25.0`; Python-generated rows must write integral floats as ints. Nothing about the vocabulary is hardcoded: marker, CLS and SEP ids come from `meta.json` / `tokenizer.json`; keep it that way. The runtime bounds state + longest branch (`meta.max_len`), the trainer bounds the whole question block: length semantics differ. The extension's JS copies (`extension/src/model/`) are the ancestors; the runtime TS copy is the maintained one. + +**See.** [model-host.md](runtime/model-host.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#invariants-and-gotchas), [genclass-model-lineage.md](genclass-model-lineage.md#how-to-change-it-safely). + +### 14. Regenerate model parity fixtures + +**Goal.** Refresh the Python-generated fixtures that pin the TypeScript model code to the Python reference. + +**Steps.** +1. **`py_fixtures.json`** (serialize, pruned tokenizer, calibration and confidence cases) **[ask first]**: needs the jev venv (`tokenizers`, `numpy`, `pydantic`) and the v0.1 tokenizer: + `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_py_fixtures.py --tokenizer <model dir>/tokenizer.json --out packages/runtime/test/fixtures/model/py_fixtures.json`. It also reads `<model dir>/calibration.json` when present. The script imports `jev_local` from the repo root (`ROOT = parents[5]`), so do not move it. +2. **`pack_fixtures.json` / `torch_fixtures.json`** are outputs of either v1 exporter, `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (both export the extension's v1 model, import torch and say "RUN ON THE AZURE VM ONLY"; their fixture-writing code in `main` is identical and does not depend on the int8 vs q8 ONNX export; which one produced the committed files is not recorded) **[ask first]**, copied from `extension/test/fixtures/` and re-serialised compactly (no whitespace). Never hand-edit them. Regenerate `requests50.json` from the same request set. +3. **An export's own fixtures:** `training/export_runtime.py` writes `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` and `parity.json` into the model directory; `packages/runtime/test/model/helpers.ts` uses them automatically when all three exist (`FIXTURES_FROM_MODEL`). +4. **WebGPU embedding variants** (outside the repo, used via `GENCLASS_WEBGPU_VARIANTS`) **[ask first]**: `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_webgpu_variants.py --src <runtime-card model dir with a q8 variant> --out <dir>` (needs `onnx`, `numpy`); writes `f32emb/` and `i8emb/`. + +**Tests.** `packages/runtime/test/model/` `serialize.test.ts`, `calibrate.test.ts`, `packer.test.ts`, `engine.test.ts` with `GENCLASS_MODEL_DIR` **[ask first]**. + +**Parity / retrain / release.** Fixtures only document parity; regenerating them never fixes a parity break. + +**Gotchas.** The committed fixture JSON files are single-line (`wc -l` prints 0); compare parsed JSON, not hashes. The browser specs always read the v0.1 fixtures (`test/browser/model-helpers.ts`), so their parity assertions only hold for the v0.1 model. `pythonOnlyFloatRequests` needs Node ≥ 21. + +**See.** [build-test-release.md](runtime/build-test-release.md#regenerate-model-fixtures). + +## Recipes: sim + +All sim runs are **[ask first]**. Before any sim change, read the matching test in `sim/test/`. Check-out sequence after the change: `npm run build` (runtime) then, in `sim/`, `npx tsup`, `SIM_RUNTIME=real npx vitest run`, `node dist/smoke.js --seeds 40` (check `internal errors` and correlation `*:none` counts), a small `gen.js` run and `python3 scripts/analyze.py <out>`. + +### 15. Add a sim feature module + +**Goal.** Add a feature combinator (a new kind of app behaviour with guards or injected defects), a domain, or a knob on an existing feature. + +**Steps.** +1. New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef` (`sim/src/app/feature.ts`); register it in `sim/src/app/features/index.ts` -> `FEATURES` and `FEATURE_WEIGHTS`. +2. Server routes via `srv.route(method, naming.route(...), handler, { feature, kind, idempotent, resource })`. Client state via `env.store(name, s.id, init, { weights, resync })`. Requests only via `Kit.op` + `Kit.call`; writes only via `Kit.write` with `role`, `intent`, `key`, `op` (`sim/src/app/kit.ts`). +3. Ground truth: set `dupOf` for accidental repeats, `anomaly: "partial"` on writes that skip derived fields, `classify` where `ContentBook` decides stale/conflict/duplicate; declare `relations()` for derived fields; surface failures with `kit.shownError()` or `kit.spawn(fn, "uncaught", …)`. +4. New data roles go into `sim/src/oracle/diagnose.ts` -> `DATA_ROLES`. Consider a held-out pattern in `sim/src/world/scenario.ts` -> `TEST_PATTERNS`. +5. Randomness only from the spec rng in `make`, `user.rng` in `session`, and keyed `env.rng.fork(<key>)` at run time. For a knob on an existing feature, append the draw at the end of `make()` (inserting one shifts every later knob). +6. Domain: append `D(...)` with two entities in `sim/src/app/vocab.ts` -> `DOMAINS`; optionally hold it out in `TEST_DOMAINS`. + +**Tests.** `sim/test/oracle.test.ts` cases via `mini(kind, patch, opts)` from `sim/test/helpers.ts` (expected diagnosis, cheapest action); `rows.test.ts`, `determinism.test.ts` with `SIM_RUNTIME=real` **[ask first]**. + +**Parity / retrain / release.** Every seed's world changes (keyed picks depend on array lengths): regenerate all data and `sim/samples/*`; never mix rows from different sim versions under one seed range. + +**Gotchas.** An `anomaly` passed to `Kit.op` is silently dropped (`OpInit` has no such field); the poll feature's `storm` anomaly never reaches the oracle for this reason. Error-message fields must have weight 0. The ideal run has no runtime and skips accidental steps, so `dupOf` / `accidental` must be right. + +**See.** [sim.md](sim.md#how-to-change-it-safely). + +### 16. Change sim oracle, labelling, ask questions or splits + +**Goal.** Change how rows are labelled (cost weights, label parameters, diagnosis rules), add an `ask` question generator, change chaos, budgets or splits. + +**Steps.** +1. **Cost weights:** `sim/src/oracle/cost.ts` -> `W`; update `sim/test/oracle.test.ts` and the README formula; regenerate data. +2. **Label parameters only:** `sim/src/oracle/cost.ts` -> `LABEL` (premiums, tie rule, tau). These can be re-derived offline from `meta.cost_futures` with `actionLabel`, without re-simulating; re-apply option drops recorded in `meta.transform` (`drop:<action>`). +3. **Diagnosis rules:** `sim/src/oracle/diagnose.ts` -> `diagnose`, `diagnoseFailure`, or a feature's `classify`. Diagnosis also changes exploration, point sampling and `fake_diagnosis`, so action rows change too. +4. **Ask questions:** a generator in `sim/src/ask/questions.ts` -> `GENS` returning `{ qid, question, label, kind }`; check the evidence appears in the serialised state and skip borderline timings. +5. **Chaos and network:** `sim/src/world/scenario.ts` -> `makeNet` (parameters), `sim/src/net/network.ts` -> `Network` (mechanics). Keep every draw keyed and ideal-mode draw counts stable; keep `NetEntry.cause` / `slowCause` accurate (diagnoses read them). +6. **Budgets:** `buildScenario` budget weights; coordinate with per-budget eval in `training/eval_runtime.py` and the runtime's auto budgets. +7. **Splits:** `sim/src/world/scenario.ts` -> `TEST_DOMAINS`, `TEST_PATTERNS`, `familyHeldOut`, `splitOf` (and their salts). Moves whole trajectories between splits; old datasets become incomparable. +8. **Runtime contract** (option names, thresholds, hooks): `sim/src/run/rt.ts` -> `createOptions`, `RuntimeLike`, and `sim/src/types.ts`. + +**Tests.** `sim/test/oracle.test.ts` (expected diagnoses and cheapest actions; 2 cases run only with `SIM_RUNTIME=real`), `rows.test.ts` (labels reference offered options, dists sum to 1, split counts over 400 seeds), `determinism.test.ts` **[ask first]**. + +**Parity / retrain / release.** Labels and targets change: regenerate data and retrain. Gate thresholds in `createOptions` must stay 0.5 with `requireDiagnosis: false`. + +**Gotchas.** `x-request-id` is the sim's correlation header; it must stay in the runtime's volatile header list and never appear in a state (`rows.test.ts` asserts it). Correlation is synchronous: the runtime's `opCreated` / `mutationProposed` hooks must fire inside the sim's calls. + +**See.** [sim.md](sim.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md). + +### 17. Generate a data set + +**Goal.** Produce CONTRACT-D rows (`{ id, split, family, state, questions, labels, meta }`) from the sim. **[ask first]** for every step: generation is CPU-heavy and the original team ran it only on the VM. + +**Steps.** +1. Build the runtime first (`npm run build` at the repo root; `sim` resolves `@genclass/runtime` through `packages/runtime/dist/`), then the sim: `cd sim && npx tsup`. +2. Samples: `node dist/gen.js --sample --workers 8` writes `sim/samples/sample.jsonl`, `EXAMPLES.md` and `sample-stats.json`. +3. A custom run: `node dist/gen.js --rows <N> --out <dir> --seed <S> --workers <W>` (other flags: `--max-points`, `--test-keep`, `--explore`, `--no-ask`, `--parts`, `--chunk`, `--merge-only`; `--allow-fake` only for tests). Output: `<dir>/{train,dev,test}.jsonl` + `stats.json`. +4. Final datasets: `bash sim/scripts/final.sh a` (600k rows, seeds from 10,000,000, `sim/out/final-a`), `final.sh b` (1.4M rows, seeds from 50,000,000, resumable parts of 100 seeds), `final.sh merge-b`. Splitting across machines needs disjoint seed ranges. +5. Summarise: `python3 sim/scripts/analyze.py <dir>` (prefers merged files over `parts/`). + +**Tests.** Check `stats.json`: drops (phase A only had `diagnosis-not-in-vocab`), 0 errors, `subject_correlated` 100%, passive-best shares per trigger. + +**Parity / retrain / release.** Data generated from a runtime whose situation code differs from the model's training data is not comparable; record the runtime commit with the data. + +**Gotchas.** `gen.js` uses the real runtime unless `--allow-fake`. A stale `dist/` from an older build silently produces old text: rebuild first. `sim`'s `build:runtime-core` writes only `dist/index.js` (+ chunks; no `.d.ts`, adapters, devtools or worker) and does not clean, so on an empty `dist/` it leaves the demos resolving files that do not exist; prefer the full build. + +**See.** [sim.md](sim.md#how-to-change-it-safely), [training.md](training.md). + +## Recipes: training + +### 18. Train, evaluate and export a model + +**Goal.** Produce a model directory the runtime can load (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`, parity fixtures). Everything here runs on Azure VMs and costs money: **[ask first]** for every step. + +**Steps.** +1. Read `training/LOG.md`, `training/EVAL.md`, `training/NEEDS.md`. Note the script layout assumption: `training/*.sh` resolve `JEV="$HERE/../.."` and expect `jev_local/`, `scripts/` and `pyproject.toml` there, while in this monorepo they are one level up. +2. **Curriculum** (if needed; `$PY` is `~/jev/.venv/bin/python` as set by `training/node.sh`, see [training.md](training.md#configuration-and-constants)): `$PY training/curriculum/generate.py --out <dir> --n <N> --seed <new seed> --workers <W> --p-runtime 0.8`; shard train into a stream bucket (`split -n l/64 …` into `<stream root>/<bucket>/`). Use a new seed and bucket name; check `stats.json` (`bad` and `errors` 0, sane `passive_best_fraction`). +3. **Import SIM data:** `training/import_final.sh SIM_OUT_DIR NAME`. +4. **Mixture and launch:** copy a `training/configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly) and `training/launch_final1.sh` with a new run name, `--stream-cache`, `--out`, `--seed`. Rank 0 must be the node holding `--init-from`. Check `mixture_plan.json`: missing buckets are dropped silently. +5. **Evaluate and calibrate:** `$PY training/eval_runtime.py --ckpt models/M --data <set> --split test --fit-split dev --records-dir out/records --out out/eval/M-<set>.json --write-calibration out/cal/M.json`; SIM eval with `bash training/eval_sim.sh <NAME> M`; tables with `$PY training/report.py M=<json> --mode=kind`. Delete `out/records/M__*` first if `models/M` was retrained. +6. **Export:** `$PY training/export_runtime.py --ckpt models/M --out out/export-M --name genclass-runtime-<size> --version X.Y.Z --calibration <cal.json> --data-rows <jsonl list>`. Without `--calibration` the export ships all-1.0 temperatures. `final_post.sh MODEL NAME VERSION` automates eval, export and serving on a rank-0 node. +7. **Validate:** `node validate.mjs <export dir> q8 120`, run in a directory where `training/ortweb/package.json` is installed (onnxruntime-node and onnxruntime-web WASM vs the PyTorch fixtures); check `parity.json` (q8 argmax agreement, `embedding_q8.fp16_free: true`, q8 size ≤ 25 MB per CONTRACT §10). +8. **Runtime parity:** `cd packages/runtime && GENCLASS_MODEL_DIR=<export dir> npx vitest run test/model` (uses the export's own fixtures), then the browser specs (their parity assertions compare against the committed v0.1 fixtures, so they only hold for the v0.1 model; load, fallback and latency checks still apply to a new export). +9. **New curriculum scenario case:** add it to the builder's `rng.choices` list in `training/curriculum/scenarios.py`, `scen_ops.py` or `scen_state.py`; build the `Trace`, facts via `fmt.pick` templates (≥ 4 phrasings so one is held out), labels leaning passive when ambiguous, primitives (`training/curriculum/prims.py`) and a `spec` that `rt.py` can render (or `no_runtime: True`). Keep the passive-best share within 0.45–0.75 (`test_curriculum.py` asserts it). +10. Variants: change `max_len` with `--max-len N` at training (the export copies it into `meta.json`); change the vocabulary with `training/prune_vocab.py` (prune both bases, rerun `test_prune_vocab.py`, retrain; marker ids move). + +**Tests.** `training/tests/test_curriculum.py` (with and without `GC_P_RUNTIME=1`), `test_export_runtime.py` after touching graph surgery, `test_prune_vocab.py` after vocabulary work. + +**Parity / retrain / release.** The trained model must have been trained on text from the runtime it will ship with (`situation-v1` today). Shipping is recipe 20. + +**Gotchas.** `training/export_runtime.py` parity `gate08`/`gate09` are a single-max proxy, not the runtime's summed-mass gate. `training/eval_runtime.py --records-dir` reuses cached logits by name even after retraining. q8 must be fp16-free so `webgpu+q8` runs without `shader-f16`. Final round 1 has no results in the repo. + +**See.** [training.md](training.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes). + +## Recipes: releases + +### 19. Publish @genclass/runtime + +**Goal.** Release a new version of the library to npm. There is no publish script and no CI; the steps are reconstructed. Publishing is irreversible and public: the user approves it and runs `npm publish` from their own logged-in machine. Agents never run `npm login` or handle npm tokens. + +**Steps.** +1. Preconditions: decide with the user whether this release can act. With `DEFAULT_MODEL_BASE_URL` pointing at the unpublished `@genclass/runtime-model@0.1.0`, a default `GenClass.init()` observes only; OPEN_TASKS plans `@genclass/runtime-model` first, then `@genclass/runtime@0.1.0` without the alpha tag. +2. Checks (local): `npm install`, `cd packages/runtime && npx tsc -p tsconfig.json --noEmit`, `npx tsup`, the full unit suite with `NODE_OPTIONS=--expose-gc`, `npm pack --dry-run` (expect `dist`, `bin`, `README.md`, `LICENSE`, `package.json`). **[ask first]**: model tests with `GENCLASS_MODEL_DIR`, `npm run test:browser`, `bash test/smoke/smoke.sh` from `packages/runtime` (registry access; leaves a `.tgz` in `packages/runtime/` and a temp app). +3. Bump `version` in `packages/runtime/package.json` and the version strings in the READMEs and `OPEN_TASKS.md`. +4. Build immediately before publishing (`npm publish` packs whatever `dist/` holds; there is no `prepublishOnly`). +5. The user, from `packages/runtime`: `npm publish --access public` (scoped packages are restricted otherwise; add `--tag <prerelease>` for prereleases; the flags used for `0.1.0-alpha.0` are not recorded). Check `npm view @genclass/runtime dist-tags` before and after. +6. With the user's approval: `git tag -a vX.Y.Z -m "@genclass/runtime X.Y.Z (npm)"` and push it; move the item to "Done" in `OPEN_TASKS.md`. + +**Tests.** As in step 2. + +**Parity / retrain / release.** The published runtime's situation code must match the model it loads (`situation-v1` for the current training round). + +**Gotchas.** No root lockfile is committed, so dependency versions float within caret ranges. `packages/runtime/bin/genclass-runtime.mjs` is committed as 644; npm sets the executable bit on install. A failed tsup build leaves a half-empty `dist/` (`clean: true`). + +**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely). + +### 20. Publish @genclass/runtime-model and point the runtime at it + +**Goal.** Make the default model URL serve a trained model so that `GenClass.init()` can act (OPEN_TASKS item 8). **[ask first]** throughout; publishing is the user's action. + +**Steps.** +1. Choose the model with the user (R17 for WASM vs R32 for WebGPU; OPEN_TASKS item 5) and get its export directory (recipe 18). +2. Put the directory under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@<version>/files/`. Check it: `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files` (card rules, hashes, `needs: shader-f16` on fp16). +3. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, version, `files` including `files/`). It becomes a workspace automatically (`packages/*`). Confirm with `npm pack --dry-run` in that directory that `files/` is included. +4. The user publishes it (`npm publish --access public`) and attaches the same files to a GitHub release tagged `runtime-model-v<version>` (the CLI's `DEFAULT_FROM` is `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`). +5. If the version is not 0.1.0, update `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`, then release the runtime (recipe 19). +6. Update `packages/runtime-model/MODEL_CARD.md` (it lacks `transient` and describes the old gate), `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, `packages/runtime/README.md` "Status", `OPEN_TASKS.md`. + +**Tests.** No automated test covers the default URL end to end. **[ask first]** In a browser: `GenClass.init()` reaches `status.state === "ready"`, the console no longer prints "Model unavailable (...); observing only.", and `npm run test:browser` passes against the published directory. + +**Parity / retrain / release.** The model must match the runtime's situation format. + +**Gotchas.** Cache Storage (`genclass-runtime-v1`) never evicts old versions. `model.json` is revalidated on every load. The demos' `?model=cdn` falls back to the runtime default (`DEFAULT_MODEL_BASE_URL`, which ends in `files/`). Only the `demos/README.md` example `GENCLASS_MODEL_URL=…@0.1.0/` lacks the `files/` suffix. + +**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely), [model-host.md](runtime/model-host.md). + +### 21. Add a CI workflow + +**Goal.** Add the CI that OPEN_TASKS item 8 plans (none exists: no `.github/`). + +**Steps.** +1. Add `.github/workflows/<name>.yml` running on Node 22 (≥ 22.12) or 24: vitest@5.0.3's `engines` excludes Node 20, 21, 23 and 25. +2. Steps: `npm install` (or have the user decide to commit a root `package-lock.json` and use `npm ci`), `npm run build`, `npm run typecheck -w @genclass/runtime`, `NODE_OPTIONS=--expose-gc npm test`. Expect 286 passed / 14 skipped without a model directory. +3. Keep root `npm run typecheck` out unless the demos typecheck works: it needs the full runtime build and the missing `demos/src/server/data/cities.ts`. It fails at this commit: `demos/tsconfig.json` includes `src/`, and three files import the missing `cities.ts` (inferred from code; not run). +4. Browser specs would need `npx playwright install --with-deps chromium` and a model directory; the smoke test needs registry access. Leave them out of a first workflow. +5. Pushing the workflow is the user's call. + +**Tests.** Run the same commands locally first. + +**Gotchas.** `review-perf.test.ts` asserts wall-clock bounds and can flake on shared runners. The gc test passes silently without `--expose-gc`. + +**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely). + +## Recipes: demos + +### 22. Add or change a demo and re-run trials + +**Goal.** Add a demo app or change a scenario, oracle, chaos knob or server route, and measure with trials. + +**Steps.** +1. **Prerequisite for any demos build:** recreate `demos/src/server/data/cities.ts` (missing from git; ignored by the root `.gitignore` pattern `data/`). It must export `searchCities(q: string)` returning `{ total, items: { id, name, country, population }[] }` and `TYPED_TARGETS: string[]`. Add a negation (`!demos/src/server/data/`) to the root `.gitignore` or rename the directory. +2. **New demo:** `demos/src/shared/protocol.ts` -> `DemoId`; a world `demos/src/server/worlds/<id>.ts` registered in `demos/src/server/sw.ts` -> `DEFS`; `demos/src/demos/<id>/{main,app,scenario,oracle}.ts` + `app.css`; `demos/<id>/index.html` (copy one; `gc-root` `../`); `demos/vite.config.ts` -> `PAGES`; `demos/e2e/eval.ts` -> `ALL_DEMOS`, `TITLES`, `SHOT_PRESET`; `demos/src/shared/demos.ts` -> `DEMOS`; `demos/src/site/art.ts` -> `ART`. `tsc` flags missing `DEFS`, `ART`, `TITLES`, `SHOT_PRESET` entries but not `DEMOS`, `PAGES`, `ALL_DEMOS`. +3. **Scenario or oracle threshold:** edit `demos/src/demos/<id>/scenario.ts` / `oracle.ts`; keep the scenario RNG label `"<demo>:<kind>:<seed>"`; update the `scored` copy in `demos/src/shared/demos.ts` and the README oracle table. +4. **Chaos knob:** `demos/src/shared/chaos.ts` -> `RouteChaos`, `CALM`, `describeChaos`; apply it in `demos/src/server/core.ts` -> `World.handle` (draw randomness from the request's rng up front); a slider in `demos/src/site/chaos-panel.ts` -> `SLIDERS`. +5. **Server route or world action:** a `Route` with a stable `key`; `w.rng` in handlers, `w.scriptRng` / `w.script` for scripted activity; oracle-relevant data in `snapshot`. +6. **GenClass init:** only `demos/src/shared/genclass.ts` -> `startGenClass`; app code never branches on mode. New runtime API: public API only, mirrored in `demos/src/dev/runtime-shim/*`. +7. **Trials** **[ask first]**: `GENCLASS_MODEL_FROM=<release dir url> bash demos/scripts/vm-eval.sh --tag <name>` (or `GENCLASS_MODEL_DIR` / `GENCLASS_MODEL_URL`), or, from `demos/`, `npm run build` then `npm run eval:fast -- --demos <id>` (`e2e/eval.ts` options include `--n`, `--clean`, `--modes`, `--workers`, `--model`, `--tag`, `--trace`, `--no-shots`). Tagged runs write `results-<tag>.*`; untagged runs replace the shipped `results.*` and the landing page numbers. +8. **Results schema or aggregation:** `demos/src/shared/aggregate.ts` -> `ModeSummary` feeds `demos/src/site/trials-panel.ts`, `demos/e2e/eval.ts` (Markdown and JSON reports) and `demos/src/site/landing.ts` (reads `results-summary.json`); keep the fields or update all three. +9. **World-clock offset (optional fix):** trial worlds start before Guard/Heal pages wait for the model, so scripted activity happens earlier relative to `t0` than in Off. Moving `link.hello(...)` in `demos/src/site/demo-page.ts` -> `bootTrial` after the `gc.ready` wait, or starting scripts from a world action sent at `demos/src/shared/harness.ts` -> `TrialHarness.begin`, removes it; either changes every seed's results. +10. **Hold-induced regressions** **[ask first]**: from `demos/`, `node --experimental-strip-types e2e/eval.ts --trace --demos board --modes off,guard,heal --tag <t>` plus an Off-only A/A run, then `node --experimental-strip-types e2e/trace-report.ts e2e/.out/traces-<t>.json [e2e/.out/traces-<offB>.json]`. + +**Tests.** There are no unit tests in `demos/`; the oracles and the eval are the tests. Typecheck: `npm run typecheck -w @genclass/demos` (needs `packages/runtime/dist/*.d.ts`) or `npm run typecheck:shim -w @genclass/demos` (the shim lacks some `Runtime` methods, so it likely fails; unverified). + +**Parity / retrain / release.** None for the model. Results are comparable only within the same scenario code, runtime build and model; re-run all modes after any scenario change. + +**Gotchas.** Test-side code (oracles, driver, harness, site panels) must use the native timers from `demos/src/shared/native.ts` and control the mock server only through `postMessage`, never `fetch`, or GenClass observes test traffic. Request bodies and event keys must not contain timestamps or random ids (they would re-roll the network per mode). Oracles read `data-testid` / `data-*` attributes: renaming one silently changes scores. Do not fix the apps' latent bugs. The activity panel classifies decisions by runtime reason strings. + +**See.** [demos.md](demos.md#how-to-change-it-safely). + +## Recipes: tests, debugging, docs + +### 23. Run each test suite + +| suite | where / command | prerequisites | expected | policy | +|---|---|---|---|---| +| runtime typecheck | `cd packages/runtime && npx tsc -p tsconfig.json --noEmit` | `npm install` | clean | local | +| runtime build | `cd packages/runtime && npx tsup` (or `npm run build` at the root) | install | `dist/` with 6 entries | local | +| runtime unit tests | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (`npm test` is equivalent; the config already excludes `test/browser/**`) | install | 36 passed + 1 skipped files; 286 passed + 14 skipped tests | local | +| one file / one test | `cd packages/runtime && npx vitest run test/atoms.test.ts -t "late discard"` | install | | local | +| model unit tests incl. parity | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> NODE_OPTIONS=--expose-gc npx vitest run test/model` | a model directory from `node packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from <url>` | all 62 MODEL tests run | **[ask first]** (download) | +| browser model specs | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> npm run test:browser` (add `--project chromium` or `swiftshader-webgpu`) | Playwright Chromium for `@playwright/test` 1.63.0, model dir; rebuilds `dist/`; also re-runs the UI spec | specs skip without `model.json` | **[ask first]** | +| devtools UI spec | `cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts` | root `npm install` (fonts from the demos workspace), Chromium | 5 tests; rewrites 18 screenshots | **[ask first]** | +| tarball smoke | `cd packages/runtime && bash test/smoke/smoke.sh` | registry access, Chromium in the Playwright cache | prints `SMOKE OK: <tgz>` | **[ask first]** | +| sim tests | `npm run build`, then `cd sim && SIM_RUNTIME=real npx vitest run` | runtime `dist/` | 17 tests (without `SIM_RUNTIME=real` the fake runtime is used and 2 oracle tests skip) | **[ask first]** | +| sim typecheck | `npm run typecheck -w @genclass/sim` | install | not run when these docs were written | local | +| demos typecheck | `npm run typecheck -w @genclass/demos` | runtime build, `cities.ts` (recipe 22) | not run when these docs were written | local | +| demos trials | recipe 22 step 7 | built site, model, Chromium | `results*.json/md` | **[ask first]** | +| training tests | on a VM: `PYTHONPATH=… python -m pytest -q training/tests/<file>` | jev venv, checkpoints for some tests | | **[ask first]** | +| legacy Python tests | `python -m pytest -q tests/<file>` (markers `model`, `slow`, `macos`) | Python env; 20 `tests/test_data_*.py` fail at collection because `jev_local/data` is missing | | **[ask first]** | +| export validation | `node validate.mjs <export dir> q8 [maxRequests]` in a directory with `training/ortweb/package.json` installed | an export dir | `ortweb_report_q8.json` | **[ask first]** | +| extension | in `extension/` on a VM: `npm ci`, `npm test`, `npm run test:e2e` | release-assets ONNX files | | **[ask first]** | + +Root scripts: `npm run build` and `npm test` run only in `@genclass/runtime`; `npm run typecheck` runs every workspace that has the script. + +**See.** [build-test-release.md](runtime/build-test-release.md#exact-commands), [build-test-release.md](runtime/build-test-release.md#tests). + +### 24. Write a runtime unit test + +**Goal.** Add a test in the house style: virtual time, virtual server, scripted model. + +**Steps.** +1. Put it in `packages/runtime/test/<area>.test.ts` (`test/model/` for model code). Import with `.js` extensions (`./helpers.js`, `../src/...js`). +2. Use `packages/runtime/test/helpers.ts` -> `setup(opts)`: `createRuntime` with `FakeClock` (starts at t = 1000), `FakeServer` (`http://app.test/`, 50 ms latency, unknown route 404), `ScriptedDecider`, `report: "silent"` and only the fetch observer on. Useful options: `triage: "always"` to force consultation, `mode: "heal"` for heal-tier actions, `script: defaultScript({ mutation: { diagnosis: "stale", action: "discard", p } })`, `decider: new ManualDecider()` to control answer timing (`answer(script)` releases the oldest pending request). +3. Drive the app with `rt.user(...)`, `rt.op(...)`, atoms and `fetch`; advance time with `await clock.advance(ms)`, `clock.flush()`, `clock.runAll()`. +4. Assert on `decider.calls[i].state`, `rt.decisions()`, `rt.interventions()`, `rt.history()`, `server.hits` / `server.log`. +5. Name the contract section in the `describe` (e.g. `"(CONTRACT §4)"`). A bug demonstration follows the `review-*.test.ts` style: header comment `// REVIEW: <area>. A failing test demonstrates a bug.`, `describe("review: ...")`, and a test name stating the required behaviour. +6. DOM tests: first line `// @vitest-environment happy-dom`; `createRuntime({ clock: new FakeClock(), global: window, decider, report: "silent", observe: { ...OFF, user: true } })` with `OFF` copied from `dom.test.ts`; `rt.destroy()` in `afterEach`. +7. Model-file tests: `describe.skipIf(!hasModelFile("model.json"))` from `packages/runtime/test/model/helpers.ts`. + +```ts +import { describe, expect, it } from "vitest"; +import { ManualDecider, defaultScript, setup } from "./helpers.js"; + +describe("my change (CONTRACT §4)", () => { + it("holds an async write until the model answers", async () => { + const manual = new ManualDecider(); + const { rt, clock } = setup({ decider: manual, triage: "always" }); + const a = rt.atom("v", 0); + void rt.op("save", () => a.set(5)); + expect(a.get()).toBe(0); // held + manual.answer(defaultScript({ mutation: { diagnosis: "expected", action: "apply" } })); + await clock.flush(); + expect(a.get()).toBe(5); + }); +}); +``` + +**Gotchas.** Tests are not type-checked. Identical `(trigger, state, questions)` within 30 s are answered from the queue cache, so `ScriptedDecider.calls` does not grow: advance the clock past 30 s or vary the situation. Tests that use `GenClass.init` must call `GenClass.destroy()`. Unit tests import fixtures from `test/browser/ui/` (`mock-runtime.ts`, `scenario.ts`, `session.ts`); do not move them. + +**See.** [build-test-release.md](runtime/build-test-release.md#write-a-new-unit-test-house-style). + +### 25. Investigate a false intervention reported by a user + +**Goal.** Find out why GenClass changed an app's behaviour when it should not have, relieve the user, and fix the right layer without adding a rule. + +**Steps.** +1. **Confirm the runtime could act.** Check `GenClass.runtime.status` (`state`, `model`, `variant`) and `GenClass.runtime.mode`. With default options, `@genclass/runtime@0.1.0-alpha.0` cannot act: its model URL is unpublished, the status ends in `error` and the console says "Model unavailable (...); observing only.". An intervention therefore implies a self-hosted `model.baseUrl` or a custom `decider`. Guard mode runs only guard-tier actions: the built-ins `discard`, `defer`, `coalesce`, `delay`, and custom actions declared with `tier: "guard"`. +2. **Collect the evidence.** The console line `[GenClass] <Lead> <noun>: <fact> <changed> (<diagnosis>, p; <action> p)` and its collapsed group; `GenClass.runtime.interventions()` -> `ActionRecord` (`id` `a<n>`, `decisionId`, `action`, `tier`, `changed`, `ok`, `error`, `late`); `GenClass.runtime.explain("a<n>")` -> `Explanation` (`situationText`, `facts`, `timeline`, `answers`, and `decision` with `diagnosisProbabilities`, `probabilities`, `candidate`, `mass`, `tier`, `reason`). The devtools overlay shows the same evidence with a Copy button for the situation text. `GenClass.runtime.history(400)` gives the event log; `debug: true` logs swallowed errors. +3. **Relieve the user.** `ActionRecord.undo?.()` exists only for `discard`, late reverts, `rollback` and custom actions with `onUndo` (undo is unguarded and does not check whether state moved since). At the next page load: `GenClass.init({ policy: { deny: ["<action>"] } })`, or `mode: "observe"`, or `?genclass=observe` / `?genclass=off` / `localStorage.genclass = "off"`. The printed "Deny this action" hint does nothing on a page where `init` already ran. +4. **Classify** (read the evidence against the code): + - **Gate:** did the decision pass `packages/runtime/src/decide/policy.ts` -> `gate` legitimately? `decision.mass` ≥ the threshold of `decision.tier` (0.9 guard / 0.8 heal unless overridden), top diagnosis ≠ `expected` (unless `requireDiagnosis: false`), the mode permits the tier. A wrong pass is a gate bug (test in `policy.test.ts`). + - **Applicability:** should the action have been offered at all? `packages/runtime/src/situation/build.ts` -> `builtinApplicable` (known: `retry` for non-idempotent POSTs, `demos/NEEDS.md` §5). Fixing it is class A (recipe 4). + - **Facts:** is any fact false (wrong order, version count, causal attribution, a redaction leak)? That is a trace or fact bug in `packages/runtime/src/situation/facts.ts`, `packages/runtime/src/trace/context.ts` or an observer; the fix is class A (recipes 1, 2). + - **Effect:** does `changed` describe what really happened; did it act on the right write or request? That is a controller bug (recipe 4 a). `late: true` means a late revert: check `StoreHub.revertable`. + - **Model:** the gate, offer, facts and effect are all correct and the model was confidently wrong. That is a precision problem for training: record the situation text and the expected passive outcome (e.g. a `training/NEEDS.md` or SIM scenario request). Do **not** add a runtime rule that maps this pattern to passive (CONTRACT §0 rule 1). + - **No `ActionRecord` at all**, but the app misbehaved: look at holds. Decisions with `reason` "the decision arrived after the hold budget expired", held writes reordered behind a newer user write (`demos/NEEDS.md` §1), added latency (§2). Mitigations: `StoreOptions.hold: false` for that store, `policy.holdBudgetMs`, observe mode. +5. **Reproduce headless.** Write a unit test (recipe 24) that recreates the trigger and forces the same model answer with `defaultScript`, then asserts the corrected gate, offer, fact or effect. The real model's probabilities can only be reproduced with model files **[ask first]**. +6. **Record.** Add the regression test; note the issue in `packages/runtime/STATUS.md` "Open issues" (or the owning NEEDS file); for precision cases, give TRAIN the situation text. + +**Gotchas.** Console reports are deduplicated in 60 s windows ("×N more"). Reason strings are parsed by devtools and the demos: do not reword them while debugging. `rt.situation(trigger)` returns the last situation built for that trigger, not a fresh rebuild. + +**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md), [learn-situation-triage.md](runtime/learn-situation-triage.md), [state-and-adapters.md](runtime/state-and-adapters.md#drift-and-open-issues), [devtools.md](runtime/devtools.md). + +### 26. Update these docs after a code change + +**Goal.** Keep `docs/agents/`, `AGENTS.md`, `CLAUDE.md` and the human docs true to the code after you change it. + +**Steps.** +1. Find every doc that cites what you changed: `grep -rn "<symbol or path>" docs/agents AGENTS.md CLAUDE.md docs/runtime packages/runtime/*.md packages/runtime/src/model/README.md sim/README.md training/README.md demos/README.md`. +2. Update the owning agent doc (sections Files, Concepts, Configuration and constants, Invariants and gotchas, How to change it safely, Tests, Drift and open issues): + +| code | agent doc | +|---|---| +| `packages/runtime/src/{index,runtime,types,errors,clock,util}.ts` (wiring, options, lifecycle, plugins) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | +| `packages/runtime/src/observe/*`, `trace/*` | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | +| `packages/runtime/src/state/*`, `adapters/*` | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | +| `packages/runtime/src/learn/*`, `situation/*` | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) and [model-io-contract.md](model-io-contract.md) | +| `packages/runtime/src/decide/*`, actions in `runtime.ts` | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/` | [runtime/model-host.md](runtime/model-host.md) and [model-io-contract.md](model-io-contract.md) | +| `packages/runtime/src/devtools/*` | [runtime/devtools.md](runtime/devtools.md) | +| package manifests, tsup, vitest, test infrastructure, `scripts/vm.sh`, publishing | [runtime/build-test-release.md](runtime/build-test-release.md) | +| `sim/` | [sim.md](sim.md) | +| `training/` | [training.md](training.md) | +| `demos/` | [demos.md](demos.md) | +| `jev_local/` | [genclass-model-lineage.md](genclass-model-lineage.md) | +| `extension/`, `bench/`, `scripts/` | [extension-and-benchmarks.md](extension-and-benchmarks.md) | +| status, ownership, open work | [status-and-known-issues.md](status-and-known-issues.md) | +| new terms, moved paths, new recipes | [glossary.md](glossary.md), [repo-map.md](repo-map.md), this file | + +3. Keep the conventions: pointers `path -> symbol`, no line numbers, "code wins". Update the "Verified against commit … (date)" line of each doc you re-verified. Remove drift rows you fixed; add new drift you found, with evidence. +4. Check every relative link you touched resolves from the linking file (`ls` the target) and that anchors still match headings. +5. Human docs: `packages/runtime/src/types.ts` JSDoc (safe to fix: no model input), `docs/runtime/API.md`, `packages/runtime/README.md`; `packages/runtime/STATUS.md` ("Updated:" line, "State" counts and commands, a batch section, "Deviations from the contract (and why)", "Open issues", example situations); `OPEN_TASKS.md` (Next -> In progress -> Done, with evidence). Fixing `BUILTIN_ACTIONS` descriptions is not a doc fix: it is model input. +6. Cross-workstream requests: add a numbered item to your own NEEDS file (addressee, status OPEN or ASK, evidence as file -> symbol, suggested fix, a regression-test sketch; `demos/NEEDS.md` §1 is the model). The requester flips it to DONE after verifying. Contract changes go to CONTRACT §13 (lead) or STATUS "Deviations" (owner); never diverge silently. +7. Do not edit legacy jev-era docs (`docs/*.md` outside `docs/runtime/` and `docs/agents/`). + +**See.** [status-and-known-issues.md](status-and-known-issues.md#how-to-change-it-safely), [README.md](README.md). + +### 27. Touch legacy code: jev_local, extension, benchmarks, ops scripts + +**Goal.** Make a change in the code the runtime grew out of. CONTRACT §1 says existing GenClass content stays as is: do this only when the user asks. + +**Steps.** +1. **`jev_local/` serialization, packing or calibration:** recipe 13 (TS and Python together, fixtures, retrain). +2. **Training losses or the stream reader** (`jev_local/train/`): add a `LossConfig` field defaulting to off so the v1 path stays bit-identical (`tests/test_train_v2_losses.py`); keep stream determinism and bump `INDEX_VERSION` if the row index layout changes; keep the trainer flags the `training/` launchers and `scripts/launch_run.sh` pass backward compatible. +3. **Extension harness logic** (`extension/src/core`): change `jev_local/harness/*.py` first (the Python is the reference), regenerate `extension/test/fixtures/*_py.json` with `extension/scripts/make_py_fixtures.py` (fix its `ROOT`/`OUT` paths first), run `npm test` in `extension/` on a VM **[ask first]**. `scripts/vm.sh` excludes `/extension/`. +4. **Engine/packer/tokenizer bug in the extension:** fix the runtime TS copy first (`packages/runtime/src/model/`); port to the extension only if it is still released. +5. **Extension features and models** (browser-only intents, shipping a new model variant with card sha256 and parity fixtures): follow [extension-and-benchmarks.md](extension-and-benchmarks.md#how-to-change-it-safely) recipes 2 and 3; builds and e2e run on a VM **[ask first]**. +6. **Benchmarks:** benchmax specs need pinned upstream revisions and pure-Python tests; changing `bench/public/jev_published.json` or targets changes frozen hashes (re-freeze before any test read). Never run paid Jev/OpenRouter calls (`scripts/jevbench.py run-jev`) without the user's explicit approval and a funded key; `run-ours`, `score` and `report` score a checkpoint without paid calls. +7. **Ops scripts:** keep `scripts/vm.sh` rsync exclusions and `--delete` semantics; keep `scripts/launch_run.sh` positional arguments (`training/launch_s2.sh` and `launch_final1.sh` depend on them). Anything that calls `az vm create/start` needs the user's go-ahead. + +**Tests.** Python tests with markers `model`, `slow`, `macos` (`tests/conftest.py` skips `macos` off macOS) **[ask first]**. + +**See.** [genclass-model-lineage.md](genclass-model-lineage.md#how-to-change-it-safely), [extension-and-benchmarks.md](extension-and-benchmarks.md#how-to-change-it-safely). + +## Related docs + +- [README.md](README.md) (index of agent docs), [overview.md](overview.md), [repo-map.md](repo-map.md), [glossary.md](glossary.md), [../../AGENTS.md](../../AGENTS.md) +- [status-and-known-issues.md](status-and-known-issues.md), [model-io-contract.md](model-io-contract.md) +- Runtime: [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), [observe-and-trace.md](runtime/observe-and-trace.md), [state-and-adapters.md](runtime/state-and-adapters.md), [learn-situation-triage.md](runtime/learn-situation-triage.md), [decide-policy-actions.md](runtime/decide-policy-actions.md), [model-host.md](runtime/model-host.md), [devtools.md](runtime/devtools.md), [build-test-release.md](runtime/build-test-release.md) +- Other subsystems: [sim.md](sim.md), [training.md](training.md), [demos.md](demos.md), [genclass-model-lineage.md](genclass-model-lineage.md), [extension-and-benchmarks.md](extension-and-benchmarks.md) +- Human sources: [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md), [`docs/runtime/API.md`](../runtime/API.md), [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md), [`OPEN_TASKS.md`](../../OPEN_TASKS.md) diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md new file mode 100644 index 00000000..4b934dea --- /dev/null +++ b/docs/agents/repo-map.md @@ -0,0 +1,856 @@ +# Repository map (GenClass-lib) + +> **Scope:** every tracked path (`git ls-files`: 749 files at 654d822), plus the generated and ignored paths that show up in a working copy. +> **Read this when:** you need to find where a file, symbol, constant, CLI command, env var or config key lives; decide whether a directory matters for `@genclass/runtime`; or want to know which paths are generated, ignored or too large to read in full. +> **Source of truth:** `git ls-files` and the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +Conventions: code pointers are `path/from/repo/root` -> `symbol`. Relevance to the runtime library: + +- **core**: ships in `@genclass/runtime` or defines what it ships. +- **supporting**: builds, trains, tests or demonstrates the runtime. +- **legacy**: the earlier GenClass project (Python model, Chrome extension, benchmarks). `docs/runtime/CONTRACT.md` §1 says: "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." Some legacy files are still reference implementations for the runtime; the notes say which. + +Workstream names (lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW) and their edit rights are defined in [status-and-known-issues.md](status-and-known-issues.md) ("Workstreams and ownership"). The index of all agent docs is [README.md](README.md); how the parts fit together is in [overview.md](overview.md). Ground rules and what you may run: [../../AGENTS.md](../../AGENTS.md); terms: [glossary.md](glossary.md); step-by-step procedures: [playbooks.md](playbooks.md). + +## 1. Top-level directories + +| dir | tracked files | what | owner / workstream | doc | relevance | +|---|---|---|---|---|---| +| `packages/runtime/` | 143 | `@genclass/runtime` 0.1.0-alpha.0, the npm library: `src/` (55), `test/` (79), `bin/genclass-runtime.mjs` CLI, package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | +| `sim/` | 59 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows | SIM | [sim.md](sim.md) | supporting | +| `training/` | 43 | Python curriculum generator, runtime-text port (`curriculum/rt.py`), eval, ONNX export, Azure launch scripts for the R17/R32 runtime model | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | +| `demos/` | 132 | `@genclass/demos`: Vite site with six demo apps, a Service Worker chaos backend, Playwright trial eval and shipped results | DEMOS | [demos.md](demos.md) | supporting | +| `scripts/` | 26 | Ops scripts. `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | +| `jev_local/` | 136 | Python package `jev-local` 0.1.0: Jev-wire API, encoder engine, trainer, voice harness, benchmark harnesses | none of the runtime workstreams (pre-runtime GenClass) | [genclass-model-lineage.md](genclass-model-lineage.md) | legacy. `serialize.py`, `confidence.py`, `engine/encoder/{tokenize_pack,calibrate,heads}.py` are the parity references for `packages/runtime/src/model`; `train/` is used by `training/` | +| `extension/` | 104 | GenClass 0.1.0 MV3 voice-control Chrome extension. Its own npm package, not a workspace | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy. `src/core/{engine,packer,tokenizer,serialize,pyutil}.js` are the ancestors of the runtime's `src/model/*.ts` | +| `bench/` | 5 | jevbench and benchmax pre-registrations, `public/` target and exclusion JSON | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | +| `tests/` | 74 | pytest suites for `jev_local` (71 `test_*.py`, `conftest.py`, 2 fixtures) | none of the runtime workstreams | [genclass-model-lineage.md](genclass-model-lineage.md) ("Tests") | legacy | +| `results/` | 3 | Benchmark write-ups (CU head-to-head, jevbench M0, Z-68m notes) | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | +| `docs/` | 15 tracked | `docs/runtime/` (3: CONTRACT, API, ARCHITECTURE: the runtime's human docs), `docs/benchmax-research/` (5), 7 legacy jev-local docs. `docs/agents/` (these docs) is untracked at 654d822 | `docs/runtime/CONTRACT.md`: lead. Rest: not recorded / legacy | [status-and-known-issues.md](status-and-known-issues.md) (doc drift tables) | `docs/runtime/`: core. Rest: legacy | + +Root files: + +| file | what | relevance | +|---|---|---| +| `package.json` | private `genclass-lib`, `"type": "module"`, workspaces `packages/*`, `sim`, `demos`; scripts `build` and `test` (runtime only), `typecheck` (all workspaces); devDep `typescript ~5.9.3`; `engines.node >=20` | core | +| `tsconfig.base.json` | shared TypeScript compiler options | core | +| `.gitignore` | ignore rules (see [section 4](#4-generated-and-ignored-paths)) | core | +| `README.md` | repo landing page: status banner, install, repo map | core | +| `OPEN_TASKS.md` | project-level status: done, in progress, next, needs the user, known risks (owner inferred: lead) | core | +| `LICENSE` | Apache-2.0 | core | +| `pyproject.toml` | Python package `jev-local` 0.1.0 (Python >=3.12,<3.14), console script `jev-local`, pytest config | legacy | +| `BENCHMARKS.md` | public summary of GenClass 0.1 benchmark results | legacy | +| [`AGENTS.md`](../../AGENTS.md), [`CLAUDE.md`](../../CLAUDE.md) | agent entry points (untracked at 654d822, written with these docs) | — | + +## 2. Tree + +One line per file for the code that matters most; one line per directory (with tracked-file counts) for legacy areas. Descriptions are summaries; the linked docs have the detail. + +### `packages/runtime/` package root (9 files) + +Doc: [runtime/build-test-release.md](runtime/build-test-release.md), [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). + +```text +packages/runtime/ + package.json @genclass/runtime 0.1.0-alpha.0; exports . ./react ./redux ./zustand ./devtools ./worker; bin genclass-runtime; + dep onnxruntime-web ^1.30.0; optional peers react/redux/zustand; scripts build typecheck test test:browser + tsconfig.json typecheck project (include src only: tests are never type-checked) + tsup.config.ts 6 ESM entries (index, adapters/react|redux|zustand, devtools/index, worker) -> dist/; .d.ts for all but worker + vitest.config.ts unit tests: test/**/*.test.ts, excludes test/browser/**, env node, testTimeout 20000 + README.md npm package README + STATUS.md CORE status: test state, headless recipe, trigger table, example situations, deviations, open issues + UI-NEEDS.md UI -> CORE request log (partly stale) + LICENSE Apache-2.0 + bin/genclass-runtime.mjs CLI (Node >= 20, no deps): fetch-model <dir> [--from] [--variant q8|fp16|all] [--force] [--quiet], info <dir> +``` + +### `packages/runtime/src/` (55 files) + +```text +packages/runtime/src/ + index.ts public facade: GenClass (init/runtime/destroy), createRuntime, re-exports; killSwitch, makeHost, NATIVE_FETCH, ALL_OFF + runtime.ts RuntimeImpl: wires every layer; installObservers, trigger (triage), onDecision, settled points, + rollback/revertChain/resync, explain, undo, destroy + types.ts every public and shared type: options, Runtime, RuntimeEvents, plugins, and the "model seam" + (JevState, Question, Answer, EvaluateRequest, DecisionProvider) mirrored by sim/src/types.ts + errors.ts GenClassUnavailableError + clock.ts browserClock (timers captured at module load, afterTask) + util.ts hashing (fnv1a, stableStringify, hashValue), URL signatures (normalizePath, isIdSegment, + requestSignature), formatting (secs, rel, fmtNum, truncate), redaction (defaultRedact) + adapters/react.ts @genclass/runtime/react: GenClassProvider, useGenClass, useGenClassState, useAtom, useGenClassDecisions/Interventions/Status + adapters/redux.ts @genclass/runtime/redux: genclassEnhancer, GENCLASS_REPLACE + adapters/zustand.ts @genclass/runtime/zustand: genclass middleware + decide/decider.ts DeciderQueue: one request at a time, priority, 32-item cap, answer cache, PROVIDER_TIMEOUT_MS, fail-open + decide/exec.ts types only: Controller, ActionEffect, NetHost, TriggerOpts, EndOpts + decide/policy.ts policyConfig (thresholds), modeAllows, permittedActions, gate (summed-mass rule), RateLimiter, holdBudget + decide/report.ts Reporter (console sink, 60 s dedupe), interventionLine, detectionLine, decisionLine + devtools/index.ts @genclass/runtime/devtools: mountDevtools, Devtools class (shadow-root overlay, 4 views) + devtools/ui.ts DOM helper h(), icons, formatting, report-wording templates, activity-event classification + devtools/css.ts CSS string with light/dark tokens, applied inside the shadow root + learn/baselines.ts Baselines: per-signature latency, outcomes, failure streak, error EWMA, rate, identity gaps (fetch/XHR) + learn/profiles.ts Profiles: transition profiles and rarity check (MIN_COMPLETIONS 20, RARE 0.01) + model/README.md MODEL's internal notes: card format, load steps, parity results, measured latency and sizes + model/host.ts createModelHost, ModelHost, DEFAULT_MODEL_BASE_URL; worker or inline transport, preload, queue, timeouts, WASM retry + model/backend.ts ModelBackend: load phases (card, download, runtime, session, warmup) and evaluate; WARMUP_STATE + model/worker.ts module Worker entry (tsup entry worker -> dist/worker.js) + model/protocol.ts ToWorker / FromWorker / EvaluateOk message types + model/loader.ts parseCard, planOrder, probeWebGPU, fetchFile (Cache Storage + sha256), CARD_FORMAT, DEFAULT_CACHE_NAME + model/engine.ts Engine: packer + ORT session + calibration -> answers; FEEDS; graph-contract check + model/packer.ts Packer, planInputs, unpackLogits, MARKERS (port of jev_local tokenize_pack.Packer) + model/tokenizer.ts Tokenizer: byte-level BPE over a HF tokenizer.json + model/serialize.ts stateSegments, questionBlock, pyJson (port of jev_local/serialize.py) + model/pyutil.ts Python value semantics: pyNumber, pyFloatRepr, pyRound, pyStrip, clip01 + model/calibrate.ts parseCalibration, calibrateLogits, buildAnswer, headerKey, K_BUCKETS (port of calibrate.py + confidence.py) + model/errors.ts GenClassModelError + 11 subclasses (ModelNotReadyError, MaxTokensExceededError, ...), serializeError + model/hash.ts pure-TS sha1/sha256; sha256Hex prefers WebCrypto + model/index.ts internal barrel; nothing in src/ imports it; only test/browser/build.mjs's fallback build uses it + observe/fetch.ts installFetch: fetch ops, request identity, request gate, failure gate, stall controller + observe/xhr.ts installXHR: XMLHttpRequest.prototype patch; request gate (XHR failures/stalls are detection-only) + observe/cache.ts ResponseCache (GET cache, coalescing table), makeResponse/blockedResponse (x-genclass header) + observe/dom-user.ts installDomUser (capture-phase user actions), describeElement, ignoredEvent (data-genclass-ignore) + observe/timers.ts installTimers: setTimeout/setInterval wrappers that carry the ambient op + observe/websocket.ts installWebSocket: WebSocket subclass + observe/nav.ts installNav: history pushState/replaceState, popstate, hashchange + observe/storage.ts installStorage: Storage.prototype setItem/removeItem/clear + observe/errors.ts installErrors: error and unhandledrejection listeners + observe/perf.ts installPerf: longtask PerformanceObserver + situation/build.ts buildSituation: subject sentence, sections, applicable actions (builtinApplicable), questions, salience + situation/facts.ts computeFacts per trigger, orderFacts, MAX_FACTS (12) + situation/describe.ts opPhrase, opLabel, userPhrase, statusText, eventLine + situation/questions.ts BUILTIN_ACTIONS, TRIGGER_ACTIONS, PASSIVE, DEFAULT_DIAGNOSES, buildQuestions, COMPACT_QUESTIONS_BUDGET + situation/serialize.ts toJevState, sectionLimits, stateChars, STATE_CHAR_BUDGET / COMPACT_BUDGET / MIN_BUDGET + situation/env.ts SitEnv (read-only runtime view for situation code), SubjectSpec, ReqMeta, FailureInfo, Violation + state/hub.ts StoreHub: atom/guard/adapter stores, mutation pipeline, field versions and logs, late revert, snapshots + state/fields.ts flatten, diffLeaves, deltaOf, changeText, patchValue, cloneValue; MAX_DEPTH, MAX_FIELDS_PER_STORE + state/invariants.ts InvariantMiner (9 templates; LEARN_AFTER, LEARN_AFTER_NONNULL), expect() predicates + trace/ops.ts OpRegistry, OpRec + trace/context.ts Context (ambient op: run, stick, isUserSync), LazyOp + trace/events.ts EventLog ring buffer +``` + +Docs by folder: `index.ts`, `runtime.ts`, `types.ts`, `errors.ts`, `clock.ts`, `util.ts` -> [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md); `observe/`, `trace/` -> [runtime/observe-and-trace.md](runtime/observe-and-trace.md); `state/`, `adapters/` -> [runtime/state-and-adapters.md](runtime/state-and-adapters.md); `learn/`, `situation/` -> [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md); `decide/` -> [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md); `model/` -> [runtime/model-host.md](runtime/model-host.md); `devtools/` -> [runtime/devtools.md](runtime/devtools.md). Everything the model reads is frozen at tag `situation-v1`: [model-io-contract.md](model-io-contract.md). + +### `packages/runtime/test/` (79 files) + +Doc: [runtime/build-test-release.md](runtime/build-test-release.md) ("Tests" has one row per file with test counts). + +```text +packages/runtime/test/ + helpers.ts core test kit: setup, FakeClock, FakeServer, ScriptedDecider, defaultScript, ManualDecider, makeGlobal, drain + adapter-seam.test.ts rt.adapter(...).propose: reducer preview, held async dispatch, discard, rollback only with io.set + adapters-react.test.ts React hooks, with MockRuntime and the real runtime (happy-dom) + adapters-redux.test.ts genclassEnhancer: hold/apply once, GENCLASS_REPLACE, replaceReducer + adapters-zustand.test.ts genclass middleware: merge semantics, hold/drop, whole-state writes + ask.test.ts ask()/decide() typed answers, GenClassUnavailableError without a model + atoms.test.ts mutation pipeline: user-sync never held, hold/apply, fail-open, late revert, defer + batch3.test.ts SIM requests a-f, ctx.builtin through the gate, GenClass.init never throws + budget.test.ts situation budgets, compact questions, auto budget, hold budget; prints example situations + context.test.ts causal context: cause/root through fetch, timers, rt.op + devtools-runtime.test.ts overlay on the real runtime via runStoreSession (happy-dom) + devtools.test.ts overlay vs MockRuntime + loadScenario (happy-dom) + dom.test.ts describeElement, DOM user observer, destroy restores globals (happy-dom) + fetch.test.ts fetch observer: coalesce, block, serve_cached, delay, retry, hedge, cache limits + invariants.test.ts InvariantMiner learning, inconsistency once per episode, rollback + learn.test.ts Baselines and Profiles; transition trigger + plugins.test.ts plugin facts/diagnoses/actions, ctx.builtin, standing questions, vocabulary + policy.test.ts gate(): summed mass, tiers, thresholds, deny/allow, rate limit, pause + report.test.ts report line format, explain(id), ?genclass=off|heal + review-actions.test.ts REVIEW regression (must pass unmodified): error-trigger rollback scope + review-dom.test.ts REVIEW: passwords never recorded, programmatic click is not a user action + review-fetch.test.ts REVIEW: request identity, coalescing edge cases, buffer limits, keepalive + review-hub.test.ts REVIEW: held patches, late-revert undo, deep changes + review-misc.test.ts REVIEW: console summaries, read-only fetch, denied heal action, ask after destroy + review-perf.test.ts REVIEW: wall-clock cost budgets on 5,000-item stores + review-precision.test.ts REVIEW: transition/inconsistency false positives + review-redaction.test.ts REVIEW: custom redact applies to invariant facts + review-timers.test.ts REVIEW: recursive timer loops; gc check needs NODE_OPTIONS=--expose-gc + review-xhr.test.ts REVIEW: sync XHR never held, abort while held + situation.test.ts one situation per trigger: key order and section limits; prints situations + smoke.test.ts atoms, context through real awaits, stale write discarded in guard mode + xhr.test.ts XHR op + cause, block, detection-only failures, destroy restores open/send + model/helpers.ts model test kit: MODEL_DIR (GENCLASS_MODEL_DIR), FIXTURES_FROM_MODEL, fixture loaders + model/calibrate.test.ts hashes and calibration vs Python/PyTorch (1 of 8 skips without model files) + model/engine.test.ts ORT-node and ORT-web parity vs PyTorch (3 of 4 skip without model files) + model/host.test.ts createModelHost with a fake worker: preload, queue, timeouts, WebGPU -> WASM recovery + model/loader.test.ts parseCard, planOrder, fetchFile, ModelBackend.load phases + model/packer.test.ts packer and tokenizer parity (all 10 skip without tokenizer.json in MODEL_DIR) + model/serialize.test.ts stateSegments/questionBlock vs Python, Python number formatting + fixtures/model/make_py_fixtures.py generator of py_fixtures.json (Python reference outputs) + fixtures/model/make_webgpu_variants.py generator of test-only WebGPU embedding variants (GENCLASS_WEBGPU_VARIANTS) + fixtures/model/py_fixtures.json serialize/tokenize/calibrate/confidence reference cases (single line) + fixtures/model/requests50.json 50 v0.1 requests {id, state, questions} (single line) + fixtures/model/pack_fixtures.json Python packer output for requests50 (single line) + fixtures/model/torch_fixtures.json PyTorch logits of the v0.1 model for requests50 (single line) + browser/.gitignore ignores .build/ + browser/playwright.config.ts model specs: projects chromium and swiftshader-webgpu; globalSetup build.mjs + browser/build.mjs global setup: buildLibrary (runs tsup, rewrites dist/), esbuild page bundle into .build/app/ + browser/server.mjs static server for the specs (startServer) + browser/model-helpers.ts spec helpers: MODEL_DIR, HAVE_MODEL, parityRun, benchmarks + browser/model.spec.ts model host in headless Chromium on WASM (skips without model.json) + browser/model-webgpu.spec.ts model host on SwiftShader WebGPU + browser/ui-devtools.spec.ts devtools overlay in Chromium; rewrites ui/screenshots/*.png + browser/page/index.html test page + browser/page/main.ts test app driving the built library (window.GC) + browser/ui/playwright.config.ts UI spec config (testMatch ui-*.spec.ts) + browser/ui/mock-runtime.ts MockRuntime: scripted Runtime (also used by adapters-*.test.ts) + browser/ui/scenario.ts loadScenario: scripted store story for MockRuntime + browser/ui/session.ts runStoreSession: real createRuntime under a VirtualClock with a rule-based SessionDecider + browser/ui/page.ts fake "Acme" store page for the UI spec (window.__gc) + browser/ui/screenshots/activity-dark.png + browser/ui/screenshots/activity-light.png + browser/ui/screenshots/detections-dark.png + browser/ui/screenshots/detections-light.png + browser/ui/screenshots/evidence-answers-dark.png + browser/ui/screenshots/evidence-answers-light.png + browser/ui/screenshots/evidence-dark.png + browser/ui/screenshots/evidence-light.png + browser/ui/screenshots/interventions-dark.png + browser/ui/screenshots/interventions-light.png + browser/ui/screenshots/loading-dark.png + browser/ui/screenshots/loading-light.png + browser/ui/screenshots/now-dark.png + browser/ui/screenshots/now-light.png + browser/ui/screenshots/overlay-dark.png + browser/ui/screenshots/overlay-light.png + browser/ui/screenshots/pill-dark.png + browser/ui/screenshots/pill-light.png + smoke/smoke.sh npm pack -> fresh Vite 8 app -> headless Chromium check (run from packages/runtime; ask first) +``` + +The 18 PNGs are written by `ui-devtools.spec.ts`; no README embeds them. + +### `packages/runtime-model/` (1 file) + +```text +packages/runtime-model/ + MODEL_CARD.md model card for R17/R32 (sizes, stage-1c accuracy, limits); the package itself does not exist yet +``` + +### `sim/` (59 files) + +Doc: [sim.md](sim.md). Row format: [model-io-contract.md](model-io-contract.md). + +```text +sim/ + package.json @genclass/sim (private); bin genclass-sim -> dist/gen.js; scripts build typecheck test gen sample build:runtime-core + tsconfig.json extends ../tsconfig.base.json, noEmit, src + test + tsup.config.ts ESM, node22, @genclass/runtime external; entries gen, worker, index, smoke -> dist/ + vitest.config.ts node env, pool forks, 120 s timeouts + README.md SIM README: commands, final datasets, known limitations + NEEDS.md SIM -> CORE requests (relayed by the lead) + scripts/final.sh final datasets on the train VM: final.sh a | b | merge-b (ask first) + scripts/analyze.py dataset summary: python3 sim/scripts/analyze.py <dir> + samples/sample.jsonl 200 rows written by gen --sample + samples/EXAMPLES.md pretty-printed example rows (renderExamples) + samples/sample-stats.json stats of the sample run + samples/stats-final-a.json stats of SIM final phase A (600,676 rows) + src/index.ts library re-exports (buildScenario, runScenario, generateTrajectory, runCost, ...) + src/types.ts structural mirror of the runtime model seam + Row/Label (CONTRACT-D) + src/rng.ts Rng (sfc32, keyed forks), hash32, hashAll + src/loop.ts VirtualLoop: deterministic virtual event loop and clocks + src/gen.ts CLI: worker pool, shard merge, stats.json, --sample, --parts, --allow-fake + src/gen/trajectory.ts generateTrajectory, pointCosts: ideal + base + counterfactual runs -> rows + src/gen/worker.ts worker_threads worker: seeds -> rows -> shard/part files + src/gen/examples.ts renderExamples (EXAMPLES.md) + src/net/network.ts Network (latency, chaos, push, fetch), IDEAL_PROFILE, SIM_OP_HEADER + src/net/server.ts VirtualServer, Db, API_STYLES + src/app/env.ts AppEnv: what generated app programs see (fetch, stores, sockets, timers) + src/app/feature.ts FeatureDef contract, UserModel, personas, relations + src/app/kit.ts Kit: tagged ops, requests, writes, error surfacing + src/app/naming.ts Naming: per-program route/store/field names + src/app/vocab.ts DOMAINS: 55 domain vocabularies + src/app/features/index.ts FEATURES, FEATURE_WEIGHTS + src/app/features/common.ts shared feature helpers + src/app/features/auth.ts feature combinator (one FeatureDef each, 15 in total) + src/app/features/benign.ts + src/app/features/board.ts + src/app/features/bulk.ts + src/app/features/cart.ts + src/app/features/chat.ts + src/app/features/counter.ts + src/app/features/editor.ts + src/app/features/form.ts + src/app/features/list.ts + src/app/features/nav.ts + src/app/features/poll.ts + src/app/features/search.ts + src/app/features/settings.ts + src/app/features/toggle.ts + src/world/scenario.ts buildScenario(seed), splitOf, TEST_DOMAINS, TEST_PATTERNS, chaos profiles + src/run/rt.ts realRuntimeFactory (dynamic import of the real runtime), createOptions + src/run/runner.ts runScenario: one run (ideal or real), recording decider, correlation, snapshots + src/run/fake-runtime.ts createFakeRuntime: test double only (rows marked meta.runtime "fake") + src/run/transform.ts transformQuestions (shuffle/drop action options), ACTION_PARA + src/oracle/knowledge.ts Knowledge: ground-truth bookkeeping (intents, sim ops, sim writes) + src/oracle/diagnose.ts diagnose, diagnoseFailure: diagnosis labels + src/oracle/cost.ts W (cost weights), LABEL, TIER, runCost, actionLabel + src/ask/questions.ts askQuestions: 11 programmatic ask generators with exact labels + src/dev/smoke.ts dev tool: base runs on many seeds, prints raw situations + test/helpers.ts testFactory (SIM_RUNTIME=real -> real runtime, else fake), mini scenario builder + test/loop.test.ts VirtualLoop ordering, Response bodies, rng forks + test/determinism.test.ts same seed -> identical rows; replay reproduces every prefix + test/rows.test.ts valid CONTRACT-D rows; splits and transform + test/oracle.test.ts diagnosis and cost/label cases (2 are real-runtime only) +``` + +### `training/` (43 files) + +Doc: [training.md](training.md). Every script here runs on Azure VMs; ask before running any of them. + +```text +training/ + README.md overview and reproduce commands (partly stale) + LOG.md dated run log (what ran where, throughput, costs, decisions) + EVAL.md metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot) + NEEDS.md TRAIN requests to SIM / CORE / MODEL, MODEL -> TRAIN notes + prune_vocab.py prune/analyze: keep the first N BPE merges (16,000 -> 16,364 tokens) of a checkpoint or HF base + eval_runtime.py accuracy, NLL/Brier/ECE, temperature fit (calibration.json), CONTRACT §8 gate metrics, SIM cost regret + export_runtime.py checkpoint -> q8/fp16 ONNX + model.json/meta.json/calibration.json/tokenizer.json + parity fixtures + report.py Markdown tables for EVAL.md from eval reports + configs/mix_s1.json mixture configs read by jev_local/train/stream.py MixConfig + configs/mix_s1b.json + configs/mix_s1c.json + configs/mix_s2.json + configs/mix_final1.json + curriculum/__init__.py package docstring + curriculum/generate.py seeded parallel curriculum generator (CONTRACT-D jsonl + stats.json); --p-runtime -> GC_P_RUNTIME + curriculum/rt.py Python port of packages/runtime/src/situation/* (runtime-exact rows); must match the frozen text + curriculum/world.py explicit world model: ops, writes with versions, baselines; varied-style rendering + curriculum/app.py App: per-row app instance (names, ids, routes, values) + curriculum/vocab.py 62 app domains (13 held out: TEST_DOMAINS), UI/error vocab + curriculum/fmt.py surface variation: Style, TEMPLATES (held-out tails), action/diagnosis vocab + curriculum/scenarios.py Scen dataclass; mutation scenarios; noise ops + curriculum/scen_ops.py request / failure / stall scenarios + curriculum/scen_state.py inconsistency / transition / error scenarios + curriculum/prims.py primitive questions with exact labels over a Trace + curriculum/rows.py decision_row, ask_row: assemble rows + curriculum/standalone.py non-situation primitive families (JSON invariants, HTTP semantics, JS errors) + ortweb/package.json onnxruntime-node + onnxruntime-web 1.30.0 for validate.mjs (not a workspace) + ortweb/validate.mjs node validate.mjs <dir> [variant] [maxRequests]: WASM parity and latency of an export + samples/runtime_samples.txt 75 hand-written runtime-like lines for prune_vocab.py analyze + tests/test_curriculum.py pytest (VM): curriculum validity, held-out splits, label consistency + tests/test_prune_vocab.py pytest (VM; GC_V1_CKPT, GC_BASE_32M): pruned tokenizer and logits parity + tests/test_export_runtime.py pytest (VM; GC_R17_INIT): int8 embeddings, Gemm->MatMul, end-to-end export + node.sh ssh/rsync wrapper for Azure hosts: node.sh HOST sync|'cmd'|get R L|put L R + import_sim.sh pull a SIM run to c01 and shard it (stage 2) + import_final.sh pull a frozen SIM run, shard, build eval subsets, bundle for nodes + launch_s2.sh launch stage-2 pilot runs (R32, R17) + launch_final1.sh launch final round 1: launch_final1.sh R32_PASSES R17_PASSES + final_post.sh on a rank-0 node: SIM eval -> export -> serve tar on :8801 + eval_sim.sh sharded logit collection + one SIM eval per model + run_evals.sh stage-1 eval batch on c01 + pull_ckpt.sh copy a servable checkpoint from a node to c01 + pull_on_train.sh on the train VM: fetch an export tar, sha256 check, run validate.mjs + deliver_final.sh from the Mac: same delivery, driven remotely +``` + +### `demos/` (132 files) + +Doc: [demos.md](demos.md). Non-`src` files: + +```text +demos/ + package.json @genclass/demos (private); scripts dev build preview typecheck typecheck:shim fetch-model eval eval:fast shots + vite.config.ts multi-page build, runtime-shim aliasing (GENCLASS_SHIM), dev Service Worker middleware + tsconfig.json app code + tsconfig.sw.json Service Worker code (lib WebWorker) + tsconfig.node.json e2e/*.ts and vite.config.ts + tsconfig.shim.json app code type-checked against the runtime shim + .gitignore node_modules/ dist/ public/genclass-model/ test-results/ playwright-report/ e2e/.out/ + index.html landing page + board/index.html one page per demo + checkout/index.html + decisions/index.html + editor/index.html + search/index.html + status/index.html + public/favicon.svg site icon + scripts/build.mjs site build + dist/sw.js IIFE + results-summary.json copy + scripts/fetch-model.sh download a model directory (runtime CLI fetch-model, curl fallback) + scripts/vm-eval.sh full VM pipeline: install, build runtime, model, build demos, eval (ask first) + e2e/eval.ts headless Playwright trials -> results.json, results.md, screenshots (ask first) + e2e/serve.ts static server for dist/ under a sub-path + e2e/trace-report.ts analyses --trace runs (e2e/.out/traces*.json) into Markdown + README.md human README: run, URL params, oracles, honesty rules + NEEDS.md DEMOS -> CORE/MODEL/UI/lead issues with evidence + results.md latest results (v0.1 model, generated before batch 3) + results.json raw trials (large) + results-summary.json summary shipped with the site + screenshots/ 30 PNGs (see below) +``` + +`demos/src/` (76 files): + +```text +demos/src/ + shared/genclass.ts startGenClass: the only place the demos create the runtime; collectStats, statusText + shared/settings.ts URL params and localStorage: getMode, modelBaseUrl, trialParams, traceOn, holdBudget + shared/chaos.ts chaos model: RouteChaos, PRESETS, resolveChaos, sampleTiming + shared/scenario-kit.ts typing rhythm (typeSteps), sampleChaos, CLEAN_CHAOS + shared/types.ts GcMode, Step, Scenario, Score, TrialResult + shared/demo-def.ts DemoDefinition, AppContext, OracleContext, Oracle + shared/driver.ts runSteps: synthetic in-page user + shared/harness.ts TrialHarness (window.__trial) + shared/aggregate.ts wilson, quantile, summarizeMode, summarizeDemo + shared/trace.ts ?trace=1 investigation tracing via hooks.mutationProposed + shared/server.ts ensureServiceWorker, ServerLink (page side of the mock server) + shared/protocol.ts page <-> Service Worker control protocol types + shared/native.ts timers captured before GenClass.init wraps globals (nativeSetTimeout, sleep) + shared/rng.ts seeded PRNG (sfc32), hashString + shared/demos.ts DEMOS copy for landing/topbar/explain cards + shared/api.ts api(path): <siteRoot>api/ + server/sw.ts Service Worker: sessions, control messages, /api/* routing, COOP/COEP headers + server/core.ts World: router, chaos/latency pipeline, SSE streams, request log, quiescence + server/worlds/search.ts searchWorld (imports data/cities.ts, which is missing from git) + server/worlds/editor.ts editorWorld + server/worlds/checkout.ts checkoutWorld, PRODUCTS + server/worlds/status.ts statusWorld, SERVICES, truthAt + server/worlds/board.ts boardWorld, COLUMNS, BOARD_SEED, TEAMMATES, teammateMove + server/worlds/decisions.ts decisionsWorld, BACKUP_MS + demos/search/main.ts bootDemo for the search typeahead + demos/search/app.ts mountSearch (atom "search"); latent bug: no request-ordering guard + demos/search/app.css + demos/search/scenario.ts searchScenario(seed, kind) + demos/search/oracle.ts searchOracle (test code only) + demos/editor/main.ts bootDemo for notes autosave + demos/editor/app.ts mountEditor; latent bugs: overlapping saves, "Saved" lies + demos/editor/app.css + demos/editor/store.ts createNotesStore: Redux + genclassEnhancer + demos/editor/scenario.ts editorScenario + demos/editor/oracle.ts editorOracle + demos/checkout/main.ts bootDemo for cart/checkout + demos/checkout/app.tsx mountCheckout (React, useGenClassState); latent bugs: double submit, retries without idempotency key + demos/checkout/app.css + demos/checkout/scenario.ts checkoutScenario + demos/checkout/oracle.ts checkoutOracle + demos/status/main.ts bootDemo for the status dashboard + demos/status/app.ts mountStatus (gc.guard "services"); latent bugs: overlapping polls, retry storm + demos/status/app.css + demos/status/scenario.ts statusScenario + demos/status/oracle.ts statusOracle + demos/board/main.ts bootDemo for the kanban board + demos/board/app.tsx mountBoard (React + SSE); latent bugs: no version check, whole-board rollback + demos/board/app.css + demos/board/store.ts createBoardStore: Zustand + genclass middleware + demos/board/scenario.ts boardScenario + demos/board/oracle.ts boardOracle + demos/decisions/main.ts bootDemo for the field journal + demos/decisions/app.ts mountDecisions: gc.ask / gc.decide with app defaults; atoms "journal", "gallery" + demos/decisions/app.css + demos/decisions/plugin.ts backgroundWorkPlugin: custom facts and the pause_background action + demos/decisions/jobs.ts BackgroundJobs, jobs (background photo backup controller) + demos/decisions/scenario.ts decisionsScenario + demos/decisions/oracle.ts decisionsOracle + site/demo-page.ts bootDemo: interactive demo page or bare trial page; mounts devtools + site/landing.ts landing page + site/activity.ts mountActivity: "GenClass activity" panel (reports, evidence, Undo) + site/chaos-panel.ts mountChaosPanel: presets, sliders, toggles + site/trials-panel.ts mountTrials: in-page trial runner (iframes) + site/netlane.ts mountNetLane: live waterfall of the server log + site/chrome.ts renderTopbar, applyTheme + site/dom.ts h(), append, esc, toast, formatting helpers + site/icons.ts icon(), BRAND_MARK + site/art.ts ART: per-demo card art + site/highlight.ts highlight(): tiny TS/JS syntax highlighter + styles/system.css design tokens (light/dark, --mode-off/guard/heal) + styles/site.css site chrome + dev/runtime-shim/index.ts observe-only stand-in for @genclass/runtime (used when dist is missing or GENCLASS_SHIM=1) + dev/runtime-shim/react.ts + dev/runtime-shim/redux.ts + dev/runtime-shim/zustand.ts + dev/runtime-shim/devtools.ts no-op mountDevtools; duplicates DevtoolsOptions (update when the options change) +``` + +`demos/src/server/data/cities.ts` is imported but not in git (the root `.gitignore` rule `data/` matches it), so a fresh clone cannot build the Service Worker or the search demo. See [demos.md](demos.md) ("Drift and open issues"). + +### `scripts/` (26 files) + +Doc: [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts", with Azure and cost flags per script). None of these should be run without the user's go-ahead. + +```text +scripts/ + vm.sh runtime build/test path: vm.sh sync|run|exec|get SLOT ...; rsync to ~/gcl/SLOT on VM "train" (Azure) + azvm.sh ssh/scp/rsync helper for named Azure VMs from ~/.jev-local/azure_hosts (used by training/*.sh) + launch_run.sh detached multi-node torch.distributed.run of jev_local.train.train (used by training/launch_*.sh; costs money) + cluster_up.sh az vm create training nodes (costs money) + vm_bootstrap.sh one-time Ubuntu VM setup + node_setup.sh fresh-node bootstrap + data bundle pull + launch_z68m.sh benchmax Z-68m retrain launch (costs money) + stage1_speedtest.sh DDP timing runs (costs money) + watch_runs.sh poll rank-0 training logs + phase3_eval.sh benchmax phase-3 eval driver (costs money) + genclass_export.py PyTorch -> ONNX exporter; ExportModel is imported by training/export_runtime.py (from ~/jev/scripts on the VM) + benchmax.py benchmax CLI: list, verify --spec, run --spec + benchmax/stage0_validation.sh adapters on non-evaluated splits (VM) + benchmax/dry_pass_validation.sh dry pass of all 19 specs (VM) + benchmax/engine_determinism.py W11 determinism report + benchmax_build_targets.py regenerate bench/public/targets.json + exclusions.json + jevbench.py jevbench CLI: build, run-ours, run-jev (OpenRouter, costs money), score, report + compare_jev.py CU head-to-head behind results/genclass-vs-jev-computer-use.md (OpenRouter, costs money) + openrouter_key.sh set/check the OpenRouter key (handles a secret; never run unprompted) + dev_to_calib.py jevbench clean-dev requests -> calibration-fitter rows + bench_encoder.py FastEngine inference/training benchmarks (Mac) + bench_decoder.py MLX decoder benchmarks (Mac only) + bench_laya.py zero-shot Laya on the harness cases (Mac) + overnight.py memory-gated overnight job runner for the 8 GB Mac + demo.py macOS voice computer-use demo entry + demo_proof.sh offline mid-sentence proof (Mac only) +``` + +### Legacy directories (one line per directory) + +Doc for `jev_local/`, `tests/` and `docs/` legacy files: [genclass-model-lineage.md](genclass-model-lineage.md). Doc for `extension/`, `bench/`, `results/`, `docs/benchmax-research/`: [extension-and-benchmarks.md](extension-and-benchmarks.md). + +```text +jev_local/ 136 Python package jev-local 0.1.0 + (top level) 8 __init__, schema (Jev wire models), serialize (parity reference), confidence (answer math, + parity reference), validate, api (ServeConfig, routing), cli, demo + engine/ 11 base.py (Engine protocol), registry.py, heuristic.py, plus: + engine/encoder/ 6 tokenize_pack (Packer), model (MaskedEncoder), heads (DecisionHeads), calibrate, engine (FastEngine) + engine/decoder/ 2 MLX Qwen3 zero-shot scorer (macOS) + harness/ 21 macOS voice computer-use harness (reference for extension/src/core) + server/ 2 FastAPI Jev-wire server (create_app) + train/ 7 trainer used by training/: train.py, stream.py (MixConfig), losses.py, ddp.py, eval.py, fixture.py + bench/ 87 jevbench v1 (registry, templates, build, metrics, ours, baselines) and: + bench/benchmax/ 80 runner, specs_a/specs_b (19 specs), bridge_b, adapters_a/ (5), adapters_b/ (70, incl. vendor/ 51) + (missing) jev_local/data/ - v1/v2 data generators; ignored by the root data/ rule, so 20 tests/test_data_*.py fail at collection +extension/ 104 GenClass 0.1.0 MV3 Chrome extension (own package.json and package-lock.json) + (top level) 8 README, MODEL_CARD, RELEASE, NOTICE, LICENSE, package.json, package-lock.json, .gitignore + src/ 28 background/ (1: sw.js), content/ (1), core/ (17: harness port + engine/packer/tokenizer/serialize/pyutil), + model/ (4: model.json, tokenizer.json, calibration.json, meta.json), offscreen/ (3), sidepanel/ (2) + static/ 11 manifest.json, panel/offscreen/welcome pages, audio worklet, icons/ (5) + store/ 13 Chrome Web Store listing, permissions, privacy, icon, screenshots/ (9) + test/ 35 unit/ (6), e2e/ (12), eval/ (7), fixtures/ (10: parity JSON, audio) + scripts/ 4 build.mjs, make_icons.mjs, compose_screens.mjs, make_py_fixtures.py + release-assets/ 4 tokenizer.json, calibration.json, meta.json, parity.json (*.onnx ignored and absent) + tools/ 1 genclass_export.py (q8 export of the v0.1 model) +bench/ 5 PREREG-jevbench.md, PREREG-benchmax.md, public/ (3: targets.json, jev_published.json, exclusions.json) +tests/ 74 pytest for jev_local: conftest.py, fixtures/ (2), 71 test_*.py (20 test_data_*.py cannot import) +docs/ 15 tracked files: + docs/runtime/ 3 CONTRACT.md (binding runtime contract, lead), API.md, ARCHITECTURE.md + docs/benchmax-research/ 5 benchmax planning notes (read-only background) + (top level) 7 legacy jev-local docs: SPEC, CONTRACT (defines the CONTRACT-D row format), CONTRACT-v2, DEMO, + GENCLASS, COMPARISON, PLAN-excel + docs/agents/ - these agent docs (untracked at 654d822) +results/ 3 genclass-vs-jev-computer-use.md, jevbench-m0.md, z68m-dev-notes.md +demos/screenshots/ 30 <demo>.png, <demo>-dark.png, <demo>-full.png and <demo>-page.png for board, checkout, + decisions, editor, status, search; index{,-dark,-full,-mobile}.png; search-mobile.png, + search-trials.png. Written by demos/e2e/eval.ts (npm run shots) +``` + +## 3. Where is X? + +Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/runtime/src/runtime.ts` unless stated. + +### Runtime public API, options and lifecycle + +| X | kind | where | doc | +|---|---|---|---| +| `GenClass` (browser singleton: `init`, `runtime`, `destroy`) | symbol | `packages/runtime/src/index.ts` -> `GenClass` | [public-api](runtime/public-api-and-lifecycle.md) | +| `createRuntime` (headless entry point) | symbol | `packages/runtime/src/index.ts` -> `createRuntime` | [public-api](runtime/public-api-and-lifecycle.md) | +| Kill switch `?genclass=off\|observe\|guard\|heal` / `localStorage.genclass` | URL param, storage key | `packages/runtime/src/index.ts` -> `killSwitch` | [public-api](runtime/public-api-and-lifecycle.md) | +| Owned model host built by `createRuntime` | symbol | `packages/runtime/src/index.ts` -> `makeHost` | [model-host](runtime/model-host.md) | +| Un-observed fetch used for model downloads | constant | `packages/runtime/src/index.ts` -> `NATIVE_FETCH` | [observe-and-trace](runtime/observe-and-trace.md) | +| All-observers-off map (inert runtime) | constant | `packages/runtime/src/index.ts` -> `ALL_OFF` | [public-api](runtime/public-api-and-lifecycle.md) | +| `RuntimeImpl` (implements every `Runtime` method) | class | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` | [public-api](runtime/public-api-and-lifecycle.md) | +| `InitOptions` (`mode`, `model`, `decider`, `observe`, `policy`, `report`, `triage`, `settleMs`, `historySize`, `situation`, ...) | type | `packages/runtime/src/types.ts` -> `InitOptions` | [public-api](runtime/public-api-and-lifecycle.md) | +| `CreateOptions` (adds `clock`, `global`, `app`, `hooks`) | type | `packages/runtime/src/types.ts` -> `CreateOptions` | [public-api](runtime/public-api-and-lifecycle.md) | +| `ModelOptions` (`baseUrl`, `preload`, ...) | type | `packages/runtime/src/types.ts` -> `ModelOptions` | [model-host](runtime/model-host.md) | +| `PolicyOptions` (`thresholds`, `holdBudgetMs`, `allow`, `deny`, `holdUserWrites`, `requireDiagnosis`) | type | `packages/runtime/src/types.ts` -> `PolicyOptions` | [decide-policy](runtime/decide-policy-actions.md) | +| `Runtime` interface | type | `packages/runtime/src/types.ts` -> `Runtime` | [public-api](runtime/public-api-and-lifecycle.md) | +| `RuntimeEvents` (decide, detect, act, report, event, status) | type | `packages/runtime/src/types.ts` -> `RuntimeEvents` | [public-api](runtime/public-api-and-lifecycle.md) | +| `Plugin` / `PluginApi` | type | `packages/runtime/src/types.ts` -> `Plugin`, `PluginApi` | [public-api](runtime/public-api-and-lifecycle.md) | +| `Decision`, `ActionRecord` | type | `packages/runtime/src/types.ts` -> `Decision`, `ActionRecord` | [decide-policy](runtime/decide-policy-actions.md) | +| `DecisionProvider`, `EvaluateRequest` (model seam) | type | `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest` | [model-io-contract](model-io-contract.md) | +| `JevState`, `TriggerKind` | type | `packages/runtime/src/types.ts` -> `JevState`, `TriggerKind` | [model-io-contract](model-io-contract.md) | +| `Clock` and the default real clock | type, constant | `packages/runtime/src/types.ts` -> `Clock`; `packages/runtime/src/clock.ts` -> `browserClock` | [public-api](runtime/public-api-and-lifecycle.md) | +| `GenClassUnavailableError` | class | `packages/runtime/src/errors.ts` -> `GenClassUnavailableError` | [public-api](runtime/public-api-and-lifecycle.md) | +| Observer install order and uninstall | method | `RuntimeImpl.installObservers` | [observe-and-trace](runtime/observe-and-trace.md) | +| Is the decider consulted? (ready/off, not paused) | method | `RuntimeImpl.consultable` | [public-api](runtime/public-api-and-lifecycle.md) | +| Trigger -> triage -> situation -> queue | method | `RuntimeImpl.trigger` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Settled points (invariants, snapshots, profiles) | method | `RuntimeImpl.settled` | [state-and-adapters](runtime/state-and-adapters.md) | +| Model answer -> gate -> action | method | `RuntimeImpl.onDecision` | [decide-policy](runtime/decide-policy-actions.md) | +| Auto situation budget by device (`budgetScale`) | method | `RuntimeImpl.situationBudget` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| `SitEnv` implementation | method | `RuntimeImpl.makeEnv` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Chain revert (error/transition rollback) | method | `RuntimeImpl.revertChain` | [state-and-adapters](runtime/state-and-adapters.md) | +| Late-revert window (2,000 ms) | constant | `packages/runtime/src/runtime.ts` -> `LATE_REVERT_MS` | [decide-policy](runtime/decide-policy-actions.md) | +| In-flight age that blocks settled points (10 s) | constant | `packages/runtime/src/runtime.ts` -> `LONG_RUNNING_MS` | [state-and-adapters](runtime/state-and-adapters.md) | +| Console line `[GenClass] Model unavailable (...); observing only.` | string | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (status subscription) | [status](status-and-known-issues.md) | + +### Observers and trace + +| X | kind | where | doc | +|---|---|---|---| +| fetch wrapper, request/failure gates, stall controller | function | `packages/runtime/src/observe/fetch.ts` -> `installFetch` | [observe-and-trace](runtime/observe-and-trace.md) | +| Max request body hashed for identity (64 KiB) | constant | `packages/runtime/src/observe/fetch.ts` -> `IDENTITY_BODY_MAX` | [observe-and-trace](runtime/observe-and-trace.md) | +| XHR patch | function | `packages/runtime/src/observe/xhr.ts` -> `installXHR` | [observe-and-trace](runtime/observe-and-trace.md) | +| DOM user-action observer | function | `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | +| `describeElement` (public helper) | function | `packages/runtime/src/observe/dom-user.ts` -> `describeElement` | [observe-and-trace](runtime/observe-and-trace.md) | +| `data-genclass-ignore` attribute handling | attribute | `packages/runtime/src/observe/dom-user.ts` -> `ignoredEvent` | [devtools](runtime/devtools.md) | +| WebSocket, timers, nav, storage, errors, longtask observers | function | `packages/runtime/src/observe/{websocket,timers,nav,storage,errors,perf}.ts` -> `installWebSocket`, `installTimers`, `installNav`, `installStorage`, `installErrors`, `installPerf` | [observe-and-trace](runtime/observe-and-trace.md) | +| GET cache and coalescing table | class | `packages/runtime/src/observe/cache.ts` -> `ResponseCache` | [observe-and-trace](runtime/observe-and-trace.md) | +| Cache limits (`MAX_BODY` 256 KB, `MAX_ENTRIES` 64, `COALESCE_WINDOW_MS` 2000) | constant | `packages/runtime/src/observe/cache.ts` | [observe-and-trace](runtime/observe-and-trace.md) | +| `x-genclass: blocked\|cached\|coalesced` response header | header | `packages/runtime/src/observe/cache.ts` -> `makeResponse`, `blockedResponse` | [observe-and-trace](runtime/observe-and-trace.md) | +| Op registry and `OpRec` | class, type | `packages/runtime/src/trace/ops.ts` -> `OpRegistry`, `OpRec` | [observe-and-trace](runtime/observe-and-trace.md) | +| Ambient op, `LazyOp` | class | `packages/runtime/src/trace/context.ts` -> `Context`, `LazyOp` | [observe-and-trace](runtime/observe-and-trace.md) | +| Event ring buffer | class | `packages/runtime/src/trace/events.ts` -> `EventLog` | [observe-and-trace](runtime/observe-and-trace.md) | +| Op signature normalisation (`GET /api/items/:id`) | function | `packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`, `requestSignature` | [observe-and-trace](runtime/observe-and-trace.md) | +| Hashing | function | `packages/runtime/src/util.ts` -> `fnv1a`, `stableStringify` | [public-api](runtime/public-api-and-lifecycle.md) | +| Default redaction | constant | `packages/runtime/src/util.ts` -> `defaultRedact` | [learn-situation-triage](runtime/learn-situation-triage.md) | + +### State and adapters + +| X | kind | where | doc | +|---|---|---|---| +| Store registry and mutation pipeline | class | `packages/runtime/src/state/hub.ts` -> `StoreHub` | [state-and-adapters](runtime/state-and-adapters.md) | +| One proposed write | type | `packages/runtime/src/state/hub.ts` -> `MutationRec` | [state-and-adapters](runtime/state-and-adapters.md) | +| Field flattening and patches | function | `packages/runtime/src/state/fields.ts` -> `flatten`, `patchValue` | [state-and-adapters](runtime/state-and-adapters.md) | +| Flattening limits (`MAX_DEPTH` 4, `MAX_KEYS_EXPAND` 32, `MAX_FIELDS_PER_STORE` 200) | constant | `packages/runtime/src/state/fields.ts` | [state-and-adapters](runtime/state-and-adapters.md) | +| Invariant miner (`LEARN_AFTER` 3, `LEARN_AFTER_NONNULL` 6) | class, constant | `packages/runtime/src/state/invariants.ts` -> `InvariantMiner` | [state-and-adapters](runtime/state-and-adapters.md) | +| Field-path normalisation for chain keys | function | `packages/runtime/src/util.ts` -> `normalizeFieldPath` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| React bindings | symbol | `packages/runtime/src/adapters/react.ts` -> `GenClassProvider`, `useGenClassState`, `useAtom` | [state-and-adapters](runtime/state-and-adapters.md) | +| Redux enhancer and replace action `"@@genclass/REPLACE"` | symbol | `packages/runtime/src/adapters/redux.ts` -> `genclassEnhancer`, `GENCLASS_REPLACE` | [state-and-adapters](runtime/state-and-adapters.md) | +| Zustand middleware | function | `packages/runtime/src/adapters/zustand.ts` -> `genclass` | [state-and-adapters](runtime/state-and-adapters.md) | + +### Learn, situation and questions (frozen at `situation-v1`) + +| X | kind | where | doc | +|---|---|---|---| +| Latency/outcome baselines | class | `packages/runtime/src/learn/baselines.ts` -> `Baselines` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Transition profiles (`MIN_COMPLETIONS` 20, `RARE` 0.01) | class, constant | `packages/runtime/src/learn/profiles.ts` -> `Profiles` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Facts per trigger (`MAX_FACTS` 12) | function | `packages/runtime/src/situation/facts.ts` -> `computeFacts` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Situation assembly | function | `packages/runtime/src/situation/build.ts` -> `buildSituation` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Which built-in actions apply to a subject | function | `packages/runtime/src/situation/build.ts` -> `builtinApplicable` | [decide-policy](runtime/decide-policy-actions.md) | +| Action catalogue, per-trigger actions, passive action | constant | `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE` | [model-io-contract](model-io-contract.md) | +| Diagnosis vocabulary (10 labels) | constant | `packages/runtime/src/situation/questions.ts` -> `DEFAULT_DIAGNOSES` | [model-io-contract](model-io-contract.md) | +| Standing-question builder; bare labels at <= 1,400 chars | function, constant | `packages/runtime/src/situation/questions.ts` -> `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | [model-io-contract](model-io-contract.md) | +| Budget-shaped state | function | `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Budgets 3,200 / 1,100 / 500 chars | constant | `packages/runtime/src/situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET` | [model-io-contract](model-io-contract.md) | +| Read-only runtime view for situation code; trigger subjects | type | `packages/runtime/src/situation/env.ts` -> `SitEnv`, `SubjectSpec` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Op phrasing in situations and `changed` sentences | function | `packages/runtime/src/situation/describe.ts` -> `opPhrase` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Python port of the situation text | function | `training/curriculum/rt.py` -> `render` | [training](training.md) | +| Freeze marker | git tag | `situation-v1` (1a77558); check `git diff situation-v1 HEAD -- packages/runtime/src` | [model-io-contract](model-io-contract.md) | + +### Decide, policy and reports + +| X | kind | where | doc | +|---|---|---|---| +| Decision queue | class | `packages/runtime/src/decide/decider.ts` -> `DeciderQueue` | [decide-policy](runtime/decide-policy-actions.md) | +| Runtime-side provider timeout (10 s) | constant | `packages/runtime/src/decide/decider.ts` -> `PROVIDER_TIMEOUT_MS` | [decide-policy](runtime/decide-policy-actions.md) | +| Summed-mass gate (CONTRACT §8) | function | `packages/runtime/src/decide/policy.ts` -> `gate` | [decide-policy](runtime/decide-policy-actions.md) | +| Default thresholds (report 0.6, guard 0.9, heal 0.8) | config | `packages/runtime/src/decide/policy.ts` -> `policyConfig` | [decide-policy](runtime/decide-policy-actions.md) | +| Hold budget (auto: clamp 150-800 ms, fallback 300) | function, constant | `packages/runtime/src/decide/policy.ts` -> `holdBudget`, `HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS` | [decide-policy](runtime/decide-policy-actions.md) | +| Rate limiter (`policy.maxActionsPerMinute`, default 60) | class | `packages/runtime/src/decide/policy.ts` -> `RateLimiter`, `policyConfig` | [decide-policy](runtime/decide-policy-actions.md) | +| `Controller` / `NetHost` seams | type | `packages/runtime/src/decide/exec.ts` -> `Controller`, `NetHost` | [decide-policy](runtime/decide-policy-actions.md) | +| Console reports and dedupe | class, function | `packages/runtime/src/decide/report.ts` -> `Reporter`, `interventionLine` | [decide-policy](runtime/decide-policy-actions.md) | + +### Model host and CLI + +| X | kind | where | doc | +|---|---|---|---| +| Model host factory | function | `packages/runtime/src/model/host.ts` -> `createModelHost` | [model-host](runtime/model-host.md) | +| Default model URL (unpublished `@genclass/runtime-model@0.1.0`) | constant | `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | [model-host](runtime/model-host.md) | +| Host defaults (`DEFAULT_TIMEOUT_MS` 10 s, `DEFAULT_MAX_QUEUE` 32) | constant | `packages/runtime/src/model/host.ts` | [model-host](runtime/model-host.md) | +| Worker URL literal `new Worker(new URL("./worker.js", import.meta.url), ...)` | code pattern | `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory` | [build-test-release](runtime/build-test-release.md) | +| Load and evaluate (in the worker or inline) | class | `packages/runtime/src/model/backend.ts` -> `ModelBackend` | [model-host](runtime/model-host.md) | +| Warm-up request | constant | `packages/runtime/src/model/backend.ts` -> `WARMUP_STATE`, `WARMUP_QUESTIONS` | [model-host](runtime/model-host.md) | +| Card format `genclass-runtime-model/1` | constant | `packages/runtime/src/model/loader.ts` -> `CARD_FORMAT`, `parseCard` | [model-host](runtime/model-host.md) | +| Plan order webgpu+fp16 -> webgpu+q8 -> wasm+q8 | function | `packages/runtime/src/model/loader.ts` -> `planOrder` | [model-host](runtime/model-host.md) | +| Cache Storage name `genclass-runtime-v1` | constant | `packages/runtime/src/model/loader.ts` -> `DEFAULT_CACHE_NAME` | [model-host](runtime/model-host.md) | +| Packer + ORT session + calibration | class | `packages/runtime/src/model/engine.ts` -> `Engine`, `FEEDS` | [model-io-contract](model-io-contract.md) | +| Packing limits (`max_len` 1536, `max_total` 8192 defaults) | config | `packages/runtime/src/model/packer.ts` -> `Packer`; `packages/runtime/src/model/engine.ts` -> `Engine` (reads `meta.json`) | [model-io-contract](model-io-contract.md) | +| Marker tokens `[Q] [O] [L] [T] [F]` | constant | `packages/runtime/src/model/packer.ts` -> `MARKERS` | [model-io-contract](model-io-contract.md) | +| BPE tokenizer | class | `packages/runtime/src/model/tokenizer.ts` -> `Tokenizer` | [model-host](runtime/model-host.md) | +| State/question text (Python parity) | function | `packages/runtime/src/model/serialize.ts` -> `stateSegments`, `questionBlock` | [model-io-contract](model-io-contract.md) | +| Calibration and answer math | function, constant | `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer`, `K_BUCKETS` | [model-io-contract](model-io-contract.md) | +| Model errors (`max_tokens_exceeded`, not ready, ...) | class | `packages/runtime/src/model/errors.ts` -> `GenClassModelError`, `ModelNotReadyError`, `MaxTokensExceededError` | [model-host](runtime/model-host.md) | +| sha256 integrity / sha1 header keys | function | `packages/runtime/src/model/hash.ts` -> `sha256Hex`, `sha1Hex` | [model-host](runtime/model-host.md) | +| Host <-> worker messages | type | `packages/runtime/src/model/protocol.ts` -> `ToWorker`, `FromWorker` | [model-host](runtime/model-host.md) | +| `genclass-runtime fetch-model <dir>` / `info <dir>` | CLI | `packages/runtime/bin/genclass-runtime.mjs` -> `fetchModel`, `info` | [model-host](runtime/model-host.md) | +| CLI default source (release `runtime-model-v0.1.0`, does not exist yet) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | + +### Devtools overlay + +| X | kind | where | doc | +|---|---|---|---| +| `mountDevtools` (`@genclass/runtime/devtools`) | function | `packages/runtime/src/devtools/index.ts` -> `mountDevtools` | [devtools](runtime/devtools.md) | +| Alt+Shift+G toggle | key binding | `packages/runtime/src/devtools/index.ts` -> `Devtools` | [devtools](runtime/devtools.md) | +| Report sentence parsing | function | `packages/runtime/src/devtools/ui.ts` -> `splitReport` | [devtools](runtime/devtools.md) | +| Stylesheet | constant | `packages/runtime/src/devtools/css.ts` -> `CSS` | [devtools](runtime/devtools.md) | + +### Build, test and release + +| X | kind | where | doc | +|---|---|---|---| +| Workspaces (`packages/*`, `sim`, `demos`) and root scripts `build`, `test`, `typecheck` | config | `package.json` -> `workspaces`, `scripts` | [build-test-release](runtime/build-test-release.md) | +| Subpath exports and `bin` | config | `packages/runtime/package.json` -> `exports`, `bin` | [build-test-release](runtime/build-test-release.md) | +| Build entries and externals | config | `packages/runtime/tsup.config.ts` -> `entry`, `dts`, `external` | [build-test-release](runtime/build-test-release.md) | +| Unit-test include/exclude | config | `packages/runtime/vitest.config.ts` | [build-test-release](runtime/build-test-release.md) | +| Typecheck: `npx tsc -p tsconfig.json --noEmit` (in `packages/runtime`) | command | `packages/runtime/package.json` -> `scripts.typecheck` | [build-test-release](runtime/build-test-release.md) | +| Unit tests: `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (in `packages/runtime`) | command | `packages/runtime/vitest.config.ts`; gc check in `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | +| Browser specs `npm run test:browser` (ask first) | command | `packages/runtime/package.json` -> `scripts.test:browser`; `packages/runtime/test/browser/playwright.config.ts` | [build-test-release](runtime/build-test-release.md) | +| Smoke test `bash test/smoke/smoke.sh` (ask first) | command | `packages/runtime/test/smoke/smoke.sh` | [build-test-release](runtime/build-test-release.md) | +| Core test harness | function, class | `packages/runtime/test/helpers.ts` -> `setup`, `FakeClock`, `FakeServer`, `ScriptedDecider`, `ManualDecider` | [build-test-release](runtime/build-test-release.md) | +| Scripted `Runtime` for UI/adapter tests | class | `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime` | [devtools](runtime/devtools.md) | +| Real runtime under virtual time for UI tests | function | `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession` | [devtools](runtime/devtools.md) | +| Scripted store story | function | `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario` | [devtools](runtime/devtools.md) | +| Playwright global setup (rebuilds `dist/`) | function | `packages/runtime/test/browser/build.mjs` -> `buildLibrary` | [build-test-release](runtime/build-test-release.md) | +| Model fixtures from an export instead of v0.1 | flag | `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL` | [build-test-release](runtime/build-test-release.md) | +| VM helper `scripts/vm.sh sync\|run\|exec\|get SLOT ...` (Azure; ask first) | command | `scripts/vm.sh` | [build-test-release](runtime/build-test-release.md) | +| Release tags `v0.1.0-alpha.0` (654d822), `situation-v1` (1a77558) | git tag | `git tag -n1` | [build-test-release](runtime/build-test-release.md) | + +### Environment variables + +| X | used by | where | doc | +|---|---|---|---| +| `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) | model unit tests and browser specs | `packages/runtime/test/model/helpers.ts` -> `MODEL_DIR`; `packages/runtime/test/browser/model-helpers.ts` -> `MODEL_DIR` | [build-test-release](runtime/build-test-release.md) | +| `GENCLASS_WEBGPU_VARIANTS` | WebGPU spec variants | `packages/runtime/test/browser/model-webgpu.spec.ts` | [build-test-release](runtime/build-test-release.md) | +| `GENCLASS_BENCH_MODELS`, `GENCLASS_OFFLINE` | browser model specs | `packages/runtime/test/browser/model.spec.ts` | [build-test-release](runtime/build-test-release.md) | +| `NODE_OPTIONS=--expose-gc` | gc check in a REVIEW test | `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | +| `SIM_RUNTIME=real` | sim tests use the real runtime | `sim/test/helpers.ts` -> `testFactory` | [sim](sim.md) | +| `GC_P_RUNTIME` (set from `--p-runtime`) | share of runtime-exact curriculum rows | `training/curriculum/generate.py` -> `P_RUNTIME` | [training](training.md) | +| `GC_V1_CKPT`, `GC_BASE_32M` | prune tests | `training/tests/test_prune_vocab.py` | [training](training.md) | +| `GC_R17_INIT` | export end-to-end test | `training/tests/test_export_runtime.py` | [training](training.md) | +| `GENCLASS_SHIM` (`1` forces the runtime shim, `0` forbids it) | demos build | `demos/vite.config.ts` | [demos](demos.md) | +| `VITE_GENCLASS_MODEL_URL` | demo model location (after `?model=`) | `demos/src/shared/settings.ts` -> `modelBaseUrl` | [demos](demos.md) | +| `GENCLASS_MODEL_FROM`, `GENCLASS_MODEL_DIR`, `GENCLASS_MODEL_URL`, `GENCLASS_MODEL_VARIANT`, `ALLOW_BROKEN_RUNTIME`, `SKIP_EVAL` | demos VM pipeline | `demos/scripts/vm-eval.sh` | [demos](demos.md) | +| `JEV_LOCAL_FAST_CKPT` | fast checkpoint dir (default `<repo>/models/jev-local-fast`) | `jev_local/engine/registry.py` -> `default_fast_ckpt` | [lineage](genclass-model-lineage.md) | +| `JEV_ENCODER` (`banded` / `reference`) | encoder choice | `jev_local/engine/encoder/engine.py`; set in `scripts/launch_run.sh` | [lineage](genclass-model-lineage.md) | +| `TIMEOUT` (default 1800 s per remote command) | VM helper | `scripts/vm.sh` | [build-test-release](runtime/build-test-release.md) | +| `GENCLASS_EXT` (unpacked extension dir) | extension e2e | `extension/test/e2e/fixtures.mjs` | [extension](extension-and-benchmarks.md) | + +### sim + +| X | kind | where | doc | +|---|---|---|---| +| Scenario from a seed; split assignment; held-out domains | function, constant | `sim/src/world/scenario.ts` -> `buildScenario`, `splitOf`, `TEST_DOMAINS` | [sim](sim.md) | +| One run (ideal or real runtime) | function | `sim/src/run/runner.ts` -> `runScenario` | [sim](sim.md) | +| Trajectory -> rows; counterfactual costs | function | `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts` | [sim](sim.md) | +| Run cost, cost weights, soft action label, tier premiums | function, constant | `sim/src/oracle/cost.ts` -> `runCost`, `W`, `actionLabel`, `LABEL`, `TIER` | [sim](sim.md) | +| Diagnosis labels | function | `sim/src/oracle/diagnose.ts` -> `diagnose` | [sim](sim.md) | +| Ground-truth bookkeeping | class | `sim/src/oracle/knowledge.ts` -> `Knowledge` | [sim](sim.md) | +| Virtual event loop | class | `sim/src/loop.ts` -> `VirtualLoop` | [sim](sim.md) | +| Seeded RNG with keyed forks | class | `sim/src/rng.ts` -> `Rng`, `hashAll` | [sim](sim.md) | +| Virtual network and ideal profile; sim op header | class, constant | `sim/src/net/network.ts` -> `Network`, `IDEAL_PROFILE`, `SIM_OP_HEADER` | [sim](sim.md) | +| Virtual server | class | `sim/src/net/server.ts` -> `VirtualServer` | [sim](sim.md) | +| Feature combinators and weights | constant | `sim/src/app/features/index.ts` -> `FEATURES`, `FEATURE_WEIGHTS` | [sim](sim.md) | +| 55 domain vocabularies | constant | `sim/src/app/vocab.ts` -> `DOMAINS` | [sim](sim.md) | +| Loading the real runtime; `createRuntime` options | function | `sim/src/run/rt.ts` -> `realRuntimeFactory`, `createOptions` | [sim](sim.md) | +| Fake runtime (test double; generator refuses it without `--allow-fake`) | function | `sim/src/run/fake-runtime.ts` -> `createFakeRuntime`; flag in `sim/src/gen.ts` | [sim](sim.md) | +| Ask questions | function | `sim/src/ask/questions.ts` -> `askQuestions` | [sim](sim.md) | +| Action-option shuffle/drop and paraphrases | function, constant | `sim/src/run/transform.ts` -> `transformQuestions`, `ACTION_PARA` | [sim](sim.md) | +| CONTRACT-D row type | type | `sim/src/types.ts` -> `Row`, `Label` | [model-io-contract](model-io-contract.md) | +| `node sim/dist/gen.js --rows N --out DIR ...` (`--sample`, `--parts`) (ask first) | CLI | `sim/src/gen.ts` -> `main` | [sim](sim.md) | +| `bash sim/scripts/final.sh a\|b\|merge-b` (VM; ask first) | command | `sim/scripts/final.sh` | [sim](sim.md) | + +### training and the Python reference + +| X | kind | where | doc | +|---|---|---|---| +| Curriculum row factory | function | `training/curriculum/generate.py` -> `make_row` | [training](training.md) | +| Scenario result dataclass | class | `training/curriculum/scenarios.py` -> `Scen` | [training](training.md) | +| Surface-variation templates | constant | `training/curriculum/fmt.py` -> `TEMPLATES`, `Style` | [training](training.md) | +| Curriculum domains (13 held out) | constant | `training/curriculum/vocab.py` -> `DOMAINS`, `TEST_DOMAINS` | [training](training.md) | +| Calibration fit and gate metrics | function | `training/eval_runtime.py` -> `fit_calibration`, `decision_metrics` | [training](training.md) | +| q8 / fp16 export | function | `training/export_runtime.py` -> `make_q8`, `make_fp16` | [training](training.md) | +| Vocabulary pruning | function | `training/prune_vocab.py` -> `prune_tokenizer_json` | [training](training.md) | +| Export check in onnxruntime-web WASM: `node validate.mjs <dir> [variant] [maxRequests]` | CLI | `training/ortweb/validate.mjs` | [training](training.md) | +| Mixture configs | config | `training/configs/mix_*.json`, read by `jev_local/train/stream.py` -> `MixConfig` | [training](training.md) | +| Row label -> training target; example encoding | function | `jev_local/train/train.py` -> `parse_target`, `encode_example` | [lineage](genclass-model-lineage.md) | +| Python serializer (reference for `model/serialize.ts`) | function | `jev_local/serialize.py` -> `state_segments`, `question_block` | [lineage](genclass-model-lineage.md) | +| Python packer (reference for `model/packer.ts`) | class | `jev_local/engine/encoder/tokenize_pack.py` -> `Packer` | [lineage](genclass-model-lineage.md) | +| Python calibration lookup (reference for `model/calibrate.ts`) | function | `jev_local/engine/encoder/calibrate.py` -> `header_key`, `tau_for` | [lineage](genclass-model-lineage.md) | +| Python answer math | function | `jev_local/confidence.py` -> `build_answer` | [lineage](genclass-model-lineage.md) | +| Decision heads | class | `jev_local/engine/encoder/heads.py` -> `DecisionHeads` | [lineage](genclass-model-lineage.md) | +| Python inference engine | class | `jev_local/engine/encoder/engine.py` -> `FastEngine` | [lineage](genclass-model-lineage.md) | +| ONNX graph definition (imported by the runtime exporter) | class | `scripts/genclass_export.py` -> `ExportModel` | [model-io-contract](model-io-contract.md) | +| Jev-wire HTTP server | function | `jev_local/server/app.py` -> `create_app` | [lineage](genclass-model-lineage.md) | + +### demos + +| X | kind | where | doc | +|---|---|---|---| +| Where the demos create the runtime | function | `demos/src/shared/genclass.ts` -> `startGenClass` | [demos](demos.md) | +| Mock-server session | class | `demos/src/server/core.ts` -> `World` | [demos](demos.md) | +| Chaos presets and per-route resolution | constant, function | `demos/src/shared/chaos.ts` -> `PRESETS`, `resolveChaos` | [demos](demos.md) | +| Clean-trial chaos | constant | `demos/src/shared/scenario-kit.ts` -> `CLEAN_CHAOS` | [demos](demos.md) | +| Trial harness | class | `demos/src/shared/harness.ts` -> `TrialHarness` | [demos](demos.md) | +| Aggregation (Wilson intervals, per-mode summary) | function | `demos/src/shared/aggregate.ts` -> `wilson`, `summarizeMode` | [demos](demos.md) | +| Demo page boot (mounts devtools; `?devtools=open`) | function | `demos/src/site/demo-page.ts` -> `bootDemo` | [demos](demos.md) | +| Demo mode type (`off`/`guard`/`heal`) | type | `demos/src/shared/types.ts` -> `GcMode` | [demos](demos.md) | +| `?trace=1` investigation tracing | URL param | `demos/src/shared/settings.ts` -> `traceOn`; `demos/src/shared/trace.ts` | [demos](demos.md) | +| Timers captured before `GenClass.init` | constant | `demos/src/shared/native.ts` -> `nativeSetTimeout` | [demos](demos.md) | +| Custom plugin example | function | `demos/src/demos/decisions/plugin.ts` -> `backgroundWorkPlugin` | [demos](demos.md) | +| `npm run eval` / `eval:fast` / `shots` (Playwright; ask first) | command | `demos/package.json` -> `scripts`; `demos/e2e/eval.ts` | [demos](demos.md) | + +## 4. Generated and ignored paths + +Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitignore` and `packages/runtime/test/browser/.gitignore`. The root rules `data/`, `models/`, `runs/`, `dist/` and `node_modules/` have no leading slash, so they match at any depth. + +| path | ignored by | produced by | notes | +|---|---|---|---| +| `node_modules/` (root) | root | `npm install` at the repo root (workspaces hoisted; about 134 packages) | `extension/` and `training/ortweb/` are not workspaces and need their own `npm install` | +| `package-lock.json` (root) | **not ignored** | `npm install` at the root | never committed; shows as untracked. Do not commit it unless asked | +| `packages/runtime/bin/genclass-runtime.mjs` mode change | — | `npm install` chmods it to 755 (committed mode 644) | shows as a modified file; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | +| `packages/runtime/dist/` | root `dist/` | `npx tsup` / `npm run build` (in `packages/runtime`); also `sim`'s `build:runtime-core` script and `packages/runtime/test/browser/build.mjs` (Playwright global setup) rewrite it | `sim` and `demos` import the runtime through this `dist/`; a working copy may hold a stale one | +| `sim/dist/` | root `dist/` | `npm run build` in `sim` (tsup: `gen`, `worker`, `index`, `smoke`) | — | +| `demos/dist/` | root and `demos/.gitignore` | `npm run build` in `demos` (`demos/scripts/build.mjs`) | — | +| `extension/dist/` | root and `extension/.gitignore` | `extension/scripts/build.mjs` (`dist/genclass/`) | — | +| `sim/out/` | root | `sim/src/gen.ts` (default `--out sim/out/run`), `sim/scripts/final.sh` (`sim/out/final-a/`, `sim/out/final-b/parts/`) | training data; excluded from `scripts/vm.sh` syncs | +| `.cache-model/` | root | `node packages/runtime/bin/genclass-runtime.mjs fetch-model .cache-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` (ask first: download; without `--from` the CLI uses the unpublished `DEFAULT_FROM`) | default `GENCLASS_MODEL_DIR`; absent in a fresh clone, so 14 model tests skip | +| `packages/runtime-model/files/` | root | intended for `training/export_runtime.py` output (the planned `@genclass/runtime-model` package) | does not exist at 654d822 | +| `demos/public/genclass-model/` | `demos/.gitignore` | `npm run fetch-model` in `demos` (`demos/scripts/fetch-model.sh`, v0.1 model) | — | +| `packages/runtime/test/browser/.build/` | `packages/runtime/test/browser/.gitignore` | `packages/runtime/test/browser/build.mjs` | bundled test app and build info | +| `test-results/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright (`packages/runtime/test-results/{browser,ui}`), model benchmarks (`packages/runtime/test-results/model-bench/`) | — | +| `playwright-report/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright HTML reporter | — | +| `demos/e2e/.out/` | `demos/.gitignore` | `demos/e2e/eval.ts` (`partial.json`, `traces*.json` with `--trace`) | input to `demos/e2e/trace-report.ts` | +| `*.tgz` | root | `npm pack` in `packages/runtime/test/smoke/smoke.sh` (left in `packages/runtime/`) | — | +| `.publish/` | root | no tracked script; added with the alpha publish (59c213f) | purpose not recorded | +| `.vite/` | root | Vite cache directory (no config in the repo sets `cacheDir`; Vite's default is `node_modules/.vite`) | — | +| `data/` (any depth) | root | not produced in this repo. Matches the missing `jev_local/data/` (data generators) and `demos/src/server/data/cities.ts`; Azure hosts keep training data under `$G/data/` | the rule hides source files that the code imports | +| `models/` (any depth) | root | `python -m jev_local.train.train --out models/<M>` (servable checkpoints); `training/prune_vocab.py --out` (on Azure, e.g. `models/r32-v16k`) | default `JEV_LOCAL_FAST_CKPT` is `<repo>/models/jev-local-fast`; none in the repo | +| `runs/` (any depth) | root | trainer state and logs (`runs/<run>/ckpt`, `log.jsonl`), `scripts/benchmax.py` (`runs/benchmax/...`), `scripts/bench_encoder.py`, `scripts/bench_decoder.py` | none in the repo | +| `extension/release-assets/*.onnx` | `extension/.gitignore` | `extension/tools/genclass_export.py` | absent | +| `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/` | root | Python venv, pytest, `pip install -e .` of `jev-local` | — | +| `.DS_Store` | root, `extension/.gitignore` | macOS Finder | — | +| `docs/agents/`, `AGENTS.md`, `CLAUDE.md` | not ignored | these agent docs | untracked at 654d822 | + +## 5. Large files: do not read in full + +Sizes from `wc -c` / `wc -l` at 654d822. "0 lines" means one line with no trailing newline: inspect it with `python3 -c` or `jq` (keys, lengths, one record) instead of opening it. + +| path | bytes | lines | what it is / how to read it | +|---|---|---|---| +| `extension/src/model/tokenizer.json` | 3,584,123 | 251,542 | HF tokenizer of the v0.1 model. Read keys only (`added_tokens`, `model.type`) | +| `extension/release-assets/tokenizer.json` | 3,584,123 | 251,542 | byte-identical copy of the above | +| `extension/test/fixtures/policy_py.json` | 3,069,755 | 0 | Python-harness policy parity fixture | +| `extension/test/fixtures/pack_fixtures.json` | 1,228,103 | 0 | Python packer output for the v0.1 requests | +| `packages/runtime/test/fixtures/model/pack_fixtures.json` | 955,379 | 0 | compact copy of the extension's pack fixtures; read through `packages/runtime/test/model/helpers.ts` -> `packs` | +| `sim/samples/sample.jsonl` | 848,581 | 200 | 200 CONTRACT-D rows (about 4 KB each); read one line, or `sim/samples/EXAMPLES.md` | +| `bench/public/targets.json` | 785,218 | 30,045 | 549 benchmax targets | +| `demos/results.json` | 773,038 | 39,384 | raw demo trials; read `demos/results.md` or `demos/results-summary.json` instead | +| `bench/public/jev_published.json` | 383,059 | 8,236 | 549 published Jev numbers | +| `extension/test/fixtures/requests50.json` | 346,737 | 9,399 | the 50 harness requests with `gold` and `screen_type` | +| `packages/runtime/test/fixtures/model/requests50.json` | 285,309 | 0 | the same 50 requests without `gold`/`screen_type` | +| `extension/test/fixtures/torch_fixtures.json` | 269,230 | 0 | PyTorch logits of the v0.1 model | +| `packages/runtime/test/fixtures/model/torch_fixtures.json` | 255,945 | 0 | compact copy of the above | +| `extension/test/fixtures/questions_py.json` | 222,955 | 16,984 | Python-harness question fixtures | +| `docs/benchmax-research/jev-published.md` | 217,513 | 2,206 | census of published Jev numbers | +| `packages/runtime/test/fixtures/model/py_fixtures.json` | 167,629 | 0 | Python reference cases for serialize/tokenize/calibrate/confidence | +| `jev_local/bench/registry.py` | 90,896 | 1,888 | jevbench dataset registry and exclusion rules (source; grep it) | +| `docs/SPEC.md` | 84,347 | 1,131 | legacy jev-local rebuild spec | +| `docs/benchmax-research/{PLAN,feasibility-targets,suite-reproduction-specs,train-data-and-supervised-ceilings}.md` | 72,630-93,641 each | 768-971 each | benchmax planning notes | +| `packages/runtime/src/runtime.ts` | 65,221 | 1,583 | `RuntimeImpl`; jump to methods by name (`trigger`, `onDecision`, `settled`) | +| `extension/test/fixtures/spans_py.json` | 59,806 | 5,458 | Python-harness span fixtures | +| `bench/public/exclusions.json` | 59,101 | 2,297 | benchmax exclusion manifest | +| `sim/samples/EXAMPLES.md` | 52,713 | 1,345 | pretty-printed sim rows | +| `scripts/benchmax_build_targets.py` | 52,170 | 671 | target/exclusion generator | +| `extension/package-lock.json` | 50,300 | 1,506 | extension lockfile | +| `packages/runtime/src/devtools/index.ts` | 49,689 | 1,291 | `Devtools` class; read by method | +| `jev_local/bench/benchmax/adapters_b/vendor/earino/val_indices.json` | 43,930 | 0 | vendored upstream indices | +| `docs/agents/*.md`, `docs/agents/runtime/*.md` (subsystem docs) | about 66,000-103,000 each | — | read the TL;DR, then the section you need | + +Binary files: 63 tracked PNGs (11,388,350 bytes in total: 18 devtools screenshots, 30 demo screenshots, 10 Chrome Web Store images, 5 extension icons) and 3 WAV clips under `extension/test/fixtures/audio/` (219,600 bytes). Model weights (`*.onnx`) are never tracked. + +Other source files over 25 KB that are better read by symbol than end to end: `packages/runtime/src/situation/facts.ts` (568 lines), `packages/runtime/src/model/host.ts` (752), `packages/runtime/src/observe/fetch.ts` (630), `packages/runtime/src/state/hub.ts` (734), `training/curriculum/rt.py` (829), `jev_local/train/train.py` (1,059), `jev_local/train/stream.py` (917), `docs/runtime/CONTRACT.md` (519), `packages/runtime/STATUS.md` (533). diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md new file mode 100644 index 00000000..794a1005 --- /dev/null +++ b/docs/agents/runtime/build-test-release.md @@ -0,0 +1,550 @@ +# Build, test and release (@genclass/runtime and the monorepo) + +> **Scope:** `package.json` (root), `tsconfig.base.json`, `.gitignore`, `packages/runtime/{package.json,tsconfig.json,tsup.config.ts,vitest.config.ts}`, `packages/runtime/test/**` (unit, model, browser, smoke, fixtures), `packages/runtime/STATUS.md` ("State" and "How to drive it headless"), `scripts/vm.sh`, `OPEN_TASKS.md` (packaging), `sim/package.json`, `demos/package.json`, `packages/runtime-model/`. +> **Read this when:** you need to build, typecheck or test the runtime; add or fix a test; regenerate fixtures; run the Playwright model/UI specs or the npm-pack smoke test; publish a version; add CI; or understand how `sim/` and `demos/` consume the runtime package. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- npm workspaces monorepo: `packages/*`, `sim`, `demos`. Root scripts only touch the runtime: `npm run build` / `npm test` run in `@genclass/runtime`; `npm run typecheck` runs every workspace's `typecheck` (`--if-present`). +- **Team rule: the Mac only edits files.** Every `npm install`, build, typecheck, vitest, Playwright, smoke test and model run happens on the Azure `train` VM through `scripts/vm.sh` in your own *slot* (the original Mac had 8 GB RAM). Stated in `scripts/vm.sh` (header) and `docs/runtime/CONTRACT.md` §0 rule 5. +- **Lead policy for agents (2026-10-07):** on machines other than that 8 GB Mac, `npm install`, typecheck, build and unit tests are light and verified to work locally. Ask the user before running the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). See [Where to run things](#where-to-run-things) and [Verified locally (2026-10-07)](#verified-locally-2026-10-07). +- Build = `tsup` (`packages/runtime/tsup.config.ts`): ESM only, 6 entries (`index`, 3 adapters, `devtools/index`, `worker`), `.d.ts` for all but the worker, `clean: true`, `splitting: true`. Output goes to `packages/runtime/dist/`, which `package.json` `exports` points at. +- Typecheck = `tsc -p tsconfig.json --noEmit` over `src/` only. **Test files are never type-checked.** +- Unit tests = vitest (`vitest run`), 37 files under `test/` and `test/model/`, 300 tests (UI 53, MODEL 62 per STATUS; the other 185 = CORE 142 + REVIEW 43). Default environment `node`; 5 files opt into `happy-dom` per file. Re-run on 2026-10-07 without a model directory: 286 passed, 14 skipped, about 2.4 s. +- Runtime unit tests run on a virtual clock (`test/helpers.ts` -> `FakeClock`), a virtual HTTP server (`FakeServer`) and a scripted model (`ScriptedDecider` / `ManualDecider`): no real time, no network, no model. Exceptions (wall-time perf checks, `loader.test.ts`'s real `browserClock`, model-file tests) are listed under gotchas. +- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). +- Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. +- `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. +- Released: `@genclass/runtime@0.1.0-alpha.0` on npm (org `genclass`, owner `meharpro`, dated 2026-10-08 in `OPEN_TASKS.md`), git tag `v0.1.0-alpha.0` on 654d822. No publish script, no `prepublishOnly`, **no CI workflow** (no `.github/`), and **no committed root `package-lock.json`** (only `extension/package-lock.json` is tracked). +- Planned: `@genclass/runtime-model@0.1.0` (the model files; the runtime's default CDN URL points at it) and then `@genclass/runtime@0.1.0`. `packages/runtime-model/` holds only `MODEL_CARD.md` today. +- `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. + +## Files + +| path | role | key contents / entry points | +|---|---|---| +| `package.json` | root, private `genclass-lib`, `"type": "module"` | workspaces `packages/*`, `sim`, `demos`; scripts `build`, `test`, `typecheck`; devDep `typescript ~5.9.3`; `engines.node >=20`; license Apache-2.0 | +| `tsconfig.base.json` | shared compiler options | see Configuration | +| `.gitignore` | ignores build and model artefacts | "GenClass runtime" block: `node_modules/`, `dist/`, `.vite/`, `test-results/`, `playwright-report/`, `sim/out/`, `packages/runtime-model/files/`, `.cache-model/`, `.publish/`, `*.tgz` (the last two added in 59c213f). Older Python block: `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/`, `data/`, `models/`, `runs/`, `dist/`, `node_modules/`, `.DS_Store`. `data/`, `models/`, `runs/` are unanchored (match at any depth). `package-lock.json` is **not** ignored | +| `package-lock.json` (root) | **not tracked** | never committed (`git log --all -- package-lock.json` is empty). A root `npm install` creates one that shows as untracked; it records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }` | +| `packages/runtime/package.json` | the published package | name `@genclass/runtime`, version `0.1.0-alpha.0`, `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | +| `packages/runtime/tsconfig.json` | typecheck project | extends base; `rootDir: src`, `outDir: dist`, `jsx: react-jsx`, `types: []`, `include: ["src"]` | +| `packages/runtime/tsup.config.ts` | build | entries, dts entries, externals | +| `packages/runtime/vitest.config.ts` | unit-test runner config | include `test/**/*.test.ts`, exclude `test/browser/**`, env `node`, `testTimeout 20000` | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (not built); committed with mode 100644, and a root `npm install` makes it 755 (see [Verified locally](#verified-locally-2026-10-07)) | `fetch-model <dir> [--from] [--variant q8\|fp16\|all] [--force] [--quiet]`, `info <dir>`; `DEFAULT_FROM` | +| `packages/runtime/test/helpers.ts` | core test kit | `drain`, `FakeClock`, `choice`, `ScriptedDecider`, `defaultScript`, `FakeServer`, `makeGlobal`, `setup`, `ManualDecider` | +| `packages/runtime/test/*.test.ts` | 31 unit test files (CORE, UI, REVIEW) | see Tests | +| `packages/runtime/test/model/helpers.ts` | model test kit | `PKG`, `FIX`, `MODEL_DIR`, `readJson`, `modelFile`, `hasModelFile`, `FIXTURES_FROM_MODEL`, `requests`, `packs`, `torch`, `exportParity`, `pyFixturesPath`, `pythonOnlyFloatRequests`, `questionsInPythonOrder`, `pruneTokenizer` (mirrors `prune_tokenizer()` in `make_py_fixtures.py`), `vocabDigest`, `isV01Tokenizer`; types `PackFixture`, `TorchFixture`, `RequestFixture` | +| `packages/runtime/test/model/*.test.ts` | 6 model test files (MODEL) | see Tests | +| `packages/runtime/test/fixtures/model/` | parity fixtures + their generators | see Fixtures | +| `packages/runtime/test/browser/playwright.config.ts` | model browser specs config | projects `chromium`, `swiftshader-webgpu`; `globalSetup: ./build.mjs` | +| `packages/runtime/test/browser/build.mjs` | Playwright global setup | builds the library, bundles `page/main.ts` + `worker.js` with esbuild into `.build/app/`, checks the worker URL pattern | +| `packages/runtime/test/browser/server.mjs` | static server for the specs | `startServer({ appDir, modelDir, models })`, `ortDistDir()`; routes `/app/`, `/model/`, `/ort/`, `/m/<name>/`, `/coi/...` | +| `packages/runtime/test/browser/page/{index.html,main.ts}` | test app driving the **built** library (`main.ts` is `// @ts-nocheck`, imports `createModelHost` from `"genclass-dist"`); `#state` reads `ready` once loaded | `window.GC.{create, ready, load, status, stats, events, evaluate, evaluateDetailed, measure, bench, dispose, cacheKeys, isolated}`. Test-only `create()` options stripped before `createModelHost`: `mockGpu` (`"f16"` or other: installs a fake `navigator.gpu` whose adapter cannot create a device), `workerUrl` (becomes a `workerFactory`), `noWorkerGlobal` (sets `window.Worker = undefined`). `cacheKeys(name = "genclass-runtime-v1")` | +| `packages/runtime/test/browser/model-helpers.ts` | spec helpers | `PKG`, `APP`, `MODEL_DIR`, `HAVE_MODEL` (`model.json` exists), `requests`/`packs`/`torch` (v0.1 fixtures, loaded only when `HAVE_MODEL`), `card`, `useServer`, `openApp`, page wrappers `create`/`ready`/`evaluate`/`evaluateDetailed`/`events`/`statusOf`, `fixtureRequest`, `compare`, `parityRun`, `PARITY_IDS`, `situation(size, seed)`, `QUESTIONS` (mutation diagnosis 8 labels + action 4 labels), `sizedRequest`, `median`, `benchSizes`, `saveResults`, `transferReport` | +| `packages/runtime/test/browser/model.spec.ts` | model host in headless Chromium (WASM) | 9 tests | +| `packages/runtime/test/browser/model-webgpu.spec.ts` | model host on SwiftShader WebGPU | adapter without `shader-f16` | +| `packages/runtime/test/browser/ui-devtools.spec.ts` | devtools overlay in a real browser + screenshots | writes `ui/screenshots/*.png` | +| `packages/runtime/test/browser/ui/playwright.config.ts` | UI specs config | `testMatch /ui-.*\.spec\.ts$/`, viewport 1280x800, DPR 2 | +| `packages/runtime/test/browser/ui/{mock-runtime,scenario,session,page}.ts` | UI fixtures, **also imported by unit tests** | `mock-runtime.ts`: `MockRuntime` (scripted `Runtime`, not the runtime), `MockClock`, `choice(probs)`, `makeDecision`, `makeAction`; `scenario.ts`: `loadScenario(rt, opts)`, `ScenarioOptions`; `session.ts`: `runStoreSession(opts)` (real `createRuntime` under virtual time), `Session`, `SessionOptions`, `VirtualClock`, `realTurn`, `READY` (a `ModelStatus`), `SessionDecider` (rule-based test decider); `page.ts`: `window.__gc` | +| `packages/runtime/test/browser/ui/screenshots/` | 18 committed PNGs | `{pill,overlay,interventions,evidence,evidence-answers,detections,activity,now,loading}-{light,dark}.png` | +| `packages/runtime/test/browser/.gitignore` | ignores `.build/` | build output of `build.mjs` | +| `packages/runtime/test/smoke/smoke.sh` | npm-pack smoke test | run from `packages/runtime` | +| `packages/runtime/STATUS.md` | CORE status + headless recipe | last measured: 37 files / 300 tests passing | +| `packages/runtime-model/MODEL_CARD.md` | only file of the planned `@genclass/runtime-model` package | no `package.json` yet, so not a workspace | +| `scripts/vm.sh` | VM helper | `sync`, `run`, `exec`, `get` | +| `sim/package.json`, `demos/package.json` | consumers of the runtime | `"@genclass/runtime": "*"`; scripts listed under "How `sim` and `demos` consume the runtime" | + +## Concepts and data structures + +| term | meaning | +|---|---| +| workstream | team role that owns files: lead, CORE (runtime core + most tests), MODEL (`src/model/**`, `bin/`, `test/model/`, model browser specs), UI (`src/devtools/**`, `src/adapters/**` per CONTRACT §13, their tests, `test/browser/ui/`), SIM, DEMOS, TRAIN, REVIEW (`test/review-*.test.ts`) | +| slot | your directory on the VM, `~/gcl/<SLOT>`; name must match `[a-zA-Z0-9_-]+`; conventional names `core`, `model`, `sim`, `demos` | +| model directory | a folder with `model.json` (card format `genclass-runtime-model/1` or the v0.1 extension card), the ONNX variants, `tokenizer.json`, `calibration.json`, `meta.json`. Fetched with `genclass-runtime fetch-model`. Tests read it from `GENCLASS_MODEL_DIR` | +| v0.1 fixture set | `test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests (ids like `cu-004219-f`) with the Python packer output and PyTorch logits of the **v0.1 GenClass model** | +| model-dir fixture set | `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` (+ `parity.json`) written next to an export by `training/export_runtime.py`. `test/model/helpers.ts` -> `FIXTURES_FROM_MODEL` is true when all three exist in `MODEL_DIR`; then the unit parity tests use them instead of the v0.1 set | +| parity | TS port output (packer, tokenizer, serializer, calibration, engine) equals the Python/PyTorch reference on fixtures | +| review test | `test/review-*.test.ts`: written by REVIEW as bug demonstrations ("A failing test demonstrates a bug"); STATUS records they pass **unmodified** | +| package build vs model-entries build | `build.mjs` -> `buildLibrary`: uses the real `npx tsup` output (`mode: "package"`) when every tsup entry file exists and `dist/index.js` mentions `createModelHost`; otherwise builds only `src/model/index.ts` + `src/model/worker.ts` into `.build/dist` (`mode: "model-entries"`) | +| worker URL pattern | the literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `src/model/host.ts` -> `defaultWorkerFactory` that app bundlers key on (its sibling `defaultOrtLoader` holds the two literal calls `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`); `build.mjs` -> `WORKER_URL_RE` asserts it survives both builds | +| `situation-v1` | annotated git tag on 1a77558 ("Frozen runtime situation format for model training"); SIM training data was generated from it | +| `v0.1.0-alpha.0` | annotated git tag on 654d822 ("@genclass/runtime 0.1.0-alpha.0 (npm)") | + +Test-kit types (exact names, `test/helpers.ts`): + +```ts +class FakeClock implements Clock { t = 1000; now(); setTimeout(fn, ms); clearTimeout(h); afterTask(fn); + get pending(): number; flush(): Promise<void>; advance(ms): Promise<void>; runAll(maxMs = 120_000): Promise<void> } +interface Route { status?: number; body?: unknown; latency?: number; error?: "network"; headers?: Record<string, string> } +class FakeServer { routes; hits: Map<string, number>; log: { method; path; t }[]; on(method, path, Route | Handler): this; fetch } +interface Setup { clock: FakeClock; server: FakeServer; g: Record<string, unknown>; decider: ScriptedDecider; rt: RuntimeImpl; fetch } +function setup(opts?: Partial<CreateOptions> & { script?: Script; extraGlobal?: Record<string, unknown> }): Setup +function defaultScript(pick?: Partial<Record<string /* trigger */, { diagnosis: string; action?: string; p?: number }>>): Script +// default: diagnosis "expected"; action falls back to the first (passive) label; extra questions: noul 0.9, +// choice = first label, score = uniform +class ScriptedDecider implements DecisionProvider { status = { state: "ready", model: "scripted" }; calls: EvaluateRequest[]; script: Script } +class ManualDecider implements DecisionProvider { status = { state: "ready", model: "manual" }; pending: { req; resolve; reject }[]; + answer(script = defaultScript()): EvaluateRequest /* throws "nothing pending" */ } +``` + +`setup()` spreads your options **after** its defaults, so `setup({ decider: manual })` replaces the decider passed to `createRuntime`, but the returned `decider` field is still the unused `ScriptedDecider`; keep your own reference to `manual`. `FakeServer.fetch` honours `init.signal` (rejects with `signal.reason`), reads only string bodies, and `error: "network"` rejects with `TypeError("Failed to fetch")`. + +Per-file fakes outside `test/helpers.ts` (copy these when testing the same area): + +| fake | file | what it replaces | +|---|---|---| +| `FakeClock` (own copy, `t = 0`) + `FakeWorker implements WorkerLike` | `test/model/host.test.ts` | clock and the worker boundary (`emit({ type: "hello" \| "status" \| "result" })`) for `createModelHost` | +| `FakeCache`, `FakeCacheStorage`, `modelDir()`, `fakeOrt()`, `NO_GPU`/`GPU_F16` (`GpuInfo`) | `test/model/loader.test.ts` | Cache Storage, a synthetic model directory with its fetch, ORT, GPU probe. Uses the **real** `browserClock` | +| `fakeOrt: OrtLike` (`Tensor`, `InferenceSession.create`, `env.wasm`) + a byte-level BPE `tokJson` | `test/model/engine.test.ts` ("engine graph contract") | ORT, for the model-free graph-contract test | +| local `setup()` with `observe: { fetch: true }` only (other observers at their defaults) | `test/smoke.test.ts` | the shared `setup()` | +| `OFF` observer map + `createRuntime({ global: window, ... })` | `test/dom.test.ts`, `test/review-dom.test.ts` | happy-dom `window` as the instrumented global | +| `makeFakeXHR(clock, handler)` / `makeXHR(clockRef, handler)` | `test/xhr.test.ts` / `test/review-xhr.test.ts` | an `XMLHttpRequest` class passed with `setup({ observe: ..., extraGlobal: { XMLHttpRequest } })`; both use `observe: { fetch: false, xhr: true }` (`XHR_ONLY` in `review-xhr.test.ts`); a passed `observe` replaces setup's map, so unlisted observers fall back to their defaults | +| `timerWorld()` (global whose `setTimeout` queues callbacks run by hand) | `test/review-timers.test.ts` | the timers observer's host global | +| `MockRuntime` / `runStoreSession` | `test/browser/ui/*` | the runtime (devtools and adapter tests) | + +Fixture record types (`test/model/helpers.ts`): + +```ts +interface RequestFixture { id: string; state: Record<string, unknown>; questions: Record<string, { type: string; instructions?: unknown; criteria?: unknown }> } +interface PackFixture { id: string; input_ids: number[]; position_ids: number[]; q_group: number[]; i_group: number[]; n_state: number; + q_index: Record<string, { kind: string; header: string; labels: string[]; q_pos: number; item_pos: number[] }> } +interface TorchFixture { id: string; logits: Record<string, number[]>; probs: Record<string, number[]>; header_key: Record<string, string> } +``` + +## How it works + +### Build (`npm run build` -> `tsup`) + +1. tsup reads `packages/runtime/tsup.config.ts`; `clean: true` empties `dist/` first. +2. Bundles the 6 entries as ESM (`target es2022`, `platform browser`, `splitting`, `treeshake`, `sourcemap`), leaving `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand` external. `onnxruntime-web/wasm` is not listed, but tsup also externalises every `dependencies`/`peerDependencies` entry and its subpaths (`^dep($|/)`), so it stays external too; `build.mjs` asserts `import("onnxruntime-web/wasm")` and `import("onnxruntime-web/webgpu")` stay dynamic imports in `dist/worker.js` or its `chunk-*.js`. +3. Emits `.d.ts` for the 5 dts entries (not the worker). + +| tsup entry key | source | output | types | `exports` subpath | +|---|---|---|---|---| +| `index` | `src/index.ts` | `dist/index.js` | `dist/index.d.ts` | `.` (also `main`, `module`, `types`) | +| `adapters/react` | `src/adapters/react.ts` | `dist/adapters/react.js` | `dist/adapters/react.d.ts` | `./react` | +| `adapters/redux` | `src/adapters/redux.ts` | `dist/adapters/redux.js` | `.d.ts` | `./redux` | +| `adapters/zustand` | `src/adapters/zustand.ts` | `dist/adapters/zustand.js` | `.d.ts` | `./zustand` | +| `devtools/index` | `src/devtools/index.ts` | `dist/devtools/index.js` | `.d.ts` | `./devtools` | +| `worker` | `src/model/worker.ts` | `dist/worker.js` | none | `./worker` (`import` only) | + +Plus shared `chunk-*.js` files (code splitting) and `.map` files. `exports` also exposes `./package.json`. Only `import` conditions exist: the package is ESM-only (no `require`). The tarball contains `files: ["dist", "bin", "README.md", "LICENSE"]` (+ `package.json`). `bin.genclass-runtime` = `./bin/genclass-runtime.mjs` (plain Node >= 20 ESM, no dependencies, not built). + +### Unit tests (`npm test` -> `vitest run`) + +1. vitest collects `test/**/*.test.ts` minus `test/browser/**` (37 files). It transpiles TS without type-checking. +2. Each file runs in `node` unless its first line is `// @vitest-environment happy-dom` (`adapters-react`, `devtools`, `devtools-runtime`, `dom`, `review-dom`). +3. A typical test calls `setup()`: builds `FakeClock` + `FakeServer` + `makeGlobal(server)` + `ScriptedDecider`, then `createRuntime({ clock, global: g, decider, report: "silent", observe: { fetch: true, all others false }, ...rest })` and casts to `RuntimeImpl` (so tests can reach `rt.hub`, `rt.ops`, `rt.ctx`, `rt.cache`, `rt.miner`, `rt.internals`). +4. The test drives the app through `rt.user(...)`, `rt.op(...)`, atoms and `fetch`, then advances virtual time: `await clock.advance(ms)` runs due timers in order, each followed by `flush()`; `flush()` drains microtasks with 4 real `setImmediate` turns (`drain`), runs `afterTask` hooks, and repeats up to 50 times. +5. The decider answers at once (an already-resolved promise) from a script (`ScriptedDecider`, records `calls`; `script` can be reassigned mid-test) or when the test calls `ManualDecider.answer(script?)` (oldest pending first). +6. Assertions read `decider.calls[i].state` (the situation), `rt.decisions()`, `rt.interventions()`, `rt.history()`, `server.hits` / `server.log`. +7. Model tests (`test/model/`) read fixtures through `test/model/helpers.ts`; parts that need model files use `describe.skipIf(!hasModelFile(...))` / `it.skipIf`. The 14 model-file tests: `calibrate.test.ts` 1 (`calibration.json`), `engine.test.ts` 3 (`model.json` + `tokenizer.json` + the variant file), `packer.test.ts` 10 (`tokenizer.json`; the 2 HF edge-case tests also need `isV01Tokenizer`). The `py_fixtures.json` blocks skip only if that committed file is missing. + +### Headless runtime recipe (STATUS "How to drive it headless") + +What `setup()` does is the minimal form of the recipe SIM and tests use. `packages/runtime/STATUS.md` gives the full form; options are defined in `src/types.ts` -> `CreateOptions` / `InitOptions` (see [public-api-and-lifecycle.md](public-api-and-lifecycle.md)): + +```ts +createRuntime({ clock, global, decider, // injected Clock, instrumented global, DecisionProvider + observe: { fetch: true, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false }, + mode: "heal", triage: "salient", report: "silent", + policy: { thresholds: { report: 0, guard: 0, heal: 0 }, holdBudgetMs: 1e9, maxActionsPerMinute: 1e9, requireDiagnosis: false }, + situation: { budget: 1000 }, // sample budgets 1000/1333/2000/3200; <= 1400 = compact questions + hooks: { opCreated(op) {}, mutationProposed(m) {} }, vocabulary: { diagnoses: {}, actions: {} } }); +``` + +Facts STATUS records for this mode (checked against `src/runtime.ts` -> `installObservers` / `consultable` / `trigger`): `global.fetch` is replaced at construction and `rt.destroy()` restores every wrapped global; `observe` defaults to every observer on except `timers`, which is on only when `global.document` exists (`src/runtime.ts`); the decider is consulted only while `status.state === "ready"`; `app` comes from `CreateOptions.app()` or `document.title` + `location.pathname` (hence `/search` in tests); same inputs give byte-identical situations at any budget. + +### Browser model specs (`npm run test:browser`) + +1. Playwright loads `test/browser/playwright.config.ts`; `globalSetup` = `build.mjs`. +2. `build.mjs` -> `buildLibrary`: `fullBuildPossible()` regex-scans `tsup.config.ts` for `"src/...ts"` strings and checks each file exists; then runs `npx tsup` in `packages/runtime` (**this rewrites `packages/runtime/dist/`**), checks the worker URL pattern and the two ORT dynamic imports, and uses `dist/` if `dist/index.js` contains `createModelHost`; else falls back to the model-entries build in `.build/dist`. +3. esbuild bundles `page/main.ts` (importing `"genclass-dist"`, aliased to the chosen `index.js`) and `worker.js` into `test/browser/.build/app/` with code splitting (`chunks/[name]-[hash]`), copies `page/index.html`, asserts that some app JS output (page bundle or a chunk) still contains the worker URL pattern, and writes `.build/app-files.json` (which chunk holds which ORT bundle) and `.build/build-info.json`. +4. Each spec starts `server.mjs` on `127.0.0.1:<random port>` serving the app, `MODEL_DIR` at `/model/`, onnxruntime-web's `dist/` at `/ort/` (`ortDistDir()` resolves `onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm`, since `onnxruntime-web/package.json` is not exported), extra model dirs at `/m/<name>/`, and the same under `/coi/` with COOP `same-origin` / COEP `require-corp` (cross-origin isolated, WASM threads). Every response carries `Cross-Origin-Resource-Policy: cross-origin`, `Access-Control-Allow-Origin: *` and `Cache-Control: no-store`; paths escaping a root get 403. It logs every request (`{ path, t }`) so specs can count downloads (`useServer().served(re)`); `openApp` waits for `#state` = `ready` and collects console + page errors. +5. Specs drive `window.GC` in the page, compare answers with PyTorch probabilities from the v0.1 fixtures (`compare`, `parityRun`: `model.spec.ts` uses the default `PARITY_IDS = [0, 7, 13, 21, 29, 36, 42, 49]`, `model-webgpu.spec.ts` passes `[0, 13, 29, 49]`), and merge numbers into `packages/runtime/test-results/model-bench/{latency,transfer}.json` (`saveResults`). + +### Browser UI spec + +1. `npx playwright test --config test/browser/ui/playwright.config.ts` (from `packages/runtime`; the file header shows the repo-root form `--config packages/runtime/test/browser/ui/playwright.config.ts`). No global setup, no model. +2. `ui-devtools.spec.ts` bundles `ui/page.ts` with esbuild (it imports `src/devtools/index.ts` and, through `session.ts`, `src/index.ts` directly, so no `dist/` build is needed; IIFE, `external: ["onnxruntime-web", "onnxruntime-web/webgpu"]`), inlines `@fontsource-variable/inter/files/inter-latin-wght-normal.woff2` and `@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-normal.woff2` as base64 from `<repo>/node_modules` (installed by the **demos** workspace), and loads the HTML with `page.setContent` after `emulateMedia({ colorScheme, reducedMotion: "reduce" })`. +3. `window.__gc.start({ scenario })`: `live` (default) = real runtime via `runStoreSession()`; `loading` = real runtime, model status loading; `mock` = `MockRuntime` + `loadScenario`; `empty`. +4. Tests check style isolation, keyboard, undo, then write screenshots to `test/browser/ui/screenshots/`. + +### Smoke test (`bash test/smoke/smoke.sh`, from `packages/runtime`) + +1. `npm run build`, then `npm pack` -> `<pkg>/genclass-runtime-0.1.0-alpha.0.tgz` (name from npm's scoped-package convention; gitignored as `*.tgz`). +2. Creates a temp Vite app (`mktemp -d`/app) whose `src/main.js` calls `GenClass.init({ model: false, report: "console" })`, creates atom `search.results`, wires an input to a `data:` URL fetch, and calls `mountDevtools(rt)`. +3. `npm install` the tarball + `vite@8` + `@playwright/test@1.63.0` (needs registry access), `npx vite build`. +4. `check.mjs` serves `dist/` on port `4191` (plain `node:http`), opens it in Chromium (`chromium.launch()` from the app's `@playwright/test`), waits for `window.__smoke.ok`, `p.fill("#q", "rea")`, waits for `#out` to read `rea-1`, prints one JSON line `{ info: { status, events, devtools }, errs }`, and exits 1 unless there are no page errors / console errors, `genclass-devtools` exists, and `rt.history().length >= 3` (`status` is printed, not asserted). Then prints `SMOKE OK: <tgz>`. +5. Leftovers: the `.tgz` stays in `packages/runtime/` and the `mktemp -d` app is not deleted. The script never runs `playwright install`: Chromium for Playwright `1.63.0` must already be in the Playwright browser cache on the machine (how the VM got it is not recorded in the repo). + +### VM workflow (`scripts/vm.sh`) + +1. Reads the `train` host IP from `~/.jev-local/azure_hosts` (line `train <ip>`), key `~/.ssh/jev_azure`, user `azureuser`, ssh options `StrictHostKeyChecking=accept-new`, `ConnectTimeout=20`, `ServerAliveInterval=30`, `ServerAliveCountMax=6`. Exits 2 if the host line is missing, the slot name has characters outside `[a-zA-Z0-9_-]`, or the subcommand is unknown. Every step is wrapped in GNU `timeout` (see Configuration). The sibling `scripts/azvm.sh HOST ...` uses the same hosts file and key for the other jev VMs (out of scope here). +2. `sync SLOT`: `ssh mkdir -p gcl/SLOT`, then `rsync -az --delete` the repo to `~/gcl/SLOT/`, excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out/`, `.cache-model/`. Excluded paths on the VM are kept (rsync does not delete excluded files without `--delete-excluded`), so `node_modules`, `dist` and model caches survive syncs. +3. `run SLOT 'cmd'` = sync + remote; `exec SLOT 'cmd'` = remote only; remote runs `export PATH=$HOME/node/bin:$PATH; cd ~/gcl/SLOT && cmd` (Node 22 per the header and CONTRACT §0 rule 6). +4. `get SLOT REMOTE LOCAL`: `scp -r` from `~/gcl/SLOT/REMOTE`. + +### How `sim` and `demos` consume the runtime + +npm workspaces symlink `node_modules/@genclass/runtime` -> `packages/runtime`, so every import goes through `packages/runtime/package.json` `exports` -> `dist/`. + +| consumer | dependency | how it resolves | build requirement | escape hatch | +|---|---|---|---|---| +| `sim` (`@genclass/sim`, private) | `"@genclass/runtime": "*"` | dynamic `import(process.env.GENCLASS_RUNTIME ?? "@genclass/runtime")` in `sim/src/run/rt.ts` -> `realRuntimeFactory`; `sim/tsup.config.ts` leaves `@genclass/runtime` external | `npm run build:runtime-core` (in `sim`: tsup of `src/index.ts` only, `--no-config --platform neutral`, no dts, into `packages/runtime/dist`) or the full runtime build | `SIM_RUNTIME=real` runs sim tests on the real runtime; otherwise they use the fake (`sim/test/helpers.ts`); `GENCLASS_RUNTIME=<specifier>` loads another build | +| `demos` (`@genclass/demos`, private) | `"@genclass/runtime": "*"` plus `react`, `redux`, `zustand`, `@fontsource-variable/*` | Vite resolves `exports` -> `dist/` | full runtime build (`demos/scripts/vm-eval.sh` runs `npm run build -w @genclass/runtime` and stops if it fails) | `GENCLASS_SHIM=1` (or a missing `packages/runtime/dist/index.js`) aliases `demos/src/dev/runtime-shim/*` in `demos/vite.config.ts`; `GENCLASS_SHIM=0` forces the real one; `npm run typecheck:shim` | +| `packages/runtime` UI spec | demos' hoisted deps | `<repo>/node_modules/@fontsource-variable/*` | root `npm install` | none | + +`sim` does **not** need `dist/` to typecheck: `sim/src/types.ts` is a structural mirror of the runtime's model seam and the only runtime import is the dynamic one in `sim/src/run/rt.ts`. `demos` typecheck does need `dist/*.d.ts` (or `typecheck:shim`, whose `demos/tsconfig.shim.json` maps `@genclass/runtime` and its `/react`, `/redux`, `/zustand`, `/devtools` subpaths to `src/dev/runtime-shim/{index,react,redux,zustand,devtools}.ts`; `/worker` is not mapped). + +Workspace scripts (verbatim from the `package.json` files): + +| workspace | script | command | +|---|---|---| +| root | `build` / `test` / `typecheck` | `npm run build -w @genclass/runtime` / `npm test -w @genclass/runtime` / `npm run typecheck --workspaces --if-present` | +| `@genclass/runtime` | `build` / `typecheck` / `test` / `test:browser` | `tsup` / `tsc -p tsconfig.json --noEmit` / `vitest run` / `playwright test --config test/browser/playwright.config.ts` | +| `@genclass/sim` (`0.0.0`, private, bin `genclass-sim` = `./dist/gen.js`) | `build`, `typecheck`, `test` | `tsup` (entries `gen`, `worker`, `index`, `smoke`; `node22`; `@genclass/runtime` external), `tsc -p tsconfig.json --noEmit`, `vitest run` | +| | `gen` / `sample` | `node dist/gen.js` / `node dist/gen.js --sample` | +| | `build:runtime-core` | `cd ../packages/runtime && tsup src/index.ts --no-config --format esm --target es2022 --platform neutral --out-dir dist --external onnxruntime-web --external onnxruntime-web/webgpu --sourcemap` | +| `@genclass/demos` (`0.1.0`, private) | `dev` / `build` / `preview` | `vite` / `node scripts/build.mjs` / `node --experimental-strip-types e2e/serve.ts dist --base /genclass/ --port 4173` | +| | `typecheck` / `typecheck:shim` | `tsc -p tsconfig.json` (or `tsconfig.shim.json`) `--noEmit && tsc -p tsconfig.sw.json --noEmit && tsc -p tsconfig.node.json --noEmit` | +| | `fetch-model` | `bash scripts/fetch-model.sh public/genclass-model` | +| | `eval` / `eval:fast` / `shots` | `node --experimental-strip-types e2e/eval.ts` (`--fast` / `--shots-only`) | + +Demos devDeps pin the same `@playwright/test` `1.63.0` as the runtime and use `vite ^8.3.3`. + +Details: [../sim.md](../sim.md), [../demos.md](../demos.md). + +### Exact commands + +```sh +# on the VM, through your slot (from the repo root on the Mac) +scripts/vm.sh run core 'npm install && npm run build' +scripts/vm.sh exec core 'npm run typecheck -w @genclass/runtime' # or: cd packages/runtime && npx tsc -p tsconfig.json --noEmit +scripts/vm.sh exec core 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl/model/.cache-model NODE_OPTIONS=--expose-gc npx vitest run' +scripts/vm.sh exec core 'cd packages/runtime && npx vitest run test/atoms.test.ts -t "late discard"' # one file / one test +scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx vitest run test/model' +scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npm run test:browser' # add --project chromium | swiftshader-webgpu +scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/browser/playwright.config.ts model.spec.ts -g "inline fallback"' # one spec / one test +scripts/vm.sh exec core 'cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts' +scripts/vm.sh exec core 'cd packages/runtime && bash test/smoke/smoke.sh' +scripts/vm.sh exec core 'cd packages/runtime && npm pack --dry-run' # list tarball contents (files: dist, bin, README.md, LICENSE) +scripts/vm.sh exec sim 'npm run build && cd sim && SIM_RUNTIME=real npx vitest run' # sim tests against the real runtime +# one-time per machine (not in any repo script; unverified that the VM needed it): npx playwright install chromium +# fetch the v0.1 model for the model tests (command from packages/runtime/src/model/README.md; default --variant all) +scripts/vm.sh exec model 'node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/' +``` + +The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runtime/STATUS.md` and `packages/runtime/src/model/README.md`; which of them exists on the VM is unverified. + +### Where to run things + +- **Team rule** (`docs/runtime/CONTRACT.md` §0 rule 5, `scripts/vm.sh` header): the Mac only edits files; every build, test, browser and model run goes through `scripts/vm.sh` on the `train` VM. The reason is RAM: the original author's Mac has 8 GB. +- **Lead policy for agents (2026-10-07):** on any other machine, run these locally; they are light and were verified (next section): + - `npm install` at the repo root; + - typecheck and build of `packages/runtime`; + - the runtime unit tests (vitest, browser specs excluded). +- **Ask the user first** before running any of: + - the sim (`sim/` generation or tests, `sim/scripts/*`); + - training (`training/*.sh`, Python training or tests); + - Playwright (`npm run test:browser`, the UI spec, `test/smoke/smoke.sh`, which also installs from the npm registry); + - model downloads (`genclass-runtime fetch-model`, `demos/scripts/fetch-model.sh`); + - the demos' eval (`demos/scripts/vm-eval.sh`, `npm run eval` in `demos`); + - any script that touches Azure (`scripts/*.sh`, including `scripts/vm.sh`). +- On the original 8 GB Mac, the team rule still applies. + +### Verified locally (2026-10-07) + +These were run at 654d822, when these docs were written, on a macOS machine (16 GB RAM, 10 CPUs, Node v25.6.0, npm 11.8.0): + +| step | command (directory) | result | time | +|---|---|---|---| +| install | `npm install` (repo root) | OK, 134 packages; one EBADENGINE warning (below) | ~18 s | +| typecheck | `npx tsc -p tsconfig.json --noEmit` (`packages/runtime`) | clean | ~1.6 s | +| build | `npx tsup` (`packages/runtime`) | 6 entries (`index`, `adapters/react`, `adapters/redux`, `adapters/zustand`, `devtools/index`, `worker`), `.d.ts` for all but `worker`; `dist/` ~1.6 MB including source maps; largest JS chunk ~258 KB and `dist/devtools/index.js` ~68 KB, both unminified | ~2.5 s | +| unit tests | `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (`packages/runtime`) | Test Files 36 passed \| 1 skipped (37); Tests 286 passed \| 14 skipped (300) | ~2.4 s | + +- **The 14 skipped tests** are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`), which did not exist on that machine: + - `test/model/packer.test.ts`: all 10 (the one fully skipped file); + - `test/model/engine.test.ts`: 3 of 4; + - `test/model/calibrate.test.ts`: 1 of 8. + + With a model directory present (as on the VM, per STATUS) all 300 pass. Getting one means a model download: ask the user first. +- **EBADENGINE warning.** `vitest@5.0.3` declares `engines.node` `^22.12.0 || ^24.0.0 || >=26.0.0`. Node 25 is outside that range, so npm warns, but the tests run. Node 22.x from 22.12, 24.x and 26+ are inside it; 23.x and 25.x are not. The VM runs Node 22, but the repo does not record its minor version. +- **Install side effects.** The root `npm install` changes two things git sees: + - It creates an untracked root `package-lock.json`, because the repo has never committed one. Do not commit it unless the lead decides to (see "No committed lockfile" under gotchas). Delete it, or leave it untracked. + - It chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, so `git status` reports a mode change from the committed 100644. Revert it with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. +- **Not run in that pass:** + - Playwright browser specs (main and UI configs); + - `test/smoke/smoke.sh`; + - the sim, training, the demos, Python tests, model downloads, anything on Azure. +- **No CI** re-runs any of this: there is no `.github/` directory. + +## Configuration and constants + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `target` / `module` / `moduleResolution` | tsc | `ES2022` / `ESNext` / `Bundler` | `tsconfig.base.json` | ESM, bundler-style resolution (uses `exports`) | +| `lib` | tsc | `ES2022, DOM, DOM.Iterable, WebWorker` | `tsconfig.base.json` | browser + worker globals | +| `strict`, `noImplicitOverride`, `isolatedModules`, `verbatimModuleSyntax` | tsc | `true` | `tsconfig.base.json` | type-only imports must use `import type` | +| `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` | tsc | `false` | `tsconfig.base.json` | | +| `declaration`, `sourceMap`, `resolveJsonModule`, `esModuleInterop`, `skipLibCheck`, `useDefineForClassFields` | tsc | `true` | `tsconfig.base.json` | | +| `types` | tsc | `[]` | `packages/runtime/tsconfig.json` | no `@types/node` in `src/`: src must not use Node APIs | +| `include` | tsc | `["src"]` | `packages/runtime/tsconfig.json` | tests are not type-checked | +| `jsx` | tsc | `react-jsx` | `packages/runtime/tsconfig.json` | | +| tsup `format` / `target` / `platform` | build | `["esm"]` / `es2022` / `browser` | `tsup.config.ts` | | +| tsup `splitting` / `treeshake` / `sourcemap` / `clean` | build | `true` | `tsup.config.ts` | `clean` wipes `dist/` at build start | +| tsup `external` | build | `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand` | `tsup.config.ts` | | +| vitest `include` / `exclude` | test | `test/**/*.test.ts` / `test/browser/**` | `vitest.config.ts` | | +| vitest `environment` / `testTimeout` | test | `node` / `20000` ms | `vitest.config.ts` | per-file override for happy-dom; model tests set `600_000` / `900_000` | +| Playwright `timeout` / `expect.timeout` | test | `600_000` / `30_000` ms | `test/browser/playwright.config.ts` | | +| Playwright `workers` / `fullyParallel` | test | `1` / `false` | both configs (`fullyParallel` main only) | serial | +| Playwright projects | test | `chromium` (ignores `*webgpu.spec.ts`); `swiftshader-webgpu` (matches it; args `--enable-unsafe-webgpu --enable-unsafe-swiftshader --use-webgpu-adapter=swiftshader`) | `test/browser/playwright.config.ts` | | +| Playwright `outputDir` | test | `packages/runtime/test-results/browser` / `.../test-results/ui` | main / UI config | | +| UI config `timeout`, viewport, DPR | test | `90_000` ms, 1280x800, `deviceScaleFactor: 2` | `test/browser/ui/playwright.config.ts` | screenshot geometry | +| `FakeClock.t` start | test | `1000` | `test/helpers.ts` | facts/timelines in tests are relative to it | +| `drain(rounds)` / `flush` loop / `runAll(maxMs)` | test | `4` / `50` / `120_000` | `test/helpers.ts` | | +| `FakeServer` defaults | test | latency `50` ms, status `200`, JSON body, unknown route -> `404 {"error":"not found"}`, base `http://app.test/` | `test/helpers.ts` | routing key is `METHOD pathname` (query ignored) | +| `makeGlobal` location | test | `http://app.test/search` (pathname `/search`) | `test/helpers.ts` | why situations say `app: /search` | +| `choice(label, labels, p)` | test | `p = 0.97`; rest split evenly; confidence `(k*p - 1)/(k - 1)` | `test/helpers.ts` | | +| `PARITY_IDS` | test | `[0, 7, 13, 21, 29, 36, 42, 49]` | `test/browser/model-helpers.ts` | browser parity requests | +| model test `MODEL_DIR` | env | `$GENCLASS_MODEL_DIR` else `<repo>/.cache-model` | `test/model/helpers.ts`, `test/browser/model-helpers.ts` | | +| `vm.sh` `TIMEOUT` | env | `1800` s (remote cmd); sync mkdir `300` s, rsync `600` s, scp `600` s, ssh `ConnectTimeout=20` | `scripts/vm.sh` | | +| smoke port / versions | script | `4191`; `vite@8`; `@playwright/test@1.63.0` | `test/smoke/smoke.sh` | | +| `@playwright/test` | devDep | `1.63.0` (exact) | `packages/runtime/package.json` | Chromium build must match | +| other devDeps | devDep | `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `tsup ^8.5.1`, `vitest ^5.0.3`, `typescript ~5.9.3`, `react`/`react-dom ^19.3.0`, `@types/react`/`@types/react-dom ^19.0.0`, `redux ^5.0.1`, `zustand ^5.0.15` | `packages/runtime/package.json` | | +| `dependencies` | dep | `onnxruntime-web ^1.30.0` (only runtime dependency; CONTRACT §0 rule 6 forbids others without the lead) | `packages/runtime/package.json` | | +| `peerDependencies` | peer | `react >=18`, `redux >=4`, `zustand >=4`, all optional | `packages/runtime/package.json` | | +| `sideEffects` | pkg | `false` | `packages/runtime/package.json` | bundlers may drop unused imports | +| `engines.node` | pkg | `>=20` (root and runtime) | `package.json`s | VM runs Node 22 | +| `DEFAULT_MODEL_BASE_URL` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default model location = the unpublished package | +| CLI `DEFAULT_FROM` | const | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | default `fetch-model --from` (planned release) | +| test env vars | env | `GENCLASS_MODEL_DIR`, `NODE_OPTIONS=--expose-gc`, `GENCLASS_BENCH_MODELS="name=dir,..."`, `GENCLASS_WEBGPU_VARIANTS=<dir>`, `GENCLASS_OFFLINE=1` | test files | see Tests | +| `HAVE_MODEL` | test | `existsSync(<MODEL_DIR>/model.json)` | `test/browser/model-helpers.ts` | every model spec calls `test.skip(!HAVE_MODEL, ...)` | +| `DEFAULT_CACHE_NAME` | const | `"genclass-runtime-v1"` | `src/model/loader.ts` | Cache Storage bucket; default of `window.GC.cacheKeys()` | +| browser parity bounds | test | `model.spec.ts`: agree >= total - 1 and max \|p - p_torch\| < `0.06`; `model-webgpu.spec.ts`: agree >= total - 1 (model dir on WebGPU), >= total - 2 (embedding variants), no probability bound | the two specs | `model.spec.ts` compares over `PARITY_IDS`; `model-webgpu.spec.ts` over `[0, 13, 29, 49]` | +| lazy fail-open bound | test | wall < `50` ms | `test/browser/model.spec.ts` | a decision before the model is ready must fail open at once | +| `benchSizes` defaults | test | `runs = 10`, `targets = [600, 1000]` state tokens | `test/browser/model-helpers.ts` | `sizedRequest` binary-searches `situation(size)` over size 0..260 (size fills facts and sections first, the rest becomes timeline lines) with `GC.measure` | +| `transferReport` compression | test | gzip level 9; brotli quality 11 (files <= 2 MB) / 9 (larger) | `test/browser/model-helpers.ts` -> `sizes` | numbers in `test-results/model-bench/transfer.json` | +| `server.mjs` bind | test | `127.0.0.1`, port `0` (random) | `test/browser/server.mjs` -> `startServer` | | +| `isV01Tokenizer` | test | 50,009 merges and 50,280 vocab entries | `test/model/helpers.ts` | gates the HF edge-case tokenizer tests | +| `make_py_fixtures.py` constants | script | `n_merges = 16000` (pruned vocab 16,364, markers 16359..16363); `random.Random(7)`; fallback v1 calibration `{"noul": 1.4, "choice": 0.7, "score": 0.9, "by_header": {}}` when `<tokenizer dir>/calibration.json` is absent | `test/fixtures/model/make_py_fixtures.py` -> `main` | regenerating with another tokenizer or calibration changes `py_fixtures.json` | + +## Invariants and gotchas + +- **Do not run builds or tests on the original 8 GB Mac.** That is the binding team rule. Elsewhere the run policy in AGENTS.md allows the light checks locally and requires the user's OK for everything heavier ([Where to run things](#where-to-run-things)). `vm.sh` needs `~/.jev-local/azure_hosts` (a `train` line) and `~/.ssh/jev_azure`, neither of which is in the repo. It also calls GNU `timeout` on the local machine, which macOS does not include by default. Without all three, `vm.sh` cannot reach a VM. If you have no VM, ask the user; do not quietly run heavy jobs locally. +- **`dist/` must exist before anything consumes the package.** `sim`, `demos` and demo typechecking resolve `@genclass/runtime` through `exports` -> `dist/`. Root `npm run typecheck` therefore needs `npm run build` first (demos' `typecheck` reads `dist/*.d.ts`; `typecheck:shim` avoids it). The demos typecheck (and `typecheck:shim`) also needs the missing `demos/src/server/data/cities.ts` (see [../demos.md](../demos.md#drift-and-open-issues) Drift 1): `demos/tsconfig.json`, `tsconfig.shim.json` and `tsconfig.sw.json` all include `src/server/worlds/search.ts`, which imports it, so the root `npm run typecheck` fails with a missing-module error in this checkout until that file is recreated (inferred from the configs; tsc was not run). +- **`clean: true` + a failed build = a half-empty `dist/`.** `demos/scripts/vm-eval.sh` refuses to measure after a failed runtime build for this reason (`ALLOW_BROKEN_RUNTIME=1` overrides). +- **`npm run test:browser` rebuilds `packages/runtime/dist/`** (its global setup runs `npx tsup`). Do not run it in a slot where another job is reading `dist/`. +- **Keep tsup entries as literal `"src/...ts"` strings.** `build.mjs` -> `fullBuildPossible` finds them with a regex over the config text. +- **Keep the worker URL pattern and the two `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` literals.** Bundlers (Vite, webpack) recognise them; `build.mjs` fails if either disappears from the output. +- **Tests are not type-checked** (`tsconfig.json` `include: ["src"]`; vitest strips types). A test can drift from the public types and still pass; `MockRuntime` in particular is "not type-checked" (STATUS). +- **Unit tests import from `test/browser/ui/`** (`mock-runtime.ts`, `scenario.ts`, `session.ts`). The vitest exclude only stops test discovery there; moving or renaming those files breaks `adapters-*.test.ts`, `devtools*.test.ts`. +- **Determinism.** Runtime code uses only the injected `Clock` (CONTRACT §0 rule 3). Tests assert byte-identical situations across runs (`situation.test.ts` "determinism", `budget.test.ts` "byte-identical"). Never use `Date.now`, `performance.now`, `Math.random` or the global `setTimeout` directly in `src/` (rule 3 names all of them); in tests use `FakeClock`, not real timers. Exceptions: wall-time measurements with `performance.now` in `review-perf.test.ts`, `test/model/engine.test.ts` and `test/model/packer.test.ts`, the real `browserClock` in `test/model/loader.test.ts`, and the 40 ms real `setTimeout` "frame" waits in `devtools.test.ts` / `devtools-runtime.test.ts`. +- **Wall-clock thresholds in `review-perf.test.ts`** (user write < 1 ms, async write < 2 ms, redux dispatch < 1 / < 2 ms, settled point < 16 ms on 5,000-item stores) can fail on a loaded machine. STATUS measured on the shared VM: keystroke write 0.14 ms, gated async write 0.19 ms, redux dispatch 0.68 ms (user) / 0.58 ms (async), settled point 0.2 ms (+1.4 ms with an unchanged 5,000-item adapter store). +- **The gc test passes silently without `--expose-gc`.** `review-timers.test.ts` "a polling loop does not retain..." logs `[review] skipped: run with NODE_OPTIONS=--expose-gc` and returns. +- **Review tests are a contract.** Never edit `test/review-*.test.ts` to make them pass; fix `src/`. +- **Situation wording is frozen at `situation-v1`.** `situation.test.ts`, `budget.test.ts` and `batch3.test.ts` assert exact fact sentences (regexes / `toContain`), and `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts` assert fact fragments; `report.test.ts`, `atoms.test.ts`, `fetch.test.ts`, `learn.test.ts` assert report / reason / `changed` wording. SIM training data was generated from that tag. The example situations in `packages/runtime/STATUS.md` are copied from the `console.log` output of `situation.test.ts` and `budget.test.ts`. Coordinate any wording change with SIM (STATUS "Open issues"). +- **Browser parity fixtures are v0.1-only.** `test/browser/model-helpers.ts` always reads `test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`, so `model.spec.ts` parity assertions only hold when `GENCLASS_MODEL_DIR` is the v0.1 GenClass model. The unit tests switch to an export's own fixtures (`FIXTURES_FROM_MODEL`); the browser specs do not. +- **The default Playwright config also runs `ui-devtools.spec.ts`.** Its `chromium` project matches every `*.spec.ts` except `*webgpu.spec.ts`, so `npm run test:browser` also re-runs the UI spec. That run uses Playwright's default viewport and device scale factor (the main config sets neither) and overwrites the committed screenshots. Use the UI config to regenerate screenshots. +- **The UI spec needs the demos workspace installed** (fonts come from `@fontsource-variable/*`, dependencies of `demos`, hoisted to `<repo>/node_modules`). Run a root `npm install`, not one scoped to the runtime. +- **Node version.** `test/model/helpers.ts` -> `pythonOnlyFloatRequests` uses `JSON.parse` source-text access (Node >= 21). On Node 20 it finds nothing, so fixtures holding Python-only float literals such as `25.0` would not be skipped by the packer parity test. Use Node 22 as on the VM. Node 25.6.0 also ran the unit tests in the 2026-10-07 pass, with an EBADENGINE warning from vitest ([Verified locally](#verified-locally-2026-10-07)). +- **Global singletons in tests.** `report.test.ts` and `batch3.test.ts` use `GenClass.init`; always `GenClass.destroy()` (and delete `globalThis.location` if you set it). happy-dom tests patch `window` globals: `rt.destroy()` in `afterEach`. `review-hub.test.ts` swaps `process` `unhandledRejection` listeners and restores them in `finally`. +- **Network-dependent steps:** `smoke.sh` (npm registry), `model.spec.ts` "default ORT wasm path" (jsDelivr; `GENCLASS_OFFLINE=1` skips it), `fetch-model` (GitHub). +- **Fixture JSON files are single-line.** `wc -l` prints `0` for `pack_fixtures.json` (955,379 bytes), `py_fixtures.json` (167,629), `requests50.json` (285,309) and `torch_fixtures.json` (255,945): no trailing newline, not empty. Use `wc -c` or a JSON parser. +- **No `prepublishOnly` and no `publishConfig`.** `npm publish` packs whatever `dist/` holds; build right before publishing. Scoped packages publish as restricted unless `--access public` is passed (npm behaviour). +- **No committed lockfile.** The root `package-lock.json` has never been in git, so `npm ci` fails on a fresh clone and dependency versions float within the `^` ranges (only `@playwright/test 1.63.0`, `onnxruntime-node 1.30.0` and `typescript ~5.9.3` are pinned tightly). A root `npm install` writes one, which shows up as untracked; committing it is a lead decision (it would fix CI reproducibility). +- **`sim`'s `build:runtime-core` leaves a partial `dist/`.** It writes only `dist/index.js` (+ chunks, maps; `--platform neutral`, no `.d.ts`, no adapters/devtools/worker) and does not clean (tsup CLI default), so whatever an earlier full build left stays. `demos/vite.config.ts` picks the real runtime whenever `dist/index.js` exists, so after this build on an empty `dist/` demos resolve `@genclass/runtime/react` etc. to files that do not exist (and the demos typecheck finds no `.d.ts`). Run the full `npm run build` before working on demos. +- **vitest `exclude` replaces the defaults.** `vitest.config.ts` sets `exclude: ["test/browser/**"]` rather than extending vitest's default exclude list. Harmless while `include` is `test/**/*.test.ts`; use `[...configDefaults.exclude, "test/browser/**"]` if `include` is ever widened. +- **A checkout may hold stale local artefacts.** `dist/`, `node_modules/`, `test/browser/.build/`, `test-results/` and `*.tgz` are ignored, so a working copy can contain a `dist/` built from older sources. Rebuild before trusting `dist/`, `sim` real-runtime runs or demo results. +- **Unanchored ignores.** `.gitignore` entries `data/`, `models/`, `runs/` (and `dist/`) match directories at any depth: a new `src/models/` folder would be silently ignored. Check `git check-ignore -v <path>` when a new file does not show up. +- **Playwright browsers are a prerequisite.** Nothing in the repo runs `npx playwright install`; `test:browser`, the UI spec and `smoke.sh` assume Chromium for `@playwright/test` `1.63.0` is already installed. The SwiftShader project additionally needs a Chromium build with WebGPU (the spec skips when no adapter appears). +- **`loader.test.ts` uses the real clock.** It passes `browserClock` (not a fake) to `ModelBackend`; the WebGPU session-timeout case waits real time (`sessionTimeoutMs: { webgpu: 30 }`, 30 ms per plan). Keep such timeouts tiny, or inject a fake clock, when adding timing cases there. +- **Fixture byte identity.** The committed `pack_fixtures.json` / `torch_fixtures.json` are compact (no-whitespace) re-serialisations of `extension/test/fixtures/*`; they differ byte-wise from the extension copies and from `genclass_export.py`'s `json.dumps` output, but are identical once whitespace is removed. Compare parsed JSON, not hashes. +- **`make_py_fixtures.py` imports the Python reference from the repo.** `ROOT = Path(__file__).resolve().parents[5]` (the repo root) is put on `sys.path` and `jev_local.{confidence,serialize,schema,engine.encoder.calibrate}` are imported from there. Moving the script changes `ROOT`. The parity tests' Python counterparts are `jev_local/engine/encoder/tokenize_pack.py` (packer), `jev_local/serialize.py`, `calibrate.py`, `confidence.py` (named in the test headers). + +## How to change it safely + +### Write a new unit test (house style) + +1. Put it in `packages/runtime/test/<area>.test.ts` (`test/model/` for model code). Import with `.js` extensions (`./helpers.js`, `../src/...js`). +2. Use `setup()` and drive time with `clock.advance` / `clock.flush`. Use `triage: "always"` to force a model consultation, `mode: "heal"` for heal-tier actions, `ManualDecider` to control answer timing. +3. Name the contract section in the `describe` (e.g. `"(CONTRACT §4)"`). For a bug demonstration, follow the `review-*.test.ts` files: a header comment `// REVIEW: <area>. A failing test demonstrates a bug.`, a `describe("review: ...")`, and a test name that states the required behaviour. +4. For DOM: first line `// @vitest-environment happy-dom`, then `createRuntime({ clock: new FakeClock(), global: window, decider, report: "silent", observe: { ...OFF, user: true } })` where `OFF` sets `fetch, xhr, errors, nav, storage, perf, websocket, timers` to `false` (copy it from `dom.test.ts`), and `rt.destroy()` in `afterEach`. +5. For model files: `describe.skipIf(!hasModelFile("model.json"))`. + +```ts +import { describe, expect, it } from "vitest"; +import { ManualDecider, defaultScript, setup } from "./helpers.js"; + +describe("my change (CONTRACT §4)", () => { + it("holds an async write until the model answers", async () => { + const manual = new ManualDecider(); + const { rt, clock } = setup({ decider: manual, triage: "always" }); + const a = rt.atom("v", 0); + void rt.op("save", () => a.set(5)); + expect(a.get()).toBe(0); // held + manual.answer(defaultScript({ mutation: { diagnosis: "expected", action: "apply" } })); + await clock.flush(); + expect(a.get()).toBe(5); + }); +}); +``` + +Run it locally (`cd packages/runtime && npx vitest run test/<file>.test.ts`) or on the VM: `scripts/vm.sh run core 'cd packages/runtime && npx vitest run test/<file>.test.ts'` ([Where to run things](#where-to-run-things)). + +### Add a browser spec + +1. Model host: `test/browser/<name>.spec.ts` (a name ending `webgpu.spec.ts` runs only in the `swiftshader-webgpu` project; `ui-*.spec.ts` is also picked up by the UI config). Start with `test.describe.configure({ mode: "serial" })` and `test.skip(!HAVE_MODEL, ...)`, then `const srv = useServer()` at file level. +2. In each test: `const { page, logs } = await openApp(browser, srv.url)`, `await create(page, { baseUrl: "/model/", device: "wasm", preload: "eager", ortWasmPaths: "/ort/" })`, `await ready(page)`, then `evaluate(page, fixtureRequest(i))` / `parityRun(page)`; assert `logs` has no `[pageerror]`. Use `/coi/model/` + `/coi/ort/` with `openApp(..., { coi: true })` for threads. +3. The page can only call what `page/main.ts` exposes on `window.GC`, and `main.ts` only imports `"genclass-dist"` (the built `dist/index.js`, or `src/model/index.ts` in the model-entries build). New host features must be exported from both entry points to be testable here. +4. Persist numbers with `saveResults("<name>", {...})` (merged into `test-results/model-bench/<name>.json`, not Playwright's `outputDir`, which is emptied each run). + +### Add a public entry point (new subpath export) + +1. Add the entry to `tsup.config.ts` `entry` **and** `dts.entry` (keep the `"src/...ts"` literal form). +2. Add `"./<name>": { "types": "./dist/<name>.d.ts", "import": "./dist/<name>.js" }` to `packages/runtime/package.json` `exports`. +3. If demos import it, add a shim to `demos/src/dev/runtime-shim/`, an alias in `demos/vite.config.ts` and a path in `demos/tsconfig.shim.json`. +4. Build locally (`npx tsup`). Then, with the user's OK (ask first), run `bash test/smoke/smoke.sh`, extending `src/main.js` in the script to import the new subpath. + +### Change situation text, facts or questions + +1. Edit `src/situation/*` only (single implementation shared with `sim/`). +2. Update the exact-text assertions in `test/situation.test.ts`, `test/budget.test.ts`, `test/batch3.test.ts`, `test/invariants.test.ts`, `test/review-fetch.test.ts`, `test/review-hub.test.ts` (facts) and, for report wording, `test/report.test.ts`, `test/atoms.test.ts`, `test/fetch.test.ts`, `test/learn.test.ts` (search for the old sentence). Changing a `review-*` assertion conflicts with "Review tests are a contract" (gotchas): raise it rather than rewrite it silently. +3. Re-run `situation.test.ts` and `budget.test.ts`, paste their printed situations into the STATUS.md example sections. +4. Tell SIM: rows must be regenerated, and models trained on `situation-v1` data were trained on the old text. See [learn-situation-triage.md](learn-situation-triage.md) and [../model-io-contract.md](../model-io-contract.md). + +### Regenerate model fixtures + +- `py_fixtures.json` (needs the jev venv: `tokenizers`, `numpy`, `pydantic`, and the v0.1 tokenizer so `isV01Tokenizer` passes): + `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_py_fixtures.py --tokenizer <model dir>/tokenizer.json --out packages/runtime/test/fixtures/model/py_fixtures.json` + It also reads `<model dir>/calibration.json` when present for the v1 calibration cases. + The script prints `wrote <out>: <n> states, <n> texts, <n> calibration cases, <n> confidence cases` and writes one line (`json.dumps(..., ensure_ascii=False)`, no trailing newline). `~/jev/.venv` is the venv `scripts/vm_bootstrap.sh` creates (CPU torch, `tokenizers`, `numpy`, `pydantic>=2`, ...). +- WebGPU embedding variants (written outside the repo, used via `GENCLASS_WEBGPU_VARIANTS`; `--src` must be a runtime-card model dir with a q8 variant; needs `onnx` + `numpy`, and `onnx` is not in `vm_bootstrap.sh`'s pip list): + `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_webgpu_variants.py --src ~/gcl-cache/model-v0.1 --out ~/gcl-cache/webgpu-variants` + Writes `f32emb/` (fp32 embedding table: `Gather(fp32)`) and `i8emb/` (int8 table + per-row fp32 scale: `Gather(int8) -> Cast -> Mul(Gather(scale))`). +- `pack_fixtures.json` / `torch_fixtures.json`: outputs of `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (identical fixture code; which one produced the committed files is not recorded). Both export the extension's v1 computer-use model, import torch and say "RUN ON THE AZURE VM ONLY"; the fixtures are Python `Packer` output and PyTorch logits, so they do not depend on the int8 vs q8 ONNX variant. They were copied from `extension/test/fixtures/` and re-serialised compactly. Do not hand-edit them; the browser parity specs depend on them matching the v0.1 model. If you regenerate, re-serialise without whitespace to keep diffs comparable, and regenerate `requests50.json` from the same request set. + +### Publish history (from git) + +| when (commit time) | commit / tag | what | +|---|---|---| +| 2026-10-07 19:19 -0400 | tag `situation-v1` -> 1a77558 | runtime fix batch 3; situation format frozen for SIM data | +| 2026-10-07 20:09 -0400 | 59c213f | `version` `0.1.0` -> `0.1.0-alpha.0`, `packages/runtime/LICENSE` added, `test/smoke/smoke.sh`, `.gitignore` gains `.publish/` and `*.tgz` | +| between 59c213f and 654d822 | (npm) | `@genclass/runtime@0.1.0-alpha.0` published; OPEN_TASKS: "2026-10-08, `genclass` org, owner meharpro", smoke-tested first | +| 2026-10-07 20:15 -0400 (00:15 UTC 10-08) | 654d822, tag `v0.1.0-alpha.0` (tagged 20:15:12 -0400) | both READMEs get an npm badge (`/npm/v/@genclass/runtime/latest`), a license badge and an "alpha" status note (the `npm install @genclass/runtime` lines were already there); OPEN_TASKS moves publish to "Done" and rewrites item 8 | + +Before 654d822, OPEN_TASKS "Needs the user" listed the prerequisites: "an `@genclass` npm org and `npm login` on this machine (not logged in), or another scope name". The exact `npm publish` flags (dist-tag, `--access`) and what `.publish/` was used for are not recorded (unverified). + +### Cut a release of `@genclass/runtime` (reconstructed; there is no script) + +1. Locally: `npm install`, `npm run build`, `npm run typecheck -w @genclass/runtime`, the unit tests with `--expose-gc`. With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs and `bash test/smoke/smoke.sh`, locally or on the VM ([Where to run things](#where-to-run-things)). +2. Bump `version` in `packages/runtime/package.json` (and the version strings in READMEs/OPEN_TASKS). +3. From `packages/runtime` on a machine logged in to npm with publish rights on the `genclass` org: `npm publish --access public` (add `--tag alpha` or similar for prereleases; the flags used for `0.1.0-alpha.0` are not recorded, unverified). +4. `git tag -a vX.Y.Z -m "@genclass/runtime X.Y.Z (npm)"` and push the tag. Update `OPEN_TASKS.md` "Done". +5. The user must approve any publish; it is an irreversible public action. + +### Publish the model package (planned, OPEN_TASKS item 8) + +1. Put a model directory (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`) under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `DEFAULT_MODEL_BASE_URL`. Check it with `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files`. +2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`). +3. Attach the same files to a GitHub release tagged `runtime-model-v0.1.0` (the CLI's `DEFAULT_FROM`). +4. Then publish `@genclass/runtime@0.1.0` without a prerelease tag. + +### Add CI (planned, OPEN_TASKS item 8) + +No workflow exists (no `.github/`, no other CI config anywhere in the repo). A minimal one (`.github/workflows/*.yml`, Node 22 (≥ 22.12) or 24, inside vitest 5.0.3's engine range (23 and 25 are outside)) would run: `npm install` (or commit a root `package-lock.json` first and use `npm ci`; none is tracked today), `npm run build`, `npm run typecheck -w @genclass/runtime`, `NODE_OPTIONS=--expose-gc npm test`. Without a model directory the 14 model-file tests skip. The root `npm run typecheck` also typechecks `sim` (no build needed) and `demos` (needs the full build first, and fails until the missing `demos/src/server/data/cities.ts` is recreated; see [../demos.md](../demos.md#drift-and-open-issues) Drift 1). Browser specs would additionally need `npx playwright install --with-deps chromium` and a model directory; the smoke test needs registry access. Treat `review-perf.test.ts` wall-clock bounds as possibly flaky on shared runners. + +## Tests + +Counts are `it(...)` cases (the `budget.test.ts` loop counts 3). The total of 300 matches STATUS (300 total, UI 53, MODEL 62) and the 2026-10-07 vitest run (300 tests: 286 passed, 14 model-file tests skipped; see [Verified locally](#verified-locally-2026-10-07)); the remaining 185 are CORE 142 + REVIEW 43. + +| test file | owner | env | tests | what it asserts | +|---|---|---|---|---| +| `test/adapter-seam.test.ts` | CORE | node | 4 | `rt.adapter(name, io).propose({fn, commit})`: reducer preview, async dispatch held then committed, discard never commits, direct library changes recorded not held, rollback offered only when `io.set` exists | +| `test/adapters-react.test.ts` | UI | happy-dom | 9 | `useGenClassState` (one atom per name, held write shown only when applied, StrictMode-safe, plain-state fallback with one `console.info` "no runtime"), `useAtom`, `useGenClass` throws "No runtime", live `useGenClassDecisions/Interventions/Status`; with the real runtime: hold, discard, undo; user-handler writes never held | +| `test/adapters-redux.test.ts` | UI | node | 11 | `genclassEnhancer`: passthrough, hold/apply once (reducer runs once), re-run on moved state, drop, middleware/thunks see the action once, no-op actions, `replaceReducer`, inner enhancers see `GENCLASS_REPLACE` for GenClass writes, `null` runtime; real runtime hold/discard/undo | +| `test/adapters-zustand.test.ts` | UI | node | 6 | `genclass(rt, name)` middleware: merge semantics, hold/drop, replace/functional/no-op/extra `set` args, GenClass whole-state writes, `null` runtime; real runtime | +| `test/ask.test.ts` | CORE | node | 5 | `ask()` typed answers (choice/noul/score), trigger `ask`, `about` an op or store, `decide()`, `GenClassUnavailableError` without a model (status `off`), timeout reason `timeout` | +| `test/atoms.test.ts` | CORE | node | 16 | mutation pipeline: user-sync writes never held, async held then applied, fail-open at `holdBudgetMs` + late discard revert + undo, no late revert when superseded / after 2 s / same chain wrote again, late defer only recorded, provider errors (`not_ready`, `max_tokens_exceeded`, `timeout`, `busy`) fail open at once, proposal order, functional re-run, patch re-apply, discard + undo, defer max 2, `hold: false`, `guard()`, same-name atoms, field versions/writers | +| `test/batch3.test.ts` | CORE | node | 13 | SIM requests a–f (word-level redaction, kanban card values, no `= undefined` state lines, item change summaries, "changed twice ... back to 6", slug ids via `normalizePath`/`isIdSegment`, pending-local-change fact), `ctx.builtin` through the gate, rate-limit warning once per minute, `ask()` after destroy, read-only globals, `GenClass.init` never throws, never-answering provider, `transient` label last | +| `test/budget.test.ts` | CORE | node | 12 | `sectionLimits` at 500/1,100/2,000/3,200; budgets 1,000/1,100/2,000 shape every section; compact questions at <= 1,400; vocabulary overrides <= 24 chars kept; determinism; auto budget (webgpu 3,200; wasm 1,000/1,333/2,000; unknown 3,200; fixed 1,500); `max_tokens_exceeded` shrinks auto budget to 2,560; `holdBudget` auto = clamp(1.5 x median, 150, 800) else 300; held write `timeoutMs` = budget + 2,000; fetch `timeoutMs` = remaining budget. Prints example situations | +| `test/context.test.ts` | CORE | node | 7 | causal context: fetch -> json -> set cause/root, concurrent chains, `rt.op` ambient in body and continuation, nested op causes, ambient cleared by `afterTask`, timers observer carries cause (`timer 300ms`), idle timers create no ops | +| `test/devtools-runtime.test.ts` | UI | happy-dom | 7 | overlay on the real runtime (`runStoreSession`): interventions, folded detections, evidence = `explain()`, activity timeline, Now view, undo, live report sentence | +| `test/devtools.test.ts` | UI | happy-dom | 20 | overlay vs `MockRuntime` + `loadScenario`: mount/unmount (shadow root, `data-genclass-ignore`, no global CSS, listeners and plugin removed), no-op handle, theme/position, feeds, activity rows, typing bursts, evidence, undo and undo errors, live pill, folding, 200-card cap, policy reasons, pause/clear, Now view, mode switch, keyboard (Alt+Shift+G), empty states | +| `test/dom.test.ts` | CORE | happy-dom | 8 | `describeElement`; DOM user observer (clicks, typing bursts, passwords never recorded, submit/change/Enter, `[data-genclass-ignore]` incl. shadow roots, destroy); destroy restores fetch/XHR/history/Storage/WebSocket/timers; uncaught errors -> error trigger | +| `test/fetch.test.ts` | CORE | node | 17 | fetch observer: plain traffic makes no model call, app body vs clone, coalesce (`x-genclass: coalesced`), block (503 `blocked`), guard never runs heal-tier, `serve_cached`, delay 250 ms first, retry backoff 200 ms, retry not offered for non-replayable bodies, network error delivered, failure/request gates fail open at 300 ms, hedge, abort, `TimeoutError` = failure, cache <= `MAX_ENTRIES` (64) and skips bodies > `MAX_BODY` (256 KB), destroy restores fetch | +| `test/invariants.test.ts` | CORE | node | 6 | `InvariantMiner` learns len/sum/equality/unique relations, ignores unchanged fields and id-like keys; inconsistency once per episode + rollback + undo; unsettled transients ignored; `expect()` predicates | +| `test/learn.test.ts` | CORE | node | 8 | `Baselines` (latency after 5 samples, EWMA 0.9 error rate, streaks, outcomes, rate vs usual, identity gaps); `Profiles` (write set < 1% of >= 20, value kind, status class); transition trigger + rollback | +| `test/plugins.test.ts` | CORE | node | 7 | plugin facts/diagnoses/custom actions, `ctx.builtin`, plugin actions default to heal tier, `applicable()`, standing questions + `onAnswer`, `setup()`/cleanup API, vocabulary overrides | +| `test/policy.test.ts` | CORE | node | 14 | `gate()` summed mass, mode tiers, thresholds 0.9 guard / 0.8 heal, passive top, `requireDiagnosis`, deny/allow, pause, rate limit with 60 s sliding window, observe never holds, `setMode`, `pause()/resume()`, loading fails open without a record, detection threshold | +| `test/report.test.ts` | CORE | node | 7 | report line format, `explain(id)`, "Not acted on (would have done ...)", console group + "(×2 more in the last minute)", `on()` listeners, `GenClass.init` idempotent, `?genclass=off`, `?genclass=heal` | +| `test/review-actions.test.ts` | REVIEW | node | 1 | error-trigger rollback only when the failing chain wrote state; user input survives | +| `test/review-dom.test.ts` | REVIEW | happy-dom | 2 | unlabeled password never recorded; programmatic `click()` inside an op is not a user action | +| `test/review-fetch.test.ts` | REVIEW | node | 11 | request identity (Request bodies, Range), coalesce with opaque / streaming responses never hangs, buffers <= 64 x 256 KB, abort listener removed, no work after destroy, guard-mode failures not held, keepalive sent synchronously, "started after" direction, error-rate counts | +| `test/review-hub.test.ts` | REVIEW | node | 8 | held value write patched over user edit, queued nested object kept, late-revert undo, in-place push summary, in-place updater while held, versions past 16 history entries, deep change in 2,000-item array, throwing commit does not strand the queue | +| `test/review-misc.test.ts` | REVIEW | node | 6 | console ×N summaries, rate-limit warning once, read-only `fetch`, `ctx.builtin` cannot run a denied heal-tier action, never-settling provider, `ask()` after destroy | +| `test/review-perf.test.ts` | REVIEW | node | 4 | wall-clock cost budgets on 5,000-item stores (see gotchas); logs numbers | +| `test/review-precision.test.ts` | REVIEW | node | 4 | short last page is not a transition, keyed keys like `m21` are not, closing a selection is not an inconsistency, a lingering violation does not freeze snapshots | +| `test/review-redaction.test.ts` | REVIEW | node | 1 | custom `redact` also applies to invariant facts | +| `test/review-timers.test.ts` | REVIEW | node | 2 | 200,000-step recursive `setTimeout` loop does not throw; polling loop does not retain ops (registry prunes beyond 2,000; gc check needs `--expose-gc`) | +| `test/review-xhr.test.ts` | REVIEW | node | 4 | sync XHR never held, abort while held means never sent, listeners added once per object, reuse after a blocked answer | +| `test/situation.test.ts` | CORE | node | 10 | one situation per trigger (mutation, request, failure, stall, inconsistency, transition, error): keys `app, trigger, facts, in_flight, timeline, state, stats`, facts <= 12, timeline <= 16, state <= 8, `stateChars <= STATE_CHAR_BUDGET`; `situation()` side-effect free; serializer drop order; determinism. Prints situations | +| `test/smoke.test.ts` | CORE | node | 3 | atoms apply synchronously when nothing is salient; context through real awaits; stale write discarded in guard mode (own local `setup()`) | +| `test/xhr.test.ts` | CORE | node | 5 | XHR op + cause, block replays 503, failures detection-only, request gate fails open at 300 ms, destroy restores `open`/`send` | +| `test/model/calibrate.test.ts` | MODEL | node | 8 | sha1 header keys vs Python, sha256 (TS and WebCrypto) at edge lengths; calibration vs PyTorch < 1e-9 (needs `calibration.json` in `MODEL_DIR`); v1/v2 calibration vs Python < 1e-12; confidence; `buildAnswer`; `tauFor`/`kBucket`/`parseCalibration` | +| `test/model/engine.test.ts` | MODEL | node | 4 | ORT-node CPU q8 and fp16 parity vs PyTorch, ORT-web WASM q8 (12 requests, 1 thread) (all need model files); graph contract with a fake ORT (feeds exactly `meta.inputs`, `ModelUnsupportedError`) | +| `test/model/host.test.ts` | MODEL | node | 20 | `createModelHost` with fake worker + own fake clock (t = 0): lazy/eager/idle preload, status, priority queue, timeouts, `maxQueue` eviction, `status.latency` window of 20, typed errors across the worker boundary, JSON normalisation, measure, dispose, crash, WebGPU -> WASM recovery once, `loadStallMs`, inline fallbacks | +| `test/model/loader.test.ts` | MODEL | node | 12 | `parseCard` (runtime + v0.1 cards, unsafe names), `planOrder`, `fetchFile` (progress, sha256, Cache Storage, integrity, no cache / quota), `fetchCard` offline, `ModelBackend.load` phases `card, download, runtime, session, warmup`, ORT build choice, cached second load, WebGPU session timeout | +| `test/model/packer.test.ts` | MODEL | node | 10 | packer vs Python fixtures (skips Python-only float requests), Map vs object criteria, special tokens stay text, markers from meta, `MaxTokensExceededError`, integer-like labels, `planInputs`/`unpackLogits`; HF tokenizer parity full + pruned (v0.1 tokenizer only); tokenizer build < 2,000 ms. All need `tokenizer.json` | +| `test/model/serialize.test.ts` | MODEL | node | 8 | `stateSegments`/`questionBlock` vs Python; `pyNumber`, `pyJson`, `pyStrip`, `toJsonValue`, `pyRound` half-even | +| `test/browser/model.spec.ts` | MODEL | Chromium | 9 | WASM load in a module worker + parity (allow 1 flip, max dp < 0.06) + Cache Storage second load; inline fallbacks; lazy/idle preload; WebGPU fallbacks; latency 1 thread; latency per model size (`GENCLASS_BENCH_MODELS`); 4 threads cross-origin isolated; default ORT wasm from jsDelivr (`GENCLASS_OFFLINE` skips). All skip without `model.json` in `MODEL_DIR` | +| `test/browser/model-webgpu.spec.ts` | MODEL | Chromium + SwiftShader | 2 + per variant + per export | model on WebGPU without `shader-f16` (runs or falls back to WASM on f16 tensors); `GENCLASS_WEBGPU_VARIANTS` variants (`f32emb` must run on WebGPU); `GENCLASS_BENCH_MODELS` exports; `auto` skips software adapters | +| `test/browser/ui-devtools.spec.ts` | UI | Chromium | 5 | style isolation, keyboard, undo, screenshots light + dark | +| `test/smoke/smoke.sh` | packaging (owner not recorded) | bash + Chromium | 1 script | npm tarball works in a fresh Vite 8 app (see How it works) | + +### Fixtures + +| file | size | generated by | consumed by | +|---|---|---|---| +| `test/fixtures/model/requests50.json` | 285,309 B, single line, 50 requests `{id, state, questions}` | same 50 requests as `extension/test/fixtures/requests50.json` minus its `gold` and `screen_type` fields (verified by comparison; the stripping script is not in the repo) | `test/model/helpers.ts` -> `requests()` (fallback), browser `model-helpers.ts` | +| `test/fixtures/model/pack_fixtures.json` | 955,379 B, single line | `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (v0.1 export; identical fixture code; which one produced the committed files is not recorded). Compact copy of `extension/test/fixtures/pack_fixtures.json` (1,228,103 B): identical after stripping whitespace, byte-different | packer, calibrate, engine, browser parity | +| `test/fixtures/model/torch_fixtures.json` | 255,945 B, single line | `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (identical fixture code; which one produced the committed files is not recorded). Compact copy of the extension's (269,230 B), identical after stripping whitespace | calibrate, engine, browser parity | +| `test/fixtures/model/py_fixtures.json` | 167,629 B, single line: 17 states, 7 questions, 98 texts, pruned (16,000 merges, vocab 16,364), 120 calibration cases, 80 confidence cases | `test/fixtures/model/make_py_fixtures.py` | `serialize.test.ts`, `calibrate.test.ts`, `packer.test.ts` | +| `<MODEL_DIR>/{requests,pack_fixtures,torch_fixtures,parity}.json` | per export | `training/export_runtime.py` | unit tests when all three exist (`FIXTURES_FROM_MODEL`), `exportParity()` | +| `<GENCLASS_WEBGPU_VARIANTS>/{f32emb,i8emb}/` | model dirs | `test/fixtures/model/make_webgpu_variants.py` | `model-webgpu.spec.ts` | + +## Drift and open issues + +Doc-vs-code mismatches (code wins): + +- `packages/runtime/STATUS.md` "Open issues" says `react-dom` is not a devDependency of `@genclass/runtime`, and `packages/runtime/UI-NEEDS.md` item 2 (still under "Open") asks for `react-dom` and `@types/react-dom`. Both are devDependencies: `react-dom ^19.3.0`, `@types/react-dom ^19.0.0`. UI-NEEDS item 1 (ignore `[data-genclass-ignore]`) is also listed as open but is implemented and tested (`dom.test.ts`). +- `STATUS.md` "For UI" says `test/browser/ui/mock-runtime.ts` needs `holdBudgetMs()` and `situationBudget()`. Both exist (return `300` and `3200`). "Not type-checked" is still true. +- `STATUS.md` runs `vitest run --exclude "test/browser/**"`. The exclude is already in `vitest.config.ts`; plain `vitest run` / `npm test` is equivalent. +- `OPEN_TASKS.md` item 8 still lists "`npm pack` smoke test in a fresh Vite app" as to do. `test/smoke/smoke.sh` exists (commit 59c213f) and "Done" says it was run for the alpha. +- `OPEN_TASKS.md` header says "Status as of 2026-10-07 23:30 UTC. Branch `runtime`", but its publish entry is dated 2026-10-08. `main`, `origin/main` and `origin/runtime` all point at 654d822, so the "Merging `runtime` into `main`" item looks done on the remote. +- `packages/runtime/src/model/README.md` ("Bundling") says `dist/worker.js` imports `onnxruntime-web/webgpu`. The worker now imports either `onnxruntime-web/webgpu` or `onnxruntime-web/wasm` on demand (`src/model/worker.ts`), and `build.mjs` checks both. +- `test/browser/model-helpers.ts` -> `saveResults` doc comment says it writes `test-results/browser/<name>.json`. The code writes `test-results/model-bench/<name>.json` (the model README is correct). +- `test/browser/ui-devtools.spec.ts` calls its output "the README screenshots", but no README or doc references `test/browser/ui/screenshots/*.png`. +- `sim/README.md` says the runtime's full tsup config "fails until those [adapter] files exist". The adapters exist; the full build works (STATUS: "`tsup` build OK"). +- `docs/runtime/CONTRACT.md` §1 describes `packages/runtime-model/` as "model card + files for the CDN package". Only `MODEL_CARD.md` exists; `files/` is gitignored and there is no `package.json`. +- `packages/runtime-model/MODEL_CARD.md` lists 9 diagnoses (no `transient`); the runtime has 10 (`DEFAULT_DIAGNOSES` ends `unusual, transient`, asserted in `batch3.test.ts`). +- Documented `GENCLASS_MODEL_DIR` locations differ: `~/gcl/model/.cache-model` (STATUS), `~/gcl-cache/model-v0.1` (model README), `~/gcl/models/genclass-v0.1` (demos `vm-eval.sh` default model dir). Unverified which exist on the VM. +- npm dist-tag of the alpha is ambiguous (unverified): `OPEN_TASKS.md` item 8 says publish `0.1.0` "without the alpha tag", while both READMEs say `npm install @genclass/runtime` (installs `latest`) and their badges query `/npm/v/@genclass/runtime/latest`. Whether `0.1.0-alpha.0` went out under `latest` or a prerelease tag is not recorded; check `npm view @genclass/runtime dist-tags` before relying on either. +- `scripts/genclass_export.py` usage text passes `--requests extension/genclass/test/fixtures/requests50.json`; that path does not exist in this repo (the file is `extension/test/fixtures/requests50.json`; the script's own instructions say to run "from ~/jev on the VM"). +- Ownership: `docs/runtime/CONTRACT.md` §1 (layout) still lists `src/adapters/` and `src/devtools/` as owner CORE, but §13 (Additions) reassigns them to UI, which matches `STATUS.md` counting their tests (`adapters-*.test.ts`, `devtools*.test.ts`, 53) as UI's. §1 is stale; the Tests table follows §13 / STATUS. + +Open items in scope (from `OPEN_TASKS.md`, STATUS): + +- Packaging (item 8): publish `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, then `@genclass/runtime@0.1.0`; add a CI workflow (build, typecheck, unit tests). Until the model package exists, the default model URL has nothing to serve and the alpha only observes (README "Status"). +- Docs (item 7): dev-only lazy import of the devtools (52 KB min / 17 KB gz). +- The VM path (`scripts/vm.sh`) depends on a hosts file and SSH key from the original team's Mac. Without them the VM is unreachable: the light checks run locally under the run policy in AGENTS.md, and anything heavier (Playwright, smoke test, model runs) needs the user's go-ahead and a place to run it ([Where to run things](#where-to-run-things)). +- Any situation-wording change must be coordinated with SIM (STATUS "Open issues"). + +## Related docs + +- Runtime docs (this set): [public-api-and-lifecycle.md](public-api-and-lifecycle.md), [observe-and-trace.md](observe-and-trace.md), [state-and-adapters.md](state-and-adapters.md), [learn-situation-triage.md](learn-situation-triage.md), [decide-policy-actions.md](decide-policy-actions.md), [model-host.md](model-host.md), [devtools.md](devtools.md) +- Cross-cutting: [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../training.md](../training.md), [../demos.md](../demos.md), [../genclass-model-lineage.md](../genclass-model-lineage.md), [../extension-and-benchmarks.md](../extension-and-benchmarks.md), [../status-and-known-issues.md](../status-and-known-issues.md), [../README.md](../README.md), [../overview.md](../overview.md), [../repo-map.md](../repo-map.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../../../AGENTS.md](../../../AGENTS.md) +- Existing sources: [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/API.md](../../runtime/API.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [packages/runtime/src/model/README.md](../../../packages/runtime/src/model/README.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md), [packages/runtime-model/MODEL_CARD.md](../../../packages/runtime-model/MODEL_CARD.md), [sim/README.md](../../../sim/README.md), [demos/README.md](../../../demos/README.md) diff --git a/docs/agents/runtime/decide-policy-actions.md b/docs/agents/runtime/decide-policy-actions.md new file mode 100644 index 00000000..58fa9ab8 --- /dev/null +++ b/docs/agents/runtime/decide-policy-actions.md @@ -0,0 +1,724 @@ +# @genclass/runtime: decision queue, policy gate, actions, reports, explain and undo + +> **Scope:** `packages/runtime/src/decide/decider.ts`, `packages/runtime/src/decide/exec.ts`, +> `packages/runtime/src/decide/policy.ts`, `packages/runtime/src/decide/report.ts`; the decision flow, action +> implementations, late revert, `explain`, undo and plugin action/question plumbing in +> `packages/runtime/src/runtime.ts`; `BUILTIN_ACTIONS` / `TRIGGER_ACTIONS` / `PASSIVE` / `DEFAULT_DIAGNOSES` in +> `packages/runtime/src/situation/questions.ts`; the request-side action controllers in +> `packages/runtime/src/observe/fetch.ts` and `packages/runtime/src/observe/xhr.ts` (followed only as far as the actions). +> **Read this when:** changing what happens after a trigger is built (queueing, deadlines, hold budget, fail-open), +> the policy gate or its defaults, any built-in action's mechanics or `changed` text, custom actions / standing +> questions, the console report wording, `Decision` / `ActionRecord` / `Explanation` shapes, `explain()` or undo. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- Every trigger goes through `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger(spec, ctl, opts)`: triage + first; if salient and the model is `ready`, the situation is submitted to a single-flight priority queue + (`DeciderQueue`), and the subject is **held** only if the trigger is holdable (`opts.hold`) **and** at least one + non-passive action is permitted by mode + policy. Otherwise the passive action runs at once and the decision is + still made in the background (detection only). +- **Fail-open everywhere:** no provider, provider not `ready`, provider error (any `code`), queue overflow, expired + deadline, runtime-side timeout, hold budget expiry, a throwing action -> the passive action runs. A missing model + never blocks the app and never produces a `Decision`. +- **Hold budget** (`policy.holdBudgetMs`, default `"auto"`): clamp(round(1.5 × median of the last 20 provider + latencies, or the model's `warmupMs` before any), 150, 800) ms; 300 ms when nothing is known + (`packages/runtime/src/decide/policy.ts` -> `holdBudget`). +- **Policy gate** (`policy.ts` -> `gate`, CONTRACT §8): A = applicable non-passive actions permitted by the mode + (observe: none; guard: guard tier; heal: guard + heal) minus `deny` (only `allow` if set). Candidate = argmax of + probability over A. It runs only if: not paused; Σ p(A) ≥ the candidate's tier threshold (guard 0.9, heal 0.8); + the model's top diagnosis ≠ `expected` (unless `requireDiagnosis: false`); fewer than `maxActionsPerMinute` (60) + actions in the last 60 s; and, for holdable triggers (mutation, request, fetch failure), the decision arrived while + the subject was still held (else late-revert rules); non-holdable triggers (stall, inconsistency, transition, error, + XHR failure) skip this check. +- **Built-in actions** are generic capabilities defined in `situation/questions.ts` -> `BUILTIN_ACTIONS` (name, tier, + model-facing description) and implemented by per-subject `Controller`s (`decide/exec.ts`): mutation controller in + `runtime.ts` -> `gateMutation`; request/failure/stall controllers in `observe/fetch.ts` and `observe/xhr.ts`; + inconsistency/transition/error controllers in `runtime.ts` (`rollback`, `revertChain`, `resync`). +- Guard tier = withhold/deduplicate/slow down (`discard`, `defer`, `coalesce`, `delay`); heal tier = change what the + app receives or restore state (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions by + default). Passive per trigger (`PASSIVE`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, + inconsistency / transition / error `ignore`. +- **Custom actions** (`rt.action(def)`, `plugin.actions`) are offered next to the built-ins, gated at their own + tier (default `heal`), run inside a GenClass op, may call `ctx.builtin(name)` (re-checked against mode/policy/rate, + not thresholds), and are followed by the passive action unless a built-in took over. **Standing questions** + (`rt.question`, `plugin.questions`) add questions to the request; `onAnswer` gets the answer before any action. +- **Late revert:** a held write that applied because its budget expired can still be reverted by a gate-passing + `discard` that arrives within 2 s (`LATE_REVERT_MS`) of it applying, if nothing superseded it. +- Every model answer to a trigger produces a `Decision` (`d<n>`; `ask`/`decide` do not); every non-passive action attempt produces an `ActionRecord` + (`a<n>`, also when it failed). Both rings keep 200. `explain(id)` accepts either id. +- Reports (`decide/report.ts`): one line per detection (`[GenClass] Flagged …`) and per intervention + (`[GenClass] Prevented …`, `Reverted …`), console output deduplicated per 60 s window with a "×N more" summary. +- `ActionRecord.undo` exists only for reversible effects (discard, late revert, rollback, custom `onUndo`); it is + idempotent, runs inside a GenClass op named `undo` and is never gated (a discard's re-applied write is still + attributed to its original cause, see Drift 12). + +## Files + +| Path | Role | Key exports / entry points | +|---|---|---| +| `packages/runtime/src/decide/decider.ts` | Single-flight priority queue in front of the `DecisionProvider`: deadlines, runtime-side timeout, answer cache, latency samples, fail-open | `DeciderQueue` (`submit`, `latencies`, `clear`, `dispose`, `length`), `DecideResult`, `PROVIDER_TIMEOUT_MS` | +| `packages/runtime/src/decide/exec.ts` | Types only: the seam between the decision flow and the subject of a trigger | `ActionEffect`, `Controller`, `TriggerOpts`, `EndOpts`, `NetHost` | +| `packages/runtime/src/decide/policy.ts` | Policy config, mode/tier permission, the §8 gate, rate limiter, hold budget | `policyConfig`, `PolicyConfig`, `modeAllows`, `restriction`, `permittedActions`, `gate`, `GateInput`, `GateOutcome`, `RateLimiter`, `holdBudget`, `HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS` | +| `packages/runtime/src/decide/report.ts` | Report sentences and console sink with dedupe | `interventionLine`, `detectionLine`, `decisionLine`, `Reporter` | +| `packages/runtime/src/runtime.ts` | Wiring: `trigger`, `onDecision`, `runCustom`, mutation controller (`gateMutation`, `waitRelated`), inconsistency/transition/error controllers (`raiseInconsistency`, `raiseTransition`, `reportError`), `watchStall`, `rollback`, `revertChain`, `resync`, `runAsGenClass`, `explain`, `decisions`, `interventions`, `holdBudgetMs`, `action`, `question`, `use`, `setMode`, `pause`, `resume`, `destroy`, `setReport`, `isPaused` | `RuntimeImpl` (exported publicly from `src/index.ts`, so its public members are reachable by apps) | +| `packages/runtime/src/situation/questions.ts` | Action catalogue and diagnosis vocabulary (model-facing wording, frozen at tag `situation-v1`) | `BuiltinAction`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | +| `packages/runtime/src/situation/build.ts` | Which actions are offered for a subject (applicability); custom action options | `buildSituation`, `ActionOption`, `BuiltSituation` (internal `builtinApplicable`, `revertableChain`) | +| `packages/runtime/src/observe/fetch.ts` | fetch controllers: request gate (`send`/`coalesce`/`delay`/`block`/`serve_cached`), failure gate (`deliver`/`retry`/`serve_cached`), stall (`wait`/`hedge`/`serve_cached`) | `installFetch` (internal `runRequest`, `failureGate`, `stallController`, `reqCtl`) | +| `packages/runtime/src/observe/xhr.ts` | XHR request gate (`send`/`delay`/`block`/`serve_cached`); XHR failures/stalls are passive-only | `installXHR` (internal `fake`, `passiveOnly`) | +| `packages/runtime/src/observe/cache.ts` | Response buffers used by `coalesce` / `serve_cached` | `ResponseCache`, `makeResponse`, `blockedResponse`, `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS` | +| `packages/runtime/src/state/hub.ts` | Applies a mutation verdict (`apply`/`discard`/`defer`), late-revert checks and patches | `StoreHub.revertable`, `.revert`, `.reapply`, `.restoreFields`, `.commit`, `Verdict` | +| `packages/runtime/src/types.ts` | Public shapes | `Decision`, `Detection`, `ActionRecord`, `Report`, `Explanation`, `PolicyOptions`, `ActionDef`, `ActionContext`, `StandingQuestion`, `Plugin`, `EvaluateRequest`, `DecisionProvider`, `RuntimeEvents` | +| `packages/runtime/src/index.ts` | Re-exports `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` and `RuntimeImpl` publicly (not `decide/*`: `DeciderQueue`, `gate`, `policyConfig`, `PROVIDER_TIMEOUT_MS` etc. are internal) | — | +| `packages/runtime/test/helpers.ts` | Test doubles for this scope | `setup`, `ScriptedDecider`, `defaultScript`, `ManualDecider`, `choice`, `FakeClock`, `FakeServer`, `drain` | + +## Concepts and data structures + +**Terms introduced here** (beyond the shared glossary): + +- **controller**: an object implementing `Controller` for one trigger subject; `passive()` lets it proceed unchanged, + `run(action)` performs a built-in action and returns an `ActionEffect` (or throws/rejects when it cannot). +- **waits**: in `RuntimeImpl.trigger`, `opts.hold && permittedActions(...).length > 0 && !paused` — whether this + subject is actually held. A holdable trigger with no permitted action is not held. +- **expired**: the hold-budget timer fired before the decision; the passive action already ran. +- **candidate / mass**: the gate's argmax permitted action and Σ p over the permitted set (`GateOutcome`). +- **detection**: a `Decision` whose diagnosis ≠ `expected` and whose diagnosis probability ≥ `thresholds.report`. +- **intervention**: a non-passive action that ran (an `ActionRecord`). +- **GenClass op**: an instant op of kind `"genclass"` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause + `null`); writes and requests made inside it are never gated (`StoreHub.propose` bypasses `genclass` causes, + `NetHost.gated` is false for `op.genclass`) and are excluded from baselines and profiles. +- **sync verdict** (mutations only): the verdict `gateMutation` observed while `trigger` was still on the stack; + `"apply"` there means the write is not held at all (see flow 1). + +`decide/decider.ts` consumes `types.ts` -> `EvaluateRequest { trigger; state: JevState; questions; priority?; +subject?: SubjectRef; timeoutMs? }` (the runtime sets the first five; the queue adds `timeoutMs`). + +`situation/questions.ts` -> `BuiltinAction { name: string; tier: Tier; description: string }`; `Tier = "passive" | +"guard" | "heal"`, `Mode = "observe" | "guard" | "heal"` (`types.ts`). + +Action helpers on `RuntimeImpl` (public members, used by the controllers; no other caller in the repo): + +```ts +runAsGenClass<T>(name: string, fn: () => T): T // run fn inside a GenClass op +rollback(stores: string[], violationIds: string[] = [], beforeSeq?: number): ActionEffect // snapshot rollback +revertChain(op: OpRec, why: string): ActionEffect // chain revert (transition/error) +resync(stores: string[]): Promise<ActionEffect> // call StoreOptions.resync handlers +``` + +`decide/exec.ts`: + +```ts +interface ActionEffect { changed: string; undo?: () => void } // one sentence: exactly what GenClass altered +interface Controller { + passive(): void; // must be idempotent in practice + run(action: string): ActionEffect | Promise<ActionEffect>; // throw/reject => passive runs, record ok:false + revertable?(): string | null; // late revert (held writes only): null = can revert + revert?(): ActionEffect; +} +interface TriggerOpts { hold: boolean; priority: number } +``` + +`decide/decider.ts`: `DecideResult { answers; latencyMs /* provider time, 0 for cache hits */; waitMs; cached }`. +Internal `QueueItem { req; deadline?: number /* absolute clock ms */; resolve; seq; t0 }`. `submit()` resolves +`null` for every fail-open path, never rejects. + +`decide/policy.ts`: + +```ts +interface PolicyConfig { thresholds: { report: number; guard: number; heal: number }; allow?: Set<string>; + deny: Set<string>; holdBudgetMs: number | "auto"; holdUserWrites: boolean; maxActionsPerMinute: number; + requireDiagnosis: boolean } +interface GateInput { actions: { name: string; tier: Tier }[] /* all offered, passive included */; + probabilities: Record<string, number>; top: string /* model argmax over offered */; diagnosis: string; + mode: Mode; paused: boolean; now: number } +interface GateOutcome { run: string | null; candidate: string | null; mass: number; reason: string | null } +``` + +`situation/build.ts` -> `ActionOption { name; tier; description; custom?: ActionDef }` — `BuiltSituation.actions` +is the offered list, built-ins first in `TRIGGER_ACTIONS` order (passive first), then applicable custom actions. + +`types.ts` (public): + +```ts +interface Decision { // id "d<n>"; Detection = Decision + id; trigger; subject /* short subject text */; at; latencyMs /* trigger -> decision, incl. queue wait */; + model /* status.model ?? status.variant ?? "custom" */; diagnosis; diagnosisConfidence /* diagnosisProbabilities[diagnosis] ?? answer.confidence ?? 0 */; + diagnosisProbabilities; action /* run ?? model top */; confidence /* probabilities[action] */; probabilities; + executed /* run !== null || tier(action) === "passive" */; reason?; facts /* all ordered facts, ≤ 12 */; + tier /* tier of action */; candidate?; mass?; ran /* action that actually ran: run ?? PASSIVE[trigger] */; + answers /* every answer incl. standing questions */; subjectRef?; +} +interface ActionRecord { // id "a<n>" + id; decisionId; action; tier; trigger; subject; at; ok; error?; changed; undo?: () => void; late?: boolean; +} +interface Report { kind: "detect" | "intervene" | "status"; message: string; decision?: Decision; action?: ActionRecord } +interface Explanation { message; decision; situationText; facts; timeline; answers; action?; changed? } +interface ActionDef { name; description; on: TriggerKind[]; tier?: "guard" | "heal" /* default heal */; + risk?: "low" | "medium" | "high" /* declared, unused */; applicable?(sit: SituationDraft): boolean; + run(ctx: ActionContext): void | Promise<void> } +interface ActionContext { trigger; decision; situation /* SituationDraft */; runtime; + builtin(name: string): Promise<boolean>; describe(changed: string): void; onUndo(fn: () => void): void } +interface StandingQuestion { id; on: TriggerKind[]; question: Question; always?: boolean; + onAnswer?(a: Answer, ctx: { decision; situation; runtime }): void } +``` + +Internal `runtime.ts` -> `ExplainRec { decision; situationText /* stateText(situation.state) */; facts; timeline; answers; action? }`, +stored in `explainMap` under both the decision id and (once it exists) the action id. + +`state/hub.ts` -> `Verdict = "apply" | "discard" | "defer"` (what a held mutation's promise resolves to). + +### Action catalogue (`situation/questions.ts`) + +`TRIGGER_ACTIONS` (passive first) and `PASSIVE`: + +| trigger | actions offered (before applicability) | passive | +|---|---|---| +| `mutation` | `apply`, `discard`, `defer` | `apply` | +| `request` | `send`, `coalesce`, `delay`, `block`, `serve_cached` | `send` | +| `failure` | `deliver`, `retry`, `serve_cached` | `deliver` | +| `stall` | `wait`, `hedge`, `serve_cached` | `wait` | +| `inconsistency` | `ignore`, `rollback`, `resync` | `ignore` | +| `transition` | `ignore`, `rollback`, `resync` | `ignore` | +| `error` | `ignore`, `rollback` | `ignore` | +| `ask` | (none) | `""` | + +`ACTION_INSTRUCTIONS` (the `action` question's instructions): mutation "What should the runtime do with this write?", +request "… with this request?", failure "… with this failed request?", stall "… with this slow request?", +inconsistency "What should the runtime do about this inconsistent state?", transition "… about this unusual state +change?", error "… about this error?". `DIAGNOSIS_INSTRUCTIONS` = "What is happening here?". + +`DEFAULT_DIAGNOSES` (order matters; `expected` is always first via `diagnosisVocabulary`): `expected`, `stale`, +`conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, `overload`, `unusual`, `transient`. Descriptions are the +exact strings in CONTRACT §6 (asserted for `transient` in `test/batch3.test.ts`). + +The `action` question is only asked when more than one action is offered (`buildQuestions`); with a single +(passive) option the runtime treats the answer as `{ [passive]: 1 }`. Question building and compact questions are +documented in [learn-situation-triage.md](learn-situation-triage.md). + +## How it works + +### 1. Trigger -> queue (`runtime.ts` -> `RuntimeImpl.trigger`) + +Call sites and their `TriggerOpts`: + +| Raised by | trigger | hold | priority | +|---|---|---|---| +| `runtime.ts` -> `gateMutation` (hub `gate` hook) | `mutation` | true | 2 | +| `observe/fetch.ts` -> `runRequest` request gate | `request` | true (`keepalive` requests raise no trigger at all: `gateRequest` is false and they are sent at once) | 2 | +| `observe/fetch.ts` -> `failureGate` | `failure` | true | 2 | +| `observe/xhr.ts` -> `wSend` (async XHR only) | `request` | true | 2 | +| `observe/xhr.ts` -> `onEnd` | `failure` | false (passive-only controller) | 1 | +| `runtime.ts` -> `watchStall` | `stall` | false | 1 | +| `runtime.ts` -> `raiseInconsistency` | `inconsistency` | false | 1 | +| `runtime.ts` -> `raiseTransition` | `transition` | false | 0 | +| `runtime.ts` -> `reportError` | `error` | false | 0 | + +Network triggers are raised only when `NetHost.gated(op)` (not paused, not destroyed, not a GenClass op). +`watchStall` (registered by fetch with the stall controller and by async XHR with `passiveOnly`) fires once per op at +`max(4 × median, 2 × p95, STALL_MIN_MS 500)` ms, and only when the signature has a latency baseline +(`Baselines.latency`, ≥ 5 samples). Settled-point triggers (`inconsistency`, `transition`) are covered in +[state-and-adapters.md](state-and-adapters.md) and [learn-situation-triage.md](learn-situation-triage.md). + +Steps: + +1. `consultable()` must be true (not paused, not destroyed, a decider exists, its `status.state` is `"ready"` or + `"off"`); else run passive and return (no record). `"loading"` and `"error"` fail open here. +2. `computeFacts(env, spec)` (cheap pass). If `triage === "salient"`, no standing question with `always` covers this + trigger, and every fact is neutral -> passive, no record. +3. `buildSituation(...)` (a throw -> passive). Stored in `lastBuilt[trigger]` (what `rt.situation(trigger)` returns). +4. If `!built.salient && !built.forced` -> passive. +5. If the provider is not `"ready"` (i.e. `"off"`): read `this.ready` (starts the lazy load) and run passive. +6. `permitted = permittedActions(policy, mode, built.actions)`; `waits = opts.hold && permitted.length > 0 && !paused`. + If `!waits`, run passive **now** (the subject proceeds) and keep deciding in the background. +7. `budget = holdBudgetMs()`. If `waits`, start a budget timer: on fire set `expired = true` and run passive. +8. Deadline: `waits` -> `t0 + budget + (ctl.revert ? LATE_REVERT_MS : 0)` (only mutation controllers have + `revert`); not waiting -> `t0 + BACKGROUND_DEADLINE_MS` (5,000). +9. `queue.submit({ trigger, state, questions, priority: waits ? opts.priority : min(opts.priority, 1), subject }, deadline)`. +10. On result: clear the budget timer; destroyed or `null` -> passive; else `onDecision(...)`. Any throw -> passive. + +The `passive` closure in `trigger` is guarded by `passiveRan`, so the controller's `passive()` runs at most once +through that path. `t0` is read after the situation is built, so `Decision.latencyMs` excludes build time. + +Mutation specifics (`gateMutation`): it returns `{}` (no hold) when `consultable()` is false. Otherwise it calls +`trigger` synchronously; if the controller's `passive()` ran during that call (steps 1–6: triage-neutral, not +salient, provider `"off"`, nothing permitted), the sync verdict is `"apply"` and it returns `{}`, so the hub applies +the write in the caller's stack with no microtask delay. Only otherwise does it return `{ held: Promise<Verdict> }`. +The hub's separate `mayHold` hook (`consultable() && mode !== "observe"`) only decides whether a hold-safe preview is +prepared ([state-and-adapters.md](state-and-adapters.md)). + +### 2. Queue (`decide/decider.ts` -> `DeciderQueue`) + +1. `submit` pushes an item; if the queue exceeds `MAX_QUEUE` (32) the lowest-priority, oldest item is resolved + `null` (fail-open). +2. `pump` (while not busy): take the highest priority, oldest (`seq`) item. + - `now >= deadline` -> `null` (never computed). + - provider missing or not `"ready"` -> `null`. + - cache key `fnv1a(trigger + "\0" + stableStringify(state) + "\0" + stableStringify(questions))` (`util.ts`; + `subject` and `priority` are not part of it); a hit with `now - t <= CACHE_TTL` (30,000 ms) resolves with + `cached: true`, `latencyMs: 0` (no latency sample, no provider call). Hits are only served while the provider is + `"ready"` (checked first). + - else `dispatch`. +3. `dispatch`: `busy = true`; runtime-side timer `limit = deadline ? max(1, deadline - t1) : PROVIDER_TIMEOUT_MS` + (10,000). The provider receives `timeoutMs = max(1, deadline - t1)` when a deadline exists. +4. Provider resolves an object -> cache it (insertion-order eviction beyond `CACHE_MAX` 64), push `t2 - t1` to the + latency ring (last `LATENCY_SAMPLES` 20), resolve. Sync throw, rejection, or timer fire -> `onError` + `null`; + a non-object answer -> `null` without `onError`. The timer passes `onError` an `Error("the decision provider did + not answer in time")` with `code: "timeout"`. `done` is idempotent; it clears `busy` and pumps the next item + (so after a runtime timeout the next request is dispatched while the abandoned call may still be running). +5. `onError` in `runtime.ts`: `code === "max_tokens_exceeded"` shrinks automatic situation budgets + (`budgetScale = max(0.5, budgetScale × 0.8)`, never restored; only affects `situation.budget: "auto"`); every + error is logged (`console.debug`) only with `debug: true`. Model-host error codes (`model/errors.ts` -> + `ModelErrorCode`): `not_ready`, `max_tokens_exceeded`, `bad_request`, `unsupported`, `timeout`, `aborted`, `busy`, + `disposed`, `load_failed`, `integrity`, `inference_failed`; all fail open the same way. +6. `clear()` resolves every queued item `null`; `dispose()` (from `RuntimeImpl.destroy`) sets `disposed` (no more + pumping) and clears. + +`rt.ask()` / `rt.decide()` also use this queue: priority 1, deadline `now + timeoutMs` when given (else the 10 s +runtime timeout). They bypass triage, the gate and `Decision` records (see +[public-api-and-lifecycle.md](public-api-and-lifecycle.md)). + +### 3. Gate and bookkeeping (`runtime.ts` -> `onDecision`, `policy.ts` -> `gate`) + +1. Read `answers.action` / `answers.diagnosis` (`ChoiceAnswer`). Missing action answer -> `{ [passive]: 1 }`; a + `choice` not among the offered actions -> top = passive; missing diagnosis -> `expected` with `{ expected: 1 }`. +2. `gate(policy, rate, { actions: offered, probabilities, top, diagnosis, mode, paused, now })`, in this order: + 1. `paused` -> `"GenClass is paused"`. + 2. A empty -> `restriction(top)` or `"no action is permitted"`. + 3. `mass < threshold(candidate tier)` -> `restriction(top)` when the top is non-passive and restricted, else + `"probability <mass> for the permitted actions (<A>) is below the <tier> threshold <th>"`. + 4. `requireDiagnosis && diagnosis === "expected"` -> `"the model's diagnosis is expected"`. + 5. `rate.full(now)` -> `"rate limit: <N> actions in the last minute"`. + 6. Else `run = candidate`. + Reasons 1–3 are reported only when the model's own top choice was non-passive; 4–5 are always set. +3. Hold checks when `run` is set: held trigger that did not wait -> `"the subject was not held"`; held and + (`expired` or passive already ran) -> late-revert path (flow 5) for `discard` with `ctl.revert`, else + `"the decision arrived after the hold budget expired"`. Non-holdable triggers (`opts.hold` false) skip these + checks. "Not held" is only reachable when `setMode` widened the permitted set between trigger and answer + (`waits` is false only when nothing was permitted, the policy is fixed after construction, and a paused runtime + never reaches `submit`). These overrides never call `rate.take`. +4. A `rate limit` reason emits a status report at most once per 60,000 ms: + `[GenClass] Rate limit reached (<N> actions/minute): running passive actions until it clears.` +5. Build `Decision` (`action = run ?? top`), push to `decisionsBuf` (keeps 200) and `explainMap` (after adding a + decision id, if the map holds more than 400 ids the single oldest entry is evicted; action ids share the map and + are added in `finish` without a size check), push an event-log entry `kind "decision"`, name = trigger, `data { id, diagnosis, action, executed }`. +6. Fire `decide`; if detected (`diagnosis !== "expected" && diagnosisConfidence >= thresholds.report`) fire `detect`. +7. Call each applicable standing question's `onAnswer(answers[q.id], { decision, situation: draft, runtime })` + (errors logged, never thrown). Applicable = `q.on` includes the trigger (`BuiltSituation.standing`); skipped when + the provider returned no answer for `q.id`. This runs before any action executes and also when nothing runs. +8. No `run`: passive; if detected, emit a `detect` report (`detectionLine`). Done. +9. `run`: `rate.take(now)`, then flow 4. + +### 4. Executing an action (`runtime.ts` -> `onDecision` -> `finish`) + +1. Choose the effect: late -> `ctl.revert()`; custom (`ActionOption.custom`) -> `runCustom`; else `ctl.run(action)`. +2. Resolve -> `finish(effect)`. Throw/reject -> run passive, then `finish(null, err)`. +3. `finish` builds the `ActionRecord`: `ok = !err`; `changed = effect.changed` or, on error, + `"Tried to <action> <subject> but it failed; the passive action ran instead."` (or `"Ran <action>."`); + `error` = message; `late: true` for late reverts; `undo` wrapper when the effect had one. +4. Push to `actionsBuf` (keeps 200), set `rec.action` and `explainMap[record.id]`, push event `kind "action"`, + name = action, `data { text: changed, id, decision, ok }`, fire `act`, emit an `intervene` report + (`interventionLine`). + +`finish` runs when the effect settles, so `act` / the report arrive after the action's wait: `delay` ≤ 8 s, +`coalesce` ≤ 8 s (`COALESCE_MAX_WAIT_MS`), `retry` ≤ 5 s of backoff; `hedge` waits for the second request to settle +and `resync` for the store handlers, and a custom action until `def.run` resolves (no GenClass cap on those three). + +Errors a controller throws (they become `ActionRecord.error`, `ok: false`, and `(failed: <error>)` in the line): + +| Thrown by | Message | +|---|---| +| any controller | `unsupported action <name>` | +| `gateMutation` -> `revert` | `the write could not be reverted` (`hub.revert` returned null) | +| fetch request gate | `the request was already sent`, `no Response constructor`, `no cached response`, `no identical request to share`, `the response of #<id> could not be shared; sent the request instead` | +| fetch failure gate | `the failure was already delivered`, `the request body cannot be replayed`, `no cached response`, `aborted` (app aborted during the retry backoff) | +| fetch stall | `already answered`, `no cached response`, `not hedgeable` | +| XHR request gate | `already decided` (also after the app aborted the held XHR), `no cached response` | +| XHR failure/stall (`passiveOnly`) | `<action> is not available for XMLHttpRequest` (never reached: only the passive action is offered) | +| `rollback` | `no consistent snapshot`, `nothing to restore: the affected stores already match the snapshot` | +| `revertChain` | `the chain wrote nothing that can be restored`, `nothing to restore: the fields already hold their earlier values` | +| `resync` | `no resync handler` (or the handler's own rejection) | +| custom action | whatever `def.run` throws or rejects with | + +### 5. Late revert (held mutations only) + +1. Budget timer fires -> passive -> the hub applies the write (`MutationRec.appliedAt` set). +2. The queue keeps waiting until `t0 + budget + 2000`. +3. A decision with gate result `run === "discard"` -> `ctl.revertable()` in `gateMutation`: + `"the write has not applied yet"`; `"too late to revert: decided <secs> after the write applied"` (age > 2,000 ms; + a backstop: the queue deadline `t0 + budget + 2000` normally expires first, so an answer that late yields no + `Decision` at all, as `test/atoms.test.ts` asserts); then `StoreHub.revertable(m)`: `"the store is gone"`, `"the write was not applied"`, + `"<store> cannot be written by GenClass"`, `"the write changed nothing"`, + `"superseded: <path> changed again after the write applied"`, + `"the same operation chain wrote <paths> after this write applied; reverting only this write would leave them inconsistent"`. + Any string becomes `Decision.reason` and nothing runs. +4. `null` -> `late = true`; `ctl.revert()` runs `hub.revert(m)` inside `runAsGenClass("revert")`: + `changed` = `Reverted the write to <≤3 paths>[ and N more][ from <cause>] (decided <secs> after it applied)[; <path> is back to <value>…≤2].`; + undo = `hub.reapply(m)`. Report lead is `Reverted`. + +Any other late non-passive action (`defer`, or a custom action) or a late request/failure decision is recorded with +`"the decision arrived after the hold budget expired"` (`apply` is passive, so it is never a gate `run` and never +reaches this path). A late request/failure decision is rare: its queue deadline equals the budget, so the queue +abandons the item when the budget expires and usually no `Decision` is recorded. + +### 6. Custom actions and standing questions (`runtime.ts` -> `action`, `question`, `use`, `runCustom`) + +Registration: `rt.action(def)` / `rt.question(def)` append to `customActions` / `standing` and return an +unregister function (removes that exact object). `rt.use(plugin)` appends `plugin.actions` and `plugin.questions`, +runs `plugin.setup(pluginApi)` (a throw is logged; a returned function is the cleanup) and returns an unregister +function; calling `use` again with the same plugin object registers nothing. Unregister / `destroy()` removes the +plugin's actions and questions and runs its cleanup. `plugin.diagnoses` labels are appended after the base +vocabulary (never overriding a label) and `plugin.facts` add neutral facts, both read at every build +([learn-situation-triage.md](learn-situation-triage.md)). Standing questions with `always: true` bypass the +salient-triage early exit (flow 1 step 2/4); their answers are delivered in flow 3 step 7. + +1. Offered (`build.ts`) when `def.on` includes the trigger, no earlier option has the same name, and + `def.applicable(draft)` is true (a throw = false). Tier `def.tier ?? "heal"`; description + `vocabulary.actions[name] ?? def.description`. +2. Gated like any action (its own tier's threshold), then `def.run(ctx)` runs inside `runAsGenClass(def.name)` on a + microtask, so its writes and requests are GenClass ops (never gated). +3. `ctx.builtin(name)`: false unless `name` is a built-in **offered for this trigger**. The passive name calls + `ctl.passive()` and returns true. Otherwise false when paused, `restriction(...)` blocks it (mode tier, deny, + allow) or the rate limiter is full; else `rate.take` (a second slot), `await ctl.run(name)`, adopt its `changed` + (if `describe` was not called yet) and `undo` (if `onUndo` was not called yet), return true. Thresholds and the + diagnosis rule are **not** re-applied. +4. After `run` resolves: if no builtin took over, `ctl.passive()` runs (the held write applies, the request is + sent). `changed = describe text || "Ran the custom action <name>."`. + +### 7. Reporting (`decide/report.ts`) + +Lines (exact templates): + +```text +interventionLine: [GenClass] <lead> <noun>: <topFact> <changed>[ (failed: <error>)] (<diagnosis>, <pDiag>; <action> <confidence>) +detectionLine: [GenClass] Flagged <noun>: <topFact>[ Not acted on (would have done <x>): <reason>.] (<diagnosis>, <pDiag>) +decisionLine: [GenClass] Checked <subject>: <diagnosis> (<pDiag>); ran <ran>[ (the model chose <action>[; <reason>])]. +``` + +- `lead`: `LEAD[action]` (`discard`/`coalesce` "Prevented", `defer` "Held back", `delay` "Slowed down", `block` + "Stopped", `serve_cached`/`retry` "Recovered from", `hedge` "Worked around", `rollback`/`resync` "Repaired"), + `"Reverted"` when `late`, `"Handled"` for custom actions. +- `noun`: `an(NOUN[trigger])` for `expected`; `"inconsistent state"` for inconsistency+inconsistent; else + `an("<diagnosis> <NOUN>")`. `NOUN`: write, request, request failure, slow request, state, state change, error, question. +- `topFact`: first fact not matching `/^This (write|request) (comes from|has no known cause)/`, with a trailing period. +- Probabilities are `toFixed(2)`, `?` when undefined or not finite. The `Not acted on (…)` clause is added only when + `Decision.reason` is set and `executed` is false. `<x>` = `"<candidate> <mass> for permitted actions"` when the + candidate differs from `action` (and `mass` is set), else `"<action> <confidence>"`. + +`Reporter.emit(r)`: + +1. Always call the listener -> runtime `report` event (also with `report: "silent"`). +2. `"silent"` -> stop. A function sink -> call it (errors swallowed), no dedupe, no grouping. +3. `"console"`: `status` -> `console.info(line)`. Others are deduped by key + `kind|action|diagnosis|trigger|subject` (subject with `#\d+` -> `#`, numbers -> `n`): the first in a 60,000 ms + window prints; repeats are counted; when the window ends `"<first line> (×N more in the last minute)"` prints via + `warn` (intervene) or `info` (detect). +4. A printed line with an `explain()` record becomes `console.groupCollapsed(line)` with: `Facts:`, `Timeline:` (if + any), `Situation sent to the model:` + exact text, `Answers:`, and for actions `Changed:`, an undo hint + (`GenClass.runtime.interventions().find(a => a.id === "<id>").undo()` or `Undo: not reversible`), a deny hint + (`GenClass.init({ policy: { deny: ["<action>"] } })`), then `explain: GenClass.runtime.explain("<id>")`. + Without `groupCollapsed`: `warn` (intervene) / `info` (detect). + +Status lines emitted by `runtime.ts`: `[GenClass] Model ready (<model, device, variant>[, <secs>]). Mode: <mode>.`, +`[GenClass] Model unavailable (<error>); observing only.`, `[GenClass] Mode set to <mode>.`, and the rate-limit line. + +### 8. explain and undo + +- `explain(id)` (`runtime.ts` -> `RuntimeImpl.explain`): looks up `explainMap`; `message` = `interventionLine` if an + action is attached, else `detectionLine` if detected, else `decisionLine`. Returns `null` for unknown/evicted ids. + `facts` are all ordered facts (≤ 12); `situationText` is the budget-limited text the model read. +- `ActionRecord.undo()` wrapper: no-op after the first call; runs the effect's undo inside + `runAsGenClass("undo")`; pushes event `kind "action"`, name `"undo"`, `data { text: "undid <action> (<id>)", id }`. + It fires no `act` event, no report, and does not mark the record. An exception from the effect's undo propagates + to the caller, after which the wrapper is already spent (`undone = true` is set first) and no event is pushed. +- `decisions(n = 200)` / `interventions(n = 200)` return the last `n` entries of the rings, oldest first + (`slice(-n)`); records are the live objects (mutating them affects later `explain` output). +- `holdBudgetMs()` (public on `Runtime`) returns the budget the next held trigger would use. + +### 9. Mode, pause, resume, destroy (decision-side effects) + +| Call | Effect in this scope | +|---|---| +| `setMode(mode)` | ignored unless `"observe" \| "guard" \| "heal"`; sets the mode used by the next `trigger` / `gate` / `ctx.builtin`; emits status `[GenClass] Mode set to <mode>.` and fires `status` with the model status | +| `pause()` | `paused = true`, `hub.gating = false` (writes commit unheld), `NetHost.gated` false (no request/failure/stall triggers); `consultable()` false, so every other trigger runs passive with no record; decisions already queued still produce a `Decision` but never run (`gate` -> `"GenClass is paused"`, shown when the model's top was non-passive); tracing continues | +| `resume()` | undoes `pause()` (no-op after `destroy`) | +| `isPaused` | getter on `RuntimeImpl` only (not on `Runtime`) | +| `destroy()` | `destroyed = true`, `hub.gating = false`, `queue.dispose()` (pending decisions resolve `null` -> passive), `reporter.dispose()` (open dedupe windows are dropped: pending "×N more" summaries never print), observers uninstalled, plugins unregistered, an owned provider disposed | +| `setReport(sink)` | `RuntimeImpl` only (not on `Runtime`): swaps the report sink live (`Reporter.setSink`) | + +### Events + +| Event (`rt.on`) | Payload | When | +|---|---|---| +| `decide` | `Decision` | every model answer that reached `onDecision` | +| `detect` | `Decision` | diagnosis ≠ `expected` and p(diagnosis) ≥ `thresholds.report` (also when an action ran) | +| `act` | `ActionRecord` | every non-passive action attempt, `ok` true or false, after its effect settled | +| `report` | `Report` | every report (detect/intervene/status), before the sink, even when silent | +| `status` | `ModelStatus` | provider `onStatus`; also on `setMode` (payload is the model status, not the mode) | +| `event` | `RtEvent` | every event-log entry, including `decision`, `action` and `undo` entries | + +`action` (and `undo`) event-log entries appear in later situations' timelines as `<rel> GenClass <changed text>` +(`situation/describe.ts` -> `eventLine`, text truncated to 100 chars); `decision` entries are not rendered. +Listener exceptions are caught and logged (`fire`), never thrown into the decision flow. + +### 10. Built-in action reference + +Tiers and descriptions come from `BUILTIN_ACTIONS`; applicability from `situation/build.ts` -> `builtinApplicable`. +`opLabel(op)` (`situation/describe.ts`) renders like `GET /api/x (#12)` (phrase truncated to 90 chars; `an earlier +operation` when missing); `secs(ms)` (`util.ts`) gives 2 decimals below 10 s (`0.30s`), 1 decimal below 1,000 s, +else whole seconds. + +| action | tier | trigger(s) | offered when | mechanics (where) | `changed` (abridged) | undo | +|---|---|---|---|---|---|---| +| `apply` | passive | mutation | always | verdict `apply`: hub applies now or at drain (`gateMutation` -> `passive`) | — | — | +| `discard` | guard | mutation | always | verdict `discard`: hub drops it, `set` caller not notified (`gateMutation`) | `Dropped the write to <paths>[ from <cause>]; <store> stays at version <v>.` | apply the write now on top of the current value (`hub.commit(st, { ...m, userSync: false, genclass: true, state: "resolved" }, false)`: functional updaters re-run, value writes patched; bypasses `propose`, so never gated); recorded with the original cause as writer (see Drift 12) | +| `defer` | guard | mutation | `m.defers < 2` | verdict `defer`: hub waits for related in-flight ops (`waitRelated`, cap `LONG_RUNNING_MS` 10,000), re-proposes the write (new trigger); after 2 defers it applies (`StoreHub.drain`/`defer`) | `Held the write to <paths> until the related in-flight operations finish, to decide again.` | — | +| `send` | passive | request | always | send now (`sendNow` / XHR `doSend`) | — | — | +| `coalesce` | guard | request | fetch only, and `cache.shareable(identity, op.id)`: an older identical fetch in flight or settled ≤ 2,000 ms ago | wait ≤ `COALESCE_MAX_WAIT_MS` 8,000 for its buffered response, answer a copy marked `x-genclass: coalesced` (opaque responses: unmarked clone), end op synthetic; unshareable -> send and throw | `Did not send <op>; reused the <status> response of the identical request #<id>[ (x-genclass: coalesced)].` | — | +| `delay` | guard | request | always | wait `min(250 × 2^failStreak(signature), 8000)` ms, then send (fetch and XHR) | `Delayed <op> by <secs> before sending it.` | — | +| `block` | heal | request | always | do not send; 503 `Response`, statusText `Blocked by GenClass`, header `x-genclass: blocked`; op ends `blocked` (XHR: faked 503 + `load`/`loadend`) | `Did not send <op>; answered 503 (x-genclass: blocked).` | — | +| `serve_cached` | heal | request | GET and a cached good response exists (`cache.peek`) | answer the last good GET body (≤ 256 KB), `x-genclass: cached`; op ends `ok` synthetic (XHR: faked response) | `Did not send <op>; answered with the cached <status> response from <age> ago (x-genclass: cached).` | — | +| `deliver` | passive | failure | always | hand the original `Response` / rejection to the app | — | — | +| `retry` | heal | failure | fetch, replayable body, `op.attempt < 4` | after `min(200 × 2^(attempt-1), 5000)` ms start a new fetch op (`attempt + 1`, cause = failed op) and send it; it passes through the failure gate again; the app gets that attempt's result | `Retried <op> after <secs> as attempt <n> (#<id>); the app will receive that attempt's result.` | — | +| `serve_cached` | heal | failure | fetch, GET, cached | answer the cached response instead of the failure | `Replaced the failed response of <op> with the cached <status> response from <age> ago (x-genclass: cached).` | — | +| `wait` | passive | stall | always | nothing | — | — | +| `hedge` | heal | stall | fetch, GET, idempotent, replayable | send a second identical request (op detail `(hedge)`, cause = original); first good answer wins | `Sent a second identical request #<id> for <op>; it answered first (<status>) and the app received it.` / `…; the original answered first.` / `…; it failed, so the app keeps waiting for the original.` | — | +| `serve_cached` | heal | stall | fetch, GET, cached | answer the cached response now; the original continues in the background | `Answered <op> with the cached <status> response from <age> ago instead of waiting (x-genclass: cached); the original request continues in the background.` | — | +| `ignore` | passive | inconsistency, transition, error | always | nothing | — | — | +| `rollback` | heal | inconsistency | a consistent snapshot exists and an involved store is writable | `RuntimeImpl.rollback(stores, violationIds)`: write the last consistent snapshot (of ≤ 8 kept) back to the involved writable stores | `Restored <store (paths)>; … to the consistent state from <secs> ago.` | write back the pre-rollback values and mute those violation ids until they hold again | +| `rollback` | heal | transition, error | the op's chain wrote fields nobody overwrote since, with a known earlier value, in a writable store (error: an ambient op existed) | `RuntimeImpl.revertChain(op, why)`: restore exactly those fields to their values before the chain's first write | `Restored <≤4 paths>[ and N more] to their values before <root op> (the <why>'s chain wrote them).` (`why` = `transition` or `error`) | restore the replaced values | +| `resync` | heal | inconsistency, transition | an involved store has `StoreOptions.resync` | call each such store's `resync()` inside `runAsGenClass("resync")` | `Reloaded <stores> from its/their source (resync handler).` | — | + +Notes: + +- Other `changed` variants: coalesce when the app was answered meanwhile -> `Coalesced <op> with #<id>, but the app + was already answered.`; retry when the app was answered during the backoff -> `Did not retry <op>: the request was + already answered.` (both `ok: true`). A retry whose signal aborted during the backoff rejects the app's promise with + the abort reason and records `ok: false`, error `aborted`. +- `defer`'s "related in-flight operations" (`runtime.ts` -> `waitRelated`): in-flight ops that are neither ancestors + nor descendants of the write's cause and either share the cause's name and kind or have a signature whose chains + have written this store before (`storeWriters`); none -> re-proposed at once. +- Store sets: inconsistency `rollback`/`resync` act on the first path segment of every violated field; transition + `resync` on the first segment of the op chain's written fields that are registered stores. `rollback` skips stores + that are unregistered, not writable or absent from the snapshot; snapshots are taken at settled points where + nothing newly broke (last 8 kept, `runtime.ts` -> `settled`). +- XHR: `coalesce`, `retry`, `hedge` and failure/stall `serve_cached` are never offered (transport check); + XHR failures and stalls use `passiveOnly()` and are detection only. Synchronous XHRs are never held. +- The response cache keeps the last good GET body per identity (`MAX_ENTRIES` 64 × `MAX_BODY` 256 KB, memory only); + coalescing buffers expire `COALESCE_WINDOW_MS` 2,000 ms after settling (≤ 64 entries, ≤ 4 MB); a body still + streaming after `BUFFER_WAIT_MS` 1,000 ms is not shareable (`observe/cache.ts`). Identity details: + [observe-and-trace.md](observe-and-trace.md). +- `rollback`'s model-facing description says "last consistent snapshot" for every trigger, but transition/error + rollback is a chain revert (see Drift). + +## Configuration and constants + +| Name | Type | Default / value | Defined in | Effect | +|---|---|---|---|---| +| `mode` | `"observe" \| "guard" \| "heal"` | `"guard"` | `runtime.ts` constructor | which tiers are permitted (`policy.ts` -> `modeAllows`); `setMode` changes it live | +| `policy.thresholds.report` | number | 0.6 | `policy.ts` -> `policyConfig` | min diagnosis probability for a detection | +| `policy.thresholds.guard` | number | 0.9 | `policyConfig` | min Σ p(A) when the candidate is guard tier | +| `policy.thresholds.heal` | number | 0.8 | `policyConfig` | min Σ p(A) when the candidate is heal tier | +| `policy.allow` | `string[]` | unset | `policyConfig` | only these non-passive actions may run | +| `policy.deny` | `string[]` | `[]` | `policyConfig` | these never run | +| `policy.holdBudgetMs` | `number \| "auto"` | `"auto"` | `policyConfig`, `holdBudget` | max hold; a number is used as `max(0, n)` | +| `HOLD_MIN_MS` / `HOLD_MAX_MS` / `HOLD_FALLBACK_MS` | ms | 150 / 800 / 300 | `policy.ts` | auto budget clamp and no-data fallback | +| `policy.holdUserWrites` | boolean | false | `policyConfig` -> `StoreHub.holdUserWrites` | hold writes made synchronously in a user handler | +| `policy.maxActionsPerMinute` | number | 60 | `policyConfig`, `RateLimiter` | sliding 60,000 ms window of non-passive actions | +| `policy.requireDiagnosis` | boolean | true | `policyConfig` | require top diagnosis ≠ `expected` | +| `report` | `"console" \| "silent" \| fn` | `"console"` | `runtime.ts` constructor; `setReport()` changes it | report sink | +| `MAX_QUEUE` | number | 32 | `decider.ts` | queue overflow drops lowest-priority, oldest | +| `CACHE_MAX` / `CACHE_TTL` | number / ms | 64 / 30,000 | `decider.ts` | identical-situation answer cache | +| `LATENCY_SAMPLES` | number | 20 | `decider.ts` | provider latencies kept for the auto hold budget | +| `PROVIDER_TIMEOUT_MS` | ms | 10,000 | `decider.ts` (exported) | runtime-side timeout when a request has no deadline | +| `LATE_REVERT_MS` | ms | 2,000 | `runtime.ts` | late-revert window; also extends held-mutation deadlines | +| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `runtime.ts` | deadline of non-held decisions | +| `DECISIONS_KEPT` | number | 200 (explainMap 400) | `runtime.ts` | `decisions()`, `interventions()`, explain retention | +| `LONG_RUNNING_MS` | ms | 10,000 | `runtime.ts` | cap on `defer`'s wait for related ops | +| `WINDOW_MS` | ms | 60,000 | `report.ts` | console dedupe window | +| rate-limit warning interval | ms | 60,000 | `runtime.ts` -> `onDecision` (literal) | at most one rate-limit status line per minute | +| `COALESCE_MAX_WAIT_MS` | ms | 8,000 | `observe/fetch.ts` | coalesce wait for the shared response | +| delay backoff | ms | `min(250 × 2^streak, 8000)` | `fetch.ts` / `xhr.ts` (literal) | `delay` | +| retry backoff | ms | `min(200 × 2^(attempt-1), 5000)` | `fetch.ts` (literal) | `retry` | +| max retry attempt | number | offered while `attempt < 4` | `build.ts` -> `builtinApplicable` | at most 3 retries | +| max defers | number | 2 | `build.ts`, `hub.ts` -> `drain` (literals) | then the write applies | +| `COMPACT_QUESTIONS_BUDGET` / `COMPACT_DESC_MAX` | chars | 1,400 / 24 | `questions.ts` | compact questions drop descriptions (custom ones too) | +| `STALL_MIN_MS` | ms | 500 | `runtime.ts` | floor of the stall delay `max(4 × median, 2 × p95, 500)` | +| `budgetScale` step / floor | factor | × 0.8 per `max_tokens_exceeded`, floor 0.5 | `runtime.ts` constructor (`onError`) | shrinks `"auto"` situation budgets | +| consistent snapshots kept | number | 8 | `runtime.ts` -> `settled` (literal) | how far back `rollback` (inconsistency) can restore | +| `MAX_FACTS` | number | 12 | `situation/facts.ts` | `Decision.facts` / `explain().facts` length cap | +| `debug` | boolean | false | `runtime.ts` constructor | `console.debug` of model errors, decisions, failed listeners/standing questions/passive actions | + +## Invariants and gotchas + +- **No rules.** Nothing in this scope may map a fact pattern to a diagnosis or action (CONTRACT §0 rule 1). The gate + only filters what the model chose; triage only decides whether to ask. +- **Fail-open is total.** `submit()` never rejects; every failure is `null` -> passive. New code paths must keep + calling the controller's `passive()` on every exit. Controllers must tolerate a second `passive()` call + (`runCustom` calls `ctl.passive()` directly, outside the `passiveRan` guard, from `ctx.builtin(<passive>)` and + after `run`). Existing ones do: the mutation `settle` resolves its promise once; fetch `sendNow`/`deliver` check + `sent`/`answered`/`handled`; the XHR request controller checks `decided`. +- **Model wording is frozen.** `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` order, `ACTION_INSTRUCTIONS`, + `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES` and `PASSIVE` are model input and are mirrored in + `training/curriculum/rt.py`, `training/curriculum/fmt.py`, `training/eval_runtime.py` and the sim. The scope + files are unchanged since tag `situation-v1` (`1a77558`). `ActionRecord.changed` is also model input: it appears in + later timelines. +- **Threshold semantics:** the threshold is the candidate's tier's, applied to the mass of all permitted actions. + Guard (0.9) is stricter than heal (0.8). With `thresholds` of 0 the gate runs the first permitted action even at + probability 0 (`p(a) > p(candidate)` is strict); the sim therefore uses 0.5 (`sim/src/run/rt.ts`). +- **`Decision.action` may differ from the model's argmax** when a permitted candidate runs while a non-permitted + action (passive or restricted) was top (only reachable with lowered thresholds or many actions: with the 0.9 + guard threshold a passive top would need ≥ 9 permitted actions). `executed` is true when an action ran, + even if it then failed (`ok: false`). +- **Failed actions count:** `rate.take` happens before the effect, so failures consume rate slots; a custom action + that calls `ctx.builtin` consumes two. +- **Holds can outlast the budget after a decision:** the budget timer is cleared when the answer arrives; `coalesce` + (≤ 8 s), `delay` (≤ 8 s), `retry` backoff (≤ 5 s) and custom actions (unbounded) keep the subject waiting. +- **Runtime timeout does not cancel the provider.** After the timer fires the queue dispatches the next request; + a late answer from the abandoned call is still cached and its latency still enters the hold-budget samples + (code reading; the model host has its own queue and timeouts, see [model-host.md](model-host.md)). +- **Determinism:** only the injected `Clock` is used (timers, `now`); ids are counters (`d<n>`, `a<n>`). Do not add + `Date.now`/`setTimeout` here (CONTRACT §0 rule 3). +- **Precision / harm:** nothing is held when no action is permitted (observe mode; failures in guard mode), so the + default mode adds no latency for triggers it could not act on. Holding still delays salient writes/requests up to + the budget (OPEN_TASKS: hold-induced harm). +- **Console hints** reference `GenClass.runtime`, which is `null` for runtimes made with `createRuntime`. +- **Devtools mirrors report wording** (`src/devtools/ui.ts` -> `LEAD`, `NOUN`, `splitReport` regexes for + `Not acted on (…)` and `(diag, p; action p)`). Changing a line format can break the overlay. +- **Compact questions** (budget ≤ 1,400 chars) send custom action descriptions as `null` unless a vocabulary + override ≤ 24 chars exists, so the model sees only the custom action's name. +- **Answer cache in tests:** identical `(trigger, state, questions)` within 30 s are answered from the queue cache, + so `ScriptedDecider.calls` does not grow and a changed script does not apply to a repeated identical situation. + Advance the fake clock past 30 s or vary the situation. +- **Undo is unguarded:** `ActionRecord.undo()` ignores mode, pause, policy and the rate limit, and never checks + whether the state moved since (a discard's undo re-runs/patches the write over the current value; a rollback's + undo writes back whole pre-rollback store values). +- **Dead surface:** `RuntimeImpl.rollback`'s `beforeSeq` parameter is never passed (only the last consistent + snapshot is used); `RuntimeImpl.setReport` has no caller (Drift 13; devtools listens to `on("report")`). + +## How to change it safely + +Run tests with `npm test` / `vitest run` in `packages/runtime`. The team ran them on the VM (CONTRACT §0 rule 5). +Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the unit tests locally (see +[build-test-release.md](build-test-release.md#where-to-run-things)). + +1. **Change a default threshold, budget or rate:** edit `policy.ts` -> `policyConfig` / `HOLD_*`; update the JSDoc + in `types.ts` -> `PolicyOptions`, `docs/runtime/API.md`, and assertions in `test/policy.test.ts`, + `test/budget.test.ts`, `test/fetch.test.ts` ("request gate fails open after the hold budget" expects 300 ms; the + failure-gate fail-open test also depends on the 300 ms fallback). +2. **Change gate logic:** edit `policy.ts` -> `gate` only; keep reason strings stable (asserted verbatim in + `test/policy.test.ts`, `test/report.test.ts`, and parsed by devtools). Check the sim's forced-action contract + (`sim/src/run/rt.ts` thresholds 0.5, `requireDiagnosis: false`). +3. **Change an action's mechanics:** edit its controller (table above). Keep: throw when it cannot run (passive then + runs); return an exact `changed` sentence; provide `undo` only if truly reversible; end synthetic ops with + `synthetic: true` so baselines ignore them. Coordinate `changed` wording with SIM (timeline input). Tests: + `test/fetch.test.ts`, `test/xhr.test.ts`, `test/atoms.test.ts`, `test/review-fetch.test.ts`, `test/review-xhr.test.ts`. +4. **Add a built-in action:** add to `BUILTIN_ACTIONS` and `TRIGGER_ACTIONS` (passive stays first), applicability in + `build.ts` -> `builtinApplicable`, implementation in the trigger's controller, `LEAD` in `report.ts` and + `devtools/ui.ts`. This changes model input: it needs a new freeze tag, sim + training mirrors, new data and a + retrained model. Do not do it inside the runtime alone. +5. **Change report wording:** `report.ts` templates; update `test/report.test.ts`, `test/atoms.test.ts` (late revert + line), `test/review-misc.test.ts`, and `src/devtools/ui.ts` + `test/devtools*.test.ts`. +6. **Change queue behaviour:** `decider.ts`; tests `test/budget.test.ts` (timeoutMs, expired items not computed), + `test/batch3.test.ts` and `test/review-misc.test.ts` (provider that never answers), `test/atoms.test.ts` + (provider error codes fail open with no time passing). +7. **Custom action / standing question API:** `runtime.ts` -> `runCustom`, `action`, `question`, `use`; `build.ts` + for offering; tests `test/plugins.test.ts`, `test/batch3.test.ts`, `test/review-misc.test.ts`. +8. **Write a test for this scope:** `test/helpers.ts` -> `setup({ mode, policy, script })` gives a headless + `RuntimeImpl` on a `FakeClock` with a `FakeServer` fetch, `report: "silent"` and only the fetch observer. + `defaultScript({ mutation: { diagnosis: "stale", action: "discard", p } })` answers per trigger (passive when the + action is not offered) via `choice(label, labels, p = 0.97)`, which puts `p` on the label and splits the rest + evenly. Use `ManualDecider` (`answer()` releases the oldest pending request) to control timing for budget + expiry / late-revert tests. Advance time with `clock.advance(ms)` / `clock.runAll()` and flush with `drain()`. +9. **Add a new trigger kind's controller:** implement `Controller` (`decide/exec.ts`), call `host.trigger(spec, + ctl, { hold, priority })`, and only add `revertable`/`revert` if the subject can be reverted exactly; a `revert` + on the controller extends the queue deadline by `LATE_REVERT_MS`, and `onDecision` only uses it for a late + `discard`. Adding the trigger kind itself changes model input (see 4). + +## Tests + +| Test file | What it asserts (scope-relevant) | +|---|---| +| `packages/runtime/test/policy.test.ts` | gate: mass split (discard 0.5 + defer 0.45 runs), mode tiers, thresholds 0.9/0.8 with exact reason text, no reason when top is passive, `requireDiagnosis`, deny/allow, pause, rate limit + sliding window, observe never holds, `setMode`, `pause/resume`, loading fails open with no record, detection threshold | +| `packages/runtime/test/report.test.ts` | intervention/detection line formats, `explain()` by action or decision id, console group contents, ×N summary at window end, `decide`/`detect`/`act`/`event` listeners | +| `packages/runtime/test/atoms.test.ts` | holds; fail-open at budget; late revert exact `changed` text, `Reverted` line and undo; refusals (superseded, same chain); an answer more than 2 s after the budget records no `Decision` (queue deadline); late `defer` only recorded; provider error codes `not_ready`/`max_tokens_exceeded`/`timeout`/`busy` fail open with no time passing; discard + undo; defer max 2 | +| `packages/runtime/test/budget.test.ts` | `holdBudget` auto values (300, 600, 800, 150, 345, fixed 50); adaptive budget from latencies; `timeoutMs` = budget + 2,000 for held writes and = budget for requests; expired queued items never computed; `max_tokens_exceeded` shrinks automatic situation budgets (queue `onError` path) | +| `packages/runtime/test/fetch.test.ts` | coalesce, block (heal), guard never runs heal, serve_cached, delay 250 ms, retry backoff 200 ms and attempts, retry not offered for streams, failure delivered, failure/request gates fail open at 300 ms, hedge | +| `packages/runtime/test/xhr.test.ts` | XHR block 503, failures detection-only, request gate hold and fail-open | +| `packages/runtime/test/review-fetch.test.ts` | coalesce never hangs (opaque, streaming), failure not held in guard mode, keepalive never held | +| `packages/runtime/test/review-hub.test.ts` | undo of a late revert restores the write exactly; a held in-place update is not visible before it applies, and `discard` really drops it | +| `packages/runtime/test/review-actions.test.ts` | error rollback offered only when the chain wrote state; other chains untouched | +| `packages/runtime/test/invariants.test.ts` | inconsistency rollback to snapshot, undo, one trigger per episode | +| `packages/runtime/test/learn.test.ts` | transition rollback restores the chain's fields (exact `changed`) | +| `packages/runtime/test/plugins.test.ts` | plugin facts/diagnoses/actions reach the model; custom action runs then passive; `ctx.builtin("discard")`; custom default heal tier; `applicable()`; standing question + `onAnswer`; vocabulary overrides | +| `packages/runtime/test/batch3.test.ts` | `ctx.builtin` obeys deny; rate-limit warning once; never-answering provider does not block; `transient` label | +| `packages/runtime/test/review-misc.test.ts` | every intervention reaches the console; rate warning once; denied heal builtin not run in guard; queue robustness; `ask()` after destroy | +| `packages/runtime/test/devtools-runtime.test.ts` | overlay undo applies a dropped write; report sentences in the overlay | +| `packages/runtime/test/smoke.test.ts` | end to end: held stale write discarded in guard mode; atoms apply synchronously when nothing is salient | +| `packages/runtime/test/review-xhr.test.ts` | sync XHR never held; an XHR the app aborts while held is never sent; XHR reused after a blocked answer shows the real state | +| `packages/runtime/test/adapters-react.test.ts`, `adapters-redux.test.ts`, `adapters-zustand.test.ts` | held async writes through adapters; `discard` drops them (no reducer/subscriber), recorded in `interventions()`; react undo | +| `packages/runtime/test/ask.test.ts` | `ask` sends a trigger-`ask` request with the single question `answer` and returns a typed answer; `decide` returns the label; `about` focuses the situation; no model -> rejects with `GenClassUnavailableError`; `timeoutMs` -> reason `timeout` | + +## Drift and open issues + +Doc-vs-code mismatches (code is authoritative): + +1. `docs/runtime/CONTRACT.md` §8 says `holdBudgetMs` default 300; code default is `"auto"` (300 is only the no-data + fallback). `demos/README.md` ("held for at most `holdBudgetMs` (300 ms)") and the `demos/src/shared/settings.ts` + comment ("default: the runtime's 300 ms") repeat the stale number. +2. CONTRACT §7 retry backoff `min(200 ms · 2^attempt, 5 s)`; code `min(200 × 2^(attempt-1), 5000)` (STATUS deviation). +3. CONTRACT §7 `rollback` = "last consistent snapshot"; code does that only for `inconsistency`; transition/error + restore only the op chain's fields. The model-facing description is unchanged for all triggers. +4. CONTRACT §8 `Decision`/`ActionRecord`/`Explanation` field lists omit `tier`, `ran`, `answers`, `subjectRef`, + `candidate`, `mass`, `ActionRecord.late`, `Explanation.message`; `DecisionProvider.evaluate` omits `priority`, + `timeoutMs`. §9 `ActionDef` omits `tier`; `StandingQuestion` omits `always`. `ActionDef.risk` is unused. + (§13 does add `EvaluateRequest.subject` / `Decision.subjectRef` and `policy.requireDiagnosis`; STATUS + "Deviations" lists the rest as extra public surface.) +5. `types.ts` JSDoc vs code: `Decision.action` ("the action the model chose (highest probability)") is `run ?? top`; + `Decision.executed` ("true when `action` ran as chosen") is also true when the passive action was the top and when + the action ran but failed; `EvaluateRequest.priority` ("held writes/requests use 2, background 0") is 2 held, + `min(priority, 1)` when not held (1 for non-held mutation/request/failure/stall/inconsistency, 0 for + transition/error) and 1 for `ask`. +6. CONTRACT §8 "summarised as ×N in the last minute"; code prints `(×N more in the last minute)` at window end and + only for the `"console"` sink. CONTRACT §0.5 / `packages/runtime/README.md` example lines ("Coalesced a + duplicate: …", "Flagged: …") do not match the real templates. +7. `packages/runtime/STATUS.md` and `sim/NEEDS.md` headless examples use thresholds `{ report: 0, guard: 0, heal: 0 }`; + the sim actually uses `guard`/`heal` 0.5 (`sim/src/run/rt.ts`) because 0 runs a zero-probability action. +8. `src/devtools/ui.ts` templates differ from `report.ts`: `NOUN.failure` "failed request" vs "request failure", + extra adjectives (`conflicting`, `excessive`), no `Reverted` lead. +9. CONTRACT §7 implies XHR parity; code never offers XHR `coalesce`/`retry`/`hedge` (STATUS deviation). +10. CONTRACT §7 calls guard-tier actions "minimal and reversible"; only `discard` (and a late revert) returns an + `undo`. `defer`, `coalesce` and `delay` have none (`Undo: not reversible` in the console group). +11. CONTRACT §8 says an `ActionRecord` is emitted "for every non-passive action that ran"; code also records failed + attempts (`ok: false`, `error`), and those consume a rate-limit slot. +12. `discard`'s undo builds a `MutationRec` with `genclass: true`, but `StoreHub.commit` writes under `m.cause` + (ambient and writer), and `StoreHub.write`/`record` never read `m.genclass`, so the re-applied write is recorded + as the original cause's write, not a GenClass op (code reading; no test asserts the writer). The comment in + `test/atoms.test.ts` ("the undo write is a GenClass write: never gated") is half right: it is never gated only + because `commit` bypasses `propose`. +13. `RuntimeImpl.setReport` JSDoc says "(devtools)", but nothing in the repo calls it; it is also absent from the + `Runtime` interface, as is `isPaused`. + +Open items (from `OPEN_TASKS.md`, `packages/runtime/STATUS.md`): + +- The published alpha takes no actions until the runtime model package is published. +- Hold-induced harm and triage sensitivity (OPEN_TASKS item 6, v0.1 model: the board demo had 9 bugs introduced in + guard mode with no interventions; search clean-run latency rose from 14 ms to 125 ms because salient writes were + held; typeahead was salient about 6 times per trial on clean runs). +- Known risk (OPEN_TASKS): slow single-thread WASM leads to more fail-open decisions. Note from code: late revert only + covers a `discard` of a held write; late request/failure decisions are never applied. +- Possible follow-ups seen in code reading (unverified at runtime): late provider answers after a runtime timeout + still feed the cache and latency samples; custom actions can hold a subject indefinitely. + +## Related docs + +- [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, options, kill switch, `ask`/`decide`. +- [observe-and-trace.md](observe-and-trace.md): fetch/XHR observers, request identity, ops and causality. +- [state-and-adapters.md](state-and-adapters.md): mutation pipeline, holds, defer, invariants, snapshots. +- [learn-situation-triage.md](learn-situation-triage.md): facts, triage, situation building, questions, budgets. +- [model-host.md](model-host.md): the default `DecisionProvider`, its queue, timeouts and error codes. +- [devtools.md](devtools.md): overlay views, report parsing, undo button. +- [build-test-release.md](build-test-release.md): running tests on the VM. +- [../overview.md](../overview.md#4-walkthrough-a-typeahead-stale-write): trigger -> queue -> gate -> discard end to end. +- [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../training.md](../training.md). +- [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md). +- Binding spec: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) §6–§9; human API: [../../runtime/API.md](../../runtime/API.md). diff --git a/docs/agents/runtime/devtools.md b/docs/agents/runtime/devtools.md new file mode 100644 index 00000000..70361461 --- /dev/null +++ b/docs/agents/runtime/devtools.md @@ -0,0 +1,712 @@ +# @genclass/runtime: devtools overlay + +> **Scope:** `packages/runtime/src/devtools/index.ts`, `packages/runtime/src/devtools/ui.ts`, `packages/runtime/src/devtools/css.ts`, `packages/runtime/UI-NEEDS.md`, `packages/runtime/test/devtools.test.ts`, `packages/runtime/test/devtools-runtime.test.ts`, `packages/runtime/test/browser/ui/*`, `packages/runtime/test/browser/ui-devtools.spec.ts` +> **Read this when:** you mount or unmount the overlay in an app or demo; change what a view shows; add an option, view, chip or evidence section; change report wording, theming or CSS; touch undo or mode switching from the UI; change a public `Runtime` API, event or type that the overlay reads; update the UI test harness (mock runtime, scenario, session, page) or the overlay screenshots; review whether the overlay may ship in production (bundle size, lazy import). +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- `mountDevtools(runtime, options?)` from `@genclass/runtime/devtools` adds one `<genclass-devtools>` host element with an **open shadow root**. All UI and CSS live inside that shadow root. It returns a `DevtoolsHandle` with `open`, `close`, `toggle`, `unmount` and `element`. With no DOM or no runtime it returns a no-op handle whose `element` is `null`. The runtime is the value of `GenClass.init()` / `GenClass.runtime` (`src/index.ts`) or of `createRuntime()`; passing `GenClass.runtime` while it is still `null` gives the no-op handle. +- It is **vanilla DOM** with no framework and no `innerHTML`: text is set with `textContent`, and SVG icons are built with `createElementNS` from constant markup, so it works under Trusted Types. It is a separate tsup entry, and the built bundle has **no runtime imports**: `../types.js` is imported for types only. +- It uses **only the public `Runtime` API**. Every way it affects the runtime, in one place: Reads: `status`, `mode`, `decisions`, `interventions`, `history`, `explain`, `situation`, `inflight` and `on(decide | detect | act | report | event | status)`. Writes: `setMode` and `ActionRecord.undo()`, nothing else. It registers one setup-only plugin with `use()` to get the runtime's `Clock`. Its host element carries `data-genclass-ignore` (`packages/runtime/src/devtools/index.ts` → `Devtools` constructor), so `packages/runtime/src/observe/dom-user.ts` → `ignoredEvent` does not record overlay clicks or keys as user ops. It never reads `rt.ready` (reading it starts a lazy model load). +- **Four views (tabs):** `interventions` (actions that ran), `detections` (findings GenClass did not act on), `activity` (the event log) and `now` (the live `runtime.situation()`). The collapsed state is a **pill** that shows the mode, the two counters, a model-status dot and a load progress bar. +- **Card routing:** an executed non-passive decision becomes an intervention card, keyed by `ActionRecord.id`. A reportable decision that did not act becomes a detection card, keyed by decision id. When an `act` arrives for a decision that is already shown as a detection, the card moves to Interventions. Identical detections that come within 60 s of each other fold into one card marked `×N`. +- **Evidence:** a card expands to show the facts, the model's answers (probability bars), the timeline, the exact situation text (`Explanation.situationText`, with a Copy button), and decision and action metadata. The data comes from `runtime.explain(id)`. When the explain buffer has dropped the entry, it falls back to the `Decision`. +- **Undo:** an Undo button appears only when `ActionRecord.undo` is a function. Clicking it calls `undo()` once and marks the card undone. If `undo()` throws, the card shows `Undo failed: <message>`. A runtime `action`/`undo` event marks the card undone even when the undo came from somewhere else. +- **Rendering is batched:** dirty bits (`STATUS | MODE | LISTS | EVENTS`) flush once per `requestAnimationFrame`, using the rAF captured at module load. Lists and activity render only while the panel is **open and not paused**. Counters and status always render. +- **Bounded memory:** at most 200 cards per feed and 400 activity rows. Internal maps have bounds of 500 to 2000 entries (see [constants](#configuration-and-constants)). +- **Isolation:** the host carries `data-genclass-ignore`, so the runtime's DOM user observer does not record clicks or keys inside the overlay. The host has the inline style `all:initial; position:fixed; z-index:2147483646`. Styles go into `adoptedStyleSheets`, or a `<style>` element inside the shadow root as a fallback. Nothing is added to the document. +- **Keyboard:** Alt+Shift+G toggles the panel (on by default). Escape closes it. Arrow, Home and End keys rove through the tabs and the mode radios. Enter or Space expands an activity row. +- Development-only use is **a documentation pattern, not code**: the README shows `if (import.meta.env.DEV) { const { mountDevtools } = await import("@genclass/runtime/devtools"); … }`. Nothing in the library stops a production app from mounting the overlay. + +## Files + +| Path | Role | Key exports / entry points | +|---|---|---| +| `packages/runtime/src/devtools/index.ts` | Public entry. The `Devtools` class does mount, subscribe, backfill, data intake, render scheduling, cards, evidence, activity, Now, controls, timing and unmount. | `mountDevtools`, `DevtoolsOptions`, `DevtoolsHandle`, `DevtoolsPosition`, `DevtoolsTab`. Internal: `Devtools`, `Entry`, `OpRow`, `bound`, `safe`, `fillMain`, `empty`, `sec`, `copyBtn` | +| `packages/runtime/src/devtools/ui.ts` | DOM helper, icons and display formatting. Report-wording templates for when no runtime report sentence is available. Classification and text of activity events. Reporting only: it decides nothing. | `setDoc`, `h`, `add`, `Kid`, `icon`, `IconName`, `mark`, `pct`, `mb`, `dur`, `clockT`, `ago`, `cap`, `phrase`, `actTitle`, `diagTitle`, `topFact`, `repeatKey`, `diagTone`, `splitReport`, `diagP`, `answerRows`, `Group`, `opKind`, `groupOf`, `kindLabel`, `eventText`, `opDuration`, `opStatus`, `dataLines`, `linesOf`, `safeJson` | +| `packages/runtime/src/devtools/css.ts` | The one stylesheet, as a string. Light and dark token sets on `.root` / `.root[data-theme=dark]`. Class selectors are unprefixed (`.pill`, `.card`, …) and a few element/attribute selectors (`*`, `button`, `input`, `svg`, `[hidden]`, `[tabindex]`, `code`) are unscoped, which is safe only because the sheet is applied inside the shadow root. | `CSS` (internal consts `LIGHT`, `DARK`) | +| `packages/runtime/UI-NEEDS.md` | UI to CORE request log, plus a summary of which runtime APIs the overlay uses. Partly stale: see [Drift](#drift-and-open-issues). | n/a | +| `packages/runtime/test/devtools.test.ts` | Unit tests against `MockRuntime` + `loadScenario`. Uses the `// @vitest-environment happy-dom` pragma (the vitest config default is `node`). | n/a | +| `packages/runtime/test/devtools-runtime.test.ts` | Integration tests (same happy-dom pragma): the overlay mounted on the real `createRuntime` after `runStoreSession()`. | n/a | +| `packages/runtime/test/browser/ui-devtools.spec.ts` | Playwright (Chromium). Checks real-browser style isolation, keyboard and undo, and writes the 18 screenshots in `test/browser/ui/screenshots/` (called "README screenshots" in its header, but no README embeds them: Drift 13). | n/a | +| `packages/runtime/test/browser/ui/mock-runtime.ts` | `MockRuntime`, a scripted `Runtime` implementation that records calls and emits what the test tells it to. Also models the store semantics (CONTRACT §4) used by `test/adapters-react.test.ts`, `test/adapters-redux.test.ts` and `test/adapters-zustand.test.ts`, so a change here can break those suites too. | `MockRuntime`, `MockClock`, `makeDecision`, `makeAction`, `choice` | +| `packages/runtime/test/browser/ui/scenario.ts` | `loadScenario(rt, opts)`: a scripted store session for the mock (3 interventions, 3 detections, events, explanations, a Now situation). | `loadScenario`, `ScenarioOptions` | +| `packages/runtime/test/browser/ui/session.ts` | `runStoreSession(opts)`: a store app on the **real** runtime under a virtual clock, a fake backend and a rule-based test decider. | `runStoreSession`, `Session`, `SessionOptions`, `VirtualClock`, `realTurn`, `SessionDecider`, `READY` | +| `packages/runtime/test/browser/ui/page.ts` | Browser page bundled by the spec. It renders a fake "Acme" store and exposes `window.__gc.start(opts)`. | `window.__gc` | +| `packages/runtime/test/browser/ui/playwright.config.ts` | Playwright config for `ui-*.spec.ts`. | default export | +| `packages/runtime/test/browser/ui/screenshots/*.png` | 18 tracked PNGs, rewritten by the spec. | n/a | + +Wiring outside the scope: + +| Path | Relevance | +|---|---| +| `packages/runtime/package.json` | `exports["./devtools"]` maps to `./dist/devtools/index.js` (+ `.d.ts`). `"sideEffects": false`. | +| `packages/runtime/tsup.config.ts` | Entry `"devtools/index": "src/devtools/index.ts"` (also in `dts.entry`). ESM, `es2022`, `splitting: true`. | +| `packages/runtime/src/observe/dom-user.ts` → `ignoredEvent`, `insideIgnored` | Skips user events whose `composedPath()[0]` or `target` is inside `[data-genclass-ignore]`, crossing shadow roots. | +| `packages/runtime/src/runtime.ts` → `fire`, `explain`, `setMode`, `decisions`, `interventions`, `history`, `inflight`, `situation` | The data the overlay reads. `setMode` fires `status`. `record.undo` pushes an `action`/`undo` event. | +| `packages/runtime/src/decide/report.ts` → `interventionLine`, `detectionLine`, `Reporter` | The report sentences that the overlay's `splitReport` parses and that `ui.ts` templates imitate. | +| `demos/src/site/demo-page.ts` | Demo mount: `mountDevtools(gc, { collapsed, theme, position: "bottom-right" })`, remounted on `gc-theme`, and `?devtools=open`. | +| `demos/src/dev/runtime-shim/devtools.ts` | A no-op stand-in that **duplicates `DevtoolsOptions`**. Update it when the options change. | +| `packages/runtime/test/smoke/smoke.sh` | Packs the tarball and checks that `document.querySelector("genclass-devtools")` exists in a Vite app. | + +## Concepts and data structures + +### Public types (`src/devtools/index.ts`) + +```ts +type DevtoolsPosition = "bottom-right" | "bottom-left" | "top-right" | "top-left"; +type DevtoolsTab = "interventions" | "detections" | "activity" | "now"; +interface DevtoolsOptions { + position?: DevtoolsPosition; // default "bottom-right" + collapsed?: boolean; // default true (pill); false opens the panel at mount + theme?: "auto" | "light" | "dark"; // default "auto" (live prefers-color-scheme) + tab?: DevtoolsTab; // default "interventions" + hotkey?: boolean; // default true: Alt+Shift+G toggles + container?: HTMLElement; // default document.body (then documentElement) +} +interface DevtoolsHandle { open(): void; close(): void; toggle(): void; unmount(): void; readonly element: HTMLElement | null } +function mountDevtools(runtime: Runtime, options?: DevtoolsOptions): DevtoolsHandle; +``` + +`handle.open/close/toggle` are "programmatic": they do not move focus. Clicking the pill, the minimize button, Escape and the hotkey are "user" actions and do move focus. `handle.element` is the host while mounted and `null` after `unmount()`. + +### Runtime data the overlay consumes + +| Runtime surface | Type | Used for | +|---|---|---| +| `on("decide")` | `Decision` | `addDecision`: cache the decision and refresh the card that refers to it | +| `on("detect")` | `Decision` (`Detection`) | `addDet`: create or fold a detection card | +| `on("act")` | `ActionRecord` | `addAct`: create an intervention card, or update a known one | +| `on("report")` | `Report` (`{kind, message, decision?, action?}`) | `addReport`: store the runtime's sentence for the card title and body (`kind: "status"` is ignored) | +| `on("event")` | `RtEvent` | `addEvent`: activity rows, op names and undo detection | +| `on("status")` | `ModelStatus` | marks `STATUS \| MODE`. The runtime also fires `status` from `setMode`. | +| `status` (getter) | `ModelStatus` | status strip, pill dot and progress, empty-state text | +| `mode` (getter) | `Mode` | mode radios, pill label, wording of "would have" notes | +| `decisions(200)`, `interventions(200)`, `history(400)` | arrays | backfill at mount | +| `explain(id)` | `Explanation \| null` | evidence (lazy, cached per card) | +| `situation()` | `Situation` (an "ask about now" situation) | Now view, polled once per second while visible | +| `inflight()` | `Op[]` | the "In flight" list in the Now view | +| `setMode(m)` | n/a | mode radios | +| `ActionRecord.undo()` | n/a | the Undo button | +| `use({ name, setup })` | `Plugin` → `PluginApi.clock` | the runtime `Clock` for "ago" labels and the overlay's own timers | + +### Internal state (`Devtools` in `src/devtools/index.ts`) + +```ts +interface Entry { // one card + kind: "act" | "det"; + id: string; // ActionRecord.id (act) or Decision.id (det; for a folded card, the first decision's id) + at: number; // runtime-clock ms (det: updated to the latest repeat) + action?: ActionRecord; decision?: Decision; + open: boolean; // evidence expanded + dirty: boolean; // re-render on next LISTS flush + fresh: boolean; // play the "new" animation once + count: number; // folded repeats (det); always 1 for act + key?: string; // repeatKey(d) for det + undone?: boolean; undoErr?: string; + ex?: Explanation | null; // cached explain(); undefined = not fetched yet + el?: HTMLElement; // rendered <article> +} +interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activity row waiting for its op.end +``` + +| Field | Shape | Bound | +|---|---|---| +| `acts` | `Map<actionId, Entry>` (insertion order = render order, newest prepended) | 200 (`MAX_CARDS`), evicted cards removed from the DOM | +| `dets` | `Map<cardId, Entry>` | 200 (`MAX_CARDS`) | +| `detOf` | decision id → detection card id (repeats share one card) | 1000 | +| `actOf` | decision id → action id | 1000 | +| `decs` | decision id → `Decision` | 500 (only on the live `decide` path) | +| `msgs` | action id or decision id → report sentence | 500 | +| `evq` | `RtEvent[]` waiting to render | 400 (`MAX_ROWS`), oldest dropped | +| `rows`, `rowBySeq`, `rowEvents`, `opRows` | rendered activity rows; seq → row; row → events (start + end); op id → row in flight | 400 rows | +| `opNames` | op id → `eventText` of its `user`/`op.start` event (names the causes in expanded rows) | 2000 | +| `hide`, `query` | activity group filters and the text filter | n/a | +| `isOpen`, `tab`, `paused`, `dead`, `unseen`, `bits`, `scheduled`, `ticking`, `ticks`, `scrolledActivity`, `clock`, `lastT` | UI state | n/a | + +### Terms introduced here + +| Term | Meaning | +|---|---| +| overlay / host | The `<genclass-devtools data-genclass-devtools data-genclass-ignore>` element plus its shadow root. | +| pill | The collapsed button (`.pill`, `data-part="pill"`): brand mark, "GenClass", mode, intervention counter (`.pc.a`), detection counter (`.pc.d`), status dot (`.pd`), load progress (`.pb`). | +| panel | The expanded `section.panel[role=dialog]`: header (brand, mode radios, minimize), status strip, tabs and pause/clear buttons, pause banner, panes. | +| view / tab / pane | One of `DevtoolsTab`. Tab button `[data-tab]`, pane `[data-pane]`. | +| intervention card | `article.card.act[data-id=<actionId>]` for an `ActionRecord`. | +| detection card | `article.card.det[data-id=<decisionId>]` for a decision that was reported (`detect`) but did not run a non-passive action. | +| repeat folding | Detections with the same `repeatKey` (trigger, diagnosis, action, and subject with digits normalised) within 60 s of the card's latest repeat become one card with a `×N` badge. | +| report sentence | `Report.message` from `on("report")`, e.g. `[GenClass] Prevented a stale write: <fact> <changed> (stale, 0.97; discard 0.98)`. The overlay splits it into a title and body. | +| templates | `actTitle` and `diagTitle` in `ui.ts`, used when no report sentence is known (anything recorded before mount). | +| evidence | The expandable `.evd` block of a card. | +| render bits | `STATUS=1`, `MODE=2`, `LISTS=4`, `EVENTS=8`, `ALL=15`. They are OR'ed into `bits` and flushed together. | +| pause (feed) | Freezes the rendering of lists, activity and Now. Intake and counters continue. Unrelated to `runtime.pause()`. | +| clear (feeds) | Removes the overlay's cards and rows. The runtime's buffers are unaffected. | +| backfill | Replays `decisions`, `interventions` and `history` at mount. Report sentences from before mount are **not** available. | + +### DOM hooks (stable selectors used by tests) + +| Selector | Element | +|---|---| +| `genclass-devtools` | host (light DOM) | +| `.root[data-pos][data-theme]` | shadow root top container (theme tokens live here) | +| `[data-part="pill" \| "panel" \| "minimize" \| "status" \| "pause" \| "clear" \| "situation"]` | pill, panel, minimize button, status strip, pause and clear buttons, the situation `<pre>` in evidence | +| `[data-tab=<id>]` (role tab, id `gc-t-<id>`), `[data-pane=<id>]` (role tabpanel, id `gc-p-<id>`) | tabs and panes | +| `[data-mode=observe\|guard\|heal]` (role radio) | mode radios | +| `article.card[data-id]`, `.ct` title, `.cx` body, `.rep` ×N, `time.ago[data-at]`, `.chips .chip`, `.note` (`.chg` changed, `.fail`), `.evd` | card parts | +| `[data-act="evidence" \| "undo" \| "undone" \| "copy"]` | card and evidence controls (focus is restored by `data-act` after a re-render) | +| `.ans[data-q]`, `.bl`, `.bt2`, `.bp` (`.top` on the chosen label) | answer bars | +| `.f[data-g]` (aria-pressed), `input.q` | activity filters | +| `.ev[data-g][data-op]`, `.t`, `.k`, `.m` (+ `.id`), `.x` (+ `.spin`), `.evx` | activity row parts | +| `.now`, `.nh`, `.subj p`, `.op .m`, `.op .x`, `.facts li` | Now view | +| `.pc.a b`, `.pc.d b`, `.n` (tab counters), `.pm` (pill mode), `.pz` (pause banner), `.st b`, `.st .sm`, `.sb i`, `.empty b` | counters, status, pause banner, empty states | + +### ARIA structure (`Devtools` constructor, `card`, `row`) + +| Element | Role / ARIA | +|---|---| +| pill `button.pill` | `aria-haspopup="dialog"`, `aria-expanded` (true while open), `aria-label` = `Open GenClass devtools: N interventions, M detections, model <state>` | +| `section.panel` | `role=dialog`, `aria-label="GenClass devtools"` | +| `.modes` | `role=radiogroup` `aria-label="Mode"`; each button `role=radio`, `aria-checked`, roving `tabindex` (0 on the checked one), `title` = the `MODES` tooltip | +| `.st` | `role=status` | +| `.tabs-in` | `role=tablist` `aria-label="GenClass views"`; tabs `role=tab`, `aria-selected`, `aria-controls=gc-p-<id>`, roving `tabindex` | +| `.pane` | `role=tabpanel`, `aria-labelledby=gc-t-<id>` | +| `.list` (Interventions, Detections) | `role=feed` with `aria-label` | +| `.evs` (Activity) | `role=log` `aria-label="Runtime activity"`; rows `role=listitem`, `tabindex=0`, `aria-expanded` | +| `.fb` | `role=toolbar` `aria-label="Activity filters"`; filter buttons use `aria-pressed` (true = group shown) | +| pause button | `aria-pressed`, `aria-label` `Pause feed` / `Resume feed` | +| Evidence button | `aria-expanded`, `aria-controls=gc-ev-<kind>-<id>` | +| icons | `aria-hidden="true" focusable="false"`; spinners `role=img aria-label="in flight"` (activity rows only) | + +### `ui.ts` helper reference (exact behaviour) + +| Helper | Behaviour | +|---|---| +| `h(tag, props, ...kids)` | Creates in the module-global document `D`. Props: `null`/`false` skipped; `class` → `className`; `text` → `textContent`; `on<event>` with a function → `addEventListener("<event>")`; `true` → empty attribute; anything else → `setAttribute(k, String(v))`. Kids (`Kid`) may be nested arrays; `null`/`false`/`undefined` are skipped; strings and numbers become text nodes. | +| `svg(markup)` (private) / `icon(name, cls = "i")` | A regex mini-parser over **constant** markup: only elements and `key="value"` (double-quoted) attributes; text, comments and single-quoted attributes are dropped. `ICONS` names: `shield`, `eye`, `pulse`, `scan`, `pause`, `play`, `clear`, `min`, `chev`, `undo`, `copy`, `check`, `alert`, `info` (24×24 viewBox, stroked via the `.i` class). `scan` is currently unused. | +| `mark()` | The brand tile SVG (gradient `#2f6cf2` → `#7b3cf0`, white trace, `#ffd166` dot). Each call gets a unique gradient id `gcm<n>` from the module counter `markN`. | +| `pct(p)` | `Math.round(p*100)%`; `"–"` for `null`/non-finite. | +| `dur(ms)` | `""` for negative or non-finite; see the constants table for formats. | +| `phrase(diagnosis, trigger)` | Noun from `NOUN[trigger]` (else the trigger, else `"event"`). No adjective for a missing or `expected` diagnosis. `failure` + `failing` → `"failing request"`. Adjective = `ADJ[diagnosis]` or the diagnosis with `_` → space, omitted when the noun already starts with it. | +| `actTitle(action, diagnosis, trigger)` | `` `${LEAD[action]} ${article(phrase)}` ``; `article` adds `a`/`an` except when the phrase ends in `state`. Unknown action → `Ran <action with _ → space>`. `LEAD`: `discard`/`coalesce` Prevented, `defer` Held back, `delay` Slowed down, `block` Stopped, `serve_cached`/`retry` Recovered from, `hedge` Worked around, `rollback`/`resync` Repaired. | +| `diagTitle` | `cap(phrase(...))`. | +| `topFact(facts)` | First fact not matching `/^This (write\|request) (comes from\|has no known cause)/`; falls back to `facts[0]`. | +| `diagP(d)` | `d.diagnosisProbabilities?.[d.diagnosis] ?? d.diagnosisConfidence`. In the real runtime both are the same calibrated probability (`src/runtime.ts`). | +| `answerRows(a)` | `noul` → `[["true", noul], ["false", 1-noul]]`; otherwise `probabilities` entries sorted descending (non-numbers → 0). | +| `eventText(e)` | `op.start`/`op.end`: `name` + `data.detail` (no space when it starts with `?`; skipped when already in the name). `user`: `name = "<value>"` (a value not already starting with `"` is quoted, and cut to 39 chars + `…` when longer than 40; an already-quoted value is used as is) plus ` (N keystrokes)` when `data.count > 1`. `state`: up to 3 of `data.paths` (or `data.changes[].path`) plus ` +N`, else `name`. `error`: `name: message` unless the message already starts with the name. `decision`: `name · diagnosis → action`, plus ` (not run)` when `data.executed === false`. `action`: `name · data.text`. `storage`: `name key`. Other kinds: `name · data.summary` (only when the summary is not already in the name). | +| `opStatus(e)` | Code from `data.code ?? data.httpStatus` (number or string). Rules as in [Activity view](#8-activity-view-renderevents-row-endop-togglerow). | +| `linesOf(v)` | `null` → `[]`; array → each item (non-strings via `safeJson`); string → non-blank lines; other → `[safeJson(v)]`. | +| `safeJson(v, space?)` | `JSON.stringify`, falling back to `String(v)` on throw or `undefined`. | + +## How it works + +### 1. Mount (`mountDevtools` → `new Devtools`) + +1. `mountDevtools` resolves `doc = options.container?.ownerDocument ?? globalThis.document`. If there is no `doc` or no `runtime`, it returns the no-op handle. +2. The `Devtools` constructor calls `setDoc(doc)` (`ui.ts`). This sets a **module-global** document that `h()`, `icon()` and `mark()` create elements in. +3. It creates the host `genclass-devtools` with `data-genclass-devtools` and `data-genclass-ignore` and the inline style `all:initial;display:block;position:fixed;z-index:2147483646;<vert>:16px;<horiz>:16px;`. `<vert>` and `<horiz>` come from splitting `position` on `-`. It then calls `attachShadow({ mode: "open" })`. +4. `adoptStyles` creates `new CSSStyleSheet()`, calls `replaceSync(CSS)` and sets `shadowRoot.adoptedStyleSheets`. If that is unsupported or throws, it appends `<style>` with `CSS` inside the shadow root. +5. It builds the pill, header (mode radios from `MODES`), status strip, tabs (from `TABS`) plus pause and clear, pause banner, the four panes and the panel. Everything goes under `.root[data-pos]`. +6. Theme: `"auto"` reads `matchMedia("(prefers-color-scheme: dark)")` and listens for `change` (removed on unmount). It sets `.root[data-theme]` to `light` or `dark`. +7. It appends the host to `container ?? doc.body ?? doc.documentElement`. +8. `subscribe()`, then `backfill()`, then (unless `hotkey === false`) a capture-phase `keydown` listener on `doc`. +9. `bits = ALL; flush()`. Since the panel is closed, this renders the status, mode and counters. If `collapsed === false`, `open(false)` follows. + +### 2. Subscribe and backfill + +1. `subscribe()` calls `rt.on(type, fn)` for `decide`, `detect`, `act`, `report`, `event` and `status`. Each callback is ignored once `dead`. Each unsubscribe function goes into `offs`. A runtime without an event is tolerated (try/catch). +2. `subscribe()` then calls `rt.use({ name: "genclass-devtools-<n>", setup: api => this.clock = api.clock })`. `<n>` is a module counter `instances`. The plugin adds no facts, actions or questions. Its disposer goes into `offs`. +3. `backfill()`: + 1. Calls `rt.decisions(200)`, sorts by `at`, and caches each decision in `decs`. + 2. Calls `rt.interventions(200)`, sorts by `at`, and runs `addAct(a, false)` on each (no pulse). + 3. For each cached decision with `diagnosis !== "expected"` and `diagP(d) >= 0.6`, runs `addDet(d, false)`. + 4. Runs `addEvent(e)` for each event of `rt.history(400)`. An `action`/`undo` event here marks an already backfilled card undone. + +### 3. Data intake and card routing + +1. **`decide`** → `addDecision(d)`: `decs.set`, then `bound(decs, 500)`. If a det or act card already refers to `d.id`, it sets `entry.decision = d` and marks `LISTS`. +2. **`detect`** → `addDet(d, live=true)`: + 1. It returns early if `actOf.has(d.id)`, `detOf.has(d.id)`, or `d.executed && d.tier !== "passive"` (an intervention, whose `ActionRecord` follows). + 2. `key = repeatKey(d)` is `` `${trigger}|${diagnosis}|${action}|${subject with /#\d+/→"#", /\d+(\.\d+)?/→"n"}` ``. The **last** existing det card with the same key and `d.at - card.at <= 60_000` absorbs the decision: `count++`, `decision = d`, `at = d.at`, `ex = undefined`, its element is removed, and it is re-inserted at the end of `dets` so it renders on top. `detOf[d.id] = card.id`. + 3. Otherwise it creates a new card keyed by `d.id`. + 4. `bound(dets, 200, removeEl)`, `bound(detOf, 1000)`, then (live only, not during backfill) `notify("d")` (pill ring in warn colour), and mark `LISTS`. +3. **`act`** → `addAct(a, live=true)`: + 1. A known id updates `action` and marks dirty. + 2. Otherwise it creates an `Entry{kind:"act"}` with `decision = decs.get(a.decisionId)`, sets `actOf[a.decisionId] = a.id`, and applies `bound(acts, 200, removeEl)` and `bound(actOf, 1000)`. + 3. If that decision had a detection card, the card is decremented (when `count > 1`) or removed. The decision moves to Interventions. + 4. Then (live only, not during backfill) `notify("a")` (pill ring in brand colour), and mark `LISTS`. +4. **`report`** → `addReport(r)`: + 1. It skips `kind === "status"` and empty messages. + 2. The id is `r.action?.id ?? actOf[r.decision.id] ?? r.decision.id` for `intervene`, and `r.decision?.id` for `detect`. + 3. It stores `msgs.set(id, message)` (bounded to 500) and marks the matching card dirty. +5. **`event`** → `addEvent(e)`: + 1. `kind === "action" && name === "undo" && typeof data.id === "string"` marks that act card `undone`. + 2. A `user` or `op.start` event with an `op` records `opNames[op] = eventText(e)`. + 3. The event is pushed to `evq` (capped at 400) and `EVENTS` is marked. +6. **`status`** → `mark(STATUS | MODE)`. +7. `notify(kind)` increments `unseen` while paused. It restarts the pill's CSS `ring` animation with class `pa` (intervention) or `pdd` (detection). `animationend` with name `ring` removes the class. + +### 4. Render scheduling (`mark` / `flush`) + +1. `mark(bits)` ORs into `this.bits`. If no flush is scheduled (and not `dead`), it schedules one with `rawRaf(run)`. Without rAF it uses `after(16, run)`, which goes through the runtime clock when one is known. +2. `flush()` swaps `bits` to 0, then: + 1. `STATUS` → `renderStatus()`. + 2. `MODE` → `renderMode()`. + 3. Only if `isOpen && !paused`: `LISTS` → `renderList(acts, …)` and `renderList(dets, …)`, and `EVENTS` → `renderEvents()`. Otherwise those two bits are put back for later. + 4. `renderCounts()` always runs. +3. Undo, evidence toggling, pause, clear and open call `flush()` synchronously after setting bits. +4. `renderList(map, list, empty)`: for each entry in insertion order, a missing `el` is built by `card(e)` and **prepended** (newest on top). A `dirty` entry is rebuilt and swapped in with `replaceWith`. If focus was inside the old card, it is restored to the element with the same `data-act`. The empty state is hidden when the map is non-empty. +5. `renderCounts()`: + 1. The intervention count is `acts.size` (so at most 200). The detection count is the **sum of `count`** over the at most 200 det cards (folded repeats can push it above 200). Neither is a runtime total. + 2. It updates the pill counters and tab counters (adds class `.on` when > 0) and the pill `aria-label`, which reads `Open GenClass devtools: N interventions, M detections, model <state>`. + 3. It updates the pause banner: `Feed paused` or `Feed paused · N new`. + +### 5. Card content (`card(e)`) + +1. `d = e.decision ?? decs.get(a.decisionId)`. +2. `msg` is `msgs[e.id] ?? msgs[a.decisionId]` (act) or `msgs[d.id]` (det). +3. `splitReport(msg, a?.changed)` cleans the sentence: + 1. Takes the first line. + 2. Strips the `[GenClass]` prefix, a `(×N …)` suffix, the trailing `(diag, p; action p)` parenthetical, and any `Not acted on (…): …` tail. + 3. Strips a trailing `changed`, because the note already shows it. + 4. Splits at the first `": "` when it falls at index 3 to 63. Otherwise the whole text is the body. +4. **Title:** det cards always use `diagTitle(diagnosis, trigger)`, e.g. "Slow request" or "Unusual state change". Act cards use the report title, or `actTitle(action, diagnosis, trigger)`, e.g. "Prevented a stale write" or "Slowed down a failing request". +5. **Body:** the report body, or else `topFact(d.facts)` (the first fact that is not `This write|request comes from|has no known cause…`), or else `a.subject`, or else `d.subject`. CSS clamps it to 3 lines. +6. **Chips:** + - Diagnosis chip, coloured `t-<diagTone>`: `ok` for expected; `bad` for failing or inconsistent; `warn` for slow or overload; `brand` otherwise. It shows the diagnosis and `pct(diagP(d))`. + - Action chip (act cards only): `<code>action</code>` and the tier. +7. **Note:** + - On an act card, `changedNote`: + - `!a.ok` → `Action failed: <error ?? "it threw">` + - undone → `Reversed: <changed || action>` + - otherwise → `a.changed` + - On a det card, `wouldNote(d)`: + - `tier === "passive"` → `The model chose <action>: nothing was changed.` + - Otherwise the note depends on `byMode`. With a reason, `byMode = /\bmode\b/.test(d.reason)`. Without one, `byMode = !(mode === "heal" || (mode === "guard" && d.tier === "guard"))`. + - `byMode` true → `Would have run <action> in <tier> mode.` + - `byMode` false → `Not acted on: <reason ?? "held back by policy">. The model chose <action> (<tier>).` +8. **Footer:** the undo control (act cards only) and the `Evidence` button (`aria-expanded`, `aria-controls="gc-ev-<kind>-<id>"`). After the first render `fresh` becomes `false`, so the `new` animation plays once. + +### 6. Evidence (`toggleEvidence` → `evidence(e, id)`) + +1. A click flips `e.open`, marks the card dirty, flushes, and `reveal()` scrolls the pane so the card fits. +2. `e.ex` is fetched once with `explain(e)`. It tries `rt.explain(id)` for `[action id, decision id]` (act) or `[decision id, card id]` (det) and caches the first non-null result. `null` is cached too. +3. Sources: `d = ex.decision ?? e.decision`, `a = e.action ?? ex.action`, `facts = ex.facts ?? d.facts`, `answers = ex.answers ?? d.answers`. +4. Sections in order: + 1. **Facts** (`ul.facts`). + 2. **Model answers**: one `.ans[data-q]` per question, ordered `diagnosis`, then `action`, then the rest. Each shows the top 6 `answerRows` (noul gives `true`/`false`; otherwise probabilities sorted in descending order). The highlighted row is the decision's chosen label when present. + 3. **Timeline** (`ex.timeline`). + 4. **Exact input sent to the model**: `ex.situationText` in `pre[data-part=situation]`, with a Copy button. + 5. When `explain` returned null: `The full situation is no longer in the runtime's decision buffer.` + 6. Metadata: decision id, action id, `<trigger> · answered in <dur(latencyMs)>`, model name. + 7. For a non-passive action, the hint `Never run this action: policy: { deny: ["<action>"] }`. +5. The runtime keeps explain records under both decision ids and action ids in `explainMap` (`src/runtime.ts`). It evicts the oldest entry when the map exceeds `DECISIONS_KEPT * 2` = 400 entries, checked on each new decision. Older cards fall back to the facts and answers stored on the `Decision`. +6. `copyBtn` writes with `navigator.clipboard.writeText`. The button shows `Copied` or `Copy failed` (also immediately when `navigator.clipboard` is missing, e.g. on a non-secure origin) and resets after 1400 ms via `rawSetTimeout`. + +### 7. Undo from the UI (`undoCtl` / `undo`) + +1. `undoCtl` renders: + - `span.done[data-act=undone]` "Undone" when `e.undone`. + - Nothing when `typeof a.undo !== "function"`. For example, `coalesce` and `delay` records in the scenario have no undo. + - Otherwise `button.btn.u[data-act=undo]` "Undo", plus `.err` text when the last attempt failed. +2. `undo(e)` calls `e.action.undo()` synchronously. On success it sets `undone = true` and clears `undoErr`. On a throw it sets `undoErr = "Undo failed: <message>"` and does not mark the card undone. Then it flushes. +3. In the real runtime, `ActionRecord.undo` is idempotent (`src/runtime.ts`: an `undone` flag in the closure). It runs the effect's undo as a GenClass op (`runAsGenClass("undo", …)`) and pushes `RtEvent { kind: "action", name: "undo", data: { id, text } }`. Through step 3.5, that event also marks the card undone when the undo was triggered from the console or app code. +4. Undo state lives on the overlay's `Entry`. After a remount it is restored only if the `action`/`undo` event is still within the last 400 events that backfill reads (`history(MAX_ROWS)`). `clear()` drops the cards themselves; cleared interventions do not come back until a remount. + +### 8. Activity view (`renderEvents`, `row`, `endOp`, `toggleRow`) + +1. `renderEvents` drains `evq`: + 1. An event whose `seq` already has a row is a typing burst that the runtime re-notified via `EventLog.touch` (`src/trace/events.ts`). Only that row's `.m` text is refreshed. + 2. Any other event goes through `row(e, fresh)`. + 3. New rows are appended in a fragment. Rows are trimmed to 400 from the top, dropping their `rowBySeq` and `opRows` entries. + 4. The pane scrolls to the bottom when the user was within 32 px of it (or the Activity tab has never been shown, `scrolledActivity === false`) and the Activity tab is selected. +2. `row(e)`: + 1. An `op.end` whose `op` has a pending row is merged into the `op.start` row by `endOp` (status and duration in `.x`; main text updated if `name` differs). No new row is created. + 2. Otherwise it builds `div.ev.g-<group>[data-g][data-op][role=listitem][tabindex=0]` with columns `.t` = `clockT(e.t)`, `.k` = `kindLabel(e)`, `.m` = `fillMain` (`eventText(e)` plus `#op`, or `← #op` for `state` events), and `.x`. + 3. `.x` holds: + - for `op.start`: a spinner, and the row is registered in `opRows` + - for an unpaired `op.end`: `fillEnd` + - otherwise: `held <dur>` when `data.heldMs` or `data.held` is a number, or `pct(data.confidence)` for `decision` events + 4. The row is hidden immediately if the current filters exclude it. + 5. New rows get class `fresh` (a 1.2 s brand-tint fade, CSS `@keyframes fresh`) only when the Activity tab has been visited before (`scrolledActivity`) **and** is the selected tab during that flush, so the initial backfill never flashes. +3. Groups (`groupOf`): + + | Event | Group | + |---|---| + | `user` | `user` | + | `op.start` / `op.end` with `opKind` = `genclass` | `gc` | + | other `op.start` / `op.end` | `op` | + | `state` | `state` | + | `error` | `error` | + | `decision`, `action` | `gc` | + | anything else (`nav`, `perf`, `storage`, `custom`) | `other` | + + Filter buttons are User, Ops, State, Errors, GenClass and Other. All are pressed (shown) at start. The text filter is a lowercase substring match on the row's `textContent`. +4. Labels (`kindLabel`): + - For op events, by `data.kind ?? data.opKind`: `fetch` or `xhr` → `net`, `ws` → `ws`, `task`, `timer`, `genclass` → `gc`, `user`, anything else → `op`. + - Otherwise: `storage` → `store`, `custom` → `event`, `decision` → `model`, `action` → `action`. Other kinds use their own name. +5. `opStatus(e)` returns text and a tone: + - `status:"error"` → code or "error", tone `bad` + - `aborted` → tone `dim` + - `blocked` → `blocked <code>`, tone `brand` + - a numeric `code >= 400` → tone `bad` + - otherwise → code, status or "done", tone `ok` + + `opDuration` uses `data.ms ?? data.duration ?? data.durationMs ?? e.t - start`. The `.x` text concatenates the status and the duration, e.g. the textContent `2001.82 s` is `200` followed by `1.82 s`. +6. Clicking a row, or pressing Enter or Space on it, toggles `.evx`. It shows `dataLines` for every event in the row (start and end joined by `\n—\n`): `kind · name`, `op: #n`, `cause: #n <op name>`, each `data` key with its value truncated to 300 characters, and `seq`. + +### 9. Now view (`renderNow`) + +1. It runs only when the panel is open, `tab === "now"` and the overlay is not `dead`. It is triggered by `setTab("now")`, by `setPaused`, and by every 1 s tick unless paused. +2. `sit = rt.situation()` (no argument, so the real runtime builds a fresh `trigger: "ask"` "about now" situation each time; `src/runtime.ts` → `situation`). A throw becomes a `.note.fail` reading `situation() failed: <message>`, and then only the header and that note render. Next, `ops = safe(rt.inflight)`. `docs/runtime/CONTRACT.md` states `situation()` is side-effect free (no ids consumed, nothing recorded); the code comment on `RuntimeImpl.build` (`src/runtime.ts`) qualifies this as "apart from caching op.reads". +3. It renders, in order: + - Header: `Live` or `Paused`, `state.app` or "What GenClass sees right now", and a `Copy state` button with the JSON of `sit.state`. + - Subject block: chips `trigger <sit.trigger>` and either `salient: the model would be asked` (warn) or `quiet: no model call needed` (ok), followed by `sit.subject`. + - Facts: `sit.facts`, or else `linesOf(state.facts)`, or else `No notable facts.` + - In flight (section title `In flight · N` when N > 0): from `inflight()` as `name` + `detail` (no space when `detail` starts with `?`) and a spinner with `kind · dur(now - start)`. Only when `inflight()` throws or returns `null`/`undefined` does it fall back to `state.in_flight` lines without `none` (an empty array shows `none`). + - Timeline (`state.timeline`), State (`state.state`) and Stats (`state.stats` without `none`). + - Actions available (`sit.actions`, the first chip labelled `passive`). + + `Situation.state` is typed `JevState` (`Record<string, unknown>`); its keys are the serializer's `SituationParts` keys `app`, `trigger`, `facts`, `in_flight`, `timeline`, `state`, `stats` (`src/situation/serialize.ts`), and an empty section is serialised as the string `"none"` (which is why the view filters `none`). See [learn-situation-triage.md](./learn-situation-triage.md). + +### 10. Controls + +| Control | Code | Effect | +|---|---|---| +| Pill click | `open(true)` | Shows the panel and hides the pill. `bits = ALL` and flush, then `setTab(tab, focus)` and `startTicking()`. | +| Minimize / Escape in panel | `close(true)` | Hides the panel, shows the pill and focuses it. Escape calls `stopPropagation`. | +| Alt+Shift+G | `toggle(true)` | Capture listener on `doc`. Requires `altKey && shiftKey && !ctrlKey && !metaKey` and `code === "KeyG"` or `key` `G`/`g`. Calls `preventDefault()` (not `stopPropagation`). | +| Tab click / arrows | `setTab(t, focus)` | Updates `aria-selected` and the roving `tabindex`, and shows the pane. Selecting `now` calls `renderNow()`. The first visit to `activity` scrolls to the bottom. | +| Mode radio click / arrows | `setMode(m, focus)` | `rt.setMode(m)` (errors swallowed), `renderMode()`, all det cards marked dirty (the wording of "would have" notes depends on the mode), mark `LISTS`. **Arrow keys change the runtime mode immediately** (selection follows focus). | +| Pause / Resume | `setPaused(p)` | Toggles `aria-pressed`, the label and the icon. Resuming resets `unseen`. Then flushes `LISTS \| EVENTS` and re-renders Now. | +| Clear | `clear()` | Removes all cards and rows and empties `acts`, `dets`, `rows`, `rowBySeq`, `detOf`, `opRows`, `evq` and `unseen`. **Keeps** `decs`, `actOf`, `msgs` and `opNames`. Shows the empty states. | +| Roving keys (`roving`) | tabs and mode radios | ArrowRight/ArrowDown → next, ArrowLeft/ArrowUp → previous (both wrap), Home → first, End → last. | + +Timing: +- `startTicking()` runs while the panel is open, every 1000 ms through `after()`. `after()` uses `clock.setTimeout` from the plugin API, or `rawSetTimeout` when no plugin clock is known. +- Each tick re-renders Now when it is visible and not paused. Every 5th tick it rewrites every `time.ago` label from `now() - data-at`. +- The tick loop stops on the first tick after the panel closes or the overlay is unmounted. +- `now()` is `clock.now()`, or else the largest `at`/`t` seen (`lastT`). + +### 11. Unmount + +`unmount()` is idempotent. It sets `dead = true`, which makes pending rAF flushes, ticks and listener callbacks no-ops. It calls every `offs` entry: runtime listeners, the plugin disposer, the `matchMedia` listener and the hotkey listener. Then it removes the host. `handle.element` becomes `null`. Remounting creates a fresh `Devtools`, which backfills from the runtime buffers again. + +### 12. Packaging, bundle size and dev-only loading + +1. Build: `packages/runtime/tsup.config.ts` has the entry `"devtools/index": "src/devtools/index.ts"` (ESM, `target: "es2022"`, `splitting: true`, also listed in `dts.entry`). `packages/runtime/package.json` → `exports["./devtools"]` = `{ types: "./dist/devtools/index.d.ts", import: "./dist/devtools/index.js" }`; the package sets `"sideEffects": false`. +2. The entry imports only `type`s from `../types.js` plus its own `./css.js` and `./ui.js`, so `dist/devtools/index.js` is self-contained: it pulls no runtime chunk and no ONNX code. It does have module-load side effects (captures `rawRaf` / `rawSetTimeout`, module counters `instances` and `markN`, and the `D` document slot in `ui.ts`) but touches no DOM until `mountDevtools` runs. +3. Size: the README and `OPEN_TASKS.md` claim **52 KB minified / 17 KB gzip**. `tsup.config.ts` sets no `minify` option (it does set `sourcemap: true` and `treeshake: true`), so `dist/devtools/index.js` from `npm run build` is unminified and larger; the 52 KB figure presumably assumes the app's bundler minifies it (unverified). See Drift item 7 for the size of the unminified build. +4. Recommended loading (documentation only, `packages/runtime/README.md`): import lazily in development so production bundles never include it: + + ```ts + if (import.meta.env.DEV) { + const { mountDevtools } = await import("@genclass/runtime/devtools"); + mountDevtools(rt); + } + ``` + + There is no `NODE_ENV` / `DEV` check inside the library (Drift item 8). `OPEN_TASKS.md` item 7 still lists this lazy-import documentation as to-do. +5. Mounting reads `rt.status` but never `rt.ready`. In the real runtime, reading `ready` starts a lazy model load (`src/runtime.ts` → `get ready`), so opening the overlay does not by itself download the model. +6. SSR: with no `document` (and no `options.container`), `mountDevtools` returns the no-op handle, so the call is safe in server code. Importing the module server-side is also safe because module load only reads `globalThis.requestAnimationFrame` / `setTimeout` optionally. + +## Configuration and constants + +| Name | Type | Value | Defined in | Effect | +|---|---|---|---|---| +| `position` option | `DevtoolsPosition` | `"bottom-right"` | `index.ts` → constructor | host offset `16px` from those two edges, `.root[data-pos]` alignment and pop-in animation | +| `collapsed` option | boolean | `true` | `index.ts` → constructor | `false` → `open(false)` at mount | +| `theme` option | `"auto" \| "light" \| "dark"` | `"auto"` | `index.ts` → constructor | `.root[data-theme]`. `auto` follows `prefers-color-scheme` live. | +| `tab` option | `DevtoolsTab` | `"interventions"` | `index.ts` → constructor | initially selected view | +| `hotkey` option | boolean | `true` | `index.ts` → constructor | Alt+Shift+G toggle listener | +| `container` option | `HTMLElement` | `document.body` (fallback `documentElement`) | `index.ts` → constructor | DOM parent and document. The host stays `position:fixed`. | +| `MAX_CARDS` | number | `200` | `index.ts` | per-feed card bound, also `interventions(MAX_CARDS)` at backfill | +| `MAX_ROWS` | number | `400` | `index.ts` | activity rows, `evq` cap, `history(MAX_ROWS)` at backfill | +| backfill decisions | literal | `200` | `index.ts` → `backfill` | `rt.decisions(200)` | +| backfill detection threshold | literal | `0.6` | `index.ts` → `backfill` | `diagP(d) >= 0.6`. Hard-coded: it does not read `policy.thresholds.report`. | +| repeat window | literal | `60_000` ms | `index.ts` → `addDet` | detection folding (measured from the card's latest repeat) | +| map bounds | literals | `decs` 500, `msgs` 500, `actOf` 1000, `detOf` 1000, `opNames` 2000 | `index.ts` | memory caps via `bound()` | +| render bits | consts | `STATUS=1`, `MODE=2`, `LISTS=4`, `EVENTS=8`, `ALL=15` | `index.ts` | dirty flags | +| rAF fallback | literal | `16` ms | `index.ts` → `mark` | used when `requestAnimationFrame` is missing | +| tick | literal | `1000` ms; "ago" labels every 5 ticks | `index.ts` → `startTicking` | Now refresh, relative times | +| auto-scroll slack | literal | `32` px | `index.ts` → `renderEvents` | stick-to-bottom threshold | +| answer rows | literal | top `6` | `index.ts` → `answer` | bars per question | +| copy feedback | literal | `1400` ms | `index.ts` → `copyBtn` | label reset | +| host z-index / offset | literals | `2147483646` / `16px` | `index.ts` → constructor | stacking and placement | +| panel size | CSS | `width:min(444px,calc(100vw - 24px))`, `height:min(660px,calc(100vh - 24px))` | `css.ts` → `.panel` | panel box | +| card body clamp | CSS | 3 lines | `css.ts` → `.cx` | body truncation | +| code block max height | CSS | `220px` | `css.ts` → `.code` | evidence and Now blocks scroll | +| `ago` "just now" | literal | `< 1500` ms (or non-finite) | `ui.ts` → `ago` | relative-time wording; otherwise `Ns ago`, `Nm ago` or `Nh ago` | +| `dur` formats | literals | `<1000` → `N ms`; `<10000` → `N.NN s`; `<60000` → `N.N s`; else `Mm SSs` | `ui.ts` → `dur` | durations | +| `clockT` | literal | `<100 s` → `12.48s`, else `m:ss.s` | `ui.ts` → `clockT` | activity timestamps | +| `mb` | literal | bytes/1048576, 1 decimal below 100 MB | `ui.ts` → `mb` | status strip sizes | +| user value quote | literal | 40 characters (39 + `…`) | `ui.ts` → `eventText` | activity text for user events | +| state paths shown | literal | 3 + `+N` | `ui.ts` → `eventText` | activity text for state events | +| expanded data value | literal | 300 characters (299 + `…`) | `ui.ts` → `dataLines` | expanded activity rows | +| `LEAD`, `NOUN`, `ADJ` | records | see source | `ui.ts` | title templates (`actTitle`, `diagTitle`, `phrase`) | +| `TABS`, `MODES`, `FILTERS`, `QLABEL` | arrays/records | 4 tabs; 3 modes with tooltips; 6 filter groups; `{diagnosis: "Diagnosis", action: "Action"}` | `index.ts` | labels | +| runtime: `DECISIONS_KEPT` | number | `200` | `src/runtime.ts` | size of `decisions()` / `interventions()` buffers; the explain map evicts its oldest entry when it exceeds `DECISIONS_KEPT * 2` = 400 (checked only when a decision is added) | +| runtime: `historySize` | `InitOptions` (inherited by `CreateOptions`) | `500` | `src/runtime.ts` (`new EventLog(o.historySize ?? 500)`) | how far back `history()` can backfill | +| runtime: `thresholds.report` | `PolicyOptions` | `0.6` | `src/decide/policy.ts` | when the runtime fires `detect` | + +Status strip strings (`renderStatus`): + +| State | Title | Meta | +|---|---|---| +| `ready` | `Model ready` | `WebGPU` or `WASM`, then `variant`, then `<mb(progress.total)> MB`, then `loaded in <dur(loadMs)>`, joined by ` · ` (only the parts that are present) | +| `loading` | `Loading model` | `<loaded> / <total> MB · <pct>`, or `starting…` | +| `error` | `Model unavailable` | `observing only · <error>` | +| `off` | `No model` | `observing only · no decisions` | + +The tooltip also shows `status.model`. + +Empty Interventions text (`renderEmpty`), checked in this order: + +| Condition | Title | +|---|---| +| status `loading` | `Model loading` | +| status `off` or `error` | `Observing only` | +| mode `observe` | `No interventions in observe mode` | +| mode `heal` | `No interventions yet` (with the heal explanation) | +| otherwise (guard) | `No interventions yet` (with the guard explanation) | + +The Detections empty state is fixed: `Nothing flagged`. The Activity empty state is `Waiting for activity`. + +Theme tokens (`css.ts` → `LIGHT` on `.root`, `DARK` on `.root[data-theme=dark]`; there is no `@media (prefers-color-scheme)` in the sheet, the `theme` option drives `data-theme`): + +| Token | Light | Dark | Used for | +|---|---|---|---| +| `--bg` / `--bg2` / `--bg3` | `#fff` / `#f8f8fa` / `#f0f0f3` | `#111215` / `#16171b` / `#202127` | surfaces, status strip and code blocks, chips/tracks | +| `--hover` | `#f6f6f8` | `#1a1b20` | row hover, expanded row | +| `--line` / `--line2` | `#e7e7ec` / `#d8d8df` | `#26272e` / `#34353e` | borders, scrollbars, idle bars | +| `--fg` / `--fg2` / `--fg3` | `#15161b` / `#4d505c` / `#868a97` | `#ececf1` / `#a3a6b3` / `#6d707e` | text levels | +| `--brand` / `--brand2` | `#5145e6` / `#7a5cf5` | `#958dff` / `#b19bff` | interventions, GenClass group, focus ring, progress gradient end | +| `--brand-bg` / `--brand-line` | `#f1f0ff` / `#dddaff` | `rgba(149,141,255,.13)` / `rgba(149,141,255,.3)` | intervention tints, `new` card border | +| `--warn` / `--warn-bg` / `--warn-line` | `#b45d09` / `#fff6e5` / `#f8dfb3` | `#f4b552` / `rgba(244,181,82,.11)` / `rgba(244,181,82,.26)` | detections, `×N`, pause banner and pressed pause button | +| `--ok` / `--ok-bg` | `#15803d` / `#eaf8ef` | `#51d28e` / `rgba(81,210,142,.11)` | ready dot, state group, `Undone`, Live | +| `--bad` / `--bad-bg` | `#d12f22` / `#fff0ee` | `#ff6f64` / `rgba(255,111,100,.11)` | error dot, failed notes, error group | +| `--blue` / `--blue-bg` | `#2563eb` / `#eef4ff` | `#6ea4ff` / `rgba(110,164,255,.12)` | user group, observe dot, progress gradient start | +| `--note` | `#f5f5f8` | `#1a1b20` | note background | +| `--seg` | `#fff` | `#2c2d35` | checked mode segment | +| `--sh` / `--sh-sm` | layered light shadows | layered dark shadows | panel / pill shadows | +| `color-scheme` | `light` | `dark` | native controls (search input, scrollbars) | +| `--font` | `Inter, "Inter Variable", ui-sans-serif, system-ui, …` | same | UI font (13px/1.45, tabular numerals) | +| `--mono` | `"JetBrains Mono", "JetBrains Mono Variable", ui-monospace, …` | same | code, timestamps, answer labels | +| `--ring` | set per class on `.pill.pa::after` (`--brand`) / `.pill.pdd::after` (`--warn`) | same | pill pulse colour | + +Animations (all disabled under `prefers-reduced-motion: reduce`): `ring` 1.5 s pill pulse, `bump` 0.5 s counter, `blink` (loading dot 1.1 s, Live dot 1.6 s), `spin` 0.8 s, `pop`/`popd` 0.22 s panel entry (bottom / top positions), `enter` 0.45 s new card, `fresh` 1.2 s new activity row. + +## Invariants and gotchas + +- **Read-only except two writes.** The overlay may only call `setMode` and `ActionRecord.undo`. Its only other runtime-visible effects are the setup-only `use()` plugin (for the `Clock`) and the `data-genclass-ignore` host attribute (next invariant). Never add calls that hold, act or ask the model from the overlay. Every runtime read is wrapped in `safe()` or try/catch, so a broken runtime method degrades a view instead of throwing into the app. +- **`data-genclass-ignore` is load-bearing.** Without it, overlay clicks, Enter/Escape keys and typing in the activity filter box (`input`/`change`) become `user` ops (the DOM user observer listens to `click`, `input`, `change`, `submit` and `keydown`). They would then appear in timelines, become causes, and corrupt "the last user action was …" facts. The skip lives in `src/observe/dom-user.ts` → `ignoredEvent` and is tested in `test/dom.test.ts`. Keep the attribute on the host, and keep interactive UI inside the host. +- **No trace pollution from timers.** The overlay's timers go through the runtime `Clock` from the plugin API. Browsers use the runtime's `browserClock`, which captured the real `setTimeout` before the timers observer wrapped it. + - `rawRaf` and `rawSetTimeout` are captured when the **devtools module** loads. `requestAnimationFrame` is never wrapped (`src/observe/timers.ts` wraps only `setTimeout`/`setInterval`). + - With the recommended lazy import after `GenClass.init`, `rawSetTimeout` may be the wrapped one. It is used only by the Copy-button reset and by the no-plugin fallback. A wrapped timer only materialises an op if its callback writes state or starts a request, and these callbacks do neither. +- **Virtual clocks.** Under a virtual clock (the sim's, or `VirtualClock` in `session.ts`), ticks and "ago" labels advance only when the clock advances. Scheduled list flushes use the real rAF, so they still render in tests. If an environment has no rAF, scheduled flushes go through `after(16)` on the plugin clock, so with a non-advancing clock they never run; only the synchronous flushes (open, undo, evidence, pause, clear) render then. +- **`setDoc` is module-global.** Two overlays in different documents loaded from one module instance (e.g. iframes) share `D`. Elements are created in whichever document was mounted last. One overlay per document per module instance is the supported case. +- **Reports from before mount are lost.** The runtime has no report history API, so cards backfilled at mount use the `ui.ts` templates. `Explanation.message` exists now but the overlay does not use it (see Drift). Template wording differs from `src/decide/report.ts` in places. +- **Detections in backfill and live can disagree.** Live detections are whatever the runtime fires on `detect` (`diagnosisConfidence >= policy.thresholds.report`). Backfill re-derives them with the literal `0.6`. An app that sets `policy.thresholds.report` sees a different Detections list after a remount. +- **Repeat folding is not the console's rule.** The overlay slides its window to the latest repeat (`same.at = d.at`). The `Reporter` uses a fixed 60 s window from the first report. Counts can differ from the console's `×N more` summaries. +- **Counters are bounded.** The intervention counter is `acts.size` (≤ 200). The detection counter is the sum of fold counts over ≤ 200 cards. Neither is a runtime total. `clear()` resets both. +- **Pause freezes rendering, not intake.** While paused, `flush` skips lists and events, and **that includes the Undo and Evidence clicks**. The undo itself runs, but the card is not redrawn until Resume (code reading; no test). Counters, status and mode still update. +- **The mode can change outside the overlay.** The `status` event updates the radios and the pill. Detection notes are refreshed only when the change came through the overlay's `setMode`, which marks det cards dirty. A console `rt.setMode()` leaves "Would have run … in X mode" notes stale until another update touches those cards (code reading). +- **Arrow keys on mode radios switch the runtime mode immediately.** This is tested (`ArrowLeft` from guard calls `setMode("observe")`). Do not "fix" it without updating `devtools.test.ts` and `ui-devtools.spec.ts`. +- **A failed action's body can repeat the failure.** `interventionLine` puts `(failed: …)` after `changed`. `splitReport` strips `changed` only when it is the exact suffix, so for a failed action with a live report sentence the body keeps `changed` plus `(failed: …)`, next to the `Action failed: …` note (code reading; no test). +- **`Decision.candidate`, `Decision.mass`, `ActionRecord.late`, `ModelStatus.phase`, `version` and `bytes` are not rendered.** A late revert shows as an ordinary intervention. Its title says "Reverted …" only when the live report sentence arrived. +- **Activity decision rows show no percentage for the real runtime.** The runtime's `decision` event data is `{ id, diagnosis, action, executed }`, with no `confidence` (`src/runtime.ts`). Only the mock scenario includes `confidence`. +- **CSS isolation rules:** + - The stylesheet must never target `html`, `body` or `:root`. A regex test enforces this. + - Every custom property the sheet reads is defined on `.root`, except `--ring`, which is set on `.pill.pa::after` / `.pill.pdd::after` where the `ring` keyframes read it. Inherited page variables with the same names (custom properties cross the shadow boundary, and `all:initial` does not reset them) are therefore shadowed. Keep that true when you add tokens. + - No `::part()` hooks or theming API are exposed. The page can only position or hide the host. + - The overlay does not load fonts. It names `Inter` and `JetBrains Mono` with system fallbacks. Only the Playwright page embeds the font files. + - `prefers-reduced-motion: reduce` disables all animations and transitions inside `.root`. +- **No `innerHTML`.** Use `h()` with `text:` and `icon()`. App-controlled strings (subjects, facts, event data) are rendered only through `textContent`. +- **The SVG mini-parser is not an HTML parser.** `ui.ts` → `svg()` understands only elements with double-quoted attributes. New icon markup with text, comments, single quotes or `>` inside attribute values renders wrong silently. Never pass app data to `svg()`. +- **Mounting must not start a model load.** The overlay reads `rt.status` and never `rt.ready` (reading `ready` starts a lazy load in `src/runtime.ts` → `get ready`). Keep it that way so `preload: "lazy"` apps stay lazy while the overlay is open. +- **The hotkey does not swallow the key.** The capture listener on `doc` only calls `preventDefault()`, so app handlers still see Alt+Shift+G. The runtime's DOM user observer records only Enter and Escape keydowns (`src/observe/dom-user.ts` → `onKey`), so the hotkey never becomes a `user` op. Escape inside the panel is stopped from bubbling and, being inside the ignored host, is not recorded either. +- **The overlay's token names collide with typical app names.** `page.ts` defines `--bg`, `--line`, `--fg` and `--fg2` on the app's `:root`. Because `.root` redefines every token it reads (`--ring` is set on the pill pseudo-elements instead), those inherited values never reach the overlay. A new `var(--x)` without a `.root` definition would silently inherit the app's value. +- **Performance budget.** Intake is O(1) per event (plus `bound()` eviction and the `evq` splice), except `addDet`, which scans up to 200 det cards for a matching `repeatKey`. Rendering is at most one flush per frame, and a list flush walks ≤ 200 entries per feed. `situation()` is called only while the Now tab is visible and the panel is open (1 Hz). `explain()` is called only when an evidence block is first opened. +- **Bundle.** The devtools entry must keep importing only `type`s from `../types.js`. A value import would pull runtime chunks into the dynamic `import("@genclass/runtime/devtools")` (tsup `splitting: true`). + +## How to change it safely + +The team runs builds and tests on the remote VM (see [build-test-release.md](./build-test-release.md)). The commands below are for that environment. Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the vitest commands locally. Ask the user before the Playwright UI spec ([where to run things](./build-test-release.md#where-to-run-things)). + +### Add a mount option + +1. Add it to `DevtoolsOptions` in `src/devtools/index.ts` with a JSDoc default, and read it in the `Devtools` constructor. +2. Mirror the field in `demos/src/dev/runtime-shim/devtools.ts`, which duplicates the interface. +3. If the option affects layout or theme, add an assertion like the "honours theme and position" test in `test/devtools.test.ts`. +4. `test/browser/ui/page.ts` passes the full options object through, so the spec can exercise it. + +### Add or change a view (tab) + +1. Extend `DevtoolsTab` and `TABS`, and add a pane in the constructor's `panes` record (`pane(id, …)`). `setTab` and the roving keys pick it up automatically. Keep `interventions` and `detections` as the first two `TABS` entries: the tab counters `nA`/`nD` are looked up as `tabBtns[0]` and `tabBtns[1]`. Also widen the `tab` union in `demos/src/dev/runtime-shim/devtools.ts`. +2. If it polls the runtime, gate it like `renderNow` (open, tab selected, not paused, not dead) and refresh it from `startTicking`. +3. Add a `data-pane` assertion test and a screenshot entry in the loop over `["detections", "activity", "now"]` in `ui-devtools.spec.ts`. + +### Show a new `Decision` or `ActionRecord` field on cards or in evidence + +1. Render it in `card()` (chips or note) or `evidence()` (a new `sec(title, extra, …)`). Use `h()` with `text`. +2. Add the field to `makeDecision` or `makeAction` in `test/browser/ui/mock-runtime.ts` and set it in `scenario.ts`. Assert it in `devtools.test.ts`. +3. When the field comes from a CORE change, coordinate through `UI-NEEDS.md` / `STATUS.md`. If it changes the situation text, SIM must be involved (see [model-io-contract.md](../model-io-contract.md)). + +### Change report wording or templates + +1. The runtime sentences come from `src/decide/report.ts` (`interventionLine`, `detectionLine`). If you change their shape, check that `splitReport`'s regexes in `ui.ts` still strip: + - the `[GenClass]` prefix + - the `(diag, p; action p)` tail + - `Not acted on (…): …` + - a `(×N …)` suffix +2. Keep `LEAD` and `NOUN` in `ui.ts` aligned with `report.ts` when you intend the same wording (the current differences are listed in Drift). +3. Update the expected titles in `devtools.test.ts` and `devtools-runtime.test.ts`. The latter's titles come from the templates, because the session runs before mount. + +### Use the runtime sentence for cards recorded before mount (UI-NEEDS item 3) + +In `card()`, when `msg` is undefined, fall back to `safe(() => this.rt.explain(id)?.message, undefined)` for the action id or decision id. Then update the assertion under the comment "reports emitted before mounting are not replayed" in the `devtools.test.ts` test "renders interventions, detections, status and counters from the runtime"; it currently expects the lead fact as the `.cx` body. Also re-check the title and `.cx` body expectations in `devtools-runtime.test.ts` (its first test matches the stale-write body against a regex). `MockRuntime.explain` returns `scenario.ts` explanations, which lack `message`. Add it there. + +### Change styling or theme + +1. Edit `css.ts` only. Add tokens to both `LIGHT` and `DARK`, and use them via `var(--x)` inside `.root` selectors. +2. Do not add selectors for `html`, `body` or `:root` (a test checks this). +3. Run `ui-devtools.spec.ts`, review the regenerated PNGs in `test/browser/ui/screenshots/` (there is no pixel diff), and commit them if intended. + +### Add an icon + +1. Add the inner SVG markup to `ICONS` in `src/devtools/ui.ts` (24×24 coordinate space, stroke-only paths, double-quoted attributes, no text). `IconName` picks it up automatically. +2. Use it with `icon("name")` (or `icon("name", "i chev")` for an extra class). The `.i` class in `css.ts` sets 16×16, `fill:none`, `stroke:currentColor`, `stroke-width:1.8`. + +### Add or change an activity event kind, label or filter group + +1. Labels: `KIND_LABEL` (non-op kinds) and `OP_LABEL` (op kinds from `data.kind ?? data.opKind`) in `ui.ts` → `kindLabel`. +2. Row text: a `case` in `ui.ts` → `eventText`. Groups: `ui.ts` → `groupOf` and the `Group` type. +3. A new group also needs an entry in `FILTERS` (`index.ts`) and, for a coloured badge, `.g-<group> .k` and `.f.g-<group>[aria-pressed=true]` rules in `css.ts`. +4. If the runtime adds a new `EventKind` (`src/types.ts`), it falls into `other` until you map it. Extend the activity assertions in `devtools.test.ts` (`rows.length`, group filters) and, for real-runtime events, `devtools-runtime.test.ts`. + +### Change the Now view + +1. Edit `renderNow` in `index.ts`. Section sources are `Situation` fields (`trigger`, `salient`, `subject`, `facts`, `actions`) and `Situation.state` keys from `src/situation/serialize.ts` (`app`, `trigger`, `facts`, `in_flight`, `timeline`, `state`, `stats`). If those keys are renamed (a SIM-coordinated, `situation-v1`-relevant change, see [learn-situation-triage.md](./learn-situation-triage.md)), update `renderNow` and `scenario.ts`'s scripted `sit.state`. +2. Keep the gating: Now polls `situation()` only when open, on the Now tab, not paused and not dead. +3. Tests: "renders the Now view from runtime.situation() and reports failures" (`devtools.test.ts`) and "renders runtime.situation() in the Now view" (`devtools-runtime.test.ts`). + +### Subscribe to a new runtime event + +1. Add it to `RuntimeEvents` in `src/types.ts` (CORE) and to `subscribe()` through the local `on()` wrapper, which handles the dead-guard and the unsubscribe. +2. Extend `MockRuntime` if needed. Update the unmount test's list `["event", "act", "detect", "decide", "status", "report"]` so that it asserts zero listeners afterwards. + +### Change the `Runtime` interface the overlay uses + +`MockRuntime implements Runtime`, but test files are not type-checked (`packages/runtime/tsconfig.json` has `include: ["src"]`). Update `mock-runtime.ts` and `demos/src/dev/runtime-shim/*` by hand, then run both devtools vitest files. + +### Commands (on the VM, from `packages/runtime`) + +- Unit and integration: `npx vitest run test/devtools.test.ts test/devtools-runtime.test.ts`. Also run `test/dom.test.ts` if you touch the ignore attribute, and `test/adapters-*.test.ts` if you touch `mock-runtime.ts`. Plain `npm test` (`vitest run`, `include: ["test/**/*.test.ts"]`, `exclude: ["test/browser/**"]`) runs all of them. +- Browser: from the repo root, `npx playwright test --config packages/runtime/test/browser/ui/playwright.config.ts`. `npm run test:browser` also picks up `ui-devtools.spec.ts`, because the main `test/browser/playwright.config.ts` matches every `*.spec.ts`. + +## Tests + +| Test file | What it asserts | +|---|---| +| `test/devtools.test.ts`, "devtools: mount" | Host tag, parent and open shadow root. `data-genclass-ignore` is set. One listener each for `event` and `act` (the only two counted at mount) and one plugin. No `<style>`/`<link>` or stylesheet added to the document. Unmount removes the host, all 6 listeners and the plugin, `element` becomes `null`, and a second unmount is safe. Styles live only in the shadow root, and `CSS` never targets `html`, `body` or `:root`. The host is `fixed` with z-index `2147483646`. A null runtime gives a no-op handle. `theme: "dark"` and `position: "top-left"` give `data-theme`, `data-pos` and `top`/`left` of `16px`. | +| `test/devtools.test.ts`, "devtools: feeds" | Counters (3 and 3), status "Model ready" with WebGPU. Intervention order `a3, a2, a1` and template titles. The body is the lead fact (pre-mount reports are not replayed). The diagnosis chip shows `stale 97%`. Undo is shown for discard and hidden for coalesce. Detection titles and "Would have run hedge in heal mode.". Activity pairing (row count = events − min(starts, ends)), `2001.82 s`, `#3`, an in-flight spinner, `← #n` on state rows, group and text filters, row expansion (`value: 3`, `op: #17`). A typing-burst re-emit updates a single row. Evidence content equals `explain("a1")` (facts, situation text, top answers, deny hint) and collapses. Undo calls `undo` once and shows Undone. A throwing undo shows `Undo failed: store gone`. A live act pulses the pill (`pa`), updates the counter and `aria-label`, and a later report sentence replaces the body minus `changed`. Detections fold ×3 with the passive note. An executed non-passive decision never becomes a detection. The 200-card cap holds while the panel is closed (newest `a210`, oldest `a11`). The policy-held note text. Pause shows `Feed paused · 1 new` while counters stay correct, and resume renders. Clear empties everything. The Now view comes from `situation()`, and a throw shows `situation() failed`. | +| `test/devtools.test.ts`, "devtools: controls" | A click on the heal radio records `calls.setMode` = `["heal"]` and updates the radio and pill. The would-have note switches wording with the mode when no reason is given. Keyboard: the pill is a `<button>`, focus moves to the tab, ArrowRight and End work, ArrowLeft on the mode radio calls `setMode("observe")`, Escape closes and focuses the pill, Alt+Shift+G reopens. Empty-state text by model state: "Model loading", `4.8 / 19.1 MB · 25%` with the bar at 25%, then "No interventions yet" and `WASM · q8`. | +| `test/devtools-runtime.test.ts` | Mounted after `runStoreSession()` on the real runtime. Interventions are, newest first: Prevented a stale write, Prevented a duplicate write, Prevented a duplicate request, Slowed down a failing request. `.chg` equals `ActionRecord.changed`. Undo is present for discard and absent for coalesce. Detections are: Slow request, Unusual state change, Inconsistent state, Failing request ×3, with their notes. The detection count matches the runtime's decisions. Evidence equals `explain()` (situation text contains `trigger: A write to search.results`, top labels `stale`/`discard`). Activity has more than 60 rows, `2001.82 s`, the typing burst `= "react" (2 keystrokes)`, an in-flight spinner, `model` rows and error rows. The Now subject equals `situation().subject`, and "Acme Store" appears. Undo really applies the dropped write (results 4 → 8) and records an `action`/`undo` event. A new live stale-write intervention uses the runtime's report sentence without duplication. | +| `test/browser/ui-devtools.spec.ts` | Real Chromium: style isolation (stylesheet count, app CTA background and body font unchanged; shadow root and ignore attribute present; only 2 `<style>` tags, fonts and app). Real keyboard flow (Enter on the pill, ArrowRight, End, ArrowRight on radios gives `heal`, Escape, Alt+Shift+G). Undo marks the card. Screenshots for light and dark: `pill`, `overlay`, `interventions`, `evidence`, `evidence-answers`, `detections`, `activity`, `now`, `loading`. They are written only, never compared. | +| `test/dom.test.ts` (outside the scope, related) | Events inside `[data-genclass-ignore]`, including inside a `genclass-devtools` shadow root, are not recorded as user actions. | + +Harness details: + +- **`MockRuntime`** (`mock-runtime.ts`): + - Test controls: `emitTo(type, v)`, `setStatus(s)` (emits `status`), `event(kind, name, {t, op, cause, data})` (emits `event`; `seq` auto-increments, `t` defaults to `clock.t`), `decision(d)` (emits `decide`, plus `detect` when `diagnosis !== "expected"` and `diagnosisProbabilities[diagnosis] ?? diagnosisConfidence` ≥ 0.6), `act(a)`, `report(r)`, `listenerCount(type)`. + - Inspectable fields: `plugins`, `calls.{setMode, situation, explain, sets}`, `explanations` (Map), `sit`, `ops`, `events`, `decs`, `acts`, `mode` (starts `"guard"`), `status` (starts `{ state: "off" }`). + - Runtime API behaviour: `situation()` throws `no situation scripted` while `sit` is `null` (how the "situation() failed" test is driven). `explain(id)` returns `explanations.get(id) ?? null`. `history(n=500)`, `decisions(n=200)`, `interventions(n=200)` slice the recorded arrays. `use()` calls `setup` synchronously with a `PluginApi` whose `clock` is the `MockClock`, and its disposer removes the plugin. `setMode` records and sets `mode` but does **not** emit `status` (unlike the real runtime). `ask()` rejects (`mock runtime: no model`), `decide()` resolves the first option, `holdBudgetMs()` → `300`, `situationBudget()` → `3200`, `destroy()` clears listeners. + - Store semantics for the adapter tests: `holdWrites` (hold every write made outside a synchronous `user()` handler unless `opts.hold === false`), `heldCount`, `flushHeld()` (apply in proposal order; functional updates re-run against the value at apply time), `dropHeld()` (the `discard` action: nothing applied, nobody notified), `genclassWrite(store, v)`, `subscribers(store)`. Applied writes emit a `state` event. + - `MockClock`: mutable `t` (starts `0`; `now()` returns it), real `setTimeout`/`clearTimeout`, `afterTask` = `setTimeout(fn, 0)`. + - `choice(probs)` returns a `ChoiceAnswer` whose `confidence` is `(k·p−1)/(k−1)` for k labels. + - `makeDecision(p)` (requires `diagnosisProbabilities` and `probabilities`) defaults: id `d<n>`, `trigger "mutation"`, `subject ""`, `at 0`, `latencyMs 31`, `model "genclass-runtime-0.1"`, diagnosis and action = the top labels, `diagnosisConfidence` = the choice confidence above (**not** a probability), `confidence = probabilities[action]`, `executed false`, `tier "passive"`, `ran = action`, `facts []`, `answers = { diagnosis, action }` built with `choice`. + - `makeAction(d, p)` defaults: id `a<n>`, fields copied from `d`, `at = d.at + 1`, `ok true`, `changed ""`, `undo` only when given. +- **`loadScenario(rt, { onUndo?, now? })`** (`scenario.ts`): + - Status `ready`, `device "webgpu"`, `variant "fp16"`, `model "genclass-runtime-0.1"`, `progress.total 24_740_000` bytes (rendered as `23.6 MB` by `mb()`), `loadMs 1240`. Decisions carry `model "genclass-runtime-0.1 · fp16"`. + - Interventions: `a1` discard (stale search write, undo calls `onUndo("a1")`), `a2` coalesce (double POST /api/orders, no undo), `a3` delay (failing GET /api/status, no undo). The mock also emits `detect` for their decisions `d1`, `d2`, `d4` (before mount in the tests, so nobody listens); at backfill `addDet` skips them because `actOf` already has them and they are executed non-passive. + - Detections: `d3` unusual transition → rollback (heal), `d6` inconsistent → rollback (heal), `d5` slow stall → hedge (heal). All three carry `reason: "guard mode does not allow heal-tier actions"`, so their notes read "Would have run … in heal mode.". + - Report sentences for all six are emitted **before** the test mounts, so the overlay never sees them (that is what "reports emitted before mounting are not replayed" relies on). + - Explanations exist for `a1`, `a2`, `a3`, `d3` and `d6`, but not `d5` (its evidence shows the "no longer in the runtime's decision buffer" line). They are built by a local `explanation()` and `stateText()` (`key:\nvalue` blocks), and omit `message`. + - Events: 48 scripted `RtEvent`s (nav, fetch op pairs with `data.kind "fetch"`, user, state with `data.paths`, decision events **with** `confidence`, action events, one `TypeError` error). `GET /api/search?q=rea` (#3) takes 2214 → 4031, i.e. the `2001.82 s` assertion is `200` + `1.82 s`. Op `#15` (`GET /api/recommendations?for=cart`, start 22100) never ends, so it shows a spinner. + - The Now situation: `trigger "ask"`, `salient true`, 4 facts, `actions []`, `questions {}`, `state` with all seven `SituationParts` keys; `rt.ops` holds op `#15`. `rt.clock.t = now ?? 27_400` (so op #15 is `5.30 s` in flight). +- **`runStoreSession(opts)`** (`session.ts`): + - Uses `createRuntime({ clock, global: { fetch: backend.fetch, Response, location }, decider, report: "silent", observe: OBSERVE, app: () => ({ title: "Acme Store", route }) })`. `OBSERVE` enables only `fetch` (`user`, `xhr`, `errors`, `nav`, `storage`, `perf`, `websocket`, `timers` are `false`), so user ops come only from explicit `rt.user()` calls and errors from `rt.reportError()`. + - Stores (atoms): `session`, `search`, `cart`, `orders`, `status`, `recs`. + - Warm-up (clock starts at `400`): `GET /api/session` and `GET /api/cart`, then 24 alternating cart add/remove ops 560 ms apart with a status poll every 4th and recommendations every 5th, so baselines, profiles and invariants are learned. + - Story: (1) 4 failing polls 2 s apart, then a held poll (`delay`); (2) a partial `POST /api/cart` response without `total` (unusual transition, broken total invariant); (3) double "Place order" 90 ms apart (`coalesce` and a duplicate write); (4) recommendations latency 9000 ms (stall → hedge, not run in guard); (5) typeahead `rea` (1820 ms) vs `react` (210 ms) (stale write → `discard`); (6) a `TypeError` reported from a `change input "Qty"` handler. + - `SessionOptions`: `warmupOnly` (return after the warm-up; used by the `loading` page scenario), `status` (initial decider status, default `READY`), `turn` (task-boundary function, default `realTurn()`). + - `Session`: `rt`, `clock` (`VirtualClock`), `backend` (knobs `statusDown`, `partialCart`, `recsLatency` default 300, `searchLatency` map with a 180 ms default, `cart`), `decider`, `stores.search`, `app.{typeSearch, placeOrder, poll}` to keep driving the app after the story (the last `devtools-runtime.test.ts` test does this). + - `VirtualClock`: `setTimeout` queues by virtual time; `advance(ms)` runs due timers in `(at, id)` order and calls `settle()` after each; `settle()` runs up to 64 rounds of 4 real turns, then the queued `afterTask` hooks, until none remain. `realTurn()` uses `setImmediate` (Node) or a `MessageChannel` (browsers). + - `SessionDecider` (`DecisionProvider` test double): `judge(req)` maps `req.trigger` plus fact regexes to `[diagnosis, p, action, pa]`, e.g. `stall` → `slow 0.84 / hedge 0.71`, `transition` → `unusual 0.88 / rollback 0.64`, `inconsistency` → `inconsistent 0.9 / rollback 0.58`, stale write → `stale 0.97 / discard 0.98`. Remaining mass is spread over the other labels (62% of what is left each step, the last label takes the rest). It answers after `22 + (length of the facts joined with "\n") % 17` virtual ms (`factsOf(req).length`, a character count, not the number of facts). `READY` = `{ state: "ready", device: "webgpu", variant: "fp16", model: "genclass-runtime-0.1", loadMs: 1240, progress: 24_740_000 / 24_740_000 }`. +- **`page.ts`**: `window.__gc = { start(opts), rt?, dt?, undos }`. `start({ scenario?, mode?, status?, ...DevtoolsOptions })` unmounts the previous overlay, destroys the previous runtime, re-injects `<style id="app-css">` and the Acme HTML, builds the runtime, applies `mode` via `setMode`, and calls `mountDevtools(rt, opts)` (the whole options object is passed through). Scenarios: + + | `scenario` | Runtime | + |---|---| + | `live` (default) | real runtime after the full `runStoreSession()` | + | `loading` | real runtime after `runStoreSession({ warmupOnly: true, status: { state: "loading", progress: { loaded: 9_830_000, total: 24_740_000 } } })` | + | `mock` | `MockRuntime` + `loadScenario`, undos pushed to `window.__gc.undos` | + | `empty` | `MockRuntime` with `clock.t = 2600` and one `GET /api/session` op (start 1130, end 1342) | + + `status` is applied only to the mock scenarios (`mock`, `empty`). The app CSS defines `--bg`, `--line`, `--fg`, `--fg2` (plus `--card`, `--accent`) on `:root`, the same names as overlay tokens (see Invariants). +- **`ui-devtools.spec.ts`**: `beforeAll` bundles `page.ts` with esbuild (`iife`, `es2022`, external `onnxruntime-web` and `onnxruntime-web/webgpu`) into one HTML string with Inter and JetBrains Mono woff2 inlined from `<repo>/node_modules/@fontsource-variable/*`. Its `start()` emulates the colour scheme **and `reducedMotion: "reduce"`**, waits for both fonts and two animation frames. `shotPanel` clips the host's box plus 28 px (24 px for the pill). Screenshot sources: `pill` (live, collapsed), `overlay` (live, full 1280×800 viewport), `interventions`, `evidence` and `evidence-answers` (live, stale-write card), `detections`, `activity`, `now` (live), `loading` (loading scenario). The keyboard and undo tests use `scenario: "mock"`. +- **UI Playwright config**: + - `testDir: ".."`, `testMatch: /ui-.*\.spec\.ts$/` + - Chromium, viewport 1280×800, `deviceScaleFactor: 2` + - timeout 90 s, 1 worker, `reporter: list`, `outputDir: ../../../test-results/ui` + - The main `test/browser/playwright.config.ts` (`testMatch: /.*\.spec\.ts$/`, `globalSetup: ./build.mjs`, 600 s timeout) also runs `ui-devtools.spec.ts` in its `chromium` project. + +## Drift and open issues + +| # | Item | Docs say | Code says | +|---|---|---|---| +| 1 | DOM observer ignoring the overlay | `UI-NEEDS.md` lists it under **Open** (item 1) | Done. `src/observe/dom-user.ts` → `ignoredEvent` / `insideIgnored` checks `composedPath()[0]` and `target` across shadow roots. Tested in `test/dom.test.ts`. `STATUS.md` ("For UI") agrees it is done. | +| 2 | `react-dom` devDependency | `UI-NEEDS.md` item 2 (Open). `packages/runtime/STATUS.md` "Open issues": "`react-dom` is not a devDependency" | `packages/runtime/package.json` devDependencies include `react-dom ^19.3.0` and `@types/react-dom ^19.0.0`. | +| 3 | `Explanation.message` (UI-NEEDS item 3) | "Nice to have"; pre-mount items fall back to templates | CORE has implemented it (`src/types.ts` → `Explanation.message`, `src/runtime.ts` → `explain`). The **overlay still ignores it**: `card()` reads only `msgs` from `on("report")`. This is open UI work (recipe above). | +| 4 | Mock needs budget methods | `STATUS.md`: mock-runtime "needs `holdBudgetMs()` and `situationBudget()`" | Present in `MockRuntime` (return `300` and `3200`). | +| 5 | Ownership | `docs/runtime/CONTRACT.md` layout table: `src/devtools/` "owner: CORE" | The same CONTRACT's later rule and `UI-NEEDS.md` say UI owns `src/devtools/**`. | +| 6 | Templates "mirror" `report.ts` | `ui.ts` comment: templates "mirror the runtime's console wording" | Differences: failure noun `failed request` (UI) vs `request failure` (report). UI-only adjectives `conflict→conflicting` and `overload→excessive`, plus the special case `failing request`. An unknown action is `Ran <action>` (UI) vs `Handled` (report). UI ignores `late` (report: `Reverted`). Detection cards use `diagTitle` ("Slow request"), never the report's "Flagged …". | +| 7 | Bundle size | `packages/runtime/README.md`: "52 KB minified, 17 KB gzip"; `OPEN_TASKS.md` item 7: "52 KB min / 17 KB gz" | The 52/17 KB figures are unverified: `tsup.config.ts` sets no `minify` and no minified build is checked in. A `tsup` build of 654d822 gives an unminified `dist/devtools/index.js` of 69,191 bytes, 20,276 bytes gzip (about 20.3 KB). | +| 8 | "dev-only lazy import" | `OPEN_TASKS.md` item 7 (**Docs**, under "Next") lists "dev-only lazy import of the devtools" as still to do | The README already shows `if (import.meta.env.DEV) { … await import("@genclass/runtime/devtools") … }`. It is a documentation item only: there is no code-level dev guard in the library. | +| 9 | Folding "like the console's rate limiting" | comment in `addDet` | Sliding window (latest repeat) vs the `Reporter`'s fixed 60 s window from the first report. | +| 10 | Detection threshold | Runtime uses `policy.thresholds.report` (default 0.6, configurable) | Overlay backfill hard-codes `0.6`. | +| 11 | `scenario.ts` data shapes | `Situation` requires `compact` and `budget`; `Explanation` requires `message` (`src/types.ts`) | The scripted `sit` omits `compact`/`budget`, and the scripted explanations omit `message`. This compiles only because tests are not type-checked. | +| 12 | Font dependency of the UI spec | n/a | `ui-devtools.spec.ts` reads `node_modules/@fontsource-variable/{inter,jetbrains-mono}`, which are declared only in `demos/package.json` and resolve through workspace hoisting (the same class of issue as UI-NEEDS item 2). | +| 13 | "README screenshots" | `ui-devtools.spec.ts` header comment ("the README screenshots") and `session.ts` header comment ("the README screenshots") | No README or doc in the repo references `test/browser/ui/screenshots/*.png`: `git grep "screenshots/"` finds only the spec's own header comment plus unrelated `demos/` and `extension/` paths, and no file names `pill-light`, `overlay-light` or `interventions-light`. The 18 PNGs are tracked but unused by docs. | +| 14 | Mock vs real `setMode` | `index.ts` → `subscribe` comment: "setMode() is announced as a status change too" | True for `RuntimeImpl.setMode` (fires `status` and a `status` report). `MockRuntime.setMode` emits nothing, so unit tests cover the overlay's own `renderMode` path, not the `on("status")` path for mode changes. | + +Status of every `UI-NEEDS.md` item, verified against the code: + +| UI-NEEDS item | File says | Verified status | Remaining work | +|---|---|---|---| +| 1. DOM user observer ignores the overlay | Open | Done in CORE (`src/observe/dom-user.ts` → `ignoredEvent`), tested in `test/dom.test.ts` | Move the item to "Done" in `UI-NEEDS.md` | +| 2. `react-dom` + `@types/react-dom` devDependencies | Open | Done (`packages/runtime/package.json`) | Move to "Done"; also fix `packages/runtime/STATUS.md` "Open issues" | +| 3. `Explanation.message` | Nice to have | CORE done (`src/runtime.ts` → `explain` builds `message` with `interventionLine` / `detectionLine` / `decisionLine`) | **UI open:** use it in `card()` for pre-mount items (recipe "Use the runtime sentence for cards recorded before mount") | +| Done: `on("report")` also with `report: "silent"` | Done | Verified: `src/decide/report.ts` → `Reporter.emit` calls the listener before the `silent` sink check | none | +| Done: `runtime.adapter()` with `propose({ fn, commit })` | Done | Out of scope here; see [state-and-adapters.md](./state-and-adapters.md) | none | + +Open UI behaviours found by code reading (no tests): +- Undo and Evidence do not redraw while the feed is paused. +- Detection notes go stale after a mode change made outside the overlay. +- Failed-action bodies built from a live report sentence keep `changed` and `(failed: …)`, repeating the `Action failed: …` note. +- `Decision.candidate`/`mass` (what GenClass *would* run under the current policy) is not shown. The overlay's "would have run" note uses `d.action` and `d.tier`. + +## Related docs + +- [public-api-and-lifecycle.md](./public-api-and-lifecycle.md): `Runtime` API, `on()` events, `explain`, `situation`, `setMode`, `use()` +- [observe-and-trace.md](./observe-and-trace.md): `RtEvent`, `EventLog` (`touch` for typing bursts), the DOM user observer and `data-genclass-ignore`, the timers observer +- [decide-policy-actions.md](./decide-policy-actions.md): `Decision`, `ActionRecord.undo`, report sentences (`src/decide/report.ts`), thresholds, tiers +- [learn-situation-triage.md](./learn-situation-triage.md): `Situation`, `SituationParts` keys rendered by the Now view, salience +- [model-host.md](./model-host.md): `ModelStatus` fields shown in the status strip +- [state-and-adapters.md](./state-and-adapters.md): the store semantics `MockRuntime` models for the adapter tests, and the adapters half of `UI-NEEDS.md` +- [build-test-release.md](./build-test-release.md): tsup entries, `exports["./devtools"]`, vitest and Playwright configs, VM-only builds +- [../overview.md](../overview.md) +- [../glossary.md](../glossary.md): devtools terms (pill, backfill, repeat folding, render bits) and runtime terms +- [../model-io-contract.md](../model-io-contract.md): what `situationText` is relative to the packed model request +- [../demos.md](../demos.md): how the demos mount the overlay (`?devtools=open`) and the runtime shim +- [../status-and-known-issues.md](../status-and-known-issues.md): UI-NEEDS, STATUS and OPEN_TASKS in context +- Source request log: [`packages/runtime/UI-NEEDS.md`](../../../packages/runtime/UI-NEEDS.md) diff --git a/docs/agents/runtime/learn-situation-triage.md b/docs/agents/runtime/learn-situation-triage.md new file mode 100644 index 00000000..baad7fa4 --- /dev/null +++ b/docs/agents/runtime/learn-situation-triage.md @@ -0,0 +1,1056 @@ +# @genclass/runtime: baselines, profiles, facts, triggers, triage and situation serialisation + +> **Scope:** `packages/runtime/src/learn/baselines.ts`, `packages/runtime/src/learn/profiles.ts`, +> `packages/runtime/src/situation/{build,facts,describe,env,questions,serialize}.ts`, the triage code in +> `packages/runtime/src/runtime.ts` (`RuntimeImpl.trigger`, `RuntimeImpl.settled`, `RuntimeImpl.situationBudget`, +> `RuntimeImpl.makeEnv`) and the text helpers they use in `packages/runtime/src/util.ts` and +> `packages/runtime/src/state/fields.ts` (`changeText`). Triage/salience lives only in `situation/facts.ts` +> (`neutral` flags), `situation/build.ts` (`salient`, `forced`) and `runtime.ts` -> `RuntimeImpl.trigger`; other +> hits for "salient" in `adapters/`, `observe/fetch.ts` and `devtools/index.ts` are comments or display. +> **Read this when:** you change any text the model reads (fact wording, timeline/state/stats lines, questions, +> action descriptions, diagnosis labels), the triage rule (what is salient), the situation budget or section limits, +> redaction, the latency/error/rate baselines, or transition profiles; or when you need to know why a trigger did or +> did not reach the model. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- **Every byte here is model input.** The sim (`sim/`) generates training rows by running the real + `createRuntime` from `@genclass/runtime` and recording exactly the `state`/`questions` this code produces + (`sim/src/run/rt.ts` -> `realRuntimeFactory`). `training/curriculum/rt.py` is a hand-written Python port of the same + modules. Changing wording, ordering, thresholds, budgets or formatters changes model inputs: the final-round + training data (SIM phase A) is generated from the runtime frozen at git tag `situation-v1` (commit 1a77558), and + final round 1 of R17/R32 was launched on it (`training/LOG.md`; results still "(in progress)" in + `training/EVAL.md`, no model package published yet per `OPEN_TASKS.md`). `git diff situation-v1 HEAD -- + packages/runtime/src` is empty at 654d822. +- **Baselines** (`Baselines`): per op signature (`GET /api/items/:id`), for fetch/XHR only: last 64 non-failure + latencies (nearest-rank median/p95, needs >= 5 samples), last 20 outcomes, failure streak, EWMA error rate + (alpha 0.1; never read by facts, stats or devtools: only `Baselines.snapshot()` returns it, and nothing in `src/` + calls `snapshot()`), last 128 start times (rate: starts in the last 10 s vs the usual rate), and per request + identity the EWMA gap between identical requests. +- **Transition profiles** (`Profiles`): per op signature (user ops: `user <name>`), counts over completions of the + written-field set, value kind per field, status class, write-count bucket and duration bucket. A completion is + *unusual* when its set, a field's kind, its status class or its write count was seen in < 1% of >= 20 previous + completions (duration is recorded but never checked). +- **Triggers** (`TriggerKind`): `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, + `ask`. Each has a `SubjectSpec` (what the situation is about) and a `SubjectRef` (structured id for the sim/tests). +- **Facts** (`computeFacts`): uniform English sentences per trigger, each with a `kind` (ranked) and a `neutral` + flag. Ordered non-neutral first, then by kind rank, stable; capped at 12 (`MAX_FACTS`). +- **Triage**: with `triage: "salient"` (default) the model is consulted only if some fact has `neutral: false`, or a + standing question with `always: true` applies, or the trigger is `ask`. Otherwise the passive action runs with no + model call and no decision record. Triage is a cost filter only; it never picks a diagnosis or an action. +- **Situation** = Jev state object with keys in fixed order `app`, `trigger`, `facts`, `in_flight`, `timeline`, + `state`, `stats` (empty arrays become the string `"none"`), plus questions `diagnosis` (always, except `ask`) and + `action` (only when > 1 action applies). +- **Budget** in characters: `STATE_CHAR_BUDGET = 3200` (full), `COMPACT_BUDGET = 1100` (compact limits), linear in + between (`sectionLimits`); `MIN_BUDGET = 500`. Over budget: drop timeline (oldest first), then state, facts (keep + >= 1), in-flight, stats; then shorten facts and the trigger. Questions are compact (bare labels) at <= 1400 chars. +- **Device sizing** ("auto"): WebGPU or unknown device 3200; WASM `1000 + round((threads - 1) * 1000 / 3)` for + 1..4 threads (1000/1333/1667/2000); scaled by 0.8 per `max_tokens_exceeded`, floor 0.5. +- **Deterministic and side-effect free**: only the injected clock is read; the only write is caching field versions + in `op.reads`. Same inputs give byte-identical situations (tested at the default 3200 in `situation.test.ts` and at + 1100 in `budget.test.ts`). +- **Model text also comes from outside this folder**: action-effect sentences, hub write summaries (`changeText`) and + observer op details reach the model through the timeline (see Invariants). + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `packages/runtime/src/learn/baselines.ts` | online per-signature latency, outcomes, failure streak, rate; identity gaps | `Baselines` (`start(sig, t, identity?)`, `end(sig, t, latency, ok, outcome, countsAsFailure)`, `noteIdentity`, `latency`, `rate(sig, now)`, `failureCounts`, `stats`, `identity`, `snapshot`; public maps `sigs`, `ids`), `SigStats`, `LatencyBaseline`, `RateBaseline`, `IdentityStats`, `isFailureOutcome`, `outcomeLabel` | +| `packages/runtime/src/learn/profiles.ts` | transition profiles and rarity check | `Profiles` (`check`, `add`, `get`, `toJSON`, `load`), `shapeOf`, `kindLabel`, `writesBucket`, `durBucket`, `Profile`, `Shape`, `Unusual`, `MIN_COMPLETIONS`, `RARE` | +| `packages/runtime/src/situation/env.ts` | what situation code may read from the runtime; trigger subjects | `SitEnv`, `SubjectSpec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo`, `CachedInfo`, `ChainWriteInfo` | +| `packages/runtime/src/situation/facts.ts` | fact computation per trigger, ordering | `computeFacts`, `orderFacts`, `MAX_FACTS` | +| `packages/runtime/src/situation/describe.ts` | how ops and events are phrased | `userPhrase`, `opPhrase`, `opLabel`, `statusText`, `eventLine` | +| `packages/runtime/src/situation/build.ts` | subject sentence, sections, applicable actions, questions, salience | `buildSituation`, `subjectOf`, `subjectRef`, `isTrigger` (exported, not used anywhere in `src/` or `sim/src`), `BuildOptions`, `BuiltSituation`, `ActionOption`; internal `subjectOp`, `involvedStores`, `involvedFields`, `inFlightLines`, `timelineLines`, `stateLines`, `statsLines`, `builtinApplicable`, `revertableChain`, `appText` | +| `packages/runtime/src/situation/questions.ts` | action catalogue, per-trigger actions, instructions, diagnosis vocabulary, question building | `BUILTIN_ACTIONS`, `BuiltinAction` (`{ name, tier, description }`), `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | +| `packages/runtime/src/situation/serialize.ts` | budget-shaped Jev state | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `SituationParts`, `SectionLimits` | +| `packages/runtime/src/runtime.ts` (parts) | owns the `Baselines`/`Profiles` instances, feeds them, implements `SitEnv`, runs triage | `RuntimeImpl.trigger`, `RuntimeImpl.settled`, `RuntimeImpl.situationBudget`, `RuntimeImpl.buildOpts`, `RuntimeImpl.makeEnv`, `RuntimeImpl.startOp`/`endOp`/`registerIdentity`/`onApplied`/`watchStall`, `RuntimeImpl.situation`, `normalizeError` | +| `packages/runtime/src/util.ts` (parts) | formatters and redaction used in every sentence | `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `defaultRedact`, `isSensitiveName`, `words`, `REDACTED`, `Redactor`, `kindOf`, `normalizeFieldPath`, `requestSignature`, `normalizePath`, `isIdSegment` | +| `packages/runtime/src/state/fields.ts` (parts) | change sentences used in facts and timeline write summaries (owned by [state-and-adapters](state-and-adapters.md)) | `changeText` (re-exported by `state/hub.ts`), `elementDiff`, `addedElements`, `normalizeLeafKind` | +| `packages/runtime/src/index.ts` | public re-exports from this area | `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` | + +Public types used here live in `packages/runtime/src/types.ts`: `TriggerKind`, `Fact`, `FactKind`, `Situation`, +`SituationDraft`, `SubjectRef`, `JevState`, `Question`, `Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier`. + +## Concepts and data structures + +| term | meaning (code name) | +|---|---| +| op signature | `requestSignature(method, where)` in `util.ts`: upper-cased method + path with id-like segments replaced by `:id` (`normalizePath`, `isIdSegment`). It is `op.name` for fetch/XHR ops and the key of `Baselines`; `Profiles` key fetch/XHR/task/ws ops by `op.name` and user ops by `user <op.name>`. | +| request identity | `ReqMeta.identity`: hash of method + URL + semantic headers + body (computed by the fetch/XHR observers). Identities starting `uniq:` never match anything. | +| outcome | string recorded per completion in `SigStats.outcomes`: HTTP code (`"200"`, `"503"`), `"timeout"`, `"network"`, or an op status; failures are stored with a `!` prefix (`"!503"`). `"aborted"` is never recorded. Facts print the label without `!` (`outcomeLabel`), and `network` as `network error` (`outcomesText` in `facts.ts`). | +| failure (for baselines) | a completion whose `EndOpts.failure` is true: network error, timeout, HTTP 5xx, 429 or 408 (`FAILURE_STATUS` in `observe/fetch.ts`; same set in `observe/xhr.ts`). A 404 is *not* a failure. | +| chain | an op and its causal descendants (shared `root`). "Same chain" in facts = one op is an ancestor-or-self of the other (`sameChain` in `facts.ts`). | +| chain write | `ChainWrite { kind, len0, len1 }` accumulated in `OpRec.chain` (keyed by **normalised** field path) for profiled ops; `ChainWriteInfo { path, count, lastIsChain, before? }` from `SitEnv.chainWrites(op)` (real paths) for facts and rollback applicability. | +| shape | `Shape { set, fields, kinds, status, writes, dur }`: one completion's transition, built by `shapeOf`. | +| unusual | `Unusual { component: "set" or "kind" or "status" or "writes", field?, seen, of, usual, usualCount, observed }` from `Profiles.check`. | +| subject | what a situation is about: `SubjectSpec` (internal, rich) and `SubjectRef` (public, ids only; `EvaluateRequest.subject`, `Decision.subjectRef`; never serialised into `state`). | +| fact | `Fact { text: string; kind: FactKind; neutral: boolean }`. `neutral: false` = makes the situation salient. | +| salient | `BuiltSituation.salient` / `Situation.salient`: `triage === "always"` or trigger `ask` or some fact non-neutral. | +| forced | `BuiltSituation.forced`: a standing question with `always: true` is registered for this trigger; consults even when not salient. | +| draft | `SituationDraft`: structured view handed to plugin `facts()` and `ActionDef.applicable()`. | +| parts | `SituationParts { app, trigger, facts[], in_flight[], timeline[], state[], stats[] }`: unbudgeted section lines. | +| state (Jev) | `JevState` = `Record<string, unknown>` produced by `toJevState(parts, budget)`; what the model reads (the model host packs it; see [model-io-contract](../model-io-contract.md)). | +| budget | situation size in characters as measured by `stateChars` (sum over keys of `key.length + 2 + text.length + 1`, arrays joined by `"\n"`). | +| compact questions | `Situation.compact` (budget <= 1400): option descriptions are `null` (bare labels), except vocabulary overrides of <= 24 chars. | +| settled point | `RuntimeImpl.settled()`: no op started < 10 s ago is in flight and no write is pending, `settleMs` (default 60 ms) after the last write/op end. Profiles and invariants learn here. | +| storeWriters | `Map<signature, Map<store, count>>` learned in `RuntimeImpl.onApplied`: how often each signature's chain (writer + up to 8 ancestors) wrote each store. Used by facts, timeline relevance, `involvedStores`. | + +### Key types (abridged) + +```ts +// packages/runtime/src/situation/env.ts +type SubjectSpec = + | { trigger: "mutation"; m: MutationRec } + | { trigger: "request"; op: OpRec; req: ReqMeta } + | { trigger: "failure"; op: OpRec; req: ReqMeta; failure: FailureInfo } + | { trigger: "stall"; op: OpRec; req: ReqMeta } + | { trigger: "inconsistency"; violations: Violation[] } + | { trigger: "transition"; op: OpRec; unusual: Unusual[]; shape: Shape } + | { trigger: "error"; error: ErrorInfo; op: OpRec | null } + | { trigger: "ask"; about: "now" | number | string }; + +// packages/runtime/src/types.ts +type FactKind = "provenance" | "versions" | "inputs" | "concurrency" | "repetition" | "outcome" | "baseline" + | "invariant" | "transition" | "error" | "delta" | "cache" | "request" | "plugin"; +interface Situation { trigger; subject: string; state: JevState; questions: Record<string, Question>; + actions: string[]; salient: boolean; facts: string[]; compact: boolean; budget: number } +``` + +`BuiltSituation` (`build.ts`) = `{ spec, draft, situation, actions: ActionOption[], facts: Fact[], parts, salient, +standing, forced, subjectRef }`. `ActionOption = { name, tier, description, custom? }`. + +```ts +// packages/runtime/src/learn/baselines.ts +interface SigStats { sig; count; failures; lat: number[]; starts: number[]; errEwma; failStreak; + outcomes: string[]; lastSuccess?; lastFailure?; firstStart } // firstStart is set but never read +interface LatencyBaseline { n; median; p95 } +interface RateBaseline { recent: number; usual?: number } // usual = starts per 10 s +interface IdentityStats { last; n; gapEwma? } + +// packages/runtime/src/learn/profiles.ts +interface Profile { sig; n; sets: Record<setKey, count>; kinds: Record<field, Record<kind, count>>; + wrote: Record<field, count>; status: Record<cls, count>; writes: Record<bucket, count>; dur: Record<bucket, count> } +interface Shape { set: string /* sorted fields joined "," ; "" = nothing */; fields: string[]; + kinds: Record<string, string>; status: string; writes: string; dur: string } +// packages/runtime/src/trace/ops.ts (accumulated on OpRec.chain) +interface ChainWrite { kind: string; len0: number /* -1 if not array */; len1: number } + +// packages/runtime/src/situation/env.ts +interface ReqMeta { method; url; signature; identity; idempotent; replayable; bodyBytes?; transport: "fetch" | "xhr" } +interface FailureInfo { kind: "network" | "timeout" | "http"; status?; statusText?; message?; durMs } +interface Violation { id; text; fields: string[]; values: string; held: number; developer? } +interface ErrorInfo { name; message; source?; raw: unknown; key } // built by runtime.ts -> normalizeError +interface CachedInfo { t; status } + +// packages/runtime/src/situation/build.ts +interface BuildOptions { vocab?; diagnoses: Record<string, string>; customActions: ActionDef[]; + questions: StandingQuestion[]; pluginFacts: { name; fn: (d: SituationDraft) => string[] }[]; + triage: "salient" | "always"; budget?: number /* default 3200 */ } + +// packages/runtime/src/situation/serialize.ts +interface SectionLimits { facts; in_flight; timeline; state; stats; + line: { app; trigger; facts; in_flight; timeline; state; stats } } +``` + +`SituationDraft` (`types.ts`): `{ trigger, subject, now, op?, root?, stores, mutation?: { id, store, changes }, +request?: { method, url, signature, identity, idempotent, replayable, identicalInFlight: number[], cached }, +failure?: { kind, status?, message? }, error?: { name, message, source? }, invariants?: { id, text }[], facts: Fact[], +inFlight: Op[] }`. `SubjectRef` (`types.ts`): `{ kind, op?, mutation?, store?, paths?, cause?, error?, invariant? }`. +`ErrorInfo.key` = `normalizeError` key: `<name>:<message with every digit run -> "n", first 120 chars>`. + +### SitEnv (read-only view of the runtime) + +`SitEnv` is implemented by `RuntimeImpl.makeEnv`. Members: `now()`, `ops` (`OpRegistry`), `hub` (`StoreHub`), +`base` (`Baselines`), `profiles`, `events` (`EventLog`), `redact` (`Redactor`), `app()` (`RuntimeImpl.appInfo`: +`CreateOptions.app()` when given, else `global.document.title` and `global.location.pathname`), `cached(identity)` +(GET cache peek, `ResponseCache.peek`), `identical(identity)` (ops with that identity started in the last 10 s or +still in flight; `registerIdentity` keeps at most 12 ops per identity and 512 identities, FIFO), +`lastConsistent()`, `consistentBefore(seq)` (from the last 8 consistent snapshots), `storeWriters`, +`recentErrors()` (last 10 s; at most 64 kept), `violations()` (current learned violations), `previewInvariants?(m)` +(invariants the pending write would break), `canCoalesce(identity, selfId)` (`ResponseCache.shareable`), +`resyncable(store)`, `writable(store)`, `chainWrites(op)` (`RuntimeImpl.chainWrites`: fields written by the op's +root chain since the root started). `writtenByChain?(a, h)` is declared in `env.ts` but not implemented by +`makeEnv` and not called anywhere. + +### Triggers and subjects + +| trigger | raised by (file -> symbol) | hold | priority | subject sentence (`subjectOf`) | `SubjectRef` | +|---|---|---|---|---|---| +| `mutation` | `runtime.ts` -> `gateMutation` (a non-bypassed write, see [state-and-adapters](state-and-adapters.md)) | yes | 2 | `A write to <paths>[ from <opLabel(cause)>] is about to be applied.` (> 3 paths: first 3 + `and N more`; no paths: store name; ` from …` only when there is a cause op) | `{kind, mutation, store, paths, cause?}` | +| `request` | `observe/fetch.ts`, `observe/xhr.ts` request gate | yes | 2 | `<opLabel(op)> is about to be sent.` | `{kind, op}` | +| `failure` | fetch `failureGate` (hold yes, priority 2); XHR (hold no, priority 1) | fetch yes | 2 / 1 | `<opLabel> failed (<HTTP <status>, timed out, or network error>) and the app has not seen the failure yet.` | `{kind, op}` | +| `stall` | `runtime.ts` -> `watchStall` timer at `max(4 x median, 2 x p95, 500 ms)`, only with a latency baseline | no | 1 | `<opLabel> has been waiting <secs> for a response.` | `{kind, op}` | +| `inconsistency` | `runtime.ts` -> `settled` -> `raiseInconsistency` (fresh violations) | no | 1 | `The relation <text>[ (and N more)] no longer holds now that the app is settled.` | `{kind, paths, store?, invariant?}` | +| `transition` | `runtime.ts` -> `settled` -> `raiseTransition` | no | 0 | `<opLabel> completed with a state change unlike its usual ones.` | `{kind, op, paths, store?}` (paths are normalised chain keys) | +| `error` | `runtime.ts` -> `reportError` (also from the errors observer) | no | 0 | `An uncaught <name> was thrown: <message <= 120>` | `{kind, error (raw), op?}` | +| `ask` | `runtime.ts` -> `ask()` / `decide()` / `situation()` (not through `trigger()`) | n/a | 1 | `The developer asks about <opLabel(op)>` / `the store <name>` / `the app right now.` | `{kind, op?, store?}` | + +The short `Situation.subject` string (`subjectOf(...).subject`; copied to `Decision.subject` and used by reports and +devtools; not part of `state`, except indirectly through the failed-action timeline text `Tried to <action> +<subject> but it failed; the passive action ran instead.` written by `RuntimeImpl`) is: mutation `write to <paths>[ from <opLabel>]` (e.g. +`write to search.results from GET /api/search?q=rea (#6)`); request `<opLabel>`; failure `<opLabel> (HTTP 503 | +timed out | network error)`; stall `<opLabel>, waiting <secs>`; inconsistency `relation <text>[ (and N more)]`; +transition `<opLabel> state change`; error `<name>: <message <= 80>`; ask `question about <opLabel>` / +`question about <store>` / `question about the app`. With no violation the inconsistency text uses `?`; an unknown +asked op prints `an earlier operation`. + +Stall details: the fetch observer (primary request only) and the XHR observer (async only) call +`host.watchStall` at send time when `host.gated(op)`; with no latency baseline yet (< 5 samples) no timer is armed, +so the first requests of a signature can never stall. The timer fires at most once per op (`op.triggered` gets +`"stall"`), and not if the op already ended. Transitions are likewise marked once per op (`op.triggered` gets +`"transition"`). + +The *subject op* (`subjectOp` in `build.ts`) is the +cause op for `mutation`, the request op for request/failure/stall/transition, the ambient op for `error`, the asked op +for `ask`, none for `inconsistency`. *Involved stores* (`involvedStores`): mutation -> its store; inconsistency -> +stores of violated fields; transition -> stores of chain keys; error -> stores changed since the op started; +request/failure/stall -> stores that this signature's chains wrote (`storeWriters`); ask -> the asked store. Only +registered stores are kept. + +## How it works + +### 1. Baselines (fed by op start/end) + +1. `RuntimeImpl.startOp`: for `fetch`/`xhr` ops not owned by GenClass -> `Baselines.start(name, t)` (push start time, + window 128). If the op has an identity -> `registerIdentity` -> `Baselines.noteIdentity(identity, op.start)` + (skipped for `uniq:` identities): first sighting stores `{last, n: 1}`; later sightings update + `gapEwma = gap` (first) then `0.8 * gapEwma + 0.2 * gap`. At most 1024 identities (FIFO eviction). +2. `RuntimeImpl.endOp`: for `fetch`/`xhr`, not synthetic (blocked/cached/coalesced answers), not GenClass -> + `Baselines.end(sig, t, latency, ok, outcome, countsAsFailure)` with `outcome = "aborted"` or `String(code)` or the + status, `ok = status "ok" and (code not a number or < 400)`, `countsAsFailure = !!EndOpts.failure`. +3. `Baselines.end`: returns early for `"aborted"` (the signature entry is still created). Otherwise `count++`, push + outcome (`"!"` prefix when failure; keep last 20). Failure: `failures++`, `failStreak++`, `lastFailure = t`, + `errEwma = errEwma * 0.9 + 0.1`. Non-failure: `failStreak = 0`, `lastSuccess = t` only if `ok`, + `errEwma *= 0.9`, push latency (keep last 64). Latency samples therefore never include failures/timeouts. +4. Reads: `latency(sig)` -> `undefined` below 5 samples, else `{ n, median, p95 }` by nearest rank on the sorted + window (`a[min(n-1, max(0, ceil(p*n) - 1))]`). `rate(sig, now)` -> `recent` = starts with `t > now - 10000`; + `usual = older / span * 10000` only when `older >= 3` and `span = (now - 10000) - oldestOlder >= 20000`. + `failureCounts(sig)` -> `{ failed, of }` over the last <= 20 outcomes (this is what facts and stats print). + `errEwma` is returned only by `snapshot()` (as `errorRate`); no code in `src/` (devtools included) calls + `snapshot()`, so the EWMA is currently unused (reachable only through `rt.internals.base`). +5. Signatures are capped at 1000 (FIFO by insertion, not LRU). Baselines are in memory only (never persisted). + +### 2. Transition profiles (fed by writes, checked at settled points) + +1. `RuntimeImpl.onApplied` (every applied write with a writer op): for the writer and up to 8 ancestors whose kind is + in `PROFILED` (`fetch`, `xhr`, `user`, `task`, `ws`; not `timer`, not GenClass) and not yet profiled: + `op.chainWrites += 1` per applied mutation, and for each changed path `op.chain.set(normalizeFieldPath(path), + { kind: normalizeLeafKind(c.afterLeaf), len0: first-seen before length (-1 if not an array), len1: latest after + length })` (`normalizeLeafKind` in `state/fields.ts` returns the leaf kind, or `"undefined"` for a removed field). It also bumps + `storeWriters[sig][store]` once per signature per write (cap 1000 signatures). +2. Ops are queued for profiling (`queueProfile`, cap 2000) on `endOp` (not aborted, not synthetic) or at creation for + instant ops. +3. `RuntimeImpl.settled()` (only when not busy): for each queued ended op not yet profiled: + `shape = shapeOf(op.chain, op.chainWrites ?? 0, statusClass(op), op.end - op.start)`; + `sig = op.kind === "user" ? "user " + op.name : op.name`; `unusual = profiles.check(sig, shape)` **then** + `profiles.add(sig, shape)` (the current completion is not part of "previous N"). Flag it if `unusual.length` and + no transition was raised for this op before. +4. "One anomaly, one trigger": a flagged op is skipped when another flagged op is its descendant (the most specific + op wins; tested in `situation.test.ts` transition case). Each survivor -> `raiseTransition` -> `trigger(...)` with + `hold: false`, priority 0. +5. `statusClass(op)`: numeric code -> `"<n>xx"` (`"2xx"`, `"5xx"`); `"timeout"`/`"network"`; else `op.status ?? "ok"`. +6. `Profiles.check(sig, s)` (returns `[]` while `p.n < 20`). `rare(seen, of) = of >= 20 && seen < 0.01 * of` + (up to and including 100 completions that means "never seen"): + - `set`: the sorted written-field set is rare **and** the most common set is not `""` (an op that usually writes + nothing may start writing: not flagged). + - `kind`: for each written field with `wrote[f] >= 20`, the observed kind is rare among that field's kinds. + - `status`: the status class is rare. + - `writes`: the write-count bucket is rare, the most common bucket is not `"0"`, and no `set` anomaly was found. + - `dur` is counted but never checked. + `usual`/`usualCount` come from `top()` (highest count; ties: lexicographically first key). +7. `Profiles.add`: increments counts; caps write sets at 64 and fields at 128 (drop least frequent, ties: oldest); + at most 2000 signatures (FIFO). Persisted to `localStorage["genclass.profiles.v1"]` only with + `learn: { persist: true }` (`saveProfilesSoon` saves 5000 ms after a settled point whose profile queue was + non-empty, with at most one save pending; loaded in the constructor; `Profiles.load` only checks `sig` and `n`). +8. `kindLabel`: arrays -> `"empty array"` / `"non-empty array"` (length change deliberately ignored), objects -> + `"object"`, else the leaf kind (`"string"`, `"number"`, `"boolean"`, `"null"`, `"undefined"`, `"map"`, `"set"`, + `"date"`, ...). `normalizeFieldPath`: every segment after the store name that is id-like or contains a digit + becomes `:id` (`chat.byId.m21` -> `chat.byId.:id`). + +### 3. Trigger -> triage -> situation (`RuntimeImpl.trigger`) + +1. Not consultable (paused, destroyed, no `DecisionProvider`, or provider state not `ready`/`off`) -> run passive, + build nothing. +2. Cheap pass: `facts = computeFacts(env, spec)`; `forced = standing.some(q => q.always && q.on.includes(trigger))`. + If `triage === "salient"` and not forced and **every fact is neutral** -> passive (no model call, no `Decision`, + `lastBuilt` untouched). +3. `buildSituation(env, spec, buildOpts(), facts)` (reuses the facts, adds plugin facts, builds sections). Any throw in + steps 2-3 -> logged (debug) and passive (fail open). +4. `lastBuilt[trigger] = built` (what `rt.situation(trigger)` returns later). If `!built.salient && !built.forced` -> + passive. +5. Provider not `ready` (lazy model) -> start loading (`this.ready`), run passive. +6. Otherwise submit `{ trigger, state, questions, priority, subject }` to the decider queue; hold/deadline/gate + handling is in [decide-policy-actions](decide-policy-actions.md). + +`ask` bypasses `trigger()`: `rt.ask(q, {about})` builds an `ask` situation and **replaces** its questions with +`{ answer: q }`. `rt.situation(trigger?)` returns `lastBuilt[trigger].situation` when one exists, else builds +`{ trigger: "ask", about: "now" }` and relabels it with the requested trigger. + +### 4. `buildSituation(env, spec, o, precomputed?)` step by step + +1. `budget = o.budget ?? STATE_CHAR_BUDGET`; `L = sectionLimits(budget)`; `subjectOf`, `subjectOp`, `involvedStores`. +2. Facts: `precomputed` or `computeFacts`. Draft: `{ trigger, subject, now, stores, facts, inFlight (non-user), + op?, root?, mutation?, request? (with identicalInFlight, cached), failure?, error?, invariants? }`. +3. Plugin facts: for each plugin with `facts(draft)`, every non-empty string -> `{ text: truncate(t.trim(), 240), + kind: "plugin", neutral: true }`; a throwing plugin is ignored. +4. `facts = orderFacts(facts).slice(0, 12)` (kept in `Situation.facts`, reports and `explain()`; the budget decides + how many reach the model). +5. Actions: `TRIGGER_ACTIONS[trigger]` filtered by `builtinApplicable` (table below), descriptions from + `actionDescription`; then custom `ActionDef`s whose `on` includes the trigger, whose name is new, and whose + `applicable(draft)` is true (throw = not applicable); tier default `"heal"`. +6. Questions: standing questions for this trigger -> `extra`; `compact = budget <= 1400`; + `buildQuestions(trigger, actions, o.diagnoses, extra, compact, o.vocab)`. +7. Sections (`parts`): `app` = `appText` (`"<title> — <route>"`, either alone, or `"unknown"`), `trigger` = subject + sentence, `facts` = texts, `in_flight` = `inFlightLines`, `timeline` = `timelineLines`, `state` = `stateLines`, + `stats` = `statsLines`. +8. `state = toJevState(parts, budget)`; `salient = o.triage === "always" || trigger === "ask" || facts.some(f => + !f.neutral)`. + +#### Applicable built-in actions (`builtinApplicable`) + +| trigger | always | conditional | +|---|---|---| +| mutation | `apply`, `discard` | `defer` iff `m.defers < 2` | +| request | `send`, `delay`, `block` | `coalesce` iff transport fetch and `canCoalesce(identity, op.id)`; `serve_cached` iff GET and a cached response exists | +| failure | `deliver` | `retry` iff replayable, `attempt < 4`, fetch; `serve_cached` iff GET, cached, fetch | +| stall | `wait` | `hedge` iff idempotent, GET, replayable, fetch; `serve_cached` iff GET, cached, fetch | +| inconsistency | `ignore` | `rollback` iff `lastConsistent()` exists and some involved store is writable; `resync` iff some involved store has a resync handler | +| transition | `ignore` | `rollback` iff `revertableChain(op)`; `resync` iff a chain store is resyncable | +| error | `ignore` | `rollback` iff an ambient op exists and `revertableChain(op)` | +| ask | (none) | | + +`revertableChain(op)` = some `chainWrites(op)` entry has `lastIsChain`, a known `before`, and a writable store. + +#### Section builders (`build.ts`) + +- **`inFlightLines`**: in-flight ops except user ops and the subject op; sorted by (same signature as subject = 0, + same root = 1, else 2), then start time; first `L.in_flight`. Line: `<opPhrase <= 80> (#id) <secs> so far[, by #cause]`. +- **`timelineLines`**: the last 96 events (`env.events.last(96)`), each rendered by `eventLine` (null lines dropped). + Relevant = `user`, `error`, `action`, `nav` events always; `state` events of involved stores; op events of the + subject or its ancestors, of the same signature, of the same root or a descendant of the subject, or of a + signature that wrote an involved store. Keep the last `L.timeline` relevant lines; if fewer, fill with the most + recent non-relevant lines; output in event order. +- **`stateLines`**: first the involved fields (mutation change paths, violated fields, transition chain keys), then + the fields of all involved stores pooled together, most recent write first; stops at `L.state`; paths with no current leaf are + skipped. Line: `<path> = <describe(value, path, redact, 90)> (v<v>[, by #writer] <secs> ago)` or `(v0)` when never + written. A store registered with `opts.describe` contributes one line `<store> = <describe() <= 110> (v<version>)` + instead of its fields. `ask` about `now` with nothing involved -> all fields of all stores by recency. +- **`statsLines`**: signatures = the subject op's (if fetch/xhr/ws/task) + every in-flight fetch/xhr; first + `L.stats` that have `count > 0`. Line: `<sig>: <count> done[, median <secs>, p95 <secs>], <failed> of last <of> + failed, <recent> in last 10s[ (usual <fmtNum>)]`. (Baselines only exist for fetch/xhr, so ws/task subjects + produce no line.) + +### 5. `describe.ts` phrasing (also used for action effect texts) + +`opLabel` is also imported by `runtime.ts`, `observe/fetch.ts` and `observe/xhr.ts` to write `ActionEffect.changed` +sentences (`Dropped the write to …`, `Retried … as attempt …`), which come back to the model as timeline `action` +lines. `decide/report.ts` and the devtools do not import `describe.ts`. + +- `userPhrase(op)` from `op.meta.action` and `op.detail` (already redacted/quoted by `rt.user`): `user clicked + <target or "the page">`, `user typed <value or "text">[ into <target>]`, `user changed <target or "a field">[ to + <value>]`, `user submitted <target or "a form">`, `user pressed <key or "a key">[ in <target>]`, `user navigated + to <target or value or "a page">` (kinds `nav` and `navigate`), else `user <kind or "action">[ <target>][ <value>]`. +- `opPhrase(op)`: user -> `userPhrase`; fetch/xhr -> `<signature><detail>` (detail is the observer's redacted query + or body summary, e.g. `?q=re`, ` {items: [1], cardNumber: [redacted]}`); timer, ws -> name; task -> `task <name>[ + <detail>]`; genclass -> `GenClass <name>`. +- `opLabel(op)` -> `<opPhrase truncated to 90> (#id)`, or `an earlier operation` when unknown. +- `statusText(op)` -> `aborted`, `blocked`, numeric code, `timed out`, `network error`, `error[ (<errorText <= 40>)]`, + else status or `pending`. +- `eventLine(e, now, op)` prefixes `rel(e.t - now)` (`-1.24s`; `-0.00s` for now): + +| event kind | line | +|---|---| +| `user` | `<t> <userPhrase> (#id)` or `(<n> keystrokes, #first–#last)` for a merged typing burst | +| `op.start` | `<t> start <opPhrase <= 80> (#id[, by #cause][, attempt n])` (user ops: none) | +| `op.end` | `<t> end <opPhrase <= 80> (#id): <statusText>[ in <secs>]` | +| `state` | `<t> write <summary <= 110>[ (by #op[, user])]` (summary = first 3 `path: changeText`, joined `; `) | +| `error` | `<t> error <message <= 100>[ (during #op)]` | +| `nav` | `<t> navigate <route <= 60>` | +| `storage` | `<t> <name>[ <key <= 40>]` | +| `perf` | `<t> <name>[ <ms>ms]` | +| `custom` | `<t> event <name <= 60>[ <summary <= 60>][ (#op)]` | +| `action` | `<t> GenClass <text <= 100>` (past GenClass actions are visible to the model: `ActionEffect.changed`, or `undid <action> (<id>)` for an undo) | +| `decision` | never shown | + +When the op is no longer in the registry: `user` prints the event name instead of the phrase, `op.start` is dropped, +`op.end` prints `<t> end <name>`. `rel` prints `+` for future times (not expected in practice). + +`changeText(c, redact)` (`state/fields.ts`; used by M15, I2 and the hub's timeline `write` summaries): same-length +arrays -> `N items, unchanged` / `N items, reordered` / `N items, K changed: {id: 3, qty: 1 → 2}[, and K-1 more]` (at +most half the items changed; `elementDiff` lists the id key and up to 3 changed keys, `+N more changed`), else the +full `before → after` when <= 90 chars, else `N items, K changed`; other arrays -> full `before → after` when <= 70 chars, else `B → A items: added +<first>[ and N more]; removed N item(s)`; objects compared by key hash -> `B → A entries: added k: v; changed k: +…; removed k1, k2[ and N more]`; anything else -> `<describe 36> → <describe 36>`. + +Formatters (`util.ts`): `secs` = 2 decimals below 10 s (`0.42s`), 1 decimal below 1000 s, else integer; +`fmtNum` = integers as is, else 1 decimal (>= 100), 2 (>= 1), 4 (< 1), trailing zeros dropped; `ratio(a, b)` = +`∞` if `b <= 0`, `<round>×` if >= 10, else `<1 decimal>×`; `times(n)` (facts.ts) = `once`, `twice`, `N times`; +`truncate(s, n)` cuts to `n - 1` chars + `…`. `plural(n, one)` = `<n> <one>` or `<n> <one>s`; `ordinal(n)` = +`1st`, `2nd`, `3rd`, `11th`. `describe(v, path, redact, max)`: strings quoted (48 chars, 24 +nested), arrays `N items [a, b, c, …]` (at most 3 elements, stopping before `max - 16` chars; nested `[N]`, empty +`0 items`), objects `{id: …, name: …, k: v, +N}` with +id-like keys first (`id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`), depth > 1 `{N keys}`, empty +`{}`, `Map(n)`, `Set(n)`, dates ISO (`Invalid Date`), bigint `<n>n`, `function`, `symbol`; the whole result is +truncated to `max`. + +### 6. Facts catalogue (`facts.ts` -> `computeFacts`) + +**Salient** = `neutral: false`. `C` = the write's cause op, `#C` its id; `<times>` = once/twice/N times; "other +chain" = writer not ancestor-or-self of `C` and vice versa. `<writer>` = `<opLabel(w)>, which started <secs> +after #C` (or `before #C`, or `started at the same time as #C`) + optional `, from the same user action (#u)`, +`, from a later user action (#u)`, `, from an earlier user action (#u)`; or `a user action` / `an operation that is no +longer tracked`. Provenance (shared helper `provenance`): `<What> comes from <opLabel(op)>, started <secs> ago[, +ended <secs> ago with <status>][; its chain began with <opLabel(root)>].` or `<What> has no known cause: no +operation was active when it started.` + +**mutation** (`mutationFacts`) + +| id | kind | salient when | condition and text | +|---|---|---|---| +| M1 | provenance | never | always: provenance of `This write` | +| M2 | versions | always | `C` set, for each of the first 3 written paths written by another chain since `C` started: `<path> was written <times> by other operations since this write's cause (#C) started (version <vStart> → <vNow>), last <secs> ago by <writer>.` (counts from the 512-entry field log) | +| M3 | versions | never | only `C`'s own chain wrote it: `<path> was written <times> by this write's own chain since this write's cause (#C) started (version a → b).` | +| M4 | versions | never | untouched: `<path> has not changed since this write's cause (#C) started (version <v>).` Side effect for every one of the first 3 paths (M2, M3 or M4): `C.reads.set(path, vStart)` with `vStart = hub.versionAt(path, C.startSeq)` | +| M5 | inputs | field is in the **same store** as the write | up to 2 other existing fields changed by other chains since `C` started (order: same store, user-written, most recent): `<path> changed <times> since … started (now <v>)` (first write no longer in the 16-entry history), or `… changed since … started: <before> → <now>[ (<n> writes)]`, or `… changed <times> since … started and is back to <v>` (values described at 40 chars), then `, last by <opLabel(w)> <secs> after #C started.` (or `, last by an untracked writer.`) | +| M6 | concurrency | at least one listed op started **after** `C` | in-flight ops outside `C`'s chain with `C`'s name and kind: `<N> other <C.name> operation(s) is/are in flight (<k> newer than this write's cause (#C)): #id <detail> started …; …` (up to 3 listed) | +| M7 | concurrency | never | other in-flight ops whose signature's chains wrote this store: `<opLabel> is in flight and its chain wrote <store> <times> before[ (<n> more such ops in flight)].` | +| M8 | baseline | `lat > 3 × median` **and** `lat − median >= 100 ms` | `C` is an ended fetch/xhr with a latency baseline: `This write's cause (#C) took <secs>, <ratio> its usual <median> (p95 <p95>).` | +| M9 | outcome | never | `C` fetch/xhr ended with status error: `This write's cause (#C) failed (<status>) before this write.` | +| M10 | versions | always | for each of the first 3 written paths: a write in the last 10 s from another chain rooted in a user op whose non-user op is still in flight: `<path> has a pending local change: <opLabel(user)> wrote it <secs> ago and its <opLabel(pending)> is still in flight; this write comes from <opLabel(C)>, which started after (or before) that user action.` (or `has no known cause`) | +| M11 | outcome | never | `m.unholdable`: `This write could not be held: <reason>.` (appears unreachable, see Drift) | +| M12 | repetition | some change is **additive** (numeric delta `n:` or array add/remove `a:`) | same change key (sorted paths + deltas) applied in the last 10 s (`hub.recent`): `An identical change to <paths> (<delta>) was applied [<n> times in the last 10s, last ]<secs> ago by <opLabel(w)>[; both come from the same user action (#u)][; they come from separate user actions <secs> apart].` `<delta>` = `+N`/`-N`, `added N item(s) <first>`, `removed N item(s)`, or `set to <value>` (first change only) | +| M13 | concurrency | never | earlier queued writes on the store: `<N> earlier write(s) to <store> is/are still waiting for a decision.` | +| M14 | invariant | never | up to 2 learned relations the write would break (`previewInvariants`): `Applying this write would break the learned relation <text> (<values>); it held at <n> settled points.` | +| M15 | delta | never | first 3 changes: `This write would change <path>: <changeText>.` | +| M16 | outcome | never | `m.defers > 0`: `This write was already deferred <times>.` | + +**request / failure / stall common part** (`requestCommon`; `<self>` = `This request (#id)` for request, `The +request (#id)` otherwise) + +| id | kind | salient when | condition and text | +|---|---|---|---| +| R1 | provenance | never | provenance of `This request` (cause op) | +| R2 | outcome | never | `attempt > 1`: `<self> is attempt <n>: it was already retried <times>.` | +| R3 | repetition | **request only**: `close` | identical-identity ops (not this one, started <= 10 s ago, `attempt === 1`): `<N> identical <sig> request(s) in the last 10s: <items>` (or `(latest 3: <items>)` when N > 3; items, last 3 only, joined `; `: `#id in flight (started <secs> ago)` or `#id answered <statusText> <secs> ago` (status ok) / `#id ended <statusText> <secs> ago`) `; #<last> started <secs> after (or before) this one` + `, from the same user action (#u)` / `; they come from separate user actions <secs> apart` / `, neither from a user action` (nothing when only one side has a user action). `close` = one of them is in flight, or the start gap to the latest `< min(2000, 0.5 × gapEwma)` (gapEwma used only when the identity was seen more than 3 times; else `< 2000` ms) | +| R4 | concurrency | never | same signature, different identity, in flight: `<N> other <sig> request(s) with different input is/are in flight: #id <detail> (started …); …` | +| R5 | outcome | **request only**: `failStreak >= 2` | not on failure; `failStreak > 0`: `The last <N> <sig> request(s) failed in a row (<last 5 outcomes>); last success <secs> ago` (or `no success yet`) | +| R6 | outcome | never | stall with `failStreak 0` and `count > 0`: `Recent <sig> outcomes: <last 5>.` | +| R7 | baseline | `recent >= 5` **and** `recent >= 3 × usual` (any of the three triggers) | usual rate known, `recent >= 3`: `<sig> was requested <times> in the last 10s; usually <usual> per 10s (<ratio>).` | +| R8 | baseline | never | no usual rate yet, `recent >= 3`: `… (no usual rate learned yet).` | +| R9 | baseline | never | not stall, latency baseline exists: `<sig> usually answers in <median> (p95 <p95>, <n> samples); error rate <x>% over <of> request(s) (<failed> failed).` (`x = round(failed / of × 100)` over the last <= 20 outcomes; `no completed requests yet` when there are none) | +| R10 | cache | never | GET with a cached response: `A cached <status> response from <secs> ago exists for this request.` | +| R11 | request | never | always: `<METHOD> is idempotent` or `is not idempotent`, then `; its body (<n> bytes) can be replayed.` or `; its body cannot be replayed.` (no body clause for GET/HEAD) | + +**request** = R1-R11. **failure** = F1-F3 then R1-R11: + +| id | kind | salient when | text | +|---|---|---|---| +| F1 | outcome | always | `The request #id failed: <HTTP <status>[ <statusText>] or timed out or network error[ (<msg <= 50>)]> after <secs>; the app has not seen the failure yet.` | +| F2 | outcome | never | only when the signature has baseline stats: `This is the <ordinal> <sig> failure in a row (recent outcomes: <last 5>; <last success <secs> ago or no success yet>); error rate <x>% over <of> request(s) (<failed> failed).` with `ordinal(max(1, failStreak))`. The failing op was already ended and recorded by `Baselines.end` before the trigger, so the streak, outcomes and counts include it (example C: 3rd, three 503s) | +| F3 | outcome | never | chain already wrote state (`chainWrites(op)` non-empty): `Before this failure its chain wrote <up to 4 paths>.` | + +**stall** = S1, S2 then R1-R11 (R9 omitted): + +| id | kind | salient when | text | +|---|---|---|---| +| S1 | baseline | always | `The request #id has been in flight for <secs>; <sig> usually takes <median> (p95 <p95>, <n> samples), <ratio> the median.` (without baseline: `… has been in flight for <secs>.`) | +| S2 | concurrency | never | other same-name in-flight requests past `3 × median`: `<N> other <sig> request(s) is/are also running past 3× the usual latency.` | + +**inconsistency** (`inconsistencyFacts`), per violation (first 3): I1 (invariant, **always salient**) `The developer +invariant "<text>" no longer holds.` or `The learned relation <text> no longer holds: <values>. It held at <n> settled +points before.`; then I2 (versions, never) for the 2 latest writes to its fields since the last consistent snapshot: +`<path> was written <secs> ago by <opLabel(w)>[ (user)]: <changeText>.` After the loop: I3 (invariant, never) +`The last consistent state is <secs> old; <n> field write(s) happened since.` or `No consistent snapshot has been +recorded yet.`; I4 (concurrency, never) `<n> operation(s) is/are in flight.` or `No operations are in flight (the app +is settled).` + +**transition** (`transitionFacts`): T1 (transition, **always salient**), first 3 `Unusual` (`<sig>` = `op.name`, or +`opPhrase` for user ops): +- set: `In the previous <of> completions of <sig> its chain wrote <usual fields> (<usualCount> of <of> times); this + time it wrote [only ]<observed fields>[ (seen <times> before)].` (`only` when observed is a strict subset; + `nothing` for an empty set; fields joined `a, b and c`) +- kind: `In the previous <of> completions of <sig> that wrote <field>, it wrote a/an <usual> (<usualCount> of <of> + times); this time it wrote a/an <observed>.` +- status: `… it ended with <usual> (<usualCount> of <of> times); this time it ended with <observed>.` +- writes: `… its chain made <usual> write(s) (<usualCount> of <of> times); this time it made <observed>.` + +Then T2 (provenance, never) of `The completed operation #id` / `The completed user action #id` (cause op, or the op +itself when it has no cause); T3 (baseline, never, fetch/xhr) `It ended <secs> ago with <status> after <secs>[ +(usual <median>)].`; T4 (delta, never) for each of the first 3 chain keys (insertion order) that has a current value +or field record: `<field> is now <describe 60>.`; T5 (invariant, +never) `The last consistent state from before #<root> started is …` / `No consistent snapshot from before #<root> +started exists.` + +**error** (`errorFacts`): E1 (error, **always salient**) `Uncaught <name>: <message <= 120>[ (at <source <= 60>)].`; +with an ambient op: E2 (provenance) `It was thrown while <opLabel(op)> was active, <secs> after it started[; that +chain began with <opLabel(root)>].` and E3 (versions) `Its chain wrote <up to 4 paths> before the error[ (<k> of them +overwritten since by other operations)].` or `Its chain wrote no state before the error.`; without: E4 (provenance) +`No operation was active when it was thrown.`; E5 (repetition) `The same error happened <times> in the last 10s.` +when the error key (`normalizeError`: `<name>:<message with digits -> n, 120 chars>`) occurred more than once (the +current error is already in `recentErrors`, so "twice" means one earlier occurrence); E6 (invariant) last-consistent +fact relative to the op's root (`The last consistent state from before #<root> started is …` / `No consistent +snapshot from before #<root> started exists.`), or the plain `The last consistent state is …` / `No consistent +snapshot has been recorded yet.` when no op was active. E2-E6 never salient. + +**ask** (`askFacts`, all neutral; `ask` is salient anyway): about an op id -> `Operation #N is not known.` when +missing, else provenance of `Operation #id (<opPhrase <= 60>)`, `It has been in flight for <secs>.` or `It ended +<secs> ago with <status> after <secs>.`, `<name> usually takes <median> (p95 <p95>).`, `Its chain wrote <up to 5 +normalised keys>.`; about a store -> `Store <name> is not registered.` when missing, else up to 6 most recent fields +`<path> is at version <v>[, last written <secs> ago by <opLabel>]`; about now -> `<N> operation(s) is/are in flight; +the oldest is <opLabel> (<secs>).` or `No operations are in flight.`, `The last <N> <sig> request(s) failed in a row +(<outcomes>).` for streaks whose last failure is < 30 s old, `<N> error(s) happened in the last 10s.`, up to 2 +`The learned relation <text> does not hold: <values>.`, and `An identical change to <paths> was applied <times> in +the last 10s.` for change keys seen more than once in 10 s. + +**Ordering** (`orderFacts`): non-neutral first, then `RANK` (`invariant`, `transition`, `error` 0; `versions` 1; +`repetition` 2; `inputs` 3; `outcome` 4; `baseline` 5; `concurrency` 6; `provenance` 7; `request` 8; `cache` 9; +`delta` 10; `plugin` 11), then original position. + +### 7. Triage: exact salience conditions + +A trigger reaches the model iff the runtime is consultable, the provider is `ready` (otherwise the first salient +situation starts the lazy load and fails open), and one of: +1. `triage: "always"`; or +2. trigger is `ask`; or +3. a standing question with `always: true` lists the trigger (`forced`); or +4. at least one computed fact is non-neutral. Per trigger: + - **failure, stall, inconsistency, transition, error**: always (F1, S1, I1, T1, E1 are non-neutral). + - **mutation**: M2 (a written field was written by another chain since the cause started), M5 (a field of the + same store moved since then), M6 (a newer op with the cause's signature is in flight), M8 (the cause took + > 3× its median and >= 100 ms over it), M10 (a pending local change is being overwritten), M12 (an identical + additive change in the last 10 s). A write with no cause op can only be salient through M10 or M12. + - **request**: R3 with `close`, R5 with `failStreak >= 2`, R7 hot rate. + +Plugin facts are always neutral and are only computed after the cheap pass, so plugins can never make a trigger +salient. Because the sim runs with `triage: "salient"`, sim decision rows exist only for salient situations (its ask +probes come separately from `rt.situation("ask")`); changing triage changes the training distribution, not just +runtime cost. + +### 8. Questions (`questions.ts` -> `buildQuestions`) + +- `ask`: only standing questions registered for `ask` (and `rt.ask()` replaces them with `{ answer }`). +- `diagnosis` (always otherwise): `{ type: "choice", instructions: "What is happening here?", criteria }` over + `o.diagnoses` = `diagnosisVocabulary(vocab, pluginLabels)`: `vocab.diagnoses` replaces `DEFAULT_DIAGNOSES` + entirely, `expected` is re-added if missing and always first, plugin labels are appended if new. +- `action` (only when more than one action applies): instructions `ACTION_INSTRUCTIONS[trigger]`, one option per + applicable action in offer order (passive first), description from `actionDescription` = `vocab.actions[name]` ?? + custom description ?? built-in description ?? name. +- Compact (`budget <= COMPACT_QUESTIONS_BUDGET` = 1400): every description becomes `null` except a vocabulary + override of <= 24 chars (`COMPACT_DESC_MAX`); custom-action and plugin-label descriptions are dropped too. +- Standing questions are added under their ids unless the id is already used (`diagnosis`/`action` cannot be + overridden). + +| label (`DEFAULT_DIAGNOSES`, in order) | description | +|---|---| +| `expected` | normal behaviour, nothing is wrong | +| `stale` | outdated data or an older operation is about to replace newer state | +| `conflict` | concurrent operations are competing over the same state or resource | +| `duplicate` | the same change or request is happening again without a new intent | +| `inconsistent` | the state contradicts itself or relationships it normally keeps | +| `failing` | an operation keeps failing or its failures follow a pattern | +| `slow` | an operation is far slower than usual | +| `overload` | work is being triggered far more often than usual | +| `unusual` | this differs from how the same operation normally behaves | +| `transient` | a one-off failure that is likely to succeed if tried again | + +| trigger | `TRIGGER_ACTIONS` (passive first) | `PASSIVE` | `ACTION_INSTRUCTIONS` | +|---|---|---|---| +| mutation | apply, discard, defer | apply | What should the runtime do with this write? | +| request | send, coalesce, delay, block, serve_cached | send | What should the runtime do with this request? | +| failure | deliver, retry, serve_cached | deliver | What should the runtime do with this failed request? | +| stall | wait, hedge, serve_cached | wait | What should the runtime do with this slow request? | +| inconsistency | ignore, rollback, resync | ignore | What should the runtime do about this inconsistent state? | +| transition | ignore, rollback, resync | ignore | What should the runtime do about this unusual state change? | +| error | ignore, rollback | ignore | What should the runtime do about this error? | +| ask | (none) | `""` | `""` | + +Built-in action descriptions and tiers (`BUILTIN_ACTIONS`): apply (passive) "let this write update the state now"; +discard (guard) "drop this write and keep the current state"; defer (guard) "hold this write until the related +in-flight operations finish, then decide again"; send (passive) "send the request now"; coalesce (guard) "do not +send; reuse the result of the identical request that is in flight or just finished"; delay (guard) "wait before +sending, backing off so the service can recover"; block (heal) "do not send; fail this request immediately"; +serve_cached (heal) "answer with the last successful response for this request instead"; deliver (passive) "pass +the failure to the application as it is"; retry (heal) "retry the request after a short backoff"; wait (passive) +"keep waiting for the request"; hedge (heal) "send a second identical request and use whichever answers first"; +ignore (passive) "leave the state as it is"; rollback (heal) "restore the affected state to its last consistent +snapshot"; resync (heal) "reload the affected state from its source". Effects: [decide-policy-actions](decide-policy-actions.md). + +### 9. Serialiser (`serialize.ts` -> `toJevState(parts, budget)`) + +1. `b = max(500, round(budget))`; `L = sectionLimits(b)` with `r = clamp((b - 1100) / (3200 - 1100), 0, 1)` and + `lerp(a, z) = Math.round(a + (z - a) * r)`. +2. Pre-shape: `app` (or `"unknown"`) and `trigger` truncated to their line limits; `facts`, `in_flight`, `state`, + `stats` keep their **first** `L.<section>` lines, `timeline` keeps its **last** `L.timeline` lines; every line + truncated to `L.line.<section>` (`…` suffix). +3. Build the object with keys in order `app, trigger, facts, in_flight, timeline, state, stats`; empty arrays -> + `"none"`. +4. While `stateChars > b`: drop timeline lines from the start (oldest) down to 0, then state lines from the end to 0, + then facts from the end down to **1**, then in_flight from the end to 0, then stats from the end to 0. +5. Still over: shorten every fact by the excess (not below 60 chars), then the trigger (not below 60 chars). + +| budget | facts | in_flight | timeline | state | stats | line limits app / trigger / facts / in_flight / timeline / state / stats | +|---|---|---|---|---|---|---| +| 500-1100 | 6 | 2 | 3 | 3 | 1 | 60 / 180 / 220 / 90 / 100 / 100 / 110 | +| 1333 (WASM 2 threads) | 7 | 2 | 4 | 4 | 1 | 67 / 187 / 224 / 93 / 104 / 106 / 113 | +| 1400 (compact-questions edge) | 7 | 3 | 5 | 4 | 1 | 69 / 189 / 226 / 94 / 106 / 107 / 114 | +| 1667 (WASM 3 threads) | 8 | 3 | 7 | 4 | 2 | 76 / 196 / 231 / 98 / 111 / 114 / 118 | +| 2000 (WASM 4 threads) | 9 | 4 | 9 | 5 | 2 | 86 / 206 / 237 / 103 / 117 / 121 / 123 | +| 2560 (WebGPU after 1 overflow) | 10 | 5 | 12 | 6 | 3 | 102 / 222 / 248 / 111 / 128 / 135 / 131 | +| 3200+ (WebGPU) | 12 | 6 | 16 | 8 | 4 | 120 / 240 / 260 / 120 / 140 / 150 / 140 | + +(Counts at 1100/2000/3200 and the 500 = 1100 equivalence are asserted in `test/budget.test.ts`; the line limits and +the other rows are computed from the same formula, not tested.) A 1-line-per-section minimum does not exist: the +counts are maxima, sections may be `"none"`, and only `facts` keeps at least 1 line under shrinking. `stateText(state)` renders `key: value` or `key:` plus +two-space-indented lines; it is for logs, `explain()` and devtools. `stateChars` does not count that indentation. +What the model actually tokenises is produced from the `JevState` by the model host's packer +(`packages/runtime/src/model/serialize.ts`), see [model-io-contract](../model-io-contract.md). + +### 10. Redaction + +- `Redactor = (path, value) => unknown`; default `defaultRedact` returns `"[redacted]"` when **any dotted segment** + of the path names a secret by meaning: `isSensitiveName` splits camelCase/snake/kebab into lower-case words and + matches `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, + iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or `SECRET_PAIRS` (card + + number/num/no/cvc/cvv/code/security; credit card; cc + number/num/no/exp/csc; api key/secret; private key; access + key; secret key; session id/token/key; security code; one time; social security). `card`, `cards`, `author`, + `passengers`, `tokens`, `pinned`, `session`, `key` are not secrets. +- Situation code applies it through `describe(v, path, env.redact, max)` (state lines, inputs-moved values, deltas, + `is now` facts) and `changeText(c, redact)` (`state/fields.ts`; timeline write summaries are produced by the hub + with the same redactor). Nested object keys are checked at `path.key`. Op details (query strings, request bodies, + typed values) are redacted earlier by the observers and `rt.user`; invariant `values` by the invariant miner. +- A custom `redact` option replaces the default everywhere (tested for invariant facts in + `test/review-redaction.test.ts`). + +### 11. Device-sized situations (`RuntimeImpl.situationBudget`) + +`situation.budget` number -> used as is. `"auto"` (default): decider `status.device === "wasm"` -> +`1000 + round((min(4, max(1, threads)) - 1) * 1000 / 3)`; otherwise (webgpu or unknown) 3200; times +`budgetScale`, which starts at 1 and becomes `max(0.5, budgetScale * 0.8)` on each `max_tokens_exceeded` error from +the decider (`DeciderQueue` error callback in the constructor). Example: 3200 -> 2560 -> 2048 -> 1638 -> 1600 +(floor); WASM 1 thread 1000 -> 800 -> 640 -> 512 -> 500. The scale is per runtime instance, never resets, and does +not apply to a numeric `situation.budget`. `env.ts` holds no sizing logic. `Runtime.situationBudget()` is public +(`types.ts` -> `Runtime`) and is what `buildOpts()` passes as `BuildOptions.budget` on every build. The sim samples +budgets 3200/2000/1000 with weights 40/30/30 (`sim/src/world/scenario.ts`, `R.fork("budget")`) and passes them as a +fixed `situation.budget`; the Python curriculum samples the same three at 35/30/35 (`training/curriculum/rt.py` -> +`BUDGETS`, override env `GC_RT_BUDGET`). Neither generates 1333/1667 or overflow-scaled budgets: at runtime those +sizes are interpolations the model never saw in training. + +### 12. Annotated examples (copied from `packages/runtime/STATUS.md`, produced by the tests) + +**A. mutation at a 1000-char budget (compact, from `test/budget.test.ts`, 998 chars).** + +``` +app: /search +trigger: A write to search.results from GET /api/search?q=rea (#6) is about to be applied. +facts: + search.results was written once by other operations since this write's cause (#6) started (version 0 → 1), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). + search.query changed since this write's cause (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. + This write comes from GET /api/search?q=rea (#6), started 0.90s ago, ended 0.00s ago with 200; its chain began with user typed "rea" into input "Search" (#5). + This write would change search.results: 2 items ["reac-1", "reac-2"] → 2 items ["rea-1", "rea-2"]. +in_flight: none +timeline: + -0.00s end GET /api/search?q=rea (#6): 200 in 0.90s +state: + search.results = 2 items ["reac-1", "reac-2"] (v1, by #8 0.69s ago) + search.query = "reac" (v4, by #7 0.81s ago) +stats: + GET /api/search: 4 done, 0 of last 4 failed, 4 in last 10s +questions: + diagnosis: What is happening here? expected | stale | conflict | duplicate | inconsistent | failing | slow | overload | unusual | transient + action: What should the runtime do with this write? apply | discard | defer +``` + +- Fact 1 is M2 (versions, salient: another chain wrote `search.results` after the cause started); fact 2 is M5 + (inputs, salient because `search.query` is in the same store). Non-neutral facts come first, then provenance + (rank 7) and delta (rank 10). +- The timeline limit at 1000 chars is 3 lines, but timeline is the first thing dropped when over budget, so only the + newest line survives. `in_flight` is empty -> `"none"`. +- `stats` has no median/p95: only 4 latency samples (< 5). Compact questions (budget <= 1400) carry bare labels + (every criterion is `null`); the `questions:` lines are the test's printout, the model receives the `questions` + object and the packer renders it. + +**B. request at the full budget (from `test/situation.test.ts`).** + +``` +app: /search +trigger: POST /api/orders {items: [1], cardNumber: [redacted]} (#4) is about to be sent. +facts: + 1 identical POST /api/orders request in the last 10s: #2 in flight (started 0.12s ago); #2 started 0.12s before this one; they come from separate user actions 0.12s apart. + This request comes from user clicked button "Place order" (#3), started 0.00s ago. + POST is not idempotent; its body (52 bytes) can be replayed. +in_flight: + POST /api/orders {items: [1], cardNumber: [redacted]} (#2) 0.12s so far, by #1 +timeline: + -0.12s user clicked button "Place order" (#1) + -0.12s start POST /api/orders {items: [1], cardNumber: [redacted]} (#2, by #1) + -0.00s user clicked button "Place order" (#3) + -0.00s start POST /api/orders {items: [1], cardNumber: [redacted]} (#4, by #3) +state: none +stats: none +questions: + diagnosis (choice): What is happening here? + action (choice): What should the runtime do with this request? + send: send the request now + coalesce: do not send; reuse the result of the identical request that is in flight or just finished + delay: wait before sending, backing off so the service can recover + block: do not send; fail this request immediately +``` + +- R3 is salient because the identical request #2 is still in flight (`close`). `cardNumber` is redacted + (`card` + `number` pair) in the op detail by the fetch observer. `serve_cached` is not offered (not a GET); + `coalesce` is offered because `canCoalesce` found #2. No baseline facts yet (no completions). `state` is `"none"` + because no store has been written by this signature. + +**C. failure at the full budget (from `test/situation.test.ts`; `app`, `in_flight`, `timeline`, `state` and the +questions are omitted here, see STATUS.md for the full text).** + +``` +trigger: GET /api/status (#12) failed (HTTP 503) and the app has not seen the failure yet. +facts: + The request #12 failed: HTTP 503 after 0.06s; the app has not seen the failure yet. + 4 identical GET /api/status requests in the last 10s (latest 3: #6 answered 200 6.00s ago; #8 ended 503 4.00s ago; #10 ended 503 2.00s ago); #10 started 2.00s before this one, neither from a user action. + This is the 3rd GET /api/status failure in a row (recent outcomes: 200, 200, 503, 503, 503; last success 6.00s ago); error rate 50% over 6 requests (3 failed). + GET /api/status was requested 5 times in the last 10s (no usual rate learned yet). + This request comes from task poll (#11), started 0.06s ago. + GET is idempotent. + A cached 200 response from 6.00s ago exists for this request. +stats: + GET /api/status: 6 done, 3 of last 6 failed, 5 in last 10s +``` + +- F1 is the only salient fact; the rest follow `RANK`: repetition (2), outcome F2 (4), baseline R8 (5), + provenance (7), request R11 (8), cache (9). R3 is neutral on `failure`. R9 is absent and stats show no median: + only 3 non-failure latency samples. The error rate uses real counts over the last <= 20 outcomes, the outcome list + shows the last 5. + +**D. transition at the full budget (from `test/situation.test.ts`; facts and stats only, see STATUS.md for the rest).** + +``` +trigger: POST /api/cart {} (#46) completed with a state change unlike its usual ones. +facts: + In the previous 22 completions of POST /api/cart its chain wrote cart.items and cart.total (22 of 22 times); this time it wrote only cart.items. + The last consistent state from before #45 started is 0.40s old; 1 field write happened since. + It ended 0.06s ago with 200 after 0.08s (usual 0.08s). + The completed operation #46 comes from user clicked button "Add" (#45), started 0.14s ago. + cart.items is now 23 items [1, 2, 3, …]. +stats: + POST /api/cart: 23 done, median 0.08s, p95 0.08s, 0 of last 20 failed, 23 in last 10s +``` + +- T1 (`set` component, salient) is first; `only` because `{cart.items}` is a strict subset of the usual set. The + profile had 22 previous completions (>= 20) and the observed set was seen 0 times (< 1% of 22). +- Neutral facts follow `RANK`: T5 invariant (0), T3 baseline (5), T2 provenance (7, cause = the user click #45), + T4 delta (10). T4 printed because `cart.items` has no id-like segment, so the normalised chain key is also a + real path. +- The click #45 is profiled too (key `user <name>`, its chain includes #46's writes) and is equally unusual, but it + is an ancestor of #46, so only #46 (the descendant) is raised; the test asserts exactly one transition call. +- `stats` shows `0 of last 20 failed` although 23 are done: outcomes keep only the last 20 (`OUTCOMES`). +- Actions offered: `ignore`, `rollback` (the chain's write is the latest and its previous value is known); no + `resync` because the test store has no resync handler. + +## Configuration and constants + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `LAT_WINDOW` | const | 64 | `learn/baselines.ts` | latency samples kept per signature | +| `START_WINDOW` | const | 128 | `learn/baselines.ts` | start times kept per signature (rate) | +| `WINDOW_MS` | const | 10000 | `learn/baselines.ts` | "recent" window for `rate()` | +| `ERR_ALPHA` | const | 0.1 | `learn/baselines.ts` | EWMA weight of the error rate | +| `MIN_LAT_SAMPLES` | const | 5 | `learn/baselines.ts` | latency baseline exists from 5 samples (also gates stall watching) | +| `OUTCOMES` | const | 20 | `learn/baselines.ts` | outcomes kept; failure counts are over these, facts list the last 5 | +| `MAX_SIGS` | const | 1000 | `learn/baselines.ts` | signatures kept (FIFO) | +| identity cap / gap EWMA | inline | 1024 ids; `0.8 * old + 0.2 * gap` | `Baselines.noteIdentity` | identical-request gap baseline | +| usual-rate guard | inline | `older >= 3`, `span >= 20000` ms | `Baselines.rate` | when `usual` is reported | +| `MIN_COMPLETIONS` | const | 20 | `learn/profiles.ts` | completions before any profile anomaly; also per-field minimum for kind anomalies | +| `RARE` | const | 0.01 | `learn/profiles.ts` | rarity threshold (`seen < 0.01 * of`) | +| `MAX_SETS` / `MAX_FIELDS` | const | 64 / 128 | `learn/profiles.ts` | per-profile caps | +| profile signature cap | inline | 2000 | `Profiles.add` | profiles kept (FIFO) | +| write buckets | fn | `0`, `1`, `2`, `3-4`, `5+` | `writesBucket` | shape component | +| duration buckets | fn | `<50ms`, `50-200ms`, `0.2-1s`, `1-5s`, `>5s` | `durBucket` | recorded, never checked | +| `PROFILED` | const | fetch, xhr, user, task, ws | `runtime.ts` | op kinds that get profiles | +| `PROFILE_KEY` | const | `"genclass.profiles.v1"` | `runtime.ts` | localStorage key with `learn.persist` | +| `STALL_MIN_MS` | const | 500 | `runtime.ts` | stall fires at `max(4 × median, 2 × p95, 500)` ms | +| `LONG_RUNNING_MS` | const | 10000 | `runtime.ts` | in-flight ops older than this do not block settled points | +| `settleMs` | option | 60 ms | `InitOptions.settleMs` | quiet time before a settled point | +| `triage` | option | `"salient"` | `InitOptions.triage` | `"always"` consults on every trigger | +| `situation.budget` | option | `"auto"` | `InitOptions.situation` | situation size in chars | +| `learn.persist` | option | false | `InitOptions.learn` | persist transition profiles | +| `MAX_FACTS` | const | 12 | `situation/facts.ts` | facts kept after ordering | +| `WINDOW` | const | 10000 | `situation/facts.ts` | repetition / pending-local-change window | +| plugin fact length | inline | 240 | `buildSituation` | plugin fact truncation | +| timeline source | inline | last 96 events | `timelineLines` | events considered for the timeline | +| `STATE_CHAR_BUDGET` | const | 3200 | `situation/serialize.ts` | full budget; default when no budget given. The `serialize.ts` comment assumes ≈ 3.2 chars/token (≈ 1,000 tokens); TRAIN measured ≈ 2.4 (`training/NEEDS.md` item 6a), i.e. ≈ 1,300–1,400 tokens ([model-io-contract](../model-io-contract.md)) | +| `COMPACT_BUDGET` | const | 1100 | `situation/serialize.ts` | budget at and below which section limits are smallest | +| `MIN_BUDGET` | const | 500 | `situation/serialize.ts` | smallest budget honoured | +| `LIMITS` | const | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | full-budget section counts | +| compact counts | inline | facts 6, in_flight 2, timeline 3, state 3, stats 1 | `sectionLimits` | compact section counts | +| line limits | inline | compact -> full: app 60->120, trigger 180->240, facts 220->260, in_flight 90->120, timeline 100->140, state 100->150, stats 110->140 | `sectionLimits` | per-line truncation | +| fact/trigger shortening floor | inline | 60 chars | `toJevState` | last-resort shortening | +| `COMPACT_QUESTIONS_BUDGET` | const | 1400 | `situation/questions.ts` | compact questions at or below | +| `COMPACT_DESC_MAX` | const | 24 | `situation/questions.ts` | vocabulary overrides kept in compact questions | +| auto budget | fn | webgpu/unknown 3200; wasm 1000/1333/1667/2000 for 1/2/3/4+ threads | `RuntimeImpl.situationBudget` | device sizing | +| `budgetScale` | field | 1, `× 0.8` per `max_tokens_exceeded`, floor 0.5 | `RuntimeImpl` constructor | shrinks auto budgets | +| `REDACTED` | const | `"[redacted]"` | `util.ts` | redaction marker | +| `redact` | option | `defaultRedact` | `InitOptions.redact` | replaces the redactor for every situation sentence | +| `app` | option | `document.title` + `location.pathname` | `CreateOptions.app` (`RuntimeImpl.appInfo`) | source of the `app` section (`"<title> — <route>"`) | +| `vocabulary` | option | none | `InitOptions.vocabulary` | `diagnoses` replaces `DEFAULT_DIAGNOSES`; `actions` overrides descriptions | +| `historySize` | option | 500 | `InitOptions.historySize` (`EventLog`) | events kept; the timeline reads the last 96 of them | +| `HIST` / `LOG` | const | 16 / 512 per field | `state/hub.ts` | rich history (before/after, used by M5 before-values, M10, I2) / version log (M2/M3 counts, `versionAt`) | +| `RECENT_MS` / `RECENT_MAX` | const | 10000 ms / 256 | `state/hub.ts` | `hub.recent` window for identical-change facts (M12, ask) | +| identical-request registry | inline | 12 ops per identity, 512 identities | `RuntimeImpl.registerIdentity` | `SitEnv.identical`, R3 | +| recent errors | inline | 64 kept, 10 s window | `RuntimeImpl.reportError` / `makeEnv` | E5, ask | +| consistent snapshots | inline | 8 kept | `RuntimeImpl.settled` | `lastConsistent`, `consistentBefore`, I3/T5/E6, rollback | +| `storeWriters` caps | inline | 1000 signatures; writer + 8 ancestors | `RuntimeImpl.onApplied` | M7, timeline relevance, involved stores | +| profile queue | inline | 2000 ops | `RuntimeImpl.queueProfile` | ops waiting for a settled point | +| profile save delay | inline | 5000 ms | `RuntimeImpl.saveProfilesSoon` | with `learn.persist` | +| `defer` limit | inline | `m.defers < 2` | `builtinApplicable` | defer offered at most twice per write | +| `retry` limit | inline | `op.attempt < 4` | `builtinApplicable` | retry offered for attempts 1-3 | +| fact list caps | inline | M2-M4/M10/M15: first 3 paths; M5: 2 fields; M6: 3 ops listed; M14: 2; R3: last 3; R4: 3; F3/E3: 4 paths; I1: 3 violations, I2: 2 writes each; T1: 3; T4: 3; ask: 5 chain keys, 6 fields, 2 violations | `facts.ts` | sentence counts per trigger | +| per-sentence truncations | inline | `opLabel` 90; in-flight/timeline op phrase 80; error message 120 (subject, E1), 80 (short subject), 100 (timeline); error source 60; network message 50; `statusText` error text 40; op detail in M6/R4 30; plugin fact 240; store `describe()` 110 (90 when the store path itself is involved) | `describe.ts`, `facts.ts`, `build.ts` | applied before section line limits | + +## Invariants and gotchas + +- **Train/runtime parity.** Any change to `src/situation/*`, `src/learn/*`, the formatters in `src/util.ts` + (`secs`, `rel`, `fmtNum`, `ratio`, `truncate`, `describe`, `normalizePath`), `changeText` in + `src/state/fields.ts`, or op details produced by observers changes model inputs. The final-round training data + comes from tag `situation-v1` (no model is deployed yet: the 0.1.0-alpha.0 runtime takes no actions until the model + package is published, per `OPEN_TASKS.md`); a change needs new sim data (`sim/`), an update of + `training/curriculum/rt.py` (Python port + of facts/describe/build/serialize/questions), retraining and new eval. Coordinate with SIM and TRAIN (STATUS.md: + "Any change to situation wording must be coordinated with SIM"). +- **Model input also lives outside `src/situation/`.** Timeline lines include `ActionEffect.changed` sentences + (`runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`, e.g. `Dropped the write to …; search stays at version 3.`), + the undo text `undid <action> (<id>)`, the failed-action text `Tried to <action> <subject> but it failed; …`, + hub write summaries (`changeText`), op details produced by observers (`redactSearch`, body summaries), and + `rt.user` target/value strings. Rewording any of these changes training inputs exactly like a fact change does. +- **What the sim exercises.** `sim/src/run/rt.ts` -> `createOptions` runs the real runtime with `model: false`, a + scripted `decider`, `mode: "heal"`, `triage: "salient"`, `historySize: 500`, observers `fetch`, `timers`, + `websocket` only (xhr, user DOM, errors, nav, storage, perf off), a fixed `situation.budget`, and the module named + by env `GENCLASS_RUNTIME` (default `@genclass/runtime`). User actions and errors are fed directly through + `runtime.user(...)` and `runtime.reportError(...)` (`sim/src/run/runner.ts`). XHR request/failure/stall + situations and `nav`/`storage`/`perf` timeline lines come only from disabled observers, so sim rows should not + contain them (inferred from `createOptions`; not checked against generated data). +- **Determinism.** Read time only from `env.now()` (injected clock). No `Date.now`, `Math.random`, locale formatting + or iteration over unordered structures. Sorts must be stable with explicit tie-breaks (as in `orderFacts`, + `inFlightLines`). Tests assert byte-identical situations. +- **Side-effect free.** Situation code must not create ops, push events or write stores. The single allowed write is + `C.reads.set(path, vStart)` in `mutationFacts`. (On the runtime side, the `SitEnv.recentErrors()` implementation in + `RuntimeImpl.makeEnv` also prunes entries older than 10 s from `RuntimeImpl.errorsRecent`; this only drops expired + entries.) The sim relies on `rt.situation()` not perturbing counterfactual replays (sim/NEEDS.md item 5). +- **Fail open.** Exceptions in `computeFacts`/`buildSituation` run the passive action; plugin `facts()` and + `applicable()` throws are swallowed. +- **Triage is cost, not policy.** A `neutral` flag must never encode "this is a bug". Making facts non-neutral + increases model calls and **holds** (writes/requests wait up to the hold budget): OPEN_TASKS lists hold-induced + latency (search clean-run latency 14 -> 125 ms with v0.1) and typeahead being salient about 6 times per clean trial. +- **Neutral is per trigger for R3/R5.** The same repetition/streak fact is salient on `request` but neutral on + `failure`/`stall`; R7 (hot rate) is salient on all three. +- **Fact order matters beyond the model.** The budget keeps the first facts; `decide/report.ts` and devtools + `topFact` (`devtools/ui.ts`) pick the first fact not matching `^This (write|request) (comes from|has no known + cause)` as the headline. Renaming provenance wording breaks that regex. +- **Two fact lists.** `Situation.facts`/`Decision.facts`/`explain()` hold up to 12 ordered facts; `state.facts` + holds what fits the budget (at least 1). Plugin facts rank last and are the first to be cut. +- **No action question with a single action.** E.g. `error` without a revertable chain offers only `ignore`, so + `questions.action` is absent and the gate sees no action answer (passive). +- **Compact thresholds differ.** Section limits bottom out at 1100 chars; compact questions start at <= 1400. +- **Budget is characters, not tokens.** Overflow in the model host raises `max_tokens_exceeded`, which permanently + shrinks auto budgets for the runtime instance (fixed numeric budgets are not scaled). +- **`opts.describe` bypasses redaction.** A store's custom `describe()` output is printed as is in state lines. +- **Normalised chain keys.** `OpRec.chain` keys are normalised (`:id`), and transition `involvedFields`, + `transitionFacts` (T4) and `SubjectRef.paths` use them; such paths have no leaf, so their state lines and + `is now` facts are silently skipped. +- **Baselines cover fetch/XHR only.** WebSocket/task subjects get no stats line, and M8 (cause latency) is only + computed for fetch/XHR causes. + 4xx responses are non-failures (they reset the streak and add latency samples) but do not update `lastSuccess`. + Latency baselines never include failed/timed-out requests, so they underestimate slowness during outages. +- **Rarity needs `seen == 0` up to 100 completions** (`seen < 0.01 * of`). Profiles check before adding, and + descendants win over ancestors when both are unusual. +- **Eviction is FIFO** for baselines (1000 signatures), identities (1024), profiles (2000): a long-lived hot + signature can be evicted by many new ones. +- **`lastBuilt` only updates past the cheap pass**, so `rt.situation("mutation")` can return an old situation or a + relabelled "ask about now" one. +- **`rt.situation()` is always `salient: true`.** With no argument (or no stored situation for the trigger) it builds + an `ask` situation, and `ask` is salient by definition. The devtools Now view (`devtools/index.ts`, which calls + `rt.situation()`) therefore always shows the "salient: the model would be asked" chip. To judge triage of a real + trigger, check whether any fact is non-neutral (`computeFacts`) or use `rt.situation(trigger)` after that trigger + was built. +- **Facts are computed before the subject proceeds.** For `failure`, the failed op is already ended and in the + baselines (fetch and XHR call `endOp` before raising the trigger; streak/outcome counts include it); for `mutation`, the write is not yet applied (M15 describes the + pending change, state lines show the current value). +- **`Profiles.load` trusts its input.** It only checks `sig` (string) and `n` (number) per entry and does not apply + the 2000-signature cap; a corrupt `genclass.profiles.v1` entry with missing maps can throw later in `check`/`add` + (inside `settled()`, unguarded) (unverified: not tested). +- **Dead declarations.** `SigStats.firstStart` and `SigStats.failures` (lifetime failure count) are written but + never read; `SigStats.errEwma` is read only by `Baselines.snapshot()`, which nothing in `src/` calls; + `SitEnv.writtenByChain` is never implemented; `isTrigger` is never imported. Removing them changes no model input. +- **Past bugs fixed in batch 3 (keep fixed):** "started X after/before" uses the real direction + (`test/review-fetch.test.ts`); failure facts use real counts, not the EWMA; version counts come from the 512-entry + log, not the 16-entry history (`test/review-hub.test.ts`); "changed twice and is back to 6" instead of "6 → 6"; + parent paths never print `= undefined`; array kinds are empty/non-empty only (short last page is not unusual); + digit-containing entity keys normalise to `:id` (`test/review-precision.test.ts`); redaction by word meaning. + +## How to change it safely + +**Change a fact's wording or add a fact** +1. Edit the relevant function in `packages/runtime/src/situation/facts.ts`; pick `kind` (sets rank) and `neutral` + deliberately (see Triage). Keep numbers explicit and relations stated ("after", "newer", "in a row"). +2. Check consumers of the wording: `decide/report.ts` and `devtools/ui.ts` regex on provenance; tests that match + text (`grep -rn "state.facts" packages/runtime/test`). +3. Update the Python port `training/curriculum/rt.py` (same computation and ordering). +4. Update tests: `test/situation.test.ts`, `test/batch3.test.ts`, `test/budget.test.ts`, plus any review test + matching the text. Update the example blocks in `packages/runtime/STATUS.md`. +5. Run locally (lead policy, [where to run things](build-test-release.md#where-to-run-things)) or on the VM: `cd packages/runtime && npx vitest run test/situation.test.ts test/budget.test.ts + test/learn.test.ts test/batch3.test.ts test/review-*.test.ts` (then the full suite; see + [build-test-release](build-test-release.md)). +6. Flag the parity break: new sim data, retraining, a new freeze tag (after `situation-v1`). + +**Change a triage threshold** (e.g. 3× latency in M8, `close` in R3, hot rate in R7): edit the `neutral` expression +in `facts.ts`; add a test that a benign case stays quiet (pattern: `test/review-precision.test.ts`) and a positive +case reaches `decider.calls`; mirror in `training/curriculum/rt.py`; regenerate sim data (the set of rows changes). + +**Change budgets or section limits**: `serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `LIMITS`, the `lerp` +endpoints) and/or `RuntimeImpl.situationBudget`; update `test/budget.test.ts` expectations, `section_limits` / +`to_state` in `training/curriculum/rt.py`, sim budget sampling in `sim/src/world/scenario.ts`, the doc comment on +`InitOptions.situation` in `types.ts`, and `docs/runtime/API.md`. Check the model host's maximum sequence length. + +**Add a trigger kind**: `TriggerKind` (`types.ts`), `SubjectSpec` (`env.ts`), `subjectOf`, `subjectOp`, +`involvedStores`, `involvedFields`, `builtinApplicable`, `subjectRef` (`build.ts`), `computeFacts` (`facts.ts`), +`TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS` (`questions.ts`), a raise site with a `Controller` in +`runtime.ts`/observers, the sim and the Python port. `isTrigger` derives from `TRIGGER_ACTIONS`. + +**Add or reword a built-in action**: `BUILTIN_ACTIONS` (tier + description), `TRIGGER_ACTIONS` (order: passive +first), `builtinApplicable`, the controller's `run()` for that trigger in `runtime.ts`/observers, policy tiers +([decide-policy-actions](decide-policy-actions.md)), `ACTIONS`/`TRIGGER_ACTIONS` in `training/curriculum/rt.py`, the +fake runtime in `sim/src/run/fake-runtime.ts`, `TIER` in `sim/src/oracle/cost.ts`, `ACTION_PARA` in +`sim/src/run/transform.ts`, `PASSIVE` in `sim/src/types.ts` (passive actions), `ACTION_DESC`/`TRIGGER_ACTIONS`/`TIER` +in `training/curriculum/fmt.py`, `TIER`/`PASSIVE` in `training/eval_runtime.py`; full list: +[model-io-contract recipes](../model-io-contract.md#recipes). + +**Change the diagnosis vocabulary**: `DEFAULT_DIAGNOSES` (keep `expected` first; `test/batch3.test.ts` asserts +`unusual`, `transient` are last), `DEFAULT_DIAGNOSES` in `sim/src/world/scenario.ts` (the sim passes it explicitly +when the runtime lacks a label), `DIAG_PARA` in `sim/src/world/scenario.ts`, `DIAGNOSES` in `sim/src/types.ts`, the +rules in `sim/src/oracle/diagnose.ts`, `DIAGNOSES` in `training/curriculum/rt.py`, `DIAG_DESC` in +`training/curriculum/fmt.py`, CONTRACT §6; full list: [model-io-contract recipes](../model-io-contract.md#recipes). + +**Change baseline estimators or profile rarity**: `baselines.ts` / `profiles.ts`; update `test/learn.test.ts`, +`test/review-precision.test.ts`, `test/situation.test.ts` (stall timing depends on median/p95). Note that +`watchStall` timing and facts R7-R9, S1, M8 all read these values. + +**Change redaction**: `isSensitiveName`/`SECRET_WORDS`/`SECRET_PAIRS` in `util.ts`; update `test/batch3.test.ts` +(SIM a) and `test/review-redaction.test.ts`; `docs/runtime/API.md` "Privacy". + +**Add a fact kind**: `FactKind` in `types.ts`, its rank in `RANK` (`facts.ts`; typed `Record<FactKind, number>`, so +the compiler forces an entry), `RANK` in `training/curriculum/rt.py`. Rank decides which facts survive the budget, +and the report/devtools headline skips only provenance. + +**Change timeline or action-effect wording**: `eventLine` (`describe.ts`), the hub's write summary +(`state/hub.ts`, `changeText` in `state/fields.ts`), `ActionEffect.changed` strings (`runtime.ts`, +`observe/fetch.ts`, `observe/xhr.ts`), `event_lines` / `phrase` in `training/curriculum/rt.py`; update the STATUS.md +example blocks; treat it as a parity break like a fact change. + +**Change what `stats` or `in_flight` show**: `statsLines` / `inFlightLines` (`build.ts`). Keep the sort keys +explicit (score, then start time) for determinism; budget tests assert per-section maxima. + +## Tests + +| test file | what it asserts | +|---|---| +| `packages/runtime/test/situation.test.ts` | one situation per trigger (except `ask`): key order, <= 12 facts, <= 16 timeline, <= 8 state lines, `stateChars <= 3200`, `diagnosis` present; first-fact text for mutation (stale write, M2), stall (`has been in flight for …; GET /api/report/:id usually takes`), inconsistency (relation values), transition ("only cart.items") and error (`Uncaught TypeError: `); some fact matches for request (identical POST in flight) and failure (`3rd GET /api/status failure in a row`); the card number value `4242` never appears in the state; inconsistency offers exactly `ignore, rollback`; transition raised once (descendant wins); `situation()` side-effect free and `trigger: "ask"`; serializer: an over-budget input ends with `timeline: "none"`, an under-budget one keeps all 16 timeline lines and empty sections become `"none"`; byte-identical determinism at the default budget | +| `packages/runtime/test/learn.test.ts` | baselines: no latency before 5 samples, nearest-rank median/p95, EWMA, streak, `!` outcomes, aborted ignored, `rate` recent/usual, identity `gapEwma`; profiles: < 1% of >= 20, op that usually writes nothing, kind and status anomalies, end-to-end transition with chain rollback | +| `packages/runtime/test/budget.test.ts` | `sectionLimits` at 1100/2000/3200/500; budgets 1000/1100/2000 respected per section with the stale-write fact first; compact questions at <= 1400 and overrides <= 24 chars; determinism at 1100; auto budget by device/threads; `max_tokens_exceeded` -> 2560; hold budget | +| `packages/runtime/test/batch3.test.ts` | `isSensitiveName` positives/negatives; no `= undefined` state lines; item change summary; "changed twice … and is back to 6"; slug-id signatures; pending-local-change fact (M10) is first and salient; `transient` label last | +| `packages/runtime/test/review-precision.test.ts` | short last page and `m<n>` keys are not unusual transitions; closing a selection is not an inconsistency | +| `packages/runtime/test/review-redaction.test.ts` | a custom `redact` also applies to invariant facts | +| `packages/runtime/test/review-hub.test.ts` ("field versions in facts") | "written 20 times by other operations" and "(version 0 → 20)" past the 16-entry history | +| `packages/runtime/test/review-fetch.test.ts` ("request facts") | "started 0.10s after this one" direction; error-rate text matches listed outcomes | +| `packages/runtime/test/review-actions.test.ts` | "Its chain wrote no state before the error." and rollback not offered then | +| `packages/runtime/test/invariants.test.ts` | learned-relation fact values; developer invariant fact text | +| `packages/runtime/test/dom.test.ts` | error fact `Uncaught TypeError: boom (at app.js:12).` | +| `packages/runtime/test/plugins.test.ts` | plugin facts reach the model; vocabulary overrides; `applicable()` gating; standing questions | +| `packages/runtime/test/atoms.test.ts`, `smoke.test.ts`, `review-xhr.test.ts` | identical additive change is salient (held); nothing salient applies synchronously; identical XHR just sent is salient | +| `packages/runtime/test/ask.test.ts` | `ask()` sends trigger `ask` with questions replaced by `{ answer }` and trigger sentence `The developer asks about the app right now.`; `about: opId` -> `The developer asks about GET /api/x (#n).`, `about: "cart"` -> `The developer asks about the store cart.` | +| `packages/runtime/test/review-precision.test.ts` ("design risk") | a lingering benign violation must not freeze the latest consistent snapshot (snapshot `seq` keeps advancing) | +| `packages/runtime/test/devtools-runtime.test.ts` | the Now view renders `runtime.situation()`; evidence view shows `explain()` facts and situation text | + +## Drift and open issues + +- **Auto budget doc comment** (`types.ts` -> `InitOptions.situation`): says "wasm 1,100 + 300 per extra thread up to + 4 threads: 2,000". Code (`RuntimeImpl.situationBudget`) and tests: `1000 + round((threads - 1) * 1000 / 3)` -> + 1000/1333/1667/2000. API.md and STATUS.md match the code. +- **Default redactor doc comment** (`types.ts` -> `InitOptions.redact`): says regex + `/pass|token|secret|card|cvv|ssn|auth/i`. Code uses word-level `isSensitiveName` (approved deviation; API.md is + correct; CONTRACT §2 still has the regex). +- **CONTRACT §4 transition profiles**: lists value kind with "length delta sign; null" and a duration bucket as part + of the shape. Code: arrays are only empty/non-empty (documented deviation in STATUS.md), duration is never checked, + and two precision rules are not in the contract (no `set` anomaly when the usual set is empty; no `writes` anomaly + when the usual bucket is `"0"` or a `set` anomaly exists). +- **CONTRACT §6 budget**: "≤ 1,000 tokens; truncate timeline first, then state, then facts". Code: characters + (3200 chars, ≈ 1,300–1,400 tokens at the measured 2.4 chars/token), device-sized, then in_flight, stats, and fact/trigger shortening. CONTRACT §6's + `runtime.situation()` shape omits `salient`, `facts`, `compact`, `budget`. +- **`rollback` description vs effect**: `BUILTIN_ACTIONS.rollback` says "restore the affected state to its last + consistent snapshot" for `inconsistency`, `transition` and `error`, but transition/error rollback restores only the + op chain's own writes (`RuntimeImpl.revertChain`). The model reads a description that does not match the effect on + 2 of 3 triggers; fixing it changes model inputs. +- **Unreachable fact M11**: `This write could not be held: …` is emitted only for `m.unholdable`, but + `StoreHub.propose` (`state/hub.ts`) commits unholdable writes immediately without calling `hooks.gate`, and + `RuntimeImpl.gateMutation` is the only place that raises `mutation` triggers. STATUS.md (batch 3) says such writes + apply "with a fact". +- **STATUS.md triage summary** says "cause latency > 3× median"; code also requires `lat − median >= 100 ms`. It says + identical requests within "min(2 s, half its usual gap)"; code uses the usual gap only after more than 3 sightings + of the identity. +- **ARCHITECTURE.md** lists diagnoses as "…failing, transient, slow, overload or unusual"; code order puts + `transient` last. Its fact example shows "(v0 → v1)"; code prints "(version 0 → 1)". +- **API.md** says plugin facts are "added to every situation": they are added only to situations that are built + (past the cheap triage pass, or `situation()`/`ask`), are neutral, rank last and may be cut by `MAX_FACTS` or the + budget. +- **sim/NEEDS.md** note "`transient` is not yet in `DEFAULT_DIAGNOSES`" is stale; it is (last). +- **CONTRACT §6 applicability footnote** is looser than `builtinApplicable`: `coalesce` also needs fetch transport + and a shareable in-flight/just-finished response (`canCoalesce`); `retry` needs replayable, `attempt < 4` and + fetch; `hedge` also needs GET and fetch; `serve_cached` on failure/stall needs fetch; error `rollback` needs an + ambient op whose chain write is still the latest with a known previous value in a writable store. XHR therefore + never gets `coalesce`/`retry`/`hedge` or failure/stall `serve_cached` (request-trigger `serve_cached` has no + transport check); STATUS.md "Deviations" states the XHR part. +- **CONTRACT §6 timeline** says "≤ 16 most recent relevant events"; `timelineLines` tops up with recent + non-relevant events when fewer relevant ones exist. +- **CONTRACT §6 triage examples** ("a baseline ratio beyond 3×", "written by another op") are coarser than code: + M8 also needs `lat − median >= 100 ms`, R7 needs `recent >= 5`, M2 counts other *chains* (not other ops), and + failure-streak/repetition facts are salient only on `request`. +- **API.md `rt.situation()`** lists `{ trigger, subject, state, questions, actions, salient, facts }`; the + `Situation` type also has `compact` and `budget`. +- **API.md / README "cheap facts are computed for every write and request"**: facts are computed only when the + runtime is consultable (a `DecisionProvider` exists, its state is `ready` or `off`, not paused or destroyed) and + only for gated writes/requests (GenClass-owned ops and bypassed writes never trigger). +- **Sim vs Python budget mix**: the sim samples 3200/2000/1000 at 40/30/30 (`sim/src/world/scenario.ts`), the + Python curriculum at 35/30/35 (`training/curriculum/rt.py` -> `BUDGETS`). Not a parity bug for a single row, but + the two data sources have different budget distributions. +- **Python port drift** (`training/curriculum/rt.py` -> `to_state`): last-resort fact shortening floor is 40 chars + (runtime 60) and the trigger is never shortened. Only reached when one fact or the trigger alone exceeds the + budget. Also: `secs`/`rel`/`fmt_num` round exact binary ties half-even (Python format) vs `toFixed` half-up + (125 ms -> `0.12s` vs `0.13s`); `secs` >= 1000 s and `ratio` >= 10× use Python `round()` vs `Math.round`; rt.py + `truncate` counts code points, `util.truncate` UTF-16 units (see + [model-io-contract gotchas](../model-io-contract.md#invariants-and-gotchas)). +- **`Situation.subject` doc comment** (`types.ts` -> `Situation`): says "One sentence naming the subject"; code + (`buildSituation`) fills it with the short subject phrase from `subjectOf` (e.g. `write to search.results from GET + /api/search?q=rea (#6)`), while the full sentence goes to `state.trigger`. +- **Open (OPEN_TASKS.md)**: "Next" item 6 lists hold-induced harm and triage sensitivity on naturally concurrent apps + (typeahead salient about 6 times per clean trial) to investigate with the trained model; "Known risks" lists thin + `conflict` and `transition` rows. + +## Related docs + +- [public-api-and-lifecycle](public-api-and-lifecycle.md): `InitOptions` (`triage`, `situation.budget`, `learn`, + `redact`, `vocabulary`), `rt.situation()`, `rt.ask()`. +- [observe-and-trace](observe-and-trace.md): ops, signatures, identities, op details, events. +- [state-and-adapters](state-and-adapters.md): mutation pipeline (which writes are gated), invariant miner, + settled points, consistent snapshots. +- [decide-policy-actions](decide-policy-actions.md): what happens after a situation is submitted (queue, hold, + gate, actions, reports, explain). +- [model-host](model-host.md) and [model-io-contract](../model-io-contract.md): how the `JevState` and questions + become packed model input and calibrated answers. +- [devtools](devtools.md): where facts and situations are displayed. +- [sim](../sim.md), [training](../training.md): consumers of this exact output; parity and regeneration. +- [status-and-known-issues](../status-and-known-issues.md), [glossary](../glossary.md). +- Existing human docs: [CONTRACT.md](../../runtime/CONTRACT.md) §4-§7, [API.md](../../runtime/API.md), + [ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md) + (example situations per trigger). diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md new file mode 100644 index 00000000..7a946401 --- /dev/null +++ b/docs/agents/runtime/model-host.md @@ -0,0 +1,670 @@ +# @genclass/runtime: model host (worker, loader, backends, engine, packer, calibration, CLI) + +> **Scope:** `packages/runtime/src/model/*.ts` (backend, calibrate, engine, errors, hash, host, index, loader, packer, protocol, pyutil, serialize, tokenizer, worker), `packages/runtime/src/model/README.md` (internal notes), `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/MODEL_CARD.md`, the `worker` entry of `packages/runtime/tsup.config.ts`, and the model sections (§2 `model` options, §8 `DecisionProvider`, §10, §13) of `docs/runtime/CONTRACT.md`. +> **Read this when:** you change how the model is downloaded, cached, verified or run; touch the worker or its message protocol; change WebGPU/WASM selection or onnxruntime-web settings; change the tokenizer, packer, Python-parity serializer or calibration; add or change a model error; work on the `genclass-runtime` CLI; debug "model unavailable", "observing only", stuck loads or slow decisions. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- `createModelHost(opts)` (`packages/runtime/src/model/host.ts`) returns a `ModelHost`, which implements the runtime's `DecisionProvider` seam (`packages/runtime/src/types.ts`). `GenClass.init()` creates one by default in a browser. The runtime only calls `status`, `ready()`, `evaluate()`, `onStatus()` and `dispose()`. +- **Fail open, never wait.** `evaluate()` rejects at once with `ModelNotReadyError` (code `not_ready`) unless `status.state === "ready"`. Every provider error makes the runtime run the passive action. While the host is `"loading"` or `"error"`, the runtime does not even build situations. +- **Transport:** inference runs in a module Worker (`dist/worker.js`, built from `src/model/worker.ts`). If the Worker cannot be created, errors before its `hello`, or sends no `hello` within 15 s, the same `ModelBackend` runs inline on the main thread. `worker: false` forces inline. +- **Load sequence** (`packages/runtime/src/model/backend.ts` -> `ModelBackend.doLoad`): + 1. The `model.json` card, fetched in parallel with a WebGPU probe. + 2. The plans are computed. + 3. In parallel: the onnxruntime-web bundle import (`/webgpu` only if a WebGPU plan exists, else `/wasm`), the tokenizer, calibration and meta files, and the first variant. + 4. The ORT `.wasm`, prefetched by us. + 5. For each plan: `InferenceSession` -> `Engine` -> a warm-up pass. The first plan that works wins. +- **Plans:** `webgpu+fp16` (adapter has `shader-f16`) -> `webgpu+q8` -> `wasm+q8`. A failed WebGPU plan alone does not trigger a retry: the same worker moves on to the next plan. Only when a worker's whole load ends in an error status, a crash or a stall after a WebGPU attempt does the host retry **once** in a fresh worker with WASM only (`retryOnWasm`). +- **Downloads** (`packages/runtime/src/model/loader.ts` -> `fetchFile`) go through Cache Storage `genclass-runtime-v1`. They are checked against the card's size and sha256 (WebCrypto, with a pure-TS fallback) and streamed with progress. The card itself is always revalidated from the network. A cached card is used only when the network fails. +- **Engine** (`engine.ts`): `Packer` (`packer.ts`, `Tokenizer` from `tokenizer.ts`, text from `serialize.ts`) packs everything into int64 feeds. One ORT forward pass produces `choice_logits` / `score_logits` / `noul_logits`. Temperature or Platt calibration (`calibrate.ts`) then gives typed `Answer`s. +- **Python parity is the contract.** `serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts` and `calibrate.ts` are ports of `jev_local` Python. The model was trained on the Python rendering, so any change here is a model-format change. The situation format is frozen as `situation-v1`. +- **The trained runtime model is not published yet.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`, and OPEN_TASKS item 8 lists publishing it as future work. The card fetch therefore fails (expected HTTP 404; not checked against the live CDN), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). +- **Status:** `off` -> `loading` (phases `card` / `download` / `runtime` / `session` / `warmup`) -> `ready` or `error`; `dispose()` -> `off`. See [Status lifecycle](#status-lifecycle-modelhoststatusstate). The runtime core reads only `state`, `device`, `threads`, `warmupMs`, `model`, `variant`, `loadMs` and `error` (the devtools overlay also shows `progress`); `status.latency` (p50/p90 of the last 20 evaluations) and `host.stats` are for tooling. +- **CLI** `genclass-runtime fetch-model <dir>` / `info <dir>` downloads and verifies a self-hostable model directory, with no dependencies. + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `packages/runtime/src/model/host.ts` | Main-thread host: chooses worker or inline transport, preload, priority queue, timeouts, status, WASM retry, latency stats | `createModelHost`, `ModelHost`, `ModelHostOptions`, `ModelHostStats`, `ModelEvaluateRequest`, `WorkerLike`, `DEFAULT_MODEL_BASE_URL`, `DEFAULT_TIMEOUT_MS`, `DEFAULT_MAX_QUEUE` | +| `packages/runtime/src/model/backend.ts` | Load sequence and evaluation. One instance runs in the worker, or inline. Sets ORT threads and wasm. Provides the warm-up request | `ModelBackend`, `ModelHostStatus`, `LatencyStats`, `OrtBuild`, `BackendLoadOptions`, `BackendEnv`, `ORT_WASM_FILES`, `ortCdnBase`, `WARMUP_STATE`, `WARMUP_QUESTIONS` | +| `packages/runtime/src/model/worker.ts` | Module Worker entry (tsup entry `worker` -> `dist/worker.js`). Wires `ModelBackend` to `postMessage` | (side-effect module; posts `hello`) | +| `packages/runtime/src/model/protocol.ts` | Host <-> worker message types | `ToWorker`, `FromWorker`, `EvaluateOk` | +| `packages/runtime/src/model/loader.ts` | Card parsing, plan order, WebGPU probe, Cache-Storage downloads with sha256, step timeouts | `parseCard`, `planOrder`, `probeWebGPU`, `fetchFile`, `fetchCard`, `cardId`, `fileUrl`, `normalizeBaseUrl`, `withTimeout`, `StepTimeoutError`, `CARD_FORMAT`, `DEFAULT_CACHE_NAME`, types `ModelCard`, `VariantSpec`, `FileSpec`, `FileRole`, `Plan`, `GpuInfo`, `DevicePreference`, `DeviceKind`, `FetchEnv`, `FetchOutcome`, `TimerEnv` | +| `packages/runtime/src/model/engine.ts` | Packer + ORT session + calibration -> answers. Checks the graph contract | `Engine`, `FEEDS`, `tensorFloats`, `ModelMeta`, `EngineOptions`, `EngineResult`, ORT structural types `OrtLike`, `OrtSessionLike`, `OrtTensorLike`, `OrtEnvLike` | +| `packages/runtime/src/model/packer.ts` | Sequence layout, ONNX feed plan, logits unpacking, token limits | `Packer`, `planInputs`, `unpackLogits`, `MARKERS`, `STATE` (= -1), types `Packed`, `PackedQuestion`, `PackerOptions`, `FeedPlan`, `HeadOutput`, `Marker` | +| `packages/runtime/src/model/tokenizer.ts` | Byte-level BPE over HF `tokenizer.json` | `Tokenizer` (`encode`, `count`, `decode`, `tokenId`, `vocabSize`), `bytesToUnicode`, `TokenizerJson`, `AddedTokenJson` | +| `packages/runtime/src/model/serialize.ts` | Jev state/question -> text. Port of `jev_local/serialize.py` | `stateSegments`, `segmentText`, `stateText`, `entryText`, `pyJson`, `toJsonValue`, `questionBlock`, `questionEntries`, `criteriaEntries`, `MAX_ARRAY_SEGMENTS`, `DEFAULT_{NOUL,CHOICE,SCORE}_INSTR`, types `Segment`, `QBlock`, `BlockKind`, `WireQuestion` | +| `packages/runtime/src/model/pyutil.ts` | Python value semantics | `pyNumber`, `pyFloatRepr`, `pyRound`, `pyStrip`, `clip01` | +| `packages/runtime/src/model/calibrate.ts` | `calibration.json` parsing, temperature/Platt lookup, answer math. Port of `calibrate.py` and `confidence.py` | `parseCalibration`, `calibrateLogits`, `buildAnswer`, `headerKey`, `tauFor`, `noulAffine`, `kBucket`, `normalizeProbs`, `choiceConfidence`, `scoreConfidence`, `K_BUCKETS`, `BUCKET_CLAMP`, `Calibration`, `Precision` | +| `packages/runtime/src/model/errors.ts` | Typed errors and their wire format | `GenClassModelError` + 11 subclasses, `serializeError`, `deserializeError`, `errorMessage` (any thrown value -> string), `ModelErrorCode`, `SerializedError`, `LoadAttempt` | +| `packages/runtime/src/model/hash.ts` | Pure-TS SHA-1 (calibration header keys) and SHA-256 (integrity; WebCrypto preferred) | `sha1Hex`, `sha256Hex` (async; `crypto.subtle` when present, else pure TS), `sha256HexSync`, `sha1`, `sha256` | +| `packages/runtime/src/model/index.ts` | Barrel for the model module (internal; not a package entry point). Nothing in `src/` imports it: the runtime imports `model/host.js` and `model/errors.js` directly. Its only user is the fallback "model-entries" build in `packages/runtime/test/browser/build.mjs`, which uses it as the `index` entry | re-exports everything above **except** `withTimeout`, `StepTimeoutError`, `TimerEnv`, `errorMessage`, `sha256HexSync`, `sha1`, `sha256`, `pyFloatRepr`, `HeadOutput`, `Marker`, `OrtEnvLike`, and the protocol types `ToWorker` / `FromWorker` (`EvaluateOk` is re-exported via `host.ts`) | +| `packages/runtime/src/model/README.md` | MODEL's internal notes: card format, load steps, parity results, measured latency and transfer sizes | — | +| `packages/runtime/src/index.ts` | Public facade. Re-exports `createModelHost`, `DEFAULT_MODEL_BASE_URL`, the host types and all error classes. Builds the host in `makeHost` | `createRuntime`, `GenClass.init`, `makeHost`, `failedProvider`, `NATIVE_FETCH` | +| `packages/runtime/tsup.config.ts` | Build. Entry `worker: "src/model/worker.ts"` -> `dist/worker.js` (not in `dts.entry`, so no `.d.ts`); `external: ["onnxruntime-web", "onnxruntime-web/webgpu", "react", "redux", "zustand"]`; ESM, `target: "es2022"`, `platform: "browser"`, `splitting: true` (the build output's `worker.js` imports `ModelBackend` from a chunk shared with `index.js`), sourcemaps | — | +| `packages/runtime/package.json` | `exports["./worker"]` -> `./dist/worker.js`; `bin.genclass-runtime` -> `./bin/genclass-runtime.mjs`; dependency `onnxruntime-web ^1.30.0` | — | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI (Node >= 20, no deps): `fetch-model`, `info` | `main`, `fetchModel`, `info`, `parseCard` (JS copy), `scanOnnx` | +| `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. **The npm package itself does not exist yet** (no `package.json`, no `files/`) | — | + +## Concepts and data structures + +| term | meaning | +|---|---| +| **model host** | `ModelHost` (`host.ts`): the main-thread object the runtime talks to. It owns one transport and a queue. | +| **backend** | `ModelBackend` (`backend.ts`): loads a model directory and runs the `Engine`. It runs inside the worker, or inline. | +| **transport** | `WorkerTransport` (posts to a Worker) or `InlineTransport` (calls a `ModelBackend` in the same realm, asynchronously via a microtask). Both speak `ToWorker` / `FromWorker`. | +| **model directory** | A URL directory (`baseUrl`) holding `model.json` plus the files it lists. | +| **model card** | `model.json`, parsed by `parseCard` into `ModelCard`. Format tag `genclass-runtime-model/1` (`CARD_FORMAT`). | +| **variant** | One ONNX file of the model, keyed by name in `card.variants`: `q8` (MatMulNBits 8-bit; meant for WASM) and `fp16` (meant for WebGPU with `shader-f16`). | +| **plan** | `{ variant, device }` tried in order by the backend. `device` is `"webgpu"` or `"wasm"`. | +| **ORT build** | `OrtBuild` = `"webgpu"` (`onnxruntime-web/webgpu`, asyncify wasm, runs the WebGPU and WASM EPs) or `"wasm"` (`onnxruntime-web/wasm`, plain wasm, CPU only). | +| **attempt** | `LoadAttempt { variant, device, error }`: a plan that failed. Collected in `status.attempts`. | +| **phase** | The load step in progress: `"card" \| "download" \| "runtime" \| "session" \| "warmup"`. | +| **warm-up** | One forward pass, two on WebGPU, over `WARMUP_STATE` + `WARMUP_QUESTIONS` (a situation-shaped request; the code comment says about 350 tokens) before `ready`. | +| **wire request** (Jev request) | `{ state: JevState, questions: Record<qid, Question> }`, the only part of `EvaluateRequest` that reaches the worker (`protocol.ts` -> `ToWorker`). `Question` is `noul` / `choice` / `score` (`types.ts`). See [glossary](../glossary.md). | +| **segment** | `Segment { key, text }`: one top-level state key (or array item) rendered as text. Segments are separated by `[SEP]` in the packed sequence. | +| **QBlock** | `{ qid, kind: "noul"\|"choice"\|"score", header, items, labels }`: one question rendered for packing. | +| **heads** | Graph outputs `choice_logits`, `score_logits`, `noul_logits` (`OUTPUT_KIND` in `engine.ts`). | +| **tau / calibration** | Post-hoc temperature (or Platt affine for noul) per header, K-bucket or kind, read from `calibration.json`. | +| **fail open** | On any provider error or not-ready state, the subject proceeds unchanged (the passive action). | +| **R17 / R32** | Runtime model candidates (MODEL_CARD). R17 = ettin-encoder-17m (d 256, 7 layers, 8.1M + 0.7M heads; q8 9.6 MB, fp16 13.6 MB). R32 = ettin-encoder-32m from GenClass 0.1 (d 384, 10 layers, 18.8M + 1.6M heads; q8 22.5 MB, fp16 34.8 MB). Both use a 16,364-token pruned vocabulary, with markers at ids 16359-16363. | +| **v0.1 model** | The older GenClass 0.1 ONNX (`genclass-q8.onnx` 56,931,453 B; `genclass-fp16.onnx` 67,154,907 B) used for development. Its card is `extension/src/model/model.json` (the "v0.1 extension card": `bundled`, `default_base_url`, no `files`). | + +### `ModelHost` API (`packages/runtime/src/model/host.ts`) + +```ts +interface ModelHost extends DecisionProvider { + readonly status: ModelHostStatus; // current snapshot (replaced on every change) + readonly stats: Readonly<ModelHostStats>; // the live counters object, not a copy + ready(): Promise<void>; // starts the load if needed + load(): Promise<void>; // starts now; after an "error" it retries + evaluate(req: ModelEvaluateRequest): Promise<Record<string, Answer>>; + evaluateDetailed(req: ModelEvaluateRequest): Promise<EvaluateOk>; // + model ("name@version"), usage, timings + measure(state: unknown, questions?: unknown): Promise<{ stateTokens: number; positions: number; total: number }>; + onStatus(fn: (s: ModelHostStatus) => void): () => void; + dispose(): void; +} +type ModelEvaluateRequest = EvaluateRequest & { timeoutMs?: number }; // EvaluateRequest: trigger, state, questions, priority?, subject?, timeoutMs? +interface ModelHostStats { requests; completed; failed; timeouts; busy; notReady; lastMs?; lastForwardMs? } // all numbers +``` + +Public exports of `@genclass/runtime` from this module (`packages/runtime/src/index.ts`): `createModelHost`, `DEFAULT_MODEL_BASE_URL`, types `ModelHost`, `ModelHostOptions`, `ModelHostStatus`, `ModelHostStats`, `ModelEvaluateRequest`, the 12 error classes, `ModelErrorCode`, `LoadAttempt`. `DEFAULT_TIMEOUT_MS`, `DEFAULT_MAX_QUEUE`, `WorkerLike`, `EvaluateOk` and `LatencyStats` are not public. + +`stats` counters: `requests` (every `evaluateDetailed` call on a live host; `evaluate` delegates to it), `notReady` (rejected because not `ready`), `completed`, `failed` (error results, unclonable requests, `toJsonValue` failures), `timeouts`, `busy` (queue evictions), `lastMs` (wall time of the last completed request, queue wait included), `lastForwardMs` (its `timings.forward`). + +### Status lifecycle (`ModelHostStatus.state`) + +| from | to | when (code) | +|---|---|---| +| (constructed) | `off` | `Host` constructor. `preload: "eager"` calls `start()` immediately | +| `off` | `loading` | `start()`: idle callback, or the first `ready()`/`load()`/`evaluate()`/`measure()`. Phases then run `card` -> `download` -> (`download` -> `runtime` -> `session` -> `warmup`) per plan | +| `loading` | `loading` | WebGPU recovery (`retryOnWasm`): the error is swallowed, a fresh worker loads with `device: "wasm"`, earlier attempts are kept | +| `loading` | `ready` | the first plan that passes its warm-up (`ModelBackend.doLoad`) | +| `loading` | `error` | the backend emits `error`, or a worker crashes after `hello`, or the stall watch fires, and no WASM retry happens. `retryOnWasm` needs a worker transport, `device !== "wasm"`, the one retry unused, and a WebGPU entry in `attempts`; a crash is only offered to it when the current `status.device` is `"webgpu"` | +| `ready` | `error` | a worker `error`/`messageerror` event after `hello` (`failEarly` -> `onWorkerCrash`): message `the model worker crashed: <why>` | +| `error` | `loading` | `host.load()` (re-sends `load` on the live transport). After a crash `started` is reset, so `load()`, `ready()`, `evaluate()` or `measure()` all start a fresh worker. After a plain load error (`started` still true) `ready()` rejects at once and starts nothing. The runtime never calls `load()`, and triggers stop calling anything in `error`. It calls `ready()` at most once (the cached `rt.ready`), so the first `rt.ask()`/`rt.decide()` or app read of `rt.ready` **after a crash** restarts the host only if `rt.ready` had not been read before | +| any | `off` | `dispose()` | + +### Card (`ModelCard`, `packages/runtime/src/model/loader.ts`) + +```ts +interface FileSpec { file: string; bytes?: number; sha256?: string } +interface VariantSpec extends FileSpec { provider?: string; needs?: string } // needs e.g. "shader-f16" +interface ModelCard { format: string; name: string; version: string; license?: string; + variants: Record<string, VariantSpec>; files: Record<"tokenizer"|"calibration"|"meta", FileSpec> } +``` +`parseCard` rules: +- It must be a JSON object with at least one variant. +- `file` must be relative: no scheme, no leading `/` or `\`, no `..` or empty path segment. Otherwise it throws `ModelUnsupportedError`. +- `bytes` must be a non-negative integer. +- `sha256` must be 64 hex characters. A `sha256:` prefix is accepted and the value is lowercased. +- `files.*` may be a bare string, and missing entries default to `tokenizer.json` / `calibration.json` / `meta.json`. +- Missing `name`, `version` and `format` default to `"genclass-model"`, `"0.0.0"` and `CARD_FORMAT`. +- `provider` is informative only. + +### `meta.json` (`ModelMeta`, `engine.ts`): only these keys are read + +`max_len` (positions budget; default 1536), `max_total` (whole sequence; default 8192), `markers`, `cls_id`, `sep_id` (all checked against the tokenizer), `inputs`, `outputs` (checked against the graph), and `name` (only the `Engine`'s fallback id; `ModelBackend.createEngine` always passes `name: "<card.name>@<card.version>"`, so the host never uses `meta.name`). `pad_id` is declared in `ModelMeta` but not used. TRAIN's `training/export_runtime.py` writes all of these, plus extra informational keys. + +### Status (`ModelHostStatus` in `backend.ts`, extends `ModelStatus` in `types.ts`) + +`state: "off"|"loading"|"ready"|"error"`, `phase?`, `progress? {loaded,total}` (model-file bytes; monotonic; throttled to one update per 100 ms, except the final one), `device?`, `variant?`, `model?` (card name), `version?`, `bytes?` (variant size), `fromCache?` (variant came from Cache Storage), `loadMs?`, `warmupMs?` (first warm-up pass), `threads?`, `worker?`, `workerError?` (why inline), `gpu?` (probe summary, e.g. `"nvidia ampere, shader-f16"` or the reason there is none), `attempts?`, `ort?` (onnxruntime-web version), `error?`. Two fields exist only on `ModelHostStatus`: `ortBuild?` and `latency?: LatencyStats`. + +```ts +interface LatencyStats { p50: number; p90: number; n: number; tokensP50: number; msPerToken: number; source: "warmup" | "evaluations" } +``` + +### Protocol (`packages/runtime/src/model/protocol.ts`) + +| direction | message | notes | +|---|---|---| +| host -> worker | `{type:"load", options: BackendLoadOptions}` | `baseUrl` (and `ortWasmPaths`) already resolved to absolute URLs on the main thread | +| host -> worker | `{type:"evaluate", id, state, questions}` | `state` is JSON-normalised by `toJsonValue`. `questions` is posted as given (structured clone; Maps survive) | +| host -> worker | `{type:"measure", id, state, questions?}` | answered synchronously from the packer | +| host -> worker | `{type:"dispose"}` | worker disposes the backend then `close()`s | +| worker -> host | `{type:"hello"}` | posted once, right after the worker module evaluates (before ORT is imported) | +| worker -> host | `{type:"status", status: ModelHostStatus}` | every backend status change | +| worker -> host | `{type:"result", id, ok:true, value}` / `{type:"result", id, ok:false, error: SerializedError}` | exactly one per `evaluate` / `measure` | + +`EvaluateOk = { answers: Record<string, Answer>; model: string; usage: { input_tokens; positions }; timings: { pack; forward; total } }`. + +### Errors (`packages/runtime/src/model/errors.ts`): every class extends `GenClassModelError { code, detail? }` + +| class | `code` | thrown by | `detail` / extra fields | what the runtime does | +|---|---|---|---|---| +| `ModelNotReadyError` | `not_ready` | `host.evaluateDetailed`/`measure` when not ready; `pump` when the load failed with jobs queued; `onWorkerCrash` for queued jobs; `ModelBackend.evaluate`/`measure` without an engine | `{state}` from the host | fail open (passive) | +| `MaxTokensExceededError` | `max_tokens_exceeded` | `Packer.pack` | `tokens` (state + longest branch), `total`, `maxTokens`; detail `{detail:"max_tokens_exceeded", tokens, total, max_tokens, max_total?}` | fail open, and `budgetScale = max(0.5, budgetScale*0.8)` (`runtime.ts`, `DeciderQueue` `onError`), so later **automatic** situation budgets are smaller (a numeric `situation.budget` is not scaled) | +| `ModelInputError` | `bad_request` | `serialize.ts` (non-object question, empty choice/score, unknown type, non-object `questions`, non-JSON state such as BigInt or cycles); `host.pump` when `postMessage` throws (e.g. `DataCloneError`) | — | fail open | +| `ModelUnsupportedError` | `unsupported` | bad card/calibration/tokenizer/meta, graph-contract mismatch, missing head for a question kind, unknown output dtype | — | fail open. During load it becomes `ModelLoadError` or an attempt | +| `ModelTimeoutError` | `timeout` | `host.timeout` (request deadline passed, queued or running) | `{timeoutMs}` | fail open | +| `ModelAbortedError` | `aborted` | **never thrown** (only rebuilt by `deserializeError`) | — | — | +| `ModelBusyError` | `busy` | host queue full (eviction) | `{queued}` | fail open | +| `ModelDisposedError` | `disposed` | any call after `dispose()`, and pending work at dispose | — | — | +| `ModelLoadError` | `load_failed` | `fetchFile`/`fetchCard` (network, HTTP status, opaque response); `ModelBackend.doLoad` (wraps every other load failure); host `setStatus(error)` (rejects `ready()`), `ready()` after error, `onWorkerCrash` (running job) | `attempts: LoadAttempt[]`; detail `{attempts}` | status `error`; runtime observes only | +| `ModelIntegrityError` | `integrity` | `fetchFile` size or sha256 mismatch | `{url, bytes, expected}` or `{url, sha256, expected}` | never reaches callers with this code: it is wrapped into `ModelLoadError` (small files) or recorded as an attempt's `error` string (variants) | +| `ModelInferenceError` | `inference_failed` | `Engine.logits` when `session.run` throws | — | fail open | +| `StepTimeoutError` (loader.ts; **not** a `GenClassModelError`) | — | `withTimeout`: `requestAdapter`/`requestDevice` (5 s each) inside `probeWebGPU`, and session creation (webgpu 60 s, wasm 180 s) in `ModelBackend.createEngine` | message `"<what> timed out after <ms> ms"` | Probe timeouts never escape: `probeWebGPU` catches them and returns `webgpu: false` with a `summary` such as `"WebGPU probe failed: requestAdapter timed out after 5000 ms"` or `"<adapter>: no device (...)"`, so no WebGPU plan is made. A session-creation timeout is recorded as an attempt. On WebGPU in a worker it stops the remaining plans | + +`ModelLoadError` messages produced by the load (useful when matching `status.error`): `model card download failed: HTTP <status> for <url>`, `model card download failed for <url>: <msg>`, `download failed: HTTP <status> for <url>`, `download failed for <url>: <msg>`, `download of <url> returned an opaque (no-CORS) response`, `WebGPU did not come up (<msg>); not trying further plans in this worker`, `no plan could run the model: <variant>/<device>: <error>; ...` (or `... the card has no usable variant`), `disposed while loading`. Host-side texts: `the model worker crashed: <why>`, `the model worker did not start in time` (only as `workerError`), `the model worker stopped responding while loading (<phase> on <device>)`. + +Not a model error: `GenClassUnavailableError` (`packages/runtime/src/errors.ts`, `reason: "off" | "error" | "timeout" | "destroyed"`) is what `rt.ask()`/`rt.decide()` throw when no model can answer. See [public-api-and-lifecycle.md](./public-api-and-lifecycle.md). + +Wire format: `SerializedError { name, message, code?, detail? }`. `serializeError` JSON-sanitises `detail`. `deserializeError` rebuilds the class from `code` and restores the original `message`. Non-`GenClassModelError` errors come back as a plain `Error` with the same `name`. + +Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the types `ModelErrorCode` and `LoadAttempt`. `serializeError` / `deserializeError` are exported only from the internal `model/index.ts`. + +## How it works + +### 1. How the runtime creates and consumes the host + +1. `packages/runtime/src/index.ts` captures `NATIVE_FETCH` (the global `fetch` as it was when the module loaded, before GenClass instruments it). +2. `GenClass.init(options)` (`initUnsafe`) does one of three things: + - kill switch `?genclass=off` / `localStorage.genclass="off"`: creates no model; + - non-browser (no `window` or `document`): sets `model: false`; + - otherwise, if `options.decider === undefined && options.model !== false`, sets `o.model = options.model ?? {}`. +3. `createRuntime` builds a host only when `options.model` is an object and no `decider` was given. `makeHost` calls `createModelHost({ ...model, fetch, clock })`: + - `fetch` is `NATIVE_FETCH`, or, when `createRuntime` got a `global`, that global's `fetch` bound before the observers install. It is used only by the inline transport; + - `clock` is passed only when `createRuntime` got one (otherwise the host uses `browserClock`). + + If construction throws, it uses `failedProvider`, a provider with `status: {state:"error"}` and no `onStatus` (so no console line and no `"status"` event). The runtime then owns the host (`ownsDecider`) and calls `dispose()` on `destroy()`. +4. `RuntimeImpl` (`packages/runtime/src/runtime.ts`) consumes the provider as follows: + - `onStatus`: re-fires as the runtime `"status"` event. On `ready` the reporter prints `[GenClass] Model ready (<model>, <device>, <variant>, <loadMs>). Mode: <mode>.`. On `error` it prints `[GenClass] Model unavailable (<error>); observing only.` Both go through `console.info` under `report: "console"`. + - `consultable()`: triggers are built only when `status.state` is `"ready"` or `"off"`. With `"loading"` or `"error"`, every trigger runs its passive action at once, and writes and requests are never held (`hub.hooks.mayHold` uses `consultable()`). + - `trigger()`: if a situation is salient but `status.state !== "ready"`, it calls `void this.ready`, which starts a load (the effective "lazy" start), and runs the passive action. The public `rt.ready` getter calls `decider.ready()` once and caches the promise, so any read of `rt.ready` by the app, and any `rt.ask()`/`rt.decide()`, also starts the load regardless of `preload`. + - `priority` per request (the `trigger(...)` call sites in `runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`; `ask` submits directly): 2 for `mutation`, `request` (fetch and XHR) and fetch `failure`; 1 for `inconsistency`, `stall`, XHR `failure` and `ask`; 0 for `transition` and `error`. In `trigger`, a request that will not hold is capped at 1 (`waits ? priority : min(priority, 1)`). + - `situationBudget()`: reads `status.device` and `status.threads`. + - `holdBudgetMs()`: seeds from `status.warmupMs` until the decider queue has its own latency samples. + - `Decision.model`: comes from `status.model ?? status.variant`. + - Calls to `evaluate()` all go through `DeciderQueue` (`packages/runtime/src/decide/decider.ts`). It allows one in flight. It passes `timeoutMs = deadline - now` (the hold budget, plus 2 s when a late revert is possible, or 5 s for background decisions). It abandons the provider after that deadline (or 10 s when there is none). Any rejection triggers `onError` and the passive action. See [decide-policy-actions.md](./decide-policy-actions.md). +5. The runtime does **not** use `measure`, `evaluateDetailed`, `stats` or `status.latency`. They exist for direct `createModelHost` users, the browser benchmarks and devtools-style tooling. + +### 2. Host start-up, preload and transports (`host.ts`) + +1. The `Host` constructor resolves `loadOptions`: + - `baseUrl`: `resolveBaseUrl(opts.baseUrl ?? DEFAULT_MODEL_BASE_URL)`, resolved against `location.href` so relative paths such as `/genclass-model/` work inside the worker; + - `device`: `opts.device ?? "auto"`; + - optional `ortWasmPaths` (resolved), `cacheName`, `warmup: false`, `maxThreads`. +2. Preload (`opts.preload ?? "idle"`): + - `"eager"`: `start()` now. + - `"idle"`: `scheduleIdle`. If `document.readyState !== "complete"`, it waits for `load` (or `LOAD_EVENT_WAIT_MS` = 5 s), then calls `requestIdleCallback(run, {timeout: 2000})`. Without `requestIdleCallback` it uses a `clock.setTimeout` of 1 s. + - `"lazy"`: nothing until the first `ready()`, `load()`, `evaluate()` or `measure()`. +3. `start()` (once): unless `opts.worker === false`, it calls `workerFactory ?? defaultWorkerFactory`. The default factory is `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`, or `null` when `Worker` is undefined. If the factory throws (CSP, `file://`, ...), the result counts as `null`. A `null` worker means `useInline()`. +4. `useWorker(w)`: + - registers `message`, `error` and `messageerror` listeners. Every `error` event is `preventDefault()`ed so it never reaches the page's error handlers or GenClass's own error observer; + - arms `helloTimer` (`helloTimeoutMs ?? 15_000`); + - sets status `{state:"loading", worker:true}`, posts `load`, and arms the stall watch. +5. Failure before `hello` (error event, `messageerror`, or hello timeout): the worker is terminated and the host calls `useInline(why)`. `status.workerError = why`. +6. `useInline()` creates an `InlineTransport`: + - `fetch` = `opts.fetch` (the runtime passes `NATIVE_FETCH`) or global `fetch`; + - `ort` = `opts.ortLoader ?? defaultOrtLoader` (dynamic `import("onnxruntime-web/webgpu")` or `import("onnxruntime-web/wasm")`); + - `caches` = `globalThis.caches`. + + It sets status `{state:"loading", worker:false}` and sends `load`. +7. `worker.ts`: + - If `self.name` starts with `em-pthread` or equals `ort-wasm-proxy-worker`, the module does nothing. ORT may start its pthread workers from the script that contains it. + - Otherwise it builds `ModelBackend({ ort: dynamic import by build, fetch: self.fetch, caches (try/catch), clock: browserClock, emit: post status, inWorker: true })`, routes messages to it, and posts `hello`. +8. Every `status` message re-arms the **stall watch** (`loadStallMs ?? 180_000`; worker transport only, only while `loading`). Silence for that long calls `onStall`. If `status.device` is `"webgpu"` it first adds an attempt `{device:"webgpu", error:"stalled"}`. It then calls `retryOnWasm`; if that returns false it calls `onWorkerCrash("the model worker stopped responding while loading (<phase> on <device>)")` (`<phase>` is `start-up` when no phase was reported yet). + +### 3. Backend load (`backend.ts` -> `ModelBackend.load` / `doLoad`) + +1. `load(opts)` joins an in-flight load and resolves at once when an engine exists. On failure `loading` resets, so a later `load` starts over. +2. Phase `card`: + - starts the GPU probe (skipped with `device:"wasm"`; `probeGpu` override or `probeWebGPU(clock)`); + - `fetchCard(fenv, baseUrl)` fetches `<baseUrl>model.json` with `cache:"no-cache"`; + - when the response is OK, parses it and writes a copy to Cache Storage (fire-and-forget); + - on a network, HTTP or JSON error, falls back to the cached copy; + - if nothing is cached, rethrows a `ModelLoadError` (`"model card download failed: HTTP <status> for <url>"` or `"model card download failed for <url>: <msg>"`); + - a `ModelUnsupportedError` from `parseCard` is rethrown immediately, without the cache fallback. +3. It sets `status.model`/`version` from the card. It awaits the probe and sets `status.gpu` to `gpu.summary` (unless `device:"wasm"`). +4. It calls `planOrder(card, device, gpu)` (loader.ts): + - GPU plans exist only if `device !== "wasm" && gpu.webgpu && (device === "webgpu" || !gpu.fallback)`. `"auto"` skips software adapters (e.g. SwiftShader). + - For each of `fp16` and `q8` present in the card: skip it if `needs === "shader-f16"` and the adapter lacks `f16`, or if it has any other non-empty `needs`. Otherwise push `webgpu+<v>`. + - Then push `wasm+q8`, or `wasm+fp16` if the card has no `q8`. If the card has neither, push every variant on WASM in card order. +5. `build = plans.some(webgpu) ? "webgpu" : "wasm"` sets `status.ortBuild`, and `env.ort(build)` starts importing onnxruntime-web. +6. Phase `download`: + - progress is seeded with the card sizes of the tokenizer, calibration, meta and the first plan's variant; + - the first variant starts downloading; + - the three small files are fetched in parallel (`fetchFile` with tag `cardId(card)` = `name@version`) and parsed: `new Tokenizer(...)`, `parseCalibration(...)`, `JSON.parse(meta)`. + - `fetchFile(env, url, spec, tag, onProgress)` (loader.ts) per file: open Cache Storage `cacheName` -> a valid hit is returned with `fromCache: true` and no network -> an invalid hit is deleted -> network `fetch(url, { cache: "no-store" })` (the HTTP cache is bypassed; Cache Storage is the only cache) -> reject opaque or non-OK responses (`ModelLoadError`) -> stream the body with per-chunk progress (`readBody`; total = card `bytes`, else `content-length`) -> size check, then sha256 check (`ModelIntegrityError`) -> `stored` = a background `cache.put` with headers `x-genclass-tag` and, when hashed, `x-genclass-sha256`. There is no retry. +7. It awaits ORT and calls `configureOrt`: + - `threads = crossOriginIsolated && inWorker ? max(1, min(maxThreads ?? 4, hardwareConcurrency || 1)) : 1`; + - `env.wasm.numThreads = threads`, `env.wasm.proxy = false`, `env.logLevel = "error"`. + + It then starts `prefetchWasm`: + - fetches `ORT_WASM_FILES[build]` from `ortWasmPaths || ortCdnBase(ort.env.versions.web || "1.30.0")` through the same cache (tag `onnxruntime-web@<version>`, no sha256); + - sets `env.wasm.wasmBinary` so ORT never fetches the wasm itself; + - if that fails, sets `env.wasm.wasmPaths = <base>` instead. +8. For each plan: + - `download` (await the variant; extra variants are fetched on demand and memoised per load); + - `runtime` (await the wasm prefetch); + - `session`: `ort.InferenceSession.create(bytes, { executionProviders: [device], graphOptimizationLevel: "all" })` under `withTimeout` (webgpu 60 s, wasm 180 s, overridable only via `BackendLoadOptions.sessionTimeoutMs`). A session that arrives late is released; + - `new Engine(...)` checks the graph contract; + - `warmup`: one `engine.evaluate(WARMUP_STATE, WARMUP_QUESTIONS)`, timed as `warmupMs`. On WebGPU a second pass is timed for latency, because the first pass compiles pipelines. The result seeds `status.latency = {p50=p90=ms, n:0, tokensP50, msPerToken, source:"warmup"}`; + - await all Cache Storage writes, then `ready` with `loadMs`, `bytes`, `fromCache` and `attempts` (if any). +9. If the backend is disposed mid-load, `ModelLoadError("disposed while loading")` is thrown at the start of the next plan or right after the warm-up (the engine is released); it is not recorded as an attempt. Otherwise a plan that throws is pushed to `attempts`, and the next plan is tried. Exception: a `StepTimeoutError` on WebGPU **inside a worker** throws `ModelLoadError("WebGPU did not come up (...); not trying further plans in this worker")`, because ORT may be wedged in WebGPU. Inline, the remaining plans continue. +10. If every plan fails, it throws `ModelLoadError("no plan could run the model: <variant>/<device>: <error>; ...", attempts)`. Any error goes through the outer catch, which emits `{state:"error", error, worker, model?, version?, gpu?, attempts?}` and rethrows. Non-`ModelLoadError` errors (integrity, unsupported tokenizer, ...) are wrapped in a `ModelLoadError` with the same message. +11. `finally`: `delete ort.env.wasm.wasmBinary`, which drops the ~25 MB reference once ORT has instantiated the wasm. + +### 4. Host reaction to statuses and WebGPU recovery (`host.ts` -> `onMessage`, `retryOnWasm`) + +1. `hello`: marks the worker alive and clears the hello timer. +2. `status`: + - If `state === "error"` and `retryOnWasm(status)` returns true, the error is swallowed and a retry starts. + - Otherwise `setStatus({...status, worker: <transport is worker>, attempts: priorAttempts + status.attempts, workerError?})` notifies listeners. On `ready` it resolves the `ready()` waiters. On `error` it rejects them with `ModelLoadError(error, attempts)`. Then `armStallWatch()`; on `ready` or `error`, `pump()`. +3. `retryOnWasm` runs at most once per host (`wasmRetried`), and only when all of these hold: + - the transport is a worker; + - `loadOptions.device !== "wasm"`; + - some attempt has `device === "webgpu"`. + + It closes the worker, keeps `priorAttempts`, and starts a fresh worker (or inline, `workerError: "could not start a second worker"`) with `{...loadOptions, device:"wasm"}`. Its triggers are a worker error status, a worker crash after `hello` while `loading` on WebGPU, and a stall (which adds a `{device:"webgpu", error:"stalled"}` attempt when it happened on WebGPU, so it retries on WebGPU or after any earlier WebGPU attempt). +4. `onWorkerCrash(why)` (crash after `hello`, or a stall, when not retried): + - closes the transport, sets `started = false` (so `load()`/`ready()` can start a new worker), and sets status `{state:"error", error, worker:true}` where `error` is `why` itself when it already starts with `"the model worker"` (the stall message), else `"the model worker crashed: <why>"`; + - rejects the running job with `ModelLoadError`, and queued jobs and pending `measure`s with `ModelNotReadyError`. +5. `load()`: + - after `error` with a live transport, it re-sends `load` with the same options (status back to `loading`); + - after a crash (no transport), it calls `ready()`, which starts a new worker; + - otherwise it is the same as `ready()`. +6. `ready()`: rejects with `ModelDisposedError` after dispose, and immediately with `ModelLoadError` when `state === "error"` and the load was started. Otherwise it waits and starts the load. + +### 5. Evaluate path (host -> worker -> engine) + +1. `host.evaluateDetailed(req)`: + - increments `stats.requests`; + - if not `ready`: `stats.notReady++`, `start()`, reject `ModelNotReadyError` with message `"the GenClass model is not loaded"` / `"... is still loading"` / `"the GenClass model failed to load: <error>"` (measured in Chromium at < 1 ms); + - otherwise `state = toJsonValue(req.state)` (a throw is a `ModelInputError`); + - creates a `Job {id, seq, priority: Number(req.priority ?? 0) || 0, ...}` with a timer of `req.timeoutMs ?? opts.timeoutMs ?? 10_000`. +2. Queue admission: if `queue.length >= maxQueue` (default 32; the running job is not counted), the victim is the lowest-priority, oldest request among the queue and the new job. With equal priorities that is the oldest queued job, not the newcomer. + - If the victim is a queued job, it is removed and rejected with `ModelBusyError`. + - If the victim is the newcomer, it is rejected with `ModelBusyError` only when a job is running. Otherwise it is queued anyway, exceeding `maxQueue`. + + Each rejection increments `stats.busy`. +3. `pump()`: if `ready` and nothing is running, it picks the highest `priority` (then lowest `seq`), skips settled jobs, and posts `evaluate`. A `postMessage` throw (e.g. `DataCloneError` for functions in `questions`) rejects the job with `ModelInputError`. If the status is `error`, all queued jobs are rejected with `ModelNotReadyError`. +4. `timeout(job)`: `stats.timeouts++`. A queued job is removed and never computed. A running job is rejected, but **keeps the slot** until the backend answers (one inference at a time). +5. Worker side: `backend.evaluate` -> `Engine.evaluate(state, questions)`: + 1. `Engine.logits` is serialised per session through a promise chain (`serial`). + 2. `packer.pack(state, questions)` -> `{packed, blocks}`. Every block's kind must be one of the model's `heads`, else `ModelUnsupportedError`. + 3. `feeds(packed)`: for each declared input name, `FEEDS[name](packed, planInputs(packed))` -> `BigInt64Array` int64 `Tensor`s. + 4. `session.run(feeds)`; a throw becomes `ModelInferenceError`. Each declared output `*_logits` is converted by `tensorFloats` (float32 / float64 / float16; float16 `Uint16Array` is decoded by `halfToFloat`). + 5. `unpackLogits(packed, heads)` gives raw logits per qid in request order. For noul it is 1 value (row g). For choice and score it is the first `labels.length` columns of row g of a `[nQ, K]` tensor. + 6. Input and output tensors are `dispose()`d. + 7. Per block: `calibrateLogits(kind, headerKey(header), logits, calib)`, then `buildAnswer(question, probs, "exact", labels)`. + 8. It returns `usage = {input_tokens: inputIds.length, positions: max(positionIds)+1}` and `timings = {pack, forward, total}` (ms, via the injected clock). +6. Host `result`: + - a late result for a timed-out job just frees the slot; + - an OK result increments `stats.completed`, sets `lastMs` (wall time including the queue) and `lastForwardMs`, calls `recordLatency`, and resolves; + - an error result increments `stats.failed` and rejects with `deserializeError(error)`; + - then `pump()`. +7. `recordLatency`: + - keeps a window of the last 20 `{ms: timings.total, tokens: usage.input_tokens}` samples; + - nearest-rank `p50`/`p90` (`a[ceil(p*n)-1]`), `tokensP50`, and `msPerToken` (median of ms/token, 3 dp), with `source:"evaluations"`; + - `p50`/`p90` are rounded to whole ms; `tokensP50` is not rounded; + - listeners are notified on the first sample and then at most every 5 s. Otherwise `status.latency` changes silently; + - the window is emptied whenever a new transport starts (`useWorker`/`useInline`, so also after a WASM retry). Until the first evaluation, `status.latency` is the backend's warm-up estimate (`source: "warmup"`, `n: 0`), absent when `warmup: false`. + +### 6. Packing and text (`serialize.ts`, `tokenizer.ts`, `packer.ts`) + +Full contract with examples: [model-io-contract.md](../model-io-contract.md). In brief: + +1. `stateSegments(state)` runs `toJsonValue` first: `undefined` keys vanish, NaN/Infinity become `null`, Dates become strings, BigInt and cycles throw `ModelInputError`. A `Map` survives (ordered) only at the top level or as a value of another `Map`; a `Map` nested inside a plain object or array goes through `JSON.stringify` and becomes `{}`. Then: + - an object state gives one segment per key. String arrays are joined with `"\n"`; everything else goes through `entryText`; + - an array state gives `[i]` segments for the first 64 items (`MAX_ARRAY_SEGMENTS`), plus a `[64:]` overflow segment; + - a string gives one segment with key `""`, stripped; + - `null` -> `"None"`, booleans -> `True`/`False`, numbers -> `pyNumber`. + + `segmentText(s) = key ? "key: text" : text`. +2. `entryText` renders individual values: + - strings are `pyStrip`ped (Python `str.strip()` whitespace set, not JS `trim`); + - string arrays become `"; "`-joined non-empty entries; + - other arrays and nested values become `pyJson` (`json.dumps` with `", "` / `": "` separators, `ensure_ascii=False`); + - objects become `"k: v | k2: v2"`; + - numbers print like Python after a JSON round trip (`pyNumber`: ints stay ints, floats use `repr` with exponent form when exp < -4 or >= 16). +3. `questionBlock(qid, q)`: + - `noul`: header = instructions or `DEFAULT_NOUL_INSTR`; items = [true criterion or `"yes"`, false criterion or `"no"`]; labels `["true","false"]`; + - `choice`: items are `"label"` when the description is null, empty or equal to the label, else `"label: desc"`. Labels keep criteria order (use a `Map` to keep integer-like labels in order); + - `score`: items are the level texts; labels are `"0".."n-1"`. + + Question ids are never shown to the model. +4. `Tokenizer.encode(text)`: HF `tokenizers` byte-level BPE, as `encode(text, add_special_tokens=False)`. Order in code: `splitAdded(normalize(text))`, then `encodePiece` per remaining piece. + - Special added tokens (`[CLS]`, `[Q]`, ...) are **never** matched in text, so user text cannot forge a marker. + - The normalizer (NFC/NFD/NFKC/NFKD/Lowercase/Sequence; ASCII-only text skips the Unicode forms) runs first, on the whole text. + - Then non-special added tokens are split out of the normalized text (scan left to right, longest match at each position), keeping their own ids. + - Each remaining piece goes through the GPT-2 ByteLevel regex (with `\p{White_Space}`), bytes-to-unicode, and heap-based merges as in `Word::merge_all`. + - Nothing is hardcoded: the vocab, ids and merges all come from the file. + - `pre_tokenizer.add_prefix_space` and `use_regex`, and `model.ignore_merges`, are honoured. Words are cached (`cacheSize` 20000, cleared when full). + - The constructor throws `ModelUnsupportedError` for: a model type other than `BPE`; BPE `dropout`; `continuing_subword_prefix`/`end_of_word_suffix`; a non-special added token with `lstrip`/`rstrip`/`single_word`; any id >= `ID_SPACE` (2^26); a missing byte-level token for a byte that can occur in UTF-8; a malformed merge or one referring to a missing token; a normalizer other than NFC/NFD/NFKC/NFKD/Lowercase/Sequence; a missing pre-tokenizer or one other than ByteLevel (or a one-element Sequence of it). + - Other methods: `count(text)`, `decode(ids)` (byte-level; for logs and tests), `tokenId(s)` (added tokens first, then vocab), `vocabSize` (max id + 1). +5. `Packer.pack(state, questions)` builds: + ``` + [CLS] seg_0 [SEP] seg_1 [SEP] ... | [Q] header_0 | [O] item_00 | [O] item_01 | ... | [Q] header_1 | ... + ``` + - Item markers: `[O]` for choice, `[L]` for score, `[T]`/`[F]` for noul. + - Positions restart per branch: the header is at `S..`, and every item at `S+len(header)..`. + - `q_group` is -1 for state tokens, else the question ordinal. `i_group` is -1 for state and header tokens, else the item ordinal. + - Limits: + - `stateTokens + max_q(len(header_q) + longest item_q) <= maxPositions` (`meta.max_len`, default 1536); + - `total <= maxTotal` (`meta.max_total`, default 8192); + - otherwise `MaxTokensExceededError`. + - Marker, CLS and SEP ids come from `meta.json` and must equal the tokenizer's (`ModelUnsupportedError` on mismatch), or from the tokenizer alone. +6. `planInputs` gives the marker indices per head. A kind with no question gets a dummy row at token 0. Items are padded to `k` with 0. +7. `Packer.measure(state, questions?)` returns `{stateTokens, positions, total}` without building the sequence (exposed as `host.measure`). It never throws `MaxTokensExceededError`; compare the result with `meta.max_len`/`max_total` yourself. Without `questions`, `positions = total = stateTokens` (which counts `[CLS]` and every `[SEP]`). + +### 7. Calibration (`calibrate.ts`) + +`parseCalibration` applies defaults `{noul:1, choice:1, score:1, by_header:{}}` and requires positive per-kind temperatures and an object `by_header` (else `ModelUnsupportedError`). The v2 keys (`by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp`) and `version` are passed through **unvalidated**: a non-numeric v2 value is not caught at load; it yields NaN probabilities, which `buildAnswer` silently turns into a uniform distribution (choice/score) or 0.5 (noul). + +| key | version | meaning | +|---|---|---| +| `noul`, `choice`, `score` | v1 | per-kind temperature | +| `by_header` | v1 | `sha1(header)[:12]` -> tau (`headerKey`, pure-TS SHA-1, cached up to 4096 headers) | +| `by_bucket` | v2 | `"<kind>:<bucket>"` -> tau; buckets `K_BUCKETS` = 2, 3-5, 6-10, 11-30, 31-100, 101-255 (K > 255 uses `101-255`) | +| `tau_k` | v2 | `{choice:[a,b], score:[a,b]}`: tau = a + b·ln(max(K,2)), clamped to `bucket_clamp` (default `BUCKET_CLAMP` = [0.5, 5.0]) | +| `noul_platt` | v2 | `{a,b}`: p = sigmoid(a·z + b) | + +Lookup order: +- choice/score: `by_header`, then `by_bucket`, then `tau_k`, then the per-kind value. The probabilities are a softmax of logits/tau. +- noul: `by_header` (as a = 1/tau, b = 0), then `noul_platt`, then (1/`noul`, 0). + +`buildAnswer` (with `Precision` `"exact"`, the engine's default; `"round"` = 2 dp half-even like the Jev server). `EngineOptions.precision` exists, but `ModelBackend.createEngine` never sets it, so host answers are always `"exact"`: +- noul: `{noul: clip01(p)}`, where a non-finite `p` becomes 0.5; +- choice: `normalizeProbs` (clip, drop non-finite, renormalise, uniform if all zero). `choice` is the argmax (ties go to the first label), `confidence = clip01((K·pmax − 1)/(K − 1))`, and `probabilities` is in label order; +- score: `score = Σ i·p_i`, `confidence = max(0, 1 − Σ p_i·|i − mode| / MAD_uniform(K))`, `probabilities` keyed `"0".."n-1"`. + +### 8. Dispose + +`host.dispose()` cancels the idle scheduling and the hello and stall timers, and rejects the running job, queued jobs, `measure`s and `ready()` waiters with `ModelDisposedError`. It then closes the transport (worker: posts `dispose` then `terminate()`; inline: `backend.dispose()`), sets status `{state:"off"}`, notifies listeners once, and clears them. Every later call rejects with `ModelDisposedError`. + +### When the default model URL 404s (the alpha today) + +The trained runtime model is not published. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/`, and OPEN_TASKS item 8 ("publish the trained model as `@genclass/runtime-model@0.1.0`") is still under "Next". The README of `packages/runtime` says the alpha "observes and records but does not act yet". Traced through the code, a default `GenClass.init()` in a browser does the following. The HTTP status itself is assumed, not fetched. + +1. The host is created with `preload: "idle"`, so the status is `off`. Until the idle start, triggers compute facts. A salient one calls `void this.ready`, which starts the load early, and runs the passive action. +2. The worker starts and posts `hello`. `doLoad` sets phase `card`, starts the WebGPU probe, and fetches `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json` (`cache:"no-cache"`). The probe is not cancelled when the card fails: on a WebGPU-capable browser it still requests an adapter and creates and destroys a device; its result is discarded. +3. The fetch returns a 404, so `fetchCard` throws `ModelLoadError("model card download failed: HTTP 404 for <url>")`. The Cache Storage has no copy, so the error is rethrown. **No ORT bundle, ORT wasm, tokenizer or ONNX file is downloaded**, because those steps come after the card. The only network traffic is the worker chunk(s) and `model.json`. If the request fails without a response instead (offline, CSP `connect-src` blocking jsDelivr, CORS), the message is `model card download failed for <url>: <fetch error message>` and the rest is identical. With `worker: false` or the inline fallback, the same happens on the main thread with `worker: false` in the status. +4. The backend emits `{state:"error", error:"model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json", worker:true}`, with no `attempts` and no `gpu`. +5. Host: `retryOnWasm` returns false (no WebGPU attempt), so `setStatus(error)` runs and `ready()` waiters reject with `ModelLoadError`. The worker is **not** terminated; it stays idle until `dispose()`. +6. Runtime: the console shows `[GenClass] Model unavailable (model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json); observing only.` (via `console.info`, only with `report: "console"`), and a `"status"` event fires. The devtools overlay shows "Model unavailable" with `observing only · <error>` (`packages/runtime/src/devtools/index.ts` -> `renderStatus`). +7. From then on `consultable()` is false. Every trigger takes the passive action immediately; no situations, decisions or detections are produced, and nothing is held. Observers, tracing and baselines keep running. +8. `rt.ask()` / `rt.decide()` reject with `GenClassUnavailableError("error", "the model failed to load: ...")`. Exception: with `opts.timeoutMs` set, `ask` awaits `Promise.race([wait, to])` without wrapping, so the raw `ModelLoadError` propagates instead. The runtime caches its `ready` promise and has no public reload. Only a direct `createModelHost` user can call `host.load()` to retry. The next page load tries the card again. +9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` release may not exist either (unverified), so pass `--from` explicitly. + +### CLI (`packages/runtime/bin/genclass-runtime.mjs`) + +``` +genclass-runtime fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet] +genclass-runtime info <dir> +``` +- Flags: `--key value` or `--key=value`. `--force` and `--quiet` are booleans. `-h`/`--help` or no command prints usage. Unknown `--flags` are accepted silently (and consume the next argument as their value). Exit code 2 for a `UsageError` (unknown command, missing dir, flag without a value, variant not in the card), 1 for other errors (including a `--from` that is not an absolute URL, and any card error from the CLI's `parseCard`, which throws plain `Error`s) and for `info` finding missing or invalid files. +- No environment variables are read. Files are processed sequentially. +- **`fetch-model`** steps: + 1. `--from` defaults to `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. A trailing slash is ensured. + 2. `--variant` defaults to `all` and accepts a comma-separated list of card variant names. + 3. Fetches `model.json` (Node `fetch`, `redirect:"follow"`, user-agent `genclass-runtime-cli`) and parses it with a JS copy of `parseCard`. + 4. For the 3 role files and the chosen variants: a valid local copy is kept unless `--force` is given. A local copy is valid when it matches the card's sha256, or its size when the card has no hash. A card with neither always re-downloads. + 5. Downloads stream into `<file>.part-<pid>` with a per-file percentage on a TTY's stderr (only when the size is known; suppressed by `--quiet`). The size and sha256 are checked **before** the `rename` to `<file>`, so a bad file never replaces a good one; the part file is removed on any failure. `safeJoin` refuses paths outside `<dir>`. A failed download aborts the command before `model.json` is written. + 6. Scans each fetched variant's graph (`graphNote`) and prints a `warning:` line on stderr (`console.warn`, not silenced by `--quiet`) only when the graph has fp16 tensors but the card lacks `"needs": "shader-f16"`. + 7. Keeps variants from an earlier `model.json` with the same name and version that are still valid on disk. + 8. Writes `<dir>/model.json` in `genclass-runtime-model/1` format: `{format, name, version, license?, variants, files, source}`, with each file's actual `bytes` and `sha256`, and variants in source-card order. +- **`info`**: + 1. Prints `name version (license) [format]`. + 2. Checks every variant (marked `*` when it has `needs`) and role file: `MISSING` / `SIZE MISMATCH` / `SHA256 MISMATCH` / `sha256 ok` / `present (no hash in card)`. + 3. Prints `meta` (`max_len`, vocab count, merges count, markers) and the graph inputs and outputs. + 4. Scans each variant's ONNX graph (`scanOnnx`: a dependency-free protobuf walk counting fp16 initializers (dtype 10), int8 initializers (dtype 3), `Cast to=FLOAT16` nodes and fp16 constants, recursing into `If`/`Loop` bodies). Prints `graph <variant> <ops>; <fp16 summary>` with counts of `MatMulNBits`, `MatMul`, `Gather`, `GatherBlockQuantized`, `MatMulInteger`, `DynamicQuantizeLinear`, and a `WARNING` line when a graph uses fp16 but the card lacks `"needs": "shader-f16"` (the card rule). The warning does not change the exit code. +- The CLI's `parseCard` is a copy of `loader.ts` -> `parseCard` with two differences: `bytes` is only `Number(...)`-converted (not checked to be a non-negative integer), and errors are plain `Error`s rather than `ModelUnsupportedError`. + +## Configuration and constants + +| name | type | default / value | defined in | effect | +|---|---|---|---|---| +| `ModelOptions.baseUrl` | string | `DEFAULT_MODEL_BASE_URL` = `"https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/"` | `types.ts` / `host.ts` | model directory (holds `model.json`); resolved against `location.href` (`resolveBaseUrl`), trailing `/` added by `normalizeBaseUrl` in the backend | +| `ModelOptions.device` | `"auto"\|"webgpu"\|"wasm"` | `"auto"` | `host.ts` constructor | plan selection (see `planOrder`) | +| `ModelOptions.worker` | boolean | `true` | `host.ts` -> `start` | `false` = inline on the main thread | +| `ModelOptions.preload` | `"eager"\|"idle"\|"lazy"` | `"idle"` | `host.ts` constructor | when the load starts | +| `ModelOptions.ortWasmPaths` | string | jsDelivr `ortCdnBase(version)` = `https://cdn.jsdelivr.net/npm/onnxruntime-web@<v>/dist/` | `backend.ts` | prefix for the ORT `.wasm` (resolved against `location.href`). It must serve the file of the build in use: `ort-wasm-simd-threaded.wasm` when `ortBuild` is `"wasm"`, `ort-wasm-simd-threaded.asyncify.wasm` when `"webgpu"`. If our prefetch fails, ORT is given the same prefix as `env.wasm.wasmPaths` | +| `ModelOptions.cacheName` | string | `DEFAULT_CACHE_NAME` = `"genclass-runtime-v1"` | `loader.ts` | Cache Storage bucket | +| `ModelHostOptions.timeoutMs` | number | `DEFAULT_TIMEOUT_MS` = 10_000 | `host.ts` | per-request deadline (queued or running); `req.timeoutMs` overrides | +| `ModelHostOptions.maxQueue` | number | `DEFAULT_MAX_QUEUE` = 32 | `host.ts` | waiting requests (excluding the running one) | +| `ModelHostOptions.maxThreads` | number | 4 | `backend.ts` -> `configureOrt` | WASM thread cap (only with `crossOriginIsolated`, in a worker) | +| `ModelHostOptions.warmup` | boolean | `true` | `backend.ts` | `false` skips the warm-up (tests). Then `warmupMs` and `latency` are absent, so the runtime's automatic hold budget is 300 ms (`HOLD_FALLBACK_MS`) until it has its own samples | +| `ModelHostOptions.helloTimeoutMs` | number | `HELLO_TIMEOUT_MS` = 15_000 | `host.ts` | worker start-up budget before the inline fallback | +| `ModelHostOptions.loadStallMs` | number | `LOAD_STALL_MS` = 180_000 | `host.ts` | silence while loading = stuck worker | +| `ModelHostOptions.fetch` / `clock` / `workerFactory` / `ortLoader` / `probeGpu` | — | native fetch / `browserClock` / real Worker / dynamic import / `probeWebGPU` | `host.ts` | injection points (runtime passes `fetch`, `clock`; tests pass the rest) | +| `BackendLoadOptions.sessionTimeoutMs` | `{webgpu?, wasm?}` | webgpu 60_000, wasm 180_000 | `backend.ts` -> `createEngine` | session-creation timeout; **not settable through the host** | +| `IDLE_TIMEOUT_MS` | ms | 2_000 (`requestIdleCallback` timeout); fallback timer `IDLE_TIMEOUT_MS / 2` = 1_000 | `host.ts` | idle preload | +| `LOAD_EVENT_WAIT_MS` | ms | 5_000 | `host.ts` | idle preload waits at most this long for `load` | +| `LATENCY_WINDOW` / `LATENCY_EMIT_MS` | n / ms | 20 / 5_000 | `host.ts` | `status.latency` window / notify rate | +| `PROGRESS_STEP_MS` | ms | 100 | `backend.ts` | progress status throttle | +| ORT env and session settings | — | `env.wasm.numThreads` = threads, `env.wasm.proxy = false`, `env.logLevel = "error"`; `InferenceSession.create(bytes, { executionProviders: [device], graphOptimizationLevel: "all" })` | `backend.ts` -> `configureOrt`, `createEngine` | fixed; not configurable | +| fetch cache modes | — | card: `cache: "no-cache"` (revalidate); every other file: `cache: "no-store"` | `loader.ts` -> `fetchCard`, `fetchFile` | Cache Storage is the only cache for model and wasm files | +| `Engine` defaults | — | `precision` `"exact"`; `name` = `"<card.name>@<card.version>"` (set by the backend; becomes `EvaluateOk.model`); `device` `"wasm"`, `variant` `"q8"` when not given | `engine.ts` constructor | host answers are never rounded | +| `headerKey` cache | number | cleared when it exceeds 4096 headers | `calibrate.ts` | SHA-1 cost per header | +| `ORT_FALLBACK_VERSION` | string | `"1.30.0"` | `backend.ts` | CDN path if ORT reports no version | +| `ORT_WASM_FILES` | record | `webgpu: "ort-wasm-simd-threaded.asyncify.wasm"` (27 MB, 5.5 MB br), `wasm: "ort-wasm-simd-threaded.wasm"` (14 MB, 3.1 MB br) | `backend.ts` | wasm file per ORT build (sizes from code comments) | +| `probeWebGPU` `timeoutMs` | ms | 5000 each for `requestAdapter` and `requestDevice` | `loader.ts` | probe never throws | +| `CARD_FORMAT` | string | `"genclass-runtime-model/1"` | `loader.ts`, CLI | card format tag | +| cache headers | string | `x-genclass-sha256`, `x-genclass-tag` | `loader.ts` (`H_SHA`, `H_TAG`) | cache-entry validity | +| `meta.max_len` -> `Packer.maxPositions` | number | 1536 if absent | `engine.ts`, `packer.ts` | positions budget (final round 1 trains with `--max-len 2048`, `training/launch_final1.sh`; the stage-2 pilot used it too) | +| `meta.max_total` -> `Packer.maxTotal` | number | 8192 if absent | `engine.ts`, `packer.ts` | whole-sequence budget | +| `Packer` `cacheSize` | number | 8192 texts (cleared when full) | `packer.ts` | encode cache | +| `Tokenizer` `cacheSize` | number | 20000 words (cleared when full) | `tokenizer.ts` | BPE word cache | +| `ID_SPACE` | number | 2^26 | `tokenizer.ts` | max token id + 1 allowed | +| `MAX_ARRAY_SEGMENTS` | number | 64 | `serialize.ts` | array state items before `[64:]` overflow | +| `DEFAULT_NOUL_INSTR` / `DEFAULT_CHOICE_INSTR` / `DEFAULT_SCORE_INSTR` | string | `"Is the statement true of the state?"` / `"Which option best fits the state?"` / `"Which level best describes the state?"` | `serialize.ts` | header when instructions are empty | +| `K_BUCKETS` / `BUCKET_CLAMP` | — | `[2,2],[3,5],[6,10],[11,30],[31,100],[101,255]` / `[0.5, 5.0]` | `calibrate.ts` | v2 calibration | +| CLI `DEFAULT_FROM` | string | `"https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/"` | `bin/genclass-runtime.mjs` | `fetch-model` source | +| Runtime-side (context only) | — | `DeciderQueue` `PROVIDER_TIMEOUT_MS` 10_000, `MAX_QUEUE` 32, answer cache 64 entries / 30 s; `BACKGROUND_DEADLINE_MS` 5000; `LATE_REVERT_MS` 2000; hold budget clamp 150..800 ms (fallback 300) | `decide/decider.ts`, `runtime.ts`, `decide/policy.ts` | see [decide-policy-actions.md](./decide-policy-actions.md) | + +Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` are typed on `InitOptions.model` (`ModelOptions` in `types.ts`). `makeHost` spreads the object into `createModelHost`, so other `ModelHostOptions` keys pass through at runtime but are not typed for `GenClass.init`. + +## Invariants and gotchas + +- **Parity with Python is load-bearing.** The model was trained on text from `jev_local/serialize.py` (via the sim's JSON rows) and the Python `Packer`. Changing any of the following changes what the model sees and needs retraining plus a new `situation-v1`-style freeze. Coordinate with TRAIN and SIM (see [training.md](../training.md), [sim.md](../sim.md)): + - rendering in `serialize.ts` or `pyutil.ts` (number formatting, whitespace, separators, `True`/`None`, `[SEP]` placement); + - BPE behaviour; + - the packer layout (position restarts, groups, marker choice). +- **Per-header calibration is keyed on the exact instruction text** (`sha1(header)[:12]`). Rewording a standing question in `packages/runtime/src/situation/questions.ts` silently falls back to bucket or kind temperatures. +- **JS cannot emit Python float literals** like `25.0` (`pyNumber(25)` = `"25"`). That is why training/NEEDS.md item 8 asks the curriculum to write integral floats as ints. +- **The public `stateText`** (`packages/runtime/src/situation/serialize.ts`, used by `explain()`) is a human rendering (indented list items). It is *not* the token text: the packer uses `model/serialize.ts` -> `segmentText` with `[SEP]` between segments. `model/serialize.ts` also has a `stateText`, which is internal. +- **Nothing about the vocabulary is hardcoded.** Marker, CLS and SEP ids come from `meta.json` (checked) or `tokenizer.json`, so pruned vocabularies (16,364 tokens, markers 16359-16363) work unchanged. Keep it that way (CONTRACT §13). +- **Graph contract:** + - The session's inputs must equal `meta.inputs` as a set, and each must be a key of `FEEDS`. + - Every `meta.outputs` entry must be a graph output, and at least one must be a known head. + - A question kind without its head fails per request with `ModelUnsupportedError`; the load still succeeds. +- **One inference at a time**, enforced in two places: the host (`running`) and `Engine.serial`. A request that times out while running keeps the slot. A forward pass that never returns therefore blocks every later request, which all time out, and there is no watchdog after load. The runtime's `DeciderQueue` also runs one at a time, so in practice the host queue holds at most a few jobs. +- **Worker vs inline differences:** + - Inline runs on the main thread (jank) and always uses 1 WASM thread: ORT pthreads would start from the app bundle URL. + - Inline does not structured-clone, so `questions` containing functions work inline but fail in the worker with `ModelInputError`. + - Inline WebGPU timeouts do not stop the remaining plans. +- **The worker and the onnxruntime threads:** `worker.ts` must stay inert when `self.name` starts with `em-pthread` or equals `ort-wasm-proxy-worker`. Removing that guard spawns nested backends. +- **`hello` is posted before ORT is imported** (ORT is a dynamic import on `load`). The 15 s hello timeout therefore only covers fetching and evaluating the worker chunk. +- **Stall vs session timeout:** `LOAD_STALL_MS` (180 s) equals the WASM session timeout (180 s), and no status is posted during session creation. On a very slow WASM session the host's stall watchdog and the backend's step timeout fire at about the same time. +- **The WASM retry happens once per host lifetime** (`wasmRetried` is never reset). +- **A worker crash after `ready` is usually permanent for the runtime.** A worker `error`/`messageerror` event after `hello` moves `ready` -> `error` (`onWorkerCrash`), rejects the running job with `ModelLoadError` and queued jobs with `ModelNotReadyError`. The runtime never calls `host.load()`, and triggers stop consulting in `error`. The one exception: `RuntimeImpl`'s `ready` getter calls `decider.ready()` only on its first read and caches the promise. If nothing had read `rt.ready` before the crash (no salient trigger while `off`, no `rt.ask()` while not ready, no app read), the first `rt.ask()`/`rt.decide()` or app read of `rt.ready` afterwards calls `host.ready()`, which starts a fresh worker because `started` was reset. Otherwise the runtime observes only until the page reloads. +- **`warmupMs` is the first warm-up pass; `status.latency` is the second on WebGPU.** The first WebGPU pass includes pipeline compilation, and the runtime seeds its automatic hold budget from `status.warmupMs` (`decide/policy.ts` -> `holdBudget`: clamp(1.5 × warmupMs, 150, 800)) until the decider queue has real latency samples. On WebGPU the seed is therefore pessimistic (likely the 800 ms cap; not measured). +- **After a load error the worker stays alive** (only a crash closes the transport), so `load()` can retry cheaply. After a crash `started` resets, so `ready()`/`load()` (and also `evaluate()`/`measure()`, which call `start()` while not ready) start a fresh worker. +- **The card is revalidated on every load** (`cache:"no-cache"`): one network request per page load, even when everything else is cached. Offline, the cached card is used. +- **Cache validity:** + - Files with a card sha256 are valid when the stored `x-genclass-sha256` header matches (and the size matches when known). + - Files without a hash (v0.1 extension card, ORT wasm) are valid when the `x-genclass-tag` header matches: `name@version` for model files, `onnxruntime-web@<version>` for the wasm. So a changed file under the same version is not refetched. + - Invalid entries are deleted and refetched. **Old versions are never evicted** (they live under other URLs in `genclass-runtime-v1`). + - Quota errors on `cache.put` and missing or blocked Cache Storage degrade to network-only. An opaque or non-200 **cached** entry is treated as invalid (deleted and refetched). An opaque **network** response is not a degradation: `fetchFile` throws `ModelLoadError("download of <url> returned an opaque (no-CORS) response")`. +- **Downloads are not retried** within a load. A failed variant download is memoised, so every plan that uses that variant fails in the same load. A new `load()` starts over (cached valid files are reused). +- **Integrity failures surface as `load_failed`**, not `integrity`, at the host. Small files: the `ModelLoadError` message carries the checksum or size text. Variants: the text is in `attempts[].error`. +- **Never use the instrumented fetch.** + - The worker uses its own realm's `fetch`, and the inline path uses `NATIVE_FETCH`, so GenClass never observes its own downloads. + - The ORT wasm is prefetched and handed over as `wasmBinary` so ORT never fetches it (offline second loads). + - Worker `error` events are `preventDefault`ed so they never reach the app's error handlers. +- **Thread count:** WASM threads need a `crossOriginIsolated` page (COOP/COEP) *and* the worker transport: `min(maxThreads ?? 4, hardwareConcurrency)`. The runtime's automatic situation budget grows with `status.threads`. +- **Self-hosting needs three things served:** the model directory (`baseUrl`), the worker chunk next to the host chunk (bundler output), and the ORT wasm (`ortWasmPaths`, default jsDelivr). Which wasm is fetched depends on the plans: `ort-wasm-simd-threaded.wasm` when no WebGPU plan exists (e.g. `device: "wasm"`, no `navigator.gpu`, software adapter under `"auto"`), else `ort-wasm-simd-threaded.asyncify.wasm`. Serve both. The model files and the wasm are `fetch`ed, so a Content-Security-Policy whose `connect-src` blocks their origin makes the load fail and the runtime observe only; a blocked worker script only triggers the inline fallback (which policy governs the worker's own fetches depends on how the worker script is served; no test covers CSP). +- **`host.stats` is the live counters object**, typed `Readonly` but mutated in place; copy it if you need a snapshot. +- **The v0.1 q8 needs `shader-f16` on WebGPU** (its embedding table is fp16; ORT's WebGPU Gather fails with "Program Gather requires f16"), but its card does not say so. The loader then wastes a `webgpu+q8` session and warm-up before WASM. TRAIN's exports use an int8 embedding table and declare `needs: "shader-f16"` only on fp16. Check with `genclass-runtime info`. +- **Bundling:** + - tsup keeps `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` verbatim; Vite and webpack 5 bundle that pattern. + - Both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")` must stay **static string specifiers** so bundlers split them into separate chunks and a page downloads only one. + - `onnxruntime-web/wasm` is missing from `tsup.config.ts` `external`. It stays external only because `onnxruntime-web` is a `dependency` (tsup externalises dependencies including subpaths). A `tsup` build of 654d822 keeps both as dynamic `import()` calls in `dist/worker.js` and in the chunk `dist/index.js` loads. +- **Determinism:** the host uses the injected `Clock` for timers. `scheduleIdle` uses the global `requestIdleCallback` and `load` event. The sim never uses the model host (it plugs in its own `decider`), so this does not affect training parity. + +## How to change it safely + +The team runs all builds and tests on the remote VM (CONTRACT §0 rule 5). Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the build and unit tests locally. Ask the user before model downloads (`fetch-model`) and Playwright specs ([build-test-release.md](build-test-release.md#where-to-run-things)). Model-file tests read `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) and **skip** when it is absent. Unit tests with fakes always run. + +```sh +node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/ +cd packages/runtime +GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx vitest run test/model +GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/browser/playwright.config.ts +``` +(The commands come from `packages/runtime/src/model/README.md`. Whether that GitHub release serves a `model.json` the CLI can read is unverified.) + +1. **Point at a published model / bump the model version.** + - Edit `DEFAULT_MODEL_BASE_URL` in `host.ts` and `DEFAULT_FROM` in the CLI. + - Update `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, `packages/runtime/README.md`, `packages/runtime-model/MODEL_CARD.md`. + - New URLs or hashes refetch automatically; old cache entries remain. + - Run `genclass-runtime info <dir>` on the published directory (card rule, hashes). + - Tests: `test/model/host.test.ts` (uses its own base URL; no change expected), the browser specs against the new directory. +2. **Ship a different model architecture (R17 vs R32, new export).** No code change is needed if the export follows the card format and `meta.json` declares `inputs`, `outputs`, `markers`, `cls_id`, `sep_id`, `max_len`, `max_total`. + - Make sure `max_len` matches training (2048 for the stage-2 pilot and final round 1). + - Keep the q8 embedding table int8 so `webgpu+q8` works without `shader-f16`. + - Device-based model selection (OPEN_TASKS item 5: R17 for WASM, R32 for WebGPU only if clearly more accurate, "Device-based model selection in the host card") is **not implemented**. It would need card support (e.g. variants per device) plus a `planOrder` change and tests in `loader.test.ts`. +3. **Add a graph input or head.** + - Add a builder to `FEEDS` (`engine.ts`), and a plan field in `planInputs` if needed. + - For a new head, add it to `OUTPUT_KIND`, a `BlockKind`, `questionBlock`, `itemMarkers`, `unpackLogits`, `calibrateLogits` and `buildAnswer`, and the `Question`/`Answer` types in `types.ts`, which form the CORE<->MODEL seam ("change that section only together"). + - Tests: `engine.test.ts` ("engine graph contract"), `packer.test.ts` (feed plan). +4. **Change the WebGPU/WASM plan order or device semantics.** + - Edit `planOrder` (loader.ts). The `ortBuild` choice follows automatically. + - Keep `wasm` as the last plan for `"webgpu"`. + - Tests: `loader.test.ts` "plans: ..." and "ModelBackend load"; `host.test.ts` "WebGPU recovery"; `test/browser/model-webgpu.spec.ts`. +5. **Add a host option.** + - Add it to `ModelHostOptions`. If it must reach the worker, also add it to `BackendLoadOptions` (structured-cloneable values only) and set it in the `Host` constructor's `loadOptions`. + - If apps should set it through `GenClass.init`, add it to `ModelOptions` in `types.ts` (CORE-owned) and document it in CONTRACT §2 and API.md. Example: exposing `sessionTimeoutMs` needs all three. +6. **Add a protocol message.** + - Update `protocol.ts`, `worker.ts`'s switch, `InlineTransport.send` (keep both paths identical) and `Host.onMessage`. + - Every request must get exactly one `result`. + - Tests: `host.test.ts` with `FakeWorker`. +7. **Add or change an error.** + - Update `ModelErrorCode`, the class, and the `deserializeError` switch (otherwise it comes back as a plain `Error`). + - Re-export it from `src/index.ts` and `src/model/index.ts`. + - If the runtime should react specially, see the `max_tokens_exceeded` handler in `runtime.ts`. + - Tests: `host.test.ts` "errors cross the worker boundary". +8. **Change serialization, tokenization, packing or calibration.** + - Only together with the Python side (`jev_local/serialize.py`, `tokenize_pack.Packer`, `calibrate.py`, `confidence.py`), TRAIN and SIM. + - Regenerate the fixtures with `packages/runtime/test/fixtures/model/make_py_fixtures.py`, which needs HF `tokenizers` and runs on the VM. + - Run `serialize.test.ts`, `packer.test.ts`, `calibrate.test.ts`, and `engine.test.ts` with a model directory. + - Expect a model retrain. +9. **Upgrade onnxruntime-web.** + - Update `package.json` (`^1.30.0`) and `ORT_FALLBACK_VERSION`. + - Check `ORT_WASM_FILES` names exist in the new `dist/` (`node_modules/onnxruntime-web/package.json` exports `./wasm`, `./webgpu` and the `.wasm` files) and that `tsup.config.ts` externals still apply. + - Update the browser test regex expecting `onnxruntime-web@1.30.x`, and `onnxruntime-node` in devDependencies (pinned `1.30.0`) for parity tests. + - Re-measure latency and transfer (Playwright writes `test-results/model-bench/{latency,transfer}.json`). +10. **Change the CLI.** Keep its `parseCard` in sync with `loader.ts` `parseCard` (same file-name safety rules and defaults). There are no automated CLI tests: verify on the VM with `fetch-model` and `info` against a real directory. +11. **Self-host everything (app integration; derived from the code).** + - `npx genclass-runtime fetch-model public/genclass-model --from <a directory URL that serves model.json>`. + - Copy **both** `node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` to e.g. `public/ort/` (the plain one is used when no WebGPU plan exists, the asyncify one otherwise). + - `GenClass.init({ model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`. For WASM threads, serve the page with COOP/COEP so it is `crossOriginIsolated`. + - Check: `status.ortBuild`, `status.threads`, `status.fromCache`, and that the network panel shows no jsDelivr requests. + +## Tests + +| test file | what it asserts | +|---|---| +| `packages/runtime/test/model/host.test.ts` | Uses a `FakeWorker` and `FakeClock`. Asserts:<ul><li>lazy preload (evaluate fails open with `not_ready` and starts the load; `ready()` loads)</li><li>idle preload via the timer fallback</li><li>status listeners and `ready()` rejecting with `ModelLoadError` and attempts</li><li>one-at-a-time priority/FIFO order</li><li>queued timeouts are never run, and a running timeout keeps the slot</li><li>full-queue eviction (`ModelBusyError`)</li><li>`status.latency` nearest-rank values and the 5 s notify throttle</li><li>typed errors across the boundary</li><li>state JSON normalisation; `measure`; `dispose`</li><li>a crash after `ready` with a request running rejects it with `ModelLoadError`, becomes an error status, and `load()` makes a fresh worker</li><li>WebGPU recovery: error with a webgpu attempt, death on webgpu, and stall all lead to one WASM-only worker, or an error on WASM</li><li>inline fallback: factory throws, error before hello, hello timeout, `worker:false`</li></ul> | +| `packages/runtime/test/model/loader.test.ts` | <ul><li>runtime and v0.1 card parsing; malformed cards and unsafe names</li><li>`planOrder` matrix (auto/webgpu/wasm × f16/no-f16/software/no GPU)</li><li>`fetchFile` streaming progress, sha256, store and cache hit</li><li>refetch on hash mismatch; size/hash corruption gives `ModelIntegrityError`; a missing file gives `ModelLoadError`</li><li>no Cache Storage and quota failures</li><li>`fetchCard` network vs offline cache</li><li>`ModelBackend` plan fallback, phases, monotonic progress, single ORT wasm fetch, `wasmBinary` released, answers, `measure`</li><li>second load needs only `model.json` from the network</li><li>v0.1 card</li><li>a WebGPU session timeout stops the remaining plans in a worker and continues inline</li><li>error status lists all attempts</li></ul> | +| `packages/runtime/test/model/engine.test.ts` | <ul><li>parity vs PyTorch on the 50 harness requests: onnxruntime-node q8/fp16 and onnxruntime-web WASM q8 (12 requests); against the export's `parity.json` when present. Needs `GENCLASS_MODEL_DIR`</li><li>graph contract: feeds exactly the declared inputs, rejects unknown or mismatched inputs, a missing head gives `ModelUnsupportedError`</li></ul> | +| `packages/runtime/test/model/packer.test.ts` | <ul><li>identical ids, positions, groups and marker positions vs Python</li><li>plain-object vs Map criteria</li><li>special tokens in text stay text</li><li>marker ids from the files, and a meta/tokenizer mismatch throws</li><li>`max_tokens_exceeded` semantics (positions vs total)</li><li>empty choices rejected</li><li>feed plan and unpacking</li><li>tokenizer parity on the full and pruned vocabularies</li><li>encode speed</li></ul> | +| `packages/runtime/test/model/calibrate.test.ts` | <ul><li>SHA-1 header keys vs Python</li><li>SHA-256 (pure TS and WebCrypto) at edge lengths</li><li>calibrated probabilities vs PyTorch (< 1e-9)</li><li>v1/v2 calibration files</li><li>confidence math</li><li>answer building (order, ties)</li><li>lookup and validation</li></ul> | +| `packages/runtime/test/model/serialize.test.ts` | <ul><li>`state_segments` / `question_block` vs Python fixtures</li><li>Python number formatting</li><li>`json.dumps` separators</li><li>`str.strip` whitespace</li><li>JSON round-trip semantics</li><li>situation-shaped states</li><li>`pyRound` half-even</li></ul> | +| `packages/runtime/test/browser/model.spec.ts` (Playwright, Chromium, built library) | <ul><li>WASM worker load, PyTorch parity, status events, Cache Storage second load, transfer sizes</li><li>inline fallback (no `Worker`, missing worker script, no page errors)</li><li>lazy (< 50 ms `not_ready`)</li><li>idle preload</li><li>WebGPU fallbacks (no adapter, an adapter without a device caught by the probe)</li><li>latency benches (1 and 4 threads)</li><li>the default ORT wasm path is jsDelivr `onnxruntime-web@1.30.x`</li></ul> Skipped without a model directory. | +| `packages/runtime/test/browser/model-webgpu.spec.ts` | On SwiftShader WebGPU: `webgpu+q8` without `shader-f16` runs or falls back; embedding variants (`GENCLASS_WEBGPU_VARIANTS`); exported models; `auto` skips a software adapter. | +| `packages/runtime/test/model/helpers.ts`, `test/browser/model-helpers.ts`, `test/fixtures/model/*` | `MODEL_DIR` resolution (both helpers: `GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`). Fixture selection in the Node helpers (`test/model/helpers.ts`): from the model directory when the export ships `requests.json`/`pack_fixtures.json`/`torch_fixtures.json` (plus `parity.json` for `exportParity`), else the v0.1 set in `test/fixtures/model`. The browser helpers always read the v0.1 set (`requests50.json`, `pack_fixtures.json`, `torch_fixtures.json`). Generators: `make_py_fixtures.py`, `make_webgpu_variants.py`. | +| `packages/runtime/test/browser/build.mjs`, `server.mjs`, `playwright.config.ts`, `page/*` | Test infrastructure, no assertions of its own. `build.mjs` (Playwright global setup) builds the library with `npx tsup` (falls back to building `src/model/index.ts` + `worker.ts` alone into `.build/dist` when a tsup entry file is missing, the package build fails, or `dist/index.js` does not mention `createModelHost`), bundles a test app with esbuild, and throws unless a built file contains the `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` pattern, `worker.js` exists, and the worker code holds both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`. `server.mjs` serves the app, `/model/` (`GENCLASS_MODEL_DIR`), `/ort/` (onnxruntime-web's `dist/`, so both wasm files), extra models at `/m/<name>/`, and the same under `/coi/` with COOP/COEP headers for WASM-thread tests. | +| `packages/runtime/test/smoke/smoke.sh` | npm tarball in a fresh Vite app. Uses `model: false`, so it does **not** exercise the model host. | +| `packages/runtime/test/atoms.test.ts` (runtime side) | "provider errors (not ready, too many tokens, timeout, busy) fail open at once": a decider throwing an error with `code` `not_ready` / `max_tokens_exceeded` / `timeout` / `busy` lets the write apply immediately, with no decision and no hold. | +| `packages/runtime/test/budget.test.ts` (runtime side) | `"auto"` situation budget from the model status (webgpu 3,200; wasm 1,000 at 1 thread to 2,000 at 4 threads); `max_tokens_exceeded` shrinks later automatic budgets; hold budget = clamp(1.5 × median latency, or the warm-up time before any, 150, 800), else 300; held requests carry `timeoutMs` = the time left. | + +Environment variables of the model tests: `GENCLASS_MODEL_DIR` (model directory; default `<repo>/.cache-model`; model-file tests skip without it), `GENCLASS_WEBGPU_VARIANTS` (embedding variants for `model-webgpu.spec.ts`), `GENCLASS_BENCH_MODELS` (`name=dir,...`: extra model directories for the per-size latency bench and WebGPU tests), `GENCLASS_OFFLINE` (skips the test that loads the default ORT wasm from jsDelivr). + +No test covers the default-URL 404 end-to-end, the CLI, the runtime's reaction to a host that goes `ready` -> `error` (the host side is covered in `host.test.ts`), or `ModelAbortedError`. The browser tests always serve both ORT wasm files, so a self-hosted `ortWasmPaths` missing one of them is not caught. + +## Drift and open issues + +Mismatches between docs and code (code wins): + +- **The default model is not published.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@<pinned>`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, but `packages/runtime-model/` has no `package.json` or `files/`, and OPEN_TASKS item 8 lists publishing as future work. Result: observe-only (see the 404 flow above). +- **Three different default model sources:** + - host: jsDelivr npm (`DEFAULT_MODEL_BASE_URL`); + - CLI: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` (`DEFAULT_FROM`); + - CONTRACT §10 and `src/model/README.md`: the dev v0.1 model at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. + + `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. Whether the `runtime-model-v0.1.0` release exists is unverified; OPEN_TASKS item 8 lists "attach it to a GitHub release" as future work. +- CONTRACT §10 says "the worker imports `onnxruntime-web/webgpu`". The code imports `onnxruntime-web/wasm` when no WebGPU plan exists, and `/webgpu` otherwise (worker and inline). The same staleness is in `src/model/README.md` "Bundling" ("`dist/worker.js` imports `onnxruntime-web/webgpu`"; "the inline fallback's `import("onnxruntime-web/webgpu")`"). +- CONTRACT §2 and `docs/runtime/API.md` list only `baseUrl`, `device`, `worker` and `preload` for `model`. `ModelOptions` in `types.ts` also has `ortWasmPaths` and `cacheName`. Host-only options (`timeoutMs`, `maxQueue`, `maxThreads`, `helloTimeoutMs`, `loadStallMs`, `warmup`) are untyped through `init`. +- CONTRACT §8 `DecisionProvider.evaluate(req)` lists `{trigger, state, questions}`. `EvaluateRequest` also has `priority`, `subject` (§13) and `timeoutMs`, which the host honours. +- `protocol.ts` comment: `hello` is "posted once when the worker module (and onnxruntime-web) finished loading". In fact ORT is imported later, on `load`. +- `host.ts` comment on `recordLatency`: "for status.latency (adaptive hold budgets and situation sizes)". No runtime code reads `status.latency`. The hold budget uses `DeciderQueue.latencies()` and `status.warmupMs`, and the situation budget uses `status.device`/`threads`. +- `types.ts` comment on `situation.budget` says "wasm 1,100 + 300 per extra thread up to 4 threads: 2,000". `RuntimeImpl.situationBudget` computes `1000 + round((threads − 1) × 1000 / 3)` (1,000 / 1,333 / 1,667 / 2,000), which matches API.md and STATUS.md. +- `MODEL_CARD.md`: + - It says the runtime acts "only when `p(action) ≥ 0.9` (guard tier) / `0.8` (heal tier)". The gate now uses the **summed** probability of the permitted actions (STATUS batch 3, CONTRACT §8). + - Its diagnosis list omits `transient`. + - It describes `calibration.json` as "per-kind temperatures", while the runtime also supports `by_header`, `by_bucket`, `tau_k` and `noul_platt`. +- CONTRACT §10 refers to `/Users/meharkhanna/jev/extension/genclass/src/` (another machine). In this repo the v0.1 card is `extension/src/model/model.json`. +- `packages/runtime/bin/genclass-runtime.mjs` is committed with mode 100644, not executable. A root `npm install` chmods it to 755, which git then reports as a mode change; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. +- CONTRACT §2 comments `device` as "default auto (webgpu+fp16 if shader-f16, else wasm+q8)". `planOrder` also tries `webgpu+q8` between them, and `"auto"` skips software (fallback) adapters. +- CONTRACT §2 says `preload: "lazy"` downloads "only when the first salient situation appears", and §10 says "on the first `evaluate`/`ready`". The host starts on the first `ready()`/`load()`/`evaluate()`/`measure()`; through the runtime that is the first salient trigger, `rt.ask`/`rt.decide`, or any read of `rt.ready`. +- `src/model/README.md` "Self-hosting everything" copies only `ort-wasm-simd-threaded.asyncify.wasm` to `public/ort/`. When no WebGPU plan exists, the backend loads `onnxruntime-web/wasm` and fetches `ort-wasm-simd-threaded.wasm` from `ortWasmPaths`, which that recipe does not provide (code-derived; not tested). Serve both files. +- `tokenizer.ts` header comment describes non-special added tokens as "split out first", with the normalizer applied to "the rest". The code normalizes the whole text first and then splits added tokens (`encode` -> `splitAdded(this.normalize(text))`). For the v0.1 tokenizer (`extension/src/model/tokenizer.json`: normalizer `NFC`, 109 non-special added tokens such as `[unusedN]` and space runs, all ASCII) the two orders give the same result; a tokenizer whose added tokens change under its normalizer could differ. The README parity table reports identical ids on the full and pruned vocabularies (unverified). +- `src/model/index.ts` header comment says `Tokenizer`/`Packer`/`stateSegments` "are exported for token budgeting of situations". Nothing in `src/` imports `model/index.ts`, and situation budgets are in characters (`STATE_CHAR_BUDGET`), not tokens. + +Open items and TODOs relevant to this scope: + +- `rt.ask(q, { timeoutMs })` after a failed load rejects with the raw `ModelLoadError` instead of `GenClassUnavailableError` (`runtime.ts` -> `ask`: the `Promise.race([wait, to])` branch is not wrapped). Without `timeoutMs` it is wrapped. +- A worker crash after `ready` usually leaves the runtime observing only for the rest of the page: the host supports `load()` after a crash, but the runtime never calls it (the only restart path is a first-ever read of `rt.ready` after the crash; see Invariants). +- `ModelAbortedError` (code `aborted`) is defined and exported but never thrown. +- `BackendLoadOptions.sessionTimeoutMs` cannot be set through `createModelHost` or `init`. +- There is no automatic reload after a failed load: the runtime caches `ready` and has no public retry. The idle worker is kept after a load error. +- Old Cache Storage entries are never evicted. +- A hung forward pass blocks the host forever: there is no post-load watchdog. +- Device-based model selection (OPEN_TASKS item 5), publishing `@genclass/runtime-model@0.1.0` plus a GitHub release (item 8), and the shipping model from the final rounds (final round 1 has no results in the repo; training/EVAL.md) are open. +- training/NEEDS.md 6a: situations average about 2.4 characters per token, so `STATE_CHAR_BUDGET` 3200 gives about 1.3–1.4× the intended tokens. TRAIN suggests budgeting with the real tokenizer, which `host.measure` already provides but the runtime does not use. Final-round exports will set `meta.json` `max_len` 2048 (from `--max-len`, which `jev_local/train/train.py` stores in the checkpoint meta that `training/export_runtime.py` copies). +- demos/NEEDS.md §2: one-at-a-time decisions queue up during typing bursts (median 826 ms); the suggestions there concern CORE's queue and hold policy. +- Measured performance (MODEL's numbers in `src/model/README.md`, Chromium on the shared VM, not re-verified): + - v0.1 q8 cold load 1.56–1.94 s from localhost; + - single-thread WASM warm forward at ~1,000 state tokens: R32 1,647 ms, R17 625 ms; + - 4 WASM threads are about 3× faster. + + Single-thread WASM with the 32M model does not fit a 300 ms hold budget. + +## Related docs + +- [public-api-and-lifecycle.md](./public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, `InitOptions.model`, `ready`/`status`, kill switch. +- [decide-policy-actions.md](./decide-policy-actions.md): `DeciderQueue`, hold budget, policy gate, late revert, fail-open handling of provider errors. +- [learn-situation-triage.md](./learn-situation-triage.md): situation building, `STATE_CHAR_BUDGET` / `COMPACT_BUDGET`, `situationBudget`, standing questions. +- [devtools.md](./devtools.md): how the overlay shows model status. +- [build-test-release.md](./build-test-release.md): tsup entries, VM test commands, npm publish. +- [../model-io-contract.md](../model-io-contract.md): situation text -> packed request -> heads -> calibrated answers (runtime, sim, training). +- [../training.md](../training.md): R17/R32 training, `export_runtime.py` (writes `model.json`/`meta.json`), calibration fitting. +- [../genclass-model-lineage.md](../genclass-model-lineage.md): `jev_local` Python originals of the serializer, packer and calibration. +- [../status-and-known-issues.md](../status-and-known-issues.md): project-wide status and drift. +- [../sim.md](../sim.md): the sim plugs in its own decider and never uses the host. +- [../glossary.md](../glossary.md): shared terms. +- Source notes: `packages/runtime/src/model/README.md`; model card: `packages/runtime-model/MODEL_CARD.md`; contract: `docs/runtime/CONTRACT.md` §2, §8, §10, §13. diff --git a/docs/agents/runtime/observe-and-trace.md b/docs/agents/runtime/observe-and-trace.md new file mode 100644 index 00000000..9a22d011 --- /dev/null +++ b/docs/agents/runtime/observe-and-trace.md @@ -0,0 +1,791 @@ +# @genclass/runtime: observers, ops and causality + +> **Scope:** `packages/runtime/src/observe/*.ts` (fetch, xhr, dom-user, errors, nav, storage, perf, websocket, timers, cache), `packages/runtime/src/trace/*.ts` (events, ops, context), and the parts of `packages/runtime/src/runtime.ts` that install/uninstall observers and route their events (`installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `destroy`). Also the helpers they depend on in `packages/runtime/src/util.ts`, `packages/runtime/src/clock.ts` and `packages/runtime/src/decide/exec.ts`. +> **Read this when:** you change or debug how GenClass patches `fetch` / `XMLHttpRequest` / `WebSocket` / timers / DOM events / history / Storage / errors / long tasks; how requests are held, faked, coalesced or served from cache; how ops, op signatures, request identities and cause/root links are produced; how the ambient op is propagated across `await`; or what lands in the event ring buffer. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- Observers are installed by `RuntimeImpl`'s constructor (`packages/runtime/src/runtime.ts` -> `installObservers`). Each installer returns an uninstall function or `null` (API missing). Installers are wrapped in try/catch, so init never throws. `destroy()` runs the uninstalls in reverse order. +- Each wrapper keeps a `disabled` flag. After `destroy()` it is a pure pass-through. A global is restored only if it still holds GenClass's wrapper; if another library wrapped on top, GenClass leaves that library's wrapper in place. Exceptions: objects created *before* `destroy()` keep their per-instance hooks (a `GenClassWebSocket` keeps recording ops and events, a timer scheduled earlier still sticks a lazy op when it fires), see "After destroy: what still runs" under Invariants. +- Everything the app does async is an **op** (`OpRec` in `packages/runtime/src/trace/ops.ts`). An op has a sequential `id`, a `kind`, a `name` (= op signature, e.g. `GET /api/items/:id`), an optional `detail` (e.g. `?q=rea`), and `cause`/`root` links. User actions, WS messages and sends, timer ticks and GenClass actions are *instant* ops. +- The **ambient op** (`packages/runtime/src/trace/context.ts` -> `Context`) is the op whose work is running. `startOp` uses it as the `cause` and state writes use it as their writer. GenClass sets it in three ways. `run` sets it synchronously. `stick` sets it until `clock.afterTask` clears it at the end of the macrotask; `stick` happens when a wrapped fetch/XHR/Response body settles, a user action is recorded, a timer fires, a WS message arrives, or `rt.op` settles. GenClass does **not** propagate context through arbitrary promises. +- Timer callbacks get a **`LazyOp`**. It becomes a real `timer` op only when something calls `ctx.op()`. A `LazyOp`'s parent is always a real op or `null`, never another `LazyOp`, so recursive `setTimeout` loops never build a chain. +- fetch is the only fully *controllable* transport. Its request gate offers send / coalesce / delay / block / serve_cached; its failure gate offers deliver / retry / serve_cached; its stall watch offers wait / hedge / serve_cached. The app's promise always settles, and a failed action falls back to sending. +- XHR supports send / delay / block / serve_cached at the request gate (block and cached answers are faked onto the XHR). XHR failures and stalls are detection-only. Synchronous XHRs and `keepalive` fetches never raise a request trigger at all. +- **Request identity** = FNV-1a of method + absolute URL + non-volatile headers + body content key. Bodies that cannot be read cheaply get a unique `uniq:N` key and so never match. +- The response cache (`packages/runtime/src/observe/cache.ts` -> `ResponseCache`) has two parts: + - a GET cache of the last good 2xx body per identity (≤ 256 KB each, ≤ 64 entries, LRU); + - a coalescing table of in-flight or recently finished (≤ 2 s) requests (≤ 64 entries, ≤ 4 MiB). + The app always reads its own `Response`; GenClass reads a clone. +- Every response GenClass synthesises carries the header `x-genclass: blocked | cached | coalesced`. Opaque responses shared by coalescing are the exception: they are unmarked clones. +- The DOM observer records click / input (typing) / change / submit / Enter / Escape at the capture phase on `window`. It skips `[data-genclass-ignore]` subtrees (shadow roots included) and events dispatched by app code while a non-user op runs. It never records sensitive field values. +- Events go to a ring buffer (`packages/runtime/src/trace/events.ts` -> `EventLog`) of `historySize` entries (default 500, minimum 16). Op names, details and event names feed the situation text the model reads and the sim's training data. The format is frozen at tag `situation-v1`, so any wording change needs coordination with SIM and TRAIN. + +## Files + +| Path | Role | Key exports / entry points | +|---|---|---| +| `packages/runtime/src/observe/fetch.ts` | Wraps `global.fetch`: op creation, request identity, request gate, failure gate, stall controller, Response instrumentation | `installFetch`, `bodyInfo`, `headersKey`, `parseRequest`, `instrumentResponse`, `IDENTITY_BODY_MAX`, `ParsedRequest` | +| `packages/runtime/src/observe/cache.ts` | GET response cache, coalescing table, bounded response buffering, synthetic responses | `ResponseCache`, `bufferResponse`, `makeResponse`, `blockedResponse`, `isOpaque`, `Buffered`, `RecentEntry`, `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS` | +| `packages/runtime/src/observe/xhr.ts` | Patches `XMLHttpRequest.prototype.{open,send,abort,setRequestHeader}` | `installXHR` | +| `packages/runtime/src/observe/dom-user.ts` | Capture-phase DOM user-action listeners and element descriptions | `installDomUser`, `describeElement` (public, re-exported from `packages/runtime/src/index.ts`), `isSensitiveField`, `ignoredEvent` | +| `packages/runtime/src/observe/errors.ts` | `error` and `unhandledrejection` listeners | `installErrors` | +| `packages/runtime/src/observe/nav.ts` | Wraps `history.pushState/replaceState` and listens to `popstate`/`hashchange` | `installNav` | +| `packages/runtime/src/observe/storage.ts` | Wraps `Storage.prototype.{setItem,removeItem,clear}` | `installStorage` | +| `packages/runtime/src/observe/perf.ts` | `PerformanceObserver` for `longtask` | `installPerf` | +| `packages/runtime/src/observe/websocket.ts` | Replaces `global.WebSocket` with a subclass | `installWebSocket`, `WsHost` | +| `packages/runtime/src/observe/timers.ts` | Wraps `setTimeout`/`setInterval` to carry context into callbacks | `installTimers`, `TimerHost` | +| `packages/runtime/src/trace/events.ts` | Event ring buffer | `EventLog` | +| `packages/runtime/src/trace/ops.ts` | Op registry | `OpRegistry`, `OpRec`, `StartOpts`, `ChainWrite` | +| `packages/runtime/src/trace/context.ts` | Ambient-op propagation | `Context`, `LazyOp`, `Ambient` | +| `packages/runtime/src/runtime.ts` | Wiring: installs observers, builds hosts, creates and ends ops, routes events and triggers | `RuntimeImpl.installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runAsGenClass`, `destroy` | +| `packages/runtime/src/decide/exec.ts` | Seam between observers and decisions | `NetHost`, `Controller`, `ActionEffect`, `EndOpts`, `TriggerOpts` | +| `packages/runtime/src/util.ts` | URL parsing, signature normalisation, hashing, redaction | `parseUrl`, `normalizePath`, `isIdSegment`, `requestSignature`, `redactSearch`, `fnv1a`, `stableStringify`, `IDEMPOTENT_METHODS`, `isSensitiveName`, `defaultRedact` | +| `packages/runtime/src/clock.ts` | Real clock: timers captured at module load, `afterTask` | `browserClock` | +| `packages/runtime/src/types.ts` | Public types | `Op`, `OpKind`, `OpStatus`, `RtEvent`, `EventKind`, `UserAction`, `ObserverName`, `Clock`, `RuntimeHooks` | +| `packages/runtime/src/situation/env.ts` | Request/failure subject types the observers fill in | `ReqMeta`, `FailureInfo`, `SubjectSpec`, `SitEnv` (`cached`, `identical`, `canCoalesce`) | +| `packages/runtime/src/situation/describe.ts` | How ops are worded in situations and `ActionEffect.changed` sentences | `opPhrase`, `opLabel`, `userPhrase` (out of scope; see [learn-situation-triage.md](learn-situation-triage.md)) | +| `packages/runtime/src/index.ts` | Entry: kill-switch observe map and the model host's un-observed fetch | `ALL_OFF`, `NATIVE_FETCH` (module-private), re-export of `describeElement` | + +## Concepts and data structures + +Terms specific to this doc (see also [../glossary.md](../glossary.md)): + +| Term | Meaning | +|---|---| +| op | An `OpRec`: an async operation, user action, timer tick, WS event or GenClass action. It has an id, kind, signature (`name`), cause and root. | +| op signature | `OpRec.name`. For requests it is `METHOD normalisedPath` (see "Signature normalisation"). | +| instant op | An op created already ended (`instant: true`, `end = start`, `status = "ok"`) and never put in `inFlight`. Used for user actions, timer ticks, WS messages and sends, and GenClass actions. | +| ambient op | `Context.cur`, read by `ctx.op()` (materialises a lazy timer op) or `ctx.peek()` (does not). | +| running op | `Context.running`: set only while `Context.run(op, fn)` executes `fn` synchronously. The DOM observer uses it to detect programmatic events. | +| lazy timer op | A `LazyOp` made for each wrapped timer callback. `materialize()` creates a real `timer` op on first use. | +| request identity | `ReqMeta.identity` / `OpRec.identity`: the hash that defines "identical requests". `""` while the body is still being read. A key starting `uniq:` (or hashed from one) matches nothing. | +| held | A request or failure waiting for a decision (the request gate or failure gate with `hold: true`). It fails open after the hold budget. | +| controller | A `Controller` from `packages/runtime/src/decide/exec.ts`. `passive()` lets the subject proceed. `run(action)` performs a built-in action and returns `ActionEffect.changed`, or throws, in which case passive runs instead. | +| gated | `NetHost.gated(op)`: `!paused && !destroyed && !op.genclass`. fetch and XHR raise request/failure/stall triggers only for gated ops (the `error` trigger from `reportError` does not use `gated`). | +| synthetic end | `endOp(..., { synthetic: true })`: the op was answered by GenClass (block, cache or coalesce). It is kept out of latency baselines and transition profiles. | + +`OpRec` (`packages/runtime/src/trace/ops.ts`; extends `Op` from `packages/runtime/src/types.ts`): + +| Field | Type | Set by / meaning | +|---|---|---| +| `id` | number | Sequential from 1 per `OpRegistry` (per runtime), never reused | +| `kind` | `OpKind` = `"user" \| "fetch" \| "xhr" \| "ws" \| "task" \| "timer" \| "genclass"` | Creator | +| `name` | string | Op signature | +| `detail?` | string | Query string or body summary (requests), quoted typed value (user), message summary (ws) | +| `start`, `end?` | number (clock ms) | `start` at creation, `end` at `OpRegistry.end` (instant ops: `end = start`) | +| `status?` | `"ok" \| "error" \| "aborted" \| "blocked"` | At end | +| `code?` | number \| string | HTTP status, `"timeout"`, `"network"`, `"aborted"`, or a WS close code | +| `cause?`, `root?` | number | `cause` = id of the parent op. `root` = `cause.root ?? cause.id`, or the op's own id when it has no cause | +| `attempt` | number | Default 1. A fetch retry gets `attempt + 1`; a hedge keeps the attempt | +| `reads` | `Map<string, number>` | Always created empty; filled lazily by situation building | +| `identity?` | string | Request identity (fetch/xhr) | +| `meta?` | object | User ops: `{ action: UserAction }` (value already redacted). Tasks: the `meta` passed to `rt.op` | +| `startSeq` | number | `hub.seq` (the global applied-mutation sequence) at start | +| `method?`, `url?` | string | Requests | +| `errorText?` | string | e.g. `HTTP 503`, the network error message | +| `instant?` | boolean | See the terms table | +| `wrote`, `storesWritten?`, `chain?`, `chainWrites?`, `profiled?` | — | Written by the state and learn code (see [state-and-adapters.md](state-and-adapters.md), [learn-situation-triage.md](learn-situation-triage.md)) | +| `triggered?` | `Set<TriggerKind>` | Triggers already raised for this op. A stall is raised once per op | +| `genclass?` | boolean | `kind === "genclass"`, or inherited from a cause that is `genclass`. Such ops are never gated, profiled, baselined or identity-registered | +| `children` | number | Count of ops that name this op as `cause` (diagnostic) | + +Op kinds as produced in practice: + +| kind | Created by | `name` format | Instant | Default cause | Pushes `op.start`? | Profiled (`PROFILED`) | Baselines + identity | +|---|---|---|---|---|---|---|---| +| `user` | `RuntimeImpl.user` (DOM observer, `rt.user`, plugin `api.user`, the sim) | `${kind} ${target}` (or bare `kind` with no target), e.g. `click button "Add to cart"`, `type input "Search"`, `key input "Search"` (the key itself is only in `meta.action.key`) | yes | `null` (always a root) | no (has its own `user` event) | yes | no | +| `fetch` | `installFetch` (also retry and hedge ops) | `GET /api/items/:id` | no | ambient (retry and hedge: explicit) | yes | yes | yes, unless `genclass` | +| `xhr` | `installXHR` | same as fetch | no | ambient | yes | yes | yes, unless `genclass` | +| `ws` | `installWebSocket` | `WS <path>` (connect), `WS message <path>`, `WS send <path>`; `<path>` is `host/path` for an absolute `ws(s):` URL on a page with a `location` (see WebSocket step 2) | message and send: yes | connect and send: ambient; message: `null` (root) | connect only (message and send push `custom` events) | yes | no | +| `task` | `rt.op(name, fn, meta)`; plugin `api.recordOp(kind, …)` can create any kind | the given name | no | ambient | yes | yes | no | +| `timer` | `LazyOp.materialize` via `RuntimeImpl.timerHost().lazyTimer` | `timer 300ms`, `timer 1.50s`, `interval 5.00s` | yes | the op that was ambient when the timer was scheduled (nearest real op) | yes (`data.instant: true`) | no | no | +| `genclass` | `RuntimeImpl.runAsGenClass(name, fn)` | `undo`, `revert`, `rollback`, `resync`, or a custom action name | yes | `null` | no (has `action` events) | no | no | + +`StartOpts` (`packages/runtime/src/trace/ops.ts`): `{ detail?; cause?: OpRec | null; identity?; attempt?; meta?; instant?; method?; url?; startSeq; t }`. `RuntimeImpl.startOp` takes `Omit<StartOpts, "startSeq" | "t">` and fills those two. `cause: undefined` means "use the ambient op"; `cause: null` forces a root. An empty `detail`/`identity`/`method`/`url` is not stored (truthiness checks). `ChainWrite` (`{ kind; len0; len1 }`, array lengths `-1` for non-arrays) belongs to transition profiles (see [learn-situation-triage.md](learn-situation-triage.md)). + +`OpRegistry` API (`packages/runtime/src/trace/ops.ts`, one per runtime, exposed as `rt.internals.ops`): + +| Member | Behaviour | +|---|---| +| `byId: Map<number, OpRec>` | Every op not yet pruned | +| `inFlight: Set<OpRec>` | Non-instant ops not yet ended. `rt.inflight()` returns a copy. Never pruned | +| `start(kind, name, o)` | Creates the op (see "Op lifecycle") | +| `end(op, t, status, code?, errorText?)` | No-op if the op already has `end` and is not in flight (so instant ops and already-ended ops cannot be re-ended; first end wins). Notifies `onEnd` listeners; listener throws are swallowed | +| `onEnd(fn)` | Returns an unsubscribe function | +| `get(id)` | `undefined` for `null`/`undefined`/pruned ids | +| `ancestors(op, max = 12)` | Direct cause upwards; stops at the first pruned ancestor | +| `isAncestorOrSelf(a, b)` | Walks at most 16 hops up from `b` | +| `userOf(op)` | Nearest `user` op in the chain, self included, ≤ 16 hops | +| `rootOf(op)` | `get(op.root) ?? op` (falls back to the op itself when the root was pruned) | + +Request `detail` format (`fetch.ts` -> `parseRequest`): the redacted query string (`?k=v&…`, ≤ 60 chars, `""` when none) followed, for methods other than GET/HEAD, by a **space** and the body summary, e.g. `?draft=1 {title: "x"}` (body `{"title":"x"}`, worded by `util.ts` -> `describe`) or ` 42 bytes` (leading space when there is no query). The leading space is deliberate: `situation/describe.ts` -> `opPhrase` renders fetch/xhr ops as `name + detail` with no separator (`GET /api/search?q=re`, `POST /api/orders {…}`). Retry ops copy `failedOp.detail`; hedge ops use `` `${op.detail ?? ""} (hedge)`.trim() ``. + +`ReqMeta` (`packages/runtime/src/situation/env.ts`): `{ method (upper case); url (absolute href); signature; identity; idempotent; replayable; bodyBytes?; transport: "fetch" | "xhr" }`. `idempotent` means the method is in `IDEMPOTENT_METHODS` = GET, HEAD, OPTIONS, PUT, DELETE, TRACE. `replayable` is false only for `ReadableStream` bodies, and for `Request` bodies that could not be cloned. + +`FailureInfo`: `{ kind: "network" | "timeout" | "http"; status?; statusText?; message?; durMs }`. + +`RtEvent` (`packages/runtime/src/types.ts`): `{ seq; t; kind: EventKind; name; op?; cause?; data? }`. Which events each producer emits: + +| `kind` | Producer | `name` | `op` | `data` | +|---|---|---|---|---| +| `user` | `RuntimeImpl.user` | op name | user op id (a typing burst points at the latest keystroke's op) | `{ kind, target, value? (JSON-quoted, redacted), count, first (first op id), lastT? }` | +| `op.start` | `RuntimeImpl.startOp` for non-instant ops, plus instant `timer`/`task` ops | op name | op id (`cause` set when the op has one) | `{ kind, detail?, instant? }` | +| `op.end` | `RuntimeImpl.endOp` | op name | op id | `{ status, code?, synthetic? }` | +| `state` | state hub (see [state-and-adapters.md](state-and-adapters.md)) | store | writer op | — | +| `error` | `RuntimeImpl.reportError` (errors observer, hub, app) | error name, e.g. `TypeError` | ambient op | `{ message: "Name: msg≤120", source? }` | +| `nav` | nav observer | route (`pathname+search+hash`, ≤ 80 chars) | — | `{ route }` | +| `perf` | perf observer | `long task` | — | `{ duration }` | +| `storage` | `RuntimeImpl.onStorage` | `localStorage.setItem` / `sessionStorage.removeItem` / `storage.clear` … | ambient op | `{ key }` (`[redacted]` when the redactor changes it) | +| `custom` | `rt.emit` (data redacted per key plus `summary` ≤ 80 chars), `ws.message` / `ws.send` (`{ path, summary }`), `xhr.send-failed` (`{ error }`) via `NetHost.emit` | event name | ambient op / message op / xhr op | as listed | +| `decision`, `action` | decision flow (see [decide-policy-actions.md](decide-policy-actions.md)) | trigger / action name | — | — | + +`EventLog` API (`packages/runtime/src/trace/events.ts`, exposed as `rt.internals.events`): + +| Member | Behaviour | +|---|---| +| `constructor(size)` | `size` is kept as given (readonly); the buffer length is `Math.max(16, size)` | +| `push(t, kind, name, { op?, cause?, data? })` | Assigns `seq = ++seq` (starts at 1), overwrites the oldest slot when full, calls every listener synchronously (throws swallowed), returns the event object (kept by reference, so callers can mutate it: typing bursts) | +| `touch(e)` | Re-notifies listeners after an in-place update; does not change `seq` or position | +| `last(n = length)` | The last `n` events, oldest first. `rt.history(n)` = `events.last(n)` | +| `since(t)` | Events with `t >= since`, oldest first | +| `length` | Number of events held (≤ buffer length) | +| `onEvent(fn)` | Returns an unsubscribe. `RuntimeImpl`'s constructor wires `events.onEvent(e => fire("event", e))`, so every push and touch reaches `rt.on("event")` listeners (devtools) | +| `clear()` | Empties the buffer; `seq` is **not** reset | + +Response buffering types (`packages/runtime/src/observe/cache.ts`): + +```ts +type Buffered = + | { kind: "body"; status; statusText; headers: [string, string][]; body: ArrayBuffer; url; t } + | { kind: "opaque"; res: Response /* a clone */; status; t }; +interface RecentEntry { op: OpRec; body: Promise<Buffered | null>; settledAt?: number; bytes: number } +``` + +`XhrState` (module-private in `packages/runtime/src/observe/xhr.ts`, kept in a module-level `WeakMap` keyed by XHR object): `{ method; url; async; headers: Map; op?; failed?: "error"|"timeout"|"abort"; held; abortedWhileHeld; faked: string[]; onEnd? }`. + +`BodyInfo` (module-private in `fetch.ts`, returned by the exported `bodyInfo`): `{ key?: string ("" = no body; undefined while pending); pending?: Promise<string>; bytes; replayable; summary }`. + +Host interfaces (what each installer receives; all built in `packages/runtime/src/runtime.ts`): + +| Interface | Defined in | Members | +|---|---|---| +| `NetHost` (fetch, XHR) | `packages/runtime/src/decide/exec.ts` | `clock`, `ctx`, `global`, `cache`, `redact()`, `baseHref()`, `startOp(kind, name, o)`, `endOp(op, status, o?)`, `gated(op)`, `trigger(spec, ctl, opts)`, `watchStall(op, req, ctl)`, `failureStreak(sig)`, `emit(name, data?, op?)`, `uniqueId()`, `setIdentity(op, req, identity)` | +| `TimerHost` | `packages/runtime/src/observe/timers.ts` | `global`, `ctx`, `lazyTimer(parent, label)` | +| `WsHost` | `packages/runtime/src/observe/websocket.ts` | `global`, `ctx`, `redact()`, `baseHref()`, `startOp(name, o)` (kind fixed to `ws`), `endOp(op, status, o?)`, `event(name, data, op?)` (a `custom` event) | +| `UserSink` (module-private) | `packages/runtime/src/observe/dom-user.ts` | `user(action, handler?)`, `ambientKind?()`, `runningKind?()` | +| `ErrorSink` (module-private) | `packages/runtime/src/observe/errors.ts` | `reportError(error, info?)` (the `RuntimeImpl` itself is passed) | +| nav / storage / perf | their files | plain callbacks: `onNav(route)`, `cb(area, op, key)`, `cb(name, duration)` | + +Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passive(): void /* called at most once */; run(action): ActionEffect | Promise<ActionEffect> /* throw = passive runs */; revertable?(); revert?() /* held writes only */ }`, `ActionEffect { changed: string; undo? }`, `TriggerOpts { hold: boolean; priority: number }`, `EndOpts { code?; errorText?; failure? /* counts as a failure in baselines */; synthetic? }`. + +## How it works + +### 1. Install, route and uninstall (`packages/runtime/src/runtime.ts`) + +1. The constructor creates `EventLog(o.historySize ?? 500)`, `Context(clock)`, `ResponseCache(clock)` and an `OpRegistry` (`clock = o.clock ?? browserClock`, `global = o.global ?? globalThis`). It wires `events.onEvent(e => fire("event", e))` and the decider's `onStatus` (its unsubscribe goes into the same `uninstall` list as the observers). It then calls `loadProfiles()` (only when `learn.persist` is set), then `installObservers(o.observe ?? {})`, then `use()` for each plugin. +2. `installObservers` reads each `observe[name]` flag. The default is `true`, except `timers`, which defaults to `typeof global.document === "object" && global.document !== null`. The install order is timers, fetch, xhr, websocket, user, errors, nav, storage, perf. Each install goes through `tryAdd`, which catches a throw (e.g. a read-only global) and logs it (only with `debug`). +3. Hosts: + - `netHost()` (`NetHost`) serves fetch and XHR. It provides `gated`, `trigger` (`RuntimeImpl.trigger`), `watchStall`, `failureStreak(sig)` (= `base.stats(sig)?.failStreak ?? 0`), `uniqueId()` (= `uniq:${++n}`), `setIdentity` (updates `op.identity` and `req.identity`, then re-registers), `emit` (a `custom` event) and `baseHref()` (= `global.location.href`). + - `timerHost()` provides `lazyTimer(parent, label)` = `new LazyOp(parent, cause => startOp("timer", label, { cause, instant: true }))`. + - `wsHost()` maps `startOp` to kind `ws` and `event` to a `custom` event. +4. Routing: + - DOM user actions go to `RuntimeImpl.user`, with `ambientKind` and `runningKind` callbacks (a `LazyOp` reports as `"timer"`). + - Errors go to `RuntimeImpl.reportError`. It creates an `error` event and raises the `error` trigger (`hold: false`, `priority: 0`). + - Nav, perf and storage become events only. They never raise triggers. +5. `destroy()` sets `destroyed` and runs every uninstall in reverse order, then unregisters plugins and calls `ctx.clear()`. It does **not** clear `ResponseCache`. Full order (`RuntimeImpl.destroy`, idempotent): + 1. `destroyed = true`, `hub.gating = false`; + 2. `queue.dispose()` (`packages/runtime/src/decide/decider.ts` -> `DeciderQueue`): every *queued* decision resolves `null`, so `RuntimeImpl.trigger` runs the controller's `passive()` (it checks `destroyed` first). The one decision already being evaluated ends when the provider answers or its deadline timer fires, and the hold-budget timer is not cleared by `destroy()`, so it also runs `passive()`. Either way a held fetch or XHR is **sent** (not dropped) and a held failure is delivered; + 3. `reporter.dispose()`, clear the settle and persist timers; + 4. run `uninstall` in reverse (observers, decider status listener); + 5. `unuse` every plugin, `unsubscribeIO` every store, `ctx.clear()`, dispose the decider if the runtime owns it. + From then on `gated(op)` is false and `consultable()` is false, so any trigger an existing object still raises runs its passive action at once. +6. `GenClass.init` (`packages/runtime/src/index.ts`) passes `observe: ALL_OFF` in three cases: outside a browser (no `window`/`document`), with the `?genclass=off` kill switch, and in the init-failure fallback. The model host downloads with `NATIVE_FETCH`, captured at module load (or `global.fetch` bound before the runtime wraps it), so GenClass never observes its own model download. + +### 2. Op lifecycle (`RuntimeImpl.startOp` / `RuntimeImpl.endOp`) + +1. `startOp(kind, name, o)`. `cause` is `o.cause` when given (including an explicit `null`); otherwise it is `ctx.op()`, which materialises a lazy timer op if one is ambient. It then calls `ops.start(kind, name, { ...o, cause, startSeq: hub.seq, t })`. +2. `OpRegistry.start`: + - assigns the id; + - sets `cause`/`root`, increments `cause.children`, and inherits `genclass`; + - for instant ops, sets `end = t` and `status = "ok"`; otherwise adds the op to `inFlight`. + It prunes when `byId.size > 2000`: the oldest non-in-flight ops are deleted until the size is ≤ 1500. +3. Back in `startOp`: + - pushes `op.start` (see the event table); + - for non-`genclass` fetch/xhr ops, calls `base.start(name, t)` and `registerIdentity(op)`; + - queues instant ops of profiled kinds for profiling; + - calls `hooks.opCreated(op)` synchronously. +4. `endOp(op, status, { code, errorText, failure, synthetic })` does nothing if the op has already ended. Otherwise it: + - calls `ops.end` (sets `end`, `status`, `code`, `errorText`; notifies `onEnd` listeners); + - pushes `op.end`; + - for non-synthetic, non-`genclass` fetch/xhr ops, calls `base.end(name, t, dur, ok, outcome, failure)`; + - queues profiled kinds that are neither aborted nor synthetic; + - calls `scheduleSettle()`. +5. `registerIdentity(op)` skips `genclass` ops and identities starting with `uniq:`. It calls `base.noteIdentity` and keeps `identicalMap[identity]`: at most 12 ops, dropping entries that ended and started more than 10 s ago, across at most 512 identities (oldest identity evicted). Situations read it through `SitEnv.identical`. + +### 3. fetch: a call through the wrapper (`packages/runtime/src/observe/fetch.ts` -> `installFetch` -> `wrapped`) + +1. If `disabled` (after destroy), call `nativeFetch(input, init)`. This is `native.call(global, ...)`; the app's `this` is ignored. +2. Parse the request: + - From a `Request` input: `method`, `url`, `keepalive`. `bodyKnown = false` when there is no `init.body`, the method is not GET/HEAD, and `input.body` is set. + - From a string/URL input: `rawUrl = String(input)`. + - `init.method`, `init.body` and `init.keepalive` override. + - Any exception means `nativeFetch` with no op. +3. Body key: + - `bodyKnown`: `bodyInfo(body, host)` (rules below). + - A `Request` with a body: `template = req.clone()` keeps a pristine copy for replays. If `content-length > 64 KB` or cloning failed, the key is `uniqueId()`. Otherwise a second clone's stream goes to `readKey`, which hashes ≤ 64 KB or falls back to `uniqueId()`; the key is then `pending`. +4. `parseRequest(host, method, rawUrl, b, headersKey(input, init))` returns `ReqMeta` (`transport: "fetch"`) plus `detail` and maybe `pendingIdentity`. +5. `host.startOp("fetch", req.signature, { detail, method, url, identity? })` runs **synchronously inside the `fetch()` call**. The cause is the ambient op. +6. `runRequest(op, parsed, input, init, template, gateRequest = !keepalive)` returns a **new Promise** owned by GenClass: + - If `signal.aborted` already: `endOp(op, "aborted", { code: "aborted" })` and reject with `signal.reason` (or `DOMException("…", "AbortError")`). Native fetch is never called. + - Otherwise add a one-shot `abort` listener. It is active only until the request is sent or answered. +7. Identity resolution. If the identity is pending and the request is not `keepalive`, `within(host, pendingIdentity, IDENTITY_READ_MS = 100, "")` waits for it (falling back to `uniqueId()` on timeout), then calls `setIdentity` and `gate()`. If the request is `keepalive`, it calls `setIdentity(uniqueId())` now, `gate()` at once, and the real identity later. +8. `gate()`: + - If `!gateRequest` (keepalive) or `!host.gated(op)`, it calls `sendNow()` synchronously. **No request trigger is raised.** + - Otherwise it calls `host.trigger({ trigger: "request", op, req }, reqCtl, { hold: true, priority: 2 })`. `RuntimeImpl.trigger` runs the passive action (`sendNow`) synchronously in these cases: the runtime is not consultable, all facts are neutral (triage `salient`), the situation is not salient, the provider is not ready, or the mode/policy permits no non-passive action. In all those cases native fetch is called inside the `fetch()` call. The exception is a pending identity (step 7): then the gate runs only after the body read, so the send is always asynchronous. Otherwise the request is **held** until the decision arrives or `holdBudgetMs()` expires; on expiry the passive action runs (fail-open). +9. `send(sendOp, primary)`: + - Each attempt is sent at most once (`WeakSet`). + - `primary` sets `sent = true` and removes the abort listener; native fetch now owns the app's signal. + - The first send uses the original `input`. Later sends (retries) use `template.clone()`. + - If `Response` exists and the identity is non-empty, `cache.track(identity, sendOp, bodyPromise)`. + - If gated, `watchStall` starts. + - Every call site passes `primary = true`; the `!primary` branches are unused. +10. On a response: + - `failed = status >= 500 || 429 || 408`. + - `tracked.settledAt = now`. `bufferResponse(res)` reads a **clone**. A `body` result for a non-failed, `res.ok` GET is put in the GET cache. The coalescing entry resolves to `null` if the request failed. + - `endOp(sendOp, failed ? "error" : "ok", { code: status, failure? })`. + - If failed and gated and not yet answered, `failureGate(...)`; else `answer(res)`. +11. On a rejection: + - `TimeoutError` (the error's name, or `signal.reason.name`) is a failure with `code: "timeout"`. + - Any other `AbortError` or aborted signal gives `endOp(..., "aborted")` and rejects with the original error. + - Everything else is `code: "network"` with `failure: true`. It goes to the failure gate if gated, else rejects with the original error. +12. `answer(res, err)` runs once. It removes the abort listener, cancels the stall watch, calls `host.ctx.stick(op)`, then resolves `instrumentResponse(host, res, op)` or rejects `err`. Because the stick comes first, the app's `await fetch()` continuation runs with this op ambient. +13. `instrumentResponse` replaces `json`, `text`, `arrayBuffer`, `blob`, `formData` and `bytes` on the Response instance with versions that call `ctx.stick(op)` on resolve and on reject. It also replaces `clone()` so that clones are instrumented too. Frozen responses are left as they are. +14. Other details of `installFetch`: + - `within(host, p, ms, fallback)` resolves with `p`'s value, or with `fallback` after `ms` on the host clock **or as soon as `p` rejects**. + - `R = g.Response ?? globalThis.Response`. Without it, responses are never tracked or buffered, and `block`, `serve_cached` and `coalesce` throw (so passive runs). + - Retries and hedges reuse the app's `init` object, including `init.signal`, so aborting the app's signal aborts them too. Without a `template` (no `Request` body) the original `input` is passed again. + - The wrapper function is tagged `__genclass = true`; nothing in the repo reads that tag. + +Body key rules (`bodyInfo`). The identity key is prefixed, then hashed together with method, URL and headers: + +| Body | Key | `replayable` | Summary (`detail` for non-GET/HEAD) | +|---|---|---|---| +| none / `null` | `""` | yes | — | +| string ≤ 256 chars | `s:<string>` | yes | JSON ≤ 16,384 chars: `describe(parsed, "body", redact, 60)`; else `<length> bytes` | +| string ≤ 1,048,576 chars | `S:<fnv1a>:<length>` | yes | as above | +| longer string | `uniq:N` | yes | as above | +| `URLSearchParams` | `q:<toString>` | yes | `redactSearch("?"+s, redact, 60)` | +| `FormData` without files | `f:<fnv1a(k=v&…)>` | yes | `form N fields` | +| `FormData` with a file | `uniq:N` | yes | `form N fields` (files count as one) | +| `Blob` ≤ 64 KB | pending: `b:<fnv32>:<len>` of its bytes | yes | `<size> bytes` | +| `Blob` > 64 KB | `uniq:N` | yes | `<size> bytes` | +| `ArrayBuffer` / view ≤ 64 KB | `b:<fnv32>:<len>` | yes | `<n> bytes` | +| > 64 KB | `uniq:N` | yes | `<n> bytes` | +| `ReadableStream` | `uniq:N` | **no** | `stream` | +| anything else | `j:<fnv1a(stableStringify(body, 4096))>` | yes | `stableStringify` truncated to 40 chars | + +`headersKey`: headers from the `Request` input, then `init.headers` (later values win), keys lower-cased. `VOLATILE_HEADERS` are dropped, the rest are sorted, and the key is `fnv1a("k:v\n…")`, or `""` when no headers remain. `parseRequest`: + +```ts +identity = fnv1a(`${METHOD} ${absoluteHref} ${hdrKey} ` + bodyKey) // "" while the body key is pending +detail = redactSearch(url.search, redact /*≤60 chars*/) + (body summary, only when method is not GET/HEAD) +``` + +### 4. fetch actions: request gate, failure gate, stall + +Request gate (`reqCtl`; `passive` = `sendNow`, which sends unless the request was already answered, sent or aborted): + +| Action | Effect | Op end | Marking | +|---|---|---|---| +| `send` (passive) | `send(op, true)` | real | — | +| `block` | answer `blockedResponse(R)`: status 503, statusText `Blocked by GenClass`, null body | `blocked`, code 503, synthetic | `x-genclass: blocked` | +| `serve_cached` | `cache.get(identity)` (LRU touch) -> `makeResponse(R, b, "cached")`; throws `no cached response` | `ok`, code `b.status`, synthetic | `x-genclass: cached` | +| `delay` | wait `min(250 · 2^failStreak(signature), 8000)` ms on the host clock, then `sendNow()` | real | — | +| `coalesce` | `cache.shareable(identity, op.id, now)` returns the newest **earlier** (lower op id) identical request that is in flight or settled ≤ 2 s ago. Waits `within(..., COALESCE_MAX_WAIT_MS = 8000, null)` for its buffered body. If that body is `null` or the response cannot be built, it calls `sendNow()` and throws (the ActionRecord records the error) | `ok`, code `b.status`, synthetic | `x-genclass: coalesced` (opaque: unmarked clone) | + +Failure gate (`failureGate`: `host.trigger({ trigger: "failure", op: failedOp, req, failure }, ctl, { hold: true, priority: 2 })`): + +| Action | Effect | +|---|---| +| `deliver` (passive) | The app gets the original failed `Response` or the original rejection | +| `retry` | Requires `req.replayable`. Waits `min(200 · 2^(failedOp.attempt − 1), 5000)` ms, then starts `retryOp = startOp("fetch", sig, { attempt: failedOp.attempt + 1, cause: failedOp, … })`, reassigns the closure's `op = retryOp` and sends it as primary. The retry is **not** re-gated at the request gate; its own failure goes through the failure gate again. `situation/build.ts` offers `retry` only when `attempt < 4`, so there are at most 3 retries (backoffs 200, 400, 800 ms). From then on the closure's `op` is the retry op: `answer()` sticks it, the app's `Response` is instrumented with it, and the stall watch is re-armed for it. If the app's signal aborted during the backoff, the app gets `signal.reason` and the action rejects (`aborted`) | +| `serve_cached` | Answer with the cached GET body (`x-genclass: cached`) | + +Whether the failure is held depends on the policy. In `guard` mode no failure action is permitted, so the failure is delivered at once and the decision is made in the background (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0`). + +Stall (`RuntimeImpl.watchStall`, armed by `send` for gated primary sends): +- It needs a latency baseline (≥ 5 samples, `MIN_LAT_SAMPLES` in `packages/runtime/src/learn/baselines.ts`). +- It fires `max(4 × median, 2 × p95, STALL_MIN_MS = 500)` ms **after the send** (not after op start; a held request starts the clock late) if the op has not ended, at most once per op (`op.triggered`), with `{ hold: false, priority: 1 }`. +- `stallController` actions: + - `wait` (passive): no-op. + - `serve_cached`: answers with the cached response; the original request keeps running in the background. + - `hedge`: requires `replayable && idempotent`; `build.ts` additionally limits it to GET. It sends `hedgeOp` (cause `op`, same attempt) through `nativeFetch(replayInput)` directly; it is not `cache.track`ed, so its body never enters the GET cache or the coalescing table. It is still an ordinary `fetch` op: it gets `op.start`/`op.end` events, latency baselines and an `identicalMap` entry. If the hedge returns a non-failure first, the app gets it. Otherwise the app keeps waiting for the original. + +The app's promise always settles. Every action that throws or rejects makes `RuntimeImpl.onDecision` call the controller's `passive()`. Once a request has been sent, GenClass stops listening to the app's `AbortSignal`. A failure held at that point is delivered or retried at decision/budget time (retry checks `signal.aborted`). + +### 5. Response cache and buffering (`packages/runtime/src/observe/cache.ts`) + +1. `bufferResponse(res, clock)` never throws. It returns: + - `opaque` (`res.clone()`) when `isOpaque(res)`: `type` is `opaque`/`opaqueredirect`/`error`, or status is 0, < 200 or > 599; + - `null` for `text/event-stream`, for `content-length > 262,144`, when the stream exceeds 262,144 bytes (the reader is cancelled), or when it is still streaming after `BUFFER_WAIT_MS = 1000` ms; + - `body` otherwise, with all headers. + The fetch wrapper buffers **every** tracked response this way, whether or not anything later shares it. The 1 s bound applies only when `clone.body` is a readable stream; otherwise it falls back to `await clone.arrayBuffer()` with no time bound and checks the size afterwards. `Buffered.t` is the clock time when buffering finished; it is the age shown in `serve_cached` sentences ("from 1.20s ago") and in `SitEnv.cached`. +2. `good` (the GET cache) is a `Map` used as an LRU. `put` accepts only `body` buffers and evicts beyond `MAX_ENTRIES = 64`. `get` refreshes recency. `peek` does not, and is used for the facts that `SitEnv.cached` reports. +3. `recent` (the coalescing table) maps identity to at most 8 `RecentEntry` items. `prune(now)` drops entries settled more than `COALESCE_WINDOW_MS = 2000` ms ago. It then evicts the oldest *settled* entries until the table holds ≤ `MAX_RECENT = 64` entries and ≤ `MAX_RECENT_BYTES = 4 MiB`. In-flight entries are never evicted. `settledAt` is set when the response headers arrive, not when buffering finishes. `RecentEntry.bytes` stays 0 until the body is buffered (and for opaque or failed entries), so the byte bound only counts finished `body` buffers. `track()` and `shareable()` both call `prune()`; so does `SitEnv.canCoalesce` (`runtime.ts` -> `makeEnv`), which situation building uses to decide whether to offer `coalesce`. +4. `makeResponse(R, b, mark)` handles the two buffer kinds: + - `opaque` returns `b.res.clone()` (unmarked); + - `body` builds `new R(body copy, { status, statusText, headers + x-genclass: mark })`. The body is `null` for 101/103/204/205/304. `url` is set with `Object.defineProperty`. The headers object is built with the module-scope `Headers` constructor, not `host.global.Headers`. +5. `blockedResponse(R)` = `new R(null, { status: 503, statusText: "Blocked by GenClass", headers: { "x-genclass": "blocked" } })`. + +### 6. XHR (`packages/runtime/src/observe/xhr.ts` -> `installXHR`) + +1. `wOpen`: + - `stateOf(xhr)` creates the state and listeners **once per object**: `readystatechange` (readyState 4 sticks `s.op`), `error`/`timeout`/`abort` (set `failed`) and `loadend` (runs `onEnd` once). + - `unfake` deletes the properties faked by a previous answer. + - Records `method`, `url`, `async` (false only when the third argument is `false`) and resets per-request state, then calls the native `open`. +2. `wSetHeader` records lower-cased header names. A repeated name overwrites the earlier value; the identity does not see the comma-joined value the browser actually sends. +3. `wSend`: + - With no state (send before `open`, `open` called before install, or any call after `destroy()`), it calls the native `send`. + - `bodyInfo(body)`; a Blob key is never read for XHR, so a Blob body gets `uniqueId()`. + - Headers are filtered by the `VOLATILE` regex. + - `parseRequest(...)` with `transport = "xhr"`, then `startOp("xhr", signature, { detail, identity, method, url })`. +4. `onEnd` (on `loadend`): + - `failed = "abort"` gives `aborted`. + - `timeout`, `error` or status 0 give `error` with code `timeout`/`network`, plus a `failure` trigger. + - Status ≥ 500, 429 or 408 gives `error` with the HTTP code, plus a `failure` trigger. + - Anything else is `ok`. + - Failure triggers use the `passiveOnly()` controller with `{ hold: false, priority: 1 }`: detection only, because the app already sees XHR failures directly. +5. Not gated, or synchronous: `doSend()` at once. **Synchronous XHRs raise no request trigger, are never held and get no stall watch.** `doSend()` arms the (detection-only) stall watch for gated async requests, then calls native `send`. If native `send` throws, it clears `onEnd`, ends the op `error` (`code: "network"`, `failure: true`) and rethrows. On this un-held path the app sees the exception exactly as without GenClass. +6. Otherwise `held = true` and `host.trigger({ trigger: "request", … }, ctl, { hold: true, priority: 2 })`: + - `passive`: `doSend()`. A throw from native `send` becomes a `custom` event `xhr.send-failed`. + - `block`: `fake(xhr, st, 503, "Blocked by GenClass", "", [["x-genclass","blocked"]])`; op ends `blocked`, synthetic. + - `serve_cached`: uses only `body` buffers, decoded as UTF-8; headers are the cached ones plus `x-genclass: cached`. + - `delay`: same formula as fetch. A throw from native `send` after the delay is swallowed (the op records it). + - `coalesce` throws `unsupported action`; `situation/build.ts` only offers it for `transport === "fetch"`. +7. `fake()` defines own-property getters for `readyState` 4, `status`, `statusText`, `response` and (for `responseType` `""`/`"text"` only) `responseText`. `response` follows `responseType`: `json` gives parsed JSON or `null`; `arraybuffer` gives UTF-8 bytes; `blob` gives a `Blob`; `document` gives `null`. It also overrides `getResponseHeader`/`getAllResponseHeaders`, then dispatches `readystatechange`, `load` and `loadend` as plain `Event`s. No progress events are fired and `responseURL` is not faked. The `block` and `serve_cached` callers set `onEnd = undefined`, end the op as synthetic and call `ctx.stick(op)` *before* `fake()`, so the app's load handlers run with the op ambient. +8. `wAbort` while held: it sets `abortedWhileHeld`, ends the op `aborted`, dispatches `abort` and `loadend`, and **never calls native `send`** (a later decision or delay is ignored). When not held, it calls the native `abort`. The held-abort path dispatches plain `Event`s only: no `readystatechange`, and `readyState`/`status` keep their native values (`OPENED`, 0), unlike a real abort of a sent request. +9. XHR responses are never buffered: XHR never populates the GET cache or the coalescing table. XHR `serve_cached` can only replay a body that fetch cached under the same identity. Identities match across transports when method, URL, headers and body match. + +### 7. DOM user actions (`packages/runtime/src/observe/dom-user.ts` -> `installDomUser`) + +1. Listeners are added on `global` if it has `addEventListener` (i.e. `window`), else on `document`, with `{ capture: true, passive: true }`, for `click`, `input`, `change`, `submit` and `keydown`. +2. Guard: an event is skipped when `ignoredEvent(e) || programmatic(e)`. + - `ignoredEvent`: `composedPath()[0]` (when `composedPath` exists) or `e.target` is inside an element with `data-genclass-ignore`; both are checked. The walk goes up `parentNode` and crosses shadow roots through `host`, for at most 1000 steps. + - `programmatic`: true if `runningKind()` is non-null and not `"user"`, i.e. app code running inside `ctx.run` of a task, GenClass, fetch or other op dispatched the event. Otherwise trusted events (`isTrusted !== false`) are kept. Untrusted events are dropped when the ambient kind (`peek`, where a `LazyOp` counts as `"timer"`) is non-null and not `"user"`. **Untrusted events with no ambient op, or with a user ambient op, are kept** (test drivers, `el.click()` inside a user handler). +3. Handlers: + +| Event | Records | Value | +|---|---|---| +| `click` | `{ kind: "click", target: describeElement(interactive(e.target)) }` | — | +| `input` | text-like targets only: `textarea`, contenteditable, or `input` whose type is one of `text search email number tel url password date time datetime-local month week ""` | `""` if `isSensitiveField`, else `textContent` (contenteditable) or `value`; plus `sensitive` | +| `change` | `select` (selected option text, ≤ 40 chars), checkbox/radio (`checked`/`unchecked`), range/color/file (`file` for file inputs) | sensitive -> `""` | +| `submit` | `form "<aria-label \| name \| id \| first h1/h2/h3/legend text>"`, or `form` | — | +| `keydown` | only `Enter` and `Escape`: `{ kind: "key", key, target }`. Auto-repeat is not filtered (`e.repeat` is not checked), so a held key records one user op per repeat | — | + + `interactive(t)` uses the parent element for text nodes, then takes the closest element matching `button,a,input,select,textarea,summary,label,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=option],[role=switch],[contenteditable=''],[contenteditable=true]`, falling back to the element itself. +4. `RuntimeImpl.user(action, handler?)`: + - `kind` is `action.kind ?? action.action ?? "action"`. + - The value becomes `[redacted]` when `sensitive` is set or `redact(target, value) !== value`. + - `detail = JSON.stringify(truncate(value, 40))`. Only `detail` is truncated: `op.meta.action.value` keeps the whole (possibly redacted) value. + - It creates an instant root op, `startOp("user", name, { cause: null, instant: true, detail, meta: { action } })`. + - **Typing bursts:** a `type` action is merged into the previous `user` event when the target is the same, the gap is ≤ `TYPING_BURST_MS = 1000` ms since the last keystroke, and that event is still the latest user event. The merge updates `count`, `value`, `lastT` and `e.op` in place and calls `events.touch(e)`. Every keystroke still creates its own user op. + - It then calls `ctx.stickUser(op)`, and runs `ctx.run(op, handler)` if a handler was given. The DOM observer passes none. Its capture listener on `window` runs before the app's handlers (except `window` capture listeners registered earlier), so they run with the user op ambient and recorded as the task's user op (`taskUser`). +5. `describeElement(el)` returns `'role "name"'`, or a bare role, or `page` for `null`. + - Name, first non-empty of: + 1. `aria-label`; + 2. `aria-labelledby` texts; + 3. fields only (input/select/textarea): `labels[0]`, then `label[for=id]`, then the closest `label`; + 4. non-fields only: `innerText ?? textContent`; + 5. `placeholder`; + 6. `title`; + 7. `name`; + 8. the `value` of an input of type button/submit/reset (never a typed value); + 9. `id`. + - Each name has whitespace collapsed and is truncated to 40 chars. + - Role: the `role` attribute; else `a` -> `link`; input button/submit/reset/image -> `button`; checkbox/radio/range/file/color -> that type; any other input -> `input`; else the tag name. + - Examples from `test/dom.test.ts`: `button "Place order"`, `input "Search"`, `link "Home"`, `checkbox "remember"`, `select "Size"`. +6. `isSensitiveField` is true for any of: `type=password`; `autocomplete` whose last token matches `/^(cc-|one-time-code$|current-password$|new-password$)/i`; or `name`/`id`/`aria-label`/`placeholder`/label text that `isSensitiveName` flags (word-level secret names in `packages/runtime/src/util.ts`). + +### 8. Timers and lazy timer ops (`packages/runtime/src/observe/timers.ts`, `packages/runtime/src/trace/context.ts`) + +1. `installTimers` wraps `setTimeout`/`setInterval` on the runtime's `global` option (`RuntimeImpl.timerHost().global` = `o.global ?? globalThis`), not on Node's `globalThis` when a custom `global` is passed. It returns `null` and installs nothing when `global.setTimeout` is not a function. In Node tests the observer is off by default (no `document`). `packages/runtime/test/helpers.ts` -> `makeGlobal` has no `setTimeout`, so `setup({ observe: { timers: true } })` alone wraps nothing. Use the recipe from `packages/runtime/test/context.test.ts` ("timers observer carries the cause into timer callbacks (debounce)"): `const holder = {}; const s = setup({ observe: { fetch: true, timers: true }, extraGlobal: { setTimeout: (fn, ms) => holder.clock.setTimeout(fn, ms), clearTimeout: (h) => holder.clock.clearTimeout(h), setInterval: () => 0 } }); holder.clock = s.clock;`. Schedule through `s.g.setTimeout`, not the Node global. A passed `observe` replaces `setup`'s all-off map, so unlisted observers return to their defaults (on, except `timers`). +2. `setTimeout` and `setInterval` are wrapped. `clearTimeout`/`clearInterval` are not; the native handle is returned unchanged. A non-function callback (a string) passes through untouched. +3. At schedule time: `amb = ctx.peek()` and `parent = amb instanceof LazyOp ? amb.nearest : amb`. `nearest` is the materialised op if there is one, else the lazy op's own parent. `label` is `timer ${delay < 1000 ? Math.round(delay) + "ms" : secs(delay)}` or `interval ${secs(delay)}`, with `delay = max(0, Number(ms) || 0)`. +4. When the callback fires (every tick, for intervals): `ctx.stick(lazyTimer(parent, label))`, then the app's callback runs (with its original `this` and arguments). The native timer receives the app's original `ms` and extra arguments; only the label uses the clamped `delay`. + - `parent` and `label` are captured once per `setTimeout`/`setInterval` call. Every tick of an interval therefore gets a fresh `LazyOp` with the **same** parent: all ticks descend from the op that was ambient when `setInterval` was called (same `root`), however long the interval runs. + - With no ambient op at schedule time, `parent` is `null` and a materialised timer op is a root (no cause). +5. Anything in the callback that calls `ctx.op()` materialises a `timer` op (instant, `cause = parent`) and replaces `cur` with it. That includes `startOp` without an explicit cause (fetch, XHR, `rt.op`, WS connect/send, plugin `recordOp`), state writes (`StoreHub.propose`), `rt.emit`, `reportError` and the storage observer. Idle callbacks create nothing (`test/context.test.ts`). +6. Why lazy ops never chain: a `LazyOp` is only ever constructed with a real op or `null` as its parent, and `materialize()` nulls its `make` and `parentOp`. A recursive `setTimeout` loop that never uses its op therefore keeps pointing at the same real ancestor. No closure chain builds up and materialising never recurses (`test/review-timers.test.ts`: 200,000 ticks, then a write). A loop that *does* materialise before it reschedules links each tick to the previous tick's real op by numeric id only (the `LazyOp` drops `parentOp` once materialised), so registry pruning can free old ticks. The gc test ("a polling loop does not retain every past tick's op forever") schedules the next tick *before* writing, so its ticks are roots; it asserts that a pruned tick op is garbage-collected, not the materialise-first linking case (untested). +7. The runtime's own scheduling uses `Clock` (`browserClock` captures the real `setTimeout`/`clearTimeout`/`setImmediate`/`MessageChannel` at module load), so the timers observer never sees GenClass's own timers. + +### 9. Ambient-op propagation rules (`packages/runtime/src/trace/context.ts` -> `Context`) + +| Mechanism | Sets `cur` to | Duration | Call sites | +|---|---|---|---| +| `run(op, fn)` | `op` (also `running`) | Synchronously during `fn`; restores the previous `cur` and `running` in `finally` | `RuntimeImpl.user` (with handler), `RuntimeImpl.op` (body), `runAsGenClass`, plugin `runInOp`, the hub applying a held write (`ctx.run(m.cause, write)`) | +| `stick(op)` | `op` or a `LazyOp` | Until `clock.afterTask` runs. It clears `cur` only if `cur` is still that op (or the op it materialised into) | fetch `answer()` and body methods; XHR readyState 4 and fake answers; WS message; timer callbacks; `rt.op` settle; `stickUser` | +| `stickUser(op)` | `op`, plus `taskUser = op` | Until afterTask | `RuntimeImpl.user` | +| `clear()` | `null` | — | `destroy()` | + +- `isUserSync(op)` is true when `op === taskUser`, or `op.root === taskUser.root || op.root === taskUser.id`. The hub uses it: user-sync writes are never held unless `policy.holdUserWrites` (default `false`) is set. +- `stick` is last-writer-wins within a task. A later stick in the same task (two responses settling in one task, `Promise.all`) overrides the earlier one. +- Context is lost across `await` on any promise GenClass did not instrument. For example, inside `rt.op(name, async () => { await somethingUninstrumented(); x.set(1) })`, the write after the await has no ambient op. It is regained only at the next instrumented settle point. +- `browserClock.afterTask` picks the first available of: `setImmediate` when there is no `window` (Node); `MessageChannel`; `setImmediate`; `setTimeout(0)`. It batches callbacks and flushes them once per posted task. The test `FakeClock` models this explicitly (`flush()` drains microtasks, then runs the afterTask hooks). + +### 10. WebSocket (`packages/runtime/src/observe/websocket.ts` -> `installWebSocket`) + +1. `global.WebSocket = class GenClassWebSocket extends Native`. Instances made after destroy (through a kept reference) skip all tracing. +2. The path is `normalizePath(parseUrl(url, baseHref).where)`. An absolute `ws:`/`wss:` URL never has the same origin as an `http(s)` page (the scheme differs), so `where` is `host + pathname` and the op name includes the host, e.g. `WS message app.example.test/ws/board` (seen in `sim/samples`). Two exceptions follow from `parseUrl`: with no `global.location` (`baseHref()` undefined) every URL counts as same-origin, and a relative URL resolves against the page's `http(s)` origin; in both cases `where` is the bare `pathname` (e.g. `WS /ws`). +3. The connect op is `WS <path>` with detail `connect` and the ambient op as cause. It ends `ok` on `open`, `error` with `{ code: "network", failure: true }` on `error`, or `error` with `{ code: CloseEvent.code }` on `close`. Only the first of these counts. Errors and closes **after** `open` are not recorded at all (the connect op has already ended; there is no disconnect op or event). If the native constructor throws (bad URL), the exception reaches the app and nothing is recorded. +4. Each `message`: + - creates an instant **root** op `WS message <path>` (`cause: null`) whose detail is the summary; + - pushes a `custom` event `ws.message` `{ path, summary }`; + - calls `ctx.stick(m)`. The listener is registered in the constructor, before any app listener or `onmessage`, so the app's handlers run with the message op ambient. +5. `send` is replaced per instance (own property). It creates an instant op `WS send <path>` (ambient cause) and a `custom` event `ws.send`, then calls the original. +6. Summary: + - strings > 16 KB or blank: `<len> chars`; + - JSON (starts with `{` or `[`): `describe(parsed, "message", redact, 60)`; + - other strings: `JSON.stringify(truncate(t, 40))`; + - Blob/ArrayBuffer: `<n> bytes`; + - else `binary`. + WS ops are neither baselined nor identity-registered. + +### 11. errors, nav, storage, perf + +- **errors** (`installErrors`): + - On `window` `error`, events with neither a string `message` nor an `error` are skipped (resource load errors). `source` is `<basename(filename)>:<lineno ?? 0>`, and is omitted when `filename` is empty. + - On `unhandledrejection`, `source` is `"unhandledrejection"`. + - Both listeners are bubble-phase listeners on `global` (`null` when it has no `addEventListener`). The value reported is `ev.error ?? ev.message` (for an `error` event) or `ev.reason`. `reportError` returns at once after `destroy()`; its ambient-op lookup (`ctx.op()`) materialises a lazy timer op. + - Both call `RuntimeImpl.reportError(error, { source })`. `normalizeError` sets the key to `Name:` + the message with each digit run replaced by `n`, message part cut to 120 chars. `errorsRecent` keeps ≤ 64 entries; the facts window is 10 s. The `error` trigger's `rollback` calls `revertChain(ambientOp)`. +- **nav** (`installNav`): the original `pushState`/`replaceState` is called first, then the route is recorded. `popstate` and `hashchange` are recorded too. The route is `truncate(pathname + search + hash, 80)` and is **not redacted**. The output is a `nav` event only; no op. Requires `global.history`, `global.location` and `addEventListener`. If the native `pushState` throws, nothing is recorded (the original runs first). The second parameter (`_rt`) is unused. A fragment navigation normally fires both `popstate` and `hashchange`, giving two `nav` events (unverified: browser behaviour; no test). +- **storage** (`installStorage`): `setItem`/`removeItem`/`clear` are wrapped on `Storage.prototype`. The area (`localStorage`, `sessionStorage` or `storage`) is found by comparing `this`. Property-assignment writes (`localStorage.k = v`) and `delete` are not observed. The event's `op` is the ambient op (`ctx.op()`, which materialises a lazy timer op). The native method runs first; if it throws (e.g. quota exceeded) no event is recorded. Cross-tab `storage` events on `window` are not observed. `clear` records key `""`. +- **perf** (`installPerf`): returns `null` when `PerformanceObserver` is missing, when `supportedEntryTypes` exists without `longtask`, or when `observe()` throws. It observes `{ type: "longtask", buffered: false }`. Each entry becomes a `perf` event `long task` with `{ duration }`. + +### 12. Signature normalisation (`packages/runtime/src/util.ts`) + +1. `parseUrl(raw, base)` evaluates `new URL(raw, base ?? "http://localhost/")`. + - `sameOrigin = !base || base.origin === url.origin`. + - `where = sameOrigin ? pathname : host + pathname`. Query and fragment never enter the signature; the query goes to `detail`. + - If parsing throws (including an invalid `base`), the fallback is `{ href: raw, where: raw before "?", search: raw from "?" (or ""), sameOrigin: true }`. + - `base` comes from `NetHost.baseHref()` = `global.location.href` when it is a string, else `undefined`. `WsHost.baseHref()` returns `global.location?.href` without the string check. +2. `requestSignature(method, where)` = `` `${METHOD} ${normalizePath(where)}` ``. The method is upper-cased here (and in `parseRequest`), so `fetch(u, { method: "post" })` gives `POST …`. +3. `normalizePath` splits on `/`. Each segment is `decodeURIComponent`'d (the raw segment is used if decoding throws) and tested with `isIdSegment`. Matches become `:id`; other segments are kept **raw** (not decoded). +4. `isIdSegment(seg)` is true if `seg` is non-empty and any of these hold: + - all digits `/^\d+$/`; + - a UUID (8-4-4-4-12 hex, case-insensitive); + - long hex: ≥ 8 hex chars containing a digit; + - long token: ≥ 16 chars of `[A-Za-z0-9_-]` containing a digit and a letter; + - `isSlugId`. This requires ≥ 4 chars of `[A-Za-z0-9_-]` with both a digit and a letter, and not a version (`/^v\d+([a-z]+\d*)?$/i`). Then, for any `-`/`_` part containing letters and digits: the part starts with a digit, **or** it has ≥ 2 letter↔digit transitions. Failing that, the whole segment is ≥ 6 chars and mixes lower case, upper case and digits. + + Exact patterns (module-private in `util.ts`): + + ```ts + const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const LONG_HEX = /^(?=[0-9a-f]*\d)[0-9a-f]{8,}$/i; + const LONG_TOKEN = /^(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}$/; + // isSlugId transitions: part.match(/[A-Za-z](?=\d)|\d(?=[A-Za-z])/g).length >= 2 + ``` + +| Input | Output | +|---|---| +| `/api/items/42` | `/api/items/:id` | +| `/api/tasks/tasks-1cam` | `/api/tasks/:id` | +| `/api/u/x7k2p/orders/ab12cd` | `/api/u/:id/orders/:id` | +| `/api/v2/items/PPBqWA9` | `/api/v2/items/:id` | +| `sha256`, `oauth2`, `ipv4`, `item42`, `v1beta1`, `html5`, `x86_64`, `utf-8` | unchanged (not ids) | +| `https://api.other.com/items/7` from page `http://app.test/` | `GET api.other.com/items/:id` | +| `/api/items/` vs `/api/items` | different signatures (trailing empty segment kept) | +| `/reports/2024-10-07` | unchanged: no letters, so not an id | +| `/reports/2024` | `/reports/:id` (any all-digit segment, years included) | +| `/api/items/%31%32` | `/api/items/:id` (tested after decoding: `12`) | +| `/files/My%20Doc` | unchanged, kept encoded (non-id segments are never decoded in the output) | +| `/blobs/cafe1234` vs `/blobs/deadbeef` | `/blobs/:id` vs unchanged (`LONG_HEX` needs a digit) | + +Transition profiles use a different normaliser, `normalizeFieldPath`, for store paths (out of scope). + +## Configuration and constants + +| Name | Type | Default / value | Defined in | Effect | +|---|---|---|---|---| +| `observe` (`ObserverName` = `fetch xhr user errors nav storage perf websocket timers`) | `Partial<Record<…, boolean>>` | all `true`; `timers` = `global.document` is a non-null object | `packages/runtime/src/runtime.ts` -> `installObservers` | Which observers install | +| `historySize` | number | 500 (buffer min 16) | `packages/runtime/src/runtime.ts` constructor, `packages/runtime/src/trace/events.ts` -> `EventLog` | Ring-buffer size. The timeline reads the last 96 events (`situation/build.ts` -> `timelineLines`) | +| `IDENTITY_BODY_MAX` | bytes | 65,536 | `packages/runtime/src/observe/fetch.ts` | Max Blob/ArrayBuffer/view/Request body hashed for identity | +| `STRING_BODY_MAX` | chars | 1,048,576 (strings ≤ 256 chars are used verbatim) | `packages/runtime/src/observe/fetch.ts` | Longer string bodies get a unique identity | +| `IDENTITY_READ_MS` | ms | 100 | `packages/runtime/src/observe/fetch.ts` | Max wait for a Request/Blob body identity before the gate | +| `COALESCE_MAX_WAIT_MS` | ms | 8,000 | `packages/runtime/src/observe/fetch.ts` | A coalesced request waits at most this long, then sends itself | +| `SUMMARY_PARSE_MAX` | chars | 16,384 | `packages/runtime/src/observe/fetch.ts` | JSON body summaries are parsed only up to this size | +| object-body stringify cap | chars | 4,096 | `packages/runtime/src/observe/fetch.ts` -> `bodyInfo` | `j:` key input | +| `VOLATILE_HEADERS` | Set | `traceparent tracestate baggage sentry-trace x-request-id x-correlation-id request-id x-amzn-trace-id x-cloud-trace-context b3 x-b3-traceid x-b3-spanid x-b3-parentspanid x-b3-sampled x-b3-flags x-datadog-trace-id x-datadog-parent-id x-datadog-sampling-priority x-datadog-origin newrelic date x-request-start x-genclass` | `packages/runtime/src/observe/fetch.ts` | Excluded from fetch identity | +| `VOLATILE` | RegExp | same list, but `x-b3-.*` and `x-datadog-.*` are wildcards | `packages/runtime/src/observe/xhr.ts` | Excluded from XHR identity | +| `FAILURE_STATUS` | predicate | status ≥ 500, 429, 408 | `packages/runtime/src/observe/fetch.ts` (inline copy in `xhr.ts` `onEnd`) | Failure classification | +| `BODY_METHODS` | list | `json text arrayBuffer blob formData bytes` (+ `clone`) | `packages/runtime/src/observe/fetch.ts` | Instrumented for context | +| delay | ms | `min(250 · 2^failStreak, 8000)` | `fetch.ts` `reqCtl`, `xhr.ts` `ctl` | `delay` action | +| retry backoff | ms | `min(200 · 2^(attempt−1), 5000)` | `fetch.ts` `failureGate` | `retry` action | +| `MAX_BODY` | bytes | 262,144 | `packages/runtime/src/observe/cache.ts` | Max buffered response body | +| `MAX_ENTRIES` | count | 64 | `packages/runtime/src/observe/cache.ts` | GET cache entries (LRU) | +| `COALESCE_WINDOW_MS` | ms | 2,000 | `packages/runtime/src/observe/cache.ts` | A settled request stays shareable this long | +| `BUFFER_WAIT_MS` | ms | 1,000 | `packages/runtime/src/observe/cache.ts` | A still-streaming body is not buffered | +| `MAX_RECENT` / `MAX_RECENT_BYTES` | count / bytes | 64 / 4,194,304 | `packages/runtime/src/observe/cache.ts` | Coalescing table bounds | +| per-identity recent list | count | 8 | `cache.ts` -> `ResponseCache.track` | Oldest dropped | +| `NULL_BODY` | statuses | 101, 103, 204, 205, 304 | `packages/runtime/src/observe/cache.ts` | Synthetic response gets a `null` body | +| `MAX_OPS` / `KEEP_OPS` | count | 2,000 / 1,500 | `packages/runtime/src/trace/ops.ts` | Registry pruning (in-flight ops are never pruned) | +| `ancestors` max / walk limits | count | 12 / 16 (`isAncestorOrSelf`, `userOf`) | `packages/runtime/src/trace/ops.ts` | Bounded chain walks | +| `TYPING_BURST_MS` | ms | 1,000 | `packages/runtime/src/runtime.ts` | Typing-burst merge window (from the last keystroke) | +| `STALL_MIN_MS` | ms | 500 | `packages/runtime/src/runtime.ts` | Stall at `max(4×median, 2×p95, 500)` | +| `MIN_LAT_SAMPLES` | count | 5 | `packages/runtime/src/learn/baselines.ts` | No stall watch before 5 latency samples | +| `LONG_RUNNING_MS` | ms | 10,000 | `packages/runtime/src/runtime.ts` | In-flight ops younger than this block settled points (`busy`) | +| `identicalMap` | count / ms | ≤ 12 per identity, 10 s, ≤ 512 identities | `packages/runtime/src/runtime.ts` -> `registerIdentity` | Identical-request facts | +| hold budget | ms | `"auto"` = clamp(1.5 × median of the last 20 model latencies (else the model's `warmupMs`), `HOLD_MIN_MS` = 150, `HOLD_MAX_MS` = 800); `HOLD_FALLBACK_MS` = 300 when neither is known; a number `policy.holdBudgetMs` is used as is (≥ 0) | `packages/runtime/src/decide/policy.ts` -> `holdBudget` | How long a held request or failure waits | +| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `packages/runtime/src/runtime.ts` | Deadline for decisions on non-held triggers (stalls, XHR failures, failures in guard mode, errors) | +| `PROFILED` | `Set<OpKind>` | `fetch xhr user task ws` | `packages/runtime/src/runtime.ts` | Op kinds whose causal chains feed transition profiles (`timer` and `genclass` never) | +| `errorsRecent` | count / ms | ≤ 64 entries; facts window 10,000 | `packages/runtime/src/runtime.ts` -> `reportError`, `makeEnv.recentErrors` | Recent-error facts | +| error key | chars | `Name:` + message with digit runs -> `n`, message part ≤ 120 | `packages/runtime/src/runtime.ts` -> `normalizeError` | Groups repeated errors | +| `uniq` counter | `uniq:N` | per runtime, from 1 | `packages/runtime/src/runtime.ts` -> `netHost().uniqueId` | Identity that matches nothing | +| timer label | string | `timer ${ms<1000 ? round(ms)+"ms" : secs(ms)}`, `interval ${secs(ms)}` (`secs`: 2 decimals < 10 s, 1 decimal < 1000 s, else integer) | `packages/runtime/src/observe/timers.ts`, `util.ts` -> `secs` | Timer op names (situation text) | +| `policy.holdUserWrites` | boolean | `false` | `packages/runtime/src/decide/policy.ts` | When false, user-sync writes are never held | +| WS JSON summary cap | chars | 16,384 | `packages/runtime/src/observe/websocket.ts` -> `summary` | Larger messages are summarised as `<len> chars` | +| element name length | chars | 40 | `dom-user.ts` -> `clean` | `describeElement` names | +| user value in `detail` | chars | 40 | `runtime.ts` -> `user` | `detail` truncation | +| nav route | chars | 80 | `nav.ts` | Route truncation | +| `insideIgnored` walk | nodes | 1,000 | `dom-user.ts` | `[data-genclass-ignore]` search | +| `redactSearch` | chars | output ≤ 60, input capped at 4,096 | `packages/runtime/src/util.ts` | Request `detail` | + +## Invariants and gotchas + +**Safety. The app must never break.** +- Every wrapper has to behave exactly like the native API when GenClass fails. + - Parsing errors fall back to `nativeFetch`. + - Tracing code inside wrapped methods (nav `pushState`/`replaceState`, storage methods, WebSocket `message` listener and `send`, the WebSocket connect `startOp`) is wrapped in try/catch. The DOM-user, XHR-state and error listeners are **not**; they are separate listeners, so a throw there is reported as an uncaught error rather than stopping the app's own handlers. + - Installers that throw are skipped (`tryAdd`). + - The app's fetch promise always settles: every controller path ends in `answer`, `sendNow` or the original rejection. +- Keep these properties when you edit. + +**Pass-through after destroy.** +- Keep the `disabled` flag check in every wrapper (fetch, XHR, timers and the WebSocket constructor check it first; nav and storage call the native method first and then check it), and restore a global only if it still holds GenClass's wrapper. +- `test/review-fetch.test.ts` checks that a fetch through an APM-style wrapper installed on top creates no ops and no cache entries after `destroy()`. + +**After destroy: what still runs** (from code reading; no test covers these). `RuntimeImpl.startOp`, `endOp`, `events.push` and `Context` do not check `destroyed`, so per-object hooks created earlier keep working: +- A `GenClassWebSocket` constructed before `destroy()` keeps its listeners and its own-property `send`: messages and sends still create `ws` ops and `custom` events, and messages still `stick`. Only sockets constructed afterwards (via a kept class reference) skip tracing. +- A timer callback scheduled before `destroy()` still calls `ctx.stick(lazyTimer(...))` when it fires; anything that then calls `ctx.op()` creates a `timer` op. +- An XHR object keeps its once-per-object listeners. After `destroy()` `open`/`send` are native again, so `st.op` is never refreshed, but a later readyState-4 still sticks that object's last op. +- Fetches already inside `runRequest` finish normally (held ones are released by `queue.dispose()`, see "Install, route and uninstall" step 5). New triggers from these objects run passive at once (`consultable()` is false). + +**Op registry.** +- Ending is idempotent: `OpRegistry.end` and `RuntimeImpl.endOp` both ignore an op that already has `end` and is not in flight. Instant ops can never be re-ended (a plugin `api.endOp` on one is a no-op). +- Pruning removes ops from `byId` only. Links are numeric ids, so `ops.get(cause)` can return `undefined`; `ancestors`/`userOf` stop early and `rootOf` falls back to the op itself. Strong references still keep a pruned op alive: a `LazyOp` parent, an interval's captured `parent` (for the interval's lifetime), an XHR's `st.op`, `identicalMap`, `RecentEntry.op`. +- Ids, `uniq:N` and event `seq` are per runtime and never reset (`EventLog.clear` keeps `seq`). + +**Multiple runtimes in one page** (from code reading; no test). Each runtime installs its own wrappers on top of the previous ones: two runtimes mean every fetch creates one op in each, and the outer runtime sees the inner wrapper as "native". `xhr.ts` -> `states` is a module-level `WeakMap`, shared by all runtimes from the same bundle. `NATIVE_FETCH` is captured at module load, so a bundle loaded after another library (or another GenClass bundle) wrapped `fetch` downloads its model through that wrapper. + +**Never observe yourself.** +- The runtime schedules only through `Clock` (timers captured at module load in `packages/runtime/src/clock.ts`). +- The model host downloads with the module-load `fetch`. +- GenClass actions run in `runAsGenClass`. Their ops, and any op caused by them, are `genclass`, so they are never gated. +- Do not call `global.setTimeout` or `global.fetch` from runtime code. + +**Determinism and sim parity.** +- Observers must use `host.clock`. No `Date.now`, `Math.random` or global timers. +- Op ids and `uniq:N` counters are sequential, so identical inputs give byte-identical situations (`test/situation.test.ts` -> "determinism"). +- The sim runs the real `fetch`, `timers` and `websocket` observers on a virtual global (`sim/src/run/rt.ts` -> `createOptions`). It drives user actions through `runtime.user(act, handler)` (`sim/src/run/runner.ts`), with targets written in the same `role "name"` format that `describeElement` produces. +- Op names, details, event names, timer labels, signature normalisation and causal links all appear in situation text. Changing any of them changes training data. The format is frozen at tag `situation-v1`, and runtime `src` is unchanged since that tag. Coordinate with SIM and TRAIN (see [../model-io-contract.md](../model-io-contract.md)). + +**No request trigger at all.** +- `keepalive` fetches are sent synchronously inside `fetch()`, so they survive unload (`test/review-fetch.test.ts` -> keepalive). +- Synchronous XHRs complete inside `send()`. +- Both skip the request trigger entirely, so there is no background decision either. +- A failed `keepalive` fetch still goes through the failure gate, and may be held in heal mode. + +**Request identities and coalescing.** +- Holding requires the identity before the gate. That is why `Request` bodies are read from a clone, bounded to 64 KB and 100 ms. Before this fix, two different `Request` POSTs coalesced into one order (`test/review-fetch.test.ts` -> "two different POST bodies sent as Request objects…"). +- Headers are part of the identity, so `Range` requests for different byte ranges are never identical. +- `headersKey` *merges* a `Request` input's headers with `init.headers`, whereas `fetch(request, { headers })` sends only `init.headers`. Identity can therefore include headers that are never sent (follows from the Fetch spec; no test). XHR identity sees only `setRequestHeader` calls, so a fetch and an XHR match only when their explicit headers match. +- Coalescing must never hang: + - opaque or status-0 responses are shared as clones; + - streaming bodies are given up after 1 s; + - the wait is capped at 8 s, after which the request really sends. + (`test/review-fetch.test.ts` -> describe "review: coalesce never hangs the app's fetch".) +- `shareable` only returns an *earlier* op (lower id). +- `settledAt` is set when the response headers arrive. +- 4xx responses are shareable by coalesce; only 5xx, 429 and 408 resolve to `null`. The GET cache keeps 2xx only. + +**Memory bounds.** +- Buffers are bounded by 64 × 256 KB for the GET cache plus 64 entries / 4 MiB for the coalescing table. `test/review-fetch.test.ts` -> "buffered response bodies stay within the contract's cache bound (64 x 256 KB)" asserts that the bytes held by both together stay ≤ 64 × 256 KB in its 20-URL scenario. +- The abort listener is removed at send or answer. Without that, a long-lived `AbortSignal` would accumulate listeners. +- XHR listeners are added once per object. +- In-flight ops are never pruned. A request that never settles keeps its op forever. +- `ResponseCache.clear()` is never called, not even by `destroy()`. + +**Cost.** +- Every request with a non-empty identity has a clone of its response buffered: up to 256 KB and up to 1 s of streaming. +- Each keystroke creates a user op, even though typing bursts share one event. +- In-flight ops (a connecting WebSocket, a long poll) delay settled points for up to 10 s each. + +**XHR.** +- Faked properties are own properties, and `unfake()` must remove them on the next `open()`. Otherwise a reused XHR shows the stale 503 (`test/review-xhr.test.ts`). +- `abort()` while held must not call native `send`. +- An app `onreadystatechange` assigned *before* the first `open()` runs before GenClass's readyState-4 listener, so it does not see the XHR op ambient. Later listeners (`onload`, `loadend`) do. (unverified: follows from listener registration order; no test) +- `states` is a module-level `WeakMap` shared by every runtime created from the same bundle. + +**Context.** +- `stick` is last-writer-wins. +- Context does not cross un-instrumented `await`s. +- The afterTask clear runs in a posted task. A non-instrumented callback that runs before that task could see a stale ambient op. (unverified: depends on the browser's task ordering; no test) +- The hub applies held writes inside `ctx.run(m.cause, …)`. Subscribers therefore run with the write's cause as the *running* op, and the DOM observer treats events they dispatch as programmatic. + +**Signatures.** +- With no `global.location` (headless runtimes without one), every URL counts as same-origin, so cross-origin hosts drop out of signatures. +- Identity uses the full `href`, including any `#fragment`. +- A `data:` URL puts its whole payload into the op name, because `pathname` is the data. (unverified: follows from `parseUrl` and WHATWG URL semantics; no test) + +**Privacy.** +- Sensitive field values are never recorded. This holds for unlabelled password inputs too (`test/review-dom.test.ts`). +- Values whose target name looks secret are redacted in `RuntimeImpl.user`. +- Request query values go through `redactSearch`. +- Nav routes are recorded and shown in timelines without redaction, and GenClass's own `learn.persist` writes (`localStorage.setItem("genclass.profiles.v1")`) appear as `storage` events. Both are also listed under open issues. + +**Past bugs and their regression tests** (the REVIEW batch; STATUS.md "Batch 3" says all 34 review findings are fixed and the `test/review-*.test.ts` files pass unchanged). Do not regress these: + +| Bug that existed | Fix (where) | Regression test (`packages/runtime/test/…` -> `it(...)`) | +|---|---|---| +| Two different `Request` POST bodies had the same identity and were coalesced into one order | Read a clone of the `Request` body before the gate (`fetch.ts` -> `wrapped`, `readKey`, `IDENTITY_READ_MS`) | `review-fetch.test.ts` -> "two different POST bodies sent as Request objects are not 'identical' (no coalesce of distinct orders)" | +| `Range` requests for different byte ranges counted as identical | Headers in the identity (`headersKey`) | `review-fetch.test.ts` -> "contract gap: concurrent Range requests for different byte ranges of one URL are not 'identical'" | +| Coalescing with an opaque / status-0 response hung the second fetch | `isOpaque` -> share a clone (`cache.ts`) | `review-fetch.test.ts` -> "coalescing with an opaque (status 0) response still settles the second fetch" | +| Coalescing waited for a whole streaming body | `BUFFER_WAIT_MS`, `COALESCE_MAX_WAIT_MS`, fall back to `sendNow()` | `review-fetch.test.ts` -> "coalescing with a still-streaming identical response does not wait for the whole stream" | +| Unbounded buffering | `MAX_BODY`, `MAX_ENTRIES`, `MAX_RECENT`, `MAX_RECENT_BYTES`, `COALESCE_WINDOW_MS` | `review-fetch.test.ts` -> "buffered response bodies stay within the contract's cache bound (64 x 256 KB)" | +| An `abort` listener left on a long-lived `AbortSignal` per request | `unlisten()` at send and at answer | `review-fetch.test.ts` -> "does not leave an abort listener on a long-lived AbortSignal for every finished request" | +| Work after `destroy()` when another library wrapped fetch on top | `disabled` flag; restore only if still ours | `review-fetch.test.ts` -> "after destroy, GenClass does no work even if another library wrapped fetch on top of it" | +| Failures held in guard mode although no failure action was permitted | `RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0` | `review-fetch.test.ts` -> "a failed response is not held for the model when the mode allows no failure action" | +| A `keepalive` (unload) save could be held, so it was not on the wire before the page went away | `gateRequest = !keepalive` | `review-fetch.test.ts` -> "a keepalive request (page-unload save) reaches the network inside the fetch() call, even when salient" | +| A sync XHR was held (cannot be: it completes inside `send()`) | `!st.async` -> `doSend()` | `review-xhr.test.ts` -> "a synchronous XHR is never held: send() returns with the response" | +| An XHR aborted while held was sent later anyway | `wAbort` -> `abortedWhileHeld` | `review-xhr.test.ts` -> "an XHR the app aborts while GenClass holds it is never sent" | +| Listeners accumulated on a reused XHR | `stateOf` adds listeners once per object | `review-xhr.test.ts` -> "reusing one XHR object for many requests does not accumulate listeners (work per request stays constant)" | +| A reused XHR showed the stale faked 503 | `unfake()` in `wOpen` | `review-xhr.test.ts` -> "after a blocked answer, reusing the same XHR shows the real state and response" | +| Recursive `setTimeout` loops built lazy-op chains (stack overflow on the first write, retention) | `LazyOp` parent is always a real op; `materialize()` drops closures | `review-timers.test.ts` -> "a long idle loop (e.g. a clock/heartbeat) does not make the next state write throw", "a polling loop does not retain every past tick's op forever" (gc; needs `NODE_OPTIONS=--expose-gc`, otherwise it logs a skip and passes) | +| An unlabelled password input's value was recorded | `isSensitiveField` (`type=password`) | `review-dom.test.ts` -> "never records a password field's value, even when the field has no label/placeholder/name" | +| `el.click()` by app code inside an op was recorded as a user action | `programmatic(e)` via `runningKind` | `review-dom.test.ts` -> "a programmatic element.click() made by app code inside an op is not recorded as a user action" | +| Init threw on hardened pages with read-only globals | `tryAdd` | `review-misc.test.ts` -> "createRuntime does not throw when a global it would wrap is read-only (frozen/hardened pages)"; `batch3.test.ts` -> "createRuntime never throws on read-only globals (the observer is skipped)" | + +## How to change it safely + +1. **Add a new observer** (e.g. `EventSource`, `BroadcastChannel`). + - Create `packages/runtime/src/observe/<name>.ts` exporting `install<Name>(host)`. It returns an uninstall function, or `null` when the API is missing. + - Use a `disabled` flag, restore the global only if it is still yours, wrap all tracing in try/catch, and use `host.clock`. + - Register it in `RuntimeImpl.installObservers` via `tryAdd` and `on("<name>")`. + - Add the name to `ObserverName` in `packages/runtime/src/types.ts`, to `ALL_OFF` in `packages/runtime/src/index.ts`, and to the observe maps in `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts`, `packages/runtime/test/review-*.test.ts` (`ONLY_*` constants) and `sim/src/run/rt.ts` (set it explicitly to `false` unless SIM wants it). + - Reuse an existing `OpKind` if you can. A new kind touches `OpKind`, `opPhrase` in `packages/runtime/src/situation/describe.ts`, `PROFILED` in `runtime.ts`, and situation text (which needs SIM/TRAIN sign-off). + - Tests to add: install and record; `destroy()` restores the global; pass-through after destroy; a read-only global does not throw. + - App-specific sources can instead use a plugin with `api.recordOp`, `api.endOp` and `api.runInOp` (`RuntimeImpl.pluginApi`). +2. **Change signature normalisation.** + - Edit `isIdSegment`/`isSlugId` in `packages/runtime/src/util.ts`. + - Signatures key the baselines, `storeWriters`, the transition profiles persisted under `genclass.profiles.v1` (old keys stop matching), WS op names and situation text. (`identicalMap` is keyed by request identity, which hashes the full `href`, not the signature.) + - Update `packages/runtime/test/batch3.test.ts` (SIM e). Run the full runtime suite and the sim tests, and re-freeze the situation tag with SIM. +3. **Add a volatile header.** Add it to both `VOLATILE_HEADERS` in `fetch.ts` and `VOLATILE` in `xhr.ts`, so identities stay equal across transports. Update STATUS.md's identity line. +4. **Change cache or buffer limits.** + - Edit the constants in `packages/runtime/src/observe/cache.ts` and `fetch.ts`. + - `test/fetch.test.ts` imports `MAX_BODY`/`MAX_ENTRIES`, and `test/review-fetch.test.ts` asserts the 64 × 256 KB bound. + - Update `docs/runtime/API.md` (`serve_cached` row) and CONTRACT §7. +5. **Add or change a request/failure/stall action.** + - Implement it in the controller (`reqCtl` / `failureGate` / `stallController` in `fetch.ts`, and `ctl` in `xhr.ts`, or throw `unsupported action`). + - Register it in `packages/runtime/src/situation/questions.ts` (`BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`) and gate when it is offered in `packages/runtime/src/situation/build.ts` -> `builtinApplicable`. + - The action set is part of the model's questions, so retraining is needed. See [decide-policy-actions.md](decide-policy-actions.md). + - Always set `synthetic: true` when GenClass answers instead of the network, and mark the response with `x-genclass`. +6. **Carry context across a new async boundary** (`requestAnimationFrame`, `queueMicrotask`, `MessagePort`). + - Copy the timers pattern: capture `ctx.peek()` at schedule time, resolve a `LazyOp` to `.nearest`, and call `ctx.stick(lazyTimer(parent, label))` in the callback. + - Never give a `LazyOp` a `LazyOp` parent, and never keep closures alive after materialisation. + - Re-run `test/review-timers.test.ts`, including the gc test under `NODE_OPTIONS=--expose-gc`. +7. **Change DOM recording.** + - Edit the handler table in `installDomUser`. Keep the `ignoredEvent(e) || programmatic(e)` guard, and the rule that sensitive fields record `""`. + - Run `test/dom.test.ts` and `test/review-dom.test.ts` (happy-dom). + - If `describeElement` output changes, coordinate with SIM: its synthetic targets mimic that format. +8. **Add an event kind or change an event's `data` keys.** + - `EventKind` lives in `packages/runtime/src/types.ts` (public API). + - Event `data` keys are load-bearing: `situation/describe.ts` -> `eventLine` reads `count`, `first` (user), `route` (nav), `key` (storage), `duration` (perf), `summary` (custom), `message` (error); `situation/build.ts` -> `timelineLines` decides relevance by `kind` (`user`, `error`, `action`, `nav` always relevant) and by `e.op` causality; `devtools/index.ts` and `devtools/ui.ts` switch on `kind`. + - Changing any of these changes situation text (`situation-v1`): coordinate with SIM and TRAIN. Re-run `test/situation.test.ts`, `test/dom.test.ts`, `test/devtools.test.ts` and `test/devtools-runtime.test.ts`. +9. **Change op names, `detail` or causality** (timer labels, WS names, user op names, the leading-space body summary, `cause: null` roots). + - These strings reach the model through `opPhrase`/`eventLine`, are mirrored by the sim (`sim/src/run/runner.ts` calls `runtime.user(act, handler)` with `role "name"` targets; `sim/src/run/rt.ts` turns on the real fetch/timers/websocket observers), and key baselines and profiles. + - Re-run `test/context.test.ts`, `test/situation.test.ts`, `test/batch3.test.ts` and the sim's tests; re-freeze with SIM. +10. **Where to run tests.** The project contract (`docs/runtime/CONTRACT.md` §0 rule 5) says every build and test runs on the `train` VM via `scripts/vm.sh`. Under the 2026-10-07 run policy in AGENTS.md, agents on machines other than the original 8 GB Mac may run the build and unit tests locally. Ask the user before Playwright or the sim. The runtime unit tests run with `vitest run` (`npm test`) from `packages/runtime` (config `packages/runtime/vitest.config.ts`: `environment: "node"`, browser specs excluded). See [build-test-release.md](build-test-release.md). + +## Tests + +All paths are under `packages/runtime/test/`. + +| Test file | What it asserts (this scope) | +|---|---| +| `helpers.ts` | `FakeClock` (timers plus a macrotask/microtask/afterTask model), `FakeServer` (virtual fetch), `ScriptedDecider`, `ManualDecider`, and `setup()`, which turns only the fetch observer on | +| `fetch.test.ts` | Neutral traffic makes no model call. The app reads its own body while GenClass reads a clone. `coalesce` reuses an in-flight POST (`x-genclass: coalesced`). `block` returns 503 `blocked` in heal mode, and guard never runs heal actions. `serve_cached` works. `delay` = 250 ms at streak 0. `retry` backs off 200 ms and the app gets attempt 2. `retry` is not offered for stream bodies. A network error is delivered as the original `TypeError`. Failure and request gates fail open at 300 ms. `hedge` wins a stall. Abort before send records `aborted`. `TimeoutError` gives `code: "timeout"`. The GET cache keeps ≤ 64 entries and skips > 256 KB. `destroy()` restores fetch | +| `review-fetch.test.ts` | `Request` bodies are part of the identity. `Range` splits the identity. Coalescing with opaque or streaming responses settles. Buffer memory ≤ 64 × 256 KB. No abort-listener leak. No work after destroy even when wrapped on top. Failures are not held in guard mode (app sees the 503 at +50 ms). `keepalive` is sent synchronously. Identical-request "after/before" direction and error-rate facts | +| `xhr.test.ts` | Op name, detail and cause. The op is ambient in `onload` (the write is attributed to it). `block` fakes a 503 `blocked` without sending. A failure is observed with no action question. The request gate holds and fails open at 300 ms. `destroy()` restores `open`/`send` | +| `review-xhr.test.ts` | A sync XHR is never held. `abort()` while held means never sent. A reused object does not accumulate listeners. Faked values are cleared on the next `open()` | +| `context.test.ts` | user -> fetch -> json -> set gives cause = fetch and root = user. Concurrent chains keep their own causes. `rt.op` is ambient in its body and after it settles. Nested fetch causes. afterTask clears the ambient op. A debounce timer carries the cause (`timer 300ms`). Idle timers create no ops | +| `review-timers.test.ts` | A 200,000-tick recursive `setTimeout` loop followed by a write does not throw. A polling loop does not retain past ticks' ops (gc test) | +| `dom.test.ts` (happy-dom) | `describeElement` names. Clicks are user writes and never held. Typing is one event per burst (`count: 3`, `value: "\"rea\""`). Passwords are never recorded. submit/change/Enter names. `[data-genclass-ignore]` is ignored, including in shadow roots. `destroy()` removes the listeners and restores fetch/XHR/history/Storage/WebSocket/timers. Nav and storage events are recorded. An `ErrorEvent` becomes an `error` trigger (`Uncaught TypeError: boom (at app.js:12).`) | +| `review-dom.test.ts` (happy-dom) | Unlabelled password values are never recorded. A programmatic `el.click()` inside `rt.op` is not a user action | +| `smoke.test.ts` | Context propagates through real awaits (user -> fetch -> json -> set) | +| `batch3.test.ts` | SIM e slug normalisation cases; `createRuntime` never throws on a read-only `fetch` global (the observer is skipped); `GenClass.init` never throws (a plugin whose `setup` throws) | +| `review-misc.test.ts` | `createRuntime` with a non-writable `fetch` does not throw | +| `situation.test.ts` | Determinism: the same scripted inputs on a fake clock give identical situations (depends on sequential op ids and identities) | +| `review-perf.test.ts` | Cost of `rt.user` keystroke writes on large stores (< 1 ms/write) | + +Coverage gaps: there are no unit tests for WebSocket ops and causality, the perf observer, `sessionStorage` area detection, XHR `serve_cached`/`delay`, XHR `responseType` faking, or nav redaction. Also untested: stall `serve_cached`, interval-tick causality, what existing WebSockets/timers do after `destroy()`, two runtimes on one page, and `EventLog`/`OpRegistry` in isolation (they are exercised only through the runtime). The Playwright specs under `test/browser/` cover the model host and the devtools UI, not the observers. + +## Drift and open issues + +Doc-vs-code mismatches (the code is right): + +| What | Doc says | Code does | +|---|---|---| +| Trusted-event filtering | `docs/runtime/ARCHITECTURE.md`: "DOM user events (capture phase, trusted events only)" | Untrusted events are kept unless a non-user op is running or ambient (`dom-user.ts` -> `programmatic`); test drivers rely on this | +| Signature normalisation | `docs/runtime/CONTRACT.md` §3: "numbers, uuids, long hex → `:id`" | Also long mixed tokens (≥ 16 chars) and short slug ids (`util.ts` -> `isIdSegment`, approved SIM e; STATUS.md records it) | +| Body methods that propagate context | CONTRACT §3 lists `json, text, arrayBuffer, blob, formData` | Also `bytes`, and `clone()` returns an instrumented clone (`fetch.ts` -> `instrumentResponse`) | +| Retry backoff | CONTRACT §7: `min(200 ms · 2^attempt, 5 s)` | `min(200 · 2^(attempt−1), 5000)`. STATUS "Deviations" and API.md are correct | +| What never matches | `docs/runtime/API.md`: "Bodies GenClass cannot read cheaply (streams, files, bodies over 64 KB) never match anything" | String bodies up to 1,048,576 chars are hashed and can match; the 64 KB limit applies only to Blob/ArrayBuffer/view/Request bodies (`fetch.ts` -> `bodyInfo`) | +| Identity definition | CONTRACT §3 and the `Op.identity` comment in `types.ts`: "hash of method+url+body" | Also non-volatile headers (`headersKey`) | +| Keepalive / sync XHR | API.md and STATUS: "never held" | They raise no request trigger at all (no background decision); the failure gate still applies to keepalive fetches | +| Observe defaults | `types.ts` `InitOptions.observe` comment: "Default: all true" | `timers` defaults to true only when `global.document` is an object (STATUS.md is correct) | +| Timer op materialisation | `timers.ts` header: "only materializes if the callback starts a request or writes state" | Also on `rt.emit`, `reportError`, storage writes, `rt.op`, WS send and plugin `recordOp`: anything that calls `ctx.op()` | +| `stick` call sites | `trace/context.ts` header: stick happens "after a wrapped fetch/XHR/body method settles, a user action is recorded, or a propagated timer fires" | Also on every WS message (`websocket.ts`) and when `rt.op` settles (`RuntimeImpl.op`) | +| `x-genclass` marking | `packages/runtime/README.md`: "Responses GenClass altered carry an `x-genclass` header" | Opaque responses shared by `coalesce` are unmarked clones. `retry`/`hedge` answers are real network responses (unmarked) | +| UI request | `packages/runtime/UI-NEEDS.md` item 1 (ignore the devtools overlay) is listed as **Open** | Implemented: `ignoredEvent` crosses shadow roots; tested in `test/dom.test.ts` | +| Instrumented sources list | ARCHITECTURE.md omits timers | Timers are an observer (browser-like globals only by default) | +| Pass-through after destroy | `packages/runtime/STATUS.md` module table: observers "all pass through after destroy" | True for the patched globals and prototypes. WebSocket instances and timer callbacks created before `destroy()` keep tracing (`websocket.ts` constructor listeners, `timers.ts` callback wrapper) | +| `Op.code` values | `types.ts` `Op.code` comment: "HTTP status, or an error name such as "TypeError" / "timeout"" | Observers set only HTTP status numbers, `"timeout"`, `"network"`, `"aborted"` and WS close codes; no error names (`fetch.ts`, `xhr.ts`, `websocket.ts`). Only plugin `api.endOp` can set arbitrary codes | +| `afterTask` mechanism | CONTRACT §3: `browserClock` uses "a `MessageChannel` for `afterTask`" | `clock.ts` -> `makeAfterTask`: `setImmediate` when there is no `window` (Node), else `MessageChannel`, else `setImmediate`, else `setTimeout(0)` | +| Which timer callbacks get context | CONTRACT §3 and API.md: "timer callbacks scheduled while an op was ambient" / "inside timers scheduled during an operation" | Every wrapped timer callback gets a `LazyOp`; with no ambient op at schedule time it materialises as a root `timer` op (`timers.ts`) | +| Abort-listener removal | STATUS "Memory": "the abort listener is removed when the request settles" | Removed when the request is **sent** (`send`, primary) or answered (`answer`), whichever comes first (`fetch.ts` -> `runRequest` -> `unlisten`) | +| Observed sources list | `packages/runtime/README.md`: "Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are observed automatically" | Also long tasks (`perf`) and, in browsers, timers | + +Open issues (from code reading; none has a test): +- Nav routes, including query strings and fragments, are not redacted. They go into `nav` events and are always "relevant" in situation timelines (`situation/build.ts` -> `timelineLines`). +- `ResponseCache` is not cleared on `destroy()`. +- `data:` URL fetches produce op names that contain the payload (unverified). +- XHR: an app `onreadystatechange` assigned before `open()` misses the ambient op (unverified). +- Header parity between `VOLATILE_HEADERS` and `VOLATILE` is not exact (e.g. `x-datadog-tags` is volatile only for XHR). +- `learn.persist` writes show up as `storage` events. +- Existing `GenClassWebSocket` instances and already-scheduled timer callbacks keep tracing after `destroy()` (see "After destroy: what still runs"). +- WebSocket disconnects after `open` (error or close) are invisible: no op, no event, no trigger. +- `setInterval` ticks all keep the scheduling op as their parent, so a long-running interval started inside a user action keeps attributing its writes to that action's causal chain. +- Hedge op detail for a GET without a query is `(hedge)`, so `opPhrase` prints `GET /api/x(hedge)` with no space (`.trim()` removes the separator). Changing it touches situation text (`situation-v1`). +- Two runtimes on one page double-wrap every global (one op per runtime per request). +- `wrappedFetch.__genclass = true` is set but never read anywhere in the repo. +- Enter/Escape auto-repeat is not filtered, so holding Enter records many `key` user ops. + +From STATUS.md / OPEN_TASKS.md (relevant here): +- The `situation-v1` freeze: OPEN_TASKS "Done" records runtime fix batch 3 as frozen at tag `situation-v1`, and STATUS "Open issues" says any change to situation wording must be coordinated with SIM. Op names, details and event names reach situation text (see "Determinism and sim parity"), so they fall under the same rule. +- OPEN_TASKS #6 "hold-induced harm": with model v0.1, search clean-run latency rose from 14 ms to 125 ms because salient *writes* were held. "Triage sensitivity on naturally concurrent apps": typeahead was salient about 6 times per trial on clean runs. Whether request-gate holds contribute is not stated there (unverified). +- Known risk: on slow devices, hold budgets expire more often (more fail-open decisions). + +## Related docs + +- [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, options, kill switch, `destroy` +- [state-and-adapters.md](state-and-adapters.md): how state writes use the ambient op (`StoreHub.propose`, user-sync bypass, held writes) +- [learn-situation-triage.md](learn-situation-triage.md): baselines, identical-request facts, timeline lines from events, triage +- [decide-policy-actions.md](decide-policy-actions.md): `RuntimeImpl.trigger`, hold budget, policy gate, action records, late revert +- [model-host.md](model-host.md): model download with the native `fetch` +- [devtools.md](devtools.md): overlay under `data-genclass-ignore`; consumes `on("event")` +- [build-test-release.md](build-test-release.md): where and how to run the tests +- [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md): parity of situation text and the sim's use of these observers +- [../overview.md](../overview.md#3-runtime-data-flow-end-to-end) (where observers sit in the end-to-end flow), [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../repo-map.md](../repo-map.md), [../../../AGENTS.md](../../../AGENTS.md) +- Original specs: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) (§3, §6, §7), [../../runtime/API.md](../../runtime/API.md), [../../runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [../../../packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md) diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md new file mode 100644 index 00000000..092b7f7c --- /dev/null +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -0,0 +1,641 @@ +# @genclass/runtime: public API, options and lifecycle + +> **Scope:** `packages/runtime/src/index.ts`, `packages/runtime/src/runtime.ts` (wiring, construction, init/destroy, modes, kill switch, option resolution, events, plugins, introspection, settled points), `packages/runtime/src/types.ts`, `packages/runtime/src/errors.ts`, `packages/runtime/src/clock.ts`, `packages/runtime/src/util.ts`, `packages/runtime/package.json`. +> **Read this when:** you add or change an init option, a `Runtime` method, an event, a plugin hook or a subpath export; you touch `GenClass.init` / `createRuntime` / the kill switch / `destroy()`; you need the exact default of any option; you add timing or scheduling code; you wire a new subsystem into `RuntimeImpl`. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- Two entry points: `GenClass.init(options)` (browser facade: singleton, never throws, kill switch, loads the local model by default) and `createRuntime(options)` (headless: tests, sim, SSR; no model unless `decider` or `model: {...}` is passed). Both return a `RuntimeImpl` typed as `Runtime`. `createRuntime` can throw on malformed options; `GenClass.init` never throws (it falls back to an inert runtime). +- `GenClass.init` is idempotent: a second call returns the first runtime and **ignores its new options**. Only `GenClass.destroy()` clears the singleton; `rt.destroy()` alone does not. +- Three modes: `observe` (never changes execution, nothing held), `guard` (default; guard-tier actions only), `heal` (guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. +- Kill switch: `?genclass=off` (URL wins) or `localStorage.genclass = "off"` gives an inert runtime; the values `observe|guard|heal` override `options.mode`. +- The decider (`DecisionProvider`) is the only seam to the model. `createRuntime` builds a model host (`createModelHost`) only when `options.decider === undefined` and `options.model` is an object; the runtime then **owns** it and disposes it on `destroy()`. A caller-supplied decider is never disposed. +- The runtime consults the decider only while its `status.state` is `"ready"` or `"off"` (lazy). `"loading"` and `"error"` mean every trigger fails open at once (passive action, nothing held, no decision recorded). +- Everything time-related goes through the injected `Clock` (`browserClock` by default). Runtime code never calls `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`; ids come from counters. This is what makes the sim deterministic and keeps train/runtime parity. +- Construction order matters: core subsystems, then queue/reporter/env, hub hooks, event and status subscriptions, persisted profiles, observers (each wrapped in try/catch), then plugins. `destroy()` is idempotent and tears down in roughly reverse order. +- A **settled point** is reached `settleMs` (default 60 ms) after the last op end / applied write / discarded write, when nothing younger than 10 s is in flight and no write is pending. Invariants and transition profiles are learned there and `inconsistency` / `transition` triggers are raised there. +- Events: `detect`, `decide`, `act`, `event`, `status`, `report` via `rt.on(type, fn)`; listener exceptions are swallowed (logged with `debug: true`). +- `util.ts` helpers (`secs`, `fmtNum`, `describe`, `normalizePath`, `isSensitiveName`, ...) shape the situation text. Changing them changes the frozen `situation-v1` format and breaks train/runtime parity. + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `packages/runtime/src/index.ts` | Public facade and root module | `GenClass` (also `default`), `createRuntime`, re-exports (see [Root module exports](#root-module-exports)); private `killSwitch`, `initUnsafe`, `makeHost`, `failedProvider`, `NATIVE_FETCH`, `MODES`, `ALL_OFF` | +| `packages/runtime/src/runtime.ts` | `RuntimeImpl`: wires trace, state, learn, situation, decide and observers; implements every `Runtime` method; actions that need runtime state (rollback, chain revert, resync, late revert); settled points | `RuntimeImpl`, `RuntimeInternals`, `normalizeError`, type re-exports `SituationDraft`, `BuiltSituation` | +| `packages/runtime/src/types.ts` | Every public and shared type. Header: CORE owns it; the "model seam" section (top) is shared with MODEL (`src/model/**`) and mirrored by `sim/src/types.ts` | `InitOptions`, `CreateOptions`, `ModelOptions`, `PolicyOptions`, `Runtime`, `RuntimeEvents`, `Plugin`, `PluginApi`, `DecisionProvider`, `Clock`, ... | +| `packages/runtime/src/errors.ts` | The one runtime-level error class | `GenClassUnavailableError` | +| `packages/runtime/src/clock.ts` | Real clock; captures timers at module load | `browserClock` | +| `packages/runtime/src/util.ts` | Deterministic helpers: hashing, stable stringify, number/time formatting, redaction, value descriptions, URL signatures | see [util.ts helpers](#utilts-helpers) | +| `packages/runtime/package.json` | Package manifest: exports map, bin, deps, peer deps | `exports`, `bin.genclass-runtime` | +| `packages/runtime/tsup.config.ts` | Build entries (one per subpath export, including `worker`) | `entry`, `dts.entry`, `external` | + +Read-only neighbours this doc leans on: `src/decide/policy.ts` (`policyConfig`, `holdBudget`, `gate`), `src/decide/decider.ts` (`DeciderQueue`), `src/decide/report.ts` (`Reporter`), `src/model/host.ts` (`createModelHost`, `DEFAULT_MODEL_BASE_URL`), `src/situation/serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`), `src/trace/events.ts` (`EventLog`), `src/state/hub.ts` (`StoreHub`). + +## Concepts and data structures + +Terms introduced in this doc: + +| term | meaning | +|---|---| +| facade | `GenClass` in `index.ts`: the singleton wrapper around `createRuntime` for apps. | +| inert runtime | A `RuntimeImpl` with every observer off (`ALL_OFF`), no decider, `report: "silent"`, `mode: "observe"`. Stores, `op`, `emit`, `user` still work (they record), nothing is ever held or asked. | +| owned decider | A model host that `createRuntime` created itself (`ownsDecider: true`). Only owned deciders are `dispose()`d by `destroy()`. | +| consultable | `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists, and its `status.state` is `"ready"` or `"off"`. Triggers and holds happen only when consultable. | +| lazy preload | When a salient trigger finds the decider not ready, the runtime reads `this.ready` (which calls `decider.ready()` once) and fails open for that trigger. | +| budget scale | `RuntimeImpl.budgetScale`, starts at 1; multiplied by 0.8 (floor 0.5) each time the decider errors with `code === "max_tokens_exceeded"`; applied to the automatic situation budget only. | + +### Package exports (`packages/runtime/package.json`) + +ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.0`, license Apache-2.0. + +| subpath | types | import | source entry (tsup) | documented in | +|---|---|---|---|---| +| `@genclass/runtime` | `./dist/index.d.ts` | `./dist/index.js` | `src/index.ts` | this doc | +| `@genclass/runtime/react` | `./dist/adapters/react.d.ts` | `./dist/adapters/react.js` | `src/adapters/react.ts` | [state-and-adapters.md](state-and-adapters.md) | +| `@genclass/runtime/redux` | `./dist/adapters/redux.d.ts` | `./dist/adapters/redux.js` | `src/adapters/redux.ts` | [state-and-adapters.md](state-and-adapters.md) | +| `@genclass/runtime/zustand` | `./dist/adapters/zustand.d.ts` | `./dist/adapters/zustand.js` | `src/adapters/zustand.ts` | [state-and-adapters.md](state-and-adapters.md) | +| `@genclass/runtime/devtools` | `./dist/devtools/index.d.ts` | `./dist/devtools/index.js` | `src/devtools/index.ts` | [devtools.md](devtools.md) | +| `@genclass/runtime/worker` | (none) | `./dist/worker.js` | `src/model/worker.ts` | [model-host.md](model-host.md) | +| `@genclass/runtime/package.json` | | `./package.json` | | | + +- Legacy top-level fields: `main` and `module` = `./dist/index.js`, `types` = `./dist/index.d.ts` (same targets as the `.` export). `repository.directory` = `packages/runtime`. +- `bin`: `genclass-runtime` -> `./bin/genclass-runtime.mjs`: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` and `info <dir>` (details in [model-host.md](model-host.md)). +- `dependencies`: `onnxruntime-web ^1.30.0` (the only runtime dependency; CONTRACT §0 forbids adding others without the lead). +- `peerDependencies` (all optional via `peerDependenciesMeta`): `react >=18`, `redux >=4`, `zustand >=4`. +- `devDependencies`: `@playwright/test 1.63.0`, `@types/react ^19.0.0`, `@types/react-dom ^19.0.0`, `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `react ^19.3.0`, `react-dom ^19.3.0`, `redux ^5.0.1`, `tsup ^8.5.1`, `typescript ~5.9.3`, `vitest ^5.0.3`, `zustand ^5.0.15`. +- `files`: `dist`, `bin`, `README.md`, `LICENSE`. Scripts: `build` (tsup), `typecheck` (`tsc -p tsconfig.json --noEmit`), `test` (`vitest run`), `test:browser` (`playwright test --config test/browser/playwright.config.ts`). +- `tsup.config.ts`: ESM only, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`. `worker` has no `.d.ts` (not in `dts.entry`). +- Git tags: `situation-v1` (situation-format freeze) and `v0.1.0-alpha.0` (the published alpha). + +### Root module exports + +| export | kind | from | +|---|---|---| +| `GenClass` (named and `default`) | const object | `src/index.ts` | +| `createRuntime` | function | `src/index.ts` | +| every type in `types.ts` (`export *`) | types only (`types.ts` has no runtime values) | `src/types.ts` | +| `browserClock` | `Clock` | `src/clock.ts` | +| `GenClassUnavailableError` | class | `src/errors.ts` | +| `createModelHost`, `DEFAULT_MODEL_BASE_URL`; types `ModelHost`, `ModelHostOptions`, `ModelHostStatus`, `ModelHostStats`, `ModelEvaluateRequest` | model host | `src/model/host.ts` | +| `GenClassModelError`, `ModelNotReadyError`, `MaxTokensExceededError`, `ModelInputError`, `ModelUnsupportedError`, `ModelTimeoutError`, `ModelAbortedError`, `ModelBusyError`, `ModelDisposedError`, `ModelLoadError`, `ModelIntegrityError`, `ModelInferenceError`; types `ModelErrorCode`, `LoadAttempt` | model errors (each has `code`) | `src/model/errors.ts` | +| `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET` (3200), `COMPACT_BUDGET` (1100) | serializer | `src/situation/serialize.ts` | +| `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` | question vocabulary | `src/situation/questions.ts` | +| `describeElement` | DOM element -> `'button "Place order"'` | `src/observe/dom-user.ts` | +| `RuntimeImpl` | class (advanced; exposes internals) | `src/runtime.ts` | + +Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/`holdBudget`/`gate`, `COMPACT_QUESTIONS_BUDGET` (1400). + +### Modes and tiers + +`Mode = "observe" | "guard" | "heal"`; `Tier = "passive" | "guard" | "heal"` (`types.ts`). The mode-tier rule is `src/decide/policy.ts` -> `modeAllows`: + +| mode | permitted tiers | holds | notes | +|---|---|---|---| +| `observe` | passive only | never (`trigger()` never waits because `permittedActions` is empty; `hub.hooks.mayHold` also returns false, so the hub does not protect live state from in-place updaters) | Decisions are still made in the background (deadline 5,000 ms) and recorded, so detections and reports work. | +| `guard` (default) | passive, guard (`discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions) | when a guard action is permitted for the trigger | | +| `heal` | passive, guard, heal (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (`rt.action` or plugins), which default to heal) | when any non-passive action is permitted | | + +Threshold defaults (`policyConfig`): `report` 0.6, `guard` 0.9, `heal` 0.8. The full gate is in [decide-policy-actions.md](decide-policy-actions.md). + +### `InitOptions` (`types.ts` -> `InitOptions`) + +Defaults below are what `RuntimeImpl`'s constructor applies, unless the row says otherwise. `GenClass.init` changes some of them per path (see [GenClass.init](#1-genclassinitoptions)). + +| option | type | default | effect / where read | +|---|---|---|---| +| `mode` | `Mode` | `"guard"` (`o.mode ?? "guard"`) | Initial mode; the kill switch overrides it in `GenClass.init`. Change later with `setMode`. | +| `model` | `ModelOptions \| false` | `GenClass.init` in a browser: `{}` (load the local model with defaults) unless `decider` is given or `model === false`. `createRuntime`: no model unless an object is passed. | Read only in `index.ts` -> `createRuntime`; `RuntimeImpl` never reads it. | +| `decider` | `DecisionProvider \| null` | `undefined` | Any provider (test double, sim, custom). Wins over `model`. `null` means "no model" even if `model` is an object. | +| `report` | `"console" \| "silent" \| (r: Report) => void` | `"console"` | Report sink (`Reporter`). `GenClass.init` defaults it to `"silent"` outside a browser. `on("report")` listeners get every report regardless of the sink. | +| `observe` | `Partial<Record<ObserverName, boolean>>` | every observer on, except `timers`, which is on only when `global.document` is a non-null object | `RuntimeImpl.installObservers`; unknown keys ignored. Forced to all-off outside a browser, by the kill switch and in the init fallback. | +| `triage` | `"salient" \| "always"` | `"salient"` | `"salient"`: ask only when some fact is non-neutral (or a standing question has `always: true`). `"always"`: build and ask for every consultable trigger (tests). | +| `policy` | `PolicyOptions` | see [PolicyOptions](#policyoptions) | `policyConfig(o.policy)` once at construction (not changeable later). | +| `redact` | `(path: string, value: unknown) => unknown` | `util.ts` -> `defaultRedact` | Return something `!==` value to redact. Used by the hub, invariant miner, observers, `emit`, `user`, situation building. | +| `plugins` | `Plugin[]` | `[]` | Installed with `use()` at the end of the constructor. | +| `historySize` | `number` | `500` | `EventLog` ring buffer size; effective minimum 16 (`new Array(Math.max(16, size))` in `src/trace/events.ts` -> `EventLog`). `NaN`, or a non-integer of 16 or more, makes `new Array(...)` throw `RangeError` in the constructor (`createRuntime` throws; `GenClass.init` falls back to the inert runtime); a fraction below 16 is silently raised to 16. | +| `debug` | `boolean` | `false` | `RuntimeImpl.log` -> `console.debug("[GenClass] ...")`: every decision, plus otherwise-silent failures (observer install, plugin setup, listener, model, passive/situation build errors). | +| `learn` | `{ persist?: boolean }` | `persist: false` | Transition profiles to `global.localStorage` key `genclass.profiles.v1`: loaded at construction; a settled point that had queued ops to profile schedules one write 5,000 ms later (`saveProfilesSoon`; not a debounce: while a write is pending, later settled points do not reschedule it). | +| `vocabulary` | `Vocabulary` (`{ diagnoses?: Record<string,string>; actions?: Partial<Record<string,string>> }`) | `undefined` | `diagnoses` replaces `DEFAULT_DIAGNOSES`; `expected` is always kept (added from the defaults if missing, always first) and plugin labels are added only when the label is not already present (`situation/questions.ts` -> `diagnosisVocabulary`). `actions[name]` overrides the description of a built-in **or custom** action (`actionDescription`: vocabulary, then `ActionDef.description`, then built-in). Changes model input wording. | +| `settleMs` | `number` | `60` | Quiet time before a settled point. | +| `situation` | `{ budget?: number \| "auto" }` | `"auto"` | Situation size in characters. A number is used as is (no device sizing, no budget scale). See `situationBudget()`. | + +### `CreateOptions` (`types.ts` -> `CreateOptions extends InitOptions`) + +| option | type | default | effect | +|---|---|---|---| +| `clock` | `Clock` | `browserClock` | All time and scheduling of this runtime (and of a model host it creates). | +| `global` | `object` | `globalThis` | The object whose `fetch`, `XMLHttpRequest`, `WebSocket`, `addEventListener`, timers, `history`, `localStorage`... are instrumented; also used for `app()` defaults, `location.href` (URL resolution) and `learn.persist` storage. Not used by the kill switch, `browserClock`, console reporting or the model host's idle scheduling (those use `globalThis`). | +| `app` | `() => { title?: string; route?: string }` | `global.document.title` and `global.location.pathname` (`RuntimeImpl.appInfo`) | App line of every situation. | +| `hooks` | `RuntimeHooks` | `{}` | `opCreated(op)` (sync, in `startOp`) and `mutationProposed({ id, store, paths, cause?, changes })` (sync, inside `set`, before gating). Exceptions swallowed. | + +`RuntimeImpl`'s constructor additionally accepts internal fields `decider?: DecisionProvider | null` (already resolved) and `ownsDecider?: boolean`; `createRuntime` sets both. + +### `ModelOptions` (`types.ts` -> `ModelOptions`; defaults applied in `src/model/host.ts`) + +| option | type | default | defined in | +|---|---|---|---| +| `baseUrl` | `string` | `DEFAULT_MODEL_BASE_URL` = `"https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/"`, resolved against `globalThis.location.href` | `model/host.ts` -> `DEFAULT_MODEL_BASE_URL`, `resolveBaseUrl` | +| `device` | `"auto" \| "webgpu" \| "wasm"` | `"auto"` | `model/host.ts` -> `Host` constructor | +| `worker` | `boolean` | `true` (only `false` disables the module Worker; inline fallback otherwise) | `model/host.ts` -> `Host.start` | +| `preload` | `"eager" \| "idle" \| "lazy"` | `"idle"`: after the `load` event (or at most 5,000 ms), then `requestIdleCallback` with a 2,000 ms timeout, or a 1,000 ms clock timer when it is missing | `model/host.ts` -> `scheduleIdle` | +| `ortWasmPaths` | `string` | `https://cdn.jsdelivr.net/npm/onnxruntime-web@<installed ORT version>/dist/` (fallback version `1.30.0`) | `model/backend.ts` -> `ortCdnBase` | +| `cacheName` | `string` | `"genclass-runtime-v1"` (Cache Storage) | `model/loader.ts` -> `DEFAULT_CACHE_NAME` | + +`createRuntime` adds `fetch` (see [createRuntime](#2-createruntimeoptions)) and `clock` before calling `createModelHost`. Host-only knobs (`timeoutMs` 10,000, `maxQueue` 32, `maxThreads`, ...) are in `ModelHostOptions`, not `ModelOptions`; to set them, build a host with `createModelHost` and pass it as `decider` (then the runtime does not own it). Details: [model-host.md](model-host.md). + +### `PolicyOptions` + +Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). Defaults from `src/decide/policy.ts` -> `policyConfig`. + +| field | default | +|---|---| +| `thresholds` | `{ report: 0.6, guard: 0.9, heal: 0.8 }` | +| `allow` | unset (all applicable actions) | +| `deny` | `[]` | +| `holdBudgetMs` | `"auto"`: `clamp(round(1.5 × median of the last 20 provider latencies, else status.warmupMs), 150, 800)`; 300 when neither is known (`HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS`). A number is used as `Math.max(0, n)` (no clamp to 150..800). | +| `holdUserWrites` | `false` (copied to `hub.holdUserWrites`) | +| `maxActionsPerMinute` | `60` | +| `requireDiagnosis` | `true` | + +### The `Runtime` interface (`types.ts` -> `Runtime`; all implemented in `runtime.ts` -> `RuntimeImpl`) + +| member | signature | what it does | owning doc | +|---|---|---|---| +| `ready` | `readonly ready: Promise<void>` | Getter. No decider: `Promise.resolve()`. Otherwise calls `decider.ready()` once and memoises the promise (also starts a lazy load). Rejects if the load fails, and keeps returning that rejected promise. | [model-host.md](model-host.md) | +| `status` | `readonly status: ModelStatus` | `decider.status`, or `{ state: "off" }` without a decider. | [model-host.md](model-host.md) | +| `mode` | `readonly mode: Mode` | Current mode. | this doc | +| `atom` | `atom<T>(name, initial, opts?): Atom<T>` | Register (or reuse) a GenClass-owned store. Same name and kind `"atom"`: returns a handle to the existing store, ignores `initial`, merges `opts` when `resync`/`describe`/`hold` given. Any other existing store of that name is replaced. | [state-and-adapters.md](state-and-adapters.md) | +| `guard` | `guard<T>(name, io: StoreIO<T>, opts?): Guarded<T>` | Wrap an app-owned store; always (re)registers, replacing a same-name store. | [state-and-adapters.md](state-and-adapters.md) | +| `adapter` | `adapter<T>(name, io: AdapterIO<T>, opts?): AdapterHandle<T>` | Seam for state libraries: `propose({ fn?/value?, commit })`, `dispose()`. `writable` only when `io.set` exists. | [state-and-adapters.md](state-and-adapters.md) | +| `expect` | `expect(name, predicate: () => boolean): () => void` | Developer invariant, checked at settled points (`miner.addExpect`). Returns a remover. | [state-and-adapters.md](state-and-adapters.md) | +| `ask` | `ask<Q extends Question>(q, opts?: AskOptions): Promise<AnswerOf<Q>>` | Ask the model about the current situation (trigger `ask`). See [ask flow](#6-ask-and-decide). | [model-io-contract.md](../model-io-contract.md) | +| `decide` | `decide<L extends string>(question, options: Record<L,string>, opts?): Promise<L>` | `ask({ type: "choice", instructions: question, criteria: options })` and return `.choice`. | this doc | +| `on` | `on<K extends keyof RuntimeEvents>(type, fn): () => void` | Subscribe; returns an unsubscribe function. An unknown `type` (bypassing TypeScript) throws `TypeError` (no listener `Set`). Listeners are snapshotted per fire, so (un)subscribing inside a listener takes effect from the next fire. | [Events](#events-runtimeevents) | +| `op` | `op<T>(name, fn, meta?): Promise<T>` | Run `fn` as a `"task"` op (ambient while it runs and when it settles). `meta.detail` (string) becomes the op detail. A sync throw ends the op with `"error"` and returns a rejected promise (never throws synchronously). | [observe-and-trace.md](observe-and-trace.md) | +| `emit` | `emit(name, data?): void` | Push a `custom` event under the ambient op. Each `data` value goes through `redact(key, value)`; a `summary` key (`k=v ...`, truncated to 80 chars) is added. | [observe-and-trace.md](observe-and-trace.md) | +| `user` | `user<T>(action: UserAction, handler?): T \| undefined` | Record an instantaneous `"user"` op (`cause: null`) named `` `${kind} ${target}` `` and run `handler` inside it (returns its result; `undefined` without a handler). `kind` falls back to a legacy `action.action` field, then `"action"`. `value` becomes `"[redacted]"` when `sensitive` or `redact(target, value)` changes it, and is stored as the op `detail` JSON-quoted and truncated to 40 chars. Consecutive `type` actions on the same target within 1,000 ms (`TYPING_BURST_MS`) update one event (`data.count`). | [observe-and-trace.md](observe-and-trace.md) | +| `reportError` | `reportError(error, info?: { source? }): void` | No-op after destroy. Normalises (`normalizeError`), records an `error` event, raises the `error` trigger (not held, priority 0). Its `rollback` controller (`revertChain`) needs the ambient op at report time; without one it throws (recorded as a failed action, passive runs); applicability normally keeps it from being offered then. Keeps the last 64 errors (10 s window) for facts. | [decide-policy-actions.md](decide-policy-actions.md) | +| `use` | `use(plugin): () => void` | Install a plugin (idempotent per object). | [Plugins](#plugin-api) | +| `action` | `action(def: ActionDef): () => void` | Add a custom action; returns a remover. No name de-duplication. | [decide-policy-actions.md](decide-policy-actions.md) | +| `question` | `question(def: StandingQuestion): () => void` | Add a standing question; returns a remover. | [decide-policy-actions.md](decide-policy-actions.md) | +| `situation` | `situation(trigger?): Situation` | With a non-`ask` trigger that was built before: the **last situation built for that trigger** (`lastBuilt`). Otherwise builds "ask about now" and, if a trigger was given, returns it with `trigger` overwritten. Records nothing (only caches `op.reads`). | [learn-situation-triage.md](learn-situation-triage.md) | +| `explain` | `explain(id): Explanation \| null` | Decision id `"d<n>"` or action id `"a<n>"` -> message, decision, situation text, facts, timeline, answers, action, changed. The decision and its action share one record, so `explain("d<n>")` of a decision whose action ran also returns `action`/`changed` and the intervention line as `message` (else the detection line when detected, else `decisionLine`). Eviction: when a decision is recorded and the map exceeds 400 (`DECISIONS_KEPT * 2`), the single oldest entry is deleted; action entries (`a<n>`) are added in `finish` without any eviction check, so the map grows by one entry per executed action beyond 400 (see Drift). | [decide-policy-actions.md](decide-policy-actions.md) | +| `history` | `history(n?): RtEvent[]` | `events.last(n)`: last `n` events (default all kept), oldest first. `history(0)` is empty; `k = Math.min(n, count)`, so a negative `n`, or a fractional `n` below the number of kept events, throws `RangeError` (`new Array(k)`). | [observe-and-trace.md](observe-and-trace.md) | +| `decisions` | `decisions(n = 200): Decision[]` | Last `n` decisions (buffer of 200). Note `decisions(0)` returns all (`slice(-0)`). | [decide-policy-actions.md](decide-policy-actions.md) | +| `interventions` | `interventions(n = 200): ActionRecord[]` | Last `n` non-passive actions that ran (buffer of 200). Same `0` quirk. | [decide-policy-actions.md](decide-policy-actions.md) | +| `inflight` | `inflight(): Op[]` | Snapshot array of in-flight ops. The elements are live internal `OpRec` objects: do not mutate. | [observe-and-trace.md](observe-and-trace.md) | +| `holdBudgetMs` | `holdBudgetMs(): number` | `holdBudget(policy, queue.latencies(), decider?.status.warmupMs)`. | [decide-policy-actions.md](decide-policy-actions.md) | +| `situationBudget` | `situationBudget(): number` | See [Configuration](#configuration-and-constants). | [learn-situation-triage.md](learn-situation-triage.md) | +| `setMode` | `setMode(mode): void` | Ignores anything but the three modes. Sets the mode, emits a status report `"[GenClass] Mode set to <mode>."` and fires `status` with the current `ModelStatus` (even if unchanged). | this doc | +| `pause` | `pause(): void` | `paused = true`, `hub.gating = false`: no triggers, no holds, requests not gated; tracing continues. `ask()` still works. | this doc | +| `resume` | `resume(): void` | No-op after destroy; else `paused = false`, `hub.gating = true`. | this doc | +| `destroy` | `destroy(): void` | Idempotent teardown; see [destroy order](#9-destroy). | this doc | + +`RuntimeImpl` members that are **not** on `Runtime` (use only from tests, the sim, devtools or internal code; cast to `RuntimeImpl`): + +| member | purpose | +|---|---| +| `clock`, `global`, `events`, `ops`, `ctx`, `hub`, `base`, `profiles`, `miner`, `cache` | Public readonly subsystem fields (tests read `rt.ops.byId`, `rt.hub` ...). | +| `internals` (getter) | `RuntimeInternals = { hub, ops, events, base, profiles, miner, ctx, clock }`. | +| `isPaused` (getter) | Whether `pause()` is in effect. No caller in the repo. | +| `setReport(sink)` | Swap the report sink at runtime (`Reporter.setSink`). JSDoc says "(devtools)" but nothing in the repo calls it. | +| `constructor(o: CreateOptions & { decider?, ownsDecider? } = {})` | Direct construction never reads `o.model` (no model host is created) and ignores the kill switch; use `createRuntime` unless you are resolving the decider yourself. | +| `build(spec: SubjectSpec): BuiltSituation` | Build a situation for a subject spec without triggering. | +| `trigger(spec, ctl, opts)` | Entry point for observers: triage, hold, queue, gate, act (see [decide-policy-actions.md](decide-policy-actions.md)). | +| `startOp(kind, name, o?)`, `endOp(op, status, o?)` | Op creation/completion with events, baselines, profiling queue, `hooks.opCreated`, settle scheduling. | +| `runAsGenClass(name, fn)` | Run `fn` inside an instant `"genclass"` op (`cause: null`): its writes and requests are never gated. | +| `settled()` | Run a settled point now (normally called by the settle timer). | +| `chainWrites(op)`, `revertChain(op, why)`, `rollback(stores, violationIds?, beforeSeq?)`, `resync(stores)` | Action implementations for error/transition/inconsistency triggers. | + +### Events (`RuntimeEvents`) + +| type | payload | fired from | when | +|---|---|---|---| +| `detect` | `Detection` (= `Decision`) | `RuntimeImpl.onDecision` | `decision.diagnosis !== "expected"` and `diagnosisConfidence >= policy.thresholds.report` (0.6), whether or not an action ran. Fired right after `decide`. | +| `decide` | `Decision` | `RuntimeImpl.onDecision` | Every model decision on a trigger (not for `ask`/`decide` calls, not while loading, not for triage-skipped triggers, and not when the queue returns no answer: deadline passed, queue overflow, provider error or timeout, runtime destroyed). | +| `act` | `ActionRecord` | `onDecision` -> `finish` | Every non-passive action that ran (also failed ones, `ok: false`), after its effect resolved. | +| `event` | `RtEvent` | `EventLog.onEvent` / `EventLog.touch` | Every traced event; a typing burst re-fires the same (mutated) event object. | +| `status` | `ModelStatus` | `decider.onStatus` subscription; `setMode` | Model status changes; also on every `setMode` call (devtools refreshes its mode view on it). | +| `report` | `Report` (`{ kind: "detect" \| "intervene" \| "status", message, decision?, action? }`) | `Reporter.emit` listener | Every report, before the sink: also with `report: "silent"`, and without the console's one-minute de-duplication. | + +Order inside one decision (`RuntimeImpl.onDecision`): `event` (an `RtEvent` of kind `"decision"`) -> `decide` -> `detect` (if detected) -> standing-question `onAnswer` callbacks -> either (no action runs: `ctl.passive()`, then a `report` detect line if detected) or (action runs: `rate.take`, the action, and once its effect resolves or fails: `event` (kind `"action"`) -> `act` -> `report` intervene line). A failed action (throw or rejection) runs the passive action first and records `ok: false`. + +Trigger priorities (`EvaluateRequest.priority`, higher is served first by `DeciderQueue`): held `mutation` (`gateMutation`), `request` and fetch `failure` = 2; `stall`, `inconsistency`, XHR `failure`, `ask` = 1; `transition`, `error` = 0. A holdable trigger that does not actually wait is capped at 1 (`Math.min(priority, 1)` in `trigger`). + +Status reports emitted by the runtime itself: `"[GenClass] Model ready (<model>, <device>, <variant>, <secs>). Mode: <mode>."`, `"[GenClass] Model unavailable (<error>); observing only."`, `"[GenClass] Mode set to <mode>."`, `"[GenClass] Rate limit reached (<n> actions/minute): running passive actions until it clears."` (at most once per 60,000 ms). + +### Plugin API + +`Plugin` (`types.ts`): `{ name; setup?(api: PluginApi): void | (() => void); facts?(sit: SituationDraft): string[]; actions?: ActionDef[]; questions?: StandingQuestion[]; diagnoses?: Record<string, string> }`. + +`RuntimeImpl.use(plugin)`: +1. Already installed (same object): return a remover, do nothing else. +2. Register `plugin.actions` into `customActions` and `plugin.questions` into `standing` (before `setup` runs). +3. Call `plugin.setup(this.pluginApi())` in try/catch; a returned function is kept as cleanup. A throwing `setup` is only logged with `debug: true`; the plugin's actions/questions/facts stay registered. +4. `facts` and `diagnoses` are read live at every situation build (`RuntimeImpl.buildOpts`), in plugin insertion order. +5. The remover (`unuse`) removes exactly this plugin's action and question objects (by identity) and calls cleanup (errors ignored). `destroy()` unuses every plugin. + +`PluginApi` (built by `RuntimeImpl.pluginApi`): + +| member | behaviour | +|---|---| +| `runtime`, `clock` | The runtime and its clock (devtools installs a plugin whose `setup` only captures `api.clock`, the runtime's clock, virtual in tests/sim). | +| `emit(name, data?)` | Same as `rt.emit`. | +| `recordOp(kind, name, meta?)` | `startOp(kind, name, { detail?, identity?, meta: meta.data })`, cause = ambient op; returns the op id. Not instant. `fetch`/`xhr` kinds feed latency baselines. | +| `endOp(id, status = "ok", info?)` | Ends the op (`code`, `errorText` from `info.error`); silently ignored when the id is unknown or pruned. | +| `runInOp(id, fn)` | Run `fn` with that op ambient; runs `fn` without context when the id is unknown. | +| `user`, `reportError`, `on` | Same as the `Runtime` methods. | +| `stores.names()`, `stores.get(name)` | Registered store names; current value via `hub.read` (or `undefined`). The value is not cloned: do not mutate it. | + +Note: `pluginApi()` builds a fresh object per `use()` call; it holds no per-plugin state, so ops started with `recordOp` are not ended when the plugin is removed. + +`ActionDef`, `ActionContext` (`builtin`, `describe`, `onUndo`), `StandingQuestion` (`always`, `onAnswer`) and how custom actions pass the policy gate are in [decide-policy-actions.md](decide-policy-actions.md). + +### Clock (`types.ts` -> `Clock`, `clock.ts` -> `browserClock`) + +```ts +interface Clock { + now(): number; // ms, monotonic + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(h: unknown): void; + afterTask(fn: () => void): void; // after the current macrotask's microtasks drain +} +``` + +`browserClock`: +- Captures `setTimeout`, `clearTimeout`, `setImmediate`, `MessageChannel` and `performance` from `globalThis` **at module load**, so the runtime's own timers never pass through its timers observer (which wraps the app's global `setTimeout`). +- `now()`: `performance.now()`; without it, a counter that increases by 1 per call (never `Date.now`). +- `setTimeout(fn, ms)`: clamps `ms` to `>= 0`; throws `"GenClass: no setTimeout available; pass a clock"` when none was captured; in Node (no `window`) calls `unref()` so housekeeping timers never keep the process alive. +- `clearTimeout(h)`: ignores `null`/`undefined`. +- `afterTask(fn)`: queues `fn`; one flush per macrotask. Transport preference: `setImmediate` when there is no `window` (Node and Node-hosted DOM shims), else `MessageChannel` (ports `unref`'d), else `setImmediate`, else `setTimeout(0)`. Callback exceptions are swallowed. +- Module-load side effects: `hasWindow` (`typeof globalThis.window === "object" && window !== null`) is fixed when `clock.ts` is evaluated, and `afterTask` is built then (`makeAfterTask()`), so importing the root module constructs one `MessageChannel` in a browser. A `window` defined after import does not change the transport or the Node `unref` behaviour. + +Test clock: `packages/runtime/test/helpers.ts` -> `FakeClock` (starts at `t = 1000`; `flush()` drains microtasks then afterTask hooks; `advance(ms)` runs due timers in order, each as its own macrotask; `runAll(maxMs = 120000)`). The sim injects its own virtual clock ([sim.md](../sim.md)). + +### Errors + +`GenClassUnavailableError` (`errors.ts`), `name = "GenClassUnavailableError"`, field `reason`: + +| reason | thrown by `ask`/`decide` when | message | +|---|---|---| +| `"destroyed"` | the runtime was destroyed | `this GenClass runtime was destroyed` | +| `"off"` | there is no decider | `GenClass has no model (model: false)` | +| `"timeout"` | `timeoutMs` elapsed while waiting for the load, or for the answer | `the model did not load in time` / `the model did not answer in time` | +| `"error"` | the load failed (no `timeoutMs`), the status is still not ready after waiting, or no answer came back | `the model failed to load: ...` / `the model is <state>` / `the model could not answer` | + +Provider errors (`GenClassModelError` subclasses, `code` in `ModelErrorCode`) never escape a trigger: `DeciderQueue` turns them into `null` and the runtime fails open. The one code the runtime reacts to is `max_tokens_exceeded` (budget scale). Codes: [model-host.md](model-host.md). + +`runtime.ts` -> `normalizeError(error, source?)` (exported from `runtime.ts`, not from the root; only caller is `reportError`) returns `ErrorInfo` (`situation/env.ts`): `{ name, message, raw, key, source? }`. `name`/`message` come from an `Error` or any object with a `message`; a string becomes the message; anything else is `JSON.stringify`'d (falling back to `String`). `key` = `` `${name}:${message with every digit run replaced by "n", first 120 chars}` `` groups repeats of the same error for the `errorsRecent` facts. + +`index.ts` -> `failedProvider(message)`: the stand-in decider when `createModelHost` throws. Its `status` is the fixed object `{ state: "error", error: "model host unavailable: <msg>" }`, `ready()`/`evaluate()` reject with `Error(message)`, and it has no `onStatus` and no `dispose`, so no `"Model unavailable"` status report is printed: the only trace is `rt.status.error`. + +### Type catalogue (`types.ts`, by section) + +| section | types | detailed in | +|---|---|---| +| model seam | `JevState`, `Question`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `Answer`, `AnswerOf`, `TriggerKind`, `ModelStatus`, `SubjectRef`, `EvaluateRequest`, `DecisionProvider` | [model-io-contract.md](../model-io-contract.md) | +| clock | `Clock` | this doc | +| trace | `EventKind`, `RtEvent`, `OpKind`, `OpStatus`, `Op`, `UserAction` | [observe-and-trace.md](observe-and-trace.md) | +| state | `StoreOptions`, `Atom`, `Guarded`, `StoreIO`, `AdapterIO`, `AdapterHandle`, `Change` | [state-and-adapters.md](state-and-adapters.md) | +| options | `Mode`, `Tier`, `ObserverName`, `PolicyOptions`, `Vocabulary`, `RuntimeHooks`, `ModelOptions`, `InitOptions`, `CreateOptions` | this doc | +| questions | `AskOptions` (`about?: "now" \| number /* op id */ \| string /* store */`, `timeoutMs?`) | this doc | +| situations | `FactKind`, `Fact`, `Situation`, `RequestInfo`, `SituationDraft` | [learn-situation-triage.md](learn-situation-triage.md) | +| decisions | `Decision`, `Detection`, `ActionRecord`, `Report`, `Explanation` | [decide-policy-actions.md](decide-policy-actions.md) | +| plugins | `ActionContext`, `ActionDef`, `StandingQuestionContext`, `StandingQuestion`, `PluginApi`, `Plugin` | this doc / [decide-policy-actions.md](decide-policy-actions.md) | +| runtime | `RuntimeEvents`, `Runtime` | this doc | + +Key literal unions: `TriggerKind = "mutation" | "request" | "failure" | "stall" | "inconsistency" | "transition" | "error" | "ask"`; `ObserverName = "fetch" | "xhr" | "user" | "errors" | "nav" | "storage" | "perf" | "websocket" | "timers"`; `ModelStatus.state = "off" | "loading" | "ready" | "error"`. + +### `RuntimeImpl` state (private fields, `runtime.ts`) + +| field | holds | bound | +|---|---|---| +| `_mode`, `paused`, `destroyed` | lifecycle flags | | +| `decider`, `ownsDecider`, `_ready` | provider, ownership, memoised `ready` promise | | +| `queue: DeciderQueue` | one evaluation at a time, priorities, 30 s answer cache, deadlines, latency samples | 32 queued, 20 latencies | +| `reporter: Reporter` | report sink + console de-dup windows | 60,000 ms windows | +| `policy: PolicyConfig`, `rate: RateLimiter` | resolved policy; action timestamps | `maxActionsPerMinute` | +| `listeners` | one `Set` per `RuntimeEvents` key | | +| `uninstall` | teardown functions (status subscription first, then observers in install order) | | +| `plugins: Map<Plugin, { cleanup? }>`, `customActions`, `standing` | extension registry | | +| `decisionsBuf`, `actionsBuf` | recent decisions / interventions | 200 each (`DECISIONS_KEPT`) | +| `explainMap` | explain records keyed by `d<n>` and `a<n>` | soft: one oldest entry evicted per decision once over 400 (`DECISIONS_KEPT * 2`); action entries are never evicted on insert, so it grows by one per executed action | +| `lastBuilt` | last built situation per trigger (for `situation(trigger)`) | 1 per trigger | +| `storeWriters` | op signature -> store -> writes by its chains | 1,000 signatures | +| `identicalMap` | request identity -> recent ops | 12 per identity, 512 identities, 10 s | +| `errorsRecent` | recent error keys | 64, 10 s window | +| `toProfile` | ops waiting for the next settled point | 2,000 | +| `snaps` | consistent snapshots `{ t, seq, values }` (newest last) | 8 | +| `episode`, `muted` | violations raised in the current episode; violations whose rollback was undone | | +| `settleTimer`, `persistTimer` | clock handles | | +| `nextDecision`, `nextAction`, `uniq` | id counters (`d<n>`, `a<n>`, `uniq:<n>`) | | +| `budgetScale`, `rateWarnedAt`, `lastTyping`, `lastUserEvent` | adaptive budget, warning throttle, typing-burst state | | +| `env: SitEnv` | read-only view handed to situation building (`makeEnv`) | | + +## How it works + +### 1. `GenClass.init(options)` + +`index.ts` -> `GenClass.init`: +1. If `current` is set, return it (options ignored). +2. Call `initUnsafe(options)` inside try/catch. On any throw: `console.warn("[GenClass] Could not start (<msg>); running without it.")`, set `current = createRuntime({ observe: ALL_OFF, decider: null, report: "silent", mode: "observe" })` and return it. + +`index.ts` -> `initUnsafe`: +1. `killSwitch(globalThis)`: read `new URLSearchParams(location.search).get("genclass")`; only if that is empty/absent, read `localStorage.getItem("genclass")`. Both reads are in try/catch. Result is `trim().toLowerCase()` or `null`. +2. Value `"off"`: `console.info('[GenClass] Disabled by ?genclass=off or localStorage.genclass = "off": nothing is installed.')`, then `current = createRuntime({ observe: ALL_OFF, model: false, decider: null, report: "silent", mode: "observe" })`. **All caller options are dropped** (no plugins, no decider). +3. Value in `MODES` (`observe`, `guard`, `heal`): it becomes the mode; any other value is ignored and `options.mode` is used. An unrecognised but non-empty URL value (e.g. `?genclass=1`) still shadows `localStorage.genclass`, which is then never read. +4. Not a browser (`typeof globalThis.window !== "object" || typeof globalThis.document !== "object"`): `current = createRuntime({ ...options, observe: ALL_OFF, model: false, decider: options.decider ?? null, report: options.report ?? "silent", mode? })`. No observers and no model host, but a caller-supplied `decider`, `plugins`, `policy` etc. are kept. +5. Browser: copy options; set the mode if resolved; if `options.decider === undefined && options.model !== false`, set `o.model = options.model ?? {}`; `current = createRuntime(o)`. + +`GenClass.runtime` is a getter for `current`. `GenClass.destroy()` sets `current = null` first, then calls `destroy()` on the old runtime. + +### 2. `createRuntime(options)` + +`index.ts` -> `createRuntime`: +1. `decider = options.decider`. If it is `undefined` and `options.model` is a truthy object: `owns = true`; choose the fetch for model downloads: with `options.global`, that object's `fetch` bound to it (or `undefined` if it has none); without it, `NATIVE_FETCH` (the global `fetch` captured when `index.ts` was evaluated, so the model download never goes through GenClass's own fetch observer). +2. `makeHost(model, fetch, options.clock)`: `createModelHost({ ...model, fetch?, clock? })`; if that throws, `failedProvider(...)`: a provider whose `status` is `{ state: "error", error: "model host unavailable: <msg>" }` and whose `ready()`/`evaluate()` reject. +3. `return new RuntimeImpl({ ...options, decider: decider ?? null, ownsDecider: owns })`. + +`createRuntime` never sets `GenClass.runtime`. + +### 3. `RuntimeImpl` constructor order + +Field initialisers run first (`ops = new OpRegistry()`, `base = new Baselines()`, `profiles = new Profiles()`, buffers, maps). Then `runtime.ts` -> `RuntimeImpl.constructor`: +1. `clock = o.clock ?? browserClock`; `global = o.global ?? globalThis`. +2. `events = new EventLog(o.historySize ?? 500)`; `ctx = new Context(clock)`; `redactFn = o.redact ?? defaultRedact`. +3. `hub = new StoreHub(clock, ctx, events, () => redactFn)`; `miner = new InvariantMiner(() => redactFn)`; `cache = new ResponseCache(clock)`. +4. `policy = policyConfig(o.policy)`; `hub.holdUserWrites = policy.holdUserWrites`; `rate = new RateLimiter(() => policy.maxActionsPerMinute)`. +5. Scalars: `_mode`, `triage`, `vocab`, `hooks`, `settleMs` (60), `budgetOpt` (`"auto"`), `appFn`, `debug`, `persist`, `decider`, `ownsDecider`. +6. `queue = new DeciderQueue(clock, () => decider, onError)`; `onError` shrinks `budgetScale` on `max_tokens_exceeded` and logs. +7. `reporter = new Reporter(o.report ?? "console", clock, id => explain(id), r => fire("report", r))`. +8. `env = makeEnv()`. +9. `hub.hooks = { gate: gateMutation, mayHold: consultable() && mode !== "observe", appError: reportError, waitRelated, applied: onApplied, discarded: scheduleSettle, proposed: hooks.mutationProposed wrapper }`. +10. `events.onEvent(e => fire("event", e))`. +11. If `decider.onStatus` exists: subscribe (fire `status`; status reports on `ready`/`error`); push the unsubscribe into `uninstall`. +12. If `learn.persist`: `loadProfiles()` from `global.localStorage["genclass.profiles.v1"]` (errors ignored). +13. `installObservers(o.observe ?? {})`, in this order: `timers`, `fetch`, `xhr`, `websocket`, `user`, `errors`, `nav`, `storage`, `perf`. Each install is in `tryAdd` (a throwing installer is skipped and logged with `debug`); a non-null returned function is pushed into `uninstall`. +14. `for (const p of o.plugins ?? []) this.use(p)`. + +Constructing a `RuntimeImpl` immediately patches the instrumented globals (fetch, XHR, timers, history, Storage, WebSocket, DOM listeners). + +### 4. Model readiness + +1. A host with `preload: "idle"` (default) starts loading after page load and idle; status goes `off` -> `loading` -> `ready` | `error`, each forwarded as a `status` event. +2. While `loading` or `error`, `consultable()` is false: observers and the hub skip triggers entirely (no facts, no holds, no decisions). +3. While `off` (lazy preload not started yet), triggers compute facts; the first salient one reads `this.ready` (starting the load via `decider.ready()`) and fails open. +4. `rt.ready` memoises the first `decider.ready()` promise and attaches a no-op `catch` so an unobserved failure is not an unhandled rejection. + +### 5. Trigger path (facade view) + +Observers and the hub call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. In order: not consultable -> passive; `computeFacts`; with `triage: "salient"`, all facts neutral and no `always` standing question -> passive; `buildSituation`; not ready -> start lazy load, passive; hold only if `hold` and some non-passive action is permitted in this mode/policy and not paused; the hold budget timer runs passive on expiry; submit to `DeciderQueue` with deadline `t0 + holdBudget (+ 2,000 ms late-revert window when the controller can revert)` for held subjects, else `t0 + 5,000 ms` and priority `min(priority, 1)`; `onDecision` gates and acts. Full detail: [decide-policy-actions.md](decide-policy-actions.md). + +### 6. `ask` and `decide` + +`runtime.ts` -> `RuntimeImpl.ask`: +1. Destroyed -> `GenClassUnavailableError("destroyed")`. No decider -> `("off")`. +2. Status not `"ready"`: await `this.ready`. With `timeoutMs`, race it against a clock timer that rejects with `("timeout", "the model did not load in time")`; without, a load failure becomes `("error", "the model failed to load: ...")`. +3. Still not ready -> `("error", "the model is <state>")`. +4. `build({ trigger: "ask", about: opts.about ?? "now" })`; questions `{ answer: q }`; `queue.submit({ trigger: "ask", state, questions, priority: 1, subject }, timeoutMs !== undefined ? now + timeoutMs : undefined)`. +5. With `timeoutMs`, race the answer against a second clock timer -> `("timeout", "the model did not answer in time")`. +6. `null` result or no `answers.answer` -> `("error", "the model could not answer")`; else return `answers.answer`. Without `timeoutMs` the request has no deadline, so the queue abandons a silent provider after `PROVIDER_TIMEOUT_MS` = 10,000 ms (`decide/decider.ts`) and `ask` rejects with this `"error"`; it also resolves `null` (-> `"error"`) when the provider is no longer `ready` at dispatch, when it rejects, or when more than 32 requests are queued and it is the lowest-priority, oldest one (evicted). + +`ask` bypasses triage, policy and `pause()`, records no `Decision`, fires no event, and can be served from the queue's 30 s cache of identical requests (same trigger, state and questions). + +### 7. Settled points + +1. `scheduleSettle()` (debounced; no-op after destroy) is called by `endOp`, `onApplied` and the hub's `discarded` hook; it (re)arms a `settleMs` clock timer. +2. `settled()` returns early when destroyed or `busy()`: any in-flight op younger than `LONG_RUNNING_MS` (10,000 ms), or a pending (held/queued) write. It does not re-arm itself; the next op end or write does. +3. Invariants: `miner.observe(hub.allLeaves(), now)`; violations not present at the previous settled point and not muted are raised as one `inconsistency` trigger (not held, priority 1). Muted ids are dropped once they hold again. +4. Snapshot: if nothing newly broke, push `{ t, seq: hub.seq, values: hub.snapshot() }` (or refresh `t` when `seq` is unchanged); keep 8. +5. Transition profiles: each queued finished op is profiled once (`shapeOf(op.chain, op.chainWrites, statusClass(op), duration)`, then `profiles.check` then `profiles.add`) under the profile key `` `user ${op.name}` `` for user ops and `op.name` otherwise; `statusClass` is `"<n>xx"` for numeric codes, `"timeout"`/`"network"`, else the op status. Unusual ones raise `transition` (not held, priority 0), keeping only the deepest when an op and its descendant are both unusual. Queued ops that have not ended yet are dropped from the queue (an op is re-queued by `endOp` when it ends). +6. With `learn.persist` and at least one queued op, `saveProfilesSoon()` writes profiles 5,000 ms later (one pending save at a time). + +Details: [state-and-adapters.md](state-and-adapters.md) (invariants, snapshots) and [learn-situation-triage.md](learn-situation-triage.md) (profiles). + +### 8. `setMode`, `pause`, `resume` + +1. `setMode(m)`: validate, set, status report, fire `status`. The new mode applies to the next gate; holds already waiting keep their computed `waits` flag. +2. `pause()`: `paused = true`, `hub.gating = false`. `consultable()` turns false, so triggers fail open; the fetch/XHR gate (`netHost.gated`) passes requests through; any hold that is still waiting is released by its own budget timer. +3. `resume()`: reverses `pause()` unless destroyed. + +### 9. `destroy()` + +`runtime.ts` -> `RuntimeImpl.destroy`, in order: +1. Return if already destroyed; set `destroyed = true`. +2. `hub.gating = false` (later writes apply immediately). +3. `queue.dispose()` (queued requests resolve `null`, so pending triggers fail open and pending `ask`s reject). The one evaluation already dispatched is not cancelled: it settles normally (or after its deadline / `PROVIDER_TIMEOUT_MS`), a trigger waiting on it runs passive because `destroyed` is set, but an `ask` waiting on it can still resolve with an answer after `destroy()`. +4. `reporter.dispose()` (open de-dup windows are dropped: pending `(×N more in the last minute)` lines are never printed). +5. Clear `settleTimer` and `persistTimer` (a pending `learn.persist` save is dropped). +6. Run `uninstall` in reverse order (observers last-installed-first, then the decider status subscription); errors ignored. Each observer's uninstall sets its `disabled` flag (its wrapper becomes a pass-through) and, for fetch for example, restores the original only if the global still holds GenClass's wrapper (`observe/fetch.ts` -> `installFetch`), so a library that wrapped on top of GenClass keeps working. +7. `unuse` every plugin (cleanup functions run). +8. `unsubscribeIO()` for every store. +9. `ctx.clear()` (no ambient op). +10. If `ownsDecider`: `decider.dispose()` (terminates the model worker). + +After destroy: listeners registered with `on()` stay attached and can still fire. `destroy()` does not detach the `EventLog` listener, so anything still recorded fires `event`: atom/guard `set` and adapter `propose` write directly (`hub.write` -> `StoreHub.record` pushes a `state` event) without gating, and `user()` / `emit()` have no `destroyed` check. An action that was already running when `destroy()` was called still fires `act` and `report` when its effect settles (`onDecision` -> `finish` has no `destroyed` check). No new decisions are made (`consultable()` is false), `reportError` is a no-op, `ask` rejects with `"destroyed"`, and `resume()` is a no-op. + +## Configuration and constants + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `MODES` | `readonly Mode[]` | `["observe", "guard", "heal"]` | `index.ts` | Kill-switch values accepted as modes. | +| `ALL_OFF` | `Record<ObserverName, boolean>` | all nine observers `false` | `index.ts` | Observer set for inert runtimes. Must list every `ObserverName` (type-enforced). | +| kill-switch key | string | URL param `genclass`, localStorage key `genclass` | `index.ts` -> `killSwitch` | `off` / `observe` / `guard` / `heal`; trimmed, case-insensitive; URL wins. | +| `NATIVE_FETCH` | `typeof fetch \| undefined` | `globalThis.fetch.bind(globalThis)` at module evaluation | `index.ts` | Fetch used by an owned model host when no `global` is passed. | +| `DECISIONS_KEPT` | number | `200` | `runtime.ts` | Size of `decisions()` / `interventions()` buffers; default `n`; the explain map evicts (one entry per decision) above `2 ×` this. | +| `LATE_REVERT_MS` | number | `2000` | `runtime.ts` | Late-revert window after a held write applied; extends the held-decision deadline. | +| `BACKGROUND_DEADLINE_MS` | number | `5000` | `runtime.ts` | Deadline for non-held decisions. | +| `STALL_MIN_MS` | number | `500` | `runtime.ts` | Stall timer at `max(4 × median, 2 × p95, 500)` ms of the signature's latency. | +| `LONG_RUNNING_MS` | number | `10000` | `runtime.ts` | Ops older than this do not block settled points; `defer` waits at most this long. | +| `PROFILED` | `Set<OpKind>` | `fetch`, `xhr`, `user`, `task`, `ws` | `runtime.ts` | Op kinds with transition profiles. | +| `TYPING_BURST_MS` | number | `1000` | `runtime.ts` | `user({ kind: "type" })` on the same target within this merges into one event. | +| `PROFILE_KEY` | string | `"genclass.profiles.v1"` | `runtime.ts` | localStorage key for `learn.persist`. | +| profile save delay | number | `5000` ms | `runtime.ts` -> `saveProfilesSoon` | Delay of the single pending profile write (the first request schedules it; later ones are ignored until it runs). | +| rate-warning throttle | number | `60000` ms | `runtime.ts` -> `onDecision` | Rate-limit status report at most once a minute. | +| budget scale | number | start `1`, `× 0.8` per `max_tokens_exceeded`, floor `0.5` | `runtime.ts` constructor | Shrinks the automatic situation budget. | +| `situationBudget()` "auto" | number | WebGPU or unknown device: `STATE_CHAR_BUDGET` = 3200; WASM: `1000 + round((threads - 1) × 1000 / 3)` with threads clamped to 1..4 (1000, 1333, 1667, 2000); then `× budgetScale`, rounded | `runtime.ts` -> `situationBudget` | Size of situation text (`budget`). A numeric `situation.budget` is returned unchanged. | +| `STATE_CHAR_BUDGET`, `COMPACT_BUDGET` | number | `3200`, `1100` | `situation/serialize.ts` | Full and compact section limits. Compact questions at budget `<= 1400` (`COMPACT_QUESTIONS_BUDGET`, `situation/questions.ts`). | +| historySize floor | number | `16` | `trace/events.ts` -> `EventLog` | Minimum ring-buffer size. | +| `MAX_OPS` / `KEEP_OPS` | number | `2000` / `1500` | `trace/ops.ts` | Op registry pruning (in-flight ops kept); `PluginApi.endOp` on a pruned id is a no-op. | +| `STRINGIFY_CAP` | number | `65536` | `util.ts` | Default cap of `stableStringify`. | +| `REDACTED` | string | `"[redacted]"` | `util.ts` | Redaction marker. | +| `IDEMPOTENT_METHODS` | `Set<string>` | `GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`, `TRACE` | `util.ts` | Request idempotency for facts/actions. | +| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | Default `model.baseUrl`. | + +Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants (`MAX_QUEUE` 32, `CACHE_TTL` 30,000 ms, `PROVIDER_TIMEOUT_MS` 10,000 ms, `LATENCY_SAMPLES` 20, host `DEFAULT_TIMEOUT_MS` 10,000) in [decide-policy-actions.md](decide-policy-actions.md) and [model-host.md](model-host.md). + +### `util.ts` helpers + +| helper | contract | +|---|---| +| `fnv1a(s)` | FNV-1a 32-bit (offset `0x811c9dc5`, prime `0x01000193`, `Math.imul`), 8 lowercase hex chars. | +| `isPlainObject(v)` | Prototype is `Object.prototype` or `null`. | +| `stableStringify(v, cap = 65536)` | JSON-like with sorted keys; `undefined`, `"[fn]"`, `"[symbol]"`, `"[cycle]"`, `123n`, non-finite numbers quoted, `Map{k:v}`, `Set[...]`, Dates as ISO; over the cap: `<first cap chars>…<length>`. | +| `hashValue(v)` | `fnv1a(stableStringify(v))`. | +| `kindOf(v)` | `"null" \| "array" \| "map" \| "set" \| "date" \|` `typeof`. | +| `truncate(s, n)` | At most `n` chars, last one `…`. | +| `secs(ms)` | `"0.42s"` (< 10 s, 2 decimals), `"12.3s"` (< 1000 s), else integer; negatives clamp to 0. | +| `rel(ms)` | Signed: `"-1.24s"` (`ms <= 0`, so 0 is `"-0.00s"`) or `"+0.10s"`. | +| `fmtNum(n)` | Integers as is; else 1 decimal if `abs(n) >= 100`, 2 if `>= 1`, 4 otherwise (trailing zeros dropped). | +| `ratio(a, b)` | `"∞"` when `b <= 0`; `"12×"` when `>= 10`; else `"1.5×"`. | +| `plural(n, one, many?)`, `ordinal(n)` | `"3 items"`; `"1st"`, `"12th"`, `"23rd"`. | +| `words(s)` | Split camelCase / snake_case / kebab-case / spaces, lowercased. | +| `isSensitiveName(name)` | True if any word is in `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or a pair in `SECRET_PAIRS` (card number/num/no/cvc/cvv/code/security, credit card, cc number/num/no/exp/csc, api key/secret, private key, access key, secret key, session id/token/key, security code, one time, social security). `"author"`, `"cards"`, `"passengers"`, a kanban `"card"` are not secrets. | +| `defaultRedact(path, value)` | `"[redacted]"` if any dot-separated segment `isSensitiveName`, else `value`. | +| `describe(v, path, redact, max = 80)` | One-line value summary used in situations (strings 48 chars top-level, 24 nested; arrays show at most 3 items, e.g. `"5 items [a, b, c, …]"` (the `, …` only when items were left out); objects list id-like keys first: `id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`). | +| `isIdSegment(seg)` | Digits, UUID, long hex (>= 8 with a digit), long token (>= 16 with letters and digits), conservative slug ids (`tasks-1cam`, `x7k2p`, `PPBqWA9`; not `sha256`, `oauth2`, `v1beta1`). | +| `normalizePath(p)` | Id segments (after `decodeURIComponent`) -> `:id`. | +| `normalizeFieldPath(p)` | Store path segments after the first that are ids or contain a digit -> `:id` (transition profiles). | +| `parseUrl(raw, base)` | `{ href, where, search, sameOrigin }`; `where` is the pathname (same origin) or `host + pathname`; base defaults to `http://localhost/`. | +| `requestSignature(method, where)` | `"GET /api/items/:id"` (the **op signature**). | +| `redactSearch(search, redact, max = 60)` | Query string (input capped at 4096 chars) with values whose `query.<key>` path is redacted replaced by `[redacted]`, truncated. | +| `type Redactor` | `(path: string, value: unknown) => unknown`: the shape of `InitOptions.redact` and `defaultRedact`. | +| `interface ParsedUrl` | `{ href; where; search; sameOrigin }`, returned by `parseUrl`. | +| `REDACTED`, `IDEMPOTENT_METHODS` | Exported constants (values in the table above). `STRINGIFY_CAP`, `SECRET_WORDS`, `SECRET_PAIRS`, `ID_KEYS` and the id regexes are module-private. | + +`fmtNum` returns `String(n)` for non-finite numbers (`"NaN"`, `"Infinity"`). `stableStringify` prints an invalid `Date` as `"Invalid Date"` and slices any single string longer than the cap before quoting. `describe` nests at most two levels (`{N keys}` deeper, nested arrays as `[N]`, `Map(N)`, `Set(N)`) and appends `, +N` for keys that did not fit. + +## Invariants and gotchas + +- **`GenClass.init` must never throw.** Every observer installer runs inside `tryAdd`; plugin `setup` errors are caught in `use`; listener, hook and reporter errors are swallowed; the outer catch falls back to an inert runtime. Tests: `batch3.test.ts` ("GenClass.init never throws", read-only globals), `review-misc.test.ts`. Do not add code to the constructor path that can throw without a guard. +- **`createRuntime` (and `new RuntimeImpl`) can throw.** Unguarded constructor steps: `new EventLog(historySize)` (`RangeError` for `NaN` or a non-integer size of 16 or more; a fraction below 16 becomes 16), `policyConfig` (`new Set(allow/deny)` with a non-iterable), and `decider.onStatus(...)` of a custom provider. All of these run before any observer is installed, so nothing is left patched. One unguarded step runs after the observers: plugin registration (`for (const p of o.plugins ?? []) this.use(p)`, and inside `use` the `for...of` over `plugin.actions` / `plugin.questions`), so a non-iterable `plugins`, `actions` or `questions` throws with the globals already patched and no runtime left to `destroy()` them (only `setup` is in try/catch). `GenClass.init` catches all of these and returns the inert fallback (dropping every option). But a model host that `createRuntime` already built for `model: {...}` is never disposed in that case, and its `preload` (`"idle"` by default, scheduled in the `Host` constructor) still downloads the model. +- **Console hints assume the facade.** Report groups print `GenClass.runtime.interventions()...undo()`, `GenClass.runtime.explain(...)` and ``Deny this action: GenClass.init({ policy: { deny: ["<action>"] } })`` (`decide/report.ts` -> `Reporter.emit`). The deny hint does nothing on a page where `GenClass.init` already ran (idempotent init ignores new options); it only takes effect after `GenClass.destroy()` and a fresh `init`, or at the next page load. +- **Silent by default.** Swallowed failures (observer install, plugin setup, provider errors) are only visible with `debug: true`. When debugging "GenClass does nothing", turn on `debug` first. +- **Singleton semantics.** `GenClass.init(newOptions)` after a first init returns the old runtime unchanged. `rt.destroy()` without `GenClass.destroy()` leaves `GenClass.runtime` pointing at a destroyed runtime, and the next `init()` returns it. Console hints printed by reports (`GenClass.runtime.interventions()...`, `GenClass.runtime.explain(...)`) only work for the facade singleton, not for `createRuntime` runtimes. +- **Kill switch scope.** It is read from `globalThis` only, by `GenClass.init` only (`createRuntime` ignores it). `off` drops all options, including `plugins` and `decider`. +- **Non-browser init is not fully inert.** It keeps `options.decider`, `plugins`, `policy`, `mode`; only observers and the model host are forced off. +- **Decider ownership.** Only a host created by `createRuntime` is disposed. If you pass `createModelHost(...)` as `decider`, you must `dispose()` it yourself. +- **`decider` vs `model`.** Any non-`undefined` `decider` (including `null`) disables model creation. `model: {}` with `createRuntime` does load the model (unlike passing nothing). +- **`rt.ready` memoises failure.** After a failed load, `rt.ready` keeps rejecting even if the host could reload via `ModelHost.load()`; `ask()` without `timeoutMs` then rejects with reason `"error"`. +- **`ask()` timeouts apply twice** (load wait and answer wait), so the worst case is about `2 × timeoutMs`; and with `timeoutMs` set, a model load failure rejects with the provider's own error (for example `ModelLoadError`), not `GenClassUnavailableError` (see Drift). +- **Event `status` is overloaded:** `setMode` fires it with the unchanged model status. Do not assume every `status` event means the model changed. +- **`event` listeners can see the same object twice** (typing bursts mutate and re-fire the event via `EventLog.touch`). +- **`inflight()` returns live `OpRec`s**; `situation()` returns the cached object for that trigger. Treat both as read-only. +- **`atom(name)` reuse vs replacement.** Same name and kind `atom` reuses the store and ignores `initial`; `guard`/`adapter` (or `atom` over a non-atom store) replace the store and lose its field history. +- **Determinism (CONTRACT §0 rule 3).** Inside `packages/runtime/src` no `Math.random`, `Date.now`, `performance.now` or global `setTimeout`/`setInterval`: use `this.clock` (or `api.clock` in plugins). Ids come from counters (`d<n>`, `a<n>`, `uniq:<n>`, op ids, event `seq`). The only `performance.now` uses are `clock.ts` and a default in `model/engine.ts` that `model/backend.ts` overrides with the injected clock (`now: () => this.env.clock.now()`). Exception outside the decision path: the devtools overlay (`src/devtools/index.ts`, owned by UI) captures the raw global `setTimeout` and `requestAnimationFrame` at module load for its own rendering. The model host's idle preload (`src/model/host.ts` -> `scheduleIdle`) also calls the global `requestIdleCallback`/`cancelIdleCallback` directly. None of these reaches situation text. `budget.test.ts` and `situation.test.ts` assert byte-identical situations for identical inputs. +- **Every timer the runtime arms must be cleared in `destroy()` or be harmless when it fires afterwards.** `destroy()` clears `settleTimer`, `persistTimer` and the reporter's de-dup windows. Hold-budget, stall and queue-dispatch timers are left to fire: `passive()` is idempotent, `watchStall` checks `destroyed`, and `trigger()`'s answer handler runs passive when `destroyed`. +- **Captured natives.** `browserClock` captures timers and `index.ts` captures `fetch` at module evaluation. If another library patched `fetch` earlier, the model host downloads through that patch. Keep these captures at module top level; moving them into functions would make the runtime observe itself (its own timers through the timers observer, its model download through the fetch observer). +- **Parity and the `situation-v1` freeze.** `util.ts` formatting (`secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `normalizePath`, `isIdSegment`, `isSensitiveName`, `defaultRedact`) and the default `vocabulary` feed the text the model reads. The tag `situation-v1` froze it; `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Changing any of these requires SIM/TRAIN coordination and regenerated data ([model-io-contract.md](../model-io-contract.md)). +- **The model seam is shared.** The first section of `types.ts` is co-owned by MODEL, and `sim/src/types.ts` mirrors it structurally. Change all three together. +- **Fail-open everywhere.** Not consultable, provider error, deadline missed, queue overflow, destroyed: the passive action runs. Never introduce a path where a missing answer blocks the app. +- **Option resolution is one-shot.** `policy`, `triage`, `vocabulary`, `settleMs`, `redact`, `report` (except via `setReport`) and `observe` are read in the constructor; only `mode` (via `setMode`) and pause state change afterwards. + +## How to change it safely + +**Add an init option** +1. Add the field with a JSDoc default to `InitOptions` (or `CreateOptions` if headless-only) in `packages/runtime/src/types.ts`. +2. Read it once in `RuntimeImpl`'s constructor with an explicit default (`o.x ?? default`). Never read options lazily from `o` later. +3. Check the four creation paths in `index.ts` (`initUnsafe` browser, non-browser, kill-switch `off`, fallback) and decide whether the option should survive each. +4. If it changes situation text or decisions, coordinate with SIM (`sim/src/run/rt.ts` -> `createOptions`) and record it in `docs/runtime/API.md`. +5. Add a test using `setup({ ...option })` from `test/helpers.ts`; run `vitest run --exclude "test/browser/**"` in `packages/runtime`, locally or on the VM (`scripts/vm.sh run <slot> '...'`); see [build-test-release.md](build-test-release.md#where-to-run-things) for where to run what. + +**Add a `Runtime` method** +1. Add it to `Runtime` in `types.ts` and implement it in `RuntimeImpl`. +2. Update every other implementer of `Runtime`: `packages/runtime/test/browser/ui/mock-runtime.ts` (`MockRuntime implements Runtime`) and `demos/src/dev/runtime-shim/index.ts` (`ShimRuntime implements Runtime`). Add it to the sim's `RuntimeLike` (`sim/src/run/rt.ts`) only if the sim calls it. +3. Devtools wraps runtime calls in `safe()`; keep new methods non-throwing if devtools will use them. + +**Change an existing `Runtime` method or option (signature or semantics)** +1. Find every caller outside `src/`: the sim's structural `RuntimeLike` (`sim/src/run/rt.ts`) calls `atom`, `user`, `reportError`, `situation`, `on`, `destroy` and optionally `decisions`, `inflight`; its `createOptions` passes `clock`, `global`, `decider`, `model: false`, `mode: "heal"`, `report: "silent"`, an explicit `observe` map, `triage: "salient"`, `policy` (`thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`), `historySize: 500`, `app`, and optionally `vocabulary`, `hooks`, `situation.budget`. The sim loads the runtime by the module name in env var `GENCLASS_RUNTIME` (default `@genclass/runtime`), so it compiles without the runtime's types: a breaking change shows up only at sim run time. +2. Also update `MockRuntime` (`test/browser/ui/mock-runtime.ts`), `ShimRuntime` (`demos/src/dev/runtime-shim/index.ts`), devtools (`src/devtools/index.ts`) and the React adapter (`src/adapters/react.ts` -> `useRuntimeList`, which calls `decisions(limit)` / `interventions(limit)`). +3. Update `docs/runtime/API.md`, the JSDoc in `types.ts` and this doc. If the change alters situation text or decisions, it breaks the `situation-v1` freeze (see Invariants). + +**Add an event type** +1. Add the key and payload to `RuntimeEvents` in `types.ts`. +2. Add a `Set` for it in the `listeners` initializer of `RuntimeImpl` (otherwise `on(newType)` throws on `undefined.add`). +3. Fire it with `this.fire(type, value)`. Update `devtools/index.ts` -> `subscribe` and the React adapter's `useRuntimeList` callers if they should react. + +**Add an observer** +1. Extend `ObserverName` in `types.ts`; TypeScript then forces the new key into `ALL_OFF` in `index.ts`. +2. Install it in `RuntimeImpl.installObservers` through `tryAdd(name, () => installX(...))`; the installer returns an uninstall function (restore the global if it is still your wrapper, else become a pass-through) or `null` when unsupported. +3. Decide the default (`on(k)` defaults to `true`; pass a second argument like `timers` does to make it conditional). +4. Add a "destroy restores the global" assertion next to `dom.test.ts` -> "browser globals are restored by destroy()". See [observe-and-trace.md](observe-and-trace.md). + +**Change a default (mode, thresholds, settleMs, historySize, budgets)** +1. Change it where it is defined (table above), then update the JSDoc in `types.ts`, `docs/runtime/API.md`, `packages/runtime/README.md`. +2. Tests pinning values: `budget.test.ts` (budgets, hold budget), `policy.test.ts`, `report.test.ts` (report line regexes include thresholds), `batch3.test.ts`. +3. Thresholds and budgets affect training/eval comparability: tell TRAIN/SIM. + +**Change the kill switch or init paths** +Edit `index.ts` -> `killSwitch` / `initUnsafe`; keep everything in try/catch; update `report.test.ts` -> "GenClass.init and the kill switch" and `batch3.test.ts` -> "lifecycle". + +**Change `destroy()`** +Keep it idempotent; clear every new timer; keep reverse uninstall order; dispose only owned deciders. Tests: `fetch.test.ts`, `xhr.test.ts`, `dom.test.ts` (restoration), `review-fetch.test.ts` (no work after destroy), `review-misc.test.ts` / `batch3.test.ts` (`ask` after destroy). + +**Add a subpath export** +Add the entry to `package.json` `exports`, `tsup.config.ts` `entry` and `dts.entry`, and externalise any new peer library. See [build-test-release.md](build-test-release.md). + +**Add time-dependent behaviour** +Use `this.clock.now()` / `this.clock.setTimeout` / `this.clock.afterTask`; store the handle and clear it in `destroy()`; test it with `FakeClock.advance`. + +## Tests + +All in `packages/runtime/test/` (vitest, `environment: "node"`, `testTimeout: 20000`, `test/browser/**` excluded; `dom.test.ts` uses `// @vitest-environment happy-dom`). Most use `setup()` from `helpers.ts`: `createRuntime` with `FakeClock`, `FakeServer`, `ScriptedDecider`, `report: "silent"` and only the fetch observer on. + +| test file | what it asserts (scope of this doc) | +|---|---| +| `report.test.ts` | `GenClass.init` idempotent, `GenClass.runtime`, `destroy` clears it; `?genclass=off` leaves `fetch` untouched, mode `observe`, exactly one `console.info`; `?genclass=heal` overrides `mode: "guard"`; `on("decide" \| "detect" \| "act" \| "event")` order and unsubscribe; report lines and console grouping/de-dup. | +| `batch3.test.ts` | Lifecycle: `ask` after destroy rejects `"destroyed"`; `createRuntime` survives read-only `fetch`; `GenClass.init` with a throwing plugin `setup` does not throw; a provider that never answers does not block later decisions; rate-limit warning once per minute. | +| `review-misc.test.ts` | Init robustness on frozen globals; `ask` after destroy (`reason: "destroyed"`); console reports reach the console as `×N` summaries; queue robustness. | +| `ask.test.ts` | `ask` sends trigger `ask` with question id `answer`; typed answers (`expectTypeOf`); `decide` returns the label; `about` op id / store; no decider -> `GenClassUnavailableError`, `status.state === "off"`, `ready` resolves; `timeoutMs` -> reason `"timeout"`. | +| `policy.test.ts` | `setMode` switches tiers at runtime; `pause()` stops consulting, `resume()` restores; loading status fails open with no record; observe mode never holds; detection threshold. | +| `plugins.test.ts` | Plugin facts/diagnoses/actions reach the model; custom action runs; `ctx.builtin`; default heal tier; `applicable`; standing questions; `setup` receives `PluginApi` (`recordOp`, `runInOp`, `emit`, `on`, `endOp`) and cleanup runs on unregister; vocabulary overrides. | +| `budget.test.ts` | `situationBudget()` "auto" values (3200 / 1000 / 1333 / 2000, threads capped at 4, unknown device 3200, fixed number wins); `max_tokens_exceeded` -> 2560; hold budget `"auto"` (300 fallback, 150..800 clamp, adapts to measured latency); determinism at a fixed budget. | +| `situation.test.ts` | `situation()` (ask about now) is side-effect free (no ops, no events); determinism of whole runs on a fake clock. | +| `smoke.test.ts` | Minimal `createRuntime` wiring: atoms apply synchronously when nothing is salient; causality through awaits; a stale write is held and discarded in guard mode. | +| `dom.test.ts` | `destroy()` restores `fetch`, XHR `open`, `history.pushState`, `Storage.prototype.setItem`, `WebSocket`, `setTimeout`, and removes DOM listeners; `describeElement`. | +| `fetch.test.ts`, `xhr.test.ts`, `review-fetch.test.ts` | `destroy()` restores fetch/XHR; after destroy GenClass does no work even when another library wrapped fetch on top. | +| `review-timers.test.ts` | Uses `rt.internals` to check op pruning (timer loops do not retain ops). | +| `test/smoke/smoke.sh` | (VM only) packs the tarball, builds a fresh Vite app with `GenClass.init({ model: false, report: "console" })` and `mountDevtools`, loads it in headless Chromium. | + +Which `initUnsafe` branch the unit tests hit: vitest runs in `environment: "node"` (no `window`), so every `GenClass.init` call in `report.test.ts` and `batch3.test.ts` goes through the **non-browser** branch (or the kill-switch `off` branch); the mode override test passes through `...(mode ? { mode } : {})` there. The **browser** branch (`o.model = options.model ?? {}`) is exercised only by `test/smoke/smoke.sh` on the VM, and only with `model: false`. + +Untested in this scope: the `localStorage.genclass` path of the kill switch, the browser branch of `initUnsafe` with a default model, the outer `catch` fallback of `GenClass.init` (the throwing-plugin test is caught inside `use`, not by the fallback), `learn.persist`, `settleMs`, `historySize`, `setReport`, `isPaused`, `createRuntime({ model: {...} })` fetch selection and `failedProvider`, and the `ask` + `timeoutMs` + load-failure path. + +## Drift and open issues + +| what | docs say | code does | evidence | +|---|---|---|---| +| Auto situation budget on WASM | `types.ts` JSDoc of `InitOptions.situation`: "wasm 1,100 + 300 per extra thread up to 4 threads: 2,000" (1100/1400/1700/2000) | `1000 + round((threads - 1) × 1000 / 3)`: 1000/1333/1667/2000 | `runtime.ts` -> `situationBudget`; `budget.test.ts` asserts 1000, 1333 and 2000. API.md, ARCHITECTURE.md and STATUS.md match the code. | +| Default redaction | `types.ts` JSDoc of `InitOptions.redact`, `docs/runtime/CONTRACT.md` §2 and `packages/runtime/README.md` ("fields matching `pass\|token\|secret\|card\|cvv\|ssn\|auth`"): substring regex | Word-level meaning (`isSensitiveName`); `"card"`, `"author"`, `"cards"` are not redacted | `util.ts` -> `defaultRedact`; STATUS.md lists it as an approved deviation; API.md matches the code. | +| Non-browser `GenClass.init` | API.md: "returns an inert runtime: no observers, no model" | Observers off and no model host, but `options.decider`, `plugins`, `policy`, `mode` are kept; `report` defaults to `"silent"` | `index.ts` -> `initUnsafe` | +| `GenClass.destroy()` | API.md: "uninstall observers, restore globals, terminate the model worker" | Terminates only a host the runtime created (`ownsDecider`); a global is restored only if it is still GenClass's wrapper, otherwise the wrapper becomes a pass-through | `runtime.ts` -> `destroy`; `observe/fetch.ts` uninstall | +| `rt.ready` | API.md/types.ts: "resolves when the model is ready" | Also rejects (provider error, e.g. `ModelLoadError`) on load failure, and the rejected promise is memoised | `runtime.ts` -> `get ready` | +| `ask` error type | API.md: rejects with `GenClassUnavailableError` when no model can answer | With `timeoutMs` and a failed load, the raw provider error propagates (the race uses the unwrapped `ready` promise); `timeoutMs` is applied to the load wait and the answer wait separately | `runtime.ts` -> `ask` | +| `on("status")` | API.md: "model loading progress and state" | Also fired by every `setMode` call | `runtime.ts` -> `setMode`; devtools relies on it | +| `pause()` | API.md: "stops consulting the model" | Triggers stop, but `ask()`/`decide()` still query the model while paused | `runtime.ts` -> `ask` has no `paused` check | +| `ModelOptions` | API.md options block lists `baseUrl`, `device`, `worker`, `preload` | Also `ortWasmPaths` and `cacheName` | `types.ts` -> `ModelOptions` | +| Default observers | `types.ts`: "Default: all true (where the global supports them)"; CONTRACT §2 `observe` list omits `timers` | `timers` defaults on only when `global.document` is a non-null object; all others default on | `runtime.ts` -> `installObservers` | +| Hold budget fallback | API.md / `types.ts` describe only `clamp(1.5 × median, 150, 800)` | 300 ms when no latency sample and no `warmupMs` | `decide/policy.ts` -> `holdBudget`, `HOLD_FALLBACK_MS` | +| `situation(trigger)` | CONTRACT §13: side-effect free | Returns the last situation built for that trigger when there is one; building caches `op.reads` | `runtime.ts` -> `situation`, `build`; acknowledged in STATUS.md "Deviations" | +| Runtime surface | CONTRACT §2 `Runtime` | Also `mode`, `adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")` | STATUS.md "Extra public surface" acknowledges all of these except `mode`, which neither CONTRACT §2 nor STATUS.md lists | +| STATUS.md open issue | "`react-dom` is not a devDependency of `@genclass/runtime`" | `package.json` devDependencies include `react-dom ^19.3.0` and `@types/react-dom ^19.0.0` (stale item) | `packages/runtime/package.json` | +| `Decision.action` | `types.ts` JSDoc: "The action the model chose (highest probability)" | `action = run ?? top`: the action that ran (the gate's most probable **permitted** candidate, which can differ from the model's top choice) or, when nothing ran, the model's top choice. API.md ("the action that ran, else the model's choice") matches the code. | `runtime.ts` -> `onDecision` | +| `EvaluateRequest.priority` | `types.ts` JSDoc: "held writes/requests use 2, background 0" | Background triggers use 1 (`stall`, `inconsistency`, XHR `failure`, `ask`) or 0 (`transition`, `error`); a holdable trigger that does not wait is capped at 1 | `runtime.ts` -> `trigger`; see [Events](#events-runtimeevents) | +| `RuntimeImpl.setReport` | JSDoc: "Report sink for a custom destination at runtime (devtools)" | No caller anywhere in the repo (devtools does not use it) | `git grep setReport` | +| API.md shapes | `Situation` listed as `{ trigger, subject, state, questions, actions, salient, facts }`; `Op` without `meta` | `Situation` also has `compact` and `budget`; `Op` also has `meta` | `types.ts` -> `Situation`, `Op` | +| README observers | "Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are observed automatically" | Also `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | +| Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | +| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr, so a default `init()` ends in status `error` until it is published (unverified whether the URL is live). The CLI's default source is a different URL (GitHub release `runtime-model-v0.1.0`). | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; OPEN_TASKS.md item 8 | +| Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | +| `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a<n>` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | +| Init with malformed `plugins` | `GenClass.init` "never throws" | It does not throw, but a non-iterable `plugins` / `plugin.actions` / `plugin.questions` throws inside `RuntimeImpl`'s constructor after the observers were installed; the fallback inert runtime is returned while the first instance's wrappers stay on the globals | `runtime.ts` -> constructor, `use`; `index.ts` -> `GenClass.init` | +| `decisions(0)` / `interventions(0)` | | Return the whole buffer (`slice(-0)`), while `history(0)` returns `[]` | `runtime.ts` | + +Open items from OPEN_TASKS.md relevant here: publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) and then `@genclass/runtime@0.1.0` without the alpha tag; add a CI workflow (build, typecheck, unit tests); write honest results into the READMEs. Until the model ships, `GenClass.init()` observes and records but never acts. + +## Related docs + +- [observe-and-trace.md](observe-and-trace.md): observers, ops, causality, `op`/`user`/`emit` internals +- [state-and-adapters.md](state-and-adapters.md): stores, mutation pipeline, invariants, snapshots, adapters +- [learn-situation-triage.md](learn-situation-triage.md): baselines, profiles, facts, triggers, triage, serialisation, budgets +- [decide-policy-actions.md](decide-policy-actions.md): decision queue, policy gate, actions, reports, explain, undo +- [model-host.md](model-host.md): `createModelHost`, worker, loader, backends, CLI +- [devtools.md](devtools.md): devtools overlay (consumer of this API) +- [build-test-release.md](build-test-release.md): build, tests, VM workflow, publishing +- [../overview.md](../overview.md#3-runtime-data-flow-end-to-end): end-to-end data flow and the stale-write walkthrough +- [../model-io-contract.md](../model-io-contract.md): situation text -> model -> answers; `situation-v1` +- [../sim.md](../sim.md): how the sim drives `createRuntime` deterministically +- [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../README.md](../README.md) +- Original sources: [docs/runtime/API.md](../../runtime/API.md), [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [packages/runtime/README.md](../../../packages/runtime/README.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md) diff --git a/docs/agents/runtime/state-and-adapters.md b/docs/agents/runtime/state-and-adapters.md new file mode 100644 index 00000000..90422f9f --- /dev/null +++ b/docs/agents/runtime/state-and-adapters.md @@ -0,0 +1,653 @@ +# @genclass/runtime: state stores, mutation pipeline, invariants and framework adapters + +> **Scope:** `packages/runtime/src/state/hub.ts`, `packages/runtime/src/state/fields.ts`, `packages/runtime/src/state/invariants.ts`, `packages/runtime/src/adapters/{react,redux,zustand}.ts`, and the store-related parts of `packages/runtime/src/runtime.ts` (`atom`, `guard`, `adapter`, `expect`, `gateMutation`, `waitRelated`, `onApplied`, settled points, rollback, chain revert, resync, pause/resume/destroy gating). +> **Read this when:** you change how state is registered, flattened, diffed, held, applied, patched, reverted or snapshotted; add or tune an invariant template; touch the React hooks, the Redux enhancer or the Zustand middleware; integrate another state library through `runtime.adapter`; debug "why was this write held / applied / dropped / not reverted"; or debug a missing or spurious `inconsistency` trigger. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- Every store lives in one `StoreHub` (`packages/runtime/src/state/hub.ts` -> `StoreHub`), keyed by a **store name** that is global per runtime. There are three kinds: `atom` (GenClass owns the value), `guard` (the app owns the value behind `get`/`set`/`subscribe`), and `adapter` (a state library owns it and the adapter commits writes). The React hooks use atoms. The Redux enhancer and the Zustand middleware use `runtime.adapter`. +- A store value is **flattened** into dotted fields: `store.key.sub`, at most 4 key levels below the store name. A plain object is expanded only when it has 1 to 32 keys and expanding it keeps the store within 200 fields (a per-object check, so the cap is soft: see "Paths and leaves"). Arrays, plain objects with more than 32 keys, and non-plain objects are one field each. Each field has a version, its last writer op, a 16-entry history that keeps values, and a 512-entry write log. +- Every `set`/`dispatch` becomes a **proposal** (`MutationRec`), except Redux no-op dispatches, Zustand `set` calls made while the store is being created, and any write after `destroy()`. It is previewed, diffed against the stored leaves, and then either **bypasses** the pipeline (applied at once, in the caller's stack) or joins the store's FIFO queue and goes through the `mutation` **trigger**. +- These writes bypass: **user-sync** writes (made in the user handler's task; `policy.holdUserWrites` defaults to false), writes made by GenClass's own ops, stores registered with `hold: false`, any write while the runtime is paused or destroyed, no-op writes, and in-place updaters that cannot be detached. +- A queued write is **held** only when the trigger is salient, the model is ready, the mode is not `observe`, and some non-passive action is permitted. Otherwise the gate answers "apply" synchronously. Queued writes to one store apply in proposal order, so a write the gate cleared can still wait behind an earlier held write (bypass writes skip the queue; see Gotchas). Verdicts are `apply`, `discard` or `defer`. When the hold budget expires the write applies anyway (**fail-open**). +- At apply time a functional update **re-runs** against the current value. A value write is re-applied as a **patch** of the fields it changed (removals first). This keeps newer user input in other fields. +- **Late revert:** a `discard` that arrives after a fail-open apply reverts exactly that write. All of these must hold: at most 2,000 ms have passed since it applied, none of its fields changed since, and the same causal chain wrote nothing after it. +- Every applied change emits a `state` event and calls `HubHooks.applied` (`RuntimeImpl.onApplied`). That updates `storeWriters` and the transition-profile accumulators, notes the changed paths for the invariant miner, and (re)schedules a **settled point**, which is debounced by `settleMs` (60 ms). +- At a settled point (no op younger than 10 s in flight and no pending write), `InvariantMiner.observe` runs the 9 templates. A newly violated learned invariant raises one `inconsistency` trigger per episode. A consistent **snapshot** (up to 8 kept) is recorded whenever nothing newly broke. +- **App errors:** if the app's setter, reducer or subscriber throws on the synchronous path, the error reaches the `set()` caller just as it would without GenClass (subscriber errors are the exception: they are always reported, never thrown). If it throws later, when GenClass applies a held write, the error is reported through `reportError`, which raises an `error` trigger, and the store's queue keeps draining. +- **Parity:** flattening, hashes, deltas and `changeText` feed the situation text, so changing them changes training data (freeze tag `situation-v1`). This scope has not changed since that tag. + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `packages/runtime/src/state/hub.ts` | Store registry, mutation pipeline (propose, gate, queue, drain, commit, record), field versions and write logs, recent changes, late-revert primitives, snapshots, query helpers | `StoreHub`, `StoreRec`, `MutationRec`, `FieldState`, `FieldHist`, `LogEntry`, `RecentChange`, `HubHooks`, `GateResult`, `Verdict`, `toChanges`, re-export `changeText` | +| `packages/runtime/src/state/fields.ts` | Incremental flattening into leaves, hashing, diff, delta signatures, one-line change summaries, patches, deep clone | `flatten`, `leafOf`, `diffLeaves`, `deltaOf`, `multisetDiff`, `addedElements`, `elementDiff`, `changeText`, `patchValue`, `cloneValue`, `normalizeLeafKind`, `Leaf`, `FieldChange`, `MAX_DEPTH`, `MAX_FIELDS_PER_STORE`, `MAX_KEYS_EXPAND` | +| `packages/runtime/src/state/invariants.ts` | Online invariant miner over the leaves of all stores; developer `expect()` predicates | `InvariantMiner` (`noteChanged`, `noteValues`, `addExpect`, `observe`, `preview`, `current`, `learned`, `candidates`), `numEq`, `LEARN_AFTER`, `LEARN_AFTER_NONNULL` | +| `packages/runtime/src/runtime.ts` (store parts) | Public store API, the gate hook, defer waiting, applied-write bookkeeping, settled points, snapshots, inconsistency trigger, rollback, chain revert, resync | `RuntimeImpl.atom`, `.guard`, `.adapter`, `.handle` (private), `.expect`, `.gateMutation` (private), `.waitRelated` (private), `.onApplied` (private), `.scheduleSettle` (private), `.busy` (private), `.settled`, `.raiseInconsistency` (private), `.chainWrites`, `.revertChain`, `.rollback`, `.resync`, `.makeEnv` (private), `.pause`/`.resume`/`.destroy`, `.runAsGenClass`, `.reportError` (target of `HubHooks.appError`), `.pluginApi` (private; builds `PluginApi.stores { names(), get(name) }`, read-only access to every store's current value), the private fields `snaps`, `episode`, `muted`, `storeWriters`, `settleTimer`; constants `LATE_REVERT_MS`, `LONG_RUNNING_MS` | +| `packages/runtime/src/adapters/react.ts` | React bindings (subpath `@genclass/runtime/react`) | `GenClassProvider`, `GenClassProviderProps`, `useGenClass`, `useGenClassState`, `useAtom`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus` | +| `packages/runtime/src/adapters/redux.ts` | Redux store enhancer (subpath `@genclass/runtime/redux`) | `genclassEnhancer`, `GENCLASS_REPLACE`, `GenclassEnhancerOptions` | +| `packages/runtime/src/adapters/zustand.ts` | Zustand middleware (subpath `@genclass/runtime/zustand`) | `genclass` | +| `packages/runtime/src/types.ts` | Public store types | `StoreOptions`, `Atom`, `Guarded`, `StoreIO`, `AdapterIO`, `AdapterHandle`, `Change`, `RuntimeHooks.mutationProposed`, `PolicyOptions.holdUserWrites`, `InitOptions.settleMs` (inherited by `CreateOptions`) | +| `packages/runtime/src/util.ts` | Helpers used here | `isPlainObject`, `kindOf`, `hashValue` (FNV-1a over `stableStringify`, capped at 65,536 chars), `fnv1a`, `isIdSegment`, `normalizeFieldPath`, `describe` | +| `packages/runtime/src/trace/context.ts` | The ambient op; user-sync detection | `Context.isUserSync`, `Context.run`, `Context.stickUser` | +| `packages/runtime/src/situation/facts.ts`, `packages/runtime/src/situation/build.ts` | Consumers: mutation and inconsistency facts, state lines, action applicability | `mutationFacts`, `inconsistencyFacts`, `stateLines`, `builtinApplicable` (all module-private) | +| `packages/runtime/src/situation/env.ts` | The read-only view the situation builder gets of the store layer, built by `RuntimeImpl.makeEnv` | `Violation`, `SitEnv` (store-related members: `hub`, `lastConsistent()`, `consistentBefore(seq)`, `storeWriters`, `violations()`, `previewInvariants?(m)`, `resyncable(store)`, `chainWrites(op)`, `writable(store)`; the optional `writtenByChain?` is not set by `makeEnv`), `ChainWriteInfo { path, count, lastIsChain, before?: { value, removed } }` | +| `packages/runtime/package.json`, `packages/runtime/tsup.config.ts` | Subpath exports `./react`, `./redux`, `./zustand`; `react`/`redux`/`zustand` are optional peer dependencies (`>=18`, `>=4`, `>=4`) and tsup externals | - | + +The state modules are **not** exported from the package index. Tests reach them through `RuntimeImpl.hub` / `.miner` (public readonly fields) or `RuntimeImpl.internals` (`RuntimeInternals { hub, ops, events, base, profiles, miner, ctx, clock }`), which is not part of the public `Runtime` type. + +## Concepts and data structures + +### Store kinds (`StoreRec.kind`) + +| kind | created by | value lives in | `hub.read(s)` | how a write commits | external changes | `writable` (GenClass may write directly: rollback, revert) | +|---|---|---|---|---|---|---| +| `atom` | `rt.atom(name, initial, opts)`; React `useGenClassState` | `StoreRec.value` | `s.value` | `record()` sets `s.value` | impossible | always | +| `guard` | `rt.guard(name, io, opts)` | the app's store | `io.get()` | `io.set(next)` | `io.subscribe` callback -> `StoreHub.external` (recorded, never held) | always | +| `adapter` | `rt.adapter(name, io, opts)`; Redux enhancer; Zustand middleware | the library's store | `io.get()` | the proposal's `commit(next)`; GenClass's own writes go through `io.set` | same as guard | only when `AdapterIO.set` exists | + +Public types (`packages/runtime/src/types.ts`): + +```ts +interface StoreOptions<T> { resync?: () => Promise<unknown> | unknown; hold?: boolean /* default true */; describe?: (v: T) => string } +interface Atom<T> { readonly name: string; get(): T; set(next: T | ((prev: T) => T)): void; update(fn: (prev: T) => T): void; subscribe(fn: (v: T) => void): () => void } +type Guarded<T> = Atom<T>; +interface StoreIO<T> { get(): T; set(v: T): void; subscribe?(fn: () => void): () => void } +interface AdapterIO<T> { get(): T; set?(v: T): void; subscribe?(fn: () => void): () => void } +interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) => T; value?: T; commit: (next: T) => void }): void; dispose(): void } +``` + +- `resync` lets the `resync` action reload this store. `describe` replaces the store's value in state lines with one line (`packages/runtime/src/situation/build.ts` -> `stateLines`). `hold: false` means writes are traced but never held. + +### Paths and leaves (`packages/runtime/src/state/fields.ts`) + +- **Path syntax:** `<store>` or `<store>.<k1>[.<k2>[.<k3>[.<k4>]]]`. Keys are joined with `.`. Arrays have no element paths: `cart.items` is one field, and the miner's text uses `cart.items[*].price` notation only inside invariant descriptions. +- `flatten(store, value, prev?)` walks plain objects (`isPlainObject`: prototype is `Object.prototype` or `null`). It expands an object only when it has between 1 and `MAX_KEYS_EXPAND` (32) keys, the depth is below `MAX_DEPTH` (4), and `out.size + keys.length <= MAX_FIELDS_PER_STORE` (200). Otherwise the object becomes one **collection** leaf (kind `object`). Empty objects are collection leaves too. +- The 200-field cap is checked once per object, before expanding it, against the leaves emitted so far. Siblings walked later still add one leaf each, so a store can end slightly above 200 fields. Example: 32 top-level keys that each hold a 32-key object give 6 expanded objects (192 leaves) plus 26 collection leaves = 218 fields. Expansion is depth-first in `Object.keys` order, so which keys get expanded depends on key order. +- `Leaf { value; hash; kind; len; elems?; keys?; khash?; src? }`: + - `kind` comes from `kindOf`: `string`, `number`, `boolean`, `null`, `undefined`, `array`, `object`, `map`, `set`, `date`, `function`, `bigint`, `symbol`. + - `value`: primitives keep the value itself. Arrays keep a **shallow copy** (`arr.slice()`). Collections keep a shallow copy (`{...obj}`). Other objects (class instances, Map, Set, Date) keep the live reference. + - `len`: array length or collection size; -1 for everything else. + - `elems`: per-element hashes (arrays). `keys` / `khash`: key order and per-key hashes (collections). `src`: the live collection object, used for a cheap "same object" check. +- Hashes (`primHash`, `valueHash`): + - Strings up to 64 chars hash as `s:<string>`; longer strings as `S:<fnv1a>:<len>`. + - Other primitives: `n:<num>`, `b:1`/`b:0`, `u`, `i:<bigint>`, `y:<symbol>`, `f` (any function), `null`. + - Objects: `o:<hashValue>`, where `hashValue` uses sorted keys, so element key order does not matter. + - `hashValue` = `fnv1a(stableStringify(v))` (`packages/runtime/src/util.ts`). `stableStringify` walks only own enumerable keys (class `#private` fields and getters are invisible), writes functions as `"[fn]"` and cycles as `"[cycle]"`, and stops walking once the output exceeds `STRINGIFY_CAP` = 65,536 chars: it returns the first 65,536 chars plus `…<len>`, where `<len>` is the length emitted when it stopped (not the full serialized length). So a change that lies entirely beyond the cut in one element or one non-plain object is not detected. + - Non-plain objects (class instances, `Map`, `Set`, `Date`) are one leaf each, re-hashed in full by `leafOf` on every flatten of their store. There is no reference fast path for them, so a large `Map` in a store costs O(size) per write. + - Array leaf hash: `fnv1a("a<n>|<elems joined by ,>")`. Collection leaf hash: `fnv1a("c<n>|k=h,...")` in key order, so reordering the keys of a collection changes its hash. +- **Incremental flattening:** pass the previous leaves (`s.leaves`). + - `arrayLeaf` returns the previous `Leaf` object unchanged when the length is the same, every element is the same reference, and a sampled re-hash finds no in-place change. Otherwise it reuses element hashes by position or by reference and hashes only new elements. + - The sampled re-hash covers `SAMPLES` = 8 positions: 0, n-1 and `floor(j*n/8)`. Elements that kept their reference are re-hashed at those positions. If any differs, every object element is re-hashed. + - `objectLeaf` does the same for collections, keyed by key. It has one extra **fastest path**: when the object is the very same reference as last time (`obj === prev.src`, i.e. mutated in place), has the same key count and the same last key, only the 8 sampled positions are checked (same key, same value reference, and an unchanged re-hash for object values) before the previous `Leaf` is returned. A value replaced or a key swapped in place at a non-sampled position of such a collection is therefore **not** detected (see Gotchas). + - Returning the same `Leaf` object matters: the miner caches per-array statistics in a `WeakMap<Leaf, ArrayStats>`. + +### Changes and deltas + +- `FieldChange { path; before; after; beforeLeaf; afterLeaf; delta }` comes from `diffLeaves(before, after)`. A path is changed when its hash differs, when it is new, or when it was removed (`afterLeaf` undefined, `delta` `x:removed`). Output order: changed and added paths in the `after` map's order, then removed paths. +- `deltaOf` signatures. They are equal for "the same change applied again" and are used in repetition facts: + +| case | delta | +|---|---| +| removed | `x:removed` | +| number -> number | `n:<after-before>` (`toPrecision(12)`) | +| array -> array | `a:+<added hashes sorted>\|-<removed hashes sorted>` (multiset diff), or `o:<hash>` for a pure reorder | +| collection -> collection | `c:<sorted +k=h, ~k=h, -k>` | +| anything else | `v:<after hash>` | + +- `changeText(c, redact)` produces the one-line summaries used in `state` events and facts. Examples: `3 → 4 items: added {id: 9, …}`, `3 items, 1 changed: {id: 3, qty: 1 → 2}`, `2 → 3 entries: added m21: …`, `"r" → "re"`, `3 items, reordered`. `elementDiff` shows an element's id key (from `id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`) and at most 3 changed keys. +- `changeText` rules (`fields.ts` -> `changeText`), which are parity-relevant: + - Array, same length: no differing position gives `N items, unchanged`. If the multiset is unchanged, the result is `N items, reordered`. When K differing positions number at most `max(1, N/2)`, the result is `N items, K changed: <elementDiff of the first>`, plus `, and K-1 more` when K > 1. Otherwise the full `before → after` text is used when it fits in 90 chars, else `N items, K changed`. + - Array, length changed: the full text if it fits in 70 chars, else `B → A items: added <first> and K more; removed N items`. + - Collection: `B → A entries: added k: …; changed k: {…}; removed k1, k2 and K more`. + - Anything else: `<before> → <after>`, each part described in at most 36 chars. + +### Field state, write logs, recent changes (`hub.ts`) + +| type | fields | bound | +|---|---|---| +| `FieldState` | `path, v` (version, starts at 0), `writer` (op id or null), `t, seq` (global seq of last write), `hist: FieldHist[], log: LogEntry[]` | one per path ever seen (fields are created at registration for the initial leaves and on first write) | +| `FieldHist` | `v, seq, writer, root` (root op of the writer's chain), `user` (user-sync), `t, delta, before, after, beforeLeaf?, afterLeaf?, mutation` (MutationRec id, 0 for non-pipeline writes) | last `HIST` = 16 per field | +| `LogEntry` | `seq, v, t, writer, root, user, mutation` | last `LOG` = 512 per field | +| `RecentChange` | `t, seq, store, paths` (sorted, comma-joined), `key` (paths + `path=delta` pairs, sorted), `writer, root, user, mutation` | the hub keeps those within `RECENT_MS` = 10,000 ms, and at most `RECENT_MAX` = 256 | + +- `StoreHub.seq` is the global **applied-change sequence number**. It is bumped once per recorded write that changed something. `OpRec.startSeq` is `hub.seq` when the op started, and facts compare field versions at that point using `versionAt(path, seq)`. `versionAt` is exact for the last 512 writes. +- Query helpers: `field`, `versionAt`, `logSince`, `writesSince`, `changedSince`, `pending`, `allLeaves`, `valueAt`, `leaf`, `describeValue`. The path-taking lookups (`field`, `versionAt`, `logSince`, `writesSince`, `valueAt`, `leaf`) resolve a path's store by `path.split(".")[0]`; `changedSince`, `pending` and `allLeaves` iterate all stores. +- `versionAt(path, seq)`: binary search of the field's 512-entry log for the last entry with `entry.seq <= seq`. If `seq` is older than the oldest kept entry it returns `log[0].v - 1` (exact only when nothing was trimmed); with an empty log it returns the current `v`; for an unknown path, 0. +- `changedSince(seq)` returns `{ path, hist, count }` for every field of every store with `f.seq > seq`: `hist` is limited to the 16-entry history, `count` comes from the 512-entry log. +- `FieldState` records are never deleted. A removed path keeps its `FieldState` (so `field(path)` still answers) while `leaf(path)` / `valueAt(path)` return undefined. + +### `MutationRec` (one proposal) + +| field | meaning | +|---|---| +| `id` | counter (`StoreHub.mid`) | +| `store`, `changes: FieldChange[]` | diff of the preview against the store's current leaves at proposal time | +| `cause: OpRec \| null`, `root` | the ambient op (`ctx.op()`) and its root | +| `t` | proposal time | +| `base` | `hub.read(s)` at proposal time | +| `preview`, `leaves` | the value the write would produce now, and its leaves | +| `fn?` | the functional updater. It is omitted when the preview had to be **detached** (see "in-place protection"), in which case the write is re-applied as a patch | +| `commit?` | custom commit (adapter `commit`); otherwise atom/guard semantics | +| `userSync`, `genclass` | bypass flags at proposal time | +| `defers` | 0, 1 or 2 | +| `state` | `queued` -> `held` -> `resolved` -> `done` | +| `verdict?: Verdict` | `"apply" \| "discard" \| "defer"` | +| `outcome?` | `applied`, `discarded`, `deferred` or `failed` (the app's setter threw) | +| `appliedAt?`, `appliedSeq?`, `applied?` | when it applied, its global seq, and the changes actually made. Late revert uses these | +| `unholdable?` | why the write could not be held | + +`StoreHub.mutations` (a `Map<id, MutationRec>`, trimmed from above 512 down to 256 by deleting `done` entries) is written but never read anywhere in `src/`. + +### `StoreRec` and `HubHooks` + +`StoreRec { name, value, version, fields, leaves, opts, io?, subs, queue, unsubscribeIO?, committing, kind, writable }`. +- `version` counts recorded writes that changed something. +- `committing` suppresses external-change detection while GenClass itself commits through `io.set` or `commit`. +- `subs` holds `Atom.subscribe` listeners. + +`HubHooks` is the seam to the runtime. `RuntimeImpl`'s constructor installs it: + +| hook | runtime implementation | purpose | +|---|---|---| +| `gate(m)` | `RuntimeImpl.gateMutation` | raise the `mutation` trigger; return `{}` (apply now) or `{ held: Promise<Verdict> }` | +| `mayHold(s)` | `consultable() && mode !== "observe"` | whether a write could be held, which decides whether live state must be protected from in-place updaters | +| `waitRelated(m)` | `RuntimeImpl.waitRelated` | for `defer`: resolves when related in-flight ops end (at most `LONG_RUNNING_MS` = 10,000 ms) | +| `applied(m, s, changes, writer)` | `RuntimeImpl.onApplied` | bookkeeping plus scheduling a settled point | +| `discarded(m)` | `scheduleSettle()` | - | +| `proposed?(m)` | calls `CreateOptions.hooks.mutationProposed({ id, store, paths, cause?, changes })` synchronously; errors are swallowed | tracing (sim, demos) | +| `appError?(e, source)` | `RuntimeImpl.reportError(e, { source })` | app code threw while GenClass applied a write later | + +`mayHold` ignores its store argument: `hold: false` stores never reach it because they already bypass in `propose`. + +### `StoreHub` surface (`packages/runtime/src/state/hub.ts` -> `StoreHub`) + +Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created once in the `RuntimeImpl` constructor. `hooks` is assigned right after. + +| member | kind | used by / purpose | +|---|---|---| +| `stores: Map<string, StoreRec>` | readonly field | the registry; also read by `situation/build.ts` and `RuntimeImpl.pluginApi` | +| `seq` | field, starts 0 | global applied-change sequence (see above) | +| `recent: RecentChange[]` | readonly field | repetition facts (`situation/facts.ts`), late-revert chain check | +| `mutations: Map<number, MutationRec>` | readonly field | written, never read (see below) | +| `hooks: HubHooks` | field | installed by `RuntimeImpl` | +| `holdUserWrites` | field, default `false` | copied from `policy.holdUserWrites` once | +| `gating` | field, default `true` | `pause()`/`destroy()` set false, `resume()` sets true | +| `register(name, kind, initial, opts, io?)` / `unregister(name)` | methods | flow 1. `unregister` unsubscribes `io` and drops the snapshot cache entry; its only caller is `AdapterHandle.dispose` | +| `get(name)` / `read(s)` | methods | lookup; current value (`io.get()` or `s.value`) | +| `propose(s, w)` | method, returns `MutationRec \| null` (never null in practice) | flow 2 | +| `commit(s, m, rethrow)` | method | flow 4; also called directly by the `discard` undo | +| `write(s, next, writer, m, commit?, rethrow = false, leaves?)` | method | flow 4; also called directly by `rollback`, its undo, and post-`destroy()` writes | +| `external(s)` / `record(...)` / `notify(s)` | methods | flows 8 and 4 | +| `revertable(m)` / `revert(m, writer)` / `reapply(m, writer)` | methods | late revert and its undo (flow 7) | +| `restoreFields(values, writer)` | method, returns restored paths | chain revert and its undo (flow 10) | +| `snapshot()` / `allLeaves()` | methods | settled points (flow 9) | +| query helpers | methods | listed above | +| `previewOf`, `restoreInPlace`, `gateAndQueue`, `drain`, `defer`, `patched`, `mid`, `snapCache` | private | pipeline internals | + +### Invariant miner (`invariants.ts`) + +- A candidate (`Cand`, private) has: `id`, `tpl`, `text`, the operands `a`/`b`/`B`/`f`/`g`, `watch` (the leaf paths whose change counts as "involved"), `held` (supporting settled points), `learned`, and `typeKind`. +- Templates: + +| tpl | id | text | proposed when (on the current leaves; paths under id-like segments skipped) | holds when | +|---|---|---|---|---| +| `type` | `type:<a>` | `typeof a stable` | every field whose kind is not null/undefined | kind == recorded kind (null/undefined: not applicable) | +| `nonnull` | `nonnull:<a>` | `a != null` | the field was never seen null/undefined, including its initial value (`nullSeen`) | value not null/undefined | +| `nonneg` | `nonneg:<a>` | `a >= 0` | number > 0 | number >= 0 (null/undefined: n/a) | +| `eq` | `eq:<a>:<b>` | `a == b` | two scalars (number/string) of the same kind, equal (`numEq` for numbers), value not 0 / `""` | equal (`numEq` for numbers, else `===`) | +| `len` | `len:<a>:<B>` | `a == len(B)` | number a (≠ 0) equals the length of a non-empty array B | `a === B.len` | +| `sum` | `sum:<a>:<B>:<f>` | `a == sum(B[*].f)` | B is a non-empty array of plain objects; f is a numeric column; `numEq(a, Σf)` | same; an empty B requires a ≈ 0 | +| `sumprod` | `sumprod:<a>:<B>:<f>:<g>` | `a == sum(B[*].f * B[*].g)` | as `sum`, for column pairs with `f < g` (string order) | same | +| `in` | `in:<a>:<B>:<k>` | `a ∈ B[*].k` | scalar a (not under B, not `""`/0) is a value of column k | the value is in the column set (null/undefined/`""`: n/a) | +| `unique` | `unique:<B>:<k>` | `B[*].k unique` | B has at least 2 elements and column k has no duplicates | no duplicates among non-null values | + +- **Columns** come from the first 32 keys of element 0. The numeric columns are those numeric in every element; the scalar columns are those number-or-string in every element. Each list keeps at most `MAX_COLUMNS` = 8. Per-array statistics (`sums`, `prods`, `sets`, `unique`) are cached per `Leaf` object. +- **Non-trivial** (`nonTrivial`): a candidate is created, or gains support, only when it says something. `eq` needs a non-zero, non-empty, non-false value. `len` needs n > 0. `sum`/`sumprod` need n > 0 and a ≠ 0. `in`/`unique` need n >= 2. `nonneg` needs a value > 0. +- `numEq(a, b)` is true when the values are equal, or within a relative 1e-6 (scaled by `max(1, |a|, |b|)`), or when they differ by less than 0.0051 and round to the same cents. +- `Violation` (`packages/runtime/src/situation/env.ts`): `{ id, text, fields, values, held, developer? }`. `values` is redacted text such as `cart.count = 4, len(cart.items) = 5`. +- **Developer expectations:** `rt.expect(name, pred)` -> `InvariantMiner.addExpect`. They are evaluated at every settled point from the start. A false or throwing predicate gives `{ id: "expect:<name>", text: <name>, fields: [], values: "the predicate returned false", held: 0, developer: true }`. `expect` returns a disposer that removes only that registration; calling `expect` again with the same name replaces the earlier predicate. +- **Which fields are considered.** `propose` walks `hub.allLeaves()` in order (stores in registration order, then flatten order) and skips `dynamicPath` paths. Per-field templates (`type`, `nonnull`, `nonneg`) are tried for every remaining field. The relational templates only see the **first** `MAX_NUMERIC` (64) finite numeric leaves, `MAX_SCALAR` (96) number/string leaves and `MAX_ARRAYS` (24) array leaves in that order, so fields of stores registered late in a big app may never get `eq`/`len`/`sum`/`in`/`unique` candidates. Once `MAX_CANDIDATES` (4,000) candidates exist, `add` creates nothing new until some are dropped. +- **Null tracking:** `noteValues` runs at registration and on every applied write with `[path, afterLeaf]`. A null/undefined value **or a removed path** marks the path `nullSeen` and drops a not-yet-learned `nonnull:<path>` candidate at once (not only at the next settled point). +- **Learned is permanent.** A learned candidate is never dropped. While it is broken it is returned in `observe()`'s violations (and `current()`) at every settled point; the runtime raises it only once per episode. +- **Shape changes count as violations.** For a learned `sum`/`sumprod`, a non-empty `B` whose elements are no longer all plain objects, or whose column `f` (or `g`) is missing or non-numeric in any element, or is no longer among the first `MAX_COLUMNS` (8) numeric columns taken from element 0's first 32 keys, evaluates to `false`, not "not applicable". For example, one placeholder element `{ id, loading: true }` without `price` breaks `total == sum(items[*].price)`. A learned `in` is also `false` once `B`'s elements are not all plain objects. `unique` returns `true` in that case. +- Introspection: `learned()` returns `{ id, text, held }[]`, `candidates()` returns the candidate count, and `points` counts settled points. Tests use them through `rt.miner` (`invariants.test.ts`) or `rt.internals.miner` (`review-perf.test.ts`). + +### Runtime-side state terms + +- **User-sync write:** the cause is the current task's user op or descends from it (`Context.isUserSync`: `op === taskUser || op.root === taskUser.root || op.root === taskUser.id`). `taskUser` is set by `RuntimeImpl.user` -> `Context.stickUser` and cleared after the macrotask (`clock.afterTask`). A write with no ambient op at all is not user-sync and is treated like async code. +- **Bypass write:** applied at once in the caller's stack. Errors propagate to the caller. +- **Consistent snapshot:** `{ t, seq, values: Map<store, deep clone> }` in `RuntimeImpl.snaps`, newest last, at most 8. +- **Episode:** the set of violation ids at the previous settled point (`RuntimeImpl.episode`). A violation is *fresh* only when it was not violated at the previous settled point. +- **Muted:** violation ids whose rollback the developer undid. They are not raised again until they hold at a settled point. +- **Chain revert:** the `rollback` used for `error`/`transition` triggers. It restores only the fields the op's causal chain wrote (see flow 10). + +## How it works + +### 1. Registering a store + +1. `RuntimeImpl.atom(name, initial, opts)`: + - If a store of kind `atom` named `name` exists, it is reused: `initial` is ignored, and `opts` are merged only if `resync`, `describe` or `hold` is given. + - Otherwise `StoreHub.register(name, "atom", initial, opts)` runs, followed by `miner.noteValues(s.leaves)`, which records fields that start out null. + - It returns `RuntimeImpl.handle(s)`. +2. `RuntimeImpl.guard(name, io, opts)` -> `register(name, "guard", io.get(), opts, io)`. If `io.subscribe` exists, the hub subscribes and calls `StoreHub.external(s)` whenever the store changes while `!s.committing`. +3. `RuntimeImpl.adapter(name, io, opts)`: + - Wraps `io` in a `StoreIO` whose `set` throws `store <name> cannot be written by GenClass` when `io.set` is missing. + - Registers kind `adapter` and sets `s.writable = typeof io.set === "function"`. + - Returns `{ name, propose, dispose }`. `propose(w)` forwards to `StoreHub.propose(s, { fn | value, commit })`. After `destroy()` it computes `next` and calls `hub.write(s, next, null, null, commit)` directly. `dispose()` unregisters only if the hub still holds this same record. +4. `StoreHub.register`: + - **Replaces** any existing store with the same name (whatever its kind), unsubscribing the old one. + - Flattens the initial value. + - Creates a `FieldState` (v 0) per leaf. +5. Atom handle (`RuntimeImpl.handle`): + - `get()` -> `hub.read(s)`. + - `set(next)` -> `hub.propose(s, { fn })` or `hub.propose(s, { value })`. After destroy it calls `hub.write` directly. + - `update(fn)` = `set(fn)`. + - `subscribe(fn)` adds to `s.subs` and returns an unsubscribe function. + +### 2. Proposing a write (`StoreHub.propose`) + +1. `cause = ctx.op()` (this materialises a lazy timer op), `base = read(s)`, `userSync = ctx.isUserSync(cause)`, `genclass = !!cause?.genclass`. +2. `bypass = (userSync && !holdUserWrites) || genclass || s.opts.hold === false || !gating`. `gating` is false after `pause()` or `destroy()`. +3. `guarded = !bypass && hooks.mayHold(s)`. +4. `previewOf(s, w, base, guarded)`: + - Value write: `preview = w.value`. + - Functional write: `preview = w.fn(base)`. If the write is `guarded`, the hub checks whether the updater mutated the live value in place: it flattens `base` against the stored leaves. + - If it did, the preview is **detached**: `cloneValue(preview)`, then `restoreInPlace` undoes the in-place edits using the recorded `beforeLeaf` values. + - If cloning or the exact restore fails, the write is marked `unholdable` ("the update changed the stored value in place, so it could not be held"). +5. `changes = diffLeaves(s.leaves, previewLeaves)`. A `MutationRec` is built and `hooks.proposed(m)` fires. This happens for bypass writes too. +6. If `changes.length === 0 || bypass || unholdable`: `commit(s, m, rethrow = true)` runs **now**, in the caller's stack, and returns. +7. Otherwise the write is pushed onto `s.queue` and `gateAndQueue(s, m)` runs. + +### 3. Gate and hold (`StoreHub.gateAndQueue` -> `RuntimeImpl.gateMutation`) + +1. If `!consultable()` (paused, destroyed, no decider, or decider status not `ready`/`off`), the gate returns `{}`: the write is resolved as `apply` and the queue drains. +2. Otherwise it builds a `Controller` and calls `RuntimeImpl.trigger({ trigger: "mutation", m }, ctl, { hold: true, priority: 2 })`. The controller's methods: + - `passive` -> verdict `apply`. + - `run("discard")` -> verdict `discard`. Its effect text is "Dropped the write to … stays at version N". Its `undo` commits the original mutation as a GenClass write. + - `run("defer")` -> verdict `defer`. + - `revertable` / `revert` are used for late reverts (flow 7). +3. Inside `trigger`, see [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md): + - If the trigger is not salient, the model is not ready, or no non-passive action is permitted (always the case in `observe` mode), `passive()` runs **synchronously**. `gateMutation` sees `syncVerdict === "apply"` and returns `{}`. + - Otherwise the write is **held**. A timer fires after `holdBudgetMs()`: then `expired = true` and `passive()` runs (fail-open). + - The decision deadline is `t0 + budget + LATE_REVERT_MS`, because the mutation controller supports `revert`. + - When the write does not wait because no non-passive action is permitted, the decision is still requested in the background for detection (queue priority capped at 1). A non-passive answer is then only recorded: `gate` finds no permitted candidate, nothing runs, and `Decision.reason` is the restriction of the model's top choice (e.g. `observe mode never changes execution`) or `no action is permitted`, set only when that top choice was non-passive. `the subject was not held` appears only if `setMode` widened the permitted set between the trigger and the answer (see [decide-policy-actions.md](decide-policy-actions.md#3-gate-and-bookkeeping-runtimets---ondecision-policyts---gate)). +4. `gateMutation` returns `{}` for a synchronous `apply`, otherwise the pending promise. It also has a defensive branch that wraps a synchronous `discard`/`defer` in `Promise.resolve(verdict)`; with the current `trigger`, actions only run in the queue's `.then` (`onDecision`), so only `apply` can be synchronous. +5. A held promise resolves to the verdict. If the gate throws, the result is treated as `{}`. If the held promise rejects, the verdict is `apply`. + +### 4. Drain, commit, record + +1. `StoreHub.drain(s)` pops resolved writes **from the head only**, which keeps proposal order per store. + - `discard` -> `outcome = "discarded"`, `hooks.discarded`. Nothing is written and app subscribers are not notified. + - `defer` with `defers < 2` -> `outcome = "deferred"` and flow 5. + - Otherwise (`apply`, or a third `defer`) -> `commit(s, m, false)`. + - Every branch is wrapped in try/catch. On an error, `hooks.appError(e, "applying a write to <store>")` runs and draining continues. +2. `StoreHub.commit(s, m, rethrow)`: + - If `read(s) === m.base`: `next = m.preview` and the precomputed leaves are reused. + - Otherwise `next = m.fn ? m.fn(current) : patched(s, m, current)`. The updater re-runs, or the value write is re-applied as a patch. + - If that throws: with `rethrow` it propagates. Without it, `appError(e, "re-running an update of <store>")` runs and the hub falls back to `next = m.preview`, the value computed at proposal time. + - Then `ctx.run(m.cause, () => write(...))`. The write's cause is the ambient op, so writes made by subscribers join the same causal chain. +3. `StoreHub.write(s, next, writer, m, commit?, rethrow, leaves?)`: + - With `commit` or `io`: set `s.committing = true` and call `commit(next)` or `io.set(next)`. + - On a throw: rethrow, or call `appError(e, "the setter of <store>")` and return `null` (`outcome = "failed"`). + - Afterwards re-read the store. If the store now holds a different reference than `next`, that value is what gets recorded. +4. `StoreHub.record(s, next, writer, m, precomputed?)`: + - Diff the new leaves and set `s.value` and `s.leaves`. + - With no changes: notify subscribers only when the reference changed or when this is a pipeline write ("every `set()` notifies subscribers"). + - With changes: + - `seq++` and `version++`. + - Per changed field: `v++`, writer, `t`, `seq`, a `FieldHist` entry and a `LogEntry`. + - Push a `RecentChange` and trim the recent list. + - Push a `state` event. Its `op` is the writer and its data is `{ store, paths, mutation, user, summary }`, where the summary covers the first 3 changes via `changeText`. + - Call `hooks.applied` and `notify(s)`. +5. `StoreHub.notify` calls each `subs` listener with `s.value`. A throwing listener goes to `appError(e, "a subscriber of <store>")` and is never rethrown, even on the synchronous path. +6. `RuntimeImpl.onApplied(m, s, changes, writer)`: + - `writer.wrote++` and `writer.storesWritten`. + - For the writer and up to 8 ancestors (GenClass ops skipped): increment `storeWriters[opSignature][store]` (capped at 1,000 signatures, FIFO). Profiled op kinds (`fetch`, `xhr`, `user`, `task`, `ws`) that are not yet profiled also accumulate `op.chain[normalizeFieldPath(path)] = { kind, len0, len1 }` and `op.chainWrites` for transition profiles. + - `miner.noteChanged(paths)` and `miner.noteValues(...)`. + - `scheduleSettle()`. + +### 5. Defer (`StoreHub.defer`) + +1. `hooks.waitRelated(m)` (`RuntimeImpl.waitRelated`) waits for the related in-flight ops. An op is related when it is not in the cause's own ancestry or descent and either has the cause's signature and kind, or its signature's chains have written this store before (`storeWriters`). The wait resolves when all of them end, or after 10,000 ms. +2. Then the write is re-proposed **at the end of the queue** with the same id, cause and intent: + - `preview = m.fn ? m.fn(cloneValue(base)) : patched(s, m, base)`. If that throws, the old preview is used. + - `defers + 1`, new `changes`. + - If nothing would change, or `gating` is off, it commits at once (errors reported, not rethrown). Otherwise it goes through `gateAndQueue` again. + - `hooks.proposed` (`mutationProposed`) is **not** called again for the re-proposal. If the store was unregistered while waiting (`!stores.has(name)`), the write is silently dropped. +3. The `defer` action is not offered once `defers >= 2` (`packages/runtime/src/situation/build.ts` -> `builtinApplicable`). The facts add "This write was already deferred once." / "… twice." (`situation/facts.ts` -> `mutationFacts`). + +### 6. Patches (`fields.ts` -> `patchValue`) + +Used by `patched` (a held or queued value write applied over newer state), `revert`, `reapply` and `restoreFields`. + +1. If a change targets the whole store (`path === store`), return its value. +2. If the current value is not a plain object, return `ok: false`. +3. `sets` = changes that are not removals. `removals` = removed changes **except** those with a set beneath them (`t.path.startsWith(c.path + ".")`). Example: when an empty object `data: {}` is filled, its collection leaf `x.data` disappears (a removal) and `x.data.name` appears (a set). Applying the removal of `x.data` would delete the whole object in the current value, including anything newer writes put under it. +4. Apply all removals first, then all sets, with copy-on-write along each path. Missing intermediate objects are created for sets and ignored for removals. A non-plain-object intermediate gives `ok: false`. +5. When a patch fails: `patched` falls back to `m.preview`, `revert`/`reapply` return null, and `restoreFields` skips that store. + +### 7. Late revert (hold budget expired, then `discard`) + +1. In `RuntimeImpl.onDecision`, when `st.hold && (st.expired || passiveRan)` and the gate chose `discard`, the runtime calls `ctl.revertable()`. It returns null or a reason string: + - `the write has not applied yet`; + - age > `LATE_REVERT_MS` (2,000 ms) -> `too late to revert: decided Xs after the write applied`; + - `StoreHub.revertable(m)`: `the store is gone`; `the write was not applied`; `<store> cannot be written by GenClass`; `the write changed nothing`; + - `superseded: <path> changed again after the write applied`, when for some applied path the field's last log entry is not this mutation; + - `the same operation chain wrote <paths> after this write applied; …`, when a `RecentChange` with `seq > appliedSeq` has the same root and a different mutation id. Writes made synchronously by subscribers count, because they run under the write's cause. +2. If it is revertable: `runAsGenClass("revert", () => hub.revert(m, op))` patches `m.applied` back to the `before` values. The `ActionRecord` gets `late: true` and the text "Reverted the write to … (decided Xs after it applied); … is back to …". `undo` -> `hub.reapply(m)`. +3. Any other verdict that arrives after expiry is only recorded, with the reason "the decision arrived after the hold budget expired". +4. The decision deadline for a held write is `t0 + holdBudgetMs() + LATE_REVERT_MS`. A request still unanswered then is abandoned by the decider queue (`decide/decider.ts` -> `DeciderQueue`), so no decision is recorded at all (`atoms.test.ts` "a late discard does not revert … or after 2 s"). Because a held write cannot apply before its own budget expires, a decision that beats the deadline is at most 2 s after the apply, so the `too late to revert` branch is effectively unreachable (found by code reading). + +### 8. External changes + +`io.subscribe` -> `StoreHub.external(s)` -> `record(s, read(s), ctx.op(), null)`. The change is recorded with the ambient op as writer, `user = ctx.isUserSync(writer)` and `mutation = 0`. It is **never held**. This is how direct `store.dispatch` calls bypassing the enhancer, or app-side changes to a guarded store, get versions. + +### 9. Settled points, invariants, snapshots, inconsistency + +1. `RuntimeImpl.scheduleSettle()` is a debounced `clock.setTimeout(settled, settleMs)`, with a default of 60 ms. It is called from `onApplied`, from `discarded`, and from every `endOp`. +2. `RuntimeImpl.settled()` returns early if the runtime is destroyed or `busy()`. `busy()` is true when any in-flight op started less than 10,000 ms ago, or `hub.pending()` is non-empty. It does **not** reschedule; the next write or op end does. +3. `miner.observe(hub.allLeaves(), now)`: + 1. `points++`. Take and clear the `changed` paths. + 2. For every candidate: `h = holds(c, L)`. Skip it when `h` is null (a field is missing, or the template does not apply to the current values, e.g. a null operand). `involved` means a watched path, or a path below it, changed since the last settled point. + - Learned: if it holds and is involved, `held++`. If it does not hold, it is a **violation** (learned candidates are never dropped). + - Not learned: if it does not hold, it is **dropped forever** (added to the `dropped` set). If it holds, is involved and is non-trivial, `held++`. It becomes learned at `LEARN_AFTER` (3), or at `LEARN_AFTER_NONNULL` (6) for `nonnull`. + 3. `propose(L)` creates new candidates (see the template table). A new candidate starts at `held = 1` if one of its fields changed at this settled point. + 4. Evaluate the developer expectations. + 5. Return the violations, also kept in `current()`. +4. Back in `settled()`: + - `brokeNow` = violations not in the previous `episode`; `fresh` = `brokeNow` minus `muted`. Then `episode = current ids`, and muted ids that hold again are cleared. + - If `brokeNow` is empty, take a **snapshot**: `hub.snapshot()` deep-clones every store, reusing unchanged stores and unchanged top-level keys. If the last snapshot has the same `seq`, only its `t` is refreshed. At most 8 snapshots are kept. + - If `fresh` is non-empty: `raiseInconsistency(fresh)` -> `trigger({ trigger: "inconsistency", violations }, ctl, { hold: false, priority: 1 })`. The actions are `ignore` (passive), `rollback` and `resync`. + - Then the transition profiles run; see [learn-situation-triage.md](learn-situation-triage.md). +5. Mutation facts also call `env.previewInvariants(m)` -> `InvariantMiner.preview`. It reports learned invariants touching the written paths that would break on the preview leaves, as a **neutral** fact, because transient breaks between two writes are common. + +### 10. State-restoring actions + +| action (trigger) | implementation | what it restores | offered when (`builtinApplicable`) | undo | +|---|---|---|---|---| +| `rollback` (`inconsistency`) | `RuntimeImpl.rollback(stores, violationIds)` | the **whole value** of each involved store that is writable and present in the newest consistent snapshot. Written via `hub.write(s, cloneValue(snapValue), genclassOp, null)`; adapters receive it through `io.set` | a consistent snapshot exists and some involved store is writable | writes the pre-rollback clones back and mutes the violation ids | +| `rollback` (`error`, `transition`) | `RuntimeImpl.revertChain(op, why)` -> `chainWrites(op)` -> `hub.restoreFields` | only the fields written by the op's root chain since `root.startSeq` that nobody else overwrote (`lastIsChain`) and whose value before the chain's first write is still in the 16-entry history | the chain wrote such a field in a writable store | `restoreFields(current values)` | +| `resync` (`inconsistency`, `transition`) | `RuntimeImpl.resync(stores)` | calls each involved store's `opts.resync()` inside a GenClass op | some involved store has `resync` | none | +| `discard` undo | `hub.commit(st, { ...m, genclass: true, … }, false)` | applies the dropped write now (re-run or patch) | - | - | + +Failure messages (thrown, so the action is recorded as failed): `no consistent snapshot`, `nothing to restore: the affected stores already match the snapshot` (`rollback`); `the chain wrote nothing that can be restored`, `nothing to restore: the fields already hold their earlier values` (`revertChain`); `no resync handler` (a rejected `resync`). Effect texts: `Restored <store> (<paths>) to the consistent state from Ns ago.`, `Restored <paths> to their values before <root op> (the <error|transition>'s chain wrote them).`, `Reloaded <stores> from its/their source (resync handler).`. `resync` awaits every handler with `Promise.all`. Ops started inside it inherit `genclass` from their cause (`packages/runtime/src/trace/ops.ts` -> `OpRegistry.start`), so the writes its requests trigger also bypass gating. + +All of these run inside `runAsGenClass(...)`, and `ActionRecord.undo` wraps undos in `runAsGenClass("undo")`, so their writes bypass gating. They are recorded with a GenClass op as the writer. The exception is the discard undo: `hub.commit` runs under `m.cause`, so it is recorded with the original cause as the writer. + +### 11. Adapters + +**React** (`packages/runtime/src/adapters/react.ts`): + +```tsx +GenClass.init(); // or <GenClassProvider runtime={rt}> +const [results, setResults] = useGenClassState("results", [] as Item[]); // shared named atom +const [cart, setCart] = useAtom(cartAtom); // any Atom from rt.atom / rt.guard +``` + +1. Which runtime is used: `useRuntimeOrNull()` returns the nearest `<GenClassProvider runtime>` value. If there is no provider (context `undefined`), it returns `GenClass.runtime`. `runtime={null}` explicitly means no GenClass. +2. `useGenClassState(name, initial, opts?)`: + - With a runtime, `atomFor` creates or reuses **one atom per (runtime, name)**, stored in a module `WeakMap<Runtime, Map<name, Atom>>`. The lazy `initial` is called once. `opts` only apply at creation. Creation is idempotent, which makes it safe under StrictMode. + - It reads with `useSyncExternalStore` over memoised wrappers of `atom.subscribe` and `atom.get` (the same getter for the server snapshot). The setter calls `atom.set`, so a held write shows up only when it applies and never when it is dropped. + - Without a runtime it is plain `useState`, and it logs one `console.info` per module (`warned`). +3. `useAtom(atom)` is `useSyncExternalStore` over any `Atom`. `getGenClassAtom(rt, name)` returns a hook-created atom so code outside React can use it. It returns `undefined` for a store created with `rt.atom` directly, because it reads only the hook registry. + - `atomFor` calls `rt.atom(name, …)`. If `name` is already an **atom**, that returns the existing store, merging `opts` when `resync`/`describe`/`hold` is given. If `name` is a **guard or adapter** store (for example a Redux store named `"cart"`), `rt.atom` re-registers it as an atom and replaces it (see Gotchas). + - Signatures: `useGenClassState<T>(name: string, initial: T | (() => T), opts?: StoreOptions<T>): [T, Dispatch<SetStateAction<T>>]`; `useAtom<T>(atom: Atom<T>): [T, (next: T | ((prev: T) => T)) => void]`; `getGenClassAtom<T>(runtime: Runtime, name: string): Atom<T> | undefined`. +4. `useGenClass()` throws `[GenClass] No runtime: …` when there is none. +5. `useGenClassDecisions(limit = 50)` refreshes on `decide`/`act`. `useGenClassInterventions(limit = 50)` refreshes on `act`. Both cache snapshots per event version. `useGenClassStatus()` returns a snapshot keyed by content, so providers that mutate the status object in place still re-render, and it returns `{ state: "off" }` without a runtime. + +**Redux** (`packages/runtime/src/adapters/redux.ts`): + +```ts +configureStore({ reducer, enhancers: (gd) => gd().concat(genclassEnhancer(GenClass.runtime, { name: "app" })) }); +createStore(reducer, compose(applyMiddleware(thunk), genclassEnhancer(rt, { name: "app" })) as StoreEnhancer); +``` + +Signature: `genclassEnhancer<S = unknown>(runtime: Runtime | null | undefined, options: GenclassEnhancerOptions<S>): StoreEnhancer`, where `interface GenclassEnhancerOptions<S> extends StoreOptions<S> { name: string }`. So `resync`, `hold` and `describe` can be passed next to `name`; everything except `name` is forwarded to `runtime.adapter` as `StoreOptions`. + +1. The enhancer wraps the reducer: + - `@@genclass/REPLACE` (`GENCLASS_REPLACE`) returns `action.state`. + - If `ready` holds `{ action, prev, next }` for this exact action object and previous state, it returns `next` without re-running the reducer. + - Otherwise it calls the current reducer. +2. If `runtime` is null, the store is returned unchanged. Only the REPLACE-aware reducer wrapper remains. +3. The store is registered as `runtime.adapter(name, { get: getState, set: v => raw({ type: GENCLASS_REPLACE, state: v }), subscribe }, storeOpts)`. Because `set` exists, Redux stores are writable (rollback works). +4. `dispatch(action)`: + - A non-action (a thunk) passes straight to the inner dispatch. + - Otherwise it computes `next = reducer(state, action)` once, as the preview. + - If `next === state`, it is a plain dispatch: subscribers are notified and nothing is proposed. + - Otherwise `handle.propose({ fn: prev => prev === state ? next : reducer(prev, action), commit: v => dispatchKnown(action, v) })`, and it returns `action` synchronously, even while the write is held. +5. `dispatchKnown` sets `ready` and calls the inner dispatch, so inner enhancers such as Redux DevTools, reducers and subscribers see the **original action exactly once**, at apply time. A dropped dispatch never reaches them. +6. `replaceReducer` swaps `current` and re-installs the wrapper. +7. Put the enhancer **last** in `compose()` (innermost). If it is outermost, the actions that thunks dispatch through the middleware API skip it; they are then only recorded as external changes and never held. + +**Zustand** (`packages/runtime/src/adapters/zustand.ts`): + +```ts +const useCart = create<Cart>()(genclass(GenClass.runtime, "cart")((set) => ({ items: [], add: (i) => set((s) => ({ items: [...s.items, i] })) }))); +create<Cart>()(devtools(genclass(rt, "cart")(creator))); // with devtools outside +``` + +Signature: `genclass(runtime: Runtime | null | undefined, name: string, opts?: StoreOptions<unknown>)` returns a middleware `(initializer) => initializer` that keeps Zustand's mutator typing. `opts` (`resync`, `hold`, `describe`) go to `runtime.adapter`. + +1. If `runtime` is null, the initializer runs unchanged. +2. `gset(partial, replace, ...rest)`: + - Before the handle exists (a `set` during creation), it calls the outer `set` directly. Such a write is neither traced nor proposed. + - Otherwise it proposes `fn: prev => { next = typeof partial === "function" ? partial(prev) : partial; if (Object.is(next, prev)) return prev; whole = replace ?? (typeof next !== "object" || next === null); return whole ? next : Object.assign({}, prev, next) }` with `commit: v => outer(v, true, ...rest)`. + - Extra arguments, such as devtools action names, are forwarded. The commit always passes `replace = true`, with the whole computed state. +3. `api.setState` is replaced by `gset`, so `store.setState` also goes through the pipeline. +4. Registration is `runtime.adapter(name, { get: () => api.getState() ?? initial, set: v => outer(v, true), subscribe }, opts)`. Zustand assigns its state after the creator returns, hence the `initial` fallback. The action functions in the state become fields of kind `function`. + +**Common to all adapters:** +- Neither the Redux enhancer nor the Zustand middleware ever calls (or exposes) `AdapterHandle.dispose()`, so their stores stay registered for the runtime's lifetime. Creating a second store with the same name (HMR, tests, two stores both named `"app"`) replaces the first hub record through `StoreHub.register`. The first store's GenClass subscription is dropped, and its handle keeps proposing to the orphaned record. +- Packaging: `adapters/react.ts` imports `GenClass` from `../index.js`. `tsup.config.ts` builds every entry with `splitting: true`, so the singleton lives in a shared chunk: in the build output, `dist/adapters/react.js` imports `GenClass` from `../chunk-*.js`. Turning splitting off would give the React subpath its own `GenClass` copy, and `GenClass.init()` from the main entry would then be invisible to the hooks. That consequence is inferred from the build config, not tested. +- `demos/` can run against development stand-ins in `demos/src/dev/runtime-shim/` (observe-only; the Redux and Zustand shims are identity wrappers), aliased by `demos/vite.config.ts` when `GENCLASS_SHIM=1`, or when `packages/runtime/dist/index.js` is missing and `GENCLASS_SHIM` is not `0`. Behaviour seen there is not the adapters' behaviour; see [../demos.md](../demos.md). + +## Configuration and constants + +| name | type | default / value | defined in | effect | +|---|---|---|---|---| +| `StoreOptions.hold` | boolean | `true` | `packages/runtime/src/types.ts` (read in `StoreHub.propose`) | `false`: writes are traced, never held | +| `StoreOptions.resync` | function | none | `types.ts` | enables `resync` for the store | +| `StoreOptions.describe` | `(v) => string` | none | `types.ts` (used in `situation/build.ts` -> `stateLines`) | one-line store description in state lines | +| `policy.holdUserWrites` | boolean | `false` | `packages/runtime/src/decide/policy.ts` -> `policyConfig`; copied once to `StoreHub.holdUserWrites` in the `RuntimeImpl` constructor | `true`: user-sync writes go through the gate too | +| `policy.holdBudgetMs` | number \| `"auto"` | `"auto"`: clamp(1.5 × median recent model latency, or warm-up time, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 when nothing is known | `decide/policy.ts` -> `holdBudget` | how long a held write waits before fail-open | +| `InitOptions.settleMs` (also on `CreateOptions`) | number | `60` | `types.ts`; default in the `runtime.ts` constructor (`o.settleMs ?? 60`) | quiet time before a settled point | +| `LATE_REVERT_MS` | const | `2000` | `runtime.ts` | late-revert window; extends the decision deadline for held writes | +| `LONG_RUNNING_MS` | const | `10_000` | `runtime.ts` | ops older than this do not block settled points; maximum wait for `defer` | +| snapshots kept | literal | `8` | `runtime.ts` -> `settled` | consistent snapshots retained | +| `storeWriters` cap | literal | 1,000 signatures | `runtime.ts` -> `onApplied` | FIFO eviction | +| ancestors per write | literal | `8` | `runtime.ts` -> `onApplied` | depth for `storeWriters` and transition accumulators | +| max defers | literal | `2` | `hub.ts` -> `drain`; `situation/build.ts` -> `builtinApplicable` | third `defer` verdict applies | +| mutation trigger priority | literal | `2` (inconsistency `1`) | `runtime.ts` | decider queue priority | +| `HIST` / `LOG` | const | `16` / `512` | `hub.ts` | rich history / compact log per field | +| `RECENT_MS` / `RECENT_MAX` | const | `10_000` ms / `256` | `hub.ts` | recent changes (repetition facts, late-revert chain check) | +| `mutations` map trim | literal | > 512 -> 256 | `hub.ts` -> `propose` | bookkeeping only | +| `MAX_DEPTH` | export const | `4` | `fields.ts` | key levels expanded below the store | +| `MAX_FIELDS_PER_STORE` | export const | `200` | `fields.ts` | an object is not expanded when `leaves so far + its keys` would exceed this (soft cap per object, not a hard store limit) | +| `STRINGIFY_CAP` | const | `65_536` chars | `util.ts` -> `stableStringify` | `hashValue` input cap (element and non-plain-object hashes) | +| `MAX_KEYS_EXPAND` | export const | `32` | `fields.ts` | larger plain objects are one collection field | +| `SAMPLES` | const | `8` | `fields.ts` | positions re-hashed to detect in-place element mutation | +| `ID_KEYS` | const | `id, _id, key, uuid, slug, name, title, label` | `fields.ts` | id key shown in element summaries | +| `cloneValue` | fn | `structuredClone`, else a manual clone (depth ≤ 32; arrays, Date, Map, Set, plain objects; other objects by reference) | `fields.ts` | snapshots, rollback values, detached previews, defer re-runs | +| `LEARN_AFTER` | export const | `3` | `invariants.ts` | supporting settled points to learn | +| `LEARN_AFTER_NONNULL` | export const | `6` | `invariants.ts` | same, for `a != null` | +| `MAX_NUMERIC` / `MAX_SCALAR` / `MAX_ARRAYS` | const | `64` / `96` / `24` | `invariants.ts` | fields considered per settled point | +| `MAX_COLUMNS` | const | `8` (from the first 32 keys) | `invariants.ts` | numeric/scalar columns per array | +| `MAX_CANDIDATES` | const | `4000` | `invariants.ts` | no new candidates beyond this | +| `MAX_DROPPED` | const | `50_000` | `invariants.ts` | the dropped set is **cleared** when full, so dropped ids can be proposed again | +| `numEq` tolerance | fn | relative 1e-6, or < 0.0051 and equal in cents | `invariants.ts` | numeric equality in invariants | +| `GENCLASS_REPLACE` | export const | `"@@genclass/REPLACE"` | `adapters/redux.ts` | action used for GenClass's whole-state writes | +| React hooks `limit` | param | `50` | `adapters/react.ts` | `useGenClassDecisions` / `useGenClassInterventions` | + +## Invariants and gotchas + +**Pipeline semantics (break these and tests in `atoms.test.ts` / `review-hub.test.ts` fail):** +- **Proposal order per store.** `drain` only pops from the head. A write the gate cleared synchronously still waits behind an earlier held write to the same store. +- **Bypass writes skip the queue.** This is an open product risk (`demos/NEEDS.md` §1). A user-sync write applies at once even when an earlier async write to the same store is held. When the held write is released, its functional updater re-runs on top of the user's change and can overwrite it, which differs from the order the app would see without GenClass. `atoms.test.ts` "functional updates re-run against the value at apply time" asserts the current behaviour. Fixing it changes that test. +- **A held write must not change live state before the decision.** Only *functional* updaters are protected (detach and restore). A *value* write of an object the app already mutated in place (`v = a.get(); v.items.push(x); a.set(v)`) changes live state before the hold, and a `discard` cannot undo that. GenClass's leaves then disagree with live state until the next write. This was found by code reading; no test covers it. +- **Updaters may run more than once:** at proposal (preview), again at apply when the state moved, and on a clone for each defer. The same holds for Redux reducers and Zustand partial functions. They must be pure. +- **Fallback to the stale preview.** If a re-run updater throws at apply time (not the synchronous path), or a patch is impossible, the hub applies `m.preview`, the value computed against the old state. That can overwrite newer fields. +- **Error routing.** On the synchronous path (`commit(…, rethrow = true)`), updater and setter errors propagate to the caller. Subscriber errors are always reported, never thrown. On the later path, `appError` -> `RuntimeImpl.reportError` (source `applying a write to X`, `re-running an update of X`, `the setter of X` or `a subscriber of X`) **raises an `error` trigger**. The queue continues, so a throwing setter never strands later writes (`review-hub.test.ts` "a commit that throws"). +- **Reads while held:** `atom.get()`, `store.getState()` and Zustand `get()` return the pre-write state until the write applies. Redux `dispatch` returns the action immediately. +- **Discard means no notification:** app subscribers and React never see a discarded value (`atoms.test.ts`, the adapter tests). +- **`gating` is the only global switch.** `pause()` and `destroy()` set it to false, and every write then applies immediately but is still recorded. After `destroy()`, atom/guard `set` and `AdapterHandle.propose` skip `propose` entirely: they call `hub.write(…, writer = null, m = null)`, so no `mutationProposed` hook fires and no cause is recorded. `destroy()` also unsubscribes every `io.subscribe`, so external changes are no longer recorded, and `scheduleSettle` becomes a no-op. +- **An updater that throws at proposal time always throws from `set()` / `dispatch` / `propose`.** `previewOf` runs `w.fn(base)` outside any try/catch, before the write is queued or recorded, so this happens whatever path the write would have taken. +- **A library subscriber that throws inside `commit` looks like a failed setter.** Redux and Zustand update their state and then call listeners inside the same `dispatch`/`setState`. If a listener throws, `StoreHub.write` catches it as `the setter of X`: it rethrows on the synchronous path, or reports it with `outcome = "failed"` later. In both cases `record` is skipped and the hub's own listener was suppressed (`committing`), so the library holds the new state while GenClass's leaves, versions and `state` events miss it until the next recorded change. Found by code reading; no test covers it. + +**Store names and paths:** +- **Store names must not contain `.`. Nothing enforces this.** Every lookup by path splits on `.` and takes segment 0 as the store name: `field`, `versionAt`, `logSince`, `writesSince`, `valueAt`, `leaf`, `restoreFields`, `snapshot` (top-level key = segment 1), `restoreInPlace` and `patchValue` (`segs = path.split(".").slice(1)`). For a store named `search.results`: + - its fields never appear in state lines (only a `describe` one-liner can); + - versions facts always say the field "has not changed", which defeats stale-write detection; + - chain revert skips it, and inconsistency `rollback`/`resync` are never offered for it (`builtinApplicable` derives the store name `search`, which does not exist); + - the in-place-updater protection cannot restore it, so such updates are marked unholdable and apply at once; + - a patched held value write on an object-valued store writes under the wrong key (`value.results.x` instead of `value.x`); + - `snapshot()` takes segment 1 (`results`) as the changed top-level key, so for an object-valued store it reuses stale clones of changed keys. + The README and the `react.ts` header use `useGenClassState("search.results", [])`. That is an array value, so the patch corruption does not happen there, but the lookups still fail. This was found by code reading; no test covers it. +- **Names are global per runtime across kinds.** `register` replaces any store with the same name. For example, `rt.atom("cart")` after `rt.guard("cart", …)` re-registers it as an atom, resetting versions and history, and old handles keep writing to the orphaned record. `rt.atom(name)` with an existing atom name returns the existing store and ignores `initial`. +- **Path ids for invariants:** `dynamicPath` skips any path with an `isIdSegment` segment (numbers, uuids, long hex, long tokens, short slug ids such as `x7k2p`). `m21` is **not** an id segment there (3 chars), but `normalizeFieldPath` (transition profiles) does treat any key with a digit as `:id`. + +**Change detection limits:** +- **In-place element mutation is only sampled.** An array or collection whose elements keep their references is re-hashed at 8 sampled positions only. Mutating element 1,234 of 5,000 in place, without replacing the element object, is not detected. Immutable updates are always detected (`review-hub.test.ts` "large arrays"). +- **A collection mutated in place is checked even less.** Arrays always compare every element reference, but a plain-object collection (more than 32 keys, e.g. `byId`) that is the same object as last time takes `objectLeaf`'s fastest path. Only the 8 sampled keys and the key count and last key are checked. So replacing the value of an existing, non-sampled key in place, as in `s.set(v => { v.byId.k17 = newItem; return v; })` with the same `byId` object, can go unrecorded: no version bump, no `state` event, and no protection for a held write. Found by code reading; no test covers it. +- History values are shallow. Array and collection leaves hold shallow copies, so element objects are shared with live state. Patches and reverts restore those references, which assumes immutable updates. +- Reordering the keys of a collection (more than 32 keys) changes its hash and is recorded as a change with delta `c:`. +- A guard or adapter store without `subscribe` records nothing when it changes outside GenClass. The next GenClass-mediated write then diffs against stale leaves and is credited with those external changes. + +**Snapshots and consistency:** +- **A snapshot is "consistent" when nothing *newly* broke, not when everything holds.** A violation that lingers from the previous settled point does not block snapshots (`review-precision.test.ts` "design risk"). An ignored inconsistency therefore becomes part of later "consistent" snapshots. CONTRACT §4 says "all learned invariants held". +- **Inconsistency rollback restores whole stores.** Every field of each involved store goes back to the snapshot, including unrelated user input written since. Chain revert (error/transition) is field-precise. +- **Possible stale snapshot for a store whose top-level value is a plain object with more than 32 keys.** That store is a single leaf at path `<store>`, so `snapshot()` derives `changedKeys = {""}` and reuses the previous clone for every existing top-level key even when its value changed. Found by code reading; no test covers it. +- `settled()` does not run while any write is pending or any op younger than 10 s is in flight. Apps with constant traffic (polling every few seconds, long-poll requests under 10 s) may rarely reach settled points, so invariants learn slowly. +- Developer `expect()` violations have `fields: []`, so they contribute no store: when they are the only violations in the trigger, neither `rollback` nor `resync` is offered and only `ignore` remains. +- **Clones are not always faithful.** `cloneValue` (snapshots, rollback values, detached previews, defer re-runs) tries `structuredClone` first. That turns class instances into plain objects (their prototype is lost), so a `rollback` writes plain objects back into a store that held class instances. Values containing functions, such as Zustand state with actions, make `structuredClone` throw, and the manual fallback then keeps functions and class instances by reference and stops copying below depth 32. Found by code reading. + +**Performance (budgets asserted in `test/review-perf.test.ts`; numbers measured on the shared VM, from `packages/runtime/STATUS.md`):** + +| scenario | budget (test) | measured | +|---|---|---| +| user-sync write (keystroke) on an atom holding a 5,000-item array | < 1 ms/write | 0.14 ms | +| async gated write (facts computed) on the same store | < 2 ms/write | 0.19 ms | +| redux-style `adapter.propose` on 5,000 normalized entities (user / async) | < 1 ms / < 2 ms | 0.68 ms / 0.58 ms | +| settled point, 5,000-item atom changed / plus an unchanged 5,000-item adapter store | < 16 ms each | 0.2 ms / +1.4 ms | + +Fixtures: `shop(5000)` is `{ items: 5,000 × { id, sku, name, price, qty, stock, rating, weight }, filter, page, pageSize, total, selected, cartCount, cartTotal, maxPrice, minPrice, version }`, and each write replaces `filter` immutably. `entities(5000)` is `{ entities: { byId: 5,000 entries }, ui: { query } }`, so `byId` is a single collection field. The settled-point case first runs 6 learning writes, then times 10 iterations of `set` + `rt.settled()`. All cases use `setup()` from `test/helpers.ts` with `FakeClock`; the measured values are logged with a `[review]` prefix. + +These numbers depend on reference-equality fast paths (`arrayLeaf`/`objectLeaf` returning the previous `Leaf`), the `WeakMap` statistics cache in the miner, and snapshot reuse (`snapCache` by version and reference). If you add per-write work that is O(n) in a store's size, such as hashing, cloning or `JSON.stringify`, these budgets break. + +**Determinism and parity:** +- Only the injected `Clock` is used (`this.clock.now()`), ids come from counters (`mid`, `seq`), and hashes are FNV-1a. There is no `Math.random`, `Date.now` or global `setTimeout` (CONTRACT §0 rule 3). +- The sim drives the real runtime through `rt.atom` (`sim/src/run/runner.ts`). Field paths, versions, deltas and `changeText` output appear verbatim in situation text. Any change to `fields.ts` or the version bookkeeping changes training data. Coordinate with the lead: a new freeze tag, and a data/sim regeneration. See [../model-io-contract.md](../model-io-contract.md) and [../sim.md](../sim.md). + +**Adapters:** +- Zustand and Redux capture `runtime` when the store is created. `genclass(GenClass.runtime, …)` evaluated before `GenClass.init()` gets `null`, and that store is never guarded. React hooks resolve the runtime at render time. +- `useAtom(guardAtom)` requires `io.get()` to return a stable reference between changes, as `useSyncExternalStore` does. +- The Zustand commit always calls the outer `set` with `replace = true`, so outer middleware (devtools) sees replace writes. +- A Redux reducer that throws during the preview throws from `dispatch` before anything is proposed. +- `useGenClassState(name)` with a `name` already used by a Redux/Zustand/guard store silently re-registers that name as an atom (`rt.atom` -> `register` replaces). The library store then loses its GenClass subscription. Use distinct names per runtime. + +## How to change it safely + +The team runs builds and tests on the VM, not on the Mac (CONTRACT §0 rule 5). Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the build and these unit tests locally ([build-test-release.md](build-test-release.md#where-to-run-things)). From `packages/runtime`, the relevant suite is `vitest run test/atoms.test.ts test/review-hub.test.ts test/invariants.test.ts test/adapter-seam.test.ts test/adapters-react.test.ts test/adapters-redux.test.ts test/adapters-zustand.test.ts test/review-perf.test.ts test/review-precision.test.ts test/situation.test.ts test/batch3.test.ts`, then the full `vitest run --exclude "test/browser/**"`. Do not edit `test/review-*.test.ts` to make it pass: `packages/runtime/STATUS.md` records that every review test passes unmodified, so treat them as required behaviour. + +1. **Integrate another state library (MobX, Jotai, Valtio, …):** + 1. Add `src/adapters/<lib>.ts`. Call `runtime.adapter(name, { get, set?, subscribe? }, opts)` once per store. + 2. Route every app write through `handle.propose({ fn | value, commit })`. `commit(next)` must perform the write on the library store synchronously; it is called later for held writes and never for discarded ones. + 3. Provide `set` if GenClass may write whole states (rollback, revert); without it the store is not writable. + 4. Add tsup entries in `tsup.config.ts` (`entry` and `dts.entry`), the `exports` subpath and an optional peer dependency in `packages/runtime/package.json`, and add the library to `external`. + 5. Write tests modelled on `test/adapters-zustand.test.ts`: `MockRuntime` (`holdWrites`, `flushHeld`, `dropHeld`, `genclassWrite`) plus one test against the real runtime with `ManualDecider`. +2. **Add an invariant template:** + 1. Extend `Tpl`. + 2. Implement it in `holds` (return null when not applicable), `nonTrivial`, `valuesText` and `propose`, with a deterministic `id` and readable `text`. The text is model-visible. + 3. Compute per-array work at most once per array version: put it in `ArrayStats` (cached per `Leaf` in `statsCache`), as `sums`, `prods`, `sets` and `unique` do. + 4. Add a learning test and a precision test (no false inconsistency on benign behaviour) to `test/invariants.test.ts` / `test/review-precision.test.ts`. + 5. This changes situations, so it needs a new freeze tag and regenerated data. +3. **Change flattening caps or hashing** (`MAX_DEPTH`, `MAX_KEYS_EXPAND`, `MAX_FIELDS_PER_STORE`, `SAMPLES`, `primHash`): re-run `review-perf` and the "large arrays" test, and check the state lines in `test/batch3.test.ts` / `test/situation.test.ts`. This is parity-affecting. +4. **Change patch semantics** (`patchValue`): keep "removals first; never remove a path with a set beneath it". Run `review-hub.test.ts` (fill an empty object while held / queued / late-reverted / undone) and `atoms.test.ts` "held value writes are re-applied as patches". +5. **Fix the user-write ordering risk** (`demos/NEEDS.md` §1): in `StoreHub.propose`, when a bypass write targets a store whose `queue` is non-empty, either apply the pending writes first in proposal order, or mark the overlapping held writes superseded and re-gate them. Add the regression test that demos suggests: hold a functional write to `s.x`, make a user-sync write to `s.x`, release with `apply`, and expect the user's value. Then update `atoms.test.ts` "functional updates re-run…", which asserts the old order. +6. **Reject or support dotted store names:** either validate in `RuntimeImpl.atom`/`guard`/`adapter` (throwing would break apps, so prefer a console warning plus a sanitised name), or stop deriving the store from `path.split(".")[0]`. That would mean passing the store explicitly to `field`, `leaf`, `valueAt` and so on, and using `path.slice(store.length + 1)` in `patchValue`/`restoreInPlace`/`snapshot`. Fix the README and `react.ts` header examples as well. +7. **Change bypass, hold or late-revert rules** (`propose` `bypass`, `LATE_REVERT_MS`, `StoreHub.revertable`): these are policy-visible. Update `docs/runtime/API.md` "State", run `atoms.test.ts`, `policy.test.ts`, `review-hub.test.ts` and `batch3.test.ts` ("a provider that never answers…"), and coordinate with [decide-policy-actions.md](decide-policy-actions.md). +8. **Change what a settled point does** (`RuntimeImpl.settled`, snapshot policy): run `invariants.test.ts`, `review-precision.test.ts`, `learn.test.ts` (transition rollback) and `review-actions.test.ts`. +9. **Change an existing adapter** (`adapters/react.ts`, `redux.ts`, `zustand.ts`). Keep these contracts, which the adapter tests assert: + - `commit` runs exactly once when a write applies and never for a discarded write. + - Redux: the reducer runs once per applied dispatch (the `ready` handoff), and inner enhancers see the original action. Zustand: the commit is a whole-state `replace = true` write that forwards the extra `set()` arguments. + - React: one atom per (runtime, name), and the hooks fall back to plain `useState` without a runtime. + - Run the adapter test files plus `adapter-seam.test.ts` and `review-perf.test.ts`. + - Update API.md "Adapters and devtools" and the header comment of the adapter file. + - The demos exercise each adapter: `demos/src/demos/editor/main.ts` (Redux), `demos/src/demos/board/store.ts` (Zustand), `demos/src/demos/checkout/app.tsx` (React). Check them on the VM; see [../demos.md](../demos.md). + +## Tests + +All paths are under `packages/runtime/test/`. Helpers: `helpers.ts` (`setup`, `ManualDecider`, `ScriptedDecider`, `defaultScript`, `FakeClock`, `FakeServer`) and `browser/ui/mock-runtime.ts` (`MockRuntime`, a scripted stand-in used by the adapter unit tests). + +| test file | what it asserts (store scope) | +|---|---| +| `atoms.test.ts` | user-sync writes never held; async writes held then applied; fail-open after `holdBudgetMs` plus late revert and its undo; no late revert when superseded, older than 2 s, or the same chain wrote again (subscriber-derived write); late defer/apply only recorded; provider errors fail open at once; proposal order per store; functional re-run on the current value; value writes patched over newer user input; discard drops without notification and undo applies; defer at most twice; `hold: false`; `guard()` writes through `io.set` and records external changes; `atom()` with an existing name; field versions, writers and history deltas | +| `review-hub.test.ts` | patching fills of empty objects while held/queued; undo of a late revert; in-place push summaries ("2 → 3 items"); a held in-place updater is invisible before apply and really dropped on discard; versions counted past the 16-entry history (512 log); a 2,000-item array change recorded once; a throwing setter does not strand later writes or settled points | +| `invariants.test.ts` | learns `count == len(items)`, `total == sum(price*qty)`, `count == badge`, `items[*].id unique` after 3 settled changes; violation values text; nothing learned from unchanged fields; id-like keys skipped; inconsistency raised once per episode, rollback to the snapshot and its undo; transient between-write states ignored; `expect()` checked from the start | +| `adapter-seam.test.ts` | `runtime.adapter`: reducer preview, async writes held, commit through the library; discarded writes never committed; direct library changes recorded and never held; rollback offered only when `set` exists | +| `adapters-react.test.ts` (happy-dom) | one shared atom per name; held writes visible only on apply, never on drop; StrictMode (one atom, balanced subscriptions); plain `useState` fallback without a runtime; `useAtom`; `useGenClass` throws without a runtime; live decision/intervention/status feeds with stable snapshots; real runtime: hold, discard, undo; user-handler writes never held | +| `adapters-redux.test.ts` | pass-through when nothing is held (reducer runs once); held dispatch applied once (reducer not re-run, subscribers notified once); re-run on moved state; discard reaches no reducer or subscriber; middleware sees each action once and thunks pass; no-op dispatch; `replaceReducer`; inner enhancers see the real action, GenClass writes as REPLACE; no runtime = unchanged store; real runtime hold/discard/undo | +| `adapters-zustand.test.ts` | merge semantics and `setState` through the pipeline; held writes merged over newer state; drops; replace, functional, no-op, extra `set()` args (`[value, true, "counter/set"]`); GenClass whole-state writes; no runtime = unchanged; real runtime hold/discard | +| `review-perf.test.ts` | the 5,000-item budgets in the performance table | +| `review-precision.test.ts` | closing a selection (null) is not an inconsistency (`!= null` needs 6); lingering violations do not freeze snapshots; transition-profile precision | +| `situation.test.ts` | mutation and inconsistency situations end to end (fact wording, `["ignore","rollback"]` offered) | +| `batch3.test.ts` | state lines never print `parent = undefined`; item-change summaries; "changed twice … and is back to 6"; pending-local-change fact; a provider that never answers does not block later decisions (held write plus a write queued behind it both apply; the runtime abandons the first request after budget + 2 s) | +| `review-actions.test.ts` | error-trigger rollback offered only when the failing chain wrote state; never reverts other chains' writes | +| `learn.test.ts` | transition trigger at a settled point; chain-revert rollback text "Restored list.items to their values before …" | +| `policy.test.ts` | observe mode never holds; `pause()`/`resume()` gating; loading model fails open with no decision | +| `smoke.test.ts` | atoms apply synchronously when nothing is salient; causality user -> fetch -> json -> set; stale write discarded in guard mode | +| `review-redaction.test.ts` | the custom `redact` applies to learned-invariant facts | +| `review-timers.test.ts` | a state write after a 200,000-tick timer loop does not throw | +| `context.test.ts` | writer attribution of state writes: after fetch -> json -> `set`, the `state` event's `op` is the fetch op, whose cause and root are the user action; two concurrent click -> fetch -> `set` chains writing two atoms keep their own writers and roots | +| `dom.test.ts` | writes made by the app's click handler are user writes and are never held | +| `devtools-runtime.test.ts` | the devtools Interventions tab's undo button applies a write GenClass dropped (`search.results` goes from 4 to 8 items) | + +## Drift and open issues + +Doc-versus-code mismatches (the code is right): + +| what | doc says | code says | evidence | +|---|---|---|---| +| Who records snapshots and when | CONTRACT §4: "the hub records a snapshot of all stores" at settled points; `lastConsistent` is "the last snapshot at which all learned invariants held" | `RuntimeImpl.settled` (not the hub) records a snapshot whenever no violation is *newly* broken; lingering violations do not block it; at most 8 are kept | `runtime.ts` -> `settled`; `review-precision.test.ts` "design risk" | +| Settled-point condition | CONTRACT §4 "no in-flight ops"; API.md "no requests in flight" | no op of any kind started less than 10 s ago in flight, **and** no pending (held or queued) write | `runtime.ts` -> `busy` | +| `a != null` support | CONTRACT §4: every candidate is learned after ≥ 3 settled snapshots | `nonnull` needs `LEARN_AFTER_NONNULL` = 6, and is never proposed for a field ever seen null | `invariants.ts` | +| Who raises `inconsistency` | CONTRACT §4: "the hub raises" it | `RuntimeImpl.settled` -> `raiseInconsistency` | `runtime.ts` | +| Field model | CONTRACT §4: arrays are one field; per-field `{ v, writer, t }` | arrays **and** plain objects with more than 32 keys are one field; at most 4 key levels and a soft cap of 200 fields per store; `FieldState` also has `seq`, a 16-entry `hist` and a 512-entry `log` | `fields.ts` -> `flatten`; `hub.ts` | +| `Mutation` shape | CONTRACT §4 `{ id, store, changes, cause, root, t }` | `MutationRec` has many more fields (see the table above) | `hub.ts` | +| `rollback` effect | CONTRACT §7: "write snapshot back" for every trigger | snapshot rollback only for `inconsistency`; `error`/`transition` use a field-precise chain revert | `runtime.ts` -> `revertChain`; API.md and STATUS.md agree with the code | +| `Runtime.adapter` | CONTRACT §2's `Runtime` interface lists only `atom`, `guard`, `expect` | `adapter()` is public (`types.ts` `Runtime.adapter`); API.md documents it | `types.ts` | +| `holdBudgetMs` default | CONTRACT §8: 300 | `"auto"` (150 to 800 ms; 300 only when nothing is known) | `decide/policy.ts` -> `holdBudget` | +| "could not be held" fact | STATUS.md: when an in-place update cannot be detached, "the write applies at once with a fact" | such a write is committed in `propose` without being gated, so `mutationFacts`' `m.unholdable` fact is never produced | `hub.ts` -> `propose`; `situation/facts.ts` | +| Example store names | README "State it can protect" and `react.ts` header: `useGenClassState("search.results", [])`; `test/smoke/smoke.sh`: `rt.atom("search.results", [])` | dotted names break path-to-store lookups (see Gotchas) | `hub.ts` -> `field`/`leaf`; `situation/build.ts` -> `stateLines` | +| UI-NEEDS item 2 | `packages/runtime/UI-NEEDS.md` asks for `react-dom` / `@types/react-dom` as devDependencies | both are already in `packages/runtime/package.json` devDependencies (stale request) | `package.json` | +| Adapter signatures | API.md "Adapters and devtools": `genclassEnhancer(runtime, { name })`, `genclass(runtime, name)(stateCreator)` | both also take `StoreOptions` (`resync`, `hold`, `describe`): Redux through `GenclassEnhancerOptions<S> extends StoreOptions<S>`, Zustand through a third `opts` parameter. This is an omission, not a contradiction | `adapters/redux.ts`, `adapters/zustand.ts` | +| `mutationProposed` coverage | `types.ts` `RuntimeHooks.mutationProposed`: "Called synchronously inside atom.set / guarded set / adapter writes, before gating" | not called for writes after `destroy()` (they go straight to `hub.write`) or for a deferred write's re-proposal | `runtime.ts` -> `handle`, `adapter`; `hub.ts` -> `defer` | +| `MAX_FIELDS_PER_STORE` | the constant's name reads as a hard per-store limit | a per-object pre-check; a store can exceed 200 fields | `fields.ts` -> `flatten` | +| Code comments in scope | `fields.ts` `FieldChange.delta` comment gives the example `"n:+1"`; `hub.ts` `RecentChange.key` comment says "Hash of paths + deltas"; `situation/env.ts` `SitEnv.lastConsistent` says "Last snapshot at which all learned invariants held" | `deltaOf` emits `n:1` (no `+` sign; `Number(d.toPrecision(12))`); `key` is the plain string `paths\|path=delta;…`, not a hash; `lastConsistent` is the newest snapshot at which nothing *newly* broke | `fields.ts` -> `deltaOf`; `hub.ts` -> `record`; `runtime.ts` -> `settled`, `makeEnv` | + +Open issues relevant to this scope: +- **User writes overtaken by held writes** (`demos/NEEDS.md` §1, CORE, product risk): +56% visible jump-backs on the board demo in guard mode with zero actions executed. The proposed fix is in recipe 5. Still open at 654d822; the code is unchanged since `situation-v1`. +- **Hold latency** (`demos/NEEDS.md` §2): typeahead result writes are salient on clean runs (127 of 148 held, median 543 ms). Suggestions there: do not hold when recent decision latency exceeds the budget; drop superseded queued decisions. This belongs to the policy and decider side; see [decide-policy-actions.md](decide-policy-actions.md). +- **App-level snapshots miss held writes** (`demos/NEEDS.md` §1): the board demo's own whole-board rollback on a failed move (`demos/src/demos/board/main.ts`, `set({ cards: before })`) captures `before` while GenClass is holding writes, so restoring it erases more (cards stuck "syncing": 6 Off, 9 Guard, 10 Heal). This is the app's rollback, not GenClass's `rollback` action (Guard executed 0 actions in those runs), but it is another consequence of holding. +- Unverified-by-test findings above: the unreachable `too late to revert` branch, dotted store names, the stale snapshot of a top-level store with more than 32 keys, value writes of mutated-in-place objects, in-place value replacement in a large collection, library listeners throwing during commit, `structuredClone` prototype loss, and the unused `StoreHub.mutations` map. +- Dead or unused code paths: + - `RuntimeImpl.rollback(stores, violationIds, beforeSeq?)`: no caller passes `beforeSeq`, so inconsistency rollback always uses the newest snapshot. `snapshotBefore` is used only for `SitEnv.consistentBefore` (facts). + - `StoreHub.revertable`'s `the write changed nothing` is unreachable: `appliedSeq` is set only when a write changed something, and the earlier `the write was not applied` check already catches the other case. + - The mutation controller's `too late to revert` branch is effectively unreachable: the decision deadline (`t0 + budget + LATE_REVERT_MS`) passes before any held write can be more than 2 s past its apply (see flow 7). + - `RuntimeImpl.onApplied` takes `m` but ignores it (`void m`). +- `OPEN_TASKS.md` lists the runtime as frozen at `situation-v1`. Changes here affect the final data and training plan, so check with the lead first. + +## Related docs + +- [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, options, pause/destroy. +- [observe-and-trace.md](observe-and-trace.md): ops, the ambient op, `Context.isUserSync`, causality. +- [learn-situation-triage.md](learn-situation-triage.md): mutation and inconsistency facts, triage, state lines, transition profiles. +- [decide-policy-actions.md](decide-policy-actions.md): the trigger/decision flow, policy gate, hold budget, actions, undo, reports. +- [devtools.md](devtools.md): the overlay (it uses the public API and the React feeds' sources). +- [build-test-release.md](build-test-release.md): the VM, vitest and the npm subpath exports. +- [../overview.md](../overview.md#4-walkthrough-a-typeahead-stale-write): a held mutation end to end +- [../glossary.md](../glossary.md) +- [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../demos.md](../demos.md), [../status-and-known-issues.md](../status-and-known-issues.md). +- Existing specs: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) (§4 State, §7 actions), [../../runtime/API.md](../../runtime/API.md) ("State", "Adapters and devtools"), [../../runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md); [../../../packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md); [../../../demos/NEEDS.md](../../../demos/NEEDS.md). diff --git a/docs/agents/sim.md b/docs/agents/sim.md new file mode 100644 index 00000000..565b31ee --- /dev/null +++ b/docs/agents/sim.md @@ -0,0 +1,823 @@ +# sim/: the training-data simulator (@genclass/sim) + +> **Scope:** `sim/README.md`, `sim/NEEDS.md`, `sim/package.json`, `sim/tsconfig.json`, `sim/tsup.config.ts`, +> `sim/vitest.config.ts`, `sim/src/**`, `sim/test/**`, `sim/scripts/**`, `sim/samples/**`. +> **Read this when:** you generate or regenerate training data; change a feature combinator, domain, chaos model, +> cost weight, label rule, ask question, split or budget; debug a dropped trajectory, a `prefix-mismatch`, a wrong +> diagnosis label or an odd action distribution; or need to know exactly what a CONTRACT-D row contains. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- The sim is a private Node package (`@genclass/sim`, ESM, Node 22) that builds **random web-app programs** from + 15 feature combinators x 55 domains, runs them with **simulated users** on a **simulated network and server** + inside a **deterministic virtual event loop**, and drives the **real runtime** (`createRuntime` from + `@genclass/runtime`, loaded dynamically) through it. Nothing in the runtime knows about the sim. +- Every time the runtime calls its `DecisionProvider.evaluate`, the sim's recording decider stores the request + verbatim (`state`, `questions`); those bytes become a training row's model input. The sim never writes situation + text itself. +- Labels come from **counterfactual outcomes**: for a sampled decision point *k*, the scenario is re-run once per + applicable action with that action forced at *k* (and passive afterwards), over up to **K = 3 paired futures**; + each run is scored by `runCost` against the **ideal run** (same intents, zero latency, no failures, no accidental + clicks, exactly-once). `actionLabel` turns costs into a soft `action` distribution (precision first: tier + premiums, ties pinned to passive). +- The `diagnosis` label is a hard label from the sim's own knowledge (`Knowledge`: intents, app ops, writes, error + tags) via `diagnose`, not from the runtime's text. Rows also include diagnosis-only rows and `ask` rows with exact + programmatic answers. +- Determinism rests on **keyed RNG forks** (`Rng.fork(label)` never depends on draw order), request draws keyed by + (seed, request identity, occurrence), **content-derived server ids**, and a replay check that every decision up + to *k* is byte-identical (`fp`) to the base run. +- Splits are per scenario: `test` = 10 held-out domains, or a held-out family hash (17%), or a held-out pattern; + `dev` = 3% of remaining families; only 33% of test trajectories are kept (`--test-keep`). +- Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/` in phase B). Row shape: + `{id, split, family, state, questions, labels, meta}` (CONTRACT-D). +- **Where to run.** The original team ran sim builds, tests and generation only on the VM (`scripts/vm.sh run|exec + sim '...'`; CONTRACT §0 rule 5, the author's Mac has 8 GB). Under the 2026-10-07 run policy in AGENTS.md, the runtime's + install, typecheck, build and unit tests run locally, but ask the user before running the sim's vitest suites, + `gen.js` or `sim/scripts/*` ([where to run things](runtime/build-test-release.md#where-to-run-things)). + Committed samples in `sim/samples/`; the frozen-runtime phase A (600,676 rows) stats are in + `sim/samples/stats-final-a.json`. +- Any change to the runtime's situation text (`packages/runtime/src/situation/*`) invalidates all data: rebuild the + runtime, regenerate everything. Any change to sim scenario generation changes every seed's world. +- Vitest suites default to a crude **fake runtime** (`createFakeRuntime`); set `SIM_RUNTIME=real` to test against the + real one (2 oracle tests run only then). `gen.js` uses the real runtime unless `--allow-fake`. + +## Files + +| path | role | key exports / entry points | +|---|---|---| +| `sim/package.json` | private package `@genclass/sim` v0.0.0, `bin: genclass-sim -> dist/gen.js` | scripts `build` (tsup), `typecheck`, `test` (vitest run), `gen`, `sample`, `build:runtime-core`; dep `@genclass/runtime: "*"` | +| `sim/tsup.config.ts` | ESM bundle, target node22, `@genclass/runtime` external | entries `gen`, `worker`, `index`, `smoke` -> `dist/{gen,worker,index,smoke}.js` | +| `sim/tsconfig.json` | extends `../tsconfig.base.json`, `noEmit`, includes `src`, `test` | - | +| `sim/vitest.config.ts` | node env, `pool: "forks"`, test/hook timeout 120000 ms | - | +| `sim/src/index.ts` | library re-exports | `buildScenario`, `splitOf`, `runScenario`, `generateTrajectory`, `actionLabel`, `runCost`, `COST_WEIGHTS` (= `W`), `LABEL_PARAMS` (= `LABEL`), `transformQuestions`, `ACTION_PARA`, `createFakeRuntime`, `VirtualLoop` | +| `sim/src/types.ts` | structural mirror of the runtime model seam + row types | `JevState`, `Question`, `NoulAnswer`/`ChoiceAnswer`/`ScoreAnswer`/`Answer`, `TriggerKind`, `ModelStatus`, `SubjectInfo`, `EvaluateRequest`, `DecisionProvider`, `Clock`, `PASSIVE`, `DIAGNOSES`, `Diagnosis`, `Row`, `Label` | +| `sim/src/rng.ts` | seeded PRNG (sfc32, splitmix32 init, 12 warm-up draws) with keyed forks | `hash32` (FNV-1a + murmur3 finalizer), `hashAll`, `Rng` (`fork`, `next`, `int`, `float`, `bool`, `pick`, `weighted`, `weightedKey`, `normal`, `lognormal`, `shuffle`, `sample`, `token`), `u01`/`keyedLognormal` (unused) | +| `sim/src/loop.ts` | virtual event loop | `VirtualLoop` (`schedule`, `at`, `cancel`, `afterTask`, `clockFor`, `settle`, `runUntil`, `pending`, `nextTime`, `stop`; fields `onSettled`, `onAppError`, `internalErrors`, `tasksRun`), `TaskOwner` (`app net runtime user sim`), `LoopError` | +| `sim/src/net/server.ts` | virtual server: DB + routed endpoints + idempotency keys | `Db`, `VirtualServer`, `API_STYLES`/`ApiStyle`, `canonical`, `clone`, `ServerSnapshot`, `ServerRequest`, `ServerResponse`, `Handler`, `RouteMeta`, `ServerLogEntry`, `Collection`, `Doc`, `Item`, `Json`, `IdStyle` | +| `sim/src/net/network.ts` | virtual network: latency, chaos, push channel, `fetch` | `Network`, `NetProfile`, `IDEAL_PROFILE`, `BASE_URL`, `NetEntry`, `NetCause`, `Win`, `Outage`/`OutageMode`, `SlowPeriod`, `ServerBug`/`BugKind`, `Lat`, `PushSub`, `SIM_OP_HEADER`, `simOpHeaderValue`, `parseSimOpHeader`, `makeResponse` | +| `sim/src/app/vocab.ts` | 55 domain vocabularies (2 entities each) | `DOMAINS`, `Domain`, `Entity`, `ROUTE_WORDS` (unused) | +| `sim/src/app/naming.ts` | per-program naming: route prefix/casing, store names, field synonyms | `Naming` (`field`, `word`, `store`, `route`, `owner`), `Casing`, `cased`, `camel`, `title`, `splitWords` | +| `sim/src/app/feature.ts` | feature contract, user model, personas, relations | `FeatureDef`, `FeatureCtx`, `FeatureClient`, `UserStep`, `StepIntent`, `UiKind`, `WorldCtx`, `ExternalEvent`, `Relation`, `rel`, `Persona`, `randomPersona`, `UserModel` (`think`, `key`, `type`, `click`), `itemName`, `numIn`, `round2` | +| `sim/src/app/env.ts` | what app programs see: global, stores, sockets, uncaught errors | `AppEnv` (`fetch`, `store`, `socket`, `subscribe`, `setRoute`, `uncaught`, `snapshot`, timers), `PlainBackend`, `SimGlobal`, `Store`, `StoreOpts`, `WriteMeta`, `StoreBackend`, `AtomLike`, `RegisteredStore` | +| `sim/src/app/kit.ts` | feature building blocks: tagged ops, requests, writes, error surfacing | `Kit` (`op`, `call`, `write`, `shownError`, `spawn`), `OpInit`, `CallOpts`, `CallResult`, `HttpError`, `errorFor`, `sleepJitter` (unused) | +| `sim/src/app/features/index.ts` | registry and frequency weights | `FEATURES`, `FEATURE_WEIGHTS` | +| `sim/src/app/features/common.ts` | shared helpers | `ContentBook`, `idsKey`, `seedItems`, `weightsOf`, `queryWords`, `errMsg`, `apiOf` | +| `sim/src/app/features/{search,editor,form,cart,toggle,counter,poll,board,chat,settings,nav,list,bulk,auth,benign}.ts` | the 15 combinators | one `FeatureDef` each (see [Feature combinators](#feature-combinators-and-the-bugs-they-create)) | +| `sim/src/world/scenario.ts` | seed -> scenario; splits; vocab randomisation; chaos profile | `buildScenario`, `BuildOptions` (`kinds`, `chaos`, `duration`, `domain`: tests only), `Scenario`, `FeatureInst` (`kind`, `id` = `f<i>`, `route`, `spec`, `pattern`), `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `familyHeldOut`, `DEFAULT_DIAGNOSES`, `Chaos` | +| `sim/src/run/rt.ts` | runtime slice the sim uses; `createRuntime` options; loader | `RuntimeLike`, `RuntimeOptions`, `RuntimeFactory`, `RuntimeHooksLike`, `SituationLike`, `AtomLike`, `createOptions`, `realRuntimeFactory` | +| `sim/src/run/runner.ts` | runs one scenario (ideal or real), recording decider, correlation, snapshots | `runScenario`, `RunOptions`, `RunResult`, `Snapshot`, `DecisionRec`, `AskRec`, `AskFacts`, `ExplorePolicy` | +| `sim/src/run/fake-runtime.ts` | **test double** of the runtime (crude text); rows marked `meta.runtime: "fake"` | `createFakeRuntime` (see [Fake runtime](#fake-runtime-test-double)) | +| `sim/src/run/transform.ts` | per-row action-option shuffle/drop; action paraphrases | `transformQuestions`, `Transformed` (`questions`, `dist`, `variant`), `ACTION_PARA` | +| `sim/src/oracle/knowledge.ts` | ground truth bookkeeping | `Knowledge`, `Intent`, `Mode`, `SimOp`, `SimWrite`, `ErrorTag`, `sigOf` | +| `sim/src/oracle/diagnose.ts` | diagnosis labels | `diagnose`, `diagnoseFailure`, `Subject`, `DiagCtx`, `fieldRefs`, `relationMatches` (unused) | +| `sim/src/oracle/cost.ts` | divergence, run cost, soft labels | `W`, `LABEL`, `TIER`, `runCost`, `CostBreakdown`, `actionLabel`, `ActionLabel`, `clientDist`, `serverDist`, `divergenceArea`, `relationViolation`, `valueDist` | +| `sim/src/ask/questions.ts` | programmatic `ask` questions with exact answers | `askQuestions`, `AskQ` (`qid`, `question`, `label`, `kind`); 11 generators in `GENS` (see [Ask questions](#ask-questions-simsrcaskquestionsts)) | +| `sim/src/gen/trajectory.ts` | one trajectory = ideal + base + counterfactuals -> rows | `generateTrajectory`, `pointCosts`, `GenOptions`, `PointStat`, `TrajectoryOut` | +| `sim/src/gen/worker.ts` | `worker_threads` worker: seeds -> rows -> shard/part files | (message protocol, see flow 1) | +| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample`, parts mode | `main`, `mergeParts` | +| `sim/src/gen/examples.ts` | `EXAMPLES.md` renderer | `renderExamples` | +| `sim/src/dev/smoke.ts` | dev tool: base runs on many seeds, print raw situations | CLI `dist/smoke.js [--seeds 40] [--from 1] [--fake] [--show <trigger\|all\|ask>] [--cf]`; prints decisions by trigger, correlation `trigger:how`, diagnoses, mutation subject roles, push writes, internal errors; `--cf` also runs `generateTrajectory` (maxPoints 4) on up to 20 seeds | +| `sim/scripts/final.sh` | final datasets on the train VM | `final.sh a \| b \| merge-b` | +| `sim/scripts/analyze.py` | dataset summary (works on merged files or `parts/`) | `python3 sim/scripts/analyze.py <dir>` | +| `sim/test/*.ts` | vitest suites (17 tests) | see [Tests](#tests) | +| `sim/samples/` | `sample.jsonl` (200 rows), `EXAMPLES.md` (16 rows), `sample-stats.json`, `stats-final-a.json` | - | +| `sim/NEEDS.md` | SIM -> CORE requests (all DONE per STATUS) | - | + +## Concepts and data structures + +| term | meaning (code) | +|---|---| +| **scenario** | `Scenario` (`sim/src/world/scenario.ts`): one program (domain, 1-3 features + optional `benign`, naming, API envelope style `api`, `idStyle`), one user session (`steps: UserStep[]`), one network profile (`net: NetProfile`, `chaos`), `external: ExternalEvent[]`, timing (`warmup`, `tUser`, `tEnd`), `askTimes`, vocabulary overrides (`diagnoses`, `actionWords`), `modelMs`, `budget`. Fully determined by `seed`. | +| **trajectory** | one scenario processed by `generateTrajectory`: 1 ideal run + 1 base run + counterfactual runs -> rows. Rows of a trajectory share one split. | +| **feature / combinator** | `FeatureDef<S>`: `make(ctx) -> spec`, `pattern(spec)`, `server(spec, srv, db)`, `client(spec, env, kit) -> FeatureClient`, `session(spec, user, win)`, optional `external(...)`, `relations(spec)`. | +| **spec** | the per-program knob values a feature's `make` picks (guards vs defects). | +| **pattern** | variant tags from `pattern(spec)`, stored prefixed with the kind (e.g. `search/guard:none`). Used for held-out test patterns and `meta.patterns`. | +| **family** | program family = sorted unique feature kinds joined by `+` (e.g. `cart+search`). A row's `family` is `<program family>/<trigger>`. | +| **intent** | `Intent` in `Knowledge`: one user step; `key` = slot it targets, `mode` `replace` (newer replace-intents on the same key **supersede** older ones, `Knowledge.superseded`) or `accumulate`; `accidental` = double click / impatient re-click with `repeatOf`. | +| **sim op** | `SimOp`: an app-level request with `role`, `intent`, `key`, `idempotent`, `attempt`, `retryOf`, `dupOf` (repeat of another op), `anomaly` (typed `partial \| shape \| empty \| benign-change \| string`, but never set on ops in practice: `Kit.op` does not copy an `anomaly` field, so poll's `anomaly: "storm"` is dropped; features set `partial`, `shape` and `benign-change` on writes instead), `background`, `handled`, `classify()`, `rtOp` (runtime op id), `net` (network entry ids). Not the runtime's op. | +| **sim write** | `SimWrite`: one store write with `role`, `op`, `intent`, `key`, `fields` (top-level fields changed), `anomaly`, `classify()`, `rtMutation`. | +| **classify** | feature-provided closure on an op/write evaluated at decision time; returns a diagnosis (`stale`, `conflict`, `duplicate`, `expected`) or `undefined`, typically from content bookkeeping (`ContentBook` in search/cart: which intent the shown data reflects; editor keeps its own text map, board/poll compare versions/ranges). A returned label takes precedence in `diagnose`. | +| **relation** | `Relation {fields, desc, check(stores)}`: an invariant the app intends to keep (count = len(items), total = sum price*qty, badge = cart count, per-column/per-status counts). Ground truth for `inconsistent` and a cost term. | +| **ideal run** | `runScenario(scn, {ideal: true})`: no runtime (`PlainBackend` atoms), `IDEAL_PROFILE` network (0 latency, no failures/chaos, 0 push latency, 0 ms socket connect), accidental and conditional (`when`) steps skipped, app-generated duplicates (`dupOf`) share the original's result (`Kit.call`). The **intended outcome**. | +| **base run** | real runtime, recording decider, exploration policy, ask probes; `record: true`. | +| **counterfactual (cf) run** | real runtime, `forced` map (explored choices before *k*, action *a* at *k*, passive after), `fpUpTo: k`, `tStop: t_k + 15000`, optional `future`. | +| **decision point** | `DecisionRec` (`k` = 0-based index of `evaluate` calls in the run, `t`, `trigger`, `state`, `questions`, `actions` = keys of `questions.action.criteria`, `chosen`, `explored`, `diagnosis`, `subject`, `fakeDiagnosis`, `fp`). | +| **fp** | fingerprint `JSON.stringify([trigger, state, questions])`; cf runs must reproduce `fp` for every decision `<= k` or the point is dropped (`prefix-mismatch`). | +| **future** | `RunOptions.future = {k, salt, t}`. Future 0 = no salt (same draws as base). Futures 1..K-1 re-seed the draws made after the decision for network latency/failures/replica lag, push latency, model latency for `idx > k` and external events (+U(0,600) ms jitter) with a salt shared by all actions (common random numbers). App-code draws (`env.rng`) and the user session are not re-seeded. | +| **subject correlation** | mapping `EvaluateRequest.subject` (runtime ids) to sim knowledge: `Subject.kind` in `write`, `op`, `error`, `invariant`, `chain`, `unknown`; `DecisionRec.subject.how` in `subject`, `sync`, `chain`, `delivered`, `last`, `text`, `none`. | +| **D(t)** | weighted client divergence of the real run's stores from the ideal run's at the same time (`clientDist`). | +| **tier** | `TIER` in `cost.ts`: passive (`apply send deliver wait ignore`), guard (`discard defer coalesce delay`), heal (`block serve_cached retry hedge rollback resync`). Drives the label premium. | +| **chaos** | `"calm" \| "normal" \| "flaky" \| "degraded" \| "storm"`, picks network parameters (`makeNet`). | +| **diagnosis-only row** | a decision with < 2 applicable actions (runtime omits the `action` question); only a `diagnosis` label; no counterfactuals; <= 3 per trajectory. | +| **ask row / ask probe** | at `scn.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records `AskFacts`; `askQuestions` attaches 1-3 questions with exact labels. | +| **budget** | `situation.budget` passed to the runtime per scenario: 3200 / 2000 / 1000 characters (runtime uses compact questions at <= 1400). Recorded in `meta.budget`. | +| **passive** | `PASSIVE` (`sim/src/types.ts`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, inconsistency `ignore`, transition `ignore`, error `ignore`. Fallback everywhere: the first offered action. | +| **user model** | `UserModel` (`feature.ts`): `think(mul)` = max(120, lognormal(thinkMs x mul, 0.5)); `key()` = max(25, lognormal(keyMs, keySigma)); `type()` emits one `type` step per keystroke (value = full input text), typo + backspace with p = typoP/6 per non-space char, pause U(150,700) ms after a space with p 0.3; `click()` adds an accidental double click U(45,190) ms later with p `doubleClickP` (or `opts.doubleP`), and, when `pendingCond` is given, with p `impatientP` 1-3 impatient re-clicks starting at impatienceMs x U(0.7,1.4), spaced U(300,1500) ms, each guarded by `when: pendingCond` (runs only while `client.cond(name)` is true). Accidental steps carry `repeatOf: -1`; the runner resolves the real intent it repeats. | +| **session window** | per feature *i*: `cover = U(0.45, 1)`, length `tUser x cover`, start `U(0, tUser - len)` (`R.fork("session", i)`); steps at `>= tUser` are dropped; all steps sorted by `t`. | +| **transform variant** | `meta.transform`: `default`, `shuffle`, `drop:<action>`, or `drop:<action>,shuffle`. | +| **NetCause** | why a request ended (`NetEntry.cause`): `ok transient outage overload ratelimit spike slow-period gateway-timeout bug replica-lag neterr aborted notfound`; plus `slowCause` `spike \| slow-period \| overload`. Diagnoses read these. | + +Row (`sim/src/types.ts` -> `Row`, CONTRACT-D): + +```ts +interface Row { id: string; split: "train"|"dev"|"test"; family: string; state: JevState; + questions: Record<string, Question>; labels: Record<string, Label>; meta: Record<string, unknown> } +type Label = {type:"choice"; label:string} | {type:"choice"; dist:Record<string,number>} + | {type:"noul"; p:number} | {type:"score"; level:number} | {type:"score"; dist:number[]}; +``` + +| row kind | `id` | `labels` | `meta` fields (beyond `meta0`) | +|---|---|---|---| +| decision | `sim-<seed>-d<k>` | `action: {type:"choice", dist}` (after transform), `diagnosis: {type:"choice", label}` when correlated and the label is in the offered vocabulary | `trigger`, `decision` (k), `t` (virtual ms), `explored_before`, `best`, `passive_best`, `costs` (mean per action, 4 dp), `cost_futures` (per-future totals), `futures`, `adjusted` (gap to best), `se`, `non_passive_mass`, `cost_parts` (future 0 breakdown: `area`, `final_client`, `final_server`, `relation_s`, `relation_final`, `errors`, `uncaught`, `wasted`, `latency_s`), `tiers`, `diagnosis` (or null), `subject`, `transform`, optional `fake_diagnosis: true` | +| diagnosis-only | `sim-<seed>-s<k>` | `diagnosis` | `trigger`, `decision`, `t`, `diagnosis`, `diagnosis_only: true`, `subject` | +| ask | `sim-<seed>-a<i>` | `q_*` per question (noul `p` 0/1, choice `label`, score `level`) | `trigger: "ask"`, `t`, `kinds` | + +`meta0` (every row): `seed`, `domain`, `family` (program family), `chaos`, `budget`, `runtime` (`"real"` or `"fake"`), +`features` (kinds), `patterns`. Situation `state` sections seen in samples: `app`, `trigger`, `facts`, `in_flight`, +`timeline`, `state`, `stats` (produced by the runtime; see [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md)). + +Random streams (every one is a keyed `Rng`; changing a key or the order of draws *within* one stream changes data): + +| stream | key | used for | +|---|---|---| +| scenario root `R` | `Rng(hashAll("scenario-v1", seed))` | forks `domain`, `program` (-> `naming`, `api`, `ids`, `kinds`, `feature,i,kind` -> `make`), `timing`, `chaos`, `net`, `persona`, `session,i` (-> `user`), `external,i`, `ask`, `vocab`, `action-vocab`, `model`, `budget` (`buildScenario`) | +| trajectory `R` | `Rng(hashAll("traj", seed))` | forks `testkeep`, `explore`, `points`, `transform,k`, `single`, `ask,i` (`generateTrajectory`) | +| server ids | `hashAll("db-<seed>", collection, createKey, n, salt)` | `Db.makeId` | +| network | `hashAll(hashAll("net", seed), [salt,] identity, occurrence)`; push `(.., "push", topic, n)`; replica lag `(.., "lag", identity, occurrence)` | `Network.send`, `publish`, `process` | +| app | `Rng(hashAll("app", seed))` = `env.rng` | run-time draws inside feature code (always `env.rng.fork(<key>)`) | +| exploration | `Rng(hashAll("explore", seed)).fork(k)` | per-decision explore draw (`runScenario` decider) | +| model latency | `hashAll("model-latency", seed, idx[, salt])` | decider delay `lognormal(modelMs, 0.35)` | +| external jitter | `hashAll("ext-jitter", salt, i)` | +U(0,600) ms for external events after `future.t` | +| futures | `hashAll("future", seed, k, j)` | salt of future *j* at point *k* (`pointCosts`) | + +## How it works + +### 1. CLI and workers (`sim/src/gen.ts`, `sim/src/gen/worker.ts`) + +1. `gen.ts` -> `parse` reads flags (table in [Configuration](#configuration-and-constants)); unknown flags throw. +2. Non-parts mode: deletes `<out>/shards`, spawns `--workers` `Worker(dist/worker.js)` with `workerData {id, out, + fake, maxPoints, askRows, testKeep (1 when --sample), exploreScale}`; feeds each idle worker 2 consecutive seeds + (`batch = 2`) from `--seed` upward until `produced >= target` (target = `--rows`, or 900 with `--sample`), then + sends `{stop: true}`. Workers already fed finish their batch, so the run overshoots slightly and the exact + last seeds depend on scheduling. +3. Worker: loads the factory once (`realRuntimeFactory()`, or `createFakeRuntime` with `--allow-fake`), then per + seed `generateTrajectory(seed, opts)`; appends rows to `shards/<split>.w<id>.jsonl`; posts a `traj` message with + compact stats. Exceptions -> `error` message (counted as drop `trajectory-exception`); a failed runtime import -> + `fatal` (aborts the run). Messages: `ready`, `idle`, `traj`, `error`, `fatal`, `part-done`. +4. When all workers exit: shards are concatenated per split (sorted by file name) into `<out>/{train,dev,test}.jsonl`, + `shards/` is removed, `stats.json` is written. +5. Parts mode (`--parts`): part *i* = seeds `[seed + i*chunk, seed + (i+1)*chunk)`. The worker writes + `parts/part-NNNNNN.<split>.jsonl.tmp`, renames them when the part is complete and writes `part-NNNNNN.json` + `{part, seeds:[first,last], rows}`. On start, `*.tmp` files are deleted and parts with a `.json` marker are skipped + and their rows counted toward `--rows`. Writes `stats.session.json` (see table below), not `stats.json`. + `--merge-only` concatenates `parts/*.<split>.jsonl` into `<out>/<split>.jsonl` (parts kept). +6. `--sample`: output to `sim/out/sample-tmp`, then writes `sim/samples/sample.jsonl` (200 rows, round-robin over + groups `trigger|diagnosis|act-or-passive`), `sim/samples/EXAMPLES.md` (`renderExamples`: 12 targeted kinds, then + distinct `trigger|best|diagnosis` up to 13, one diagnosis-only, two ask rows) and `sim/samples/sample-stats.json`. +7. Progress is logged at most every 15 s, checked when a `traj` message arrives (`[gen] <produced>/<target> rows, + ...`). `--merge-only` implies `--parts`. + +Output files of one `gen.js` run (`<out>` = `--out`, resolved against the cwd; `final.sh` first `cd`s into `sim/`): + +| file | written by | content | +|---|---|---| +| `<out>/shards/<split>.w<id>.jsonl` | worker (non-parts) | per-worker rows; merged then deleted | +| `<out>/{train,dev,test}.jsonl` | `main` merge / `mergeParts` | final rows (one JSON `Row` per line) | +| `<out>/stats.json` | `main` (non-parts only) | aggregate stats (keys below) | +| `<out>/parts/part-NNNNNN.<split>.jsonl[.tmp]` | worker (parts) | rows of one part; `.tmp` until the part is complete | +| `<out>/parts/part-NNNNNN.json` | worker (parts) | `{part, seeds:[first,last], rows:{split:n}}` completion marker | +| `<out>/stats.session.json` | `main` (parts) | `{note, rows, seconds, rowsBySplitTrigger, drops, errors}`; all but `rows` cover this session only (`rows` also counts the rows of parts finished in earlier sessions) | + +`stats.json` keys (`gen.ts` -> `main`): `args`, `rows` (per split), `rows_by_split_trigger`, `trajectories`, `runs`, +`decisions_seen`, `seconds`, `rows_per_sec_total`, `diagnosis_by_split_trigger`, `best_action_by_split_trigger`, +`passive_best_by_split_trigger` (`{rows, passive_best, frac}` per `split|trigger`), +`harm_of_non_passive_when_passive_best` (per trigger/action `{n, mean, p10, median, frac_harmful}`, harmful = cost +increase > 0.05), `gain_of_best_over_passive_when_not_passive`, `by_budget` (`rows`, `state_chars` and +`token_estimate` p50/p90/max, `passive_best_by_trigger`), `label_sharpness` (per trigger: passive-best rows with +passive mass >= 0.9; intervene-best rows with non-passive mass >= 0.95 / >= 0.9 / < 0.6; `points_with_3_futures` = +share of points with > 1 future), `ask_question_kinds`, `ask_labels` (`<qid>=<value>` counts), `token_estimate` (chars/3.6 of state+questions +JSON: p50/p90/p99/max), `subject_correlated` (`yes`/`no` per labelled point), `exploration` (`on-passive-path` / +`after-exploration`), `drops`, `skipped` (reason prefix before `:`), `domains`, `families` (count), `features`, +`errors` (first 20). Stats count only decision points (`PointStat`) for label statistics; row counts include +diagnosis-only and ask rows. + +### 2. One trajectory (`sim/src/gen/trajectory.ts` -> `generateTrajectory`) + +1. `buildScenario(seed)`; `split = splitOf(scn)`; trajectory rng `R = Rng(hashAll("traj", seed))`. +2. If `split === "test"` and `R.fork("testkeep").next() >= testKeep`: return `skipped: "test-subsample"` (no runs). +3. Ideal run (`ideal: true, serverTimeline: true`). Internal errors -> drop `ideal-internal-error`. +4. Exploration: `eps = R.fork("explore").weighted([[0,4],[0.08,3],[0.2,2]]) * exploreScale`. Per decision that + offers a non-passive action, probability `eps` if the sim's diagnosis is set and not `expected`, else `eps/4`, to + pick a uniformly random non-passive action (`explorePolicy`). Draws use `Rng(hashAll("explore", seed)).fork(k)`. +5. Base run (real runtime, `record: true`, `probeAsk`, explore). Internal errors -> drop `base-internal-error`, + `skipped: "base-error: ..."`. +6. `pickPoints(base.decisions, maxPoints, R.fork("points"))`: candidates have >= 2 actions; weighted sampling + without replacement with `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, + transition 3, error 2.2) x 1.5 when the diagnosis is set and not `expected`; sorted by `k` (all candidates are + kept when there are at most `maxPoints`). +7. For each point: `pointCosts` (flow 4) -> `actionLabel(futures, passive)` (flow 5) -> `transformQuestions(..., + R.fork("transform", k))` -> labels. `diagnosis` label only if the diagnosis is in the offered criteria and + `subject.kind !== "unknown"`; otherwise drop counters `diagnosis-not-in-vocab` / `diagnosis-uncorrelated`. +8. Diagnosis-only rows: decisions with < 2 actions, a diagnosis and a known subject; `R.fork("single").sample(.., 3)`; + a sampled decision is skipped (not replaced) when its label is not among the offered diagnosis criteria. +9. Ask rows (unless `--no-ask`, which also turns off the base run's ask probes: `probeAsk = askRows`): for each + `base.asks[i]`, `askQuestions(a, R.fork("ask", i))`; a probe that yields no question produces no row. + +### 3. One run (`sim/src/run/runner.ts` -> `runScenario`) + +1. New `VirtualLoop`, `Db(scn.idStyle, "db-<seed>")`, `VirtualServer`; each feature's `server()` registers routes and + seeds data; `relations()` collected. +2. `Network(loop, server, ideal ? IDEAL_PROFILE : scn.net, hashAll("net", seed))`; `makeGlobal` builds `SimGlobal`: + `fetch` = `network.fetch`, timers on the loop (owner `app`), `location` at `https://app.example.test/`, + `document.title`, and a `WebSocket` class (`makeWebSocketClass`) over the push channel + (`wss://<host>/ws/<topic>`, connect delay `40 + (topic.length % 7) * 10` ms, 0 in the ideal run; `send` not modelled). +3. Real runs: `factory(RuntimeOptions)` -> `createRuntime(createOptions(...))` with the recording decider, + `loop.clockFor("runtime")`, vocabulary overrides, `budget`, `hooks`, `app: () => ({title, route})`. Stores are + runtime atoms (`rt.atom(name, initial, {resync})`); ideal runs use `PlainBackend`. +4. `AppEnv` + one `Kit` per feature; `client()` per feature; initial route = first feature's route. +5. Schedules: `init()` of every client at t = 0; every user step at `st.t` (owner `user`; skipped if `when` is false; + real runs wrap `client.handle` in `runtime.user(act, handler)` with `know.callingIntent` set); external events + (owner `sim`; in a re-seeded future, events later than `future.t` are delayed by U(0,600) ms); ask probes (real + runs with `probeAsk`, i.e. base runs only). + Each executed step creates a `Knowledge.intent`; an accidental step's `repeatOf` resolves to the latest + non-accidental intent with the same `feature|action|intent.key`. `act` = `{kind: ui.kind, target, value?}`. + Ask probes call `runtime.situation("ask")` (a throw is an internal error) and record `AskRec {t, state, + facts}`. +6. `loop.onSettled` pushes a client snapshot after every settled macrotask that changed a store (`env.dirty`) and, + with `serverTimeline`, a server snapshot after every DB write. +7. `loop.settle()`, `loop.runUntil(min(tEnd, tStop))`, then collect `RunResult` (snapshots, final, server, decisions, + asks, know, netLog, error counts/times, `userOpMs`, internal errors, weights, relations) and `runtime.destroy()`. + +### 4. Counterfactuals (`sim/src/gen/trajectory.ts` -> `pointCosts`) + +1. `forcedPrefix` = `{d.k: d.chosen}` for explored base decisions before *k* (non-explored ones were passive, which is + the cf default). +2. For future `j = 0..K-1` (K = `GenOptions.futures ?? 3`): with `adaptive` (default true), stop after future 0 + unless some non-passive action beats passive by > 0.05 there. +3. Future `j >= 1`: `salt = hashAll("future", seed, k, j)`; if any external event is after `t_k`, re-run the ideal + world with that salt (`future.k = -1`) so external timing matches. +4. For each action: `runScenario(scn, {forced: prefix + {k: a}, fpUpTo: k, tStop: t_k + W.finalMs, future})`. + Exception -> drop `cf-exception`; internal error -> `cf-internal-error`; decisions `<= k` must equal the base run's + `fp` -> else `prefix-mismatch`. +5. `runCost(cf, idealJ, t_k, scn.tEnd).total` (4 dp) per action per future; `cost_parts` and `results` from future 0. + +### 5. Cost and labels (`sim/src/oracle/cost.ts`) + +1. `stop = min(tEnd, t_k + 15000, run.tStop)`. +2. `area` = `divergenceArea` over `[t_k, min(stop, t_k + 10000)]` (seconds) of `clientDist(real, ideal)`. + `clientDist`: per store/field weight from `env.store(..., {weights})` (default 1, weight <= 0 skipped); lists compare + as multisets of content with volatile keys ignored (`id version rev revision etag updatedAt updated_at clientId + pending seq`); numbers 0/1; objects averaged per key (depth < 3). The first field of every violated relation + adds its full weight even if it equals the ideal value. +3. `finalClient` = `clientDist` at `stop`; `finalServer` = `serverDist(real.server, ideal server at stop)`: + `25 x min(5, extra/missing items) + 6 x min(5, changed items)` per collection, `6 x min(3, differing fields)` per + doc, `6 x min(3, |delta|)` per counter (counters named `*beats` ignored); volatile server fields stripped. +4. Error terms: shown-error episodes and uncaught errors in `[t_k, stop]` beyond the ideal run's count; `wasted` = + per-signature server arrivals in `[t_k, stop]` beyond the ideal run's; `latencyS` = seconds non-background ops + were pending in `[t_k, stop]` (absolute, not relative to ideal); relation-violation area over the 10 s horizon and + count at `stop`. +5. `total = 1.0*area + 4.0*finalClient + finalServer + 1.5*shownErrors + 1.0*uncaught + 0.08*wasted + 0.25*latencyS + + 0.8*relationArea + 2.0*relationFinal`. +6. `actionLabel(costs, passive)`: per-future costs paired by index (K = min length). Non-passive action whose mean + is within `tieEps` 0.05 of passive's -> adjusted = passive's costs + `exactTie` 1.5; else cost + tier premium + (passive 0, guard 0.25, heal 0.5). `best` = argmin mean adjusted (ties keep passive). `gap_a = max(0, mean(adj_a - + adj_best))`, `tau_a = 0.10 + 1.0 * SE_a` (SE of the paired difference, 0 with one future), `p_a ∝ exp(-gap_a/tau_a)`, + rounded to 4 dp. + +### 6. A request through the world (correlation) + +1. Feature code: `kit.op({role, method, url, intent, key, ...})` -> `Knowledge.beginOp` (sim op id). +2. `Kit.callNet` adds `x-request-id: req-<hash>-<opId base36>` (`SIM_OP_HEADER`, `simOpHeaderValue`), app timeout via + `AbortController` with a `TimeoutError` reason, then `AppEnv.fetch` sets `know.callingOp` and calls + `G.fetch` (runtime-instrumented). +3. The runtime creates its fetch op synchronously -> `hooks.opCreated` maps runtime op -> sim op (`know.rtOps`, + `op.rtOp`), records causal parents (`know.rtParents`), and maps runtime user ops to intents (`know.rtUserOps`). + The runtime treats `x-request-id` as a volatile tracing header (not part of request identity, never serialized). +4. If the runtime lets it through, `Network.fetch` strips the header (`parseSimOpHeader` -> `NetEntry.simOp`), draws + latency keyed by `(netSeed, [salt,] identity, occurrence)`, and `onSend` appends the entry id to `op.net`. +5. Arrival after `0.35 x latency`; checks in order: outage -> capacity (non-latency mode) -> per-endpoint rate limit -> + random transient (`transientP`; non-GET commits first with `postCommitP`, then 500) -> network error (`netErrP`, 50% + commit) -> normal processing (server bug mutation, replica lag) -> gateway timeout 504 if the response would land + after `t0 + gatewayMs`. A normal response is delivered `(0.05 + 0.6) x latency` after arrival (fast-fail paths + such as outages and 429s use shorter offsets); bodies are real undici `Response` objects (`makeResponse`). + Exact failure shapes: outage `neterr` -> `TypeError("Failed to fetch")`; `hang` -> 504 at `t0 + gatewayMs`; + `empty` -> GETs processed with the `empty-list` bug (2xx, cause `outage`), writes 503; `503/500/502` -> that + status. Capacity (`load` = arrivals in the last 1000 ms > `perSec`): 429 with `retry-after: 1` or 503; in + `latency` mode the latency is multiplied by `1 + (load - perSec)/perSec` at send time instead. Rate limit: + 429, `retry-after: 1|2` when enabled. Random transient: post-commit -> 500, else one of 500/502/503. Server bug + mutations (`mutateForBug`) apply only to responses < 400: `drop-field`/`null-field` on `field` of every item + (depth <= 3), `empty-list` empties arrays and zeroes numeric `count|total` keys, `html` replaces the body with + `text/html`. Replica lag swaps the resource (`RouteMeta.resource`, GET only) to its value before the earliest + write in `(t - lagMs, t]` for the duration of the handler. In ideal mode the request is processed on arrival with + no checks (latency 0, two dummy draws keep the stream aligned). +6. Server (`VirtualServer.handle`): routes match by method + segment count (`:param` segments capture); no match -> + 404 `{error:"not_found"}`; a throwing handler -> 500 `{error:"internal"}`. `Idempotency-Key` responses are + remembered per `signature|key` when status < 500 and replayed (logged `note: "idempotent-replay"`, + `committed: false`). `committed` in the server log = not a replay and status < 400; the network only counts + non-GET commits. Every DB write increments `Db.writes` and stores a pre-write snapshot per resource key (`c:`, + `d:`, `n:`; last 64) for replica lag. `snapshot()` strips `version updatedAt updated_at rev etag seq`. +7. `Kit` classifies the outcome (`ok`, `http-error`, `neterr`, `aborted`, `timeout`, `parse-error` for HTML/invalid + JSON) and calls `Knowledge.endOp` (updates the per-signature failure `streak`: reset on `ok`, unchanged on + `aborted`, +1 otherwise; signature = `sigOf`). `Kit.op` defaults `idempotent` to true for GET/PUT/DELETE and + false for POST/PATCH unless the feature passes it; `Kit.callNet` also sets `accept: application/json` and, with a + body, `content-type: application/json`. Outcome mapping of a rejected fetch: app timeout fired -> `timeout`; + `AbortError`/`TimeoutError` -> `aborted`; anything else -> `neterr`. A 2xx whose body is not JSON (bug `html`) + becomes `parse-error` with a synthetic `SyntaxError`. +8. Writes: `env.store(...).set(next, meta)` records a `SimWrite` (changed top-level fields; `input` role updates + `userFieldTime`) and sets `know.writing` during `atom.set`, so `hooks.mutationProposed` maps runtime mutation -> + sim write (`know.rtMutations`). + +### 7. A decision (recording decider in `runScenario`) + +1. `evaluate(req)`: `idx = k++`; actions = keys of `req.questions.action.criteria`; `correlate(req)` -> `Subject`: + mutation via `subject.mutation` (else ambient `know.writing`); request/failure/stall/transition via `subject.op` + (runtime retries/hedges map through causal parents up to 6 hops); transition on a user/timer op -> the chain of + app ops descending from it (8 hops); request fallback ambient `know.callingOp` (`how: "sync"`); failure fallback + `network.lastDelivered`; error via `subject.error` (else last + uncaught error); inconsistency via `subject.invariant` + `paths` (else trigger/facts text). +2. `diagnose(trigger, subject, {know, network, relations, now, stores})` (flow 8). +3. Choice: `forced.get(idx)` -> else exploration -> else passive (`PASSIVE[trigger]`). A forced or explored action + that is not among the offered actions falls back to passive (or the first offered action). `DecisionRec.subject` + = `{kind, how, ref?}` where `ref` is the sim op/write id. +4. Answers: action = probability 1 on the chosen action; diagnosis = the sim's label, but if a non-passive action + is chosen and the label is `expected`, answer `unusual` (or the first non-`expected` key) and set + `fakeDiagnosis`; other noul questions 0.5, score level 0. +5. Records a `DecisionRec` (`record`, or `idx <= fpUpTo` with state/questions blanked). At `idx === future.k` the + network switches to the future salt; model latency `lognormal(scn.modelMs, 0.35)` keyed by `(seed, idx[, salt])`. +6. Runtime policy (from `createOptions`): thresholds guard/heal 0.5 with `requireDiagnosis: false` -> exactly the + forced action runs (the summed non-passive mass is 1 or 0). + +Error paths into the runtime's `error` trigger: `Kit.spawn(fn, "uncaught", tag)` tags the rejection +(`Knowledge.tagError`, default tag `{cause:"unhandled", diagnosis:"failing"}`) and calls `env.uncaught(e, +"unhandledrejection")`; a throw inside an `app`/`user` loop task is tagged `{cause:"handler-threw", +diagnosis:"failing"}` (if untagged) and reported as `window.onerror`. `env.uncaught` -> `runtime.reportError(err, +{source})`. `benign` noise errors are tagged `expected`. + +### 8. Diagnosis rules (`sim/src/oracle/diagnose.ts` -> `diagnose`, first match wins) + +| trigger | rules | +|---|---| +| mutation | `write.classify()`; `anomaly === "partial"` -> inconsistent; `shape`/`empty`, server bug, or outage-emptied data with status < 400 -> unusual; op `dupOf` or accidental intent -> duplicate; replica lag -> stale; data role (`DATA_ROLES`) of a superseded intent -> stale; non-input write over fields the user changed after the op started -> stale; `push` write while a non-background op on the same key is in flight -> conflict; else expected | +| request | `op.classify()`; `dupOf`/accidental -> duplicate; non-idempotent retry whose original committed -> duplicate; `anomaly: "storm"` (dead branch, see sim op) or >= 6 req/s to that signature (2 s window) -> overload; non-background superseded intent -> stale; streak >= 2 -> failing; else expected | +| failure | `diagnoseFailure`: outage -> failing; timeout/504/`TimeoutError`: slow period or overload -> slow, else streak >= 2 -> slow, else transient; 429/503 shedding or rate limit: client >= 3 req/s (signature of the entry, 2 s window) or storm -> overload, else failing; bug -> unusual; storm -> overload; streak >= 2 -> failing; else transient. Both storm checks read `op.anomaly`, which is never set, so they never fire | +| stall | request inside an outage window -> failing; `slowCause === "overload"` -> overload; else slow | +| inconsistency | `inconsistent` only if a relation is violated in the current client snapshot and its fields overlap the invariant's `store.field` refs (`fieldRefs`); else expected | +| transition | a network entry of the op(s) with cause bug or replica lag, or cause outage with status < 400 or no status (outage-emptied 2xx, and also `neterr`-mode outages, which carry no status) -> unusual; a write with `partial`/`shape` anomaly for the op or chain intent -> unusual; failed op -> `diagnoseFailure`; else expected | +| error | untagged error -> expected; tag `expected` -> expected; tagged op with `parse-error` -> unusual; tagged op -> `diagnoseFailure`; else the tag's diagnosis | + +Details: `diagnose` returns `undefined` (no label, drop counter `diagnosis-uncorrelated`) when the subject is +missing (mutation without a write, request without an op, stall with neither entry nor op, transition with neither +op nor chain). A failure always gets a label (`diagnoseFailure` falls back to `transient`), but the row still loses it +because `subject.kind` is `unknown`. In `diagnoseFailure`, `streak` = `know.streak[sigOf(op)] + 1`. For a `failure` +trigger the op has usually not ended yet (the `+1` stands for the current failure), so "streak >= 2" means at least +one earlier consecutive failure. For `error` and `transition` callers the op has already ended (`Knowledge.endOp` +counted it), so unless a later op of the same signature reset the streak, the `+1` counts the current failure twice +and a first failure already yields `failing` (or `slow` for a timeout). Error tags without an `op` (form, poll, nav +and cart-checkout spawns, `handler-threw`) return the tag's own `failing`. Both are consistent with phase A train +`error` points (94.8% `failing`, 0.1% `transient`). The request rule uses the raw `know.streak >= 2`. Client rates (`clientRate`) count +`NetEntry`s with the same route signature sent in the last 2000 ms, divided by 2. `DATA_ROLES` = `results echo +refetch poll-result view-data append data load confirm created push cache resync conflict-refetch bulk-result +presence swr-cache clear placed`. + +### Feature combinators and the bugs they create + +`FEATURE_WEIGHTS` (`sim/src/app/features/index.ts`): search 10, editor 9, poll 9, form 8, cart 8, board 7, nav 7, +list 7, toggle 6, chat 6, counter 5, settings 5, bulk 4, auth 3, benign 4 (benign is never drawn by weight; it is +added with p 0.3). + +| feature | knobs -> pattern tags | bug opportunities (what the runtime should catch) | relations / external | +|---|---|---|---| +| `search` (typeahead) | `guard:none\|abort\|reqid\|check` (4/2/2/2), `debounce` (0 or 120-450 ms), `cache` (0.25), `err:show\|silent\|throw`, `timeout` (2.5-9 s); minLen 0-2 | no guard -> out-of-order results overwrite newer ones (stale mutation); per-keystroke requests; `err:throw` -> unhandled rejection | - | +| `editor` (autosave + echo) | `save:debounce\|interval\|button`, `overlap:allow\|serialize`, `echo:always\|if-unchanged\|version-only`, `vcheck:refetch\|overwrite\|show` or `novcheck`, `live:blind\|if-clean` or `nolive`, `retry:none\|once\|backoff` | overlapping saves; echo of an older save over newer typing (stale); 409 conflicts; blind live edits during local edits (conflict); retry of old text (stale) | external: 0-2 random collaborator edits; plus (live only) for the first 3 of the user's save steps (and about 4% of edit keystrokes), each with p 0.5, a conflicting edit 20-900 ms later | +| `form` (create) | `disable`, `idem`, `retry:none\|same-key\|no-key`, `retry-on:timeout\|5xx`, `ok:append\|refetch`, `optimistic+rollback\|optimistic-norollback\|pessimistic`, `count\|count-partial\|nocount` | double submit; retry without key after a committed timeout -> duplicate item (server damage); optimistic append without rollback; count not kept on refetch/rollback (`anomaly: partial`); 25% intentional identical re-creates (benign) | count == len(list) | +| `cart` | `mode:optimistic\|server\|echo`, `rollback`, `recompute:always\|skip-rollback\|skip-echo\|items-only-qty`, `addguard`, `co-disable`, `co-idem`, `co-retry:*`, `badge` | non-idempotent add POST + double click; full-cart echo stale with several updates in flight; totals not recomputed (partial); checkout double submit / retry without key -> duplicate orders | total = sum price*qty (abs diff < 0.011); count = sum qty; badge = cart count | +| `toggle` | `ep:absolute\|relative`, `rollback`, `echo`, `pending-guard\|noguard`, `count\|count-partial\|nocount` | relative (non-idempotent) toggle + double click flips back; echo flip-back (stale); no rollback; partial count | flagged count | +| `counter` | `ep:increment\|absolute`, `echo:always\|latest-only\|none`, `retry:none\|retry` | non-idempotent increment + retries/double clicks over-count; stale echo after rapid clicks | - | +| `poll` (dashboard) | `mode:interval\|chain`, `skip-inflight\|overlap`, `fail:backoff\|tight\|ignore\|throw`, `seq\|noseq`, `timeout` | overlapping polls (`dupOf`); tight retry loop (50 ms sleep after each failed response, up to 30 consecutive fails); it passes `anomaly: "storm"` to `kit.op`, which drops it, so these retries are `overload` only through the >= 6 req/s rate rule; throw after 2 failures; stale range responses | external: 2-8 metric changes | +| `board` (kanban + live) | `push:blind\|version\|skip-pending`, `echo`, `rollback`, `counts\|counts-partial\|nocounts`, `vcheck` | blind push over a pending local move (conflict); out-of-date push (stale); counts not updated on push (partial); 409 on version mismatch | per-column counts; external: 1-5 random moves + 30% of user moves followed by a conflicting move 30-700 ms later | +| `chat` | `optimistic\|pessimistic`, `dedupe:id\|clientId\|none`, `resp:replace\|append\|ignore`, `disable`, `unread` | duplicate messages (response + own push); pessimistic send clears a draft typed meanwhile; double send; 15% intentional repeats | external: 0-4 incoming messages | +| `settings` | `echo:full\|key\|none`, `seq\|noseq`, `serialize\|parallel`, `rollback` | full-object echo reverts a newer toggle (stale) | - | +| `nav` (views) | `mode:all\|allSettled\|chain`, `route-guard\|noguard`, `abort\|noabort`, `err:throw\|banner\|partial`, `swr` | previous view's data written into the current view (stale); `err:throw` unhandled rejection; partial render (`anomaly: benign-change`) | - | +| `list` (filters + infinite scroll) | `guard:none\|reqid\|abort`, `more-guard\|more-noguard` | stale page after filter/sort change; duplicate page appends from repeated scroll events (`doubleP` 0.35) | - | +| `bulk` | `assume-all\|per-result`, `counts\|counts-partial\|nocounts`, `disable` | assume all succeeded although locked items failed (207/409; `anomaly: shape` -> unusual); partial counts | per-status counts | +| `auth` (expiring tokens) | `single-flight\|per-request-refresh` | one refresh per 401 -> second refresh uses the rotated token -> 401 -> forced logout; duplicate refresh request | - | +| `benign` | `beacon-timer\|beacon-user`, `noise:0\|1\|2` | none by design: heartbeats (identical POSTs), beacons with ignored failures, config prefetch, harmless uncaught errors (`ResizeObserver loop...`, `Script error.`, ...). All ops/writes classify `expected`. | - | + +Exact negative tags emitted by `pattern()` (needed when editing `TEST_PATTERNS`): search `nodebounce nocache +notimeout`; form `nodisable noidem`; cart `norollback noaddguard co-nodisable co-noidem nobadge`; toggle +`norollback noecho`; poll `notimeout` (positive `timeout`); board `noecho norollback novcheck`; chat `nodisable +nounread`; settings `norollback`; nav `noswr`; bulk `nodisable`. Tags are stored as `<kind>/<tag>`. + +Knob draws in each feature's `make()` (weights `a:w`, probabilities `p`): + +| feature | draws | +|---|---| +| search | guard none:4 abort:2 reqid:2 check:2; debounce 0:4 / int(120,450):4; cache p 0.25; minLen 0/1/2 equal; loadingFlag p 0.7; totalField p 0.6; onError show:5 silent:2 throw:2; timeout 0:3 / int(2500,9000):2; 12-40 seeded items; pageSize 10/20/25 | +| editor | save debounce:5 (300-1500 ms) / interval:2 (1500-5000 ms) / button:3; overlap allow:5 serialize:4; echo always:5 if-unchanged:3 version-only:2; versionCheck p 0.4; onConflict refetch:2 overwrite:1 show:2; live p 0.4 (blind:1 if-clean:1); retry none:3 once:2 backoff:2; timeout 0:3 / int(3000,10000):2; method PUT p 0.7 else PATCH; externalEdits 0:3 1:2 2:1 | +| form | retry none:4 same-key:2 no-key:3; idemKey = same-key or p 0.25; disable p 0.45; retryOn timeout:1 5xx:1; timeout (retry none: 0:2 / int(2000,6000):1, else int(1500,6000)); onSuccess append:3 refetch:1; optimistic p 0.35; rollback p 0.6; countField p 0.7; countOnAllPaths p 0.4; onError show:4 throw:1; 2-8 seeded items | +| cart | mode optimistic:3 server:3 echo:3; rollback p 0.6; recompute always:3 skip-rollback:4 skip-echo:2 items-only-qty:1; addGuard p 0.4; badge store p 0.5; checkout disable p 0.5, retry none:3 same-key:2 no-key:2, idem = same-key or p 0.3, timeout 0:2 / int(2000,7000):3; 4-10 products | +| toggle | endpoint absolute:3 relative:2; rollback p 0.6; echo p 0.5; pendingGuard p 0.35; countField p 0.65; countPartial p 0.5; 4-12 items | +| counter | endpoint increment:3 absolute:2; echo always:3 latest-only:2 none:1; retry none:3 retry:2; 3-8 items | +| poll | intervalMs 800:2 1000:3 1500:3 2000:2 3000:1 5000:1; mode interval:3 chain:3; skipIfInflight p 0.5; onFail backoff:3 tight:2 ignore:3 throw:1; timeout 0:3 / int(1500,6000):2; seqGuard p 0.35; 2-8 metric changes; 2-4 metrics | +| board | push blind:4 version:3 skip-pending:2; echo p 0.5; rollback p 0.6; countsField p 0.7; countsOnPush p 0.4; versionInBody p 0.3; 5-12 cards; 1-5 external moves | +| chat | optimistic p 0.6; dedupe id:2 clientId:2 none:3; onResponse replace:3 append:2 ignore:1; disable p 0.3; unread p 0.5; 0-4 incoming | +| settings | 2-3 keys; echo full:4 key:2 none:2; seqGuard p 0.3; serialize p 0.25; rollback p 0.5 | +| nav | 2-4 views x 2-3 resources (later resources depend on the first with p 0.3); mode all:4 allSettled:2 chain:2; routeGuard p 0.45; abortOnNav p 0.3; onError throw:2 banner:3 partial:2; swr p 0.3 | +| list | guard none:4 reqid:3 abort:2; moreGuard p 0.5; 15-45 items; pageSize 5/8/10 | +| bulk | applyAll p 0.45; countsField p 0.7; countsPartial p 0.5; disable p 0.5; 6-14 items, each `locked` p 0.2 | +| auth | ttlMs int(2500,9000); singleFlight p 0.5; 2 resources under `me/<entity>` | +| benign | heartbeatMs 2000/3000/5000; beaconOnTimer 0/2500/4000 ms; noise errors at U(500,14000) ms (count: see gotchas) | + +The network adds failure-mode opportunities independent of features: random 5xx, network errors, latency spikes, +slow periods, outages (`503 500 502 neterr hang empty`), capacity overload (`503 429 latency`), rate limits with or +without `retry-after`, replica lag, and server bugs (`drop-field null-field empty-list stale-replica html`). + +### Domains and naming (`sim/src/app/vocab.ts`, `sim/src/app/naming.ts`) + +- `DOMAINS` (55, in array order; **bold** = `TEST_DOMAINS`): commerce, chat, docs, project, finance, health, + travel, iot, games, media, crm, hr, education, maps, analytics, social, support, inventory, logistics, banking, + calendar, food, realestate, **music**, news, email, notes, todo, fitness, **weather**, rides, events, **hotel**, + library, **legal**, insurance, energy, **farm**, fleet, pharmacy, devops, code, marketing, **survey**, nonprofit, + **permits**, sports, photos, jobs, **pets**, **auction**, wiki, procurement, **payroll**, invoicing. +- A `Domain` has `name`, `titles` (app titles), `entities` (2 x `Entity {s, p, name, words, nums, status, flags, + create}`), `docs` (`[noun, textFields]`), `metrics`, `topics`, `settings`, `bulk` verbs, `people`. Built with the + string helpers `D(...)` / `E(...)` (nums as `field=lo-hi-decimals`). +- `Naming` per program (`rP.fork("naming")`): route casing kebab:5 snake:2 camel:1; route prefix `/api`:5 + `/api/v1`:3 `/api/v2`:1 `/v1`:2 `/rest`:1 `/svc/<app-title-kebab>`:1 none:1; store names camelCase p 0.8 else + snake_case (unique: suffix `2`, `3`, ... or `_2`, `_3`, ... in snake case); field names camelCase p 0.82 else snake_case. `field(role, scope)` + picks once per `(role, scope)` from the synonym pool `SYN` (e.g. `list`: items results rows list entries + records data hits; `loading`: loading isLoading pending busy fetching inFlight). `route(...)` prefixes a scope + word (`shop admin team my app store hub desk`, chosen by a hash of the owning feature id) when a path could + match another feature's route, so features never share an endpoint. +- Each feature's view route (`FeatureInst.route`) is `/<kebab of entity plural | "editor" | app|home|workspace>`; + the program starts on the first feature's route (`runScenario` -> `env.setRoute`), except that a `nav` feature's + `init()` switches to its own first view route, and its navigation steps change the route later. + +### Fake runtime (test double) + +`sim/src/run/fake-runtime.ts` -> `createFakeRuntime` implements `RuntimeLike` crudely so tests run without the real +runtime (default when `SIM_RUNTIME` is unset; `gen.js --allow-fake`). It wraps `global.fetch`, calls +`hooks.opCreated` / `hooks.mutationProposed`, and emits only these triggers: `request` (when an identical request +was sent in the last 3 s or the endpoint has a failure streak; actions `send [coalesce] delay block +[serve_cached]`), `failure` (`deliver retry`, plus `serve_cached` for an HTTP failure of a cached GET), `stall` (after max(1000 ms, 4 x median) once >= 3 latency samples +exist; `wait [hedge]`), `mutation` (an async fetch-caused write to a store written by another op since it started; +`apply discard defer`, defer = re-apply after 300 ms) and `error` (`ignore` only, so error rows are diagnosis-only). +No `inconsistency`/`transition` triggers. Situation sections: `app`, `trigger`, `facts`, `in_flight`, `timeline`. +Rows from it carry `meta.runtime: "fake"` and must never be used for training. + +### Ask questions (`sim/src/ask/questions.ts`) + +`askQuestions(a, rng)` shuffles the 11 generators, wants `rng.int(1, 3)` questions, and keeps the first that do +not return `null`; each generator gets `rng.fork(name)`. `text` = `JSON.stringify(a.state)`. Facts come from +`AskFacts` (`runner.ts` -> `askFacts`): network entries in flight / delivered in the last 15 s, last user intent +time, longest pending non-background sim op, last `save`-role op, current route. + +| qid | type | label | skip (returns null) when | +|---|---|---|---| +| `q_write_inflight` | noul | any non-GET network entry in flight | never | +| `q_any_inflight` | noul | any entry in flight | never | +| `q_pending` | score (4 options) | `min(3, in-flight count)` | > 6 in flight | +| `q_last_failed` | choice `e1..e3` + `none` | latest failed entry (HTTP >= 400 or neterr) in the last 12 s, else `none` | < 2 distinct signatures; the failed endpoint's last literal path segment is not in `text` | +| `q_recent_failure` | noul | a failure in the last 5 or 10 s | a failure is within 1 s of the window edge | +| `q_fail_count` | score | `min(3, failures in 10 s)` | count differs between 9 s and 11 s windows | +| `q_user_waiting` | noul | longest pending non-background op > N s (N in 1,2,3,5) | within 400 ms of N s | +| `q_user_recent` | noul | last user intent < N s ago (N in 1,2,3) | within 300 ms of N s | +| `q_last_save` | noul | last finished `save` op was `ok` | no finished save | +| `q_route` | choice `r1..r3` | current route among 2 decoys | route not in `text` | +| `q_slowest` | choice `o1..o4` | oldest in-flight request | < 2 in flight (age > 0); top two within 300 ms or same signature; the last literal path segment of any in-flight request is missing from `text` | + +## Configuration and constants + +| name | type | default / value | defined in | effect | +|---|---|---|---|---| +| `--rows` | number | 1000 (900 with `--sample`) | `gen.ts` -> `parse` | target rows (parts mode: total across sessions) | +| `--out` | path | `sim/out/run` (relative to cwd) | `gen.ts` | output dir; `--sample` ignores it (`sim/out/sample-tmp`) | +| `--seed` | number | 1 | `gen.ts` | first scenario seed | +| `--workers` | number | 4 (`final.sh`: `WORKERS` env, 56) | `gen.ts`, `scripts/final.sh` | worker threads | +| `--max-points` | number | 6 | `gen.ts` | labelled decision points per trajectory | +| `--test-keep` | number | 0.33 (1 with `--sample`) | `gen.ts` | fraction of test trajectories kept | +| `--explore` | number | 1 | `gen.ts` | multiplies exploration eps | +| `--no-ask` / `--allow-fake` / `--sample` | flags | off | `gen.ts` | no ask rows / fake runtime (never for training) / sample mode | +| `--parts`, `--chunk`, `--merge-only` | flag, number, flag | off, 100, off | `gen.ts` | resumable parts of `chunk` seeds; merge only | +| `batch` | const | 2 seeds per worker message | `gen.ts` | non-parts feeding | +| `SIM_RUNTIME` | env | unset (fake) | `sim/test/helpers.ts` -> `testFactory` | `real` runs tests on the real runtime | +| `SIM_DEBUG` | env | unset | `sim/test/oracle.test.ts` | prints state, cost parts and snapshots in the real-only invariant test | +| `TIMEOUT` | env (s) | 1800 | `scripts/vm.sh` | every `vm.sh run/exec` command is wrapped in `timeout`; phase A took 2,444 s, so long `gen.js` runs need a larger `TIMEOUT` (how phase A was launched is unverified) | +| scenario root key | string | `"scenario-v1"` | `scenario.ts` -> `buildScenario` | salt of every scenario draw; changing it re-rolls every seed | +| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` -> `realRuntimeFactory` | module specifier to import | +| runtime options | object | `model:false, mode:"heal", report:"silent", observe{fetch,timers,websocket: true; xhr,user,errors,nav,storage,perf: false}, triage:"salient", policy{thresholds{report 0, guard 0.5, heal 0.5}, holdBudgetMs 1e9, maxActionsPerMinute 1e9, requireDiagnosis false}, historySize 500` | `rt.ts` -> `createOptions` | forced-action contract with the runtime | +| feature count | weighted | 1:35, 2:45, 3:20; +benign p 0.3 | `scenario.ts` -> `buildScenario` | program size | +| `idStyle` | weighted | num 4, uuid 2, prefixed 2, slug 1 | `scenario.ts` | server id format (`Db.makeId`): num = `1000 + h % 899000`; uuid v4-shaped; prefixed = `<3-letter noun>_<digit><letter><12 chars>`; slug = `<noun[:6]>-<4 base36 chars>`. The runtime normalises a slug id in signatures only when `isSlugId` (`packages/runtime/src/util.ts`) accepts it: the 4-char suffix must start with a digit or alternate letters/digits at least twice (`k2x9`, `1cam`); all-letter, all-digit and single-transition suffixes (`abc1`, `a123`) stay literal. The sim's own `sigOf` never normalises slugs | +| API style | uniform | `items`, `data`, `bare`, `results` | `server.ts` -> `API_STYLES` | response envelopes | +| `tUser` | ms | 15%: U(120000, 300000); else U(20000, 75000) | `scenario.ts` | user session length | +| `warmup` | ms | `tUser x U(0.3, 0.6)` | `scenario.ts` | earliest start of outages/slow periods/bugs; ask probes from `warmup x 0.5` | +| `tEnd` | ms | `tUser + U(2500, 5000)` | `scenario.ts` | run end | +| chaos | weighted | calm 2, normal 3, flaky 3, degraded 3, storm 1 | `scenario.ts` | network profile | +| latency multiplier `m` | number | calm 0.5, normal 1, flaky 1.5, degraded/storm 2 | `scenario.ts` -> `makeNet` | scales medians: read U(50,220)m, write U(90,380)m, auth U(80,300)m, upload U(300,1500)m, bulk U(200,900)m; 25% of endpoints get U(100,1200)m | +| `spikeP`, `spikeMul` | number | calm 0.005; normal U(0.01,0.04); else U(0.01,0.1); mul [3, U(6,25)] | `makeNet` | latency spikes | +| `transientP`, `postCommitP` | number | calm 0; normal U(0,0.015); else U(0.02,0.12); post-commit U(0.2,0.7) | `makeNet` | random 5xx (some after commit) | +| `netErrP` | number | calm 0; normal U(0,0.004); else U(0,0.03) | `makeNet` | network errors (50% commit) | +| `gatewayMs` | ms | int(8000, 30000) | `makeNet` | 504 after this time in flight | +| outages | windows | degraded/storm, or flaky p 0.4: 1-2, length U(1500,9000), modes 503:4 500:2 502:2 neterr:2 hang:1 empty:2, endpoints `*` (p 0.4) or 1-3 | `makeNet` | outage failures | +| slow period | window | non-calm, p 0.25 (normal) / 0.6: length U(2000,10000), mul U(3,15) | `makeNet` | slow responses | +| capacity | object | storm, or degraded p 0.4: perSec int(4,14), mode 503:2 429:2 latency:1 | `makeNet` | overload shedding | +| rate limit | object | non-calm p 0.25: one endpoint, perSec int(2,6), `retry-after` p 0.6 | `makeNet` | 429s | +| replica lag | object | non-calm p 0.15: ms int(300,2500), p U(0.1,0.5) | `makeNet` | stale reads | +| server bug | window | p 0.05 calm / 0.18: a read endpoint, length U(2000,8000), kinds drop-field 2, null-field 2, empty-list 3, stale-replica 1 (2500 ms lag), html 1 | `makeNet` | malformed responses | +| push latency | lognormal | median U(20,150), sigma U(0.2,0.8); in order per topic | `makeNet`, `Network.publish` | live updates | +| persona | object | keyMs U(70,210), keySigma U(0.25,0.6), thinkMs U(500,2600), doubleClickP 0:3 0.06:3 0.18:2 0.4:1, impatientP 0:3 0.3:3 0.7:2, impatienceMs U(900,3500), typoP U(0,0.25) | `feature.ts` -> `randomPersona` | user behaviour | +| ask times | ms | 1-3 at U(warmup x 0.5, tEnd - 200) | `scenario.ts` | ask probes | +| `diagnoses` vocab | object/null | 50% default; else 30% drop 1-2 of `conflict slow overload unusual inconsistent duplicate transient`, each label paraphrased p 0.6 (`DIAG_PARA`) | `scenario.ts` -> `diagVocab` | runtime `vocabulary.diagnoses` | +| `actionWords` vocab | object/null | 50% default; else each action paraphrased p 0.6 (`ACTION_PARA`) | `scenario.ts` -> `actionVocab` | runtime `vocabulary.actions` | +| `modelMs` | ms | U(6, 25); latency `lognormal(modelMs, 0.35)` | `scenario.ts`, `runner.ts` | decider latency | +| `budget` | chars | 3200:40, 2000:30, 1000:30 | `scenario.ts` | runtime `situation.budget` | +| `TEST_DOMAINS` | set | weather, legal, pets, auction, farm, permits, music, hotel, payroll, survey | `scenario.ts` | held-out domains (10/55) | +| `TEST_PATTERNS` | set | `search/guard:check`, `settings/serialize`, `toggle/pending-guard`, `list/guard:abort`, `cart/recompute:items-only-qty`, `editor/echo:version-only`, `poll/fail:throw` | `scenario.ts` | held-out patterns | +| family hold-out | hash | `hashAll("family-split-v1", family) % 100 < 17` | `scenario.ts` -> `familyHeldOut` | test families | +| dev split | hash | `hashAll("dev-split-v1", family) % 100 < 3` | `scenario.ts` -> `splitOf` | dev families | +| `TRIGGER_W` | weights | mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2 (x1.5 non-expected) | `trajectory.ts` | point sampling | +| futures K / adaptive gain | number | 3 / > 0.05 | `trajectory.ts` -> `pointCosts` | extra futures | +| `W` | object | area 1.0, horizonMs 10000, finalMs 15000, finalClient 4.0, serverItem 25, serverField 6, shownError 1.5, uncaught 1.0, relation 0.8, relationFinal 2.0, wasted 0.08, latency 0.25 | `cost.ts` | cost weights | +| `LABEL` | object | tier {passive 0, guard 0.25, heal 0.5}, exactTie 1.5, tieEps 0.05, tau0 0.1, seMul 1.0 | `cost.ts` | soft labels; an action missing from `TIER` gets the heal premium and `meta.tiers` value `heal`; `adjusted`/`se` rounded to 3 dp, `dist` to 4 dp | +| cost volatile keys | set | client: `id version rev revision etag updatedAt updated_at clientId pending seq`; server snapshot: `version updatedAt updated_at rev etag seq` | `cost.ts` (`VOLATILE`), `server.ts` (`VOLATILE`) | ignored when comparing list items / server items | +| server history | number | 64 pre-write snapshots per resource key | `server.ts` -> `Db.recordWrite` | replica-lag lookback | +| arrival windows | number | global list <= 512 (oldest 256 dropped when exceeded), per signature <= 256 (oldest 128 dropped); load window 1000 ms | `network.ts` -> `noteArrival` | capacity and rate-limit counting | +| transform | probs | 50% unchanged; else drop one non-passive non-best action p 0.12 (needs >= 3 options), shuffle p 0.5 | `transform.ts` | option order/subsets | +| diagnosis-only rows | count | <= 3 per trajectory | `trajectory.ts` | - | +| ask questions | count | 1-3 per probe, 11 generators | `ask/questions.ts` | - | +| loop limits | number | 2,000,000 tasks per `runUntil`; 1000 `afterTask` re-arms | `loop.ts` | `LoopError` -> trajectory exception | +| `BASE_URL` | string | `https://app.example.test` | `network.ts` | app origin | +| app timeouts | ms | cart add/qty 8000, toggle 8000, counter 6000, board 8000, settings 8000, chat 10000, bulk 10000, list 9000, nav 10000, auth 8000, beacon 5000, heartbeat 4000 | feature files | `timeout` outcomes | + +## Invariants and gotchas + +- **Never use unkeyed randomness or real time in world code.** No `Math.random`, `Date.now` or `performance.now` + inside a run (`performance.now` is only for trajectory/smoke timing stats, `Date.now` only for the CLI's timing + and progress log). Use the + spec rng in `make`, `user.rng` in `session`, the `rng` passed to `external`, and at run time + `env.rng.fork(<key derived from the intent>)` (e.g. idempotency keys `env.rng.fork("idem", ref)`). A draw whose + order depends on the forced action shifts unrelated draws and breaks futures or the prefix check. +- **Request draws are keyed by `(seed, identity, occurrence)`** (`identity = method + path + search + body`). Two + requests with identical identity share an occurrence counter; adding a request in a cf run only shifts later + occurrences of the same identity. +- **Server ids are content-derived** (`Db.makeId`: hash of the `db-<seed>` salt, collection, create key (the + canonical/JSON body or a feature-chosen key such as `seed:<name>` or `line:<productId>`), and how many identical + keys were created before). The same intent gets the same id in every run; a duplicate gets a new one. Changing + a create body format changes ids. +- **`runtime.situation()` must stay side-effect free**: ask probes run only in the base run; if a probe consumed + runtime ids, every cf prefix would mismatch (NEEDS item 5). +- **Correlation is synchronous.** `know.callingOp` / `know.writing` / `know.callingIntent` are set only around the + synchronous `fetch` / `atom.set` / `runtime.user` call; the runtime's `opCreated` / `mutationProposed` hooks must + fire inside those calls. If a correlation fails, `subject.kind` is `unknown` and the row loses its diagnosis label. + Phase A: 100% correlated (`subject_correlated`). +- **`x-request-id` is the correlation channel.** The runtime ignores it for identity and never prints it; + `sim/test/rows.test.ts` asserts no `x-request-id` / `req-xxxxxxxx-` text appears in any `state`. Changing the + header requires it to remain in the runtime's volatile header list. +- **Gate thresholds must stay 0.5** with `requireDiagnosis: false`: the decider puts probability 1 on the forced + action; with 0 the gate would run the argmax non-passive action even when passive is forced. +- **Task owners matter.** Exceptions in `app`/`user` tasks become app uncaught errors (`window.onerror`, reported via + `runtime.reportError`); exceptions in `net`/`runtime`/`sim` tasks (and in `afterTask` hooks) are internal errors and + drop the trajectory (ideal or base run) or the decision point (cf run). +- **The ideal run has no runtime** and skips accidental and `when`-conditional steps; app-generated duplicates + (`dupOf`) share the original result. Features must set `dupOf`/`accidental` correctly or the ideal world contains + the duplicate. +- **Store weights shape the oracle.** Set per feature with `weightsOf` in `env.store(...)`. Error-message fields are + always 0 (errors are charged as episodes; a branch must never win by hiding a message); typical values: data lists + 1, totals/placed 0.8, counts 0.4-0.6, inputs/drafts/filters/view 0.3-0.5, saved flag 0.3, loading/busy flags 0.1-0.12, + versions 0. A field missing from the weights counts 1. +- **`DATA_ROLES`** (`diagnose.ts`) gates the "superseded intent -> stale" rule for mutations. A new feature role that + applies server data must be added there. +- **Calm warm-up is partial.** Only outages, slow periods and server bugs start after `warmup`; random transients, + spikes, network errors, capacity, rate limits and replica lag apply from t = 0. +- **Compact questions at budget 1000.** The runtime prints bare labels/names (null descriptions) when the budget is + <= 1400 and keeps a vocabulary override only if it is <= 24 characters; every diagnosis paraphrase and most action + paraphrases are longer (a few, e.g. `send it now`, are not), so wording randomisation mostly affects 2000/3200 rows + (label subsets still apply). +- **Scenario changes ripple to every seed.** Adding a domain, a feature, a weight or an rng draw in `buildScenario` + changes the keyed picks (e.g. `R.fork("domain").pick(DOMAINS)` depends on the array length), so the same seed yields + a different program. Do not mix rows from different sim versions under the same seed range. Splits stay + consistent across machines and versions only while `TEST_DOMAINS`, `TEST_PATTERNS` and the hash salts + (`family-split-v1`, `dev-split-v1`) are unchanged; every seed's world also depends on `scenario-v1` and the other + stream keys listed under [Concepts](#concepts-and-data-structures). +- **`stats.json` is per run**; parts mode writes `stats.session.json`; use `scripts/analyze.py` for totals. +- **The VM path.** The team never ran the sim on the 8 GB Mac (`scripts/vm.sh` header); agents ask the user before + running sim tests or generation. `scripts/vm.sh` needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are + not in the repo. `scripts/vm.sh run sim` rsyncs with `--delete` but + excludes `/sim/out/` and `dist/`, so outputs survive and builds must be redone on the VM. On the VM the repo is at + `~/gcl/sim`, so outputs land in `~/gcl/sim/sim/out/...` (the paths `training/import_*.sh` use). +- Exploration answers a fake diagnosis (`meta.fake_diagnosis: true`) when forcing a non-passive action on an + `expected` situation; later rows of that trajectory can contain the effects of explored actions + (`meta.explored_before`). +- **Non-parts vs parts determinism.** Non-parts mode hands out 2-seed batches on demand, so which seeds near the end + are included depends on worker scheduling. Parts mode uses fixed seed ranges (`seed + i*chunk`), so finished + parts are reproducible; only how many parts finish before `--rows` is reached varies. +- **`analyze.py` prefers merged files.** It reads `<dir>/<split>.jsonl` when present and only falls back to + `parts/part-*.<split>.jsonl`; after a `merge-b`, newer parts are ignored until you merge again. +- **`benign` noise count quirk.** `make()` loops `for (i = 0; i < rng.int(0, 2); i++)`, re-drawing the bound every + iteration, so `noise:0/1/2` occur with p 1/3, 4/9, 2/9 (not uniform). Fixing it changes every benign world. +- **Slug-id programs (idStyle slug, weight 1/9).** The sim's `sigOf` keeps slug ids literal, so for those programs + failure `streak`s are per item and the request rule's `clientRate(network, sigOf(op))` (compared against route + signatures with `:id`) never matches item URLs; since `anomaly: "storm"` never reaches an op, such item requests are + never diagnosed `overload` by the request rule. +- **Ideal run and futures.** The ideal run has no decider, so `future.k = -1` only moves external events; ideal + network draws are trivially 0. The ideal run is re-done per future only when an external event lies after `t_k`. +- **The cost's initial state** for both runs is the *real* run's first snapshot (`runCost`), and the window ends at + `min(tEnd, t_k + 15000, real.tStop)`; relation areas and `area` use the 10 s horizon, finals use `stop`. + +## How to change it safely + +Before any change: read the matching test in `sim/test/`. After it (ask the user first; +[where to run things](runtime/build-test-release.md#where-to-run-things)), the team ran on the VM: +`npm run build:runtime-core && npx tsup`, `SIM_RUNTIME=real npx vitest run`, `node dist/smoke.js --seeds 40` (check `internal errors`, correlation +`*:none` counts), then a small `gen.js` run and `analyze.py`. + +1. **Add a feature combinator.** New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef`; register in + `FEATURES` and `FEATURE_WEIGHTS`. Server routes via `srv.route(method, naming.route(...), handler, {feature, kind, + idempotent, resource})` (resource `c:`/`d:`/`n:` keys enable replica lag). Client: `env.store(name, s.id, init, + {weights, resync})`, requests only via `kit.op` + `kit.call`, writes only via `kit.write` with `role`, `intent`, + `key`, `op`; set `dupOf` for accidental repeats, `anomaly: "partial"` on writes of paths that skip derived fields + (an `anomaly` passed to `kit.op` is silently dropped: `OpInit` has no such field; add it to `OpInit` and `Kit.op` + if an op-level anomaly is needed), `classify` + where content bookkeeping (`ContentBook`) decides stale/conflict/duplicate; declare `relations()` for derived + fields; `cond()` for `pendingCond` re-clicks. Surface failures with `kit.shownError()` (charged as an error + episode) or `kit.spawn(fn, "uncaught", {cause, diagnosis, op})` (becomes an `error` trigger); use `"swallow"` for + handled background work. Add new data roles to `DATA_ROLES`. Consider adding a held-out pattern to + `TEST_PATTERNS`. Every seed's world changes: regenerate all data and samples. + + *Adding a knob to an existing feature:* append the draw at the end of `make()` if you can: draws come from one + stream (`rf.fork("make")`), so inserting one in the middle shifts every later knob of that feature. A new + `naming.field(role, scope)` call draws from the program-wide naming stream (`rP.fork("naming")`, shared by all + features of the program), so it also changes field names picked later by other features. New tags in + `pattern()` change `meta.patterns` and possibly the test split (via `TEST_PATTERNS`). +2. **Add or edit a domain.** Append `D(...)` in `sim/src/app/vocab.ts` (2 entities via `E(...)`); hold it out via + `TEST_DOMAINS` if desired. Changes every seed's domain pick. +3. **Change cost weights (`W`).** Totals change; regenerate data. Re-check `sim/test/oracle.test.ts` and the README + formula. Changing only `LABEL` (premiums, tie, tau) can be re-derived offline from `meta.cost_futures` with + `actionLabel` (same pairing), without re-simulating; re-apply any option drop recorded in `meta.transform` + (`drop:<action>`), because `cost_futures` keeps every offered action. +4. **Change a diagnosis rule.** Edit `diagnose`/`diagnoseFailure` or a feature's `classify`; diagnosis does not + affect costs, but it affects exploration (`eps` vs `eps/4`), point sampling (x1.5) and `fake_diagnosis`, so action + rows can change too. Update oracle tests' expected diagnoses. +5. **Change chaos or network behaviour.** `makeNet` (parameters) and `Network.send` (mechanics). Keep every draw + keyed (`Rng(hashAll(seed, [salt,] ...))`), keep ideal-mode draw counts stable, and keep `NetEntry.cause` / + `slowCause` accurate: diagnoses read them. +6. **Add an ask question.** Add a generator to `GENS` in `sim/src/ask/questions.ts` returning `{qid, question, label, + kind}`; check the evidence appears in `text` (the serialized state) and skip borderline timings; labels must be + valid for the question type (`rows.test.ts` checks this). +7. **Change budgets.** `budget` weights in `buildScenario`; keep `meta.budget`; coordinate with TRAIN (per-budget + eval in `training/eval_runtime.py`) and the runtime's auto budgets. +8. **Change the runtime contract** (option names, thresholds, hooks). Edit `createOptions` and the structural types + in `rt.ts`/`types.ts`; run `SIM_RUNTIME=real` tests (the two real-only oracle tests and the determinism suite). +9. **After any runtime situation change** (`packages/runtime/src/situation/*`): rebuild the runtime core, regenerate + all datasets and `sim/samples/*` (`node dist/gen.js --sample --workers 8`), tell TRAIN (and update + `training/curriculum/rt.py` mirrors). Data trained so far uses tag `situation-v1`. +10. **Produce final data.** `bash sim/scripts/final.sh a` (600k rows, seeds from 10,000,000, `out/final-a`); + `bash sim/scripts/final.sh b` (1.4M rows, seeds from 50,000,000, parts of 100 seeds, resumable after the 03:00 UTC + VM shutdown); `final.sh merge-b`. To split across machines give disjoint seed ranges (phase A: about 5.8 rows + per seed, counting test-subsampled seeds). +11. **Change splits.** Edit `TEST_DOMAINS`, `TEST_PATTERNS`, or the salts/percentages in `familyHeldOut` / `splitOf`. + This moves whole trajectories between splits, so previously generated datasets become incomparable; rerun + `rows.test.ts` (split counts over 400 seeds) and regenerate. + +## Tests + +(Ask the user first; [where to run things](runtime/build-test-release.md#where-to-run-things).) The team ran on the +VM: `cd sim && SIM_RUNTIME=real npx vitest run` (17 tests; without `SIM_RUNTIME=real` the suites use the +fake runtime and the two real-only tests are skipped). + +| test file | test | what it asserts | +|---|---|---| +| `sim/test/loop.test.ts` | orders macrotasks / drains microtasks | (time, seq) order; microtask chains and `afterTask` hooks run before the next macrotask; `now` ends at `tEnd` | +| | Response bodies within one macrotask | `Response.clone().json()` settles before the next macrotask | +| | keyed rng forks | `fork(label)` independent of prior draws | +| `sim/test/determinism.test.ts` | same seed -> identical rows | seeds 11-13: identical rows, 0 `prefix-mismatch`, identical final client/server state and `fp` lists | +| | replay reproduces every prefix | seeds 100-129, skipping bases with < 2 decisions (no new seed once >= 12 checks): forcing each action at decision indices 0, mid and last reproduces all `fp <= k`; asserts > 5 checks | +| `sim/test/rows.test.ts` | valid CONTRACT-D rows | 40 trajectories: no base errors, no prefix mismatch, > 40 rows, ask + >= 2 other triggers, labels reference offered options, dists sum to 1, no `x-request-id` text, passive best on > 20% of decision rows | +| | splits and transform | 400 seeds: > 40 test, > 150 train; transform keeps passive and best, renormalises the dist over remaining options | +| `sim/test/oracle.test.ts` | stale overwrite | search without guard: diagnosis `stale`, `discard` cheapest and label best | +| | one stale write among later stale writes | discarding one write still cheaper than apply; best in `discard`/`defer` | +| | intentional double add | counter increment: request diagnosis `expected`, `send` cheapest, `coalesce` > send + 1 | +| | duplicate POST after committed timeout | form retry without key: `duplicate`; `block`/`coalesce` beat `send` | +| | outage failure streak | poll during 503 outage: request diagnosis `failing`; `delay`/`serve_cached` beat `send` | +| | benign concurrency | cart server mode, two adds: `expected`, best `apply` | +| | label sharpness | `actionLabel`: sharp (> 0.95 non-passive) when futures agree, soft (passive > 0.15) when they disagree, passive > 0.9 when interventions slightly harmful | +| | exact ties | ties -> passive (> 0.95); dist sums to 1 | +| | (real only) partial-update invariant break | cart `skip-rollback` + outage: inconsistency diagnosis `inconsistent`; `rollback`/`resync` beat `ignore` | +| | (real only) duplicate token refresh | auth per-request refresh: request `duplicate`; `coalesce` beats `send` | + +Helpers (`sim/test/helpers.ts`): `testFactory`, `mini(kind, patch, opts)` (one-feature calm scenario with exact +latencies via `latencyFn`, optional outages), `step`, `runBoth`, `argmin`, `find`. `mini` = `buildScenario(4242, +{kinds:[kind], chaos:"calm", duration: opts.duration ?? 6000, domain: opts.domain ?? "commerce"})` with `patch` +merged into the spec, scripted steps (feature `f0`), no external events / ask probes / vocabulary overrides, +`tEnd = duration + 3000`, latencies read 80 / write 120 / auth 80 / upload 300 / bulk 200 ms with sigma 0, and no +spikes, transients, network errors, slow periods, bugs, rate limits, capacity or replica lag. Trajectory tests use +`maxPoints` 3 (determinism) or 4 (rows), `askRows: true`, `testKeep: 1`, `exploreScale: 1`. + +### Sample stats (`sim/samples/`) + +- `stats-final-a.json` (phase A, frozen runtime, seeds from 10,000,000, 56 workers): 600,676 rows (train 448,420 / + dev 14,613 / test 137,643), 104,116 trajectories (32,729 skipped by test-subsample), 2,401,160 runs, 2,443.8 s, + 245.8 rows/s, 937 families, drops only `diagnosis-not-in-vocab` 4,219, 0 errors. +- Trigger mix: ask 23.8%, mutation 23.3%, request 17.2%, failure 14.7%, stall 9.1%, inconsistency 5.5%, error 3.6%, + transition 2.8%. Most stall/error and a third of transition rows are diagnosis-only. +- Passive best (train): mutation 88.1%, request 74.3%, failure 70.4%, stall 64.0%, inconsistency 83.8%, transition + 85.9%, error 99.0%. +- Train diagnoses: mutation expected 49.8 / stale 17.5 / duplicate 14.1 / conflict 9.7 / inconsistent 8.4 / unusual + 0.5%; failure transient 53.6 / failing 39.1 / slow 5.8 / overload 1.5%; inconsistency expected 90.7 / inconsistent + 9.3%; stall slow 90.7 / failing 9.2%; request expected 70.9 / duplicate 16.9 / failing 10.0 / overload 1.4 / + stale 0.8%; transition expected 43.9 / failing 30.0 / transient 13.5 / unusual 6.1 / slow 6.1 / overload 0.3%; + error failing 94.8 / overload 4.1 / slow 0.7%. +- Per budget (state chars p50/max): 1000 -> 994/1069; 2000 -> 1854/2132; 3200 -> 2438/3387. Token estimate + (chars/3.6 of state+questions) p50 726, p99 1206, max 1262 (an estimate only: TRAIN measured ≈ 2.4 chars/token + with the runtime's pruned tokenizer, training/NEEDS.md 6a, so real counts are ≈ 1.5× higher). Rows per budget: 1000: 180,010; 2000: 180,232; + 3200: 240,434. +- Labelled points: 389,393 (all correlated), 29.9% after exploration; 3,464,871 decisions seen in base runs. + Points with 3 futures (adaptive): failure 43%, request 54%, stall 66%, mutation 19%, inconsistency 22%, + transition 26%, error 2%. Label sharpness (`label_sharpness`): passive-best rows with passive mass >= 0.9: + mutation 93%, request 68%, failure 87%, stall 71%; intervene-best rows with non-passive mass >= 0.95: mutation + 57%, request 32%, failure 60%, stall 52%, inconsistency 66%. +- Ask questions asked (phase A): `write_inflight` 33,851, `route` 33,826, `pending_count` 33,576, `any_inflight` + 33,559, `user_waiting` 32,773, `user_recent` 30,993, `recent_failure` 30,314, `fail_count` 27,996, `last_failed` + 22,409, `last_save` 4,271, `slowest` 1,835. +- `sample-stats.json` (`--sample`, seed 1000, 8 workers): 994 rows (train 630, test 364; no dev), 116 trajectories. + +## Drift and open issues + +- **README limitation 5 is stale.** It says `conflict` rows are under 1% of mutation rows because the runtime does + not flag a remote write over a pending local change (NEEDS f). The runtime now has the pending-local-change fact + (`packages/runtime/src/situation/facts.ts`; STATUS "SIM requests a-f: DONE") and phase A has `conflict` on 9.7% of + train mutation rows. +- **`sim/NEEDS.md` is stale.** Observations a-f are still listed as ASK (STATUS: all done in batch 3); the note that + `transient` is missing from the runtime's `DEFAULT_DIAGNOSES` is false (it is there, last), so the fallback in + `realRuntimeFactory` is inactive. Its header's `createRuntime` options (no `websocket`, thresholds 0) differ from + `createOptions` (websocket on, guard/heal 0.5, `model: false`, `historySize: 500`). +- **README "every [ask] generator checks that its evidence appears in the situation text"**: only `last_failed`, + `route` and `slowest` check the text; `recent_failure`, `fail_count`, `user_waiting`, `user_recent` skip + borderline timings; `write_inflight`, `any_inflight`, `pending_count` (skips > 6), `last_save` check nothing. +- **README "calm warm-up of 30-60%"**: only windowed chaos respects it (see gotchas). +- **README limitation 6** ("genuine relation breaks ... about 4% of mutation rows"): phase A has 8.4% of train + mutation rows labelled `inconsistent` (from `anomaly: "partial"` writes, not a relation check). +- **README cost formula omits the caps** in `serverDist` (5 extra/missing and 5 changed items per collection, 3 + fields per doc, 3 units per counter, `*beats` counters ignored). It also does not say that the latency term is + absolute (unlike the error and wasted-request terms, it is not relative to the ideal run). +- **Code comments:** `rt.ts` header says the fake runtime lives in `test/fake-runtime.ts` (it is + `src/run/fake-runtime.ts`); `NetEntry.simOp` mentions an `x-sim-op` header (renamed to `x-request-id` after + `situation-v1`); `gen.ts` header shows `--test-keep 0.5` and "~12" examples (defaults 0.33 and up to 16) and omits + `--parts/--chunk/--merge-only`; the `diagnoseFailure` comment says a spike-caused timeout is `transient` (code: + any timeout outside a slow period/overload is `slow` once streak >= 2, else `transient`); `Persona.typoP` says + "per word" (code: `typoP/6` per non-space character). +- **Slug ids:** the `server.ts` comment in `Db.makeId` ("the runtime does not treat it as an id") and NEEDS + observation e predate batch 3; the runtime's `isSlugId` (`packages/runtime/src/util.ts`) now normalises slug ids + whose suffix starts with a digit or alternates letters/digits twice (STATUS "e"), so only part of the sim's + slug-id programs keep per-item signatures. +- **Poll `storm` anomaly never reaches the oracle (code bug).** `sim/src/app/features/poll.ts` passes + `anomaly: "storm"` to `kit.op` for tight retries, but `sim/src/app/kit.ts` -> `Kit.op` copies only the `OpInit` + fields, so `SimOp.anomaly` is never set. The README ("overload (storm code path, ...)"), the `diagnoseFailure` + comment and the three `anomaly === "storm"` checks in `diagnose.ts` assume it is. Fixing it changes diagnoses (and, + through exploration and point sampling, action rows) of tight-poll programs: regenerate data. +- **`RunOptions.explore` doc comment** in `runner.ts` ("Decisions >= this index take the passive action") describes + counterfactual futures, not the exploration policy it annotates. +- **README flag list** omits `--parts`, `--chunk`, `--merge-only` (only `final.sh b` mentions parts mode) and says + "about 5.7 rows per trajectory" (phase A: 5.77 rows per seed incl. test-subsampled seeds, 8.4 per simulated + trajectory). +- **CONTRACT §11** asks to randomise diagnosis paraphrases/subsets "per row"; the sim does it per trajectory + (scenario) through the runtime's `vocabulary`, and only option order/subset is per row (`transformQuestions`). +- **`docs/runtime/ARCHITECTURE.md`** lists "uploads" among the 15 combinators; there is no upload feature (`upload` + is only a latency kind no route uses). +- **CONTRACT §11** calls the ideal world "serial"; the sim's ideal run is zero-latency and failure-free, not + explicitly serialised. +- **training/NEEDS.md item 3** (marked DONE there) asks for `meta.passive`, `meta.program_family`, `meta.action_names`; the sim emits + `meta.family` (program family) and `meta.tiers`, no `passive` (derive from `PASSIVE`), no `action_names` (option + keys are never renamed). Item 4 (clean-run rows, `meta.clean`) is not implemented. +- **Budgets:** the runtime's auto budget also yields 1,333 / 1,667 (2-3 WASM threads); the sim samples only 1000 / + 2000 / 3200. +- **Sim changed after the freeze tag:** `git diff situation-v1 HEAD -- sim/src` shows the header rename, thresholds + 0 -> 0.5, budget 1100 -> 1000, parts mode. `packages/runtime/src` is unchanged since the tag (only the runtime's + README, package.json, LICENSE and a smoke test changed). `stats-final-a.json` `args` lack + the parts keys, so phase A ran on a `gen.js` before parts mode (exact commit unverified). +- **Dead code:** `u01`, `keyedLognormal` (`rng.ts`), `relationMatches` (`diagnose.ts`), `searchLabel`, `listKey`, + `sleepJitter`, `ROUTE_WORDS`, `Network.committedBefore`, `Knowledge.inflight`, `Knowledge.appliedReadStart`; + `Knowledge.localChange` and `errorList` are written but never read; `runCost` has a no-op ternary + (`real.tStop <= stop ? real.server : real.server`). +- **Label-quality limitations** (README "Known limitations", still accurate unless noted above): only K = 3 futures + (noisy SE; `meta.cost_futures` allows re-derivation); the failure-free ideal can be unreachable after a real + failure; diagnosis and action are labelled independently (e.g. `expected -> coalesce`, kept passive by the + runtime gate); `defer` is scored as defer-then-apply; thin classes (transitions about 3% of rows); token lengths + are estimates; ask labels are imbalanced (phase A: `q_user_waiting` 92% "no", `q_write_inflight` 71% "no"). +- **Open work (OPEN_TASKS.md):** phase B (1.4M rows) in progress, resumable; training round 2 uses phase A + B. + +## Related docs + +- [model-io-contract.md](model-io-contract.md): row -> packed request -> heads -> calibrated answers. +- [training.md](training.md): how rows are imported (`training/import_final.sh`), trained on and evaluated. +- [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): the facts, triage and serializer that + produce every `state` the sim records. +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): the gate the forced actions pass through. +- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): ops, `opCreated`, causality used for correlation. +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `createRuntime` options. +- [runtime/build-test-release.md](runtime/build-test-release.md): VM workflow, how `sim` consumes the runtime build. +- [demos.md](demos.md): the independent external test (never modelled by the sim). +- [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [repo-map.md](repo-map.md). +- Source docs: [../../sim/README.md](../../sim/README.md), [../../sim/NEEDS.md](../../sim/NEEDS.md), + [../runtime/CONTRACT.md](../runtime/CONTRACT.md) §11 and §13. diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md new file mode 100644 index 00000000..d1378a67 --- /dev/null +++ b/docs/agents/status-and-known-issues.md @@ -0,0 +1,642 @@ +# Project status, ground rules, open work, known issues and doc drift + +> **Scope:** `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `demos/NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, +> `packages/runtime/UI-NEEDS.md`, `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md`, `README.md`, +> `packages/runtime/README.md`, git history and tags, code TODO markers. Cross-checked against +> `packages/runtime/src/**`, `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime/package.json`, +> `training/{LOG,EVAL}.md`, `sim/README.md`, `sim/samples/stats-final-a.json`, `demos/results.md`. +> **Read this when:** you land in the repo cold and need to know what is shipped, what is in flight and who owns it; +> before any change that could break a binding rule (situation text, determinism, dependencies, where to run builds); +> before trusting `docs/runtime/*.md` or a README over the code; when you finish work and must update STATUS/NEEDS/OPEN_TASKS. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +Path convention in this doc: `src/…`, `test/…` and `bin/…` are relative to `packages/runtime/`; bare runtime module +paths (`runtime.ts`, `types.ts`, `util.ts`, `index.ts`, `state/hub.ts`, `situation/build.ts`, `decide/policy.ts`, +`model/host.ts`, …) are relative to `packages/runtime/src/`. Every other path is from the repo root. + +- **Shipped:** `@genclass/runtime@0.1.0-alpha.0` on npm (per `OPEN_TASKS.md`; registry not re-checked). Runtime core, + model host, devtools and adapters are built and tested (STATUS: 37 files, 300 tests passing on the VM). Re-run + on 2026-10-07 without a model directory: typecheck clean, `tsup` build OK, 286 tests passed and the 14 + model-file tests skipped (see [Gotchas](#gotchas)). +- **Not shipped:** the trained runtime model. `DEFAULT_MODEL_BASE_URL` (`src/model/host.ts`) points at + `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, a package that does not exist yet + (`packages/runtime-model/` holds only `MODEL_CARD.md`). A default `GenClass.init()` therefore ends with model status + `error`, prints `[GenClass] Model unavailable (...); observing only.`, and from then on never consults the model or + takes an action (only while the status is still `off`, before the idle preload starts, are salient situations built, + and those fail open). It still traces, learns baselines/invariants/profiles and answers `rt.situation()`. No runtime + test covers this default path. +- **Frozen:** the situation format is frozen at tag `situation-v1` (commit 1a77558). `git diff situation-v1 HEAD -- + packages/runtime/src` is empty at 654d822. The final training data (SIM phase A, 600k rows) was generated from it. + Any change to text the model reads breaks parity with that data. Only the runtime source is frozen: sim, training + and demos changed after the tag (59c213f, 654d822). +- **In flight at 654d822:** SIM phase B data (1.4M rows), TRAIN final round 1 (R17 and R32 on phase A), DEMOS screenshot + tour. **Next:** choose R17 and/or R32, publish `@genclass/runtime-model@0.1.0` and a GitHub release, then + `@genclass/runtime@0.1.0`, add CI, then re-run the demos with the trained model. +- **Binding rules** (CONTRACT §0, §0.5): no hardcoded bug rules (facts and triage only; the model decides), one + situation implementation shared with the sim, determinism via the injected `Clock`, sim and demos never read each + other, builds/tests/models run only on the `train` VM (the 2026-10-07 run policy in AGENTS.md relaxes this for + light checks on other machines; see [ground rule 5](#ground-rules-binding-contract-0-and-05-restated) (Mac safety, + CONTRACT §0 rule 5; current policy in [../../AGENTS.md](../../AGENTS.md) §4)), no new runtime dependency besides + `onnxruntime-web`, precision first. +- **Workstreams:** lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW. They talk through `STATUS.md` (CORE's state) and + per-workstream `NEEDS.md` files (requests with OPEN / ASK / DONE status; sim/NEEDS and training/NEEDS say they are + "relayed by the lead"). +- **Biggest open product risks:** holding writes can reorder them behind a newer user write (board demo: +56% visible + jump-backs with zero actions, `demos/NEEDS.md` §1); holds add latency to typeahead-like apps (§2); `retry` is offered + for non-idempotent POSTs (§5). All three are open in code. +- **Docs drift a lot.** CONTRACT.md was last edited in a53dd38, before batch 3 landed (it already specifies the + summed-mass §8 gate and `transient`, but none of STATUS's deviations); READMEs, STATUS, UI-NEEDS and sim/NEEDS each + have stale items. The full list with evidence is in [Drift and open issues](#drift-and-open-issues). There are + **no** TODO/FIXME/XXX/HACK comments in code. + +## Files + +| path | role | key content | +|---|---|---| +| `OPEN_TASKS.md` | Project-level status (owner inferred: lead) | Done / In progress (1–2) / Next (3–8) / Needs the user / Known risks | +| `packages/runtime/STATUS.md` | CORE's status, read by SIM, DEMOS, UI, MODEL | test state, batch 3 changes, headless recipe, trigger table, example situations, **Deviations from the contract**, **Open issues** | +| `docs/runtime/CONTRACT.md` | Binding build contract (lead) | §0 ground rules, §0.5 product principles, §1 layout and owners, §2–§12 spec, §13 approved additions | +| `docs/runtime/API.md` | Public API reference | options, state, ops, ask, events, triggers/actions, policy, reports, plugins, headless, types | +| `docs/runtime/ARCHITECTURE.md` | Design overview | principles, data flow, training and evaluation summary | +| `packages/runtime/UI-NEEDS.md` | UI → CORE requests | Open (1–2), Nice to have (3), Done | +| `sim/NEEDS.md` | SIM → CORE requests and observations | Requests 1–5 (DONE), observations a–f (marked ASK), SIM notes | +| `training/NEEDS.md` | TRAIN's needs from SIM, CORE, MODEL; MODEL → TRAIN notes | items 1–10, 6a; TRAIN status for frozen data | +| `demos/NEEDS.md` | DEMOS → CORE/MODEL/UI/lead | §1–§8 evidence-backed product issues from traced Playwright runs | +| `README.md` | Repo landing page | install, status banner, repo map, how it works | +| `packages/runtime/README.md` | npm package README | status banner, modes, adapters, privacy, limits | +| `packages/runtime-model/MODEL_CARD.md` | Model card for the unpublished `@genclass/runtime-model` (lead) | R17/R32 sizes, stage-1c accuracy, limits | +| `training/LOG.md`, `training/EVAL.md` | TRAIN's dated log and results | stage 1c, stage-2 pilot, final round 1 launch (EVAL final section "(in progress)") | +| `demos/results.md`, `demos/results.json`, `demos/results-summary.json` | Demo trial results with the **v0.1** model (generated 2026-10-07T19:30Z) | bug rate, false interventions, latency per demo and mode | +| `training/README.md`, `sim/README.md`, `demos/README.md`, `src/model/README.md` | Per-workstream READMEs | owner lines ("Owner: TRAIN", "Owner: MODEL"), sim "Known limitations" 1–8, demos "Honesty rules", MODEL measurements | +| `sim/samples/stats-final-a.json` | Stats of SIM final phase A | rows per split/trigger, diagnosis counts, passive-best fractions | +| `scripts/vm.sh` | The team's way to build/test per CONTRACT §0 rule 5 (`sync`, `run`, `exec`, `get` per SLOT); light checks may run locally under the run policy in AGENTS.md ([ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)) | needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure` (not in repo) | +| `packages/runtime/test/review-*.test.ts` | REVIEW's regression tests (10 files) | must pass unchanged | +| `packages/runtime/test/smoke/smoke.sh` | npm tarball smoke test (Vite app, headless Chromium) | runs with `model: false` | +| `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/SPEC.md`, … | **Legacy jev-local docs**, not the runtime contract | CONTRACT §1: "stays as is. Do not edit it." | + +## Concepts and data structures + +### Workstreams and ownership + +| workstream | owns (edit rights) | writes | reads / serves | +|---|---|---|---| +| **lead** (also "LEAD", "coordinator") | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`; `training/` per CONTRACT §1; `OPEN_TASKS.md` (inferred: the file has no owner line) | contract changes (§13 "Additions (approved …)"), approvals of deviations and dependencies, merges, publishing | relays sim/NEEDS and training/NEEDS (titles say "relayed by the lead"); reads demos/NEEDS ("Read by CORE, MODEL, UI and the lead"); answers UI-NEEDS 2 | +| **CORE** | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; owns `src/situation/*` wording and `src/types.ts` | `packages/runtime/STATUS.md`, `docs/runtime/API.md` (inferred: CONTRACT §1 names no owner for API.md; it was last changed in CORE's batch 3) | sim/NEEDS, UI-NEEDS, demos/NEEDS, training/NEEDS (CORE → TRAIN) | +| **MODEL** | `packages/runtime/src/model/**`, `bin/genclass-runtime.mjs`; co-owns the "model seam" section at the top of `src/types.ts` | `src/model/README.md`; MODEL → TRAIN entries in training/NEEDS | training/NEEDS (MODEL items) | +| **UI** | `src/devtools/**`, `src/adapters/**` (CONTRACT §13; §1's table still says CORE) | `packages/runtime/UI-NEEDS.md` | STATUS "For UI" | +| **SIM** | `sim/` | `sim/NEEDS.md`, `sim/README.md`, data under `sim/out/` (gitignored) | STATUS, training/NEEDS (SIM → TRAIN) | +| **DEMOS** | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*.{md,json}` | STATUS | +| **TRAIN** | `training/` (`training/README.md`: "Owner: TRAIN") | `training/NEEDS.md`, `LOG.md`, `EVAL.md` | sim output, MODEL card format | +| **REVIEW** | `packages/runtime/test/review-*.test.ts` | 34 findings (all fixed in batch 3) | runtime code | + +Separation rule (CONTRACT §0 rule 4): SIM and DEMOS are built by different people who do not read each other's code. + +### Communication file conventions + +- **`STATUS.md` (CORE).** Header `Updated: <date> (<batch>). Owner: CORE. SIM, DEMOS, UI and MODEL read this file.` + Sections: State (VM test command and counts), the latest batch's changes grouped by origin (REVIEW findings, SIM + requests, contract changes), "How to drive it headless", per-consumer notes ("For UI"), trigger/triage table, + example situations copied from tests, **Deviations from the contract (and why)**, **Open issues**. +- **`NEEDS.md` files.** Live in the *requester's* directory (exception: `UI-NEEDS.md` lives in `packages/runtime/`; + training/NEEDS also carries MODEL's answers and notes to TRAIN, "MODEL → TRAIN (from MODEL)"). + Title states direction ("SIM → CORE requests", "What the demos need from @genclass/runtime", "TRAIN needs"). Status + legend (sim, training): **OPEN** (needed), **ASK** (would help), **DONE** (landed; verified by the requester), plus + **INFO** in training/NEEDS. UI-NEEDS uses sections Open / Nice to have / Done. demos/NEEDS uses numbered sections with + the addressee in parentheses ("(CORE, product risk)") and evidence (traces, seeds, tables). +- **Contract changes.** A workstream that needs the contract changed tells the lead ("do not silently diverge"). Approved + additions are appended to CONTRACT §13; accepted divergences are listed in STATUS "Deviations". §13 ("Additions + (approved 2026-10-07)") holds seven items: `EvaluateRequest.subject` (exposed as `Decision.subjectRef`), + `createRuntime({ hooks })`, `policy.requireDiagnosis`, `vocabulary`, side-effect-free `situation(trigger)` (since + softened by a STATUS deviation), the pruned 16,364-token vocabulary with marker ids read from files, and UI ownership + of `src/devtools/**` and `src/adapters/**`. +- **Batches.** CORE ships in numbered batches: batch 1 (SIM requests 1–5), batch 2 ("model integration, latency, UI + requests" per the a53dd38 STATUS: `situation: { budget }`, `sectionLimits`, auto hold budget, late revert, provider + errors fail open; 239 tests), batch 3 (REVIEW's 34 findings, SIM a–f, summed-mass §8 gate, `transient`, compact + questions) = commit 1a77558. +- **VM slots.** Each workstream builds in its own directory on the `train` VM: `scripts/vm.sh run <SLOT> '<cmd>'` with + SLOT such as `core`, `model`, `sim`, `demos` (`~/gcl/<SLOT>`; slot names `[a-zA-Z0-9_-]` only). `run`/`exec` + commands are wrapped in `timeout $TIMEOUT` (default 1800 s); the sync and `get` steps use fixed 300/600 s timeouts. + `sync`/`run` use `rsync -az --delete` (excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, + `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out/`, `.cache-model/`), + so files created in a slot outside those paths are deleted by the next sync. Use + `scripts/vm.sh get <SLOT> <remote> <local>` to bring results back. + +### Git history (all 13 commits; author Mehar Khanna, every message prefixed "Mehar commit: …") + +| commit | date (−04:00) | what | relevance now | +|---|---|---|---| +| 7a7ff6d, 72ec517 | 2026-10-04 01:58–02:00 | README, Apache-2.0 licence, GenClass vs Jev benchmarks | legacy | +| 3b2121f | 2026-10-04 02:07 | Open-source GenClass: `jev_local/`, server, voice harness, training, benchmarks, `docs/*.md` | legacy content; CONTRACT §1 says do not edit | +| c2ddfa5, 666080e, 58d0f66 | 2026-10-04 09:44–10:59 | Chrome extension v0.1.0 and two store-listing fixes | legacy; holds the v0.1 model card (`extension/src/model/model.json`) | +| 353b0a4 | 2026-10-07 14:18 | WIP runtime core, model host, sim, demos, training scaffolding | first runtime commit; CONTRACT.md created | +| a53dd38 | 2026-10-07 19:02 | Runtime core, model host, devtools, adapters, sim, training, demos (WIP) + `OPEN_TASKS.md` | **last change to CONTRACT.md, UI-NEEDS.md, sim/NEEDS.md** | +| c14151c | 2026-10-07 19:05 | Runtime-first README, package README, ARCHITECTURE.md | only commit touching ARCHITECTURE.md; message understates scope: also changes `packages/runtime/src` (`decide/policy.ts`, `decide/decider.ts`, `situation/{facts,build,questions,env}.ts`, …) and adds `docs/GENCLASS.md` | +| 1a77558 | 2026-10-07 19:19 | Runtime fix batch 3 (34 REVIEW findings, summed-mass gate, `transient`, compact questions) | tag `situation-v1`; last change to STATUS.md, API.md, training/NEEDS.md, `packages/runtime-model/MODEL_CARD.md` and to `packages/runtime/src` | +| 501cec7 | 2026-10-07 19:20 | OPEN_TASKS: runtime frozen, final data and training plan | | +| 59c213f | 2026-10-07 20:09 | Runtime LICENSE, tarball smoke test; also sim (gate thresholds 0.5, 1,000-char WASM budget, op header `x-request-id`, resumable parts, `stats-final-a.json`), training final-round scripts, demos tracing (`demos/e2e/trace-report.ts`, common random numbers) | message understates scope: 59 files | +| 654d822 | 2026-10-07 20:15 | Publish `0.1.0-alpha.0`; READMEs, OPEN_TASKS, demos/NEEDS rewritten (also `training/LOG.md`, two demos files) | HEAD; tag `v0.1.0-alpha.0` | + +The freeze covers `packages/runtime/src` only: `git diff --stat situation-v1 HEAD` lists 65 changed files (demos 27, +training 16, sim 15, `packages/runtime/{LICENSE,README.md,package.json,test/smoke/smoke.sh}`, root `README.md`, +`OPEN_TASKS.md`, `.gitignore`; nothing under `docs/`). The sim changes in 59c213f are, by inference, the code that +produced phase A (`stats-final-a.json` lands in the same commit and its `by_budget` has 1000-char rows). + +### Version markers + +| marker | value at 654d822 | meaning | +|---|---|---| +| `main`, `origin/main`, `origin/runtime` | all 654d822 | OPEN_TASKS still calls the branch `runtime` and asks to merge it into `main` | +| tag `situation-v1` | → 1a77558, message "Frozen runtime situation format for model training" | freeze point for situation text; SIM final data and TRAIN final rounds use it | +| tag `v0.1.0-alpha.0` | → 654d822, message "@genclass/runtime 0.1.0-alpha.0 (npm)" | the published alpha | +| `packages/runtime/package.json` `version` | `0.1.0-alpha.0` | | +| `@genclass/runtime-model@0.1.0` | not created (no `package.json`, `files/` gitignored) | default model location | +| GitHub release `runtime-model-v0.1.0` | no such tag in the repo | the CLI's default `--from` | +| v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** trained for runtime decisions; used by demos and model tests | +| R17 / R32 | 17M / 32M runtime candidates, pruned 16,364-token vocab, int8 (q8) exports 9.58 / 22.47 MB | `training/EVAL.md` | + +### Status at 654d822 + +| item | state | owner | evidence | +|---|---|---|---| +| Runtime core, model host, devtools, adapters | done, frozen | CORE, MODEL, UI | `OPEN_TASKS.md` Done; `git diff situation-v1 HEAD -- packages/runtime/src` empty | +| Runtime fix batch 3 (34 REVIEW findings, summed gate, `transient`, compact questions, word-level redaction) | done | CORE | commit 1a77558; `test/review-*.test.ts`, `test/batch3.test.ts` | +| npm alpha `0.1.0-alpha.0` | published 2026-10-08 (npm org `genclass`, owner meharpro) | lead | OPEN_TASKS Done; tag `v0.1.0-alpha.0` | +| Tarball smoke test | done | lead | `test/smoke/smoke.sh` (commit 59c213f) | +| SIM final phase A | done: train 448,420 / dev 14,613 / test 137,643 rows | SIM | `sim/samples/stats-final-a.json`, `training/LOG.md` | +| SIM final phase B (1.4M rows, seeds from 50,000,000, resumable parts) | in progress | SIM | OPEN_TASKS item 1; `sim/README.md` | +| Stage 1c (curriculum) R17/R32 | done: held-out `rt1` action 98.0 / 98.2%, diagnosis 98.3 / 98.4%, 0 false interventions | TRAIN | `training/EVAL.md`, `MODEL_CARD.md` | +| Stage-2 pilot (pre-freeze SIM r300k) | done: action 77.5 / 78.3% (R32 / R17), diagnosis 90.8 / 91.1%, heal FIR 0.06 / 0.08% but heal recall 1.3 / 1.4% | TRAIN | `training/EVAL.md` "Stage 2 pilot" | +| Final round 1 (phase A) | launched 2026-10-08 00:06–00:12 UTC, training ETA ≈ 01:28–01:30 UTC; eval, calibration and export "by about 02:40 UTC" (OPEN_TASKS 3) by an autonomous tail (`training/final_post.sh` on c02/c09, `training/pull_on_train.sh` on the VM) | TRAIN | `training/LOG.md`; EVAL final section "(in progress)" | +| Final round 2 (phase A + B, longer) | next, after the 03:00 UTC VM shutdown | TRAIN | OPEN_TASKS item 3 | +| Demos (6), Service Worker backend, Playwright harness | built; numbers only with v0.1; `demos/src/server/data/cities.ts` missing (see [demos.md](demos.md#drift-and-open-issues)) | DEMOS | `demos/results.md` (2026-10-07) | +| Choose shipping model(s), device-based selection | next | lead, MODEL | OPEN_TASKS item 5 | +| Publish runtime model + release, then `@genclass/runtime@0.1.0`; CI | next | lead | OPEN_TASKS item 8; no `.github/` directory exists | +| Honest-results docs, model card numbers, dev-only lazy import of the devtools (52 KB min / 17 KB gz) | next | lead | OPEN_TASKS item 7 (the package README already shows the `import.meta.env.DEV` dynamic-import pattern) | +| Public demo hosting (GitHub Pages) | waiting on the user | lead | OPEN_TASKS "Needs the user" | + +## How it works + +### 1. What a default install does today (model unpublished) + +1. App calls `GenClass.init()` in a browser. `src/index.ts` -> `initUnsafe` reads the kill switch (URL `?genclass=`, else + `localStorage.genclass`; `off` installs nothing). Otherwise it sets `model: {}` and calls `createRuntime`. +2. `createRuntime` -> `makeHost` -> `createModelHost` with `baseUrl = DEFAULT_MODEL_BASE_URL`, `preload: "idle"` + (`src/model/host.ts`). Status starts as `{ state: "off" }`. +3. Observers install (`RuntimeImpl.installObservers`). Tracing, field versions, baselines, invariant mining and + transition profiles run from now on, whatever the model state (`RuntimeImpl.settled` has no model check). +4. After `load` + idle (≤ 2 s idle timeout, ≤ 5 s load wait), the host fetches `<baseUrl>model.json` + (`src/model/loader.ts` -> `fetchCard`). The package does not exist, so the fetch fails (expected HTTP 404; not checked + against the live CDN) and no cached card exists: `ModelLoadError("model card download failed: …")`; status becomes `error`. +5. `RuntimeImpl` constructor's `onStatus` listener emits a status report: `[GenClass] Model unavailable (<error>); + observing only.` (`console.info` with `report: "console"`; always delivered to `on("report")`). +6. From now on `RuntimeImpl.consultable()` is false (it is true only for `ready` or `off`): `trigger()` runs the passive + action without building a situation, `gateMutation` never holds. No `Decision`, `Detection` or `ActionRecord` is ever recorded. +7. `rt.ready` rejects with the load error (memoised); `rt.ask()`/`decide()` reject with + `GenClassUnavailableError` (`reason: "error"`), or with the raw provider error when `timeoutMs` is set. +8. There is no automatic retry: the runtime memoises `ready`; `ModelHost.load()` would retry but nothing calls it. + +Before step 4: while status is `off` (idle preload not started), a salient trigger is built, fails open at once +(`trigger()` -> `provider.status.state !== "ready"`) and starts the load (`void this.ready`); while `loading`, +`consultable()` is false and triggers are skipped. To see decisions today, self-host the **v0.1** model with +`npx genclass-runtime fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` and pass +`model: { baseUrl }`. Without `--from` the CLI uses `DEFAULT_FROM` (the unpublished release), which is expected to +fail (not checked against GitHub). v0.1 answers +`unusual` almost always (`demos/NEEDS.md` §8), so its decisions only exercise the pipeline. + +### 2. How a request moves between workstreams + +1. The requester writes an item in its NEEDS file with evidence and a status (OPEN or ASK), addressed to an owner. +2. The lead relays it (and, for a contract change, approves it into CONTRACT §13 or rejects it). +3. The owner lands it in a batch and records it in its status file (CORE: STATUS.md batch section; deviations under + "Deviations from the contract (and why)"). +4. The requester verifies it on the VM and flips the item to DONE with a verification note (example: sim/NEEDS 1–5 + "Verified: 100% of decisions in a 20k-row run correlate…"). +5. If the change alters situation text, SIM and TRAIN regenerate data (STATUS: "Fact and question wording changed again + in batch 3 … regenerate rows"). + +Step 4 is often skipped: several items are implemented but still marked OPEN/ASK (see Drift). + +### 3. How a runtime change reaches the shipped model + +1. CORE changes `packages/runtime/src/situation/*` (or anything that changes the text: `util.ts` formatting, vocab, + op/event names). +2. The lead freezes it with a tag (`situation-v1`). +3. SIM generates rows by driving that exact runtime (`sim/src/run/rt.ts`, `npm run build:runtime-core`). +4. TRAIN mirrors the wording in the curriculum (`training/curriculum/rt.py`), imports SIM rows, trains, calibrates on + dev, evaluates on held-out test, exports q8/fp16 (`training/export_runtime.py`, `training/ortweb/validate.mjs`). +5. MODEL checks parity of the TS packer/engine against the export's `parity.json` (an export artefact, not in the + repo; training/NEEDS, MODEL → TRAIN 7). +6. The lead publishes the model directory as `@genclass/runtime-model@0.1.0` (jsDelivr serves `files/`) plus GitHub + release `runtime-model-v0.1.0`, then publishes `@genclass/runtime@0.1.0`. + +## Configuration and constants + +Status-relevant values only; the subsystem docs list the rest. + +| name | type | value | defined in | effect | +|---|---|---|---|---| +| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default `model.baseUrl`; unpublished → status `error`, observe only | +| `DEFAULT_FROM` | string | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | `fetch-model` default source; no `runtime-model-v0.1.0` tag in the repo (GitHub releases not checked) | +| v0.1 model URL | string | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | `demos/scripts/fetch-model.sh`, CONTRACT §10 | the only model that exists publicly | +| runtime `dependencies` | — | `onnxruntime-web ^1.30.0` only; optional peers `react >=18`, `redux >=4`, `zustand >=4` | `packages/runtime/package.json` | dependency policy (CONTRACT §0 rule 6) | +| `engines.node` | — | `>=20` (VM runs Node 22) | `packages/runtime/package.json`, root `package.json` | | +| `policy.thresholds` | numbers | report 0.6, guard 0.9, heal 0.8 | `src/decide/policy.ts` -> `policyConfig` | precision-first gate | +| `policy.requireDiagnosis` | boolean | `true` | `policyConfig` | non-passive needs top diagnosis ≠ `expected` | +| `policy.holdBudgetMs` | number \| "auto" | "auto" = clamp(1.5 × median of last 20 latencies (else warm-up), 150, 800); 300 if nothing known | `decide/policy.ts` -> `holdBudget`, `HOLD_MIN_MS`/`HOLD_MAX_MS`/`HOLD_FALLBACK_MS` | how long holds last | +| `policy.maxActionsPerMinute` | number | 60 | `policyConfig` | rate limit | +| `LATE_REVERT_MS` | ms | 2000 | `src/runtime.ts` | late `discard` window | +| `PROVIDER_TIMEOUT_MS` | ms | 10,000 | `src/decide/decider.ts` | runtime-side provider abandonment | +| `STATE_CHAR_BUDGET` | chars | 3200 (comment: "≈ 3.2 chars per token") | `src/situation/serialize.ts` | full situation budget; TRAIN measured 2.4 chars/token (training/NEEDS 6a) | +| `COMPACT_BUDGET` | chars | 1100 | `situation/serialize.ts` | floor of `sectionLimits` interpolation (not the compact-questions switch) | +| `COMPACT_QUESTIONS_BUDGET` | chars | 1400 | `src/situation/questions.ts` | at or below: bare labels/names in questions | +| auto situation budget | chars | webgpu 3200; wasm `1000 + round((threads − 1) × 1000 / 3)` with threads clamped to 1–4 (1000/1333/1667/2000); unknown device 3200; all × `budgetScale` (1, × 0.8 per `max_tokens_exceeded`, floor 0.5) | `RuntimeImpl.situationBudget` | device sizing; a numeric `situation.budget` wins | +| `DEFAULT_DIAGNOSES` | labels | expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient | `situation/questions.ts` | frozen vocabulary order | +| kill switch | URL / localStorage | `genclass=off\|observe\|guard\|heal` (URL wins) | `src/index.ts` -> `killSwitch` | rule GenClass out while debugging | + +## Invariants and gotchas + +### Ground rules (binding; CONTRACT §0 and §0.5, restated) + +CONTRACT: "This file binds every workstream. If something here is wrong, tell the lead; do not silently diverge." + +1. **No hardcoded bugs, patterns, recoveries or demo rules in the runtime (§0 rule 1).** The runtime may compute generic, + uniform facts (happens-before order, versions, repetition counts, failure streaks, latency vs learned baselines, + learned invariants, value deltas) and may decide whether a situation is worth asking the model about (triage). It + must never map a fact pattern to a diagnosis or an action with an if/then. Diagnoses and actions come from the model. + If the model is unavailable, the runtime observes only and always takes the passive action. + *In code:* triage is `facts.every((f) => f.neutral)` in `RuntimeImpl.trigger`; actions are chosen only by + `decide/policy.ts` -> `gate` from model probabilities; report templates (`decide/report.ts`) are reporting only. + Applicability checks (`situation/build.ts` -> `builtinApplicable`) only say whether an action *can* run. +2. **Train/runtime parity (§0 rule 2).** The sim drives the real runtime code (same trace, facts, serializer, questions) in a + deterministic virtual world. There is exactly one implementation of situation building and serialization: + `packages/runtime/src/situation/*`. *In code:* `sim/package.json` depends on `@genclass/runtime` and builds it with + `build:runtime-core`. Wording changes after `situation-v1` invalidate the final data. +3. **Determinism (§0 rule 3).** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly, and never + schedules with the global `setTimeout`; it uses the injected `Clock` (`src/clock.ts` -> `browserClock` captures + real timers at module load). IDs come from counters. Same inputs give byte-identical situations + (`test/budget.test.ts`, `test/situation.test.ts`). *Exceptions found:* `src/model/engine.ts` defaults `now` to + `performance.now()` (timing only), `src/model/host.ts` -> `scheduleIdle` calls `requestIdleCallback` for preload, and + the devtools render with a `requestAnimationFrame` captured at module load (`src/devtools/index.ts`; UI only, never + situation text). No `Math.random` or `Date.now` anywhere in `packages/runtime/src`. +4. **Honest evaluation (§0 rule 4).** `demos/` and `sim/` are built by different people who do not read each other's code. + The sim never models a demo. Demos contain no hints beyond a normal integration (stores, optional `resync` + handlers, custom actions/questions only in the extensibility demo). `demos/README.md` "Honesty rules" restates this. +5. **Mac safety (§0 rule 5).** The Mac only edits files. Every build, test, browser and model run happens on the `train` VM + via `scripts/vm.sh` in your own slot. Never run `npm install`, `tsc`, `vitest`, Playwright or a model locally. + *Lead policy for agents (2026-10-07):* the rule exists because the original author's Mac has 8 GB RAM. On other + machines `npm install`, typecheck, build and the runtime unit tests are light and verified to work locally. Ask + the user before running the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' + eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). Details and the verified + commands: [runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things). +6. **Language and dependencies (§0 rule 6).** TypeScript, strict mode (`tsconfig.base.json` `"strict": true`), ESM only, + Node 22 on the VM. No new runtime dependency besides `onnxruntime-web` without asking the lead. +7. **Do not edit legacy content (§1).** "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is." + This covers the pre-runtime GenClass content: `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, the legacy + `docs/*.md` (jev-local contracts and specs), `docs/benchmax-research/` and the legacy scripts in `scripts/`. It does + not cover `docs/runtime/`, `docs/agents/` or `scripts/vm.sh` (added by the runtime team in 353b0a4). + +**Product principles (§0.5, "from the user, 2026-10-07; binding").** Claim: *install one library; find and prevent +runtime failures automatically, with low false positives.* + +1. **False positives.** Default mode takes only minimal, reversible guard actions at very high calibrated confidence; a + non-passive action also requires the model's diagnosis to say something is wrong; the false-intervention rate on + clean runs is a first-class metric in the sim test split and in every demo. +2. **Performance.** Tiered detection: facts and baselines always on and nearly free; the model only for salient + situations, in a worker, loaded at idle or lazily, cached. Target model: pruned vocabulary + int8 embeddings, ≤ 25 MB q8. +3. **Observability.** One plain-English console line per detection/intervention with collapsible evidence, `explain(id)`, + undo for reversible actions, `x-genclass` response marks, kill switch `?genclass=off`. + +Adoption path: `observe` → `guard` (default) → `heal`. CONTRACT §11 adds **precision first** for training data: benign +but salient-looking situations must be well represented, and the sim reports per trigger the passive-best fraction and +the harm of each non-passive action on passive-best rows. + +### Gotchas + +- **Code wins over every doc here.** CONTRACT.md was last changed in a53dd38, before batch 3. STATUS.md was last + changed in 1a77558, UI-NEEDS and sim/NEEDS in a53dd38. Check the Drift tables before relying on them. +- **The runtime is frozen.** Do not change situation text, fact wording, action/diagnosis descriptions, `util.ts` + formatting (`secs`, `rel`, `describe`, `normalizePath`, `isSensitiveName`, …) or op/event names without the lead, + SIM and TRAIN. Pipeline-only fixes (e.g. demos §1 ordering) do not change text but still change sim dynamics. +- **REVIEW tests are a contract.** STATUS: "including every `test/review-*.test.ts` (no review test was modified)". Fix + code, not these tests. +- **No CI and no type-checking of tests.** There is no `.github/` directory. `packages/runtime/tsconfig.json` includes + only `src`, so test files (and `test/browser/ui/mock-runtime.ts`) are not type-checked. +- **No VM access by default.** `scripts/vm.sh` needs `~/.jev-local/azure_hosts` (a `train` line) and `~/.ssh/jev_azure`, + neither in the repo, plus GNU `timeout` on the local `PATH`. Without them the VM is unreachable. Run the light checks + locally (lead policy, [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)) and ask the + user before anything heavier. Gitignored `node_modules/` and + `packages/runtime/dist/` in a working copy may be stale; rebuild before trusting them. +- **Test counts.** STATUS reports 37 files / 300 tests passing on the VM with a model directory. The lead re-ran the + unit tests on 2026-10-07 at 654d822: macOS, Node v25.6.0, no model directory, `packages/runtime`, + `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"`. Result: Test Files 36 passed | 1 skipped (37), + Tests 286 passed | 14 skipped (300), about 2.4 s. That confirms STATUS's file and test totals and the 286 tests that + need no model. The 14 skips are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default + `<repo>/.cache-model`): `test/model/packer.test.ts` all 10, `engine.test.ts` 3 of 4, `calibrate.test.ts` 1 of 8. + That those 14 pass comes from STATUS's VM run. The same pass confirmed STATUS's "`tsc --noEmit` clean" and "`tsup` + build OK". It did not run the Playwright specs or `test/smoke/smoke.sh`. A static count of `it(`/`test(` call sites + is lower than 300 because some tests are generated in loops. +- **The shipped default path is untested.** No file under `packages/runtime/test/` references `DEFAULT_MODEL_BASE_URL` + or the "Model unavailable … observing only." line, and no `RuntimeImpl` test drives a provider whose status is + `error` (`test/model/host.test.ts` and `test/model/loader.test.ts` cover the host's own `error` status only); the + tarball smoke test uses `model: false`. What a default `init()` does today (How it works §1) is verified by code + reading only. +- **No committed lockfile at the root.** Only `extension/package-lock.json` is tracked; root `npm install` resolves + caret ranges (`onnxruntime-web ^1.30.0`, `vitest ^5.0.3`, …) fresh each time. A root `npm install` also leaves two + changes git sees: an untracked root `package-lock.json` (do not commit it unless the lead decides to), and + `bin/genclass-runtime.mjs` chmodded from the committed 100644 to 755, a mode change. Revert the mode with + `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. +- **Two "compact" constants.** `COMPACT_BUDGET` = 1100 shapes section sizes; `COMPACT_QUESTIONS_BUDGET` = 1400 + switches to bare labels. Do not merge them; both are frozen. +- **`docs/CONTRACT.md` is not the runtime contract.** The runtime contract is `docs/runtime/CONTRACT.md`. +- **Demo numbers measure the harness, not the product.** `demos/results.md` used the v0.1 model. +- **`OPEN_TASKS.md` mixes time zones and dates.** The header says "as of 2026-10-07 23:30 UTC" while its Done entry is + dated 2026-10-08; commit 654d822 is 2026-10-08 00:15 UTC. + +## How to change it safely + +**Record status after landing a runtime change (CORE)** +1. Update `packages/runtime/STATUS.md`: "Updated:" line, State (VM command and counts), a batch section, Deviations + (with the reason) and Open issues. +2. If the public surface changed, update `docs/runtime/API.md` and the JSDoc in `src/types.ts` in the same change. +3. Move the item in `OPEN_TASKS.md` (Next → In progress → Done), with evidence. +4. Ask the requester to flip its NEEDS item to DONE after verifying. Do not close or rewrite another workstream's items + yourself; owners may add answers under their own heading in the requester's file, as MODEL did in `training/NEEDS.md` + ("MODEL → TRAIN (from MODEL, 2026-10-07)"). + +**Propose a contract change or deviation** +1. Write the request with evidence in your NEEDS file (or tell the lead directly). +2. After approval, the lead appends it to CONTRACT §13 or the owner lists it in STATUS "Deviations from the contract (and why)". +3. Never diverge silently. A deviation without a STATUS entry is a bug. + +**Change anything the model reads (after `situation-v1`)** +1. Get the user's go-ahead: it invalidates SIM phase A/B data and the final training rounds. +2. Change only `packages/runtime/src/situation/*` (one implementation) plus `util.ts` helpers if needed. Update example + situations in STATUS from `test/situation.test.ts` / `test/budget.test.ts` output. +3. Tell SIM (regenerate) and TRAIN (`training/curriculum/rt.py` mirror; per-header calibration in `calibration.json` is + keyed on exact instruction text, training/NEEDS 5). Expect a new freeze tag (convention suggested by `situation-v1`; no v2 exists). +4. Run locally or on the VM in your slot (STATUS "State"; where to run: + [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)): `npm install` at the repo root, then in `packages/runtime` + `npx tsc --noEmit` and `GENCLASS_MODEL_DIR=~/gcl/model/.cache-model NODE_OPTIONS=--expose-gc npx vitest run` + (model tests need the v0.1 model directory; the gc test needs `--expose-gc`). Exact commands: + [runtime/build-test-release.md](runtime/build-test-release.md). + +**Fix doc drift** +1. Confirm the behaviour in code first. Code wins; do not change code to match a doc unless the lead decides the doc is the spec. +2. Edit the doc owned by the right workstream: CONTRACT (lead), STATUS/API (CORE), UI-NEEDS (UI), sim/NEEDS (SIM), etc. +3. Fixing JSDoc in `src/types.ts` is safe (no situation text). Fixing `BUILTIN_ACTIONS` descriptions is **not** (model input). + +**File a cross-workstream request** +1. Add a numbered item to your NEEDS file: addressee, status (OPEN or ASK), evidence (trace, seeds, row ids, file -> symbol), a + suggested fix and, for CORE, a regression test sketch (demos/NEEDS §1 is the model). + +**Run checks** (where to run: [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated) and [runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things)) +- Runtime unit tests (local or VM): in `packages/runtime`, `NODE_OPTIONS=--expose-gc npx vitest run` (`vitest.config.ts` + already excludes `test/browser/**`; without `--expose-gc`, `test/review-timers.test.ts` logs "[review] skipped: run with + NODE_OPTIONS=--expose-gc" and passes without checking anything). +- Tarball smoke (ask the user first; Playwright Chromium and npm registry): `bash test/smoke/smoke.sh` from `packages/runtime`. +- Sim tests (ask the user first): from the repo root, `npm run build && cd sim && SIM_RUNTIME=real npx vitest run` (the sim + imports `@genclass/runtime` through `packages/runtime/dist`, `sim/src/run/rt.ts` -> `realRuntimeFactory`, so build first). + +## Tests + +| test file | what it asserts (status-relevant) | +|---|---| +| `test/review-actions.test.ts` | error-trigger `rollback` offered only when the failing chain wrote state; never reverts other chains' writes | +| `test/review-hub.test.ts` | held value writes re-applied as patches; late-revert undo; in-place updaters while held; versions past the 16-entry history; 2,000-item arrays; throwing commits do not strand queues | +| `test/review-dom.test.ts` | password values never recorded; programmatic `el.click()` inside an op is not a user action | +| `test/review-fetch.test.ts` | request identity (Request bodies, Range); coalesce never hangs; memory bounds (64 × 256 KB); destroy pass-through; no holds in guard mode for failures; keepalive never held; failure/error-rate fact wording | +| `test/review-xhr.test.ts` | sync XHR never held; abort while held; listeners once per object; reuse after block | +| `test/review-timers.test.ts` | recursive `setTimeout` loops: no stack overflow, no retention | +| `test/review-precision.test.ts` | short last page not unusual; `m21`-style keys; null selection not an inconsistency; lingering violation does not freeze `lastConsistent` | +| `test/review-redaction.test.ts` | custom `redact` applies to invariant facts | +| `test/review-misc.test.ts` | console ×N summaries; rate-limit warning once; init robustness on read-only globals; `ctx.builtin` cannot bypass policy; never-settling provider; `ask` after destroy rejects `destroyed` | +| `test/review-perf.test.ts` | cost with 5,000-item stores; asserts per-write < 1 ms (keystroke), < 2 ms (gated async write), redux dispatch < 1 ms (user) / < 2 ms (async), settled point < 16 ms (STATUS measured 0.14, 0.19, 0.68/0.58, 0.2 ms) | +| `test/batch3.test.ts` | SIM a–f (redaction by meaning, state lines, "back to V", item diffs, slug ids, pending-local-change fact); `transient` after `unusual`; lifecycle guarantees | +| `test/budget.test.ts` | section limits (1,100: 6/2/3/3/1, 2,000: 9/4/9/5/2, 3,200: 12/6/16/8/4; 500 = 1,100); compact questions (≤ 24-char overrides kept); byte-identical determinism; auto budgets webgpu 3,200, wasm 1,000 / 1,333 / 2,000 at 1 / 2 / 4 threads (16 threads → 2,000), unknown device 3,200, a fixed number wins; `max_tokens_exceeded` shrink; hold-budget formula and `timeoutMs` of held requests | +| `test/situation.test.ts` | one situation per trigger (the STATUS examples); side-effect-free `ask` situation; shrink order; identical situations on a fake clock | +| `test/policy.test.ts` | §8 gate: summed mass, tiers, thresholds, deny/allow, pause, rate limit, observe never holds, fail-open while loading, detection threshold | +| `test/smoke.test.ts` | atoms apply synchronously when not salient; context through awaits; stale write held and discarded in guard mode | +| `test/smoke/smoke.sh` | packed tarball installs into Vite 8, builds, loads in headless Chromium with devtools, ≥ 3 events, no console errors (`model: false`) | + +## Drift and open issues + +### Open issues by owner (as of 654d822, verified in code where marked) + +| owner | issue | source | state in code | +|---|---|---|---| +| CORE | **Held writes land after a newer user write.** User-sync writes bypass the store queue and apply at once; an earlier held write later re-runs its updater on top and overwrites the user's change. Board: jump-backs 3.07 → 4.80 per session, 0 actions | demos/NEEDS §1 | open: `state/hub.ts` -> `StoreHub.propose` (`bypass` → `commit` immediately) | +| CORE | **Holds cost latency** when the model is slower than the budget; decision requests queue one at a time; superseded requests are not dropped | demos/NEEDS §2 | open: `RuntimeImpl.trigger` holds whenever an action is permitted; `DeciderQueue` has no supersede logic | +| CORE | **`retry` offered for non-idempotent requests** (duplicate orders after a 502/504 that committed) | demos/NEEDS §5 | open: `builtinApplicable` → `replayable && attempt < 4 && fetch` (no idempotency check). `req.idempotent` (from `util.ts` -> `IDEMPOTENT_METHODS` = GET, HEAD, OPTIONS, PUT, DELETE, TRACE, set in `observe/fetch.ts`) gates only `hedge` among actions; the model sees it only as the request fact "POST is not idempotent; …", and the `retry` description says nothing about idempotency | +| CORE | Observe `EventSource`/`BroadcastChannel` messages as ops | demos/NEEDS §6 | open: no reference in `src/` | +| CORE | Keep observing synthetic DOM events | demos/NEEDS §7 | satisfied (no `isTrusted` filter), except: any event while a non-user op's code is running, untrusted events while a non-user op is ambient (`observe/dom-user.ts` -> `programmatic`), and events inside `[data-genclass-ignore]` (`ignoredEvent`) | +| CORE | In-place mutation detection is best effort (8 sampled elements/values) | STATUS Open issues | open by design | +| CORE | Situation budget assumes 3.2 chars/token; measured 2.4 | training/NEEDS 6a | open: `STATE_CHAR_BUDGET` = 3200 unchanged; TRAIN trains with `max_len` 2048 | +| CORE | `rollback` description ("last consistent snapshot") does not match transition/error effect (chain revert) | code reading | open; fixing it changes model input | +| CORE | Fact "could not be held: the update changed the stored value in place" is unreachable (unholdable writes commit in `propose` without gating) | code reading | open | +| MODEL | Device-based model selection in the host card | OPEN_TASKS 5 | not started: `model/loader.ts` -> `parseCard` reads one model's variants (`q8`/`fp16`) per card; `planOrder` picks only variant and device | +| UI | Overlay ignores `Explanation.message` | UI-NEEDS 3 | CORE side done (`types.ts` -> `Explanation.message`, `runtime.ts` -> `explain`); the overlay still takes lines only from `on("report")` (`devtools/index.ts` -> `addReport`) and otherwise falls back to its own templates. See [runtime/devtools.md](runtime/devtools.md) | +| SIM | Phase B (1.4M rows) | OPEN_TASKS 1 | in progress | +| SIM | Phase A is below TRAIN's stated volume: train 448,420 (asked ≥ 1M, target 1–2M) and **dev 14,613 (asked ≥ 20k)**; test 137,643 meets ≥ 40k | training/NEEDS 1 (still OPEN) | phase B should cover train; whether dev grows is not recorded | +| SIM | Clean-run rows flagged `meta.clean: true` | training/NEEDS 4 (ASK) | not found in `sim/src` | +| TRAIN | Final rounds 1 and 2, calibration, export, parity, EVAL.md per trigger and budget | OPEN_TASKS 3–4 | round 1 running at commit time | +| DEMOS | Screenshot tour and README; evaluation with the trained model (bug rate Off/Guard/Heal, clean-run false interventions) | OPEN_TASKS 2, 6 | v0.1 numbers only | +| DEMOS | **`demos/src/server/data/cities.ts` is missing from git** (root `.gitignore` line `data/` ignores it). `demos/src/server/worlds/search.ts`, `demos/src/demos/search/scenario.ts` and `demos/src/demos/search/oracle.ts` import it, and `demos/tsconfig.json` includes `src`, so it blocks the demos build, the demos typecheck (and with it the root `npm run typecheck`, which runs every workspace's `typecheck`; inferred from the code, `tsc` not run) and the Service Worker bundle | [demos.md](demos.md#drift-and-open-issues) Drift 1 | open: `demos/src/server/data/` does not exist | +| lead | Publish `@genclass/runtime-model@0.1.0` + release `runtime-model-v0.1.0`, then `@genclass/runtime@0.1.0`; CI (build, typecheck, unit tests); honest-results docs; model card numbers; dev-only lazy devtools import | OPEN_TASKS 7–8 | not done | +| CORE / lead | A test for the shipped default path (model card 404 → status `error` → observe only, status report printed) | code reading (see Gotchas) | none exists | + +### Known risks + +- **Single-thread WASM speed** (OPEN_TASKS): hold budgets cap at 800 ms, so slow devices fail open more. Measured + (Node, 1 thread, q8): R17 188 / 339 / 608 ms and R32 499 / 879 / 1,539 ms at 500 / 780 / 1,170 tokens (`training/EVAL.md`). +- **Training-label noise** (OPEN_TASKS): costs come from K = 3 sampled futures (`sim/README.md` limitation 1); "66% of + passive-best request rows put ≥ 0.9 on passive" (in OPEN_TASKS since a53dd38, so a pre-freeze figure; phase A + `label_sharpness.request.passive_mass_ge_0_9` = 0.676, and only 0.379 of intervene-best request rows put ≥ 0.9 on + non-passive actions; `label_sharpness` is not split by train/dev/test). Diagnosis and action are labelled independently: + "expected → coalesce" is about 11% of request rows (`sim/README.md` limitation 3); the runtime's diagnosis gate + keeps those passive. +- **Thin classes** (OPEN_TASKS): in SIM phase A train, `diagnosis_by_split_trigger` counts `conflict` 10,204 and + `unusual` 1,049 of 291,031 diagnosis labels, and `transition` is 12,360 of 341,204 non-`ask` rows + (`sim/samples/stats-final-a.json`). +- **Hold-induced harm and triage sensitivity** (OPEN_TASKS 6, demos/NEEDS §1–§2), all with v0.1: + - Board, guard mode, no interventions: OPEN_TASKS and `demos/results.md` say 9 bugs introduced vs 1 fixed. demos/NEEDS + §4 attributes most of that to the mock server's single random stream. The corrected traced run (common random + numbers) shows 5 introduced / 3 fixed and +56% visible jump-backs (§1). + - Search, clean runs: `demos/results.md` user-latency p50 14 ms (Off) → 125 ms (Guard); demos/NEEDS §2 (final + results, calm typist, 15 seeds) 6 ms → 389 ms, with 127 of 148 result writes held (median 543 ms). + - Typeahead is salient about 6 times per clean trial (OPEN_TASKS 6). +- **v0.1 is not a runtime model**: `unusual` for 6,328 of 6,386 decisions, never `expected`; 0 false interventions only + because it rarely clears thresholds in time (demos/NEEDS §8). +- **Paired demo results with v0.1** (`demos/results.md` summary table, 30 chaos seeds, fixed / introduced vs Off): + Guard: search 0/0, editor 1/1, checkout 0/2, status 2/0, board 1/9, decisions 3/5; Heal: 0/0, 0/1, 0/2, 0/0, 2/9, + 2/5. False interventions on clean runs: 0 in every demo and mode. These predate the mock-server fix (demos/NEEDS §4). +- **Stage 1 does not transfer to SIM labels**: zero-shot on SIM's 123-row sample ≈ 50% action accuracy and 18–34% + heal-mode false interventions (`MODEL_CARD.md`, `training/LOG.md`); the shipping model must come from the final rounds. +- **R17 vs R32 precision off the runtime-exact format**: on varied surface styles (`cur1/test`) heal FIR is 1.70% + for R17 (stall 11.5%) vs 0.60% for R32 (`training/EVAL.md`). Relevant to OPEN_TASKS 5 (ship R17 for WASM). +- **Stage-2 pilot was precise but timid**: heal recall 1.3% (R32) / 1.4% (R17) on pre-freeze soft labels; final rounds + use sharper labels. + +### Decisions waiting on the user / repo owner + +Recorded in `OPEN_TASKS.md` "Needs the user": +1. **Public demo hosting** (GitHub Pages on this repo): OK to publish? Open. +2. **Merging `runtime` into `main`.** `main`, `origin/main` and `origin/runtime` already point at 654d822, so this looks + done; the owner should confirm and remove the item. + +Pending lead/owner decisions inferred from NEEDS and OPEN_TASKS (not recorded as user questions): +3. Ship R17 only, or R32 for WebGPU "only if clearly more accurate" (OPEN_TASKS 5). +4. Whether to change the frozen runtime for demos §1/§2 (behaviour only) or §5/§6 and the `rollback` description + (model-visible text, so new data and retraining). +5. Whether to rebudget situations by real tokens (training/NEEDS 6a). +6. VM access (hosts file, SSH key) for new agents. Partly settled on 2026-10-07: the lead allows the light checks (install, + typecheck, build, runtime unit tests) locally on other machines. Heavy jobs still need the user's go-ahead and a place + to run: sim, training, Playwright, model runs, demo eval. + +### Doc drift: `docs/runtime/API.md` vs `src/types.ts`, `src/index.ts`, runtime + +| # | API.md says | code does | evidence | +|---|---|---|---| +| 1 | Self-host with `npx genclass-runtime fetch-model public/genclass-model` | Default `--from` is the unpublished release `runtime-model-v0.1.0`; today it needs an explicit `--from` (e.g. the v0.1 URL) | `bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | +| 2 | `baseUrl` default "jsDelivr CDN" | Correct URL, but the package is unpublished: default init observes only | `model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | +| 3 | `model` options: `baseUrl`, `device`, `worker`, `preload` | Also `ortWasmPaths`, `cacheName` | `types.ts` -> `ModelOptions` | +| 4 | `rt.ready` resolves when ready (immediately with no model) | Rejects with the provider's error on load failure; memoised | `runtime.ts` -> `get ready` | +| 5 | `ask`/`decide` reject with `GenClassUnavailableError` | With `timeoutMs` and a failed load the raw provider error propagates; `timeoutMs` applies to the load wait and the answer wait separately | `runtime.ts` -> `ask` | +| 6 | `pause()` stops consulting the model | `ask`/`decide` still query it (no `paused` check) | `runtime.ts` -> `ask` | +| 7 | Kill switch: `localStorage.genclass = "off"`; URL `?genclass=observe\|guard\|heal` | localStorage also accepts `observe\|guard\|heal`; URL wins | `index.ts` -> `killSwitch`, `initUnsafe` | +| 8 | Outside a browser `init()` returns an inert runtime: no observers, no model | Observers off and no host, but `options.decider` is kept; `report` defaults to `"silent"` | `index.ts` -> `initUnsafe` | +| 9 | `holdBudgetMs: "auto"` = clamp(1.5 × median, 150, 800) | Plus 300 ms fallback when no latency and no `warmupMs` | `decide/policy.ts` -> `holdBudget` | +| 10 | Bodies over 64 KB never match | String bodies up to 1 MB are hashed and can match; 64 KB applies to Blob/ArrayBuffer/view/Request bodies | `observe/fetch.ts` -> `STRING_BODY_MAX`, `IDENTITY_BODY_MAX` | +| 11 | Report example "(v0 → v1)" | "(version 0 → 1)" | `situation/facts.ts`; STATUS examples | +| 12 | `situation()` returns `{ trigger, subject, state, questions, actions, salient, facts }` | Also `compact`, `budget`; returns the last situation built for that trigger if any, else the "ask about now" situation relabelled with that trigger (so `actions` is empty) | `types.ts` -> `Situation`; `runtime.ts` -> `situation` | +| 13 | Plugin facts are "added to every situation" | Only to built situations (after triage), always neutral, ranked last, may be cut | `situation/build.ts` -> `buildSituation` | +| 14 | `on("status")`: model loading progress and state | Also fired by every `setMode` | `runtime.ts` -> `setMode` | +| 15 | Type listings | Omit `UserAction.data`, `Op.meta`, `ActionDef.risk` (unused) | `types.ts` | +| 16 | Exports | Undocumented: `browserClock`, `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES`, `describeElement`, `RuntimeImpl`, default export, model errors beyond the five named (`GenClassModelError`, `ModelInputError`, `ModelUnsupportedError`, `ModelAbortedError`, `ModelDisposedError`, `ModelIntegrityError`, `ModelInferenceError`), host types; `./worker` subpath; React `GenClassProvider`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus`; Redux `GENCLASS_REPLACE`; Zustand `genclass(runtime, name, opts?)` | `index.ts`, `package.json` `exports`, `src/adapters/*.ts` | +| 17 | `observe` defaults not stated | `timers` on only when `global.document` is a non-null object; others on | `runtime.ts` -> `installObservers` | +| 18 | Trigger/action tables do not distinguish fetch from XHR | XHR: no `coalesce`; failure `retry`/`serve_cached` and stall `hedge`/`serve_cached` are fetch-only, so XHR failures and stalls are detection-only; XHR requests can still get `delay`, `block`, `serve_cached` | `situation/build.ts` -> `builtinApplicable`; STATUS deviation 2 | +| 19 | Types section lists `Decision`, `ActionRecord`, `Explanation`, `RtEvent`, `Op` | Public types a plugin or provider author needs are not listed: `SituationDraft` (input of `facts()`, `applicable()`, `ActionContext.situation`), `Fact`/`FactKind`, `RequestInfo`, `SubjectRef`, `EvaluateRequest`, full `ModelStatus` (`model`, `loadMs`, `version`, `bytes`, `fromCache`, `warmupMs`, `worker`, `workerError`, `gpu`, `attempts`, `ort`), `ChoiceAnswer.confidence` = (k·max p − 1)/(k − 1), `AdapterIO`/`AdapterHandle`, `RuntimeHooks.mutationProposed` payload, `StandingQuestionContext` | `types.ts` | + +API.md is otherwise accurate for batch 3 (summed gate, `candidate`/`mass`, `transient`, compact questions, retry +backoff `min(200 · 2^(attempt−1), 5000)`, word-level redaction, `data-genclass-ignore`). + +### Recorded contract deviations (STATUS "Deviations from the contract (and why)") + +These are accepted by CORE and listed in STATUS; CONTRACT.md was not updated. Each also appears in the table below. + +| # | deviation | why (STATUS) | code | +|---|---|---|---| +| 1 | `retry` backoff `min(200 ms · 2^(attempt−1), 5 s)` (first retry waits 200 ms) | — | `observe/fetch.ts` (failure handler) | +| 2 | `coalesce` not offered for XHR; XHR failures/stalls detection-only | the app receives XHR events directly | `situation/build.ts` -> `builtinApplicable` | +| 3 | Transition profiles compare array kinds as empty / non-empty only (no length-delta sign) | precision: a short last page or a removal is ordinary | `learn/profiles.ts` -> `kindLabel` | +| 4 | Error/transition `rollback` restores only the fields the op's own chain wrote; inconsistency uses the snapshot | the snapshot would also revert other chains' writes (e.g. user input) | `runtime.ts` -> `revertChain`; `situation/build.ts` -> `revertableChain` | +| 5 | Default redaction by word-level secret names, not the §2 regex | approved SIM request a | `util.ts` -> `defaultRedact`, `isSensitiveName` | +| 6 | `situation(trigger)` returns the last situation built for that trigger | — | `runtime.ts` -> `situation` | +| 7 | Extra public surface (`adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")`, extra `Situation`/`Decision`/`ActionRecord`/`Explanation`/option fields) | additive | `types.ts` | + +### Doc drift: `docs/runtime/CONTRACT.md` vs implementation + +| § | CONTRACT says | code does | +|---|---|---| +| 1 | `src/observe/` = fetch, xhr, dom-user, errors, nav, storage, perf, websocket | Also `timers.ts` and `cache.ts` (response cache); extra top-level `src/util.ts`, `src/errors.ts`; `situation/` also has `build.ts`, `describe.ts`, `env.ts` | +| 2 | Kill switch: `localStorage.genclass = "off"`; adapters: React `useGenClassState`, `useAtom`, `useGenClass` | localStorage also accepts `observe\|guard\|heal`; adapters also export `GenClassProvider`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus`, Redux `GENCLASS_REPLACE`; Redux `genclassEnhancer` and Zustand `genclass` accept a null runtime and pass through, React `useGenClassState` falls back to plain `useState`, but `useGenClass()` throws without a runtime (`src/adapters/*.ts`) | +| 4 | Mutations "applied in proposal order per store (a later-decided mutation waits for earlier ones on the same store)" | Only for queued writes: user-sync writes (unless `holdUserWrites`), GenClass writes, `hold: false` stores and paused runtimes bypass the queue and commit at once, overtaking held writes (`state/hub.ts` -> `StoreHub.propose`; demos/NEEDS §1) | +| 6 | `hedge` applicable when the body is replayable and the method idempotent | Also GET only and fetch only (`builtinApplicable`) | +| 1 | `src/plugins.ts`; `state/` "atom, guard, diff/summaries, invariant miner, snapshots"; `decide/` "built-in actions, executor"; `learn/` baselines only | No `plugins.ts` (plugins in `runtime.ts`); `state/{hub,fields,invariants}.ts`; action catalogue in `situation/questions.ts`, `decide/exec.ts` is only the `Controller` seam; `learn/profiles.ts` exists | +| 1 | adapters/devtools owner CORE; `training/` owner LEAD; `runtime-model/` "model card + files"; CLI "fetch-model" | §13 and UI-NEEDS: UI; training/README: TRAIN; only `MODEL_CARD.md`; CLI also has `info <dir>` | +| 2 | `redact` default `/pass\|token\|secret\|card\|cvv\|ssn\|auth/i` | Word-level `isSensitiveName` (approved SIM a) — `util.ts` -> `defaultRedact` | +| 2 | `InitOptions` listing without `decider`, `learn`, `vocabulary`, `settleMs`, `situation`, `observe.timers` (§4 mentions `settleMs` and `learn: { persist }`, §13 approves `vocabulary`); `Runtime` without `mode`, `adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")` | All exist (STATUS "Extra public surface") | +| 2 | `device: auto` = webgpu+fp16 if shader-f16, else wasm+q8 | Plans webgpu+fp16 → webgpu+q8 → wasm+q8; auto skips software adapters (`model/loader.ts` -> `planOrder`) | +| 3 | `Op` fields; identity = hash of method+url+body; ids normalised: numbers, uuids, long hex; body methods `json,text,arrayBuffer,blob,formData` | Adds `Op.meta`; identity adds non-volatile headers; also long mixed tokens and short slug ids (`util.ts` -> `isIdSegment`); also `bytes` | +| 4 | Hub records snapshots; every template (incl. `a != null`) is learned after ≥ 3 settled snapshots; profile kind includes length delta sign; duration bucket in the shape | `RuntimeImpl.settled` records them (≤ 8, lingering violations do not block); `state/invariants.ts`: `LEARN_AFTER` = 3 but `LEARN_AFTER_NONNULL` = 6 for `a != null`; array kinds empty/non-empty only (STATUS deviation); `dur` recorded but never raises a transition (`learn/profiles.ts` -> `Profiles.check`) | +| 4 | Settled = no in-flight ops | No in-flight op younger than 10 s **and** no pending write (`RuntimeImpl.busy`) | +| 6 | Budget ≤ 1,000 tokens; truncate timeline, then state, then facts; `situation()` returns `{trigger, subject, state, questions, actions}` | Character budget, device-sized; then in-flight/stats and fact shortening; extra `salient/facts/compact/budget` | +| 6 | Triage example "baseline ratio beyond 3×" | Cause latency > 3× median **and** ≥ 100 ms over it; rate ≥ 3× usual **and** ≥ 5 in 10 s (`situation/facts.ts`) | +| 7 | `retry` backoff `min(200 ms · 2^attempt, 5 s)` | `min(200 · 2^(attempt−1), 5000)` (STATUS deviation) | +| 7 | `rollback` writes the snapshot back | Snapshot only for `inconsistency`; error/transition revert only the chain's fields (STATUS deviation) | +| 7 | Implied XHR parity | XHR: no `coalesce`, `retry`, `hedge`, failure/stall `serve_cached` (STATUS deviation) | +| 8 | `holdBudgetMs` default 300 | `"auto"` (150–800; 300 only as fallback) | +| 8 | `Decision`/`ActionRecord`/`Explanation`/`DecisionProvider` field lists | Add `tier`, `ran`, `answers`, `subjectRef`, `candidate`, `mass`, `late`, `message`, `priority`, `timeoutMs` | +| 8 | Repeats "summarised as ×N in the last minute" | `(×N more in the last minute)` printed at window end, console sink only | +| 9 | `ActionDef` without `tier`; `StandingQuestion` without `always`; PluginApi without `runInOp`, `runtime` | All exist; `risk` is declared but unused | +| 10 | Worker imports `onnxruntime-web/webgpu`; reference engine at `/Users/meharkhanna/jev/...` | Imports `/wasm` or `/webgpu` on demand (`model/worker.ts`); path is another machine (v0.1 card is `extension/src/model/model.json` here) | +| 13 | `situation(trigger)` is side-effect free | Returns the cached last-built situation; building caches `op.reads` (STATUS deviation) | +| 0.5 | Console examples "Coalesced a duplicate: …", "Flagged: …" | Templates: `[GenClass] <Lead> a/an <diagnosis> <noun>: <top fact> <changed> (<diag>, p; <action> p)`; coalesce lead is "Prevented", late reverts "Reverted", actions without a `LEAD` entry (plugin actions) "Handled"; detections "Flagged a/an …" (`decide/report.ts` -> `interventionLine`, `detectionLine`) | + +### Other doc drift + +| file | stale statement | code / repo reality | +|---|---|---| +| `packages/runtime/README.md` | Privacy: "fields matching `pass\|token\|secret\|card\|cvv\|ssn\|auth` are redacted" | Word-level redaction; "card", "cards", "author" kept (`util.ts` -> `isSensitiveName`) | +| `packages/runtime/README.md` (status banner and "Self-hosting" bullet) | "self-host a model with `npx genclass-runtime fetch-model`" | Needs `--from` (see API #1). The root `README.md` does not mention `fetch-model` | +| `packages/runtime/README.md`, `docs/runtime/ARCHITECTURE.md` | "2,000 with WASM threads" | 2,000 only at 4 threads (1,333 at 2, 1,667 at 3) | +| `packages/runtime/README.md`, `README.md`, CONTRACT §0.5 | Console example lines | Real format differs (see CONTRACT §0.5 row); API.md's example is close | +| `packages/runtime/README.md`, OPEN_TASKS | ORT WASM 2.7 MB br (no WebGPU) / 4.7 MB | Not a real conflict: `src/model/README.md` measures 2.69 / 4.69 MB at brotli q9 and notes jsDelivr serves the wasm at 3.07 / 5.53 MB, the figures `model/worker.ts`'s comment rounds to 3.1 / 5.5 MB | +| `README.md` "How it works" 5 | guard acts "when the model is ≥ 90% sure" | Summed probability of the permitted non-passive actions ≥ 0.9 **and** top diagnosis ≠ `expected` (`decide/policy.ts` -> `gate`); the package README's wording ("very sure (≥ 0.9) that acting beats doing nothing") is accurate | +| `packages/runtime/UI-NEEDS.md` 3 | `Explanation.message` is "Nice to have" | Implemented by CORE (`types.ts` -> `Explanation.message`, `runtime.ts` -> `explain`; API.md documents it); only the overlay's use of it is missing | +| `packages/runtime/STATUS.md` Open issues; UI-NEEDS 2 | `react-dom` is not a devDependency | `react-dom ^19.3.0`, `@types/react-dom ^19.0.0` are devDependencies | +| `packages/runtime/STATUS.md` For UI | mock-runtime needs `holdBudgetMs()`/`situationBudget()` | Present in `test/browser/ui/mock-runtime.ts` | +| `packages/runtime/STATUS.md` batch 3 | Unholdable in-place write "applies at once with a fact" | Applies at once without gating, so no fact (`state/hub.ts` -> `StoreHub.propose`) | +| `packages/runtime/STATUS.md`, sim/NEEDS header | Headless thresholds `{ report: 0, guard: 0, heal: 0 }` | The sim uses guard/heal 0.5 (`sim/README.md`) | +| `packages/runtime/UI-NEEDS.md` 1 | Ignore the devtools overlay: Open | Done: `observe/dom-user.ts` -> `ignoredEvent`; STATUS "For UI" agrees | +| `sim/NEEDS.md` a–f | ASK | DONE in batch 3 (STATUS; `test/batch3.test.ts`) | +| `sim/NEEDS.md` Notes | `transient` not yet in `DEFAULT_DIAGNOSES` | It is, last (`situation/questions.ts`) | +| `sim/README.md` limitation 5 | Triage does not flag a remote write over a pending local change | It does (`situation/facts.ts` "has a pending local change"; SIM f) | +| `training/NEEDS.md` | "Still to mirror when CORE's fix batch lands" | Done per `training/LOG.md` 23:05–23:35 (`rt.py` re-ported; MODEL NEEDS 8 fixed) | +| `OPEN_TASKS.md` item 8 | `npm pack` smoke test is next | Done (`test/smoke/smoke.sh`, Done list) | +| `OPEN_TASKS.md` item 7 | "ARCHITECTURE.md are written; still to do: … ARCHITECTURE.md" | Self-contradictory; the to-do is "honest results" content | +| `OPEN_TASKS.md` item 6, `demos/results.md` | Board: 9 bugs introduced in guard mode | Superseded by demos/NEEDS §1/§4 (5 introduced / 3 fixed after the mock-server fix) | +| `OPEN_TASKS.md` risks | Thin classes "until the batch-3 runtime facts land" | Batch 3 landed before phase A; see Known risks for counts | +| `docs/runtime/ARCHITECTURE.md` | DOM events "trusted events only"; sources omit timers; diagnosis order "…failing, transient, slow…"; fact "(v0 → v1)" | Untrusted events kept unless a non-user op is running or ambient (`observe/dom-user.ts` -> `programmatic`); timers observer exists; `transient` last; "(version 0 → 1)" | +| `packages/runtime-model/MODEL_CARD.md` | 9 diagnoses; acts when `p(action) ≥ 0.9/0.8`; q8 is "for onnxruntime-web WASM"; status "stage 2 piloted" | 10 (with `transient`); summed probability of permitted actions; MODEL verified q8 also runs on the WebGPU EP without shader-f16 (training/NEEDS, MODEL → TRAIN 7); final round 1 is running | +| `sim/README.md` limitation 8, `stats-final-a.json` `token_estimate` | Token counts estimated as characters / 3.6 | TRAIN measured 2.4 chars/token with the runtime tokenizer (training/NEEDS 6a), so SIM's token estimates are ≈ 1.5× low | +| `src/types.ts` JSDoc | `InitOptions.redact` regex; `InitOptions.situation` auto wasm budget "1,100 + 300 per extra thread"; `Decision.action` "The action the model chose (highest probability)"; `InitOptions.observe` "Default: all true" | word-level; `1000 + round((t−1)·1000/3)`; `run ?? top` in `runtime.ts` (the action that ran, else the model's choice); timers conditional | +| `src/situation/serialize.ts` comment | `STATE_CHAR_BUDGET` ≈ 3.2 chars per token | Measured 2.4 (training/NEEDS 6a) | +| `packages/runtime/bin/genclass-runtime.mjs` | — | Committed as mode 100644 (not executable). A root `npm install` chmods it to 755 (observed with npm 11.8.0 on 2026-10-07), which git reports as a mode change; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | + +### Code TODOs + +None. `grep -rn "TODO\|FIXME\|HACK\|XXX"` over the repo (excluding `node_modules`, `.git`, `dist`) matches only +vocabulary entries in `extension/**/tokenizer.json` and prose in agent docs. Open work lives in the NEEDS, +STATUS and OPEN_TASKS files instead. + +Comments that act like TODOs or temporary workarounds (found by grepping `packages/runtime/src`, `sim/src`, +`demos/src`, `training` for "until", "not yet", "for now", "stub", "workaround"): + +| where | what it says | state at 654d822 | +|---|---|---| +| `sim/src/run/rt.ts` -> `realRuntimeFactory` | "Until the runtime's default vocabulary has every contract label, pass the contract's defaults explicitly"; also "CORE's API is in flux" and the error "does not export createRuntime yet" | Inert: runtime `DEFAULT_DIAGNOSES` has all 10 labels, so `missing` is false; the wording is stale | +| `sim/src/run/fake-runtime.ts` | "TEST DOUBLE ONLY": rows it produces are marked `meta.runtime = "fake"` and "must never be used for training" | Guarded: `sim/src/gen.ts` uses it only with `--allow-fake` | +| `src/model/backend.ts` -> `WARMUP_STATE`, `WARMUP_QUESTIONS` | Hand-copied situation and question wording for the warm-up pass ("What is going on?" vs the runtime's `DIAGNOSIS_INSTRUCTIONS` "What is happening here?") | Harmless: used only for the warm-up pass in `ModelBackend` load (also re-exported from `model/index.ts`); never a decision. Do not treat it as a wording reference | +| `src/types.ts` JSDoc, `src/situation/serialize.ts` comment | Stale values (see Other doc drift) | Safe to fix (no model-visible text) | + +### Subsystem drift tracked elsewhere + +The tables above cover the human docs (API.md, CONTRACT.md, READMEs, STATUS, NEEDS, MODEL_CARD) against the runtime +code. Each subsystem doc has its own Drift section with more detail: [public API](runtime/public-api-and-lifecycle.md), +[observe](runtime/observe-and-trace.md), [state](runtime/state-and-adapters.md), +[situation](runtime/learn-situation-triage.md), [decide](runtime/decide-policy-actions.md), +[model host](runtime/model-host.md), [devtools](runtime/devtools.md), [build](runtime/build-test-release.md), +[model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md), [demos.md](demos.md) (e.g. +Drift 1, the missing `cities.ts`), [genclass-model-lineage.md](genclass-model-lineage.md) and +[extension-and-benchmarks.md](extension-and-benchmarks.md). + +## Related docs + +- Agent docs: [README.md](README.md), [overview.md](overview.md), [repo-map.md](repo-map.md), [glossary.md](glossary.md), + [playbooks.md](playbooks.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md), + [demos.md](demos.md), [genclass-model-lineage.md](genclass-model-lineage.md), + [extension-and-benchmarks.md](extension-and-benchmarks.md), [../../AGENTS.md](../../AGENTS.md) +- Runtime agent docs: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), + [runtime/observe-and-trace.md](runtime/observe-and-trace.md), [runtime/state-and-adapters.md](runtime/state-and-adapters.md), + [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), + [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [runtime/model-host.md](runtime/model-host.md), + [runtime/devtools.md](runtime/devtools.md), [runtime/build-test-release.md](runtime/build-test-release.md) +- Sources: [OPEN_TASKS.md](../../OPEN_TASKS.md), [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md), + [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md), [docs/runtime/API.md](../runtime/API.md), + [docs/runtime/ARCHITECTURE.md](../runtime/ARCHITECTURE.md), [demos/NEEDS.md](../../demos/NEEDS.md), + [sim/NEEDS.md](../../sim/NEEDS.md), [training/NEEDS.md](../../training/NEEDS.md), + [packages/runtime/UI-NEEDS.md](../../packages/runtime/UI-NEEDS.md), [training/EVAL.md](../../training/EVAL.md), + [training/LOG.md](../../training/LOG.md), [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), + [demos/results.md](../../demos/results.md), [sim/README.md](../../sim/README.md), [scripts/vm.sh](../../scripts/vm.sh) diff --git a/docs/agents/training.md b/docs/agents/training.md new file mode 100644 index 00000000..4aa11827 --- /dev/null +++ b/docs/agents/training.md @@ -0,0 +1,523 @@ +# training/: the GenClass runtime model (curriculum, training, export, eval) + +> **Scope:** `training/` (README.md, LOG.md, EVAL.md, NEEDS.md, `prune_vocab.py`, `eval_runtime.py`, `export_runtime.py`, `report.py`, every `*.sh`, `curriculum/**`, `configs/*.json`, `ortweb/**`, `tests/**`, `samples/**`), plus the parts of `jev_local/train/{train,stream,eval}.py`, `jev_local/engine/encoder/{engine,calibrate,tokenize_pack}.py`, `scripts/genclass_export.py` and `scripts/launch_run.sh` that `training/` calls. +> **Read this when:** you regenerate or change the stage-1 curriculum; mirror a runtime situation/question wording change into `curriculum/rt.py`; change mixtures or launch a training round on Azure; evaluate a checkpoint, fit calibration or read EVAL.md numbers; export a model directory (q8/fp16 ONNX, `model.json`, `meta.json`, `calibration.json`) or validate it with onnxruntime-web; change the vocabulary; pick between R17 and R32. +> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. + +## TL;DR + +- `training/` builds the model behind `@genclass/runtime`: a Jev-style typed-decision encoder (one forward pass reads a *situation* and answers typed *questions*: choice / noul / score). Owner workstream: TRAIN (CONTRACT §1 says LEAD). +- Two **model candidates**, both with a pruned 16,364-token vocabulary: **R17** (`jhu-clsp/ettin-encoder-17m`, d 256, 7 layers, fresh heads) and **R32** (GenClass 0.1 `jev-local-fast` = ettin-32m, d 384, 10 layers, v1 heads). Plan: R17 for WASM, R32 for WebGPU only if clearly more accurate (OPEN_TASKS item 5). +- Pipeline: `prune_vocab.py` (keep first 16,000 BPE merges) → **stage 1** on a synthetic curriculum (`curriculum/`, exact labels, ~55% passive-best decision rows) → **stage 2 / final round** on SIM rows from `sim/` (counterfactual-cost labels) plus curriculum replay → `eval_runtime.py` (product metrics + temperature fit) → `export_runtime.py` (fp16-free int8 **q8** ONNX for WASM, fp16 ONNX for WebGPU) → `ortweb/validate.mjs`. +- `curriculum/rt.py` is a Python port of `packages/runtime/src/situation/*` so a share of curriculum rows are **runtime-exact** (byte-identical format to what the runtime sends). Any wording change in the runtime situation code must be mirrored there (and is frozen as tag `situation-v1`). +- Training itself is `jev_local/train/train.py` in stream mode (DDP over torchrun/gloo on CPU) launched with `scripts/launch_run.sh`; all heavy work runs on Azure VMs (`c01` workbench, `c02`–`c11` F80 training nodes, `train` VM), never on the Mac. +- Data mixes (`configs/mix_*.json` → `jev_local/train/stream.py` → `MixConfig`) weight **buckets** = the parent directory names of train shards found under the `--stream` roots; weights are renormalised over the buckets present, so a missing bucket is silently dropped. +- The eval **gate** mirrors CONTRACT §8: candidate = argmax over permitted non-passive actions *A*; fire iff Σ_{a∈A} p(a) ≥ tier threshold (guard 0.9, heal 0.8) and top diagnosis ≠ `expected`. Headline metric: **FIR** (false-intervention rate on passive-best rows). +- Trained checkpoints ship with all-1.0 temperatures; the real `calibration.json` comes from `eval_runtime.py --write-calibration` and must be passed to `export_runtime.py --calibration`. +- Status at this commit: stage 1c final (rt1 action/diagnosis ≈ 98%, FIR 0%); stage-2 pilot on pre-freeze SIM was precise but almost never acted (recall ≈ 1.3%); **final round 1** (frozen `situation-v1`, SIM phase A) was launched 2026-10-08 00:06 UTC and has **no results in the repo** (EVAL.md says "(in progress)"). +- Shell scripts assume a nested checkout: `JEV="$HERE/../.."` must contain `jev_local/`, `scripts/` and `pyproject.toml` (the original `/Users/meharkhanna/jev/<checkout>/training` layout). In this monorepo those live at the repo root, one level up (see Gotchas). + +## Files + +| Path | Role | Key entry points | +|---|---|---| +| `training/README.md` | Overview and reproduce commands (partly stale, see Drift) | — | +| `training/LOG.md` | Dated run log 2026-10-07/08: what ran where, throughput, costs, decisions | — | +| `training/EVAL.md` | Metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot) | — | +| `training/NEEDS.md` | Requests to SIM / CORE / MODEL (OPEN/ASK/DONE) | — | +| `training/prune_vocab.py` | First-N-merges BPE pruning of a checkpoint or HF base; inflation analysis | `prune_tokenizer_json`, `vocab_layout`, `prune_checkpoint`, `prune_hf_dir`, `slice_weights`, `remap_model_config` (+ `CONFIG_ID_KEYS`), `remap_tokenizer_config`, `iter_texts`, `analyze`, `main` (`prune` / `analyze` subcommands) | +| `training/curriculum/__init__.py` | Package docstring only | — | +| `training/curriculum/generate.py` | Parallel, seeded generator of CONTRACT-D jsonl (train/dev/test) + `stats.json` | `make_row`, `work`, `_validate`, `main`; `TRIGGERS`, `KINDS`, `TRAIN_DOMAINS`, `HELD_DOMAINS`, `P_RUNTIME` | +| `training/curriculum/world.py` | Explicit world model: ops, writes with versions, extras, baselines; varied-style rendering | `Op`, `Write`, `Extra`, `Baseline`, `Trace`, `render_timeline`, `render_in_flight`, `render_state_line`, `render_stats`, `status_phrase`, `_events`, `STATUS_TEXT`, `USER_VERB` | +| `training/curriculum/app.py` | Per-row app instance (names, ids, routes, values) from a domain | `App` (`ident`, `coll_url`, `item_url`, `new_id`, `route`, `app_line`, `body`, `list_summary`, `query_prefixes`), `rand_token` | +| `training/curriculum/vocab.py` | 62 app domains (13 held out), UI/error vocab | `Domain`, `DOMAINS`, `TEST_DOMAINS`, `domain_split`, `plural`, `PLURALS`, `PERSON_FIRST`, `COMPONENTS`, `FILE_EXT`, `INPUT_TARGETS`, `THIRD_PARTY` | +| `training/curriculum/fmt.py` | Surface variation: `Style`, paraphrase `TEMPLATES` with held-out tails, action/diagnosis vocab, `js_numbers` | `Style.make`, `pick`, `pick_from`, `held_count`, `js_numbers`, `TEMPLATES`, `ACTION_DESC`, `DIAG_DESC`, `DIAGNOSES`, `TRIGGER_ACTIONS`, `PASSIVE`, `TIER`, `DISTRACTOR_ACTIONS`, `ACTION_INSTR`, `DIAG_INSTR`, `CANONICAL_KEYS`, `KEY_VARIANTS` | +| `training/curriculum/scenarios.py` | `Scen` dataclass; mutation scenarios; noise ops | `Scen`, `mutation`, `mut_typeahead`, `mut_detail`, `mut_autosave`, `mut_live`, `mut_dupchange`, `add_noise_ops`, `cap_now`, `PASSIVE_OF` | +| `training/curriculum/scen_ops.py` | Request / failure / stall scenarios | `request`, `failure`, `stall` | +| `training/curriculum/scen_state.py` | Inconsistency / transition / error scenarios | `inconsistency`, `transition`, `error`, `ERR_MSGS` (5 entries) | +| `training/curriculum/prims.py` | Primitive questions with exact labels over a `Trace` | `noul`, `choice`, `score`, `temporal`, `causal`, `versions`, `identity`, `streak_q`, `latency_q`, `failure_q`, `failure_kind`, `ratio_level`, `RATIO_LEVELS`, `RETRYABLE`, `FAILURE_KIND_DESC` | +| `training/curriculum/rows.py` | Assemble rows: situation state, standing questions, primitives | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `add_prims`, `RENAMES` | +| `training/curriculum/standalone.py` | Non-situation primitive families | `json_invariants`, `http_semantics`, `js_errors`, `described_options`, `DECIDE` (12), `HTTP_CASES` (15), `JS_ERRS` (9), `JS_KIND_DESC` (8 kinds) | +| `training/curriculum/rt.py` | Runtime-exact rendering (port of runtime `situation/{facts,describe,build,serialize,questions}.ts`) | `render`, `to_state`, `section_limits`, `size_chars`, `signature`, `is_id`, `mutation_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`, `subject_sentence`, `event_lines`, `in_flight_lines`, `state_lines`, `stats_lines`, `order`, `provenance`, `started_rel`, `user_relation`, `failure_text`, `failure_counts`, `error_rate_text`; ports of `util.ts` `truncate`, `secs`, `rel`, `fmt_num` (`fmtNum`), `ratio`, `plural`, `ordinal`, plus `times` (a local helper of `facts.ts`); constants `DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `TRIGGER_ACTIONS`, `ACTION_INSTR`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `COMPACT_QUESTIONS_MAX`, `BUDGETS`, `RANK`, `LIMITS`, `WINDOW`. `LINE` and `err_rate` are defined but unused. | +| `training/eval_runtime.py` | Evaluation: accuracy, NLL/Brier/ECE, temperature fit, gate metrics, SIM cost regret | `collect`, `get_records` (+ `dump_records`, `load_records`), `fit_calibration`, `fit_tau`, `fit_tau_noul`, `probs`, `group_of`, `canonical`, `softmax`, `ece`, `question_metrics`, `decision_metrics`, `load_rows`, `main`; `TIER`, `PASSIVE`, `THRESH`, `N_BINS` | +| `training/report.py` | Markdown tables (for EVAL.md) from eval reports | `main` (`name=path ... [--mode=kind\|raw\|group\|header]`) | +| `training/export_runtime.py` | ONNX export, q8/fp16 graph surgery, parity, model directory | `main`, `make_q8`, `make_fp16`, `quantize_embedding`, `gemm_to_matmul`, `requests_from_rows`; `CARD_FORMAT`, `OUTPUTS` | +| `training/ortweb/validate.mjs`, `package.json` | onnxruntime-node + onnxruntime-web 1.30.0 (WASM in Node) parity and latency check | CLI `node validate.mjs <dir> [variant=q8] [maxRequests=60]` | +| `training/configs/mix_*.json` | Mixture configs (`jev_local/train/stream.py` → `MixConfig`) | `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` | +| `training/node.sh` | ssh/rsync wrapper for Azure hosts | `node.sh HOST sync\|'cmd'\|get R L\|put L R` | +| `training/import_sim.sh` | Pull a SIM run to c01, shard train (stage 2) | `import_sim.sh SIM_OUT_DIR NAME` | +| `training/import_final.sh` | Pull a frozen SIM run, shard, build eval subsets, bundle for nodes | `import_final.sh SIM_OUT_DIR NAME` | +| `training/launch_s2.sh` | Launch stage-2 pilot runs (R32, R17) | no args | +| `training/launch_final1.sh` | Launch final round 1 | `launch_final1.sh R32_PASSES R17_PASSES` | +| `training/final_post.sh` | On a rank-0 node: SIM eval → export → serve tar on :8801 | `final_post.sh MODEL NAME VERSION` | +| `training/eval_sim.sh` | On c01 / a rank-0 node: sharded parallel logit collection over `data/NAME_t*`, `data/NAME_d*`, merge, one SIM eval per model (dev-fitted temps) | `bash eval_sim.sh NAME model...` → `out/eval/<M>-NAME.json`, `out/cal/<M>-NAME.json`, marker `out/eval/.done-sim-NAME` | +| `training/run_evals.sh` | On c01: stage-1 eval batch, 10 threads per job | `bash run_evals.sh TAG model...` → `out/eval/<M>-{rt1,sim,cur1,cur2}.json`, `out/cal/<M>.json` (rt1-dev fit), marker `out/eval/.done-TAG` | +| `training/pull_ckpt.sh` | Tar `~/gcl-train/models/NAME` on a node, serve it on `<node private IP>:8801`, untar into c01 `~/gcl-train/models/` | `pull_ckpt.sh NAME NODE` | +| `training/pull_on_train.sh` | On the train VM: wait for an export tar, unpack, sha256 check, run validate.mjs | `pull_on_train.sh IP MODEL ROUND SUB` | +| `training/deliver_final.sh` | From the Mac: same delivery as above, driven remotely | `deliver_final.sh MODEL NODE ROUND SUB` | +| `training/samples/runtime_samples.txt` | 75 hand-written lines of runtime-like text (7 subject sentences, facts, timeline lines, question headers, key names, action/diagnosis labels) for `prune_vocab.py analyze --group runtime=...`. Written before CORE's situation code: uses `op N` refs, not the runtime's `#N`. | — | +| `training/tests/test_*.py` | pytest suites (VM only) | see Tests | + +## Concepts and data structures + +Terms beyond the shared [glossary](glossary.md) (op, situation, questions, diagnosis, action, passive, mode, tier, budget, R17/R32, q8, `situation-v1`): + +| Term | Meaning here | +|---|---| +| CONTRACT-D row | One jsonl training example `{id, split, family, state, questions, labels, meta}` (CONTRACT §11). For decision/ask rows `state` is the Jev state object (`app, trigger, facts, in_flight, timeline, state, stats`, key names varied in non-canonical styles); standalone rows use other keys (`request`/`response`/..., `error`/`stack`/`recent`, `situation`, a store name) or a plain string. `questions` maps qid → `{type, instructions, criteria}`. | +| Label formats | Parsed by `jev_local/train/train.py` → `parse_target`: noul `{"type":"noul","p":0..1}`; choice `{"type":"choice","label":x}` (x must be an offered label) or `{"dist":{x:p}}` (renormalised over offered labels); score `{"type":"score","level":k}` (0 ≤ k < K) or `{"dist":[...]}` (length K). In training a rejected label leaves that question in the input but unsupervised (counted as `bad_labels` in the log); the curriculum generator's `_validate` drops such rows entirely. | +| Standing questions | `action` (applicable actions, passive first) and `diagnosis` (10 labels). The runtime asks `action` only when ≥ 2 actions apply. | +| Primitive question | Exact-label question about the trace (qids `t_*` temporal, `c_*` causal, `v_*` versions, `i_*` identity, `o_*` outcomes, `b_*` baselines, `f_*` failure, `j_*` JSON, `h_*` HTTP, `js_*` JS errors, `decide`, plus scenario-specific `l_newer`, `d_same`, `d_gap`, `n_settled`, `n_explained`, `tr_novel`, `tr_hist`, `e_appcode`, `e_state`, `e_comp`). | +| Scenario / case | A builder in `scenarios.py` / `scen_ops.py` / `scen_state.py` returns a `Scen`; `Scen.case` is `"<builder>/<case>"`, e.g. `typeahead/stale`, `request/double_submit`. | +| `Scen` fields | `trigger, case, subject, subj, facts, actions, action (str or dist), diag (str or dist), state_paths, extra_state, stats_sigs, prims, exclude_inflight, trace, spec`; property `passive_best`. `spec` carries what `rt.py` needs (`cause`/`op`, `paths`, `after`, `cached`, `usual_per_10s`, `recent_count`, `err_rate`, `rel`, `values`, `held`, `fields`, `lc_age`, `unusual_text`, `chain_fields`, `repetition`, `no_runtime`, ...). | +| Trace | `world.py` → `Trace`: `ops` (id → `Op`), `writes` (`Write{t, path, version, op, summary}`), `extras` (error/nav/offline events), `baselines` (sig → `Baseline{sig, med, p95, err_rate, n}`), `version0/values0`, `now`. All ground truth is computed from the Trace, never from rendered text. | +| Style (varied) | `fmt.py` → `Style`: op-ref format (`op {n}`, `#{n}`, `op#{n}`, `req {n}`, `[{n}]`, `op-{n}`), 6 time formats (`rel_s`, `rel_ms`, `ago`, `clock`, `offset`, `t_minus`), duration format, 4 timeline line formats (A–D), key-name variants. 55% of rows use the canonical style. | +| Runtime-exact (style `runtime`) | Row rendered by `rt.render`: exactly the runtime's subject sentence, facts, `#id` refs, sections, budget shaping and standing questions. `meta.style` = `"runtime"`; otherwise `"varied"`. SIM rows have no `style` (eval groups them as `"sim"`). | +| Held-out templates | `fmt.pick_from`: the trailing `held_count(n)` = max(1, round(0.2 n)) entries of any list with ≥ 4 entries are test-only. | +| Held-out domains | `vocab.TEST_DOMAINS` (13 of 62): auction, ci dashboard, energy usage, forum, insurance claims, language learning, maps, parking, payroll, photo gallery, recipes, restaurant reservations, weather dashboard. Test rows use only these; train/dev never. | +| Bucket | A mixture group = the parent directory name of a shard file (`jev_local/train/stream.py` → `_names`), e.g. `data/s3/simA/shard07.jsonl` → bucket `simA`. A top-level `bucket` field in a row would override it (`_row_fields`); curriculum and SIM rows have none. | +| Pass / `pass_tokens` | One draw of the mixture; bucket token budget = weight × `pass_tokens`. `--passes` may be fractional. | +| Servable checkpoint vs trainer state | `--out models/<M>` (`backbone/`, `heads.safetensors`, `calibration.json`, `meta.json` with `final`) vs `runs/<run>/ckpt` (weights + optimizer, used by `--resume` and as `--init-from`). | +| Stage 1 / 1c / 2 / final round | s1: curriculum `cur1` + v1 `gen`/`cu` replay (`mix_s1`); s1c: continuation with runtime-exact `cur2` (`mix_s1c`); s2: pilot on pre-freeze SIM `r300k` (`mix_s2`); final1: frozen SIM phase A + replay (`mix_final1`). | +| FIR | False-intervention rate = gate fires on passive-best rows ÷ passive-best rows (per mode). | +| Replay | Curriculum/v1 buckets mixed into SIM training (`cur*`, `gen`, `cu`). | +| Hosts | `train` VM (10.0.0.4; SIM runs, delivery, MODEL's node_modules), `c01` (10.0.0.6; TRAIN workbench: prune, generate, eval, export, data hub), `c02`–`c11` (F80 training nodes; c02 = 10.0.0.7 is R32 rank 0, c09 = 10.0.0.14 is R17 rank 0). F80 ≈ $5.46/h (LOG). | +| `Op` (curriculum) | `world.py` → `Op{id, kind (user\|fetch\|timer\|ws\|task\|load), start, method, url, sig, body, end, status (ok\|error\|aborted), code, err ("timeout"\|"network error"\|""), cause, root, action, target, value, attempt}`; properties `req`, `identity` (`"{method} {url} {body}"`), `idempotent` (GET/HEAD/PUT/DELETE/OPTIONS). Ids start at `rng.randint(3, 400)` and advance by 1/1/1/2/3. `root` is inherited from `cause` at creation. | +| `Trace` API | Builders `user`, `timer`, `fetch`, `finish` (status `ok` iff code < 400 and no err), `abort`, `init_field`, `write` (version = previous + 1), `extra`, `baseline`; queries `version(path, t)`, `writes_between`, `last_write`, `value`, `in_flight(t)` (fetches with `start < t`, so a `request` subject created at `now` is not in flight), `requests`, `users`, `root_of`, `root_desc`. `scenarios.cap_now` turns fetches ending after `now` back into in-flight ops. | + +Model candidates (README, EVAL.md, LOG; embedding arithmetic from the verified row counts): + +| | R17 | R32 | +|---|---|---| +| Init | `jhu-clsp/ettin-encoder-17m` (MIT), downloaded to `~/jev/models/base/ettin-encoder-17m` (`pytorch_model.bin`) | GenClass 0.1 `models/jev-local-fast` (v1, Apache-2.0, trained on the repo's own synthetic `data/cu` + `data/gen`), a fine-tune of ettin-encoder-32m (MIT) | +| Backbone | ModernBERT/ettin, d 256, 7 layers | ModernBERT/ettin, d 384, 10 layers | +| Heads | fresh (seeded by `jev_local/engine/encoder/engine.py` → `init_model`) | v1 heads | +| Nominal size | 17M parameters (full 50,368-row vocabulary) | 32M parameters (full vocabulary) | +| Embedding after pruning | 50,368 × 256 ≈ 12.9M → 16,364 × 256 ≈ 4.2M params | 50,373 (50,368 + 5 markers) × 384 ≈ 19.3M → 16,364 × 384 ≈ 6.3M params | +| Pruned start point | `models/base/ettin-17m-v16k` (HF base; markers appended by `init_model`) | `models/r32-v16k` (pruned fast-engine checkpoint) | +| `--base` in launches | `$G/models/base/ettin-17m-v16k` | `$G/models/r32-v16k/backbone` | +| q8 / fp16 export (stage 1c) | 9.58 MB / 13.57 MB | 22.47 MB / 34.79 MB | +| Intended use | WASM default | WebGPU, only if clearly more accurate | + +`models/r17-v16k-init` (random heads, used by `test_export_runtime.py` and MODEL's latency runs) also exists on c01; the command that created it is not recorded (`jev_local/train/train.py` has `--init-only`, which writes an untrained servable with meta `trained: false`; unverified that it was used). + +Primitive question ids (`prims.py`; `add_prims` dedups by `(instructions, type)` and suffixes a repeated qid with `2`, `3`, ...): + +| Builder | qid → type | +|---|---| +| `temporal` | `t_before` noul, `t_first` choice, `t_ooo` noul (out-of-order response), `t_lastend` choice, `t_inflight` score (0..3) | +| `causal` | `c_root` choice, `c_same` noul, `c_count` score (none/one/two/three or more) | +| `versions` | `v_changed` noul, `v_newer` noul, `v_behind` score (0/1/2/3 or more), `v_writer` choice | +| `identity` | `i_ident` noul, `i_which` choice, `i_sameact` noul, `i_gap` score (<100 ms / 100 ms–1 s / 1–5 s / >5 s) | +| `streak_q` | `o_streak` score (0..5 or more), `o_last` noul | +| `latency_q` | `b_ratio` score (`RATIO_LEVELS`: <1.5×, 1.5–3×, 3–10×, ≥10× the median), `b_p95` noul (elapsed > p95), `b_anom` noul (ratio > 3 and elapsed > p95) | +| `failure_q` | `f_kind` choice over 4 of the 9 `FAILURE_KIND_DESC` kinds (timeout, network, rate_limited, auth, forbidden, not_found, conflict, validation, server; `failure_kind` maps code/err), `f_retry` noul = (idempotent or idempotency key) and `RETRYABLE[code]` (default True) | +| scenario-specific | `l_newer` noul (`mut_live`), `d_same` noul / `d_gap` score (`mut_dupchange`), `n_settled` score / `n_explained` noul (`inconsistency`), `tr_novel` noul / `tr_hist` score (`transition`), `e_appcode` noul / `e_state` noul / `e_comp` choice (`error`) | + +Standalone families (`standalone.py`, 28% of rows; `meta.kind = "prim"`): + +| Family (`family`) | Content | qids | +|---|---|---| +| `cur/prim/json_invariants` | a store as nested JSON, flattened keys, or a JSON string; 2–4 of the checks total / count / selected / unique / nonneg; "which relation is violated" when ≤ 1 is broken; a price-threshold count | `j_<check>` noul, `j_which` choice, `j_count` score (overwrites the count check, see Gotchas) | +| `cur/prim/http` | one of 15 `HTTP_CASES` (code, err, headers, body) rendered as a dict (50%) or one line; 30% of POSTs carry an idempotency key; `meta` adds `code`, `err` | `f_kind`, `f_retry`, `h_wait` score (429/503 with Retry-After), `h_auth` noul (401), `h_side` choice client/server/network (not for timeouts), `h_field` choice (422 only) | +| `cur/prim/js_errors` | one of 9 `JS_ERRS`; 25% third-party stacks (`THIRD_PARTY`), else first-party component frames; dict or raw "Uncaught ..." text (30%) | `js_kind` choice over 4 of 8 `JS_KIND_DESC` kinds, `js_first` noul, `js_comp` choice (first-party only) | +| `cur/prim/decide` | one of 12 `DECIDE` described-option situations (e.g. 401 with/without refresh token) | `decide` choice | + +Remote layout (scripts and LOG; `G=/home/azureuser/gcl-train`): + +| Where | Path | Contents | +|---|---|---| +| Mac | `~/.jev-local/azure_hosts`, `~/.ssh/jev_azure` | host table (name, public IP, private IP), ssh key (user `azureuser`) | +| every node | `~/gcl-train/training/` | rsynced copy of `training/` (`node.sh sync`, `--delete`) | +| every node | `~/jev/{jev_local,scripts,pyproject.toml}`, `~/jev/.venv/bin/python` | jev code (rsync without `--delete`) and the Python env (`$PY`) | +| every node | `$G/data/<set>/`, `$G/data/s{1,1b,2,3}/<bucket>/shardNN.jsonl` | generator / SIM outputs; stream roots with one dir per mixture bucket | +| every node | `$G/models/<M>/` | servable checkpoints (`--out`) | +| every node | `$G/runs/<run>/{ckpt/,log.jsonl}` | trainer state (`--runs-dir`) and the rank-0 training log | +| every node | `~/jev/runs/<run>/rank<R>.out` | stdout/stderr of each node's torchrun (`scripts/launch_run.sh`) | +| every node | `$G/cache/<round>/` | stream index cache (`--stream-cache`) | +| c01 / rank-0 nodes | `$G/out/{eval,cal,records,export-<M>}/`, `$G/logs/` | eval reports, calibration files, cached logits, exports, job logs | +| c01 / nodes | `~/xfer/` | tars served by `python3 -m http.server` (ports below) | +| train VM | `~/gcl/sim/sim/out/<run>/` | SIM outputs (`r300k`, `final-a`) | +| train VM | `~/gcl/train-out/<round>/<sub>/`, `~/gcl/train-out/ortweb/` | delivered exports; validation dir (`node_modules` → `~/gcl/model/node_modules`, Node at `$HOME/node/bin`) | + +Stream-root contents (which bucket lives under which root). Only `data/s2/<NAME>` and `data/s3/<NAME>` are created by scripts; the rest is inferred from launch flags and mixtures (unverified): + +| Root | Buckets | +|---|---| +| `data/s1` | `cur1`, `gen`, `cu` (stage 1); also streamed in s2 and final1 | +| `data/s1b` | `cur2` (streamed from s1c on) | +| `data/s2` | `sim1` (`import_sim.sh`), `cur3` (README) | +| `data/s3` | `simA` (`import_final.sh`); `cur4` must also sit under `data/s3` or `data/s1` for `mix_final1.json` to find it (no script puts it there; see Gotchas) | + +Datasets referenced by configs and scripts (sizes from LOG/EVAL; generator flags marked unverified where not in a script): + +| Bucket / dir | Rows (train / dev / test) | Source | Notes | +|---|---|---|---| +| `cur1` | 800k / 6k / 12k | `generate.py --n 800000 --dev 6000 --test 12000 --seed 1 --workers 72` | all varied style (generated before `rt.py` existed); 818k rows in ≈ 8 s on 72 processes; packed length mean 482 / p95 885 / max 1,208 tokens; sharded into 64 files | +| `cur2` | 400k / ? / 8k | seed 2, `--p-runtime 0.6` | 60% of decision rows runtime-exact, rendered by the first `rt.py` port (pre-freeze wording, 3,200-char budget only) | +| `rt1` | — / 6k / 12k | `--p-runtime 1.0` (seed unverified) | runtime-style eval/calibration set, same pre-freeze port as `cur2`. Only decision rows are rendered runtime-style (and `failure/offline` falls back to varied); ask and standalone rows are varied. 12,000 test rows hold 6,583 decision rows (EVAL.md). | +| `cur3` | 300k | seed 4, `--p-runtime 0.8` | stage-2 replay; adds coincidental-invariant cases; budgets 3,200 / 2,000 / 1,100 at 40/35/25% (before `transient`, compact questions and the 1,000 budget, LOG 18:41–19:02); at `data/s2/cur3` | +| `cur4` | 300k | seed 5, `--p-runtime 0.8` | final replay, frozen `situation-v1` wording (current `rt.py`); the raw set is `data/cur4/{train,dev,test}.jsonl` | +| `gen`, `cu` | — | GenClass 0.1 v1 synthetic data (`data/gen` all, slice of `data/cu`) | replay only | +| `sim1` | 224,051 / 7,426 / 68,790 | SIM `r300k` (pre-freeze) via `import_sim.sh` | `sim1e/test.jsonl` = 20k random test rows | +| `simA` | 448,420 / 14,613 / 137,643 | SIM `final-a` (frozen) via `import_final.sh` | `simAe` = 8k dev / 20k test random rows | +| `simsample` | 200 (123 decision rows) | `sim/samples/sample.jsonl` | zero-shot check in `run_evals.sh` | + +Row `meta` written by the curriculum (`rows.py` → `decision_row`): `kind="decision"`, `trigger`, `case`, `domain`, `passive_best`, `action_gold` (shown name), `action_canonical`, `passive` (shown passive name), `diag_gold`, `action_names` (canonical → shown), `prims`, `heldout_templates_possible`, `soft_action`, `style`. Ask rows (`ask_row`): `kind="ask"`, `trigger="ask"`, `source_trigger`, `case`, `domain`, `prims`. Standalone: `kind="prim"`, `family`, `domain` (+ `code`, `err` for HTTP). Families: `cur/<trigger>/<case suffix>` (builder name dropped, see below), `cur/ask/<trigger>`, `cur/prim/{json_invariants,http,js_errors,decide}`. Curriculum rows carry **no `meta.budget`**. + +## How it works + +### 1. Vocabulary pruning (`training/prune_vocab.py`) + +1. `vocab_layout` classifies a byte-level BPE `tokenizer.json`: ids 0–1 added tokens, 2–244 the 243 base byte symbols, 245+i = result of merge i (50,009 merges in ettin), added tokens from 50254 (whitespace runs, specials, `[unused0..82]`, and in GenClass checkpoints the markers `[Q] [O] [L] [T] [F]`). Raises if a merge result is missing or two merges produce the same token. +2. `prune_tokenizer_json(tj, N)` keeps base ids + the first N merge results + all added tokens, checks closure under composition (raises `merges are not closed under composition`), and remaps ids in kept order: ids < 245+N are unchanged, added tokens move down to 245+N.. . It also remaps `post_processor` TemplateProcessing ids and `padding.pad_id`. +3. `prune_hf_dir` slices every `[vocab, d]` (and `[vocab]`) tensor via `index_select` (`slice_weights`, always writes safetensors; reads `pytorch_model.bin` for HF bases), writes `config.json` (`vocab_size` + remapped `*_token_id`), `tokenizer.json`, `tokenizer_config.json` (`added_tokens_decoder` remapped) and `prune.json` (`merges_kept`, `merges_total`, `vocab_old`, `vocab_new`, `embedding_keys`, `source`, `source_tokenizer_sha256`). +4. `prune_checkpoint` (a GenClass fast-engine checkpoint with `backbone/`) prunes `backbone/`, copies `heads.safetensors` and `calibration.json`, and annotates `meta.json` with `vocab_pruned` and `pruned_from`. Written to a temp sibling then renamed. +5. For an HF base (R17), markers are added later by `jev_local/engine/encoder/engine.py` → `init_model` (resize embeddings, seeded marker init), so markers land at the end. +6. `analyze --src ... --group name=a.jsonl,b.txt --merges 8000,12000,...` reports tokens-per-char inflation vs the full vocab (`iter_texts` tokenises state segments `"key: text"`, question headers and items like the packer; `.txt` = one text per line; `--limit-rows` default 2000). + +Result used everywhere: N = 16,000 merges → vocab **16,364** = 245 + 16,000 + 119; markers `[Q] [O] [L] [T] [F]` = ids **16359–16363**. R32 and R17 tokenizers are identical (LOG). Inflation at 16k: +10.8% tokens on runtime-like text, +12.3% v1 gen, +10.9% v1 cu (LOG table). + +### 2. Curriculum generation (`training/curriculum/generate.py`) + +1. `main` builds jobs of `--chunk` (default 5000) rows per split; dev default = max(2000, n/50), test default = max(4000, n/25). Workers run `work(split, chunk, n, seed, out)` with `random.Random(f"{seed}:{split}:{chunk}")`, so output is independent of `--workers` but depends on `--chunk`. +2. `make_row`: test split draws a domain from `TEST_DOMAINS`, else from train domains; builds `App` and `Style.make(rng, test)`; picks a kind from `KINDS` = decision 0.58, ask 0.14, json 0.10, http 0.08, js 0.04, decide 0.06. +3. Decision/ask: pick a trigger from `TRIGGERS` (mutation 0.26, request 0.20, failure 0.18, stall 0.12, inconsistency 0.09, transition 0.08, error 0.07), run its builder → `Scen`, then `rows.decision_row(sc, app, st, rng, P_RUNTIME)` or `rows.ask_row`. +4. `decision_row`: if `p_runtime > 0` and `rng.random() < p_runtime`, call `rt.render`; on success emit runtime-exact state/questions (labels restricted to offered actions, 0–2 primitives: choice of (0,0,1,2), `style="runtime"`). Otherwise varied: `situation_state` (≤ 12 facts, shuffled 25%; ≤ 8 state lines; timeline ≤ 16; in-flight ≤ 6; 15% drop one of in_flight/stats/state; 10% shuffle key order; key names from `Style`), `action_question` (10%: rename via `RENAMES`; 15%: insert 1–2 `DISTRACTOR_ACTIONS`; 50% shuffle; descriptions canonical or paraphrased; 10% bare names), `diagnosis_question` (20%: subset keeping gold + `expected` + 2–5 others; 50% shuffle; 10% bare labels), 15% question order swapped, `action` removed if < 2 actions, 0–3 primitives (choice of (0,1,2,2,3)). +5. `_validate` runs `jev_local.serialize.state_segments`, `question_block` and the trainer's `parse_target` on every label; invalid rows are counted in `stats["bad"]`, generator exceptions in `stats["errors"]`; neither is emitted. Each chunk tries at most 3n times. +6. Valid rows get id `cur-{split}-{chunk:05d}-{i:06d}`; `fmt.js_numbers` is applied to `state` and `questions` (integral floats → ints, NEEDS item 8). Chunks are concatenated into `{train,dev,test}.jsonl`; `stats.json` has per-split counters and `passive_best_fraction` per trigger. + +Ask rows (`rows.ask_row`): the same `Scen` situation via `situation_state(..., ask=True)` with the trigger line replaced by "Developer question about the current situation." / "ask" / "Question from the app developer.", `facts` dropped 30% of the time (the answer must then come from timeline/state), and 2–5 primitives only (a row with none is discarded). Family `cur/ask/<trigger>`. + +Varied-style wording vs the runtime's: `rows.action_question` draws instructions from `fmt.ACTION_INSTR[trigger]` and `rows.diagnosis_question` from `fmt.DIAG_INSTR`. For mutation, request, stall and error the first entry equals the runtime's `ACTION_INSTRUCTIONS`; for failure ("...with this failure?"), inconsistency and transition, and for the diagnosis question ("What is going on here?"), the varied lists do not contain the runtime sentence. The exact runtime instructions (`rt.ACTION_INSTR`, `rt.DIAG_INSTR` = "What is happening here?") appear only in runtime-exact rows. Descriptions: forced canonical (`ACTION_DESC[a][0]`, `DIAG_DESC[d][0]`, = runtime text) 50% of the time, else `pick_from` over the list (which may also return the canonical entry; held-out tails only on test rows). + +Row families use the case suffix only: `family = f"cur/{trigger}/{case.split('/')[-1]}"` (e.g. `typeahead/stale` → `cur/mutation/stale`), so builders sharing a case name share a family; `meta.case` keeps the full `"<builder>/<case>"`. + +Scenario cases and labels (weights are the `rng.choices` weights in each builder): + +| Trigger | Cases → action / diagnosis | +|---|---| +| mutation (`mutation`: typeahead 0.42, detail 0.20, autosave 0.16, live 0.11, dupchange 0.11) | `*/stale` → discard / stale; `*/moved_inflight` → {defer .7, discard .2, apply .1} / {stale .8, conflict .2}; `fresh`, `older_between`, `same_root`, `two_saves_last`, `live/newer`, `dupchange/separate_clicks`, `dupchange/idempotent_set` → apply / expected; `dupchange/dup_append` → discard / duplicate | +| request | `double_submit`, `same_root_get` → coalesce / duplicate; `separate_intent`, `deliberate_repeat`, `polling_ok`, `typing_burst`, `normal` → send / expected; `retry_storm` → delay / overload; `runaway` → {delay .6, block .3, send .1} / overload; `failing_backoff` → delay / failing; `outage_cached` → {serve_cached .55, delay .35, send .1} / failing | +| failure | `transient_get`, `timeout_get`, `post_with_key` → retry / transient; `post_no_key` → deliver / transient; `outage_cached` → {serve_cached .7, deliver .2, retry .1} / failing; `offline` with cache → {serve_cached .6, deliver .4} / failing, else deliver / failing; `rate_limited` → deliver / overload (high rate) or failing; `longpoll_expected` → deliver / expected; `outage_no_cache`, `app_retry_loop` → deliver / failing | +| stall | `tail_get` → hedge / slow; `tail_get_cached` → {hedge .6, serve_cached .3, wait .1} / slow; `api_degraded` → {wait .7, hedge .3} (GET) / slow; `slow_upload` → wait / slow if > p95 else expected; `within_p95`, `slow_endpoint_ok` → wait / expected | +| inconsistency | `partial_sum`, `count_drift`, `negative` → resync (if handler) else rollback / inconsistent; `dup_ids` → same / {inconsistent .6, duplicate .4}; `explained_discount`, `coincidental`, `weak_invariant` → mostly ignore (soft, ≥ 0.8) / expected | +| transition | `missing_write`, `null_write` → soft resync/rollback/ignore mixes / unusual; `common_variant`, `few_obs`, `empty_after_filter` → ignore / expected | +| error | `bad_write` → {rollback .7, ignore .3} / {unusual .6, inconsistent .4}; `third_party`, `resize_observer` → ignore / expected; `unhandled_fetch`, `chunk_load` → ignore / {transient .6, failing .4} | + +Case weights (`rng.choices` in each builder): typeahead stale .36 / fresh .22 / older_between .20 / moved_inflight .12 / same_root .10; detail stale .40 / fresh .30 / moved_inflight .15 / older_between .15; autosave stale .50 / fresh .30 / two_saves_last .20; live stale .50 / newer .50; dupchange dup_append .45 / separate_clicks .35 / idempotent_set .20; request normal .17 / double_submit .13 / same_root_get .07 / separate_intent .10 / deliberate_repeat .08 / retry_storm .08 / failing_backoff .10 / outage_cached .06 / polling_ok .09 / typing_burst .07 / runaway .05; failure transient_get .17 / post_no_key .13 / post_with_key .07 / outage_cached .08 / outage_no_cache .10 / rate_limited .10 / offline .08 / timeout_get .10 / longpoll_expected .09 / app_retry_loop .08; stall tail_get .25 / within_p95 .22 / slow_endpoint_ok .15 / api_degraded .14 / slow_upload .12 / tail_get_cached .12; inconsistency partial_sum .15 / count_drift .12 / negative .09 / dup_ids .08 / explained_discount .16 / weak_invariant .15 / coincidental .25; transition missing_write .25 / null_write .18 / common_variant .22 / few_obs .17 / empty_after_filter .18; error bad_write .34 / third_party .20 / resize_observer .14 / unhandled_fetch .18 / chunk_load .14. + +Offered actions (`Scen.actions`, which become the `action` criteria): mutation always apply/discard/defer; request send/delay/block, + `coalesce` (always for `same_root_get`; for the POST repeat cases only when the earlier identical request is in flight or ended < 2 s ago) and + `serve_cached` for `outage_cached`; failure deliver/retry, + `serve_cached` for `outage_cached` and half of offline GETs; stall `wait`, + `hedge` for GETs, + `serve_cached` for `tail_get_cached`; inconsistency/transition ignore/rollback, + `resync` in 50% of rows (`has_resync`); error `ignore`, + `rollback` only for `bad_write`. So non-GET stalls (`slow_upload`, POST `slow_endpoint_ok`) and every error case except `bad_write` are single-action rows with no `action` question. + +Measured passive-best shares of `cur1` train decision rows: mutation 0.50, request 0.51, failure 0.54, stall 0.63, inconsistency 0.42, transition 0.70, error 0.66 (LOG; generated before the `coincidental` and `transient` changes). + +### 3. Runtime-exact rendering (`training/curriculum/rt.py` → `render`) + +1. Returns `None` (row falls back to varied style) when `sc.spec` is empty or `spec["no_runtime"]` (currently `failure/offline`: CORE cannot produce an offline fact). +2. Per trigger builds facts as `(text, kind, neutral)` tuples with CORE's computations: `mutation_facts` (provenance, per-path versions with same-chain vs other-writer logic and `started_rel` "started 0.09s after #6", inputs moved incl. "is back to", concurrency, baseline, failed cause, pending local change, repetition, delta), `request_common` (provenance, attempt, identical requests in the last 10 s, other same-signature requests, failure streak, rate vs usual, baseline with `error_rate_text`, cache, idempotency), `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`. +3. `order` sorts non-neutral first, then by `RANK` (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), stable; identical to `packages/runtime/src/situation/facts.ts` → `RANK`. +4. Sections: `subject_sentence`, `in_flight_lines`, `event_lines` (timers omitted, like CORE), `state_lines`, `stats_lines` ("F of last N failed" over ≤ 20 outcomes via `failure_counts`). +5. Budget: `GC_RT_BUDGET` env (analysis) or `spec["budget"]` or a draw from `BUDGETS` = 3200 (0.35) / 2000 (0.30) / 1000 (0.35). `to_state` applies `section_limits` (linear between `COMPACT_BUDGET` 1100 and `STATE_CHAR_BUDGET` 3200, `MIN_BUDGET` 500) then shrinks timeline (oldest first) → state → facts (floor 1) → in_flight → stats until `size_chars` ≤ budget; mirrors `packages/runtime/src/situation/serialize.ts` → `toJevState`. +6. Questions: `diagnosis` always, with `DIAG_INSTR` "What is happening here?" and `DIAGNOSES` (10 labels); `action` only if ≥ 2 of `TRIGGER_ACTIONS[trigger]` are in `sc.actions`, with `ACTION_INSTR[trigger]`. At budget ≤ `COMPACT_QUESTIONS_MAX` (1400) every criterion is `null` (bare labels), as in `questions.ts` → `buildQuestions`. +7. Details that matter for byte parity: `app` = `"{app.title} — {app.route()}"`; an empty list section becomes the string `"none"`; `size_chars(state)` = Σ over keys of `len(key) + 2 + len(text) + 1`, where `text` is `"\n".join(value)` for a list and `str(value)` otherwise (= `serialize.ts` → `stateChars`); `failure_text` prints `HTTP <code>` and appends the `world.STATUS_TEXT` reason phrase for a deterministic ≈ 30% of ops (`(op.id * 2654435761) % 10 < 3`), because `Response.statusText` is usually empty in browsers and in SIM. Spec keys `extra_facts` (rendered as `plugin`-kind facts) and `budget` are read by `render` but no scenario sets them, so the budget is always drawn from `BUDGETS` (or `GC_RT_BUDGET`). Mutation rows add `spec["state_extra"]` paths (e.g. the query field) to the state section. + +### 4. Training (stage 1, stage 2, final round) + +1. Sync code to a node: `training/node.sh HOST sync` (rsync `training/` → `~/gcl-train/training/` with `--delete`; `jev_local`, `scripts`, `pyproject.toml` → `~/jev/`). +2. Data must be sharded (the stream index/length cache is built per file in parallel: one 1.8 GB file took minutes, 64 shards 24 s). The import scripts use `split -n l/64`. +3. From the Mac, a launch script calls `scripts/launch_run.sh RUN MASTER_IP NPROC THREADS "nodes" -- <train.py args>`. For each node (in order, node rank = position) it ssh-es and starts `python -m torch.distributed.run --nnodes N --nproc-per-node NPROC --node-rank R --master-addr MASTER --master-port 29500 -m jev_local.train.train --ddp --threads THREADS --run-name RUN ...` detached (`setsid nohup nice -n 5`, from `~/jev` with `.venv/bin/python`), with `OMP_NUM_THREADS=THREADS`, `GLOO_SOCKET_IFNAME=eth0`, `JEV_ENCODER=banded`, `TOKENIZERS_PARALLELISM=false`, `HF_HUB_OFFLINE=1`; stdout/stderr go to `~/jev/runs/RUN/rank<R>.out` while the trainer's own state and `log.jsonl` go to `--runs-dir` (`$G/runs/RUN/`). +4. `jev_local/train/train.py` → `train`: `init_model(--base)`; rank 0 alone loads `runs/<run>/ckpt` if `--resume` and it exists, else `--init-from` (servable dir or trainer-state dir, weights only, fresh optimizer/schedule), then broadcasts. So **rank 0 must be the node holding the `--init-from` path**. +5. Stream mode builds `MixConfig.from_json(--mixture, **CLI overrides)` over `--stream` roots; `stream.py` → `discover` walks each root recursively (`<root>/raw/**` if present, else `<root>/**`; `*.jsonl` and `*.jsonl.zst`; hidden dirs skipped), buckets come from the shard's parent directory name (`_names`), and rows are filtered by their `split` field (default `("train",)`), so dev/test files under a root are ignored. Weights merge over `DEFAULT_BUCKET_WEIGHTS` (the v2 `b1_*`…`s0_families` table, irrelevant here); buckets absent from `bucket_weights` get `OTHER_BUCKET_WEIGHT` = 0.04 unless `buckets` restricts them; weights are renormalised over the buckets actually present, so a missing bucket silently drops out; unknown JSON keys raise. +6. Checkpoints every `--ckpt-every` steps to `runs/<run>/ckpt` and the servable `--out` (meta adds `base`, `max_len`, `run`, `trained`, `step`, `final`); `final: true` only when step ≥ total. `calibration.json` in the servable is the default (all temperatures 1.0). +7. Stop cleanly with `pkill -TERM -f "run-name r32-s1[c] "` on the rank-0 node (bracket trick so pkill does not match itself); ranks agree to drop the partial step and rank 0 checkpoints. + +Runs as executed (LOG; `G=/home/azureuser/gcl-train`). The s1c, s2 and final1 commands (README, launch scripts) all pass `--balance --amp --no-grad-ckpt --device cpu --batch-tokens 8192 --log-every 10 --ckpt-every 50 --runs-dir $G/runs --resume` with 8 ranks × 10 threads per node; the exact `*-s1` commands are not in the repo (unverified beyond LOG): + +| Run | Nodes (rank 0 first) | Mixture / streams | Init | lr / head-lr | grad-accum | max-len | Passes / steps | +|---|---|---|---|---|---|---|---| +| `r32-s1` | c02–c08 (4 × 20 threads) | `mix_s1` | pruned v1 `models/r32-v16k` | 1.5e-4 / 6e-4 | ? | ? (unverified) | 2 planned, stopped at step 190 | +| `r17-s1` | c09–c11 (4 × 20 threads) | `mix_s1` | `models/base/ettin-17m-v16k` + fresh heads | 3e-4 / 2e-3 | ? | ? (unverified) | stopped at step 382 | +| `r32-s1c` | c02–c08, master 10.0.0.7 | `mix_s1c`; `data/s1b data/s1` | `runs/r32-s1/ckpt` | 1.2e-4 / 5e-4 | 3 | 1536 | 1 pass, 312 steps / 36 min | +| `r17-s1c` | c09–c11, master 10.0.0.14 | `mix_s1c` | `runs/r17-s1/ckpt` | 2.5e-4 / 1.5e-3 | 2 | 1536 | 1 pass, 1,092 steps / 39 min | +| `r32-s2` (`launch_s2.sh`) | c02–c05 | `mix_s2`; `data/s2 data/s1b data/s1`, seed 2 | `runs/r32-s1c/ckpt` | 1e-4 / 4e-4 | 3 | 2048 | 1.5, 625 steps | +| `r17-s2` | c09 c10 c11 c06 c07 c08 | `mix_s2` | `runs/r17-s1c/ckpt` | 2e-4 / 1e-3 | 2 | 2048 | 4, 1,664 steps | +| `r32-final1` (`launch_final1.sh`) | c02–c07 | `mix_final1`; `data/s3 data/s1`, seed 3, cache `cache/final1` | `runs/r32-s1c/ckpt` | 1e-4 / 4e-4 | 3 | 2048 | 2.4 × 498M tokens (in progress) | +| `r17-final1` | c09 c10 c11 c08 | `mix_final1` | `runs/r17-s1c/ckpt` | 2e-4 / 1e-3 | 2 | 2048 | 3.0 (in progress) | + +Measured throughput (LOG): `r32-s1` ≈ 215k tok/s (5 s/step), falling to 134k with the 4 × 20 layout; `r17-s1` 165–210k; 1-node R17 pilot 68–70k (4 × 20) vs 93–95k (8 × 10); `r32-s2` ≈ 168k, `r17-s2` ≈ 449k; `r32-final1` ≈ 253k, `r17-final1` ≈ 322–333k tok/s. Stage-1 loss 0.28 / 0.27 at steps 60 / 140; first stage-2 step 0.76 (R32) / 0.80 (R17). Stage 1c logged no dropped questions and no bad labels. + +Final rounds deliberately restart from the stage-1c weights (the s2 pilots saw pre-freeze text). Layout rule from LOG: 8 ranks × 10 threads per F80 node; 4 × 20 left ranks idle ≈ 45% of each step (per-micro-batch Python overhead dominates for these small models). + +### 5. Final-round pipeline (frozen data) + +1. `training/import_final.sh /home/azureuser/gcl/sim/sim/out/final-a simA` (from the Mac): train VM serves the SIM dir on `10.0.0.4:8802`; c01 downloads `{train,dev,test}.jsonl` (+ `stats.json`) into `data/simA/`, splits train into `data/s3/simA/shardNN.jsonl` (64), builds `data/simAe/test.jsonl` (`shuf -n 20000`, random source `yes 7`) and `data/simAe/dev.jsonl` (8000, `yes 8`), shards them into `data/simAe_t{0..3}/test.jsonl` and `data/simAe_d{0,1}/dev.jsonl`, tars `data/s3 data/simAe data/simAe_* data/cur4 training` into `~/xfer/final_simA.tar` (2.57 GB) and serves `~/xfer` on `10.0.0.6:8799`. +2. Start c02–c11, `node.sh <node> sync`, pull and untar `final_simA.tar` from `10.0.0.6:8799` on each node (manual step). `mix_final1.json` needs a `cur4` bucket, i.e. `cur4` train shards under `data/s3/cur4/` or `data/s1/cur4/`; `import_final.sh` bundles the whole `data/s3` and the raw `data/cur4/`, but no script in the repo shards `cur4` into a stream root (presumably done by hand on c01; unverified). If it is missing, the trainer silently renormalises over `simA`, `cur1`, `gen`. +3. `training/launch_final1.sh <R32 passes> <R17 passes>`. +4. On each rank-0 node a detached waiter (not in the repo) waits for `models/<M>/meta.json` `"final": true`, then runs `training/final_post.sh <M> <name> <version>` (example in the script: `r17-final1 genclass-runtime-r17 1.0.0-rc1`): `EVAL_THREADS=12 eval_sim.sh simAe <M>` → `out/eval/<M>-simAe.json` + `out/cal/<M>-simAe.json`; `export_runtime.py --calibration out/cal/<M>-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 --threads 24` → `out/export-<M>/`; markers `out/.post-done-<M>`, `out/.served-<M>`; tar without `ref/` → `~/xfer/export-<M>.tar`, served on `<hostname -I first IP>:8801`. The script runs with `set -u` but not `-e`: a failed eval still runs the export (which then fails on the missing calibration file) and the markers are touched anyway, so check `logs/final-eval-<M>.log` and `logs/final-export-<M>.log`. Its first redirect writes `logs/final-eval-<M>.log` before `eval_sim.sh` creates `logs/`, so `~/gcl-train/logs/` must already exist on the node. +5. On the train VM, detached: `pull_on_train.sh <rank-0 ip> <M> final1 <r17|r32>` polls `http://IP:8801/export-<M>.tar` (400 × 30 s), unpacks into `~/gcl/train-out/final1/<sub>/`, checks each file's sha256 against `model.json` (the card's `bytes` are printed, not compared; same in `deliver_final.sh`), runs `node validate.mjs <dir> q8 120` in `~/gcl/train-out/ortweb` (node_modules symlinked from `~/gcl/model/node_modules`). `deliver_final.sh` does the same driven from the Mac and also copies `validate.mjs` there. + +### 6. Evaluation (`training/eval_runtime.py` → `main`) + +1. `load_rows` reads `<data>/<split>.jsonl` (with `--limit`), keeps `meta`, `labels`, `family` and a `_budget` bucket: `meta.budget` (or `meta.situation.budget`) when present (SIM), else by state chars `≤1100` / `≤2100` / `>2100`. +2. `get_records` → `collect` calls `jev_local/train/eval.py` → `collect` (banded encoder, `max_len` from ckpt meta, default 2048) and keeps one record per supervised question `{id, qid, kind, labels, logits, target, header}`; `header` is `sha1(header)[:12]`. With `--records-dir`, raw logits are cached as `<ckpt.name>__<data.name>__<split>.jsonl` and **reused whenever the file exists**. +3. Calibration: `--calibration file` loads `noul/choice/score/by_header` (action and diagnosis use `choice`). `--fit-split dev` instead fits: `fit_tau` (golden section on log τ in [0.2, 5], 40 iterations, soft-target NLL) for `choice` (all choice questions incl. standing ones), `score`, `action`, `diagnosis`; `fit_tau_noul` (61-point log grid in [0.2, 5]); `by_header` for standing-question headers with ≥ 300 records. A split-half check fits on even `crc32(id)` and scores odd ids. +4. For each mode in raw/kind/group/header (only raw without temperatures): `question_metrics` (per group `action`, `diagnosis`, `choice`, `score`, `noul`, `all`: n, acc, NLL, Brier, ECE with 15 bins) and `decision_metrics`. +5. `decision_metrics` (rows with both `action` and `diagnosis`): maps shown names back with `meta.action_names`; passive-best = gold == `PASSIVE[trigger]` (fallback `meta.passive` for unknown triggers) or `TIER[gold] == "passive"`; per mode guard (guard tier) / heal (guard + heal): *A* = offered actions whose tier is permitted (unknown names default to heal), candidate = argmax p over *A*, fire iff Σ p(A) ≥ `THRESH[tier(candidate)]` and top diagnosis ≠ `expected`. Counts FIR, precision (candidate == gold), recall (on rows whose gold is a permitted non-passive action), and with `meta.costs`: mean cost of policy / always-passive / oracle and harm on passive rows. Breakdowns `by_trigger`, `by_case`, `by_style`, `by_budget`; `sweep` at 0.5/0.6/0.7/0.8/0.9/0.95 (heal set); `diag_confusion`; top-30 `false_fires_detail` (`mode:trigger:cand<-gold`). +6. `primitive_acc` per qid family (trailing digits stripped). Report JSON to `--out`; `--write-calibration` writes `{noul, choice, score, by_header, _fit}` (`by_header` only with `--header-calibration`, else `{}`). The fitted `action` / `diagnosis` temperatures are only recorded in `_fit.taus`: the shipped file applies `choice` to the standing questions unless `--header-calibration` adds their exact headers (lookup is by header, then by kind, with optional `by_bucket` / `tau_k` / `noul_platt` steps in between that these files never contain; there is no per-qid key: `packages/runtime/src/model/calibrate.ts`, `jev_local/engine/encoder/calibrate.py` → `calibrate_logits` / `tau_for`). If both `--calibration` and `--fit-split` are given, the fit wins. Console prints the `kind` mode summary. +7. Report layout: `ckpt, data, split, n_rows, n_questions, taus, calibration_from | calibration_fit_on, split_half{taus_even, odd_raw, odd_with_even_taus_{kind,group,header}}, questions_<mode>{<group>: {n, acc, nll, brier, ece}}, decisions_<mode>{n, action_acc, diag_acc, modes{guard,heal}, by_trigger, by_case, by_style, by_budget, sweep, diag_confusion, false_fires_detail}, primitive_acc`. Each `modes.<m>` = `{false_intervention_rate, false_fires, passive_rows, precision, fires, recall, active_rows[, mean_cost{policy, always_passive, oracle, rows, harm_on_passive_rows}]}`. +8. Batch drivers: `run_evals.sh TAG M...` (stage 1, per model in parallel): `rt1` test with `rt1` dev fit → `out/cal/<M>.json`, then SIM sample (`data/simsample/test.jsonl`, how it was created from `sim/samples/sample.jsonl` is not scripted) with that calibration; `cur1` test with its own dev fit; `cur2` test raw. `eval_sim.sh NAME M...`: for every shard dir `data/NAME_t*` (test) and `data/NAME_d*` (dev) it runs `eval_runtime.py --records-dir out/records --batch 32 --threads $EVAL_THREADS` in parallel only to fill the logit cache, concatenates `out/records/<M>__NAME_t*__test.jsonl` → `<M>__NAME__test.jsonl` (same for dev), then one `eval_runtime.py --data data/NAME --split test --fit-split dev --write-calibration out/cal/<M>-NAME.json` reads the merged cache. +9. `training/report.py name=report.json ... [--mode=kind]` (default `kind`; falls back to `raw` when the report has no `decisions_<mode>`) prints the EVAL.md tables (main table, SIM cost table when `mean_cost` exists, per trigger, per budget, sweep, taus + split-half NLL/ECE). + +### 7. Export (`training/export_runtime.py` → `main`) + +1. `load_checkpoint(--ckpt, encoder="reference")`; calibration = `--calibration` file if given, else the checkpoint's (all 1.0 after training). `ExportModel(enc, heads)` and `plan_inputs`/`unpack` are imported from `scripts/genclass_export.py` (single source of the graph; same I/O as GenClass 0.1). +2. Parity requests: `--requests file` or `requests_from_rows(--data-rows, --n-per-file (40), max_tokens 1500)` (random rows per file, seed 0). Written to `requests.json`. +3. `torch.onnx.export` (opset `--opset` 17, `dynamo=False`, dynamic axes L/G/K/S/K2/M) of fp32 and a `.half()` copy into `--out/ref/` (`<name>-fp32.onnx`, `<name>-fp16-fullemb.onnx`). +4. `make_q8`: `gemm_to_matmul` (Gemm with transA=0, alpha=beta=1 → MatMul + Add, so the noul head's first layer is quantised too) → onnxruntime `MatMulNBitsQuantizer` (`DefaultWeightOnlyQuantConfig(block_size=--block 32, is_symmetric=True, bits=8, op_types_to_quantize=("MatMul",), quant_axes=(("MatMul", 0),))`) → `quantize_embedding(..., "float32")` → **fp16 check**: any FLOAT16 initializer or Cast-to-FLOAT16 raises `ValueError` → `onnx.checker` → `<name>-q8.onnx`. +5. `quantize_embedding`: finds the single Gather over a `[vocab, d]` initializer, replaces it with `Gather(int8 table) → Cast → Mul(Gather(per-row scale))`; symmetric per row, `scale = max|row| / 127` (zero rows get scale 1), `q = clip(rint(w/scale), -127, 127)`. +6. `make_fp16`: the fp16 graph + int8 embeddings with fp16 Cast/scale → `<name>-fp16.onnx`. +7. Parity on ORT CPU (fp32, fp16, q8; plus 1-thread sessions for q8/fp16) vs PyTorch `FastEngine(encoder="banded")` with the same calibration → `parity.json`; packer outputs → `pack_fixtures.json`; PyTorch logits/probs/header keys → `torch_fixtures.json`. +8. Model directory: `tokenizer.json` (copied from `ckpt/backbone`), `calibration.json`, `meta.json`, `model.json` (card). `ref/` is not part of the card and is excluded from delivery tars. + +CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; the delivery convention is `genclass-runtime-r17` / `-r32`), `--requests` or `--data-rows` is required in practice (with neither, the request list is empty and `main` raises on `max(packs, ...)` before exporting; the requests also fix the dummy shapes used for tracing), `--n-per-file 40`, `--opset 17`, `--threads 16`, `--block 32`. The parity packer is `Packer(tok, max_len=8192)`. `meta.json` `merges_kept` is read from the checkpoint's `meta.vocab_pruned`, which only `prune_vocab.py prune_checkpoint` writes; trainer-written servables (`jev_local/engine/encoder/engine.py` → `write_checkpoint`, called by `jev_local/train/train.py` → `train`) do not carry it, so exports of trained models have `merges_kept: null`. + +### 8. ortweb validation (`training/ortweb/validate.mjs`) + +1. Install `onnxruntime-node` and `onnxruntime-web` 1.30.0 (`training/ortweb/package.json`) in a working dir; run `node validate.mjs <export dir> [q8|fp16] [maxRequests]`. +2. Builds feeds from `pack_fixtures.json` exactly like `plan_inputs` (dummy row when a kind has no question), runs onnxruntime-node CPU (4 and 1 threads) and onnxruntime-web WASM (`numThreads` 1 and 4; `wasmPaths` = the directory of the resolved `onnxruntime-web` entry file), compares raw (uncalibrated) logits with `torch_fixtures.json`. +3. Per backend: `missing_inputs` (`meta.json` `inputs` absent from the session), `max_abs_logit`, `argmax_agree/argmax_total` (questions with > 1 logit), `ms_p50/p90`, `tokens_p50`, `runtime_sized` (requests ≥ 400 tokens), and `est_ms_at_seq_tokens` at 500 / 780 / 1170 tokens (≈ 330 / 600 / 1,000-token states plus the standing questions) from a least-squares fit `ms ≈ a + bL + cL²`. Writes `<dir>/ortweb_report_<variant>.json` (`{dir, variant, file, bytes, results[]}`). +4. It has no pass/fail: a backend error is caught and recorded as `{backend, error}` (the process still exits 0; only unreadable `model.json`/fixtures crash it). There are no thresholds; read `max_abs_logit`, `argmax_agree` and `error` yourself (the delivery scripts print them). + +## Configuration and constants + +| Name | Type | Value / default | Defined in | Effect | +|---|---|---|---|---| +| merges kept | int | 16,000 (`--merges`, required) | `prune_vocab.py` CLI; decision in LOG | vocab 16,364; markers 16359–16363 | +| `analyze --merges` / `--limit-rows` | csv / int | `8000,12000,16000,24000,32000` / 2000 | `prune_vocab.py` → `main` | merge counts compared; jsonl rows read per file | +| `CONFIG_ID_KEYS` | tuple | pad/bos/eos/cls/sep/mask/unk/decoder_start `_token_id` | `prune_vocab.py` | `config.json` ids remapped on prune | +| `--workers` | int | `os.cpu_count() or 8` | `generate.py` | parallelism only (output independent of it) | +| `KINDS` | weights | decision .58, ask .14, json .10, http .08, js .04, decide .06 | `curriculum/generate.py` | row kind mix | +| `TRIGGERS` | weights | mutation .26, request .20, failure .18, stall .12, inconsistency .09, transition .08, error .07 | `curriculum/generate.py` | trigger mix of decision/ask rows | +| `--n` / `--dev` / `--test` | int | 600,000 / max(2000, n // 50) / max(4000, n // 25) (= 12,000 / 24,000 at the default n) | `generate.py` → `main` | split sizes | +| `--chunk` | int | 5000 | `generate.py` | RNG stream unit (changing it changes rows) | +| `--p-runtime` | float | 0.0 | `training/curriculum/generate.py` → `main` | probability that a decision row is rendered runtime-exact (`training/curriculum/rows.py` → `decision_row`: `p_runtime > 0 and rng.random() < p_runtime` → `rt.render`; if `rt.render` returns None (scenario without `spec`, or `spec.no_runtime`) the row falls back to varied style, so the realised share is <= p_runtime). Omitted = 0.0 = no runtime-exact rows. `main()` writes `os.environ["GC_P_RUNTIME"] = str(args.p_runtime)` and sets the global `P_RUNTIME` before the worker pool starts, so a `GC_P_RUNTIME` exported in the shell is overwritten by the CLI value; always pass `--p-runtime` explicitly. | +| `GC_P_RUNTIME` | env float | `"0"` | `generate.py` module level (`P_RUNTIME = float(os.environ.get("GC_P_RUNTIME", "0"))`) | read only when `generate` is imported without `main()` (e.g. `training/tests/test_curriculum.py` → `make_row`); `main()` overrides it from `--p-runtime` | +| `GC_RT_BUDGET` | env int | unset | `rt.py` → `render` | force one budget (analysis) | +| `Style.make(canonical=)` | float | 0.55 | `fmt.py` | share of canonical-style rows | +| `held_count` | fn | max(1, round(0.2 n)) if n ≥ 4 else 0 | `fmt.py` | held-out template tail | +| `TEST_DOMAINS` | set | 13 of 62 | `vocab.py` | test-only domains (test asserts 15–30%) | +| `STATE_CHAR_BUDGET` | int | 3200 | `rt.py` (= `serialize.ts`) | full-size situation | +| `COMPACT_BUDGET`, `MIN_BUDGET` | int | 1100, 500 | `rt.py` (= `serialize.ts`) | section-limit interpolation floor; smallest budget | +| `COMPACT_QUESTIONS_MAX` | int | 1400 | `rt.py` (= `questions.ts` `COMPACT_QUESTIONS_BUDGET`) | bare-label standing questions at ≤ this budget | +| `BUDGETS` | (chars, weight) | (3200, .35), (2000, .30), (1000, .35) | `rt.py` | budget draw; mirrors runtime "auto" budgets (WASM 1 thread 1000 … 4 threads 2000; else 3200: `packages/runtime/src/runtime.ts` → `situationBudget`) | +| `LIMITS` | dict | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `rt.py` | full-budget section sizes | +| `section_limits` | fn | facts 6→12, in_flight 2→6, timeline 3→16, state 3→8, stats 1→4; line caps app 60→120, trigger 180→240, facts 220→260, in_flight 90→120, timeline 100→140, state 100→150, stats 110→140 | `rt.py` | linear in budget between 1100 and 3200 | +| `WINDOW` | ms | 10,000 | `rt.py` (= `facts.ts`) | "in the last 10s" windows | +| mixture `max_repeat` default | float | 2.0 | `jev_local/train/stream.py` → `MixConfig` | per-pass repeat cap per group | +| `OTHER_BUCKET_WEIGHT` | float | 0.04 | `stream.py` | weight of buckets not named in `bucket_weights` | +| `mix_s1.json` | mixture | cur1 .90, gen .04, cu .06; `pass_tokens` 420M; max_repeat `*` 2.0, cur1 1.5 | `configs/` | stage 1 (realised pass 406M: cur1 93.1%, cu 6.2%, gen 0.7%) | +| `mix_s1b.json` | mixture | cur2 .75, cur1 .15, gen .04, cu .06; 250M; cur2 1.2 | `configs/` | not referenced by LOG/scripts (unused, unverified) | +| `mix_s1c.json` | mixture | cur2 .55, cur1 .37, gen .03, cu .05; 520M; cur2 1.5, cur1 1.0 | `configs/` | stage 1c | +| `mix_s2.json` | mixture | sim1 .76, cur3 .12, cur2 .05, cur1 .03, gen .01, cu .03; 420M; sim1 1.5 | `configs/` | stage-2 pilot | +| `mix_final1.json` | mixture | simA .85, cur4 .12, cur1 .02, gen .01; `buckets` = those 4; 500M; `*` 2.0, simA 1.3 | `configs/` | final round 1 | +| `--max-len` | int | trainer default 1536; 1536 in stage 1c (s1 command unrecorded); 2048 stage 2/final (SIM packed p95 1,523, max 1,761) | `jev_local/train/train.py`, README, launch scripts | written to servable/exported `meta.json` `max_len` | +| `--batch-tokens` | int | 8192 | launch scripts | micro-batch token budget | +| `--ckpt-every` | int | trainer default 500; launch scripts pass 50 | `jev_local/train/train.py` | checkpoint cadence (a SIGKILL loses at most this many steps) | +| `MAX_TRAIN_LEN` | int | 8192 | `jev_local/train/train.py` | upper bound for `--max-len` | +| `--seed` | int | s1c 1, s2 2, final1 3 | launch scripts | mixture/shuffle seed | +| `DEFAULT_CALIBRATION` | dict | `{noul: 1.0, choice: 1.0, score: 1.0, by_header: {}}` | `jev_local/engine/encoder/calibrate.py` | what every trainer-written servable ships | +| `node.sh` remote env | env | `PYTHONPATH=$HOME/jev:$HOME/gcl-train/training`, `PY=$HOME/jev/.venv/bin/python`, `HF_HUB_OFFLINE=1`, `TOKENIZERS_PARALLELISM=false`, cwd `~/gcl-train` | `node.sh` | environment of `node.sh HOST 'cmd'` (also set by `eval_sim.sh`, `run_evals.sh`, `final_post.sh`) | +| torchrun master port | int | 29500 | `scripts/launch_run.sh` | DDP rendezvous | +| `TIER` | dict | passive: apply/send/deliver/wait/ignore; guard: discard/defer/coalesce/delay; heal: block/serve_cached/retry/hedge/rollback/resync | `eval_runtime.py` and `fmt.py` (duplicated) | gate tiers (= runtime `BUILTIN_ACTIONS`) | +| `THRESH` | dict | guard 0.9, heal 0.8 | `eval_runtime.py` | gate thresholds (= CONTRACT §8 defaults) | +| `N_BINS` | int | 15 | `eval_runtime.py` | ECE bins | +| τ search range | float | [0.2, 5.0] | `eval_runtime.py` → `fit_tau`, `fit_tau_noul` | temperature fit | +| `by_header` min records | int | 300 | `eval_runtime.py` → `fit_calibration` | per-header τ only when well populated | +| eval `--batch` / `--threads` | int | 16 / 32 | `eval_runtime.py` | collection speed (scripts use 32 / 6–12) | +| `EVAL_THREADS` | env int | 6 | `eval_sim.sh` | threads per shard job (`final_post.sh` sets 12) | +| `CARD_FORMAT` | str | `genclass-runtime-model/1` | `export_runtime.py` | `model.json` `format` (same constant in `packages/runtime/src/model/loader.ts`, which records the field but does not reject other values) | +| `OUTPUTS` | list | `choice_logits`, `score_logits`, `noul_logits` | `export_runtime.py` | graph outputs | +| graph inputs | list | `input_ids, position_ids, q_group, i_group, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f` | `scripts/genclass_export.py` → `plan_inputs` | written to `meta.json` `inputs` | +| export `--opset` / `--threads` / `--block` / `--n-per-file` | int | 17 / 16 / 32 / 40 | `export_runtime.py` | ONNX opset; ORT threads; MatMulNBits block; parity rows per file | +| parity request cap | tokens | 1500 | `export_runtime.py` → `requests_from_rows` | longer rows skipped | +| `meta.json` `max_len` / `max_total` | int | ckpt meta `max_len` or 1536 / 8192 | `export_runtime.py` | runtime packer limits | +| ortweb versions | str | onnxruntime-node 1.30.0, onnxruntime-web 1.30.0 | `ortweb/package.json` | validation runtime | +| validate defaults | args | variant q8, 60 requests (delivery scripts pass 120) | `validate.mjs` | — | +| ports | int | 8798 (train VM → c01 one-off v1 tar), 8799 (c01 data bundles, 10.0.0.6), 8801 (node → c01/train VM tars), 8802 (train VM SIM dir, 10.0.0.4) | scripts, LOG | `python3 -m http.server` transfers on the private network | +| `TIMEOUT` | env s | 900 | `node.sh` | per-call ssh/scp timeout for `'cmd'`/`get`/`put` (`sync` uses fixed 120 s / 600 s timeouts; `scripts/azvm.sh` and therefore `scripts/launch_run.sh` ignore it) | + +Model directory files (`export_runtime.py`): + +| File | Content | +|---|---| +| `model.json` | `{format, name, version, license: "Apache-2.0", variants: {q8: {file, bytes, sha256, provider: "wasm"}, fp16: {file, bytes, sha256, provider: "webgpu", needs: "shader-f16"}}, files: {tokenizer, calibration, meta: {file, bytes, sha256}}}` | +| `meta.json` | `name` (`<name>-<version>`), `source_checkpoint`, `max_len`, `max_total`, `window`, `hidden_size`, `layer_types`, `markers` (from the tokenizer), `cls_id`, `sep_id`, `pad_id`, `vocab_size`, `merges_kept`, `inputs`, `outputs`, `embedding_quant` = `int8-rowwise-symmetric`, `matmul_quant` = `MatMulNBits-8bit-b32-symmetric (q8); fp16 weights (fp16)`, `license` | +| `calibration.json` | as passed (from `eval_runtime.py --write-calibration`: `noul`, `choice`, `score`, `by_header`, `_fit`) | +| `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json` | graphs and pruned tokenizer | +| `parity.json` | per variant: `max_abs_logit`, `max_abs_prob`, `argmax_rate`, `noul_side_rate`, `gate08_rate`, `gate09_rate`, `ort_cpu_ms_p50`, `ort_cpu_1thread_ms_p50`, `file_mb`; `n_requests`, `tokens{min,median,max}`, `embedding_q8` (incl. `fp16_free`, `matmulnbits`, `gemm_converted`, `matmul_unquantized_with_weight`, `fp32_initializer_mb`), `embedding_fp16` | +| `pack_fixtures.json`, `torch_fixtures.json`, `requests.json` | JS parity fixtures (also used by MODEL's TS packer/engine tests) | +| `ref/` | fp32 and fp16-full-embedding reference graphs (not shipped) | + +## Invariants and gotchas + +- **Runtime parity of `rt.py` is load-bearing.** Constants and wording (`DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR`, `TRIGGER_ACTIONS`, `RANK`, `LIMITS`, budgets, `secs`/`rel`/`ratio`/`fmt_num`, `signature`/`is_id`) must equal `packages/runtime/src/situation/{questions,serialize,facts,describe,build}.ts` and `src/util.ts`. They match at this commit (runtime situation code is unchanged since tag `situation-v1` = 1a77558; `rt.py` was re-ported after it). Per-header calibration keys are `sha1(instructions)[:12]`, so any instruction text change silently orphans `by_header` temperatures. +- **Known small parity gaps** in `rt.py`: `to_state`'s last-resort shortening truncates facts to max(40, …) and never shortens the trigger, while `toJevState` uses max(60, …) and then shortens the trigger; Python `round()` (banker's) vs JS `Math.round` in `secs` (≥ 1000 s) and `ratio` (≥ 10×); Python format specs (`f"{x:.2f}"`, half-even on exact binary ties) vs JS `toFixed` (ties up) in `secs`/`rel`/`fmt_num`, e.g. `secs(125)` is `0.12s` in Python and `0.13s` in JS; `truncate` counts code points (Python `len`) vs UTF-16 code units (JS `length`), so text with astral characters such as emoji is cut at different points. Rare, but they produce text the runtime never sends. +- **Numbers as JS prints them.** `fmt.js_numbers` turns integral floats into ints in `state` and `questions` (not in `labels`/`meta`); without it the model trains on `25.0`, which the JS runtime never emits (NEEDS item 8). Keep it when adding new emit paths. +- **Determinism** is per code version: `random.Random(f"{seed}:{split}:{chunk}")`, sorted iteration where sets are involved. Changing any generator code, `--chunk`, or `--p-runtime` from 0 to > 0 (it adds an RNG draw) changes the rows; `cur1`/`cur2` cannot be regenerated byte-identically from the current code (the generator gained `transient`, `coincidental`, budgets and compact questions since). +- **Held-out integrity:** test rows only use `TEST_DOMAINS` and may use held-out templates; train/dev never do. `test_curriculum.py` asserts both. Do not add a domain to `DOMAINS` without deciding its split. +- **Precision first:** decision rows must keep a large passive-best share (test bound 0.45–0.75); soft labels for ambiguous cases lean passive. SIM's passive-best shares are much higher (pre-freeze SIM sample: 70–96% per EVAL.md; phase A train: 64% stall to 99% error, `sim/samples/stats-final-a.json`, see [sim.md](sim.md)), which is why stage 2 is required. +- **Single-action rows** have no `action` question/label (runtime behaviour). `eval_runtime.py` skips them in `decision_metrics`, so `diag_acc` there covers only rows that also have an `action` question. +- **Calibration must be shipped explicitly.** A trained servable's `calibration.json` is all 1.0; `export_runtime.py` without `--calibration` ships uncalibrated temperatures. The runtime gate thresholds assume calibrated probabilities. +- **Stale logit cache:** `eval_runtime.py --records-dir` reuses `<ckpt.name>__<data.name>__<split>.jsonl` if present, even after the checkpoint changed. Delete `out/records/<M>__*` before re-evaluating a retrained model with the same name. `eval_sim.sh` concatenates shard records by this naming. +- **q8 must be fp16-free.** Onnxruntime's WebGPU Gather on an fp16 table requires `shader-f16` ("Program Gather requires f16"); the int8 table + fp32 row scales runs on WebGPU without it (MODEL confirmed in Chromium/SwiftShader). `make_q8` raises on any fp16 tensor or cast; keep the `gemm_to_matmul` rewrite (without it the noul head stays fp32, +2.9 MB). +- **Rank 0 holds the init.** Only rank 0 reads `--resume` state or `--init-from`; the first node in the launcher list must have `runs/<model>-s1c/ckpt` (c02 for R32, c09 for R17). `--resume` wins over `--init-from` when `runs/<run>/ckpt/trainer.json` exists, so reusing a run name resumes instead of re-initialising. +- **Mixture buckets are directory names.** Put shards in `<stream root>/<bucket>/`. Without a `buckets` list, any extra bucket dir under a stream root silently gets weight 0.04 (`OTHER_BUCKET_WEIGHT`); `mix_final1.json` is the only config that lists `buckets`. +- **Marker ids moved.** With the pruned vocab, `[Q] [O] [L] [T] [F]` are 16359–16363; runtime, sim tooling and tests must read them from `tokenizer.json` / `meta.json` (CONTRACT §10). With 16k merges, keys like `trigger`, `facts`, `apply`, `defer` split into several tokens (harmless; trained on the pruned tokenizer). +- **Token budget vs characters:** the runtime's 3200-char budget assumes ≈ 3.2 chars/token, measured ≈ 2.4 (NEEDS 6a), so situations are ≈ 1.3–1.4× the intended 1,000 tokens; 3.9% of SIM `r300k` packed rows exceed 1,536 tokens, hence `max_len` 2048 for stage 2 (LOG). The smaller 1,000/2,000-char WASM budgets were adopted for latency (LOG 19:00 coordinator/MODEL note). +- **Script path layout:** `node.sh`, `import_*.sh`, `deliver_final.sh`, `launch_*.sh` resolve `JEV="$HERE/../.."` (or `cd "$(dirname "$0")/../.."`) and expect `jev_local/`, `scripts/launch_run.sh`, `scripts/azvm.sh`, `pyproject.toml` there. In this monorepo they are at the repo root (`$HERE/..`), so run them from a checkout nested inside a jev tree or adjust the path (unverified). `~/.jev-local/azure_hosts` columns: name, public IP ($2, used for ssh), private IP ($3); key `~/.ssh/jev_azure`, user `azureuser`. Mac-side scripts use GNU `timeout`. Only the Mac-side `.sh` files are committed executable (git mode 100755); `run_evals.sh`, `eval_sim.sh` and all `.py` files are 100644, so invoke them via `bash` / `$PY`. +- **Python import paths:** `export_runtime.py`, `eval_runtime.py`, `generate.py`, `prune_vocab.py analyze` and the tests insert `~/jev` (and `~/jev/scripts`) into `sys.path`; elsewhere set `PYTHONPATH=<repo>:<repo>/scripts:<repo>/training`. +- **`azvm.sh` ignores `TIMEOUT`** (only `node.sh` honours it), so `TIMEOUT=... scripts/azvm.sh` lines in `import_sim.sh`/`deliver_final.sh` and `TIMEOUT=300 scripts/launch_run.sh` in `launch_*.sh` have no timeout. `import_final.sh` deliberately has no `pkill` (a self-killing `pkill` was a past bug: the remote shell's command line matched the pattern); stop the train VM's :8802 server with `pkill -f "http.server 880[2]"` in a command that does not itself contain `http.server 8802`. `import_sim.sh`'s first remote command still has the old pattern (its `pkill` runs only when :8802 is already listening, and the same command line later contains `http.server 8802 --bind`, so it can kill its own shell); stop any running server first or reuse `import_final.sh`'s logic. +- **`pull_on_train.sh` expects `validate.mjs` already in `~/gcl/train-out/ortweb`** (it does not copy it; `deliver_final.sh` does). +- **Bug (curriculum):** `standalone.json_invariants` writes the `count` invariant check as `j_count` and then overwrites `questions["j_count"]`/`labels["j_count"]` with the "price above threshold" score question, so the count==len check never reaches the data. Rows stay valid. +- **Tests do not exercise `rt.py` by default.** `generate.make_row` reads the module global `P_RUNTIME` (from `GC_P_RUNTIME`, default 0), and `test_curriculum.py` calls `make_row` directly, so runtime-exact rendering is only tested with `GC_P_RUNTIME=1` in the environment. Run it both ways after touching `rt.py`. Setting `GC_P_RUNTIME` has no effect on a `generate.py` CLI run; there, `--p-runtime` wins. +- **`rt1` and `cur2` predate the freeze.** They were rendered by the first `rt.py` port (3,200-char budget, pre-`situation-v1` fact wording, no `transient`, no compact questions), so the stage-1c `rt1` numbers measure the old runtime format. Only `cur4` (and SIM `final-a`) use the frozen wording. Regenerating `rt1` with today's code gives a different set. +- **Runtime budgets between the drawn ones.** The runtime's auto budget is `1000 + round((threads - 1) * 1000 / 3)` on WASM (1,000 / 1,333 / 1,667 / 2,000 for 1–4 threads), else 3,200, and either is multiplied by `budgetScale` (starts at 1; × 0.8 per `max_tokens_exceeded` model error, floor 0.5); a numeric `budget` option overrides all of it (`packages/runtime/src/runtime.ts` → `situationBudget`). `rt.BUDGETS` only draws 1,000 / 2,000 / 3,200; intermediate budgets rely on `section_limits` interpolation generalising. +- **Missing mixture buckets are silent.** `stream.py` renormalises weights over the buckets it finds, so a typo in a bucket dir or a forgotten `cur4` shard dir trains on a different mix without an error. Check the plan before or at launch: `python -m jev_local.train.stream <roots...> --mixture <mix.json>` prints it, and the trainer writes `$G/runs/<run>/mixture_plan.json` (corpus summary + pass-0 plan; LOG's "cur1 93.1%, cu 6.2%, gen 0.7%" for `mix_s1` is this kind of realised share). +- **`merges_kept: null` in exported `meta.json`** for every trainer-written checkpoint (see Export). Nothing reads it today; `vocab_size` and `markers` are always set. +- **Dead code in `rt.py`:** `LINE` (superseded by `section_limits`' line caps) and `err_rate` (EWMA emulation, superseded by `failure_counts`) are unused; edit `section_limits` / `failure_counts` instead. +- **Past bugs recorded in LOG:** typeahead requests could start out of keystroke order (fixed with a per-app debounce in `mut_typeahead`); noul head Gemm left fp32 (fixed by `gemm_to_matmul`); Python float literals in rows (fixed by `js_numbers`). +- **Licensing hygiene:** no TRAIN script reads `jev-local-fast-v2`, `meharsjev-68m-z`, `z-cal-*`, `z-mid*` or any benchmark/third-party dataset (verified by grep at this commit). Keep it that way; the model card claims Apache-2.0 synthetic-only data. + +## How to change it safely + +**Reproduce the pipeline** (Azure only; commands run in `~/gcl-train` via `node.sh HOST '...'`, `$PY` and `G` as above): +1. Prune (c01): `$PY training/prune_vocab.py prune --src ~/jev/models/jev-local-fast --out models/r32-v16k --merges 16000` and `... --src ~/jev/models/base/ettin-encoder-17m --out models/base/ettin-17m-v16k --merges 16000`. Optional: `prune_vocab.py analyze --src ~/jev/models/jev-local-fast --group runtime=training/samples/runtime_samples.txt --group gen=<v1 gen jsonl> --out out/inflation.json`. +2. Generate (c01): `cur1` = `generate.py --out ~/gcl-train/data/cur1 --n 800000 --dev 6000 --test 12000 --seed 1 --workers 72`; `cur2` seed 2 `--p-runtime 0.6` (400k train); `cur3` seed 4 / `cur4` seed 5, `--p-runtime 0.8` (300k each). `rt1` used `--p-runtime 1.0` with 6k dev / 12k test (exact command unrecorded). Today's code reproduces none of these byte for byte (see Determinism). +3. Shard each train split into its stream root: `split -n l/64 -d -a 2 --additional-suffix=.jsonl data/<set>/train.jsonl data/<root>/<set>/shard` (roots in Concepts). +4. Stage 1 (`r*-s1`, exact command not in the repo) then stage 1c: the `launch_run.sh r32-s1c ...` / `r17-s1c ...` commands in `training/README.md` §3. +5. Stage 2 / final: `import_sim.sh` + `launch_s2.sh`, or `import_final.sh` + distribute the tar + `launch_final1.sh P32 P17`. +6. Copy servables to c01 if needed (`pull_ckpt.sh <M> <node>`), evaluate (`run_evals.sh` for curriculum sets, `eval_sim.sh <NAME>e <M>` for SIM), tabulate with `report.py`. +7. Export with the fitted calibration, validate with `ortweb/validate.mjs`, deliver with `pull_on_train.sh` / `deliver_final.sh` (or `final_post.sh` on the rank-0 node for the automated tail). + +**Regenerate a curriculum set** (on c01, after `node.sh c01 sync`): +``` +$PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --seed 6 --workers 72 --p-runtime 0.8 +``` +Then shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl <root>/<bucket>/shard`) under a stream root, add the bucket to a mixture, and check `stats.json` (`bad`, `errors` = 0; `passive_best_fraction` sane). Use a new seed and bucket name; never overwrite a set a run is training on. + +**Mirror a runtime situation/question wording change** (CORE changed `packages/runtime/src/situation/*`): +1. Diff the runtime files since the last port and update the matching `rt.py` function (`*_facts`, `subject_sentence`, `event_lines`, `state_lines`, `stats_lines`, `to_state`/`section_limits`, constants). +2. If an instruction or description changed, also update `fmt.py` canonical first entries (`ACTION_DESC[a][0]`, `DIAG_DESC[d][0]`) and expect `by_header` calibration to be re-fitted. +3. Render a few rows at each budget and compare with SIM rows (`sim/samples/sample.jsonl`) for the same situations. +4. Regenerate the replay set (`cur*` with `--p-runtime 0.8`), retrain, re-evaluate. Coordinate a new freeze tag with the lead (SIM data must match). Run `test_curriculum.py`. + +**Add a scenario case:** add it to the builder's `rng.choices` list in `scenarios.py`/`scen_ops.py`/`scen_state.py`, build the `Trace`, facts (via `fmt.pick` templates with ≥ 4 phrasings so one is held out), labels (soft dist leaning passive when ambiguous), primitives (`prims.*`) and a `spec` that `rt.py` can render (or `no_runtime: True`). Keep the passive-best share within 0.45–0.75 and run `test_curriculum.py` (validity, determinism, label consistency, version semantics). + +**Add a diagnosis label or a built-in action:** it must exist in the runtime first (`questions.ts` `DEFAULT_DIAGNOSES` / `BUILTIN_ACTIONS` / `TRIGGER_ACTIONS`). Then update `fmt.DIAG_DESC` (canonical first) or `fmt.ACTION_DESC`, `fmt.TRIGGER_ACTIONS`, `fmt.TIER`, `rows.RENAMES` (optional), `rt.DIAGNOSES`/`rt.ACTIONS`/`rt.TRIGGER_ACTIONS`, and `eval_runtime.TIER`/`PASSIVE` (unknown actions default to heal tier in eval). Add scenarios that use it. + +**Change a mixture / launch a new round:** copy a `configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly), copy `launch_final1.sh` with a new run name, `--stream-cache`, `--out`, `--seed`, and keep rank 0 = the node holding `--init-from`. Use 8 ranks × 10 threads per F80 node. Make sure every bucket named in the mixture has train shards under one of the `--stream` roots (check `mixture_plan.json`). Watch `~/jev/runs/<run>/rank0.out` and `$G/runs/<run>/log.jsonl` on the rank-0 node; deallocate idle nodes. + +**Evaluate a checkpoint and fit calibration:** +``` +$PY training/eval_runtime.py --ckpt models/M --data data/rt1 --split test --fit-split dev \ + --records-dir out/records --out out/eval/M-rt1.json --write-calibration out/cal/M.json +bash training/eval_sim.sh simAe M # SIM: sharded logits, dev-fitted temperatures +$PY training/report.py M=out/eval/M-rt1.json --mode=kind +``` +Clear `out/records/M__*` first if `models/M` was retrained. + +**Export and validate:** +``` +$PY training/export_runtime.py --ckpt models/M --out out/export-M --name genclass-runtime-r17 --version X.Y.Z \ + --calibration out/cal/M-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 +node validate.mjs out/export-M q8 120 # in a dir with training/ortweb/package.json installed +``` +Check `parity.json` (q8 argmax agreement, `embedding_q8.fp16_free: true`, q8 size ≤ 25 MB per CONTRACT §10) and `ortweb_report_q8.json`. Run `test_export_runtime.py` after touching graph surgery. + +**Change the vocabulary size:** rerun `prune_vocab.py analyze` on `samples/runtime_samples.txt` and SIM rows, prune both bases, rerun `test_prune_vocab.py`, retrain from the pruned bases (embedding rows change), and tell MODEL (marker ids and model size change; the runtime reads them from files). + +**Change gate semantics or thresholds in eval:** keep `eval_runtime.py` → `decision_metrics` in sync with `packages/runtime/src/decide/policy.ts` → `gate` and CONTRACT §8; update EVAL.md's "Runtime gate" definition and recompute reports from cached records (`--records-dir` makes this cheap). + +## Tests + +All tests run on a VM (`cd ~/gcl-train && PYTHONPATH=~/jev[:~/gcl-train/training] ~/jev/.venv/bin/python -m pytest -q training/tests/<file>`); none run in the npm/vitest suites. + +| Test file | What it asserts | +|---|---| +| `training/tests/test_curriculum.py` (5 tests) | `test_all_rows_valid_and_deterministic`: 400 train rows from the same seed have identical `state` across two runs (only `state` is compared) and all pass `_validate`; `test_test_split_uses_only_heldout_domains`: train never / test always in `TEST_DOMAINS`, held-out share 15–30%; `test_heldout_templates_never_in_train_picks`; `test_decision_labels_consistent`: action label/dist ⊆ offered criteria, dist sums to 1, diagnosis gold offered, passive offered, passive-best share 0.45–0.75, no `action` label when not asked; `test_stale_vs_benign_versions_semantics`: `v_newer` true for `typeahead|detail/stale`, false for `fresh`, `older_between`, `same_root`, `moved_inflight` | +| `training/tests/test_prune_vocab.py` (6 tests; need `GC_V1_CKPT`, `GC_BASE_32M`) | ettin layout (243 base ids 2–244, merges from 245); pruned tokenizer at 4k/8k/16k encodes random unicode/control text, ids in range, decodes to the same text, never fewer tokens, ids < 245+N unchanged, specials/markers kept and special, markers in user text not matched; logits identical (< 1e-4) to the unpruned v1 model when tokenisation is unchanged (`vocab_new` = 245+N+119); HF-base prune → `init_model` appends markers at V..V+4 and runs a forward pass | +| `training/tests/test_export_runtime.py` (3 tests; e2e needs `GC_R17_INIT`, default `~/gcl-train/models/r17-v16k-init`) | int8 embedding error ≤ scale/2 and zero rows survive; Gemm→MatMul+Add preserves outputs; end-to-end export: card format, bytes/sha256 of every file, `meta.markers`/`cls_id`/`sep_id` match `tokenizer.json`, parity fp32 < 1e-3, q8/fp16 < 0.5 (random heads), R17 q8 < 12 MB | + +Last recorded runs (LOG): `test_prune_vocab.py` 6/6, `test_curriculum.py` 5/5 on c01. No run of `test_export_runtime.py` is recorded. + +Test inputs and skips: `test_curriculum.py` needs `~/jev` on `sys.path` (it imports `jev_local` for `_validate`) and covers only the varied style unless `GC_P_RUNTIME` is set (see Gotchas). `test_prune_vocab.py`: `GC_V1_CKPT` (default `~/jev/models/jev-local-fast`; 5 tests skip without `backbone/tokenizer.json`) and `GC_BASE_32M` (default `~/jev/models/base/ettin-encoder-32m`; the HF-base test prunes it to 8,000 merges and skips without it). `test_export_runtime.py`: the two graph-surgery tests are self-contained (tiny ONNX graphs); the end-to-end test skips unless `GC_R17_INIT/backbone` exists and runs `export_runtime.py` as a subprocess on 6 hand-written requests. + +## Drift and open issues + +Results and status (from EVAL.md / LOG.md; held-out data, temperatures fitted on the matching dev split): + +| Set | Model | Action / diagnosis acc | Guard FIR | Heal FIR | Heal precision (fires) / recall | Notes | +|---|---|---|---|---|---|---| +| `rt1/test` | GenClass 0.1 baseline (zero-shot) | 37.6 / 8.0 | — | 0.0–0.33% | 39% | pruned v1: 37.6 / 43.5 | +| `rt1/test` | R32-s1c | 98.2 / 98.4 | 0.00% (0/3,355) | 0.00% | 100.0 (2,777) / 86.0 | ECE 0.050 / 0.017; mutation hardest (94.1 / 94.4) | +| `rt1/test` | R17-s1c | 98.0 / 98.3 | 0.00% | 0.00% | 100.0 (2,774) / 85.9 | ECE 0.048 / 0.017 | +| `cur1/test` | R32-s1c | 95.8 / 97.8 | 0.00% | 0.60% (23/3,830) | 98.6 (2,544) / 80.2 | | +| `cur1/test` | R17-s1c | 94.0 / 97.2 | 0.03% | 1.70% (65/3,830) | 96.1 (2,510) / 77.1 | stall heal FIR 11.5% (R32 4.5%) | +| SIM sample (123) | R32-s1c / R17-s1c | 51.2 / 49.6; 48.0 / 43.9 | 13.6%; 9.7% | 34.0%; 18.4% | 19.1%; 22.2% | stage 1 does not transfer to SIM labels | +| SIM `r300k` test (20k) | R32-s2-pilot | 77.5 / 90.8 | 0.02% | 0.06% (6/10,234) | 75.5 (49) / 1.3% | cost policy 33.99 vs passive 34.03 vs oracle 32.88 | +| SIM `r300k` test (20k) | R17-s2-pilot | 78.3 / 91.1 | 0.00% | 0.08% (8/10,234) | 65.5 (58) / 1.4% | cost 33.97 / 34.03 / 32.88 | +| SIM phase A | R32/R17-final1 | — | — | — | — | launched 00:06 UTC 2026-10-08, ETA ≈ 01:30; no results in repo | + +Size/latency (stage 1c exports): R17 q8 **9.58 MB** / fp16 13.57 MB, WASM 1-thread 188 / 339 / 608 ms at 500 / 780 / 1,170 tokens, ORT CPU 1-thread 39 / 71 / 132 ms; R32 q8 22.47 / fp16 34.79 MB, 499 / 879 / 1,539 ms, 93 / 163 / 289 ms. q8 vs PyTorch agreement (argmax / gate@0.8 / gate@0.9): R17 99.5 / 99.4 / 98.8%, R32 100 / 97.0 / 99.4%. Calibration: τ choice 0.71, score 0.59–0.66, noul 0.85–1.0. Cost to 23:05 UTC ≈ $215. + +More numbers from EVAL.md / LOG (same sources): +- `rt1/test` guard mode: precision 100.0% (1,398 fires), recall 88.5% for both models; all-question accuracy R32 96.3%, R17 96.1%; no false fire at sweep t ≥ 0.6 (R32 has 8 at t = 0.5). Split-half on `rt1` dev: NLL 0.078 → 0.070, ECE 0.025 → 0.011. +- `cur1/test` guard precision R32 99.3%, R17 98.3%; ECE action/diag R32 0.024 / 0.016, R17 0.035 / 0.018. `cur2/test` (raw temperatures): R32 96.9 / 97.9, heal FIR 0.14%; R17 96.1 / 97.8, heal FIR 0.81%. +- SIM sample mean cost (heal policy / always passive / oracle): R32-s1c 23.26 / 23.61 / 22.36, R17-s1c 23.24 / 23.61 / 22.36. +- Stage-2 pilot: guard fires 2 (R32) / 4 (R17); ECE action/diag 0.24 / 0.012 and 0.26 / 0.017; per trigger action/diag ≈ error 94.5 / 93, failure 71 / 85, inconsistency 85 / 97, mutation 84–86 / 90, request 72 / 95, stall 64–68 / 87–89, transition 83–85 / 89–90; heal sweep: at 0.8 130 / 173 fires with 70% / 66% precision, at 0.9 21 / 27 fires with 81% / 93%. Gated policy saves ≈ 0.05 of the 1.15 cost units available per decision. Pre-freeze SIM action labels were soft (≈ temperature 2 over costs), hence the low recall. +- Packed sequence length by state budget (pruned tokenizer, ≈ 2.4–2.5 chars/token): 1,000–1,100 chars ≈ 600 tokens, 2,000 ≈ 1,000, 3,200 → SIM `r300k` mean 1,108 / p95 1,523 / max 1,761; standing questions add ≈ 185 tokens. At ≈ 600 tokens R17 decides in ≈ 0.25 s and R32 in ≈ 0.65 s (WASM, 1 thread). MODEL measured R32 at 780 tokens in Chromium at 837–940 ms, and ≈ 3× faster with 4 threads in a crossOriginIsolated page (Node shows no speed-up). +- Final round 1 sizes: SIM `final-a` train 448,420 / dev 14,613 / test 137,643; `r32-final1` 2.4 passes × 498M tokens on 48 ranks, `r17-final1` 3.0 passes on 32 ranks, ETA ≈ 01:28–01:30 UTC; c01 deallocated 00:12. + +NEEDS items not listed below: 2 (row format) and 3 (meta) DONE on `sim/samples/sample.jsonl`; 6 DONE (card format `genclass-runtime-model/1`, `meta.json` fields); 7 answered by MODEL: the int8-embedding q8 runs under onnxruntime-web 1.30 WebGPU on an adapter without shader-f16, while the v0.1 q8 with an fp16 table fails with "Program Gather requires f16"; MODEL's TS packer reproduces `export-r32-v1pruned/parity.json` (q8 450/454 decisions, fp16 453/454; 89/90 requests pack bit-exactly); 9 INFO: `genclass-runtime info <dir>` enforces "any fp16 tensor → `needs: shader-f16`"; 10 INFO: MODEL's single-thread WASM latency R17 177 / 245 / 360 / 625 ms vs R32 458 / 601 / 908 / 1,647 ms at ≈ 300 / 400 / 600 / 1,000 state tokens. + +Doc-vs-code drift: +- `training/README.md` §2 says diagnosis has "9 labels"; code has 10 (`transient` added; `fmt.DIAG_DESC`, `rt.DIAGNOSES`). +- `training/README.md` §4 describes the old gate ("non-passive top action, p ≥ 0.9 / 0.8"); `eval_runtime.py` uses the summed-mass gate over permitted actions (EVAL.md is current). `packages/runtime-model/MODEL_CARD.md` has the same old gate wording, omits `transient`, and its status line ("stage 1c final") predates final round 1. +- `export_runtime.py` parity metrics `gate08`/`gate09` still use the single-max-probability gate, not the summed-mass gate. +- `training/README.md` §3 points at `/Users/meharkhanna/jev/scripts/launch_run.sh`; in this repo it is `scripts/launch_run.sh`, and the `.sh` scripts resolve jev code at `$HERE/../..` rather than the repo root. +- `prune_vocab.py` module docstring shows `analyze --texts a.jsonl b.txt`; the CLI takes `--group name=path1,path2`. +- `ortweb/validate.mjs` header says it writes `ortweb_report.json`; it writes `ortweb_report_<variant>.json`. +- `report.py` docstring shows `--mode kind|raw|group|header`; `main` only recognises `--mode=<mode>` (a bare `--mode kind` is parsed as a `name=path` argument and fails). +- `import_sim.sh` header says the bundle is "served on 10.0.0.6:8799"; the script only writes `~/xfer/s2_<NAME>.tar` and starts no server. `data/sim1e` (20k eval rows) is not produced by any script. +- `training/NEEDS.md` item 8 is still "ASK" but is implemented (`fmt.js_numbers`, LOG 23:05). Its "TRAIN status for the frozen data (23:10)" section ("still to mirror ... corrected fact wording"; "Ready to run: import_sim.sh → launch_s2.sh") is superseded by the 23:05–23:35 re-port and `import_final.sh` / `launch_final1.sh`. +- `eval_runtime.py` → `probs` docstring lists modes raw/kind/group; `header` also exists. +- CONTRACT §1 lists `training/` owner as LEAD; README says TRAIN. +- `pull_on_train.sh` and `deliver_final.sh` headers say they "verify bytes + sha256" / "sizes/hashes"; the inline Python only compares sha256 and prints the card's `bytes` value. +- `launch_final1.sh` header says "SIM phase A + 15% frozen-wording curriculum replay"; `mix_final1.json` replay is 15% in total but only `cur4` (0.12) has the frozen wording (`cur1` 0.02 is varied style, `gen` 0.01 is v1 data). +- `training/README.md` §1 says pruning keeps "all 119 added tokens (…, markers)"; that holds for a GenClass checkpoint (R32). An HF base (R17) has no markers yet: pruning keeps its 114 non-marker added tokens (vocab 16,359) and `init_model` appends the 5 markers (16,364). +- `training/README.md` §3 describes the stage-2 mixture as "≈ 80% SIM and ≈ 20% curriculum replay"; `configs/mix_s2.json` is sim1 0.76 + 0.24 replay (EVAL.md says 24%). README says 800k rows in "≈ 10 s"; LOG measured ≈ 8 s for 818k. +- Exported `meta.json` `merges_kept` is `null` for trained checkpoints (code reads `meta.vocab_pruned`, which only pruned-but-untrained checkpoints carry). No runtime code reads the field, so it is informational only; fix it in `export_runtime.py` (e.g. fall back to the tokenizer's merge count) if anything starts depending on it. +- `final_post.sh` header says it "writes out/eval/..., out/cal/..., out/export-<M>/ and touches out/.post-done-<M>"; it touches the marker even when eval or export failed (no `set -e`). +- `training/README.md` §2 says ask rows carry "2–5 primitive questions only" and decision rows "0–3"; runtime-exact decision rows draw 0–2 (`rows.decision_row`: `rng.choice((0, 0, 1, 2))`). +- `curriculum/rt.py` module docstring says "Scenario facts that CORE cannot compute are dropped; scenarios whose label would then be unjustifiable return None"; the only such scenario is `failure/offline` via `spec["no_runtime"]`. + +Open items relevant to this scope: +- Final round 1 evaluation, calibration, export and delivery (OPEN_TASKS 3–4); EVAL.md "Final round 1" is empty. Round 2 on SIM phase A + B with longer schedules. +- Choose shipping models (OPEN_TASKS 5) and publish `@genclass/runtime-model@0.1.0` (OPEN_TASKS 8). +- NEEDS 1 (OPEN): stage 2 wants ≥ 1M SIM train rows; phase A gave 448k. NEEDS 4 (ASK): clean-run SIM rows (`meta.clean`) for a direct FIR on clean traffic. NEEDS 5 (ASK): keep instructions/descriptions stable. NEEDS 6a (ASK): budget with the real tokenizer (≈ 2.4 chars/token). +- Stage-2 pilot lesson: soft pre-freeze SIM action labels gave recall ≈ 1%; frozen SIM uses sharper uncertainty-based labels (≥ 0.95 on clear cases), which final round 1 trains on. Re-check q8 parity on trained models and consider MatMulNBits block 16 (+1.8 MB for R32) if gate agreement is low (LOG). +- Known risks (OPEN_TASKS): label noise from few sampled futures; thin `conflict` and `transition` classes. +- `standalone.json_invariants` `j_count` overwrite (see Gotchas). + +## Related docs + +- [glossary.md](glossary.md): shared term list (stage 1 / 1c / 2, final round 1 / 2, phase A / B, bucket, `COMPACT_BUDGET` vs `COMPACT_QUESTIONS_BUDGET`). +- [model-io-contract.md](model-io-contract.md): situation text → packed request → heads → calibrated answers (shared by runtime, sim and training). +- [sim.md](sim.md): the SIM generator that produces the rows for the stage-2 pilot (`r300k`) and the final rounds (phase A/B): `meta.costs`, `meta.budget`, splits. +- [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): the runtime situation code that `curriculum/rt.py` mirrors. +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): the runtime gate and action tiers that `eval_runtime.py` reproduces. +- [runtime/model-host.md](runtime/model-host.md): how the exported model directory is loaded, verified and run (card format, `meta.json`, calibration lookup). +- [genclass-model-lineage.md](genclass-model-lineage.md): `jev_local/` (trainer, engine, packer) and GenClass 0.1 (the R32 init). +- [demos.md](demos.md): demo trials that will evaluate the trained model. +- [status-and-known-issues.md](status-and-known-issues.md), [runtime/build-test-release.md](runtime/build-test-release.md). +- Source docs: [../../training/README.md](../../training/README.md), [../../training/EVAL.md](../../training/EVAL.md), [../../training/LOG.md](../../training/LOG.md), [../../training/NEEDS.md](../../training/NEEDS.md), [../runtime/CONTRACT.md](../runtime/CONTRACT.md) (§8 gate, §10 model, §11 SIM), [../../packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), [../../OPEN_TASKS.md](../../OPEN_TASKS.md). From f3636b220ae902e233e5b798df685a33d29ef7e6 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Wed, 7 Oct 2026 23:30:34 -0400 Subject: [PATCH 02/25] runtime: default mode is observe; guard opt-in, heal experimental GenClass.init() and createRuntime() now start in observe when no mode is given: a fresh install reports findings and never holds, delays or changes anything. guard stays available via mode: "guard" or ?genclass=guard. - runtime.ts: o.mode ?? "observe"; types.ts JSDoc; devtools mode labels (observe default, guard opt-in, heal experimental) and mode fallback. - New test/default-mode.test.ts: the default is observe for both entry points, guard is opt-in, and the default never holds writes (atom and adapter), requests or failures, whether the model is sure or never answers, while findings are still reported. - Tests that exercise interventions now ask for guard explicitly: the helpers.ts harness, smoke.test.ts, browser/ui/session.ts, and the headless() helper of review-fetch.test.ts (one option added; no assertion changed). - docs/runtime: API.md, ARCHITECTURE.md, and CONTRACT.md with the change recorded in section 13. Situation text does not depend on the mode, so situation-v1 training data stays valid. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/runtime/API.md | 10 +-- docs/runtime/ARCHITECTURE.md | 6 +- docs/runtime/CONTRACT.md | 14 ++- packages/runtime/src/devtools/index.ts | 8 +- packages/runtime/src/runtime.ts | 2 +- packages/runtime/src/types.ts | 5 +- packages/runtime/test/browser/ui/session.ts | 2 +- packages/runtime/test/default-mode.test.ts | 98 +++++++++++++++++++++ packages/runtime/test/helpers.ts | 2 + packages/runtime/test/review-fetch.test.ts | 2 +- packages/runtime/test/smoke.test.ts | 2 +- 11 files changed, 130 insertions(+), 21 deletions(-) create mode 100644 packages/runtime/test/default-mode.test.ts diff --git a/docs/runtime/API.md b/docs/runtime/API.md index edfb3873..a69b91d4 100644 --- a/docs/runtime/API.md +++ b/docs/runtime/API.md @@ -7,7 +7,7 @@ risky. Depending on the mode it reports what it saw, or prevents the failure wit ```ts import { GenClass } from "@genclass/runtime"; -const rt = GenClass.init(); // guard mode, local model, console reports +const rt = GenClass.init(); // observe mode, local model, console reports const cart = rt.atom("cart", { items: [], total: 0 }); // state GenClass can protect ``` @@ -27,9 +27,9 @@ GenClass.destroy(): void // uninstall observers, restore | mode | what it does | |---|---| -| `observe` | Watches and reports detections. Never changes execution: nothing is held, no action runs. | -| `guard` (default) | Also takes *guard-tier* actions at very high confidence: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down; they never invent data or fail a request. | -| `heal` | Also takes *heal-tier* actions: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, plugin actions. | +| `observe` (default) | Watches and reports detections. Never changes execution: nothing is held, no action runs. | +| `guard` (opt-in) | Also takes *guard-tier* actions at very high confidence: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down; they never invent data or fail a request. | +| `heal` (experimental) | Also takes *heal-tier* actions: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, plugin actions. | Kill switch, for "is my app broken or did GenClass change something?": @@ -43,7 +43,7 @@ no model. Use [`createRuntime`](#headless-use-tests-ssr-simulation) for headless ```ts interface InitOptions { - mode?: "observe" | "guard" | "heal"; // default "guard" + mode?: "observe" | "guard" | "heal"; // default "observe"; "guard" is opt-in, "heal" experimental model?: { // or false: no model (observe only) baseUrl?: string; // directory with model.json (default: jsDelivr CDN) device?: "auto" | "webgpu" | "wasm"; // default "auto" diff --git a/docs/runtime/ARCHITECTURE.md b/docs/runtime/ARCHITECTURE.md index d337104b..042d67a4 100644 --- a/docs/runtime/ARCHITECTURE.md +++ b/docs/runtime/ARCHITECTURE.md @@ -11,9 +11,9 @@ This document explains how the parts fit together and why they are built this wa generic facts and asks the model. All runtimes compute the same facts: happens-before order, versions, repetition, failure streaks, latency against learned baselines, learned invariants and transition profiles. The diagnosis and the action come from the model. -2. **Precision first.** A false intervention costs more than a missed bug. The default `guard` mode takes only - minimal, reversible actions, and only when the model is very confident and its own diagnosis says something - is wrong. +2. **Precision first.** A false intervention costs more than a missed bug. The default `observe` mode only + reports. The opt-in `guard` mode takes only minimal actions, and only when the model is very confident and its + own diagnosis says something is wrong. `heal` is experimental. 3. **Observable.** Every detection and intervention is reported in plain English with its evidence, can be explained after the fact, and can be undone where possible. A kill switch rules GenClass out in one step. 4. **Cheap by default.** Facts are cheap and always on. The model runs only for salient situations, off the main diff --git a/docs/runtime/CONTRACT.md b/docs/runtime/CONTRACT.md index bed88c25..db455c4e 100644 --- a/docs/runtime/CONTRACT.md +++ b/docs/runtime/CONTRACT.md @@ -42,7 +42,8 @@ The narrow, real claim: **install one library; find and prevent runtime failures positives.** Three things kill the product, and the design answers each: 1. **False positives.** If GenClass "heals" correct code and creates a bug, developers uninstall it. So: the - default mode only takes minimal, reversible *guard* actions at very high calibrated confidence; a non-passive + default mode (`observe`, §13) only reports; the opt-in `guard` mode takes only minimal *guard* actions at very + high calibrated confidence; a non-passive action also requires the model's own diagnosis to say something is wrong; false-intervention rate on clean runs is a first-class metric in the sim test split and in every demo. 2. **Performance.** Tiered detection: generic facts and learned baselines run always and cost ~nothing; the @@ -53,7 +54,8 @@ positives.** Three things kill the product, and the design answers each: reversible actions, responses marked with `x-genclass`, and a kill switch (`?genclass=off`). Adoption path = modes: **observe** (find anomalies you didn't know existed) → **guard** (prevent only -extremely-high-confidence failures; default) → **heal** (broader autonomous recovery). +extremely-high-confidence failures; opt-in) → **heal** (broader autonomous recovery; experimental). The default +mode is **observe** (§13, 2026-10-08). The console should read like: ``` @@ -108,7 +110,7 @@ export const GenClass: { export function createRuntime(options?: CreateOptions): Runtime; // advanced/headless (sim, tests, SSR-safe) interface InitOptions { - mode?: "observe" | "guard" | "heal"; // default "guard" (section 8). observe never changes execution. + mode?: "observe" | "guard" | "heal"; // default "observe" (§13, 2026-10-08). observe never changes execution. model?: { baseUrl?: string; // directory holding model.json (default: CDN of @genclass/runtime-model@<pinned>) device?: "auto" | "webgpu" | "wasm"; // default auto (webgpu+fp16 if shader-f16, else wasm+q8) @@ -489,7 +491,7 @@ A Vite multi-page site (works as static files, deployable to GitHub Pages). The mock server (real `fetch` from the page's point of view) with chaos controls (latency, jitter, failure rate, outages, slowdowns). Each demo: a real small app, a GenClass on/off switch, chaos controls, the devtools overlay, and a "Run trials" button that drives scripted user sessions and reports the bug rate measured by the -demo's own oracle, GenClass off vs on (observe = off baseline, guard = default, heal), plus **false +demo's own oracle, GenClass off vs on (off, observe, guard, heal), plus **false interventions on clean runs** (no chaos, correct behaviour: any non-passive action there is a false positive) as a headline number next to the bug rate. A Playwright script on the VM runs all trials headless and writes `demos/results.json`. Demos use only the public API. Required demos (all @@ -517,3 +519,7 @@ genuinely different failures or decisions): - The runtime model uses a pruned vocabulary (first 16,000 BPE merges; 16,364 tokens incl. markers). Marker and special ids are read from `tokenizer.json`/`meta.json`, never hardcoded. - Devtools and adapters are owned by UI (`src/devtools/**`, `src/adapters/**`). +- **Default mode is `observe`** (approved by the user 2026-10-08, MVP): `GenClass.init()` and `createRuntime()` start + in `observe` when no `mode` is given, so a fresh install reports findings and never holds, delays or changes + anything. `guard` is opt-in (`mode: "guard"` or `?genclass=guard`); `heal` is experimental. Situation text, + facts and questions are unchanged (they do not depend on the mode), so `situation-v1` training data stays valid. diff --git a/packages/runtime/src/devtools/index.ts b/packages/runtime/src/devtools/index.ts index f2d4931a..e3020044 100644 --- a/packages/runtime/src/devtools/index.ts +++ b/packages/runtime/src/devtools/index.ts @@ -107,9 +107,9 @@ const TABS: [DevtoolsTab, string][] = [ ["now", "Now"], ]; const MODES: [Mode, string, string][] = [ - ["observe", "Observe", "Observe: never changes execution; reports what GenClass would have done"], - ["guard", "Guard", "Guard (default): prevents only extremely-high-confidence failures with minimal, reversible actions"], - ["heal", "Heal", "Heal: broader autonomous recovery (retry, cached responses, rollback, resync)"], + ["observe", "Observe", "Observe (default): never changes execution; reports what GenClass would have done"], + ["guard", "Guard", "Guard (opt-in): prevents only extremely-high-confidence failures with minimal actions (drop, defer, coalesce, delay)"], + ["heal", "Heal", "Heal (experimental): broader autonomous recovery (retry, cached responses, rollback, resync)"], ]; const FILTERS: [Group, string][] = [ ["user", "User"], @@ -664,7 +664,7 @@ class Devtools { } private mode(): Mode { - return safe(() => this.rt.mode, "guard" as Mode); + return safe(() => this.rt.mode, "observe" as Mode); } private renderMode(): void { diff --git a/packages/runtime/src/runtime.ts b/packages/runtime/src/runtime.ts index 5551f661..b0aa17f0 100644 --- a/packages/runtime/src/runtime.ts +++ b/packages/runtime/src/runtime.ts @@ -202,7 +202,7 @@ export class RuntimeImpl implements Runtime { this.hub.holdUserWrites = this.policy.holdUserWrites; this.hub.holdWrites = this.policy.holdWrites; this.rate = new RateLimiter(() => this.policy.maxActionsPerMinute); - this._mode = o.mode ?? "guard"; + this._mode = o.mode ?? "observe"; this.triage = o.triage ?? "salient"; this.vocab = o.vocabulary; this.hooks = o.hooks ?? {}; diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts index e74f011b..60e16e75 100644 --- a/packages/runtime/src/types.ts +++ b/packages/runtime/src/types.ts @@ -328,7 +328,10 @@ export interface ModelOptions { } export interface InitOptions { - /** Default "guard". observe never changes execution. */ + /** + * Default "observe": reports what GenClass sees and would do, and never holds, delays or changes anything. + * "guard" (opt-in) takes minimal guard-tier actions at very high confidence; "heal" is experimental. + */ mode?: Mode; /** false: no model (observe-only). */ model?: ModelOptions | false; diff --git a/packages/runtime/test/browser/ui/session.ts b/packages/runtime/test/browser/ui/session.ts index 076734b1..49c64332 100644 --- a/packages/runtime/test/browser/ui/session.ts +++ b/packages/runtime/test/browser/ui/session.ts @@ -277,7 +277,7 @@ export async function runStoreSession(opts: SessionOptions = {}): Promise<Sessio const decider = new SessionDecider(clock, opts.status ?? READY); let route = "/search"; const g: Record<string, unknown> = { fetch: backend.fetch, Response, location: { href: "https://acme.test/search", pathname: "/search", search: "" } }; - const rt = createRuntime({ clock, global: g, decider, report: "silent", observe: OBSERVE, app: () => ({ title: "Acme Store", route }) }); + const rt = createRuntime({ clock, global: g, decider, mode: "guard", report: "silent", observe: OBSERVE, app: () => ({ title: "Acme Store", route }) }); const http = g.fetch as typeof fetch; const json = (path: string, init?: RequestInit) => http(path, init).then((r) => r.json()); diff --git a/packages/runtime/test/default-mode.test.ts b/packages/runtime/test/default-mode.test.ts new file mode 100644 index 00000000..d7315aff --- /dev/null +++ b/packages/runtime/test/default-mode.test.ts @@ -0,0 +1,98 @@ +// The default mode is observe: with no `mode`, GenClass reports what it sees and never holds, delays or changes +// anything, even when the model is sure, and even when the model never answers. guard is opt-in. + +import { afterEach, describe, expect, it } from "vitest"; +import { GenClass } from "../src/index.js"; +import type { Detection } from "../src/types.js"; +import { ManualDecider, defaultScript, setup } from "./helpers.js"; + +/** A minimal redux-like store for the adapter seam. */ +function counterStore() { + let state = { count: 0 }; + const subs = new Set<() => void>(); + return { + getState: () => state, + subscribe: (f: () => void) => (subs.add(f), () => subs.delete(f)), + inc: (s: { count: number }) => ({ count: s.count + 1 }), + commit(next: { count: number }) { + state = next; + subs.forEach((f) => f()); + }, + }; +} + +describe("default mode is observe (MVP)", () => { + const g = globalThis as unknown as Record<string, unknown>; + afterEach(() => { + GenClass.destroy(); + delete g.location; + }); + + it("createRuntime without a mode starts in observe", () => { + const { rt } = setup({ mode: undefined }); // the test harness otherwise defaults to guard + expect(rt.mode).toBe("observe"); + }); + + it("GenClass.init without a mode starts in observe; guard is opt-in (option or ?genclass=guard)", () => { + const opts = { model: false as const, report: "silent" as const, observe: { fetch: false, timers: false } }; + expect(GenClass.init(opts).mode).toBe("observe"); + GenClass.destroy(); + expect(GenClass.init({ ...opts, mode: "guard" }).mode).toBe("guard"); + GenClass.destroy(); + g.location = { search: "?genclass=guard", href: "http://x/?genclass=guard", pathname: "/" }; + expect(GenClass.init(opts).mode).toBe("guard"); + }); + + it("never holds writes or requests even when the model is sure; findings are still reported", async () => { + const { rt, clock, server, fetch } = setup({ + mode: undefined, + triage: "always", + script: defaultScript({ mutation: { diagnosis: "stale", action: "discard", p: 0.99 }, request: { diagnosis: "overload", action: "block", p: 0.99 } }), + }); + const detections: Detection[] = []; + rt.on("detect", (d) => detections.push(d)); + server.on("GET", "/api/x", { body: 1, latency: 5 }); + const a = rt.atom("a", 0); + void rt.op("w", () => a.set(1)); + expect(a.get()).toBe(1); // applied synchronously + const t0 = clock.now(); + const p = fetch("/api/x"); + await clock.advance(5); + expect((await p).status).toBe(200); + expect(server.log[0].t).toBe(t0); // sent at once + await clock.flush(); + expect(a.get()).toBe(1); + const ds = rt.decisions(); + expect(ds.map((d) => d.trigger).sort()).toEqual(["mutation", "request"]); + expect(ds.every((d) => !d.executed)).toBe(true); + expect(rt.interventions()).toEqual([]); + expect(detections.map((d) => d.diagnosis).sort()).toEqual(["overload", "stale"]); + }); + + it("never waits for the model: with a model that never answers, nothing is delayed", async () => { + const manual = new ManualDecider(); + const { rt, clock, server, fetch } = setup({ mode: undefined, decider: manual, triage: "always" }); + server.on("GET", "/api/ok", { body: 1, latency: 5 }); + server.on("GET", "/api/fail", { status: 500, body: { error: "boom" }, latency: 5 }); + + const a = rt.atom("a", 0); + void rt.op("w", () => a.set(1)); + expect(a.get()).toBe(1); + + const store = counterStore(); + const h = rt.adapter("shop", { get: store.getState, subscribe: store.subscribe }); + void rt.op("sync", () => h.propose({ fn: (prev) => store.inc(prev as { count: number }), commit: (n) => store.commit(n as { count: number }) })); + expect(store.getState().count).toBe(1); // an async adapter write is committed at once (guard would hold it) + + const t0 = clock.now(); + const ok = fetch("/api/ok"); + const fail = fetch("/api/fail"); + await clock.advance(5); + expect((await ok).status).toBe(200); + expect((await fail).status).toBe(500); // the failure is delivered as is, not held for a retry decision + expect(server.log.map((l) => l.t)).toEqual([t0, t0]); + + expect(manual.pending.length).toBeGreaterThan(0); // the model is still asked, in the background + expect(rt.interventions()).toEqual([]); + }); +}); diff --git a/packages/runtime/test/helpers.ts b/packages/runtime/test/helpers.ts index d8f90a3a..1d3e41ab 100644 --- a/packages/runtime/test/helpers.ts +++ b/packages/runtime/test/helpers.ts @@ -198,6 +198,8 @@ export function setup(opts: Partial<CreateOptions> & { script?: Script; extraGlo clock, global: g, decider, + // Most CORE tests exercise interventions, so the harness keeps guard; the product default is observe. + mode: "guard", report: "silent", observe: { fetch: true, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false }, ...rest, diff --git a/packages/runtime/test/review-fetch.test.ts b/packages/runtime/test/review-fetch.test.ts index 3cc82a5b..8ab83ddd 100644 --- a/packages/runtime/test/review-fetch.test.ts +++ b/packages/runtime/test/review-fetch.test.ts @@ -11,7 +11,7 @@ function headless(fetchImpl: (input: unknown, init?: Record<string, unknown>) => const clock = new FakeClock(); const g: Record<string, unknown> = { fetch: fetchImpl, Response, location: { href: "http://app.test/", pathname: "/", search: "" } }; const decider = new ScriptedDecider(script); - const rt = createRuntime({ clock, global: g, decider, report: "silent", observe: ONLY_FETCH }) as RuntimeImpl; + const rt = createRuntime({ clock, global: g, decider, mode: "guard", report: "silent", observe: ONLY_FETCH }) as RuntimeImpl; return { clock, g, decider, rt, fetch: (u: unknown, i?: RequestInit) => (g.fetch as (u: unknown, i?: RequestInit) => Promise<Response>)(u, i) }; } diff --git a/packages/runtime/test/smoke.test.ts b/packages/runtime/test/smoke.test.ts index 26ff6bde..623448d3 100644 --- a/packages/runtime/test/smoke.test.ts +++ b/packages/runtime/test/smoke.test.ts @@ -8,7 +8,7 @@ function setup(script = defaultScript()) { const server = new FakeServer(clock); const g = makeGlobal(server); const decider = new ScriptedDecider(script); - const rt = createRuntime({ clock, global: g, decider, report: "silent", observe: { fetch: true } }) as RuntimeImpl; + const rt = createRuntime({ clock, global: g, decider, mode: "guard", report: "silent", observe: { fetch: true } }) as RuntimeImpl; return { clock, server, g, decider, rt, fetch: (u: string, i?: RequestInit) => (g.fetch as typeof fetch)(u, i) }; } From b435acbc4034f0f5fd14f1d5f6970267427ef044 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 00:15:50 -0400 Subject: [PATCH 03/25] ci: GitHub Actions for @genclass/runtime; commit the root lockfile Ported from mvp (a7519e0) onto the situation-v2 runtime: - .github/workflows/ci.yml: Node 22, npm ci, typecheck, build, unit tests (browser tests excluded; model parity tests skip without a model dir). The REVIEW perf budgets run in their own step with --retry=2: they time a 5,000-item store and fail intermittently next to parallel test files, never alone. ONNXRUNTIME_NODE_INSTALL=skip keeps onnxruntime-node from downloading CUDA binaries on Linux. Triggers include mvp-v2. - package-lock.json regenerated from a clean install of this branch (lockfileVersion 3, Linux optional binaries included) so CI can npm ci. - bin/genclass-runtime.mjs committed executable (npm sets 755 on install). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/ci.yml | 53 + package-lock.json | 3203 +++++++++++++++++++++ packages/runtime/bin/genclass-runtime.mjs | 0 3 files changed, 3256 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 package-lock.json mode change 100644 => 100755 packages/runtime/bin/genclass-runtime.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..a4ca7638 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: [main, runtime, mvp, mvp-v2] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + runtime: + name: "@genclass/runtime: typecheck, build, unit tests" + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + # onnxruntime-node (dev-only, for the model parity tests) would otherwise download CUDA binaries on Linux. + ONNXRUNTIME_NODE_INSTALL: skip + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + + - name: Install + run: npm ci --no-audit --no-fund + + - name: Typecheck + run: npm run typecheck -w @genclass/runtime + + - name: Build + run: npm run build -w @genclass/runtime + + # Browser (Playwright) tests are excluded. Model parity tests skip without a model directory (GENCLASS_MODEL_DIR). + # The perf budgets run in their own step: they time a 5,000-item store and are noisy next to parallel test files. + - name: Unit tests + working-directory: packages/runtime + env: + NODE_OPTIONS: --expose-gc + run: npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts + + - name: Perf budgets + working-directory: packages/runtime + env: + NODE_OPTIONS: --expose-gc + run: npx vitest run test/review-perf.test.ts --retry=2 diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..7b016fe5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,3203 @@ +{ + "name": "genclass-lib", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "genclass-lib", + "license": "Apache-2.0", + "workspaces": [ + "packages/*", + "sim", + "demos" + ], + "devDependencies": { + "typescript": "~5.9.3" + }, + "engines": { + "node": ">=20" + } + }, + "demos": { + "name": "@genclass/demos", + "version": "0.1.0", + "dependencies": { + "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/jetbrains-mono": "^5.3.0", + "@genclass/runtime": "*", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "redux": "^5.0.1", + "zustand": "^5.0.15" + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/node": "^22.0.0", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "~5.9.3", + "vite": "^8.3.3" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fontsource-variable/inter": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz", + "integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/jetbrains-mono": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz", + "integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@genclass/demos": { + "resolved": "demos", + "link": true + }, + "node_modules/@genclass/runtime": { + "resolved": "packages/runtime", + "link": true + }, + "node_modules/@genclass/sim": { + "resolved": "sim", + "link": true + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.153.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", + "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@playwright/test": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", + "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", + "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", + "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", + "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", + "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", + "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", + "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", + "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", + "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", + "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", + "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", + "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", + "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", + "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", + "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.2.tgz", + "integrity": "sha512-gjNDUwMswogkw3fNqV00u54uZlgmInuw5EU/1TeqQ6K0bEagoGvqjPdKzy112lKyhe7PkGudZ/kSQHsc9qroIg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.2.tgz", + "integrity": "sha512-YkAW8q7p5SCLSaGWaUkmsRnBEb3MGA1pB5nI/8k0lAK5fZsQKRBqkdR1h4UU9p8u3c7ZGdUF2Zcx7mK+E/pUKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.2.tgz", + "integrity": "sha512-hNmuIHv+LnrP/+q/44vsmIMWfoh7X2YXOp5FLtjGuvqN52VdtFpOpnshTc1k28tWv1wE/0D5gLjsozBUowEGbQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.2.tgz", + "integrity": "sha512-B0t5CoxgF2KL7R5FHAsyN8yVEQCSIkh4XVs8MCDjuBLNjEa8l3zd5tVKaFMv53LfUtHs9p2rnqeavPTOunV+Ww==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.2.tgz", + "integrity": "sha512-QQdYnfwrPmc1DoPlddjFvQPzUHFbStKXsHrG6EBYsWHhBVUCjsCRdcfGGXGAvhDpDtTzKK4vy1UrGFJ45rQaiw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.2.tgz", + "integrity": "sha512-1xRxtGWif6BB58VSfMavi0Yfs2M4x6CtRp4o7ScY4W7AGlgvf6GSPKdDNdw7TX3tMiQwZY5W/mvyrOJTq/7AKA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.2.tgz", + "integrity": "sha512-CXFLEt384BUwwOLR9DURWNHl1bQOVLd1ibOee+yKBJm/fZtvrSAOZ0JbxjAxszVMIovYMwFMS+oP+Q1aPcx8Eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.2.tgz", + "integrity": "sha512-T1dorY0WHm5mMNpMHFl5rYRZ02gLSZcr6J45r66tYb3S3R3DyIRGiGWVdLtF+zOQjratNJaObl9jYumueRiL1A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.2.tgz", + "integrity": "sha512-ia6bfaCIc0ldp6bvs9oEkFrJVJKNUMoiDF0+LBZsQAZg+vE0znXnzGqH+ew/FYswE30cruAWPTO3dPw7keaVkQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.2.tgz", + "integrity": "sha512-mB/gwfBfXtT0EBpbSssqKCqMFuX8b21Zy2TGoIhehSJEssZ5ksybxymwp1BkEM5Nczh/AAxpmh5q+MkhtundGg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.2.tgz", + "integrity": "sha512-VPd0a+XlHoNRI9jIPRHww2UKhDkD6XjbtcKYXZijAnhJS1jLLbiNtVl6a5LyEfNN+eyiyWcJOZXPzBo69oTsew==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.2.tgz", + "integrity": "sha512-10N1I6oBpERqzGtHKcCLrEpHlbXSBbMK9TURHvqgWbIFZuU3oJROxJ0H2nHfq96TVI0XJHQ9qzolJMFd2tz0LA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.2.tgz", + "integrity": "sha512-dhJrLVZ3wNNhwCmy9/VTg6Pq6J8a8eZ0n15dVRlbSWcDb+8V/1mDfbnvis+vt8W6Pbxzv6gUbTEl4piOT3bbUQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.2.tgz", + "integrity": "sha512-tPd2QuwxkTxgju5eARyb3RdgBWWi/O9dn/NFH0VkvGbLzoQeXrH6qMABtW8IODb5lUeBzB3sy2U7qmI4MtQ72g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.2.tgz", + "integrity": "sha512-njtDdPvSQWI9CDhIPPxsiEMeHayCfu7wwcbSQ7c2kYPhGVviL+WGVhq6Jfj/b+VuhSTkFuQ0z4ZFbFjkWwBFmg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.2.tgz", + "integrity": "sha512-EbOBo3dqCj9ecEV9Z7zvulB6AieMP2ztnKQYGVOSN0pzIyOu+3JH2YJZnLmbPeVvfn6yP6Qi7NbBM27EzGbj2w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.2.tgz", + "integrity": "sha512-8wLt2Q5n4qmfiE2Gk8V6KNLSf+oJuBX7Kdw5joFDtnZIZvirS0hLzBc79OiJjV71oYDmBUZLNy6pDgvylo4qiQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.2.tgz", + "integrity": "sha512-aIChbkhC4d33bxkVP0LSi2/2lUSGRXE6k4Qa0G7tgpgTOK7kxHTixmx5qC3SKUJ6yUMznHBtQoWaG4QMqLUnhw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.2.tgz", + "integrity": "sha512-gQ+TkVZRfjZVcl/UOAxxfWw+sHjzIXoieNwxEyJlD3tRBmBhR8ZDq11w+QEgQDcpslEB+fhN/OEpaTsDoIIHhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.2.tgz", + "integrity": "sha512-sUaJpMKS2JBCvUk8fYimG7aMq2jHVT4kw/uVHxPolKLrMmkKy0KXirmZyZehdNpL7PffqAlPAWUELQcTiD8ChA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.2.tgz", + "integrity": "sha512-j1RdJWb0CrlSuwt12OPjLucPlwfLtA/KMOKVvh5rXSJEtl/WDoIGR3CSykK/jLGTo9RqNfW5Ub6kY5Z5ccYl9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.2.tgz", + "integrity": "sha512-i3r04aHCIY3eggTBLUp/4IxiBjDpAgQaK89Ue2nMJ2MKuIXX5JfoeZjHw+kPjGGNVDlhi8FT8xzuGMJZe3aehg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.2.tgz", + "integrity": "sha512-kCQ15h/uwNMGdN8gjXBZGf+aGE+ODzHfbi90/cAm4+Q89WoMiLODNoj8HoGZmYx87HPxfu5CBNPsZ+ZG4uIAoA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.2.tgz", + "integrity": "sha512-yYAuySSs+0X2gSMJPw/Q4jHsHZHyMq1dpAE+XnN790Jg1WuReUAD/+j+e4vuDvS4PXJ4PA4NCzTR4OYtDf18/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.2.tgz", + "integrity": "sha512-JY1rQdWOJrKutORqKO1uzrHXV86jFiQzfLFKx2s8S1CjLXL9fC5LOIvk0q7Z7PXJvsByt+sdoE1Q2a9gBr4gLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", + "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.152.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz", + "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.3", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz", + "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/adm-zip": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", + "integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/global-agent": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.3.tgz", + "integrity": "sha512-KUJEViiuFT3I97t+GYMikLPJS2Lfo/S2F+DQuBWzuzaMPnvt5yyZePzArx36fBzpGTxZjIpDbXLeySLgh+k76g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "globalthis": "^1.0.2", + "matcher": "^4.0.0", + "semver": "^7.3.5", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, + "node_modules/happy-dom": { + "version": "20.14.5", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.5.tgz", + "integrity": "sha512-x/RzkpWO40bTjIoT30iQtt64FLLmH/iRcUCN2X//bLx7H3ifkdfPXyqsro/OYtqzIAhiLMMA7mmiOR9C3NOKjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/matcher": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-4.0.0.tgz", + "integrity": "sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.30.0.tgz", + "integrity": "sha512-7fdVWjAID1dVhH/G8qK3APARunV4VkBFoCQAP7qp4Wkab0mrorvmc+sqiT+mKXOzDqdjN5j+/Z9nb4gzNPWcyA==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.30.0.tgz", + "integrity": "sha512-twhs1C2C/BFkz1yc5OY0KIU2GUq6DURO7hD4bx5Q2Qy3nAMJwRXW8xU3NVczE29VA9lolLOYepoD8fjTGOfIqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.6.0", + "global-agent": "^4.1.3", + "onnxruntime-common": "1.30.0" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.30.0.tgz", + "integrity": "sha512-q0y+JrrtukXSzsBWEMccVfqX25LRmosXHF+CaRJmg8pZClzcV7svNc4rKY3jL02Vb7QmRMDs1SigqR4CXAfKYQ==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.30.0", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.0" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/redux": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", + "license": "MIT" + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rolldown": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", + "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.153.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.13", + "@rolldown/binding-android-arm64": "1.2.13", + "@rolldown/binding-darwin-arm64": "1.2.13", + "@rolldown/binding-darwin-x64": "1.2.13", + "@rolldown/binding-freebsd-x64": "1.2.13", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", + "@rolldown/binding-linux-arm64-gnu": "1.2.13", + "@rolldown/binding-linux-arm64-musl": "1.2.13", + "@rolldown/binding-linux-ppc64-gnu": "1.2.13", + "@rolldown/binding-linux-s390x-gnu": "1.2.13", + "@rolldown/binding-linux-x64-gnu": "1.2.13", + "@rolldown/binding-linux-x64-musl": "1.2.13", + "@rolldown/binding-openharmony-arm64": "1.2.13", + "@rolldown/binding-win32-arm64-msvc": "1.2.13", + "@rolldown/binding-win32-x64-msvc": "1.2.13" + } + }, + "node_modules/rollup": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.2.tgz", + "integrity": "sha512-RxXm0XVVV1hFI3dYe12ruaOgsYQ725lUcUWeMSQqkF9tTxVErY+fy2Ets6vWhItL9MZMSNZGbvZFc7rH/VHp2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.2", + "@rollup/rollup-android-arm64": "4.64.2", + "@rollup/rollup-darwin-arm64": "4.64.2", + "@rollup/rollup-darwin-x64": "4.64.2", + "@rollup/rollup-freebsd-arm64": "4.64.2", + "@rollup/rollup-freebsd-x64": "4.64.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.2", + "@rollup/rollup-linux-arm-musleabihf": "4.64.2", + "@rollup/rollup-linux-arm64-gnu": "4.64.2", + "@rollup/rollup-linux-arm64-musl": "4.64.2", + "@rollup/rollup-linux-loong64-gnu": "4.64.2", + "@rollup/rollup-linux-loong64-musl": "4.64.2", + "@rollup/rollup-linux-ppc64-gnu": "4.64.2", + "@rollup/rollup-linux-ppc64-musl": "4.64.2", + "@rollup/rollup-linux-riscv64-gnu": "4.64.2", + "@rollup/rollup-linux-riscv64-musl": "4.64.2", + "@rollup/rollup-linux-s390x-gnu": "4.64.2", + "@rollup/rollup-linux-x64-gnu": "4.64.2", + "@rollup/rollup-linux-x64-musl": "4.64.2", + "@rollup/rollup-openbsd-x64": "4.64.2", + "@rollup/rollup-openharmony-arm64": "4.64.2", + "@rollup/rollup-win32-arm64-msvc": "4.64.2", + "@rollup/rollup-win32-ia32-msvc": "4.64.2", + "@rollup/rollup-win32-x64-gnu": "4.64.2", + "@rollup/rollup-win32-x64-msvc": "4.64.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinybench": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.1.tgz", + "integrity": "sha512-IAbQaPJIIdhVxi0mqy9lez1wEwje0UQf9F1vwtbelEG5Nbgn0nPOxCvU+mNeNS9gyJTAhrHp74CbUaSynQpZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tsup": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz", + "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.27.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "^0.7.6", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz", + "integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.11", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz", + "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.3", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "^6.1.4", + "tinyexec": "^1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.3", + "@vitest/browser-preview": "5.0.3", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.3", + "@vitest/coverage-v8": "5.0.3", + "@vitest/ui": "5.0.3", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/vitest/node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zustand": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz", + "integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + }, + "packages/runtime": { + "name": "@genclass/runtime", + "version": "0.1.0-alpha.0", + "license": "Apache-2.0", + "dependencies": { + "onnxruntime-web": "^1.30.0" + }, + "bin": { + "genclass-runtime": "bin/genclass-runtime.mjs" + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "esbuild": "^0.27.0", + "happy-dom": "^20.14.5", + "onnxruntime-node": "1.30.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "redux": "^5.0.1", + "tsup": "^8.5.1", + "typescript": "~5.9.3", + "vitest": "^5.0.3", + "zustand": "^5.0.15" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "react": ">=18", + "redux": ">=4", + "zustand": ">=4" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "redux": { + "optional": true + }, + "zustand": { + "optional": true + } + } + }, + "sim": { + "name": "@genclass/sim", + "version": "0.0.0", + "dependencies": { + "@genclass/runtime": "*" + }, + "bin": { + "genclass-sim": "dist/gen.js" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "tsup": "^8.5.1", + "typescript": "~5.9.3", + "vitest": "^5.0.3" + } + } + } +} diff --git a/packages/runtime/bin/genclass-runtime.mjs b/packages/runtime/bin/genclass-runtime.mjs old mode 100644 new mode 100755 From b561244f3dffb8e4f6a0950765793534eb5f9b9a Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 01:25:46 -0400 Subject: [PATCH 04/25] docs: refresh all agent docs for situation-v2; honest READMEs; OPEN_TASKS; RELEASE.md - docs/agents: all 15 subsystem docs re-verified and updated for mvp-v2 (origin/runtime 74f17c0 = situation-v2, batches 4-5, plus default observe and CI), each fact-checked against the code; new docs/agents/realapps.md for the real-browser corpus and never-worse harness; index, overview, repo map, glossary and playbooks updated; status doc records the 2026-10-08 review (52 confirmed findings). - AGENTS.md/CLAUDE.md: v2 ground rules (situation-v2 freeze), HANDOFF.md as the team's live handoff, verified commands and counts. - README.md and packages/runtime/README.md (the npm page): honest status (no v2 model yet), delivery decisions at the network boundary, modes with observe default, model quality, performance, privacy, and known limitations including the confirmed review findings. - OPEN_TASKS.md body brought in line with HANDOFF.md and RESULTS.md. - RELEASE.md: exact procedure for 0.1.0-alpha.1 now and for the model-backed release once a situation-v2 model exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 327 ++-- CLAUDE.md | 2 +- OPEN_TASKS.md | 212 +- README.md | 140 +- RELEASE.md | 456 +++++ docs/agents/README.md | 155 +- docs/agents/demos.md | 162 +- docs/agents/extension-and-benchmarks.md | 34 +- docs/agents/genclass-model-lineage.md | 61 +- docs/agents/glossary.md | 178 +- docs/agents/model-io-contract.md | 754 ++++---- docs/agents/overview.md | 687 ++++--- docs/agents/playbooks.md | 844 ++++---- docs/agents/realapps.md | 404 ++++ docs/agents/repo-map.md | 563 ++++-- docs/agents/runtime/build-test-release.md | 380 ++-- docs/agents/runtime/decide-policy-actions.md | 833 ++++---- docs/agents/runtime/devtools.md | 69 +- docs/agents/runtime/learn-situation-triage.md | 1717 ++++++++--------- docs/agents/runtime/model-host.md | 100 +- docs/agents/runtime/observe-and-trace.md | 389 ++-- .../runtime/public-api-and-lifecycle.md | 181 +- docs/agents/runtime/state-and-adapters.md | 329 ++-- docs/agents/sim.md | 1300 ++++++------- docs/agents/status-and-known-issues.md | 1127 +++++------ docs/agents/training.md | 278 ++- packages/runtime/README.md | 383 +++- 27 files changed, 7055 insertions(+), 5010 deletions(-) create mode 100644 RELEASE.md create mode 100644 docs/agents/realapps.md diff --git a/AGENTS.md b/AGENTS.md index 44d92c88..ae0b5dda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,192 +1,187 @@ # AGENTS.md -Root entry point for AI coding agents in GenClass-lib. Verified against commit 654d822 (2026-10-07). -The code is the source of truth: if this file or any other doc disagrees with it, the code wins. +Root entry point for AI coding agents in GenClass-lib. + +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## 1. What this repo is - `@genclass/runtime` (`packages/runtime/`) is an npm library for self-healing web apps. It observes a running app - (fetch/XHR/WebSocket, user actions, timers, state stores, errors, causality) and computes generic facts. -- For salient situations a small local model (ONNX in a Web Worker, WebGPU or WASM) chooses a diagnosis and an action. - Actions are minimal (only `discard`, a late revert, `rollback` and custom actions with `onUndo` can be undone), and they - pass a precision-first policy gate. Without a model the runtime only observes. -- `sim/` generates training data by driving the real runtime. `training/` trains and exports the model, and `demos/` holds six evaluation apps. -- `jev_local/`, `extension/`, `bench/`, `results/` and the legacy `docs/*.md` are the older GenClass model, Chrome extension and benchmarks that the runtime builds on. -- npm workspaces: `packages/*`, `sim`, `demos`. Branches `main`, `origin/main` and `origin/runtime` all point at 654d822. - -Read next: [docs/agents/README.md](docs/agents/README.md) (index: which doc answers which question), then -[docs/agents/overview.md](docs/agents/overview.md) (how the parts fit together). Also: -[repo-map](docs/agents/repo-map.md), [glossary](docs/agents/glossary.md), [playbooks](docs/agents/playbooks.md), and -[status-and-known-issues](docs/agents/status-and-known-issues.md) before you change anything. - -## 2. Status in brief - -- `@genclass/runtime@0.1.0-alpha.0` is on npm (per `OPEN_TASKS.md`; git tag `v0.1.0-alpha.0` = 654d822). **It only observes.** - `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which is - not published yet (`packages/runtime-model/` holds only `MODEL_CARD.md`). So a default `GenClass.init()` ends with model status `error` and - prints `[GenClass] Model unavailable (...); observing only.` From then on it never holds a write or takes an action. -- The runtime source is frozen at tag `situation-v1` (1a77558): `git diff situation-v1 HEAD -- packages/runtime/src` is - empty. SIM phase A (600,676 rows) came from that code. Final training round 1 was launched, and the repo has no results from it. -- Next (`OPEN_TASKS.md`): choose the shipping model (R17 and/or R32), publish `@genclass/runtime-model@0.1.0` and its GitHub - release, publish `@genclass/runtime@0.1.0`, add CI, then re-run the demos with the trained model. -- The repo has no CI (no `.github/`) and no committed root `package-lock.json`. Demo results so far use the v0.1 GenClass model - (a general classifier, not trained for runtime decisions). -- `demos/src/server/data/cities.ts` is not in git (root `.gitignore` rule `data/`), so a fresh clone cannot build or typecheck the demos. -- Open product risks (`demos/NEEDS.md` §1, §2, §5, all still open in code): held writes can land after a newer user write, holds add - latency, and `retry` is offered for non-idempotent requests. Details: [status doc](docs/agents/status-and-known-issues.md). - -## 3. Ground rules (binding; `docs/runtime/CONTRACT.md` §0 and §0.5) - -CONTRACT: "If something here is wrong, tell the lead; do not silently diverge." The workstream roles in the docs -(lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule says "ask the lead", ask the user. - -1. **No hardcoded bug rules in the runtime (§0 rule 1).** The runtime may compute generic, uniform facts and may triage, which means - deciding whether a situation is worth asking the model about. It must never map a fact pattern to a diagnosis or an action with an if/then. Diagnoses and - actions come from the model. In code, triage is `facts.every((f) => f.neutral)` in `packages/runtime/src/runtime.ts` -> - `RuntimeImpl.trigger`. Actions are chosen only by `packages/runtime/src/decide/policy.ts` -> `gate` from model probabilities. - `packages/runtime/src/situation/build.ts` -> `builtinApplicable` says only whether an action *can* run. -2. **Train/runtime parity (§0 rule 2).** There is exactly one implementation of situation building and serialization: - `packages/runtime/src/situation/*`. The sim drives the real runtime (`sim/src/run/rt.ts` -> `realRuntimeFactory`), and - `training/curriculum/rt.py` is a Python port of it. The situation format is frozen at tag `situation-v1`. **Any change to - situation text, facts, questions, action/diagnosis wording, `packages/runtime/src/util.ts` formatting or op/event names - invalidates the SIM data and the trained model.** Do not make such a change without the user's explicit go-ahead. -3. **Determinism (§0 rule 3).** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly, and never - schedules with the global `setTimeout`. It uses the injected `Clock` (`packages/runtime/src/clock.ts` -> `browserClock` - captures the real timers at module load). IDs come from counters (e.g. `OpRegistry` `nextId`, action ids `a<n>`). - Same inputs give byte-identical situations. Known exceptions, none of which touch situation text: - `packages/runtime/src/model/engine.ts` defaults `now` to `performance.now()` (timing only), - `packages/runtime/src/model/host.ts` -> `scheduleIdle` uses `requestIdleCallback`, and - `packages/runtime/src/devtools/index.ts` captures the global `requestAnimationFrame` and `setTimeout` at module load - (`rawRaf`, `rawSetTimeout`: render flushes, the Copy-button reset and the no-plugin timer fallback). -4. **Honest-evaluation separation (§0 rule 4).** `sim/` and `demos/` never read or model each other. The sim never models a - demo. Demos contain nothing beyond a normal integration: stores, optional resync handlers, and custom actions or questions only in - the extensibility demo. Do not copy code, scenarios or knowledge between the two. -5. **Precision first, fail open (§0 rule 1, §0.5 principle 1, §8, §11).** The default mode (`guard`) takes only minimal guard-tier - actions (`discard`, `defer`, `coalesce`, `delay`; only `discard` has an undo, so CONTRACT's "reversible" is drift: - [decide-policy-actions](docs/agents/runtime/decide-policy-actions.md) Drift 10). An action runs only when the summed calibrated - probability of the permitted non-passive actions reaches the candidate action's tier threshold (guard-tier 0.9, heal-tier 0.8; - `packages/runtime/src/decide/policy.ts` -> `gate`), and the model's top diagnosis is not `expected`. If the model is unavailable, loading, late or erroring, the runtime takes the passive action. Held writes and - requests are released when the hold budget expires. False interventions on clean runs are a first-class metric. -6. **Dependencies (§0 rule 6).** `onnxruntime-web` is the only runtime `dependency` (`packages/runtime/package.json`). Do not - add another runtime dependency without asking. React, Redux and Zustand are optional peers. -7. **TypeScript strict, ESM only (§0 rule 6).** `tsconfig.base.json` sets `strict`, `verbatimModuleSyntax` and `isolatedModules`. - The package is ESM-only (no `require` export). `packages/runtime/tsconfig.json` has `types: []`, so `src/` must not use Node APIs. -8. **Leave legacy content alone (§1).** "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is." This - covers the pre-runtime GenClass content: `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, the legacy `docs/*.md`, - `docs/benchmax-research/` and the legacy scripts in `scripts/`. It does not cover `docs/runtime/`, `docs/agents/` or - `scripts/vm.sh`. Edit legacy content only when the user asks ([playbooks](docs/agents/playbooks.md) recipe 27). -9. **REVIEW tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make them pass. Fix `src/` instead. + (fetch/XHR/WebSocket/EventSource, user actions, timers, state stores, errors, causality) and computes generic facts. + For salient situations a small local model (ONNX in a Web Worker, WebGPU or WASM) chooses a diagnosis and an action, + which must pass a precision-first policy gate. Without a model the runtime only observes. +- **Situation-v2 design:** decisions happen at the network boundary. The `delivery` trigger (`packages/runtime/src/types.ts` + -> `TriggerKind`) holds only the delivery of a response or push message, and only when newer data already sits in the + fields it would write. Store writes are not held by default (`policy.holdWrites` is opt-in). +- `sim/` generates training data by driving the real runtime. `realapps/` runs real framework apps in headless Chromium + with the real runtime for real-browser training rows and the "never worse" sweep. `training/` trains and exports the + model. `demos/` holds six evaluation apps. +- `jev_local/`, `extension/`, `bench/`, `results/`, `tests/` and the legacy `docs/*.md` are the older GenClass model, + Chrome extension and benchmarks that the runtime builds on. +- npm workspaces: `packages/*`, `sim`, `demos` (`realapps/` has its own `package.json` but is not a workspace). + +Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current by the colleague, Mehar) and +**[docs/agents/README.md](docs/agents/README.md)** (index: which doc answers which question), then +[overview](docs/agents/overview.md), [repo-map](docs/agents/repo-map.md), [glossary](docs/agents/glossary.md), +[playbooks](docs/agents/playbooks.md), [status-and-known-issues](docs/agents/status-and-known-issues.md) and +[RELEASE.md](RELEASE.md) (release procedure). + +## 2. Status in brief (2026-10-08) + +- **Branches.** `mvp-v2` (here) = `origin/runtime` 74f17c0 (Mehar's latest: runtime batches 4 and 5, situation-v2, `realapps/`, + v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus three local commits: 7dab2b3 (these agent docs), + f3636b2 (default mode `observe`), b435acb (CI, committed root lockfile, CLI mode 100755). Not pushed. The local + branch `mvp` is based on situation-v1 (654d822) and is superseded. +- **Runtime:** situation-v2, frozen at tag `situation-v2` (6e5e86e). Since that tag, `packages/runtime/src` changed only in + f3636b2 (`runtime.ts`, `types.ts`, `devtools/index.ts`); `git diff situation-v2 HEAD -- packages/runtime/src/situation` is empty. +- **Model: none for v2.** Round-1 R17/R32 models were trained on situation-v1 and do not match this runtime. The v2 plan + (HANDOFF "Current state"): 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> + DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. +- **Data is being generated now on Azure by Mehar** (per `training/NEEDS.md`): SIM situation-v2 gold and unlabeled rows on + 20 nodes, REAL real-browser gold rows on 3 nodes. Nobody on our side touches Azure. +- **npm:** `@genclass/runtime@0.1.0-alpha.0` is `latest`. It predates situation-v2, defaults to `guard`, and has no model. + `@genclass/runtime-model` is not published, so `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the + CLI's `DEFAULT_FROM` 404: a default `GenClass.init()` ends with model status `error` and logs + `[GenClass] Model unavailable (...); observing only.` A `0.1.0-alpha.1` patch (NaN fix) waits on the owner's 2FA + (`OPEN_TASKS.md` "Needs the user"). Release plan: [RELEASE.md](RELEASE.md) (see also + [build-test-release](docs/agents/runtime/build-test-release.md) "Cut a release"). +- **Stale human docs:** `HANDOFF.md` ('Modes: observe → guard (default; ...)') and the published `0.1.0-alpha.0` still + say guard is the default; both READMEs now say observe. Test counts in STATUS/HANDOFF are older. Drift tables: [status-and-known-issues](docs/agents/status-and-known-issues.md). +- **Open defects found by review at b435acb** (details and fixes in the subsystem docs' "Drift and open issues"): + the F2 content fact can print the raw text of redacted fields (`situation/content.ts` -> `contentFacts`); a delivery + `discard` applies a Redux/Zustand dispatch whole when it also changes other fields, yet the record names the fields + as dropped (`state/hub.ts` -> `StoreHub.applyFilter`); SIM still samples the + v1 3,200-char budget (`sim/src/world/scenario.ts`); unlabeled SIM rows hard-label `expected` diagnoses that S1 would + relabel. Several of these touch model-visible text or live data generation: coordinate with the user before fixing. +- `demos/src/server/data/cities.ts` is not in git (root `.gitignore` rule `data/`), so a fresh clone cannot build or + typecheck the demos, and root `npm run typecheck` fails. + +## 3. Ground rules (binding; `docs/runtime/CONTRACT.md` §0, §0.5, §13) + +CONTRACT: "If something here is wrong, tell the lead; do not silently diverge." The roles in the docs (lead, CORE, MODEL, +UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule says "ask the lead", ask the user. + +1. **No hardcoded bug rules in the runtime.** The runtime may compute generic facts and triage (decide whether a situation + is worth asking the model about). It never maps a fact pattern to a diagnosis or action with an if/then. Triage is + `facts.every((f) => f.neutral)` in `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`; actions are chosen only by + `packages/runtime/src/decide/policy.ts` -> `gate`; `packages/runtime/src/situation/build.ts` -> `builtinApplicable` + says only whether an action *can* run. +2. **Situation-v2 freeze (train/runtime parity).** There is one implementation of situation building and serialization: + `packages/runtime/src/situation/*`. The sim drives the real runtime (`sim/src/run/rt.ts` -> `realRuntimeFactory`), + realapps bundles it from source, and `training/curriculum/rt.py` ports it. **Any change to + `packages/runtime/src/situation/*` or to other model-visible text** (facts, questions, action/diagnosis wording, + `packages/runtime/src/util.ts` formatting and redaction, op/event names) **means a new tag and regenerated data** (and + an `rt.py` mirror and retraining). Data is being generated from this code right now: never make such a change without + the user's explicit go-ahead. See [model-io-contract](docs/agents/model-io-contract.md). +3. **Determinism.** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly and never schedules + with the global `setTimeout`; it uses the injected `Clock` (`packages/runtime/src/clock.ts`). IDs come from counters. + Same inputs give byte-identical situations. Known exceptions, none touching situation text: + `packages/runtime/src/model/engine.ts` (default `now`), `packages/runtime/src/model/host.ts` -> `scheduleIdle` + (`requestIdleCallback`), `packages/runtime/src/devtools/index.ts` (`rawRaf`, `rawSetTimeout`). +4. **Honest-evaluation separation.** `sim/` and `realapps/` never read or model `demos/`; demos are never tuned and contain + nothing beyond a normal integration. (`realapps/` does import the sim's cost weights and label rule from `sim/src`.) +5. **Default `observe`; never make a correct app worse.** Since f3636b2 the default mode is `observe` (`runtime.ts` -> + `o.mode ?? "observe"`, CONTRACT §13): it never takes an action. `guard` is opt-in (minimal guard-tier actions: + `discard`, `defer`, `coalesce`, `delay`); `heal` is experimental. An action runs only when the summed calibrated + probability of permitted non-passive actions reaches the tier threshold (`decide/policy.ts`: guard 0.9, heal 0.8) and + the top diagnosis is not `expected`. Model unavailable, loading, late or erroring means the passive action; holds are + released when the hold budget expires. False interventions on clean runs are a first-class metric: report FIR next to + every recall number (HANDOFF "How to continue" step 4). +6. **Dependencies.** `onnxruntime-web` is the only runtime `dependency`. Ask before adding another. React, Redux and + Zustand are optional peers. Keep the committed root `package-lock.json` in sync (CI runs `npm ci`). +7. **TypeScript strict, ESM only.** `tsconfig.base.json` sets `strict`, `verbatimModuleSyntax`, `isolatedModules`. + `packages/runtime/tsconfig.json` has `types: []`, so `src/` must not use Node APIs. +8. **Leave legacy content alone** (CONTRACT §1): `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, legacy + `docs/*.md`, `docs/benchmax-research/`, legacy `scripts/`. Not covered: `docs/runtime/`, `docs/agents/`, `scripts/vm.sh`. +9. **REVIEW tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make them pass. Fix `src/`. ## 4. Where to run things -- **The team's rule (CONTRACT §0 rule 5).** "The Mac only edits files." Every build, test, browser and model run went to the Azure `train` VM through - `scripts/vm.sh` in a per-workstream slot, because the original author's Mac has 8 GB RAM. `vm.sh` needs - `~/.jev-local/azure_hosts`, `~/.ssh/jev_azure` and GNU `timeout`, none of which are in the repo. -- **Policy for agents (set when these docs were written, 2026-10-07).** On other machines, `npm install`, typecheck, build and unit tests are - light and were verified locally (macOS, 16 GB RAM, Node v25.6.0, npm 11.8.0). You may run the verified commands in §5. -- **Ask the user first** before running any of these: the sim (generation, `sim/scripts/*`), training (`training/*.sh`, any Python training or eval), - Playwright (`npm run test:browser`, the UI spec, `test/smoke/smoke.sh`), model downloads (`genclass-runtime fetch-model`, - `demos/scripts/fetch-model.sh`), the demos' eval (`npm run eval` in `demos/`, `demos/scripts/vm-eval.sh`), or any script that touches Azure - (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). -- **Side effects of `npm install` at the root.** It creates an untracked root `package-lock.json` (never committed; whether to commit - one is the user's decision). It also chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, which git reports as a mode change - (committed mode is 644). Revert it with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. - -## 5. Commands +- **Our run policy (lead, 2026-10-08).** Light local checks are fine on this machine (macOS, 16 GB, Node v25.6.0): + `npm install`/`npm ci`, `tsc`, `tsup`, vitest unit tests (runtime and sim). +- **Ask the user first** before: Playwright (`npm run test:browser`, the UI spec), `test/smoke/smoke.sh`, the sim generator + (`sim/scripts/*`, `gen.js`), training (`training/*.sh`, any Python training or eval), realapps runs (`gen.js`, + `debug.js`, `realapps/scripts/*`), the demos' eval, model downloads (`genclass-runtime fetch-model`), **anything on + Azure** (`scripts/*.sh`, `az`, ssh to nodes), **`git push`** and **`npm publish`**. +- `HANDOFF.md` "Rules" ("never run npm, tsc, vitest ... on the Mac"; build and test on the Azure `train` VM via + `scripts/vm.sh`) describes Mehar's workflow on his 8 GB Mac and his Azure cluster. It is context, not instructions for us. -Verified when these docs were written, 2026-10-07 (Node v25.6.0). "Dir" is where to run the command from. +## 5. Commands (verified 2026-10-08 on mvp-v2, Node v25.6.0) | command | dir | result / notes | |---|---|---| -| `npm install` | repo root | OK in 18 s, 134 packages. One EBADENGINE warning: vitest 5.0.3 wants Node `^22.12.0 \|\| ^24.0.0 \|\| >=26.0.0` (Node 25 works). Side effects: see §4 | -| `npx tsc -p tsconfig.json --noEmit` | `packages/runtime` | clean, ~1.6 s. Checks `src/` only: test files are never type-checked | -| `npx tsup` | `packages/runtime` | ~2.5 s. Cleans `dist/` first. 6 entries: `index`, `adapters/{react,redux,zustand}`, `devtools/index`, `worker`; `.d.ts` for all but `worker`; ~1.6 MB with maps | -| `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` | `packages/runtime` | ~2.4 s. Files 36 passed, 1 skipped (37). Tests 286 passed, 14 skipped (300). The 14 skips are model-parity tests that need model files at `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`): `test/model/packer.test.ts` (all 10), `engine.test.ts` (3 of 4), `calibrate.test.ts` (1 of 8). With a model dir, all 300 pass | - -Not verified when these docs were written (taken from [build-test-release.md](docs/agents/runtime/build-test-release.md)): - -| command | dir | notes | -|---|---|---| -| `npm run build` / `npm test` | repo root | run only in `@genclass/runtime` (`tsup` / `vitest run`). `vitest.config.ts` already excludes `test/browser/**` | -| `npm run typecheck` | repo root | every workspace. The demos typecheck needs `packages/runtime/dist/*.d.ts`, so build first; it also needs the missing `demos/src/server/data/cities.ts` (see [demos.md](docs/agents/demos.md)). Until that file is recreated, the demos typecheck, and so the root typecheck, fails (inferred from the imports; not run) | -| `npx vitest run test/atoms.test.ts -t "late discard"` | `packages/runtime` | one file or one test | -| `npm run test:browser` | `packages/runtime` | **ask first.** Playwright, rebuilds `dist/`, needs Chromium for `@playwright/test` 1.63.0 and a model dir, overwrites the committed UI screenshots | -| `npx playwright test --config test/browser/ui/playwright.config.ts` | `packages/runtime` | **ask first.** Devtools UI spec, writes 18 screenshots | -| `bash test/smoke/smoke.sh` | `packages/runtime` | **ask first.** `npm pack` into a temp Vite 8 app (registry access), then headless Chromium; leaves the `.tgz` and the temp dir | -| `npm run build && cd sim && SIM_RUNTIME=real npx vitest run` | repo root | **ask first** (sim). Sim tests against the real runtime; without `SIM_RUNTIME=real` they use a fake runtime | -| `node packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | repo root | **ask first** (download). Fetches the v0.1 model for the model tests (`GENCLASS_MODEL_DIR=<dir>`). The default `--from` is an unpublished release | -| `scripts/vm.sh run\|exec <SLOT> '<cmd>'` | repo root | **ask first** (Azure). The original team's path for every command above | +| `npm ci --no-audit --no-fund` | repo root | OK from the committed lockfile (fresh clone too). Add `ONNXRUNTIME_NODE_INSTALL=skip` on Linux, as CI does. EBADENGINE warning from vitest on Node 25 is harmless | +| `npx tsc -p tsconfig.json --noEmit` | `packages/runtime` | clean. Checks `src/` only: test files are never type-checked | +| `npx tsup` | `packages/runtime` | OK. 6 entries (`index`, 3 adapters, `devtools/index`, `worker`) into `dist/` | +| `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` | `packages/runtime` | Files 40 passed, 1 skipped (41). Tests 332 passed, 14 skipped (346). The 14 skips are model-parity tests needing `GENCLASS_MODEL_DIR` | +| `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | `packages/runtime` | 4 passed. Run it alone: in a full parallel run it flaked once (5.5 ms vs a 2 ms bound). CI uses `--retry=2` | +| `npm run build` then `SIM_RUNTIME=real npx vitest run` | root, then `sim/` | 19 passed (5 files). Sim `tsc` clean. Without `SIM_RUNTIME=real` the sim tests use a fake runtime | + +Total: 350 runtime unit tests (336 passed, 14 skipped without a model dir). CI (`.github/workflows/ci.yml`, Node 22) runs +`npm ci` -> runtime typecheck -> build -> the two vitest steps above; triggers: push to `main`/`runtime`/`mvp`/`mvp-v2`, +`pull_request`, `workflow_dispatch`. It has not run on GitHub yet (mvp-v2 is not pushed). Not run by us: Playwright, +`smoke.sh`, realapps, demos eval, Python tests, training. One test: `npx vitest run test/delivery.test.ts -t "<name>"`. ## 6. Top-level layout | path | what it is | doc | |---|---|---| -| `packages/` | `runtime/`: the `@genclass/runtime` library (`src/`, `test/`, `bin/genclass-runtime.mjs` CLI, `STATUS.md`, `UI-NEEDS.md`). `runtime-model/`: only `MODEL_CARD.md` of the unpublished model package | [docs/agents/runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle, [build-test-release](docs/agents/runtime/build-test-release.md)) and [model-io-contract](docs/agents/model-io-contract.md) | -| `sim/` | `@genclass/sim`: training-data simulator driving the real runtime (private, Node 22 ESM) | [sim.md](docs/agents/sim.md) | -| `training/` | Python training, eval and export of the runtime model (R17/R32), plus Azure scripts | [training.md](docs/agents/training.md) | -| `demos/` | `@genclass/demos`: six Vite demo apps, Service Worker chaos backend, Playwright trial harness | [demos.md](docs/agents/demos.md) | -| `docs/` | `runtime/` (`CONTRACT.md`, which is binding, plus `API.md` and `ARCHITECTURE.md`; all three drift from the code), `agents/` (these docs), legacy `*.md` and `benchmax-research/` (do not edit) | [status-and-known-issues](docs/agents/status-and-known-issues.md) (drift tables) | -| `jev_local/` | legacy Python predecessor (`jev-local`): the model the runtime's `src/model` was ported from, the trainer `training/` drives, server and harness | [genclass-model-lineage.md](docs/agents/genclass-model-lineage.md) | -| `tests/` | Python tests for `jev_local` (the 20 `test_data_*.py` files fail at collection: `jev_local/data` is gitignored) | [genclass-model-lineage.md](docs/agents/genclass-model-lineage.md) | -| `extension/` | legacy GenClass 0.1.0 MV3 voice-control Chrome extension, the JS ancestor of `src/model` | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) | -| `bench/`, `results/` | benchmark pre-registrations and published results (jevbench, benchmax, CU head-to-head) | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) | -| `scripts/` | ops and benchmark scripts; for the runtime: `vm.sh` (VM build/test), `azvm.sh` and `launch_run.sh` (called by `training/*.sh`), and `genclass_export.py` (its `ExportModel` is imported by `training/export_runtime.py`) | [extension-and-benchmarks.md](docs/agents/extension-and-benchmarks.md) (one row per script) | -| root files | `package.json` (workspaces), `tsconfig.base.json`, `pyproject.toml` (`jev-local`), `OPEN_TASKS.md`, `README.md`, `BENCHMARKS.md`, `LICENSE` (Apache-2.0) | [status-and-known-issues](docs/agents/status-and-known-issues.md) | +| `packages/runtime/` | `@genclass/runtime`: `src/`, `test/`, `bin/genclass-runtime.mjs` CLI, `STATUS.md` (runtime state, example situations, deviations), `UI-NEEDS.md` | [runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle and [build-test-release](docs/agents/runtime/build-test-release.md)), [model-io-contract](docs/agents/model-io-contract.md) | +| `packages/runtime-model/` | only `MODEL_CARD.md` of the unpublished model package | [model-host](docs/agents/runtime/model-host.md) | +| `sim/` | `@genclass/sim`: deterministic training-data simulator (S1/S2 labels, `SEPARABILITY.md`) | [sim.md](docs/agents/sim.md) | +| `realapps/` | 91 real apps (corpus + 14 open-source Conduit front-ends) in headless Chromium; REAL rows and the never-worse sweep | [realapps.md](docs/agents/realapps.md) | +| `training/` | Python training, curriculum (`curriculum/rt.py`), eval, export, Azure launch scripts; `NEEDS.md`, `LOG.md`, `EVAL.md` | [training.md](docs/agents/training.md) | +| `demos/` | `@genclass/demos`: six Vite demo apps, Service Worker chaos backend, Playwright trials | [demos.md](docs/agents/demos.md) | +| `docs/runtime/` | `CONTRACT.md` (binding; changes appended to §13), `API.md`, `ARCHITECTURE.md`, [RESULTS.md](docs/runtime/RESULTS.md) (model and design comparisons, data volume, training log) | [status-and-known-issues](docs/agents/status-and-known-issues.md) | +| `docs/agents/` | these docs | [README](docs/agents/README.md) | +| `.github/workflows/ci.yml` | the only CI workflow | [build-test-release](docs/agents/runtime/build-test-release.md) | +| `jev_local/`, `tests/` | legacy Python predecessor and its tests | [genclass-model-lineage](docs/agents/genclass-model-lineage.md) | +| `extension/`, `bench/`, `results/`, `scripts/` | legacy extension and benchmarks; `scripts/vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py` serve the runtime | [extension-and-benchmarks](docs/agents/extension-and-benchmarks.md) | +| root files | `HANDOFF.md` (live handoff), `OPEN_TASKS.md`, [`RELEASE.md`](RELEASE.md) (release procedure), `package.json` + `package-lock.json`, `tsconfig.base.json`, `pyproject.toml`, `README.md`, `BENCHMARKS.md`, `LICENSE` (Apache-2.0) | [repo-map](docs/agents/repo-map.md) | ## 7. Conventions -**Code (observed in `packages/runtime/src`; there is no formatter or linter config).** -- Every module opens with a `//` header comment that states its role and invariants. Many cite the CONTRACT section they implement - (e.g. `// Policy gate for non-passive actions (CONTRACT §8)`). Most `packages/runtime/src/model/*` headers name the - `jev_local` Python file or extension code they port. -- Comments are sparse: about 4-10% of lines in the large modules. Use `/** */` JSDoc on exported symbols and non-obvious fields. Inline - comments mostly explain why, or state an invariant. -- Naming: PascalCase classes and types (`RuntimeImpl`, `StoreHub`, `OpRegistry`), camelCase functions, UPPER_SNAKE module constants - (`LATE_REVERT_MS`, `CACHE_MAX`), short locals. Named exports only. The one default export is - `packages/runtime/src/index.ts` -> `GenClass`. -- Imports: relative paths with `.js` extensions; `import type` for types (`verbatimModuleSyntax`). Style: 2-space indent, - double quotes, semicolons, lines mostly at most 120 chars. -- Errors: never throw into the host app. Hooks, plugins, listeners and callbacks run in `try/catch` with a comment - (`/* hooks never break the app */`, `/* listeners never break tracing */`). `ask()`/`decide()` reject with - `GenClassUnavailableError` and a `reason` (`packages/runtime/src/errors.ts`); with `timeoutMs` set, a failed model load - rejects with the provider's own error instead. A failing action controller throws a plain `Error` with an English - message: the runtime records `ok: false` plus `error` on the `ActionRecord` and runs the passive action instead. -- Every user-visible or model-visible string (facts, reports, `changed` sentences) is plain English. Model-visible text is frozen (rule 2). +**Code (observed in `packages/runtime/src`; no formatter or linter config).** +- Every module opens with a `//` header comment stating its role and invariants, often citing the CONTRACT section. +- Sparse comments; `/** */` JSDoc on exported symbols and non-obvious fields. PascalCase classes/types (`RuntimeImpl`, + `StoreHub`, `OpRegistry`), camelCase functions, UPPER_SNAKE module constants (`LATE_REVERT_MS`, `CACHE_MAX`). + Named exports only, except `packages/runtime/src/index.ts` -> `GenClass` (default export). +- Relative imports with `.js` extensions; `import type` for types. 2-space indent, double quotes, semicolons, ~120 chars. +- Never throw into the host app: hooks, plugins, listeners and callbacks run in `try/catch` with a comment. + `ask()`/`decide()` reject with `GenClassUnavailableError` (`packages/runtime/src/errors.ts`). A failing action + records `ok: false` on the `ActionRecord` and the passive action runs instead. +- Model-visible text is plain English and frozen (rule 2). **Tests (`packages/runtime/test/`, vitest).** -- One `<area>.test.ts` per area (`test/model/` for model code). Use `test/helpers.ts`: `setup()` returns `{ clock, server, g, decider, rt, fetch }` - and builds a `FakeClock`, a `FakeServer`, an instrumented global and a `ScriptedDecider` around `createRuntime`. There is no real time, network or model. -- Drive time with `clock.advance(ms)` / `clock.flush()`. Control answers with `defaultScript({ <trigger>: { diagnosis, action } })`, - or with `ManualDecider` plus `answer()`. Force consultation with `triage: "always"`. Assert on `decider.calls[i].state`, `rt.decisions()`, - `rt.interventions()`, `server.hits`. -- Name the CONTRACT section in the `describe` (e.g. `"atoms and the mutation pipeline (CONTRACT §4)"`). DOM tests start with - `// @vitest-environment happy-dom`. Never use real timers or `Date.now` in tests except where noted in the build doc. - -**Coordination files (the original team's protocol; keep using it).** -- `OPEN_TASKS.md` (lead): project status in Done / In progress / Next / Needs the user / Known risks. -- `packages/runtime/STATUS.md` (CORE): test state, batch changes, headless recipe, trigger table, example situations, - **Deviations from the contract (and why)**, **Open issues**. -- `NEEDS.md` files live in the *requester's* directory: `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and - (an exception) `packages/runtime/UI-NEEDS.md`. `sim/NEEDS.md` and `training/NEEDS.md` mark items OPEN (needed) / ASK (would help) / - DONE (landed and verified by the requester), and training/NEEDS also uses INFO. `UI-NEEDS.md` uses Open / Nice to have / Done - sections. `demos/NEEDS.md` uses numbered sections addressed to an owner. Owners may add answers to a requester's file - (training/NEEDS has "CORE → TRAIN" and "MODEL → TRAIN (from MODEL, ...)" sections); only the requester closes an item. -- `docs/runtime/CONTRACT.md` (lead): the binding spec. An approved change is appended to §13, and an accepted divergence goes into STATUS - "Deviations". A deviation without a STATUS entry is a bug. CONTRACT, STATUS, API.md and the NEEDS files are stale in places - (CONTRACT was last edited before batch 3): check the drift tables in the status doc before relying on them. +- One `<area>.test.ts` per area (`test/model/` for model code). `test/helpers.ts` -> `setup()` returns + `{ clock, server, g, decider, rt, fetch }` around `createRuntime` with `FakeClock`, `FakeServer` and `ScriptedDecider`. + No real time, network or model. +- `setup()` defaults to `mode: "guard"` (not the product default); pass `mode: undefined` for `observe` + (`test/default-mode.test.ts`). Held store writes need `policy: { holdWrites: true }`; delivery behaviour is in + `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts`. +- Drive time with `clock.advance(ms)` / `clock.flush()`; control answers with `defaultScript(...)` or `ManualDecider`; + force consultation with `triage: "always"`. Name the CONTRACT section in the `describe`. DOM tests start with + `// @vitest-environment happy-dom`. + +**Coordination files (the team's protocol; keep using it).** +- `HANDOFF.md`: live state and how to continue. `OPEN_TASKS.md`: Done / In progress / Next / Needs the user / Known risks. +- `packages/runtime/STATUS.md`: test state, batch changes, example situations, "Deviations from the contract", "Open issues". +- [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md): update it with every result (HANDOFF repo map). +- `NEEDS.md` files live in the requester's directory (`sim/`, `training/`, `demos/`, plus `packages/runtime/UI-NEEDS.md`); + only the requester closes an item. `training/NEEDS.md` also holds Azure node claims and data locations. +- `docs/runtime/CONTRACT.md`: approved changes go to §13; an accepted divergence goes into STATUS "Deviations". ## 8. Definition of done -1. If you touched `packages/runtime/src`: `npx tsc -p tsconfig.json --noEmit` is clean, and `npx tsup` still builds when you changed - entries, exports or the worker. Keep tsup entries as literal `"src/...ts"` strings, and keep the worker URL and ORT `import()` literals. -2. Unit tests pass: 286 passed and 14 skipped without a model dir (all 300 with one), plus new tests in house style for new - behaviour. No `review-*.test.ts` was edited. For sim or demos changes, name the checks you could not run and why. -3. No model-visible text changed (rule 2), unless the user explicitly approved it. If it was approved, also update the exact-text - tests and the STATUS example situations, and flag that SIM data and training must be regenerated. -4. Update the affected `docs/agents/` doc(s) (see [docs/agents/README.md](docs/agents/README.md)) and set its header line - `Verified against commit <sha> (<date>)` to the commit you re-checked it against. A public-surface change also updates - `docs/runtime/API.md` and the JSDoc in `packages/runtime/src/types.ts`. -5. If behaviour changed: update `packages/runtime/STATUS.md` (Updated line, batch section, Deviations, Open issues) and move the item - in `OPEN_TASKS.md`. Add or answer the relevant `NEEDS.md` item. -6. Leave no `npm install` side effects in the diff: revert the `bin/genclass-runtime.mjs` mode change and do not commit the root - `package-lock.json` unless the user decided to. +1. If you touched `packages/runtime/src`: `tsc` clean and `tsup` builds (keep tsup entries as literal `"src/...ts"` + strings and the worker URL / ORT `import()` literals). +2. Runtime unit tests pass in both CI steps (§5: 332 + 14 skipped, then review-perf 4), plus new tests in house style. + No `review-*.test.ts` edited. For sim, realapps, demos or training changes, name the checks you could not run and why. +3. No model-visible text changed (rule 2) unless the user approved it; if approved, update exact-text tests and STATUS + example situations, and flag that a new situation tag, `rt.py` mirror, regenerated data and retraining are needed. +4. Update the affected `docs/agents/` doc(s) and set the header's "Verified against" line to the commit you re-checked. + A public-surface change also updates `docs/runtime/API.md` and the JSDoc in `packages/runtime/src/types.ts`. +5. If behaviour changed: update `packages/runtime/STATUS.md`, `OPEN_TASKS.md`, `HANDOFF.md` if its state table changes, + `docs/runtime/RESULTS.md` for new numbers, and the relevant `NEEDS.md` item. +6. A dependency change commits the updated root `package-lock.json` in the same commit. +7. Commit locally with the attribution the session gives you; **do not push or publish without the user** (publish steps: [RELEASE.md](RELEASE.md)). diff --git a/CLAUDE.md b/CLAUDE.md index f26a7604..2224461e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,3 +1,3 @@ -GenClass-lib: monorepo for @genclass/runtime, a self-healing web-app runtime with a local ONNX model, plus its training-data simulator (sim/), model training (training/) and demos (demos/). Agent instructions live in AGENTS.md, imported below. +GenClass-lib: monorepo for @genclass/runtime, a self-healing web-app runtime with a local ONNX model (situation-v2, default mode observe), plus its training-data simulator (sim/), real-browser corpus (realapps/), model training (training/) and demos (demos/). Live team handoff: HANDOFF.md. Agent instructions live in AGENTS.md, imported below; the doc index is docs/agents/README.md. @AGENTS.md diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 173b1f57..1055e321 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -1,104 +1,168 @@ # Open tasks: @genclass/runtime -Status as of 2026-10-08. New sessions: start with HANDOFF.md. Branch `runtime`. Spec: [docs/runtime/CONTRACT.md](docs/runtime/CONTRACT.md). +Status as of 2026-10-08 (~04:15 UTC). New sessions: start with [HANDOFF.md](HANDOFF.md). Branches: `runtime` +(the colleague's, at 74f17c0) and `mvp-v2` (= `runtime` + AI-agent docs, default mode `observe`, CI). Spec: +[docs/runtime/CONTRACT.md](docs/runtime/CONTRACT.md). Results and numbers: [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md). The runtime decides through a trained local model; nothing here is hardcoded per bug pattern. +The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). No situation-v2 model exists yet. + ## Done - **Published `@genclass/runtime@0.1.0-alpha.0` to npm** (2026-10-08, `genclass` org, owner meharpro). The tarball was smoke-tested in a fresh Vite app in headless Chromium (`packages/runtime/test/smoke/smoke.sh`). - The alpha takes no actions until the runtime model package is published. -- **Runtime fix batch 3** (frozen as tag `situation-v1`): all 34 review findings fixed, each with its - regression test; summed-probability gate; `transient`; compact questions; redaction by field meaning; - 300 tests passing. A keystroke write on a 5,000-item store takes 0.14 ms. + The alpha takes no actions: `@genclass/runtime-model` is not published, so the default model URL returns 404. + It predates batches 4–5 and the observe default (its default mode is guard). - **Runtime core** (`packages/runtime/src`): observers (fetch, XHR, DOM user actions, errors, nav, storage, - long tasks, WebSocket, timers), causal context propagation, stores (atoms, guard, adapter seam), mutation - pipeline with holds, learned invariants and transition profiles, latency/error/rate baselines, generic facts, + long tasks, WebSocket, EventSource, timers), causal context propagation, stores (atoms, guard, adapter seam), + mutation pipeline, learned invariants and transition profiles, latency/error/rate baselines, generic facts, situation serializer, triage, policy gate, built-in actions, console reports, `explain`, undo, kill switch, - plugins, device-sized situations, late revert. 239 tests passing before the current fix batch. + plugins, device-sized situations, late revert. +- **Runtime fix batch 3** (frozen as tag `situation-v1`): all 34 review findings fixed with regression tests; + summed-probability gate; `transient`; compact questions; redaction by field meaning. +- **Runtime batch 4: decisions at the network boundary** (fcd1e68). Store writes are no longer held by default; + the runtime holds only the delivery of a response or message (the `delivery` trigger) when newer data already sits + in the fields it would write, and drops its stale writes synchronously. Adds EventSource observation and the + `untrustedEvents` option. Motivation (v1 demos, guard, zero actions): board 11 card jump-backs, editor 37 + overwritten keystrokes, checkout 24 reset quantities, search clean latency 6 → 389 ms (RESULTS.md §4). +- **Runtime batch 5 + `situation-v2` freeze** (6e5e86e): real-app text fixes (shadow DOM, label text, leaf-field + redaction) and the separability facts F1, F2, F3, F5, F6, F7, F8, F9 and read-your-writes + (`packages/runtime/STATUS.md`). 346 tests on `runtime` per STATUS.md. +- **Never-worse sweep on v2** (realapps harness, all-passive model, heal vs observe): **0/396** clean runs changed + over the 66 apps then in the corpus; Conduit 0/30; chaos 3/198 changed (request-time holds shift a request by + ~25 ms); determinism 198/198 (RESULTS.md §4, STATUS.md). What the sweep compares is narrower than "same + requests, bodies, server state and DOM" (see Known risks). +- **Final training round 1** (situation-v1, 448k phase-A rows): R17 diagnosis 90.5%, action 81.9%, guard FIR + 0.05%, heal FIR 0.24%, calibration error 0.009, but recall on clear stale/duplicate cases only 7.7%; R32 is no + better (89.7% / 81.8% / 0.05% / 5.9%). R17 chosen as the default model (9.58 MB q8, 177/323/589 ms at + 500/780/1,170 tokens single-thread WASM) (RESULTS.md §1–2). Superseded: v1 models do not match the v2 runtime. +- **Separability analysis** (`sim/SEPARABILITY.md`) and its fixes: S1 labels (by the cause of the divergence), + S2 futures (re-draw latents the runtime cannot observe), and the F1–F9 facts in situation-v2. Effect on + visible-text separability, v1 → v2 (RESULTS.md §3): failure look-alikes 40% → 17%, request 48% → 38%, stall + 31% → 5%, mutation 8% → 2%; inconsistency linear recall at 1% FIR 10% → 20%. +- **Real-browser corpus** (`realapps/`, fcb8189 and later): real apps in 23 stacks in headless Chromium with the + sim's label semantics. 66 apps at the sweep; **91 apps in the tree now** (77 written + 14 open-source Conduit + front-ends). v2 pilot: 400 trajectories, 2,519 gold rows (135 `delivery`), 0 drops (`training/NEEDS.md` item 16). + See [docs/agents/realapps.md](docs/agents/realapps.md). +- **Curriculum ported to v2** (`training/curriculum/rt.py` mirrors the situation-v2 renderer; known divergences + under Next). +- **v2 data generation launched** (~04:00 UTC): SIM ~10M gold + ~50M unlabeled on 20 nodes; REAL ~495k + real-browser gold rows on 3 nodes (RESULTS.md §6–7). - **Model host** (`src/model`): TypeScript port of the GenClass engine (packing identical to Python on all 50 - fixtures; q8 decisions 79/80 vs PyTorch in Chromium), Web Worker with inline fallback, Cache Storage + sha256, - WebGPU → WASM plans, idle/lazy preload, latency stats, WASM-only ORT build when WebGPU is unavailable (2.7 MB br - instead of 4.7 MB), CLI `genclass-runtime fetch-model | info`. -- **Devtools overlay + adapters** (`src/devtools`, `src/adapters`): interventions/detections/activity/now views - with evidence and undo; React hooks, Redux enhancer, Zustand middleware. -- **Training-data simulator** (`sim/`): random apps over 55 domains driving the real runtime in a deterministic - virtual world; labels from counterfactual outcomes over 3 sampled futures; held-out domains for test. -- **Training pipeline** (`training/`): vocabulary pruning (16k merges), fp16-free int8 exports (R17 9.6 MB, - R32 22.5 MB), curriculum generator, stage-1 curriculum training of both candidates, stage-2 pilots. + fixtures), Web Worker with inline fallback, Cache Storage + sha256, WebGPU → WASM plans, idle/lazy preload, + latency stats, WASM-only ORT build, CLI `genclass-runtime fetch-model | info`. R17/R32 q8 exports agree with + PyTorch on 233/233 decisions in onnxruntime-web (RESULTS.md §2). +- **Devtools overlay + adapters** (`src/devtools`, `src/adapters`): React hooks, Redux enhancer, Zustand middleware. +- **Training-data simulator** (`sim/`) and **training pipeline** (`training/`): vocabulary pruning (16k merges), + fp16-free int8 exports, curriculum (~1.9M rows), stage 1 and stage 2 pilots. +- **On `mvp-v2` only** (not on `runtime`): default mode `observe` (guard opt-in, heal experimental) with + `test/default-mode.test.ts`; GitHub Actions CI (`.github/workflows/ci.yml`: typecheck, build, unit tests, + review-perf separately with retries) and a committed root `package-lock.json`; AI-agent docs (`AGENTS.md`, + `CLAUDE.md`, `docs/agents/**`). Verified locally on `mvp-v2`: 332 passed + 14 skipped (model parity) in the unit + run, plus 4 review-perf tests run alone (350 in total); review-perf can flake under parallel load. ## In progress -1. **Final data, phase A** (SIM): 600k rows from the frozen runtime (tag `situation-v1`), then phase B - (1.4M more, disjoint seeds) until the 03:00 UTC VM shutdown; resumable. -2. **Demos** (DEMOS): six demos, Service Worker backend, Playwright trial harness; screenshot tour and README. - Current numbers use the untrained v0.1 model and only validate the harness. +1. **v2 data on Azure** (Mehar operates the cluster; nobody else touches Azure). SIM: ≥ 10M gold + ≥ 50M + unlabeled rows on c02–c09 and c12–c23 into `train:/data/sim-out/v2-*`. REAL: production batches `v2b1`/`v2b2`/ + `v2b3` on c01, c10, c11 (30k trajectories each, target ≥ 500k gold), then copied to `train:/data/real-out/`. + Locations and manifests: `training/NEEDS.md`. +2. **Demos** (DEMOS): six demos, Service Worker backend, Playwright trial harness. Current numbers use the + untrained v0.1 model and only validate the harness (RESULTS.md §5: guard executed 0 actions; heal took 156, + which fixed nothing; 0 false interventions on clean runs). ## Next -3. **Runtime batch 4: move decisions to the network boundary** (CORE). The demos showed that holding - *store writes* makes correct apps worse even when GenClass takes no action: - - board: held writes landed after a newer user move and moved cards back (11 visible jump-backs over 30 - sessions); - - editor: 37 delayed save echoes rewrote newer keystrokes; - - checkout: 24 delayed confirmations reset quantities; - - search: clean-run latency rose from about 6 ms to 230–390 ms. - - The redesign holds only the delivery of a response or message (equivalent to network latency) when newer - data already sits in the fields it will write, and drops its stale writes synchronously. It also adds - EventSource observation and an `untrustedEvents` option. Produces the situation format `situation-v2`. -4. **Then regenerate all data on v2** (sim gold, unlabeled and on-policy rows; the real-app corpus) and run the - scaled training (teacher, then distillation into R17/R32, then retraining on the model's own mistakes). +The usual order (HANDOFF.md): v2 data collected → teacher → labels → distillation → DAgger → EVAL → model +package → demos rerun → runtime release. -3. **Final training round 1** (tonight, on phase A): R17 and R32 from their stage-1 weights, then eval, - calibration and export by about 02:40 UTC. **Round 2** (after the shutdown) uses phase A + B with longer - schedules. -4. **Final training details** (heavy, Azure): stage 2 for R17 and R32 on the frozen data plus curriculum replay; - calibration fit on dev, checked on held-out test; export; parity; EVAL.md with guard/heal precision, - false-intervention rate and regret per trigger and per budget. -5. **Choose shipping models**: R17 for WASM (about 0.2–0.3 s per decision single-threaded), and R32 for WebGPU - only if it is clearly more accurate. Device-based model selection in the host card. -6. **Demo evaluation with the trained model**: bug rate Off / Guard / Heal and false interventions on clean runs - for all six demos. Investigate: - - **hold-induced harm:** with v0.1, the board demo had 9 bugs introduced in guard mode with no interventions, - and search clean-run latency rose from 14 ms to 125 ms because salient writes were held; - - **triage sensitivity on naturally concurrent apps:** typeahead was salient about 6 times per trial on - clean runs. -7. **Docs**: READMEs and ARCHITECTURE.md are written; still to do: fill in honest results (install, two-line init, modes, what it detects, observability, performance, - honest results), ARCHITECTURE.md, model card, and dev-only lazy import of the devtools (52 KB min / 17 KB gz). -8. **Packaging**: publish the trained model as `@genclass/runtime-model@0.1.0` (the runtime's default CDN URL) - and attach it to a GitHub release, then publish `@genclass/runtime@0.1.0` without the alpha tag; - CI workflow (build, typecheck, unit tests); `npm pack` smoke test in a fresh Vite app. +3. **Check the v2 data before training on it** (from the review findings): SIM samples budget 3,200 for ~40% of + trajectories (`sim/src/world/scenario.ts` → `budget`), above the v2 device budgets; unlabeled rows hard-label + `expected` diagnoses that S1 would relabel (`sim/src/gen/trajectory.ts` → `unlabeledTrajectory`; a relabel pass + can drop them); REAL manifests hardcode `situation-v1` (`realapps/src/harness/gen.ts` → `manifest`). Decide + with Mehar whether to filter, relabel or regenerate. +4. **150M teacher on v2 gold** (SIM + REAL). +5. **Teacher labels on the unlabeled rows** (`training/label_cluster.sh`, `training/label_teacher.py`). Before + running: the script cannot read `.jsonl.gz` shards, marks itself done unconditionally, has no train-split + filter and no gather step. +6. **Distil R17 (default) and R32**, then the T1 expected-advantage target on v2 (the v1 T1 runs were stopped at + the freeze; `training/LOG.md`). `training/launch_student.sh` fails when INIT is omitted. +7. **DAgger** via SIM `--on-policy` (on-policy runs use heal mode, while the default is observe and the precision + target is guard). +8. **EVAL** (`training/EVAL.md`): guard/heal precision, false-intervention rate and regret per trigger and per + budget; calibration fit on dev, checked on held-out test; parity. `training/final_post.sh` and + `training/eval_sim.sh` are hard-wired to the v1 eval set (`simAe`), and `training/eval_runtime.py` caches logits + by name only: fix before evaluating a v2 model. The real-app eval set (`realapps/scripts/evalset.py`) draws + from the train split by default and ignores the `delivery` trigger. Targets (RESULTS.md §1): guard FIR ≤ 0.1%, + heal FIR ≤ 0.5%, calibration error ≤ 0.02, diagnosis ≥ 95%, clear-case recall ≥ 80%. +9. **Model package** `@genclass/runtime-model@0.1.0` (the runtime's default CDN URL) plus a GitHub release. + Device-based model selection in the host card (R17 everywhere unless R32 is clearly better on WebGPU). +10. **Demo rerun with the trained model**: bug rate Off / Guard / Heal and false interventions on clean runs for + all six demos (RESULTS.md §5 is the v0.1 baseline). Investigate triage sensitivity on naturally concurrent apps + (v0.1: typeahead was salient about 6 times per trial on clean runs; v2 reports 0 model calls on clean + typeahead, RESULTS.md §4). The synthetic in-page driver records no user actions since `untrustedEvents` + defaults to false. +11. **Publish `@genclass/runtime@0.1.0`** without the alpha tag (2FA by the user), after `npm pack` smoke test; procedure in [RELEASE.md](RELEASE.md). +12. **CI**: done on `mvp-v2` (`.github/workflows/ci.yml`); lands on `runtime`/`main` with the merge. +13. **Docs**: + - `HANDOFF.md`, `realapps/README.md` and RESULTS.md say 66 apps; the tree has 91. + - `docs/runtime/CONTRACT.md` still describes the old substring redaction rule. + - Still open from before: model card; honest results in the READMEs. Devtools ships as the separate + `@genclass/runtime/devtools` entry; whether a dev-only lazy import is still needed is (unverified). +14. **Review fixes** (adversarial review of `mvp-v2`, 2026-10-08; most change runtime behaviour, so coordinate + with Mehar, and anything under `packages/runtime/src/situation/*` needs a new format tag): + - delivery: discard is a silent no-op on redux/zustand stores but is recorded as a drop + (`state/hub.ts` → `StoreHub.applyFilter`); a discard mark drops fresh writes of later ops chained from the + discarded one for 10 s and survives `pause()`/`setMode("observe")` (`runtime.ts` → `dropFilter`); observe + mode still holds deliveries up to 100 ms and its background delivery decisions are always dropped as stale + (`runDelivery`, `trigger`); a delivery `defer` can stall a WS/SSE channel for 20 s; held WS/SSE messages are + dispatched after `close()` (`observe/messages.ts` → `MessageGate.pump`); XHR listeners see + `currentTarget === null`; `holdWrites` flush/discard mismatch. + - situation: the F2 fact prints raw text of redacted fields (`situation/content.ts` → `contentFacts`); the + leaf-based default redactor no longer redacts numbers/arrays under secret-named containers (`util.ts` → + `isSensitivePath`); "nor the value when #X started" asserted without checking; every POST JSON response + counted as a create; HTTP 502 called "not processed". + - curriculum parity (`training/curriculum/rt.py`): extra "Recent … outcomes" fact on failure rows, last-N + timeline instead of relevance-first, no-op writes, F1 instead of F2 wording on long text, rounding, bracket + paths, missing ages. + - realapps: a crashed Chromium drains its worker's seed queue as instant failures; resume can duplicate rows; + unpinned dependencies; the README's runtime pinning does not reach the VM. ## Model quality: where it stands and why -- **Round 1** (situation-v1, 448k simulated rows, R17 9.6 MB): - - guard false-intervention rate 0.05%, heal 0.24%, calibration error 0.009, diagnosis 90.5%; - - but it acts on only 7.7% of clear stale/duplicate cases; - - R32 (3× the compute) is no better. -- **Separability analysis** (`sim/SEPARABILITY.md`): - - the ceiling is in the data: 62–82% of clear cases have a benign twin with identical visible facts; - - 24% of clear rows were mislabelled `expected`; - - labels were hindsight-certain about things a runtime cannot observe (the user's next action, how long an - outage lasts, whether a failed write committed). -- **Fixes in progress:** - - generic facts measured to separate the cases: F1 put-back-a-replaced-value, F2 overwrites newer typing, - F3 response changes nothing, F9 known-stale provenance, F6 refresh/save cadence; - - the labelling fix (S1); - - futures that re-draw unobservable latents, so labels become expected cost given what is observable (S2); - - an expected-advantage training target (T1). +- **Round 1** (situation-v1, 448k simulated rows, R17 9.6 MB): guard FIR 0.05%, heal 0.24%, calibration error + 0.009, diagnosis 90.5%; but it acts on only 7.7% of clear stale/duplicate cases; R32 (3× the compute) is no + better. +- **Why** (`sim/SEPARABILITY.md`): the ceiling is in the data. 62–82% of clear cases had a benign twin with + identical visible facts; 24% of clear rows were mislabelled `expected`; labels were hindsight-certain about + things a runtime cannot observe (the user's next action, outage length, whether a failed write committed). +- **Fixes, now in the v2 format and data:** facts F1–F9 and read-your-writes; S1 labelling; S2 futures. The + expected-advantage target (T1) is still to be trained on v2. +- **Round 2** (situation-v2): data generating; no result yet. ## Needs the user -- **Patch release `0.1.0-alpha.1`** (fixes a crash when app state contains `NaN`, found after alpha.0 was published): - publishing needs your 2FA approval; I'll prepare the tarball and the command. +- **2FA publishes:** patch release `0.1.0-alpha.1` (fixes a crash when app state contains `NaN`, ad24804, found + after alpha.0 was published), later `@genclass/runtime-model@0.1.0` and `@genclass/runtime@0.1.0`. Agents + prepare the tarball and the exact command per [RELEASE.md](RELEASE.md) (alpha.1: `npm publish + genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha`); nothing is packed yet. - **Public demo hosting** (GitHub Pages on this repo): OK to publish? -- **Merging `runtime` into `main`** when ready. +- **Merging into `main`**: `runtime` and/or `mvp-v2` when ready. +- **Default mode decision:** `mvp-v2` defaults to `observe` (f3636b2); HANDOFF.md and the published alpha + say `guard`. Pick one before 0.1.0. +- **Re-enable the Azure auto-shutdown schedules when the training push ends** (disabled with the user's OK at + 00:35 UTC; command in HANDOFF.md). Spend so far about $400 (RESULTS.md §7). ## Known risks - **Single-thread WASM speed**: hold budgets adapt and late revert covers slow decisions, but slow devices see more fail-open decisions. -- **Training-label noise**: costs come from a few sampled futures; benign request rows are the softest - (66% of passive-best request rows put ≥ 0.9 on passive). -- **Thin classes**: `conflict` and `transition` rows are thin until the batch-3 runtime facts land. +- **Training-label noise**: costs come from a few sampled futures; benign request rows are the softest (66% of + passive-best request rows put ≥ 0.9 on passive). +- **Data generated with known defects**: v2 SIM/REAL data is being produced by the runtime and harness that the + review findings above describe; fixing a runtime defect that changes situations or delivery behaviour means a + new format tag and regenerated data. +- **Never-worse claims are narrower than stated**: the interference sweep compares final visible text and server + content (not requests, stores, errors or input values), covers 66 of the 91 apps, never compares observe mode + against no runtime, and the determinism check reruns only the base run. Chaos runs: 3/198 changed. +- **Thin classes**: `conflict` and `transition` rows were thin on v1; unmeasured on v2. diff --git a/README.md b/README.md index 344b8a88..434de7cd 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # GenClass Runtime [![npm](https://img.shields.io/npm/v/@genclass/runtime/latest?label=%40genclass%2Fruntime)](https://www.npmjs.com/package/@genclass/runtime) +[![CI](https://github.com/daybot-solutions-inc/GenClass-lib/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml) [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) -**An AI runtime for self-healing web apps. Install one library. Find and prevent runtime failures automatically.** +**A runtime for web apps. It watches the app from the inside and uses a small local model to flag, and optionally +prevent, stale responses, races, duplicate requests, inconsistent state and failure storms.** ```bash npm install @genclass/runtime @@ -12,53 +14,121 @@ npm install @genclass/runtime ```ts import { GenClass } from "@genclass/runtime"; -GenClass.init(); +GenClass.init(); // observe mode by default: reports only; pass { mode: "guard" } to let it act ``` -GenClass Runtime runs inside your web app and keeps track of what it is doing: user actions, async operations, -network requests, state changes, errors, timing, causality and recent history. When something looks risky, a -small GenClass model running locally in the browser (WebGPU or WASM, cached) judges what is happening and what to -do. It reports what it saw, or prevents the failure with a minimal, reversible action. It has no hardcoded list of -bugs; the model infers from runtime context. +GenClass Runtime records what the app does: user actions, async operations and their causal chains, network +traffic (fetch, XHR, WebSocket, EventSource), store writes with per-field versions, errors and timing. It computes +generic facts about each write, request and response, and asks a small GenClass model only about salient situations. +The model runs in the browser (WebGPU or WASM, in a Web Worker). It answers two questions: what is happening, and +which available action is best. There is no list of known bugs in the code. -``` -[GenClass] Prevented a stale write: GET /api/search?q=rea (started 1.8 s ago) would have overwritten - search.results written 0.4 s ago by a newer GET /api/search?q=react. Dropped it. (stale, 0.97) -``` +> **Status: alpha. The runtime is built; its model is still in training.** +> +> - **Runtime:** works and is unit-tested (situation format `situation-v2`, tag `situation-v2`). +> - **Default mode** is `observe`. `guard` is opt-in; `heal` is experimental. +> - **No model is published for this format yet.** `@genclass/runtime-model` is not on npm, so a default +> `GenClass.init()` prints `[GenClass] Model unavailable (...); observing only.` and finds nothing. +> - **Round 1 models** (format `situation-v1`) exist but do not match this runtime. +> - **`@genclass/runtime@0.1.0-alpha.0` on npm** is the older v1 runtime. It defaults to guard, holds store writes, +> and has a `NaN` crash that has since been fixed. +> +> What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: +> start at [AGENTS.md](AGENTS.md). + +## How it works + +1. **Observe.** Fetch, XHR, WebSocket, EventSource, DOM events, errors, navigation, storage, long tasks and timers + are instrumented. Async work is linked into causal chains. Stores created through GenClass, or wrapped with its + Redux, Zustand, React or generic adapters, get per-field versions and write histories. +2. **Learn.** The runtime learns per-operation baselines (latency, failure rate, request rate) and which fields each + operation usually writes. It also learns cadences (polling, debounced saves) and relations that keep holding + (`total == sum(items[*].price × qty)`, `selectedId ∈ items[*].id`). +3. **Triage.** Cheap facts are computed for every write and request. Only salient situations reach the model: a + response landing over newer data, a repeated request, a failure streak, a broken relation, an error. +4. **Decide at the network boundary.** Responses and push messages are judged *before the app sees them*: + - `deliver` (passive); + - `discard` (deliver, but drop the writes it makes over newer data); + - `defer` (wait for related in-flight work). + + Store writes are never held or reordered by default. Salient writes that no delivery decision covered are + decided in the background, and can be reverted within 2 s under strict rules. +5. **Act by mode.** -> **Status: alpha.** [`@genclass/runtime@0.1.0-alpha.0`](https://www.npmjs.com/package/@genclass/runtime) is on -> npm. The runtime, model host, devtools and adapters are built and tested. The runtime-specialist model is still -> being trained and is not yet published, so for now the alpha observes and records but does not act yet. The -> demos will be evaluated with the trained model. See [OPEN_TASKS.md](OPEN_TASKS.md); contributors and agents continuing the work: [HANDOFF.md](HANDOFF.md). + | mode | behaviour | + |---|---| + | `observe` (default) | reports only | + | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability is ≥ 0.9 | + | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions (≥ 0.8) | + +6. **Explain.** + - Every detection and intervention is logged in plain English, with the exact situation text the model read. + - Reversible actions can be undone. + - `?genclass=off` installs nothing. + +Full guide (modes, triggers, adapters, observability, performance, privacy, known limitations): +**[packages/runtime/README.md](packages/runtime/README.md)**. API: [docs/runtime/API.md](docs/runtime/API.md). + +## Results so far + +All numbers are on held-out data, with each recall reported next to its false-intervention rate (FIR). Source: +[docs/runtime/RESULTS.md](docs/runtime/RESULTS.md). + +| what | result | +|---|---| +| Round 1 model, R17 (9.6 MB int8; **previous format** `situation-v1`), simulated apps | diagnosis 90.5%, action 81.9%, guard FIR 0.05%, heal FIR 0.24%, calibration error 0.009. Recall on clear stale/duplicate cases is only 7.7% (precise but timid). | +| Why round 1 was timid ([sim/SEPARABILITY.md](sim/SEPARABILITY.md)) | Many clear cases had benign twins with identical visible facts; 24% of clear rows were mislabelled `expected`; labels assumed knowledge a runtime cannot have. v2 adds measured facts and fixes the labels. | +| Round 2 (`situation-v2`, this runtime) | **in progress**: ~10M simulated gold rows, ~50M unlabeled rows for teacher labelling, ~0.5M rows from real apps in headless Chromium | +| Never make a correct app worse (always-passive model, heal vs observe, 66 real apps × 6 seeds) | 0/396 clean runs changed: final page text (inputs and alerts excluded) and server state. Request timing and store contents are not compared, nor is observe mode against no runtime. With chaos: 3/198 changed. | +| Same check on the v1 runtime (store-write holds) | 4/198 clean runs changed; the React/Redux RealWorld app never rendered its home feed | +| Demos | Baseline only, with the untrained GenClass 0.1 model: guard took 0 actions. Rerun when the v2 model exists. | ## What's in this repo | path | what | |---|---| -| [`packages/runtime`](packages/runtime) | `@genclass/runtime`, the library: observers, causality, stores, learned invariants and profiles, facts, triage, policy, actions, model host (Web Worker, ONNX Runtime on WebGPU/WASM), devtools overlay, React/Redux/Zustand adapters. [README](packages/runtime/README.md) · [API](docs/runtime/API.md) | -| [`sim`](sim) | Training-data simulator: thousands of random apps run on the real runtime in a deterministic virtual world, labelled by counterfactual outcomes | -| [`training`](training) | Curriculum, vocabulary pruning, multi-node CPU training on Azure, int8 ONNX export, evaluation | +| [`packages/runtime`](packages/runtime) | `@genclass/runtime`, the library. Observers, causality, stores and adapters, learned baselines/relations/profiles, facts, triage, policy gate, actions, model host (Web Worker, ONNX Runtime Web on WebGPU/WASM), devtools overlay. [README](packages/runtime/README.md) · [STATUS](packages/runtime/STATUS.md) | +| [`packages/runtime-model`](packages/runtime-model) | Model card for the not-yet-published `@genclass/runtime-model` | +| [`sim`](sim) | Training-data simulator: random apps run on the real runtime in a deterministic virtual world, labelled by counterfactual outcomes | +| [`realapps`](realapps) | About 90 real apps (written for the corpus, plus open-source ones) run with the real runtime in headless Chromium, labelled the same way; the never-worse sweep covered the first 66. [README](realapps/README.md) | +| [`training`](training) | Vocabulary pruning, curriculum (`curriculum/rt.py` mirrors the runtime's renderer), multi-node CPU training on Azure, int8 ONNX export, evaluation | | [`demos`](demos) | Six demo apps (typeahead, autosave, checkout, flaky dashboard, live kanban, real-time decisions) with a Service Worker chaos backend and Playwright trials | -| [`docs/runtime`](docs/runtime) | [Results & comparisons](docs/runtime/RESULTS.md) · [Architecture](docs/runtime/ARCHITECTURE.md) · [build contract](docs/runtime/CONTRACT.md) · [API](docs/runtime/API.md) | +| [`docs/runtime`](docs/runtime) | [Results](docs/runtime/RESULTS.md) · [Architecture](docs/runtime/ARCHITECTURE.md) · [Build contract](docs/runtime/CONTRACT.md) · [API](docs/runtime/API.md) | +| [`docs/agents`](docs/agents/README.md), [`AGENTS.md`](AGENTS.md) | Docs for AI coding agents: subsystem guides with code pointers (runtime, sim, [realapps](docs/agents/realapps.md), training, model I/O contract, demos) and the rules for working here | | `jev_local`, `extension`, `bench`, … | The GenClass model, Jev-compatible server, voice harness, Chrome extension and benchmarks this runtime builds on ([details](docs/GENCLASS.md)) | -## How it works +## Development + +Node ≥ 20. From the repo root: + +```bash +ONNXRUNTIME_NODE_INSTALL=skip npm ci # the root lockfile is committed; skip onnxruntime-node's CUDA download +npm run typecheck -w @genclass/runtime +npm run build -w @genclass/runtime +cd packages/runtime +NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts +NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # timing budgets, run alone +``` + +The same steps run in CI ([.github/workflows/ci.yml](.github/workflows/ci.yml), Node 22) on pushes to `main`, +`runtime`, `mvp` and `mvp-v2`, on pull requests, and on manual dispatch. + +Last full local run (2026-10-08): 336 tests passed and 14 skipped. The skips are model-parity tests, which need +`GENCLASS_MODEL_DIR`. The perf tests time a 5,000-item store and can fail under parallel load. + +Releasing: [RELEASE.md](RELEASE.md). + +Not covered by CI: + +- Playwright browser tests: `npm run test:browser` in `packages/runtime`. +- The npm tarball smoke test: `test/smoke/smoke.sh`. +- The sim, the real-app corpus, the demos' evaluation, and training. + +These are heavier or need Azure; see [AGENTS.md](AGENTS.md) before running them. -1. **Observe.** Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are instrumented, and async - operations are linked into causal chains. State registered through GenClass gets per-field versions. -2. **Learn.** It learns latency, error and rate baselines per operation, invariants that keep holding (such as - `total == sum(price·qty)`), and which fields each operation usually writes. -3. **Triage.** Generic facts are computed for every write and request. Only salient situations (concurrency, - repeats, failures, anomalies, broken relations, errors) are passed to the model. -4. **Decide.** The local model reads the situation and answers two typed questions: what is happening, and which - available action is best. -5. **Act carefully.** - - `observe` mode reports only. - - `guard` (the default) takes minimal, reversible actions (drop or defer a stale write, coalesce a duplicate, - back off) when the model is ≥ 90% sure. - - `heal` also retries, serves cached responses, and rolls back or resyncs inconsistent state. -6. **Explain.** Every detection and intervention is logged in plain English with its evidence, can be explained - and undone, and `?genclass=off` turns everything off. +**The training format is frozen** at tag `situation-v2`. Any change to `packages/runtime/src/situation/*` (or other +text the model reads) changes the model's input and means a new tag and regenerated data. See +[docs/agents/model-io-contract.md](docs/agents/model-io-contract.md). ## License diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 00000000..8fa206f6 --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,456 @@ +# Release procedure: `@genclass/runtime` and `@genclass/runtime-model` + +> **Scope:** publishing `@genclass/runtime` (`packages/runtime`) and the planned `@genclass/runtime-model` (`packages/runtime-model`) to npm, their git tags and GitHub releases, and the checks before and after each publish. +> **Read this when:** you are asked to cut a release, prepare a tarball for the user to publish, or package a trained model. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. + +## TL;DR + +- **Two releases, in this order.** + - **Part A (now, no model).** An optional `@genclass/runtime@0.1.0-alpha.1` from `mvp-v2`, published under dist-tag `alpha`. It ships the NaN fix (ad24804), the situation-v2 runtime (batch 4 fcd1e68, batch 5 6e5e86e), the `observe` default (f3636b2) and updated docs. + - **Part B (after a situation-v2 model exists).** First `@genclass/runtime-model@0.1.0` plus the GitHub release `runtime-model-v0.1.0`. Then a demos eval (Off / Observe / Guard). Last, `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. +- **Who runs what.** Agents prepare and check everything: worktree, install, typecheck, build, unit tests, `npm pack`, the exact commands. **Only the user publishes** (`npm publish` and `npm dist-tag` need their npm 2FA). The user also approves every `git push`, tag push and `gh release`. Agents must ask before Playwright and `smoke.sh`, model downloads, demos eval, and anything that touches training or Azure. Those runs belong to Mehar's setup (`HANDOFF.md`). +- **Registry today** (`npm view`, 2026-10-08): + - `@genclass/runtime` has versions `0.0.0-stage` and `0.1.0-alpha.0`, with `latest` = `0.1.0-alpha.0`. That build is situation-v1, defaults to `guard`, still has the NaN crash, and has no model. + - `@genclass/runtime-model` is **404**. + - The npm org `genclass` has two members: `meharpro` (owner) and `karanvir1729` (developer). Both have read-write access to `@genclass/runtime`. +- **The default model URL is pinned.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. Both 404 today. npm versions are immutable, so **whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently**. Validate before publishing. +- **Never publish the round-1 R17 (`situation-v1`) as `0.1.0`.** The loader does not check a situation version: `packages/runtime/src/model/loader.ts` checks only the card format `genclass-runtime-model/1`. A v1 model would therefore load into the v2 runtime without any error and decide on text it was never trained on. +- **npm 11 refuses to publish a prerelease without `--tag`.** npm 11.8.0 `lib/commands/publish.js` throws "You must specify a tag using --tag when publishing a prerelease version.", so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. A non-prerelease needs no tag: the first one (`0.1.0`) becomes `latest`, because prereleases are left out of npm's "higher version" check. + +## Files + +| path | role in a release | +|---|---| +| `packages/runtime/package.json` | `@genclass/runtime`, `version` `0.1.0-alpha.0` on `mvp-v2`. `files`: `dist`, `bin`, `README.md`, `LICENSE`. No `prepublishOnly`, no `publishConfig`, no publish script | +| `package-lock.json` (root) | committed (b435acb). Records the workspace versions, so a version bump changes it. CI's `npm ci` fails if it is out of sync | +| `packages/runtime/README.md` | the npm page. Packed into the tarball, so it must be correct **before** packing | +| `packages/runtime/LICENSE` | Apache-2.0. Packed | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (`fetch-model`, `info`) and used here to validate model directories. Mode 100755 | +| `packages/runtime/test/smoke/smoke.sh` | packs the tarball, installs it into a fresh Vite 8 app, builds it, and loads it in headless Chromium (Playwright 1.63.0) | +| `packages/runtime/test/model/helpers.ts` | `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`, gitignored). `FIXTURES_FROM_MODEL` switches the parity fixtures to the model directory's own `requests.json`, `pack_fixtures.json` and `torch_fixtures.json` | +| `packages/runtime-model/MODEL_CARD.md` | the only tracked file of the model package. It still describes round 1 (situation-v1) | +| `packages/runtime-model/files/` | gitignored (`.gitignore` line `packages/runtime-model/files/`). Holds the model directory to pack. **Does not exist in this checkout**. `training/LOG.md` says round 1 R17 sits in `files/r17/` on Mehar's Mac only | +| `training/final_post.sh`, `training/export_runtime.py`, `training/pull_on_train.sh`, `training/deliver_final.sh`, `training/ortweb/validate.mjs` | TRAIN's eval -> export -> delivery -> onnxruntime-web check chain (Part B, step B1) | +| `demos/scripts/vm-eval.sh`, `demos/e2e/eval.ts`, `demos/src/shared/{types,genclass}.ts` | demos eval (Part B, step B6) | +| `.gitignore` | ignores `*.tgz` and `.publish/`, so packed tarballs never get committed | + +## Concepts + +| term | meaning | +|---|---| +| dist-tag | npm label pointing at one version. `latest` is what `npm i @genclass/runtime` installs. `alpha` and `beta` are opt-in: `npm i @genclass/runtime@alpha` | +| prerelease | a version with a `-` suffix (`0.1.0-alpha.1`, `0.1.0-beta.0`). npm 11 requires `--tag` to publish one | +| release worktree | a clean `git worktree` of the commit being released. The main checkout may hold other agents' uncommitted edits (on 2026-10-08 it had the uncommitted DL-7 fix in `packages/runtime/src/state/hub.ts` plus a new `test/atoms.test.ts` test; it ships only if committed before A2), and `tsup` bundles whatever is on disk | +| model export | the directory `training/export_runtime.py` writes: `model.json` (card `genclass-runtime-model/1`, with `bytes` and `sha256`), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU, `needs: shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, plus the parity files `parity.json`, `requests.json`, `pack_fixtures.json` and `torch_fixtures.json`. The fp32 reference in `ref/` is left out of the delivered tar | +| `ortweb_report_q8.json` | written into the export by `training/ortweb/validate.mjs <dir> q8 <n>`. It holds onnxruntime-web (WASM in Node) and onnxruntime-node logits compared with PyTorch, per backend: `argmax_agree`, `argmax_total`, `max_abs_logit`, `est_ms_at_seq_tokens`, `error` | + +Step markers used below: **[agent]** is light and allowed locally. **[ask first]** needs the user's OK in chat. **[user only]** is run by the user with their npm 2FA, or by Mehar on his Azure setup. + +## Part A: `@genclass/runtime@0.1.0-alpha.1` (now, no model) + +### A0. Decisions for the user (before any work) + +1. **Publish alpha.1 at all?** It is optional (`OPEN_TASKS.md` "Needs the user" asks for it only for the NaN fix). Without a model it observes only. Nothing it decides can change an app. +2. **Dist-tag.** `--tag alpha` leaves `latest` on `0.1.0-alpha.0`. That build has the NaN crash, is situation-v1 and defaults to `guard`. To make plain `npm i @genclass/runtime` get the fix, the user can also move `latest` after the publish (step A7). +3. **Which commit and branch.** `mvp-v2` (b435acb plus the doc commits) is not pushed. Mehar's working branch is `origin/runtime` (74f17c0). The release commit and tag must reach `origin`, and the user picks the branch: push `mvp-v2`, or merge into `runtime` with Mehar. +4. **Known open issues.** The 2026-10-08 review found several issues; see [Drift and open issues](#drift-and-open-issues). None of them can change app behaviour in alpha.1, because no model exists and the default is `observe`. They go into the release notes, not the blocker list. Part B treats them as blockers. + +### A1. Fix what the tarball ships (docs) **[agent, edits owned by the docs task]** + +The npm README is packed, so these must be committed before packing: + +- `packages/runtime/README.md`: + - status line: `0.1.0-alpha.0` becomes `0.1.0-alpha.1`; + - "Modes" table: already says `observe` is the default (matches `packages/runtime/src/runtime.ts`: `o.mode ?? "observe"`); re-check only the status/version text; + - it mentions `npx genclass-runtime fetch-model`; confirm the "none for this runtime yet" caveat is still present before packing (`DEFAULT_FROM` 404s and no v2 model exists). +- Root `README.md`: re-check the status box and alpha version (the default-mode text already says `observe`). + +Check: + +```sh +grep -n "(default)\|alpha\|fetch-model" packages/runtime/README.md README.md +``` + +### A2. Clean release worktree **[agent]** + +```sh +cd /Users/karanvirkhanna/GenClass-lib # the main checkout +git status --short # note other agents' edits; they must not be in the release +git worktree add -b release/runtime-0.1.0-alpha.1 ../GenClass-lib-release mvp-v2 +cd ../GenClass-lib-release +git log --oneline -1 # the commit being released (must include A1) +git status --porcelain # must print nothing +``` + +### A3. Pre-flight checks **[agent]** (all in the release worktree; same steps as `.github/workflows/ci.yml`) + +```sh +npm ci --no-audit --no-fund # committed lockfile; on Linux prefix ONNXRUNTIME_NODE_INSTALL=skip as CI does +npm run typecheck -w @genclass/runtime # tsc -p tsconfig.json --noEmit over src/ +npm run build -w @genclass/runtime # tsup -> packages/runtime/dist (6 entries) +cd packages/runtime +NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts +NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 +npm pack --dry-run +``` + +Expected at b435acb, with no `.cache-model`: + +- the unit run reports "Test Files 40 passed | 1 skipped (41)" and "Tests 332 passed | 14 skipped (346)" at b435acb; if the release commit includes the `packages/runtime/src/state/hub.ts` DL-7 fix and its new `test/atoms.test.ts` test, expect "Tests 333 passed | 14 skipped (347)"; +- the perf run reports 4 passed; +- `npm pack --dry-run` lists 26 files: `LICENSE`, `README.md`, `bin/genclass-runtime.mjs`, `package.json` and 22 files under `dist/`. + +The 14 skips are model-parity tests that need a model directory. If counts differ, check for untracked `test/zz-*.test.ts` files from parallel agents; a fresh worktree has none. Node 25 prints an EBADENGINE warning for vitest 5, which is harmless. CI uses Node 22. + +### A4. Version bump **[agent]** + +```sh +cd ../GenClass-lib-release # repo root of the worktree +npm version 0.1.0-alpha.1 -w @genclass/runtime --no-git-tag-version +git diff --stat # expect packages/runtime/package.json and package-lock.json only +``` + +`npm version -w` updates both the workspace `package.json` and the root lockfile's `packages/runtime` entry. This was checked with npm 11.8.0 on a scratch monorepo. Nothing in `src/`, `dist/` or `bin/` embeds the version, so no rebuild is needed for the bump. Commit: + +```sh +git add packages/runtime/package.json package-lock.json +git commit -m "release: @genclass/runtime 0.1.0-alpha.1 + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +### A5. Pack, and smoke-test the exact tarball + +```sh +cd packages/runtime +bash test/smoke/smoke.sh # [ask first] Playwright + registry installs; prints "SMOKE OK: <path>/genclass-runtime-0.1.0-alpha.1.tgz" +# without the smoke test [agent]: +npm run build && npm pack # -> genclass-runtime-0.1.0-alpha.1.tgz in packages/runtime (gitignored *.tgz) +shasum -a 1 genclass-runtime-0.1.0-alpha.1.tgz # keep it; compare with dist.shasum after the publish +``` + +`smoke.sh` runs `npm run build` and `npm pack` itself, so the tarball it leaves behind is the one to publish. It needs Chromium for Playwright 1.63.0 (revision 1243) in the Playwright cache; this machine has `chromium-1243` and `chromium_headless_shell-1243` in `~/Library/Caches/ms-playwright`. It leaves a temp Vite app behind (`mktemp -d`). It asserts no page or console errors, a mounted `genclass-devtools` element, and `rt.history().length >= 3`. None of these depend on the mode (not re-run on `mvp-v2`). + +Optional **[agent, tell the user first: it is an `npm publish` invocation, but it uploads nothing]**: + +```sh +npm publish genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha --dry-run +``` + +### A6. Publish **[user only]** + +On a machine logged in to npm as `karanvir1729` or `meharpro` (`npm whoami`), from `packages/runtime` in the release worktree: + +```sh +npm whoami +npm publish genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha +``` + +npm asks for the 2FA code, or opens the browser; `--otp <code>` also works. Publishing the tarball file publishes exactly what was smoke-tested. Running `npm publish` without a file would pack again from whatever `dist/` holds. A version can never be republished, even after an unpublish. + +### A7. Optional: move `latest` **[user only, decision A0.2]** + +```sh +npm dist-tag add @genclass/runtime@0.1.0-alpha.1 latest +``` + +### A8. Verify **[agent]** + +```sh +npm view @genclass/runtime dist-tags # alpha: 0.1.0-alpha.1 (latest: alpha.0 or alpha.1 per A7) +npm view @genclass/runtime@0.1.0-alpha.1 version dist.shasum dist.fileCount # shasum = A5's; fileCount 26 +T=$(mktemp -d) && cd "$T" && npm init -y >/dev/null \ + && npm i --no-audit --no-fund @genclass/runtime@0.1.0-alpha.1 \ + && node -e "import('@genclass/runtime').then(m => console.log(Object.keys(m).length, m.DEFAULT_MODEL_BASE_URL))" \ + && npx genclass-runtime --help | head -3 +``` + +The import check works in Node: it was checked against the workspace build, which exports 30 names. The registry may take a minute to show the new version. + +### A9. Tag, push, GitHub release **[ask first for every push; `gh release` is the user's call]** + +These follow the `0.1.0-alpha.0` precedent: an annotated tag "@genclass/runtime 0.1.0-alpha.0 (npm)", and a GitHub pre-release with the `.tgz` as an asset. + +```sh +cd ../GenClass-lib-release # repo root of the worktree +git tag -a v0.1.0-alpha.1 -m "@genclass/runtime 0.1.0-alpha.1 (npm)" +git push origin release/runtime-0.1.0-alpha.1 # or the branch agreed in A0.3 +git push origin v0.1.0-alpha.1 +gh release create v0.1.0-alpha.1 packages/runtime/genclass-runtime-0.1.0-alpha.1.tgz \ + -R daybot-solutions-inc/GenClass-lib --verify-tag --prerelease \ + --title "@genclass/runtime 0.1.0-alpha.1" --notes-file <notes.md> +``` + +Release notes, compared with `0.1.0-alpha.0`: + +- NaN in app state no longer recurses forever (`test/nan.test.ts`); +- the default mode is `observe` (was `guard`; `guard` is opt-in and `heal` is experimental); +- decisions happen at the network boundary (`delivery` trigger), and store writes are not held by default (`policy.holdWrites`); +- EventSource is observed; +- synthetic DOM events are ignored unless `observe: { untrustedEvents: true }` is set; +- the situation format is v2; +- no model is published yet, so the runtime only observes; +- known issues: list the open review findings from [Drift](#drift-and-open-issues). + +Then bring the release commit back to `mvp-v2`: `git -C /Users/karanvirkhanna/GenClass-lib merge --ff-only release/runtime-0.1.0-alpha.1`. If other agents' uncommitted edits touch the same files, the merge refuses: commit or stash them first, with the user's say. Then remove the worktree: `git worktree remove ../GenClass-lib-release`. + +### A10. Bookkeeping **[agent]** + +Update every place that still lists `0.1.0-alpha.0` as latest or alpha.1 as pending: + +- `OPEN_TASKS.md`: move "Needs the user: Patch release `0.1.0-alpha.1`" to "Done"; +- `HANDOFF.md`: the "Current state" npm row; +- `AGENTS.md`: the npm line; +- `docs/agents/runtime/build-test-release.md`: "Publish history"; +- `docs/agents/status-and-known-issues.md`. + +Find them with `git grep -n "0.1.0-alpha" -- '*.md'`. + +## Part B: model package, then `@genclass/runtime@0.1.0` (after a situation-v2 model exists) + +Order from `HANDOFF.md` "How to continue": v2 data, then the teacher, then distillation (R17 default, R32), then DAgger via SIM `--on-policy`, then EVAL, then **`@genclass/runtime-model@0.1.0`**, then the demos rerun, then **`@genclass/runtime@0.1.0`**. Everything up to EVAL is TRAIN's work on Azure (Mehar). Nobody on our side touches it. + +### B0. Gates before packaging anything + +- **EVAL exists for a situation-v2 model.** It must be in `training/EVAL.md` and `docs/runtime/RESULTS.md`, with the false-intervention rate (guard and heal) next to every recall number (`HANDOFF.md` rule "Report honestly"). The default is R17 (`HANDOFF.md`, round-1 choice in `training/LOG.md`). Choosing R32 for WebGPU is a separate user decision (`OPEN_TASKS.md` item 9). +- **TRAIN's post-processing is v2-correct.** `training/final_post.sh` is hard-wired to the situation-v1 eval set `simAe`: it runs `eval_sim.sh simAe`, uses `--calibration out/cal/$M-simAe.json`, and uses `--data-rows data/simAe/dev.jsonl,...`. It also does not stop when an eval fails (`set -u` only). `training/eval_runtime.py` caches logits by checkpoint and data *name* only. Unless these are fixed (TRAIN/Mehar), the export's `calibration.json` can be fitted on v1 situations or on stale logits. Confirm which eval set and which checkpoint the calibration came from before trusting the export. +- **Version.** The card's `version` must be `0.1.0`, and the npm package version must be exactly `0.1.0`, because `DEFAULT_MODEL_BASE_URL` pins `@0.1.0`. Any other version also needs a code change in `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`, and therefore a runtime release. + +### B1. Get the export **[user only (Mehar) for the Azure side; ask first to copy it here: model download]** + +TRAIN's chain, from the scripts: + +1. On the model's rank-0 node, `bash training/final_post.sh <M> <NAME> <VER>` (header example: `final_post.sh r17-final1 genclass-runtime-r17 1.0.0-rc1`). For the v2 release, use `<NAME>` = `genclass-runtime-r17` and `<VER>` = `0.1.0`. The script: + - runs the SIM eval and fits the temperatures; + - runs `training/export_runtime.py --ckpt models/<M> --out out/export-<M> --name <NAME> --version <VER> --calibration ...`; + - touches `out/.post-done-<M>`; + - tars `out/export-<M>` without `ref/` into `~/xfer/export-<M>.tar` and serves it on port 8801. +2. On the `train` VM, `training/pull_on_train.sh <IP> <M> <ROUND> <SUB>` (or `training/deliver_final.sh <M> <NODE> <ROUND> <SUB>` from the Mac) does the following: + - unpacks the tar into `~/gcl/train-out/<ROUND>/<SUB>/`; + - checks every file's sha256 against `model.json`; + - runs `ortweb/validate.mjs <dir> q8 120`, which writes `ortweb_report_q8.json` there. + + Round 1 landed in `~/gcl/train-out/final1/{r17,r32}/`. The v2 round's directory name is not decided yet (unverified). +3. Copy it to the release machine as `<repo>/.cache-model/`. That path is gitignored, and it is the default `GENCLASS_MODEL_DIR` of the model tests. On Mehar's setup, `scripts/vm.sh get` copies from `~/gcl/<SLOT>/<REMOTE>`, so `scripts/vm.sh get train-out <ROUND>/<SUB> .cache-model` should work (unverified; it needs his hosts file and key). + +Expected contents, from `export_runtime.py`: + +- `model.json`; +- `genclass-runtime-r17-q8.onnx` and `genclass-runtime-r17-fp16.onnx`; +- `tokenizer.json`, `calibration.json`, `meta.json`; `meta.json`'s `name` is `genclass-runtime-r17-0.1.0`; +- `parity.json`, `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, `ortweb_report_q8.json`. + +### B2. Validate **[agent once the directory is here; ask first where marked]** + +```sh +cd /Users/karanvirkhanna/GenClass-lib # or the release worktree +node packages/runtime/bin/genclass-runtime.mjs info .cache-model +node -e "const c=require('./.cache-model/model.json'); console.log(c.format, c.name, c.version, Object.keys(c.variants))" +cd packages/runtime +GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run test/model +GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" +``` + +- **`info`** must exit 0: + - every listed file reads `sha256 ok`; + - `fp16*` is marked "needs a WebGPU feature"; + - there are no `WARNING` lines (the graph check is "any fp16 tensor -> needs: shader-f16"); + - the card prints `genclass-runtime-model/1`, name `genclass-runtime-r17`, version `0.1.0`, and variants `q8` and `fp16`. +- **Model unit tests.** Because the export contains `requests.json`, `pack_fixtures.json` and `torch_fixtures.json`, `FIXTURES_FROM_MODEL` is true. The packer, engine and calibration tests then compare the TypeScript packer and ONNX engine (onnxruntime-node CPU, and onnxruntime-web WASM in Node) with the export's own PyTorch fixtures and its `parity.json`. Without a model directory these tests skip (14 skips). With one, they should run. Which ones stay skipped, and whether the py-fixture cases tied to the v0.1 tokenizer still pass, has not been checked on any v2 export (unverified). Read failures before dismissing them. +- **`ortweb_report_q8.json`.** For every backend in `results`: `argmax_agree` equals `argmax_total`, and there is no `error`. Note `est_ms_at_seq_tokens`, the latency for the model card. Round 1 got 233/233 decisions on both runtimes (`training/LOG.md`). To re-run it here **[ask first; installs onnxruntime-node/web in `training/ortweb`]**: `cd training/ortweb && npm install && node validate.mjs ../../.cache-model q8 120`. +- **Browser model specs [ask first; Playwright]:** `GENCLASS_MODEL_DIR=$PWD/../../.cache-model npm run test:browser` in `packages/runtime`. Caveat (from the code, not run): `test/browser/model-helpers.ts` always loads the **v0.1** `requests50.json`, `pack_fixtures.json` and `torch_fixtures.json` from `test/fixtures/model/`. It has no `FIXTURES_FROM_MODEL` switch, so the parity part of the first `model.spec.ts` test ("loads over WASM ... matches PyTorch ...") is expected to fail on a v2 model. The other specs (fallbacks, preload modes, WebGPU probe, latency) are model-agnostic. To make that test meaningful, teach `model-helpers.ts` to use the export's fixtures. + +### B3. Package `@genclass/runtime-model@0.1.0` **[agent]** + +1. Fill `files/` with **only** the card's files, flat. `model.json` must sit directly in `files/`, because the runtime fetches `<baseUrl>model.json` (`packages/runtime/src/model/loader.ts`). Remove anything else, especially a leftover `files/r17/` (the situation-v1 round-1 model). + + ```sh + cd /Users/karanvirkhanna/GenClass-lib + rm -rf packages/runtime-model/files && mkdir -p packages/runtime-model/files + cp .cache-model/{model.json,tokenizer.json,calibration.json,meta.json,genclass-runtime-r17-q8.onnx,genclass-runtime-r17-fp16.onnx} packages/runtime-model/files/ + node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files + cp packages/runtime/LICENSE packages/runtime-model/LICENSE + ``` + +2. Create `packages/runtime-model/package.json`: + + ```json + { + "name": "@genclass/runtime-model", + "version": "0.1.0", + "description": "The GenClass runtime model for @genclass/runtime (situation-v2): q8 ONNX for WASM, fp16 ONNX for WebGPU, tokenizer and calibration. Loaded from jsDelivr as the runtime's default model.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/daybot-solutions-inc/GenClass-lib.git", + "directory": "packages/runtime-model" + }, + "homepage": "https://github.com/daybot-solutions-inc/GenClass-lib#readme", + "files": ["files/", "MODEL_CARD.md"] + } + ``` + + `files/` stays gitignored but **is packed**. Listing it in `files` overrides the ignore rule; this was checked with npm 11.8.0 on a scratch monorepo with the same `.gitignore` line, from the package directory and with `-w`. npm always adds `package.json`, `LICENSE` and any `README*`. With no README the npm page shows none, so optionally add a short `README.md` that links to `MODEL_CARD.md`. + +3. The new `package.json` makes `packages/runtime-model` a workspace (root `workspaces: ["packages/*"]`). Update and commit the lockfile, or CI's `npm ci` fails: + + ```sh + npm install --no-audit --no-fund # adds packages/runtime-model to package-lock.json + cd packages/runtime-model && npm pack --dry-run # expect LICENSE, MODEL_CARD.md, package.json + the 6 files/ entries + ``` + +4. Rewrite `packages/runtime-model/MODEL_CARD.md` for the v2 model. It still says "final round 1 on the frozen runtime (situation-v1)" and quotes round-1 numbers. Take the numbers from the v2 `training/EVAL.md`. Keep false-intervention rates next to recall. Give the sizes and latencies from `parity.json` and `ortweb_report_q8.json`. +5. Commit `packages/runtime-model/{package.json,LICENSE,MODEL_CARD.md}` and `package-lock.json` (never `files/`). The npm package size is about 23 MB for R17 (round-1 q8 9.58 MB plus fp16 13.57 MB). Whether jsDelivr's npm size limit matters for adding R32 too is unverified. `training/LOG.md` only notes that "R32 + R17 would exceed 60 MB". + +### B4. Publish the model **[user only]** + +```sh +cd packages/runtime-model +npm pack # genclass-runtime-model-0.1.0.tgz (gitignored) +shasum -a 1 genclass-runtime-model-0.1.0.tgz +npm publish genclass-runtime-model-0.1.0.tgz --access public +``` + +- `--access public` is required: scoped packages default to restricted. +- No `--tag` is needed: `0.1.0` is not a prerelease, and it becomes `latest`. +- `karanvir1729` has the developer role in the `genclass` org. Whether that role may *create* a new package in the scope is unverified. If npm refuses, `meharpro` (owner) publishes. +- **This publish is irreversible:** `0.1.0` can never be reused, and every runtime that uses the default URL loads it. + +### B5. GitHub release `runtime-model-v0.1.0` **[ask first; user's call]** + +`fetch-model` resolves each card file as `new URL(file, from)`. The assets must therefore be the same six files, flat, with exactly the card's names: + +```sh +git tag -a runtime-model-v0.1.0 -m "@genclass/runtime-model 0.1.0 (npm)" +git push origin runtime-model-v0.1.0 +gh release create runtime-model-v0.1.0 packages/runtime-model/files/* \ + -R daybot-solutions-inc/GenClass-lib --verify-tag --latest=false \ + --title "@genclass/runtime-model 0.1.0" --notes-file packages/runtime-model/MODEL_CARD.md +``` + +### B6. Verify the CDN and the release + +```sh +npm view @genclass/runtime-model dist-tags version dist.shasum dist.fileCount # [agent] shasum = B4's +curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ + | grep -i -E "^HTTP|access-control-allow-origin|content-type" # [agent] 200, CORS allowed +curl -fsS https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ + | diff - packages/runtime-model/files/model.json && echo "CDN card identical" # [agent] +# [ask first: model downloads] end-to-end bytes + sha256 from both sources, then the card check +node packages/runtime/bin/genclass-runtime.mjs fetch-model /tmp/gc-cdn --from https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/ +node packages/runtime/bin/genclass-runtime.mjs info /tmp/gc-cdn +node packages/runtime/bin/genclass-runtime.mjs fetch-model /tmp/gc-gh # default --from = DEFAULT_FROM (the GitHub release) +node packages/runtime/bin/genclass-runtime.mjs info /tmp/gc-gh +``` + +`fetch-model` checks bytes and sha256 against the remote card and writes a normalised `model.json`. `info` checks again and exits 1 on any mismatch. Use a scratch directory instead of `/tmp` when the agent's rules require it. + +### B7. Demos eval: Off / Observe / Guard **[ask first; runs on Mehar's VM; needs two code changes first]** + +What it answers: does the shipped default (`observe` with the model) or `guard` make the six demos worse than the baseline, and what does guard fix? The demos are honest evaluation: never tune them for a result (`HANDOFF.md`). + +Prerequisites (code changes, not done at b435acb): + +1. **`demos/src/server/data/cities.ts` is missing from git.** The root `.gitignore` rule `data/` ignores it. The search world, scenario and oracle import it, so a fresh clone cannot build the demos. Recreate it with the exports `searchCities(q)` and `TYPED_TARGETS` (see [docs/agents/demos.md](docs/agents/demos.md)), and add it with `git add -f` or narrow the ignore rule. +2. **An `observe` demo mode.** + - `GcMode` in `demos/src/shared/types.ts` is `"off" | "guard" | "heal"`. Today demo **Off** = `GenClass.init({ mode: "observe", model: false })` (`demos/src/shared/genclass.ts` -> `startGenClass`). + - Add `"observe"` to `GcMode` and `MODES`, `demos/e2e/eval.ts` -> `ALL_MODES`, and the `MODE_LABEL`/`MODE_HINT` records in `demos/src/site/demo-page.ts` and `demos/src/site/trials-panel.ts`; `tsc` flags any `Record<GcMode, ...>` you miss. + - `startGenClass` already passes any non-off mode through as `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`, so `observe` gets the model loaded. + - While there, fix the stale "guard (the default)" comment in `genclass.ts`. + +Run (from `demos/scripts/vm-eval.sh`'s header; arguments pass through to `e2e/eval.ts`): + +```sh +scripts/vm.sh run demos 'GENCLASS_MODEL_URL=cdn setsid nohup bash demos/scripts/vm-eval.sh --modes off,observe,guard --tag runtime-model-0.1.0 > ~/gcl/logs/demos-eval.log 2>&1 < /dev/null &' +``` + +- `GENCLASS_MODEL_URL=cdn` makes the pages load the runtime's default URL, which tests the published package itself. `GENCLASS_MODEL_FROM=https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` serves a local copy instead. +- The results go to `demos/results-runtime-model-0.1.0.{json,md}`. +- Gate for B8: on clean runs, Observe and Guard introduce no bugs that Off does not have. Report every fixed count with its false interventions. +- Record the result in `docs/runtime/RESULTS.md` §5 (it currently holds the v0.1-model baseline). + +### B8. `@genclass/runtime@0.1.0-beta.0` or `0.1.0` **[same steps as Part A]** + +Blockers to clear or explicitly accept with the user and Mehar first: + +- the high-severity review findings: the F2 redaction bypass, the redactor regression, and the redux/zustand discard no-op; +- the observe-mode delivery holds, which affect the default. + +All are listed in [Drift](#drift-and-open-issues). Fixes under `packages/runtime/src/situation/*` change the model's input. They mean a new frozen tag after `situation-v2` and regenerated data, so coordinate with Mehar (`HANDOFF.md` "The training format is frozen"). + +Then repeat A1–A10 with: + +- **README status:** the model is published; the "Modes" table says what observe, guard and heal do *with* the model. +- **Version:** + - `npm version 0.1.0-beta.0 -w @genclass/runtime --no-git-tag-version`, published with `--tag beta`; optionally `npm dist-tag add @genclass/runtime@0.1.0-beta.0 latest`; + - **or** `npm version 0.1.0 -w @genclass/runtime --no-git-tag-version`, published with **no** `--tag`. It becomes `latest`, because no non-prerelease version exists yet (npm 11.8.0 leaves prereleases out of its "higher version" check). +- **Smoke with the model [ask first]:** in a page built from the tarball, `GenClass.init()` (default `observe`) should reach `GenClass.runtime.status.state === "ready"`, with `status.model`/`status.version` from the CDN card and `status.variant` `q8` (WASM) or `fp16` (WebGPU). `smoke.sh` passes `model: false`, so this check needs a variant of it, or the demos. +- **Tag:** `v0.1.0-beta.0` or `v0.1.0`. Make it a GitHub pre-release only for the beta. +- **Bookkeeping:** `OPEN_TASKS.md` item 11 (and item 9 for the model) to "Done"; `HANDOFF.md` npm/model rows; `packages/runtime/README.md`, `docs/runtime/API.md` and `docs/runtime/CONTRACT.md` where they say no model is published. + +## Invariants and gotchas + +- **Publish only tarballs you checked.** Run `npm publish <file>.tgz`, not a bare `npm publish`. A bare publish packs again from the current `dist/`, and `tsup`'s `clean: true` means a failed build leaves a half-empty `dist/`. +- **Build from a clean tree.** The main checkout can hold other agents' uncommitted runtime edits; use the release worktree (A2). +- **Never commit `files/` or `*.tgz`.** Both are gitignored. The model package is reproducible only from the export, so keep the export directory (and its sha256s in `model.json`) on the train VM. +- **Lockfile.** A version bump or a new workspace changes `package-lock.json`. Commit it in the same commit, or CI's `npm ci` fails. +- **Dist-tags.** A prerelease without `--tag` is refused (npm 11). A non-prerelease that is not the highest non-prerelease is also refused without `--tag` ("Cannot implicitly apply the \"latest\" tag ..."). `npm dist-tag add` moves a tag without republishing. +- **The default model URL is a contract.** `DEFAULT_MODEL_BASE_URL` (`@0.1.0/files/`) and `DEFAULT_FROM` (`runtime-model-v0.1.0`) are pinned in code. Changing either means a runtime release. +- **2FA and accounts.** Agents never run `npm login`, handle tokens, or publish. Hand the user the exact command. +- **Run policy.** On machines other than Mehar's 8 GB Mac, `npm ci`, `tsc`, `tsup`, vitest and `npm pack` are fine. The `HANDOFF.md` rule "never run npm/tsc/vitest on the Mac" is about his machine. Ask first before Playwright, `smoke.sh`, model downloads, the demos eval, training, realapps, Azure, `git push`, `gh release` and `npm publish`. + +## Tests + +| step | what proves it | +|---|---| +| A3 | CI-equivalent run: 332 passed + 14 skipped (346) at b435acb, or 333 + 14 (347) with the DL-7 fix committed, then perf 4 passed; `npm pack --dry-run` lists 26 files | +| A5 | `smoke.sh` prints `SMOKE OK: <tgz>` | +| A8 | `dist-tags`, `dist.shasum` equal to the local tarball's sha1, a clean install that imports, `npx genclass-runtime --help` | +| B2 | `genclass-runtime info` exits 0; `vitest run test/model` with `GENCLASS_MODEL_DIR` (export fixtures); `ortweb_report_q8.json` with full argmax agreement | +| B6 | CDN card identical to the packed one; `fetch-model` from the CDN and from the GitHub release verifies every sha256 | +| B7 | demos eval Off / Observe / Guard, with no clean-run regressions | + +## Drift and open issues + +- **Stale release text elsewhere (as of b435acb):** + - `HANDOFF.md` gives the publish command without `--tag`, which fails for prereleases; + - `packages/runtime/README.md` mentions `fetch-model`, whose default source is 404; confirm the "none for this runtime yet" caveat is still present before packing; + - `MODEL_CARD.md` describes round 1. +- **Open review findings (2026-10-08) that matter for B8**, by `path` -> `symbol`: + - **high:** + - `packages/runtime/src/situation/content.ts` -> `contentFacts`: the F2 fact prints raw text of redacted fields through `stringDiff`; + - `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter`: a delivery discard is a no-op on redux/zustand stores but is recorded as a drop. + - **medium:** + - `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`: observe mode (the default) still holds deliveries up to 100 ms, and XHR listeners run outside dispatch; + - background delivery decisions are dropped as stale; + - discard marks catch later chained polls (`RuntimeImpl.dropFilter`); + - a delivery `defer` can stall a push channel for 20 s; + - held WS/SSE messages are delivered after `close()` (`packages/runtime/src/observe/messages.ts` -> `MessageGate.pump`). + - **low:** + - `packages/runtime/src/util.ts` -> `isSensitivePath`/`defaultRedact` no longer redacts numbers or arrays under secret-named containers; + - `packages/runtime/src/situation/evidence.ts` -> `NOT_PROCESSED` treats 502 as "not processed". + - **TRAIN-side (they affect the model's quality, not the packaging):** + - unlabeled rows keep `expected` diagnoses that S1 would relabel (`sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`, `training/label_teacher.py`); + - `training/label_cluster.sh` can report done without labelling anything; + - `training/final_post.sh` is tied to `simAe` (see B0); + - SIM still samples the v1 3,200-char budget (`sim/src/world/scenario.ts`); + - several `training/curriculum/rt.py` divergences from the frozen renderer. +- **Real-app claims.** The "0/396 changed" never-worse sweep (`docs/runtime/RESULTS.md` §4) compares only final visible text and server content. It covers 66 of the now 91 apps, and it never compares observe mode against no runtime. Quote it that way in release notes; see [docs/agents/realapps.md](docs/agents/realapps.md). +- **Unverified:** + - the v2 round's delivery directory name on the train VM; + - whether the `genclass` developer role can create `@genclass/runtime-model`; + - jsDelivr's size limit for a larger model package; + - which model tests skip with a v2 export; + - `smoke.sh` on `mvp-v2`. + +## Related docs + +- [docs/agents/runtime/build-test-release.md](docs/agents/runtime/build-test-release.md): build, tests, CI, publish history. +- [docs/agents/runtime/model-host.md](docs/agents/runtime/model-host.md): the model card, loader, CLI and default URL. +- [docs/agents/model-io-contract.md](docs/agents/model-io-contract.md): what a model must accept to match the runtime. +- [docs/agents/training.md](docs/agents/training.md): TRAIN's eval and export chain. +- [docs/agents/demos.md](docs/agents/demos.md): the demos eval, `cities.ts`, demo modes. +- [docs/agents/realapps.md](docs/agents/realapps.md): the real-app corpus and the never-worse sweep. +- [docs/agents/playbooks.md](docs/agents/playbooks.md): recipes 19 and 20. +- [HANDOFF.md](HANDOFF.md), [OPEN_TASKS.md](OPEN_TASKS.md), [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md), [packages/runtime/STATUS.md](packages/runtime/STATUS.md), [packages/runtime-model/MODEL_CARD.md](packages/runtime-model/MODEL_CARD.md). diff --git a/docs/agents/README.md b/docs/agents/README.md index 44015fdb..cb4adc8d 100644 --- a/docs/agents/README.md +++ b/docs/agents/README.md @@ -2,28 +2,32 @@ > **Scope:** every doc in `docs/agents/`, the root entry points `AGENTS.md` and `CLAUDE.md`, and how these docs relate to the human docs in `docs/runtime/`. > **Read this when:** you need the right doc for a task, want to know what a doc covers, or must update the docs after changing code. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## Purpose and reading order -These docs are for AI coding agents that arrive in this repo with no context. Each subsystem doc describes one area as the code stands at a stated commit, with `file -> symbol` pointers so you can go straight to the source. They are not product documentation. For that, see `README.md`, `packages/runtime/README.md` and `docs/runtime/*.md`. +These docs are for AI coding agents that arrive in this repo with no context. Each subsystem doc describes one area as the code stands at a stated commit, with `file -> symbol` pointers so you can go straight to the source. They are not product documentation. For that, see `README.md`, `packages/runtime/README.md` and `docs/runtime/*.md` (several of which are stale; see the Drift sections). Read them in this order: 1. [`../../AGENTS.md`](../../AGENTS.md): ground rules, what you may run locally, and what needs the user's OK first. -2. [overview.md](overview.md): what the product is and how runtime, sim, training, model and demos fit together. +2. [overview.md](overview.md): what the product is and how runtime, sim, realapps, training, model and demos fit together. 3. The subsystem doc for your task (see the [routing table](#routing-table)). Read its TL;DR first, then "Invariants and gotchas" and "How to change it safely" before you edit anything. 4. [playbooks.md](playbooks.md): procedures for tasks that span several subsystems. Keep three docs open for reference: [repo-map.md](repo-map.md) (where things live), [glossary.md](glossary.md) (terms) and [status-and-known-issues.md](status-and-known-issues.md) (what is shipped, frozen, open and stale). -Three facts change how you should read every other doc: +For live state and results, also use the human sources [HANDOFF.md](../../HANDOFF.md) (the colleague's current state and next steps), [docs/runtime/RESULTS.md](../runtime/RESULTS.md) (measured results and training log) and [RELEASE.md](../../RELEASE.md) (release procedure). -- **The situation format is frozen** at tag `situation-v1` (1a77558). `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Any change to text the model reads needs the user's go-ahead (ask the user; the workstream roles belonged to the original team), regenerated sim data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). -- **The published alpha only observes.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which has not been published (OPEN_TASKS item 8; the CDN was not checked live). A default `GenClass.init()` ends in model status `error` and never acts. See [runtime/model-host.md](runtime/model-host.md). -- **The subsystem docs still state the original run rule:** everything on the Azure VM via `scripts/vm.sh`, never locally (CONTRACT §0 rule 5, written for an 8 GB Mac). The current policy for agents is in `AGENTS.md`: - - You may run `npm install`, typecheck, the tsup build and the vitest unit tests locally. The lead checked all four on 2026-10-07. - - Ask the user before you run the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). +Five facts change how you should read every other doc: + +- **The situation format is frozen at tag `situation-v2`** (6e5e86e, runtime batch 5). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts` (the default mode), `types.ts` (its JSDoc) and `devtools/index.ts` (mode labels); no model-visible code changed. The old tag `situation-v1` (1a77558) is the format of all data and models trained so far, so **no trained model matches the current runtime**. Any change to text the model reads needs the user's go-ahead (coordinate with the colleague who runs SIM/REAL/TRAIN), a new tag, regenerated SIM and realapps data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). +- **Decisions happen at the network boundary.** situation-v2 adds the `delivery` trigger (a fetch/XHR response or a WebSocket/EventSource message about to reach the app; actions `deliver` / `discard` / `defer`) and no longer holds store writes by default (`policy.holdWrites: false`). Older docs and the human docs often still describe held store writes. See [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md). +- **The default mode is `observe`** on `mvp-v2` (our commit f3636b2: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`). `guard` is opt-in and `heal` experimental. The published `@genclass/runtime@0.1.0-alpha.0` (situation-v1 code) still defaults to `guard`, and so does `HANDOFF.md` (both READMEs now say `observe`). The unit-test harness (`packages/runtime/test/helpers.ts` -> `setup`) passes `mode: "guard"`. See [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). +- **No model is published, so every install only observes.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which is a 404 on npm, as is the CLI's `DEFAULT_FROM`. A default `GenClass.init()` ends in model status `error` and never decides. The situation-v2 model comes from the scaled program in [training.md](training.md) (teacher -> distillation -> DAgger -> EVAL -> export). See [runtime/model-host.md](runtime/model-host.md). +- **Run policy for agents** (set by the lead for this machine; `HANDOFF.md`'s "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac): + - You may run `npm install` / `npm ci`, typecheck, the tsup build and the vitest unit tests locally. All of them were run when these docs were written, on 2026-10-08 (350 tests: 336 passed, 14 model-parity skips). + - Ask the user before you run Playwright (including `test/smoke/smoke.sh`), the sim generator, training, anything in `realapps/` that launches Chromium or touches a VM, the demos' eval, model downloads, anything on Azure, `git push` or `npm publish`. The colleague is operating the Azure cluster right now (SIM on c02–c09 and c12–c23, REAL on c01, c10, c11); nobody on our side touches it. ## Routing table @@ -33,83 +37,95 @@ Each row names the doc to read, and then any further docs to check. "Ask first" | If your task is ... | Read | Then | |---|---|---| -| Learn what is shipped, frozen or in flight, and who owns what | [status-and-known-issues.md](status-and-known-issues.md) | [overview.md](overview.md) | +| Learn what is shipped, frozen or in flight, and who owns what | [status-and-known-issues.md](status-and-known-issues.md) | [overview.md](overview.md) ("Where the project stands") | | Find where a file, package or script lives | [repo-map.md](repo-map.md) | the "Files" table of the subsystem doc | -| Look up a term (situation, trigger, tier, settled point, hold budget, FIR, R17/R32) | [glossary.md](glossary.md) | the doc's "Concepts and data structures" | -| Decide whether a change forces new sim data and retraining | [model-io-contract.md](model-io-contract.md) ("Versioning: what invalidates the trained model") | [status-and-known-issues.md](status-and-known-issues.md) ("Change anything the model reads") | -| Record status after a change (STATUS.md, NEEDS files, OPEN_TASKS.md) or file a cross-workstream request | [status-and-known-issues.md](status-and-known-issues.md) ("How to change it safely") | — | -| Handle a human doc (API.md, CONTRACT.md, a README, STATUS.md) that disagrees with the code | [status-and-known-issues.md](status-and-known-issues.md) ("Drift and open issues", "Fix doc drift") | the subsystem doc's "Drift and open issues" | +| Look up a term (situation, trigger, delivery, discard mark, tier, settled point, hold budget, FIR, S1/S2, R17/R32, T150) | [glossary.md](glossary.md) | the doc's "Concepts and data structures" | +| Decide whether a change forces new data and retraining | [model-io-contract.md](model-io-contract.md) ("Versioning: what invalidates the trained model") | [status-and-known-issues.md](status-and-known-issues.md) | +| Record status after a change (STATUS.md, NEEDS files, OPEN_TASKS.md, HANDOFF.md) or file a cross-workstream request | [status-and-known-issues.md](status-and-known-issues.md) ("How to change it safely") | — | +| Handle a human doc (API.md, CONTRACT.md, a README, STATUS.md, OPEN_TASKS.md) that disagrees with the code | [status-and-known-issues.md](status-and-known-issues.md) ("Drift and open issues") | the subsystem doc's "Drift and open issues" | ### Runtime: public API, observers, state | If your task is ... | Read | Then | |---|---|---| -| Add or change an init/`createRuntime` option or a default (mode, thresholds, `settleMs`, `historySize`) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [sim.md](sim.md) (`sim/src/run/rt.ts` -> `createOptions`) if it reaches situations or decisions | +| Add or change an init/`createRuntime` option or a default (mode, `holdWrites`, thresholds, `settleMs`, `historySize`) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [sim.md](sim.md) (`sim/src/run/rt.ts` -> `createOptions`) and [realapps.md](realapps.md) (`realapps/src/world/index.ts`) if it reaches situations or decisions | +| Understand or change the default mode (`observe` since f3636b2) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/devtools.md](runtime/devtools.md) (mode labels), [runtime/build-test-release.md](runtime/build-test-release.md) (`setup()` passes `guard`) | | Add a `Runtime` method or event | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/devtools.md](runtime/devtools.md) (`MockRuntime`), [demos.md](demos.md) (runtime shim) | | Change `GenClass.init`, the kill switch or `destroy()` | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (how globals are restored) | | Write a plugin, custom action or standing question | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (plugin API) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [model-io-contract.md](model-io-contract.md) (no retrain; quality unmeasured) | | Add code that depends on time (timers, timestamps, ids) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`Clock` rules) | [runtime/build-test-release.md](runtime/build-test-release.md) (`FakeClock` tests) | -| Add an observer (`EventSource`, `BroadcastChannel`, ...) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) if you add an `OpKind` | +| Add an observer, or change the WebSocket/EventSource observers or the message gate (`observe/messages.ts` -> `MessageGate`) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) if you add an `OpKind` | | Debug how fetch/XHR requests are held, coalesced, retried, hedged or served from cache | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Change where fetch/XHR/WS/SSE hand a response or message to the delivery gate, or how the body clone is read | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) ("The delivery gate") | | Change op signatures, request identity or volatile headers | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [model-io-contract.md](model-io-contract.md) (op names reach the model) | | Carry the ambient op across a new async boundary | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (`LazyOp` timer pattern) | — | -| Change DOM user-action recording or `data-genclass-ignore` | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/devtools.md](runtime/devtools.md) | +| Change DOM user-action recording, `observe.untrustedEvents` or `data-genclass-ignore` | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | [runtime/devtools.md](runtime/devtools.md), [demos.md](demos.md) (the in-page driver uses synthetic events) | | Integrate another state library through `runtime.adapter` | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (subpath export) | | Change the React hooks, Redux enhancer or Zustand middleware | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [demos.md](demos.md) (a demo exercises each adapter) | -| Debug why a write was held, applied, dropped or not reverted | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (hold budget, late revert) | +| Debug why a write was applied, dropped by a discard mark, late-reverted or (with `holdWrites`) held | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (late revert, delivery `discard`) | | Add or tune an invariant template; debug a missing or spurious `inconsistency` trigger | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | -| Fix held writes landing after a newer user write (`demos/NEEDS.md` §1) | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | [status-and-known-issues.md](status-and-known-issues.md), [demos.md](demos.md) | +| Check the old "held write lands after a newer user write" bug (`demos/NEEDS.md` §1) | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) (addressed in code, unmeasured on the demos) | [demos.md](demos.md) | ### Runtime: situation, decisions, model host, devtools | If your task is ... | Read | Then | |---|---|---| -| Find out why a trigger did or did not reach the model (triage) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | -| Change fact wording or timeline/state/stats lines, or add a fact | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md) | +| Find out why a trigger did or did not reach the model (triage, delivery pre-filter) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Debug why a response or message was held, delivered at once, discarded or deferred | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) ("Delivery gate") | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) (salience), [runtime/state-and-adapters.md](runtime/state-and-adapters.md) (drop filter) | +| Change the delivery gate (predicted writes, conflicts, body read, discard marks, `defer`) | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [model-io-contract.md](model-io-contract.md) (salience decides which rows exist) | +| Change fact wording (incl. F1–F9, read-your-writes) or timeline/state/stats lines, or add a fact | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md) | | Change the situation budget or section limits | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [model-io-contract.md](model-io-contract.md), [training.md](training.md) (`rt.py` must match) | -| Change redaction (`isSensitiveName`), latency/error baselines or transition profiles | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`util.ts` helpers) | -| Add a trigger kind | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`Controller`), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md) | -| Change the policy gate, thresholds, hold budget or rate limit | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [training.md](training.md) (`eval_runtime.py` mirrors the gate) | +| Change redaction (`isSensitiveName`, `isSensitivePath`), latency/error baselines, cadence or transition profiles | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`util.ts` helpers) | +| Add a trigger kind | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`Controller`), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [realapps.md](realapps.md) | +| Change the policy gate, thresholds, hold budget, `expectedLatency` or rate limit | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [training.md](training.md) (`eval_runtime.py` mirrors the gate) | | Change a built-in action's mechanics or its `changed` sentence | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (request/failure/stall controllers) | -| Add a built-in action or a diagnosis label | [model-io-contract.md](model-io-contract.md) ("Recipes") | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [sim.md](sim.md), [training.md](training.md) | +| Add a built-in action or a diagnosis label | [model-io-contract.md](model-io-contract.md) ("Recipes") | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md) | | Change console report wording, `explain()` or undo | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/devtools.md](runtime/devtools.md) (the overlay mirrors report templates) | -| Change the decider queue (priorities, deadlines, timeout, answer cache) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/model-host.md](runtime/model-host.md) | +| Change the decider queue (priorities, deadlines, stale drop, timeout, answer cache) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | [runtime/model-host.md](runtime/model-host.md) | | Debug "Model unavailable (...); observing only.", a stuck load or slow decisions | [runtime/model-host.md](runtime/model-host.md) | [status-and-known-issues.md](status-and-known-issues.md) | -| Point at a published model, bump the model version, or self-host model files (`genclass-runtime fetch-model`) | [runtime/model-host.md](runtime/model-host.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (publishing the model package) | +| Point at a model, bump the model version, or self-host model files (`genclass-runtime fetch-model`) | [runtime/model-host.md](runtime/model-host.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (publishing the model package) | | Change WebGPU/WASM plan order, the worker protocol, a model error class or the onnxruntime-web version | [runtime/model-host.md](runtime/model-host.md) | [runtime/build-test-release.md](runtime/build-test-release.md) (externals, browser specs) | | Change the TS serializer, tokenizer, packer or calibration | [model-io-contract.md](model-io-contract.md) | [runtime/model-host.md](runtime/model-host.md), [genclass-model-lineage.md](genclass-model-lineage.md) (Python side), [runtime/build-test-release.md](runtime/build-test-release.md) (fixtures) | | Mount the devtools overlay, or change a view, option, card, theme or keyboard handling | [runtime/devtools.md](runtime/devtools.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (events it subscribes to) | | Update the overlay's Playwright spec or its screenshots (ask first) | [runtime/devtools.md](runtime/devtools.md) | [runtime/build-test-release.md](runtime/build-test-release.md) | -| Investigate a false intervention or unexpected behaviour reported by a user | [playbooks.md](playbooks.md#25-investigate-a-false-intervention-reported-by-a-user) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Investigate a false intervention or unexpected behaviour reported by a user | [playbooks.md](playbooks.md) (recipe "Investigate a false intervention reported by a user") | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | -### Build, test and release +### Build, test, CI and release | If your task is ... | Read | Then | |---|---|---| -| Build, typecheck or run the unit tests | [runtime/build-test-release.md](runtime/build-test-release.md) | [`../../AGENTS.md`](../../AGENTS.md) (what may run locally) | -| Write a unit test in house style (`setup()`, `FakeClock`, `ManualDecider`) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`defaultScript`) | +| Build, typecheck or run the unit tests (`npm ci` works from the committed lockfile) | [runtime/build-test-release.md](runtime/build-test-release.md) | [`../../AGENTS.md`](../../AGENTS.md) (what may run locally) | +| Write a unit test in house style (`setup()` defaults to `guard`, `FakeClock`, `ManualDecider`, `holdWrites: true` for held writes) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) (`defaultScript`) | +| Change the CI workflow (`.github/workflows/ci.yml`: Node 22, `npm ci`, typecheck, build, unit tests, `review-perf` alone with retries) | [runtime/build-test-release.md](runtime/build-test-release.md) ("CI") | — | | Add a public entry point (subpath export) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | | Run the Playwright specs or the npm-pack smoke test (ask first) | [runtime/build-test-release.md](runtime/build-test-release.md) | — | -| Cut a release, publish `@genclass/runtime-model`, or add CI (there is no `.github/`) | [runtime/build-test-release.md](runtime/build-test-release.md) | [playbooks.md](playbooks.md#19-publish-genclassruntime) recipes 19–21, [status-and-known-issues.md](status-and-known-issues.md) | +| Prepare the `0.1.0-alpha.1` patch (NaN fix; the user publishes with 2FA, and npm 11 needs `--tag` for a prerelease) | [../../RELEASE.md](../../RELEASE.md) (Part A); [runtime/build-test-release.md](runtime/build-test-release.md) ("Cut a release") | [status-and-known-issues.md](status-and-known-issues.md), [playbooks.md](playbooks.md) ("Publish @genclass/runtime") | +| Publish `@genclass/runtime-model@0.1.0`, then `@genclass/runtime@0.1.0` (only after a situation-v2 model passes EVAL) | [../../RELEASE.md](../../RELEASE.md) (Part B); [runtime/build-test-release.md](runtime/build-test-release.md) ("Publish the model package") | [training.md](training.md) (export), [runtime/model-host.md](runtime/model-host.md) (card format), [playbooks.md](playbooks.md) | -### Sim, training and demos +### Sim, realapps, the v2 training program and demos | If your task is ... | Read | Then | |---|---|---| -| Generate or regenerate training data (ask first) | [sim.md](sim.md) | [model-io-contract.md](model-io-contract.md) | +| Generate or regenerate SIM data: gold, `--unlabeled` or `--on-policy` rows (ask first) | [sim.md](sim.md) | [model-io-contract.md](model-io-contract.md) | | Add a feature combinator, domain, chaos behaviour or ask-question generator | [sim.md](sim.md) | — | -| Change cost weights or label parameters | [sim.md](sim.md) | [model-io-contract.md](model-io-contract.md) (how the sim labels rows) | -| Debug a dropped trajectory, a `prefix-mismatch` or an odd label | [sim.md](sim.md) | — | +| Change cost weights, label parameters, S1 relabelling or S2 latent re-draws | [sim.md](sim.md) | [realapps.md](realapps.md) (imports the sim's weights and label rule), [model-io-contract.md](model-io-contract.md) | +| Debug a dropped trajectory, a `prefix-mismatch` or an odd label | [sim.md](sim.md) or [realapps.md](realapps.md) | — | | Change the runtime options the sim passes (`createOptions`) | [sim.md](sim.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | -| Mirror a runtime wording change into `training/curriculum/rt.py` | [training.md](training.md) | [model-io-contract.md](model-io-contract.md) | +| Understand what a REAL row (`meta.source = "realapps"`) is and how it was labelled | [realapps.md](realapps.md) | [model-io-contract.md](model-io-contract.md) | +| Add an app to the real-app corpus, or change the in-page world, probe or harness | [realapps.md](realapps.md) | [sim.md](sim.md) (shared cost and label code) | +| Run the never-worse (`debug.js --interference`) or determinism sweep (Chromium; ask first) | [realapps.md](realapps.md) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| Generate real-browser data or build the real-app eval set (`realapps/scripts/evalset.py`; Chromium/Azure, ask first) | [realapps.md](realapps.md) | [training.md](training.md) | +| Mirror a runtime wording change into `training/curriculum/rt.py` (frozen at `situation-v2`) | [training.md](training.md) | [model-io-contract.md](model-io-contract.md) | | Regenerate the curriculum, change a mixture or launch a training round (Azure; ask first) | [training.md](training.md) | [genclass-model-lineage.md](genclass-model-lineage.md) (the `jev_local` trainer) | +| Run the v2 program: T150 teacher, soft-labelling (`label_teacher.py`, `label_cluster.sh`), student distillation (`launch_student.sh`), DAgger (Azure; ask first) | [training.md](training.md) ("Teacher, soft-labelling and distillation") | [sim.md](sim.md) (unlabeled and on-policy rows), [realapps.md](realapps.md) | +| Work on the T1 expected-gain side track (`t1_relabel.py`, `eval_gain.py`) | [training.md](training.md) | [sim.md](sim.md) (`meta.cost_futures`) | | Evaluate a checkpoint, fit calibration or read EVAL.md numbers | [training.md](training.md) | [model-io-contract.md](model-io-contract.md) ("Re-calibrate only") | | Export and validate a model directory; choose between R17 and R32 | [training.md](training.md) | [runtime/model-host.md](runtime/model-host.md) (card format), [status-and-known-issues.md](status-and-known-issues.md) | | Change the tokenizer vocabulary | [training.md](training.md) | [genclass-model-lineage.md](genclass-model-lineage.md) | | Build the demos from a fresh clone (`demos/src/server/data/cities.ts` is missing) | [demos.md](demos.md) | — | | Add a demo, or change a scenario, oracle, chaos knob or mock route | [demos.md](demos.md) | — | | Use a new runtime API from the demos (runtime shim) | [demos.md](demos.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | -| Evaluate a model in the demos (`demos/scripts/vm-eval.sh`; ask first) | [demos.md](demos.md) | [runtime/model-host.md](runtime/model-host.md) | +| Evaluate a model in the demos (`demos/scripts/vm-eval.sh`; ask first; planned after the v2 model) | [demos.md](demos.md) | [runtime/model-host.md](runtime/model-host.md) | | Investigate a regression caused by holds (`e2e/eval.ts --trace`) | [demos.md](demos.md) | [runtime/state-and-adapters.md](runtime/state-and-adapters.md), [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | ### Legacy GenClass, extension and benchmarks @@ -125,52 +141,53 @@ Each row names the doc to read, and then any further docs to check. "Ask first" ## Catalogue -Line counts were taken with `wc -l` and are approximate. +Line counts were taken with `wc -l docs/agents/*.md docs/agents/runtime/*.md AGENTS.md CLAUDE.md` on 2026-10-08 while the set was being refreshed for situation-v2; treat them as approximate. | Path | Scope | Read when | Lines | |---|---|---|---| | [`../../AGENTS.md`](../../AGENTS.md) | Entry point: what the repo is, status, ground rules, where to run things, commands, conventions, definition of done | First, always | ~190 | | [`../../CLAUDE.md`](../../CLAUDE.md) | Claude Code entry point: one-line repo summary that imports `AGENTS.md` (`@AGENTS.md`) | Loaded for you by Claude Code | 3 | -| [README.md](README.md) | This index: routing, catalogue, conventions, maintenance | Finding a doc; updating docs | ~185 | -| [overview.md](overview.md) | The mental model: component map, runtime data flow, offline loops (sim -> training -> model), modes, fail-open behaviour | Second, after AGENTS.md | ~415 | +| [README.md](README.md) | This index: routing, catalogue, conventions, maintenance | Finding a doc; updating docs | ~200 | +| [overview.md](overview.md) | The mental model: component map, runtime data flow with the delivery gate, a v2 walkthrough, offline loops (sim + realapps -> teacher -> distillation -> DAgger -> export), modes, fail-open behaviour, where the project stands | Second, after AGENTS.md | ~500 | | [repo-map.md](repo-map.md) | Every tracked path, plus generated and ignored paths in a working copy | Finding where a file, symbol, constant, CLI command, env var or config key lives | ~855 | | [glossary.md](glossary.md) | Terms used across the docs | When a term is unclear | ~445 | | [playbooks.md](playbooks.md) | End-to-end procedures across subsystems | Before a multi-subsystem change | ~775 | -| [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | `index.ts`, `runtime.ts` wiring, `types.ts`, errors, `Clock`, `util.ts`, `package.json` | Options, `Runtime` methods, events, plugins, init/destroy, kill switch | ~640 | -| [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | `observe/*`, `trace/*`, observer install/route code in `runtime.ts` | Patching fetch/XHR/WS/timers/DOM/history/Storage; ops, identity, causality | ~790 | -| [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | `state/*`, `adapters/*`, store code in `runtime.ts` | Holds, patches, reverts, snapshots, invariants, React/Redux/Zustand | ~650 | -| [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | `learn/*`, `situation/*`, triage in `runtime.ts` | Any model-visible text, triage, budgets, redaction, baselines | ~1050 | -| [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | `decide/*`, action controllers, `explain`, undo | Queue, policy gate, built-in actions, reports | ~720 | -| [runtime/model-host.md](runtime/model-host.md) | `model/*`, worker, CLI `bin/genclass-runtime.mjs`, `packages/runtime-model/` | Model loading, caching, WebGPU/WASM, packer, calibration, CLI | ~670 | -| [runtime/devtools.md](runtime/devtools.md) | `devtools/*`, `UI-NEEDS.md`, devtools tests and UI spec | The overlay, its views, theming, screenshots | ~710 | -| [runtime/build-test-release.md](runtime/build-test-release.md) | Workspace config, tsup/vitest/Playwright, fixtures, smoke, `scripts/vm.sh`, publishing | Build, test, fixtures, release, CI | ~550 | -| [model-io-contract.md](model-io-contract.md) | Situation text -> packed request -> heads -> calibrated answers, across runtime, sim and training | Any change the model can see; shipping a model directory | ~690 | -| [sim.md](sim.md) | `sim/**` | Training data generation, labels, splits, budgets | ~820 | -| [training.md](training.md) | `training/**` and the `jev_local` parts it calls | Curriculum, training rounds, eval, calibration, export | ~520 | -| [demos.md](demos.md) | `demos/**` | Demo apps, mock server, chaos, Playwright eval, results | ~540 | -| [genclass-model-lineage.md](genclass-model-lineage.md) | `jev_local/**` (except bench), Python tests, legacy `docs/*.md` | Python reference for parity; trainer; legacy server and harness | ~530 | -| [extension-and-benchmarks.md](extension-and-benchmarks.md) | `extension/**`, `bench/**`, `jev_local/bench/**`, `results/**`, `scripts/**` | Chrome extension, benchmarks, ops scripts | ~560 | -| [status-and-known-issues.md](status-and-known-issues.md) | OPEN_TASKS, STATUS, NEEDS files, `docs/runtime/*`, git history | Status, ground rules, owners, open issues, cross-doc drift | ~625 | +| [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | `index.ts`, `runtime.ts` wiring, `types.ts`, errors, `Clock`, `util.ts`, `package.json`; modes and the observe default | Options, `Runtime` methods, events, plugins, init/destroy, kill switch | ~690 | +| [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | `observe/*` (incl. EventSource and the message gate), `trace/*`, observer install/route code in `runtime.ts` | Patching fetch/XHR/WS/SSE/timers/DOM/history/Storage; ops, identity, causality; the four network gates | ~900 | +| [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | `state/*`, `adapters/*`, store code in `runtime.ts` | Writes (not held by default), drop filter, late revert, opt-in holds, snapshots, invariants, stale marks, React/Redux/Zustand | ~750 | +| [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) | `learn/*` (incl. cadence), `situation/*`, triage and the delivery gate in `runtime.ts` | Any model-visible text, delivery salience, triage, budgets, redaction, baselines | ~905 | +| [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | `decide/*`, action controllers (incl. delivery), `explain`, undo | Queue, hold rules, policy gate, built-in actions, late revert, reports | ~830 | +| [runtime/model-host.md](runtime/model-host.md) | `model/*`, worker, CLI `bin/genclass-runtime.mjs`, `packages/runtime-model/` | Model loading, caching, WebGPU/WASM, packer, calibration, CLI | ~680 | +| [runtime/devtools.md](runtime/devtools.md) | `devtools/*`, `UI-NEEDS.md`, devtools tests and UI spec | The overlay, its views, mode labels, theming, screenshots | ~720 | +| [runtime/build-test-release.md](runtime/build-test-release.md) | Workspace config, lockfile, CI, tsup/vitest/Playwright, fixtures, smoke, `scripts/vm.sh`, publishing | Build, test, fixtures, CI, release | ~620 | +| [model-io-contract.md](model-io-contract.md) | Situation text -> packed request -> heads -> calibrated answers, across runtime, sim, realapps and training; row kinds and labels | Any change the model can see; shipping a model directory | ~660 | +| [sim.md](sim.md) | `sim/**` | Training data generation (gold, unlabeled, on-policy), S1/S2 labels, splits, budgets | ~710 | +| [realapps.md](realapps.md) | `realapps/**` | Real-app corpus in headless Chromium, REAL rows and labels, never-worse and determinism sweeps, eval set | ~405 | +| [training.md](training.md) | `training/**` and the `jev_local` parts it calls | Curriculum (`rt.py` at situation-v2), training rounds, teacher/distillation/DAgger, eval, calibration, export | ~645 | +| [demos.md](demos.md) | `demos/**` | Demo apps, mock server, chaos, Playwright eval, results (v0.1 model, situation-v1 runtime) | ~550 | +| [genclass-model-lineage.md](genclass-model-lineage.md) | `jev_local/**` (except bench), Python tests, legacy `docs/*.md` | Python reference for parity; trainer; legacy server and harness | ~570 | +| [extension-and-benchmarks.md](extension-and-benchmarks.md) | `extension/**`, `bench/**`, `jev_local/bench/**`, `results/**`, `scripts/**` | Chrome extension, benchmarks, ops scripts | ~565 | +| [status-and-known-issues.md](status-and-known-issues.md) | OPEN_TASKS, HANDOFF, STATUS, NEEDS files, `docs/runtime/*`, git history | Status, ground rules, owners, open issues, cross-doc drift | ~640 | ## Conventions used in these docs -- **Header block.** Every subsystem doc opens with three lines: **Scope** (the files it covers), **Read this when** and **Source of truth**. The last line reads "Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins." -- **Fixed sections.** All 15 subsystem docs use the same sections in the same order: TL;DR, Files, Concepts and data structures, How it works, Configuration and constants, Invariants and gotchas, How to change it safely, Tests, Drift and open issues, Related docs. Jump straight to the one you need. -- **Code pointers** look like `path/from/repo/root.ts` -> `symbolName`, for example `packages/runtime/src/decide/policy.ts` -> `gate`. They never give line numbers; find a symbol with `rg -n "symbolName" <path>`. Some runtime docs shorten paths to `src/…` and `test/…`, relative to `packages/runtime/`. [status-and-known-issues.md](status-and-known-issues.md) states its own path convention at the top of its TL;DR. -- **Code wins.** A doc describes the code at its verified commit. If a doc disagrees with the code, trust the code, then fix the doc. This applies to the human docs too: CONTRACT.md, API.md, the READMEs, STATUS.md, the NEEDS files and MODEL_CARD.md all have stale items. +- **Header block.** Every subsystem doc opens with three lines: **Scope** (the files it covers), **Read this when** and **Source of truth**. The last line reads "Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins." A doc that still names commit 654d822 has not been re-checked for situation-v2; treat it with suspicion. +- **Fixed sections.** All 16 subsystem docs (the 8 under `runtime/`, plus model-io-contract, sim, realapps, training, demos, genclass-model-lineage, extension-and-benchmarks and status-and-known-issues) use the same sections in the same order: TL;DR, Files, Concepts and data structures, How it works, Configuration and constants, Invariants and gotchas, How to change it safely, Tests, Drift and open issues, Related docs. Jump straight to the one you need. overview, glossary, repo-map and playbooks have their own layout. +- **Code pointers** look like `path/from/repo/root.ts` -> `symbolName`, for example `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`. They never give line numbers; find a symbol with `rg -n "symbolName" <path>`. Some runtime docs shorten paths to `src/…` and `test/…`, relative to `packages/runtime/`. [status-and-known-issues.md](status-and-known-issues.md) states its own path convention at the top of its TL;DR. +- **Code wins.** A doc describes the code at its verified commit. If a doc disagrees with the code, trust the code, then fix the doc. This applies to the human docs too: CONTRACT.md (no `delivery` trigger, old budgets, old redaction rule), API.md, HANDOFF.md (still says guard is the default), STATUS.md, OPEN_TASKS.md (body still describes situation-v1 phase A and training round 1 as current), the NEEDS files and MODEL_CARD.md all have stale items. - **Drift sections.** "Drift and open issues" lists two things: - where docs or code comments disagree with the code, and what the code really does; - - open questions, and findings that came only from reading the code, with no test behind them. + - open questions, and findings that came only from reading the code, with no test behind them, including the findings of the 2026-10-08 adversarial review of the v2 changes (delivery, situation, sim/training scripts, realapps, project docs). Check this section before you rely on a human doc. [status-and-known-issues.md](status-and-known-issues.md) holds the cross-cutting drift tables (human docs vs the runtime code). Subsystem-specific drift is only in each doc's own Drift section. -- **"(unverified)"** marks a claim that nobody could confirm from the code or a run at the verified commit. Typical cases are live URLs, browser behaviour, VM state and results that are not in the repo. Treat such a claim as a hypothesis. "Inferred" and "code reading only" mean the claim was derived from the source and no test asserts it. +- **"(unverified)"** marks a claim that nobody could confirm from the code or a run at the verified commit. Typical cases are live URLs, browser behaviour, Azure/VM state and results that are not in the repo. Treat such a claim as a hypothesis. "Inferred" and "code reading only" mean the claim was derived from the source and no test asserts it. ## Keeping the docs current 1. **Update the doc in the same change as the code.** If you change code under a doc's Scope, edit the affected sections in that doc (Files, constants, How it works, Tests). Remove Drift entries your change resolves, and add any mismatch it creates. -2. **Update the commit line.** Set "Verified against commit … (date)" to the commit you checked the doc against. If you re-checked only part of the doc, name those sections in that line. -3. **Fix every copy of a repeated fact.** Several facts appear in more than one doc: the unpublished default model, the `situation-v1` freeze, the default hold budget, test counts. Before you finish, search for the symbol or value you changed and fix every hit, for example `rg -n "DEFAULT_MODEL_BASE_URL" docs/agents`. -4. **Model-visible changes cascade.** A change to situation text, questions, labels or budgets touches [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md) and [status-and-known-issues.md](status-and-known-issues.md) (freeze tag). +2. **Update the "Source of truth" line.** Name the branch and commit you checked the doc against, and the date. If you re-checked only part of the doc, name those sections in that line. +3. **Fix every copy of a repeated fact.** Several facts appear in more than one doc: the `situation-v2` freeze, the default mode `observe`, `holdWrites` off by default, the unpublished model and its 404 URLs, the default hold budget, the 2,400-char full budget, test counts (350 = 336 passed + 14 skipped), the realapps app count (91 at b435acb). Before you finish, search for the symbol or value you changed and fix every hit, for example `rg -n "DEFAULT_MODEL_BASE_URL|situation-v1" docs/agents`. +4. **Model-visible changes cascade.** A change to situation text, delivery salience, questions, labels or budgets touches [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md) and [status-and-known-issues.md](status-and-known-issues.md) (freeze tag). 5. **New docs.** A new subsystem doc keeps the same header block and ten sections. Add it to the catalogue and the routing table here, and to [repo-map.md](repo-map.md). Refresh the line counts with `wc -l docs/agents/*.md docs/agents/runtime/*.md` when a doc grows or shrinks a lot. 6. **Mark what you could not check.** Write "(unverified)" next to anything you could not confirm. Never add line numbers. @@ -178,8 +195,10 @@ Line counts were taken with `wc -l` and are approximate. The agent docs are derived from the code. They cite the human docs mainly to record drift, and they do not replace them: -- `docs/runtime/CONTRACT.md` is the binding build contract. The lead owns it. It holds the §0 ground rules, the spec, and the approved additions in §13. To change it, write a NEEDS item or ask the user (who now stands in for the lead); an approved deviation goes into CONTRACT §13 or STATUS "Deviations from the contract (and why)". +- `docs/runtime/CONTRACT.md` is the binding build contract. It holds the §0 ground rules, the spec, and the approved additions in §13 (our default-mode change is recorded there). The batch 4/5 contract deltas (the `delivery` trigger, salience rules, budgets, redaction) exist only in `packages/runtime/STATUS.md` ("Contract deltas"). To change the contract, write a NEEDS item or ask the user (who now stands in for the lead); an approved deviation goes into CONTRACT §13 or STATUS "Deviations from the contract (and why)". - `docs/runtime/API.md` is the public API reference for library users. If you change the public surface, update API.md and the JSDoc in `packages/runtime/src/types.ts` in the same change, then the agent doc. -- `docs/runtime/ARCHITECTURE.md` is the design overview for humans. Its known drift is listed in [status-and-known-issues.md](status-and-known-issues.md). -- The workstream status files (`packages/runtime/STATUS.md`, `packages/runtime/UI-NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, `OPEN_TASKS.md`) are how the team coordinates. Follow the process in [status-and-known-issues.md](status-and-known-issues.md), and do not close or rewrite another workstream's items: the requester flips an item to DONE after verifying (owners may add answers under their own heading, as MODEL did in `training/NEEDS.md`). +- `docs/runtime/ARCHITECTURE.md` is the design overview for humans. [docs/runtime/RESULTS.md](../runtime/RESULTS.md) holds the measured comparisons and the training log (HANDOFF asks for an update with every result). Their known drift is listed in [status-and-known-issues.md](status-and-known-issues.md). +- [HANDOFF.md](../../HANDOFF.md) is the colleague's entry point for a new session (state, rules, how to continue). Its run rules are for his 8 GB Mac and the Azure cluster; our agents follow `AGENTS.md`. +- [RELEASE.md](../../RELEASE.md) at the repo root is the release procedure: Part A for `0.1.0-alpha.1`, Part B for the model and `0.1.0`. +- The workstream status files (`packages/runtime/STATUS.md`, `packages/runtime/UI-NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, `OPEN_TASKS.md`) are how the team coordinates. Follow the process in [status-and-known-issues.md](status-and-known-issues.md), and do not close or rewrite another workstream's items: the requester flips an item to DONE after verifying (owners may add answers under their own heading). REAL has no NEEDS file of its own; its requests and node claims live in `training/NEEDS.md`. - The legacy jev-local docs (`docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`) and `docs/benchmax-research/` are not the runtime contract. CONTRACT §1 says this earlier GenClass content "stays as is". They are summarised in [genclass-model-lineage.md](genclass-model-lineage.md) and [extension-and-benchmarks.md](extension-and-benchmarks.md). diff --git a/docs/agents/demos.md b/docs/agents/demos.md index 1add95d8..ae27ec0f 100644 --- a/docs/agents/demos.md +++ b/docs/agents/demos.md @@ -2,20 +2,23 @@ > **Scope:** `demos/` (`README.md`, `NEEDS.md`, `results.md`, `results*.json`, `package.json`, `vite.config.ts`, `tsconfig*.json`, `scripts/**`, `e2e/**`, `src/**`, `index.html`, `*/index.html`). > **Read this when:** you change a demo app, its scenario or oracle; touch the Service Worker mock server or chaos model; run or change the Playwright eval; read or regenerate `results.*`; update the runtime API the demos use (shim); or work on a `demos/NEEDS.md` item. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> +> **What changed since situation-v1 (654d822):** no demos *code* changed. Commit 04a264f replaced the measured data (`results.json`, `results.md`, `results-summary.json`, all `screenshots/*.png`, new `decisions-heal.png`) with an 810-trial run on the **frozen batch-3 runtime** and rewrote `NEEDS.md` §1, §5, §8 and the README results section. The runtime under the demos then changed a lot (batch 4 fcd1e68: decisions at the network boundary, store-write holds opt-in, EventSource observed, synthetic DOM events ignored by default; batch 5 6e5e86e: situation-v2 frozen; f3636b2: runtime default mode `observe`). The shipped results therefore describe a runtime that no longer exists; see [Drift](#drift-and-open-issues). ## TL;DR - `@genclass/demos` (private workspace) is a Vite multi-page static site: a landing page plus six small apps (`search`, `editor`, `checkout`, `status`, `board`, `decisions`), each with a deliberate, realistic latent bug that only shows under network chaos. - The backend is a **mock API inside a Service Worker** (`src/server/`): real `fetch` and a real `EventSource` from the page's point of view. Each page or trial gets its own server session (**world**). The page controls the server only via `postMessage`, never `fetch`, so GenClass never observes test traffic. -- GenClass is created in exactly one place, `src/shared/genclass.ts` -> `startGenClass`. Demo **Off** = `GenClass.init({ mode: "observe", model: false })` (the baseline; nothing is held or decided). **Guard** / **Heal** = `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. App code is identical in all three. +- GenClass is created in exactly one place, `src/shared/genclass.ts` -> `startGenClass`. Demo **Off** = `GenClass.init({ mode: "observe", model: false })` (the baseline; nothing is held or decided). **Guard** / **Heal** = `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. App code is identical in all three. The demos always pass `mode` explicitly, so the runtime's new default (`observe`, f3636b2) does not change what they measure; the demo site's own default mode is still `guard` (`settings.ts` -> `getMode`), and `genclass.ts`'s header comment and the landing page's Guard card (`landing.ts` -> `modes`, `badge: "default"`) are now stale. - A **trial** = seeded scenario (scripted user steps + chaos + server params + intent) run in a fresh page, then scored by the demo's **oracle** (test code that reads only the DOM and the mock server's truth). **Chaos** trials measure bug rate; **clean** trials (calm network, calm user, app is correct) count **false interventions** (any non-passive action that ran). - Two drivers run the same steps: the in-page "Run trials" panel (iframes, synthetic DOM events, `src/shared/driver.ts`) and the headless eval (`e2e/eval.ts`, Playwright, real keyboard and mouse). -- Fairness devices: **common random numbers** (the n-th identical request/event gets the same latency and failure draws in every mode) and **native timers** captured before `GenClass.init` for all test code. Known gap: scripted world activity is timed from world creation, which precedes the Guard/Heal model wait (`gc.loadMs` 0.67–2.08 s in the shipped run), see [Invariants](#invariants-and-gotchas). -- Shipped results (`results.md`, 810 trials, the v0.1 GenClass model, which was not trained for runtime decisions, q8 WASM): no executed action lowered a bug rate (the only drop, status under Guard 100% -> 93%, came with zero actions executed), 0 false interventions (mostly because decisions missed thresholds or the hold budget), and holding writes cost latency (search) and introduced bugs (board, 9 of 30 seeds under both Guard and Heal). -- Open runtime work for CORE is in `demos/NEEDS.md`; at HEAD §1 (held write lands after a newer user write), §2 (holds cost latency), §5 (`retry` offered for non-idempotent requests) and §6 (no EventSource observer) are still open in code. -- **Blocking gotcha:** `demos/src/server/data/cities.ts` is imported by the search world, scenario and oracle but is **not in git** (the root `.gitignore` line `data/` ignores it). A fresh clone cannot build the Service Worker or the search page until it is recreated. See [Drift](#drift-and-open-issues). -- Ground rules: the original team ran every build, browser and model run on the `train` VM through `scripts/vm.sh` (slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([../../AGENTS.md](../../AGENTS.md) §4), ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`), model downloads (`npm run fetch-model`) or anything on Azure. Demos and `sim/` must not read each other, and oracles are never passed to GenClass. +- Fairness devices: **common random numbers** (the n-th identical request/event gets the same latency and failure draws in every mode) and **native timers** captured before `GenClass.init` for all test code. Known gap: scripted world activity is timed from world creation, which precedes the Guard/Heal model wait (`gc.loadMs` 1.31–3.01 s, median ~1.57 s in the shipped run), see [Invariants](#invariants-and-gotchas). +- Shipped results (`results.md`, generated 2026-10-08T00:49Z, 810 trials, runtime 0.1.0 dist `5155180d4baf` = **frozen batch 3**, situation-v1 era; v0.1 GenClass model, not trained for runtime decisions, q8 WASM): Guard executed **0** actions in every demo yet raised bug rates (editor 83 -> 90%, checkout 70 -> 77%, board 57 -> 63%, decisions 83 -> 97%); Heal executed 156 actions (all on chaos runs) and lowered no bug rate; 0 false interventions in every demo and mode (because v0.1 rarely clears the thresholds); clean-run search latency rose 10 -> 234 ms (Guard). Traced runs pin the editor/checkout/board harm on store-write holds reordering app writes (`NEEDS.md` §1); the decisions demo's rise comes from v0.1's `ask`/`decide` answers, not holds (same section). +- Those findings drove runtime batch 4 (fcd1e68): store writes are no longer held by default (`policy.holdWrites` defaults to `false`), decisions about responses and messages happen at a new `delivery` trigger, EventSource messages are observed, and nothing is held when the model is not expected to answer within the hold budget. **None of this has been measured on the demos yet**: there is no situation-v2 model, and the demos rerun comes after `@genclass/runtime-model@0.1.0` in `HANDOFF.md`'s order. `docs/runtime/RESULTS.md` §4 reports the v2 runtime's own "never worse" check (always-passive model) on [realapps](realapps.md); its v2 "Demos" cell ("holds only at delivery; clean typeahead makes 0 model calls and holds for 0 ms") matches the unit test `packages/runtime/test/delivery.test.ts` (`describe("delivery: typeahead")`, per `packages/runtime/STATUS.md`), not a demos eval run. +- `demos/NEEDS.md` vs the code at b435acb: §1 (held write lands after a newer user write) and §6 (EventSource) are **addressed in code, unmeasured on the demos**; §2 (holds cost latency) is **largely addressed** (store writes not held by default; request/failure/delivery holds are skipped when the model is expected to be slower than the budget; superseded queued decision requests are dropped; the 800 ms ceiling is unchanged); §5 (`block`/`retry` on non-idempotent user writes) is **still open**; §7 (keep observing synthetic DOM events) is **now opt-in** (`observe.untrustedEvents`, default `false`) and the demos do not opt in, so the in-page "Run trials" driver's user actions are invisible to the runtime (the headless eval uses real input and is unaffected). +- **Blocking gotcha:** `demos/src/server/data/cities.ts` is imported by the search world, scenario and oracle but is **not in git** (the root `.gitignore` line `data/` ignores it). A fresh clone cannot build the Service Worker or the search page, and the root `npm run typecheck` (which runs every workspace's) fails, until it is recreated. See [Drift](#drift-and-open-issues). +- Ground rules: the original team ran every build, browser and model run on the `train` VM through `scripts/vm.sh` (slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([../../AGENTS.md](../../AGENTS.md) §4), light checks (`npm ci`, `tsc`) are fine locally; ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`, it drives Playwright), model downloads (`npm run fetch-model`) or anything on Azure. `sim/` and `realapps/` must not read the demos (`HANDOFF.md`; verified: no code in `sim/src` or `realapps/src` references `demos/`, and the demos' code references neither), and oracles are never passed to GenClass. The demos are not built or checked by CI (`.github/workflows/ci.yml` covers `@genclass/runtime` only). ## Files @@ -35,8 +38,8 @@ | `demos/scripts/vm-eval.sh` | full VM pipeline: install, build runtime, model, build demos, typecheck, eval | env `GENCLASS_MODEL_FROM/DIR/URL/VARIANT`, `ALLOW_BROKEN_RUNTIME`, `SKIP_EVAL` | | `demos/e2e/eval.ts` | headless Playwright eval: trials, reports, screenshots | CLI options (see Configuration) | | `demos/e2e/serve.ts` | static server for `dist/` under a sub-path, with extra mounts | `serveStatic(rootDir, base, port, mounts)` | -| `demos/e2e/trace-report.ts` | analyses `--trace` runs (held writes, apply order); prints Markdown to stdout. Sections: "Board: what holding writes does" (per mode/kind: writes, held = waited > 2 ms, median hold, held writes applied after a newer user write to the same card), A/A flips (with the optional 2nd file), per-seed card timelines for seeds clean in Off but buggy in Guard/Heal plus "mechanism counts"; "Search: where the latency goes" (held response writes, decision latency, holds released before their decision arrived) | `node --experimental-strip-types e2e/trace-report.ts [traces.json (default e2e/.out/traces.json)] [offB.json]` | -| `demos/src/shared/genclass.ts` | the only place the runtime is created; session stats | `startGenClass`, `collectStats`, `statusText`, `RUNTIME_KIND`, `GcSession` | +| `demos/e2e/trace-report.ts` | analyses `--trace` runs (held writes, apply order); prints Markdown to stdout. Built for the batch-3 runtime's store-write holds: "held" = proposal-to-apply gap; under the v2 default (`holdWrites: false`) that gap is ~0 and delivery holds (before the write is proposed) are not visible to it (inferred from code). Sections: "Board: what holding writes does" (per mode/kind: writes, held = waited > 2 ms, median hold, held writes applied after a newer user write to the same card), A/A flips (with the optional 2nd file), per-seed card timelines for seeds clean in Off but buggy in Guard/Heal plus "mechanism counts"; "Search: where the latency goes" (held response writes, decision latency, holds released before their decision arrived) | `node --experimental-strip-types e2e/trace-report.ts [traces.json (default e2e/.out/traces.json)] [offB.json]` | +| `demos/src/shared/genclass.ts` | the only place the runtime is created; session stats (header comment still calls Guard "the default"; the runtime default is now `observe`) | `startGenClass`, `collectStats`, `statusText`, `RUNTIME_KIND`, `GcSession` | | `demos/src/shared/settings.ts` | URL params and localStorage | `getMode`, `setMode`, `modelBaseUrl`, `trialParams` (`TrialParams { seed, kind, mode, run }`), `traceOn`, `holdBudget`, `sessionId`, `loadChaos`, `saveChaos`, `siteRoot`, `getTheme`/`setTheme`, `urlParams` | | `demos/src/shared/chaos.ts` | chaos model (shared by page and Service Worker) | `RouteChaos`, `Chaos`, `CALM`, `PresetId` (`calm\|busy\|flaky\|storm\|outage`), `PRESETS`, `withPreset`, `matchPreset`, `mergeChaos`, `resolveChaos`, `Timing { up, down, spike }`, `sampleTiming`, `sampleEventDelay`, `describeChaos` | | `demos/src/shared/protocol.ts` | page <-> Service Worker control protocol | `DemoId`, `ControlMessage`, `ControlReply`, `LogEntry`, `EventEntry`, `ServerInfo` (exported, unused) | @@ -72,8 +75,8 @@ | `demos/src/dev/runtime-shim/*.ts` | observe-only stand-in for `@genclass/runtime`, `/react`, `/redux`, `/zustand`, `/devtools`; re-exports all types from `packages/runtime/src/types.ts` by relative path | `index.ts`: `GenClass` (singleton `init`, `runtime` getter, `destroy`), `createRuntime`, `GenClassUnavailableError` (no `reason` field); `react.ts`: `useGenClass`, `useAtom`, `useGenClassState`; `redux.ts`: `genclassEnhancer` (identity); `zustand.ts`: `genclass` (identity); `devtools.ts`: `mountDevtools` (no-op handle), `DevtoolsOptions` | | `demos/README.md` | human README (run, URL params, oracles table, latest results, honesty rules) | | | `demos/NEEDS.md` | what DEMOS needs from CORE/MODEL, with evidence | | -| `demos/results.md`, `results.json`, `results-summary.json` | latest measurements (raw trials only in `results.json`); summary ships with the site | | -| `demos/screenshots/*.png` | captured by the eval's screenshot tour | | +| `demos/results.md`, `results.json`, `results-summary.json` | latest measurements (raw trials only in `results.json`); summary ships with the site. Current files: 2026-10-08T00:49Z, frozen batch-3 runtime (`runtimeBuild.dist` `5155180d4baf`), v0.1 model card recorded | | +| `demos/screenshots/*.png` | captured by the eval's screenshot tour (all re-captured in 04a264f, including `decisions-heal.png`) | | ## Concepts and data structures @@ -101,6 +104,7 @@ Additional terms used in this doc (repo-wide terms such as op, trigger, situatio | A/A noise | flips between two Off runs of the same seeds; the floor for reading fixed/introduced (board: 1 of 30 after CRN, per `NEEDS.md` §4). | | jump-back | board oracle metric: a card the user moved shows its previous column again 400 ms–5 s after the server accepted the move, before any newer move of that card. | | trace run | `?trace=1` / `eval.ts --trace`: records every proposed write (`hooks.mutationProposed`), each `state` event (applied write), ops and decisions into `window.__gcTrace`. Off by default; never in published results. | +| store-write hold (batch 3) vs delivery hold (v2) | What the shipped results measured: a salient store write waited for the model (up to the hold budget) inside `StoreHub.propose`, and could land after a newer user write (`NEEDS.md` §1). At b435acb store-write holds are opt-in (`policy.holdWrites`, default `false`, `packages/runtime/src/state/hub.ts` -> `StoreHub.holdWrites`); instead a fetch/XHR response or WebSocket/EventSource message may be held at the **`delivery`** trigger before the app sees it (latency only, order kept; its non-passive actions are `discard`, which delivers but drops only the writes over newer data, and `defer`), and `Runtime` holds only when `expectedLatency() <= holdBudgetMs()` (`packages/runtime/src/runtime.ts`). See [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md). | | runtime shim | `src/dev/runtime-shim/`: observe-only stand-in aliased when `packages/runtime/dist/index.js` is missing or `GENCLASS_SHIM=1`; results then say `runtime: "shim"`. | | COI | cross-origin isolation: the Service Worker adds COOP/COEP/CORP headers so `crossOriginIsolated` is true and WASM threads are available to the model. | @@ -202,7 +206,7 @@ Trace shape (`src/shared/trace.ts`, stored in `window.__gcTrace` and `TrialResul ### 5. Drivers -- **Synthetic** (`src/shared/driver.ts` -> `runSteps`): per typed char `keydown` (`code` `KeyX`/`DigitN`/`Space`), `keypress`, `beforeinput` + `setRangeText` + `input` (`insertText`; `\n` -> Enter), `keyup`; Backspace -> `deleteContentBackward`; Enter in `<input>` -> `form.requestSubmit()`; clicks fire `pointerover/enter`, `mouseover`, `pointerdown`, `mousedown`, focus, `pointerup`, `mouseup`, `click` (+ `dblclick` when `count === 2 && gap < 300`); clicks on disabled controls do nothing; selectors are awaited up to 5 s (clicks 4 s). All waits use native timers. The runtime's DOM observer keeps untrusted events when no app op is running (`packages/runtime/src/observe/dom-user.ts` -> `programmatic`). +- **Synthetic** (`src/shared/driver.ts` -> `runSteps`): per typed char `keydown` (`code` `KeyX`/`DigitN`/`Space`), `keypress`, `beforeinput` + `setRangeText` + `input` (`insertText`; `\n` -> Enter), `keyup`; Backspace -> `deleteContentBackward`; Enter in `<input>` -> `form.requestSubmit()`; clicks fire `pointerover/enter`, `mouseover`, `pointerdown`, `mousedown`, focus, `pointerup`, `mouseup`, `click` (+ `dblclick` when `count === 2 && gap < 300`); clicks on disabled controls do nothing; selectors are awaited up to 5 s (clicks 4 s). All waits use native timers. **At b435acb the runtime ignores these events**: `packages/runtime/src/observe/dom-user.ts` -> `programmatic` drops every `isTrusted === false` event unless the app passed `observe: { untrustedEvents: true }` (batch 4), and `startGenClass` does not pass it. The app still reacts to them, but GenClass sees no user actions in in-page runner trials, so their situations (and any results from the panel) differ from the Playwright eval's. The batch-3 runtime that produced the shipped results recorded them. - **Playwright** (`e2e/eval.ts` -> `runSteps`): `page.keyboard.type/press` (one char at a time after its delay; missing delays default to 90 ms in both drivers), `locator.click` (click waits up to 1,500 ms for an enabled, visible element on the first click, 200 ms on repeats; `click` timeout 2,000 ms, errors ignored), `waitForFunction` for `until` (polling 25 ms); `wait` is `page.waitForTimeout` (Node side, invisible to the runtime). With `harness = false` (screenshot tour on the interactive page) `mark` is skipped, `chaos`/`server` go through `window.__demo`, `until` just waits `min(1500, timeout)` and `unless` is never true. - `TrialHarness.check(cond)` returns `false` when the oracle has no `check` or throws, so a broken condition makes `until` steps time out (counted in `metrics.untilTimeouts`) instead of failing the trial. @@ -233,7 +237,7 @@ Trace shape (`src/shared/trace.ts`, stored in `window.__gcTrace` and `TrialResul 1. `policy = holdBudgetMs ? { holdBudgetMs } : undefined` (`?budget=<ms>`). 2. Trace runs pass `hooks: traceHooks(trace)` (cast through `Partial<InitOptions>`; `GenClass.init` spreads options into `createRuntime`) and `attachTrace` subscribes to `event` (`state`, `op.start`, `user`) and `decide`. -3. Off: `GenClass.init({ mode: "observe", model: false, plugins, policy })`. Guard/Heal: `GenClass.init({ mode, model: { baseUrl?, preload: "eager" }, plugins, debug, policy })`. +3. Off: `GenClass.init({ mode: "observe", model: false, plugins, policy })`. Guard/Heal: `GenClass.init({ mode, model: { baseUrl?, preload: "eager" }, plugins, debug, policy })`. No `observe` option is passed (so `untrustedEvents` stays `false` and every observer, including the new `eventsource` one, is installed) and no `policy.holdWrites` (so on the v2 runtime store writes are never held). 4. Session arrays fed by `gc.on("decide" | "detect" | "act" | "report")`; `readyAt` from `gc.ready`. 5. `collectStats(session)` -> `GcStats`: `runtime` = `RUNTIME_KIND` (from the `__RUNTIME_KIND__` define), `isolated` = `crossOriginIsolated`, `status`/`model`/`device`/`variant` from `gc.status`, `loadMs` = `status.loadMs` or `readyAt − initAt`, `diagnoses` counted over all decisions, `notExecuted` over decisions with `!executed && reason`, `interventions` = every `act` record (`{ action, tier, trigger, changed, at }`), `decisionLatencyMs` rounded to 0.1 ms. `statusText(gc)` formats `gc.status` for compact display. @@ -311,9 +315,9 @@ Common: each `main.ts` calls `bootDemo` with `host`, `mount`, `scenario`, `oracl ### 11. Site shell (`src/site/`) -1. **Landing** (`index.html` -> `src/site/landing.ts`, module side effects, no GenClass runtime on this page): `applyTheme()`, then replaces `#page` with `renderTopbar("home")` and sections `hero` (install snippet with Copy; the three "[GenClass]" console lines are **illustrative copy, not real output**), `modes` (Observe / Guard (default) / Heal adoption path), `demos` (cards from `DEMOS` + `ART`, links `<root><id>/`), `results` (fetches `<root>results-summary.json` with `cache: "no-store"`; reads `demos.<id>.<mode>.chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`; shows "No measurements ship with this build yet" when absent), `how`, `observability`, footer (Apache-2.0, `REPO_URL`). +1. **Landing** (`index.html` -> `src/site/landing.ts`, module side effects, no GenClass runtime on this page): `applyTheme()`, then replaces `#page` with `renderTopbar("home")` and sections `hero` (install snippet with Copy; the three "[GenClass]" console lines are **illustrative copy, not real output**), `modes` (Observe / Guard / Heal adoption path; the Guard card carries `badge: "default"`, stale since f3636b2), `demos` (cards from `DEMOS` + `ART`, links `<root><id>/`), `results` (fetches `<root>results-summary.json` with `cache: "no-store"`; reads `demos.<id>.<mode>.chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`; shows "No measurements ship with this build yet" when absent), `how`, `observability`, footer (Apache-2.0, `REPO_URL`). 2. **Demo page layout** (`bootInteractive`): top bar; hero (`DEMO_BY_ID[id]` `n`, `tagline`, `title`, `summary`, `stack` badges) + mode card; main column = app frame (`.app-frame` with fake window chrome, `def.host`, mode chip, `.app-body` where the app mounts) + net lane + explain cards (`wrong`, `scored`, `def.code`); side column = Try it (`tryIt` HTML), Activity, Network chaos; then Run trials; footer. -3. **Activity panel** (`activity.ts` -> `mountActivity`): one row per `gc.on("report")` (`kind: "intervene"` counts as "prevented", anything else non-status as "flagged"; `kind: "status"` updates one status row in place). Titles from `ACTION_TITLE` (`discard`, `defer`, `coalesce`, `delay`, `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`) and `DIAG_TITLE` (`stale`, `conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, `transient`, `overload`, `unusual`). "Evidence" calls `gc.explain(id)` and shows `changed`, `facts`, diagnosis and action probability bars, `timeline`, and a toggle for `situationText`. "Undo" calls `ActionRecord.undo()`. Each intervention flashes the app frame (`gc-flash` class) and adds a shield toast over it (max 3, auto-close 7 s). A "Model consulted N× (median …)" line classifies every `decide`: executed with a non-passive tier -> acted, executed passive -> "chose to let it be", otherwise by `reason` substring (`"hold budget"` -> late, `"below the"` -> low confidence, `"expected"` -> judged expected, else not allowed in this mode); an "Observed …" line counts `event`s (`op.start` named like an HTTP method = request, `state` = write, `user`). +3. **Activity panel** (`activity.ts` -> `mountActivity`): one row per `gc.on("report")` (`kind: "intervene"` counts as "prevented", anything else non-status as "flagged"; `kind: "status"` updates one status row in place). Titles from `ACTION_TITLE` (`discard`, `defer`, `coalesce`, `delay`, `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`) and `DIAG_TITLE` (`stale`, `conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, `transient`, `overload`, `unusual`). "Evidence" calls `gc.explain(id)` and shows `changed`, `facts`, diagnosis and action probability bars, `timeline`, and a toggle for `situationText`. "Undo" calls `ActionRecord.undo()`. Each intervention flashes the app frame (`gc-flash` class) and adds a shield toast over it (max 3, auto-close 7 s). A "Model consulted N× (median …)" line classifies every `decide`: executed with a non-passive tier -> acted, executed passive -> "chose to let it be", otherwise by `reason` substring (`"hold budget"` -> late, `"below the"` -> low confidence, `"expected"` -> judged expected, else not allowed in this mode; the v2 runtime's reason "the subject was not held (decided in the background)" from `packages/runtime/src/runtime.ts` therefore lands in "not allowed in this mode"); an "Observed …" line counts `event`s (`op.start` named like an HTTP method = request, `state` = write, `user`). 4. **Net lane** (`netlane.ts` -> `mountNetLane(link)`): polls `link.log(since)` every 300 ms (re-polling from the oldest pending entry; paused while the tab is hidden) and renders a 10 s waterfall on `requestAnimationFrame` (every ≥ 70 ms): 8 rows of 12 px, label `METHOD path?query` (≤ 34 chars), labels dropped when > 22 bars are visible, class per `LogEntry.outcome` and `spike`, tooltip with status, duration, `effect` and "aborted by the page". 5. **Chaos panel extras**: `DemoDefinition.chaosExtras(link)` renders demo-specific server controls under the sliders: status "Real incidents (12 s)" (service select, Degrade / Start outage -> `world("incident", { svc, status, dur: 12000 })`, Resolve all -> `world("resolveAll")`); board teammate buttons (see the board table). @@ -400,7 +404,8 @@ Common: each `main.ts` calls `bootDemo` with `host`, `mount`, `scenario`, `oracl | `GENCLASS_SHIM` | `1` force shim, `0` force real; default shim iff `packages/runtime/dist/index.js` missing | `vite.config.ts` | | | `BUILD_ID` | env or `Date.now().toString(36)` | `vite.config.ts`, `build.mjs` | page/worker version match | | `vm-eval.sh` model | default `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` -> `~/gcl/models/genclass-v0.1`, variant `q8` | `scripts/vm-eval.sh` | `GENCLASS_MODEL_FROM`, `GENCLASS_MODEL_DIR`, `GENCLASS_MODEL_URL` (pass `--model`, serve nothing), `GENCLASS_MODEL_VARIANT` | -| runtime policy defaults (not demos code) | thresholds report 0.6 / guard 0.9 / heal 0.8; `holdBudgetMs: "auto"` = clamp(1.5 × median latency, 150, 800), 300 when unknown | `packages/runtime/src/decide/policy.ts` -> `policyConfig`, `holdBudget` | explains `notExecuted` reasons | +| runtime policy defaults (not demos code) | thresholds report 0.6 / guard 0.9 / heal 0.8; `holdBudgetMs: "auto"` = clamp(1.5 × median of recent model latencies (warm-up time before any), `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800), `HOLD_FALLBACK_MS` 300 when nothing is known; `holdWrites: false` (batch 4) | `packages/runtime/src/decide/policy.ts` -> `policyConfig`, `holdBudget` | explains `notExecuted` reasons; with v0.1 on WASM (decisions ~0.4–1.8 s p50 in the shipped run) the budget sits at its 800 ms ceiling | +| runtime init defaults the demos rely on (not demos code) | `mode` default `observe` (f3636b2; the demos always pass it); `observe.untrustedEvents` default `false` (batch 4) | `packages/runtime/src/runtime.ts`, `packages/runtime/src/types.ts` -> `InitOptions` | see [How it works §5](#5-drivers) | ## Invariants and gotchas @@ -415,7 +420,7 @@ Common: each `main.ts` calls `bootDemo` with `host`, `mount`, `scenario`, `oracl - **Trial pages wait for the model** in Guard/Heal before mounting; Off mounts immediately. Decision latency includes queueing: the model host answers one request at a time, and 8 parallel eval workers share the VM's CPU (impact on latency unmeasured). - **Clean trials of a seed differ from chaos trials of the same seed** (scenario RNG includes `kind`); clean seeds also start at base + 500. - **Status uses `settle: false`** because polling never stops; it gets only 350 ms after freeze. -- **The world clock starts before the model wait (fairness risk, inferred from code; impact unmeasured).** `bootTrial` sends `hello` (world created, `WorldDef.start` runs) and only then waits for `gc.ready` in Guard/Heal, while Off mounts at once. Status incidents (`from = w.created + at`, at 3–9 s), board teammate moves (`Exp(teamEveryMs) + 3000` ms after start) and anything else scheduled with `World.script`/`after` therefore happen earlier relative to the session `t0` in Guard/Heal, by roughly the model load time (`gc.loadMs` 672–2,077 ms over the 540 Guard/Heal trials in `results.json`, median ~834 ms). Per-request CRN draws are unaffected. Moving `hello` after the model wait, or scheduling scripts from a `start` world action sent at `begin()`, would remove the offset; either changes every seed's results. +- **The world clock starts before the model wait (fairness risk, inferred from code; impact unmeasured).** `bootTrial` sends `hello` (world created, `WorldDef.start` runs) and only then waits for `gc.ready` in Guard/Heal, while Off mounts at once. Status incidents (`from = w.created + at`, at 3–9 s), board teammate moves (`Exp(teamEveryMs) + 3000` ms after start) and anything else scheduled with `World.script`/`after` therefore happen earlier relative to the session `t0` in Guard/Heal, by roughly the model load time (`gc.loadMs` 1,312–3,014 ms over the 540 Guard/Heal trials in the current `results.json`, median ~1,574 ms; the previous run's was 672–2,077 ms). Per-request CRN draws are unaffected. Moving `hello` after the model wait, or scheduling scripts from a `start` world action sent at `begin()`, would remove the offset; either changes every seed's results. - **Clocks across contexts.** Oracles compare page `epochNow()` with Service Worker log times (both `performance.timeOrigin + performance.now()`, but of different globals); the decisions app stamps `askedAt` with `Date.now()`. These agree to within clock skew, which matters only for windows close to the boundary (e.g. "no key in 2.5 s"). - **The activity panel parses runtime reason strings** (`"hold budget"`, `"below the"`, `"expected"`) to classify decisions; rewording `Decision.reason` in the runtime silently moves counts between buckets (the same applies to `notExecuted` keys in results). - **Mock-server state is in worker memory only.** A Service Worker restart loses every world. The interactive page reloads (`onRestart`) only if its heartbeat `ping` notices first (`known: false`); if an app request arrives first, `identify` makes it re-`hello` into a fresh, reset world without reloading. A trial in flight gets a fresh, empty world the same way and will usually be scored as a bug or fail its `until` steps. @@ -430,11 +435,13 @@ Common: each `main.ts` calls `bootDemo` with `host`, `mount`, `scenario`, `oracl - **Two Off notions:** demo Off (`observe`, `model: false`, stats still collected) vs `?genclass=off` (runtime kill switch: nothing installed). - **`act` counts as an intervention** even when the action failed (`ok: false`) or was a late revert; `notExecuted` is keyed by the runtime's reason string with numbers masked, so changing reason wording in the runtime changes report keys. - **Off has `ask`/`decide` reject immediately** (`GenClassUnavailableError` reason `off`), so decisions latency is 0 ms in Off. The decisions app labels every `GenClassUnavailableError` (including the runtime's `"timeout"` reason) as "no model: app default"; any other rejection is labelled "no answer in time: app default". -- **Redaction:** the runtime's default redactor drops any path segment that is a secret word (`packages/runtime/src/util.ts` -> `isSensitiveName`, `SECRET_WORDS` includes `auth`). The status store keys services by id, so `services.services.auth.*` is redacted from situations (inferred from code; not observed in a trace). +- **Redaction:** the runtime's default redactor now looks at the **leaf** field (`packages/runtime/src/util.ts` -> `isSensitivePath`, `defaultRedact`); an ancestor segment that is only a weak container word (`WEAK_CONTAINER`: `auth`, `authorization`, `cookie`, `session`) redacts only opaque credential-looking strings (`OPAQUE`). So the status store's `services.services.auth.status` / `.latencyMs` stay visible (inferred from code; the earlier "auth segment is redacted" gotcha no longer applies). +- **Results are runtime-version specific.** `results.json` records `runtimeBuild` (`packages/runtime` version + dist hash). The shipped run's `5155180d4baf` is batch 3; every number about holds, jump-backs, decision counts per trial and `notExecuted` reasons can change on the v2 runtime. Quote them as "batch 3, v0.1 model", never as the current runtime's behaviour. +- **`e2e/trace-report.ts` measures the old mechanism.** Its "held" means a gap between `hooks.mutationProposed` and the `state` event. On the v2 runtime with the default `holdWrites: false` that gap is ~0, and a delivery hold delays the response *before* the app writes, so the report would show almost no held writes even when responses were held (inferred from code; not run). `src/shared/trace.ts` already records every decision with its `trigger` and `op`, so `delivery` decisions and their `latencyMs` are in the trace; to study v2 holds, extend `trace-report.ts` to analyse them. ## How to change it safely -The original team ran all builds, browsers and model runs on the `train` VM (`scripts/vm.sh`, slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things)), ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`), model downloads (`npm run fetch-model`) or anything on Azure. +The original team ran all builds, browsers and model runs on the `train` VM (`scripts/vm.sh`, slot `demos`), because the author's Mac has 8 GB. Under the current agent policy ([runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things)), `npm ci` and `tsc` are fine locally; ask the user before the demos' eval (`npm run eval*`, `scripts/vm-eval.sh`), model downloads (`npm run fetch-model`) or anything on Azure. A demos rerun is only meaningful once a situation-v2 model exists (none does at b435acb; R17-final1 is situation-v1 and does not match the v2 runtime). 1. **Recreate the missing city data (prerequisite for any build).** Add `demos/src/server/data/cities.ts` exporting `searchCities(q: string): { total: number; items: { id: number; name: string; country: string; population: number }[] }` (deterministic, short prefixes match more) and `TYPED_TARGETS: string[]`. Either rename the directory or add a negation (`!demos/src/server/data/`) to the root `.gitignore`, otherwise it will be ignored again. The UI copy says 340 cities. 2. **Add a demo.** Add `DemoId` in `src/shared/protocol.ts`; a world `src/server/worlds/<id>.ts` and register it in `sw.ts` -> `DEFS`; `src/demos/<id>/{main,app,scenario,oracle}.ts` + `app.css`; `<id>/index.html` (copy one, `gc-root` `../`); add to `PAGES` (`vite.config.ts`), `ALL_DEMOS`/`TITLES`/`SHOT_PRESET` (`e2e/eval.ts`), `DEMOS` (`src/shared/demos.ts`: `n`, `title`, `tagline`, `stack`, `summary`, `wrong`, `scored`, `failure`, `tryIt`), `ART` (`src/site/art.ts`). `DEFS`, `ART`, `TITLES` and `SHOT_PRESET` are `Record<DemoId, …>` literals, so `tsc` flags a missing entry there; it does **not** flag `DEMOS` (an array; `DEMO_BY_ID` is built from it with a cast), `PAGES` or `ALL_DEMOS`, so add those by hand. Keep oracles on native timers and `data-testid`s. Run `npm run typecheck`, `npm run build`, `npm run eval:fast -- --demos <id>` (ask first). @@ -442,12 +449,13 @@ The original team ran all builds, browsers and model runs on the `train` VM (`sc 4. **Add a chaos knob.** Add the field to `RouteChaos` and `CALM`; apply it in `World.handle` (draw any randomness from the request's `rrng` up front, not lazily); add a slider in `chaos-panel.ts` -> `SLIDERS` and text in `describeChaos`; include it in `ChaosRanges` usage in scenarios. Typecheck both `tsconfig.json` and `tsconfig.sw.json`. 5. **Add a server route or world action.** Add a `Route` with a stable `key` (chaos rules and oracles use it); use `w.rng` inside handlers and `w.scriptRng` / `w.script` for scripted activity; add oracle-relevant data to `snapshot`. World actions return `undefined` for unknown names (the control reply is then `ok: false`). 6. **The demos need a new runtime API.** Use only the public API (`@genclass/runtime`, `/react`, `/redux`, `/zustand`, `/devtools`). Mirror it in `src/dev/runtime-shim/*` (and `tsconfig.shim.json` paths / `vite.config.ts` aliases for new entry points), then run `npm run typecheck:shim`. -7. **Evaluate a new model (ask first).** `GENCLASS_MODEL_FROM=<release dir url> bash demos/scripts/vm-eval.sh --tag <name>` (or `GENCLASS_MODEL_URL=<url>|cdn`). Tagged runs write `results-<tag>.*` and do not replace the shipped results; untagged runs replace `results.json/.md/-summary.json` and the landing page numbers. Check `model.card` and `runtimeBuild` in the JSON. -8. **Investigate a hold-induced regression (ask first).** Run `eval.ts --trace --demos board --modes off,guard,heal --tag <t>` (and a second Off-only run for A/A), then `node --experimental-strip-types e2e/trace-report.ts e2e/.out/traces-<t>.json [e2e/.out/traces-<offB>.json]`. It reports held writes, median holds, held writes applied after a newer user write, and per-card timelines for introduced bugs. -9. **Change the GenClass init.** Only edit `src/shared/genclass.ts` -> `startGenClass`; the mode mapping must stay identical for every demo and app code must not branch on mode. -10. **Change the results schema or aggregation.** `ModeSummary` feeds three consumers: `trials-panel.ts` -> `renderTable`, `eval.ts` -> `mdTable`/`mdDemo`/`writeReports`, and `landing.ts` -> `results` (its local `ResultsFile` type reads `demos.<id>.<mode>.chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`). Keep those fields or update all three; an old `results-summary.json` keeps shipping until an untagged eval replaces it. -11. **Change the activity panel or devtools wiring.** Use only `Report`, `Decision`, `ActionRecord`, `Explanation` fields from the public types; if you add a decision bucket, match on `Decision.reason` text from `packages/runtime/src/decide/` and expect it to drift. Theme changes must dispatch `gc-theme` so the devtools overlay remounts. -12. **Fix the world-clock offset (if wanted).** Either move `link.hello(...)` in `bootTrial` after the `gc.ready` wait, or start scripted activity from a world action sent at `TrialHarness.begin()`. Then re-run all modes and both kinds; numbers are not comparable with the shipped `results.*`. +7. **Evaluate a new model (ask first).** `GENCLASS_MODEL_FROM=<release dir url> bash demos/scripts/vm-eval.sh --tag <name>` (or `GENCLASS_MODEL_URL=<url>|cdn`). Tagged runs write `results-<tag>.*` and do not replace the shipped results; untagged runs replace `results.json/.md/-summary.json` and the landing page numbers. Check `model.card` and `runtimeBuild` in the JSON. The planned rerun (`OPEN_TASKS.md` item 10, `HANDOFF.md` step 3) uses the trained situation-v2 model on the v2 runtime; when it lands, also update `demos/README.md` "Latest results", `NEEDS.md`, `docs/runtime/RESULTS.md` §5 and the results section of this doc. `vm-eval.sh`'s default `GENCLASS_MODEL_FROM` is still the v0.1 release. +8. **Investigate a hold-induced regression (ask first).** Run `eval.ts --trace --demos board --modes off,guard,heal --tag <t>` (and a second Off-only run for A/A), then `node --experimental-strip-types e2e/trace-report.ts e2e/.out/traces-<t>.json [e2e/.out/traces-<offB>.json]`. It reports held writes, median holds, held writes applied after a newer user write, and per-card timelines for introduced bugs. This is how `NEEDS.md` §1 was found on batch 3; on the v2 runtime it only detects store-write holds (`policy.holdWrites: true`), see the trace-report gotcha in [Invariants](#invariants-and-gotchas). +9. **Make the in-page runner visible to the v2 runtime (optional, changes what Guard/Heal see in panel trials).** Pass `observe: { untrustedEvents: true }` from `startGenClass` only on trial pages driven by the synthetic driver (it is a harness option documented for this, `packages/runtime/src/types.ts` -> `InitOptions.observe`), identically in all three modes. The Playwright eval uses trusted input and is unaffected either way. Not done at b435acb. +10. **Change the GenClass init.** Only edit `src/shared/genclass.ts` -> `startGenClass`; the mode mapping must stay identical for every demo and app code must not branch on mode. +11. **Change the results schema or aggregation.** `ModeSummary` feeds three consumers: `trials-panel.ts` -> `renderTable`, `eval.ts` -> `mdTable`/`mdDemo`/`writeReports`, and `landing.ts` -> `results` (its local `ResultsFile` type reads `demos.<id>.<mode>.chaos.{rate,k,n}`, `falseInterventions`, `cleanTrials`, `decisionP50`, `actions`, plus `model.note`, `trials`, `generatedAt`). Keep those fields or update all three; an old `results-summary.json` keeps shipping until an untagged eval replaces it. +12. **Change the activity panel or devtools wiring.** Use only `Report`, `Decision`, `ActionRecord`, `Explanation` fields from the public types; if you add a decision bucket, match on `Decision.reason` text from `packages/runtime/src/decide/` and expect it to drift. Theme changes must dispatch `gc-theme` so the devtools overlay remounts. +13. **Fix the world-clock offset (if wanted).** Either move `link.hello(...)` in `bootTrial` after the `gc.ready` wait, or start scripted activity from a world action sent at `TrialHarness.begin()`. Then re-run all modes and both kinds; numbers are not comparable with the shipped `results.*`. ## Tests @@ -463,78 +471,82 @@ There are no unit tests under `demos/`. The oracles and the eval are the tests; | `src/demos/decisions/oracle.ts` | every answer equals the ground truth recomputed at ask time (health within ±1 level) | | `e2e/eval.ts` | runs every oracle with real input in all modes; warm-up checks that pages reach cross-origin isolation (a failure is only logged, the run continues); screenshot tour exercises the interactive pages and the in-page runner | | `npm run typecheck` | `tsc` over `tsconfig.json`, `tsconfig.sw.json`, `tsconfig.node.json` (needs `packages/runtime/dist/*.d.ts` and the missing `src/server/data/cities.ts`) | -| `npm run typecheck:shim` | the same against the shim | +| `npm run typecheck:shim` | the same against the shim (fails at b435acb, see [Drift](#drift-and-open-issues) item 11) | | `e2e/eval.ts` -> `shootTrialsUI` | the in-page runner (iframes, synthetic events) on `search`, Guard page, selector set to 3 (3 chaos + 2 clean seeds per mode, 15 trials) finishes within 900 s; logs row and error counts (not a pass/fail gate: a timeout is caught and logged) | | `e2e/trace-report.ts` | diagnostic only: quantifies held writes and write reordering on traced board/search runs | | `scripts/vm-eval.sh` | end-to-end gate: refuses to evaluate when `@genclass/runtime` does not build (unless `ALLOW_BROKEN_RUNTIME=1`) | -### Results so far (v0.1 model, not trained for runtime decisions) +### Results so far (frozen batch-3 runtime, v0.1 model not trained for runtime decisions) -Source: `demos/results.md` / `results-summary.json`, generated 2026-10-07T19:30:09Z, 810 trials (6 demos × 3 modes × (30 chaos + 15 clean)), seeds chaos 1000–1029, clean 1500–1514, Playwright real input, model "GenClass v0.1 (self-hosted copy)" on WASM q8, all 540 Guard/Heal runs cross-origin isolated, 0 errored trials. +Source: `demos/results.md` / `results.json` / `results-summary.json` (commit 04a264f), generated 2026-10-08T00:49:05Z, 810 trials (6 demos × 3 modes × (30 chaos + 15 clean)), seeds chaos 1000–1029, clean 1500–1514, Playwright real input, `runtime: "real"`, `runtimeBuild` `@genclass/runtime` 0.1.0 dist `5155180d4baf` (batch 3, commit 1a77558 per `NEEDS.md`), `model.card` `genclass-model` 0.1.0 q8 (`genclass-q8.onnx`, 56.9 MB) self-hosted, `policy: "runtime defaults"`; all 540 Guard/Heal trials cross-origin isolated with model status `ready`; 0 errored trials. **This runtime predates batch 4 and situation-v2; nothing here has been re-measured on b435acb.** | Demo | Bug rate Off | Guard | Heal | False interventions Guard / Heal | Fixed/introduced Guard; Heal | User latency p50 clean Off / Guard / Heal | Decision p50 Guard / Heal | |---|---|---|---|---|---|---|---| -| search | 13% (4/30) | 13% | 13% | 0 / 0 | 0/0; 0/0 | 14 ms / 125 ms / 126 ms | 481 / 495 ms | -| editor | 83% (25/30) | 83% | 87% | 0 / 0 | 1/1; 0/1 | 779 / 775 / 783 ms | 333 / 340 ms | -| checkout | 83% (25/30) | 90% | 90% | 0 / 0 | 0/2; 0/2 | 205 / 204 / 206 ms | 363 / 366 ms | -| status | 100% (30/30) | 93% | 100% | 0 / 0 | 2/0; 0/0 | 1.33 / 1.26 / 1.28 s | 1.20 / 1.25 s | -| board | 50% (15/30) | 77% | 73% | 0 / 0 | 1/9; 2/9 | 19 / 31 / 33 ms | 346 / 360 ms | -| decisions | 83% (25/30) | 90% | 93% | 0 / 0 | 3/5; 2/5 | 0 / 151 / 157 ms | 308 / 304 ms | +| search | 23% (7/30) | 23% | 27% | 0 / 0 | 1/1; 2/3 | 10 ms / 234 ms / 335 ms | 805 / 791 ms | +| editor | 83% (25/30) | 90% | 87% | 0 / 0 | 1/3; 2/3 | 784 / 783 / 783 ms | 505 / 499 ms | +| checkout | 70% (21/30) | 77% | 83% | 0 / 0 | 1/3; 0/4 | 207 / 211 / 215 ms | 581 / 503 ms | +| status | 100% (30/30) | 100% | 100% | 0 / 0 | 0/0; 0/0 | 1.32 / 1.66 / 1.54 s | 1.75 / 1.78 s | +| board | 57% (17/30) | 63% | 77% | 0 / 0 | 3/5; 2/8 | 10 / 27 / 26 ms | 1.10 / 1.14 s | +| decisions | 83% (25/30) | 97% | 97% | 0 / 0 | 1/5; 1/5 | 0 / 215 / 219 ms | 413 / 424 ms | -How to read it (aggregated from `results.json` `raw`): +How to read it (aggregated from `results.json` `raw` unless noted): - Off is bug-free on all clean runs and fails often under chaos: the latent bugs are real. -- Chosen but not run (all modes): below a threshold 958 (reason "below the guard threshold" 730 + "below the heal threshold" 228), arrived after the hold budget 663, "guard mode does not allow heal-tier actions" 277. Diagnoses: `unusual` 6,328, `inconsistent` 58, never `expected`, so the "diagnosis ≠ expected" gate never blocked. -- Guard executed nothing. Heal executed 92 actions: `retry` 30 (decisions 10, board 9, editor 8, checkout 3), `block` 62 (60 of the decisions heartbeat `GET /api/ping`, 2 editor autosaves `PUT /api/notes/:id`). No Heal bug rate dropped below Off. -- Status Guard 100% -> 93% came without any action; the README's explanation (held requests spaced out the immediate retries) is a hypothesis, not traced. -- Holds cost latency (search clean p50 14 -> 125 ms) and introduced board bugs (9/30); `NEEDS.md` §1 attributes the board effect to the write-ordering issue using traced runs from a later runtime (batch 3), not this run. -- Decisions: accuracy under chaos 0.42 (defaults) -> 0.62 (Guard) / 0.59 (Heal); on clean runs 1.00 -> 0.27 (Guard and Heal clean bug rate 15/15): v0.1 answers as if something were always wrong. -- Fixed/introduced are noisy: read them against A/A flips (1/30 on the board after CRN). Wilson 95% intervals are in `results.md`. -- These numbers measure the runtime, integration and harness, not the runtime-specialist model; re-run with the trained model is `OPEN_TASKS.md` item 6. +- 5,855 decisions in all. Diagnoses: `unusual` 5,729, `inconsistent` 126, never `expected`, so the "diagnosis ≠ expected" gate never blocked. Chosen but not run: below a threshold 1,029 (guard threshold 894, of which "(discard, defer) is below the guard threshold" 854; heal threshold 135), "guard mode does not allow heal-tier actions" 415, and **0** "arrived after the hold budget" (the previous run had 663). +- Guard executed **nothing** in any demo and still worsened editor, checkout, board and decisions (for decisions through v0.1's `ask`/`decide` answers, not holds, per `NEEDS.md` §1). Heal executed 156 actions, all on chaos runs: `block` 124 (decisions 92, checkout 13, status 12, editor 5, board 2), `retry` 29 (decisions 14, editor 9, checkout 4, status 1, board 1), `serve_cached` 3 (decisions 2, status 1). `NEEDS.md` §5 breaks the blocks down by route (88 decisions heartbeat `GET /api/ping`, 5 `POST /api/orders`, 8 `POST /api/cart/lines`, 5 `PUT /api/notes/:id`, 4 `PUT /api/journal`, 2 board moves) and notes 1 retried non-idempotent `POST /api/cards/:id/move`. +- The harm with zero actions is the store-write hold mechanism (`NEEDS.md` §1, from separate traced runs of the same seeds): board Guard 408 of 1,081 writes held (median 681 ms), 50 held writes applied after a newer user move of the same card, 11 visibly put it back, jump-backs 3.07 -> 4.80 per session, stuck "syncing" 6 -> 9; editor 37 held save echoes rewrote newer keystrokes; checkout 24 confirmations reset quantities. A/A (Off twice) flips 1 board seed of 30. +- Latency: holds delayed search results on clean runs (p50 10 -> 234 ms Guard, 335 ms Heal; `NEEDS.md` §2's traced run: 6 -> 389 ms, 127 of 148 result writes held, decisions queueing 504 -> 941 ms within a session); status cards react 0.2–0.3 s later (clean p50 1.32 s Off -> 1.66 s Guard / 1.54 s Heal). +- Decisions demo: accuracy under chaos 0.37 (app defaults) -> 0.61 (Guard) / 0.60 (Heal); on clean runs 1.00 -> 0.27 (Guard and Heal clean bug rate 15/15): v0.1 answers as if something were always wrong. +- The previous run (2026-10-07T19:30Z, 654d822 doc) is superseded; its numbers (e.g. status Guard 93%, board Guard 77%) were from an older runtime and an eval without `runtimeBuild`. +- These numbers measure the batch-3 runtime, integration and harness, not the runtime-specialist model. `docs/runtime/RESULTS.md` §4's v2 "Demos" cell (holds only at delivery; clean typeahead makes 0 model calls and holds 0 ms) comes from runtime unit tests (`packages/runtime/test/delivery.test.ts`, "typeahead zero calls" per `packages/runtime/STATUS.md`), not from a demos eval run; on the demos themselves it is unmeasured. ## Drift and open issues -Doc-vs-code mismatches: - -1. **`demos/src/server/data/cities.ts` is missing from the repo.** Imported by `src/server/worlds/search.ts`, `src/demos/search/scenario.ts`, `src/demos/search/oracle.ts`; `git check-ignore -v` attributes it to the root `.gitignore` pattern `data/`; it never appears in `git log --all`. The SW bundle (imports all worlds) and the search page cannot build from a clean clone. -2. **Hold budget "300 ms".** `demos/README.md` (results text and "Model decision p50" bullet), `src/shared/settings.ts` -> `holdBudget` comment and `e2e/eval.ts` (`policy.note`, results header) say the default is 300 ms. HEAD runtime default is `"auto"` = clamp(1.5 × median, 150, 800) with 300 only as fallback (`packages/runtime/src/decide/policy.ts`). The shipped results were measured when the default was a fixed 300 ms (commit 353b0a4 `holdBudgetMs ?? 300`); `NEEDS.md` and `harness.ts` already assume the 800 ms ceiling. -3. **Shipped results predate the current eval and runtime.** `results.json` has no `model.card` or `runtimeBuild` (README says the card is recorded there); `results.md` "How to reproduce" differs from what `eval.ts` writes now; `screenshots/` lacks `decisions-heal.png`. Results were generated 19:30Z, before commits a53dd38 and 1a77558 (batch 3); `NEEDS.md`'s traced numbers (board Guard 19/30) come from a different, later run than `results.md` (23/30). -4. README says the harness waits for quiet + 2.5 s; for `status` (`settle: false`) there is no quiet wait and only 350 ms. -5. UI copy in `src/shared/demos.ts`: board "beyond a 1 s grace" (code: 1.5 s window, bug at > 2 s); status "beyond one poll of grace" (code: 3.5 s grace); decisions "Bug rate = share of wrong decisions" (code: a trial is a bug when any one decision is wrong, so bug rate is the share of trials with at least one wrong decision; per-decision accuracy is the `accuracy` metric). Its header also claims it is imported by `vite.config.ts` and injected at build time; it is not. -6. `src/demos/status/scenario.ts` comment says incidents are the same in clean and chaos runs of a seed; the RNG label includes `kind`, so they differ. -7. `eval.ts` options `--trace`, `--kinds`, `--base`, `--port`, `--trial-timeout`, `--out` are not listed in the README or the file header. -8. The runtime shim is behind the `Runtime` interface: `ShimRuntime implements Runtime` lacks `adapter()`, `holdBudgetMs()` and `situationBudget()` (`packages/runtime/src/types.ts` -> `Runtime`), so `npm run typecheck:shim` likely fails (unverified). The shim's `GenClassUnavailableError(message)` also lacks the real class's `reason` field (`"off" | "error" | "timeout" | "destroyed"`, `packages/runtime/src/errors.ts`). -9. README example `GENCLASS_MODEL_URL=https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/` lacks the `files/` suffix of the runtime's `DEFAULT_MODEL_BASE_URL`; the model package is not published yet (`OPEN_TASKS.md` item 8), so `?model=cdn` currently cannot load a model. -10. README results table shows decisions latency "–"; `results.md` has 0 / 151 / 157 ms. -11. README ("Latest results") says the default redaction hides the board's `cards` from the model "(§2)". In `NEEDS.md` redaction is §3 and is marked resolved in batch 3; the README sentence describes the pre-batch-3 measured run and points at the wrong section. -12. README "Files" block and the `eval.ts` header omit `e2e/trace-report.ts`. -13. Not drift but an open risk found while reviewing: the world-clock offset between Off and Guard/Heal trials (see [Invariants](#invariants-and-gotchas)); none of `README.md`, `NEEDS.md` or `results.md` mention it. - -Open `NEEDS.md` items for CORE (checked against HEAD): - -| § | Item | State at 654d822 | +Doc-vs-code mismatches (checked at b435acb): + +1. **`demos/src/server/data/cities.ts` is missing from the repo.** Imported by `src/server/worlds/search.ts`, `src/demos/search/scenario.ts`, `src/demos/search/oracle.ts`; `git check-ignore -v` attributes it to the root `.gitignore` pattern `data/`. The SW bundle (imports all worlds), the search page and `npm run typecheck` cannot succeed from a clean clone; nor can the root `npm run typecheck` (`--workspaces --if-present` includes the demos). Checked 2026-10-08: `tsc -p demos/tsconfig.json --noEmit` against the built v2 runtime reports only the three missing-module errors plus two implicit-type errors that follow from them (`search/oracle.ts`, `search/scenario.ts`); every other demos file type-checks against the v2 public API. CI is unaffected (it type-checks `@genclass/runtime` only). Still open. +2. **Shipped results are from the batch-3 runtime.** `results.*`, `README.md` "Latest results (frozen runtime batch 3 …)", `NEEDS.md` (header: "Runtime: frozen batch 3 (commit 1a77558)") and `docs/runtime/RESULTS.md` §5 all describe store-write holds that the v2 runtime no longer does by default. The landing page ships these numbers via `results-summary.json`. Needs a rerun once a situation-v2 model exists. +3. **In-page runner invisible to the runtime.** `NEEDS.md` §7 asks CORE to keep observing synthetic DOM events; batch 4 made that opt-in (`observe.untrustedEvents`, default `false`) and `startGenClass` does not opt in. `NEEDS.md` §7 and the in-page panel's copy were not updated. Fix: [How to change it safely](#how-to-change-it-safely) step 9. +4. **"Default" wording after f3636b2.** `src/shared/genclass.ts` header comment ("guard … (the default)"), `src/site/landing.ts` -> `modes` (Guard card `badge: "default"`, and "the default mode only takes actions that withhold …") and the runtime shim (`src/dev/runtime-shim/index.ts` -> `ShimRuntime` constructor `opts.mode ?? "guard"`) still say Guard is the default; the runtime default is now `observe`. The demo site's own default (`getMode` -> `guard`) is a separate, intentional choice. +5. **Hold budget "300 ms".** `demos/README.md` ("How it works" bullet: "`holdBudgetMs` (300 ms)"), `src/shared/settings.ts` -> `holdBudget` comment and `e2e/eval.ts` (`policy.note` "raised from the default 300 ms", results header with `--budget`) say the default is 300 ms. The runtime default is `"auto"` = clamp(1.5 × median, 150, 800) with 300 only as fallback. The README results section itself now says "auto" reaches 800 ms. +6. **`e2e/trace-report.ts` and the activity panel assume batch-3 semantics** (store-write holds; reason strings). See [Invariants](#invariants-and-gotchas). +7. README says the harness waits for quiet + 2.5 s; for `status` (`settle: false`) there is no quiet wait and only 350 ms. +8. UI copy in `src/shared/demos.ts`: board "beyond a 1 s grace" (code: 1.5 s window, bug at > 2 s); status "beyond one poll of grace" (code: 3.5 s grace); decisions "Bug rate = share of wrong decisions" (code: a trial is a bug when any one decision is wrong). Its header also claims it is imported by `vite.config.ts` and injected at build time; it is not. +9. `src/demos/status/scenario.ts` comment says incidents are the same in clean and chaos runs of a seed; the RNG label includes `kind`, so they differ. +10. `eval.ts` options `--base`, `--port`, `--trial-timeout`, `--out` are still not in the README (which now lists `--kinds` and `--trace`); the `eval.ts` header comment lists neither those nor `--trace`, `--kinds`, `--tag`, `--budget`, `trace-report.ts`. +11. The runtime shim is behind the public types, and `npm run typecheck:shim` fails (checked 2026-10-08 with `tsc -p demos/tsconfig.shim.json --noEmit`): `ShimRuntime implements Runtime` lacks `adapter()`, `holdBudgetMs()` and `situationBudget()` (`packages/runtime/src/types.ts` -> `Runtime`), and its `situation()` return lacks `Situation.compact` and `Situation.budget`; the cities.ts errors of item 1 come on top. These members already existed at 654d822, so the gap predates v2. The shim's `GenClassUnavailableError(message)` also lacks the real class's `reason` field (`packages/runtime/src/errors.ts`), and its constructor still defaults `mode` to `"guard"` (item 4). +12. README example `GENCLASS_MODEL_URL=https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/` lacks the `files/` suffix of the runtime's `DEFAULT_MODEL_BASE_URL`; `@genclass/runtime-model` is not published (npm 404), so `?model=cdn` and `--model cdn` cannot load a model. The README's re-run recipe uses a placeholder `https://…/runtime-model-v0.1.0/`. +13. README results table shows decisions latency "–"; `results.md` has 0 / 215 / 219 ms. +14. Not drift but an open risk: the world-clock offset between Off and Guard/Heal trials (see [Invariants](#invariants-and-gotchas)); none of `README.md`, `NEEDS.md` or `results.md` mention it. The current run's model load (median ~1.6 s) makes it larger than in the previous run. + +Resolved since 654d822: `results.json` now records `model.card` and `runtimeBuild`; `results.md` "How to reproduce" matches `eval.ts`; `screenshots/decisions-heal.png` exists; `NEEDS.md`'s traced board numbers (Guard 19/30) match `results.md`; the README no longer cites the wrong redaction section and now lists `e2e/trace-report.ts` in its Files block; the `auth` redaction gotcha no longer applies. + +`NEEDS.md` items for CORE vs the code at b435acb: + +| § | Item | State at b435acb | |---|---|---| -| 1 | A held write lands after the user's newer write (board jump-backs +56%, 9 introduced bugs) | **open**: `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` still commits user-sync bypass writes immediately while earlier writes wait in `s.queue`; see [state-and-adapters](runtime/state-and-adapters.md) | -| 2 | Holds cost interactive latency while the model is slower than the budget; decision requests queue | **open**: holds depend only on `mayHold` (`consultable() && mode !== "observe"`), no latency-based skip or superseded-request drop | -| 3 | Redaction of ordinary fields (`board.cards`) | resolved in batch 3 (word-level `isSensitiveName`); note the new `auth` segment case above | +| 1 | A held write lands after the user's newer write (board jump-backs 3.07 -> 4.80, editor 37 overwritten keystrokes, checkout 24 reset quantities) | **addressed in code, unmeasured on demos**: batch 4 made store-write holds opt-in (`policy.holdWrites`, default `false`; when on, `StoreHub` flushes the queue before a user write and reads see pending writes). See [state-and-adapters](runtime/state-and-adapters.md) | +| 2 | Holds cost interactive latency while the model is slower than the budget; decision requests queue | **largely addressed, unmeasured**: store writes are no longer held by default; holds remain at the `request`, fetch `failure` and new `delivery` triggers, and any hold is skipped when `expectedLatency() > holdBudgetMs()` (`packages/runtime/src/runtime.ts` -> `trigger`; `expectedLatency` counts the decisions queued ahead). Superseded queued requests are dropped: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue.pump` resolves `null` for an item whose `stale()` is true (a write no longer the last one on its fields, or a delivery already released; `runtime.ts` -> `mutationController`, `runDelivery`). Not done: a lower ceiling for writes the user waits on (`HOLD_MAX_MS` is still 800) | +| 3 | Redaction of ordinary fields (`board.cards`) | resolved in batch 3; leaf-based since (see Invariants) | | 4 | Demos-side fixes (CRN, native timers) | done, for the record | -| 5 | `retry` offered for non-idempotent requests | **open**: `packages/runtime/src/situation/build.ts` -> `builtinApplicable` offers `retry` for any replayable fetch with `attempt < 4`; idempotency is only a fact | -| 6 | Observe EventSource (and BroadcastChannel) messages as ops | **open**: no EventSource observer in `packages/runtime/src/observe/` | -| 7 | Keep observing synthetic DOM events | satisfied: `observe/dom-user.ts` keeps untrusted events unless an app op is running | -| 8 | Notes on the v0.1 model | informational | +| 5 | Heal acts on non-idempotent writes (`block` of user writes, `retry` of a POST) | **open**: `packages/runtime/src/situation/build.ts` -> `builtinApplicable` still offers `retry` for any replayable fetch with `attempt < 4` (no idempotency check), and `block` stays in the `request` trigger's action list (`packages/runtime/src/situation/questions.ts`) with no exception for user-initiated writes | +| 6 | Observe EventSource (and BroadcastChannel) messages as ops | **EventSource done** (`packages/runtime/src/observe/eventsource.ts`, observer name `eventsource`; messages pass the delivery gate in stream order); BroadcastChannel: no observer found | +| 7 | Keep observing synthetic DOM events | **changed**: opt-in via `observe.untrustedEvents` (default `false`); the demos do not opt in (drift item 3) | +| 8 | Notes on the v0.1 model | informational; superseded once a v2 model exists | -Other open items: `OPEN_TASKS.md` item 2 (demos in progress), item 6 (re-evaluate with the trained model; investigate hold-induced harm and triage sensitivity on typeahead, salient about 6 times per clean trial), and "Needs the user: public demo hosting (GitHub Pages) OK to publish?". +Other open items: `OPEN_TASKS.md` item 2 (demos) and item 10 (rerun with the trained model), and "Needs the user: public demo hosting (GitHub Pages) OK to publish?". `HANDOFF.md` orders the demos rerun after `@genclass/runtime-model@0.1.0` and before `@genclass/runtime@0.1.0`. ## Related docs - [demos/README.md](../../demos/README.md), [demos/NEEDS.md](../../demos/NEEDS.md), [demos/results.md](../../demos/results.md) -- [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) (§0 ground rules, §12 demos, §13 hooks) -- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `GenClass.init`, options, kill switch -- [runtime/state-and-adapters.md](runtime/state-and-adapters.md): holds, `propose` ordering risk, React/Redux/Zustand adapters, redaction -- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): policy gate, thresholds, hold budget, `retry`/`block`, late revert -- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): DOM/fetch/timer observers, ops +- [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) (§0 ground rules, §12 demos, §13 hooks), [docs/runtime/RESULTS.md](../runtime/RESULTS.md) (§4 "never worse" design comparison, §5 demos), [HANDOFF.md](../../HANDOFF.md), [OPEN_TASKS.md](../../OPEN_TASKS.md) +- [realapps.md](realapps.md): the real-app corpus (91 apps at b435acb, headless Chromium) whose interference sweep over the 66 apps then in it measured the v2 runtime's "never worse" property; independent from the demos by rule (`realapps/apps/README.md`: never read `demos/`) +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `GenClass.init`, options (default mode `observe`, `observe.untrustedEvents`), kill switch +- [runtime/state-and-adapters.md](runtime/state-and-adapters.md): `holdWrites`, ordering, React/Redux/Zustand adapters, redaction +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): policy gate, thresholds, hold budget, `delivery` trigger, `retry`/`block`, late revert +- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): DOM/fetch/timer/EventSource observers, ops - [runtime/model-host.md](runtime/model-host.md): model loading, `fetch-model` CLI, WASM threads - [runtime/devtools.md](runtime/devtools.md): the overlay mounted by the demo page -- [runtime/build-test-release.md](runtime/build-test-release.md): workspace build order, `scripts/vm.sh` +- [runtime/build-test-release.md](runtime/build-test-release.md): workspace build order, CI, `scripts/vm.sh` - [sim.md](sim.md) (independent from demos by rule), [model-io-contract.md](model-io-contract.md), [training.md](training.md) - [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [playbooks.md](playbooks.md), [repo-map.md](repo-map.md), [overview.md](overview.md), [../../AGENTS.md](../../AGENTS.md) diff --git a/docs/agents/extension-and-benchmarks.md b/docs/agents/extension-and-benchmarks.md index f2848609..400ce695 100644 --- a/docs/agents/extension-and-benchmarks.md +++ b/docs/agents/extension-and-benchmarks.md @@ -2,18 +2,20 @@ > **Scope:** `extension/**`, `bench/**`, `jev_local/bench/**`, `BENCHMARKS.md`, `results/**`, `scripts/**`, `docs/benchmax-research/**` (summarised). > **Read this when:** you touch the GenClass voice-control Chrome extension; you need to know where the runtime's model engine/packer/tokenizer came from and how parity was proven; you run, extend or quote a benchmark (jevbench, benchmax, the computer-use head-to-head); you need to know what a script in `scripts/` does and whether it touches Azure, money or secrets. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> +> **What changed since 654d822:** nothing under `extension/`, `bench/`, `jev_local/bench/`, `BENCHMARKS.md`, `results/`, `scripts/` or `docs/benchmax-research/` (`git diff --stat 654d822 b435acb` over those paths is empty). What changed is who calls into this area: three new training launchers (`training/{launch_student,launch_t150,launch_r68}.sh`) call `scripts/launch_run.sh`, the new `training/cluster_expand.sh` reuses `scripts/cluster_up.sh`'s VM settings, the new `realapps/` README builds and pilot-runs through `scripts/vm.sh` (slot `real`; its cluster-scale runs use `realapps/scripts/cluster.sh`, which does its own ssh/rsync and calls nothing in `scripts/`), and the new CI workflow (`.github/workflows/ci.yml`) covers only `@genclass/runtime`, not the extension or any Python here. ## TL;DR - **This whole area is adjacent/legacy relative to `@genclass/runtime`.** It is the pre-runtime GenClass project (the "jev-local" era): a voice-controlled MV3 Chrome extension (GenClass 0.1.0), the Python benchmark harnesses that compared the model with TypeSafe's hosted Jev, and the Azure/Mac ops scripts. `docs/runtime/CONTRACT.md` says "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." -- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh` and the `training/README.md` recipes to start multi-node torchrun jobs) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the `runtime-model-v0.1.0` release of GenClass-lib; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. +- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it, and `realapps/README.md` runs the realapps build, debug runs and pilot generator through it with slot `real`, see [realapps.md](realapps.md); our CI and the lead's local checks on a 16 GB machine do not use it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh`, and (new since 654d822) `training/launch_student.sh`, `training/launch_t150.sh` and `training/launch_r68.sh`, plus the `training/README.md` recipes, to start multi-node torchrun jobs), `scripts/cluster_up.sh` (whose VNet/subnet/NSG/PPG/image/key settings `training/cluster_expand.sh` copies when it adds nodes) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the `runtime-model-v0.1.0` release of GenClass-lib (both 404 as of 2026-10-08: no situation-v2 model exists yet, and the situation-v1 R17-final1 does not match the v2 runtime; see [status-and-known-issues.md](status-and-known-issues.md)). The v0.1 extension model reads the extension's own `state` serialisation, not runtime situation text (v1 or v2), so it is useful only for engine/packer/loader mechanics, never for decision quality; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/realapps/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. - **Extension architecture:** service worker (`src/background/sw.js`: tabs, navigation, feature plumbing) + offscreen document "brain" (`src/offscreen/offscreen.js`: model, speech, decision loop) + content script (`src/content/content.js`: page observation, in-page actions, ad hiding) + side panel (`src/sidepanel/panel.js`: view + settings). Pure-JS decision logic lives in `src/core/`: `types`, `catalog`, `questions`, `state`, `spans`, `stream`, `policy`, `safety` and `controller` port the Python macOS harness `jev_local/harness/*`; `tokenizer`, `packer` and `engine` port `jev_local/engine/encoder/{tokenize_pack,engine,calibrate}.py` plus `jev_local/confidence.py`; `serialize` ports `jev_local/serialize.py`; `features`, `sites` and the numbered-pick/rescue code are GenClass-only additions. - **The model is asked typed questions** (choice / noul / score) about a `state` object (screen, focused element, recent actions, pending, transcript). Questions are block-isolated in the attention mask, so the extension asks in two exact stages (intent/complete/is_command/destructive first, then only the argument question the intent needs). - **Mid-sentence acting is safe** because of a consumed-prefix transcript cursor (`core/stream.js` -> `Stream`), stability gates (`core/policy.js` -> `evaluatePolicy`), deterministic safety rules plus spoken confirmation (`core/safety.js` -> `gate`), and a 3 actions/s rate limit. - **Benchmarks** come in three generations: the computer-use head-to-head vs Jev (`results/genclass-vs-jev-computer-use.md`, summarised in `BENCHMARKS.md`); **jevbench v1** (25 public datasets, pre-registered in `bench/PREREG-jevbench.md`, release read M0 in `results/jevbench-m0.md`, Jev pass blocked by billing); **benchmax** (549 published Jev numbers, 154 counted; 19 publisher-harness adapter specs; pre-registered draft in `bench/PREREG-benchmax.md`; no test-split scoreboard exists in the repo). - **Headline numbers:** v1 32M model beats Jev on mid-sentence intent (90.4% vs 66.4%, n=664) and typed span (94.9% vs 75.5%, n=98); Jev wins on held-out generic questions (94.7% vs 80.5%, n=451) and AG News (0.882 vs 0.315). jevbench M0 skill index for v1 = 10.1 [9.7, 10.7]. -- **Rules that bind anyone touching this area:** the original team rule (CONTRACT §0 rule 5) was that the Mac only edits files. Under the current agent policy ([../../AGENTS.md](../../AGENTS.md) §4), nothing in this area runs without the user's OK (extension `npm ci`/`npm test`/e2e, Python tests, benchmarks, `scripts/*`); Jev outputs are evaluation-only; OpenRouter/Jev calls cost real money (lifetime cap $5 per the benchmax PLAN) and need the user's OK; benchmark test splits are read once per release. +- **Rules that bind anyone touching this area:** the original team rule (CONTRACT §0 rule 5, repeated in `HANDOFF.md`) was that the colleague's 8 GB Mac only edits files; that rule is about that machine. The current agent policy ([../../AGENTS.md](../../AGENTS.md) §4) requires the user's OK for Playwright (which includes the extension's e2e), model downloads and any script that touches Azure (`scripts/*.sh`); nothing else in this area (extension `npm ci`/`npm test`, the Python tests, `scripts/*.py`, benchmarks) is in the verified command set either, so ask first; Jev outputs are evaluation-only; OpenRouter/Jev calls cost real money (lifetime cap $5 per the benchmax PLAN) and need the user's OK; benchmark test splits are read once per release. ## Files @@ -21,7 +23,7 @@ | path | role | key exports / entry points | |---|---|---| -| `extension/README.md`, `MODEL_CARD.md`, `RELEASE.md`, `NOTICE`, `LICENSE` | product docs, model card, manual release checklist, third-party notices, Apache-2.0 text | — | +| `extension/README.md`, `MODEL_CARD.md`, `RELEASE.md`, `NOTICE`, `LICENSE` | product docs, model card, manual release checklist (legacy extension checklist; not the runtime release procedure in the root `RELEASE.md`), third-party notices, Apache-2.0 text | — | | `extension/package.json` (+ own `package-lock.json`) | scripts `build`, `package`, `test`, `test:e2e`; deps `onnxruntime-web ^1.31.0-dev.20260914-8d85527a0`, `@huggingface/transformers ^4.3.0`; dev `@playwright/test ^1.63.0`, `esbuild ^0.28.2` | not in root `package.json` `workspaces` | | `extension/static/manifest.json` | MV3 manifest; `minimum_chrome_version` 116; permissions `sidePanel offscreen storage scripting alarms system.memory`; host `<all_urls>`; `content.js` declared as a content script for `http://*/*` and `https://*/*` at `document_idle` (tabs opened before install get it via `sw.js` -> `ensureContent`); commands `toggle-listening` (Alt+Shift+G), `kill-switch` (Alt+Shift+K); CSP `script-src 'self' 'wasm-unsafe-eval'`; COEP `require-corp`, COOP `same-origin` | — | | `extension/static/{panel.html,panel.css,offscreen.html,welcome.html,audio-worklet.js,icons/}` | pages, styles, mic AudioWorklet (`genclass-capture`, posts 1600-sample = 100 ms chunks) | — | @@ -108,12 +110,12 @@ | script | purpose | where it runs | Azure? | notes | |---|---|---|---|---| -| `azvm.sh` | `azvm.sh HOST 'cmd'` (ssh), `--put LOCAL REMOTE` (single-file scp), `--get REMOTE LOCAL` (recursive scp), `--sync` (rsync `--delete` of `jev_local scripts tests pyproject.toml` to `~/jev/`) for a named VM from `~/.jev-local/azure_hosts` (user `azureuser`, key `~/.ssh/jev_azure`) | Mac | yes | used by most other ops scripts and by `training/*.sh`; **no timeout of its own** (a `TIMEOUT=` prefix is ignored); `--sync` does **not** copy `bench/` or `docs/` | +| `azvm.sh` | `azvm.sh HOST 'cmd'` (ssh), `--put LOCAL REMOTE` (single-file scp), `--get REMOTE LOCAL` (recursive scp), `--sync` (rsync `--delete` of `jev_local scripts tests pyproject.toml` to `~/jev/`) for a named VM from `~/.jev-local/azure_hosts` (user `azureuser`, key `~/.ssh/jev_azure`) | Mac | yes | used by most other ops scripts and by `training/*.sh` (via `$JEV/scripts/azvm.sh` in the parent-repo layout; `HANDOFF.md` names the colleague's copy `/Users/meharkhanna/jev/scripts/azvm.sh` as the ssh helper); **no timeout of its own** (a `TIMEOUT=` prefix is ignored); `--sync` does **not** copy `bench/` or `docs/` | | `vm.sh` | subcommands `sync SLOT`, `run SLOT 'cmd'` (sync then run), `exec SLOT 'cmd'` (no sync), `get SLOT REMOTE LOCAL`: rsync `-az --delete` of this repo to `~/gcl/SLOT` on VM `train` (host from `azure_hosts`), run commands in it with `$HOME/node/bin` on PATH; SLOT must match `[a-zA-Z0-9_-]+` | Mac | yes | **the runtime build/test path**; `TIMEOUT` default 1800 s per remote command (sync: 300 s mkdir + 600 s rsync; `get`: 600 s); rsync excludes `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, **`/extension/`**, `/sim/out/`, `.cache-model/`; `--delete` removes slot files that are not in your local working copy unless they are under an excluded path; model dirs under `.cache-model/` or `<slot>/models/` survive | -| `cluster_up.sh` | `cluster_up.sh NAME:SIZE …`: `az vm create` training nodes `vm-jev-<NAME>` (Ubuntu 24.04, resource group `rg-jev-train`, 256 GB Premium disk, proximity group `ppg-jev`), appends `NAME PUBLIC_IP PRIVATE_IP SIZE` to `azure_hosts`, auto-shutdown 18:00 UTC | Mac | yes **$** | serial `az` only | +| `cluster_up.sh` | `cluster_up.sh NAME:SIZE …`: `az vm create` training nodes `vm-jev-<NAME>` (Ubuntu 24.04, resource group `rg-jev-train`, 256 GB Premium disk, proximity group `ppg-jev`), appends `NAME PUBLIC_IP PRIVATE_IP SIZE` to `azure_hosts`, auto-shutdown 18:00 UTC | Mac | yes **$** | serial `az` only, no `timeout` wrapper; `training/cluster_expand.sh` (new since 654d822) creates further nodes with the same VNet/subnet/NSG/PPG/image/key (retrying without the PPG if it lacks capacity, each `az` call under `timeout`) but, instead of `az vm auto-shutdown`, adds a DevTestLab schedule (03:00 UTC) in **Disabled** state; per `training/NEEDS.md`, c12–c23 were created that way, and `HANDOFF.md` says the nightly schedules are currently disabled for the training push (re-enable when it ends) | | `vm_bootstrap.sh` | one-time Ubuntu 24.04 VM setup: venv, CPU torch, data tooling | on a VM | yes | | | `node_setup.sh` | on a fresh node: bootstrap + pull `v2_bundle.tar` from data VM `10.0.0.5:8797` | on a VM | yes | | -| `launch_run.sh` | `launch_run.sh RUN MASTER_PRIV_IP NPROC THREADS "node1 node2 …" -- <train args>`: detached (`setsid nohup nice -n 5`) multi-node `torch.distributed.run -m jev_local.train.train --ddp` over `azvm.sh`, master port 29500, env `OMP_NUM_THREADS=THREADS GLOO_SOCKET_IFNAME=eth0 JEV_ENCODER=banded TOKENIZERS_PARALLELISM=false HF_HUB_OFFLINE=1` | Mac | yes **$** | logs `~/jev/runs/<RUN>/rank<k>.out`; calls `scripts/azvm.sh` by a relative path, so run it from the repo root; reads no `TIMEOUT`; **also used by the runtime model training** (`training/launch_s2.sh`, `training/launch_final1.sh`, `training/README.md`) and by `launch_z68m.sh` / `stage1_speedtest.sh` | +| `launch_run.sh` | `launch_run.sh RUN MASTER_PRIV_IP NPROC THREADS "node1 node2 …" -- <train args>`: detached (`setsid nohup nice -n 5`) multi-node `torch.distributed.run -m jev_local.train.train --ddp` over `azvm.sh`, master port 29500, env `OMP_NUM_THREADS=THREADS GLOO_SOCKET_IFNAME=eth0 JEV_ENCODER=banded TOKENIZERS_PARALLELISM=false HF_HUB_OFFLINE=1` | Mac | yes **$** | logs `~/jev/runs/<RUN>/rank<k>.out`; calls `scripts/azvm.sh` by a relative path, so run it from the repo root; reads no `TIMEOUT`; **also used by the runtime model training** (`training/launch_s2.sh`, `training/launch_final1.sh`, `training/launch_student.sh`, `training/launch_t150.sh`, `training/launch_r68.sh`, `training/README.md`) and by `launch_z68m.sh` / `stage1_speedtest.sh` | | `launch_z68m.sh` | phase-2 benchmax Z-68m retrain: sync, distribute Z bundle (sha256 `a333fd88…`), launch 8 nodes x 4 ranks x 20 threads | Mac | yes **$** | expects `bench/public/mix_z_run.json` (not in repo) | | `stage1_speedtest.sh` | PLAN-excel stage 1: 20-step 8-node DDP timing runs, copies timing logs to `runs/stage1/<RUN>/` | Mac | yes **$** | | | `watch_runs.sh` | `watch_runs.sh INTERVAL_S "run:node …"`: poll rank-0 logs, print step/loss/tok/s, exit with `EVENT:` on DONE/ERROR/STOPPED | Mac | yes | | @@ -460,9 +462,9 @@ All are documents in the repo; none can be reproduced from the repo alone (the d - **Words are consumed once.** Any change to `consumedFor`, `Stream.consume` or the fired-key set can make an action run twice or swallow the next command. - **Fixture regeneration:** `pack_fixtures.json`/`torch_fixtures.json` come from an exporter run (`extension/tools/genclass_export.py` or the older `scripts/genclass_export.py`, whose fixture-writing code is identical; which one produced the committed files is not recorded) (torch, VM); the `*_py.json` fixtures from `extension/scripts/make_py_fixtures.py` (torch-free; it also reads `tests/fixtures/harness_cases.json` and `requests50.json`). Do not hand-edit them. - **Cache names differ:** extension `genclass-models-v1`, runtime `genclass-runtime-v1`. They never share entries. -- **Mac safety:** `scripts/vm.sh` excludes `/extension/` from its rsync, so the standard runtime VM path cannot build or test the extension; there is no script for it (see Drift). +- **Mac safety:** `scripts/vm.sh` excludes `/extension/` from its rsync, so the standard runtime VM path cannot build or test the extension; there is no script for it, and CI does not build or test it either (see Drift item 4). Running the extension's `npm ci`/`npm test`/e2e anywhere needs the user's OK. - **`vm.sh` mirrors with `rsync --delete`.** Anything you create only on the VM in `~/gcl/<SLOT>` (outside the excluded paths) is deleted on the next `sync`/`run`; that is why `demos/` keeps model directories outside the synced tree. -- **`azvm.sh` has no timeout.** Unlike `vm.sh`, it never reads `TIMEOUT`; the `TIMEOUT=… "$JEV/scripts/azvm.sh" …` prefixes in `training/{deliver_final,import_sim}.sh` and the `TIMEOUT=300 scripts/launch_run.sh …` prefixes in `training/{launch_s2,launch_final1}.sh` have no effect (`launch_run.sh` reads no `TIMEOUT` either; `training/node.sh`, default 900 s, and `vm.sh`, default 1800 s, do honour it). A hung ssh blocks until the connection drops (`ServerAliveInterval=30`, `ServerAliveCountMax=6`). +- **`azvm.sh` has no timeout.** Unlike `vm.sh`, it never reads `TIMEOUT`; the `TIMEOUT=… "$JEV/scripts/azvm.sh" …` prefixes in `training/{deliver_final,import_sim}.sh` and the `TIMEOUT=300 scripts/launch_run.sh …` prefixes in `training/{launch_s2,launch_final1,launch_student,launch_t150,launch_r68}.sh` have no effect (`launch_run.sh` reads no `TIMEOUT` either; `training/node.sh`, default 900 s, and `vm.sh`, default 1800 s, do honour it). A hung ssh blocks until the connection drops (`ServerAliveInterval=30`, `ServerAliveCountMax=6`). - **`azvm.sh --sync` copies only `jev_local scripts tests pyproject.toml`** to `~/jev/`. The benchmax adapters read `bench/public/targets.json` at run time (`runner.py` -> `TARGETS_PATH`, used by `deusser.py`, `jevbench_hf.py`, `bridge_b.py`), so the VM needs that file from some other copy (how it got there is unverified). - **Extension state lives in the offscreen document.** The undo stack (`B.undo`, max 20), the decision log and the loaded engine are module state in `offscreen.js`; if Chrome closes the offscreen document they are gone and `ensure_brain` recreates a fresh one. Only settings, `parked`, `ramFreed` and `ramStatus` persist in `chrome.storage.local`. - **The model is not a general classifier.** `MODEL_CARD.md` and `test/eval/features_eval_q8.json` (4/18 exact) show zero-shot ad/clickbait classification near chance; that is why `filter.model` is off by default and deterministic markers decide ads. Focus mode leans on keyword overlap and session use for the same reason. @@ -478,12 +480,12 @@ All are documents in the repo; none can be reproduced from the repo alone (the d 2. **Add a browser-only intent.** Add it to `catalog.js` `BROWSER_EXTRA_INTENTS`, `types.js` `Kind`, `spans.js` `NO_ARG_INTENTS` (if argument-free), `controller.js` `LEFTOVER_WORDS`, `safety.js` `IN_APP_KINDS`/risk sets as appropriate, `policy.js` `ARG_QUESTIONS` (if it reads an argument), and an executor branch in `sw.js` -> `execute` or `content.js` -> `execute`. Add an eval row to `test/eval/commands_eval.mjs`. 3. **Ship a new model in the extension.** Export on the VM with `tools/genclass_export.py --ckpt … --requests test/fixtures/requests50.json --out …`; copy `tokenizer/calibration/meta.json` into `src/model/` and `release-assets/`; update `src/model/model.json` bytes/sha256 (and `needs` if any fp16 tensor remains); copy `pack_fixtures.json`/`torch_fixtures.json` into `test/fixtures/`; run `GENCLASS_VARIANTS=q8,fp16 npm test`; then `node scripts/build.mjs --release` (it re-verifies sha256). 4. **Fix an engine/packer/tokenizer bug.** The runtime copy (`packages/runtime/src/model/`) is the maintained one; fix it there with its tests ([runtime/model-host.md](runtime/model-host.md)). Port to the extension only if the extension is still being released, and re-run `pack_parity` + `engine_parity`. -5. **Build and test the extension.** On the VM (never the Mac): get `extension/` onto the VM yourself (not covered by `scripts/vm.sh`), `npm ci`, `npm test` (unit; ONNX-dependent tests skip without `release-assets/genclass-*.onnx`), put `genclass-q8.onnx` (and `-fp16.onnx` for WebGPU) into `release-assets/` (from the v0.1.0 GitHub release, or `packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` and copy the `.onnx` files over), `npm run build`, `npm run test:e2e` (Playwright Chromium with the unpacked extension; `SWIFTSHADER=1` for software WebGPU; `speech.spec.mjs` needs network to Hugging Face). +5. **Build and test the extension.** Only with the user's OK; historically on the VM (never the colleague's 8 GB Mac): get `extension/` onto the VM yourself (not covered by `scripts/vm.sh`), `npm ci`, `npm test` (unit; ONNX-dependent tests skip without `release-assets/genclass-*.onnx`), put `genclass-q8.onnx` (and `-fp16.onnx` for WebGPU) into `release-assets/` (from the v0.1.0 GitHub release, or `packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` and copy the `.onnx` files over), `npm run build`, `npm run test:e2e` (Playwright Chromium with the unpacked extension; `SWIFTSHADER=1` for software WebGPU; `speech.spec.mjs` needs network to Hugging Face). 6. **Add a benchmax spec.** Use the exact `spec_id` string from `targets.json`; group A: a class with `add_arguments`/`verify`/`run` (subclass of `runner.py` -> `Adapter`, with `default_overflow`/`allow_truncate`) registered in `specs_a.py`; group B: a module `adapters_b/<suite>.py` with `SPEC_ID`, `TARGETS` and a class `Adapter(AdapterB)` implementing `prepare(split)`, `items(split, limit, tasks)`, `score(...)` and optionally `fit(...)`, registered in `specs_b.py` -> `SPECS_B` as `"<module>:Adapter"` (bridged automatically because `bridge_b.is_group_b_class` sees `prepare/items/score` and no `verify/run/add_arguments`). Pin every upstream commit/revision and sha256. Add pure-Python tests (`tests/test_bm_adapters_*.py`), then `scripts/benchmax.py verify --spec <id>` and a validation-split `run` on the VM. 7. **Update targets or the published-Jev list.** Edit `bench/public/jev_published.json`, run `scripts/benchmax_build_targets.py --write-registry` then `--check` (fix the feasibility-note path first), run `tests/test_bench_registry.py`; this changes frozen hashes, so write a new freeze before any test read. 8. **Score a new checkpoint on jevbench.** `scripts/jevbench.py run-ours --ckpt … --release <r>` then `score` and `report` on the VM; do not run `run-jev` without the user's OK (cost) and a funded key. 9. **Re-measure the extension's model-backed behaviour.** On the VM with `release-assets/genclass-q8.onnx` present: `node test/eval/commands_eval.mjs`, `node test/eval/features_eval.mjs`, `node test/eval/focus_heldout.mjs` (each rewrites its JSON: `commands_eval.json`, `features_eval_<variant>.json`, `focus_heldout.json`). If a threshold such as `FOCUS_MODEL_MIN` or filter `minP` changes, update the eval JSON and the README numbers together. -10. **Touch an ops script.** Keep `vm.sh`'s rsync exclusions (`/extension/`, `/models/`, `/runs/`, `/data/`, `/sim/out/`, `.cache-model/`) and `--delete` semantics in mind: every workstream depends on them. Do not change `launch_run.sh`'s argument order (`RUN MASTER NPROC THREADS "nodes" -- args`): `training/launch_s2.sh` and `training/launch_final1.sh` call it positionally. Anything that calls `az vm create/start` or OpenRouter needs the user's go-ahead. +10. **Touch an ops script.** Keep `vm.sh`'s rsync exclusions (`/extension/`, `/models/`, `/runs/`, `/data/`, `/sim/out/`, `.cache-model/`) and `--delete` semantics in mind: every workstream depends on them. Do not change `launch_run.sh`'s argument order (`RUN MASTER NPROC THREADS "nodes" -- args`): `training/{launch_s2,launch_final1,launch_student,launch_t150,launch_r68}.sh` call it positionally. Keep `vm.sh`'s slot layout too: `realapps/README.md` uses slot `real` and keeps its outputs in `~/gcl/real-out` outside the synced tree. Anything that calls `az vm create/start` or OpenRouter needs the user's go-ahead. ## Tests @@ -521,7 +523,7 @@ Run commands: extension unit tests `npm test` = `node --test --test-concurrency= 1. `docs/runtime/CONTRACT.md` §10 cites the extension engine at `extension/genclass/src/core/{engine,packer,tokenizer,serialize,pyutil,runtime}.js` "in the parent jev repo" (read-only reference `/Users/meharkhanna/jev/extension/genclass/src/`) and the card at `extension/genclass/src/model/model.json`. In this repo the path is `extension/src/core/` and there is no `runtime.js`. 2. `extension/package.json` says `"license": "MIT"`; `extension/README.md`, `LICENSE`, `NOTICE` and the store listing say Apache-2.0. 3. `extension/scripts/make_py_fixtures.py` assumes the old `extension/genclass/` layout: `ROOT = parents[3]` resolves to the directory above the repo and `OUT` is `extension/genclass/test/fixtures`. `extension/tools/genclass_export.py` usage text and `RELEASE.md` ("push the contents of `extension/genclass/`") have the same stale path. -4. `scripts/vm.sh` excludes `/extension/` from its rsync, while `extension/README.md` documents `npm ci` / `npm test` / `npm run test:e2e` and the runtime contract forbids running them on the Mac. There is no supported way to build or test the extension. +4. `scripts/vm.sh` excludes `/extension/` from its rsync, while `extension/README.md` documents `npm ci` / `npm test` / `npm run test:e2e` and the runtime contract forbids running them on the Mac. There is no supported way to build or test the extension. The new CI workflow (`.github/workflows/ci.yml`, job `runtime`) does not fill the gap: it runs only typecheck, build and unit tests of `@genclass/runtime`; `extension/` is not an npm workspace (root `package.json` workspaces are `packages/*`, `sim`, `demos`) and no Python test runs in CI. 5. `extension/README.md` lists q8 for "WASM, and WebGPU without f16". The runtime's WebGPU notes (`packages/runtime/src/model/README.md`) found that the v0.1 q8 needs `shader-f16` on WebGPU; `src/model/model.json` declares no `needs` for q8. 6. `extension/README.md` says a closed-set command acts "as soon as the model says the command is complete and two partials agree". The code (`policy.js` -> `evaluatePolicy`) acts on a partial when `complete` ≥ 0.65 and (`complete` ≥ 0.85 **or** the same pick twice), or once the phrase is settled. For local ASR the 600 ms payload gate is raised to `round(2 x cadence + 150)` ms (`controller.js` -> `silenceGatesFor`), where cadence = max(`stepMs`, last decode ms), so at least 650 ms for Moonshine (`stepMs` 250). 7. `features_rt.js` -> `Features.run` says "voice always wins"; nothing gives voice priority over feature requests on the shared engine queue. @@ -538,8 +540,8 @@ Run commands: extension unit tests `npm test` = `node --test --test-concurrency= 18. `BENCHMARKS.md` points to "`runs/compare/report.md` in the development repo", which is not here. It also promises that in-browser WebGPU latency "will be published with the first extension release". The extension README says WebGPU is not measured (no GPU in CI). Still open. 19. jevbench M0 is incomplete. OpenRouter returned 402 after 4,420 Jev responses, so Jev is valid only on AG News and Yahoo, and no claim was evaluated. Finishing it needs about $4.50 of credit, which is a user action (`results/jevbench-m0.md`). 20. The benchmax freeze is DRAFT and its hash is unpublished (user decision). No test-split scoreboard exists in the repo. 132 of the 154 headline rows have a registered spec; 22 rows (16 `study:*` spec ids) have no adapter. Z-68m trained and converged at v2's dev level. Its calibration does not transfer, so it ships with identity calibration (`results/z68m-dev-notes.md`). -21. `training/{deliver_final,import_sim,import_final,node}.sh` set `JEV="$(cd "$HERE/../.." && pwd)"` with `HERE` = `training/`, i.e. the directory **above** this repo (the parent-repo layout; `node.sh` comments it as `/Users/meharkhanna/jev`). The first three then call `$JEV/scripts/azvm.sh`; `node.sh` rsyncs `$JEV/jev_local`, `$JEV/scripts` and `$JEV/pyproject.toml` to the node. In this standalone checkout those paths are outside the repo; whether a jev checkout exists there is machine-dependent (see [training.md](training.md)). The same applies to `scripts/launch_run.sh`: `training/launch_s2.sh` and `training/launch_final1.sh` `cd "$(dirname "$0")/../.."` (commented `/Users/meharkhanna/jev`) and then call `scripts/launch_run.sh` relative to that directory. -22. `training/{deliver_final,import_sim}.sh` prefix `azvm.sh` calls with `TIMEOUT=<s>`, but `scripts/azvm.sh` never reads `TIMEOUT` (it has no timeout wrapper), so those calls are unbounded. The same holds for `TIMEOUT=300 scripts/launch_run.sh …` in `training/{launch_s2,launch_final1}.sh`. `training/import_final.sh` uses coreutils `timeout 120` instead, which does work. +21. `training/{deliver_final,import_sim,import_final,node}.sh` set `JEV="$(cd "$HERE/../.." && pwd)"` with `HERE` = `training/`, i.e. the directory **above** this repo (the parent-repo layout; `node.sh` comments it as `/Users/meharkhanna/jev`). The first three then call `$JEV/scripts/azvm.sh`; `node.sh` rsyncs `$JEV/jev_local`, `$JEV/scripts` and `$JEV/pyproject.toml` to the node. In this standalone checkout those paths are outside the repo; whether a jev checkout exists there is machine-dependent (see [training.md](training.md)). The same applies to `scripts/launch_run.sh`: `training/launch_s2.sh` and `training/launch_final1.sh` `cd "$(dirname "$0")/../.."` (commented `/Users/meharkhanna/jev`) and then call `scripts/launch_run.sh` relative to that directory. The launchers added since 654d822, `training/{launch_student,launch_t150,launch_r68}.sh`, do the same (`cd "$HERE/../.."`, then `scripts/launch_run.sh`). +22. `training/{deliver_final,import_sim}.sh` prefix `azvm.sh` calls with `TIMEOUT=<s>`, but `scripts/azvm.sh` never reads `TIMEOUT` (it has no timeout wrapper), so those calls are unbounded. The same holds for `TIMEOUT=300 scripts/launch_run.sh …` in `training/{launch_s2,launch_final1,launch_student,launch_t150,launch_r68}.sh` (the last three are new since 654d822). `training/import_final.sh` uses coreutils `timeout 120` for its `azvm.sh` call instead, which does work, and its `TIMEOUT=2400` / `training/label_cluster.sh`'s `TIMEOUT=` prefixes go to `training/node.sh`, which honours them. 23. Docstrings point at research paths that are not in this repo: `jev_local/bench/__init__.py` and `scripts/jevbench.py` cite `docs/research/v2/PLAN.md`; `jev_local/bench/benchmax/__init__.py`, `scripts/benchmax_build_targets.py` (as a real input path, item 12), `bench/PREREG-*.md`, `bench/public/targets.json` and the `docs/benchmax-research/*.md` notes cite `docs/research/benchmax/*` or `docs/research/v2/*` (the benchmax notes now live in `docs/benchmax-research/`; the v2 notes are absent). There is no `docs/research/` directory. 24. `docs/GENCLASS.md` (outside this scope) says both that the extension zip and weights "are in the v0.1.0 release" and, further down, that they "are coming in the first release". `extension/README.md` and `RELEASE.md` treat v0.1.0 as released; whether the GitHub release exists cannot be checked from the repo (unverified). 25. `jev_local/bench/benchmax/adapters_b/__init__.py` documents a **module-level** function contract (`prepare(work, split)`, `items(work, split, limit, tasks)`, `SPLITS` at module level). The 15 adapters actually expose module-level `SPEC_ID`/`TARGETS` plus a class `Adapter(AdapterB)` whose methods take no `work` argument (`args.work` is passed to the constructor), as `specs_b.py`'s docstring and `common.py` -> `AdapterB` describe. Follow the class contract. @@ -554,6 +556,8 @@ Run commands: extension unit tests `npm test` = `node --test --test-concurrency= - [model-io-contract.md](model-io-contract.md): situation text -> packed request -> heads -> calibrated answers - [genclass-model-lineage.md](genclass-model-lineage.md): `jev_local` (Python model, server, macOS harness, training) - [training.md](training.md): curriculum, R17/R32, export (`training/export_runtime.py`) -- [runtime/build-test-release.md](runtime/build-test-release.md): `scripts/vm.sh` usage, runtime tests and release +- [runtime/build-test-release.md](runtime/build-test-release.md): `scripts/vm.sh` usage, runtime tests and release, and the CI workflow +- [realapps.md](realapps.md): the real-app corpus and generator, built and pilot-run on the `train` VM through `scripts/vm.sh` (slot `real`) and run at scale on F80 nodes through `realapps/scripts/cluster.sh` (own ssh/rsync) +- [sim.md](sim.md): the situation-v2 data generator that the current training push runs on the F80 cluster nodes (c12–c23 were added with `training/cluster_expand.sh`'s settings per `training/NEEDS.md`; that c01–c11 came from `scripts/cluster_up.sh` is unverified) - [status-and-known-issues.md](status-and-known-issues.md) - Sources: [extension/README.md](../../extension/README.md), [extension/MODEL_CARD.md](../../extension/MODEL_CARD.md), [extension/RELEASE.md](../../extension/RELEASE.md), [BENCHMARKS.md](../../BENCHMARKS.md), [bench/PREREG-jevbench.md](../../bench/PREREG-jevbench.md), [bench/PREREG-benchmax.md](../../bench/PREREG-benchmax.md), [results/jevbench-m0.md](../../results/jevbench-m0.md), [results/genclass-vs-jev-computer-use.md](../../results/genclass-vs-jev-computer-use.md), [docs/benchmax-research/PLAN.md](../benchmax-research/PLAN.md), [packages/runtime/src/model/README.md](../../packages/runtime/src/model/README.md), [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) diff --git a/docs/agents/genclass-model-lineage.md b/docs/agents/genclass-model-lineage.md index e8a7a492..35c4f6f6 100644 --- a/docs/agents/genclass-model-lineage.md +++ b/docs/agents/genclass-model-lineage.md @@ -1,8 +1,10 @@ # GenClass model lineage: jev_local (Python model, server, harness, training) and legacy docs > **Scope:** `jev_local/**` except `jev_local/bench/**` (`api.py`, `schema.py`, `serialize.py`, `confidence.py`, `validate.py`, `cli.py`, `demo.py`, `engine/**`, `harness/**`, `server/**`, `train/**`), `pyproject.toml`, `tests/**` (Python), and the legacy design docs `docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`. -> **Read this when:** you touch anything that changes the text the model reads or the numbers it returns (serialization, packing, markers, heads, calibration, answer math); you need to know what `packages/runtime/src/model` was ported from and how parity is checked; you run or change the Python trainer that `training/` drives; you need the Jev-compatible HTTP server or the macOS voice harness; you want to know which Python is legacy and safe to ignore for the self-healing runtime. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Read this when:** you touch anything that changes the text the model reads or the numbers it returns (serialization, packing, markers, heads, calibration, answer math); you need to know what `packages/runtime/src/model` was ported from and how parity is checked; you run or change the Python trainer that `training/` drives (including teacher soft-labelling and the T1 gain work for situation-v2); you need the Jev-compatible HTTP server or the macOS voice harness; you want to know which Python is legacy and safe to ignore for the self-healing runtime. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> +> **What changed since the previous verification (654d822 = v0.1.0-alpha.0, situation-v1 format; the situation-v1 tag is 1a77558):** nothing under `jev_local/**`, `tests/**`, `pyproject.toml` or the legacy docs (`git diff --stat 654d822 b435acb` on those paths is empty), and nothing in `packages/runtime/src/model` or its fixtures. What changed is around it: `training/` gained the scaled program (teacher T150, students R17/R32/R68, teacher soft-labelling, T1 expected-gain targets) that drives this `jev_local` (see "Situation-v2 training and this package" under How it works), the optional **gain head** was added to the **parent repo's** `jev_local` only (not to this tree), and `packages/runtime-model/MODEL_CARD.md` now describes R17-final1, a **situation-v1** model that does not match the v2 runtime. ## TL;DR @@ -11,7 +13,8 @@ - The model (`FastEngine`, "jev-local-fast") is an **ettin/ModernBERT encoder** with **typed heads over marker tokens** `[Q] [O] [L] [T] [F]`. One packed sequence holds the state once plus every question; a block attention mask makes each option see only the state, its own header and itself, so answers are **exactly invariant to option order and to other questions**. - Raw logits are turned into probabilities by **post-hoc calibration** (`calibration.json`: per kind, per header hash, per (kind, K-bucket), τ(K), noul Platt), then into Jev answers by `confidence.build_answer`. - **The runtime model is a direct descendant.** `packages/runtime/src/model` is a TypeScript port of `serialize.py`, the HF tokenizer call, `tokenize_pack.Packer` (single-pass subset), `calibrate.py` lookup and `confidence.py`. The network itself is exported to ONNX by `scripts/genclass_export.py` (graph) / `training/export_runtime.py` (q8/fp16 + card). Parity is pinned by Python-generated fixtures in `packages/runtime/test/fixtures/model/`. -- **R32** (runtime candidate) is initialised from the v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers) with a pruned 16,364-token vocabulary; **R17** starts from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers per `training/README.md`; fresh `DecisionHeads(enc.hidden_size)`), also pruned to 16,364 tokens. Both are trained with `jev_local/train/train.py` (stream mode, DDP) launched from `training/`. Caveat: `training/node.sh sync` copies `jev_local/` from the **parent jev repo** (`$HERE/../..`), not from this repo's root (see Drift). +- **R32** (runtime candidate) is initialised from the v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers) with a pruned 16,364-token vocabulary; **R17** starts from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers per `training/README.md`; fresh `DecisionHeads(enc.hidden_size)`), also pruned to 16,364 tokens. The scaled program (`training/PLAN-v1.md`, 2026-10-08) adds **R68** (ettin-68m student benchmark; never trained, per `training/LOG.md`) and **T150** (ettin-150m **teacher**, never shipped); their pruned bases `ettin-68m-v16k` / `ettin-150m-v16k` are made on each node by the launchers when missing. All are trained with `jev_local/train/train.py` (stream mode, DDP) launched from `training/` (`training/launch_student.sh` is the generic launcher). Caveat: `training/node.sh sync` copies `jev_local/` from the **parent jev repo** (`$HERE/../..`), not from this repo's root, and the two copies have now **diverged** (the parent has the gain head; see Drift). +- **No situation-v2 model exists yet.** The newest trained models (`r17-final1` = R17 default, `r32-final1`) were trained on situation-v1 SIM data and do not match the v2 runtime (`packages/runtime-model/MODEL_CARD.md`, `training/LOG.md`). Next per `HANDOFF.md`: T150 teacher on v2 gold -> teacher labels on unlabeled rows (`training/label_teacher.py`, which calls this package's `load_checkpoint` / `Packer` / `collate_tree` / `build_plan` / `calibrate_logits`) -> distil R17 and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` (release procedure: [RELEASE.md](../../RELEASE.md)). The text contract (serialize/pack/calibrate) is unchanged by v2; what changed is the *content* of the situations (e.g. the new `delivery` trigger with actions `deliver` (passive) / `discard` / `defer`; `deliver` itself already existed as the `failure` passive in v1) rendered by `packages/runtime/src/situation/*` (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`). - Python entry points: console script `jev-local` (`cli.py`), and `python -m` on `jev_local.server.app`, `jev_local.train.train`, `jev_local.train.eval`, `jev_local.train.stream`, `jev_local.engine.encoder.calibrate`, `jev_local.harness.observe`, `jev_local.demo` (table in Files). - **Changing `serialize.py`, `tokenize_pack.py`, marker ids, `heads.py`, `calibrate.py` lookup or `confidence.py` breaks train/runtime parity** unless the TS port, fixtures and model are changed together. - Legacy for the runtime library (safe to ignore unless asked): `api.py` routing and benchmax `ServeConfig`, `validate.py`, `server/app.py`, `engine/registry.py`, `engine/heuristic.py`, `engine/decoder/mlx_scorer.py`, all of `harness/**`, `demo.py`, `cli.py`, and the legacy docs listed in Scope. @@ -132,7 +135,9 @@ Terms not in the shared terminology list: - **Trainer records** (`train/train.py`). `QTarget(dist, hard)` (choice/score: distribution over labels; noul: `[p]`; `hard` = one-hot or p ∈ {0, 1}; `losses.smooth` applies label smoothing only to hard choice/score targets, never to nouls). `Row(pack: Packed, targets: dict[qid, QTarget], example_id, meta)` = one packed sequence. `DataStats(examples, rows, dropped_qids, bad_labels, unsupervised_examples)`. `losses.Targets` = the batch's supervised targets as index tensors aligned with `HeadPlan` groups (`choice_idx/choice/choice_hard`, `score_*`, `noul_idx/noul`, consistency `neg_*`, `nc_*`, `sc_*`). - **CalibRecord** (`calibrate.py`): `(qid, kind, header, logits, target)` where `header` is already `header_key(...)`, `logits` are raw (τ = 1), choice/score `[K]`, noul `[1]`; `.k` = 2 for noul. `train.eval.collect` returns `Collected(records, metas: list[RecMeta(example_id, prefix, labels, source)], calib, n_examples, dropped_qids)`; `training/eval_runtime.py` consumes exactly this. - **ServeConfig / preset / W1–W11.** Per-run serving options for the benchmark ("benchmax") effort, chosen once at server start and never per request; W-numbers are requirement ids from `docs/benchmax-research/suite-reproduction-specs.md` (W1 argmax ties, W3 precision, W4 refusals, W5 truncation, W8 label alias, W9 calibration by run config, W10 public id, W11 determinism). -- **Model lineage names.** *jev-local-fast v1* (`models/jev-local-fast`, ettin-32m) = **GenClass 0.1** (`genclass-model-0.1.0`, ONNX in the Chrome extension) = the R32 initialisation. *v2* (`jev-local-fast-v2`, ettin-68m) = public id `meharsjev-68m`, renamed `genclass-<size>`; not used by `training/`. *R32 / R17* = runtime model candidates (see [glossary.md](glossary.md)). +- **Model lineage names.** *jev-local-fast v1* (`models/jev-local-fast`, ettin-32m) = **GenClass 0.1** (`genclass-model-0.1.0`, ONNX in the Chrome extension) = the R32 initialisation. *v2* (`jev-local-fast-v2`, ettin-68m) = public id `meharsjev-68m`, renamed `genclass-<size>`; not used by `training/`. (This "v2" is the old Jev-benchmark model generation; it is unrelated to the runtime's `situation-v2` format.) *R32 / R17* = runtime model candidates (see [glossary.md](glossary.md)); *R68* = ettin-68m student benchmark; *T150* = ettin-150m teacher (pruned to the same 16k vocabulary, fresh heads, never shipped). *r17-final1 / r32-final1* = final round 1 on situation-v1 (R17 is the default; v1 only). Run names `t150-g1`, `r17-t1g10`, `r17-t1g20`, `r17-t1h` were stopped v1 experiments (`training/LOG.md`): `t150-g1` at step 69 around 01:30 UTC when the lead announced the move to situation-v2 (checkpoint kept on c12's disk), the three T1 runs at the situation-v2 freeze (03:32–03:35 UTC). +- **Teacher soft labels** (`training/label_teacher.py`). A calibrated checkpoint's probabilities written back as CONTRACT-D labels: choice `{"type":"choice","dist":{...}}`, score `{"type":"score","dist":[...]}`, noul `{"type":"noul","p":...}`; gold labels kept unless `--overwrite`; `meta.teacher` = `{ckpt, <qid>: {top, margin, non_passive_mass (action only)}}` for choice/score questions and `{p}` for nouls; probabilities rounded to 5 dp; default `--max-len 2048`, `--batch 32`, `--threads 16`; resumable by line count. Its `PASSIVE` set is `apply, send, deliver, wait, ignore` (the passive actions of every trigger; `deliver` is the passive of both `failure` and the v2 `delivery` trigger). It reuses this package's training-side inference path (`load_checkpoint(..., encoder="banded")` (the `JEV_ENCODER` env var overrides it), `train.encode_example`, `train.train_buckets`, `Packer`, `collate_tree`, `build_plan`, `calibrate_logits` + `header_key`), not `FastEngine`; packing goes through `Packer.pack_split` rather than `FastEngine`'s `plan_passes`, so the numbers should match `FastEngine` only for rows that fit one pass (unverified). +- **T1 / expected-gain targets** (`training/t1_relabel.py`, sim/SEPARABILITY.md §7; no `jev_local` import). gain(a) = mean cost(passive) − mean cost(a) − premium (guard 0.25, heal 0.5; an action with no tier in `meta.tiers` pays the heal premium), clipped ±30, costs from `meta.cost_futures` (fallback `meta.costs`); the action label becomes softmax(gain/τ), or with `--keep-dist` SIM's label is kept and gains are added for a **gain head**. The gain head (an MLP over option marker states, one scalar per option, `HeadOut.gain`, trainer `--gain-loss W`) exists **only in the parent repo's `jev_local`** per `training/LOG.md`; this tree's `heads.HeadOut` has only `choice`, `score`, `noul`. Details: [training.md](training.md). ## How it works @@ -243,6 +248,22 @@ Illustrative request and response (numbers made up but consistent with the answe 3. Export: `training/export_runtime.py` imports `scripts/genclass_export.py`'s `ExportModel` (dense block mask built in-graph, raw logits at τ = 1) over `load_checkpoint(..., encoder="reference")`, writes `<name>-q8.onnx` / `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`, `model.json`, plus `parity.json`, `pack_fixtures.json`, `torch_fixtures.json`, `requests.json` computed with the Python `Packer` and `calibrate_logits`. 4. In the browser, `packages/runtime/src/model` re-implements packing and calibration in TypeScript and runs the ONNX graph with onnxruntime-web; its tests compare against those fixtures (port table below). Details: [runtime/model-host.md](runtime/model-host.md), [model-io-contract.md](model-io-contract.md). +### 10. Situation-v2 training and this package (2026-10-08 plan; v2 data generation running, no training run on v2 yet) + +The runtime's situation format is frozen at tag `situation-v2` (6e5e86e). SIM generates v2 gold and unlabeled rows and REAL generates real-browser rows ([realapps.md](realapps.md)); both are CONTRACT-D rows, so the trainer and serialization here are unchanged. The planned pipeline (`training/PLAN-v1.md`, `HANDOFF.md`) and which `jev_local` pieces each step uses: + +| step | script | `jev_local` used | +|---|---|---| +| prune bases (to 16,000 merges = 16,364 tokens) | `training/prune_vocab.py prune`; the launchers call it on each node when the pruned base is missing: `launch_student.sh` for 68m and 150m (whatever ARCH), `launch_t150.sh` for 150m, `launch_r68.sh` for 68m. The 17m base `ettin-17m-v16k` and `r32-v16k` are not auto-pruned and must already exist on the nodes | tokenizer + checkpoint I/O | +| teacher T150 on v2 gold (+ curriculum replay) | `training/launch_student.sh RUN t150 ...` or the older `training/launch_t150.sh` (stream `data/s3` only, fixed `mix_t150.json`, seed 4; its header comment says 6 ranks × 13 threads but the code defaults to `RANKS=8`, `THREADS=10`) -> `scripts/launch_run.sh` -> `python -m torch.distributed.run ... -m jev_local.train.train --ddp` | trainer (stream mode, `--balance --amp --no-grad-ckpt --device cpu --max-len 2048 --batch-tokens 8192 --ckpt-every 25 --resume`) | +| teacher soft labels on unlabeled rows | `training/label_cluster.sh` (fan-out over nodes; untested per LOG) -> `training/label_teacher.py` | inference path listed in Concepts | +| distil R17 (default) and R32 (and R68) | `training/launch_student.sh RUN {r17,r32,r68} PASSES MIX "nodes" [INIT]` | trainer | +| evaluate / fit temperatures | `training/eval_sim.sh`, `training/eval_runtime.py` (now also reports `recall_clear` and `recall_clear_stale_dup` per gate mode), `training/report.py` | `train.eval.collect` | +| T1 gain evaluation | `training/eval_gain.py` (numpy only), `training/collect_gain.py` (needs the parent repo's gain head for `gain_pred`; see Drift) | inference path | +| export | `training/export_runtime.py` | as in §9 step 3 | + +`launch_student.sh` defaults per ARCH (base, lr, head lr, grad-accum, ranks × threads): r17 `ettin-17m-v16k`, 2e-4, 1e-3, 2, 8×10; r32 `r32-v16k/backbone`, 1e-4, 4e-4, 3, 8×10; r68 `ettin-68m-v16k`, 2e-4, 1e-3, 2, 8×10; t150 `ettin-150m-v16k`, 2e-4, 1e-3, 2, 8×10; streams `data/s3` and `data/s1`, seed 7; overrides via `RANKS`, `THREADS`, `GA_OVERRIDE`, `LR_OVERRIDE`, `HLR_OVERRIDE`; trainer args after `--` are passed through. The older `training/launch_r68.sh` differs (lr 3e-4, seed 5, fixed 8 × 10, `mix_r68.json`). New mixture files (`training/configs/mix_t150.json`, `mix_r68.json`, `mix_t1a.json`, `mix_t1b.json`, `mix_t1h.json`) use a per-bucket `max_repeat` dict (e.g. `{"*": 2.0, "simA": 1.2}`), which this tree's `stream.MixConfig.repeat` supports; their SIM buckets are situation-v1 phase-A data (`simA`, `simAg10`, `simAg20`, `simAh`, plus `cur4` / `cur1` / `gen`), so the v2 mixtures are still to be written. Full training-side detail: [training.md](training.md). + ### Port map: Python -> TypeScript (`packages/runtime/src/model`) The port went Python -> the GenClass extension's JS core (`extension/src/core/{serialize,packer,tokenizer,pyutil,engine}.js`) -> TypeScript. @@ -265,9 +286,9 @@ Fixtures (all in `packages/runtime/test/fixtures/model/`): `py_fixtures.json` (s | `jev_local` part | used by `training/` / runtime pipeline? | how | |---|---|---| | `train/train.py`, `train/stream.py`, `train/losses.py`, `train/ddp.py` | **yes** | the trainer for R17/R32 (stream mode, DDP, `--balance`, `--init-from`; the `training/` launchers pass no `--loss`, so the v1 loss default applies) | -| `train/eval.py` | **yes** | `collect` used by `training/eval_runtime.py`; `train.parse_target` used by `training/curriculum/generate.py` to validate labels | -| `engine/encoder/{tokenize_pack,model,heads,engine}.py` | **yes** | `init_model`, `load_checkpoint`, `write_checkpoint`, `Packer`, `collate_tree`, `build_plan`, `FastEngine` (export, prune tests) | -| `engine/encoder/calibrate.py` | lookup **yes** (export parity); fitting/CLI no (TRAIN fits in `eval_runtime.py`) | `calibrate_logits`, `header_key` | +| `train/eval.py` | **yes** | `collect` used by `training/eval_runtime.py`; `train.parse_target` used by `training/curriculum/generate.py` to validate labels; `train.encode_example` and `train.train_buckets` (both in `train/train.py`) used by `training/label_teacher.py` and `training/collect_gain.py` | +| `engine/encoder/{tokenize_pack,model,heads,engine}.py` | **yes** | `init_model`, `load_checkpoint`, `write_checkpoint`, `Packer`, `collate_tree`, `build_plan`, `FastEngine` (export, prune tests); teacher labelling and gain collection use `load_checkpoint` + `Packer` + `collate_tree` + `build_plan` directly, not `FastEngine` | +| `engine/encoder/calibrate.py` | lookup **yes** (export parity, teacher labels); fitting/CLI no (TRAIN fits in `eval_runtime.py`) | `calibrate_logits`, `header_key` | | `schema.py`, `serialize.py` | **yes** | `question_from_json`, `question_block`, `state_segments` (curriculum validation, export, pruning) | | `confidence.py` | parity only | TS port + `packages/runtime/test/fixtures/model/make_py_fixtures.py` | | `api.py`, `validate.py`, `server/**`, `engine/registry.py`, `engine/heuristic.py`, `engine/decoder/**` | no | Jev-compatible server and benchmarks (legacy) | @@ -392,7 +413,7 @@ Calibrate CLI (`calibrate.main`): `--ckpt` (required), `--data`, `--extra`, `--s | `LONG_BUCKETS` | 3072, 4096, 6144, 8192 | `train_buckets` | | `LossConfig()` (v1) | smoothing 0.02, rps 0.25 (score), brier 0, kl False, spherical 0, coral 0, noise off, consistency 0 | `losses.py` | | `LossConfig.v2()` | smoothing 0.02, rps 1.0, kl True, spherical 0.5, coral 0.25, consistency 0.1 | `losses.py` | -| `MixConfig()` | `seed=0`, `splits=("train",)`, `licenses=None`, `buckets=None`, `bucket_weights=DEFAULT_BUCKET_WEIGHTS`, `weight_unit="tokens"`, `alpha=0.5`, `source_cap=None`, `class_cap=None`, `max_repeat=2.0`, `pass_tokens=None` (one capped epoch), `passes=1.0`, `pool=4096`, `batch_tokens=16384`, `layout="tree"`, `batch_rows=None`, `max_len=8192`, `curriculum=()`, `balance=False` | `stream.py` | +| `MixConfig()` | `seed=0`, `splits=("train",)`, `licenses=None`, `buckets=None`, `bucket_weights=DEFAULT_BUCKET_WEIGHTS`, `weight_unit="tokens"`, `alpha=0.5`, `source_cap=None`, `class_cap=None`, `max_repeat=2.0` (each of the three also accepts a per-bucket dict with a `"*"` default, read by `caps` / `repeat`), `pass_tokens=None` (one capped epoch), `passes=1.0`, `pool=4096`, `batch_tokens=16384`, `layout="tree"`, `batch_rows=None`, `max_len=8192`, `curriculum=()`, `balance=False` | `stream.py` | | `DEFAULT_BUCKET_WEIGHTS` | `b1_tasksource_jev` 0.36, `b2_label_semantics` 0.10, `b3_nli` 0.05, `b4_procedural` 0.08, `b5_open_jev` 0.04, `b6_synthetic` 0.14, `b7_laurer` 0.06, `b8_extractive` 0.04, `b9_cu` 0.12, `s0_families` 0.14; any other bucket `OTHER_BUCKET_WEIGHT` 0.04 (renormalised over buckets present) | `stream.py` | | `SPLITS`, `LICENSES` | `("train", "dev_mix", "dev_family", "dev", "test")`, `("commercial", "research", "unknown")` | `stream.py` | | AdamW | betas (0.9, 0.98), eps 1e-6; groups: decayed backbone, no-decay backbone (ndim < 2, `norm`, `embeddings`), heads at `--head-lr` with no decay | `train.py` -> `param_groups` | @@ -408,7 +429,7 @@ Calibrate CLI (`calibrate.main`): `--ckpt` (required), `--data`, `--extra`, `--s ## Invariants and gotchas - **Text parity is the contract with the runtime.** The trained weights only work on text produced exactly as `serialize.py` + `Packer` produce it. Any change to `entry_text`, `state_segments`, default instructions, item rendering (`"label: desc"` vs bare label), `[SEP]`/`[CLS]` placement, marker set or order, or position numbering silently degrades every existing model and breaks `packages/runtime/test/model/*` parity. -- **Python number rendering leaks into the text.** `str(25.0)` is `"25.0"` but JS can only produce `25`; rows with integral floats train on text the runtime never sends (`training/NEEDS.md` item 8: write integral floats as ints). Booleans render `True`/`False`, `None` as `""` in dicts. +- **Python number rendering leaks into the text.** `str(25.0)` is `"25.0"` but JS can only produce `25`; rows with integral floats train on text the runtime never sends (`training/NEEDS.md` item 8). The curriculum generator now normalises them (`training/curriculum/fmt.py` -> `js_numbers`); any new row producer (teacher labelling keeps the input `state` untouched; SIM and REAL emit JSON from JS) must do the same. Booleans render `True`/`False`, `None` as `""` in dicts. - **Isolation is exact, not approximate.** Option order and unrelated questions cannot change an answer (tests: `test_encoder_engine.py` -> `test_permuting_options_is_exact`, `test_unrelated_question_is_exact`). Do not add cross-question or cross-option attention; it would break this and the multi-pass equivalence. - **`max_tokens` is a positions budget.** It bounds state + header + longest item; the whole request may be far longer (multi-pass). The router compares `positions_needed`, not `count_tokens`. The TS port has **no** multi-pass and also enforces a total (`maxTotal`), so the runtime must keep situations inside its budgets. - **Three different length checks.** `Packer.pack` (used by `scripts/genclass_export.py` and `training/export_runtime.py` to build parity fixtures) bounds the **total** sequence by `max_len` (`EngineError` 400 `{"detail": "max_tokens_exceeded", "tokens", "max_tokens"}`); `FastEngine` bounds **positions** via `plan_passes` and splits the rest into passes; `FastEngine.count_tokens` (= `Packer.count`) is the total and is what `usage.input_tokens` reports, while routing uses `positions_needed`. The TS packer checks both positions (`maxPositions`) and total (`maxTotal`). Both exporters build fixtures with `Packer(tok, max_len=8192)`, so fixture totals stay ≤ 8192 (= TS `maxTotal` default), but `Packer.pack` does not bound positions; `training/export_runtime.py` -> `requests_from_rows` only samples data rows whose total is ≤ 1500 tokens, which keeps them under `maxPositions` 1536. Requests passed with `--requests` get no such filter. @@ -427,6 +448,8 @@ Calibrate CLI (`calibrate.main`): `--ckpt` (required), `--data`, `--extra`, `--s - **Mac safety** (`docs/CONTRACT-v2.md`): on the 8 GB M1 run only pure-Python tests; torch, models, datasets, training and benchmarks run on Azure VMs. The executor defaults to dry-run; live actions only by the user. - **`pyproject.toml` lists pyobjc unconditionally** and lacks `zstandard`, `onnx`, `onnxruntime`; installing on Linux VMs may need manual handling (unverified). - **Which `jev_local` the VMs run.** `training/node.sh sync` rsyncs `${HERE}/../..` + `/jev_local`, `/scripts`, `/pyproject.toml` (comment: "parent repo with jev_local") to `~/jev/` on the node, and commands run with `PYTHONPATH=~/jev:~/gcl-train/training`. Edits to this repo's `jev_local/` reach the cluster only if that parent copy is the same tree; check before assuming a Python change is live in training. +- **This tree's `jev_local` is behind the one the cluster runs.** The parent repo copy has the optional gain head (`DecisionHeads(gain_head=...)`, `add_gain_head()`, `HeadOut.gain`, trainer `--gain-loss`, `load_checkpoint` building the head when a checkpoint has `gain_mlp.*`) per `training/LOG.md` (03:00–03:12 entry); none of it is here. A checkpoint with `gain_mlp.*` keys cannot be loaded through this tree: `engine.load_checkpoint` calls `heads.load_state_dict(...)` with the default `strict=True`, so the unexpected keys raise; and `training/collect_gain.py` reads `o.gain`, which raises `AttributeError` on this tree's `HeadOut`. If you port the gain head, keep it default-off so `heads.safetensors` keys and the ONNX export stay unchanged. +- **Situation format is frozen, the text contract is not the format.** `situation-v2` changes what the runtime puts in `state` and `questions` (e.g. the new `delivery` trigger whose actions are `deliver` / `discard` / `defer`), not how `serialize.py` / `Packer` turn them into tokens. A v1 checkpoint therefore loads and runs on v2 situations without error but was never trained on them; do not treat R17-final1 numbers as v2 numbers. - **Collection errors abort pytest.** The 20 `tests/test_data_*.py` files import the absent `jev_local.data`; a plain `pytest tests` stops at collection. Ignore them (see Tests). ## How to change it safely @@ -441,8 +464,9 @@ Calibrate CLI (`calibrate.main`): `--ckpt` (required), `--data`, `--extra`, `--s 5. **Change training losses**: add a `LossConfig` field defaulting to off so the v1 path stays bit-identical (`test_train_v2_losses.py` -> `test_v1_default_is_bit_identical`); expose a CLI flag in `build_parser` and `loss_config`. Every new term must be a proper scoring rule (zero gradient at p = t). 6. **Change the mixture / data reader**: `stream.py` is numpy-only; keep determinism and world-size-independent cursors (`test_train_v2_stream.py`). Bump `INDEX_VERSION` if the per-row index layout changes (old caches are rebuilt by manifest key). 7. **Change harness vocabularies** (`harness/catalog.py`, `questions.py` instructions): these strings are model input, so a change requires regenerating data and retraining the computer-use model; run `test_policy.py`, `test_safety.py`, `test_controller.py`, `test_heuristic.py`. The extension's JS core mirrors these modules, so its parity fixtures (`extension/scripts/make_py_fixtures.py`) change too (see [extension-and-benchmarks.md](extension-and-benchmarks.md)). -8. **Ship a `jev_local` change to training runs**: `training/` imports `jev_local` from `~/jev` on the VMs (`training/node.sh sync` source is `$HERE/../..`, see Invariants); make sure the copy that gets synced contains your change, then re-run `training/tests/` on a VM (see [training.md](training.md)). Keep trainer flags that the `training/` launchers and `scripts/launch_run.sh` pass (`--ddp`, `--threads`, `--run-name`, `--stream`, `--stream-cache`, `--mixture`, `--runs-dir`, `--max-len`, `--batch-tokens`, `--balance`, `--amp`, `--no-grad-ckpt`, `--device`, `--base`, `--init-from`, `--out`, `--lr`, `--head-lr`, `--grad-accum`, `--resume`, ...) backward compatible; note `scripts/launch_run.sh` also exports `JEV_ENCODER=banded`. -9. **Add a Python test**: put it in `tests/test_<module>.py`; mark `@pytest.mark.model` (needs downloaded weights), `@pytest.mark.slow` (> 10 s), `@pytest.mark.macos` (AX/AppKit; auto-skipped off macOS by `tests/conftest.py`). +8. **Ship a `jev_local` change to training runs**: `training/` imports `jev_local` from `~/jev` on the VMs (`training/node.sh sync` source is `$HERE/../..`, see Invariants); make sure the copy that gets synced contains your change (and that it is based on the parent copy with the gain head, or you would drop it on the cluster), then re-run `training/tests/` on a VM (see [training.md](training.md)). Keep trainer flags that the `training/` launchers and `scripts/launch_run.sh` pass (`--ddp`, `--threads`, `--run-name`, `--stream`, `--stream-cache`, `--mixture`, `--runs-dir`, `--max-len`, `--batch-tokens`, `--balance`, `--amp`, `--no-grad-ckpt`, `--device`, `--base`, `--init-from`, `--out`, `--lr`, `--head-lr`, `--grad-accum`, `--resume`, ...) backward compatible; note `scripts/launch_run.sh` also exports `JEV_ENCODER=banded`. +9. **Port the gain head into this tree** (if asked): copy the parent repo's additive change (heads, `HeadOut.gain`, `load_checkpoint`, trainer `--gain-loss`, `load_weights` tolerance), keep it off by default so v1 runs stay bit-identical (`test_train_v2_losses.py` -> `test_v1_default_is_bit_identical`), and keep it out of the ONNX export unless the runtime gains a consumer for it; the TS model host has no gain output. +10. **Add a Python test**: put it in `tests/test_<module>.py`; mark `@pytest.mark.model` (needs downloaded weights), `@pytest.mark.slow` (> 10 s), `@pytest.mark.macos` (AX/AppKit; auto-skipped off macOS by `tests/conftest.py`). ## Tests @@ -487,6 +511,8 @@ JEV_LOCAL_FAST_CKPT=~/jev/models/jev-local-fast-v2 .venv/bin/python -m pytest -q | `test_overnight.py`, `test_bench_*.py`, `test_bm_adapters_*.py`, `test_bm_integrate.py` | scripts / benchmarks | pure, except `test_bench_ours.py` (`model`, skips on darwin and without a checkpoint) | out of scope: see [extension-and-benchmarks.md](extension-and-benchmarks.md) | | `test_data_*.py` (20 files) | data generators | `jev_local.data` | **cannot run in this repo**: the package is not in it | +TypeScript side of the parity contract (`packages/runtime/test/model/{serialize,packer,calibrate,engine}.test.ts`): run in the normal `vitest` unit run and in CI (`.github/workflows/ci.yml`); the sections that compare against the committed `py_fixtures.json` (serialize, calibration and answer math vs Python) always run; the sections that need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`, see `packages/runtime/test/model/helpers.ts` -> `MODEL_DIR`) use `describe.skipIf` / `it.skipIf` and skip when it is absent. Those are exactly the 14 skipped tests on `mvp-v2`: 10 in `packer.test.ts` (tokenizer + packer vs the parity requests, HF tokenizer edge cases, tokenizer performance), 3 in `engine.test.ts` (q8/fp16 on onnxruntime-node, q8 on onnxruntime-web WASM) and 1 in `calibrate.test.ts` (calibration vs PyTorch). Checked on 2026-10-08: `npx vitest run test/model` in `packages/runtime` -> 48 passed, 14 skipped; the lead's full unit run: 332 passed, 14 skipped, plus `review-perf` 4 passed. No model directory can be fetched today: `@genclass/runtime-model` is not published and `DEFAULT_MODEL_BASE_URL` returns 404. The Python tests above are not run by CI. + Fixtures: `tests/fixtures/official_examples.json` (Jev doc examples, server + SDK tests), `tests/fixtures/harness_cases.json` (decoder cases, `test_mlx_scorer.py`). `tests/conftest.py` only skips `macos` tests off macOS; there are no shared fixtures. ## Drift and open issues @@ -516,10 +542,17 @@ Code wins in every row. | 19 | `training/node.sh` / `training/README.md`: `jev_local/` comes from the parent jev repo at `$HERE/../..` | in this repo `jev_local/` sits at the repo root (`$HERE/..`); `node.sh sync` would copy `<parent of repo>/jev_local`, not this tree | | 20 | `engine/encoder/heads.py` docstring: noul `p = sigmoid(z / tau)`; `engine/encoder/engine.py` docstring lists only the v1 `calibration.json` keys | `FastEngine` applies `calibrate.calibrate_logits`: `by_header` τ, else `noul_platt` `sigmoid(a·z + b)`, else per-kind τ; v2 keys `by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp` are honoured | | 21 | `engine/base.py` docstring: answers are built "in `jev_local.api.build_answer`" | defined in `jev_local/confidence.py` -> `build_answer`; `api.py` only imports it | +| 22 | `training/LOG.md` (03:00–03:12): `jev_local` has an optional gain head (`DecisionHeads(gain_head=…)`, `add_gain_head()`, `HeadOut.gain`, `--gain-loss`) | only in the **parent repo's** copy; this tree's `heads.DecisionHeads(d=384)` / `HeadOut(choice, score, noul)` have no gain head and `train.py` has no `--gain-loss`; `training/collect_gain.py` (reads `o.gain`) and loading a `gain_mlp.*` checkpoint fail against this tree | +| 23 | `training/launch_student.sh` usage comment: MIX "e.g. `mix_v2_distill.json`" | no such file in `training/configs/` (existing: `mix_final1`, `mix_r68`, `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_t150`, `mix_t1a`, `mix_t1b`, `mix_t1h`); the v2 mixtures are not written yet | +| 24 | `training/NEEDS.md` item 8 is still an open ASK (curriculum rows carry Python-only float literals such as `25.0`) | `training/curriculum/fmt.py` -> `js_numbers` (already present at 654d822) turns integral floats into ints, and `training/curriculum/generate.py` applies it to `state` and `questions`; rows generated before it (e.g. the one in export-r32's `requests.json`) still carry `25.0` | +| 25 | `training/NEEDS.md` item 11 (asks for the runtime tag, example `situation-v1`) and its "SIM → TRAIN: scaled data" section ("Runtime tag `situation-v1`") | the scaled SIM and REAL runs now in progress are `situation-v2` (`HANDOFF.md`; NEEDS item 16 and the c02–c09/c12–c23 claim row); `training/PLAN-v1.md` already says everything in it starts on v2 data | +| 26 | `packages/runtime-model/MODEL_CARD.md` status: R17 "delivered" in `files/r17/` | `packages/runtime-model/files/` is gitignored (not in the repo); R17-final1 is situation-v1 and does not match the v2 runtime; `@genclass/runtime-model` is unpublished (npm 404) | Open issues relevant to this scope: -- `training/NEEDS.md` item 8: curriculum rows contain Python-only float literals (`25.0`), so Python-packed text differs from runtime text on those rows (one of 90 parity requests). +- No situation-v2 model: every number in `packages/runtime-model/MODEL_CARD.md` and `training/EVAL.md` is a v1 number (round-1 results: [RESULTS.md](../runtime/RESULTS.md)). CI exercises the serialize, calibration and answer-math parity against the committed `py_fixtures.json`, but the tokenizer/packer, ONNX engine and torch-calibration parity tests need a local model directory, so CI does not exercise them today. +- The two `jev_local` copies (this tree vs the parent repo synced to the cluster) have diverged (row 22). Decide which is canonical before changing either; until then, Python edits here do not reach training. +- T1 (expected-gain targets / gain head) was stopped on v1 with no result and is to be rerun on v2 data; LOG reports the gain-head interim loss barely beat trivial predictors (0.85 vs 0.97–1.01). - TS port intentionally lacks multi-pass option batching and `lr`/median answer modes; the runtime must stay within `maxPositions` / `maxTotal`. - `docs/GENCLASS.md` / `docs/COMPARISON.md` / `docs/PLAN-excel.md` numbers (90.4% vs 66.4%, v2 skill 36.8, staged budgets) describe the computer-use and benchmark lineage, not the runtime model; do not quote them as runtime results. @@ -528,7 +561,9 @@ Open issues relevant to this scope: - [runtime/model-host.md](runtime/model-host.md) — the TypeScript model host built from this engine. - [model-io-contract.md](model-io-contract.md) — situation text -> packed request -> heads -> calibrated answers across runtime, sim and training. - [training.md](training.md) — `training/` (curriculum, prune, export, eval) that drives `jev_local/train`. -- [sim.md](sim.md) — the simulator that writes CONTRACT-D rows for the stage-2 pilot and the final rounds. +- [sim.md](sim.md) — the simulator that writes CONTRACT-D rows for the stage-2 pilot, the final rounds and the situation-v2 scaled runs. +- [realapps.md](realapps.md) — the real-browser corpus (REAL): CONTRACT-D rows from real apps running the runtime, the second v2 data source. - [extension-and-benchmarks.md](extension-and-benchmarks.md) — Chrome extension (JS core between Python and TS), `jev_local/bench`, scripts. - [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [repo-map.md](repo-map.md). +- Training plans and logs: [`training/PLAN-v1.md`](../../training/PLAN-v1.md), [`training/LOG.md`](../../training/LOG.md), [`training/NEEDS.md`](../../training/NEEDS.md), [`HANDOFF.md`](../../HANDOFF.md); round-1 results [RESULTS.md](../runtime/RESULTS.md); release procedure [RELEASE.md](../../RELEASE.md). - Legacy sources: [SPEC](../SPEC.md), [CONTRACT](../CONTRACT.md), [CONTRACT-v2](../CONTRACT-v2.md), [DEMO](../DEMO.md), [GENCLASS](../GENCLASS.md), [COMPARISON](../COMPARISON.md), [PLAN-excel](../PLAN-excel.md); runtime contract [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md); port notes [packages/runtime/src/model/README.md](../../packages/runtime/src/model/README.md). diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md index 8cc07f81..e8d1749e 100644 --- a/docs/agents/glossary.md +++ b/docs/agents/glossary.md @@ -1,10 +1,10 @@ # Glossary -> **Scope:** every term defined in the subsystem docs under `docs/agents/`, the shared runtime vocabulary (op, trigger, situation, hold, tier, ...) and project jargon (workstreams, datasets, training stages, hosts, model names, benchmark names). One alphabetical list. A qualifier in parentheses separates words that mean different things in different subsystems, e.g. *chaos (demos)* vs *chaos (sim)*, *Decision (runtime)* vs *Decision (extension)*. +> **Scope:** every term defined in the subsystem docs under `docs/agents/`, the shared runtime vocabulary (op, trigger, situation, hold, tier, delivery, ...) and project jargon (workstreams, datasets, label rules S1/S2/T1, training stages and the teacher/distillation/DAgger pipeline, hosts, model names, benchmark names, the realapps sweeps). One alphabetical list. A qualifier in parentheses separates words that mean different things in different subsystems, e.g. *chaos (demos)* vs *chaos (sim)*, *Decision (runtime)* vs *Decision (extension)*, *S1 (fact)* vs *S1 (sim label rule)*. > **Read this when:** a doc, a status file or the code uses a word you do not know, or two docs seem to use one word differently. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this glossary, a subsystem doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. -Conventions: **Code:** `path/from/repo/root` -> `symbol` (a method is written `Class.method`). **Doc:** the subsystem doc with the full detail. "See *x*" points to another entry of this glossary. Runtime numbers (thresholds, budgets, sizes) are the defaults at 654d822. +Conventions: **Code:** `path/from/repo/root` -> `symbol` (a method is written `Class.method`). **Doc:** the subsystem doc with the full detail. "See *x*" points to another entry of this glossary. Runtime numbers (thresholds, budgets, sizes) are the defaults at b435acb. Fact ids: the runtime's own fact ids (M2, R3, F1 for "failure", S1 for "stall", ...) predate batch 5 and collide with the batch-5 evidence facts **F1–F9** (named after `sim/SEPARABILITY.md` §6) and with SIM's label rules **S1/S2**; the qualifier in each entry says which is meant. Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](#g) · [H](#h) · [I](#i) · [J](#j) · [K](#k) · [L](#l) · [M](#m) · [N](#n) · [O](#o) · [P](#p) · [Q](#q) · [R](#r) · [S](#s) · [T](#t) · [U](#u) · [V](#v) · [W](#w) · [X](#x) · [Z](#z) @@ -13,12 +13,12 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **A/A noise (demos)**: Bug-verdict flips between two Off runs of the same seeds; the noise floor against which *fixed / introduced* counts are read (board demo: 1 of 30 after common random numbers). Doc: [demos](demos.md). - **action**: The model's answer to the `action` question: one of the actions offered for the trigger, built-ins first (passive first, then the applicable guard/heal actions), then applicable custom actions. The `action` question is asked only when at least 2 actions apply; with one, the runtime treats the answer as `{ <passive>: 1 }`. See *built-in actions*. Code: `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS`, `buildQuestions`; `packages/runtime/src/situation/build.ts` -> `builtinApplicable`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **actionLabel (sim)**: The sim's soft `action` label from counterfactual costs: each action's per-future cost gets a tier premium (or the tie rule), then `p_a ∝ exp(−gap_a / τ_a)`, where `gap_a` is the mean paired cost difference to the best action and `τ_a = 0.10 + 1.0 × SE` of that difference. Code: `sim/src/oracle/cost.ts` -> `actionLabel`, `LABEL`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). -- **ActionRecord**: The record `a<n>` of one non-passive action attempt (built-in, custom or late revert), kept also when it failed (`ok: false`): `decisionId, action, tier, trigger, subject, at, ok, error?, changed, undo?, late?`. Fires the `act` event; `rt.interventions()` returns the last 200. Also called an *intervention*. Code: `packages/runtime/src/types.ts` -> `ActionRecord`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **ActionRecord**: The record `a<n>` of one non-passive action attempt (built-in, custom or late revert), kept also when it failed (`ok: false`): `decisionId, action, tier, trigger, subject, at, ok, error?, changed, undo?, late?`, plus `dropped?` (delivery `discard`: the paths dropped so far, growing while the 10 s discard mark lasts). Fires the `act` event; `rt.interventions()` returns the last 200. Also called an *intervention*. Code: `packages/runtime/src/types.ts` -> `ActionRecord`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **adapter (store kind)**: A store whose value lives in a state library; writes commit through the proposal's `commit(next)`, and GenClass may write directly (rollback, revert) only when `AdapterIO.set` exists (`writable`). The Redux enhancer and the Zustand middleware create adapter stores. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.adapter`; `packages/runtime/src/types.ts` -> `AdapterIO`, `AdapterHandle`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **adapters (framework)**: Subpath exports owned by UI: `@genclass/runtime/react` (`GenClassProvider`, `useGenClass`, `useGenClassState`, which registers an atom, plus decision/status hooks), `@genclass/runtime/redux` (`genclassEnhancer`) and `@genclass/runtime/zustand` (`genclass` middleware). Code: `packages/runtime/src/adapters/react.ts` -> `useGenClassState`; `packages/runtime/src/adapters/redux.ts` -> `genclassEnhancer`; `packages/runtime/src/adapters/zustand.ts` -> `genclass`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **ambient op**: The op whose work is running now (`Context.cur`). `startOp` uses it as the `cause` of new ops and the hub records it as the writer of state writes. `Context.run` sets it synchronously, `Context.stick` until the end of the macrotask; GenClass does not propagate it through arbitrary promises. Code: `packages/runtime/src/trace/context.ts` -> `Context`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **answer cache**: The `DeciderQueue` cache of provider answers keyed by `fnv1a(trigger + state + questions)` (subject and priority excluded): 64 entries, 30 s TTL, served only while the provider is `ready`, with no latency sample. Code: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **apply (action)**: Passive action of the `mutation` trigger: let the write update the state now (or when the store's queue drains). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **apply (action)**: Passive action of the `mutation` trigger: keep the write. By default (`holdWrites` off) the write has already applied when the non-blocking `mutation` trigger is decided, so `apply` changes nothing; with `policy.holdWrites: true` it lets the held write update the state (or when the store's queue drains). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.observeWrite`, `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **ask (trigger)**: The developer-question trigger. `rt.ask(question, { about, timeoutMs })`, `rt.decide(question, options)` and `rt.situation()` build an `ask` situation about now, an op id or a store outside `trigger()`: no triage, no gate, no `Decision`, queue priority 1. `rt.ask` replaces the questions with `{ answer: q }`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.ask`, `RuntimeImpl.decide`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **ask row / ask probe (sim)**: At `scenario.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records it; `askQuestions` attaches 1–3 programmatic questions with exact labels (`q_*` qids). Code: `sim/src/ask/questions.ts` -> `askQuestions`. Doc: [sim](sim.md). - **atom (store kind)**: A store whose value GenClass owns (`StoreRec.value`), created by `rt.atom(name, initial, opts)` and by the React hook `useGenClassState`; always writable. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.atom`. Doc: [state-and-adapters](runtime/state-and-adapters.md). @@ -31,21 +31,24 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **BandedEncoder**: See *tree layout / BandedEncoder*. - **base run (sim)**: The scenario run with the real runtime, a recording decider, exploration (ε of 0, 0.08 or 0.2, weighted 4/3/2; ε where the sim sees a problem, ε/4 elsewhere) and ask probes. Its recorded decisions are the candidate decision points. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md). - **baseline**: Online statistics per op signature, for fetch/XHR ops only (not synthetic, not GenClass): last 64 non-failure latencies (nearest-rank median/p95, need ≥ 5 samples), last 20 outcomes, failure streak, an EWMA error rate (computed but never read), last 128 start times (recent vs usual rate), and per request identity an EWMA gap between identical requests. Memory only; feeds facts, stats lines, the stall timer and `delay` backoff. Code: `packages/runtime/src/learn/baselines.ts` -> `Baselines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **batch (CORE)**: A numbered CORE release of fixes. Batch 1 = SIM requests 1–5; batch 2 = situation budget, `sectionLimits`, auto hold budget, late revert, provider errors fail open; batch 3 = REVIEW's 34 findings, SIM a–f, summed-mass gate, `transient`, compact questions (commit 1a77558, tagged `situation-v1`). Doc: [status-and-known-issues](status-and-known-issues.md). +- **batch (CORE)**: A numbered CORE release of runtime changes, recorded in `packages/runtime/STATUS.md`. Batch 1 = SIM requests 1–5; batch 2 = situation budget, `sectionLimits`, auto hold budget, late revert, provider errors fail open; batch 3 = REVIEW's 34 findings, SIM a–f, summed-mass gate, `transient`, compact questions (commit 1a77558, tagged `situation-v1`); *batch 4* and *batch 5* (see their entries) make situation-v2. Doc: [status-and-known-issues](status-and-known-issues.md). +- **batch 4**: Runtime batch fcd1e68, "decide at the network boundary, never reorder app writes": the new *delivery* trigger (fetch/XHR responses, WebSocket and the new EventSource observer), store writes no longer held by default (`policy.holdWrites` opt-in; a salient write raises a non-blocking `mutation` that only a *late revert* can enforce), *covered writes*, version *conflicts* (`situation/conflicts.ts`), the `observe.untrustedEvents` option, `STATE_CHAR_BUDGET` 3,200 → 2,400. Motivated by the demos, where holding store writes made correct apps worse (board jump-backs, overwritten keystrokes, search latency). Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **batch 5**: Runtime batch "separability facts, real-app text fixes; freeze situation-v2" (commit 6e5e86e, tagged `situation-v2`): the evidence facts *F1–F9* and read-your-writes (`situation/content.ts`, `situation/evidence.ts`, `learn/cadence.ts`), stricter delivery salience, relation-quality rules and count-by-group invariants (F8), `UserAction.clicks`. Part of it landed earlier inside the realapps commit fcb8189: `situation/content.ts` (F1–F3), diff-centred string previews (`state/fields.ts` -> `stringDiff`), leaf-based redaction (`util.ts` -> `isSensitivePath`) and DOM-observer fixes (shadow DOM, nested labels). Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **benchmax**: Campaign to beat every published Jev number through each publisher's own harness: 549 targets (154 headline/counted), tracks Z and S, 19 registered adapter specs; no test-split scoreboard exists in the repo. Code: `jev_local/bench/benchmax/__init__.py` -> `Spec`; `scripts/benchmax.py`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **block (action)**: Heal-tier `request` action: do not send; answer with a 503 `Response` (statusText `Blocked by GenClass`, header `x-genclass: blocked`) and end the op `blocked` (XHR: a faked 503). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `blockedResponse`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **branch (packing)**: State + one question header + one of its items. Positions restart per branch (header at `S..`, every item at `S + len(header)..`). In the runtime TS packer `meta.max_len` (default 1536) bounds the state plus the longest branch and `meta.max_total` (8192) the whole sequence; `FastEngine` also bounds positions and splits the rest into passes. The Python `Packer.pack` bounds the total sequence by `max_len` (default 2048) and the trainer's `Packer.pack_split` bounds state + whole question blocks per sequence. Code: `packages/runtime/src/model/packer.ts` -> `Packer`; `jev_local/engine/encoder/tokenize_pack.py` -> `Packer.pack`, `Packer.pack_split`; `jev_local/engine/encoder/engine.py` -> `plan_passes`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **browserClock**: The default `Clock`: `performance.now()` (or a counter), with `setTimeout`, `clearTimeout`, `setImmediate`, `MessageChannel` and `performance` captured at module load so the runtime's own timers never pass through its timers observer; `afterTask` runs via `setImmediate` (Node) or `MessageChannel`. Code: `packages/runtime/src/clock.ts` -> `browserClock`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **bucket (training mixture)**: A mixture group named after the parent directory of a shard file (`data/s3/simA/shard07.jsonl` -> `simA`). Weights in `mix_*.json` are renormalised over the buckets present, so a missing bucket is silently dropped. Code: `jev_local/train/stream.py` -> `_names`, `MixConfig`. Doc: [training](training.md). - **budget**: Overloaded word; check which one is meant: *situation budget* (characters of situation text), *hold budget* (ms a subject may be held), *budget scale* (shrink factor of the auto situation budget), the packer's token limits `max_len` / `max_total` (see *max_tokens_exceeded*), *pass / pass_tokens* (training tokens per mixture draw) and *budget (sim)*. -- **budget (sim)**: The `situation.budget` the sim passes to the runtime per scenario: 3200, 2000 or 1000 characters (weights 40/30/30), recorded in `meta.budget`. Code: `sim/src/world/scenario.ts` -> `buildScenario`. Doc: [sim](sim.md). +- **budget (sim)**: The `situation.budget` the sim passes to the runtime per scenario: 3200, 2000 or 1000 characters (weights 40/30/30), recorded in `meta.budget`. These are still the situation-v1 device budgets: the v2 runtime's full budget is 2,400 and its auto budgets are 2,400 / 2,000 / 1,667 / 1,333 / 1,000, so about 40% of v2 sim rows use a size production never produces (open review finding; realapps samples the same 3,200 / 2,000 / 1,000). Code: `sim/src/world/scenario.ts` -> `buildScenario`. Doc: [sim](sim.md). - **budget scale**: `RuntimeImpl.budgetScale`: starts at 1 and is multiplied by 0.8 (floor 0.5, never restored) each time the provider fails with `max_tokens_exceeded`; it applies only to the automatic situation budget. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). -- **built-in actions**: The 15 generic actions in `BUILTIN_ACTIONS` (name, tier, model-facing description), offered per trigger by `TRIGGER_ACTIONS` and applicability: passive `apply`, `send`, `deliver`, `wait`, `ignore`; guard `discard`, `defer`, `coalesce`, `delay`; heal `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`. Each has its own entry here. Code: `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **bypass write**: A write applied at once in the caller's stack without gating: user-sync writes, writes from GenClass ops, stores registered with `hold: false`, writes while gating is off (paused or destroyed), no-op writes and unholdable writes. Errors propagate to the caller. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). +- **built-in actions**: The 15 generic actions in `BUILTIN_ACTIONS` (name, tier, model-facing description), offered per trigger by `TRIGGER_ACTIONS` and applicability: passive `apply`, `send`, `deliver`, `wait`, `ignore`; guard `discard`, `defer`, `coalesce`, `delay`; heal `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`. `delivery` reuses `deliver`, `discard` and `defer` with its own descriptions. Each has its own entry here. Code: `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **bypass write**: A write applied at once in the caller's stack without any trigger: user-sync writes, writes from GenClass ops, stores registered with `hold: false`, writes while gating is off (paused or destroyed), no-op writes and unholdable writes. Errors propagate to the caller. Since batch 4 every write applies at once by default anyway; the difference is that only a non-bypassed write may raise a non-blocking `mutation` trigger. Every non-GenClass write, bypassed or not, first passes the delivery drop filter (`StoreHub.propose`). Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). ## C -- **c01 / c02–c11**: Azure hosts used by TRAIN: `c01` (10.0.0.6) is the workbench and data hub (prune, generate, eval, export); `c02`–`c11` are F80 training nodes (`c02` is R32 rank 0, `c09` is R17 rank 0). The host table lives in `~/.jev-local/azure_hosts` (not in the repo). See *train VM*. Doc: [training](training.md). +- **c01 / c02–c23**: Azure F80 hosts (`vm-jev-c01`…`c23` in resource group `rg-jev-train`). `c01` (10.0.0.6) is TRAIN's workbench and data hub (prune, generate, eval, export); `c02`–`c11` were the round-1 training nodes (`c02` R32 rank 0, `c09` R17 rank 0); `c12`–`c23` were added on 2026-10-08 by `training/cluster_expand.sh`. During v2 data generation SIM holds c02–c09 and c12–c23 and REAL holds c01, c10 and c11 (`training/NEEDS.md`); nobody on our side touches Azure. The host table lives in `~/.jev-local/azure_hosts` (not in the repo). See *train VM*. Doc: [training](training.md), [sim](sim.md), [realapps](realapps.md). +- **cadence (F6)**: What the runtime learned about when a request signature is sent: `periodic { period, intervals, last, next }` (a schedule: requests not caused by user actions, ≥ 4 runs, ≥ 75% of intervals within ±25%, dropped after 3 missed periods) or `debounced { delay, matching, of }` (sent a fixed delay after the user's last input, from timers started by user actions). Stated by fact F6 ("GET /api/feed runs on a schedule: every 1.00s …; the next run is due in 0.95s."), always neutral; it tells the model whether a stale value will heal by itself. Code: `packages/runtime/src/learn/cadence.ts` -> `Cadence`, `CadenceInfo`; `packages/runtime/src/situation/evidence.ts` -> `cadenceFact`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **calibration / calibration.json**: Post-hoc temperature scaling of raw logits read from `calibration.json`: τ by header key, else by `(kind, K-bucket)`, else `τ(K) = a + b·ln K` clamped to `[0.5, 5.0]`, else per kind; a noul uses its header temperature, else a Platt affine, else the per-kind temperature. Trained checkpoints ship all-1.0 temperatures; the real file comes from `training/eval_runtime.py --write-calibration`. Code: `packages/runtime/src/model/calibrate.ts` -> `tauFor`, `noulAffine`, `calibrateLogits`; `jev_local/engine/encoder/calibrate.py` -> `tau_for`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). - **candidate**: See *permitted set / candidate / mass*. - **cause / root (op)**: `OpRec.cause` is the id of the op that was ambient (or passed explicitly) when the op started; `root` is the cause's root, or the op's own id when it has no cause. User ops and WS messages are always roots; a retry or hedge op names the original op as its cause. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). @@ -54,11 +57,12 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **chain revert**: The `rollback` implementation for `transition` and `error` triggers: restore exactly the fields the op's root chain wrote (not overwritten since, with a known earlier value, in a writable store) to their values before the chain's first write; undo restores the replaced values. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.revertChain`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). - **chain write**: `ChainWrite { kind, len0, len1 }`, accumulated per normalised path in `OpRec.chain` of profiled ops (the writer plus up to 8 ancestors) by `RuntimeImpl.onApplied`; the input to transition profiles. `ChainWriteInfo` (`SitEnv.chainWrites`) is the real-path view used by facts and rollback applicability. Code: `packages/runtime/src/trace/ops.ts` -> `ChainWrite`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **chaos (demos)**: `RouteChaos` knobs (latency, jitter, failRate, commitFailRate, timeoutRate, hangMs, spikeRate, spikeFactor, reorder, outage, offline) plus per-route overrides, applied by the Service Worker mock server; environment only, never app logic. Clean trials use `CLEAN_CHAOS` (45 ± 15 ms, no failures). Code: `demos/src/shared/chaos.ts` -> `RouteChaos`, `resolveChaos`; `demos/src/shared/scenario-kit.ts` -> `CLEAN_CHAOS`. Doc: [demos](demos.md). -- **chaos (sim)**: Per-scenario network regime `calm | normal | flaky | degraded | storm` (weights 2/3/3/3/1) that `makeNet` turns into latency multipliers, transient and network-error rates, outages, slow periods, capacity, rate limits, replica lag and server bugs. Code: `sim/src/world/scenario.ts` -> `buildScenario`, `makeNet`. Doc: [sim](sim.md). +- **chaos (sim)**: Per-scenario network regime `calm | normal | flaky | degraded | storm | mobile | peak | deploy` (weights 2/3/3/3/1/1/1/1; the last three, added in round 2, start from the flaky/degraded/normal base and add their own conditions) that `makeNet` turns into latency multipliers, transient and network-error rates, outages, slow periods, capacity, rate limits, replica lag and server bugs. Code: `sim/src/world/scenario.ts` -> `buildScenario`, `makeNet`. Doc: [sim](sim.md). - **chaos trial / clean trial (demos)**: A chaos trial randomises chaos and stresses the simulated user, and measures bug rate; a clean trial uses a calm network and a calm user on which the app is correct, so any executed non-passive action is a *false intervention*. Doc: [demos](demos.md). - **choice (question kind)**: A typed question answered by a softmax over 2–255 labels (`criteria`: label -> description or `null`); the answer is `{ choice, confidence, probabilities }` with probabilities in criteria order. `diagnosis` and `action` are choice questions; `rt.decide()` is a choice shortcut. Code: `packages/runtime/src/types.ts` -> `Question`, `ChoiceAnswer`; `jev_local/schema.py` -> `ChoiceQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). -- **CI**: There is none: the repo has no `.github/` directory; adding CI is open work in `OPEN_TASKS.md`. Doc: [build-test-release](runtime/build-test-release.md). +- **CI**: `.github/workflows/ci.yml` (added in b435acb on `mvp-v2`), job `runtime`: on push to `main`, `runtime`, `mvp`, `mvp-v2`, on pull requests and on manual dispatch; Ubuntu, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci` from the committed root lockfile, `typecheck` and `build` of `@genclass/runtime`, then the unit tests without `test/browser/**` and `review-perf`, then `review-perf` alone with `--retry=2` (it is a wall-clock test that flakes under parallel load). Playwright, `smoke.sh`, the sim, realapps and Python tests are not in CI. Doc: [build-test-release](runtime/build-test-release.md). - **classify (sim)**: A feature-provided closure on a sim op or sim write, evaluated at decision time, that returns a diagnosis (`stale`, `conflict`, `duplicate`, `expected`) from content bookkeeping; a returned label takes precedence in `diagnose`. Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [sim](sim.md). +- **clean run (realapps)**: One of the 8% of realapps scenarios with the first (correct) flag options, a calm network and no accidental clicks; the never-worse sweep counts how many clean runs change. Code: `realapps/src/harness/scenario.ts` -> `buildScenario`. Doc: [realapps](realapps.md). - **clear (devtools)**: Overlay-only removal of cards and rows; runtime buffers are untouched and a remount backfills them again. Doc: [devtools](runtime/devtools.md). - **Clock**: The injected time interface `{ now(), setTimeout(fn, ms), clearTimeout(h), afterTask(fn) }` through which all runtime time and scheduling go. Runtime code never calls `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`, which keeps the sim deterministic. Defaults to `browserClock`; tests use `FakeClock`, the sim its `VirtualLoop` clock. Code: `packages/runtime/src/types.ts` -> `Clock`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **coalesce (action)**: Guard-tier `request` action, fetch only: do not send; wait (≤ 8 s) for the buffered response of an identical request that is in flight or settled ≤ 2 s ago, and answer a copy marked `x-genclass: coalesced`. Offered only when `ResponseCache.shareable` finds such a request. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `ResponseCache`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). @@ -66,50 +70,57 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **common random numbers (CRN)**: Pairing device that gives compared runs the same random draws. In the sim, counterfactual futures share one salt across all actions; in the demos, `World.rngFor(key)` gives the n-th occurrence of the same logical request or live event the same RNG in every mode, so Off/Guard/Heal comparisons measure GenClass rather than re-rolled network. Code: `sim/src/gen/trajectory.ts` -> `pointCosts`; `demos/src/server/core.ts` -> `World.rngFor`. Doc: [sim](sim.md), [demos](demos.md). - **compact questions**: At a situation budget ≤ 1400 characters (`COMPACT_QUESTIONS_BUDGET`) every option description becomes `null` (bare labels), except vocabulary overrides of ≤ 24 characters; custom-action and plugin-label descriptions are dropped too. Instructions are unchanged. Code: `packages/runtime/src/situation/questions.ts` -> `buildQuestions`, `COMPACT_QUESTIONS_BUDGET`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). - **COMPACT_BUDGET vs COMPACT_QUESTIONS_BUDGET**: Two distinct constants. `COMPACT_BUDGET` (1100, `serialize.ts`, exported from the root) is the budget at and below which section limits are smallest; `COMPACT_QUESTIONS_BUDGET` (1400, `questions.ts`, not exported from the root) is the threshold for compact questions. Code: `packages/runtime/src/situation/serialize.ts` -> `COMPACT_BUDGET`; `packages/runtime/src/situation/questions.ts` -> `COMPACT_QUESTIONS_BUDGET`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md). +- **conflict (newer data / pending local change)**: The two situation-v2 version conflicts on a field an op X will write (`situation/conflicts.ts`). *Newer-data conflict*: the field changed since X started, written by an op that started after X, outside X's chain, not itself a user action, with no newer request of X's signature still in flight. *Pending local change*: a user action's chain wrote the field in the last 10 s (`PENDING_WINDOW_MS`) and an op of that chain with a different signature is still in flight. Only these make a version fact non-neutral, and they drive delivery salience. Code: `packages/runtime/src/situation/conflicts.ts` -> `newerConflict`, `pendingConflict`, `conflictsOn`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **consistency pair**: A `meta.pairs` entry (`neg`, `noul_choice`, `score_choice`) that the v2 training loss penalises to keep related answers coherent. Code: `jev_local/train/losses.py` -> `consistency_terms`. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **consistent snapshot**: A deep clone of all stores taken at a settled point where no violation newly broke (lingering ones allowed); `RuntimeImpl.snaps` keeps the last 8. Inconsistency `rollback` writes the last one back. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`, `RuntimeImpl.rollback`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **consultable**: `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists and its `status.state` is `"ready"` or `"off"`. When false, every trigger runs its passive action without building a situation and no write is held; a default install today reaches this state because the unpublished model ends in status `error`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.consultable`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [status-and-known-issues](status-and-known-issues.md). - **consumed prefix (extension)**: Transcript words already acted on; later partials must still start with them (fillers and chain words ignored) or the stream freezes (`revised_after_act`), so an action never runs twice. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **CONTRACT (legacy)**: `docs/CONTRACT.md` (the jev-local v0.1 build contract per workstream A–H, whose section D defines the CONTRACT-D row format), with `docs/CONTRACT-v2.md`, `docs/SPEC.md` and the other jev-local design docs. Legacy: runtime CONTRACT §1 says not to edit them. Doc: [genclass-model-lineage](genclass-model-lineage.md). -- **CONTRACT (runtime)**: `docs/runtime/CONTRACT.md`, the binding build contract owned by the lead: §0 ground rules (no hardcoded bug rules, one situation implementation shared with the sim, determinism through the injected `Clock`, sim and demos never read each other, no runtime dependency besides `onnxruntime-web`, builds on the VM), §0.5 product principles, §1 layout and owners, §2–§12 spec (§8 = the policy gate), §13 approved additions. Last edited in a53dd38, before batch 3, so it lags the code. Doc: [status-and-known-issues](status-and-known-issues.md). +- **CONTRACT (runtime)**: `docs/runtime/CONTRACT.md`, the binding build contract owned by the lead: §0 ground rules (no hardcoded bug rules, one situation implementation shared with the sim, determinism through the injected `Clock`, sim and demos never read each other, no runtime dependency besides `onnxruntime-web`, builds on the VM), §0.5 product principles, §1 layout and owners, §2–§12 spec (§8 = the policy gate), §13 approved additions. Substantively last edited in a53dd38 (before batch 3); f3636b2 only appended the observe-default §13 entry. It has no `delivery` trigger or `holdWrites`, so it lags the code. See also [HANDOFF.md](../../HANDOFF.md), [RESULTS.md](../runtime/RESULTS.md). Doc: [status-and-known-issues](status-and-known-issues.md). - **CONTRACT-D row**: One JSONL training example `{id, split, family, state, questions, labels, meta}` (legacy CONTRACT section D, referenced by runtime CONTRACT §11), written by the sim and the curriculum and read by the trainer. Labels: choice `{label}` or `{dist}`, noul `{p}`, score `{level}` or `{dist}`; a qid without a label is packed but unsupervised. Code: `sim/src/types.ts` -> `Row`, `Label`; `jev_local/train/train.py` -> `parse_target`. Doc: [model-io-contract](model-io-contract.md), [sim](sim.md), [training](training.md). - **Controller (extension)**: The extension's incremental voice decision loop (debounce, coalescing, stale rule, execute, consume, re-decide), a port of `jev_local/harness/controller.py`. See *harness (extension)*. Code: `extension/src/core/controller.js` -> `Controller`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **Controller (runtime)**: The seam between the decision flow and one trigger subject: `passive()` lets the subject proceed unchanged; `run(action)` performs a built-in action and returns `ActionEffect { changed, undo? }`, or throws/rejects, after which the passive action runs and the attempt is recorded `ok: false`. Held mutations also have `revertable()` / `revert()` for a late revert. Code: `packages/runtime/src/decide/exec.ts` -> `Controller`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **CORE (workstream)**: Owns `packages/runtime/**` except `packages/runtime/src/{model,devtools,adapters}/**`, including the situation wording and `packages/runtime/src/types.ts`; writes `packages/runtime/STATUS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). - **cost (sim)**: `runCost`, a run's cost relative to the ideal run: 1.0 × D(t) integrated over the 10 s after the decision + 4.0 × final client divergence + server damage (25 per extra/missing item, 6 per differing field or counter unit) + 0.8 × relation-violation seconds + 2.0 × relations still violated at the end + 1.5 × shown errors + 1.0 × uncaught errors + 0.08 × extra requests + 0.25 × pending seconds; "final" is decision + 15 s. Code: `sim/src/oracle/cost.ts` -> `runCost`, `W`. Doc: [sim](sim.md). - **counterfactual run / counterfactual cost (sim)**: A sim re-run with a forced map (explored choices before decision `k`, action `a` at `k`, passive after), stopped at `t_k + 15 s` and required to reproduce the base run's fingerprints up to `k`; its `runCost` against the ideal run is the counterfactual cost of `a` at `k`. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `pointCosts`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). +- **covered write**: A store write whose causal chain (≤ 16 ancestors) passed a delivery gate whose predicted write set was known and includes every changed path, and that delivery was not salient or was decided in time. A covered write raises no `mutation` trigger (never covered with `triage: "always"`), so one response costs at most one model call. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.covered`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **createRuntime**: The headless entry point (tests, sim, SSR): builds a `RuntimeImpl`, creating and owning a model host only when `decider` is `undefined` and `model` is an object. It can throw on malformed options and never sets `GenClass.runtime`. Code: `packages/runtime/src/index.ts` -> `createRuntime`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **CU / GEN**: The two sets of the GenClass-vs-Jev head-to-head: CU = synthetic computer-use harness examples (the extension's domain), GEN = generic questions from task families held out of training. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **cur1 / cur2 / cur3 / cur4**: Curriculum datasets from `training/curriculum/generate.py`: `cur1` 800k train rows, all varied style (seed 1); `cur2` 400k, `--p-runtime 0.6` with the pre-freeze `rt.py` (seed 2); `cur3` 300k stage-2 replay, `--p-runtime 0.8`, pre-freeze wording (seed 4); `cur4` 300k final replay in the frozen `situation-v1` wording, `--p-runtime 0.8` (seed 5). `--p-runtime` is the share of decision rows rendered runtime-exact. Doc: [training](training.md). +- **cur1 / cur2 / cur3 / cur4**: Curriculum datasets from `training/curriculum/generate.py`: `cur1` 800k train rows, all varied style (seed 1); `cur2` 400k, `--p-runtime 0.6` with the pre-freeze `rt.py` (seed 2); `cur3` 300k stage-2 replay, `--p-runtime 0.8`, pre-freeze wording (seed 4); `cur4` 300k final replay in the frozen `situation-v1` wording, `--p-runtime 0.8` (seed 5). `--p-runtime` is the share of decision rows rendered runtime-exact. All four predate situation-v2; `training/curriculum/rt.py` now renders v2 text (d73d20c), but no v2 curriculum set has been generated (and the review found several places where `rt.py` diverges from the runtime). Doc: [training](training.md). - **custom action**: An `ActionDef` added with `rt.action(def)`, a plugin's `actions` or the `plugins` option. Offered when `def.on` includes the trigger, the name is new and `applicable(draft)` is true; gated at its own tier (default `heal`); runs inside a GenClass op; `ctx.builtin(name)` may run an offered built-in (re-checked for mode, deny/allow, pause and rate limit, not thresholds); if no built-in took over, the passive action runs afterwards. Code: `packages/runtime/src/types.ts` -> `ActionDef`, `ActionContext`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). ## D +- **DAgger / on-policy rows**: The planned last training phase (PLAN-v1 P5): export a trained student, run it as the sim's policy (`gen.js --on-policy <export dir>`: the runtime's own model host on onnxruntime-web WASM decides through the production gate, no exploration, no ask probes), counterfactual-label the states the student actually visits, and retrain on them so the model learns from its own mistakes. On-policy rows have ids `p-<seed>-d<k>` and `meta.on_policy: true`, `model_probs`, `model_choice`, `model_diagnosis`, `ran`, `false_intervention`, `miss`. Not scripted in `training/` yet; no student to run exists for situation-v2. Note the sim's runtime runs in `heal` mode, not the shipped default. Code: `sim/src/run/onpolicy.ts` -> `loadModelDecider`; `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md), [training](training.md). - **D(t) (sim)**: Weighted client divergence of a run's stores from the ideal run's at the same time: each field contributes `w × d` with `d ∈ [0, 1]`, lists compared as multisets of item content. Integrated over the 10 s after a decision in the cost. Code: `sim/src/oracle/cost.ts` -> `clientDist`, `divergenceArea`. Doc: [sim](sim.md). - **data-genclass-ignore**: Attribute that makes the DOM user observer skip events from inside the marked subtree, crossing shadow roots; the devtools host carries it. Code: `packages/runtime/src/observe/dom-user.ts` -> `ignoredEvent`. Doc: [devtools](runtime/devtools.md), [observe-and-trace](runtime/observe-and-trace.md). -- **DeciderQueue**: The single-flight priority queue in front of the `DecisionProvider`: highest priority then oldest first; ≤ 32 queued (overflow drops the lowest-priority, oldest item); deadlines; a 10 s runtime-side timeout when there is no deadline; the answer cache; the last 20 provider latencies for the auto hold budget. Every fail-open path resolves `null`, never rejects. Code: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **DeciderQueue**: The single-flight priority queue in front of the `DecisionProvider`: highest priority then oldest first; ≤ 32 queued (overflow drops the lowest-priority, oldest item); deadlines; a stale check (since batch 4, a queued item whose subject already proceeded or was superseded is dropped without a model call, `Controller.stale`); a 10 s runtime-side timeout when there is no deadline; the answer cache; the last 20 provider latencies for the auto hold budget. Every fail-open path resolves `null`, never rejects. Code: `packages/runtime/src/decide/decider.ts` -> `DeciderQueue`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **Decision (extension)**: The extension controller's per-update result `{verdict, action, reason, seq, retryInMs, answers, latencyMs, risk}`. See *verdict (extension)*. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **Decision (runtime)**: The record `d<n>` made for every model answer to a trigger that reaches `onDecision` (never for `ask`/`decide`, while loading, for triage-skipped triggers or for failed queue items): diagnosis and its probabilities, `action` (the action that ran, else the model's top choice), `ran` (what actually executed, passive included), `executed`, `reason`, `candidate`, `mass`, facts (≤ 12), `answers`, `subjectRef`. `Detection` is a type alias. Code: `packages/runtime/src/types.ts` -> `Decision`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **decision point (sim)**: `DecisionRec`: one `evaluate` call recorded in the base run (`k` = 0-based index, `t`, `trigger`, `state`, `questions`, `actions`, `chosen`, `explored`, `diagnosis`, `subject`, `fp`); a trajectory labels up to `maxPoints` of them. Code: `sim/src/run/runner.ts` -> `DecisionRec`. Doc: [sim](sim.md). - **Decision Score (jevbench)**: `clip(1 − mean Brier / mean prior Brier, −1, 1)` per dataset. Code: `jev_local/bench/metrics.py` -> `decision_score`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **DecisionProvider**: The only seam between the runtime and a model: `{ status, ready(), evaluate(req), onStatus?(fn), dispose?() }`. Implemented by the model host, the test deciders, the sim's recording decider and `failedProvider`; passed as `options.decider`, which wins over `options.model` (`null` = no model). `evaluate` receives `EvaluateRequest { trigger, state, questions, priority?, subject?, timeoutMs? }`. Code: `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [model-io-contract](model-io-contract.md). - **decontamination stage 1 (benchmax)**: Name-level exclusion of training sources per track. Code: `jev_local/bench/registry.py` -> `is_excluded`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS item 8; no `runtime-model-v0.1.0` tag in the repo; the URL was not checked), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). -- **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published at 654d822, so a default `GenClass.init()` ends with model status `error` and only observes. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). -- **defer (action)**: Guard-tier `mutation` action, offered while the write was deferred fewer than 2 times: wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS "Next": Model package, currently item 9; release procedure in [RELEASE.md](../../RELEASE.md) Part B; no `runtime-model-v0.1.0` tag in the repo; the lead found it returns 404 on 2026-10-08), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published (npm 404 on 2026-10-08, and no situation-v2 model exists to publish), so a default `GenClass.init()` ends with model status `error` and only observes; since f3636b2 it is also in `observe` mode by default. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **defer (action)**: Guard-tier action of `mutation` and `delivery`, offered while the subject was deferred fewer than 2 times. Mutation: with `holdWrites: true`, wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies; with `holdWrites` off it is offered but only recorded (the write already applied). Delivery: offered only when related ops are in flight (same name outside the op's chain, or whose signatures wrote a matched store); hold the response or message, wait for them (`waitOps`), then decide again. A review finding: each delivery defer waits up to 10 s (`LONG_RUNNING_MS`), not the hold budget, so two defers can hold a response for 20 s, and on a push channel every later message waits behind it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`, `RuntimeImpl.runDelivery`, `RuntimeImpl.waitOps`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **delay (action)**: Guard-tier `request` action (fetch and XHR): wait `min(250 × 2^failStreak, 8000)` ms, where `failStreak` is the signature's current failure streak, then send. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **deliver (action)**: Passive action of the `failure` trigger: hand the original `Response` or rejection to the app. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **deliver (action)**: Passive action of the `failure` trigger (hand the original `Response` or rejection to the app) and of the `delivery` trigger (pass the response or message to the app now). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **delivery (trigger)**: The situation-v2 decision point (batch 4): a fetch or async-XHR response, or a WebSocket/EventSource message, is about to reach the app. `runDelivery` predicts the op's write set (from its transition profile, else the last completion of its signature) and raises the trigger only when that set has a newer-data conflict the body would change, a pending local change the body would put back (F1), or text the user typed since the request started that the body would replace (F2); it reads the body (a clone, JSON, ≤ 256 KB) only for such candidates, waiting ≤ 100 ms (`BODY_WAIT_MS`). Holdable, priority 2; held only when a non-passive action is permitted and the expected model latency fits the hold budget, so holding a delivery is only added latency and channel order is kept. Actions `deliver` (passive), `discard`, `defer`. Trigger sentence: `The response to <opLabel> arrived and is about to be delivered; …`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`; `packages/runtime/src/situation/env.ts` -> `DeliverySpec`; `packages/runtime/src/observe/messages.ts` -> `MessageGate`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **delta signature**: `deltaOf` output that is equal for "the same change applied again": `n:<diff>` (numbers), `a:+added|-removed` (array multiset diff), `o:<hash>` (pure reorder), `c:+k/~k/-k` (collections), `v:<hash>` (anything else), `x:removed`. Feeds `RecentChange.key` and the repetition facts. Code: `packages/runtime/src/state/fields.ts` -> `deltaOf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). -- **demo mode**: `GcMode = "off" | "guard" | "heal"`. Off = `GenClass.init({ mode: "observe", model: false })`, the baseline; Guard and Heal init with that mode and `model: { baseUrl, preload: "eager" }`. Not the same as `?genclass=off`, the runtime kill switch that installs nothing. Code: `demos/src/shared/types.ts` -> `GcMode`; `demos/src/shared/genclass.ts` -> `startGenClass`. Doc: [demos](demos.md). +- **demo mode**: `GcMode = "off" | "guard" | "heal"`. Off = `GenClass.init({ mode: "observe", model: false })`, the baseline; Guard and Heal init with that mode and `model: { baseUrl, preload: "eager" }`. The demos always pass a mode explicitly, so the runtime's default-mode change does not affect them (the file comment still calls guard "the default"). Not the same as `?genclass=off`, the runtime kill switch that installs nothing. Code: `demos/src/shared/types.ts` -> `GcMode`; `demos/src/shared/genclass.ts` -> `startGenClass`. Doc: [demos](demos.md). - **DEMOS (workstream)**: Owns `demos/`; writes `demos/NEEDS.md`, `demos/README.md` and `demos/results*.{md,json}`. Doc: [status-and-known-issues](status-and-known-issues.md), [demos](demos.md). - **describeElement**: Public helper returning `role "name"` for a DOM element (e.g. `button "Place order"`); the name comes from aria-label, labelledby, labels, text, placeholder, title, name, button value or id (≤ 40 chars), never from a typed value. Code: `packages/runtime/src/observe/dom-user.ts` -> `describeElement`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **detached preview / unholdable**: When a guarded functional updater mutated the stored value in place, the hub clones the result and restores the live value (`restoreInPlace`) so the write can still be held; if that fails the write is *unholdable* and applies at once. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **detection**: A `Decision` whose diagnosis is not `expected` and whose diagnosis probability is ≥ `thresholds.report` (0.6), whether or not an action ran. Fires the `detect` event, and a `[GenClass] Flagged …` report when no action ran. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **detection card (devtools)**: `article.card.det`, keyed by decision id, for a detection that did not run a non-passive action; it moves to Interventions when an `act` arrives for that decision. Doc: [devtools](runtime/devtools.md). -- **diagnosis**: The `diagnosis` question (choice, header "What is happening here?") asked on every trigger except `ask`, over the diagnosis vocabulary: by default `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`, `expected` always first. The policy gate requires the top diagnosis to differ from `expected` (`requireDiagnosis`). In sim rows the label is a hard label from the sim's own knowledge. Code: `packages/runtime/src/situation/questions.ts` -> `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). +- **determinism sweep (realapps)**: `debug.js --det <seeds>`: runs each app's base run twice in one browser context and compares the snapshots, network and server; at situation-v2 198/198 runs were identical (66 apps, seeds 1–3). It does not check counterfactual, re-seeded-future or cross-worker runs. Code: `realapps/src/harness/debug.ts`. Doc: [realapps](realapps.md). +- **diagnosis**: The `diagnosis` question (choice, header "What is happening here?") asked on every trigger except `ask`, over the diagnosis vocabulary: by default `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`, `expected` always first. The policy gate requires the top diagnosis to differ from `expected` (`requireDiagnosis`). In sim rows the label is a hard label from the sim's own knowledge, corrected by *S1 (sim label rule)* when acting clearly wins, and `delivery` diagnoses come from the verdict of the first write the delivered op or message makes; realapps uses its own in-page rules (`realapps/src/world/diagnose.ts`). Code: `packages/runtime/src/situation/questions.ts` -> `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). - **diagnosis-only row (sim)**: A decision with fewer than 2 applicable actions (so no `action` question): the row carries only a `diagnosis` label and no counterfactuals; at most 3 per trajectory. Doc: [sim](sim.md). -- **discard (action)**: Guard-tier `mutation` action: drop the held write and keep the current state (the `set` caller is not notified); undo applies the write on top of the current value. Also the action behind a late revert. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **draft (SituationDraft)**: The structured view of a situation handed to plugin `facts()` and `ActionDef.applicable()`: trigger, subject, now, op, root, stores, mutation/request/failure/error/invariant details, facts, in-flight ops. Code: `packages/runtime/src/types.ts` -> `SituationDraft`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **discard (action)**: Guard-tier action of `mutation` and `delivery`. **Delivery**: deliver the response or message anyway, but drop the state changes its chain makes over newer data, by setting a *discard mark* on the op; the `ActionRecord` lists the dropped paths in `dropped`. **Mutation**: with `holdWrites` on, drop the held write and keep the current state (the `set` caller is not notified; undo applies the write on top of the current value); by default (non-blocking mutation) a gate-passing discard becomes a *late revert*. Review findings: on Redux/Zustand adapter stores a delivery discard a dispatch that also changes other fields is applied whole (fail-open) while the record's `changed` text still names the dropped fields (`dropped: []`); a dispatch whose every change is dropped is discarded, and the mark can also drop later fresh writes chained from the discarded op. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`, `RuntimeImpl.gateMutation`, `RuntimeImpl.mutationController`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **discard mark / drop filter**: `OpRec.discardMark = { protect, until, dropped, onDrop? }`, set by a delivery `discard` for `DISCARD_MARK_MS` (10 s). While it lasts, `StoreHub.propose` asks `RuntimeImpl.dropFilter` which changes of each non-user-sync write caused by that op (walking ≤ 16 causes) to drop: paths in `protect` (the conflicting fields at decision time) and any path that a user action or a newer op outside the marked op's chain wrote since it started (`writtenOver`). The hub's private `applyFilter` removes them before the write applies. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter`, `RuntimeImpl.writtenOver`, `RuntimeImpl.onDropped`; `packages/runtime/src/trace/ops.ts` -> `OpRec`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **distillation (student)**: Training a small shippable *student* (R17 by default, R32, or the R68 benchmark) on gold rows plus rows soft-labelled by the never-shipped *teacher* (T150), with 5–10% curriculum replay (PLAN-v1 P4). Launched with `training/launch_student.sh`; no distillation mixture exists yet and nothing has been distilled for situation-v2. Doc: [training](training.md). +- **draft (SituationDraft)**: The structured view of a situation handed to plugin `facts()` and `ActionDef.applicable()`: trigger, subject, now, op, root, stores, mutation/request/failure/error/invariant details, `delivery?: { channel, predicted, conflicts }`, facts, in-flight ops. Code: `packages/runtime/src/types.ts` -> `SituationDraft`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). ## E @@ -126,22 +137,23 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## F -- **F80**: The Azure VM size of the TRAIN nodes (`c01`, `c02`–`c11`), about $5.46/h per node (`training/LOG.md`); training runs use 8 ranks × 10 threads per node. Doc: [training](training.md). +- **F1–F9 (evidence facts)**: The situation-v2 facts proposed in `sim/SEPARABILITY.md` §6 to separate clear actionable cases from benign look-alikes, implemented in batches 4–5 (not to be confused with the runtime's older per-trigger fact ids such as F1 = "this request failed"). **F1** put back an older value: the response/write has the value a newer op (or a still-pending user change) replaced, per field or per item cell joined on an id key (salient). **F2** replace typed text: the response would replace text the user typed into a field after the request started, with a diff-centred preview (salient). **F3** no change: the body equals the current value of everything it is predicted to write (neutral; for a delivery this also makes it non-salient and logs `delivery.unchanged`). **F4** has no runtime fact of that name; SEPARABILITY's F4 idea became the *read-your-writes* fact. **F5** failure scope (other endpoints of the origin failing, `navigator.onLine` false) and commit ambiguity of a failed non-GET. **F6** learned *cadence*. **F7** repeat-action evidence (`MouseEvent.detail`, request still in flight). **F8** relation quality in the invariant miner (no spurious `==`/`∈` relations; count-by-group template); it changes which invariants exist, not a fact sentence. **F9** stale marks: a field last written by a response delivered over newer data, a ≥ 5× slow response, a write after an ambiguous failure, or a push received while its channel had been down. All are neutral unless stated. Review findings: F2 can print redacted text, and F5 calls HTTP 502 "usually not processed". Code: `packages/runtime/src/situation/content.ts` -> `contentFacts`, `pendingRevertFacts`, `rywFacts`; `packages/runtime/src/situation/evidence.ts` -> `markFacts`, `cadenceFact`, `scopeFacts`, `commitAmbiguity`, `repeatEvidence`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **F80**: The Azure VM size of the cluster nodes (`c01`–`c23`), about $5.46/h per node (`training/LOG.md`); training runs use 8 ranks × 10 threads per node. Doc: [training](training.md). - **facade**: `GenClass` (named and default export), the browser singleton around `createRuntime`. `GenClass.init(options)` never throws (it falls back to an inert runtime), is idempotent (a second call returns the first runtime and ignores its options), applies the kill switch and loads the local model by default; `GenClass.runtime` and `GenClass.destroy()` complete it. Code: `packages/runtime/src/index.ts` -> `GenClass`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **fact**: `Fact { text, kind, neutral }`: a uniform English sentence computed per trigger by `computeFacts`; `neutral: false` makes the situation salient. Ordered non-neutral first, then by kind rank (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), capped at 12 (`MAX_FACTS`). Plugin facts are always neutral. Code: `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **fail open**: The universal fallback: no provider, provider not ready, any provider error, queue overflow, an expired deadline, hold-budget expiry or a throwing action all run the passive action, so a missing or slow model never blocks the app. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [model-host](runtime/model-host.md). - **failure (baseline)**: A completion whose `EndOpts.failure` is set: network error, timeout, HTTP 5xx, 429 or 408 (a 404 is not a failure). Failures feed fail streaks and outcomes, never latency samples. Code: `packages/runtime/src/observe/fetch.ts` -> `FAILURE_STATUS`; `packages/runtime/src/learn/baselines.ts` -> `Baselines.end`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **failure (trigger)**: Raised when a request fails (see *failure (baseline)*) before the app sees the failure. Fetch failures go through the holdable failure gate (priority 2 when held), but are held only when a non-passive failure action is permitted: `retry` and `serve_cached` are heal tier, so in the default `guard` mode (and in `observe`) the failure is delivered at once and decided in the background (priority 1, 5 s deadline) unless a guard-tier custom action applies. XHR failures are never held (priority 1) and are detection-only. Actions `deliver` (passive), `retry`, `serve_cached`; fact F1 makes it always salient. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **failure (trigger)**: Raised when a request fails (see *failure (baseline)*) before the app sees the failure. Fetch failures go through the holdable failure gate (priority 2 when held), but are held only when a non-passive failure action is permitted: `retry` and `serve_cached` are heal tier, so in the default `observe` mode and in `guard` the failure is delivered at once and decided in the background (priority 1, 5 s deadline) unless a guard-tier custom action applies. XHR failures are never held (priority 1) and are detection-only. Actions `deliver` (passive), `retry`, `serve_cached`; fact F1 makes it always salient. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **fake runtime (sim)**: `createFakeRuntime`, a crude test double of the runtime used by default in the sim's vitest suites (`SIM_RUNTIME=real` switches to the real one). Its rows are marked `meta.runtime: "fake"`; `gen.js` uses it only with `--allow-fake`. Code: `sim/src/run/fake-runtime.ts` -> `createFakeRuntime`. Doc: [sim](sim.md). - **FakeClock / FakeServer**: Runtime test kit: `FakeClock` is a virtual clock starting at `t = 1000` with `advance(ms)`, `flush()` and `runAll(maxMs = 120000)`; `FakeServer` is a virtual HTTP server exposed as `fetch` (routes keyed `METHOD pathname`, default latency 50 ms, unknown routes 404) that records hits. Code: `packages/runtime/test/helpers.ts` -> `FakeClock`, `FakeServer`. Doc: [build-test-release](runtime/build-test-release.md). - **false intervention (demos)**: One `act` event (an executed non-passive action, including failed attempts and late reverts) on a clean trial. A different metric from TRAIN's *FIR*. Doc: [demos](demos.md). - **family (sim)**: Program family = the sorted feature kinds joined by `+` (e.g. `cart+search`); a sim row's `family` is `<program family>/<trigger>`, and families whose hash falls in the first 17% go to test. Curriculum rows use `cur/<trigger>/<case>` families instead. Code: `sim/src/world/scenario.ts` -> `familyHeldOut`, `splitOf`. Doc: [sim](sim.md), [training](training.md). - **FastEngine**: The Python model engine ("jev-local-fast"): an ettin encoder with typed heads over marker tokens and one packed sequence per request with block attention, so answers are exactly invariant to option order and to other questions. Checkpoints are `backbone/`, `heads.safetensors`, `calibration.json`, `meta.json`. Code: `jev_local/engine/encoder/engine.py` -> `FastEngine`. Doc: [genclass-model-lineage](genclass-model-lineage.md). -- **feature combinator (sim)**: A `FeatureDef` (`make`, `pattern`, `server`, `client`, `session`, optional `external`, `relations`) from which scenarios build random apps; 15 kinds: search, editor, form, cart, toggle, counter, poll, board, chat, settings, nav, list, bulk, auth, benign. Code: `sim/src/app/feature.ts` -> `FeatureDef`; `sim/src/app/features/index.ts` -> `FEATURES`. Doc: [sim](sim.md). +- **feature combinator (sim)**: A `FeatureDef` (`make`, `pattern`, `server`, `client`, `session`, optional `external`, `relations`) from which scenarios build random apps; 46 kinds: the 15 round-1 kinds (search, editor, form, cart, toggle, counter, poll, board, chat, settings, nav, list, bulk, auth, benign) and 31 round-2 kinds (badge, cascade, cdn, clockskew, countdown, etag, exportjob, facets, flags, graphql, infinite, inventory, longtask, masterdetail, money, multitab, offline, payment, permissions, prefetch, presence, querycache, ratelimit, reorder, saga, schemadrift, swcache, undo, upload, wizard, wsreconnect); 6 are held out for test (`TEST_FEATURES`). Code: `sim/src/app/feature.ts` -> `FeatureDef`; `sim/src/app/features/index.ts` -> `FEATURES`. Doc: [sim](sim.md). - **feed pause (devtools)**: Overlay-only freeze of list, activity and Now rendering; intake and counters continue and "N new" is counted. Unrelated to `runtime.pause()`. Doc: [devtools](runtime/devtools.md). - **field / path / leaf**: A store value is flattened into dotted fields `store.k1.k2` (at most 4 key levels). Arrays, plain objects with more than 32 keys or none, and non-plain objects are one leaf each; a store has a soft cap of 200 fields. `Leaf { value, hash, kind, len, elems?, keys?, khash?, src? }`. Code: `packages/runtime/src/state/fields.ts` -> `flatten`, `Leaf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **FieldState / FieldHist / LogEntry**: Per-field bookkeeping in the hub: version `v`, writer op, `t` and `seq`; the last 16 writes with before/after values (history); the last 512 writes as compact entries (log). Facts read field versions from them. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). -- **final round 1 / 2**: TRAIN's final training of R17 and R32 on frozen-format data. Round 1 = SIM phase A plus `cur4`/`cur1`/`gen` replay (`mix_final1`), launched 2026-10-08 00:06–00:12 UTC, with no results in the repo; round 2 = phase A + B with longer schedules, planned. Doc: [training](training.md), [status-and-known-issues](status-and-known-issues.md). +- **final round 1 / round 2**: TRAIN's training rounds on frozen-format data. Round 1 = R17 and R32 on situation-v1 SIM phase A plus `cur4`/`cur1`/`gen` replay (`mix_final1`), 2026-10-08 00:06–01:36 UTC, done: R17 90.5% diagnosis, 81.9% action, guard FIR 0.05%, heal FIR 0.24%, but recall on clear stale/duplicate cases only 7.7% (R32 no better, so R17 is the default on every device). Its exports live only on the train VM and the colleague's Mac and do not match the v2 runtime. "Round 2" (format v2: ~10M SIM gold + ~50M unlabeled + ~0.5M real-browser rows) is now the teacher → distillation → DAgger program of `training/PLAN-v1.md`, in progress (data generating). Doc: [training](training.md), `docs/runtime/RESULTS.md`. - **FIR**: False-intervention rate in TRAIN's evaluation: gate fires on passive-best rows ÷ passive-best rows, per mode (guard, heal), with the runtime's policy gate mirrored in Python. Code: `training/eval_runtime.py` -> `decision_metrics`. Doc: [training](training.md). - **fixed / introduced (demos)**: Paired with Off on the same chaos seed: *fixed* = Off had the bug and the mode did not; *introduced* = Off was fine and the mode had the bug. Read against A/A noise. Code: `demos/src/shared/aggregate.ts` -> `summarizeMode`. Doc: [demos](demos.md). - **FIXTURES_FROM_MODEL**: Flag in the model test helpers, true when `requests.json`, `pack_fixtures.json` and `torch_fixtures.json` exist in the model directory (written by `training/export_runtime.py`); the unit parity tests then use them instead of the v0.1 fixture set (browser specs never do). Code: `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL`. Doc: [build-test-release](runtime/build-test-release.md). @@ -149,11 +161,12 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **fp (fingerprint, sim)**: `JSON.stringify([trigger, state, questions])` of a decision. A counterfactual run must reproduce the base run's fp for every decision up to `k`; otherwise the point is dropped as `prefix-mismatch`. Doc: [sim](sim.md). - **fragment / pass (FastEngine)**: When a choice/score question's header and items exceed the room left after the state, `plan_passes` splits it into contiguous option fragments (header repeated) packed into passes that each repeat the state; fragment logits are concatenated and calibrated with one softmax, so the result equals a single pass. Python only: the runtime packer is single-pass. Code: `jev_local/engine/encoder/engine.py` -> `plan_passes`. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **freeze / quiet / settle (demos)**: After a trial's steps the harness freezes scripted world activity, waits for quiet (no request in flight and no pending SSE delivery for `idleMs`, default 700 ms, timeout 20,000 ms) unless the demo sets `settle: false`, then waits 2,500 ms (350 ms with `settle: false`) so held writes and late reverts land before the oracle scores. Code: `demos/src/server/core.ts` -> `World.quiet`. Doc: [demos](demos.md). -- **frozen runtime**: `packages/runtime/src` unchanged since tag `situation-v1`. Changing anything that reaches model input needs the lead, SIM and TRAIN; only the runtime source is frozen (sim, training and demos changed after the tag). Doc: [status-and-known-issues](status-and-known-issues.md). -- **future (sim)**: One re-seeded continuation after a decision point. Future 0 keeps the base run's draws; futures 1..K−1 re-seed network, push, model-latency and external-event draws after the decision with a salt shared by all actions (common random numbers). K = 3, but futures beyond 0 run only when some non-passive action beats passive by more than 0.05 in future 0. Code: `sim/src/gen/trajectory.ts` -> `pointCosts`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). +- **frozen runtime**: The model-input code of `packages/runtime/src` (situation, learn, `util.ts` formatters, `state/fields.ts` text helpers, questions, budgets) unchanged since the current freeze tag, now `situation-v2` (6e5e86e); `situation-v1` is the previous one. On `mvp-v2` only `runtime.ts`, `types.ts` and `devtools/index.ts` changed after the tag (the default mode), which is not model input. Changing anything that reaches model input needs the lead, SIM, REAL and TRAIN, a new tag and regenerated data (HANDOFF: "coordinate before touching it"). Doc: [status-and-known-issues](status-and-known-issues.md). +- **future (sim)**: One re-seeded continuation after a decision point. Future 0 keeps the base run's draws; futures 1..K−1 re-seed network, push, model-latency and external-event draws after the decision with a salt shared by all actions (common random numbers), and with *S2* on (default) also re-draw the unobservable latents. K = 3: with S2 on, future 1 always runs and future 2 only when some non-passive action beat passive by more than 0.05 in a future seen so far (with S2 off, futures beyond 0 need that margin in future 0). Code: `sim/src/gen/trajectory.ts` -> `pointCosts`; `sim/src/run/latent.ts` -> `FutureSpec`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). ## G +- **gain head / gain (T1)**: An extra per-action regression head that predicts the expected *gain* of an action over passive, E[gain | situation], from SIM's `meta.cost_futures`: gain(a) = mean over futures of cost(passive) − cost(a) − tier premium (guard 0.25, heal 0.5), clipped to ±30. The idea is to fire when predicted gain exceeds a tier margin instead of gating on summed probability (*T1*). The head, the trainer flag `--gain-loss` and `HeadOut.gain` exist only in the parent-repo `jev_local` on the Azure nodes, not in this monorepo, so `training/collect_gain.py` fails here. The one gain-head run (`r17-t1h`, v1 data) was stopped at about step 1,000 with no result. Code: `training/t1_relabel.py` -> `gains_of`; `training/collect_gain.py`. Doc: [training](training.md), `sim/SEPARABILITY.md` §5, §7. - **gated (`NetHost.gated`)**: `!paused && !destroyed && !op.genclass`. Only gated fetch/XHR ops raise request, failure or stall triggers, are held or are stall-watched. Code: `packages/runtime/src/decide/exec.ts` -> `NetHost`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **gen / cu (buckets)**: GenClass 0.1 (v1) synthetic training data (`data/gen`, a slice of `data/cu`: generic and computer-use examples) mixed into runtime-model training as replay only. Doc: [training](training.md). - **GenClass**: Project name: the GenClass 0.1 model and Chrome extension of the jev-local era, and now `@genclass/runtime`. In code, the facade object `GenClass` exported by the runtime. See *facade*, *GenClass 0.1*. @@ -161,40 +174,44 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **GenClass op**: An instant op of kind `genclass` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause `null`) for undo, revert, rollback, resync and custom actions. Writes and requests inside it are never gated and are excluded from baselines and profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runAsGenClass`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **genclass-<size> / meharsjev-<size>**: Model ids allowed for benchmax runs (`genclass-<size>`, legacy `meharsjev-<size>`); `jev-*` and `typesafe/*` ids are rejected (W10). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **genclass-runtime (CLI)**: The package's bin: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info <dir>` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`. Doc: [model-host](runtime/model-host.md). -- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`); `0.1.0-alpha.0` is published (per `OPEN_TASKS.md`). Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md). -- **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0. Only `packages/runtime-model/MODEL_CARD.md` exists. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). -- **`@genclass/sim` / `@genclass/demos`**: The private workspaces `sim/` and `demos/`. Both depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first. Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). +- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.0` is the latest published version: it predates batches 4–5 and the observe default (its default is `guard`), and with no published model it takes no actions. A `0.1.0-alpha.1` patch with the NaN fix needs the owner's 2FA (`OPEN_TASKS.md` "Needs the user"); `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) +- **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0 (npm 404). Only `packages/runtime-model/MODEL_CARD.md` exists. 0.1.0 must be a situation-v2 model, which does not exist yet. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **`@genclass/sim` / `@genclass/demos` / `@genclass/realapps`**: The private packages `sim/` and `demos/` (root workspaces) and `realapps/` (not a workspace). `sim` and `demos` depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first; `realapps/build.mjs` bundles the runtime from source instead (`RW_RUNTIME_SRC`, default the working tree). Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). - **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `<repo>/.cache-model`, filled with `genclass-runtime fetch-model <dir> --from <v0.1 release URL>` (ask first; the default `--from` is unpublished)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). - **GENCLASS_REPLACE**: `"@@genclass/REPLACE"`, the Redux action the enhancer uses for GenClass's whole-state writes (rollback, revert); it never reaches the app reducer. Code: `packages/runtime/src/adapters/redux.ts` -> `GENCLASS_REPLACE`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **GenClassUnavailableError**: The error `rt.ask()` / `rt.decide()` reject with when no model can answer; `reason` is `destroyed`, `off`, `timeout` or `error` (with `timeoutMs` set, a raw provider load error can escape instead). Provider errors never escape a trigger. Code: `packages/runtime/src/errors.ts` -> `GenClassUnavailableError`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **gold row**: A training row with counterfactual action labels (SIM's default row mode; REAL's decision rows): the scenario is re-run once per applicable action at the decision point over 2–3 paired futures, and costs become a soft `action` label (`actionLabel`) plus a hard `diagnosis` label (with *S1*). SIM v2 targets ≥ 10M gold rows (seeds from 11e9), REAL about 495k ([HANDOFF](../../HANDOFF.md)/[RESULTS](../runtime/RESULTS.md); NEEDS target ≥ 500k). Contrast *unlabeled rows* and *on-policy rows* (see *DAgger*). Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts`. Doc: [sim](sim.md), [realapps](realapps.md). - **guard (store kind)**: A store whose value the app owns behind `get` / `set` / `subscribe` (`rt.guard(name, io, opts)`); external changes arrive through `subscribe` and are recorded, never held; always writable. Not the same as the guard mode or tier (see *mode*, *tier*). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.guard`; `packages/runtime/src/types.ts` -> `StoreIO`. Doc: [state-and-adapters](runtime/state-and-adapters.md). ## H +- **HANDOFF.md**: The colleague's repo-root "read this first" for continuing Claude sessions (d73d20c): current state (npm, git tags, runtime, model, data, training), repo map, hard rules (the 8 GB Mac must not run npm/tsc/vitest/browsers/models; Azure etiquette; the frozen format; licensing; commit identity) and how to continue. Its Mac rule is about the colleague's machine; our run policy lives in `AGENTS.md`. It still calls guard the default mode. Doc: [status-and-known-issues](status-and-known-issues.md)., [HANDOFF.md](../../HANDOFF.md), [RESULTS.md](../runtime/RESULTS.md) - **harness (extension)**: The extension's incremental voice decision loop (`extension/src/core/controller.js` with the policy, safety, stream and spans modules) and its Python original `jev_local/harness/*` (macOS voice computer use); the JS core is parity-tested against fixtures generated from the Python. Code: `extension/src/core/controller.js` -> `Controller`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **header / item**: A question's header is its `instructions` text (a default when missing); its items are the options (choice: `label` or `label: desc`), the levels (score) or the true/false criteria (noul). Question ids are never shown to the model. Code: `packages/runtime/src/model/serialize.ts` -> `questionBlock`. Doc: [model-io-contract](model-io-contract.md). - **header key**: `sha1(header)[:12]`, the key of `calibration.json` `by_header` (e.g. `041ccfa6318c` = "What is happening here?"). Code: `packages/runtime/src/model/calibrate.ts` -> `headerKey`. Doc: [model-io-contract](model-io-contract.md). - **heads**: The graph outputs `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` (raw, τ = 1), computed from marker hidden states: choice and score MLPs over `[h_Q; h_item; h_Q*h_item]`, noul over `[h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F]` with a sigmoid. Code: `jev_local/engine/encoder/heads.py` -> `DecisionHeads`; `packages/runtime/src/model/engine.ts` -> `Engine`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). - **hedge (action)**: Heal-tier `stall` action for an idempotent, replayable fetch GET: send a second identical request (op detail `(hedge)`, cause = the original); the first good answer reaches the app. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **held-out domains / templates (curriculum)**: Curriculum test rows use only the 13 held-out app domains of 62 (`TEST_DOMAINS`), and the trailing `max(1, round(0.2 n))` entries of every template list with at least 4 entries appear only in test rows. See *split (sim)* for the sim's hold-outs. Code: `training/curriculum/vocab.py` -> `TEST_DOMAINS`; `training/curriculum/fmt.py` -> `pick_from`, `held_count`. Doc: [training](training.md). -- **hold / held**: Making a subject wait for the model's decision: a store write (`mutation`), a fetch/XHR request (`request`) or a fetch failure (`failure`). A trigger holds only when it is holdable, the runtime is consultable, the situation is salient, the model is ready and the mode/policy permits at least one non-passive action (see *waits*); when the hold budget expires the subject proceeds with the passive action. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **hold / held**: Making a subject wait for the model's decision: a response or push message about to be delivered (`delivery`), a fetch/XHR request (`request`), a fetch failure (`failure`), or, only with `policy.holdWrites: true`, a store write (`mutation`). A trigger holds only when it is holdable, the runtime is consultable, the situation is salient, the model is ready, the mode/policy permits at least one non-passive action and the expected model latency fits the hold budget (see *waits*); when the hold budget expires the subject proceeds with the passive action. In the default `observe` mode nothing is permitted, so nothing is held (a review finding: `runDelivery` can still delay a delivery by up to 100 ms while it reads the body). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `RuntimeImpl.runDelivery`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). - **hold budget**: The longest a held subject waits for the decision (after a gate-passing answer the action itself may keep it waiting: `delay`/`coalesce` ≤ 8 s, `retry` backoff ≤ 5 s, custom actions unbounded): `policy.holdBudgetMs`, default `"auto"` = `clamp(round(1.5 × median of the last 20 provider latencies, or the model's warmupMs before any), 150, 800)` ms, and 300 ms when neither is known; a number is used as `max(0, n)`. `rt.holdBudgetMs()` returns the current value. Code: `packages/runtime/src/decide/policy.ts` -> `holdBudget`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **holdable**: A trigger raised with `TriggerOpts.hold: true` (mutation, fetch and async-XHR request, fetch failure); it is actually held only when it *waits*. Not to be confused with an *unholdable* write. See *hold / held*, *waits*. Code: `packages/runtime/src/decide/exec.ts` -> `TriggerOpts`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **holdable**: A trigger raised with `TriggerOpts.hold: true` (delivery; fetch and async-XHR request; fetch failure; mutation only through `gateMutation` with `holdWrites: true`, while the default `observeWrite` mutation is not holdable); it is actually held only when it *waits*. Not to be confused with an *unholdable* write. See *hold / held*, *waits*. Code: `packages/runtime/src/decide/exec.ts` -> `TriggerOpts`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **holdWrites**: `policy.holdWrites` (default `false` since batch 4). Off: store writes always apply at once; a salient write that no delivery decision covers raises a non-blocking `mutation` trigger (`RuntimeImpl.observeWrite`, priority 1) whose only enforcement is a *late revert*. On (opt-in): salient writes are held for the model as in situation-v1 (`RuntimeImpl.gateMutation`, priority 2), and a hold never reorders a store's writes (`StoreHub.flushQueue`). Tests that exercise held writes pass it explicitly (`atoms.test.ts`). Code: `packages/runtime/src/types.ts` -> `PolicyOptions.holdWrites`; `packages/runtime/src/state/hub.ts` -> `StoreHub.holdWrites`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **hooks (RuntimeHooks)**: `createRuntime({ hooks })`: `opCreated(op)` (sync, in `startOp`) and `mutationProposed({ id, store, paths, cause?, changes })` (sync, before gating); exceptions are swallowed. The sim uses them for subject correlation and the demos' trace run for proposals. Code: `packages/runtime/src/types.ts` -> `RuntimeHooks`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). ## I -- **ideal run (sim)**: `runScenario(scn, { ideal: true })`: no runtime, `IDEAL_PROFILE` network (0 latency, no failures or chaos), accidental and conditional steps skipped, app duplicates share the original's result. It is the intended outcome every cost is measured against. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/net/network.ts` -> `IDEAL_PROFILE`. Doc: [sim](sim.md). +- **ideal run (sim)**: `runScenario(scn, { ideal: true })`: no runtime, `IDEAL_PROFILE` network (0 latency, no failures or chaos), accidental and conditional steps skipped (in an S2 future, which repeats count as accidental is re-drawn by `idealRepeatSkips`), app duplicates share the original's result. It is the intended outcome every cost is measured against. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/net/network.ts` -> `IDEAL_PROFILE`. Doc: [sim](sim.md). - **ignore (action)**: Passive action of `inconsistency`, `transition` and `error`: leave the state as it is. Code: `packages/runtime/src/situation/questions.ts` -> `PASSIVE`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **in_flight (section)**: The situation section listing in-flight ops other than user ops and the subject op, same signature first, then same root, then by start time: `<opPhrase> (#id) <secs> so far[, by #cause]`. Code: `packages/runtime/src/situation/build.ts` -> `inFlightLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **inconsistency (trigger)**: Raised at a settled point for fresh violations of learned or developer invariants (once per episode); not held, priority 1; actions `ignore`, `rollback` (to the last consistent snapshot), `resync`. Fact I1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseInconsistency`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **inert runtime**: A `RuntimeImpl` with every observer off (`ALL_OFF`), no decider, `report: "silent"`, mode `observe`, produced by the `off` kill switch and by `GenClass.init`'s fallback after a throw. Stores, `op`, `emit` and `user` still record; nothing is held or asked. Code: `packages/runtime/src/index.ts` -> `GenClass`, `initUnsafe`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **instant op**: An op created already ended (`end = start`, status `ok`) and never in flight: user actions, timer ticks, WS messages and sends, GenClass actions. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **intent (sim)**: `Intent` in `Knowledge`: one user step with the slot (`key`) it targets, `mode` `replace` (a newer replace-intent on the same key supersedes older ones, making them stale) or `accumulate`, and an `accidental` flag (double click, impatient re-click) with `repeatOf`. Code: `sim/src/oracle/knowledge.ts` -> `Intent`. Doc: [sim](sim.md). +- **interference (realapps)**: How much the runtime changes an app's behaviour when it takes no actions; measured by the *never-worse sweep*. - **intervention**: A non-passive action that ran (or was attempted); see *ActionRecord*. - **intervention card (devtools)**: `article.card.act`, keyed by `ActionRecord.id`: shows the `changed` note, an Undo button when `ActionRecord.undo` exists, and evidence. Doc: [devtools](runtime/devtools.md). - **invariant**: A relation over store fields checked at settled points. Developer invariants come from `rt.expect(name, predicate)`; learned invariants are mined from 9 templates (`type, nonnull, nonneg, eq, len, sum, sumprod, in, unique`) over non-dynamic paths, learned after 3 involved, non-trivial settled points (6 for `nonnull`) and dropped for good if falsified while learning. A freshly broken invariant raises `inconsistency`. Code: `packages/runtime/src/state/invariants.ts` -> `InvariantMiner`, `LEARN_AFTER`. Doc: [state-and-adapters](runtime/state-and-adapters.md). -- **involved stores**: The registered stores a situation is about: mutation -> its store; inconsistency -> stores of violated fields; transition -> stores of chain keys; error -> stores changed since the op started; request/failure/stall -> stores this signature's chains wrote (`storeWriters`); ask -> the asked store. They select state lines and timeline relevance and decide rollback/resync applicability. Code: `packages/runtime/src/situation/build.ts` -> `involvedStores`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **involved stores**: The registered stores a situation is about: mutation -> its store; inconsistency -> stores of violated fields; transition -> stores of chain keys; error -> stores changed since the op started; delivery -> stores of the predicted write patterns; request/failure/stall -> stores this signature's chains wrote (`storeWriters`); ask -> the asked store. They select state lines and timeline relevance and decide rollback/resync applicability. Code: `packages/runtime/src/situation/build.ts` -> `involvedStores`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). ## J @@ -212,10 +229,10 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## L -- **late revert**: When a held write applied because its hold budget expired, a gate-passing `discard` that arrives within `LATE_REVERT_MS` (2,000 ms) reverts exactly that write if `StoreHub.revertable` allows it (store writable, none of its fields changed since, no later write from the same root chain). The `ActionRecord` gets `late: true` and the report lead `Reverted`; undo re-applies the write. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; `packages/runtime/src/state/hub.ts` -> `StoreHub.revertable`, `StoreHub.revert`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). +- **late revert**: When a write already applied (by default every write applies at once and its `mutation` trigger is decided in the background; with `holdWrites`, a held write whose hold budget expired), a gate-passing `discard` that arrives within `LATE_REVERT_MS` (2,000 ms) reverts exactly that write if `StoreHub.revertable` allows it (store writable, none of its fields changed since, no later write from the same root chain). The `ActionRecord` gets `late: true` and the report lead `Reverted`; undo re-applies the write. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; `packages/runtime/src/state/hub.ts` -> `StoreHub.revertable`, `StoreHub.revert`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). - **lazy preload**: When a salient trigger finds the provider in state `off`, the runtime reads `rt.ready` (calling `decider.ready()` once, which starts loading) and fails open for that trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **LazyOp (lazy timer op)**: Created for each wrapped timer callback; it becomes a real instant `timer` op only when something calls `ctx.op()`. Its parent is always a real op or `null` (`LazyOp.nearest`), so recursive timer loops never build a chain. Code: `packages/runtime/src/trace/context.ts` -> `LazyOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). -- **lead**: The coordinator workstream: owns `docs/runtime/CONTRACT.md`, `packages/runtime-model/` and (per CONTRACT §1) `training/`; approves contract additions (§13) and new dependencies, relays NEEDS items, publishes. Doc: [status-and-known-issues](status-and-known-issues.md). +- **lead**: The coordinator workstream: owns `docs/runtime/CONTRACT.md`, `packages/runtime-model/` and (per CONTRACT §1) `training/`; approves contract additions (§13) and new dependencies, relays NEEDS items, publishes. On `mvp-v2` we act as lead for `AGENTS.md`, `CLAUDE.md`, `docs/agents/**`, `test/default-mode.test.ts` and CI. Doc: [status-and-known-issues](status-and-known-issues.md). - **learned invariant**: See *invariant*. ## M @@ -226,35 +243,40 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **mass**: See *permitted set / candidate / mass*. - **max_tokens_exceeded**: The packer's limit error (`MaxTokensExceededError`): state + longest question branch > `meta.max_len` (default 1536), or the whole sequence > `meta.max_total` (default 8192). The runtime reacts by multiplying its budget scale by 0.8 (floor 0.5). Code: `packages/runtime/src/model/errors.ts` -> `MaxTokensExceededError`; `packages/runtime/src/model/packer.ts` -> `Packer`. Doc: [model-host](runtime/model-host.md). - **meharsjev**: See *genclass-<size> / meharsjev-<size>*. -- **mix_* (mixture config)**: `training/configs/mix_{s1,s1b,s1c,s2,final1}.json`: bucket weights for a training round, read as `MixConfig`; `mix_final1` = simA 0.85, cur4 0.12, cur1 0.02, gen 0.01. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). +- **MessageGate**: The batch-4 delivery gate for push channels: one per WebSocket or EventSource, intercepting `message` events, queueing them per channel in arrival order, asking `runDelivery` for each and re-dispatching released messages to the app's listeners, so a held message delays later ones instead of being overtaken. Review findings: held messages can be dispatched after the app called `close()`, a capture-phase listener can see a held message twice, and EventSource `open` is not kept in order. Code: `packages/runtime/src/observe/messages.ts` -> `MessageGate`, `MsgHost`; installed by `packages/runtime/src/observe/websocket.ts` -> `installWebSocket` and `packages/runtime/src/observe/eventsource.ts` -> `installEventSource`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **mix_* (mixture config)**: `training/configs/mix_*.json`: bucket weights for a training round, read as `MixConfig`. Round-1 era: `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` (simA 0.85, cur4 0.12, cur1 0.02, gen 0.01). Added since: `mix_t150` (teacher: simA 0.9, cur4 0.1), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs on `simAg10` / `simAg20` / `simAh`). All name v1 buckets; no v2 or distillation mixture exists yet. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). - **MockRuntime / loadScenario / runStoreSession**: The devtools and adapter UI test harness: `MockRuntime` is a scripted `Runtime`; `loadScenario` scripts a store story with 3 interventions and 3 detections; `runStoreSession` drives the real `createRuntime` with a virtual clock, a fake backend and the rule-based `SessionDecider`. Code: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`; `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario`; `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession`. Doc: [devtools](runtime/devtools.md). -- **mode**: `observe | guard | heal` (default `guard`): which action tiers may run. `observe` permits passive only (never holds, but still decides in the background so detections and reports work); `guard` adds guard-tier actions; `heal` adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`. Code: `packages/runtime/src/types.ts` -> `Mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **mode**: `observe | guard | heal`, which action tiers may run. **Default `observe`** since f3636b2 on `mvp-v2` (`o.mode ?? "observe"`; it was `guard` up to and including `0.1.0-alpha.0` and origin/runtime). `observe` permits passive only: it never runs an action or holds a request or write, but while a model is consultable a conflicting delivery can still wait up to 100 ms (`BODY_WAIT_MS`) for its body read and WebSocket/EventSource messages are re-dispatched as clones (see [observe-and-trace](runtime/observe-and-trace.md) Drift); but triggers are still built and decided in the background so detections and reports work (review finding: background `delivery` decisions are dropped as stale, so delivery detections and delivery standing questions never answer in observe mode). `guard` (opt-in) adds guard-tier actions; `heal` (experimental) adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`; devtools labels them "Observe (default)", "Guard (opt-in)", "Heal (experimental)". The test harness `setup()` still defaults to `guard`, and the sim and realapps pass `heal` explicitly. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `Mode`, `InitOptions.mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`; test `packages/runtime/test/default-mode.test.ts`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **MODEL (workstream)**: Owns `packages/runtime/src/model/**` and `packages/runtime/bin/genclass-runtime.mjs`, and co-owns the "model seam" section of `packages/runtime/src/types.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). - **model card**: `model.json` in format `genclass-runtime-model/1`: `name`, `version`, `variants` (`q8`, `fp16`: file, bytes, sha256, provider, needs) and `files` (`tokenizer`, `calibration`, `meta`). `parseCard` also accepts the v0.1 extension card. Code: `packages/runtime/src/model/loader.ts` -> `parseCard`, `CARD_FORMAT`. Doc: [model-host](runtime/model-host.md). - **model directory**: A folder or URL holding `model.json` plus the ONNX variants, `tokenizer.json`, `calibration.json` and `meta.json`; produced by `training/export_runtime.py`, fetched with `genclass-runtime fetch-model`, passed as `model: { baseUrl }`, read by tests from `GENCLASS_MODEL_DIR`. Downloads are cached in Cache Storage `genclass-runtime-v1`. Doc: [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md). - **model host (ModelHost)**: `ModelHost` from `createModelHost`: the main-thread `DecisionProvider` that owns the worker or inline transport, preload scheduling (`eager | idle | lazy`, default `idle`), a priority queue, timeouts (10 s), status and one WASM-only retry after a failed WebGPU load. `evaluate()` rejects at once unless `ready` (fail open, never wait). `GenClass.init` creates one by default in a browser; `createRuntime` only with `model: {...}`. Code: `packages/runtime/src/model/host.ts` -> `createModelHost`. Doc: [model-host](runtime/model-host.md). - **model status**: `rt.status` (`ModelStatus`; the host's `ModelHostStatus` adds detail): `state` `off` (not started, or no decider) -> `loading` (phases `card`, `download`, `runtime`, `session`, `warmup`) -> `ready` or `error`; `dispose()` returns it to `off`. The runtime consults the model in `ready` (and in `off`, which starts the lazy load); `loading` and `error` fail open at once. Code: `packages/runtime/src/types.ts` -> `ModelStatus`; `packages/runtime/src/model/backend.ts` -> `ModelHostStatus`. Doc: [model-host](runtime/model-host.md). - **ModelBackend**: The load-and-evaluate wrapper that runs in the worker or inline: fetches the card, computes plans, imports ORT, downloads files, creates sessions, warms up, then evaluates; it emits a `ModelHostStatus` on every change. Code: `packages/runtime/src/model/backend.ts` -> `ModelBackend`. Doc: [model-host](runtime/model-host.md). -- **mutation (trigger)**: Raised through the hub's gate hook for a queued (non-bypassed) store write; holdable, priority 2; actions `apply` (passive), `discard`, `defer`. Salient through facts M2, M5, M6, M8, M10 or M12. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **mutation (trigger)**: Raised for a non-bypassed store write that no delivery decision covers. Default (`holdWrites` off): `RuntimeImpl.observeWrite` builds the situation as of the proposal, the write applies at once, and the trigger is decided in the background (not holdable, priority 1; a gate-passing `discard` becomes a late revert). With `holdWrites: true`: `RuntimeImpl.gateMutation`, holdable, priority 2. Actions `apply` (passive), `discard`, `defer` (offered while `defers < 2`; with `holdWrites` off a `defer` is only recorded, nothing is held). Salient through a newer-data or pending-local-change conflict (M5 "inputs that moved" and M6 "same-signature op in flight" are always neutral since batch 4), F1 and other non-neutral facts. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.observeWrite`, `RuntimeImpl.gateMutation`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **MutationRec (proposal)**: One proposed write: changes, cause, base, preview, optional `fn` / `commit`, `userSync`, `genclass`, `defers`, state `queued | held | resolved | done`, verdict `apply | discard | defer`, outcome `applied | discarded | deferred | failed`, `appliedAt` / `appliedSeq`. Code: `packages/runtime/src/state/hub.ts` -> `MutationRec`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **muted**: See *episode / muted*. ## N +- **NaN fix / 0.1.0-alpha.1**: Commit ad24804 fixed infinite recursion when a store value is `NaN` (`packages/runtime/src/util.ts`, test `test/nan.test.ts`), found after `0.1.0-alpha.0` was published. The planned `0.1.0-alpha.1` patch release needs the owner's npm 2FA; it is not published. Doc: [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) - **native timers (demos)**: Timers captured before `GenClass.init` wraps the globals; all test code (driver, oracle) uses them, so the runtime never sees test ops. Code: `demos/src/shared/native.ts`. Doc: [demos](demos.md). - **NATIVE_FETCH**: `globalThis.fetch` captured when `index.ts` is evaluated; an owned model host downloads with it, so GenClass never observes its own model download. Code: `packages/runtime/src/index.ts` -> `NATIVE_FETCH`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exception `packages/runtime/UI-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). - **NetCause (sim)**: Why a simulated request ended (`NetEntry.cause`): `ok, transient, outage, overload, ratelimit, spike, slow-period, gateway-timeout, bug, replica-lag, neterr, aborted, notfound`; diagnoses read it. Code: `sim/src/net/network.ts` -> `NetCause`. Doc: [sim](sim.md). +- **never-worse sweep**: The check of the product principle "never make a correct app worse": REAL's `debug.js --interference` runs each realapps scenario in `observe` mode and in `heal` mode with an all-passive decider and counts runs whose outcome differs. Situation-v2 result (STATUS.md, RESULTS.md §4): 0/396 clean runs changed (all 66 apps of the time, seeds 1–6), 3/198 under chaos (request-time holds shifting a request by ~25 ms; open item), Conduit 0/30; situation-v1 changed 4/198 and the React/Redux Conduit never rendered its feed. Caveats from review: it compares only final non-input, non-alert DOM text and server content (not requests, stores or errors), it never compares `observe` against no runtime at all, and the 25 apps added later were never swept. The runtime-side regression test is `test/no-reorder.test.ts`. Code: `realapps/src/harness/debug.ts`. Doc: [realapps](realapps.md)., [RESULTS.md](../runtime/RESULTS.md) - **noul**: A typed question asking for the absolute probability that a statement is true (sigmoid head; `criteria` optional `{ true?, false? }`); the answer is `{ noul: P(true) }`, with no confidence field. Code: `packages/runtime/src/types.ts` -> `NoulAnswer`; `jev_local/schema.py` -> `NoulQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **Now view (devtools)**: Renders `runtime.situation()` (an "ask about now" situation) and `inflight()`, refreshed every second while visible. Doc: [devtools](runtime/devtools.md). - **numbered pick (extension)**: After "which element?", the top-3 candidates get page badges; "number two" within 10 s and ≤ 5 words clicks it without a model call (still through the safety gate). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). ## O -- **observers**: `ObserverName` = `fetch, xhr, user, errors, nav, storage, perf, websocket, timers`, installed by `RuntimeImpl.installObservers`, each in try/catch (`timers` is on by default only when a `document` exists). fetch is the only fully controllable transport; XHR supports send/delay/block/serve_cached and its failures and stalls are detection-only; nav, perf and storage only record events. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`. Doc: [observe-and-trace](runtime/observe-and-trace.md). -- **op / OpRec**: Anything the app does asynchronously, recorded in `OpRegistry`: kind `user | fetch | xhr | ws | task | timer | genclass`, a sequential `id` per runtime, `name` (the op signature), optional `detail`, start/end, status (`ok | error | aborted | blocked`), `code`, `cause` / `root`, `attempt`, `identity`. User actions, timer ticks, WS messages and sends, and GenClass actions are instant ops. Code: `packages/runtime/src/trace/ops.ts` -> `OpRec`, `OpRegistry`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **observe (mode)**: The default mode since f3636b2; see *mode*. +- **observers**: `ObserverName` = `fetch, xhr, user, errors, nav, storage, perf, websocket, eventsource, timers` (ten; `eventsource` added in batch 4), installed by `RuntimeImpl.installObservers` in the order timers, fetch, xhr, websocket, eventsource, user, errors, nav, storage, perf, each in try/catch (`timers` is on by default only when a `document` exists). The same `observe` map carries the flag `untrustedEvents`, which is not an observer. fetch is the only fully controllable transport; XHR supports send/delay/block/serve_cached plus delivery holds, and its failures and stalls are detection-only; WebSocket and EventSource messages go through a `MessageGate`; nav, perf and storage only record events. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **on-policy rows**: See *DAgger / on-policy rows*. +- **op / OpRec**: Anything the app does asynchronously, recorded in `OpRegistry`: kind `user | fetch | xhr | ws | task | timer | genclass`, a sequential `id` per runtime, `name` (the op signature), optional `detail`, start/end, status (`ok | error | aborted | blocked`), `code`, `cause` / `root`, `attempt`, `identity`, and since batch 4 `delivery` (the delivery gate's record) and `discardMark`. User actions, timer ticks, WS messages and sends, and GenClass actions are instant ops. Code: `packages/runtime/src/trace/ops.ts` -> `OpRec`, `OpRegistry`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **op signature**: `OpRec.name`, the key ops are grouped by. For fetch/XHR it is `METHOD normalisedPath` (`requestSignature`: path only, host + path when cross-origin, no query or fragment, id-like segments -> `:id`, e.g. `GET /api/items/:id`); other kinds use their own names (`click button "Add to cart"`, `WS message <path>`, `timer 300ms`, a task name). It keys baselines, transition profiles (user ops as `user <name>`) and `storeWriters`. Code: `packages/runtime/src/util.ts` -> `requestSignature`, `normalizePath`, `isIdSegment`. Doc: [observe-and-trace](runtime/observe-and-trace.md), [learn-situation-triage](runtime/learn-situation-triage.md). -- **OPEN_TASKS.md**: Repo-root project status maintained by the lead: Done / In progress / Next / Needs the user / Known risks. Doc: [status-and-known-issues](status-and-known-issues.md). +- **OPEN_TASKS.md**: Repo-root project status maintained by the lead: Done / In progress / Next / Needs the user / Known risks. The working-tree rewrite numbers items 1–14 (In progress: 1 v2 data, 2 Demos; Next: 3 data checks … 8 EVAL, 9 Model package, 10 demo rerun, 11 publish 0.1.0, 12 CI (done), 13 Docs, 14 Review fixes); cite items by title, since numbers change. Doc: [status-and-known-issues](status-and-known-issues.md). - **opLabel / opPhrase**: How ops are worded in model text: `opPhrase` gives `<signature><detail>` for requests (e.g. `GET /api/search?q=re`), the user phrase for user ops, `task <name>` and `GenClass <name>`; `opLabel` = `<opPhrase truncated to 90> (#id)`, or `an earlier operation` when the op is unknown. Also used in `ActionEffect.changed` sentences. Code: `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `opLabel`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **oracle (demos)**: Per-demo scorer (`start`, `check`, `finish` -> `Score { bug, reasons, metrics }`) that samples the DOM with native timers and reads the mock server's truth and log; never passed to GenClass or the app. Code: `demos/src/shared/demo-def.ts` -> `Oracle`. Doc: [demos](demos.md). - **ORT / ORT build**: ORT = onnxruntime-web, the runtime's only dependency. The ORT build is the bundle the backend imports: `webgpu` (`onnxruntime-web/webgpu`, asyncify wasm, WebGPU and WASM execution providers) when any WebGPU plan exists, else `wasm` (`onnxruntime-web/wasm`, CPU only); reported as `status.ortBuild`. Doc: [model-host](runtime/model-host.md). @@ -266,26 +288,27 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **package build vs model-entries build**: The two library builds of the Playwright setup. When every tsup entry file exists, `buildLibrary` runs `npx tsup` and uses `packages/runtime/dist` if its `index.js` mentions `createModelHost` ("package" mode); otherwise, or if that build fails, it bundles only `packages/runtime/src/model/{index,worker}.ts` into `packages/runtime/test/browser/.build/dist` ("model-entries" mode). Code: `packages/runtime/test/browser/build.mjs` -> `buildLibrary`. Doc: [build-test-release](runtime/build-test-release.md). - **Packer**: The TypeScript port of `jev_local`'s `tokenize_pack.Packer` (single-pass subset): turns a wire request into `[CLS] key: text [SEP] … | [Q] header [O] item …` token ids, with positions restarting per branch and `q_group` / `i_group` for block attention; throws `MaxTokensExceededError` past `max_len` / `max_total`. Code: `packages/runtime/src/model/packer.ts` -> `Packer`. Doc: [model-io-contract](model-io-contract.md), [model-host](runtime/model-host.md). -- **parity**: The hard invariant that the TypeScript model path (serializer, tokenizer, packer, calibration, engine) reproduces the Python reference (`jev_local`, `scripts/genclass_export.py`) the model was trained with, and that `training/curriculum/rt.py` renders situations exactly like the runtime. Checked against Python-generated fixtures. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). +- **parity**: The hard invariant that the TypeScript model path (serializer, tokenizer, packer, calibration, engine) reproduces the Python reference (`jev_local`, `scripts/genclass_export.py`) the model was trained with, and that `training/curriculum/rt.py` renders situations exactly like the runtime (now at situation-v2). Checked against Python-generated fixtures; the v2 `rt.py` port has known divergences from the runtime (review: extra failure facts, timeline selection, no-op writes, rounding), so its runtime-style rows are not byte-exact. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **parity fixtures**: Python-generated files the runtime's model tests compare against: the v0.1 set in `packages/runtime/test/fixtures/model/` (`requests50.json`, `pack_fixtures.json`, `torch_fixtures.json`, plus `py_fixtures.json`) and the model-dir set (`requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, `parity.json`) that `training/export_runtime.py` writes next to an export. Doc: [build-test-release](runtime/build-test-release.md), [model-io-contract](model-io-contract.md). - **parts (SituationParts)**: The unbudgeted section lines `{ app, trigger, facts[], in_flight[], timeline[], state[], stats[] }` that `toJevState` shapes to the budget. Code: `packages/runtime/src/situation/serialize.ts` -> `SituationParts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **parts mode (sim)**: `gen.js --parts`: resumable fixed seed chunks (default 100 seeds) written as `parts/part-NNNNNN.<split>.jsonl` with a `.json` marker; finished parts are skipped on restart. Used for phase B. Code: `sim/src/gen.ts` -> `main`, `mergeParts`. Doc: [sim](sim.md). - **pass / pass_tokens (training)**: One draw of the training mixture; each bucket's token budget per pass is weight × `pass_tokens`, and `--passes` may be fractional. Not the FastEngine *fragment / pass*. Doc: [training](training.md). -- **passive (action)**: The action that lets the subject proceed unchanged, per trigger (`PASSIVE`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. It is offered first, permitted in every mode and runs on every fail-open path. Code: `packages/runtime/src/situation/questions.ts` -> `PASSIVE`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **passive (action)**: The action that lets the subject proceed unchanged, per trigger (`PASSIVE`): mutation `apply`, request `send`, delivery `deliver`, failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. It is offered first, permitted in every mode and runs on every fail-open path. Code: `packages/runtime/src/situation/questions.ts` -> `PASSIVE`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **patch (patchValue)**: Re-applies a set of field changes on top of the current store value (removals first, never removing a path that has a set beneath it, copy-on-write); used for queued value writes, revert, reapply and restoreFields, so newer input in other fields survives. Code: `packages/runtime/src/state/fields.ts` -> `patchValue`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **pattern (sim)**: Variant tag a feature's `pattern(spec)` returns, prefixed with the kind (e.g. `search/guard:none`); held-out patterns (`TEST_PATTERNS`) go to test. Code: `sim/src/world/scenario.ts` -> `TEST_PATTERNS`. Doc: [sim](sim.md). - **pause / resume**: `rt.pause()` stops triggers, holds and request gating (`hub.gating = false`) while tracing continues; decisions already queued still produce a `Decision` but never run; `ask()` still works. `rt.resume()` undoes it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.pause`, `RuntimeImpl.resume`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **pending (extension)**: A risky action waiting for a spoken confirmation from a later utterance; it expires after `confirm_timeout_ms` (default 8,000 ms). Code: `extension/src/core/controller.js` -> `Controller`; `extension/src/core/safety.js` -> `confirmationAllowed`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **permitted set / candidate / mass**: In the policy gate, A = the offered non-passive actions whose tier the mode permits, minus `policy.deny` (or only `policy.allow` when set); the candidate is the action with the highest probability in A; the mass is Σ p over A, compared with the candidate tier's threshold. Recorded as `Decision.candidate` / `mass`. Code: `packages/runtime/src/decide/policy.ts` -> `permittedActions`, `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **phase (model load)**: The load step in progress, `status.phase`: `card | download | runtime | session | warmup`. Doc: [model-host](runtime/model-host.md). -- **phase A / phase B (SIM)**: The final SIM datasets from the frozen runtime (`sim/scripts/final.sh`). Phase A = 600,676 rows (train 448,420 / dev 14,613 / test 137,643), seeds from 10,000,000, in `sim/out/final-a`; phase B = 1.4M more rows from seeds 50,000,000 upward as resumable parts in `sim/out/final-b`, in progress at 654d822. Doc: [sim](sim.md), [status-and-known-issues](status-and-known-issues.md). +- **phase A / phase B (SIM)**: The SIM datasets from the frozen situation-v1 runtime (`sim/scripts/final.sh`). Phase A = 600,676 rows (train 448,420 / dev 14,613 / test 137,643), seeds from 10,000,000, in `sim/out/final-a` (on the train VM: `/data/sim-out/final-a`); phase B = 1,415,344 more rows from seeds 50,000,000 upward as parts in `final-b/parts/`. Both are done and superseded by the situation-v2 data (RESULTS.md §6); phase A trained final round 1. Doc: [sim](sim.md), [status-and-known-issues](status-and-known-issues.md)., [RESULTS.md](../runtime/RESULTS.md) - **pill (devtools)**: The collapsed overlay button: mode, intervention and detection counters, a model-status dot and a load progress bar; it pulses on new items. Doc: [devtools](runtime/devtools.md). - **plan (model load)**: A `{ variant, device }` pair the backend tries in order: `webgpu+fp16` (needs `shader-f16`) -> `webgpu+q8` -> `wasm+q8` (`wasm+fp16` when there is no q8 variant); the first plan that passes its warm-up wins. Code: `packages/runtime/src/model/loader.ts` -> `planOrder`. Doc: [model-host](runtime/model-host.md). - **plugin**: `Plugin { name, setup?(api), facts?(draft), actions?, questions?, diagnoses? }`, installed with `rt.use(plugin)` or the `plugins` option. Plugin facts are always neutral (they cannot make a trigger salient), plugin actions default to the heal tier, plugin diagnosis labels are appended if new. `PluginApi` offers `runtime`, `clock`, `emit`, `recordOp` / `endOp` / `runInOp`, `user`, `reportError`, `on`, `stores`. Code: `packages/runtime/src/types.ts` -> `Plugin`, `PluginApi`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.use`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). -- **policy gate**: The final check between the model's answer and an action (runtime CONTRACT §8, the "summed-mass gate"): an action runs only if the runtime is not paused, the permitted set's mass ≥ the candidate tier's threshold (guard 0.9, heal 0.8), the top diagnosis is not `expected` (`requireDiagnosis`), fewer than `maxActionsPerMinute` (60) actions ran in the last minute, and, for holdable triggers only (mutation, request, fetch failure), the subject is still held (otherwise late-revert rules apply). It only filters what the model chose; `training/eval_runtime.py` mirrors it. Code: `packages/runtime/src/decide/policy.ts` -> `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [training](training.md). +- **policy gate**: The final check between the model's answer and an action (runtime CONTRACT §8, the "summed-mass gate"): an action runs only if the runtime is not paused, the permitted set's mass ≥ the candidate tier's threshold (guard 0.9, heal 0.8), the top diagnosis is not `expected` (`requireDiagnosis`), fewer than `maxActionsPerMinute` (60) actions ran in the last minute, and, for holdable triggers only (delivery, request, fetch failure, held mutation), the subject is still held (otherwise late-revert rules apply). It only filters what the model chose; `training/eval_runtime.py` mirrors it. Code: `packages/runtime/src/decide/policy.ts` -> `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [training](training.md). +- **predicted write set (P)**: For a delivery, the field patterns the op's chain is expected to write: from its signature's transition profile (`Profile.wrote`), else what the last completion of its signature wrote (`SitEnv.lastChain`), else unknown. Stated in the delivery trigger sentence and fact D4; delivery salience, matched fields and *covered writes* are computed against it. Code: `packages/runtime/src/situation/conflicts.ts` -> `predictedWrites`, `matchFields`, `Predicted`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **prefix-mismatch**: See *fp (fingerprint, sim)*. - **primitive question (curriculum)**: An exact-label question about the curriculum trace (qid prefixes `t_` temporal, `c_` causal, `v_` versions, `i_` identity, `o_` outcomes, `b_` baselines, `f_` failure, `j_` JSON, `h_` HTTP, `js_` JS errors, plus `decide` and scenario-specific ids). Code: `training/curriculum/prims.py`; `training/curriculum/standalone.py`. Doc: [training](training.md). -- **programmatic event**: A DOM event the user observer drops: dispatched while a non-user op is running (`ctx.running`), or untrusted while a non-user op is ambient. Code: `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **programmatic event**: A DOM event the user observer drops: any event dispatched while a non-user op's code is running (`runningKind`); any untrusted (`isTrusted === false`) event unless `observe.untrustedEvents: true` (default `false` since batch 4); and, when untrusted events are allowed, one dispatched while a non-user op is ambient. Code: `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Consequence: test drivers and the demos' in-page synthetic driver produce no user actions unless they opt in. See *untrustedEvents*. Code: `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **proposal**: See *MutationRec (proposal)*. - **pruned vocabulary**: The shipped tokenizer: 245 base ids + the first 16,000 BPE merges of the ettin tokenizer + 119 added tokens = 16,364 tokens, markers at 16359–16363; R17 and R32 share it. Code: `training/prune_vocab.py` -> `prune_tokenizer_json`. Doc: [training](training.md). @@ -298,18 +321,24 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## R -- **R17**: Runtime model candidate initialised from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers, fresh heads) with the pruned 16,364-token vocabulary: 8.1M + 0.7M head parameters, q8 9.6 MB, fp16 13.6 MB. Planned WASM default. Doc: [training](training.md), [model-host](runtime/model-host.md). +- **R17**: Runtime model candidate initialised from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers, fresh heads) with the pruned 16,364-token vocabulary: 8.1M + 0.7M head parameters, q8 9.58 MB, fp16 13.6 MB; WASM single-thread ≈ 177 / 323 / 589 ms at 500 / 780 / 1,170 tokens. Chosen as the default on every device after final round 1 (RESULTS.md §2); the existing R17 checkpoints are situation-v1 and must be retrained (distilled) for v2. Doc: [training](training.md), [model-host](runtime/model-host.md)., [RESULTS.md](../runtime/RESULTS.md) - **r300k**: The pre-freeze SIM run used for the stage-2 pilot, imported as bucket `sim1`. Doc: [training](training.md). -- **R32**: Runtime model candidate initialised from GenClass 0.1 `jev-local-fast` (ettin-32m, d 384, 10 layers, v1 heads) with the pruned 16,364-token vocabulary: 18.8M + 1.6M head parameters, q8 22.5 MB, fp16 34.8 MB. Planned for WebGPU only if clearly more accurate than R17. Doc: [training](training.md), [model-host](runtime/model-host.md). +- **R32**: Runtime model candidate initialised from GenClass 0.1 `jev-local-fast` (ettin-32m, d 384, 10 layers, v1 heads) with the pruned 16,364-token vocabulary: 18.8M + 1.6M head parameters, q8 22.5 MB, fp16 34.8 MB. In final round 1 it matched R17 at about 3× the size and latency, so it is not the default; it remains a distillation student in PLAN-v1. +- **R68**: Student benchmark candidate on `ettin-encoder-68m` (≈ 42M parameters, pruned vocabulary) in PLAN-v1, with `mix_r68.json` and `training/launch_r68.sh`; never run. Doc: [training](training.md). Doc: [training](training.md), [model-host](runtime/model-host.md). - **rate limit**: `policy.maxActionsPerMinute` (default 60): a sliding 60 s window of non-passive actions. When full, the gate refuses with `rate limit: …`, and a status line is emitted at most once a minute. Code: `packages/runtime/src/decide/policy.ts` -> `RateLimiter`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **raw logits**: Head outputs at τ = 1 (`choice_logits`, `score_logits`, `noul_logits`) before calibration; what PyTorch parity fixtures and calibration fitting use. Doc: [model-io-contract](model-io-contract.md). -- **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when any path segment names a secret by meaning (`isSensitiveName`: password, token, card number, api key, ...), not by substring. Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitiveName`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **read-your-writes (fact)**: Batch-5 fact (SEPARABILITY's F4 idea): create responses (POST, or 201) are parsed in the background (`RuntimeImpl.noteResponse`, `createdIds`), and a list loaded by a request that started after the create is checked for the created item: "… created item "weekend" 0.10s ago (201), and does not contain it." / "… contains item … twice". Salient. Used for lists in delivery bodies, mutation values, inconsistency and transition fields, within `RYW_WINDOW_MS` (10 s). Review finding: every successful JSON POST counts as a "create". Code: `packages/runtime/src/situation/content.ts` -> `rywFacts`, `createdIds`, `RYW_WINDOW_MS`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **REAL (workstream)**: Owns `realapps/` and the real-browser training data (`training/NEEDS.md` items 13–16; batches `v2b1`–`v2b3` on c01, c10, c11 into `train:/data/real-out/`); a colleague-side workstream added after 654d822, and the source of batch 5's "real-app text fixes". Doc: [realapps](realapps.md). +- **realapps**: The real-browser corpus in `realapps/` (fcb8189): 91 apps at b435acb (77 written for it + 14 open-source RealWorld "Conduit" front-ends; READMEs still say 66) across 23 frameworks, run in headless Chromium with the real runtime bundled from source, on virtual time with an in-page mock backend and chaos. It labels decisions by counterfactual outcome with the sim's cost weights and label rule and writes CONTRACT-D rows (`meta.source = "realapps"`, ids `real-<app>-<seed>-…`), and hosts the *never-worse* and *determinism* sweeps. Not a workspace, not in CI, no tests; everything real needs Chromium or Azure (ask first). Doc: [realapps](realapps.md). +- **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when `isSensitivePath(path, value)` holds: since fcb8189 the rule looks at the leaf field name by meaning (words and secret pairs such as password, token, card number, api key, ...), with container rules (a strong secret container redacts strings beneath it, a broad one only opaque-looking strings), never at the store's name. Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Review findings: numbers and arrays under a secret container are no longer redacted, the F2 diff preview can print redacted text, and `docs/runtime/CONTRACT.md` still describes the old substring rule; use a custom redactor for app-specific secrets. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **relation (sim)**: An app-declared executable invariant (`Relation { fields, desc, check(stores) }`, e.g. count = len(items), total = Σ price × qty, badge = cart count); ground truth for the `inconsistent` diagnosis and a cost term. Code: `sim/src/app/feature.ts` -> `Relation`. Doc: [sim](sim.md). +- **RELEASE.md**: Repo-root release procedure (untracked at b435acb; commit it with docs that link it): Part A `0.1.0-alpha.1` under dist-tag `alpha`; Part B `@genclass/runtime-model@0.1.0` (plus the `runtime-model-v0.1.0` GitHub release), then the runtime. Only the user publishes. Doc: [RELEASE.md](../../RELEASE.md). - **render bits (devtools)**: Dirty flags `STATUS=1, MODE=2, LISTS=4, EVENTS=8` (ALL=15) OR'ed by `mark()` and flushed once per animation frame; LISTS and EVENTS are deferred while the panel is closed or paused. Doc: [devtools](runtime/devtools.md). - **repeat folding (devtools)**: Detections with the same `repeatKey` (trigger, diagnosis, action and subject, digits normalised) within 60 s of a card's latest repeat fold into one card with a `×N` badge. Code: `packages/runtime/src/devtools/ui.ts` -> `repeatKey`. Doc: [devtools](runtime/devtools.md). - **replay (training)**: Curriculum (`cur1`–`cur4`) and GenClass 0.1 (`gen`, `cu`) buckets mixed into SIM-based rounds. Doc: [training](training.md). - **report / Reporter**: The runtime's one-line console sentences: `[GenClass] Flagged …` per detection without action, `[GenClass] <lead> …` per intervention (`Prevented`, `Held back`, `Slowed down`, `Stopped`, `Recovered from`, `Worked around`, `Repaired`, `Reverted`, `Handled`), plus status lines. Sink `report: "console" | "silent" | fn` (console output deduplicated per 60 s window); every report also fires the `report` event. Code: `packages/runtime/src/decide/report.ts` -> `Reporter`, `interventionLine`, `detectionLine`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **report sentence (devtools)**: `Report.message` from `on("report")`, split by `splitReport` into card title and body; unavailable for items recorded before mount, which use *templates*. Code: `packages/runtime/src/devtools/ui.ts` -> `splitReport`. Doc: [devtools](runtime/devtools.md). +- **RESULTS.md**: `docs/runtime/RESULTS.md`, the results log (model rounds, never-worse sweep, data volumes). Doc: [RESULTS.md](../runtime/RESULTS.md). - **request (trigger)**: Raised by the fetch and async-XHR request gates before a gated request is sent; holdable, priority 2; actions `send` (passive), `coalesce`, `delay`, `block`, `serve_cached`. Keepalive fetches and synchronous XHRs raise none. Salient through facts R3 (a close identical request), R5 (fail streak ≥ 2) or R7 (hot request rate). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [observe-and-trace](runtime/observe-and-trace.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **request identity**: The hash that defines "identical requests": FNV-1a of method + absolute URL + non-volatile headers (tracing headers and `x-genclass` excluded) + a body content key. Bodies that cannot be read cheaply get a unique `uniq:N` key and never match; the identity is `""` while a body is still being read (≤ 100 ms). Ops with the same identity started in the last 10 s or still in flight are the identical requests behind repetition facts and `coalesce`. Code: `packages/runtime/src/observe/fetch.ts` -> `parseRequest`, `bodyInfo`, `headersKey`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **rescue (extension)**: `rescueTarget`: for a click whose target answer is `none` or weak, use the unique on-screen label (≥ 3 chars) that occurs verbatim in the transcript; logged as `rescue`. Code: `extension/src/core/controller.js` -> `rescueTarget`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). @@ -330,7 +359,9 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## S -- **salient**: `BuiltSituation.salient` / `Situation.salient`: `triage === "always"`, or the trigger is `ask`, or at least one fact is non-neutral. Failure, stall, inconsistency, transition and error situations are always salient (facts F1, S1, I1, T1, E1); mutation and request only through specific facts. Not model input. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **S1 (sim label rule)**: SIM's diagnosis fix (SEPARABILITY §7): when a non-passive action beats passive by ≥ 1 cost unit (`S1_GAP`) but the subject's knowledge-based diagnosis is `expected`, the label names what the action repairs (`stale`, `inconsistent`, `duplicate`, …) via rules a–e (`meta.diagnosis_s1` = `a-write | b-repeat | c-twin | d-diverged | e-other`). Fixes the 24% of clear round-1 rows labelled `expected`, which the gate (`requireDiagnosis`) never acts on. Not the runtime's stall fact S1. Review finding: unlabeled rows still hard-label `expected` diagnoses that S1 would relabel. Code: `sim/src/gen/trajectory.ts` -> `diagnosisFromOutcome`, `S1_GAP`. Doc: [sim](sim.md). +- **S2 (sim label rule)**: SIM's label fix for hindsight: counterfactual futures 1..K−1 also re-draw what a runtime cannot observe at the decision (later user timing, the remaining length of outages/offline/slow windows and socket drops, whether an ambiguous failed write committed, remaining time of in-flight requests, whether a recent repeat click was accidental), so the action label is the expected cost given the observable situation. A re-draw that breaks the observed prefix falls back to a network-only future (`info:latent-fallback`). On by default (`SIM_S2=0` turns it off). Code: `sim/src/run/latent.ts` -> `futureProfile`, `futureStepTimes`, `idealRepeatSkips`, `REPEAT_PRIOR`, `S2`; `sim/src/net/network.ts` -> `Network`. Doc: [sim](sim.md). +- **salient**: `BuiltSituation.salient` / `Situation.salient`: `triage === "always"`, or the trigger is `ask`, or at least one fact is non-neutral. Failure, stall, inconsistency, transition and error situations are always salient (runtime facts F1, S1, I1, T1, E1, not the batch-5 F-facts); mutation and request only through specific facts; a delivery reaches the model only when `runDelivery`'s pre-filter finds it salient (conflict the body would change, F1, F2) or `triage: "always"` / an `always` standing question applies. Not model input. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **Scen / case (curriculum)**: A curriculum scenario result (`Scen`: trigger, case, subject, facts, actions, action, diag, prims, trace, spec, ...); `case` is `"<builder>/<case>"` (e.g. `typeahead/stale`), and the row family drops the builder (`cur/mutation/stale`). Code: `training/curriculum/scenarios.py` -> `Scen`. Doc: [training](training.md). - **scenario (demos)**: Seeded `Scenario { seed, kind, chaos, params, steps, intent, label }`; `steps` is a union discriminated by `k` (`type`, `key`, `click`, `focus`, `caret`, `wait`, `until`, `chaos`, `server`, `mark`); `intent` is read only by the oracle. Code: `demos/src/shared/demo-def.ts` -> `DemoDefinition`. Doc: [demos](demos.md). - **scenario (sim)**: `Scenario` from `buildScenario(seed)`: a program (domain, 1–3 features plus optional `benign`, naming, API style, id style), a user session, a network profile and chaos, external events, timing, ask times, vocabulary overrides, model latency and situation budget, all determined by the seed. Code: `sim/src/world/scenario.ts` -> `buildScenario`. Doc: [sim](sim.md). @@ -338,39 +369,43 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **ScriptedDecider / ManualDecider / defaultScript**: Test `DecisionProvider`s: `ScriptedDecider` answers at once from a script and records calls; `ManualDecider` queues requests until `answer()`; `defaultScript(pick)` answers each trigger's diagnosis/action from `pick` at p = 0.97, otherwise `expected` and the first (passive) action. Code: `packages/runtime/test/helpers.ts` -> `ScriptedDecider`, `ManualDecider`, `defaultScript`. Doc: [build-test-release](runtime/build-test-release.md). - **segment**: One `key: text` unit of the packed state: one per top-level key of an object state (string-array values joined with `\n`), `[i]` per item of an array state (first 64, then a `[64:]` tail), or one keyless segment for a string state; segments are separated by `[SEP]`. Code: `packages/runtime/src/model/serialize.ts` -> `stateSegments`, `Segment`; `jev_local/serialize.py` -> `state_segments`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **send (action)**: Passive action of the `request` trigger: send the request now. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **separability / benign twin**: The analysis in `sim/SEPARABILITY.md` of why round-1 R17 acts on only ~8% of clear cases: a linear model on the visible text hits the same recall ceiling (the limit is information, not capacity), 62–82% of clear actionable rows had a *benign twin* with an identical fact set, 24% of clear rows were labelled `expected`, and labels were hindsight-certain about unobservable things. It led to the F1–F9 facts, S1, S2 and T1. Scripts: `sim/scripts/separability*.py`; probes `SIM_PROBE=1`. Doc: [sim](sim.md), `docs/runtime/RESULTS.md` §3., [RESULTS.md](../runtime/RESULTS.md) - **servable checkpoint vs trainer state**: `models/<M>/` (`backbone/`, `heads.safetensors`, `calibration.json` with all-1.0 temperatures, `meta.json` with a `final` flag) is what eval and export read; `runs/<run>/ckpt` holds weights plus optimizer for `--resume` and `--init-from`. Doc: [training](training.md). - **serve_cached (action)**: Heal-tier action for `request`, `failure` and `stall` on a GET with a cached good response (fetch only for failure and stall): answer with the last good 2xx body for that identity (≤ 256 KB), marked `x-genclass: cached`; on a stall the original request continues in the background. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/cache.ts` -> `ResponseCache`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **ServeConfig / preset**: Per-run serving options of the `jev_local` HTTP server for benchmax (precision, overflow refuse/truncate, refusal status/style, public model id, label alias), chosen once at server start, never per request. Code: `jev_local/api.py` -> `ServeConfig`, `PRESETS`. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **settle (demos)**: See *freeze / quiet / settle (demos)*. - **settled point**: `RuntimeImpl.settled()`, run `settleMs` (default 60 ms) after the last op end, applied write or discarded write. It does nothing while an op younger than 10 s is in flight or a write is pending (the next op end or write schedules it again); otherwise it runs the invariant miner, takes consistent snapshots, learns transition profiles and raises `inconsistency` / `transition` triggers. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [state-and-adapters](runtime/state-and-adapters.md). -- **setup() (tests)**: The runtime test factory: `createRuntime` with a `FakeClock`, a global whose `fetch` is a `FakeServer` (location `http://app.test/search`), a `ScriptedDecider`, `report: "silent"` and only the fetch observer; returns `{ clock, server, g, decider, rt, fetch }`. Options you pass override these defaults, so keep your own reference to a custom decider. Code: `packages/runtime/test/helpers.ts` -> `setup`. Doc: [build-test-release](runtime/build-test-release.md). +- **setup() (tests)**: The runtime test factory: `createRuntime` with a `FakeClock`, a global whose `fetch` is a `FakeServer` (location `http://app.test/search`), a `ScriptedDecider`, `report: "silent"`, only the fetch observer and **`mode: "guard"`** (kept by f3636b2 so existing tests still exercise guard; pass `mode: undefined` for the product default `observe`, as `default-mode.test.ts` does); returns `{ clock, server, g, decider, rt, fetch }`. Options you pass override these defaults, so keep your own reference to a custom decider. Code: `packages/runtime/test/helpers.ts` -> `setup`. Doc: [build-test-release](runtime/build-test-release.md). - **shape / Unusual**: See *transition profile*. -- **SIM (workstream)**: Owns `sim/`; writes `sim/NEEDS.md`, `sim/README.md` and the training data under `sim/out/` (gitignored). Doc: [status-and-known-issues](status-and-known-issues.md), [sim](sim.md). +- **SIM (workstream)**: Owns `sim/`; writes `sim/NEEDS.md`, `sim/README.md`, `sim/SEPARABILITY.md` and the training data (`sim/out/` locally, gitignored; v2 production on Azure into `train:/data/sim-out/v2-*` via `sim/scripts/cluster/`). Doc: [status-and-known-issues](status-and-known-issues.md), [sim](sim.md). - **sim op / sim write**: The sim's app-level ground-truth records, not runtime ops: `SimOp` (a request with role, intent, key, idempotent, attempt, `retryOf`, `dupOf`, `classify()`, linked runtime op id) and `SimWrite` (a store write with role, op, intent, key, changed fields, anomaly, `classify()`, linked runtime mutation). Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`. Doc: [sim](sim.md). - **simA / sim1 (buckets)**: Training buckets of SIM data: `simA` = phase A (`final-a`, frozen format; 448,420 / 14,613 / 137,643 rows), `sim1` = the pre-freeze run `r300k` (224,051 / 7,426 / 68,790). `simAe` (8k dev / 20k test) and `sim1e` (20k test) are random eval subsets; `simsample` is the 200-row `sim/samples/sample.jsonl`. Doc: [training](training.md). - **SitEnv**: The read-only view of the runtime that situation code receives (ops, hub, baselines, profiles, events, redactor, cache peek, identical requests, consistent snapshots, `storeWriters`, `chainWrites`, ...), implemented by `RuntimeImpl.makeEnv`. Code: `packages/runtime/src/situation/env.ts` -> `SitEnv`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **situation**: The model input for one trigger: a `JevState` with seven keys in fixed order, `app`, `trigger` (the subject sentence), `facts`, `in_flight`, `timeline`, `state` (store field lines), `stats` (signature baselines), shaped to the situation budget, plus the typed `questions`. The `Situation` object (`rt.situation()`, `buildSituation`) also carries `trigger, subject, actions, salient, facts, compact, budget`, which the model does not read. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). -- **situation budget**: The situation's size in characters as measured by `stateChars`: `STATE_CHAR_BUDGET` 3200 (full), `COMPACT_BUDGET` 1100 (smallest section limits), floor `MIN_BUDGET` 500, linear in between (`sectionLimits`). `situation.budget: "auto"` (default) gives 3200 for WebGPU or an unknown device and `1000 + round((threads − 1) × 1000 / 3)` for WASM with 1–4 threads, times the budget scale; a number is used as is. Over budget, `toJevState` drops timeline lines (oldest first), then state, facts (keeping ≥ 1), in-flight and stats lines, then shortens facts and the trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **situation-v1**: Annotated git tag on commit 1a77558 ("Frozen runtime situation format for model training"). SIM phase A/B and TRAIN's final rounds use this format; `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Any change to text the model reads (situation code, `util.ts` formatters, `changeText`, questions, vocabulary, budgets) needs regenerated SIM data, a matching change to the `training/curriculum/rt.py` port and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference the model was trained with. Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). +- **situation budget**: The situation's size in characters as measured by `stateChars`: `STATE_CHAR_BUDGET` 2400 (full; 3200 in situation-v1, lowered in batch 4), `COMPACT_BUDGET` 1100 (smallest section limits), floor `MIN_BUDGET` 500, linear in between (`sectionLimits`). `situation.budget: "auto"` (default) gives 2400 for WebGPU or an unknown device and 1000 / 1333 / 1667 / 2000 for WASM with 1 / 2 / 3 / 4+ threads, times the budget scale; a number is used as is. Over budget, `toJevState` drops timeline lines (oldest first), then state, facts (keeping ≥ 1), in-flight and stats lines, then shortens facts and the trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **situation-v1**: Annotated git tag on commit 1a77558 ("Frozen runtime situation format for model training"), the previous training format: SIM phase A/B, `cur4` and final round 1 (the R17/R32 checkpoints that exist) use it. Superseded by *situation-v2*; nothing trained on v1 matches the current runtime. +- **situation-v2**: Annotated git tag on commit 6e5e86e ("Frozen runtime situation format v2"), the **current** frozen training format: batches 4 and 5 (the *delivery* trigger, non-blocking mutations, conflicts, F1–F9, 2,400-char budget, leaf redaction). The v2 SIM gold/unlabeled data, REAL batches `v2b1`–`v2b3` and `training/curriculum/rt.py` ("FROZEN at git tag `situation-v2`") target it; no v2 model exists yet. On `mvp-v2`, `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts`, `types.ts` and `devtools/index.ts` (the default mode), not model input. Any change to text the model reads (situation code, `learn/`, `util.ts` formatters, `state/fields.ts` `changeText`/`stringDiff`, questions, vocabulary, budgets) needs a new tag, regenerated SIM and REAL data, a matching `rt.py` change and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference. Doc: [model-io-contract](model-io-contract.md), [learn-situation-triage](runtime/learn-situation-triage.md). Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). - **skill (jevbench)**: `clip((m − c) / (1 − c), 0, 1)` for primary metric `m` and chance level `c`. Code: `jev_local/bench/metrics.py` -> `skill`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **slot (VM slot)**: A per-workstream directory `~/gcl/<SLOT>` on the Azure `train` VM used by `scripts/vm.sh` (names `[a-zA-Z0-9_-]+`, conventionally `core`, `model`, `sim`, `demos`). `sync` uses `rsync --delete`, so files created in a slot outside the excluded paths are removed on the next sync. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). - **smoke test**: `packages/runtime/test/smoke/smoke.sh`: build, `npm pack`, install the tarball into a temporary Vite 8 app, build it and load it in headless Chromium (Playwright) on port 4191, requiring no errors, a devtools element and ≥ 3 history events; runs with `model: false`. Doc: [build-test-release](runtime/build-test-release.md). - **Spec (benchmax)**: Registry entry `{ id, suite, adapter, harness, verification, counted_rows, description, owner }` whose `id` equals a `targets.json` `spec_id` byte for byte; 19 are registered (4 group A, 15 group B). Code: `jev_local/bench/benchmax/__init__.py` -> `Spec`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **split (sim)**: Decided per scenario: test = one of 10 held-out domains, a held-out family hash (first 17%) or a held-out pattern; dev = 3% of the remaining families; only 33% of test trajectories are kept (`--test-keep`). All rows of a trajectory share its split. Code: `sim/src/world/scenario.ts` -> `splitOf`. Doc: [sim](sim.md). +- **split (sim)**: Decided per scenario: test = a held-out domain, a held-out family hash (first 17%), a held-out pattern or (since round 2) a held-out feature (`TEST_FEATURES`, disabled by `SIM_FEATURE_HOLDOUT=off`); dev = 3% of the remaining families; only 33% of test trajectories are kept (`--test-keep`). All rows of a trajectory share its split. realapps has its own held-out apps and frameworks (`TEST_APPS`, `TEST_FRAMEWORKS`). Code: `sim/src/world/scenario.ts` -> `splitOf`. Doc: [sim](sim.md). - **stage 1 / 1c / 2 (training)**: Training rounds before the freeze: s1 = curriculum `cur1` + `gen`/`cu` replay (`mix_s1`); s1c = continuation with runtime-exact `cur2` (`mix_s1c`), the current best checkpoints (`rt1` action ≈ 98%, FIR 0%); s2 = pilot on the pre-freeze SIM run `r300k` (`mix_s2`), precise but with heal recall ≈ 1.3%. Final rounds restart from the s1c weights. Doc: [training](training.md). - **staged evaluation (extension)**: The extension first asks the `STAGE1` questions (intent, complete, is_command, destructive) and, only when the policy returns `need_args`, the argument question the intent needs (`ARG_QUESTIONS[intent]`); exact because questions are block-isolated in the attention mask. Code: `extension/src/core/policy.js` -> `evaluatePolicy`, `ARG_QUESTIONS`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **stall (trigger)**: Raised once per gated fetch or async XHR by `RuntimeImpl.watchStall` at `max(4 × median, 2 × p95, 500 ms)` after sending, only when the signature has a latency baseline (≥ 5 samples); not held, priority 1; actions `wait` (passive), `hedge`, `serve_cached` (XHR: passive only). Fact S1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.watchStall`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **stale mark (F9)**: `StaleMark { t, op, why }` on a field's `FieldState.mark`, set by `RuntimeImpl.markWrites` / `RuntimeImpl.onChannel` when a write is known to be suspicious (its response was delivered over newer data or a pending local change without a decision to drop it, took ≥ 5× its usual time, followed an ambiguous failure, or came from a push channel that had been down) and cleared by the next write. Stated by fact F9 in later delivery, mutation, inconsistency, transition and error situations. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.markWrites`; `packages/runtime/src/situation/evidence.ts` -> `markFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **stall (trigger)**: Raised once per gated fetch or async XHR by `RuntimeImpl.watchStall` at `max(4 × median, 2 × p95, 500 ms)` after sending, only when the signature has a latency baseline (≥ 5 samples); not held, priority 1; actions `wait` (passive), `hedge`, `serve_cached` (XHR: passive only). The runtime's stall fact S1 (not the sim label rule) makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.watchStall`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **stall watch (model host)**: A host timer re-armed by every worker status while loading (180 s); silence means a stuck worker, which leads to the one WASM retry if WebGPU was involved, otherwise to status `error`. Code: `packages/runtime/src/model/host.ts` -> `LOAD_STALL_MS`. Doc: [model-host](runtime/model-host.md). - **standing question**: `StandingQuestion { id, on, question, always?, onAnswer? }`, registered with `rt.question` or a plugin: asked next to `diagnosis` / `action` on its triggers; `always: true` makes the trigger *forced* (bypasses triage); `onAnswer` receives the answer after the decide/detect events, before any action. Docs also call the built-in `diagnosis` and `action` questions "standing questions". Code: `packages/runtime/src/types.ts` -> `StandingQuestion`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **state (section)**: The `state` key inside a situation, not the whole `JevState`: lines `<path> = <value> (v<version>[, by #writer] <secs> ago)` for the involved fields first, then fields of all involved stores, most recent write first; a store registered with `describe` contributes one line instead. Code: `packages/runtime/src/situation/build.ts` -> `stateLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **stats (section)**: The situation section of baseline lines for the subject op's signature and every in-flight fetch/XHR signature: `<sig>: <count> done[, median <secs>, p95 <secs>], <failed> of last <of> failed, <recent> in last 10s[ (usual <n>)]`. Code: `packages/runtime/src/situation/build.ts` -> `statsLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **STATUS.md**: `packages/runtime/STATUS.md`, CORE's status file read by SIM, DEMOS, UI and MODEL: test state, batch changes, the headless recipe, the trigger table, example situations, "Deviations from the contract (and why)" and "Open issues". Last changed at 1a77558. Doc: [status-and-known-issues](status-and-known-issues.md). +- **STATUS.md**: `packages/runtime/STATUS.md`, CORE's status file read by SIM, DEMOS, UI and MODEL: test state, batch changes, the headless recipe, the trigger table, example situations, "Deviations from the contract (and why)" and "Open issues". Now also the batch 4 and 5 sections and the never-worse sweep; last changed in bac4409 (it predates `default-mode.test.ts`, so its "41 files, 346 tests" excludes that file). Doc: [status-and-known-issues](status-and-known-issues.md). - **stick**: `Context.stick(op)`: makes `op` ambient until `clock.afterTask` clears it at the end of the macrotask (only if it is still that op); done when a fetch/XHR/Response body settles, a user action is recorded, a timer fires, a WS message arrives or `rt.op` settles. Code: `packages/runtime/src/trace/context.ts` -> `Context.stick`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **store / StoreHub**: Every store registered with a runtime lives in one `StoreHub`, keyed by a store name that is global per runtime. The hub holds the three store kinds (*atom*, *guard*, *adapter*), the mutation pipeline, per-field versions and logs, recent changes, late-revert primitives and snapshots. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **storeWriters**: `Map<signature, Map<store, count>>` learned in `RuntimeImpl.onApplied` (the writer plus up to 8 ancestors; ≤ 1000 signatures): how often each signature's chain wrote each store. Used for involved stores, timeline relevance, concurrency facts and `defer`'s related ops. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **student**: A small model meant to ship (R17 default, R32; R68 benchmark only), trained by *distillation* from the teacher's labels plus gold data. See *teacher*, *distillation*. - **subject / SubjectSpec / SubjectRef**: What a trigger is about. `SubjectSpec` is the rich internal description (one variant per trigger: the `MutationRec`, the op and `ReqMeta`, the violations, ...); `SubjectRef` is the public id-only reference (`{ kind, op?, mutation?, store?, paths?, cause?, error?, invariant? }`) passed as `EvaluateRequest.subject` and `Decision.subjectRef` and never serialised into model input. The short `Situation.subject` string is for reports and devtools. Code: `packages/runtime/src/situation/env.ts` -> `SubjectSpec`; `packages/runtime/src/types.ts` -> `SubjectRef`; `packages/runtime/src/situation/build.ts` -> `subjectOf`, `subjectRef`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **subject correlation (sim)**: How the sim maps `EvaluateRequest.subject` (runtime op/mutation ids) to its own knowledge, via `hooks.opCreated` / `mutationProposed` and the `x-request-id` header; recorded as `how` (`subject`, `sync`, `chain`, `delivered`, `last`, `text`, `none`). An unknown subject gets no diagnosis label. Code: `sim/src/run/runner.ts` -> `runScenario`. Doc: [sim](sim.md). -- **subject op**: The op a situation centres on: the cause op for `mutation`, the request op for request/failure/stall/transition, the ambient op for `error`, the asked op for `ask`, none for `inconsistency`. Code: `packages/runtime/src/situation/build.ts` -> `subjectOp`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **subject op**: The op a situation centres on: the cause op for `mutation`, the op for request/delivery/failure/stall/transition, the ambient op for `error`, the asked op for `ask`, none for `inconsistency`. Code: `packages/runtime/src/situation/build.ts` -> `subjectOp`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **summed-mass gate**: See *policy gate*. - **sync verdict**: For mutations only: the verdict `gateMutation` sees while `trigger()` is still on the stack. `apply` there (triage-neutral, not salient, provider `off`, nothing permitted) means the write is not held at all and applies in the caller's stack. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **synthetic end**: `endOp(..., { synthetic: true })`: the op was answered by GenClass (block, cache, coalesce); excluded from latency baselines and transition profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). @@ -378,6 +413,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## T +- **T1 (expected-gain target)**: TRAIN's proposal from SEPARABILITY §5/§7: train on expected advantage instead of "probability of being best", either by relabelling the action as softmax(gain/τ) (`r17-t1g10` τ 1, `r17-t1g20` τ 2; buckets `simAg10`/`simAg20`) or by keeping SIM's label and adding a *gain head* (`r17-t1h`, bucket `simAh`), then gating on predicted gain per action. All three runs were on v1 data and were stopped at the v2 freeze with no results; T1 labels put ≥ 0.5 non-passive mass on 64% of rows, so they must be evaluated with `eval_gain.py`'s `gain>m` / `head>m` policies, not the summed-mass gate. Not the runtime's transition fact T1. Code: `training/t1_relabel.py`, `training/eval_gain.py`. Doc: [training](training.md). +- **T150 / teacher**: The *teacher* is a large model that is never shipped (T150 = `ettin-encoder-150m`, ≈ 111M parameters, pruned vocabulary, fresh heads; T400 only if T150 clearly beats R68). It is trained on gold rows, then its calibrated probabilities become `dist` labels on unlabeled rows (`training/label_teacher.py`, across nodes `training/label_cluster.sh`, which is untested) for *distillation*. The only teacher run so far, `t150-g1` on v1 data (`mix_t150`), was stopped at step 69 at the v2 freeze; HANDOFF's next step is a 150M teacher on v2 gold. Code: `training/launch_t150.sh`, `training/label_teacher.py` -> `main`. Doc: [training](training.md). - **Tail / vid (extension)**: `Tail` is the unconsumed transcript `{ vid, text, words, cursor, isFinal, silentMs, uid, joined }`; `vid` is the virtual utterance id `"<uid>+<gen>"`, where `gen` increments on every consume. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **templates (devtools)**: `actTitle`, `diagTitle` and `phrase`: card titles used when no report sentence is known; they approximate the wording of `packages/runtime/src/decide/report.ts`. Code: `packages/runtime/src/devtools/ui.ts` -> `actTitle`, `diagTitle`, `phrase`. Doc: [devtools](runtime/devtools.md). - **tier**: The mode an action needs: `passive` (always allowed), `guard` (withhold, deduplicate or slow down: `discard`, `defer`, `coalesce`, `delay`) or `heal` (change what the app receives or restore state: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`; custom actions by default). The policy gate compares the mode with the tier and uses the tier's threshold (guard 0.9, heal 0.8). Code: `packages/runtime/src/types.ts` -> `Tier`; `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). @@ -387,17 +424,17 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **Trace (curriculum)**: The explicit curriculum world model (ops, writes with versions, extra events, baselines) from which every curriculum label is computed; labels never come from rendered text. Code: `training/curriculum/world.py` -> `Trace`. Doc: [training](training.md). - **trace run (demos)**: `?trace=1` or `eval.ts --trace`: records proposed writes (`hooks.mutationProposed`), applied state events, ops and decisions into `window.__gcTrace`, analysed by `demos/e2e/trace-report.ts`; off by default and never in published results. Doc: [demos](demos.md). - **track Z / S (benchmax)**: Z = zero-shot (no benchmark data of any split in training); S = supervised (official train splits allowed and disclosed). Their scoreboards are never merged. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **TRAIN (workstream)**: Owns `training/` (`training/README.md` says "Owner: TRAIN"; runtime CONTRACT §1 lists the lead); writes `training/NEEDS.md`, `training/LOG.md` and `training/EVAL.md`. Doc: [status-and-known-issues](status-and-known-issues.md), [training](training.md). -- **train VM**: The Azure VM named `train` (10.0.0.4): the team's build/test host for every workstream slot (`scripts/vm.sh`), where SIM generates data and exported models are delivered and validated; it has a 03:00 UTC auto-shutdown. Doc: [build-test-release](runtime/build-test-release.md), [training](training.md), [sim](sim.md). +- **TRAIN (workstream)**: Owns `training/` (`training/README.md` says "Owner: TRAIN"; runtime CONTRACT §1 lists the lead); writes `training/NEEDS.md`, `training/LOG.md`, `training/EVAL.md` and `training/PLAN-v1.md` (results summary also in `docs/runtime/RESULTS.md`). Holds no Azure node during v2 data generation. Doc: [status-and-known-issues](status-and-known-issues.md), [training](training.md). +- **train VM**: The Azure VM named `train` (10.0.0.4): the team's build/test host for every workstream slot (`scripts/vm.sh`), where SIM bundles cluster runs, exported models are delivered and validated, and large artifacts go to `/data` (1 TB: `/data/sim-out/`, `/data/real-out/`). Its 03:00 UTC auto-shutdown (and the nodes') is disabled during the training push, per `HANDOFF.md`. Doc: [build-test-release](runtime/build-test-release.md), [training](training.md), [sim](sim.md). - **trajectory (sim)**: One scenario processed by `generateTrajectory`: ideal run + base run + counterfactual runs for up to `maxPoints` decision points -> decision rows, diagnosis-only rows and ask rows, all in one split. Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md). - **transform variant (sim)**: Per-row post-processing of the recorded `action` question (`meta.transform`): `default`, `shuffle`, `drop:<action>` or `drop:<action>,shuffle`, with the label distribution adjusted to match. Code: `sim/src/run/transform.ts` -> `transformQuestions`. Doc: [sim](sim.md). -- **transition (trigger)**: Raised at a settled point for an op whose completion is unusual for its signature (see *transition profile*); the most specific flagged op wins and each op is raised at most once; not held, priority 0; actions `ignore`, `rollback` (chain revert), `resync`. Fact T1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseTransition`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **transition (trigger)**: Raised at a settled point for an op whose completion is unusual for its signature (see *transition profile*); the most specific flagged op wins and each op is raised at most once; not held, priority 0; actions `ignore`, `rollback` (chain revert), `resync`. The runtime's transition fact T1 (not TRAIN's T1 target) makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseTransition`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **transition profile**: `Profiles`: per op signature (user ops as `user <name>`), counts over completions of the written-field set (normalised chain keys), each field's value kind (arrays only empty/non-empty), the status class, a write-count bucket and a duration bucket. At a settled point `Profiles.check` returns `Unusual` items for a set, kind, status or write count seen in < 1% of ≥ 20 previous completions (duration is never checked), which raises `transition`. Persisted to `localStorage` only with `learn: { persist: true }`. Code: `packages/runtime/src/learn/profiles.ts` -> `Profiles`, `shapeOf`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **transport (model host)**: How the host reaches its `ModelBackend`: `WorkerTransport` (a module Worker running `dist/worker.js`) or `InlineTransport` (same realm, via a microtask), used when the Worker cannot start, errors before `hello`, sends no `hello` within 15 s, or `worker: false`. Both speak `ToWorker` / `FromWorker`, which carry only `state` and `questions`. Code: `packages/runtime/src/model/host.ts` -> `WorkerTransport`, `InlineTransport`; `packages/runtime/src/model/protocol.ts` -> `ToWorker`. Doc: [model-host](runtime/model-host.md). - **tree layout / BandedEncoder**: Python attention implementations: `collate_tree` computes the block-mask attention as trunk (state), head (header) and item-chunk sub-problems; `BandedEncoder` is a faster exact version (`JEV_ENCODER=reference` selects `MaskedEncoder`). Code: `jev_local/engine/encoder/tokenize_pack.py` -> `collate_tree`; `jev_local/engine/encoder/engine.py` -> `BandedEncoder`. Doc: [genclass-model-lineage](genclass-model-lineage.md). -- **triage**: The cost filter before a model call: with `triage: "salient"` (default) the model is consulted only if some fact is non-neutral, a standing question with `always: true` covers the trigger, or the trigger is `ask`; otherwise the passive action runs with no model call and no `Decision`. `"always"` consults on every consultable trigger. Triage never picks a diagnosis or action, but it shapes the sim's training distribution (the sim runs with `"salient"`). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`; `packages/runtime/src/situation/facts.ts` -> `computeFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **triage**: The cost filter before a model call: with `triage: "salient"` (default) the model is consulted only if some fact is non-neutral, a standing question with `always: true` covers the trigger, or the trigger is `ask`; `delivery` is additionally pre-filtered by `RuntimeImpl.runDelivery` before any fact is computed, and covered writes raise no `mutation` at all; otherwise the passive action runs with no model call and no `Decision`. `"always"` consults on every consultable trigger. Triage never picks a diagnosis or action, but it shapes the sim's training distribution (the sim runs with `"salient"`). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`; `packages/runtime/src/situation/facts.ts` -> `computeFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **trial (demos)**: A seeded scenario run in a fresh page (in-page "Run trials" driver or the Playwright eval `demos/e2e/eval.ts`) and scored by the demo's oracle; chaos trials measure bug rate, clean trials count false interventions. Doc: [demos](demos.md). -- **trigger**: A `TriggerKind` event that asks "should the runtime intervene here?": `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, plus `ask` for developer questions. Each has a `SubjectSpec`, a passive action, offered actions, a hold flag and a queue priority (held mutation/request/fetch failure 2; stall, inconsistency, XHR failure, ask 1; transition, error 0). Observers and settled points call `RuntimeImpl.trigger(spec, controller, opts)`. Code: `packages/runtime/src/types.ts` -> `TriggerKind`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **trigger**: A `TriggerKind` event that asks "should the runtime intervene here?": `mutation`, `request`, `delivery` (new in situation-v2), `failure`, `stall`, `inconsistency`, `transition`, `error`, plus `ask` for developer questions. Each has a `SubjectSpec`, a passive action, offered actions, a hold flag and a queue priority (delivery, request, fetch failure and held mutation 2; default non-blocking mutation, stall, inconsistency, XHR failure, ask 1; transition, error 0; a holdable trigger that does not *wait* is queued at priority ≤ 1). Observers and settled points call `RuntimeImpl.trigger(spec, controller, opts)`. Code: `packages/runtime/src/types.ts` -> `TriggerKind`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **typed decision**: One forward pass that answers typed questions (`choice`, `noul`, `score`) about a state object, with calibrated probabilities; the Jev request shape and the model family used throughout this repo. See *Jev*. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **TypeSafe**: The company behind Jev; see *Jev*. @@ -406,6 +443,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **UI (workstream)**: Owns `packages/runtime/src/devtools/**` and `packages/runtime/src/adapters/**` (CONTRACT §13; §1's table still says CORE); writes `packages/runtime/UI-NEEDS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). - **undo**: `ActionRecord.undo()`, present only for reversible effects (discard, late revert, rollback, chain revert, custom `onUndo`): idempotent, runs inside a GenClass op named `undo`, never gated, pushes an `action` event `undid <action> (<id>)`, and fires no `act` event or report. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **unholdable**: See *detached preview / unholdable*. +- **unlabeled rows**: SIM's cheap row mode (`gen.js --unlabeled`): one base run per scenario (exploration × 1.5, ask probes always on), every decision point becomes a row with the gold `diagnosis` (when correlated) but no action label; ids `u-<seed>-d<k>`, `meta.unlabeled: true`. About 150 rows/s per worker vs about 4.4 for gold. They exist to be soft-labelled by the *teacher*; SIM v2 targets ≥ 50M of them (seeds from 16e9), REAL writes `-u<k>` rows too. Review finding: their hard `expected` diagnoses ignore S1, and `label_teacher.py` keeps existing labels unless `--overwrite`. Code: `sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`. Doc: [sim](sim.md), [training](training.md). +- **untrustedEvents**: `observe.untrustedEvents` (default `false`, batch 4): whether synthetic DOM events (`isTrusted === false`, e.g. `el.dispatchEvent(new MouseEvent("click"))`, testing-library) count as user actions. Off, they are dropped, so scripted drivers that are not real browser input (the demos' in-page synthetic driver, unit tests) record no user ops unless they opt in; realapps turns it on for its scripted user (`realapps/src/harness/trajectory.ts` -> `OBSERVE`). It is a flag in the `observe` map, not an observer. Code: `packages/runtime/src/types.ts` -> `InitOptions.observe`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **user model (sim)**: `UserModel`: think times (`max(120, lognormal)` ms), per-keystroke typing with typos and backspaces, accidental double clicks and impatient re-clicks guarded by `when` conditions; accidental steps carry `repeatOf`. Code: `sim/src/app/feature.ts` -> `UserModel`. Doc: [sim](sim.md). - **user-sync write**: A write whose cause is the current task's user op or shares its root (`Context.isUserSync`); it bypasses gating and is never held unless `policy.holdUserWrites` is true. Code: `packages/runtime/src/trace/context.ts` -> `Context.isUserSync`. Doc: [state-and-adapters](runtime/state-and-adapters.md). @@ -413,7 +452,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **v0.1 fixture set**: `packages/runtime/test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests with the Python packer output and PyTorch logits of the v0.1 GenClass model. Doc: [build-test-release](runtime/build-test-release.md). - **v0.1 model**: See *GenClass 0.1 (v0.1 model)*. -- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0` (published per `OPEN_TASKS.md`; the registry was not re-checked). Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). +- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, still the latest on npm (checked 2026-10-08). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **v2b1 / v2b2 / v2b3 (REAL batches)**: REAL's situation-v2 production batches on c01, c10 and c11 (30k trajectories each, about 495k gold rows in total per HANDOFF/RESULTS; NEEDS target ≥ 500k), to be copied to `train:/data/real-out/` (`training/NEEDS.md` item 16; not verifiable from the repo). Their `manifest.json` still says `situation-v1` (hardcoded in `realapps/src/harness/gen.ts`). Doc: [realapps](realapps.md). - **variant (jevbench)**: Request flavour per item: `main` (the only one counted), `shuffle` (option-order rotation), `bare` (no descriptions), `choice` (SST-2 only). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **variant (model)**: One ONNX file of a model, keyed in `card.variants`: `q8` (meant for WASM) or `fp16` (meant for WebGPU with `shader-f16`). See *q8*, *plan*. Doc: [model-host](runtime/model-host.md). - **varied style**: See *runtime-exact row / varied style (curriculum)*. @@ -428,11 +468,11 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **W1–W11**: Engine and wire requirements for benchmax runs from `docs/benchmax-research/suite-reproduction-specs.md` §1.2 (e.g. W1 choice = argmax of unrounded probabilities with ties to the first key, W2 score fields, W3 precision, W4 refusal bodies, W5 overflow refuse/truncate, W9 one global calibration file, W10 model id never `jev-*`, W11 determinism). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`; `jev_local/api.py` -> `ServeConfig`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **wait (action)**: Passive action of the `stall` trigger: keep waiting for the response. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **waits**: In `RuntimeImpl.trigger`, `opts.hold && permittedActions(policy, mode, actions).length > 0 && !paused`: whether the subject is actually held. A holdable trigger with nothing permitted runs its passive action at once and is decided in the background (detection only, 5 s deadline). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **waits**: In `RuntimeImpl.trigger`: `opts.hold`, at least one non-passive action permitted by mode and policy, not paused, and (since batch 4) the expected model latency fits the hold budget (`expectedLatency() <= holdBudgetMs()`): whether the subject is actually held. A holdable trigger that does not wait runs its passive action at once and is decided in the background (detection only, `BACKGROUND_DEADLINE_MS` 5 s), which is what every trigger does in the default `observe` mode. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **warm-up**: One forward pass (two on WebGPU) over `WARMUP_STATE` / `WARMUP_QUESTIONS` before a plan is accepted; it sets `status.warmupMs` (which seeds the auto hold budget) and seeds `status.latency`. Code: `packages/runtime/src/model/backend.ts` -> `ModelBackend`, `WARMUP_STATE`. Doc: [model-host](runtime/model-host.md). - **wire request**: `{ state, questions }`, the only part of `EvaluateRequest` the model host uses; `trigger`, `subject`, `priority` and `timeoutMs` are scheduling and test metadata that never reach the packer. Code: `packages/runtime/src/model/protocol.ts` -> `ToWorker`. Doc: [model-io-contract](model-io-contract.md). - **worker URL pattern**: The literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `defaultWorkerFactory` (and the literal `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` calls beside it) that app bundlers recognise; the browser-test build asserts they survive bundling. Code: `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory`. Doc: [build-test-release](runtime/build-test-release.md). -- **workstream**: A team role that owns paths (runtime CONTRACT §1 and §13): lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW. They communicate through `packages/runtime/STATUS.md` and per-requester NEEDS files; each has its own entry here. Doc: [status-and-known-issues](status-and-known-issues.md). +- **workstream**: A team role that owns paths (runtime CONTRACT §1 and §13): lead, CORE, MODEL, UI, SIM, REAL (added with `realapps/`), DEMOS, TRAIN, REVIEW. The colleague's Claude sessions play all of them; they communicate through `packages/runtime/STATUS.md`, `HANDOFF.md` and per-requester NEEDS files (REAL's requests live in `training/NEEDS.md`); each has its own entry here. Doc: [status-and-known-issues](status-and-known-issues.md). - **world (demos)**: One mock-server session in the demos' Service Worker, keyed by `live-<demo>-<rand>` or `trial-<demo>-<run>`; it owns state, chaos, request and event logs, SSE streams and timers. The page controls it only via `postMessage`, so GenClass never observes test traffic. Code: `demos/src/server/core.ts` -> `World`. Doc: [demos](demos.md). ## X diff --git a/docs/agents/model-io-contract.md b/docs/agents/model-io-contract.md index f8632605..24a50381 100644 --- a/docs/agents/model-io-contract.md +++ b/docs/agents/model-io-contract.md @@ -1,64 +1,73 @@ # Model I/O contract: situation text -> packed request -> model heads -> calibrated answers (runtime, sim and training) -> **Scope:** `packages/runtime/src/situation/{serialize,questions,build,describe,env}.ts`, `packages/runtime/src/model/{packer,serialize,tokenizer,calibrate,engine,protocol,loader}.ts` (+ `pyutil.ts`), the model seam of `packages/runtime/src/types.ts`, `sim/src/ask/questions.ts`, `sim/src/gen.ts`, `sim/src/gen/*.ts`, `sim/src/oracle/cost.ts` (+ `sim/src/run/transform.ts`, `sim/src/run/rt.ts`), `training/export_runtime.py`, `training/eval_runtime.py`, `training/curriculum/{fmt,rows}.py` (+ `rt.py`), `packages/runtime-model/MODEL_CARD.md`, the example situations in `packages/runtime/STATUS.md`. Python reference counterparts in `jev_local/` and `scripts/genclass_export.py` are cited where they define the other side of the contract. -> **Read this when:** you change any text the model reads (facts, subject sentences, timeline/state/stats lines, question instructions, option descriptions, diagnosis labels, budgets); you change the packer, tokenizer, feeds, heads or calibration; you change how the sim labels rows or how training reads them; you export or ship a model directory; you need to know whether a change forces regenerating data and retraining. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/situation/{serialize,questions,build,describe,env}.ts` (+ the delivery text in `facts.ts` -> `predictedText` and `conflicts.ts` -> `predictedWrites`), `packages/runtime/src/model/{packer,serialize,tokenizer,calibrate,engine,protocol,loader}.ts` (+ `pyutil.ts`), the model seam of `packages/runtime/src/types.ts`, `sim/src/ask/questions.ts`, `sim/src/gen.ts`, `sim/src/gen/*.ts`, `sim/src/oracle/cost.ts`, `sim/src/run/{transform,rt,latent,onpolicy}.ts`, `training/export_runtime.py`, `training/eval_runtime.py`, `training/curriculum/{fmt,rows,rt}.py`, the T1/teacher scripts (`training/{t1_relabel,label_teacher,collect_gain,eval_gain}.py`), `packages/runtime-model/MODEL_CARD.md`, the example situations in `packages/runtime/STATUS.md`. Python reference counterparts in `jev_local/` and `scripts/genclass_export.py` are cited where they define the other side of the contract. +> **Read this when:** you change any text the model reads (facts, subject sentences, timeline/state/stats lines, question instructions, option descriptions, diagnosis labels, budgets); you change the packer, tokenizer, feeds, heads or calibration; you change how the sim labels rows (gold, unlabeled, on-policy) or how training reads them; you export or ship a model directory; you need to know whether a change forces regenerating data and retraining. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR -- One pipeline, three consumers. The **runtime** builds a situation (`JevState` + typed questions). The **model host** packs it into token ids, runs the ONNX graph and calibrates the logits into answers. The **sim** records the same `state`/`questions` verbatim from the real runtime, attaches labels, and **training** packs them with the Python reference (`jev_local`). Every step on the TypeScript side is a byte-exact port of the Python step. That makes train/serve parity a hard invariant. -- The **situation** is a 7-key object in fixed order: `app, trigger, facts, in_flight, timeline, state, stats`. Each value is a string or an array of strings (one line each). Empty arrays become `"none"`. It is sized by a **character budget** (`STATE_CHAR_BUDGET` 3,200; compact 1,100; floor 500) and shrunk deterministically (`toJevState`). -- **Questions** are Jev-wire objects `{type, instructions, criteria}` of kind `choice | noul | score`. Standing qids are `diagnosis` (always, except on `ask`) and `action` (only when ≥ 2 actions apply). Qids are never shown to the model. At budgets ≤ 1,400 chars, options are bare labels (`null` descriptions, called **compact questions**). -- **Diagnosis labels (10, in order):** `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`. **Actions:** 15 built-ins, 7 trigger kinds, passive first: `apply|send|deliver|wait|ignore` are passive. -- **Packing:** `[CLS] key: text [SEP] … | [Q] header [O] item … | [Q] …`. Positions restart per question branch and per item. `q_group`/`i_group` drive block attention, so options and questions are isolated: option order and unrelated questions cannot change an answer. Limits: positions (state + longest single branch) ≤ `meta.max_len` (default 1536), total ≤ `meta.max_total` (default 8192). -- **Heads → answers:** raw logits (τ = 1) per question → calibration (`calibration.json`: by-header, then by-bucket, then τ(K), then per-kind temperature; or Platt for noul) → `Answer` (`choice`, `confidence`, `probabilities` in criteria order). The runtime gate reads only `probabilities` and the diagnosis `choice`. -- **SIM labels:** `action` is a soft distribution from **counterfactual costs**. The sim re-runs the scenario with each action forced, over up to 3 paired futures, adds a tier premium and a tie rule, then takes `p ∝ exp(−gap/τ)`. `diagnosis` is a hard label from the sim's own knowledge. `ask` rows get exact noul/score/choice labels. -- **Model directory** (`export_runtime.py`): `model.json` (card `genclass-runtime-model/1`, bytes + sha256), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU + `shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, and parity fixtures. -- **Freeze:** tag `situation-v1` (commit 1a77558) froze the situation format. `git diff situation-v1 HEAD -- packages/runtime/src jev_local scripts/genclass_export.py` is empty at 654d822. Any change to text, questions, vocabulary, budgets, packing, tokenizer or labels needs regenerated SIM data (and the `rt.py` port) plus retraining. +- One pipeline, three consumers. The **runtime** builds a situation (`JevState` + typed questions). The **model host** packs it into token ids, runs the ONNX graph and calibrates the logits into answers. The **sim** (and the real-browser corpus in `realapps/`, see [realapps.md](realapps.md)) records the same `state`/`questions` verbatim from the real runtime, attaches labels, and **training** packs them with the Python reference (`jev_local`). Every step on the TypeScript side is a byte-exact port of the Python step, so train/serve parity is a hard invariant. +- **Format version: `situation-v2`** (tag on 6e5e86e, "Runtime batch 5", 2026-10-07 23:26 -0400). The old `situation-v1` tag (1a77558) is the format of round-1 data and the round-1 model (R17-final1), which therefore does **not** match the current runtime. `git diff situation-v2 b435acb -- packages/runtime/src/situation packages/runtime/src/util.ts packages/runtime/src/state packages/runtime/src/learn` is empty; the model side (`src/model`, `jev_local`, `scripts/genclass_export.py`, `export_runtime.py`) is unchanged since `situation-v1`. +- The **situation** is a 7-key object in fixed order: `app, trigger, facts, in_flight, timeline, state, stats`. Values are strings or arrays of strings (one line each); empty arrays become `"none"`. It is sized by a **character budget** (`STATE_CHAR_BUDGET` **2,400** since v2, was 3,200; compact 1,100; floor 500) and shrunk deterministically (`toJevState`). +- **Triggers (8 + ask):** `mutation, request, delivery, failure, stall, inconsistency, transition, error`, plus `ask`. **`delivery` is new in v2:** a fetch/XHR response or a WebSocket/EventSource message about to reach the app; actions `deliver` (passive), `discard`, `defer`, with trigger-specific descriptions (`TRIGGER_DESCRIPTIONS`). Store writes are no longer held by default, so most stale-response decisions are now `delivery`, not `mutation`. +- **Questions** are Jev-wire objects `{type, instructions, criteria}` of kind `choice | noul | score`. Standing qids are `diagnosis` (always, except on `ask`) and `action` (only when ≥ 2 actions apply). Qids are never shown to the model. At budgets ≤ 1,400 chars, options are bare labels (`null` descriptions, **compact questions**). +- **Diagnosis labels (10, in order):** `expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient`. **Actions:** 15 built-ins; passive per trigger `apply|send|deliver|deliver|wait|ignore|ignore|ignore`. +- **Packing:** `[CLS] key: text [SEP] … | [Q] header [O] item … | [Q] …`. Positions restart per item; `q_group`/`i_group` drive block attention, so option order and unrelated questions cannot change an answer. Limits: state + longest branch ≤ `meta.max_len` (default 1536), total ≤ `meta.max_total` (default 8192). +- **Heads → answers:** raw logits (τ = 1) → calibration (`calibration.json`: by-header, by-bucket, τ(K), per-kind temperature; Platt for noul) → `Answer`. The runtime gate reads only `probabilities` and the diagnosis `choice`. Since f3636b2 the default mode is `observe`, so by default no answer changes execution. +- **SIM rows now come in three kinds** (`sim/src/gen.ts`): **gold** (counterfactual soft `action` dist + hard `diagnosis`; ids `sim-…`), **unlabeled** (`--unlabeled`: every decision point of a base run, diagnosis only; ids `u-…`), **on-policy** (`--on-policy <model dir>`: a real export decides through the production gate, DAgger rows; ids `p-…`). Labels gained **S1** (never `expected` where acting clearly wins; `meta.diagnosis_s1`) and **S2** (re-seeded futures re-draw what the runtime cannot observe; `src/run/latent.ts`). +- **Training-side gains (T1):** `training/t1_relabel.py` derives expected-gain labels from `meta.cost_futures` (`gain(a) = mean c(passive) − mean c(a) − premium`), `eval_gain.py` scores gate policies by captured gain, `label_teacher.py` soft-labels unlabeled rows with a teacher. +- **Model directory** (`export_runtime.py`, unchanged): `model.json` (card `genclass-runtime-model/1`, bytes + sha256), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU + `shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, and parity fixtures. **No situation-v2 model exists yet** and `@genclass/runtime-model` is not published. ## Files | path | role | key exports / entry points | |---|---|---| -| `packages/runtime/src/situation/build.ts` | Assembles a situation: subject sentence, facts, in-flight, timeline, state, stats, applicable actions, standing questions, triage flag | `buildSituation`, `subjectOf`, `subjectRef`, `isTrigger`, `BuildOptions`, `BuiltSituation`, `ActionOption` | +| `packages/runtime/src/situation/build.ts` | Assembles a situation: subject sentence, facts, in-flight, timeline, state, stats, applicable actions, standing questions, triage flag | `buildSituation`, `subjectOf`, `subjectRef`, `relatedInFlight`, `isTrigger`, `BuildOptions`, `BuiltSituation`, `ActionOption` | | `packages/runtime/src/situation/serialize.ts` | Budget-shaped `JevState` (key order, section and line limits, shrink order) | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `SituationParts`, `SectionLimits` | -| `packages/runtime/src/situation/questions.ts` | Action catalogue, per-trigger actions/passive/instructions, diagnosis vocabulary, standing-question builder | `BUILTIN_ACTIONS`, `BuiltinAction`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | +| `packages/runtime/src/situation/questions.ts` | Action catalogue, per-trigger actions/passive/instructions/descriptions, diagnosis vocabulary, standing-question builder | `BUILTIN_ACTIONS`, `BuiltinAction`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | | `packages/runtime/src/situation/describe.ts` | How ops/events are named in subject sentences, facts and timeline lines | `opPhrase`, `opLabel`, `userPhrase`, `statusText`, `eventLine` | -| `packages/runtime/src/situation/env.ts` | Read-only view of the runtime used by situation building; subject specs per trigger | `SitEnv`, `SubjectSpec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo` | -| `packages/runtime/src/situation/facts.ts` | (out of scope, see [learn-situation-triage.md](runtime/learn-situation-triage.md)) fact computation and ordering | `computeFacts`, `orderFacts`, `MAX_FACTS` | -| `packages/runtime/src/util.ts` | Formatting helpers that appear in the text (`secs`, `rel`, `fmtNum`, `truncate`, `describe`, redaction) | `secs`, `rel`, `truncate`, `describe` | -| `packages/runtime/src/types.ts` | Model seam types (CORE + MODEL change together; the file's "model seam" section) plus the situation/plugin types the text depends on | `JevState`, `Question`, `Answer`, `AnswerOf`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `TriggerKind`, `ModelStatus`, `EvaluateRequest`, `DecisionProvider`, `SubjectRef`, `Situation`, `SituationDraft`, `Fact`, `FactKind`, `Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier` | +| `packages/runtime/src/situation/env.ts` | Read-only view of the runtime used by situation building; subject specs per trigger | `SitEnv`, `SubjectSpec`, `DeliverySpec`, `CreateRec`, `OutcomeRec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo` | +| `packages/runtime/src/situation/conflicts.ts` | (detail in [learn-situation-triage.md](runtime/learn-situation-triage.md)) predicted write set P and newer-data / pending-local-change conflicts | `predictedWrites`, `matchFields`, `conflictsOn`, `Predicted`, `Conflict`, `PENDING_WINDOW_MS` | +| `packages/runtime/src/situation/{facts,content,evidence}.ts` | (out of scope, see [learn-situation-triage.md](runtime/learn-situation-triage.md)) fact computation and ordering; v2 content facts F1–F3, evidence facts F5–F7/F9, read-your-writes | `computeFacts`, `orderFacts`, `predictedText`, `MAX_FACTS`; `contentFacts`, `analyzeBody`; `scopeFacts`, `cadenceFact`, `markFacts` | +| `packages/runtime/src/util.ts` | Formatting helpers that appear in the text (`secs`, `rel`, `fmtNum`, `truncate`, `describe`); redaction by leaf field since v2 | `secs`, `rel`, `truncate`, `describe`, `isSensitivePath`, `defaultRedact` | +| `packages/runtime/src/types.ts` | Model seam types (CORE + MODEL change together) plus the situation/plugin types the text depends on | `JevState`, `Question`, `Answer`, `AnswerOf`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `TriggerKind`, `ModelStatus`, `EvaluateRequest`, `DecisionProvider`, `SubjectRef`, `Situation`, `SituationDraft`, `Fact`, `FactKind`, `Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier` | | `packages/runtime/src/model/serialize.ts` | Port of `jev_local/serialize.py`: state segments and question blocks with Python-after-JSON value semantics | `stateSegments`, `segmentText`, `questionBlock`, `questionEntries`, `entryText`, `toJsonValue`, `pyJson`, `criteriaEntries`, `stateText`, `MAX_ARRAY_SEGMENTS`, `DEFAULT_NOUL_INSTR`, `DEFAULT_CHOICE_INSTR`, `DEFAULT_SCORE_INSTR`, `QBlock`, `Segment`, `BlockKind`, `WireQuestion` | | `packages/runtime/src/model/pyutil.ts` | Python formatting semantics (`str.strip`, float `repr`, `round`) | `pyStrip`, `pyNumber`, `pyFloatRepr`, `pyRound`, `clip01` | | `packages/runtime/src/model/tokenizer.ts` | Byte-level BPE over a HF `tokenizer.json` (`encode_special_tokens = True` semantics) | `Tokenizer`, `bytesToUnicode`, `TokenizerJson` | | `packages/runtime/src/model/packer.ts` | Port of `jev_local/engine/encoder/tokenize_pack.Packer` (FastEngine length semantics) + ONNX feed plan | `Packer` (`pack`, `measure`, `encode`, `stateIds`), `PackerOptions`, `MARKERS`, `Marker`, `STATE` (= −1), `Packed`, `PackedQuestion`, `planInputs`, `unpackLogits`, `FeedPlan`, `HeadOutput` | | `packages/runtime/src/model/engine.ts` | Packer + ORT session + calibration → answers; builds exactly the inputs `meta.json` declares | `Engine` (`evaluate`, `logits`, `release`), `EngineOptions`, `FEEDS`, `ModelMeta`, `EngineResult`, `tensorFloats`, `OrtLike`, `OrtSessionLike`, `OrtTensorLike` | | `packages/runtime/src/model/calibrate.ts` | Port of `jev_local/engine/encoder/calibrate.py` lookup and `jev_local/confidence.py` answer math | `Calibration`, `parseCalibration`, `headerKey`, `kBucket`, `tauFor`, `noulAffine`, `calibrateLogits`, `buildAnswer`, `Precision`, `normalizeProbs`, `choiceConfidence`, `scoreConfidence`, `K_BUCKETS`, `BUCKET_CLAMP` | -| `packages/runtime/src/model/protocol.ts` | Main thread ↔ worker messages (`state`, `questions` only; trigger/subject never cross). `evaluate` and `measure` requests; one `result` per id | `ToWorker`, `FromWorker`, `EvaluateOk` | +| `packages/runtime/src/model/protocol.ts` | Main thread ↔ worker messages (`state`, `questions` only; trigger/subject never cross) | `ToWorker`, `FromWorker`, `EvaluateOk` | | `packages/runtime/src/model/loader.ts` | Model card parsing, plan order, downloads with sha256 | `parseCard`, `CARD_FORMAT`, `DEFAULT_CACHE_NAME`, `cardId`, `planOrder`, `fetchFile`, `fetchCard`, `ModelCard`, `FileSpec`, `VariantSpec`, `FileRole`, `Plan` | -| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample` | `main`, `mergeParts` | -| `sim/src/gen/trajectory.ts` | One scenario → decision rows, diagnosis-only rows, ask rows; counterfactual costs | `generateTrajectory`, `pointCosts`, `GenOptions`, `PointStat`, `TrajectoryOut` | -| `sim/src/gen/worker.ts` | Worker thread: writes `shards/<split>.w<id>.jsonl` or `parts/part-NNNNNN.<split>.jsonl` | (module) | +| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample`, row mode `--unlabeled` / `--on-policy <dir>` | `parse`, `main`, `mergeParts` (module-internal; nothing is exported) | +| `sim/src/gen/trajectory.ts` | One scenario → decision rows, diagnosis-only rows, ask rows (gold / unlabeled / on-policy); counterfactual costs; S1 | `generateTrajectory`, `pointCosts`, `diagnosisFromOutcome`, `metaOf`, `S1_GAP`, `GenOptions`, `PointStat`, `TrajectoryOut` | +| `sim/src/gen/worker.ts` | Worker thread: writes `shards/<split>.w<id>.jsonl` or `parts/part-NNNNNN.<split>.jsonl`; loads the on-policy model | (module) | | `sim/src/gen/examples.ts` | `sim/samples/EXAMPLES.md` renderer | `renderExamples` | -| `sim/src/oracle/cost.ts` | Run cost vs the ideal run; soft action label | `W`, `LABEL`, `TIER`, `runCost`, `actionLabel`, `clientDist`, `serverDist`, `valueDist`, `divergenceArea`, `relationViolation`, `CostBreakdown`, `ActionLabel` | -| `sim/src/oracle/diagnose.ts` | (detail in [sim.md](sim.md)) hard `diagnosis` label from the sim's knowledge | `diagnose`, `diagnoseFailure` | -| `sim/src/world/scenario.ts` | (detail in [sim.md](sim.md)) scenario seed → domain, budget, ask times, vocabulary paraphrases, split | `buildScenario`, `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `DEFAULT_DIAGNOSES` | +| `sim/src/oracle/cost.ts` | Run cost vs the ideal run; soft action label; divergence probes used by S1 | `W`, `LABEL`, `TIER`, `runCost`, `actionLabel`, `clientDist`, `serverDist`, `valueDist`, `divergenceArea`, `relationViolation`, `clientDivergenceAt`, `divergedFieldsAt`, `CostBreakdown`, `ActionLabel` | +| `sim/src/oracle/diagnose.ts` | (detail in [sim.md](sim.md)) hard `diagnosis` label from the sim's knowledge; `delivery` filled after the run | `diagnose`, `diagnoseFailure` | +| `sim/src/run/latent.ts` | S2: what a re-seeded future re-draws after the decision | `S2`, `FutureSpec`, `futureProfile`, `futureStepTimes` | +| `sim/src/run/onpolicy.ts` | On-policy decider: the runtime's own model host (built into `sim/dist/model-host`) reading an export directory | `loadModelDecider` | +| `sim/src/world/scenario.ts` | (detail in [sim.md](sim.md)) scenario seed → domain (115), budget, chaos (8 regimes), clean runs, ask times, vocabulary paraphrases, split | `buildScenario`, `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `TEST_FEATURES`, `DOMAINS`, `DEFAULT_DIAGNOSES` | | `sim/src/ask/questions.ts` | Programmatic `ask` questions with exact labels | `askQuestions`, `AskQ` | | `sim/src/run/transform.ts` | Post-transform of recorded questions (shuffle/drop action options); action paraphrases | `transformQuestions`, `ACTION_PARA` | -| `sim/src/run/rt.ts` | Options the sim passes to `createRuntime` | `createOptions`, `realRuntimeFactory` | +| `sim/src/run/rt.ts` | Options the sim passes to `createRuntime` | `createOptions`, `realRuntimeFactory`, `RuntimeOptions` | | `sim/src/types.ts` | Sim mirror of the seam + row schema | `Row`, `Label`, `PASSIVE`, `DIAGNOSES` | -| `training/curriculum/rows.py` | Stage-1 curriculum rows (decision / ask), varied style or runtime-exact | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `RENAMES` | +| `sim/scripts/relabel.py` | Re-derive gold action labels from `meta.cost_futures` (mirrors `actionLabel`) | — | +| `training/curriculum/rows.py` | Stage-1 curriculum rows (decision / ask), varied style or runtime-exact; maps actions when `rt.render` renders a delivery | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `RENAMES` | | `training/curriculum/fmt.py` | Surface variation (key names, time formats, paraphrase templates with held-out tails), vocab copies | `Style`, `TEMPLATES`, `ACTION_DESC`, `DIAG_DESC`, `TRIGGER_ACTIONS`, `TIER`, `DISTRACTOR_ACTIONS`, `js_numbers`, `pick_from` | -| `training/curriculum/rt.py` | Python port of the runtime's situation text (frozen wording) for runtime-exact curriculum rows | `render`, `to_state`, `section_limits`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR` | +| `training/curriculum/rt.py` | Python port of the runtime's situation text, **frozen at `situation-v2`** (delivery, conflicts, F1–F3, F5–F7/F9, 2,400 budget) | `render`, `to_state`, `section_limits`, `size_chars`, `delivery_spec`, `predicted_text`, `DIAGNOSES`, `ACTIONS`, `TRIGGER_DESCRIPTIONS`, `TRIGGER_ACTIONS`, `ACTION_INSTR`, `BUDGETS`, `P_DELIVERY`, `DELIVERY_ACTION`, `STATE_CHAR_BUDGET` | | `training/curriculum/generate.py` | (detail in [training.md](training.md)) curriculum CLI: row ids, `js_numbers`, validation through the trainer's own parser | `make_row`, `_validate`, `work`, `main` (`--p-runtime` → env `GC_P_RUNTIME`) | | `training/prune_vocab.py` | (detail in [training.md](training.md)) prunes the ettin tokenizer to the shipped `tokenizer.json` (16,000 merges) | — | -| `training/eval_runtime.py` | Accuracy, calibration fit (`calibration.json`), §8 gate metrics | `fit_calibration`, `decision_metrics`, `question_metrics`, `main` | +| `training/eval_runtime.py` | Accuracy, calibration fit (`calibration.json`), §8 gate metrics incl. clear-case recall | `fit_calibration`, `decision_metrics`, `question_metrics`, `main` | +| `training/t1_relabel.py` | T1: expected-gain action labels from `meta.cost_futures` (`meta.egain`) | `gains_of`, `main` | +| `training/label_teacher.py` | Teacher soft labels for (unlabeled) rows; `meta.teacher` | `main` | +| `training/collect_gain.py`, `training/eval_gain.py` | Raw logits (+ `gain_pred` from a gain head) and expected-gain evaluation of gate policies | `main` | | `training/export_runtime.py` | Checkpoint → ONNX q8/fp16 + model directory + parity fixtures | `make_q8`, `make_fp16`, `quantize_embedding`, `gemm_to_matmul`, `requests_from_rows`, `main` | -| `jev_local/serialize.py`, `jev_local/engine/encoder/tokenize_pack.py`, `jev_local/engine/encoder/calibrate.py`, `jev_local/engine/encoder/heads.py`, `jev_local/train/train.py` | Python reference: serialization, packing, calibration, heads, label → target | `state_segments`, `question_block`, `Packer.pack`/`pack_split`, `header_key`, `DecisionHeads`, `parse_target`, `encode_example` | +| `jev_local/serialize.py`, `jev_local/engine/encoder/tokenize_pack.py`, `jev_local/engine/encoder/calibrate.py`, `jev_local/engine/encoder/heads.py`, `jev_local/train/train.py` | Python reference: serialization, packing, calibration, heads, label → target | `state_segments`, `question_block`, `Packer.pack`/`pack_split`, `header_key`, `DecisionHeads`, `HeadOut`, `build_plan`, `parse_target`, `encode_example` | | `scripts/genclass_export.py` | ONNX graph definition and feed plan (imported by `export_runtime.py`) | `ExportModel`, `plan_inputs`, `unpack` | | `packages/runtime-model/MODEL_CARD.md` | Model card (only file in that package today) | — | -| `packages/runtime/test/fixtures/model/` | Parity fixtures for the TS ports: `py_fixtures.json` (made by `make_py_fixtures.py`: `serialize`, `tokenize`, `pruned`, `calibrate`, `confidence` sections), v0.1 `requests50.json` / `pack_fixtures.json` / `torch_fixtures.json`, `make_webgpu_variants.py` (WebGPU embedding-encoding variants) | read by `test/model/helpers.ts` | -| `packages/runtime/STATUS.md` ("Example situations") | Real rendered situations: the same stale write at 1,000 chars (998, compact questions) and 2,000 chars (1,494); one full-budget situation per trigger (mutation, request, failure, stall, inconsistency, transition, error) | copied from `test/budget.test.ts` / `test/situation.test.ts` | +| `packages/runtime/test/fixtures/model/` | Parity fixtures for the TS ports: `py_fixtures.json` (made by `make_py_fixtures.py`), v0.1 `requests50.json` / `pack_fixtures.json` / `torch_fixtures.json`, `make_webgpu_variants.py` | read by `test/model/helpers.ts` | +| `packages/runtime/STATUS.md` ("Example situations") | Real rendered v2 situations: the stale typeahead **delivery** at 1,000 chars (951, compact questions) and 2,000 chars (1,760); full-budget (2,400) examples per trigger and per new fact | copied from `test/budget.test.ts`, `test/situation.test.ts`, `test/delivery.test.ts`, `test/content.test.ts` | ## Concepts and data structures @@ -70,9 +79,12 @@ Terms used here beyond the shared terminology (see [glossary.md](glossary.md)): - **Marker**: special token `[Q] [O] [L] [T] [F]` whose hidden state feeds a head. **Branch**: state + one question's header + one of its items (what `max_len` bounds). - **Raw logits**: head outputs at τ = 1. **Header key**: `sha1(header)[:12]`, the key of `calibration.json.by_header`. - **Compact questions**: options with `null` descriptions when the situation budget ≤ `COMPACT_QUESTIONS_BUDGET` (1,400). -- **CONTRACT-D row**: one JSONL training example `{id, split, family, state, questions, labels, meta}`. -- **Counterfactual cost**: cost of a re-run with one action forced at a decision point, measured against the ideal run (`sim/src/oracle/cost.ts` -> `runCost`). **Future**: one re-seeded continuation after the decision (common random numbers across actions). -- **Tier premium / tie rule**: label-time adjustments that favour passive (`LABEL` in `cost.ts`). +- **Format tag**: a git tag that freezes the text the model reads (`situation-v1`, `situation-v2`). Training data and a model are valid only for the tag they were generated/trained on. +- **Delivery**: v2 trigger raised when a response or push message is about to reach the app. **Predicted write set P**: what the delivering op's signature wrote before (transition profile, else the last completion, else unknown; `conflicts.ts` -> `predictedWrites`). It is stated in the trigger sentence. +- **CONTRACT-D row**: one JSONL training example `{id, split, family, state, questions, labels, meta}`. **Gold / unlabeled / on-policy**: the three sim row kinds (`GenOptions.mode`). +- **Counterfactual cost**: cost of a re-run with one action forced at a decision point, measured against the ideal run (`sim/src/oracle/cost.ts` -> `runCost`). **Future**: one re-seeded continuation after the decision (common random numbers across actions). **S2**: re-seeded futures also re-draw latents the runtime cannot observe (`latent.ts`). +- **S1**: a label rule: a decision where a non-passive action clearly wins (passive's adjusted gap ≥ `S1_GAP` = 1.0) never keeps the diagnosis `expected` (`trajectory.ts` -> `diagnosisFromOutcome`). +- **Tier premium / tie rule**: label-time adjustments that favour passive (`LABEL` in `cost.ts`). **Gain** (T1): `gain(a) = mean_f c(passive) − mean_f c(a) − premium(tier(a))`, the training-side expected advantage of acting. ### Seam types (`packages/runtime/src/types.ts`) @@ -85,6 +97,7 @@ type Question = interface NoulAnswer { type: "noul"; noul: number } // calibrated P(true) interface ChoiceAnswer { type: "choice"; choice: L; confidence: number; probabilities: Record<L, number> } interface ScoreAnswer { type: "score"; score: number; confidence: number; probabilities: Record<string, number> } +type TriggerKind = "mutation" | "request" | "delivery" | "failure" | "stall" | "inconsistency" | "transition" | "error" | "ask"; interface EvaluateRequest { trigger: TriggerKind; state: JevState; questions: Record<string, Question>; priority?: number; subject?: SubjectRef; timeoutMs?: number } interface DecisionProvider { readonly status: ModelStatus; ready(): Promise<void>; @@ -97,7 +110,7 @@ Other `types.ts` shapes on the model path (`Vocabulary`, `StandingQuestion.quest ```ts interface Vocabulary { diagnoses?: Record<string, string>; // replaces the default label set (expected re-added, plugin labels appended) - actions?: Partial<Record<string, string>> } // per-action description override + actions?: Partial<Record<string, string>> } // per-action description override (all triggers) interface StandingQuestion { id: string; on: TriggerKind[]; question: Question; always?: boolean /* consult even when not salient */; onAnswer?(a, ctx): void } interface ActionDef { name; description; on: TriggerKind[]; tier?: "guard" | "heal" /* default heal */; @@ -105,11 +118,12 @@ interface ActionDef { name; description; on: TriggerKind[]; tier?: "guard" | "he type AnswerOf<Q> = /* noul → NoulAnswer; choice → ChoiceAnswer<keyof criteria>; score → ScoreAnswer */ ``` -- **salient** (`build.ts` -> `buildSituation`): `triage === "always" || trigger === "ask" || facts.some(f => !f.neutral)`. **forced**: some standing question for this trigger has `always: true`. Neither is model input. -- **`SubjectRef`** (`build.ts` -> `subjectRef`; never serialized, the model host ignores it): mutation `{mutation, store, paths, cause?}`; request/failure/stall `{op}`; transition `{op, paths, store?}`; inconsistency `{paths, store?, invariant?}` (first violation's text); error `{error: raw, op?}`; ask `{op?}` or `{store?}`. -- **`EvaluateRequest.priority`** is queue order only (`types.ts` comment: held writes/requests 2, background 0); see [decide-policy-actions.md](runtime/decide-policy-actions.md). +- **salient** (`build.ts` -> `buildSituation`): `triage === "always" || trigger === "ask" || facts.some(f => !f.neutral)`. **forced**: some standing question for this trigger has `always: true`. Neither is model input. Delivery salience (which conflicts are non-neutral, body comparison) is detailed in [learn-situation-triage.md](runtime/learn-situation-triage.md). +- **`SubjectRef`** (`build.ts` -> `subjectRef`; never serialized, the model host ignores it): mutation `{mutation, store, paths, cause?}`; request/failure/stall `{op}`; **delivery `{op, paths?, store?}`** (paths = conflicting fields, else the matched predicted ones; `store` = first path's store); transition `{op, paths, store?}`; inconsistency `{paths, store?, invariant?}`; error `{error: raw, op?}`; ask `{op?}` or `{store?}`. +- **`SituationDraft.delivery`** (`{channel: "response" | "websocket" | "eventsource", predicted, conflicts}`) is what plugin facts and `ActionDef.applicable` see; it is not model text by itself. +- **`EvaluateRequest.priority`** is queue order only; see [decide-policy-actions.md](runtime/decide-policy-actions.md). -### Model-side structures (`packages/runtime/src/model/`) +### Model-side structures (`packages/runtime/src/model/`, unchanged since `situation-v1`) | type | fields | |---|---| @@ -118,11 +132,11 @@ type AnswerOf<Q> = /* noul → NoulAnswer; choice → ChoiceAnswer<keyof criteri | `Packed` | `inputIds`, `positionIds`, `qGroup`, `iGroup`, `nState`, `qIndex: Map<qid, PackedQuestion>` | | `PackedQuestion` | `kind`, `header`, `labels`, `qPos` (index of `[Q]`), `itemPos` (index of each `[O]`/`[L]`, or `[T]`,`[F]`) | | `FeedPlan` | `choice {q, items, k}`, `score {q, items, k}`, `noul {q, t, f}` | -| `ModelMeta` (keys read) | `max_len`, `max_total`, `markers`, `cls_id`, `sep_id`, `inputs`, `outputs`; `name` only as the `Engine` fallback when no `name` option is passed (the backend always passes one); `pad_id` declared but unused | +| `ModelMeta` (keys read) | `max_len`, `max_total`, `markers`, `cls_id`, `sep_id`, `inputs`, `outputs`; `name` only as the `Engine` fallback when no `name` option is passed; `pad_id` declared but unused | | `Calibration` | `noul`, `choice`, `score` (τ > 0, default 1.0), `by_header`, optional `by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp`, `version` | | `ModelCard` | `format`, `name`, `version`, `license?`, `variants{name: {file, bytes?, sha256?, provider?, needs?}}`, `files{tokenizer, calibration, meta}` | -### Diagnosis vocabulary (`questions.ts` -> `DEFAULT_DIAGNOSES`, order is the option order) +### Diagnosis vocabulary (`questions.ts` -> `DEFAULT_DIAGNOSES`, order is the option order; unchanged in v2) | label | description (what the model reads at full budget) | |---|---| @@ -139,12 +153,13 @@ type AnswerOf<Q> = /* noul → NoulAnswer; choice → ChoiceAnswer<keyof criteri `diagnosisVocabulary(vocab, pluginLabels)`: `vocab.diagnoses` replaces the defaults. `expected` is always kept and moved first. Plugin labels are appended if their names are new. The header is always `DIAGNOSIS_INSTRUCTIONS` = `"What is happening here?"`. -### Actions per trigger (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `BUILTIN_ACTIONS`; applicability in `build.ts` -> `builtinApplicable`) +### Actions per trigger (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `BUILTIN_ACTIONS`; applicability in `build.ts` -> `builtinApplicable`) | trigger | action header (exact) | actions, passive first | offered only when | |---|---|---|---| | `mutation` | What should the runtime do with this write? | `apply`, `discard`, `defer` | `defer`: the mutation was deferred < 2 times | | `request` | What should the runtime do with this request? | `send`, `coalesce`, `delay`, `block`, `serve_cached` | `coalesce`: fetch and `env.canCoalesce`; `serve_cached`: GET and a cached response | +| `delivery` | What should the runtime do with this response or message? | `deliver`, `discard`, `defer` | `discard`: always; `defer`: deferred < 2 times **and** `relatedInFlight` is non-empty (an in-flight op outside the subject's chain with the same signature, or whose chain wrote one of the matched fields' stores) | | `failure` | What should the runtime do with this failed request? | `deliver`, `retry`, `serve_cached` | `retry`: replayable, attempt < 4, fetch; `serve_cached`: GET, cached, fetch | | `stall` | What should the runtime do with this slow request? | `wait`, `hedge`, `serve_cached` | `hedge`: idempotent GET, replayable, fetch; `serve_cached`: GET, cached, fetch | | `inconsistency` | What should the runtime do about this inconsistent state? | `ignore`, `rollback`, `resync` | `rollback`: a consistent snapshot and a writable store; `resync`: a store with a resync handler | @@ -152,27 +167,27 @@ type AnswerOf<Q> = /* noul → NoulAnswer; choice → ChoiceAnswer<keyof criteri | `error` | What should the runtime do about this error? | `ignore`, `rollback` | `rollback`: the ambient op's chain wrote revertable state | | `ask` | (none) | (none) | — | -Built-in descriptions and tiers (`BUILTIN_ACTIONS`; the sim's `TIER`, curriculum `fmt.TIER` and `eval_runtime.TIER` are copies): +Built-in descriptions and tiers (`BUILTIN_ACTIONS`; the sim's `TIER`, curriculum `fmt.TIER`, `eval_runtime.TIER`, `sim/scripts/relabel.py` `TIER`, `t1_relabel`/`eval_gain` `PREM` are copies): -| action | tier | description | -|---|---|---| -| `apply` | passive | let this write update the state now | -| `discard` | guard | drop this write and keep the current state | -| `defer` | guard | hold this write until the related in-flight operations finish, then decide again | -| `send` | passive | send the request now | -| `coalesce` | guard | do not send; reuse the result of the identical request that is in flight or just finished | -| `delay` | guard | wait before sending, backing off so the service can recover | -| `block` | heal | do not send; fail this request immediately | -| `serve_cached` | heal | answer with the last successful response for this request instead | -| `deliver` | passive | pass the failure to the application as it is | -| `retry` | heal | retry the request after a short backoff | -| `wait` | passive | keep waiting for the request | -| `hedge` | heal | send a second identical request and use whichever answers first | -| `ignore` | passive | leave the state as it is | -| `rollback` | heal | restore the affected state to its last consistent snapshot | -| `resync` | heal | reload the affected state from its source | - -Custom (plugin) actions are appended after the built-ins when `def.on` includes the trigger, the name is new, and `def.applicable(draft)` is truthy (no `applicable` = applicable; a throw counts as false). Their tier defaults to `heal`, and their description comes from `actionDescription` (vocabulary override, then `def.description`, then the built-in text, then the name). +| action | tier | description | delivery description (`TRIGGER_DESCRIPTIONS.delivery`) | +|---|---|---|---| +| `apply` | passive | let this write update the state now | — | +| `discard` | guard | drop this write and keep the current state | deliver it but drop the state changes it would make over newer data | +| `defer` | guard | hold this write until the related in-flight operations finish, then decide again | hold it until the related in-flight operations finish, then decide again | +| `send` | passive | send the request now | — | +| `coalesce` | guard | do not send; reuse the result of the identical request that is in flight or just finished | — | +| `delay` | guard | wait before sending, backing off so the service can recover | — | +| `block` | heal | do not send; fail this request immediately | — | +| `serve_cached` | heal | answer with the last successful response for this request instead | — | +| `deliver` | passive | pass the failure to the application as it is | pass it to the application now | +| `retry` | heal | retry the request after a short backoff | — | +| `wait` | passive | keep waiting for the request | — | +| `hedge` | heal | send a second identical request and use whichever answers first | — | +| `ignore` | passive | leave the state as it is | — | +| `rollback` | heal | restore the affected state to its last consistent snapshot | — | +| `resync` | heal | reload the affected state from its source | — | + +`actionDescription(name, vocab, custom?, trigger?)` precedence: `vocab.actions[name]` → `custom` (a plugin's `def.description`) → `TRIGGER_DESCRIPTIONS[trigger][name]` → `BUILTIN_ACTIONS[name].description` → the name. Built-in actions are described with their trigger (`build.ts` passes `s.trigger`); custom actions are not. Custom (plugin) actions are appended after the built-ins when `def.on` includes the trigger, the name is new, and `def.applicable(draft)` is truthy (no `applicable` = applicable; a throw counts as false). Their tier defaults to `heal`. ### Training row (`sim/src/types.ts` -> `Row`, `Label`; same schema as docs/CONTRACT.md §D) @@ -183,7 +198,17 @@ type Label = { type: "choice"; label: string } | { type: "choice"; dist: Record< | { type: "noul"; p: number } | { type: "score"; level: number } | { type: "score"; dist: number[] }; ``` -A qid without a label is packed but unsupervised. +A qid without a label is packed but unsupervised (unlabeled rows rely on this for `action`). + +| row kind | id | labels | distinguishing `meta` | +|---|---|---|---| +| gold decision | `sim-<seed>-d<k>` | `action` dist (always) + `diagnosis` label (when in the criteria and correlated) | `best`, `passive_best`, `costs`, `cost_futures`, `futures`, `adjusted`, `se`, `non_passive_mass`, `cost_parts`, `tiers`, `diagnosis_s1?`, `diagnosis_subject?`, `probe?` | +| diagnosis-only | `sim-<seed>-s<k>` (also in on-policy runs) | `diagnosis` | `diagnosis_only: true` | +| ask | `sim-<seed>-a<i>` (gold) / `u-<seed>-a<i>` (unlabeled) | exact noul/score/choice | `trigger: "ask"`, `kinds` | +| unlabeled decision | `u-<seed>-d<k>` | `diagnosis` only (when in the criteria and correlated), never `action` | `unlabeled: true`, `actions`, `ran`, `explored` | +| on-policy decision | `p-<seed>-d<k>` | as gold | `on_policy: true`, `model_probs`, `model_choice`, `model_diagnosis`, `ran`, `false_intervention`, `miss` | + +Every row of a trajectory shares `metaOf(scn, o)`: `seed, domain, family, program_family, chaos, clean, persona, budget, runtime, features, patterns`. Decision and diagnosis-only rows add `trigger, passive, subject_feature, decision, t, subject`. Teacher-labelled and T1 rows add `meta.teacher` / `meta.egain` (training side, section 10). ## How it works @@ -194,6 +219,8 @@ A qid without a label is packed but unsupervised. |---|---|---| | mutation | `A write to <p1, p2, p3[ and N more] \| store>[ from <opLabel(cause)>] is about to be applied.` | `write to <paths>[ from <opLabel>]` | | request | `<opLabel> is about to be sent.` | `<opLabel>` | + | delivery (response) | `The response to <opLabel> arrived and is about to be delivered; <predicted>.` | `response to <opLabel>` | + | delivery (message) | `A <WebSocket \| server-sent> message <channel path> (#id) arrived and is about to be delivered; <predicted>.` | `<WebSocket \| server-sent> message <path> (#id) <summary>` | | failure | `<opLabel> failed (<HTTP 503 \| timed out \| network error>) and the app has not seen the failure yet.` | `<opLabel> (<failure>)` | | stall | `<opLabel> has been waiting <secs> for a response.` | `<opLabel>, waiting <secs>` | | inconsistency | `The relation <text \| ?>[ (and N more)] no longer holds now that the app is settled.` | `relation <text>[ (and N more)]` | @@ -201,53 +228,47 @@ A qid without a label is packed but unsupervised. | error | `An uncaught <Name> was thrown: <message, truncated to 120>` | `<Name>: <message ≤ 80>` | | ask | `The developer asks about <opLabel>.` / `The developer asks about the store <name>.` / `The developer asks about the app right now.` | `question about <opLabel \| name \| the app>` | - `opPhrase` by op kind (`describe.ts`): user → `userPhrase` (`user clicked <target>`, `user typed <value>[ into <target>]`, `user changed …`, `user submitted …`, `user pressed <key>…`, `user navigated to …`); fetch/xhr → `<op.name><op.detail>` where `name` is the op signature and `detail` the query string plus, for non-GET/HEAD, a redacted body summary (`observe/fetch.ts`; e.g. `GET /api/search?q=rea`, `POST /api/orders {items: [1], cardNumber: [redacted]}`); timer/ws → name; task → `task <name>[ <detail>]`; genclass → `GenClass <name>`. Time and number formats come from `util.ts`: `secs(ms)` = 2 dp below 10 s (`0.42s`), 1 dp below 1,000 s (`12.3s`), else integer; `rel(ms)` = signed timeline stamp (`-1.24s`, `+…` for future); `fmtNum` = integers as is, else 1/2/4 dp by magnitude (≥ 100 / ≥ 1 / < 1); `truncate(s, n)` = first `n−1` UTF-16 code units + `…`. -2. Facts: `computeFacts` (or precomputed facts from triage), plus plugin facts (each truncated to 240, `kind: "plugin"`, neutral). Then `orderFacts` (non-neutral first, then kind rank, stable) and `.slice(0, MAX_FACTS = 12)`. + `<predicted>` = `facts.ts` -> `predictedText`: response `its operation usually writes <fields>` (transition profile) / `its operation last wrote <fields>` (last completion) / `no earlier completion shows which state it writes`; message `messages like it usually write …` / `messages like it last wrote …` / `no earlier message shows which state it writes`. `<fields>` lists up to 4 normalised paths (`a, b, c and d (+N more)`). + + `opPhrase` by op kind (`describe.ts`, unchanged in v2): user → `userPhrase` (`user clicked <target>`, `user typed <value>[ into <target>]`, …); fetch/xhr → `<op.name><op.detail>` where `name` is the op signature and `detail` the query string plus, for non-GET/HEAD, a redacted body summary (e.g. `GET /api/search?q=rea`, `POST /api/orders {items: [1], cardNumber: [redacted]}`); timer/ws → name; task → `task <name>[ <detail>]`; genclass → `GenClass <name>`. Redaction is by the **leaf field** since v2 (`util.ts` -> `isSensitivePath`: `auth.loading` visible, `auth.token` redacted). Time and number formats come from `util.ts`: `secs(ms)` = 2 dp below 10 s (`0.42s`), 1 dp below 1,000 s, else integer; `rel(ms)` = signed timeline stamp; `fmtNum` = integers as is, else 1/2/4 dp by magnitude; `truncate(s, n)` = first `n−1` UTF-16 code units + `…`. Long string changes use a diff-centred preview (`state/fields.ts` -> `stringDiff`), e.g. `"…e sword shield market lib" → "…e sword shield" (removes " market lib")`. +2. Facts: `computeFacts` (or precomputed facts from triage), plus plugin facts (each truncated to 240, `kind: "plugin"`, neutral). Then `orderFacts` (non-neutral first, then kind rank, stable) and `.slice(0, MAX_FACTS = 12)`. v2 adds delivery facts (provenance of the response/message, profile counts, version conflicts), content facts F1–F3, evidence facts F5–F7/F9 and read-your-writes; catalogue and wording in [learn-situation-triage.md](runtime/learn-situation-triage.md) and `packages/runtime/STATUS.md` "Batch 5". 3. Section lines (details in [learn-situation-triage.md](runtime/learn-situation-triage.md)): - `app`: `` `${title} — ${route}` ``, or whichever exists, else `unknown`. - - `in_flight`: non-user in-flight ops except the subject, same signature first, then same root, then by start: `<opPhrase≤80> (#id) <secs> so far[, by #cause]`. - - `timeline`: from the last 96 events, the relevant ones (≤ section limit), topped up with the most recent irrelevant ones and sorted by `seq`. Lines come from `describe.ts` -> `eventLine`, for example `-0.90s start GET /api/search?q=rea (#6, by #5)`, `-0.00s end … (#6): 200 in 0.90s`, `-0.69s write search.results: 0 items → 2 items […] (by #8)`, `-1.05s user typed "reac" into input "Search" (4 keystrokes, #1–#7)`, `… error <msg≤100> (during #2)`, `… navigate <route≤60>`, `… GenClass <text≤100>`. `decision` events are never shown. - - `state`: involved fields first, then other fields of the involved stores by most recent write: `path = value (vN, by #writer <secs> ago)` or `(v0)`. A store with a `describe` option renders `store = <describe≤110> (vN)`. - - `stats`: `<sig>: N done[, median Xs, p95 Ys], F of last N failed, R in last 10s[ (usual U)]`. + - `in_flight`: non-user in-flight ops except the subject (`subjectOp`; for a delivery, the delivering op), same signature first, then same root, then by start: `<opPhrase≤80> (#id) <secs> so far[, by #cause]`. + - `timeline`: from the last 96 events, the relevant ones (≤ section limit), topped up with the most recent irrelevant ones and sorted by `seq`; lines from `describe.ts` -> `eventLine`. `decision` events are never shown. + - `state`: involved fields first (delivery: conflicting paths, then matched predicted paths), then other fields of the involved stores (delivery: stores of P) by most recent write: `path = value (vN, by #writer <secs> ago)` or `(v0)`. + - `stats`: `<sig>: N done[, median Xs, p95 Ys], F of last M failed, R in last 10s[ (usual U)]` (M is the failure window, not N), for the subject's signature (fetch/xhr/ws/task) and then each in-flight fetch/xhr signature. 4. `toJevState(parts, budget)`: - 1. `b = max(MIN_BUDGET 500, round(budget))`; `L = sectionLimits(b)`, with `r = clamp((b − 1100) / 2100, 0, 1)` and every limit `Math.round(a + (b − a)·r)` (half-up). - 2. Cap each section: facts/in_flight/state/stats keep the first N, timeline keeps the **last** N. Each line is truncated to its line limit with `…` (`util.truncate`: first `n−1` chars + `…`). + 1. `b = max(MIN_BUDGET 500, round(budget))`; `L = sectionLimits(b)`, with `r = clamp((b − 1100) / (2400 − 1100), 0, 1)` and every limit `Math.round(a + (b − a)·r)` (half-up). Limits saturate at 2,400: `sectionLimits(3200)` equals `sectionLimits(2400)` (tested). + 2. Cap each section: facts/in_flight/state/stats keep the first N, timeline keeps the **last** N. Each line is truncated to its line limit with `…`. 3. Build the object in key order `app, trigger, facts, in_flight, timeline, state, stats`. An empty array becomes the string `"none"`. 4. Size = `stateChars` = Σ over keys of `len(key) + 2 + len(value joined by "\n") + 1`. While size > `b`, shrink in this order: timeline (drop oldest, floor 0), state (drop last, floor 0), facts (drop last, **floor 1**), in_flight (drop last), stats (drop last). - 5. If still over (`over = size − b`): shorten every fact to `max(60, len − over)`. If still over, shorten the trigger to `max(60, len − remaining excess)` (the excess is recomputed after the fact shortening). + 5. If still over (`over = size − b`): shorten every fact to `max(60, len − over)`. If still over, shorten the trigger to `max(60, len − remaining excess)`. 5. The situation is deterministic: the same inputs and clock give byte-identical output (`test/situation.test.ts`, `test/budget.test.ts`). -6. The budget comes from `RuntimeImpl.situationBudget` (`src/runtime.ts`). A numeric `situation.budget` is used as is. With `"auto"`: webgpu or an unknown device gives 3,200; wasm gives `1000 + round((threads − 1)·1000/3)` with threads clamped to 1..4 (1,000 / 1,333 / 1,667 / 2,000). The result is multiplied by `budgetScale`, which starts at 1 and becomes `max(0.5, ×0.8)` after each `max_tokens_exceeded` (auto only). +6. The budget comes from `RuntimeImpl.situationBudget` (`src/runtime.ts`). A numeric `situation.budget` is used as is. With `"auto"`: webgpu or an unknown device gives **2,400**; wasm gives `1000 + round((threads − 1)·1000/3)` with threads clamped to 1..4 (1,000 / 1,333 / 1,667 / 2,000). The result is multiplied by `budgetScale`, which starts at 1 and becomes `max(0.5, ×0.8)` after each `max_tokens_exceeded` (auto only; 2,400 → 1,920 after one, tested). ### 2. Standing questions (`questions.ts` -> `buildQuestions`) 1. `compact = budget <= COMPACT_QUESTIONS_BUDGET` (1,400). This is a different constant from `COMPACT_BUDGET` 1,100. 2. `ask` trigger: only standing questions (from `rt.question` or a plugin) for `ask`. `runtime.ask(q)` sends its own `{answer: q}` (`runtime.ts` -> `ask`). 3. Otherwise `diagnosis = {type: "choice", instructions: "What is happening here?", criteria}`, where `criteria[label]` is the description. In compact mode it is `null`, unless a `vocabulary.diagnoses` override of ≤ 24 chars (`COMPACT_DESC_MAX`) exists for that label. -4. `action` is added only if more than one action applies, with `criteria[name]` = the description (compact: `null` unless a `vocabulary.actions` override ≤ 24 chars). The header is `ACTION_INSTRUCTIONS[trigger]` and is fixed per trigger (no subject interpolation). -5. Standing questions (from `rt.question` or a plugin) follow, by their `id`, only if the id is not already in the object (`if (!(k in qs))`). So an id `diagnosis` is always skipped, but an id `action` is **inserted** when the built-in `action` question is absent (≤ 1 applicable action). Insertion order is `diagnosis, action, <standing qids>`. For `ask` the result is `{...extra}` (standing questions for `ask` only, nothing skipped). +4. `action` is added only if more than one action applies, with `criteria[name]` = the `ActionOption.description` built by `actionDescription` (trigger-specific for delivery). Compact: `null` unless a `vocabulary.actions` override ≤ 24 chars. The header is `ACTION_INSTRUCTIONS[trigger]`, fixed per trigger (no subject interpolation). +5. Standing questions follow, by their `id`, only if the id is not already in the object (`if (!(k in qs))`). So an id `diagnosis` is always skipped, but an id `action` is **inserted** when the built-in `action` question is absent. Insertion order is `diagnosis, action, <standing qids>`. ### 3. Wire → segments and blocks (`model/serialize.ts`, port of `jev_local/serialize.py`) -1. The host calls `toJsonValue(req.state)` (`host.ts` -> `evaluateDetailed`; questions are passed as given and converted per value inside `questionBlock`). This is the value Python sees after `json.loads(JSON.stringify(v))`: `undefined` keys vanish, NaN/±Infinity become `null`, Dates become strings, Maps are kept as ordered maps (entries whose value is `undefined`, a function or a symbol are dropped). BigInt and cyclic values throw `ModelInputError`. `pyJson` is `json.dumps(v, ensure_ascii=False, separators=(", ", ": "))`: non-ASCII characters stay raw, numbers go through `pyNumber`. +1. The host calls `toJsonValue(req.state)` (`host.ts` -> `evaluateDetailed`). This is the value Python sees after `json.loads(JSON.stringify(v))`: `undefined` keys vanish, NaN/±Infinity become `null`, Dates become strings; a Map is kept as an ordered map when it is the value itself or nested in another Map (a Map inside a plain object or array goes through `JSON.stringify` and becomes `{}`). BigInt and cyclic values throw `ModelInputError`. `pyJson` is `json.dumps(v, ensure_ascii=False, separators=(", ", ": "))`. 2. `stateSegments(state)`: - object: one segment per top-level key, `text = valueText(v)`: an array of strings is joined with `"\n"` (not stripped); anything else goes through `entryText`. - array: up to 64 (`MAX_ARRAY_SEGMENTS`) `[i]` segments plus one `[64:]` remainder. - string: one segment with key `""` (stripped). - `null` → `None`; booleans → `True`/`False`; numbers → Python repr. -3. `entryText`: - - `null` → `""`. - - string → `pyStrip` (Python whitespace set). - - all-string array → items joined with `"; "`, skipping empties. - - other array → `json.dumps(…, separators=(", ", ": "))`. - - object → `k: v | k: v` (nested objects and non-string arrays as JSON). - - number → `pyNumber`: JSON integers print as ints; others print as Python `repr(float)`, with an exponent form outside `[1e-4, 1e16)`. -4. `segmentText` = `` `${key}: ${text}` `` (or `text` when the key is empty). The model therefore reads `facts: <fact1>\n<fact2>`. The indented `facts:\n <fact1>` rendering in STATUS.md and `explain()` comes from `situation/serialize.ts` -> `stateText` and is display only. (`model/serialize.ts` -> `stateText` is a different helper: `key:\ntext` blocks joined by blank lines, also display only.) +3. `entryText`: `null` → `""`; string → `pyStrip`; all-string array → items joined with `"; "`, skipping empties; other array → `json.dumps(…)`; object → `k: v | k: v`; number → `pyNumber` (JSON integers print as ints; others as Python `repr(float)`). +4. `segmentText` = `` `${key}: ${text}` `` (or `text` when the key is empty). The model therefore reads `facts: <fact1>\n<fact2>`. The indented `facts:\n <fact1>` rendering in STATUS.md and `explain()` comes from `situation/serialize.ts` -> `stateText` and is display only. 5. `questionBlock(qid, q)`: - header = `entryText(instructions)` or the default (`Is the statement true of the state?` / `Which option best fits the state?` / `Which level best describes the state?`). - choice: items `label` when the description is `null`, `""`, or equal to the label after strip; otherwise `label: <entryText(desc)>`. Labels are in criteria order (a Map keeps integer-like labels in order; a plain object moves them first). Empty criteria → `ModelInputError`. - - score: items = level texts, labels `"0".."n-1"`. Empty criteria → `ModelInputError`. - - noul: items `[true || "yes", false || "no"]`, labels `["true","false"]`. - - Any other type → `ModelInputError`. + - score: items = level texts, labels `"0".."n-1"`. noul: items `[true || "yes", false || "no"]`, labels `["true","false"]`. Any other type → `ModelInputError`. 6. `questionEntries(questions)`: request order (`Object.entries`, or Map order). ### 4. Packing (`packer.ts` -> `Packer.pack`) @@ -256,430 +277,383 @@ A qid without a label is packed but unsupervised. [CLS] seg_0 [SEP] seg_1 [SEP] … seg_n [SEP] | [Q] header_0 | [O] item_00 | [O] item_01 … | [Q] header_1 | [L] lvl_10 … | [Q] header_2 | [T] true | [F] false ``` -1. Each text is tokenized on its own with no special tokens (`Packer.encode` -> `Tokenizer.encode`, cached by text, 8,192 entries). Special added tokens (`[CLS]`, `[Q]`, …) are **never** matched inside text, so user text cannot forge a marker. In code order (`Tokenizer.encode`): the file's normalizer runs on the whole text first (NFC for the shipped file; `NFC/NFD/NFKC/NFKD/Lowercase/Sequence` supported), then non-special added tokens (whitespace runs, `|||…|||`, `[unusedN]`) are split out leftmost-longest and keep their own ids, then each remaining piece goes ByteLevel regex → BPE merges (heap, `Word::merge_all` order). +1. Each text is tokenized on its own with no special tokens (`Packer.encode` -> `Tokenizer.encode`, cached by text, 8,192 entries). Special added tokens are **never** matched inside text, so user text cannot forge a marker. In code order: the normalizer runs on the whole text first (NFC for the shipped file), then non-special added tokens are split out leftmost-longest, then each remaining piece goes ByteLevel regex → BPE merges. 2. State ids: `[CLS]`, then each segment's ids followed by `[SEP]`. `nState = S` is the count. 3. Per question `qn`: header = `[Q]` + header ids. Each item = its marker + item ids. Markers: `[O]` choice, `[L]` score, `[T]`/`[F]` noul. 4. `position_ids`: state `0..S−1`. Header tokens `S..S+h−1`. Every item **restarts** at `S+h`. -5. `q_group`: −1 for state, `qn` for header and items. `i_group`: −1 for state and header tokens, the item ordinal for item tokens. The graph builds the block mask from these: a token sees the state plus its own header and its own item. ModernBERT local (`sliding_attention`) layers also require `|pos_q − pos_k| ≤ window`; the window is a graph constant (`ExportModel.window`), recorded as `meta.json` `window` but not read by the host. -6. Limits: `positions = S + max over questions(len(header) + longest item)` must be ≤ `maxPositions` (`meta.max_len`, default 1536), and `total = S + Σ(header + all items)` ≤ `maxTotal` (`meta.max_total`, default 8192). Otherwise `MaxTokensExceededError` (`code: "max_tokens_exceeded"`) is thrown. There is no truncation inside the model host: the situation budget is the only size control. -7. Marker, `[CLS]` and `[SEP]` ids come from `meta.json` when given and must equal the tokenizer's ids, otherwise `ModelUnsupportedError`. Nothing is hardcoded. The pruned runtime tokenizer has markers at ids 16359–16363 (MODEL_CARD). -8. `Packer.measure(state, questions?)` returns `{stateTokens, positions, total}` with the same arithmetic as `pack` but never throws `MaxTokensExceededError` (host `measure`, worker message `measure`; the runtime itself does not call it, see [model-host.md](runtime/model-host.md)). -9. Tokenizer constraints (`tokenizer.ts` -> `Tokenizer` constructor, all `ModelUnsupportedError`): model type must be `BPE`; no dropout; no `continuing_subword_prefix`/`end_of_word_suffix`; pre-tokenizer must be `ByteLevel` (or a one-element `Sequence` of it); normalizer one of `NFC/NFD/NFKC/NFKD/Lowercase/Sequence` or none; non-special added tokens may not use `lstrip`/`rstrip`/`single_word`; every byte that can occur in UTF-8 needs its byte-level token; every merge must refer to vocab tokens; every id < `ID_SPACE` (2^26, module-private). The pre-tokenizer regex spells `\s` as `\p{White_Space}` to match Rust/Oniguruma. +5. `q_group`: −1 for state, `qn` for header and items. `i_group`: −1 for state and header tokens, the item ordinal for item tokens. A token sees the state plus its own header and its own item. ModernBERT local layers also require `|pos_q − pos_k| ≤ window` (`ExportModel.window`, recorded in `meta.json` but not read by the host). +6. Limits: `positions = S + max over questions(len(header) + longest item)` ≤ `maxPositions` (`meta.max_len`, default 1536), and `total = S + Σ(header + all items)` ≤ `maxTotal` (`meta.max_total`, default 8192). Otherwise `MaxTokensExceededError` (`code: "max_tokens_exceeded"`). There is no truncation inside the model host: the situation budget is the only size control. +7. Marker, `[CLS]` and `[SEP]` ids come from `meta.json` when given and must equal the tokenizer's ids, otherwise `ModelUnsupportedError`. The pruned runtime tokenizer has markers at ids 16359–16363 (MODEL_CARD). +8. `Packer.measure(state, questions?)` returns `{stateTokens, positions, total}` with the same arithmetic but never throws `MaxTokensExceededError` (see [model-host.md](runtime/model-host.md)). +9. Tokenizer constraints (`tokenizer.ts` -> `Tokenizer` constructor, all `ModelUnsupportedError`): BPE only; no dropout; no `continuing_subword_prefix`/`end_of_word_suffix`; `ByteLevel` pre-tokenizer; normalizer `NFC/NFD/NFKC/NFKD/Lowercase/Sequence` or none; non-special added tokens without `lstrip`/`rstrip`/`single_word`; every UTF-8 byte token present; merges over vocab tokens; ids < `ID_SPACE` (2^26). ### 5. Feeds, graph and heads (`engine.ts`, `packer.ts` -> `planInputs`/`unpackLogits`; graph `scripts/genclass_export.py` -> `ExportModel`) -1. `planInputs` groups questions by kind in request order: - - `choice_q [G]`, `choice_items [G, K]` (padded with 0); - - `score_q [S]`, `score_items [S, K2]`; - - `noul_q/noul_t/noul_f [M]`. - A kind with no question gets one dummy row pointing at token 0. -2. `Engine` feeds exactly `meta.inputs`. The set must equal the session's input names, and every name must be in `FEEDS`: `input_ids, position_ids, q_group, i_group, attention_mask, token_type_ids, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f`. All feeds are int64, and token rows are `[1, L]`. Shipped exports declare the 11 inputs without `attention_mask`/`token_type_ids`. -3. Outputs map by name: `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` (fp16 outputs are converted to numbers). -4. Heads (`jev_local/engine/encoder/heads.py`): - - choice: `z_i = MLP([h_Q; h_Oi; h_Q*h_Oi])`; - - score: `z_k = MLP([h_Q; h_Lk; h_Q*h_Lk])`; - - noul: `z = MLP([h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F])`, an absolute sigmoid rather than a 2-way softmax. - MLP = Linear → GELU → Linear(d → 1). Every `h_*` is first passed through the heads' shared LayerNorm (`DecisionHeads.norm`; `pairwise`/`n` in `ExportModel.forward`). +1. `planInputs` groups questions by kind in request order: `choice_q [G]`, `choice_items [G, K]` (padded with 0); `score_q [S]`, `score_items [S, K2]`; `noul_q/noul_t/noul_f [M]`. A kind with no question gets one dummy row pointing at token 0. +2. `Engine` feeds exactly `meta.inputs`; the set must equal the session's input names, and every name must be in `FEEDS` (`input_ids, position_ids, q_group, i_group, attention_mask, token_type_ids, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f`). All feeds are int64, token rows `[1, L]`. Shipped exports declare the 11 inputs without `attention_mask`/`token_type_ids`. +3. Outputs map by name: `choice_logits [G, K]`, `score_logits [S, K2]`, `noul_logits [M]` (fp16 outputs are converted). +4. Heads (`jev_local/engine/encoder/heads.py`): choice `z_i = MLP([h_Q; h_Oi; h_Q*h_Oi])`; score `z_k = MLP([h_Q; h_Lk; h_Q*h_Lk])`; noul `z = MLP([h_Q; h_T; h_F; h_Q*h_T; h_Q*h_F])` (absolute sigmoid). MLP = Linear → GELU → Linear(d → 1), inputs through the shared LayerNorm. The repo's `HeadOut` has no gain head (see Drift: `collect_gain.py`). 5. `unpackLogits` returns raw logits per qid in request order, taking the first `labels.length` columns. `Engine.logits` serializes forward passes (one at a time per session). -6. `Engine` constructor checks (all `ModelUnsupportedError`): the session's input names must equal `meta.inputs` as a set (if `meta.inputs` is absent, the session's names are used); every input must be a `FEEDS` key; every `meta.outputs` name must be a graph output; outputs are filtered to `choice_logits`/`score_logits`/`noul_logits` and at least one must remain. A question whose kind has no head fails at `logits` time. Output tensors of type float16 (`Uint16Array`) are decoded by `tensorFloats`; float32/float64 pass through; any other type throws. The reported model id comes from the backend: `name: "<card.name>@<card.version>"` (`backend.ts` -> `createEngine`); `meta.name` is only a fallback when no name is passed. +6. `Engine` constructor checks (all `ModelUnsupportedError`): input names = `meta.inputs` as a set; every input a `FEEDS` key; every `meta.outputs` name a graph output; at least one of the three logit outputs. A question whose kind has no head fails at `logits` time. The reported model id is `"<card.name>@<card.version>"` (`backend.ts` -> `createEngine`). ### 6. Logits → calibrated probabilities → answers (`calibrate.ts`) -0. `parseCalibration(json)` (backend load) fills missing `noul`/`choice`/`score` with 1.0 and `by_header` with `{}`, then throws `ModelUnsupportedError` if the file is not an object, any of the three is not a number > 0, or `by_header` is not an object. Other keys (`by_bucket`, `tau_k`, `noul_platt`, `bucket_clamp`, `version`, and an unknown `_fit`) are passed through unchecked. -1. `hk = headerKey(header)` = `sha1(header)[:12]` (UTF-8). Example keys: `041ccfa6318c` = "What is happening here?", `bb11f7f0f3a7` = "What should the runtime do with this write?", `61d7c396157f` (request), `3616530c70a5` (failure), `94978d9e82be` (stall), `1b36f88322a0` (inconsistency), `6a2432a6e7de` (transition), `3f494eb3a731` (error). -2. choice/score: `tauFor(calib, kind, hk, K)` takes the first that applies: - 1. `by_header[hk]`; - 2. `by_bucket["<kind>:<bucket(K)>"]`, with buckets `2 | 3-5 | 6-10 | 11-30 | 31-100 | 101-255` (K > 255 → `101-255`); - 3. `tau_k[kind] = [a, b]` → `clamp(a + b·ln max(K, 2), bucket_clamp)` (default `[0.5, 5.0]`); - 4. `calib[kind]`. - Then `softmax(z / τ)` (max-subtracted, float64). +0. `parseCalibration(json)` fills missing `noul`/`choice`/`score` with 1.0 and `by_header` with `{}`, then throws `ModelUnsupportedError` if the file is not an object, any of the three is not a number > 0, or `by_header` is not an object. Other keys pass through unchecked. +1. `hk = headerKey(header)` = `sha1(header)[:12]` (UTF-8). Keys: `041ccfa6318c` = "What is happening here?", `bb11f7f0f3a7` (mutation), `2a615ca90e33` (delivery, new in v2), `61d7c396157f` (request), `3616530c70a5` (failure), `94978d9e82be` (stall), `1b36f88322a0` (inconsistency), `6a2432a6e7de` (transition), `3f494eb3a731` (error). +2. choice/score: `tauFor(calib, kind, hk, K)` takes the first that applies: `by_header[hk]`; `by_bucket["<kind>:<bucket(K)>"]` (buckets `2 | 3-5 | 6-10 | 11-30 | 31-100 | 101-255`); `tau_k[kind] = [a, b]` → `clamp(a + b·ln max(K, 2), bucket_clamp)` (default `[0.5, 5.0]`); `calib[kind]`. Then `softmax(z / τ)`. 3. noul: `noulAffine` gives `[1/by_header[hk], 0]`, else `noul_platt (a, b)`, else `[1/calib.noul, 0]`. Then `p = sigmoid(a·z + b)`. 4. `buildAnswer(q, probs, precision = "exact", labels)`: - - choice: `normalizeProbs` (non-finite or ≤ 0 → 0, renormalize; all zero → uniform). `choice` = argmax (first label wins ties). `confidence = clip01((K·pmax − 1)/(K − 1))`. `probabilities` is a plain object in criteria order. - - score: `score = Σ i·p_i`. `confidence = max(0, 1 − Σ p_i·|i − mode| / MAD_uniform(K))`, with mode = first argmax and `MAD_uniform(K) = mean_i |i − (K−1)/2|`. `probabilities` is keyed `"0".."K−1"` (not the level texts). K ≤ 1 gives confidence 1 for both choice and score. + - choice: `normalizeProbs`; `choice` = argmax (first label wins ties); `confidence = clip01((K·pmax − 1)/(K − 1))`; `probabilities` in criteria order. + - score: `score = Σ i·p_i`; `confidence = max(0, 1 − Σ p_i·|i − mode| / MAD_uniform(K))`; `probabilities` keyed `"0".."K−1"`. - noul: `noul = clip01(p)` (0.5 if p is not finite). - - `precision: "round"` rounds every number to 2 dp, half-even (`pyRound`), like the Jev server. -5. `EngineResult`: `{model: "<card.name>@<card.version>", answers, usage: {input_tokens, positions: max(position_id)+1}, timings}`. + - `precision: "round"` rounds every number to 2 dp, half-even (`pyRound`). +5. `EngineResult`: `{model: "<card.name>@<card.version>", answers, usage: {input_tokens, positions}, timings}`. ### 7. How the runtime consumes answers (detail in [decide-policy-actions.md](runtime/decide-policy-actions.md)) `runtime.ts` -> `onDecision`: -- It reads `answers.action.probabilities`, or `{<passive>: 1}` when there is no `action` question. The top action is `answers.action.choice`, or the passive action if that choice is not offered. -- It reads `answers.diagnosis.choice`, or `expected`. -- `decide/policy.ts` -> `gate`: A = the permitted non-passive actions; the candidate is the argmax over A. The candidate runs iff `Σ_{a∈A} p(a)` ≥ the candidate tier's threshold (defaults guard 0.9, heal 0.8) and the diagnosis is not `expected` (unless `requireDiagnosis: false`). -- `Answer.confidence` is **not** used by the gate. `Decision.confidence` = `probabilities[action]`. +- It reads `answers.action.probabilities`, or `{<passive>: 1}` when there is no `action` question. The top action is `answers.action.choice`, or the passive action if that choice is not offered. It reads `answers.diagnosis.choice`, or `expected`. +- `decide/policy.ts` -> `gate`: A = the permitted non-passive actions; the candidate is the argmax over A. It runs iff `Σ_{a∈A} p(a)` ≥ the candidate tier's threshold (defaults guard 0.9, heal 0.8) and the diagnosis is not `expected` (unless `requireDiagnosis: false`). `Answer.confidence` is **not** used. +- **Mode decides what is permitted.** Since f3636b2 the default is `observe` (`runtime.ts` -> `o.mode ?? "observe"`): the model is still consulted and answers are reported (except for `delivery`: a delivery candidate may wait up to `BODY_WAIT_MS` (100 ms) for its body, then proceeds at once and its queued decision is dropped as stale before the model sees it, `runtime.ts` -> `RuntimeImpl.runDelivery` controller `stale: () => released`; the same happens in guard mode whenever a delivery does not wait), but no action runs and no write or request is held. `guard` (opt-in) permits guard-tier actions (for delivery: `discard`, `defer`); `heal` (experimental) adds heal-tier ones. The text the model reads does not depend on the mode. The sim runs in `heal` (`sim/src/run/rt.ts` -> `createOptions`). +- Delivery enforcement: `discard` delivers the response but drops the writes its chain makes over newer data (`ActionRecord.dropped`); `defer` holds until related in-flight ops finish and re-asks. Holding is latency only (STATUS.md "Batch 4"). -### 8. Annotated example (real SIM row `sim-1071-d17` from `sim/samples/sample.jsonl`, budget 1,000) +### 8. Annotated example (real SIM row `sim-42-d48` from `sim/samples/sample.jsonl`, budget 1,000) -`state`/`questions` are exactly what the runtime handed its decider (843 chars by `stateChars`): +`state`/`questions` are exactly what the runtime handed its decider (894 chars by `stateChars`): ```jsonc -{ "app": "Snapvault — /albums", // title — route, ≤ 60 chars at this budget - "trigger": "A write to routeData.model.photos, routeData.model.owners, routeData.model.activity and 2 more from GET /v1/photos/photos (#73) is about to be applied.", - "facts": [ // compact limit 6; 2 remain (the shrink loop never drops the last one); each ≤ 220 chars ("…") - "routeData.model.photos was written once by other operations since this write's cause (#73) started (version 7 → 8), last 0.16s ago by user navigated to link \"Albums\" (#87), which started 2.07s after #73, from a later us…", - "routeData.model.owners was written once by other operations since this write's cause (#73) started (version 8 → 9), last 0.16s ago by user navigated to link \"Albums\" (#87), which started 2.07s after #73, from a later us…" ], - "in_flight": [ "GET /v1/albums/photos (#88) 0.16s so far, by #87", "GET /v1/albums/albums (#89) 0.16s so far, by #87" ], - "timeline": "none", // emptied by the shrink loop (dropped first) - "state": "none", // emptied by the shrink loop, or no state lines to begin with - "stats": [ "GET /v1/photos/photos: 4 done, 0 of last 4 failed, 1 in last 10s" ] } +{ "app": "PatentPath — /applications", + "trigger": "The response to GET /public/responses/:id?nocache=1791381656694.1008 (#186) arrived and is about to be delivered; its operation usually writes responsePublic.arguments, responsePu…", + // delivery sentence; cut at the compact trigger line limit (180) + "facts": [ // compact limit 6; 2 in this row (whether any were shrunk away is not recorded) + "The response would replace text the user typed into responsePublic.title after #186 started (1 user write, the last 0.17s ago): \"… gripper hinge \" → \"… gripper hinge\" (removes \" \").", // F2, non-neutral + "In 11 earlier completions of GET /public/responses/:id its chain wrote responsePublic.arguments, responsePublic.etag, responsePublic.failure and responsePublic.title (6 of 11 wrote state)." ], // profile counts + "in_flight": [ "GET /public/responses/:id?nocache=1791381656714.0552 (#187) 1.22s so far, by #179", "POST /ping {status: \"active\"} (#185) 1.93s so far, by #184" ], + "timeline": "none", // dropped first by the shrink loop + "state": "none", + "stats": [ "GET /public/responses/:id: 15 done, median 1.81s, p95 2.73s, 3 of last 15 failed, 4 in last 10s (usual 2.5)" ] } ``` ```json { "diagnosis": { "type": "choice", "instructions": "What is happening here?", "criteria": { "expected": null, "stale": null, "conflict": null, "duplicate": null, "inconsistent": null, "failing": null, "slow": null, "overload": null, "unusual": null, "transient": null } }, - "action": { "type": "choice", "instructions": "What should the runtime do with this write?", - "criteria": { "apply": null, "discard": null, "defer": null } } } + "action": { "type": "choice", "instructions": "What should the runtime do with this response or message?", + "criteria": { "deliver": null, "discard": null, "defer": null } } } ``` -At budgets > 1,400 the same criteria carry descriptions (for example `"discard": "drop this write and keep the current state"`), and the item text becomes `discard: drop this write and keep the current state`. +At budgets > 1,400 the same criteria carry the delivery descriptions, so the item text becomes `discard: deliver it but drop the state changes it would make over newer data`. -Packed (schematic): `[CLS] "app: Snapvault — /albums" [SEP] "trigger: A write to …" [SEP] "facts: <f1>\n<f2>" [SEP] "in_flight: <l1>\n<l2>" [SEP] "timeline: none" [SEP] "state: none" [SEP] "stats: GET /v1/photos/photos: …" [SEP] [Q] "What is happening here?" [O] "expected" … [O] "transient" [Q] "What should the runtime do with this write?" [O] "apply" [O] "discard" [O] "defer"`. +Packed (schematic): `[CLS] "app: PatentPath — /applications" [SEP] "trigger: The response to …" [SEP] "facts: <f1>\n<f2>" [SEP] "in_flight: <l1>\n<l2>" [SEP] "timeline: none" [SEP] "state: none" [SEP] "stats: GET /public/…" [SEP] [Q] "What is happening here?" [O] "expected" … [O] "transient" [Q] "What should the runtime do with this response or message?" [O] "deliver" [O] "discard" [O] "defer"`. -- `q_group`: −1 for the state, 0 for diagnosis, 1 for action. -- Feed plan: `choice_q = [qPos_diag, qPos_action]`, `choice_items` is `[2, 10]` (the action row is padded with 0 after 3), and score/noul get dummy rows. -- `choice_logits [2, 10]` → diagnosis uses 10 values, action the first 3. -- Calibration: `by_header["041ccfa6318c"]` / `["bb11f7f0f3a7"]` if present, else `choice:6-10` / `choice:3-5` buckets, else `tau_k`, else `choice`. +- `q_group`: −1 for the state, 0 for diagnosis, 1 for action. Feed plan: `choice_q = [qPos_diag, qPos_action]`, `choice_items` is `[2, 10]` (the action row padded with 0 after 3); score/noul get dummy rows. +- Calibration: `by_header["041ccfa6318c"]` / `["2a615ca90e33"]` if present, else `choice:6-10` / `choice:3-5` buckets, else `tau_k`, else `choice`. -Labels and the cost evidence in `meta`: +Labels and the cost evidence in `meta` (excerpt): ```json -"labels": { "action": { "type": "choice", "dist": { "apply": 0, "discard": 1, "defer": 0 } }, +"labels": { "action": { "type": "choice", "dist": { "deliver": 0.1524, "discard": 0.628, "defer": 0.2196 } }, "diagnosis": { "type": "choice", "label": "stale" } } -"meta": { "trigger": "mutation", "budget": 1000, "best": "discard", "passive_best": false, - "costs": { "apply": 69.2888, "discard": 64.6921, "defer": 67.9801 }, - "adjusted": { "apply": 4.347, "discard": 0, "defer": 3.288 }, "se": { "apply": 0.004, "discard": 0, "defer": 0.012 }, - "futures": 3, "non_passive_mass": 1, "transform": "default", "diagnosis": "stale", … } +"meta": { "trigger": "delivery", "passive": "deliver", "subject_feature": "cdn", "budget": 1000, "chaos": "degraded", "clean": false, + "best": "discard", "passive_best": false, + "costs": { "deliver": 38.6908, "discard": 38.2584, "defer": 42.4544 }, + "cost_futures": { "deliver": [42.3626, 30.8184, 42.8913], "discard": [41.9014, 30.4436, 42.4302], "defer": [42.2028, 42.4275, 42.7329] }, + "adjusted": { "deliver": 0.182, "discard": 0, "defer": 4.196 }, "se": { "deliver": 0.029, "discard": 0, "defer": 3.894 }, + "futures": 3, "non_passive_mass": 0.8476, "transform": "default", "diagnosis": "stale", … } ``` How the label falls out of `actionLabel`: -- Adjusted costs: apply = 69.29 + 0 (passive premium), discard = 64.69 + 0.25, defer = 67.98 + 0.25. No tie with passive, since the gaps exceed 0.05. -- Best = discard. gap_apply = 4.347 and gap_defer = 3.288, with τ ≈ 0.10–0.11. -- `exp(−gap/τ)` ≈ 0, so the distribution is one-hot on `discard`. +- Adjusted costs: deliver = 38.69 + 0 (passive), discard = 38.26 + 0.25, defer = 42.45 + 0.25. Best = discard; gaps deliver 0.182, defer 4.196. +- Per-action temperature τ = 0.1 + SE: deliver 0.129, defer 3.994. `exp(−0.182/0.129)` ≈ 0.244, `exp(−4.196/3.994)` ≈ 0.350, discard 1 → normalized ≈ 0.153 / 0.628 / 0.219. The large SE of `defer` (future 1 differs by ~12) keeps it soft: an S2-style "outcome depends on the future" label rather than a one-hot. +- T1 gain view of the same row (`t1_relabel.py`): gain(discard) = 38.69 − 38.26 − 0.25 ≈ 0.18, gain(defer) ≈ −4.0. #### Reading the STATUS.md examples -`packages/runtime/STATUS.md` ("Example situations") prints situations with `stateText` (indented list items) and a display-only `questions:` footer; the model reads `key: line1\nline2` segments and the question blocks of section 3. What they show: +`packages/runtime/STATUS.md` prints situations with `stateText` (indented list items) and a display-only `questions:` footer; the model reads `key: line1\nline2` segments and the question blocks of section 3. -- **Compact vs full** (`test/budget.test.ts`): the same stale write at budget 1,000 (998 chars) and 2,000 (1,494 chars). Limits at 1,000 are facts 6 / timeline 3, and the shrink loop leaves 1 timeline line; at 2,000, `r = 900/2100`, so timeline = `round(3 + 13r)` = 9 lines. At 1,000 the questions are bare labels (≤ 1,400); at 2,000 they carry descriptions. -- **One per trigger at 3,200** (`test/situation.test.ts`): mutation, request (redacted body `cardNumber: [redacted]`, `serve_cached` absent because the request is a POST and `serve_cached` needs a GET with a cached response, `state: none`, `stats: none`), failure, stall, inconsistency, transition, error. These strings are what `rt.py` must reproduce and what a wording change must update. +- **Compact vs full** (`test/budget.test.ts`): the stale typeahead **delivery** at budget 1,000 (951 chars) and 2,000 (1,760 chars). At 2,000, `r = 900/1300`, so facts = `round(6 + 6r)` = 10 and timeline = `round(3 + 13r)` = 12. At 1,000 the questions are bare labels (≤ 1,400); at 2,000 they carry descriptions. +- **Full budget 2,400** (`test/situation.test.ts`, `test/delivery.test.ts`, `test/content.test.ts`): four delivery situations (stale out-of-order response with F1 third value; F1 list undo; F2 autosave over typed text; a WebSocket message reverting a pending local change), then mutation, request, failure (×2: F5/F6), stall, inconsistency, transition, error. These strings are what `rt.py` must reproduce and what a wording change must update. ### 9. SIM rows (`sim/src/gen/trajectory.ts` -> `generateTrajectory`) -1. `buildScenario(seed)` fixes the domain, features, chaos, wording and `budget` (weighted 3,200:40 / 2,000:30 / 1,000:30). The split comes from `splitOf`: test if the domain is in `TEST_DOMAINS` (10 of 55), the family hash is in the held-out 17% (`"family-split-v1"`), or a pattern is in `TEST_PATTERNS`; dev if `hash("dev-split-v1", family) % 100 < 3`; else train. Test trajectories are kept with probability `testKeep` (CLI default 0.33). -2. **Ideal run** (no runtime, zero latency, exactly-once), then the **base run** on the real `createRuntime`. Options come from `sim/src/run/rt.ts` -> `createOptions`: `mode: "heal"`, `triage: "salient"`, `model: false`, `report: "silent"`, thresholds `{report 0, guard 0.5, heal 0.5}`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`, `historySize: 500`, observers fetch + timers + websocket only (xhr, user, errors, nav, storage, perf off; user actions and errors enter through `runtime.user()`/`reportError()`), `situation: {budget}`, `vocabulary` when paraphrased. The runtime module is `process.env.GENCLASS_RUNTIME ?? "@genclass/runtime"` (`realRuntimeFactory`), which also passes the sim's own `DEFAULT_DIAGNOSES` if the runtime's default vocabulary lacks any contract label. `--allow-fake` uses `sim/src/run/fake-runtime.ts` instead (`meta.runtime: "fake"`; tests only). - - The recording decider (`sim/src/run/runner.ts`) records `{state, questions}` verbatim, answers with probability 1 on the chosen action, and adds a lognormal virtual latency (median 6–25 ms, σ 0.35). - - Exploration ε ∈ {0, 0.08, 0.2} (weights 4:3:2) × `exploreScale`, used fully where the sim sees a problem and at ε/4 elsewhere. -3. Decision points (`pickPoints`): decisions with ≥ 2 actions, up to `maxPoints` (CLI default 6). They are weighted by `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2), ×1.5 when the sim's diagnosis is not `expected`. -4. `pointCosts`: for each action and each future j < K (default 3), re-run with the base run's explored choices before k, the action at k and passive after k. Each run stops at `t_k + W.finalMs` (15 s). - - Futures 1..K−1 re-seed everything after the decision with a salt `hashAll("future", seed, k, j)` shared across actions (common random numbers). When the scenario has external events after `t_k`, the ideal run is re-run with the same salt for that future. - - Adaptive: futures 1+ run only if some non-passive action beats passive by > 0.05 in future 0. `meta.futures` = the number of futures actually run (1 or K). - - Any prefix fingerprint mismatch, internal error or exception drops the point (`prefix-mismatch`, `cf-internal-error`, `cf-exception`). -5. `runCost(real, ideal, from, tEnd)`, with `stop = min(tEnd, from + 15 s, real.tStop)`, sums: - - `area`: ∫ client divergence over [from, min(stop, from + 10 s)]; - - 4.0 × final client divergence at `stop` + the server divergence `serverDist` vs the ideal server state at `stop`: per collection `25 × min(5, extra/missing items) + 6 × min(5, changed items)`; per document `6 × min(3, differing fields)`; per counter `6 × min(3, |difference|)` (counters ending in `beats` ignored); - - 1.5 × extra shown-error episodes + 1.0 × extra uncaught errors (counts in [from, stop] beyond the ideal run's); - - 0.08 × requests beyond the ideal run per signature (requests that arrived at the server in [from, stop], `NetEntry.ta`); - - 0.25 × seconds non-background ops were pending inside [from, stop]; - - 0.8 × ∫ violated app relations over [from, min(stop, from + 10 s)] + 2.0 × relations still violated at `stop`. - Client divergence `clientDist` = Σ over store fields of `weight × valueDist` (weights from the app, default 1; the first field (`fields[0]`) of every violated app relation counts its full weight even if it equals the ideal value, and is then skipped in the per-field comparison). `valueDist` ∈ [0, 1]: lists compare as multisets of content with volatile keys (`id, version, rev, revision, etag, updatedAt, updated_at, clientId, pending, seq`) ignored; objects recurse to depth 3 averaging over non-volatile keys; numbers equal within 1e-9. -6. `actionLabel(futures, passive)`: - 1. Premium per action tier: passive 0, guard 0.25, heal 0.5. - 2. A non-passive action whose mean cost is within 0.05 of passive's is a tie and is pinned to passive's costs + 1.5. - 3. Best = lowest mean adjusted cost (passive wins exact ties). - 4. `p_a ∝ exp(−max(0, mean(adj_a − adj_best)) / (0.1 + 1.0·SE_a))`, rounded to 1e-4. `SE_a` = sample SD of the paired per-future differences / √K (0 with one future). Futures are paired by index and truncated to the shortest list. - 5. `meta.costs` = per-action mean raw cost (1e-4); `meta.cost_futures` = the raw per-future costs (1e-4); `meta.adjusted` = gap to best (1e-3), `meta.se` (1e-3), `meta.non_passive_mass` (1e-4). -7. `transformQuestions`, with an independent RNG per row: - - 50%: unchanged. - - Otherwise, for `action` only: with p 0.12, if there are ≥ 3 options, drop one option that is neither passive nor best and renormalize the distribution. With p 0.5, shuffle the options. - - `meta.transform` records the variant (`default`, `drop:<a>`, `shuffle` or `drop:<a>,shuffle`). - - Instructions and descriptions are never changed. Wording variation comes from the runtime's `vocabulary`, per trajectory: - - diagnoses: 50% default; otherwise each label is paraphrased with p 0.6, and with p 0.3 one or two of `conflict, slow, overload, unusual, inconsistent, duplicate, transient` are dropped; - - actions: 50% default; otherwise each action is paraphrased with p 0.6 (`ACTION_PARA`). -8. Labels written: `labels.action = {type: "choice", dist}` always. `labels.diagnosis = {type: "choice", label: diag}` only if the sim's diagnosis is in the row's criteria and the subject correlated; otherwise the row is still emitted, counting drops `diagnosis-not-in-vocab` / `diagnosis-uncorrelated`. - - The diagnosis is **not** derived from costs or from the runtime's text: `sim/src/oracle/diagnose.ts` -> `diagnose(trigger, subject, ctx)` maps the sim's ground truth (superseded intent → `stale`, competing intents → `conflict`, repeated intent → `duplicate`, broken app relation → `inconsistent`, failure streak/outage → `failing`, isolated 5xx/network/timeout → `transient`, latency anomaly → `slow`, rate anomaly → `overload`, genuine shape anomaly/server bug → `unusual`, else `expected`). Exact rules per trigger: [sim.md](sim.md) flow 8. -9. Other row kinds: - - **Diagnosis-only** rows (`sim-<seed>-s<k>`): up to 3 per trajectory, sampled from decisions with < 2 actions, a diagnosis and a correlated subject; questions = the recorded `questions` **untransformed** (normally just `{diagnosis}`); meta `{…scenario meta, trigger, decision, t, diagnosis, diagnosis_only: true, subject}`. - - **Ask** rows (`sim-<seed>-a<i>`, family `<scenario family>/ask`): `runtime.situation("ask")` (always about `"now"`, so `trigger` = `The developer asks about the app right now.`) at 1–3 probe times (`scenario.askTimes`), with 1–3 questions from `askQuestions` (generators tried in shuffled order, each may return null). Labels are exact. The generators that name things (`last_failed`, `route`, `slowest`) check that their evidence appears in `JSON.stringify(state)`; the timing generators skip borderline values (table below). Meta `{…scenario meta, trigger: "ask", t, kinds}`. - - | qid | type | options (criteria) | label | skipped when | - |---|---|---|---|---| - | `q_write_inflight` | noul | true `yes, a write is in flight` / false `no write is in flight` | a POST/PUT/PATCH/DELETE in flight | never | - | `q_any_inflight` | noul | default (`yes`/`no`) | any request in flight | never | - | `q_pending` | score | `none, one, two, three or more` or `0 requests, 1 request, 2 requests, 3+ requests` | `min(3, in-flight count)` | > 6 in flight | - | `q_last_failed` | choice | `e1..e3` = endpoint signatures, `none` = a "none" phrase | id of the last failing signature (≥ 400 or network error, last 12 s), else `none` | < 2 known signatures; its path tail not in the text | - | `q_recent_failure` | noul | default | a failure in the last 5 or 10 s | a failure within 1 s of the window edge | - | `q_fail_count` | score | `none, one, two, three or more` | `min(3, failures in last 10 s)` | counts at 9 s and 11 s differ | - | `q_user_waiting` | noul | default | user-initiated wait > N s (N ∈ 1, 2, 3, 5) | within 400 ms of N s | - | `q_user_recent` | noul | default | user input within N s (N ∈ 1, 2, 3) | within 300 ms of N s | - | `q_last_save` | noul | true `the last save succeeded` / false `the last save failed` | last save ok | no save yet | - | `q_route` | choice | `r1..r3` = the route + 2 from a fixed list (`/settings`, `/home`, …) | id of the current route | route not in the text | - | `q_slowest` | choice | `o1..o4` = in-flight signatures | id of the oldest in-flight request | < 2 in flight; top two within 300 ms or same signature; a path tail missing from the text | -10. Ids, family and meta: - - Ids: `sim-<seed>-d<k>` (decision), `-s<k>`, `-a<i>`. `family` = `<scenario family>/<trigger>`. - - Decision meta: `seed, domain, family, chaos, budget, runtime, features, patterns, trigger, decision, t, explored_before, best, passive_best, costs, cost_futures, futures, adjusted, se, non_passive_mass, cost_parts{area, final_client, final_server, relation_s, relation_final, errors, uncaught, wasted, latency_s}, tiers, diagnosis, subject{kind, how, ref?}, transform, fake_diagnosis?`. - - Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/part-NNNNNN.<split>.jsonl`, written as `.tmp` and renamed when the part completes, with a `part-NNNNNN.json` marker; `--merge-only` concatenates them). `stats.json` `token_estimate` is `(len(JSON state) + len(JSON questions)) / 3.6`, not real tokens. - - `--sample`: target 900 rows, `testKeep` 1, then a stratified 200 rows (round-robin over `trigger|diagnosis|act-or-passive`) to `sim/samples/sample.jsonl`, plus `EXAMPLES.md` (`renderExamples`) and `sample-stats.json`. Full CLI: [sim.md](sim.md). +Mode is chosen by the CLI (`sim/src/gen.ts` -> `parse`): default `gold`; `--unlabeled`; `--on-policy <model dir>` (the worker loads `sim/src/run/onpolicy.ts` -> `loadModelDecider`, which runs the runtime's own `createModelHost` inline on onnxruntime-web WASM from `sim/dist/model-host`, built by `npm run build:model-host`). + +1. `buildScenario(seed)` fixes the domain (115 = 55 original + 60 in `vocab2.ts`), features, chaos (`calm, normal, flaky, degraded, storm, mobile, peak, deploy`; mobile personas get `mobile` with p 0.7), **clean runs** (p 0.05: calm network, no failures, no accidental clicks, no feature env; `meta.clean`), tab switches, clock skew, wording and `budget` (weighted 3,200:40 / 2,000:30 / 1,000:30). Split (`splitOf`): test if the domain is in `TEST_DOMAINS` (19 of 115), the family hash is in the held-out 17%, a pattern is in `TEST_PATTERNS`, or (unless `SIM_FEATURE_HOLDOUT=off`) a family feature is in `TEST_FEATURES` (`swcache, presence, cascade, saga, prefetch, permissions`); dev if `hash("dev-split-v1", family) % 100 < 3`; else train. Test trajectories are kept with probability `testKeep` (CLI default 0.33). +2. **Ideal run**, then the **base run** on the real `createRuntime`. Options (`sim/src/run/rt.ts` -> `createOptions`): `mode: "heal"`, `triage: "salient"`, `model: false`, `report: "silent"`, thresholds `{report 0, guard 0.5, heal 0.5}`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`, `historySize: 500`, observers fetch + timers + websocket + **storage** (xhr, user, errors, nav, perf off), `situation: {budget}`, `vocabulary` when paraphrased. On-policy runs pass `production: true`, which replaces the policy with `{holdBudgetMs: 1e9, maxActionsPerMinute: 1e9}`: default thresholds (0.6/0.9/0.8) and the diagnosis gate, still `heal` mode. The runtime module is `process.env.GENCLASS_RUNTIME ?? "@genclass/runtime"`. + - The recording decider (`sim/src/run/runner.ts`) records `{state, questions}` verbatim, answers with probability 1 on the chosen action, and adds a lognormal virtual latency. On-policy: the model answers; `modelProbs`/`modelChoice`/`modelDiagnosis` and what the gate actually ran (`ran`) are recorded, and replays force `ran`. + - Exploration ε ∈ {0, 0.08, 0.2} (weights 4:3:2) × `exploreScale`: full where the sim sees a problem, ε/4 elsewhere, **ε/2 for delivery** (its diagnosis is only known after the run). None on-policy; ×1.5 in unlabeled mode. + - Delivery diagnoses are filled after the run: the verdict of the first write the delivered op (or push message) made, each write being diagnosed at proposal time with the `mutation` rules (`SimWrite.diag`). +3. Decision points: gold `pickPoints` takes decisions with ≥ 2 actions and `k < DENSE_K` (600), up to `maxPoints` (CLI default 6), weighted by `TRIGGER_W` (mutation 1, **delivery 1.2**, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2), ×1.5 when the diagnosis is not `expected`. On-policy `pickOnPolicy` weights 4 if a non-passive action ran, 3 if the model chose one, 2 if the diagnosis is not `expected`, else 1. +4. `pointCosts`: for each action and each future j < K (default 3), re-run with the base run's explored choices before k, the action at k and passive after k, stopping at `t_k + W.finalMs` (15 s). + - Futures 1..K−1 re-seed everything after the decision with a salt `hashAll("future", seed, k, j)` shared across actions. With **S2** (`SIM_S2` ≠ `0`, default on) they also re-draw the user's later step timing, outage/offline/slow/socket-drop/server-bug windows, prefix latents (did an ambiguous failed write commit, remaining time of in-flight requests) and the hidden intent of earlier repeats (ideal run only). The ideal run is re-run for a re-seeded future when external events follow `t_k` or S2 is on. + - Adaptive: with S2, future 1 always runs; later futures only if some non-passive action beat passive by > 0.05 in a future seen so far (without S2 the same rule already applies from future 1, so future 1 needs such a gain in future 0). `meta.futures` = futures actually run. + - A prefix mismatch in an S2 future is retried once with network/timing re-draws only (`noLatent`; counted as `info:latent-fallback`). Any remaining prefix mismatch, internal error or exception drops the point (`prefix-mismatch`, `cf-internal-error`, `cf-exception`). +5. `runCost(real, ideal, from, tEnd)` (unchanged): `area` ∫ client divergence over ≤ 10 s; 4.0 × final client divergence + server divergence at `stop`; 1.5 × extra shown-error episodes + 1.0 × extra uncaught errors; 0.08 × extra requests per signature; 0.25 × seconds non-background ops were pending; 0.8 × ∫ violated relations + 2.0 × relations still violated. Weights in `W` (table below); full definitions in [sim.md](sim.md). +6. `actionLabel(futures, passive)` (unchanged): premium per tier (passive 0, guard 0.25, heal 0.5); a non-passive action within 0.05 of passive is pinned to passive + 1.5; best = lowest mean adjusted cost (passive wins exact ties); `p_a ∝ exp(−max(0, mean(adj_a − adj_best)) / (0.1 + 1.0·SE_a))`, rounded to 1e-4. `meta.costs`, `cost_futures`, `adjusted`, `se`, `non_passive_mass` as in the example. +7. **S1** (gold and on-policy): if the diagnosis is undefined or `expected`, the subject is correlated, passive is not best and `adjusted[passive] ≥ S1_GAP` (1.0), the diagnosis becomes `diagnosisFromOutcome`: (a) for each field already diverged from the ideal run, the last write to it before the decision; if that write's verdict is not `expected`, the latest such verdict wins; (b) `duplicate` for a repeat of an accidental action (or an op marked as a duplicate); (c) `duplicate` on a `request` point whose best action is coalesce/block, with an identical request in flight or answered in the last 10 s; (d) `inconsistent` (inconsistency/transition) or `stale` when fields diverged without a named cause; (e) `unusual`. `meta.diagnosis_s1` = rule (`a-write`, `b-repeat`, `c-twin`, `d-diverged`, `e-other`), `meta.diagnosis_subject` = the subject-only verdict. +8. `transformQuestions`, with an independent RNG per row: 50% unchanged; otherwise, for `action` only, with p 0.12 (≥ 3 options) drop one option that is neither passive nor best and renormalize, and with p 0.5 shuffle. `meta.transform` records the variant. Wording variation comes from the runtime's `vocabulary`, per trajectory: diagnoses 50% default, else each label paraphrased with p 0.6 and p 0.3 of dropping one or two of `conflict, slow, overload, unusual, inconsistent, duplicate, transient`; actions 50% default, else each action paraphrased with p 0.6 (`ACTION_PARA`, keyed by action name only; see gotchas for delivery). +9. Labels written (gold): `labels.action = {type: "choice", dist}` always; `labels.diagnosis = {type: "choice", label}` only if the diagnosis is in the row's criteria and the subject correlated (drops `diagnosis-not-in-vocab` / `diagnosis-uncorrelated` otherwise). Unlabeled rows get only the diagnosis label (no S1, no costs; `transformQuestions` with no dist and `best = passive`). The diagnosis is never derived from the runtime's text: `sim/src/oracle/diagnose.ts` maps sim ground truth ([sim.md](sim.md) flow 8). +10. Other row kinds: + - **Diagnosis-only** (`sim-<seed>-s<k>`): up to 3 per trajectory from decisions with < 2 actions, a diagnosis and a correlated subject; questions untransformed. + - **Ask** (`sim-<seed>-a<i>`, gold only when `askRows`; always in unlabeled mode as `u-<seed>-a<i>`; never on-policy): `runtime.situation("ask")` at 1–3 probe times with 1–3 questions from `askQuestions` (table below). Labels are exact. + + | qid | type | options (criteria) | label | skipped when | + |---|---|---|---|---| + | `q_write_inflight` | noul | true `yes, a write is in flight` / false `no write is in flight` | a POST/PUT/PATCH/DELETE in flight | never | + | `q_any_inflight` | noul | default (`yes`/`no`) | any request in flight | never | + | `q_pending` | score | `none, one, two, three or more` or `0 requests, 1 request, 2 requests, 3+ requests` | `min(3, in-flight count)` | > 6 in flight | + | `q_last_failed` | choice | `e1..e3` = endpoint signatures, `none` | id of the last failing signature (≥ 400 or network error, last 12 s), else `none` | < 2 known signatures; its path tail not in the text | + | `q_recent_failure` | noul | default | a failure in the last 5 or 10 s | a failure within 1 s of the window edge | + | `q_fail_count` | score | `none, one, two, three or more` | `min(3, failures in last 10 s)` | counts at 9 s and 11 s differ | + | `q_user_waiting` | noul | default | user-initiated wait > N s (N ∈ 1, 2, 3, 5) | within 400 ms of N s | + | `q_user_recent` | noul | default | user input within N s (N ∈ 1, 2, 3) | within 300 ms of N s | + | `q_last_save` | noul | true `the last save succeeded` / false `the last save failed` | last save ok | no save yet | + | `q_route` | choice | `r1..r3` = the route + 2 from a fixed list | id of the current route | route not in the text | + | `q_slowest` | choice | `o1..o4` = in-flight signatures | id of the oldest in-flight request | < 2 in flight; top two within 300 ms or same signature; a path tail missing | +11. Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/part-NNNNNN.<split>.jsonl` with a `part-NNNNNN.json` marker; `--merge-only` concatenates them). `stats.json` `token_estimate` is `(len(JSON state) + len(JSON questions)) / 3.6`, not real tokens. `SIM_PROBE=1` adds `meta.probe` (sim-only hidden facts; analysis rows, **not** training data). `--sample`: target 900 rows, `testKeep` 1, then a stratified 200 rows to `sim/samples/sample.jsonl` plus `EXAMPLES.md` and `sample-stats.json`. Full CLI and cluster orchestration: [sim.md](sim.md). The real-browser corpus writes the same schema with `meta.source = "realapps"` ([realapps.md](realapps.md)). ### 10. Training consumes rows (`jev_local/train/train.py` -> `encode_example`, `parse_target`) -1. Every question goes through `question_from_json` → `question_block`, and the state through `state_segments`. This is the Python original of `model/serialize.ts`, so SIM rows (written by `JSON.stringify`) render identically on both sides. -2. `parse_target(block, label)`: - - noul `p` → `[p]` (hard if 0/1). - - choice `label` → one-hot over `block.labels` (rejected if not an option). - - choice `dist` → values aligned to `block.labels` (missing → 0), renormalized; always `hard=False`, **even when one-hot**, so label smoothing never applies to SIM action labels (they are always `dist`). A dist summing to 0 is rejected. - - score `level` → one-hot (rejected outside `0..K−1`); score `dist` (length must equal K) → renormalized, soft. - - A type mismatch or bad label makes the question unsupervised (`bad_labels`); a label for a qid that has no question is ignored by the trainer (the curriculum's `_validate` rejects such rows). -3. `Packer.pack_split(segments, blocks, --max-len)`: questions are isolated, so an over-long example splits into several sequences that repeat the state (greedy, in request order). A question whose state + whole block exceeds `max_len` is dropped (`dropped_qids`); a state that alone exceeds `max_len` therefore drops every question. -4. Losses (`jev_local/train/losses.py`): proper scoring rules. Defaults reproduce v1 (CE, label smoothing 0.02 on hard labels, RPS 0.25 on score). See [training.md](training.md) for the configs actually used. -5. Final round 1 (`training/launch_final1.sh`, `training/configs/mix_final1.json`): `--max-len 2048`, `--batch-tokens 8192`, mixture `simA 0.85, cur4 0.12, cur1 0.02, gen 0.01`, `pass_tokens` 500,000,000, `max_repeat` `{"*": 2.0, "simA": 1.3}`. -6. Curriculum rows (`rows.py`; full detail in [training.md](training.md)): - - `decision_row` emits either runtime-exact text (`rt.render`, style `runtime`, share `--p-runtime` = env `GC_P_RUNTIME`, default 0; `cur4` used 0.8) or varied text (style `varied`; also the fallback when `rt.render` returns `None`, e.g. a scenario with no `spec` or `no_runtime`). Runtime-style rows get the runtime's exact questions plus 0–2 primitive questions (choice of `(0, 0, 1, 2)`); `action` is labelled only if `rt.render` produced an `action` question. - - Varied text: renamed keys (`KEY_VARIANTS`), op/time/duration formats (`Style.make`), facts ≤ 12 shuffled (25%), one of `in_flight`/`stats`/`state` dropped (15%), key order shuffled (10%), state ≤ 8 lines, timeline ≤ 16; action labels renamed (10%, each with p 0.5, `RENAMES`), 1–2 `DISTRACTOR_ACTIONS` inserted (15%), options shuffled (50%), descriptions = canonical (50%) or a paraphrase; diagnosis subset of gold + `expected` + 2–5 others (20%), shuffled (50%); bare `null` criteria (10% per question); question order swapped (15%); 0–3 primitives (choice of `(0, 1, 2, 2, 3)`). Headers come from `fmt.ACTION_INSTR[trigger]` (some with `{subj}`) and `fmt.DIAG_INSTR`; these lists do **not** contain `What is happening here?` nor the runtime's exact failure/inconsistency/transition headers, so those four strings appear only in `rt.render` rows (the runtime's mutation, request, stall and error action headers are also among the varied choices). - - `ask_row`: varied state with an ask trigger sentence (`facts` dropped 30%), 2–5 primitive questions, meta `{kind: "ask", trigger: "ask", source_trigger, case, domain, prims}`, family `cur/ask/<trigger>`. - - Decision meta: `kind, trigger, case, domain, passive_best, action_gold, action_canonical, passive, diag_gold, action_names, prims, heldout_templates_possible, soft_action, style`; family `cur/<trigger>/<case tail>`. `meta.action_names` maps canonical → shown names (`eval_runtime.canonical` reverses it). - - `generate.py` writes ids `cur-<split>-<chunk:05d>-<i:06d>`, applies `js_numbers` to `state` and `questions` (integral floats → ints, as JS prints them; labels and meta untouched), and drops rows that fail `_validate` (jev_local `state_segments`/`question_block`/`parse_target`, no unknown qids, ≥ 1 label). +1. Every question goes through `question_from_json` → `question_block`, and the state through `state_segments`: the Python original of `model/serialize.ts`, so SIM rows (written by `JSON.stringify`) render identically on both sides. +2. `parse_target(block, label)`: noul `p` → `[p]` (hard if 0/1); choice `label` → one-hot (rejected if not an option); choice `dist` → aligned to `block.labels`, renormalized, always `hard=False` (no label smoothing on SIM action labels); score `level` → one-hot; score `dist` (length K) → soft. A type mismatch or bad label makes the question unsupervised (`bad_labels`). +3. `Packer.pack_split(segments, blocks, --max-len)`: questions are isolated, so an over-long example splits into several sequences that repeat the state. A question whose state + whole block exceeds `max_len` is dropped. +4. Losses (`jev_local/train/losses.py`): proper scoring rules (CE, label smoothing 0.02 on hard labels, RPS 0.25 on score). Configs in [training.md](training.md). +5. Round 1 (`training/launch_final1.sh`, `configs/mix_final1.json`) trained on **situation-v1** SIM phase A; its numbers are the baseline only. Every committed mixture config is v1-era and names v1 buckets (`simA`, `simAh`, `cur1`, `cur4`, `gen`): `configs/mix_t150.json` (`simA 0.9, cur4 0.1`, `pass_tokens` 470M; the `t150-g1` teacher run that was stopped for v2, `training/LOG.md` 01:13–01:56), `mix_r68.json` (R68 benchmark, not started), `mix_t1{a,b,h}.json` (T1 variants on v1 data, stopped at the v2 freeze, LOG 03:32). No v2 mixture is committed at b435acb; the v2 runs will need new configs or v2 data under these bucket names on the VM (unverified). +6. **T1 and teacher labels** (training side; nothing in the runtime changes): + - `t1_relabel.py --in DIR --out DIR --tau τ [--keep-dist]`: for SIM decision rows with an `action` label and `meta.cost_futures` (falling back to `meta.costs`), `gain(a) = mean_f c(passive) − mean_f c(a) − premium` (passive 0, guard 0.25, heal 0.5), clipped to ±30, label `softmax(gain/τ)` over the offered actions; `meta.egain` keeps the gains. With `--keep-dist` the SIM dist is kept and the gains are added as `labels.action.gain` and `meta.egain` (gain-head training). + - `label_teacher.py --ckpt T --in rows --out rows`: every question (or `--qids`) gets a calibrated soft label (choice dist, score dist, noul p); gold labels are kept unless `--overwrite`; `meta.teacher` records checkpoint, top probability, margin and summed non-passive mass (its `PASSIVE` set is `apply, send, deliver, wait, ignore`). + - `collect_gain.py` writes eval_runtime-format records (+ `gain_pred` when the checkpoint has a gain head); `eval_gain.py` compares gate policies (`gate@t`, `gate@t-nodiag`, `gain>m`, `head>m`) by fired share, clear-case recall, harmful share and gain captured vs the oracle. +7. Curriculum rows (`rows.py`; full detail in [training.md](training.md)): + - `decision_row` emits runtime-exact text (`rt.render`, style `runtime`, share `--p-runtime` = env `GC_P_RUNTIME`, default 0) or varied text (style `varied`, also the fallback when `rt.render` returns `None`). + - **v2:** `rt.render(sc, app, rng, info)` renders a `mutation` scenario whose cause is a completed fetch or WS message as a **`delivery`** with probability `P_DELIVERY` = 0.5 (forced by `spec["delivery"]`), when the gold action survives the mapping `DELIVERY_ACTION` (`apply→deliver, discard→discard, defer→defer`; `defer` removed unless related work is in flight). `info["trigger"]` and `info["action_map"]` let `decision_row` rename labels and set `meta.trigger`, `meta.passive`, `meta.action_names` and the family `cur/delivery/<case tail>`. + - Runtime-exact budgets: `rt.BUDGETS` = 2,400:0.35 / 2,000:0.2 / 1,667:0.05 / 1,333:0.05 / 1,000:0.35 (`GC_RT_BUDGET` forces one budget for analysis). Questions use `TRIGGER_DESCRIPTIONS` for delivery and bare labels at ≤ 1,400. + - Varied text, `ask_row`, ids, `js_numbers` and `_validate` are unchanged since v1; varied rows never use the trigger `delivery` (`fmt.TRIGGER_ACTIONS` has no delivery entry). ### 11. Evaluation and calibration fit (`training/eval_runtime.py`) -CLI: `--ckpt` (required), `--data DIR` (required; reads `DIR/<split>.jsonl`), `--split` (default `test`), `--fit-split`, `--limit`, `--batch` (16), `--threads` (32), `--out report.json`, `--write-calibration`, `--calibration` (evaluate with a given file; reads only `noul`, `choice`, `score`, `by_header`, so v2 keys are ignored), `--records-dir` (cache raw logits as `<ckpt>__<data>__<split>.jsonl`), `--header-calibration`. - -1. Raw logits per supervised question come from `jev_local.train.eval.collect`. `header` is the header key (`sha1(header)[:12]`, computed in `jev_local/train/eval.py`). -2. `fit_calibration` (on `--fit-split`): - - noul τ on a 61-point log grid in [0.2, 5]; - - choice τ by golden section on log τ in [0.2, 5] (40 iterations) over all choice questions, `action` and `diagnosis` included; - - score τ the same way; - - `action` and `diagnosis` also get their own τ (used by the `group` metric mode, never written); - - `by_header` (sha1 keys) only for standing questions with ≥ 300 examples. - - Split-half check: refit on fit-split records with even `crc32(id)`, evaluate on odd ones (`report.split_half`). - - Metric modes: `raw` (τ 1), `kind` (per-kind τ, what the runtime does with a v1 file), `group`, `header`; the report has `questions_<mode>` (acc, NLL, Brier, ECE 15 bins) and `decisions_<mode>` for each, plus `primitive_acc`. Rows are bucketed by `meta.budget` (else by state chars `≤1100` / `≤2100` / `>2100`) for `by_budget`. -3. `--write-calibration` writes `{noul, choice, score, by_header, _fit}`. `by_header` stays `{}` unless `--header-calibration` is passed, and `final_post.sh` (which runs the eval through `training/eval_sim.sh`) does not pass it. Shipped files are therefore v1 per-kind temperatures; the runtime ignores `_fit`. -4. Decision metrics re-implement the runtime §8 gate (summed mass, `THRESH` guard 0.9 / heal 0.8, top diagnosis ≠ `expected`; unknown actions count as heal). Reports per trigger/case/style/budget: FIR, precision, recall, mean counterfactual cost vs always-passive vs oracle (SIM rows with `meta.costs`), plus a threshold sweep. +CLI: `--ckpt`, `--data DIR` (reads `DIR/<split>.jsonl`), `--split` (default `test`), `--fit-split`, `--limit`, `--batch` (16), `--threads` (32), `--out report.json`, `--write-calibration`, `--calibration` (reads only `noul`, `choice`, `score`, `by_header`), `--records-dir`, `--header-calibration`. -### 12. Export → model directory (`training/export_runtime.py` -> `main`) +1. Raw logits per supervised question come from `jev_local.train.eval.collect`; `header` is the header key. +2. `fit_calibration` (on `--fit-split`): noul τ on a 61-point log grid in [0.2, 5]; choice and score τ by golden section on log τ in [0.2, 5]; `action`/`diagnosis` τ for the `group` mode (never written); `by_header` only for standing questions with ≥ 300 examples; split-half check. Metric modes `raw`, `kind`, `group`, `header`; `by_budget` buckets by `meta.budget` (else state chars `≤1100` / `≤2100` / `>2100`). +3. `--write-calibration` writes `{noul, choice, score, by_header, _fit}`; `by_header` stays `{}` unless `--header-calibration`. +4. Decision metrics re-implement the runtime §8 gate (summed mass, `THRESH` guard 0.9 / heal 0.8, top diagnosis ≠ `expected`; unknown actions count as heal). The passive action is `PASSIVE[trigger]`, falling back to `meta.passive` (the map has no `delivery` key; delivery rows carry `meta.passive`), and a gold action with tier `passive` counts as passive-best. New since v1: `recall_clear` (gold non-passive, permitted, target mass ≥ 0.9) and `recall_clear_stale_dup` (the same for gold diagnosis `stale`/`duplicate`), the metrics of `training/PLAN-v1.md` §1. -Run by `training/final_post.sh` after the eval (`eval_sim.sh simAe <M>`): `--calibration out/cal/<M>-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 --threads 24`; it then tars the export without `ref/` for `pull_on_train.sh`. +### 12. Export → model directory (`training/export_runtime.py` -> `main`, unchanged since `situation-v1`) -CLI defaults: `--ckpt`, `--out` (required), `--name genclass-runtime`, `--version 0.1.0`, `--requests` (a JSON list) or `--data-rows a.jsonl,b.jsonl`, `--n-per-file 40`, `--calibration` (default: the checkpoint's), `--opset 17`, `--threads 16`, `--block 32`. It imports `jev_local` and `genclass_export` from `~/jev` and `~/jev/scripts` (VM layout). Steps: +Run by `training/final_post.sh` after the eval: `--calibration out/cal/<M>-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 --threads 24`. CLI defaults: `--name genclass-runtime`, `--version 0.1.0`, `--n-per-file 40`, `--opset 17`, `--threads 16`, `--block 32`. It imports `jev_local` and `genclass_export` from `~/jev` (VM layout). Packaging, validating and publishing the result: [RELEASE.md](../../RELEASE.md) Part B. -1. `load_checkpoint(ckpt, "cpu", float32, encoder="reference")`; `ExportModel(enc, heads)`; parity requests sampled per file (random permutation, seed 0) keeping those that pack to ≤ 1,500 tokens with the Python `Packer(tok, max_len=8192)`. -2. `torch.onnx.export` fp32 and fp16 references into `ref/` with dynamic axes `L` (tokens), `G/K` (choice), `S/K2` (score), `M` (noul). -3. `make_q8`: `gemm_to_matmul` (Gemm with transA 0, alpha = beta = 1 and an initializer weight → MatMul [+ Add]), `MatMulNBitsQuantizer` (8-bit, block 32, symmetric, axis 0), then `quantize_embedding` (per-row `scale = max|row| / 127`, zero rows scale 1, `q = clip(rint(w/scale), −127, 127)`); refuses any fp16 initializer or Cast-to-fp16. `make_fp16`: the fp16 reference with the same int8 embedding, scale stored fp16. -4. Parity on CPU (ORT `CPUExecutionProvider` with `--threads` intra-op threads for fp32/fp16/q8, plus a 1-thread session for fp16/q8 only) vs `FastEngine(…, encoder="banded")` logits, both calibrated with the shipped calibration → `parity.json`. -5. Copy tokenizer, write calibration, `meta.json`, then `model.json` with byte sizes and sha256 of every file. +1. `load_checkpoint(ckpt, "cpu", float32, encoder="reference")`; `ExportModel(enc, heads)`; parity requests sampled per file (seed 0) that pack to ≤ 1,500 tokens. +2. `torch.onnx.export` fp32 and fp16 references into `ref/` with dynamic axes `L`, `G/K`, `S/K2`, `M`. +3. `make_q8`: `gemm_to_matmul`, `MatMulNBitsQuantizer` (8-bit, block 32, symmetric), then `quantize_embedding` (per-row `scale = max|row| / 127`); refuses any fp16 tensor. `make_fp16`: fp16 reference with the same int8 embedding. +4. Parity on CPU vs `FastEngine(…, encoder="banded")` logits, both calibrated with the shipped calibration → `parity.json`. +5. Copy tokenizer, write calibration, `meta.json`, then `model.json` with byte sizes and sha256. | file | content | |---|---| -| `model.json` | `{format: "genclass-runtime-model/1", name, version, license: "Apache-2.0", variants: {q8: {file, bytes, sha256, provider: "wasm"}, fp16: {file, bytes, sha256, provider: "webgpu", needs: "shader-f16"}}, files: {tokenizer, calibration, meta: {file, bytes, sha256}}}` | -| `<name>-q8.onnx` | MatMulNBits 8-bit, block 32, symmetric, on every MatMul (Gemm rewritten first) + int8 row-wise token embedding (Gather int8 → Cast fp32 → Mul per-row scale); must contain no fp16 tensor | -| `<name>-fp16.onnx` | fp16 weights/compute, fp32 I/O, int8 embedding (Cast fp16) | -| `tokenizer.json` | copied from `<ckpt>/backbone/tokenizer.json` (pruned: 16,000 merges, 16,364 tokens) | +| `model.json` | `{format: "genclass-runtime-model/1", name, version, license: "Apache-2.0", variants: {q8: {file, bytes, sha256, provider: "wasm"}, fp16: {file, bytes, sha256, provider: "webgpu", needs: "shader-f16"}}, files: {tokenizer, calibration, meta}}` | +| `<name>-q8.onnx` | MatMulNBits 8-bit block 32 on every MatMul + int8 row-wise token embedding; no fp16 tensor | +| `<name>-fp16.onnx` | fp16 weights/compute, fp32 I/O, int8 embedding | +| `tokenizer.json` | from `<ckpt>/backbone/tokenizer.json` (pruned: 16,000 merges, 16,364 tokens) | | `calibration.json` | `--calibration` file, else the checkpoint's | -| `meta.json` | `name` (`<name>-<version>`), `source_checkpoint`, `max_len` (checkpoint meta, else 1536; 2048 for final round 1), `max_total: 8192`, `window`, `hidden_size`, `layer_types`, `markers`, `cls_id`, `sep_id`, `pad_id`, `vocab_size`, `merges_kept`, `inputs`, `outputs: ["choice_logits","score_logits","noul_logits"]`, `embedding_quant`, `matmul_quant`, `license` | -| `requests.json` | `[{id, state, questions, tokens}]`: parity requests (≤ 1,500 tokens, `--n-per-file` per data file) | -| `pack_fixtures.json` | per request `{id, input_ids, position_ids, q_group, i_group, n_state, q_index: {qid: {kind, header, labels, q_pos, item_pos}}}` from the Python packer | -| `torch_fixtures.json` | per request `{id, logits: {qid: [...]}, probs: {qid: [...]}, header_key: {qid: hk}}` (PyTorch, calibrated with the shipped file) | -| `parity.json` | per variant `fp32`/`fp16`/`q8`: `max_abs_logit`, `max_abs_prob`, `argmax_agree`/`argmax_total`/`argmax_rate`, `noul_side_agree`/`noul_total`/`noul_side_rate`, `gate08_agree`/`gate09_agree`/`gate_total`/`gate08_rate`/`gate09_rate` (same argmax and same side of pmax ≥ 0.8 / 0.9 on choice questions), `ort_cpu_ms_p50`, `ort_cpu_1thread_ms_p50` (fp16, q8), `file_mb`; plus `n_requests`, `tokens{min, median, max}`, `embedding_q8`, `embedding_fp16` (quantization error stats) | -| `ref/` | `<name>-fp32.onnx`, `<name>-fp16-fullemb.onnx` references (not in the card; excluded from the served tar) | +| `meta.json` | `name` (`<name>-<version>`), `source_checkpoint`, `max_len` (checkpoint meta, else 1536; 2048 for round 1), `max_total: 8192`, `window`, `hidden_size`, `layer_types`, `markers`, `cls_id`, `sep_id`, `pad_id`, `vocab_size`, `merges_kept`, `inputs`, `outputs`, `embedding_quant`, `matmul_quant`, `license` | +| `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` | parity requests and the Python packer / PyTorch outputs for them (read by the runtime parity tests and `validate.mjs`) | +| `parity.json` | per variant: `max_abs_logit`, `max_abs_prob`, argmax / noul-side / gate08 / gate09 agreement, CPU p50 latencies, `file_mb`; plus token stats and embedding quantization errors | +| `ref/` | fp32 and fp16-fullemb references (excluded from the served tar) | -Shipped candidates (MODEL_CARD, measured at stage 1c): R17 `genclass-runtime-r17` (ettin-encoder-17m, d 256, 7 layers, 8.1M + 0.7M heads) q8 9.6 MB / fp16 13.6 MB; R32 `genclass-runtime-r32` (ettin-encoder-32m, d 384, 10 layers, 18.8M + 1.6M heads) q8 22.5 MB / fp16 34.8 MB; both vocab 16,364. +Candidate students (MODEL_CARD; sizes of the round-1 `final1` exports, `training/LOG.md`): R17 `genclass-runtime-r17` (ettin-17m, d 256, 7 layers) q8 9.6 MB / fp16 13.6 MB; R32 `genclass-runtime-r32` (ettin-32m, d 384, 10 layers) q8 22.5 MB / fp16 34.8 MB; both vocab 16,364. `training/PLAN-v1.md` adds R68 and a 150M teacher (T150, never shipped). -The runtime reads `model.json` (`loader.ts` -> `parseCard`; missing `files` default to `tokenizer.json`/`calibration.json`/`meta.json`; `files` entries may be bare file names; file names must be relative with no scheme, leading slash, `..` or empty segment; `sha256` may carry a `sha256:` prefix; `format` defaults to `CARD_FORMAT` and is **not** checked; `name`/`version` default to `genclass-model`/`0.0.0`), then the `meta.json` keys listed in Concepts and every `calibration.json` key listed in step 6. Load plans (`planOrder`): webgpu+fp16 (needs `shader-f16`) → webgpu+q8 → wasm+q8 (wasm+fp16 if the card has no q8; only when the card has neither `q8` nor `fp16` are its other variant names tried on WASM in card order). `device: "auto"` skips WebGPU on a software (fallback) adapter; `"wasm"` never touches the GPU. The default base URL is `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`host.ts` -> `DEFAULT_MODEL_BASE_URL`), and that package is not published yet. More in [model-host.md](runtime/model-host.md). +The runtime reads `model.json` (`loader.ts` -> `parseCard`; `format` defaults to `CARD_FORMAT` and is **not** checked), then `meta.json` and `calibration.json`. Load plans (`planOrder`): webgpu+fp16 → webgpu+q8 → wasm+q8. The default base URL is `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`host.ts` -> `DEFAULT_MODEL_BASE_URL`), which returns 404 today. More in [model-host.md](runtime/model-host.md). ## Configuration and constants | name | type | value | defined in | effect | |---|---|---|---|---| -| `STATE_CHAR_BUDGET` | number | 3200 | `situation/serialize.ts` | full section sizes; default budget | +| `STATE_CHAR_BUDGET` | number | **2400** (v1: 3200) | `situation/serialize.ts` | full section sizes; default budget; webgpu/unknown auto budget | | `COMPACT_BUDGET` | number | 1100 | `situation/serialize.ts` | budget at or below which section limits are minimal | | `MIN_BUDGET` | number | 500 | `situation/serialize.ts` | smallest budget honoured | -| `LIMITS` (full) | object | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | lines per section at ≥ 3,200 | +| `LIMITS` (full) | object | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | lines per section at ≥ 2,400 | | compact section limits | — | facts 6, in_flight 2, timeline 3, state 3, stats 1 | `serialize.ts` -> `sectionLimits` | lines per section at ≤ 1,100 | | line limits compact→full | — | app 60→120, trigger 180→240, facts 220→260, in_flight 90→120, timeline 100→140, state 100→150, stats 110→140 | `serialize.ts` -> `sectionLimits` | per-line truncation | | last-resort fact/trigger floor | — | 60 chars | `serialize.ts` -> `toJevState` | pathological over-budget case | | `COMPACT_QUESTIONS_BUDGET` | number | 1400 | `situation/questions.ts` | bare labels/names at or below | | `COMPACT_DESC_MAX` | number | 24 | `situation/questions.ts` (private) | vocabulary override kept in compact mode | +| `TRIGGER_DESCRIPTIONS` | object | `delivery`: deliver / discard / defer texts | `situation/questions.ts` | trigger-specific option descriptions | | `MAX_FACTS` | number | 12 | `situation/facts.ts` | facts kept before budgeting | +| `PENDING_WINDOW_MS` | number | 10000 | `situation/conflicts.ts` | pending-local-change window | | plugin fact length | — | 240 | `build.ts` -> `buildSituation` | plugin fact truncation | -| phrase truncations (before line limits) | chars | `opLabel` phrase 90; in-flight phrase 80; error trigger message 120 (`Situation.subject` 80); timeline start/end phrase 80, write summary 110, error 100, navigate 60, GenClass action 100, custom name/summary 60/60, storage key 40; state value 90 (`describe`), store-level `describe` 110 | `describe.ts`, `build.ts` | text shape | -| timeline candidates | — | last 96 events | `build.ts` -> `timelineLines` | events considered | -| auto budget | — | webgpu/unknown 3,200; wasm `1000 + round((t−1)·1000/3)`, t ∈ 1..4 | `runtime.ts` -> `situationBudget` | device-sized situations | +| phrase truncations | chars | `opLabel` phrase 90; in-flight phrase 80; error trigger message 120; timeline: op phrases 80, write summaries 110, error messages 100, nav 60, custom events 60, storage keys 40 | `describe.ts`, `build.ts` | text shape | +| timeline candidates | — | last 96 events | `build.ts` | events considered | +| auto budget | — | webgpu/unknown 2,400; wasm `1000 + round((t−1)·1000/3)`, t ∈ 1..4 | `runtime.ts` -> `situationBudget` | device-sized situations | | `budgetScale` | number | 1, ×0.8 per `max_tokens_exceeded`, floor 0.5 | `runtime.ts` | shrinks auto budgets only | +| default mode | string | `observe` (since f3636b2) | `runtime.ts` | answers reported, no action runs | | `MAX_ARRAY_SEGMENTS` | number | 64 | `model/serialize.ts` | array states | -| `DEFAULT_NOUL/CHOICE/SCORE_INSTR` | string | see step 3.5 | `model/serialize.ts` | empty instructions | -| `Packer.maxPositions` | number | `meta.max_len` ?? 1536 | `packer.ts`, `engine.ts` | positions limit | -| `Packer.maxTotal` | number | `meta.max_total` ?? 8192 | `packer.ts`, `engine.ts` | whole-sequence limit | +| `Packer.maxPositions` / `maxTotal` | number | `meta.max_len` ?? 1536 / `meta.max_total` ?? 8192 | `packer.ts`, `engine.ts` | length limits | | packer text cache / tokenizer word cache | number | 8192 / 20000 | `packer.ts` / `tokenizer.ts` | cleared when full | -| `MARKERS` | tuple | `[Q] [O] [L] [T] [F]` | `packer.ts` (= `tokenize_pack.MARKERS`) | head read points | +| `MARKERS` | tuple | `[Q] [O] [L] [T] [F]` | `packer.ts` | head read points | | `ID_SPACE` | number | 2^26 | `tokenizer.ts` | max token id | -| `K_BUCKETS` | list | 2, 3-5, 6-10, 11-30, 31-100, 101-255 | `calibrate.ts` | `by_bucket` keys | -| `BUCKET_CLAMP` | pair | [0.5, 5.0] | `calibrate.ts` | τ(K) clamp | +| `K_BUCKETS` / `BUCKET_CLAMP` | — | 2, 3-5, 6-10, 11-30, 31-100, 101-255 / [0.5, 5.0] | `calibrate.ts` | `by_bucket` keys / τ(K) clamp | | calibration defaults | number | `noul`/`choice`/`score` 1.0, `by_header` `{}` | `calibrate.ts` -> `parseCalibration` | missing keys | -| header-key cache | number | 4096 | `calibrate.ts` -> `headerKey` | — | -| `Precision` default | string | `"exact"` | `engine.ts` | `"round"` = 2 dp half-even | | policy thresholds | number | report 0.6, guard 0.9, heal 0.8 | `decide/policy.ts` | gate on calibrated probabilities | | `W` | object | area 1.0, horizonMs 10000, finalMs 15000, finalClient 4.0, serverItem 25.0, serverField 6.0, shownError 1.5, uncaught 1.0, relation 0.8, relationFinal 2.0, wasted 0.08, latency 0.25 | `sim/src/oracle/cost.ts` | run cost | | `LABEL` | object | tier {passive 0, guard 0.25, heal 0.5}, exactTie 1.5, tieEps 0.05, tau0 0.1, seMul 1.0 | `sim/src/oracle/cost.ts` | soft action label | -| futures K / adaptive gain | number | 3 / > 0.05 | `trajectory.ts` -> `pointCosts` | label sharpness | -| `TRIGGER_W` | object | see step 9.3 | `trajectory.ts` | decision point sampling | -| sim CLI defaults | — | rows 1000, seed 1, workers 4, max-points 6, test-keep 0.33, explore 1, ask on | `sim/src/gen.ts` -> `parse` | generation | +| futures K / adaptive gain | number | 3 / > 0.05 (S2: future 1 always) | `trajectory.ts` -> `pointCosts` | label sharpness | +| `S1_GAP` | number | 1.0 | `trajectory.ts` | S1 diagnosis rule threshold | +| `DENSE_K` | number | 600 | `trajectory.ts` | gold points only among the first 600 decisions | +| `maxUnlabeled` | number | 40 | `trajectory.ts` (`GenOptions`) | unlabeled rows per trajectory | +| `TRIGGER_W` | object | mutation 1, delivery 1.2, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2 | `trajectory.ts` | decision point sampling | +| sim CLI defaults | — | rows 1000, seed 1, workers 4, max-points 6, test-keep 0.33, explore 1, ask on, mode gold | `sim/src/gen.ts` -> `parse` | generation | +| `SIM_S2` / `SIM_PROBE` / `SIM_FEATURE_HOLDOUT` | env | on / off / on | `latent.ts` / `oracle/probe.ts` / `scenario.ts` | S2 re-draws; probe meta; feature hold-out | | scenario budgets | weights | 3200:40, 2000:30, 1000:30 | `sim/src/world/scenario.ts` | `meta.budget` | +| clean-run share | prob | 0.05 | `scenario.ts` -> `buildScenario` | `meta.clean` | | transform | prob | unchanged 0.5; drop 0.12 (≥ 3 options); shuffle 0.5 | `sim/src/run/transform.ts` | option order/subsets | -| sim gate thresholds | number | report 0, guard 0.5, heal 0.5; `requireDiagnosis: false` | `sim/src/run/rt.ts` | forced action runs exactly | +| sim gate thresholds | number | report 0, guard 0.5, heal 0.5; `requireDiagnosis: false` (on-policy: runtime defaults) | `sim/src/run/rt.ts` | forced action runs exactly | +| `rt.BUDGETS` | weights | 2400:0.35, 2000:0.2, 1667:0.05, 1333:0.05, 1000:0.35 | `training/curriculum/rt.py` | runtime-exact curriculum budgets | +| `P_DELIVERY` | prob | 0.5 | `training/curriculum/rt.py` | mutation scenarios rendered as delivery | | eval `THRESH` | number | guard 0.9, heal 0.8 | `training/eval_runtime.py` | must mirror the runtime | | eval calibration fit | — | τ ∈ [0.2, 5]; noul grid 61; by_header ≥ 300 examples; ECE 15 bins | `training/eval_runtime.py` | `calibration.json` | +| T1 | — | premiums guard 0.25 / heal 0.5, clip ±30, `--tau` | `training/t1_relabel.py` | gain labels | | export | — | opset 17, block 32, `max_total` 8192, parity requests ≤ 1,500 tokens, `--n-per-file` 40 | `training/export_runtime.py` | model directory | -| `CARD_FORMAT` | string | `genclass-runtime-model/1` | `loader.ts`, `export_runtime.py` | card format (written, not validated on read) | -| `DEFAULT_CACHE_NAME` | string | `genclass-runtime-v1` | `loader.ts` | Cache Storage bucket for model files | -| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | where the card is fetched (package unpublished) | -| export `OUTPUTS` | list | `choice_logits, score_logits, noul_logits` | `export_runtime.py` | `meta.outputs` | -| export CLI | — | `--name genclass-runtime`, `--version 0.1.0`, `--n-per-file 40`, `--opset 17`, `--threads 16`, `--block 32` | `export_runtime.py` -> `main` | model directory | -| eval CLI | — | `--split test`, `--batch 16`, `--threads 32`; `N_BINS` 15 | `eval_runtime.py` -> `main` | report / calibration | +| `CARD_FORMAT` | string | `genclass-runtime-model/1` | `loader.ts`, `export_runtime.py` | written, not validated on read | +| `DEFAULT_CACHE_NAME` | string | `genclass-runtime-v1` | `loader.ts` | Cache Storage bucket | +| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | unpublished (404) | | `--p-runtime` / `GC_P_RUNTIME` | float | 0.0 (`cur4`: 0.8) | `training/curriculum/generate.py` | share of runtime-exact decision rows | -| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` -> `realRuntimeFactory` | runtime module the sim imports | -| `GENCLASS_MODEL_DIR` | env | `<repo>/.cache-model` | `packages/runtime/test/model/helpers.ts` | model directory for parity tests; fixtures come from it when it ships `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, else from `test/fixtures/model/` (v0.1) | -| sim runtime options | — | `historySize` 500, `holdBudgetMs` 1e9, `maxActionsPerMinute` 1e9, `report: "silent"` | `sim/src/run/rt.ts` -> `createOptions` | no time/rate limits on forced actions | +| `GC_RT_BUDGET` | env | unset | `training/curriculum/rt.py` -> `render` | render every runtime row at one budget (analysis) | +| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` | runtime module the sim imports | +| `GENCLASS_MODEL_DIR` | env | `<repo>/.cache-model` | `packages/runtime/test/model/helpers.ts` | model directory for parity tests | ## Invariants and gotchas -- **Parity chain:** runtime text → `JSON.stringify` (sim row) → Python `serialize.py` → `tokenize_pack.Packer` → PyTorch. On the serving side: runtime text → `toJsonValue` → `model/serialize.ts` → `Packer` (TS) → ORT. Both sides must produce identical token ids. Do not "improve" `pyStrip`, `pyNumber`, `entryText`, the item `label: desc` rule or marker placement on one side only. -- **JS numbers vs Python floats:** JS can only print `25`, never `25.0`. Rows produced in Python must write integral floats as ints (`fmt.js_numbers`). Otherwise the model trains on text the runtime never sends. `test/model/helpers.ts` -> `pythonOnlyFloatRequests` skips such fixtures. -- **Two different compact constants:** `COMPACT_BUDGET` (1,100) shapes sections, while `COMPACT_QUESTIONS_BUDGET` (1,400) bares the questions. Budgets in (1,100, 1,400] get almost-minimal sections plus bare questions. -- **`facts` floor is 1:** the shrink loop never removes the last fact, so the trigger sentence plus one fact (when there was any) always survive; in the pathological case both may be shortened to 60 chars. -- **Display ≠ model text:** `stateText` (STATUS.md, `explain()`, devtools) indents list items. The model reads `key: line1\nline2`. -- **Qids are invisible to the model:** only headers and items are tokenized. Renaming a qid changes nothing for the model but breaks `answers.action`/`answers.diagnosis` lookups. A header change, by contrast, changes the text *and* the `by_header` key. -- **Option order is irrelevant to the model** (isolation), but it decides the order of `probabilities` and the tie-break of `choice`. Plain-object criteria with integer-like labels are reordered by JS. Pass a `Map` to keep the order. -- **Question order:** `diagnosis` comes before `action` in runtime situations. The curriculum swaps it in 15% of varied rows. Answers do not depend on it. -- **`action` is absent when only one action applies:** consumers must treat a missing `answers.action` as passive (`onDecision` does). -- **The runtime never truncates inside the model host:** a situation that does not fit throws `max_tokens_exceeded`, the decision fails open, and auto budgets shrink by 20% (to ≥ 50%). Training drops (does not truncate) questions whose block does not fit `--max-len`. -- **Length semantics differ:** the runtime bounds state + longest branch (`max_len`). The trainer's `pack_split` bounds state + the whole question block per sequence. A many-option question can be valid at runtime yet never have been trained. -- **Markers and specials are read from files:** a re-pruned tokenizer moves ids, and `meta.json` must agree with `tokenizer.json` or loading fails (`ModelUnsupportedError`). -- **Calibration keys are text-sensitive:** any change to an instruction string orphans its `by_header` entry. Shipped files have `by_header: {}`, so this matters only if `--header-calibration` is used. -- **The gate uses probabilities, not `confidence`:** recalibrating changes intervention rates. Re-run `eval_runtime.py` with the new file and compare FIR/precision before shipping. -- **The sim needs thresholds 0.5:** the decider answers with probability 1 on the forced action, so the permitted mass is 1 or 0. A threshold of 0 would run the argmax non-passive action even when passive is forced (comment in `sim/src/run/rt.ts`). -- **Sim determinism:** the counterfactual prefix check compares `JSON.stringify([trigger, state, questions])` for every decision up to k. Any nondeterminism in situation building (time, random ids, iteration order) shows up as `prefix-mismatch` drops. `situation()` must stay side-effect free. -- **`x-request-id` is the sim's correlation header:** the runtime excludes it from request identity and never serializes it. `sim/test/rows.test.ts` asserts it never appears in a state. +- **Parity chain:** runtime text → `JSON.stringify` (sim row) → Python `serialize.py` → `tokenize_pack.Packer` → PyTorch. Serving side: runtime text → `toJsonValue` → `model/serialize.ts` → `Packer` (TS) → ORT. Both sides must produce identical token ids. Do not "improve" `pyStrip`, `pyNumber`, `entryText`, the item `label: desc` rule or marker placement on one side only. +- **Data and model are tied to a format tag.** Round-1 data (SIM phase A/B, `gold-r1x`, REAL pilots) and R17-final1 are `situation-v1`; the runtime now emits `situation-v2` (delivery trigger, 2,400 budget, new facts and wording). Never mix v1 rows into v2 training without accepting the text mismatch, and never ship a v1 model as the v2 default. Check `meta.runtime` / batch manifests. +- **JS numbers vs Python floats:** JS prints `25`, never `25.0`. Python-produced rows must write integral floats as ints (`fmt.js_numbers`). +- **Two different compact constants:** `COMPACT_BUDGET` (1,100) shapes sections, `COMPACT_QUESTIONS_BUDGET` (1,400) bares the questions. Budgets in (1,100, 1,400] get almost-minimal sections plus bare questions. +- **Section limits saturate at 2,400, the char budget does not.** A 3,200 budget (40% of SIM scenarios) has the same section/line limits as 2,400 but more room before the shrink loop drops lines; production webgpu situations are 2,400. See Drift. +- **`facts` floor is 1:** the shrink loop never removes the last fact. +- **Display ≠ model text:** `stateText` indents list items. The model reads `key: line1\nline2`. +- **Qids are invisible to the model:** renaming a qid changes nothing for the model but breaks `answers.action`/`answers.diagnosis` lookups. A header change changes the text *and* the `by_header` key. +- **Same action name, different text per trigger:** `deliver`, `discard` and `defer` read differently under `delivery` (`TRIGGER_DESCRIPTIONS`). A `vocabulary.actions` override is per name and wins over the trigger text in every trigger, so an app (or the sim) overriding `discard` changes the delivery description too. +- **Sim action paraphrases are failure/mutation-flavoured:** `ACTION_PARA.deliver` ("let the application see the failure", …) and `ACTION_PARA.discard`/`defer` ("throw this write away …") are chosen per trajectory by name, so in paraphrased trajectories delivery rows carry those texts instead of the delivery descriptions (`actionDescription` precedence). Runtime defaults never produce them. +- **Option order is irrelevant to the model** (isolation), but decides the order of `probabilities` and the tie-break of `choice`. Pass a `Map` to keep integer-like labels in order. +- **`action` is absent when only one action applies.** Consumers treat a missing `answers.action` as passive. A delivery always has at least `deliver` and `discard` (`discard` is always applicable), so delivery situations always carry an `action` question. +- **No truncation inside the model host:** an oversize situation throws `max_tokens_exceeded`, the decision fails open, and auto budgets shrink by 20% (to ≥ 50%). Training drops (does not truncate) questions whose block does not fit `--max-len`. +- **Length semantics differ:** the runtime bounds state + longest branch; the trainer's `pack_split` bounds state + the whole block per sequence. +- **Markers and specials are read from files:** `meta.json` must agree with `tokenizer.json` or loading fails. +- **The gate uses probabilities, not `confidence`.** Recalibrating changes intervention rates; with T1 gain-shaped labels the summed-mass gate becomes approximately an expected-gain gate (`t1_relabel.py` docstring: gain ≥ τ·ln 4 / τ·ln 9 for one dominant action). +- **The default mode does not change the text.** `observe` vs `guard` vs `heal` changes only what runs, so data generated in `heal` mode (sim) is valid for an `observe` default. +- **The sim needs thresholds 0.5:** the decider answers with probability 1 on the forced action. On-policy runs instead use the production gate (`production: true`). +- **Sim determinism:** the counterfactual prefix check compares fingerprints of every decision up to k. Nondeterminism in situation building shows up as `prefix-mismatch` drops; S2 latents that change the observed prefix fall back to `noLatent`. `situation()` must stay side-effect free (it caches `op.reads` only). +- **Delivery diagnoses are post-hoc in the sim:** filled from the first write the delivery caused, after the run. Exploration on delivery uses ε/2 because the diagnosis is unknown at decision time. +- **Unlabeled rows have no `action` label and no S1:** the `action` question is packed but unsupervised until `label_teacher.py` fills it. Do not compute action accuracy on them. +- **`x-request-id` is the sim's correlation header:** never serialized (`sim/test/rows.test.ts`). - **Description vs effect:** the `rollback` description says "last consistent snapshot", but transition/error rollback restores only the op chain's own writes. Changing the text is a model-input change. -- **SIM action labels are never label-smoothed:** they are always `{type: "choice", dist}`, which `parse_target` marks soft even when one-hot. Converting them to `label` would change the loss. -- **`budgetScale` only shrinks:** each `max_tokens_exceeded` multiplies it by 0.8 (floor 0.5) and nothing resets it for the life of the runtime (`runtime.ts`). Numeric `situation.budget` values are never scaled. -- **Standing question id `action`:** it is skipped only when the built-in `action` question exists. With ≤ 1 applicable action (only the passive one, which is always applicable) it is inserted, and `onDecision` copies its `probabilities` into the decision as if they were action probabilities. The gate still runs nothing (no non-passive action is offered), but reports are misleading. Avoid standing-question ids `action`/`diagnosis`. -- **`situation()` is almost side-effect free:** `env.ts` notes it caches field versions in `op.reads`. Anything more breaks the sim's prefix fingerprints. -- **Varied curriculum headers ≠ runtime headers:** `fmt.ACTION_INSTR`/`DIAG_INSTR` never produce `What is happening here?` or the runtime's failure/inconsistency/transition headers. If `--p-runtime` is 0, the model never sees those exact strings from the curriculum (SIM rows still carry them). -- **Python vs JS number text in `rt.py`:** Python `f"{x:.2f}"` rounds exact binary ties half-even, while JS `toFixed(2)` rounds them up (125 ms → Python `0.12s`, JS `0.13s`; 12.25 s → `12.2s` vs `12.3s`). `rt.py`'s `secs`, `rel` and `fmt_num` therefore differ from `util.ts` on such values. `secs` ≥ 1000 s and `ratio` ≥ 10× also use Python `round()` (banker's) where `util.ts` uses `Math.round`. This affects runtime-exact curriculum rows only; SIM rows record the runtime's own text. -- **Truncation units:** `util.truncate` counts UTF-16 code units, `rt.py.truncate` counts code points. They differ only for astral-plane characters (emoji), and the TS cut can split a surrogate pair (behaviour downstream of a lone surrogate is unverified). +- **SIM action labels are never label-smoothed:** always `{type: "choice", dist}`. +- **Varied curriculum headers ≠ runtime headers:** `fmt.ACTION_INSTR`/`DIAG_INSTR` never produce `What is happening here?`, the delivery header, or the runtime's failure/inconsistency/transition headers; only `rt.render` rows (and SIM/REAL rows) carry them. +- **Python vs JS number text in `rt.py`:** Python `f"{x:.2f}"` rounds exact binary ties half-even, JS `toFixed(2)` rounds them up; `rt.py`'s `secs`, `rel` and `fmt_num` differ from `util.ts` on such values. Affects runtime-exact curriculum rows only. +- **Truncation units:** `util.truncate` counts UTF-16 code units, `rt.py.truncate` counts code points. ## How to change it safely ### Versioning: what invalidates the trained model -`situation-v1` is a git tag on commit 1a77558 ("Runtime fix batch 3", 2026-10-07). It freezes the text the SIM final data (phase A: train 448,420 / dev 14,613 / test 137,643, per `training/LOG.md`) and the final training round were built on. At 654d822, `packages/runtime/src`, `jev_local/` and `scripts/genclass_export.py` are unchanged since the tag. The sim changed after the tag in 59c213f: correlation header `x-sim-op` → `x-request-id` (excluded from request identity), sim thresholds 0 → 0.5, 1-thread budget 1100 → 1000, resumable parts. Phase A rows carry budgets 1000/2000/3200 (`training/LOG.md`), so at least the budget change was in effect. Whether the other changes were in effect when phase A was generated is (unverified). The same commit changed the training side: `training/curriculum/rt.py` was re-ported to the frozen `situation-v1` wording (relation phrasing such as "started 0.09s after #6", "pending local change" fact, error-rate text, slug-id signatures, budget-shaped sections via `section_limits`/`to_state`; compact questions and `transient` were already in `rt.py` before the tag, at a53dd38), `fmt.js_numbers` was added and applied in `generate.py`, and `eval_runtime.py` gained `by_budget`. `cur4` (300k rows, seed 5, 80% runtime-exact) was generated with that wording (`training/LOG.md`). Curriculum sets made earlier (`cur1`, `cur2`, `cur3`) predate it. +| tag | commit | what it froze | data / models on it | +|---|---|---|---| +| `situation-v1` | 1a77558 ("Runtime fix batch 3", 2026-10-07 19:19 -0400) | v1 text: no `delivery`, held mutations, 3,200 budget | SIM phase A (600,676 rows) and B (1,415,344), `gold-r1x` (832,279), REAL pilots, `cur4`; round-1 models R17/R32-final1 | +| `situation-v2` | 6e5e86e ("Runtime batch 5 …; freeze situation-v2", 2026-10-07 23:26 -0400) | v2 text: `delivery` trigger + descriptions, non-blocking mutations, newer-data/pending conflicts, F1–F3, F5–F7, F9, read-your-writes, leaf-field redaction, diff previews, 2,400 budget | SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL v2 batches (`v2-pilot`, `v2b1–3`), `rt.py` port (d73d20c); no model yet | + +Since `situation-v2`, `packages/runtime/src/situation`, `util.ts`, `state/` and `learn/` are unchanged at b435acb; the only `src` changes are f3636b2 (default mode, devtools labels, `InitOptions.mode` JSDoc), none of them model text. The model side (`src/model`, `jev_local`, `scripts/genclass_export.py`, `export_runtime.py`, the parity fixtures) is unchanged since `situation-v1`, so a v2 export uses the same packer/tokenizer/graph contract. | change in … | invalidates | required follow-up | |---|---|---| -| `situation/{build,facts,describe,serialize,questions}.ts`, `util.ts` formatting/redaction, `state/hub.ts` change summaries, signature normalization, baselines/profiles numbers that appear in text | model input text | regenerate SIM data, re-port `training/curriculum/rt.py`, retrain, re-eval, re-export; new freeze tag | -| `DEFAULT_DIAGNOSES`, `BUILTIN_ACTIONS` descriptions, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `TRIGGER_ACTIONS` membership/order, compact thresholds | model input text and label space (and `by_header` keys) | same as above; also update copies in `sim/src/types.ts` (`PASSIVE`, `DIAGNOSES`), `sim/src/world/scenario.ts` (`DEFAULT_DIAGNOSES`, `DIAG_PARA`), `sim/src/run/transform.ts` (`ACTION_PARA`), `sim/src/oracle/cost.ts` (`TIER`), `fmt.py`, `rt.py`, `eval_runtime.py` (`TIER`, `PASSIVE`) | -| `sectionLimits`, `STATE_CHAR_BUDGET`, auto budget mapping, scenario budget weights | situation length distribution | regenerate data, retrain; check token percentiles vs `max_len` | -| triage / trigger conditions (`learn`, `runtime.ts`) | which situations get recorded (distribution), not text | regenerate data; retrain recommended | +| `situation/{build,facts,conflicts,content,evidence,describe,serialize,questions}.ts`, `util.ts` formatting/redaction, `state/fields.ts` change text, `state/hub.ts` change summaries, signature normalization, baselines/profiles/cadence numbers that appear in text | model input text | regenerate SIM and REAL data, re-port `training/curriculum/rt.py`, retrain, re-eval, re-export; new freeze tag (`situation-v3`) | +| `DEFAULT_DIAGNOSES`, `BUILTIN_ACTIONS`, `TRIGGER_DESCRIPTIONS`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `TRIGGER_ACTIONS` membership/order, compact thresholds | model input text and label space (and `by_header` keys) | same as above; also update copies in `sim/src/types.ts` (`PASSIVE`, `DIAGNOSES`), `sim/src/world/scenario.ts` (`DEFAULT_DIAGNOSES`, `DIAG_PARA`), `sim/src/run/transform.ts` (`ACTION_PARA`), `sim/src/oracle/cost.ts` (`TIER`), `sim/scripts/relabel.py`, `fmt.py`, `rt.py`, `eval_runtime.py` (`TIER`, `PASSIVE`), `t1_relabel.py`/`eval_gain.py` (`PREM`), `label_teacher.py` (`PASSIVE`), realapps harness ([realapps.md](realapps.md)) | +| a new trigger | text, label space, sim correlation | everything above plus `TriggerKind` in `sim/src/types.ts`, sim `TRIGGER_W`, exploration, `diagnose.ts`, `runner.ts` correlation, `rt.py` rendering | +| `sectionLimits`, `STATE_CHAR_BUDGET`, auto budget mapping, scenario/curriculum budget weights | situation length distribution | regenerate data, retrain; check token percentiles vs `max_len` | +| triage / salience (`learn`, `runtime.ts`, delivery salience) | which situations get recorded (distribution), not text | regenerate data; retrain recommended | | `model/serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts`, `FEEDS` | token ids | change `jev_local` in lockstep, re-run parity tests; retrain if the Python side changed | | `tokenizer.json` (pruning), heads, graph inputs/outputs | the model | retrain/re-export; `meta.json` `inputs`/`outputs`/`markers` | | `calibrate.ts` math or `calibration.json` | answers, not text | re-run `eval_runtime.py`; check `calibrate.test.ts` parity | -| `sim/src/oracle/{cost,diagnose}.ts`, `trajectory.ts`, `transform.ts`, `ask/questions.ts`, `scenario.ts` splits/vocab | labels/targets | regenerate data, retrain (`meta.cost_futures` lets you re-derive action labels offline without re-simulating) | -| `training/curriculum/{rt,fmt,rows}.py`, scenario modules | curriculum text/labels (training distribution, not runtime text) | regenerate the curriculum set (e.g. a new `curN`), update the mixture, retrain; `rt.py` must still equal the runtime's text | -| `eval_runtime.py` metrics, `export_runtime.py` graph surgery/quantization | evaluation numbers / the ONNX files, not the trained weights | re-eval or re-export; re-run `test_export_runtime.py`, `ortweb/validate.mjs`, the runtime parity tests | -| `decide/policy.ts` thresholds, host/loader/worker, `EvaluateRequest.subject/priority/timeoutMs` | nothing the model sees | mirror the gate in `eval_runtime.py` if the gate changes | +| `sim/src/oracle/{cost,diagnose}.ts`, `trajectory.ts` (S1), `latent.ts` (S2), `transform.ts`, `ask/questions.ts`, `scenario.ts` splits/vocab | labels/targets | regenerate data, retrain (`meta.cost_futures` lets you re-derive action labels offline: `sim/scripts/relabel.py`, `t1_relabel.py`) | +| `training/curriculum/{rt,fmt,rows}.py`, scenario modules | curriculum text/labels | regenerate the curriculum set, update the mixture, retrain; `rt.py` must still equal the runtime's text | +| `eval_runtime.py`/`eval_gain.py` metrics, `export_runtime.py` graph surgery/quantization | evaluation numbers / the ONNX files | re-eval or re-export; re-run `test_export_runtime.py`, `ortweb/validate.mjs`, the runtime parity tests | +| `decide/policy.ts` thresholds, default mode, host/loader/worker, `EvaluateRequest.subject/priority/timeoutMs` | nothing the model sees | mirror the gate in `eval_runtime.py`/`eval_gain.py` if the gate changes | ### Recipes 1. **Change wording the model reads** (a fact, sentence, description or instruction): 1. Edit `packages/runtime/src/situation/*`. - 2. Update `test/situation.test.ts`/`test/budget.test.ts` expectations and the STATUS.md examples. - 3. Mirror the change in `training/curriculum/rt.py`. - 4. Regenerate SIM data (`bash sim/scripts/final.sh a`) (ask the user first). - 5. Retrain, then run `final_post.sh` (eval → calibration → export). - 6. Tag a new freeze. Coordinate with SIM and TRAIN first (`training/NEEDS.md` item 5). -2. **Add a diagnosis label:** - 1. Add it to `DEFAULT_DIAGNOSES` (order = option order; `expected` stays first). - 2. Teach the sim to emit it (`sim/src/oracle/diagnose.ts`). - 3. Add it to `sim/src/types.ts` -> `DIAGNOSES`, `scenario.ts` -> `DEFAULT_DIAGNOSES`/`DIAG_PARA`, `fmt.py` -> `DIAG_DESC` (`fmt.DIAGNOSES` is derived from it), `rt.py` -> `DIAGNOSES`. - 4. Regenerate data and retrain. Without retraining the model never picks it reliably. -3. **Add a built-in action:** - 1. Add it to `BUILTIN_ACTIONS` + `TRIGGER_ACTIONS` + `builtinApplicable` + the executor ([decide-policy-actions.md](runtime/decide-policy-actions.md)). - 2. Add its tier to `cost.ts` `TIER`, `fmt.TIER`, `eval_runtime.TIER`, `ACTION_PARA`, `fmt.ACTION_DESC`, `fmt.TRIGGER_ACTIONS`, `rt.py` `ACTIONS`/`TRIGGER_ACTIONS`, `eval_runtime.PASSIVE` and `sim/src/types.ts` -> `PASSIVE` (passive actions), and `sim/src/run/fake-runtime.ts` (`ACTIONS`/`DESC`, tests only). - 3. Make the sim able to force it, then regenerate and retrain. -4. **Standing questions (from `rt.question` or a plugin) or custom actions** need no retrain to run: the model reads the description. Quality is unmeasured, though. Check with `runtime.ask`/the demos. -5. **Change budgets or limits:** keep `rt.py` `section_limits`/`to_state` identical, including JS half-up rounding. Check token lengths: TRAIN measured about 2.4 chars/token (`training/NEEDS.md` 6a), so 3,200 chars ≈ 1,300+ tokens. -6. **Re-calibrate only:** `eval_runtime.py --fit-split dev --write-calibration cal.json`, then `export_runtime.py --calibration cal.json`. No retrain. The text does not change, so the freeze is unaffected. -7. **Change `max_len`:** train with `--max-len N`. The export copies it into `meta.json`, so the runtime positions limit follows automatically. -8. **Tests to run** (runtime vitest runs locally under the run policy in AGENTS.md; ask the user before the sim tests, training pytest, `validate.mjs` and anything that needs a model download; see [where to run things](runtime/build-test-release.md#where-to-run-things)): - - `packages/runtime`: `vitest run test/situation.test.ts test/budget.test.ts test/model/` (model parity tests read `GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`, filled by `genclass-runtime fetch-model`; with a new export, its own `requests.json`/`pack_fixtures.json`/`torch_fixtures.json` replace the v0.1 fixtures automatically). - - `sim`: `vitest run test/rows.test.ts test/determinism.test.ts test/oracle.test.ts`. - - `training/tests/test_curriculum.py`, `training/tests/test_export_runtime.py`. + 2. Update `test/situation.test.ts`/`test/budget.test.ts`/`test/delivery.test.ts`/`test/content.test.ts` expectations and the STATUS.md examples. + 3. Mirror the change in `training/curriculum/rt.py` (and `test_curriculum.py`). + 4. Regenerate SIM and REAL data (ask the user first; cluster runs are Mehar's: see [sim.md](sim.md), [realapps.md](realapps.md)). + 5. Retrain, eval, calibrate, export. Tag a new freeze. Coordinate first (`HANDOFF.md`: "The training format is frozen at `situation-v2`"). +2. **Add a diagnosis label:** add it to `DEFAULT_DIAGNOSES` (`expected` stays first); teach `sim/src/oracle/diagnose.ts` (and S1 `diagnosisFromOutcome` if relevant); add it to `sim/src/types.ts` -> `DIAGNOSES`, `scenario.ts` -> `DEFAULT_DIAGNOSES`/`DIAG_PARA`, `fmt.py` -> `DIAG_DESC`, `rt.py` -> `DIAGNOSES`; regenerate and retrain. +3. **Add a built-in action:** `BUILTIN_ACTIONS` + `TRIGGER_ACTIONS` (+ `TRIGGER_DESCRIPTIONS` if its text differs per trigger) + `builtinApplicable` + the executor; tiers/passives in every copy listed in the versioning table, `ACTION_PARA`, `fmt.ACTION_DESC`, `fmt.TRIGGER_ACTIONS`, `rt.py` `ACTIONS`/`TRIGGER_ACTIONS` (and `DELIVERY_ACTION` if it maps), `sim/src/run/fake-runtime.ts`; make the sim able to force it; regenerate and retrain. +4. **Standing questions or custom actions** need no retrain to run: the model reads the description. Quality is unmeasured; check with `runtime.ask`/the demos. +5. **Change budgets or limits:** keep `rt.py` `section_limits`/`to_state` identical (JS half-up rounding) and update `rt.BUDGETS` and the sim's scenario budget weights together. TRAIN measured about 2.4 chars/token, so 2,400 chars ≈ 1,000 tokens. +6. **Re-calibrate only:** `eval_runtime.py --fit-split dev --write-calibration cal.json`, then `export_runtime.py --calibration cal.json`. No retrain; the freeze is unaffected. +7. **Relabel without regenerating:** `sim/scripts/relabel.py` (new τ/premiums for the soft dist) or `training/t1_relabel.py` (gain labels) on rows that carry `meta.cost_futures`. +8. **Change `max_len`:** train with `--max-len N`; the export copies it into `meta.json`. +9. **Tests to run** (runtime vitest runs locally under the run policy in AGENTS.md; ask the user before the sim generator, training pytest that needs checkpoints, `validate.mjs` and anything that needs a model download; see [where to run things](runtime/build-test-release.md#where-to-run-things)): + - `packages/runtime`: `NODE_OPTIONS=--expose-gc npx vitest run test/situation.test.ts test/budget.test.ts test/delivery.test.ts test/content.test.ts test/model/` (model parity tests read `GENCLASS_MODEL_DIR`; `test/model/{packer,serialize,calibrate,engine}.test.ts` contain the conditional skips, and the lead's local run reported 14 skipped model-parity tests without a model directory). + - `sim`: `SIM_RUNTIME=real npx vitest run test/rows.test.ts test/determinism.test.ts test/oracle.test.ts test/latent.test.ts` (the lead's whole-suite run `SIM_RUNTIME=real npx vitest run` saw 19 passed in 5 files, the fifth being `test/loop.test.ts`). + - `training/tests/test_curriculum.py` (`test_runtime_rows_situation_v2` is pure Python), `training/tests/test_export_runtime.py`. - `training/ortweb/validate.mjs <export dir> q8`. ## Tests | test file | what it asserts | |---|---| -| `packages/runtime/test/situation.test.ts` | one situation per trigger (mutation, request, failure, stall, inconsistency, transition, error): key order, section caps (facts ≤ 12, timeline ≤ 16, state ≤ 8), `stateChars` ≤ 3,200, a `diagnosis` question, and regexes on selected facts (not the whole text; the full text is printed with `console.log`, which is where the STATUS.md examples come from); `ask`: `situation()` is side-effect free (same state twice, no new ops or events) and has trigger `ask`; serializer: an over-budget input stays ≤ 3,200 chars with `timeline: "none"`, an under-budget one keeps all 16 timeline lines and gives `"none"` for its empty sections; same scripted inputs → identical situations | -| `packages/runtime/test/budget.test.ts` | section limits compact 1,100 / full 3,200 / linear; every budget shapes sections and keeps top facts; compact questions keep ≤ 24-char overrides; determinism; auto budget 3,200 / 1,000–2,000; `max_tokens_exceeded` shrinks auto budgets | -| `packages/runtime/test/model/serialize.test.ts` | `state_segments`/`question_block` on edge cases vs Python fixtures; Python number printing; `json.dumps` separators; `str.strip` whitespace; JSON-round-trip semantics; situation-shaped states; `round` half-even | -| `packages/runtime/test/model/packer.test.ts` | identical ids/positions/groups/marker positions/question order vs the Python packer on the parity requests; plain-object criteria = Python-ordered Maps; special tokens stay text; marker ids from files, meta must agree; typed `max_tokens_exceeded` (positions vs total); Map label order, empty choices rejected; feed plan + unpack; HF tokenizer edge cases (full and pruned vocab); speed | -| `packages/runtime/test/model/calibrate.test.ts` | sha1 header keys = Python; reproduces PyTorch calibrated probabilities (< 1e-9); v1 and v2 files; confidence/score math; answer shapes and tie-break | -| `packages/runtime/test/model/engine.test.ts` | end-to-end TS packer → ORT (onnxruntime-node CPU, and onnxruntime-web 1.30 WASM single thread) → TS calibration vs PyTorch fixtures: within the export's own `parity.json` (agreement ≥ its count − 1, max logit diff < its value + 0.05) when the model directory has one, else ≥ 99% agreement and max logit diff < 1.0 (q8) / 0.1 (fp16); feeds exactly `meta.inputs` and rejects unknown ones | -| `packages/runtime/test/model/loader.test.ts`, `host.test.ts` | card parsing, plans, sha256 cache; host queueing/fail-open (see [model-host.md](runtime/model-host.md)) | -| `packages/runtime/test/browser/model.spec.ts`, `model-webgpu.spec.ts` (Playwright) | the model loads over WASM in a module worker and matches PyTorch, Cache Storage reuse, inline fallback, preload modes, WebGPU fallbacks (no adapter, no `shader-f16`, software adapter), latency at ~300–1,000 state tokens | -| `packages/runtime/test/fixtures/model/make_py_fixtures.py` | (generator, run on the VM) writes `py_fixtures.json` from jev_local `serialize`, HF `tokenizers`, `calibrate_logits` (v1 and v2 files) and `confidence` | -| `sim/test/rows.test.ts` | 40 trajectories produce valid CONTRACT-D rows: labels reference real options, dists sum to 1 (±0.01), noul p ∈ {0, 1}, score level in range, no `x-request-id` in states, passive-best share > 0.2, 0 prefix mismatches; splits hold out domains/families; transform renormalizes | +| `packages/runtime/test/situation.test.ts` | one situation per trigger (delivery: a stale response about to overwrite newer results; mutation: an older task's write not covered by a delivery decision; request, failure, stall, inconsistency, transition, error): key order, section caps, `stateChars` ≤ `STATE_CHAR_BUDGET` (2,400), a `diagnosis` question, regexes on selected facts (full text printed with `console.log` → STATUS.md); `ask` is side-effect free; serializer over/under-budget; determinism | +| `packages/runtime/test/budget.test.ts` | section limits compact 1,100 / `sectionLimits(1750)` = 9/4/10/6/3 / full 2,400 / `sectionLimits(3200)` = `sectionLimits(2400)`; 1,000/1,100/2,000 budgets shape a delivery situation and keep the version fact; compact questions keep ≤ 24-char overrides; determinism; auto budget 2,400 / 1,000–2,000; `max_tokens_exceeded` shrinks auto budgets (2,400 → 1,920) | +| `packages/runtime/test/delivery.test.ts` | delivery salience and enforcement: typeahead zero calls, stale out-of-order response → `discard` drops only the stale field, holding is latency only, no hold when the model cannot answer in time, background decisions and late revert, superseded queued decisions dropped, WebSocket order and pending-change revert, EventSource, XHR holds and abort | +| `packages/runtime/test/content.test.ts` | v2 facts: F3 (no call when unchanged), F1 field and item cells, F2 salience and diff preview, F9 stale marks, F6 cadence, F5 scope/offline/commit ambiguity, F7, F8, read-your-writes | +| `packages/runtime/test/default-mode.test.ts` | `createRuntime` and `GenClass.init` start in `observe` without `mode`; observe never holds writes or requests even when the model is sure, still reports findings, and never waits for the model (f3636b2) | +| `packages/runtime/test/model/serialize.test.ts` | `state_segments`/`question_block` vs Python fixtures; Python number printing; `json.dumps` separators; `str.strip`; JSON-round-trip semantics; `round` half-even | +| `packages/runtime/test/model/packer.test.ts` | ids/positions/groups/marker positions/question order identical to the Python packer; special tokens stay text; marker ids from files; typed `max_tokens_exceeded`; feed plan + unpack; HF tokenizer edge cases | +| `packages/runtime/test/model/calibrate.test.ts` | sha1 header keys = Python; calibrated probabilities = PyTorch (< 1e-9); v1 and v2 calibration files; confidence/score math | +| `packages/runtime/test/model/engine.test.ts` | TS packer → ORT (node CPU and web WASM) → TS calibration vs PyTorch fixtures within the export's `parity.json` (or fixed tolerances); feeds exactly `meta.inputs` | +| `packages/runtime/test/model/loader.test.ts`, `host.test.ts` | card parsing, plans, sha256 cache; host queueing/fail-open ([model-host.md](runtime/model-host.md)) | +| `packages/runtime/test/browser/model.spec.ts`, `model-webgpu.spec.ts` (Playwright; ask first) | WASM worker load and parity, Cache Storage, fallbacks, latency | +| `packages/runtime/test/fixtures/model/make_py_fixtures.py` | (generator, VM) writes `py_fixtures.json` from jev_local, HF `tokenizers`, `calibrate_logits`, `confidence` | +| `sim/test/rows.test.ts` | valid CONTRACT-D rows (labels reference options, dists sum to 1, …), no `x-request-id` in states, passive-best share > 0.2, 0 prefix mismatches, splits hold out domains/families; **S1:** a gold `expected` diagnosis never comes with `adjusted[passive] ≥ 1` when passive is not best | | `sim/test/determinism.test.ts` | same seed → identical rows and final states; forced replays reproduce every prefix | -| `sim/test/oracle.test.ts` | stale overwrite → discard best; single-point credit; intentional double add → passive/expected; duplicate POST → block/coalesce; outage → delay/serve_cached; benign concurrency → apply; sharp vs soft labels; exact ties favour passive | -| `training/tests/test_curriculum.py` | rows valid against the trainer's label parser and deterministic; held-out domains/templates only in test; label consistency; version semantics | -| `training/tests/test_export_runtime.py` | int8 embedding close and valid (zero rows survive); Gemm→MatMul rewrite preserves outputs; end to end: card bytes/sha256 match, meta markers/`cls_id`/`sep_id` = tokenizer added tokens, fp32 parity < 1e-3, R17 q8 < 12 MB | -| `training/tests/test_prune_vocab.py` | the pruned tokenizer's layout matches ettin, encodes every sample, and gives identical model outputs where tokenization is unchanged (needs the v1 checkpoint: `GC_V1_CKPT`, `GC_BASE_32M`) | -| `training/ortweb/validate.mjs` | (script: `node validate.mjs <export dir> [variant=q8] [maxRequests=60]`) onnxruntime-web WASM + node on the export, feeds from `pack_fixtures.json`, vs `torch_fixtures.json`; writes `<export dir>/ortweb_report_<variant>.json` (e.g. `ortweb_report_q8.json`; the script's header comment still says `ortweb_report.json`) | +| `sim/test/oracle.test.ts` | stale out-of-order response → **delivery** decision with `discard` best (was `mutation` in v1); single-point credit (`discard` vs `deliver`); benign concurrency asks nothing or prefers passive; duplicate POST → block/coalesce; outage → delay/serve_cached; sharp vs soft labels; exact ties favour passive | +| `sim/test/latent.test.ts` | S2: re-seeded futures re-draw only what lies after the decision (windows, user steps); hidden repeat intent drawn from its posterior in ideal runs only | +| `training/tests/test_curriculum.py` | rows valid against the trainer's parser and deterministic; held-out domains/templates; label consistency; **`test_runtime_rows_situation_v2`**: runtime-style rows fit 2,400 chars, delivery rows appear with "about to be delivered", action labels/passive map into the runtime's actions | +| `training/tests/test_export_runtime.py` | int8 embedding, Gemm→MatMul rewrite, end to end card bytes/sha256, meta markers = tokenizer, fp32 parity < 1e-3, R17 q8 < 12 MB | +| `training/tests/test_prune_vocab.py` | pruned tokenizer layout and identical outputs (needs `GC_V1_CKPT`, `GC_BASE_32M`) | +| `training/ortweb/validate.mjs` | onnxruntime-web WASM on an export vs `torch_fixtures.json`; writes `ortweb_report_<variant>.json` | ## Drift and open issues -- **MODEL_CARD.md** (`packages/runtime-model/MODEL_CARD.md`): - - It lists 9 diagnoses (no `transient`); the code has 10. - - It says the runtime acts when "`p(action) ≥ 0.9` (guard) / `0.8` (heal)". The code gates on the **summed** probability of the permitted non-passive actions (`decide/policy.ts` -> `gate`, mirrored in `eval_runtime.py`). - - Accuracy numbers are stage 1c; the shipping model is the final-round model ([EVAL.md](../../training/EVAL.md) "Final round 1" is "(in progress)"). -- **training/README.md**: - - §2 says "diagnosis (9 labels …)"; `fmt.DIAG_DESC` has 10. - - §4 says the gate is "non-passive top action, p ≥ 0.9 guard / 0.8 heal"; `eval_runtime.py` implements the summed-mass gate. -- **docs/runtime/CONTRACT.md §6**: - - It says the action instructions are "What should the runtime do with <subject>?". The code uses fixed per-trigger sentences without the subject (`ACTION_INSTRUCTIONS`). - - It gives the budget as "≤ 1,000 tokens; truncate timeline first, then state, then facts". The code uses characters (3,200 default, device-sized) and the 5-step shrink plus fact/trigger shortening. - - Its `runtime.situation()` shape omits `salient`, `facts`, `compact`, `budget`. -- **`types.ts` -> `InitOptions.situation` comment**: says "wasm 1,100 + 300 per extra thread … 2,000". The code gives 1,000 / 1,333 / 1,667 / 2,000 (`situationBudget`). STATUS.md and the tests match the code. -- **`serialize.ts` header comment**: assumes ≈ 3.2 chars/token. TRAIN measured 2.4 chars/token on SIM states (mean 963, p95 1,340, max 1,569 state tokens), so 3,200 chars ≈ 1.3–1.4× the intended 1,000 tokens (`training/NEEDS.md` 6a, open ASK). -- **sim/NEEDS.md preamble and STATUS.md "How to drive it headless"** show `thresholds {guard: 0, heal: 0}`. `sim/src/run/rt.ts` uses 0.5 (changed after the tag; see the gotcha). sim/NEEDS.md's note that `transient` is missing from `DEFAULT_DIAGNOSES` is stale. -- **`training/curriculum/rt.py` -> `to_state`**: the last-resort fact shortening floor is 40 chars (runtime 60), and the trigger is never shortened. This only matters when a single fact or the trigger exceeds the budget. -- **`rollback` description vs effect** (see gotchas): fixing it is a model-input change. -- **`docs/runtime/ARCHITECTURE.md`** lists diagnoses with `transient` before `slow`. The code order puts it last. Order affects only answer key order and tie-breaks. -- **Not published:** `@genclass/runtime-model@0.1.0`. The package directory holds only `MODEL_CARD.md`, so the default base URL cannot serve a model until OPEN_TASKS item 8 lands. OPEN_TASKS says the alpha takes no actions until then. -- **Open (OPEN_TASKS.md / training/NEEDS.md):** - - final training round 1 on phase A, then round 2 on A + B; - - choose R17 (WASM) vs R32 (WebGPU); - - device-based model selection in the card; - - clean-run rows (`meta.clean`) requested by TRAIN (ASK); - - thin `conflict`/`transition` classes; - - label noise on benign request rows (OPEN_TASKS: 66% of passive-best request rows put ≥ 0.9 on passive; phase A `sim/samples/stats-final-a.json` `label_sharpness.request.passive_mass_ge_0_9` = 0.676). -- **`meta.json.name`** is `<name>-<version>`, while the runtime reports `<card.name>@<card.version>` and ignores `pad_id` and, in practice, `meta.name` (an `Engine` fallback only; `backend.ts` -> `createEngine` always passes a name). This is harmless but confusing. -- **`training/curriculum/rt.py` vs `util.ts` number formatting** (see gotchas): half-even vs half-up on exact binary ties in `secs`/`rel`/`fmt_num`, so runtime-exact curriculum rows are not always byte-identical to the runtime. `rt.py.to_state` also uses Python `round(budget)` where the runtime uses `Math.round` (irrelevant for integer budgets). -- **`model/tokenizer.ts` header comment** says non-special added tokens are split out first and the normalizer runs on the rest; `Tokenizer.encode` normalizes the whole text first, then splits added tokens. Likely equivalent for the shipped NFC normalizer and ASCII added tokens (unverified; OPEN_TASKS.md reports packing identical to Python on all 50 v0.1 fixtures); it would matter for a normalizer that rewrites added-token text (e.g. `Lowercase` and `[unusedN]`). -- **`export_runtime.py` parity `gate08`/`gate09`** compare the max choice probability per question, not the runtime's summed non-passive mass gate. They are a proxy, not the product gate. -- **docs/runtime/CONTRACT.md §11** says option order/subsets and diagnosis paraphrases/subsets are randomised "per row". In code, order/drop is per row (`transformQuestions`) but description wording and diagnosis subsets are per trajectory (runtime `vocabulary` from `scenario.ts`). -- **MODEL_CARD.md status line** ("stage 1c final, stage 2 piloted on pre-freeze SIM data"; "`calibration.json` (per-kind temperatures)") predates final round 1; the per-kind part still matches what `final_post.sh` writes. +- **No situation-v2 model; npm default URL 404.** R17-final1 is `situation-v1` and exists only on the train VM / Mehar's Mac. `@genclass/runtime-model` is not published, so `DEFAULT_MODEL_BASE_URL` (and the CLI default) return 404; `@genclass/runtime@0.1.0-alpha.0` ships no model (and still defaults to `guard`; a 0.1.0-alpha.1 NaN-fix patch needs the owner's 2FA, OPEN_TASKS.md). Plan per HANDOFF: T150 teacher on v2 gold → teacher labels on unlabeled rows → distil R17 (default) and R32 → DAgger via `--on-policy` → EVAL → `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0`. Release procedure: [RELEASE.md](../../RELEASE.md) (Part A alpha.1, Part B model packaging and validation). +- **SIM scenario budgets still 3,200 / 2,000 / 1,000** (`scenario.ts`, comment "3,200 WebGPU"; sim/README.md says the same), while the runtime's webgpu/unknown auto budget is 2,400 and section limits saturate at 2,400. SIM v2 data never renders the production webgpu budget exactly, and its 3,200 rows are longer than anything a v2 runtime sends by default. `rt.py` `BUDGETS` uses 2,400. `training/PLAN-v1.md` ECE targets and MODEL_CARD latency still quote 3,200. +- **Sim action paraphrases on delivery** (gotchas): `ACTION_PARA` is keyed by action name, so paraphrased trajectories give delivery `deliver`/`discard`/`defer` failure- or write-flavoured descriptions; there is no delivery-specific paraphrase set. +- **`collect_gain.py` needs a gain head the repo does not have:** it reads `o.gain` from `heads(...)`, but `jev_local/engine/encoder/heads.py` -> `HeadOut` defines no `gain` field. The gain-head code (`r17-t1h`, `training/LOG.md` 03:00–03:12) presumably lives in the VM's `~/jev` (unverified). No T1 result exists on v1; T1 is to be rerun on v2 (`training/LOG.md` 03:32). +- **training/NEEDS.md "SIM → TRAIN: scaled data"** still says "Runtime tag `situation-v1`" for the scaled row types; the v2 runs (`v2-*`) are generated from `situation-v2` per HANDOFF and the claims table (manifests not checked here, unverified). +- **docs/runtime/CONTRACT.md:** §5 has no `delivery` trigger; §6 still says action instructions are "What should the runtime do with <subject>?" (code: fixed per-trigger sentences) and "≤ 1,000 tokens; truncate timeline first, then state, then facts" (code: 2,400 chars + 5-step shrink + fact/trigger shortening); its `runtime.situation()` shape omits `salient`, `facts`, `compact`, `budget`; §11 says option order/subsets and diagnosis paraphrases are randomised "per row" (code: order/drop per row, wording per trajectory). The §13 default-mode entry (from f3636b2) says "`situation-v1` training data stays valid"; the mode claim holds, but v1 data no longer matches the v2 text anyway. +- **MODEL_CARD.md:** lists 9 diagnoses (no `transient`); describes the gate as `p(action) ≥ 0.9/0.8` (code: summed permitted non-passive mass); lists actions without the delivery trio; says round-1 files are in `files/r17/` "here", but `packages/runtime-model/` contains only `MODEL_CARD.md`; latency is quoted at the v1 1,000/2,000/3,200 budgets. +- **HANDOFF.md** "Modes" line still says guard is the default (code since f3636b2: observe). +- **training/README.md:** §2 says "diagnosis (9 labels …)"; §4 describes the gate as "non-passive top action, p ≥ 0.9 / 0.8" (`eval_runtime.py` implements the summed-mass gate). +- **sim/NEEDS.md preamble** shows `thresholds {guard: 0, heal: 0}` (`rt.ts` uses 0.5) and says `transient` is missing from `DEFAULT_DIAGNOSES` (it is present). STATUS.md's headless block is now correct (0.5). +- **docs/runtime/ARCHITECTURE.md** lists diagnoses with `transient` before `slow`; code order puts it last (affects only answer key order and tie-breaks). +- **`training/curriculum/rt.py` -> `to_state`**: last-resort fact floor 40 chars (runtime 60), trigger never shortened; `round(budget)` vs `Math.round`; half-even number formatting (gotchas). Unchanged by the v2 port. +- **`rollback` description vs effect** (gotchas): fixing it is a model-input change. +- **`meta.json.name`** is `<name>-<version>`, while the runtime reports `<card.name>@<card.version>` and ignores `pad_id` and, in practice, `meta.name`. +- **`model/tokenizer.ts` header comment** describes added-token splitting before normalization; `Tokenizer.encode` normalizes first. Equivalent for the shipped NFC file (unverified for other normalizers). +- **`export_runtime.py` parity `gate08`/`gate09`** compare the max choice probability, not the summed-mass gate: a proxy only. +- **`eval_runtime.py` `PASSIVE`** has no `delivery` key (falls back to `meta.passive`, present on SIM, REAL and curriculum rows); a row without `meta.passive` would get `None` as passive but still counts passive-best through `TIER`. +- **Open (OPEN_TASKS.md / training/NEEDS.md / RESULTS.md):** v2 data collection (≈ 10M gold + 50M unlabeled SIM on 20 nodes; ≈ 495k REAL gold on c01/c10/c11; generation is running on Azure under Mehar, nobody on our side touches it); teacher/distillation/DAgger; R17 vs R32; device-based model selection in the card; round-1 recall on clear cases ≈ 5–8% at FIR 0.05% (the separability analysis behind S1/S2 and the v2 facts is in `sim/SEPARABILITY.md`, summarized in `docs/runtime/RESULTS.md` §3). +- **Resolved since 654d822** (removed from this list): the `serialize.ts` header now states 2.4 chars/token (measured); the `types.ts` `InitOptions.situation` comment now matches `situationBudget` (webgpu 2,400; wasm 1,000–2,000 linear). ## Related docs -- [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): facts catalogue, triage salience, section line details, redaction +- [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): facts catalogue (incl. v2 delivery, F1–F9), triage and delivery salience, section line details, redaction - [runtime/model-host.md](runtime/model-host.md): worker/inline host, loader, backends, CLI, errors -- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): queue, gate, action execution, reports -- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `vocabulary`, `situation.budget`, `ask`/`decide`, plugins -- [runtime/build-test-release.md](runtime/build-test-release.md): where and how tests run -- [sim.md](sim.md), [training.md](training.md), [genclass-model-lineage.md](genclass-model-lineage.md) (jev_local Python reference), [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md) -- Source docs: [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) §5–§8, §10, §11; [docs/CONTRACT.md](../CONTRACT.md) §B (packing, heads) and §D (row format); [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md) (example situations); [sim/README.md](../../sim/README.md); [training/README.md](../../training/README.md); [training/NEEDS.md](../../training/NEEDS.md); [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md) +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): queue, gate, modes, action execution (delivery `discard`/`defer`), reports +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `vocabulary`, `situation.budget`, `mode`, `ask`/`decide`, plugins +- [RELEASE.md](../../RELEASE.md): release procedure for `@genclass/runtime` and `@genclass/runtime-model` +- [runtime/build-test-release.md](runtime/build-test-release.md): where and how tests run, CI +- [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md), [genclass-model-lineage.md](genclass-model-lineage.md) (jev_local Python reference), [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md) +- Source docs: [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md) §5–§8, §10, §11, §13; [docs/CONTRACT.md](../CONTRACT.md) §B (packing, heads) and §D (row format); [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md) (batches 4–5, example situations); [sim/README.md](../../sim/README.md), [sim/SEPARABILITY.md](../../sim/SEPARABILITY.md); [training/README.md](../../training/README.md), [training/PLAN-v1.md](../../training/PLAN-v1.md), [training/NEEDS.md](../../training/NEEDS.md); [docs/runtime/RESULTS.md](../runtime/RESULTS.md); [HANDOFF.md](../../HANDOFF.md); [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md) diff --git a/docs/agents/overview.md b/docs/agents/overview.md index b2bd8e6b..b7cfb3bc 100644 --- a/docs/agents/overview.md +++ b/docs/agents/overview.md @@ -1,13 +1,15 @@ # GenClass-lib system overview: the mental model > **Scope:** the whole monorepo at the level of one mental model: `@genclass/runtime` (`packages/runtime/src/**`), -> the unpublished model package (`packages/runtime-model/`), `sim/`, `training/`, `demos/`, and the legacy GenClass -> content it builds on (`jev_local/`, `extension/`, `bench/`, `results/`, `scripts/`, legacy `docs/*.md`). Detail lives -> in the subsystem docs linked from every section; this doc names the stages and the seams between them. +> the unpublished model package (`packages/runtime-model/`), `sim/`, `realapps/`, `training/`, `demos/`, and the +> legacy GenClass content it builds on (`jev_local/`, `extension/`, `bench/`, `results/`, `scripts/`, legacy +> `docs/*.md`). Detail lives in the subsystem docs linked from every section; this doc names the stages and the seams +> between them. > **Read this when:** you land in the repo cold and need to know what the parts are, how one runtime decision flows -> from an observed event to an action, how the offline loops (sim -> training -> model package, demos evaluation) -> connect to it, what each mode allows, what happens without a model, who owns what, and where the project stands. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> from an observed event to an action (now mostly at the network boundary), how the offline loops (sim + realapps -> +> teacher -> distillation -> DAgger -> export, demos evaluation) connect to it, what each mode allows, what happens +> without a model, who owns what, and where the project stands. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. Path convention: every code pointer is `path/from/repo/root` -> `symbol`. Runtime source is under `packages/runtime/src/`. @@ -15,318 +17,401 @@ Path convention: every code pointer is `path/from/repo/root` -> `symbol`. Runtim ## TL;DR - `@genclass/runtime` is a browser library for self-healing web apps. It instruments the page (fetch, XHR, - WebSocket, timers, DOM user events, errors, navigation, storage, long tasks) and the app's state stores, keeps a - causal trace, learns baselines, invariants and transition profiles, and turns a suspicious moment (a *trigger*) into - a plain-English *situation*. A small local model (ONNX in a Web Worker, WebGPU or WASM) answers two typed questions - about it (diagnosis, action). A policy gate runs a minimal action (undoable only for `discard`, late reverts, - `rollback` and custom `onUndo`) only at high calibrated confidence; otherwise the passive action (let it happen) runs. + WebSocket, EventSource, timers, DOM user events, errors, navigation, storage, long tasks) and the app's state + stores, keeps a causal trace, learns baselines, invariants, transition profiles and request cadence, and turns a + suspicious moment (a *trigger*) into a plain-English *situation*. A small local model (ONNX in a Web Worker, WebGPU + or WASM) answers two typed questions about it (diagnosis, action). A policy gate runs a minimal action only at high + calibrated confidence; otherwise the passive action (let it happen) runs. +- **situation-v2 decides at the network boundary.** The main trigger is `delivery`: a fetch/XHR response or a + WebSocket/EventSource message is about to reach the app, and the fields its operation is predicted to write already + hold newer data that the body would change (or a pending local change / typed text the body would overwrite). The + runtime can hold the delivery (pure latency, at most the hold budget) and `discard` it: deliver it, but drop the + writes its chain makes over newer data, synchronously inside each write. **Store writes are not held by default** + (`policy.holdWrites: false`); a salient write no delivery decision covers is decided in the background and can only + be late-reverted. - The runtime never maps a fact pattern to a diagnosis or action with an if/then (CONTRACT §0 rule 1). Facts are - generic; triage only decides whether the model is worth asking; the model decides; the gate filters. -- One situation implementation (`packages/runtime/src/situation/*`) is shared by the runtime and by the sim, which - drives the real runtime to produce training rows. Its text is frozen at git tag `situation-v1` (1a77558); - `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. -- Modes: `observe` (never changes execution), `guard` (default; guard-tier actions such as `discard`, `coalesce`), - `heal` (adds heal-tier actions such as `retry`, `serve_cached`, `rollback`). Kill switch: `?genclass=off`. -- Fail open everywhere: no model, a loading or failed model, a timeout or any error means the passive action runs; a - held write or request never waits for the model longer than the hold budget (at most 800 ms with the default - `"auto"`); an action that then runs can add its own wait (`delay` and `coalesce` ≤ 8 s, `retry` backoff ≤ 5 s, - `defer` ≤ 10 s per deferral before the write is re-decided, custom actions unbounded). -- **Where it stands:** `@genclass/runtime@0.1.0-alpha.0` is on npm, but the trained model package - (`@genclass/runtime-model@0.1.0`, the default model URL) is not published, so a default install observes and learns - but never decides or acts. SIM phase A data (600,676 rows) exists; final training round 1 was launched with no - results in the repo; the demos have only been run with the v0.1 model (not trained for runtime decisions). + generic; triage and the delivery pre-filter only decide whether the model is worth asking; the model decides; the + gate filters. +- One situation implementation (`packages/runtime/src/situation/*`) is shared by the runtime, by the sim and by the + real-app corpus, which both drive the real runtime to produce training rows. Its text is **frozen at tag + `situation-v2`** (6e5e86e); `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts` (default + mode), `types.ts` and `devtools/index.ts`. Everything trained so far used the older `situation-v1` format. +- Modes: **`observe` (default since our commit f3636b2**; never acts, decides in the background for detection), + `guard` (opt-in; guard-tier actions such as `discard`, `defer`, `coalesce`), `heal` (experimental; adds `retry`, + `serve_cached`, `rollback`, ...). Kill switch: `?genclass=off`. +- Fail open everywhere: no model, a loading or failed model, a timeout or any error means the passive action runs; + the runtime holds only when a non-passive action is permitted **and** the model is expected to answer within the + hold budget (at most 800 ms with the default `"auto"`). +- **Where it stands:** `@genclass/runtime@0.1.0-alpha.0` (situation-v1 code, default `guard`) is on npm; no model is + published (`@genclass/runtime-model` is a 404), so any install only observes. No situation-v2 model exists. The + colleague is generating v2 data on Azure (SIM ~10M gold + ~50M unlabeled rows on 20 nodes; REAL ~0.5M real-browser + gold rows on 3 nodes); next comes the 150M teacher, distillation into R17/R32, DAgger, EVAL, the model package, a + demos rerun and `@genclass/runtime@0.1.0`. ## 1. The problem and the product principles -Web apps fail at runtime in ways their code does not handle: an older response overwrites newer state (stale write), -the same request is sent twice from one intent (duplicate), a request keeps failing, a request hangs, a store ends up -contradicting a relation it normally keeps, an operation makes a state change unlike its usual ones. CONTRACT §0.5 -states the claim: *install one library; find and prevent runtime failures automatically, with low false positives.* +Web apps fail at runtime in ways their code does not handle: an older response overwrites newer state (stale +response), the same request is sent twice from one intent (duplicate), a request keeps failing, a request hangs, a +store ends up contradicting a relation it normally keeps, an operation makes a state change unlike its usual ones. +CONTRACT §0.5 states the claim: *install one library; find and prevent runtime failures automatically, with low false +positives.* HANDOFF.md's product principle: *never make a correct app worse*. Binding principles (`docs/runtime/CONTRACT.md` §0 and §0.5; restated with code locations in -[status-and-known-issues](status-and-known-issues.md#ground-rules-binding-contract-0-and-05-restated)): +[status-and-known-issues](status-and-known-issues.md)): | principle | what it means in code | |---|---| -| Precision first | Default mode `guard` allows only guard-tier actions. The gate needs Σ p(permitted actions) ≥ 0.9 (guard) / 0.8 (heal) and a top diagnosis other than `expected` (`packages/runtime/src/decide/policy.ts` -> `gate`, `policyConfig`). The sim labels favour passive (tier premiums, tie rule). The false-intervention rate on clean runs is the headline metric in training eval and demos. | -| Cheap by default | Facts and baselines always run and are cheap; the model is consulted only for *salient* situations (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`), runs in a Worker, loads at idle or lazily, and is cached. Target model size ≤ 25 MB q8 (R17 q8 9.58 MB, R32 q8 22.47 MB). | -| Observable | One console line per detection/intervention with collapsible evidence (`packages/runtime/src/decide/report.ts` -> `Reporter`), `explain(id)`, `undo()` for reversible actions, the `x-genclass` response header on synthetic answers (`blocked`, `cached`, `coalesced`), devtools overlay, kill switch. | -| No hardcoded bugs | Facts (`packages/runtime/src/situation/facts.ts` -> `computeFacts`) are uniform sentences with a `neutral` flag; applicability (`packages/runtime/src/situation/build.ts` -> `buildSituation`, internal `builtinApplicable`) only says whether an action *can* run. Only the model's probabilities choose. Without a model the runtime observes only. | -| Determinism and parity | Runtime code reads time only from the injected `Clock` (no `Math.random`, `Date.now`, global timers), so the sim can replay it byte for byte. The sim drives the same code; `training/curriculum/rt.py` is a Python port of the situation text. | -| Honest evaluation | `sim/` and `demos/` are built by different people who do not read each other's code (CONTRACT §0 rule 4). | +| Never make a correct app worse | Default mode `observe` acts on nothing. When a mode permits actions, the runtime holds only a delivery or request (latency, never reordering), never a store write unless `policy.holdWrites` is on; a discard drops only fields that already hold newer data. The realapps never-worse sweep ("an always-passive model changes nothing") reports 0/396 clean runs changed for the v2 runtime (STATUS.md; see [realapps](realapps.md) for what it compares). | +| Precision first | The gate needs Σ p(permitted actions) ≥ 0.9 (guard) / 0.8 (heal) and a top diagnosis other than `expected` (`packages/runtime/src/decide/policy.ts` -> `gate`, `policyConfig`). Labels favour passive (tier premiums, tie rule). The false-intervention rate (FIR) is reported next to every recall number. | +| Cheap by default | Facts and baselines always run and are cheap; a delivery reads its body only when it is already a candidate; the model is consulted only for *salient* situations (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `RuntimeImpl.runDelivery`), runs in a Worker, loads at idle or lazily, and is cached. Target model size ≤ 25 MB q8 (R17 q8 9.58 MB, R32 q8 22.5 MB). | +| Observable | One console line per detection/intervention with collapsible evidence (`packages/runtime/src/decide/report.ts` -> `interventionLine`, `detectionLine`), `explain(id)`, `undo()` for reversible actions, the `x-genclass` response header on synthetic answers, the devtools overlay, the kill switch. | +| No hardcoded bugs | Facts (`packages/runtime/src/situation/facts.ts` -> `computeFacts`, plus `conflicts.ts`, `content.ts`, `evidence.ts`) are uniform sentences with a `neutral` flag; applicability (`packages/runtime/src/situation/build.ts` -> `builtinApplicable`) only says whether an action *can* run. Only the model's probabilities choose. | +| Determinism and parity | Runtime code reads time only from the injected `Clock` (no `Math.random`, `Date.now`, global timers), so the sim and realapps (virtual time) replay it exactly. Both drive the same code; `training/curriculum/rt.py` is a Python port of the situation text, frozen at `situation-v2`. | +| Honest evaluation | `sim/`, `realapps/` and `demos/` must not read each other's code (CONTRACT §0 rule 4, HANDOFF.md). Demos are never tuned. | -Adoption path: `observe` -> `guard` -> `heal`. +Adoption path: `observe` (default) -> `guard` -> `heal`. ## 2. Component map ```text - ONLINE: inside the app's page packages/runtime (npm: @genclass/runtime) - +------------------------------------------------------------------------------------------------+ - | app code: fetch / XHR / WebSocket / timers / DOM events / store writes (atoms, Redux, Zustand) | - | | | | - | v v | - | observe/* --ops, events--> trace/* state/* StoreHub --writes--> InvariantMiner | - | (patched globals) (OpRegistry, Context, EventLog) learn/* Baselines, Profiles | - | | request / failure / stall | mutation | settled point: inconsistency, | - | | triggers | trigger | transition triggers; error | - | +---------------------------------+--------------------+ | - | v | - | runtime.ts RuntimeImpl.trigger: facts -> triage -> situation + questions (situation/*) | - | | EvaluateRequest { state, questions } | - | v | - | decide/decider.ts DeciderQueue --> DecisionProvider (default: model/* ModelHost) | - | Worker: ModelBackend -> Engine -> onnxruntime-web | - | | calibrated Answers (diagnosis, action) | - | v | - | decide/policy.ts gate --> Controller.run(action) or passive() | - | v | - | Decision / ActionRecord --> report.ts console lines, explain(), undo(), rt.on() events | - | --> devtools/* overlay, adapters/* hooks | - +------------------------------------------------------------------------------------------------+ - ^ model directory: model.json, *-q8.onnx, *-fp16.onnx, - | tokenizer.json, calibration.json, meta.json - OFFLINE | (planned home: @genclass/runtime-model, unpublished) - sim/ --drives the real createRuntime--> rows {state, questions, labels} - | - training/ curriculum + jev_local/train --> eval_runtime.py --> export_runtime.py --> model directory - demos/ GenClass.init Off / Guard / Heal --> seeded trials + oracles --> demos/results.md - legacy: jev_local/ (Python model, packer, trainer), extension/ (v0.1 model card), bench/, results/ + ONLINE: inside the app's page packages/runtime (npm: @genclass/runtime) + +-------------------------------------------------------------------------------------------------------+ + | app code: fetch / XHR / WebSocket / EventSource / timers / DOM events / store writes (atoms, Redux, | + | Zustand) | + | | | | + | v v | + | observe/* (patched globals) --ops--> trace/* state/* StoreHub: propose -> drop filter -> commit | + | | OpRegistry, Context, EventLog | (no holds by default) learn/* Baselines, | + | | | Profiles, Cadence; | + | | NETWORK BOUNDARY | salient write not InvariantMiner at | + | | response / message about to reach app | covered by a delivery settled points | + | v v decision | | + | runtime.ts runDelivery: predicted writes, observeWrite: background | inconsistency, | + | conflicts, body read (<= 100 ms) `mutation` (late revert only) | transition, error | + | | delivery | request / failure / stall | | + | +--------------------------+-----------------+--------------------------------+ | + | v | + | runtime.ts RuntimeImpl.trigger: facts -> triage -> situation + questions (situation/*) | + | | hold only if an action is permitted AND expectedLatency <= budget | + | v | + | decide/decider.ts DeciderQueue (stale drop) --> DecisionProvider (default: model/* ModelHost) | + | Worker: ModelBackend -> Engine -> onnxruntime-web | + | | calibrated Answers (diagnosis, action) | + | v | + | decide/policy.ts gate --> Controller.run(action) (deliver/discard/defer, coalesce, ...) or passive | + | v | + | Decision / ActionRecord --> report.ts console lines, explain(), undo(), rt.on() events | + | --> devtools/* overlay, adapters/* hooks | + +-------------------------------------------------------------------------------------------------------+ + ^ model directory: model.json, *-q8.onnx, *-fp16.onnx, + | tokenizer.json, calibration.json, meta.json + OFFLINE | (planned: @genclass/runtime-model@0.1.0, a 404 today) + sim/ --drives the real createRuntime in a virtual world--> gold / unlabeled / on-policy rows + realapps/ --91 real apps + the real runtime in headless Chromium--> gold / unlabeled REAL rows + training/ curriculum (rt.py) + T150 teacher on gold -> teacher labels on unlabeled rows + -> distil R17 / R32 -> DAgger (SIM --on-policy) -> eval_runtime.py -> export_runtime.py + demos/ GenClass.init Off / Guard / Heal --> seeded trials + oracles --> demos/results.md + legacy: jev_local/ (Python model, packer, trainer), extension/ (v0.1 model), bench/, results/ ``` -| component | path | role | state at 654d822 | doc | +| component | path | role | state at b435acb | doc | |---|---|---|---|---| -| Public API and wiring | `packages/runtime/src/index.ts` (`GenClass`, `createRuntime`), `packages/runtime/src/runtime.ts` (`RuntimeImpl`), `types.ts`, `clock.ts`, `util.ts` | facade, construction, modes, kill switch, events, plugins, settled points | done, frozen | [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md) | -| Observers and trace | `packages/runtime/src/observe/*`, `packages/runtime/src/trace/*` | patch globals, ops with causes, ambient context, event log, fetch/XHR action controllers | done, frozen | [observe-and-trace](runtime/observe-and-trace.md) | -| State | `packages/runtime/src/state/*`, `packages/runtime/src/adapters/*` | `StoreHub` (atom/guard/adapter stores), mutation pipeline and holds, invariant miner, snapshots; React/Redux/Zustand adapters | done, frozen | [state-and-adapters](runtime/state-and-adapters.md) | -| Learn, situation, triage | `packages/runtime/src/learn/*`, `packages/runtime/src/situation/*` | baselines, transition profiles, facts, triage, situation text and questions (model input) | done, frozen at `situation-v1` | [learn-situation-triage](runtime/learn-situation-triage.md) | -| Decide | `packages/runtime/src/decide/*` | queue, hold budget, policy gate, actions, reports, explain, undo | done, frozen | [decide-policy-actions](runtime/decide-policy-actions.md) | -| Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | done, frozen | [model-host](runtime/model-host.md) | -| Devtools | `packages/runtime/src/devtools/*` | shadow-DOM overlay on the public API | done, frozen | [devtools](runtime/devtools.md) | -| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}` | tsup ESM build (6 entries), vitest, Playwright, smoke test | alpha published; no CI | [build-test-release](runtime/build-test-release.md) | -| Model I/O contract | runtime `situation/*` + `model/*`, `sim/`, `training/` | situation text -> packed request -> heads -> calibrated answers | frozen | [model-io-contract](model-io-contract.md) | -| Model package | `packages/runtime-model/` | planned home of the published model directory | only `MODEL_CARD.md`; package not created | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | -| Sim | `sim/` (`@genclass/sim`) | training-data generator driving the real runtime in a virtual world | phase A done (600,676 rows); phase B in progress at commit time | [sim](sim.md) | -| Training | `training/` | curriculum, R17/R32 training, eval, ONNX export | final round 1 launched, no results in repo | [training](training.md) | -| Demos | `demos/` (`@genclass/demos`) | six demo apps, Service Worker chaos backend, trial harness | built; results only with v0.1 model | [demos](demos.md) | +| Public API and wiring | `packages/runtime/src/index.ts` (`GenClass`, `createRuntime`), `packages/runtime/src/runtime.ts` (`RuntimeImpl`), `types.ts`, `clock.ts`, `util.ts` | facade, construction, modes (default `observe`), kill switch, events, plugins, settled points, delivery gate wiring | situation-v2 + our default-mode commit | [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md) | +| Observers and trace | `packages/runtime/src/observe/*` (incl. `eventsource.ts`, `messages.ts` -> `MessageGate`), `packages/runtime/src/trace/*` | patch globals, ops with causes, ambient context, event log; request, failure, stall and delivery gates | frozen at `situation-v2` | [observe-and-trace](runtime/observe-and-trace.md) | +| State | `packages/runtime/src/state/*`, `packages/runtime/src/adapters/*` | `StoreHub` (atom/guard/adapter stores), drop filter, late revert, opt-in holds, invariant miner (10 templates), stale marks, snapshots; React/Redux/Zustand adapters | frozen at `situation-v2` | [state-and-adapters](runtime/state-and-adapters.md) | +| Learn, situation, triage | `packages/runtime/src/learn/*` (incl. `cadence.ts`), `packages/runtime/src/situation/*` (incl. `conflicts.ts`, `content.ts`, `evidence.ts`) | baselines, profiles, cadence, version conflicts, content facts F1–F3, evidence facts F5–F9, triage, situation text and questions (model input) | frozen at `situation-v2` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Decide | `packages/runtime/src/decide/*`, controllers in `runtime.ts` | queue (stale drop, deadlines), hold budget, policy gate, actions, reports, explain, undo | frozen at `situation-v2` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | unchanged since `situation-v1`; no model to load | [model-host](runtime/model-host.md) | +| Devtools | `packages/runtime/src/devtools/*` | shadow-DOM overlay on the public API | mode labels "Observe (default)", "Guard (opt-in)", "Heal (experimental)" | [devtools](runtime/devtools.md) | +| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}`, root `package-lock.json`, `.github/workflows/ci.yml` | tsup ESM build (6 entries), vitest (351 tests), Playwright, smoke test, CI | alpha.0 published; lockfile and CI committed (CI not yet run on GitHub: `mvp-v2` is not pushed) | [build-test-release](runtime/build-test-release.md) | +| Model I/O contract | runtime `situation/*` + `model/*`, `sim/`, `realapps/`, `training/` | situation text -> packed request -> heads -> calibrated answers; row kinds and labels | format `situation-v2` | [model-io-contract](model-io-contract.md) | +| Model package | `packages/runtime-model/` | planned home of the published model directory | only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | +| Sim | `sim/` (`@genclass/sim`) | training-data generator driving the real runtime in a virtual world: 46 feature combinators × 115 domains; gold, unlabeled and on-policy rows; S1/S2 labels | v1 data on disk (phase A 600,676, phase B 1,415,344 rows); v2 runs in progress on Azure | [sim](sim.md) | +| Real-app corpus | `realapps/` | 91 real apps (77 written + 14 OSS RealWorld front-ends, 23 frameworks) with the real runtime in headless Chromium on virtual time; same labels as the sim; the never-worse sweep | v2 batches `v2b1`–`v2b3` in progress on c01/c10/c11 (per `training/NEEDS.md`, unverified from here); no tests, not in CI or the workspaces | [realapps](realapps.md) | +| Training | `training/` | vocabulary, curriculum (`rt.py` at situation-v2), training rounds, teacher labelling, distillation, eval, ONNX export | final round 1 (situation-v1) done and superseded; v2 program prepared, not run | [training](training.md) | +| Demos | `demos/` (`@genclass/demos`) | six demo apps, Service Worker chaos backend, trial harness | results only with the v0.1 model on the situation-v1 runtime | [demos](demos.md) | | GenClass model lineage | `jev_local/`, `scripts/genclass_export.py`, `tests/` | Python predecessor: model, packer, calibration, trainer; reference for parity | legacy except trainer, export graph, parity reference | [genclass-model-lineage](genclass-model-lineage.md) | | Extension, benchmarks, ops scripts | `extension/`, `bench/`, `results/`, `BENCHMARKS.md`, `scripts/` | GenClass 0.1 Chrome extension, Jev benchmarks, Azure/VM scripts | legacy; `scripts/vm.sh`, `scripts/azvm.sh`, `scripts/launch_run.sh` still used | [extension-and-benchmarks](extension-and-benchmarks.md) | -| Status and team files | `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `*/NEEDS.md`, `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md` | plan, status, requests, binding contract | drift documented | [status-and-known-issues](status-and-known-issues.md) | +| Status and team files | `HANDOFF.md`, `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `*/NEEDS.md`, `docs/runtime/{CONTRACT,API,ARCHITECTURE,RESULTS}.md` | handoff, plan, status, requests, binding contract, results | drift documented | [status-and-known-issues](status-and-known-issues.md) | Paths and per-directory detail: [repo-map](repo-map.md). Terms: [glossary](glossary.md). ## 3. Runtime data flow end to end -Every stage below runs inside `RuntimeImpl` (constructed by `GenClass.init` or `createRuntime`). The first four stages -always run, model or not; stages 5 onward run only while the runtime is *consultable* (not paused, not destroyed, a +Every stage below runs inside `RuntimeImpl` (constructed by `GenClass.init` or `createRuntime`). Stages 1–4 always +run, model or not; stages 5 onward run only while the runtime is *consultable* (not paused, not destroyed, a `DecisionProvider` exists, and its `status.state` is `ready` or `off`). | # | stage | what happens | code (file -> symbol) | doc | |---|---|---|---|---| -| 1 | Observers | Constructor installs, in order, timers, fetch, xhr, websocket, user (DOM), errors, nav, storage, perf; each in try/catch; each patched global becomes a pass-through after `destroy()` (WebSocket instances and timer callbacks created before `destroy()` keep tracing; see [observe-and-trace](runtime/observe-and-trace.md), 'After destroy: what still runs'). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | -| 2 | Trace, ops, causality | Every async unit is an `OpRec` (id, kind, signature name such as `GET /api/search`, detail such as `?q=rea`, cause, root). The ambient op (set by `run`, `stick`, `stickUser`) becomes the cause of new ops and the writer of state writes. Events go to a ring buffer (default 500). | `packages/runtime/src/trace/ops.ts` -> `OpRegistry`; `packages/runtime/src/trace/context.ts` -> `Context`, `LazyOp`; `packages/runtime/src/trace/events.ts` -> `EventLog`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`, `RuntimeImpl.user` | [observe-and-trace](runtime/observe-and-trace.md) | -| 3 | Stores | Store values are flattened into versioned dotted fields with writer ops and history. Each `set`/`dispatch` becomes a `MutationRec`: user-sync, GenClass, paused, `hold: false`, no-op and unholdable writes bypass; the rest go through the hub's `gate` hook in per-store FIFO order. | `packages/runtime/src/state/hub.ts` -> `StoreHub.propose`, `StoreHub.commit`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.onApplied` | [state-and-adapters](runtime/state-and-adapters.md) | -| 4 | Learned baselines, invariants, profiles | Fetch/XHR latency (≥ 5 samples), outcomes, failure streaks and rates per signature; at *settled points* (60 ms after the last op end or write, nothing younger than 10 s in flight and no held or queued write) the invariant miner checks 9 generic templates and transition profiles flag rare state changes (< 1% of ≥ 20 completions). | `packages/runtime/src/learn/baselines.ts` -> `Baselines`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner.observe`; `packages/runtime/src/learn/profiles.ts` -> `Profiles`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled` | [learn-situation-triage](runtime/learn-situation-triage.md), [state-and-adapters](runtime/state-and-adapters.md) | -| 5 | Trigger | A raise site calls `trigger(spec, controller, { hold, priority })`. Kinds: `mutation` (held), `request` (held), `failure` (fetch: holdable, held only when a failure action is permitted, i.e. in heal mode or with a guard-tier custom failure action), `stall`, `inconsistency`, `transition`, `error`; `ask` comes from `rt.ask`/`rt.situation`. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `gateMutation`, `watchStall`, `raiseInconsistency`, `raiseTransition`, `reportError`; `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `runRequest`, `failureGate`) | [decide-policy-actions](runtime/decide-policy-actions.md) | -| 6 | Facts | Uniform English sentences per trigger, each with a kind and a `neutral` flag; ordered non-neutral first; at most 12. | `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts` | [learn-situation-triage](runtime/learn-situation-triage.md) | -| 7 | Triage | With `triage: "salient"` (default) the model is asked only if some fact is non-neutral, a standing question has `always: true`, or the trigger is `ask`. Otherwise the passive action runs with no model call and no record. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` | [learn-situation-triage](runtime/learn-situation-triage.md) | -| 8 | Situation + questions | 7-key `JevState` (`app, trigger, facts, in_flight, timeline, state, stats`) sized by a character budget (3,200 full; auto 1,000-2,000 on WASM); `diagnosis` question (10 labels) and `action` question (applicable actions, passive first, only when ≥ 2 apply); bare labels at ≤ 1,400 chars. | `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`; `packages/runtime/src/situation/questions.ts` -> `buildQuestions`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget` | [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md) | -| 9 | Hold or not | The subject is held only if the trigger is holdable and the mode and policy permit at least one non-passive action; the wait for the decision lasts at most the hold budget (`"auto"`: clamp(round(1.5 × median of the last 20 provider latencies, or the model's `warmupMs` before any), 150, 800) ms; 300 ms when neither is known). Otherwise the passive action runs now and the decision continues in the background (detection only). | `packages/runtime/src/decide/policy.ts` -> `permittedActions`, `holdBudget` | [decide-policy-actions](runtime/decide-policy-actions.md) | -| 10 | Decision queue | Single-flight priority queue (32 items, 30 s answer cache, deadlines, 10 s runtime-side timeout); every miss, error or timeout resolves `null` -> passive. | `packages/runtime/src/decide/decider.ts` -> `DeciderQueue.submit` | [decide-policy-actions](runtime/decide-policy-actions.md) | -| 11 | Model host | `evaluate` rejects at once unless `ready`. In the Worker (inline fallback), the packer renders the state and questions with Python-parity serialization, tokenizes, packs `[CLS] key: text [SEP] ... [Q] header [O] item ...` with block attention, and runs one ONNX forward pass (heads `choice_logits`, `score_logits`, `noul_logits`). | `packages/runtime/src/model/host.ts` -> `createModelHost`, `ModelHost.evaluate`; `packages/runtime/src/model/backend.ts` -> `ModelBackend.evaluate`; `packages/runtime/src/model/engine.ts` -> `Engine.evaluate`; `packages/runtime/src/model/packer.ts` -> `Packer.pack` | [model-host](runtime/model-host.md), [model-io-contract](model-io-contract.md) | -| 12 | Calibrated answers | Per-question temperature (by header, bucket or kind) or Platt scaling turns logits into `Answer`s (`choice`, `confidence`, `probabilities`). The gate reads only `probabilities` and the diagnosis `choice`. | `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer` | [model-io-contract](model-io-contract.md) | -| 13 | Policy gate | A = applicable non-passive actions the mode allows minus `deny`; candidate = argmax over A; runs iff not paused, Σ p(A) ≥ the candidate tier's threshold, top diagnosis ≠ `expected`, < 60 actions in the last minute, and, for holdable triggers (mutation, request, fetch failure), the answer arrived while the subject was still held (else late-revert rules; non-holdable triggers skip this check). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`; `packages/runtime/src/decide/policy.ts` -> `gate` | [decide-policy-actions](runtime/decide-policy-actions.md) | -| 14 | Action or passive | The subject's `Controller` performs the action (`run`) or lets it through (`passive`). A throw runs passive. | `packages/runtime/src/decide/exec.ts` -> `Controller`; controllers in `packages/runtime/src/runtime.ts` -> `gateMutation`, `RuntimeImpl.rollback`, `RuntimeImpl.revertChain`, `RuntimeImpl.resync` and `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `reqCtl`, `failureGate`, `stallController`) | [decide-policy-actions](runtime/decide-policy-actions.md) | -| 15 | Report, explain, undo, events | Every model answer to a trigger is a `Decision` (`d<n>`); every non-passive attempt an `ActionRecord` (`a<n>`, exact `changed` sentence, optional idempotent `undo`); console lines deduped per 60 s; events `decide`, `detect`, `act`, `report`, `status`, `event`; past actions reappear in later timelines as `GenClass <changed>`. | `packages/runtime/src/decide/report.ts` -> `Reporter`, `interventionLine`, `detectionLine`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.explain`, `RuntimeImpl.on`; `packages/runtime/src/devtools/index.ts` -> `mountDevtools` | [decide-policy-actions](runtime/decide-policy-actions.md), [devtools](runtime/devtools.md) | - -## 4. Walkthrough: a typeahead stale write +| 1 | Observers | The constructor installs, in order, `timers fetch xhr websocket eventsource user errors nav storage perf`, each in try/catch; each patched global becomes a pass-through after `destroy()`. Synthetic DOM events are recorded only with `observe.untrustedEvents: true`. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | +| 2 | Trace, ops, causality | Every async unit is an `OpRec` (id, kind, signature name such as `GET /api/search`, detail such as `?q=rea`, cause, root). The ambient op becomes the cause of new ops and the writer of state writes; a released response or dispatched message makes its op ambient while the app's handlers run. Events go to a ring buffer (default 500). | `packages/runtime/src/trace/ops.ts` -> `OpRegistry`; `packages/runtime/src/trace/context.ts` -> `Context`, `LazyOp`; `packages/runtime/src/trace/events.ts` -> `EventLog` | [observe-and-trace](runtime/observe-and-trace.md) | +| 3 | Stores | Values are flattened into versioned dotted fields with writer ops, history and write logs. Each `set`/`dispatch` is a `MutationRec`: first the **drop filter** removes changes that an active discard mark protects; then the write applies at once (user-sync, GenClass, paused, `hold: false` and no-op writes bypass everything); a non-bypass write not `covered` by a delivery decision is handed to `observeWrite` first (a background `mutation` trigger). Only with `holdWrites: true` does the old held pipeline (`gateMutation`) run. | `packages/runtime/src/state/hub.ts` -> `StoreHub.propose`, `StoreHub.applyFilter`, `StoreHub.commit`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter`, `RuntimeImpl.observeWrite`, `RuntimeImpl.covered`, `RuntimeImpl.onApplied` | [state-and-adapters](runtime/state-and-adapters.md) | +| 4 | Learned baselines, invariants, profiles, cadence | Fetch/XHR latency (≥ 5 samples), outcomes, failure streaks, rates and cadence (schedule or debounce) per signature; at *settled points* (60 ms after the last op end or write, nothing younger than 10 s in flight, no pending write) the invariant miner checks 10 generic templates and transition profiles flag rare state changes (< 1% of ≥ 20 completions). Profiles also give the delivery gate its predicted write set. | `packages/runtime/src/learn/baselines.ts` -> `Baselines`; `packages/runtime/src/learn/profiles.ts` -> `Profiles`; `packages/runtime/src/learn/cadence.ts`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner.observe`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled` | [learn-situation-triage](runtime/learn-situation-triage.md), [state-and-adapters](runtime/state-and-adapters.md) | +| 5 | Delivery pre-filter (network boundary) | fetch (a non-failure response, before the app's promise resolves), XHR (first completion event, before any app completion listener) and WebSocket/EventSource (each message, before any app listener; per-channel order kept) call `runDelivery`. It computes the predicted write set P, matches live fields and finds conflicts (`newer`: written by a later op outside the chain, not a user action, with no newer same-signature request in flight; `pending`: an unconfirmed optimistic user change). No conflict and no typed-into text field -> released synchronously, no body read. Otherwise it waits at most 100 ms for the body (a clone) and keeps the delivery only if the body would change newer data, put back the value a pending change replaced (F1) or replace typed text (F2). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`; `packages/runtime/src/situation/conflicts.ts` -> `predictedWrites`, `matchFields`, `conflictsOn`; `packages/runtime/src/situation/content.ts` -> `analyzeBody`; `packages/runtime/src/observe/messages.ts` -> `MessageGate` | [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md) | +| 6 | Trigger | A raise site calls `trigger(spec, controller, { hold, priority })`. Kinds: `delivery` (holdable, priority 2), `request` (holdable), `failure` (fetch: holdable), `mutation` (background by default; holdable only with `holdWrites`), `stall`, `inconsistency`, `transition`, `error`; `ask` comes from `rt.ask`/`rt.situation`. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `runDelivery`, `observeWrite`, `gateMutation`, `watchStall`, `raiseInconsistency`, `raiseTransition`, `reportError`; `packages/runtime/src/observe/fetch.ts` -> `installFetch` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 7 | Facts | Uniform English sentences per trigger, each with a kind and a `neutral` flag; non-neutral first; at most 12 at the full budget. v2 adds version-conflict facts, F1 (would put back an older value), F2 (would replace typed text), F3 (changes nothing), F5 (failure scope, commit ambiguity), F6 (cadence), F7 (repeat evidence), F9 (known-stale values) and read-your-writes. | `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts`; `situation/content.ts`; `situation/evidence.ts` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| 8 | Triage | With `triage: "salient"` (default) the model is asked only if some fact is non-neutral, a standing question has `always: true`, or the trigger is `ask`. Otherwise the passive action runs with no model call and no record. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| 9 | Situation + questions | 7-key `JevState` (`app, trigger, facts, in_flight, timeline, state, stats`) sized by a character budget: full 2,400 (WebGPU or unknown device), WASM 1,000–2,000 by threads; `diagnosis` question (10 labels) and `action` question (applicable actions, passive first, only when ≥ 2 apply); bare labels at ≤ 1,400 chars. | `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`; `packages/runtime/src/situation/questions.ts` -> `buildQuestions`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget` | [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md) | +| 10 | Hold or not | `waits = hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`. `expectedLatency` = median recent provider latency (warm-up before any) × (1 + queued decisions) + the one computing; infinite while the provider is stuck. Hold budget `"auto"`: clamp(round(1.5 × median of the last 20 latencies, or `warmupMs`), 150, 800) ms; 300 ms when neither is known. If not waiting, the passive action runs now and the decision continues in the background (5 s deadline). | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`, `RuntimeImpl.expectedLatency`; `packages/runtime/src/decide/policy.ts` -> `permittedActions`, `holdBudget` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 11 | Decision queue | Single-flight priority queue (32 items, 30 s answer cache, deadlines, 10 s runtime-side timeout). An item whose subject was superseded (`ctl.stale`: response already released, write overwritten) is dropped before the model sees it. Every miss, error or timeout resolves `null` -> passive. | `packages/runtime/src/decide/decider.ts` -> `DeciderQueue.submit`, `DeciderQueue.pump` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 12 | Model host | `evaluate` rejects at once unless `ready`. In the Worker (inline fallback), the packer renders the state and questions with Python-parity serialization, tokenizes, packs `[CLS] key: text [SEP] ... [Q] header [O] item ...` with block attention, and runs one ONNX forward pass. | `packages/runtime/src/model/host.ts` -> `createModelHost`; `packages/runtime/src/model/engine.ts` -> `Engine.evaluate`; `packages/runtime/src/model/packer.ts` -> `Packer.pack` | [model-host](runtime/model-host.md), [model-io-contract](model-io-contract.md) | +| 13 | Calibrated answers | Per-question temperature or Platt scaling turns logits into `Answer`s (`choice`, `confidence`, `probabilities`). The gate reads only `probabilities` and the diagnosis `choice`. | `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer` | [model-io-contract](model-io-contract.md) | +| 14 | Policy gate | A = applicable non-passive actions the mode allows minus `deny`; candidate = argmax over A; runs iff not paused, Σ p(A) ≥ the candidate tier's threshold, top diagnosis ≠ `expected`, < 60 actions in the last minute, and the subject has not already proceeded (except a late-revert `discard` of a write, and custom actions). A delivery decided before release is marked `decided`, which makes its chain's writes `covered`. | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`; `packages/runtime/src/decide/policy.ts` -> `gate` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 15 | Action or passive | The subject's `Controller` performs the action (`run`) or lets it through (`passive`). Delivery: `deliver` releases; `discard` releases and sets a 10 s discard mark; `defer` waits for related in-flight ops (≤ 10 s) and decides again (≤ 2 times). A throw runs passive. | `packages/runtime/src/decide/exec.ts` -> `Controller`; `packages/runtime/src/runtime.ts` -> `runDelivery`, `mutationController`, `rollback`, `revertChain`, `resync`; `packages/runtime/src/observe/fetch.ts` -> `installFetch` | [decide-policy-actions](runtime/decide-policy-actions.md) | +| 16 | Report, explain, undo, events | Every model answer to a trigger is a `Decision` (`d<n>`); every non-passive attempt an `ActionRecord` (`a<n>`, exact `changed` sentence, `dropped` paths for a delivery discard, optional `undo`); console lines deduped per 60 s; events `decide`, `detect`, `act`, `report`, `status`, `event`; past actions and drops reappear in later timelines. | `packages/runtime/src/decide/report.ts` -> `interventionLine`, `detectionLine`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.explain`, `RuntimeImpl.on`; `packages/runtime/src/devtools/index.ts` -> `mountDevtools` | [decide-policy-actions](runtime/decide-policy-actions.md), [devtools](runtime/devtools.md) | + +## 4. Walkthrough: a stale typeahead response held at delivery and dropped The canonical bug. The user types into a search box; each keystroke sends `GET /api/search?q=...`; an older, slower -response arrives after a newer one and is about to overwrite newer results. The situation text below is Example A -from [learn-situation-triage](runtime/learn-situation-triage.md#12-annotated-examples-copied-from-packagesruntimestatusmd-produced-by-the-tests), -produced by `packages/runtime/test/budget.test.ts` -> `typeahead` at a 1,000-char budget. That test registers -`rt.atom("search", { query: "", results: [] })`, types `r`, `re`, `rea`, `reac` through `rt.user(...)`, and serves -`q=rea` with 900 ms latency and every other query with 120 ms. Op ids: `#5` user typed `rea`, `#6` `GET -/api/search?q=rea`, `#7` user typed `reac`, `#8` `GET /api/search?q=reac` (`#1`-`#4` are the `r` and `re` prefixes). -The steps assume a `ready` model and the default `guard` mode; the table after them covers the other cases. +response arrives after a newer one and is about to overwrite newer results. This is the scenario of +`packages/runtime/test/budget.test.ts` -> `typeahead`, whose situations are printed in `packages/runtime/STATUS.md` +("Example situations: compact budgets" and "delivery: a stale out-of-order response"). The test registers +`rt.atom("search", { query: "", results: [] })`; each `rt.user({ kind: "type", ... })` handler writes `query` and +fetches; after `await res.json()` the app writes `results`. It types `r`, `re`, `rea`, `reac` (80, 70 and 90 ms +apart) and serves `q=rea` with 900 ms latency and every other query with 120 ms. Op ids: `#1`/`#2` user `r` and its +GET, `#3`/`#4` for `re`, `#5` user typed `rea`, `#6` `GET /api/search?q=rea`, `#7` user typed `reac`, `#8` +`GET /api/search?q=reac`. The test harness runs in `guard` mode (`test/helpers.ts` -> `setup`); the steps below +assume `mode: "guard"` and a `ready` model. The table after them covers the default `observe` mode and the +fail-open cases. A sibling test, `packages/runtime/test/delivery.test.ts` -> "a stale out-of-order response gets a +delivery decision; discard drops only the stale field writes", asserts the discard end to end. 1. **Keystroke -> user op.** In a browser, the capture-phase `input` listener (`packages/runtime/src/observe/dom-user.ts` - -> `installDomUser`) calls the sink with `{ kind: "type", target: 'input "Search"', value }`, which is - `RuntimeImpl.user`. It starts an instant `user` op, merges keystrokes on the same target into one typing event, and - calls `Context.stickUser`, so the app's own listener in the same task runs with that op as ambient (the test calls - `rt.user(action, handler)` directly, which runs the handler inside `Context.run`). -2. **Query write bypasses.** The handler's `search.set(v => ({ ...v, query: q }))` reaches `StoreHub.propose`. Its cause - is the task's user op, so it is *user-sync* and bypasses the gate (`policy.holdUserWrites` is false): applied at once, - `search.query` gets a new version with writer `#5`. -3. **Request -> fetch op.** `fetch("/api/search?q=rea")` hits the wrapper from `installFetch`: `startOp("fetch", "GET - /api/search")` with detail `?q=rea` and cause `#5` (`#6`); `Baselines.start` records the start; `registerIdentity` - records the request identity. The request gate raises a `request` trigger (hold, priority 2). Its salient facts - would be R3 (an *identical* request close by), R5 (≥ 2 failures in a row) or R7 (hot rate); `q=rea` and `q=reac` - have different identities, nothing failed, and no usual rate is learned yet, so every fact is neutral and the - request is sent at once with no model call. The same happens 90 ms later for `#7` -> `#8`. -4. **The newer response lands first.** `#8` answers after 120 ms. `endOp` records latency and outcome; the fetch op is - stuck as ambient while the app reads the body (`instrumentResponse`), so `search.set(... results ...)` is a write - with cause `#8`. `gateMutation` -> `trigger({ trigger: "mutation", m })` computes facts: no other chain wrote the - written fields since `#8` started, and the only other in-flight `GET /api/search` (`#6`) is older, so nothing is - salient; the controller's `passive()` runs synchronously and the write applies in the caller's stack. - `search.results` goes to version 1, writer `#8`. -5. **The older response arrives.** `#6` answers at 900 ms; its write proposes `results: ["rea-1", "rea-2"]` with cause - `#6`. Now `computeFacts` (`mutationFacts`) finds M2 (salient: `search.results` was written by another chain since - `#6` started) and M5 (salient: `search.query`, same store, changed by another chain since then), plus neutral - provenance (M1) and delta (M15). Triage passes. `buildSituation` builds the situation; `toJevState` shapes it to the - budget (the test fixes 1,000 chars, which is also the auto budget on single-threaded WASM): + -> `installDomUser`; trusted events only unless `observe.untrustedEvents`) calls `RuntimeImpl.user`, which starts + an instant `user` op and sticks it as ambient so the app's own listener in the same task runs under it (the test + calls `rt.user(action, handler)` directly). +2. **Query write applies at once.** `search.set(v => ({ ...v, query: q }))` reaches `StoreHub.propose`. Its cause is + the task's user op, so it is *user-sync*: it bypasses everything and applies in the caller's stack (`search.query` + gets a new version, writer `#5`). Store writes are never held by default anyway. +3. **Request -> fetch op.** `fetch("/api/search?q=rea")` hits `installFetch`'s wrapper: `startOp` creates `#6` + (cause `#5`), `Baselines.start` records it, and the request gate raises a `request` trigger. Its facts are neutral + (different identities, nothing failed, no learned rate), so the request is sent at once with no model call. Same + for `#8` 90 ms later. +4. **Earlier responses pass the delivery gate without cost.** When `#2` (`q=r`) arrives, its signature has no + completed run yet, so its predicted write set is unknown and it is released at once. When `#8` arrives after + 120 ms, `predictedWrites` says the signature writes `search.results` (what its last completion wrote); the last + writer of that field (`#4`) started before `#8`, so there is no conflict: `runDelivery` releases synchronously, reads + no body and asks nothing. The app's write `results = ["reac-1", "reac-2"]` (writer `#8`) is `covered` by that + delivery (`op.delivery` known, covering the field, not salient), so it raises no `mutation` trigger either. This is + why clean, in-order typeahead makes zero model calls (`delivery.test.ts` -> "clean typing ... makes zero model + calls"). +5. **The stale response arrives (`#6`, after 900 ms).** `runDelivery` finds a **newer-data conflict** on + `search.results`: it changed since `#6` started, and `#8` started after `#6`, is outside `#6`'s chain, is not a user + action, and no newer `GET /api/search` is still in flight. `op.delivery.salient` is set. Because a conflict exists, + the gate reads the buffered clone of the body (≤ 256 KB JSON, waiting at most 100 ms); `analyzeBody` locates + `results` in `{ q, results: ["rea-1", "rea-2"] }` and finds it differs from the current `["reac-1", "reac-2"]`, so + the delivery stays salient. The app's `await fetch(...)` promise has not resolved yet. +6. **Trigger, facts, situation.** `trigger(spec, ctl, { hold: true, priority: 2 })` recomputes the facts (the version + fact is non-neutral), passes triage and builds the situation. `defer` is not offered because no related operation + is in flight, so the action question is `deliver | discard`. At a 1,000-char budget (1-thread WASM; compact + questions) the model receives this (STATUS.md, "delivery at 1000 chars (951)"): ```text app: /search -trigger: A write to search.results from GET /api/search?q=rea (#6) is about to be applied. +trigger: The response to GET /api/search?q=rea (#6) arrived and is about to be delivered; its operation last wrote search.results. facts: - search.results was written once by other operations since this write's cause (#6) started (version 0 → 1), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). - search.query changed since this write's cause (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. - This write comes from GET /api/search?q=rea (#6), started 0.90s ago, ended 0.00s ago with 200; its chain began with user typed "rea" into input "Search" (#5). - This write would change search.results: 2 items ["reac-1", "reac-2"] → 2 items ["rea-1", "rea-2"]. + search.results was written twice by other operations since its operation (#6) started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). + The response has search.results = 2 items ["rea-1", "rea-2"]: neither the current value 2 items ["reac-1", "reac-2"], nor the value when #6 started. + search.query changed since its operation (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. + The response to GET /api/search?q=rea (#6) arrived after 0.90s (200); the app has not seen it yet. + This request comes from user typed "rea" into input "Search" (#5), started 0.90s ago. in_flight: none -timeline: - -0.00s end GET /api/search?q=rea (#6): 200 in 0.90s -state: - search.results = 2 items ["reac-1", "reac-2"] (v1, by #8 0.69s ago) - search.query = "reac" (v4, by #7 0.81s ago) +timeline: none +state: none stats: GET /api/search: 4 done, 0 of last 4 failed, 4 in last 10s questions: diagnosis: What is happening here? expected | stale | conflict | duplicate | inconsistent | failing | slow | overload | unusual | transient - action: What should the runtime do with this write? apply | discard | defer + action: What should the runtime do with this response or message? deliver | discard ``` - This is `stateText` of the `JevState` plus the test's printout of the questions. The model receives the `state` - object and a `questions` object of two `choice` questions whose `criteria` are all `null` (compact questions at - ≤ 1,400 chars). At the full 3,200-char budget the same write carries a 16-line timeline and described options; that - version is in `packages/runtime/STATUS.md` ("Example situations: full budget"). Its timeline also shows that in this - test the `#2` and `#4` writes were themselves dropped (`GenClass Dropped the write to search.results from GET - /api/search?q=re (#4); search stays at version 3.`), which is why `search.results` was still at version 0 when `#6` - started. -6. **Hold.** In `guard` mode the permitted set is `discard` and `defer` (guard tier; `defer` is offered while - `m.defers < 2`), so `waits` is true: `gateMutation` returns `{ held }` and the hub keeps the write queued. A budget - timer is armed (`RuntimeImpl.holdBudgetMs`), and `DeciderQueue.submit` gets priority 2 and deadline - `t0 + budget + 2000` (the extra 2 s is the late-revert window, since mutation controllers can revert). -7. **Model.** `ModelHost.evaluate` -> Worker -> `ModelBackend.evaluate` -> `Engine.evaluate`: `Packer.pack`, one forward - pass, `unpackLogits`, `calibrateLogits` and `buildAnswer` per question. The result is `{ diagnosis: ChoiceAnswer, - action: ChoiceAnswer }`, each with `probabilities` in criteria order. -8. **Gate.** `RuntimeImpl.onDecision` -> `gate`: A = {`discard`, `defer`}; candidate = the more probable of the two; it - runs iff p(discard) + p(defer) ≥ 0.9, the top diagnosis is not `expected`, the rate limiter has room, and the subject - is still held. A `Decision` is recorded either way; `decide` fires, and `detect` fires when the diagnosis is not - `expected` with p ≥ 0.6. -9. **Action.** If `discard` passes: `rate.take`, then the mutation controller's `run("discard")` settles the verdict - `discard`; the hub drops the write and the app is never notified, so `search.results` keeps the `reac` results. The - `ActionRecord` has `changed` = `Dropped the write to search.results from GET /api/search?q=rea (#6); search stays at - version <v>.` and an `undo` that commits the original write as a GenClass write. An `action` event is pushed, so - later situations show `GenClass Dropped the write ...` in their timeline. -10. **Report.** With diagnosis `stale`, `interventionLine` prints `[GenClass] Prevented a stale write: <first - non-provenance fact> <changed> (stale, <p>; discard <p>)`, here led by the M2 fact. The console groups the facts, - timeline, exact situation text and answers under it, plus an undo hint and a deny hint. `rt.explain("<id>")` - returns the same evidence; the devtools Interventions card offers Undo. - -Other outcomes of the same trigger: + The second fact is F1's "third value" form (the response matches neither the current value nor the value when `#6` + started). At 2,000 and 2,400 chars the same delivery carries a full timeline and state section and described + options; both versions are in STATUS.md. +7. **Hold.** In `guard` mode `discard` is permitted, so if `expectedLatency() <= holdBudgetMs()` the delivery waits: + a budget timer is armed and `DeciderQueue.submit` gets priority 2, deadline `t0 + budget` (a delivery has no + late-revert window) and `ctl.stale` (true once the response is released). Holding is only latency: the `Response` + object is unchanged. +8. **Model.** `ModelHost.evaluate` -> Worker -> `Engine.evaluate`: pack, one forward pass, calibrate. The result is + `{ diagnosis, action }`, each with `probabilities` in option order. +9. **Gate.** `RuntimeImpl.onDecision` -> `gate`: A = {`discard`}; it runs iff p(discard) ≥ 0.9, the top diagnosis + is not `expected`, the rate limiter has room and the delivery has not been released. `op.delivery.decided` is set, + which makes `#6`'s later writes `covered` (no extra `mutation` decision). A `Decision` is recorded either way. +10. **Discard.** The controller's `run("discard")` sets `op.discardMark = { protect: {search.results}, until: now + + 10 s }` and releases the response. The app's promise resolves, it parses the JSON and calls + `search.set(v => ({ ...v, results }))` with `#6` as the ambient cause. `StoreHub.propose` -> `applyFilter` -> + `RuntimeImpl.dropFilter` walks the cause chain to `#6`'s mark and drops the change to `search.results` (protected, + and written over by `#8`). Other fields of the same write would still apply; here none remain, so the write is + dropped whole and nothing is notified. An `action` event `dropped the write of search.results by GET + /api/search?q=rea (#6) over newer data` is pushed. `search.results` keeps the `reac` results. +11. **Record and report.** The `ActionRecord` has `changed` = `Delivered the response to GET /api/search?q=rea (#6) + and dropped the state changes it makes over newer data (search.results).`, `dropped: ["search.results"]` and an + `undo` that restores the dropped values. The console prints `[GenClass] Prevented a stale response: <first fact> + <changed> (stale, <p>; discard <p>)` with the evidence grouped under it; `rt.explain(id)` returns the same + evidence and the devtools Interventions card offers Undo. + +Other outcomes of the same delivery: | condition | result | |---|---| -| gate fails (mass < 0.9, top diagnosis `expected`, rate limit) | `apply` runs when the answer arrives; the stale results show; if the diagnosis is `stale` with p ≥ 0.6, a `Flagged a stale write: ...` detection line prints (with a `Not acted on (...)` clause when the gate recorded a reason) | -| model slower than the hold budget | the budget timer applies the write (fail open); a gate-passing `discard` within 2 s can still revert it if nothing changed those fields since (`Reverted a stale write: ...`, `ActionRecord.late`) | -| `mode: "observe"` | nothing is permitted, so the write applies at step 6 with no hold; the decision is made in the background (deadline 5 s) and can only flag | -| model loading, failed or absent (the alpha default once the card fetch fails) | `consultable()` is false; `gateMutation` returns no hold, no facts are computed, nothing is recorded; the stale write applies exactly as without GenClass | -| model status `off` (lazy preload not started) | facts and triage run; this salient write starts the model load and applies at once (fail open) | - -Known product risks on exactly this path (open in code, `demos/NEEDS.md`): holds add latency to typeahead-like apps -(§2; search clean p50 14 -> 125 ms with v0.1), and a held write can land after a newer user-sync write to the same -store (§1). Store names must not contain `.` (for example `search.results` as a store name): nothing enforces it, -and the version facts that detect this bug then always say the field "has not changed" -([state-and-adapters](runtime/state-and-adapters.md)). +| default `mode: "observe"` | nothing is permitted, so `waits` is false and the response is released as soon as the trigger runs (after the body read, up to 100 ms: the pre-filter does not check the mode). The release marks the chain as delivered over newer data (F9). Because the subject is already released, the queued delivery decision is dropped as stale before the model sees it; the app's write is not `covered` (salient, not decided), so `observeWrite` raises a background `mutation` decision instead, which can only flag (`[GenClass] Flagged a stale write: ...`). | +| gate fails (mass < 0.9, top diagnosis `expected`, rate limit) | `deliver`: the stale results show; a `Flagged a stale response` detection line prints when the diagnosis is not `expected` with p ≥ 0.6 | +| model not expected within the hold budget (`expectedLatency` too high) or slower than the budget | the response is released at once or at the budget (fail open); the writes are then not `covered`, so they get a background `mutation` decision, and a gate-passing `discard` can **late-revert** the write within 2 s if nothing changed those fields since (`delivery.test.ts` -> "a slow model: the response is released at the budget, its writes are decided in the background and late-reverted") | +| model loading, failed or absent (every install today: the default model URL 404s) | `consultable()` is false: `runDelivery` releases at once, no facts are computed, nothing is recorded; the stale write applies exactly as without GenClass | +| model status `off` (lazy preload not started) | the pre-filter and facts run; this salient delivery starts the model load and is released at once (fail open) | +| `heal` mode | as `guard` here (no heal-tier delivery action) | + +Known risks on exactly this path, from the 2026-10-08 adversarial review (open at b435acb; details and proposed fixes +in [decide-policy-actions](runtime/decide-policy-actions.md) and [state-and-adapters](runtime/state-and-adapters.md)): + +- The discard mark lasts 10 s and is found by walking the cause chain, so later operations chained from the + discarded one (a `setTimeout` poll loop, a saga) can have their fresh writes dropped too (`RuntimeImpl.dropFilter`, + `RuntimeImpl.writtenOver`). +- On Redux/Zustand stores a write that would be only partly dropped is applied whole (`StoreHub.applyFilter`, + fail-open), yet the `ActionRecord` still says the changes were dropped (`dropped: []`). +- Observe mode, the new default, still delays a candidate delivery by up to 100 ms for the body read, and XHR + completion listeners queued during that wait run outside the original dispatch (`e.currentTarget === null`). +- Discard marks survive `pause()` and `setMode("observe")`; a delivery `defer` (two rounds of up to 10 s each) can + stall a whole WebSocket/EventSource channel; held WebSocket/EventSource messages are dispatched even after the app + called `close()` (`MessageGate.pump`). ## 5. Offline loops -### 5.1 Training-data loop (sim) +Training rows come from three producers that all record the runtime's own `EvaluateRequest` bytes (`state`, +`questions`) or a byte-exact Python port of them, and share one row schema (CONTRACT-D: `{id, split, family, state, +questions, labels, meta}`). Details: [model-io-contract](model-io-contract.md). + +### 5.1 SIM: simulated apps driving the real runtime ```text -seed -> buildScenario (domain, features, net, budget, split) -> ideal run + base run (real runtime, recording decider) - -> sampled decision points k -> one counterfactual run per applicable action x up to K=3 paired futures - -> runCost vs ideal -> actionLabel (soft action distribution) + diagnose (hard diagnosis label) - -> CONTRACT-D rows {id, split, family, state, questions, labels, meta} -> <out>/{train,dev,test}.jsonl + stats.json +seed -> buildScenario (domain, features, personas, net + chaos, budget, split) + -> ideal run + base run (real createRuntime on a VirtualLoop, recording decider) + -> gold: sampled decision points k -> one counterfactual run per applicable action + x K = 2-3 paired futures (S2: futures 1-2 re-draw what the runtime cannot observe) + -> runCost vs ideal -> actionLabel (soft) + diagnose (hard; S1 relabels `expected` when acting + clearly wins) + -> unlabeled: every decision point of the base run (gold diagnosis, no action label) [--unlabeled] + -> on-policy: an exported model decides through the production gate; points labelled as gold [--on-policy] + -> <out>/{train,dev,test}.jsonl + stats.json; cluster runs collect to gz shards ``` -- CLI and workers: `sim/src/gen.ts` -> `main`; one trajectory: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, - `pointCosts`; one run: `sim/src/run/runner.ts` -> `runScenario` on a `VirtualLoop` (`sim/src/loop.ts`). -- The real runtime is loaded by `sim/src/run/rt.ts` -> `realRuntimeFactory` with `createOptions`: `model: false`, the - sim's recording decider, `mode: "heal"`, `triage: "salient"`, a fixed `situation.budget` (3200/2000/1000), observers - `fetch`, `timers`, `websocket` only, gate thresholds 0.5 with `requireDiagnosis: false` so exactly the forced action - runs. The decider stores every `EvaluateRequest`'s `state` and `questions` verbatim: the sim never writes situation - text, which is what keeps train/runtime parity. -- Labels: `sim/src/oracle/cost.ts` -> `runCost`, `actionLabel` (tier premium 0/0.25/0.5, ties within 0.05 pinned to - passive); `sim/src/oracle/diagnose.ts` -> `diagnose`. Plus diagnosis-only rows and `ask` rows with exact labels. -- Output so far: phase A on the frozen runtime, 600,676 rows (`sim/samples/stats-final-a.json`). Detail: [sim](sim.md). - -### 5.2 Training and export loop +- CLI and workers: `sim/src/gen.ts` -> `main` (modes `gold`, `unlabeled`, `onpolicy`); one trajectory: + `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts`; one run: `sim/src/run/runner.ts` -> + `runScenario`; latent re-draws: `sim/src/run/latent.ts`. +- The real runtime is loaded by `sim/src/run/rt.ts` -> `realRuntimeFactory` with `createOptions`: `model: false`, + the recording decider, `mode: "heal"` (so the observe default does not affect the sim), `triage: "salient"`, + observers `fetch`, `timers`, `websocket`, `storage`, thresholds 0.5 with `requireDiagnosis: false` and + `holdBudgetMs: 1e9`, so exactly the forced action runs. The sim never writes situation text. +- Data: phase A (600,676 rows) and phase B (1,415,344) are situation-v1 and do not match the runtime. The v2 runs + (≥ 10M gold + ≥ 50M unlabeled) are being generated on 20 Azure nodes into `train:/data/sim-out/v2-*` by the + colleague (HANDOFF.md, `training/NEEDS.md`; unverified from here). Detail: [sim](sim.md). + +### 5.2 REAL: real apps in headless Chromium + +- `realapps/` runs 91 apps built with real frameworks (React, Vue, Svelte, Solid, Lit, Angular, Elm, jQuery, Redux, + Zustand, TanStack Query, SWR, XHR libraries, ...) with the runtime bundled **from source**, on virtual time with an + in-page mock backend and chaos (`realapps/src/world/*`). It closes the sim-to-real gap (framework schedulers, query + dedupe, XHR libraries, middleware). It is also the only producer of XHR deliveries and of user actions recorded by + the DOM observer, since the sim turns off the `xhr` and `user` observers (it calls `runtime.user` directly) and no + sim code references `EventSource` (inferred from `createOptions` and a grep; see + [learn-situation-triage](runtime/learn-situation-triage.md) Drift). +- It labels sampled decisions the same way as the sim, importing the sim's cost weights, `actionLabel` and question + transforms (`realapps/src/harness/trajectory.ts` -> `generateTrajectory`, `realapps/src/harness/cost.ts` -> + `runCost`), and writes gold, unlabeled, diagnosis-only and ask rows with `meta.source = "realapps"` + (`realapps/src/harness/gen.ts`). Runs use an explicit `mode` (default `heal`), so the observe default does not + change them. +- It is also the runtime's never-worse harness (`realapps/src/harness/debug.ts` -> `--interference`, `--det`). +- Data: v2 batches `v2b1`–`v2b3` on c01, c10, c11 (≈ 30k trajectories each, target ≥ 500k gold rows) go to + `train:/data/real-out/` (`training/NEEDS.md`, HANDOFF.md; unverified from here). `realapps/scripts/evalset.py` + builds the real-app eval set (366 rows exist from a v1 pilot per RESULTS.md §6). Detail: [realapps](realapps.md). + +### 5.3 The v2 training program: teacher -> distillation -> DAgger -> export ```text -prune_vocab.py (16,000 merges -> 16,364 tokens) - -> stage 1 / 1c: synthetic curriculum (curriculum/generate.py; cur1 varied style in s1, cur2 adds rt.py runtime-exact rows in s1c) - -> stage 2 / final rounds: jev_local/train/train.py on SIM rows + curriculum replay (configs/mix_*.json, Azure nodes) - -> eval_runtime.py (FIR, precision, recall, cost regret, ECE; --write-calibration -> calibration.json) - -> export_runtime.py (<name>-q8.onnx: 8-bit MatMulNBits + int8 embeddings; <name>-fp16.onnx; tokenizer.json, - calibration.json, meta.json, model.json card "genclass-runtime-model/1"; parity fixtures) - -> ortweb/validate.mjs (onnxruntime-web WASM vs torch logits) - -> [planned] publish as @genclass/runtime-model@0.1.0 (jsDelivr serves files/ = DEFAULT_MODEL_BASE_URL) - + GitHub release runtime-model-v0.1.0 (the CLI's default --from) - -> runtime: model/loader.ts fetchCard -> parseCard -> planOrder -> fetchFile (size + sha256, Cache Storage) - -> ModelBackend.load -> Engine (graph-contract check, warm-up) -> status "ready" +prune_vocab.py (16,000 merges -> 16,364 tokens, shared by every model) + -> curriculum/generate.py (+ rt.py runtime-exact rows, frozen at situation-v2; no v2 set generated yet) + -> P1 T150 teacher (ettin-150m, never shipped) on SIM v2 gold (+ REAL gold) launch_t150.sh / launch_student.sh + -> P3 teacher soft-labels a prioritised subset of the unlabeled rows label_teacher.py, label_cluster.sh + -> P4 distil students R17 (default) and R32 (R68 as a benchmark) on gold + teacher labels + curriculum replay + -> P5 DAgger x3: export students -> SIM --on-policy rows -> retrain + -> eval_runtime.py (FIR, precision, recall, regret, ECE; --write-calibration -> calibration.json) + -> export_runtime.py (<name>-q8.onnx, <name>-fp16.onnx, tokenizer.json, calibration.json, meta.json, + model.json card "genclass-runtime-model/1", parity fixtures) -> ortweb/validate.mjs + -> [planned] @genclass/runtime-model@0.1.0 (jsDelivr serves files/ = DEFAULT_MODEL_BASE_URL) + -> runtime: model/loader.ts fetchCard -> planOrder -> fetchFile (size + sha256, Cache Storage) -> Engine -> "ready" ``` -- Candidates: R17 (ettin-encoder-17m, d 256 × 7 layers, intended for WASM) and R32 (GenClass 0.1 `jev-local-fast`, - ettin-32m, d 384 × 10 layers, WebGPU only if clearly better; OPEN_TASKS item 5). -- Code: `training/curriculum/generate.py`, `training/curriculum/rt.py` -> `render`, `to_state`; - `jev_local/train/train.py`; `training/eval_runtime.py` -> `fit_calibration`, `decision_metrics`; - `training/export_runtime.py` -> `main` (graph from `scripts/genclass_export.py`); - `packages/runtime/src/model/loader.ts` -> `fetchCard`, `parseCard`, `planOrder`, `fetchFile`. -- Results so far: stage 1c held-out `rt1` action/diagnosis about 98% with 0% FIR; the stage-2 pilot (pre-freeze data) - was precise but rarely acted (heal recall about 1.3%); final round 1 has no results in the repo. Detail: - [training](training.md), [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - -### 5.3 Evaluation loop (demos) +- Plan and phases: `training/PLAN-v1.md` (P0–P5, cost estimates ≈ $3–4k); order of work: HANDOFF.md "How to + continue". A T1 side track (`training/t1_relabel.py`, `eval_gain.py`) trains on expected-advantage targets from + SIM `meta.cost_futures`. +- Candidates: R17 (`jhu-clsp/ettin-encoder-17m`, d 256 × 7 layers, q8 9.58 MB) is the default on every device; + R32 (GenClass 0.1 `jev-local-fast`, ettin-32m, d 384 × 10 layers, q8 22.5 MB) matched it at about 3× the latency + in round 1 (RESULTS.md §2). +- Baseline to beat: final round 1 (situation-v1, 448k phase-A rows) R17: diagnosis 90.5%, action 81.9%, guard FIR + 0.05%, heal FIR 0.24%, ECE 0.009, but guard recall on clear stale/duplicate cases only 7.7%. `sim/SEPARABILITY.md` + traced that to the data (benign twins with identical facts, `expected` mislabels, hindsight labels), which v2 + addresses with new facts (F1–F9), S1 and S2. +- Code: `training/curriculum/rt.py` -> `render`, `to_state`; `jev_local/train/train.py`; + `training/label_teacher.py` -> `main`; `training/eval_runtime.py` -> `fit_calibration`, `decision_metrics`; + `training/export_runtime.py` -> `main`. Detail: [training](training.md), [genclass-model-lineage](genclass-model-lineage.md). + +Known risks in this pipeline from the 2026-10-08 review (none fixed at b435acb; tell the colleague before acting, +since his v2 generation is running): + +- `sim/src/world/scenario.ts` still samples the v1 3,200-char budget for 40% of trajectories (`[[3200, 40], [2000, + 30], [1000, 30]]`); the runtime never exceeds 2,400, and `realapps/src/harness/scenario.ts` does the same. +- SIM and REAL unlabeled rows carry a hard `diagnosis` label, including `expected` cases that S1 would relabel, and + `label_teacher.py` keeps existing labels by default. +- `training/label_cluster.sh` lists `*.jsonl` only (collected SIM shards are gz), has no split filter and no gather + step, and touches its done marker unconditionally; `training/final_post.sh` and `eval_sim.sh` are hard-wired to the + v1 eval set `simAe`. +- `realapps/scripts/evalset.py` reads `test,dev,train` by default and does not classify `delivery` rows; + `realapps/src/harness/gen.ts` writes `runtime: "situation-v1 ..."` into every batch manifest. +- `training/curriculum/rt.py` diverges from the frozen renderer in several common cases (an extra "Recent ... + outcomes" fact on failure rows, timeline selection, no-op writes, F1 vs F2 wording). + +### 5.4 Evaluation loop (demos) - Six apps (`search`, `editor`, `checkout`, `status`, `board`, `decisions`), each with a deliberate latent bug, on a Service Worker mock API with seeded chaos. GenClass is created only in `demos/src/shared/genclass.ts` -> - `startGenClass`: **Off** = `GenClass.init({ mode: "observe", model: false })` (installed, never decides), - **Guard** / **Heal** = `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. App code is identical. -- A trial is a seeded scenario run in a fresh page by `demos/src/shared/harness.ts` -> `TrialHarness` with the - synthetic driver (`demos/src/shared/driver.ts` -> `runSteps`) or Playwright (`demos/e2e/eval.ts`), scored by the - demo's oracle (DOM + server truth only). `demos/src/shared/aggregate.ts` -> `summarizeMode` reports Wilson bug - rates on chaos trials, false interventions on clean trials, fixed/introduced vs Off, and latency medians. -- Shipped `demos/results.md` (810 trials, v0.1 model (not trained for runtime decisions), WASM q8): no executed action lowered a bug rate, - 0 false interventions, holds added latency (search) and introduced board bugs. Detail: [demos](demos.md). - -### 5.4 How a runtime change reaches the shipped model - -CORE changes text the model reads -> the lead freezes it with a tag -> SIM regenerates rows from that exact runtime -> -TRAIN mirrors the wording in `training/curriculum/rt.py`, trains, calibrates, evaluates, exports -> MODEL checks TS -packer/engine parity against the export's fixtures -> the lead publishes the model package, then the runtime. Any -change to facts, timeline/state/stats lines, question wording, diagnosis labels, budgets, `util.ts` formatters, op or -event names, the packer, tokenizer or calibration lookup is a model-format change -([model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md)). + `startGenClass`: **Off** = `GenClass.init({ mode: "observe", model: false })`, **Guard** / **Heal** = + `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`. The demos always pass `mode`, so the new default + does not change them; the in-page "Run trials" driver uses synthetic events, which the runtime now ignores unless + `observe.untrustedEvents` is on (the Playwright eval uses real input). +- Shipped `demos/results.md` (810 trials) used the v0.1 model (not trained for runtime decisions) on the frozen + batch-3 runtime (situation-v1): Guard executed 0 actions yet raised bug rates through store-write holds, which + drove the v2 redesign. Nothing has been measured on the demos with the v2 runtime; the rerun comes after the v2 + model package. Detail: [demos](demos.md). + +### 5.5 How a runtime change reaches the shipped model + +CORE changes text the model reads -> a new freeze tag (now `situation-v2`) -> SIM and REAL regenerate rows from that +exact runtime (REAL pins it with `RW_RUNTIME_SRC`/`RW_RUNTIME_TAG` from a `git archive` of the tag) -> TRAIN mirrors the +wording in `training/curriculum/rt.py`, trains the teacher, labels, distils, runs DAgger, calibrates, evaluates and +exports -> MODEL checks TS packer/engine parity against the export's fixtures -> the user publishes the model +package, then the runtime (2FA). Any change to facts, delivery salience, timeline/state/stats lines, question wording, +diagnosis labels, budgets, `util.ts` formatters and redaction, op or event names, the packer, tokenizer or +calibration lookup is a model-format change ([model-io-contract](model-io-contract.md)). ## 6. Modes and what each allows Mode-tier rule: `packages/runtime/src/decide/policy.ts` -> `modeAllows`. Thresholds from `policyConfig`: report 0.6, -guard 0.9, heal 0.8. +guard 0.9, heal 0.8. Default: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"` +(f3636b2; CONTRACT §13 entry; `test/default-mode.test.ts`). | mode | how to get it | actions that can run | holds | decisions and reports | |---|---|---|---|---| -| off (kill switch) | `?genclass=off` or `localStorage.genclass = "off"` (URL wins), read by `packages/runtime/src/index.ts` -> `killSwitch` | none | never | inert runtime: every observer off, no decider, `report: "silent"`; all caller options dropped | -| `observe` | `mode: "observe"`, `?genclass=observe`, `setMode` | passive only | never | with a ready model, salient triggers are still decided in the background and recorded; detections print `Flagged ...` | -| `guard` (default) | `mode` default | passive + guard tier: `discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions | when a guard action is permitted for that trigger | decisions, detections, interventions | -| `heal` | `mode: "heal"` | guard + heal tier: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (default tier heal) | when any non-passive action is permitted | decisions, detections, interventions | - -Also: `policy.allow` / `policy.deny` narrow the permitted set; `pause()` stops gating and triggers while tracing -continues; `setMode` applies to the next gate. Passive actions per trigger: mutation `apply`, request `send`, -failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. Details: -[public-api-and-lifecycle](runtime/public-api-and-lifecycle.md#modes-and-tiers), -[decide-policy-actions](runtime/decide-policy-actions.md). +| off (kill switch) | `?genclass=off` or `localStorage.genclass = "off"` (URL wins), read by `packages/runtime/src/index.ts` -> `killSwitch` | none | never | inert runtime: every observer off, no decider, `report: "silent"`; caller options dropped | +| `observe` (**default**) | no `mode`, `mode: "observe"`, `?genclass=observe`, `setMode` | passive only | never (a candidate delivery may still wait ≤ 100 ms for its body; see section 4) | with a ready model, salient triggers are decided in the background and recorded; detections print `Flagged ...`; delivery decisions are dropped as stale and their writes are decided as `mutation` instead | +| `guard` (opt-in) | `mode: "guard"`, `?genclass=guard` | passive + guard tier: `discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions | when a guard action is permitted for that trigger and the model is expected within the hold budget | decisions, detections, interventions | +| `heal` (experimental) | `mode: "heal"`, `?genclass=heal` | guard + heal tier: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (default tier heal) | when any non-passive action is permitted and the model is expected in time | decisions, detections, interventions | + +Also: `policy.allow` / `policy.deny` narrow the permitted set; `policy.holdWrites: true` re-enables held store writes +(opt-in, never reorders a store's writes); `pause()` stops gating and triggers while tracing continues; `setMode` +applies to the next gate. Passive actions per trigger: mutation `apply`, request `send`, delivery `deliver`, failure +`deliver`, stall `wait`, inconsistency/transition/error `ignore`. The published alpha.0 and HANDOFF.md still say +`guard` is the default; the unit-test harness passes `mode: "guard"`. Details: +[public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). ## 7. With no model: fail open, observe only @@ -335,71 +420,68 @@ and its state is `ready` or `off`. Consequences: | provider state | what triggers do | |---|---| -| no provider (`createRuntime` without `decider`/`model`, `GenClass.init` outside a browser without a `decider`, `model: false`, kill switch) | nothing is computed or held; every subject proceeds; no `Decision` ever | -| `off` (idle preload not started yet) | facts and triage run; the first salient situation starts the load (`void this.ready`) and fails open | +| no provider (`createRuntime` without `decider`/`model`, `model: false`, kill switch) | nothing is computed or held; every delivery is released at once; no `Decision` ever | +| `off` (idle preload not started yet) | the delivery pre-filter, facts and triage run; the first salient situation starts the load (`void this.ready`) and fails open | | `loading` | skipped entirely: no facts, no holds, no records | | `error` | same as `loading`, permanently: `ready` is memoised and nothing retries the load | | `ready` | full pipeline | -What a default `GenClass.init()` does at 654d822 (verified by code reading only; no test covers it): it creates a -model host for `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` -(`packages/runtime/src/model/host.ts`), the idle preload fetches `model.json` from a package that does not exist, -the status becomes `error`, the console prints `[GenClass] Model unavailable (...); observing only.`, and from then on -no situation is built and nothing is held or acted on. Tracing, field versions, baselines, invariants and profiles keep -learning; `rt.situation()` still works; `rt.ask()` rejects with `GenClassUnavailableError` (or the raw provider error -when `timeoutMs` is set). To exercise the decision -pipeline today, self-host the v0.1 GenClass model (`npx genclass-runtime fetch-model <dir> --from -https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, then `model: { baseUrl }`); v0.1 is a general -classifier, not trained for runtime decisions, and answers `unusual` almost always. Full sequence: -[status-and-known-issues](status-and-known-issues.md#1-what-a-default-install-does-today-model-unpublished). +What a default `GenClass.init()` does at b435acb (code reading; no test covers the browser path): it creates a model +host for `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` +(`packages/runtime/src/model/host.ts`); the idle preload fetches `model.json` from a package that does not exist (a +404 per a check on 2026-10-08), the status becomes `error`, the console prints `[GenClass] Model unavailable +(...); observing only.`, and from then on no situation is built and nothing is held or acted on. Tracing, field +versions, baselines, cadence, invariants and profiles keep learning; `rt.situation()` still works; `rt.ask()` rejects. +The CLI's default source (`genclass-runtime fetch-model`, `DEFAULT_FROM`) is a 404 too. The only trained runtime model, +R17-final1, is situation-v1 and lives only on the train VM / the colleague's Mac; it does not match this runtime. Full +sequence: [model-host](runtime/model-host.md). ## 8. Workstreams and ownership -The project was built by parallel workstreams coordinated by a lead, communicating through status and NEEDS files -(detail, conventions and drift: [status-and-known-issues](status-and-known-issues.md#workstreams-and-ownership)). +The project was built by parallel workstreams (roles; every commit up to 74f17c0 is by the colleague, Mehar, and +HANDOFF.md addresses the Claude sessions that continue the work), coordinating through status and NEEDS files (detail, conventions and drift: +[status-and-known-issues](status-and-known-issues.md#people-workstreams-and-ownership)). | workstream | owns | writes | |---|---|---| -| lead | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`, `OPEN_TASKS.md` (inferred); approvals, merges, publishing; `training/` per CONTRACT §1 | contract additions (CONTRACT §13) | -| CORE | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; situation wording; `src/types.ts` | `packages/runtime/STATUS.md` (with "Deviations from the contract") | -| MODEL | `packages/runtime/src/model/**`, `packages/runtime/bin/genclass-runtime.mjs`; co-owns the model-seam section of `types.ts` | `packages/runtime/src/model/README.md`, MODEL -> TRAIN notes in `training/NEEDS.md` | +| lead | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`, `OPEN_TASKS.md`, `HANDOFF.md` (inferred); approvals, merges, publishing (the user's 2FA) | contract additions (CONTRACT §13); `docs/runtime/RESULTS.md` (HANDOFF: "update it with every result") | +| CORE | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; situation wording; `src/types.ts` | `packages/runtime/STATUS.md` (batches, contract deltas, deviations) | +| MODEL | `packages/runtime/src/model/**`, `packages/runtime/bin/genclass-runtime.mjs`; co-owns the model-seam section of `types.ts` | `packages/runtime/src/model/README.md`, notes in `training/NEEDS.md` | | UI | `packages/runtime/src/devtools/**`, `packages/runtime/src/adapters/**` (CONTRACT §13) | `packages/runtime/UI-NEEDS.md` | -| SIM | `sim/` | `sim/NEEDS.md`, `sim/README.md` | +| SIM | `sim/` | `sim/NEEDS.md`, `sim/README.md`, `sim/SEPARABILITY.md` | +| REAL | `realapps/` | `realapps/README.md`, `realapps/EXAMPLES.md`, requests and node claims in `training/NEEDS.md` | | DEMOS | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*.{md,json}` | -| TRAIN | `training/` (per `training/README.md`; CONTRACT §1 lists the lead as owner) | `training/NEEDS.md`, `training/LOG.md`, `training/EVAL.md` | +| TRAIN | `training/` (per `training/README.md`; CONTRACT §1 lists the lead as owner) | `training/NEEDS.md`, `training/LOG.md`, `training/EVAL.md`, `training/PLAN-v1.md` | | REVIEW | `packages/runtime/test/review-*.test.ts` (a contract: fix code, not these tests) | findings fixed in batch 3 | +| us (this machine) | commits 7dab2b3 (agent docs), f3636b2 (default mode `observe`), b435acb (CI, lockfile) on `mvp-v2` | `AGENTS.md`, `CLAUDE.md`, `docs/agents/**` | -NEEDS items carry OPEN / ASK / DONE (plus INFO in `training/NEEDS.md`); contract changes go through the lead; SIM and -DEMOS must not read each other's code. For an agent working alone, these files are the record of intent: update the -relevant STATUS/NEEDS entry when you change behaviour they describe. +NEEDS items carry OPEN / ASK / DONE (plus INFO in `training/NEEDS.md`); contract changes go through the lead; SIM, +REAL and DEMOS must not read each other's code. For an agent working alone, these files are the record of intent: +update the relevant STATUS/NEEDS entry when you change behaviour they describe. -## 9. Where the project stands (654d822) +## 9. Where the project stands (b435acb, 2026-10-08) | item | state | |---|---| -| Runtime core, model host, devtools, adapters | done; source frozen at `situation-v1` | -| npm | `@genclass/runtime@0.1.0-alpha.0` published (per `OPEN_TASKS.md`; tag `v0.1.0-alpha.0`); it takes no actions until the model package exists | -| Model package | `@genclass/runtime-model@0.1.0` not created (`packages/runtime-model/` has only `MODEL_CARD.md`); no `runtime-model-v0.1.0` tag exists for the planned GitHub release | -| SIM data | phase A done (600,676 rows); phase B (1.4M rows) in progress at commit time | -| Training | stage 1c done; stage-2 pilot done; final round 1 (R17, R32 on phase A) launched, no results in the repo | -| Demos | built; results only with the v0.1 model (not trained for runtime decisions); `demos/src/server/data/cities.ts` is missing from git (root `.gitignore` rule `data/`), which blocks building the search demo from a fresh clone | -| Next (`OPEN_TASKS.md`) | choose R17/R32, publish the model package and release, then `@genclass/runtime@0.1.0`; add CI; re-run demos with the trained model; investigate hold-induced harm and typeahead triage sensitivity (salient about 6 times per clean trial) | -| Open runtime issues | `demos/NEEDS.md` §1 (held write lands after a newer user write), §2 (hold latency), §5 (`retry` offered for non-idempotent requests), §6 (no EventSource observer) | -| Infrastructure | no `.github/` (no CI); no committed root `package-lock.json`; test files are not type-checked; `jev_local/data/` is missing (gitignored), so 20 legacy Python test files fail at collection | - -**Local verification when these docs were written (2026-10-07; macOS, 16 GB RAM, Node v25.6.0, npm 11.8.0).** `npm install` at the -root succeeds in about 18 s (one EBADENGINE warning for vitest 5.0.3 on Node 25; it creates an untracked root -`package-lock.json` and chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, revert with `git checkout -- -packages/runtime/bin/genclass-runtime.mjs`). In `packages/runtime`: `npx tsc -p tsconfig.json --noEmit` is clean; -`npx tsup` builds in about 2.5 s; `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` gives -286 passed and 14 skipped (the model-parity tests that need `GENCLASS_MODEL_DIR`). Not run: Playwright, the smoke -test, sim, training, demos, Python tests, model downloads, anything on Azure. - -**Working rule for agents (set when these docs were written).** CONTRACT §0 rule 5 ("the Mac only edits files"; everything on the -Azure `train` VM through `scripts/vm.sh`) existed because the original author's Mac had 8 GB RAM. On other machines, -`npm install`, typecheck, build and unit tests are light and verified to work locally. Ask the user before running the -sim, training, Playwright, model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, -`training/*.sh`, `sim/scripts/*`). Do not change situation text without a plan for regenerating data and retraining. +| Branches | `mvp-v2` = origin/runtime 74f17c0 + our three commits (not pushed). The local branch `mvp` (based on 654d822, situation-v1) is superseded. Tags: `situation-v1` (1a77558), `situation-v2` (6e5e86e, current format), `v0.1.0-alpha.0` (654d822). | +| Runtime | batches 4 and 5 done: decisions at the network boundary, no store holds by default, EventSource observer, F1–F9 facts, leaf-based redaction, 2,400-char full budget; default mode `observe` (ours). | +| Tests | lead's run on `mvp-v2` (macOS, Node v25.6.0): `tsc` clean, `tsup` OK, vitest 351 tests = 337 passed + 14 model-parity skips (333 + 14 in the main run, counting the uncommitted `atoms.test.ts` test, 4 in `review-perf.test.ts` alone; it flaked once at 5.5 ms vs its 2 ms bound under parallel load). sim: `tsc` clean, `SIM_RUNTIME=real npx vitest run` 19 passed in 5 files. Not run: Playwright, `smoke.sh`, realapps, demos eval, Python tests, training. | +| CI | `.github/workflows/ci.yml` (Node 22, `npm ci`, typecheck, build, unit tests, then `review-perf` with `--retry=2`); its steps pass in a fresh clone; it has not run on GitHub yet. | +| npm | `@genclass/runtime@0.1.0-alpha.0` is `latest` (situation-v1 code, default `guard`, no model). Pending with the user's 2FA: `0.1.0-alpha.1` (NaN fix, `OPEN_TASKS.md` "Needs the user"). `@genclass/runtime-model` is a 404. Release procedure: [RELEASE.md](../../RELEASE.md). | +| Model | no situation-v2 model. R17-final1 (situation-v1) is the baseline only (section 5.3). | +| Data | SIM v2 (≥ 10M gold + ≥ 50M unlabeled) on c02–c09 and c12–c23; REAL v2 (≥ 500k gold) on c01, c10, c11; the colleague is operating the cluster (a read-only portal look at 04:14 UTC showed c01–c23 and `vm-jev-train` running, `vm-jev-data` deallocated). Nobody on our side touches Azure. | +| Never worse | realapps sweep, v2 runtime, all-passive model: 0/396 clean runs changed, 3/198 with chaos (request-time holds shifting chaos draws; open), determinism 198/198, conduit 0/30 (STATUS.md). These cover the 66 apps at the time, not the 25 added since, and compare final visible text and server content only ([realapps](realapps.md)). | +| Next (HANDOFF.md) | v2 data collected -> 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. | +| Doc drift | HANDOFF.md still calls `guard` the default; CONTRACT.md lacks `delivery`; `realapps/README.md` and HANDOFF.md say 66 apps. See [status-and-known-issues](status-and-known-issues.md). | +| Open runtime issues | the review findings in section 4; `demos/NEEDS.md` §5 (`retry`/`block` on non-idempotent writes) still open; §1, §2 and §6 addressed in code but unmeasured on the demos. | +| Other infrastructure | test files are not type-checked; `demos/src/server/data/cities.ts` is missing from git (root `.gitignore` rule `data/`); `jev_local/data/` is missing (gitignored), so 20 legacy Python test files fail at collection; realapps has no lockfile, no tests and no CI. | + +**Working rule for agents.** CONTRACT §0 rule 5 and HANDOFF.md ("never run npm, tsc, vitest ... on the Mac"; build +and test on the Azure `train` VM through `scripts/vm.sh`) exist because the colleague's Mac has 8 GB RAM. On this +machine `npm install`/`npm ci`, typecheck, build and unit tests are light and verified to work locally. Ask the user +before Playwright, `smoke.sh`, the sim generator, training, realapps runs, the demos' eval, model downloads, anything +on Azure, `git push` or `npm publish`. Do not change situation text without a plan for a new tag, regenerated data +and retraining. ## Related docs @@ -411,8 +493,9 @@ sim, training, Playwright, model downloads, the demos' eval, or any script that [decide-policy-actions](runtime/decide-policy-actions.md), [model-host](runtime/model-host.md), [devtools](runtime/devtools.md), [build-test-release](runtime/build-test-release.md). - Cross-cutting: [model-io-contract](model-io-contract.md), [status-and-known-issues](status-and-known-issues.md). -- Offline and legacy: [sim](sim.md), [training](training.md), [demos](demos.md), +- Offline and legacy: [sim](sim.md), [realapps](realapps.md), [training](training.md), [demos](demos.md), [genclass-model-lineage](genclass-model-lineage.md), [extension-and-benchmarks](extension-and-benchmarks.md). -- Human docs (drift documented in status-and-known-issues): [CONTRACT.md](../runtime/CONTRACT.md), - [API.md](../runtime/API.md), [ARCHITECTURE.md](../runtime/ARCHITECTURE.md), - [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md), [OPEN_TASKS.md](../../OPEN_TASKS.md). +- Human docs (drift documented in status-and-known-issues): [HANDOFF.md](../../HANDOFF.md), [RELEASE.md](../../RELEASE.md), + [OPEN_TASKS.md](../../OPEN_TASKS.md), [CONTRACT.md](../runtime/CONTRACT.md), [API.md](../runtime/API.md), + [ARCHITECTURE.md](../runtime/ARCHITECTURE.md), [RESULTS.md](../runtime/RESULTS.md), + [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md). diff --git a/docs/agents/playbooks.md b/docs/agents/playbooks.md index aa8d68f7..77d62b7f 100644 --- a/docs/agents/playbooks.md +++ b/docs/agents/playbooks.md @@ -1,89 +1,111 @@ # Playbooks: recipes for common changes -> **Scope:** step-by-step recipes for the edits agents are most often asked to make in this monorepo: the runtime (`packages/runtime`), its model host and devtools, the adapters, `sim/`, `training/`, `demos/`, releases, test runs, debugging a reported intervention, and these docs. Each recipe merges and deduplicates the "How to change it safely" sections of the subsystem docs. +> **Scope:** step-by-step recipes for the edits agents are most often asked to make in this monorepo: the runtime (`packages/runtime`), its model host and devtools, the adapters, `sim/`, `realapps/`, `training/`, `demos/`, releases, CI, test runs, debugging a reported intervention, and these docs. Each recipe merges and deduplicates the "How to change it safely" sections of the subsystem docs. > **Read this when:** you have a concrete change to make and need the full checklist: files and symbols to touch, tests to add and run, parity / retrain / release consequences, and the traps. -> **Source of truth:** the code. Pointers verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. If this doc and a subsystem doc disagree, check the code and fix whichever is wrong (recipe 26). +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. If this doc and a subsystem doc disagree, check the code and fix whichever is wrong (recipe 26). + +## TL;DR + +- The runtime is **situation-v2** (tag `situation-v2` = 6e5e86e): decisions happen at the network boundary (trigger `delivery`), store writes are not held by default, and the model-visible text is **frozen**. Any change to what the model reads needs the user's go-ahead, a new tag, regenerated SIM **and** realapps data, and a retrain (recipe 6). +- On `mvp-v2` the only runtime changes since the tag are ours: f3636b2 (default mode `observe`; `guard` opt-in, `heal` experimental) and b435acb (CI, committed root lockfile, CLI 100755). Neither touches model text. +- **No situation-v2 model exists.** The plan (HANDOFF): 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0` (recipes 30, 20, 22, 19; release procedure in [`RELEASE.md`](../../RELEASE.md)). +- Light local checks are fine: `npm ci`, runtime `tsc`/`tsup`/vitest, sim `tsc` and `SIM_RUNTIME=real` vitest. **Ask the user first** for Playwright, `smoke.sh`, the sim generator, realapps, training, demos eval, model downloads, anything on Azure, `git push`, `npm publish`. Azure is operated by the colleague (Mehar) right now; nobody on our side touches it. +- Baseline at b435acb: runtime unit tests 332 passed + 14 skipped (40 + 1 files) without `review-perf`, which passes alone (4); sim 19 passed (5 files). CI (`.github/workflows/ci.yml`) runs the same runtime steps (recipe 21). +- New recipes: never-worse sweep (28), add a realapps app (29), the v2 training pipeline (30). Conventions used below: -- Code pointers are `path/from/repo/root.ts` -> `symbol`. A method is written `Class.method`. +- Code pointers are `path/from/repo/root.ts` -> `symbol`. A method is written `Class.method`. No line numbers. - In "Tests" lines, test files are listed after their directory, e.g. `packages/runtime/test/`: `atoms.test.ts`, `policy.test.ts`. -- **[ask first]** marks a step that runs something the run policy in AGENTS.md reserves for the user's approval (see [Where to run things](#3-where-to-run-things)). +- **[ask first]** marks a step that runs something the run policy reserves for the user's approval (see [Where to run things](#3-where-to-run-things)). - **Model input** means any byte that reaches `EvaluateRequest.state` or `EvaluateRequest.questions` (situation text, question headers, option descriptions, diagnosis labels), plus the token ids derived from it. -- Recipes say "the lead", "SIM" or "TRAIN" where the original workstream protocol required their sign-off. In an agent session, stop and get the user's decision at those points; record it the way the protocol describes (recipe 26). +- Recipes say "the lead", "SIM", "REAL" or "TRAIN" where the original workstream protocol required their sign-off. In an agent session, stop and get the user's decision at those points; record it the way the protocol describes (recipe 26). +- "(unverified)" marks a statement that could not be checked from the repo. ## Before you start -### 1. Ground rules (binding: `docs/runtime/CONTRACT.md` §0 and §0.5) +### 1. Ground rules (binding: `docs/runtime/CONTRACT.md` §0 and §0.5, `HANDOFF.md` "Rules") - **No rules in the runtime.** The runtime computes generic facts and decides whether to ask the model (triage); it never maps a fact pattern to a diagnosis or action with an if/then. The model chooses; `packages/runtime/src/decide/policy.ts` -> `gate` only filters. This also holds when you fix a false intervention (recipe 25). -- **One situation implementation.** `packages/runtime/src/situation/*` is the only code that builds situation text. The sim runs it unchanged (`sim/src/run/rt.ts` -> `realRuntimeFactory`), and `training/curriculum/rt.py` is a hand port of it. -- **Determinism.** Inside `packages/runtime/src`, never call `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`/`setInterval`. Use the injected `Clock` (`this.clock` in `RuntimeImpl`, `api.clock` in plugins), take ids from counters, and clear every timer you arm in `RuntimeImpl.destroy` (or make it harmless when it fires later). Sim world code uses keyed `Rng` forks only (`sim/src/rng.ts` -> `Rng.fork`). +- **One situation implementation.** `packages/runtime/src/situation/*` is the only code that builds situation text. The sim runs it unchanged (`sim/src/run/rt.ts` -> `realRuntimeFactory`), realapps bundles it into every app (`realapps/build.mjs`, `RW_RUNTIME_SRC`), and `training/curriculum/rt.py` is a hand port of it. +- **Never make a correct app worse.** The default path applies store writes in the caller's stack, in order, and the default mode (`observe`) permits no action. Do not add anything that delays or reorders a default-path write (`packages/runtime/test/no-reorder.test.ts`, `default-mode.test.ts`), and check runtime changes with the realapps sweep (recipe 28). +- **Determinism.** Inside `packages/runtime/src`, never call `Math.random`, `Date.now`, `performance.now` or the global `setTimeout`/`setInterval`. Use the injected `Clock` (`this.clock` in `RuntimeImpl`, `api.clock` in plugins), take ids from counters, and clear every timer you arm in `RuntimeImpl.destroy` (or make it harmless when it fires later). Sim world code uses keyed `Rng` forks only (`sim/src/rng.ts` -> `Rng.fork`); realapps keys every draw by (seed, salt, request identity, occurrence). - **Fail open.** Every path that has no usable answer runs the controller's passive action. Never make the app wait on the model. - **`GenClass.init` never throws.** Observers install inside `tryAdd` in `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; plugin `setup` errors are swallowed. -- **Honest evaluation.** `sim/` and `demos/` never import or read each other. Do not fix the demo apps' latent bugs or tune them for GenClass. -- **Dependencies.** No new runtime dependency besides `onnxruntime-web` without the lead. TypeScript strict, ESM only. +- **Honest evaluation.** `sim/`, `realapps/` and `demos/` never import or read each other's apps (realapps imports sim's cost/label code by design, never `demos/`). Do not fix the demo apps' latent bugs or tune them for GenClass. +- **Dependencies.** No new runtime dependency besides `onnxruntime-web` without the lead. TypeScript strict, ESM only. The root `package-lock.json` is committed: a dependency change must update it (`npm install` at the root) or CI's `npm ci` fails. - **Legacy content stays as is** (CONTRACT §1): `jev_local/`, `extension/` and the jev-era `docs/*.md`. This does not cover `docs/runtime/` or `docs/agents/`. - **Review tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make it pass; fix `src/`. -- **Code wins over docs.** `docs/runtime/CONTRACT.md` was last edited in a53dd38, before batch 3. STATUS, the READMEs, `UI-NEEDS.md`, `sim/NEEDS.md` and `training/NEEDS.md` have stale items. Check the drift tables in [status-and-known-issues.md](status-and-known-issues.md#drift-and-open-issues) before trusting them. +- **Licensing for training:** only v1 `jev-local-fast` or MIT ettin bases plus synthetic/sim/realapps data. Never v2/Z/S checkpoints or benchmark datasets (HANDOFF). +- **Code wins over docs.** `docs/runtime/CONTRACT.md`, `HANDOFF.md` (it still says guard is the default), STATUS test counts and the NEEDS files have stale items. Check the drift sections of the subsystem docs before trusting them. + +### 2. The `situation-v2` freeze -### 2. The `situation-v1` freeze +| tag | commit | data and models built on it | +|---|---|---| +| `situation-v1` | 1a77558 | SIM phase A (600,676 rows) and B (1,415,344), `gold-r1x`, REAL pilots `pilot4`/`pilot-all`, curriculum `cur1`–`cur4`, round-1 R17/R32-final1. Superseded: does not match the v2 runtime. | +| `situation-v2` | 6e5e86e | **current.** SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL `v2-pilot` and `v2b1`–`v2b3`, the `rt.py` port (d73d20c). No model yet. | -Tag `situation-v1` is commit 1a77558. `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. SIM phase A (600,676 rows) and TRAIN final round 1 were built on that exact text. Before editing, classify your change (condensed from [model-io-contract.md](model-io-contract.md#versioning-what-invalidates-the-trained-model)): +`git diff situation-v2 b435acb -- packages/runtime/src` touches only `devtools/index.ts`, `runtime.ts` (the default mode) and `types.ts` (JSDoc), all f3636b2, none of them model text. Before editing, classify your change (condensed from [model-io-contract.md](model-io-contract.md#versioning-what-invalidates-the-trained-model)): | class | what you touch | consequence | |---|---|---| -| **A. Model input text or label space** | `packages/runtime/src/situation/{facts,describe,build,serialize,questions}.ts`; `packages/runtime/src/util.ts` formatters, redaction and signature normalisation; `packages/runtime/src/state/fields.ts` -> `changeText`; `ActionEffect.changed` sentences (`packages/runtime/src/runtime.ts`, `packages/runtime/src/observe/fetch.ts`, `packages/runtime/src/observe/xhr.ts`); observer op names, details and event `data` keys; which actions are offered (`packages/runtime/src/situation/build.ts` -> `builtinApplicable`) | user approval, SIM regeneration, `training/curriculum/rt.py` re-port, retrain, re-eval, re-export, a new freeze tag (recipe 6) | -| **B. Distribution only** | `neutral` flags and thresholds in `packages/runtime/src/situation/facts.ts`, trigger conditions, baseline/profile estimators, invariant learning, hold/bypass rules | regenerate SIM data; retrain recommended | +| **A. Model input text or label space** | `packages/runtime/src/situation/{build,facts,conflicts,content,evidence,describe,serialize,questions}.ts`; `packages/runtime/src/util.ts` formatters (`secs`, `rel`, `fmtNum`, `ratio`, `truncate`, `describe`), redaction (`isSensitiveName`, `isSensitivePath`, `defaultRedact`) and signatures (`normalizePath`, `normalizeFieldPath`, `isIdSegment`); `packages/runtime/src/state/fields.ts` -> `changeText`, `stringDiff`; change summaries in `packages/runtime/src/state/hub.ts`; `ActionEffect.changed` sentences (`packages/runtime/src/runtime.ts`, `packages/runtime/src/observe/fetch.ts`, `packages/runtime/src/observe/xhr.ts`); observer op names, details and event `data` keys; which actions are offered (`packages/runtime/src/situation/build.ts` -> `builtinApplicable`); `TRIGGER_DESCRIPTIONS`, `BUILTIN_ACTIONS`, `DEFAULT_DIAGNOSES` | user approval, coordination with whoever is generating data, a new freeze tag, SIM **and** realapps regeneration, `training/curriculum/rt.py` re-port, retrain, re-eval, re-export (recipe 6) | +| **B. Distribution only** | `neutral` flags and triage thresholds, delivery salience (`conflicts.ts` -> `conflictsOn`, `content.ts` -> `analyzeBody`, `PENDING_WINDOW_MS`, `RYW_WINDOW_MS`), trigger conditions, baseline/profile estimators, invariant learning, hold/bypass rules, situation budgets and the SIM/realapps budget weights | regenerate SIM and realapps data; retrain recommended | | **C. Token ids** | `packages/runtime/src/model/{serialize,pyutil,tokenizer,packer}.ts`, `packages/runtime/src/model/engine.ts` -> `FEEDS` | change `jev_local/` in lockstep, regenerate fixtures, retrain if the Python side changed (recipe 13) | | **D. Answers only** | `packages/runtime/src/model/calibrate.ts`, `calibration.json` | re-run `training/eval_runtime.py`; no retrain | -| **E. Nothing the model sees** | `packages/runtime/src/decide/policy.ts` defaults, host/loader/worker, devtools, adapters, report wording | runtime tests only; mirror gate changes in `training/eval_runtime.py` | +| **E. Nothing the model sees** | `packages/runtime/src/decide/policy.ts` defaults, the default mode, host/loader/worker, devtools, adapters, report wording, CI | runtime tests only; mirror gate changes in `training/eval_runtime.py` and `training/eval_gain.py` | -Class A and C changes need the user's go-ahead **before** you edit. +Class A, B and C changes need the user's go-ahead **before** you edit. HANDOFF: "The training format is frozen at `situation-v2` … Coordinate before touching it." Data generation on Azure runs with this exact runtime right now, so a "small fix" to a fact also splits the in-flight data. ### 3. Where to run things -Run policy (set when these docs were written, 2026-10-07): the original team ran every build and test on an Azure VM through `scripts/vm.sh`, because the original author's Mac has 8 GB RAM (CONTRACT §0 rule 5; the subsystem docs repeat "VM only"). On other machines the light steps below are verified to work locally and may be run without asking. Everything else needs the user's approval first. +Run policy for agents (the lead, 2026-10-08): `HANDOFF.md`'s "never run npm, tsc, vitest, node … on the Mac" is about the colleague's 8 GB Mac. On this machine the light steps below were verified and may be run without asking. Everything else needs the user's approval first. -| task | run locally? | command | verified result (macOS, 16 GB, 10 CPUs, Node v25.6.0, npm 11.8.0) | +| task | run locally? | command | verified result (macOS, 16 GB, Node v25.6.0, 2026-10-08) | |---|---|---|---| -| install | yes | `npm install` at the repo root | 18 s, 134 packages. One `EBADENGINE` warning (vitest@5.0.3 wants node `^22.12.0 \|\| ^24.0.0 \|\| >=26.0.0`; Node 25 works). Side effects: an untracked root `package-lock.json` (never committed; do not commit it without the user's decision) and a mode change on `packages/runtime/bin/genclass-runtime.mjs` (committed 644, npm sets 755): revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | -| runtime typecheck | yes | `cd packages/runtime && npx tsc -p tsconfig.json --noEmit` | clean, ~1.6 s. Covers `src/` only: tests are never type-checked | -| runtime build | yes | `cd packages/runtime && npx tsup` | ~2.5 s; entries `index`, `adapters/{react,redux,zustand}`, `devtools/index`, `worker`; `.d.ts` for all but `worker`; `dist/` ~1.6 MB with maps | -| runtime unit tests | yes | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` | Test Files 36 passed, 1 skipped (37); Tests 286 passed, 14 skipped (300); ~2.4 s | -| the 14 skipped model-parity tests | **[ask first]** (model download) | same command with `GENCLASS_MODEL_DIR=<model dir>` (default `<repo>/.cache-model`) | skipped files/tests: `test/model/packer.test.ts` (10 of 10), `engine.test.ts` (3 of 4), `calibrate.test.ts` (1 of 8). With a model directory all 300 pass (per STATUS) | -| Playwright (model specs, devtools UI spec), `packages/runtime/test/smoke/smoke.sh` | **[ask first]** | see recipe 23 | not run when these docs were written | -| sim (tests, smoke, generation), training, demos eval, Python tests, model downloads | **[ask first]** | see recipes 17, 18, 22, 23 | not run when these docs were written | -| anything that touches Azure: `scripts/*.sh`, `training/*.sh`, `sim/scripts/*` | **[ask first]** | | `scripts/vm.sh` also needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are not in the repo | - -There is **no CI** (no `.github/` directory). Your local typecheck and unit-test run is the only gate before review. +| install | yes | `npm ci` at the repo root (or `npm install` when you change dependencies; commit the lockfile) | OK from the committed lockfile; an `EBADENGINE` warning (vitest@5.0.3 wants node `^22.12.0 \|\| ^24.0.0 \|\| >=26.0.0`; Node 25 works). No longer leaves an untracked lockfile or a mode change on the CLI | +| runtime typecheck | yes | `npm run typecheck -w @genclass/runtime` (= `cd packages/runtime && npx tsc -p tsconfig.json --noEmit`) | clean. Covers `src/` only: tests are never type-checked | +| runtime build | yes | `npm run build -w @genclass/runtime` (= `npx tsup`) | OK; entries `index`, `adapters/{react,redux,zustand}`, `devtools/index`, `worker`; `.d.ts` for all but `worker` | +| runtime unit tests | yes | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | Test Files 40 passed \| 1 skipped (41); Tests 332 passed \| 14 skipped (346); `review-perf` alone 4 passed (it once failed at 5.5 ms vs its 2 ms bound inside a full parallel run: contention) | +| sim typecheck and tests | yes (build the runtime first) | `cd sim && npx tsc -p tsconfig.json --noEmit`; `SIM_RUNTIME=real npx vitest run` | clean; 19 passed (5 files). Without `SIM_RUNTIME=real`, `oracle.test.ts` fails by design ([sim.md](sim.md#tests)) | +| the 14 skipped model-parity tests | **[ask first]** (model download) | the unit command with `GENCLASS_MODEL_DIR=<model dir>` (default `<repo>/.cache-model`) | `test/model/packer.test.ts` (10 of 10), `engine.test.ts` (3 of 4), `calibrate.test.ts` (1 of 8). No v2 model exists; the v0.1 fixtures still pin the packer | +| Playwright (model specs, devtools UI spec), `packages/runtime/test/smoke/smoke.sh` | **[ask first]** | recipe 23 | not run | +| Python tests (`training/tests`, `tests/`) | **[ask first]** | recipe 23 | not run by the lead (a docs agent ran 5 of 6 `test_curriculum.py` functions locally; see [training.md](training.md#tests)) | +| sim generator, realapps (anything that launches Chromium), training, demos eval, model downloads | **[ask first]** | recipes 17, 18, 22, 28–30 | not run | +| anything that touches Azure: `scripts/*.sh`, `training/*.sh`, `sim/scripts/cluster/*`, `realapps/scripts/{cluster,node_setup}.sh`, `az` | **[ask first]**, and in practice no: the colleague operates the cluster | | needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are on the colleague's machine | +| `git push`, tags, GitHub releases, `npm publish` | **[ask first]**; `npm publish` and `npm dist-tag` are the user's action (npm 2FA) | recipes 19, 20 | | + +Untracked `packages/runtime/test/zz-*.test.ts` files from parallel agents may exist in a shared working copy; vitest collects them. Count only tracked files (`git status`) before trusting a red or inflated run. ### 4. Read these first | file | why | |---|---| -| [status-and-known-issues.md](status-and-known-issues.md) | what is shipped, frozen, in flight; ownership; open product risks; drift tables | -| the subsystem doc for your area (index below) | "Invariants and gotchas", "How to change it safely", "Tests" | -| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | the lead's task list (Next / In progress / Done / Needs the user) | -| [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md) | CORE's state, example situations per trigger, "Deviations from the contract", "Open issues" | -| [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md) | binding rules (§0, §0.5), workstream layout (§1), additions (§13). Stale in places | -| [`docs/runtime/API.md`](../runtime/API.md) | human API reference; update it with any public-surface change | -| NEEDS files: [`demos/NEEDS.md`](../../demos/NEEDS.md), [`sim/NEEDS.md`](../../sim/NEEDS.md), [`training/NEEDS.md`](../../training/NEEDS.md), [`packages/runtime/UI-NEEDS.md`](../../packages/runtime/UI-NEEDS.md) | open cross-workstream requests (OPEN / ASK / DONE); `demos/NEEDS.md` §1, §2, §5, §6 are open in runtime code | -| [`training/LOG.md`](../../training/LOG.md), [`training/EVAL.md`](../../training/EVAL.md) | before any training or eval work | - -Ownership (CONTRACT §1 and §13): CORE owns `packages/runtime/src` except `model/` (MODEL) and `adapters/` + `devtools/` (UI); SIM owns `sim/`, TRAIN `training/` (CONTRACT §1 lists the lead), DEMOS `demos/`, REVIEW the `review-*` tests. +| [`HANDOFF.md`](../../HANDOFF.md) | the colleague's current state, rules and "How to continue" (more current than OPEN_TASKS) | +| [status-and-known-issues.md](status-and-known-issues.md) | what is shipped, frozen, in flight; ownership; drift tables | +| the subsystem doc for your area (index below) | "Invariants and gotchas", "How to change it safely", "Tests", "Drift and open issues" (the review findings at b435acb live there) | +| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | the lead's task list; describes the v2 pipeline (items 1-14) and "Needs the user" | +| [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md) | CORE's state, example situations per trigger, "Never worse", "Deviations from the contract", "Open issues" | +| [`docs/runtime/RESULTS.md`](../runtime/RESULTS.md) | model comparisons, never-worse table, data volume, training log summary | +| [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md), [`docs/runtime/API.md`](../runtime/API.md) | binding rules (§0, §0.5, §13); the human API reference (update it with any public-surface change) | +| NEEDS files: [`demos/NEEDS.md`](../../demos/NEEDS.md), [`sim/NEEDS.md`](../../sim/NEEDS.md), [`training/NEEDS.md`](../../training/NEEDS.md), [`packages/runtime/UI-NEEDS.md`](../../packages/runtime/UI-NEEDS.md) | open cross-workstream requests; `training/NEEDS.md` holds node claims and SIM/REAL data locations (items 10–16) | +| [`training/LOG.md`](../../training/LOG.md), [`training/EVAL.md`](../../training/EVAL.md), [`training/PLAN-v1.md`](../../training/PLAN-v1.md) | before any training or eval work | +| `realapps/README.md`, `realapps/apps/README.md` | before any realapps work ([realapps.md](realapps.md)) | + +Ownership (CONTRACT §1 and §13): CORE owns `packages/runtime/src` except `model/` (MODEL) and `adapters/` + `devtools/` (UI); SIM owns `sim/`, REAL `realapps/`, TRAIN `training/` (CONTRACT §1 lists the lead), DEMOS `demos/`, REVIEW the `review-*` tests. ### 5. Recipe index | # | recipe | area | can change model input? | needs **[ask first]** runs to finish? | |---|---|---|---|---| | 1 | [Add or change an observer](#1-add-or-change-an-observer) | runtime | yes (op names, details, events) | no | -| 2 | [Add or change a generic fact](#2-add-or-change-a-generic-fact) | runtime | yes | for the parity follow-up | -| 3 | [Add a trigger kind](#3-add-a-trigger-kind) | runtime + sim + training | yes | yes | -| 4 | [Add or change a built-in action](#4-add-or-change-a-built-in-action) | runtime (+ sim, training) | yes | for a new action | -| 5 | [Change a policy threshold or default](#5-change-a-policy-threshold-or-default) | runtime | no (distribution for triage) | no | -| 6 | [Change situation text, serialiser, budgets or questions](#6-change-situation-text-serialiser-budgets-or-questions) | runtime + sim + training | yes | yes | -| 7 | [Change the state pipeline or invariants](#7-change-the-state-pipeline-or-invariants) | runtime | sometimes | no | +| 2 | [Add or change a generic fact](#2-add-or-change-a-generic-fact) | runtime | yes | yes (recipe 6) | +| 3 | [Add a trigger kind](#3-add-a-trigger-kind) | runtime + sim + realapps + training | yes | yes | +| 4 | [Add or change a built-in action](#4-add-or-change-a-built-in-action) | runtime (+ sim, realapps, training) | yes | for a new action | +| 5 | [Change a policy threshold or default](#5-change-a-policy-threshold-or-default) | runtime | no | sweep for default-path changes | +| 6 | [Change model-visible text under the situation-v2 freeze](#6-change-model-visible-text-under-the-situation-v2-freeze) | runtime + sim + realapps + training | yes | yes | +| 7 | [Change the state pipeline or invariants](#7-change-the-state-pipeline-or-invariants) | runtime | sometimes | sweep | | 8 | [Add or change a framework adapter](#8-add-or-change-a-framework-adapter) | runtime (UI) | no | smoke test only | | 9 | [Add a public API method, option, event or subpath export](#9-add-a-public-api-method-option-event-or-subpath-export) | runtime | only if it alters situations | smoke test only | | 10 | [Add a custom action, standing question or plugin (app side)](#10-add-a-custom-action-standing-question-or-plugin-app-side) | app code | no retrain needed | no | @@ -93,98 +115,109 @@ Ownership (CONTRACT §1 and §13): CORE owns `packages/runtime/src` except `mode | 14 | [Regenerate model parity fixtures](#14-regenerate-model-parity-fixtures) | model tests | no | yes | | 15 | [Add a sim feature module](#15-add-a-sim-feature-module) | sim | data only | yes | | 16 | [Change sim oracle, labelling, ask questions or splits](#16-change-sim-oracle-labelling-ask-questions-or-splits) | sim | labels only | yes | -| 17 | [Generate a data set](#17-generate-a-data-set) | sim | n/a | yes | -| 18 | [Train, evaluate and export a model](#18-train-evaluate-and-export-a-model) | training | n/a | yes | -| 19 | [Publish @genclass/runtime](#19-publish-genclassruntime) | release | n/a | yes (user publishes) | +| 17 | [Generate a SIM data set](#17-generate-a-sim-data-set) | sim | n/a | yes | +| 18 | [Train, evaluate and export a model (mechanics)](#18-train-evaluate-and-export-a-model-mechanics) | training | n/a | yes | +| 19 | [Publish @genclass/runtime](#19-publish-genclassruntime) | release | n/a | yes (the user publishes) | | 20 | [Publish @genclass/runtime-model and point the runtime at it](#20-publish-genclassruntime-model-and-point-the-runtime-at-it) | release | n/a | yes | -| 21 | [Add a CI workflow](#21-add-a-ci-workflow) | repo | no | no | +| 21 | [Change the CI workflow](#21-change-the-ci-workflow) | repo | no | no | | 22 | [Add or change a demo and re-run trials](#22-add-or-change-a-demo-and-re-run-trials) | demos | no | yes | | 23 | [Run each test suite](#23-run-each-test-suite) | all | n/a | some | | 24 | [Write a runtime unit test](#24-write-a-runtime-unit-test) | runtime tests | n/a | no | | 25 | [Investigate a false intervention reported by a user](#25-investigate-a-false-intervention-reported-by-a-user) | runtime | depends on the fix | no | | 26 | [Update these docs after a code change](#26-update-these-docs-after-a-code-change) | docs | n/a | no | | 27 | [Touch legacy code: jev_local, extension, benchmarks, ops scripts](#27-touch-legacy-code-jev_local-extension-benchmarks-ops-scripts) | legacy | possibly | yes | +| 28 | [Run and read a never-worse sweep (realapps)](#28-run-and-read-a-never-worse-sweep-realapps) | realapps + runtime | no | yes | +| 29 | [Add a realapps app](#29-add-a-realapps-app) | realapps | data only | yes | +| 30 | [Run the v2 training pipeline (teacher, labels, distil, DAgger)](#30-run-the-v2-training-pipeline-teacher-labels-distil-dagger) | training + sim + realapps | n/a | yes, all of it | ## Definition of done A change is done when all of these hold. Say explicitly in your final report which ones you could not meet. -1. **Typecheck clean:** `cd packages/runtime && npx tsc -p tsconfig.json --noEmit`. If you touched `sim/src` types, also `npm run typecheck -w @genclass/sim` (light; not run when these docs were written). -2. **Unit tests pass:** the full runtime suite (command in [Where to run things](#3-where-to-run-things)). Without a model directory the baseline is 286 passed / 14 skipped in 36 + 1 files; your new tests add to "passed" and nothing new is skipped. No `review-*.test.ts` was edited. -3. **New behaviour has a test** in house style (recipe 24), including a "benign stays quiet" test for anything that can make a situation salient. -4. **Build passes** (`npx tsup`) if you touched `package.json` exports, `tsup.config.ts`, the worker, dynamic imports or anything bundling-related. -5. **Mirrors updated by hand** (the runtime's `tsc` checks none of them; the sim loads the runtime by module name, so a mismatch shows up only at sim run time): `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`, `demos/src/dev/runtime-shim/*` (`ShimRuntime`), `sim/src/run/rt.ts` -> `RuntimeLike` / `createOptions`, `sim/src/types.ts`, `training/curriculum/rt.py`, the devtools copies of report wording (`packages/runtime/src/devtools/ui.ts` -> `LEAD`, `NOUN`). -6. **Freeze respected:** `git diff situation-v1 -- packages/runtime/src` shows no class A/B/C change, or the user approved it and your report lists the follow-ups (SIM regeneration, `training/curriculum/rt.py` re-port, retrain, re-export, new freeze tag). Do not create freeze tags yourself. -7. **Docs updated** (recipe 26): `packages/runtime/src/types.ts` JSDoc, `docs/runtime/API.md`, `packages/runtime/README.md` for public surface; `packages/runtime/STATUS.md`; the matching `docs/agents/*.md`; `OPEN_TASKS.md` when a listed item moves. -8. **Workspace clean:** no root `package-lock.json` committed (unless the user decided to), the bin file mode reverted, no `dist/`, `*.tgz` or regenerated screenshots committed by accident. -9. **Nothing irreversible without the user:** no `npm publish`, `git push`, tag, GitHub release, Azure VM start or paid API call unless the user explicitly asked for that action. -10. **Report** lists the commands you ran with their results, and the **[ask first]** suites you did not run (Playwright, smoke, sim, model tests, training). +1. **Typecheck clean:** `npm run typecheck -w @genclass/runtime`. If you touched `sim/src` or anything the sim imports, also `cd sim && npx tsc -p tsconfig.json --noEmit`. `realapps/` has no tsconfig and no typecheck: review type changes there by reading. +2. **Unit tests pass:** the runtime suite as in [Where to run things](#3-where-to-run-things) (baseline at b435acb: 332 passed / 14 skipped in 40 + 1 files, plus `review-perf` 4 passed alone). Your new tests add to "passed" and nothing new is skipped. No `review-*.test.ts` was edited. If the sim consumes what you changed, `SIM_RUNTIME=real npx vitest run` in `sim/` (19 passed) after `npm run build -w @genclass/runtime`. +3. **New behaviour has a test** in house style (recipe 24), including a "benign stays quiet" test for anything that can make a situation salient, and a default-mode (`observe`) test for anything that could delay, hold or reorder app work. +4. **Build passes** (`npm run build -w @genclass/runtime`) if you touched `package.json` exports, `tsup.config.ts`, the worker, dynamic imports or anything bundling-related. +5. **CI steps pass locally** (they are the commands above; `.github/workflows/ci.yml`). A dependency change updates and commits the root `package-lock.json`. +6. **Mirrors updated by hand** (the runtime's `tsc` checks none of them): `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`, `demos/src/dev/runtime-shim/*` (`ShimRuntime`), `sim/src/run/rt.ts` -> `RuntimeLike` / `createOptions`, `sim/src/types.ts`, `realapps/src/harness/trajectory.ts` (`OBSERVE`, `TRIGGER_W`), `realapps/src/world/{index,probe,diagnose}.ts`, `realapps/scripts/{analyze,evalset}.py` (`PASSIVE` copies), `training/curriculum/rt.py`, `training/label_teacher.py` / `training/eval_runtime.py` (`PASSIVE`, `TIER`), the devtools copies of report wording (`packages/runtime/src/devtools/ui.ts` -> `LEAD`, `NOUN`). +7. **Freeze respected:** `git diff situation-v2 -- packages/runtime/src` shows nothing beyond f3636b2's three files and no class A/B/C change, or the user approved it and your report lists the follow-ups of recipe 6. Do not create freeze tags yourself. +8. **Docs updated** (recipe 26): `packages/runtime/src/types.ts` JSDoc, `docs/runtime/API.md`, `packages/runtime/README.md` (and root `README.md`) for public surface; `packages/runtime/STATUS.md`; `docs/runtime/RESULTS.md` for any new measured result; the matching `docs/agents/*.md`; `OPEN_TASKS.md` / `HANDOFF.md` when a listed item moves. +9. **Workspace clean:** no `dist/`, `*.tgz`, regenerated screenshots, `zz-*` scratch tests or local model directories committed by accident. +10. **Nothing irreversible without the user:** no `npm publish`, `git push`, tag, GitHub release, Azure call or paid API call unless the user explicitly asked for that action in chat. +11. **Report** lists the commands you ran with their results, and the **[ask first]** suites you did not run (Playwright, smoke, sim generator, realapps sweeps, model tests, training, Python tests). ## Recipes: runtime core ### 1. Add or change an observer -**Goal.** Trace a new async source (e.g. `EventSource`, requested in `demos/NEEDS.md` §6, or `BroadcastChannel`), or change how an existing observer records ops and events. +**Goal.** Trace a new async source (e.g. `BroadcastChannel`, requested with EventSource in `demos/NEEDS.md` §6; EventSource itself is done in v2), or change how an existing observer records ops and events. **Steps.** 1. Decide whether you need core code. App-specific sources can stay in a plugin: `PluginApi.recordOp` / `endOp` / `runInOp` (`packages/runtime/src/runtime.ts` -> `RuntimeImpl.pluginApi`), with no core or parity impact (recipe 10). -2. Create `packages/runtime/src/observe/<name>.ts` exporting `install<Name>(...)` that returns an uninstall function, or `null` when the global is missing. Follow `packages/runtime/src/observe/fetch.ts` -> `installFetch`: a `disabled` flag so the wrapper becomes a pass-through after `destroy()`, restore the global only if it still holds your wrapper, wrap all tracing in try/catch, use the host's clock. +2. Create `packages/runtime/src/observe/<name>.ts` exporting `install<Name>(...)` that returns an uninstall function, or `null` when the global is missing. Follow `packages/runtime/src/observe/fetch.ts` -> `installFetch`: a `disabled` flag so the wrapper becomes a pass-through after `destroy()`, restore the global only if it still holds your wrapper, wrap all tracing in try/catch, use the host's clock. A push channel follows `packages/runtime/src/observe/eventsource.ts` -> `installEventSource` and `packages/runtime/src/observe/messages.ts` -> `MessageGate` (deliveries in channel order, behind any held message). 3. Register it in `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers` with `if (on("<name>")) tryAdd("<name>", () => install<Name>(...))`. `on(k)` defaults to true; pass a second argument (as `timers` does with `browserLike`) to make the default conditional. 4. Add the name to `packages/runtime/src/types.ts` -> `ObserverName`; TypeScript then forces it into `packages/runtime/src/index.ts` -> `ALL_OFF`. -5. Add the key to every explicit observe map: `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts` (`OBSERVE`), the `ONLY_*` constants in `review-fetch.test.ts` / `review-timers.test.ts`, `const OFF` in `dom.test.ts`, and `sim/src/run/rt.ts` -> `createOptions` (set it to `false` unless SIM wants it). -6. Reuse an existing `packages/runtime/src/types.ts` -> `OpKind` if you can. A new kind also touches `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `packages/runtime/src/runtime.ts` -> `PROFILED`, and situation text (class A). +5. Explicit observe maps that omit a key leave it **on**. None of these lists `eventsource` today (harmless only where no `EventSource` global exists): `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts` (`OBSERVE`), the `ONLY_*` constants in `review-fetch.test.ts` / `review-timers.test.ts`, `const OFF` in `dom.test.ts`, `sim/src/run/rt.ts` -> `createOptions`, `realapps/src/harness/trajectory.ts` -> `OBSERVE` and `realapps/src/world/index.ts` (`ALL_OFF` of the ideal run; realapps also sets `window.EventSource = undefined` in `src/world/netapi.ts`). Add your key to each, `false` unless SIM/REAL want it. +6. Reuse an existing `packages/runtime/src/types.ts` -> `OpKind` if you can. A new kind also touches `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `opLabel`, the `PROFILED` set in `packages/runtime/src/runtime.ts`, and situation text (class A). 7. To carry causality across a new async boundary (`requestAnimationFrame`, `queueMicrotask`, `MessagePort`), copy `packages/runtime/src/observe/timers.ts` -> `installTimers`: capture `ctx.peek()` at schedule time, resolve a `LazyOp` to `.nearest`, call `ctx.stick(lazyTimer(parent, label))` in the callback. Never give a `LazyOp` a `LazyOp` parent. -8. Changing DOM recording (`packages/runtime/src/observe/dom-user.ts` -> `installDomUser`): keep the `ignoredEvent(e) || programmatic(e)` guard and the rule that sensitive fields record `""`. If `describeElement` output changes, the sim's synthetic targets must follow. -9. Adding a volatile header: add it to both `packages/runtime/src/observe/fetch.ts` -> `VOLATILE_HEADERS` and `packages/runtime/src/observe/xhr.ts` -> `VOLATILE`, so identities match across transports. +8. Network observers that deliver data must route the delivery through `RuntimeImpl.runDelivery` (fetch via `NetHost.deliver`, XHR via `arrive()`, push channels via `MessageGate.decide`) so the `delivery` trigger sees it; keep listener order and keep the app's dispatch semantics (known gaps: XHR listeners released from the queue see `e.currentTarget === null`; a capture-phase message listener can see a held message twice; see [observe-and-trace.md](runtime/observe-and-trace.md#drift-and-open-issues)). +9. Changing DOM recording (`packages/runtime/src/observe/dom-user.ts` -> `installDomUser`): keep the `ignoredEvent(e) || programmatic(e)` guard, the `untrustedEvents` option (default false: synthetic `isTrusted: false` events are not recorded; realapps passes `true`) and the rule that sensitive fields record `""`. If `describeElement` output changes, the sim's synthetic targets must follow. +10. Adding a volatile header: add it to both `packages/runtime/src/observe/fetch.ts` -> `VOLATILE_HEADERS` and `packages/runtime/src/observe/xhr.ts` -> `VOLATILE`, so identities match across transports. `x-request-id` (the sim's correlation header) must stay volatile. -**Tests.** `packages/runtime/test/`: install and record; `destroy()` restores the global (next to `dom.test.ts` "browser globals are restored by destroy()"); pass-through after destroy (`review-fetch.test.ts` pattern); a read-only global does not throw (`batch3.test.ts`, `review-misc.test.ts` patterns). For context changes run `context.test.ts` and `review-timers.test.ts` with `NODE_OPTIONS=--expose-gc` (otherwise the gc test logs a skip and passes). For DOM changes run `dom.test.ts`, `review-dom.test.ts`. +**Tests.** `packages/runtime/test/`: install and record; `destroy()` restores the global (next to `dom.test.ts` "browser globals are restored by destroy()"); pass-through after destroy (`review-fetch.test.ts` pattern); a read-only global does not throw (`batch3.test.ts`, `review-misc.test.ts` patterns); delivery order and holds (`delivery.test.ts`). For context changes run `context.test.ts` and `review-timers.test.ts` with `NODE_OPTIONS=--expose-gc` (otherwise the gc test logs a skip and passes). For DOM changes run `dom.test.ts`, `review-dom.test.ts`. -**Parity / retrain / release.** A new observer that the sim leaves off adds no training rows, but its ops, op names, `detail` strings and event `data` keys appear in timelines and facts at runtime: they are class A for any trigger the sim does produce. Renaming existing op names, details or event keys (`packages/runtime/src/situation/describe.ts` -> `eventLine` reads `count`, `first`, `route`, `key`, `duration`, `summary`, `message`) is class A. Signature normalisation (`packages/runtime/src/util.ts` -> `isIdSegment`, `isSlugId`) also keys baselines and the persisted profiles under `genclass.profiles.v1`. +**Parity / retrain / release.** A new observer that SIM and realapps leave off adds no training rows, but its ops, op names, `detail` strings and event `data` keys appear in timelines and facts at runtime: they are class A for any trigger the data does produce. Renaming existing op names, details or event keys (`packages/runtime/src/situation/describe.ts` -> `eventLine`) is class A. Signature normalisation (`packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`) also keys baselines and the persisted profiles under `genclass.profiles.v1`. -**Gotchas.** Captured natives (`packages/runtime/src/clock.ts` -> `browserClock` timers, `packages/runtime/src/index.ts` -> `NATIVE_FETCH`) must stay at module top level, or the runtime observes its own timers and model download. Two runtimes on one page double-wrap every global. WebSocket instances and timer callbacks created before `destroy()` keep tracing. Sync XHR and keepalive fetch raise no request trigger. Nav routes are not redacted. +**Gotchas.** Captured natives (`packages/runtime/src/clock.ts` -> `browserClock` timers, `packages/runtime/src/index.ts` -> `NATIVE_FETCH`) must stay at module top level, or the runtime observes its own timers and model download. Two runtimes on one page double-wrap every global. WebSocket/EventSource instances and timer callbacks created before `destroy()` keep tracing. Sync XHR and keepalive fetch raise no request trigger. Nav routes are not redacted. The demos' in-page synthetic trial driver produces untrusted events, so with the default `untrustedEvents: false` it records no user actions (`demos/src/shared/genclass.ts` does not pass the option). **See.** [observe-and-trace.md](runtime/observe-and-trace.md#how-to-change-it-safely), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely). ### 2. Add or change a generic fact -**Goal.** Add a new uniform fact, reword one, change whether it is `neutral` (triage), or change a triage threshold such as the M8 latency ratio. +**Goal.** Add a new uniform fact, reword one, change whether it is `neutral` (triage), or change a triage threshold. **Steps.** -1. Get the user's go-ahead: every variant is class A (wording) or class B (neutral flag, threshold). -2. Edit the per-trigger function in `packages/runtime/src/situation/facts.ts`: `mutationFacts`, `requestCommon` (shared by request/failure/stall), `failureFacts`, `stallFacts`, `inconsistencyFacts`, `transitionFacts`, `errorFacts`, `askFacts`; all dispatched by `computeFacts`. Build facts with the module's `fact(text, kind, neutral)` helper. State relations and numbers explicitly ("after", "newer", "in a row"); never phrase a verdict ("this is a bug"). -3. Data comes only from `SitEnv` (`packages/runtime/src/situation/env.ts`), implemented by `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Add a read-only member there if needed. Read time only from `env.now()`. No ops, events or store writes (the single allowed write is the `op.reads` cache in `mutationFacts`). -4. Pick `kind` deliberately: `packages/runtime/src/situation/facts.ts` -> `RANK` decides which facts survive the budget. A new kind needs `packages/runtime/src/types.ts` -> `FactKind`, an entry in `RANK` (typed `Record<FactKind, number>`, so the compiler forces it) and `RANK` in `training/curriculum/rt.py`. -5. Pick `neutral` deliberately: `false` makes the trigger salient, which means a model call and possibly a hold of the user's write or request. Triage is per trigger (the same repetition fact is salient on `request`, neutral on `failure`/`stall`). +1. Get the user's go-ahead: every variant is class A (wording) or class B (neutral flag, threshold). Then follow recipe 6 for everything after the code edit. +2. Find the builder. v2 facts are spread over four modules, dispatched by `packages/runtime/src/situation/facts.ts` -> `computeFacts`: + - `facts.ts`: `mutationFacts`, `deliveryFacts`, `requestCommon` (shared by request/failure/stall), `failureFacts`, `stallFacts`, `inconsistencyFacts`, `transitionFacts`, `errorFacts`, `askFacts`, plus the shared builders `versionFacts`, `movedFacts`, `concurrencyFacts`, `provenance`; + - `conflicts.ts`: what a delivery or write is predicted to overwrite (`predictedWrites`, `matchFields`, `newerConflict`, `pendingConflict`, `conflictsOn`, `newerSameSignature`); + - `content.ts`: body-versus-store comparisons (F1 put back a replaced value, F2 overwrites newer typing, F3 changes nothing: `compareField`, `contentFacts`, `pendingRevertFacts`; read-your-writes: `createdIds`, `rywFacts`); + - `evidence.ts`: F5–F7, F9 (`scopeFacts`, `commitAmbiguity`, `repeatEvidence`, `cadenceFact`, `markFacts`). + Build facts with each module's `fact(text, kind, neutral)` helper. State relations and numbers explicitly ("after", "newer", "in a row"); never phrase a verdict ("this is a bug"). +3. Data comes only from `SitEnv` (`packages/runtime/src/situation/env.ts`), implemented by `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Add a read-only member there if needed. Read time only from `env.now()`. No ops, events or store writes. +4. Pick `kind` deliberately: `packages/runtime/src/situation/facts.ts` -> `RANK` decides which facts survive the budget. A new kind needs `packages/runtime/src/types.ts` -> `FactKind`, an entry in `RANK` (typed `Record<FactKind, number>`) and `RANK` in `training/curriculum/rt.py`. +5. Pick `neutral` deliberately: `false` makes the trigger salient, which means a model call and, in guard/heal, possibly a hold of a delivery or request. Triage is per trigger. 6. Keep ordering deterministic: `orderFacts` sorts non-neutral first, then by rank, stable; `MAX_FACTS` = 12. -7. Check wording consumers: `packages/runtime/src/decide/report.ts` -> `topFact` and `packages/runtime/src/devtools/ui.ts` skip provenance with the regex `^This (write|request) (comes from|has no known cause)`; keep it matching. -8. Mirror the computation and ordering in `training/curriculum/rt.py` (`mutation_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`, `order`). -9. Variant, the numbers behind facts: baseline estimators live in `packages/runtime/src/learn/baselines.ts` -> `Baselines` (latency needs ≥ 5 samples, 64-sample window, failure streak, 10 s rate), transition rarity in `packages/runtime/src/learn/profiles.ts` -> `Profiles` (`MIN_COMPLETIONS`, `RARE`). Stall timing (`RuntimeImpl.watchStall`) and several request facts read them. Tests: `learn.test.ts`, `review-precision.test.ts`, `situation.test.ts`. Class B (class A where a number is printed). +7. Redaction: any fact that prints a field value must go through `env.redact` (or `changeText(..., redact)`). The F2 fact currently prints raw `stringDiff` text for redacted fields (open review finding, [learn-situation-triage.md](runtime/learn-situation-triage.md#drift-and-open-issues)); do not copy that pattern. +8. Check wording consumers: `packages/runtime/src/decide/report.ts` -> `topFact` and `packages/runtime/src/devtools/ui.ts` skip provenance with the regex `^This (write|request) (comes from|has no known cause)`; keep it matching. +9. Mirror the computation and ordering in `training/curriculum/rt.py` (`mutation_facts`, `delivery_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`, `version_facts`, `content_facts`, `scope_facts`, `commit_ambiguity`, `repeat_evidence`, `cadence_fact`, `mark_facts`, `order`). +10. Variant, the numbers behind facts: baseline estimators live in `packages/runtime/src/learn/baselines.ts` -> `Baselines` (latency needs ≥ 5 samples), transition rarity in `packages/runtime/src/learn/profiles.ts` -> `Profiles`. Class B (class A where a number is printed). -**Tests.** Add a positive test (the situation reaches `decider.calls`) and a benign test (nothing salient; pattern: `packages/runtime/test/review-precision.test.ts`). Update exact-text assertions found with `grep -rn "<old sentence>" packages/runtime/test`: typically `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `learn.test.ts`. If a `review-*` assertion must change, raise it with the user instead of rewriting it. Paste the situations printed by `situation.test.ts` and `budget.test.ts` into the example blocks of `packages/runtime/STATUS.md`. +**Tests.** A positive test (the situation reaches `decider.calls`) and a benign test (nothing salient; pattern: `packages/runtime/test/review-precision.test.ts`). Update exact-text assertions found with `grep -rn "<old sentence>" packages/runtime/test`: typically `situation.test.ts`, `budget.test.ts`, `delivery.test.ts`, `content.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `learn.test.ts`. If a `review-*` assertion must change, raise it with the user instead of rewriting it. Paste the situations printed by `situation.test.ts` and `budget.test.ts` into the STATUS.md example blocks. -**Parity / retrain / release.** Follow recipe 6, "Parity" (SIM regeneration, `training/curriculum/rt.py`, retrain, new freeze tag). A threshold change alters which situations become rows even when no sentence changes. +**Parity / retrain / release.** Recipe 6 in full. A threshold change alters which situations become rows even when no sentence changes. -**Gotchas.** Plugin facts are always neutral and rank last. `rt.situation()` with no argument builds an `ask` situation, which is always salient, so the devtools Now view cannot tell you whether a trigger would be salient. Facts are computed only while the runtime is consultable. Making facts non-neutral increases holds: OPEN_TASKS lists hold-induced latency (search clean p50 14 -> 125 ms with v0.1) and typeahead being salient about 6 times per clean trial. +**Gotchas.** Plugin facts are always neutral and rank last. `rt.situation()` with no argument builds an `ask` situation, which is always salient. Facts are computed only while the runtime is consultable. `rt.py` already diverges from the frozen renderer in several common cases (an extra "Recent … outcomes" fact on failure rows, last-N timeline selection, no-op writes, F1 wording where the runtime shows F2; [training.md](training.md#drift-and-open-issues)); a re-port is the moment to fix them. **See.** [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes). ### 3. Add a trigger kind -**Goal.** Add a new kind of moment at which the model is consulted (alongside `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, `ask`). +**Goal.** Add a new kind of moment at which the model is consulted (alongside `mutation`, `request`, `delivery`, `failure`, `stall`, `inconsistency`, `transition`, `error`, `ask`). **Steps.** -1. Get the user's go-ahead: this adds a new question family to the model's input and needs data and retraining. -2. `packages/runtime/src/types.ts` -> `TriggerKind`. The compiler then flags every `Record<TriggerKind, …>`: `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS` (passive first), `PASSIVE`, `ACTION_INSTRUCTIONS`; `packages/runtime/src/decide/report.ts` -> `NOUN`. `packages/runtime/src/devtools/ui.ts` -> `NOUN` is a `Record<string, string>` and must be updated by hand. -3. `packages/runtime/src/situation/env.ts` -> `SubjectSpec` (the subject's shape), then `packages/runtime/src/situation/build.ts` -> `subjectOf`, `subjectOp`, `involvedStores`, `involvedFields`, `builtinApplicable`, `subjectRef` (`isTrigger` derives from `TRIGGER_ACTIONS`). +1. Get the user's go-ahead: this adds a new question family to the model's input and needs data and retraining (recipe 6). +2. `packages/runtime/src/types.ts` -> `TriggerKind`. The compiler then flags every `Record<TriggerKind, …>`: `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS` (passive first), `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`; `packages/runtime/src/decide/report.ts` -> `NOUN`. `packages/runtime/src/devtools/ui.ts` -> `NOUN` is a `Record<string, string>` and must be updated by hand. +3. `packages/runtime/src/situation/env.ts` -> `SubjectSpec`, then `packages/runtime/src/situation/build.ts` -> `subjectOf`, `subjectOp`, `involvedStores`, `involvedFields`, `builtinApplicable`, `subjectRef` (`isTrigger` derives from `TRIGGER_ACTIONS`). 4. `packages/runtime/src/situation/facts.ts` -> a new facts function wired into `computeFacts` (recipe 2). -5. A raise site: implement `Controller` (`packages/runtime/src/decide/exec.ts`) and call `RuntimeImpl.trigger(spec, ctl, { hold, priority })` from `packages/runtime/src/runtime.ts` or an observer. Add `revertable`/`revert` only if the subject can be reverted exactly (a `revert` extends the queue deadline by `LATE_REVERT_MS`). -6. Mirrors: `sim/src/types.ts` (`TriggerKind`, `PASSIVE`), sim scenarios that can produce it and the oracle (`sim/src/oracle/diagnose.ts`, `sim/src/oracle/cost.ts`), `training/curriculum/rt.py` (`TRIGGER_ACTIONS`, `ACTION_INSTR`, a facts port), `training/curriculum/fmt.py` -> `TRIGGER_ACTIONS`, `training/eval_runtime.py` -> `PASSIVE`, devtools labels. +5. A raise site: implement `Controller` (`packages/runtime/src/decide/exec.ts`) and call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. Add `revertable`/`revert` only if the subject can be reverted exactly. Pass `stale` only when the decision is held (background decisions passed a `stale` check are dropped; open finding on `delivery` in [decide-policy-actions.md](runtime/decide-policy-actions.md#drift-and-open-issues)). +6. Mirrors: `sim/src/types.ts` (`TriggerKind`, `PASSIVE`), `sim/src/gen/trajectory.ts` -> `TRIGGER_W`, sim exploration, `sim/src/oracle/diagnose.ts`, `sim/src/oracle/cost.ts`, `sim/src/run/runner.ts` correlation; realapps `src/world/diagnose.ts`, `src/harness/trajectory.ts` -> `TRIGGER_W`, `scripts/{analyze,evalset}.py` `PASSIVE`; `training/curriculum/rt.py` (`TRIGGER_ACTIONS`, `ACTION_INSTR`, `TRIGGER_DESCRIPTIONS`, a facts port), `training/curriculum/fmt.py` -> `TRIGGER_ACTIONS`, `training/eval_runtime.py` -> `PASSIVE`, `training/label_teacher.py` -> `PASSIVE`, devtools labels. -**Tests.** `packages/runtime/test/`: a `situation.test.ts` case (key order, section caps, first fact), a controller test in the style of `atoms.test.ts` / `fetch.test.ts` (hold, fail-open at the budget, passive on every exit), `report.test.ts` for the report noun, `devtools.test.ts` if the overlay labels it. +**Tests.** `packages/runtime/test/`: a `situation.test.ts` case, a controller test in the style of `delivery.test.ts` / `fetch.test.ts` (hold, fail-open at the budget, passive on every exit, nothing held in default mode), `report.test.ts`, `devtools.test.ts` if the overlay labels it. -**Parity / retrain / release.** Class A plus a new label space: recipe 6 "Parity" in full, and the sim must be able to force every action of the new trigger. +**Parity / retrain / release.** Class A plus a new label space: recipe 6 in full; SIM and realapps must be able to force every action of the new trigger. -**Gotchas.** Controllers must tolerate a second `passive()` call (`runCustom` calls it outside the guard). Priority 2 is used only for held subjects; non-held ones are capped at 1. +**Gotchas.** Controllers must tolerate a second `passive()` call. Priority 2 is used only for held subjects; non-held ones are capped at 1. **See.** [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [decide-policy-actions.md](runtime/decide-policy-actions.md#how-to-change-it-safely). @@ -193,116 +226,121 @@ A change is done when all of these hold. Say explicitly in your final report whi **Goal.** (a) Change what an existing built-in action does or the `changed` sentence it reports; or (b) add a new built-in action. **Steps for (a), mechanics.** -1. Find the controller: mutation -> `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; inconsistency, transition and error -> `RuntimeImpl.raiseInconsistency`, `raiseTransition`, `reportError`, whose `rollback` runs `RuntimeImpl.rollback` (inconsistency: last consistent snapshot) or `RuntimeImpl.revertChain` (transition, error: the chain's own writes) and whose `resync` runs `RuntimeImpl.resync`; request, failure and stall -> `packages/runtime/src/observe/fetch.ts` -> `installFetch` (internal `reqCtl`, `failureGate`, `stallController`) and `packages/runtime/src/observe/xhr.ts` -> `installXHR` (request gate only; XHR failures and stalls are passive-only). -2. Keep the controller contract: throw when the action cannot run (the passive action then runs); return an exact `changed` sentence; provide `undo` only if the effect is truly reversible and idempotent; mark answers GenClass synthesises with `synthetic: true` and an `x-genclass` header; tolerate repeated `passive()` calls. -3. Applicability (whether it is offered) lives in `packages/runtime/src/situation/build.ts` -> `builtinApplicable`. Example open issue: `retry` is offered for any replayable fetch with `attempt < 4`, including non-idempotent POSTs (`demos/NEEDS.md` §5). +1. Find the controller: + - delivery (`deliver` / `discard` / `defer`) -> `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` (discard marks: `markWrites`, `dropFilter`, `writtenOver`, `onDropped`; store side `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter`); + - mutation -> `RuntimeImpl.mutationController`; held path (`policy.holdWrites: true`) `RuntimeImpl.gateMutation`; default non-holding path `RuntimeImpl.observeWrite` (a passing `discard` becomes a late revert); + - inconsistency, transition, error -> `RuntimeImpl.raiseInconsistency`, `raiseTransition`, `reportError`, whose `rollback` runs `RuntimeImpl.rollback` (inconsistency) or `RuntimeImpl.revertChain` (transition, error) and whose `resync` runs `RuntimeImpl.resync`; + - request, failure, stall -> `packages/runtime/src/observe/fetch.ts` -> `installFetch` and `packages/runtime/src/observe/xhr.ts` -> `installXHR`. +2. Keep the controller contract: throw when the action cannot run (the passive action then runs); return an exact `changed` sentence, built from what actually happened (the delivery `discard` sentence is written at decision time and can claim drops that did not happen on redux/zustand stores: open finding); provide `undo` only if the effect is truly reversible and idempotent; mark synthesised answers `synthetic: true` with an `x-genclass` header; tolerate repeated `passive()` calls. +3. Applicability lives in `packages/runtime/src/situation/build.ts` -> `builtinApplicable` (class A). Example open issue: `retry` is offered for any replayable fetch with `attempt < 4`, including non-idempotent POSTs (`demos/NEEDS.md` §5). **Steps for (b), a new action.** Do not do this in the runtime alone. 1. Get the user's go-ahead (class A, new label). -2. `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS` (name, tier `guard` or `heal`, model-facing description) and `TRIGGER_ACTIONS` (passive stays first). -3. `packages/runtime/src/situation/build.ts` -> `builtinApplicable`; the controller's `run()` for that trigger (step a1). +2. `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS` (name, tier `guard` or `heal`, description) and `TRIGGER_ACTIONS` (passive stays first), plus `TRIGGER_DESCRIPTIONS` if its text differs per trigger. +3. `builtinApplicable`; the controller's `run()` (step a1). 4. `packages/runtime/src/decide/report.ts` -> `LEAD` and `packages/runtime/src/devtools/ui.ts` -> `LEAD`. -5. Sim: `sim/src/oracle/cost.ts` -> `TIER`, `sim/src/run/transform.ts` -> `ACTION_PARA`, the test double `sim/src/run/fake-runtime.ts`, and a scenario in which forcing it is meaningful. -6. Training: `training/curriculum/fmt.py` -> `ACTION_DESC` (canonical description first), `TRIGGER_ACTIONS`, `TIER`; `training/curriculum/rt.py` -> `ACTIONS`, `TRIGGER_ACTIONS`; `training/eval_runtime.py` -> `TIER` (unknown actions default to heal tier in eval). +5. Sim: `sim/src/oracle/cost.ts` -> `TIER`, `sim/src/run/transform.ts` -> `ACTION_PARA`, `sim/src/run/fake-runtime.ts`, `sim/scripts/relabel.py`, and a scenario in which forcing it is meaningful. realapps reuses sim's tiers and transform; check its probe can force it. +6. Training: `training/curriculum/fmt.py` -> `ACTION_DESC`, `TRIGGER_ACTIONS`, `TIER`; `training/curriculum/rt.py` -> `ACTIONS`, `TRIGGER_ACTIONS` (and `DELIVERY_ACTION` if it maps); `training/eval_runtime.py` -> `TIER`; `training/t1_relabel.py` / `eval_gain.py` -> `PREM`. -**Tests.** `packages/runtime/test/`: `fetch.test.ts`, `xhr.test.ts`, `atoms.test.ts`, `review-fetch.test.ts`, `review-xhr.test.ts` (mechanics and `changed` text); `policy.test.ts` (tiers); `report.test.ts`, `devtools.test.ts`, `devtools-runtime.test.ts` (lead words); for a new action also `situation.test.ts` (options offered). +**Tests.** `packages/runtime/test/`: `delivery.test.ts`, `fetch.test.ts`, `xhr.test.ts`, `atoms.test.ts`, `review-fetch.test.ts`, `review-xhr.test.ts` (mechanics and `changed` text; add redux/zustand variants for store-side effects); `policy.test.ts` (tiers); `report.test.ts`, `devtools.test.ts`, `devtools-runtime.test.ts`; for a new action also `situation.test.ts`. -**Parity / retrain / release.** `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` membership/order, applicability and `ActionEffect.changed` (it reappears in later timelines) are all model input: recipe 6 "Parity". A pure mechanics change with the same `changed` text and the same applicability is class E. +**Parity / retrain / release.** `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` membership/order, applicability and `ActionEffect.changed` (it reappears in later timelines) are model input: recipe 6. A pure mechanics change with the same `changed` text and applicability is class E, but it changes SIM/realapps counterfactual costs (labels): tell SIM and REAL. -**Gotchas.** The rate limiter takes its slot before the effect, so failed attempts count; a custom action calling `ctx.builtin` takes two. `coalesce` (≤ 8 s), `delay` (≤ 8 s), `retry` backoff (≤ 5 s) keep the subject waiting after the hold budget timer is cleared. Only `discard` (and a late revert), `rollback` and custom actions with `onUndo` have an undo. The known `rollback` description mismatch (it says "last consistent snapshot" but transition/error rollback restores only the chain's writes) can only be fixed as a model-input change. +**Gotchas.** The rate limiter takes its slot before the effect, so failed attempts count. Delivery `discard` keeps dropping the chain's writes for `DISCARD_MARK_MS` (10 s), including later fresh polls chained from the discarded op, and survives `pause()`/`setMode("observe")`; each delivery `defer` can wait up to `LONG_RUNNING_MS` (10 s), two defers are allowed (a 20 s hold was reproduced), and it stalls the whole push channel behind it (open findings). `coalesce` (≤ 8 s), `delay` (≤ 8 s), `retry` backoff (≤ 5 s) keep the subject waiting after the hold budget timer is cleared. Only `discard` (and a late revert), `rollback` and custom actions with `onUndo` have an undo. **See.** [decide-policy-actions.md](runtime/decide-policy-actions.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes), [sim.md](sim.md#how-to-change-it-safely), [training.md](training.md#how-to-change-it-safely). ### 5. Change a policy threshold or default -**Goal.** Change a default such as a gate threshold, the hold budget, the rate limit, the default mode, `settleMs` or `historySize`, or change the gate logic itself. +**Goal.** Change a default such as a gate threshold, the hold budget, the rate limit, the default mode, `settleMs` or `historySize`, or the gate logic itself. **Where defaults live.** | default | value | defined in | |---|---|---| -| `mode` | `"guard"` | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor | +| `mode` | `"observe"` (f3636b2; `"guard"` before, and still in `0.1.0-alpha.0` on npm) | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | | `settleMs`, `historySize` | 60, 500 | same constructor | | `policy.thresholds` report / guard / heal | 0.6 / 0.9 / 0.8 | `packages/runtime/src/decide/policy.ts` -> `policyConfig` | -| `policy.holdBudgetMs` | `"auto"`: clamp(1.5 × median latency, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 with no data | `policyConfig`, `holdBudget` | -| `maxActionsPerMinute`, `requireDiagnosis`, `holdUserWrites` | 60, true, false | `policyConfig` | +| `policy.holdBudgetMs` | `"auto"`: clamp(round(1.5 × median latency), `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 with no data | `policyConfig`, `holdBudget` | +| `policy.holdWrites`, `holdUserWrites` | false, false | `policyConfig` | +| `maxActionsPerMinute`, `requireDiagnosis` | 60, true | `policyConfig` | | queue: `MAX_QUEUE`, `CACHE_MAX`, `CACHE_TTL`, `LATENCY_SAMPLES`, `PROVIDER_TIMEOUT_MS` | 32, 64, 30 s, 20, 10 s | `packages/runtime/src/decide/decider.ts` | -| `LATE_REVERT_MS`, `BACKGROUND_DEADLINE_MS` | 2,000 ms, 5,000 ms | `packages/runtime/src/runtime.ts` | +| `LATE_REVERT_MS`, `BACKGROUND_DEADLINE_MS`, `DISCARD_MARK_MS`, `BODY_WAIT_MS`, `LONG_RUNNING_MS`, `STALL_MIN_MS` | 2,000, 5,000, 10,000, 100, 10,000, 500 ms | `packages/runtime/src/runtime.ts` | | response cache and coalescing: `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS`; `COALESCE_MAX_WAIT_MS` | 256 KB, 64, 2,000 ms, 1,000 ms; 8,000 ms | `packages/runtime/src/observe/cache.ts`; `packages/runtime/src/observe/fetch.ts` | -| situation budgets | 3,200 / 1,100 / 500 chars | recipe 6 (model input) | +| situation budgets | `STATE_CHAR_BUDGET` 2,400, `COMPACT_BUDGET` 1,100, `MIN_BUDGET` 500; auto by device (WebGPU or unknown 2,400; WASM 1,000 at 1 thread to 2,000 at 4 threads) | `packages/runtime/src/situation/serialize.ts`; `RuntimeImpl.situationBudget` (model input: recipe 6) | **Steps.** -1. Change the value where it is defined (table). Options are read once in the constructor (`o.x ?? default`); only `setMode` changes behaviour live. -2. Update the JSDoc in `packages/runtime/src/types.ts` (`PolicyOptions`, `InitOptions`), `docs/runtime/API.md` ("Options", "Policy"), `packages/runtime/README.md`. +1. Change the value where it is defined. Options are read once in the constructor (`o.x ?? default`); only `setMode` changes behaviour live. +2. Update the JSDoc in `packages/runtime/src/types.ts` (`PolicyOptions`, `InitOptions`), `docs/runtime/API.md` ("Options", "Policy"), `packages/runtime/README.md`, the root `README.md`, and CONTRACT §13 for a default the contract names. The mode change f3636b2 did the JSDoc, API.md, ARCHITECTURE and §13; both READMEs now say observe is the default, but `HANDOFF.md` still says guard. 3. Gate logic: edit only `packages/runtime/src/decide/policy.ts` -> `gate`. Keep the reason strings verbatim: `policy.test.ts` and `report.test.ts` assert them, the console report prints them, devtools shows them, `demos/src/site/activity.ts` classifies decisions by the substrings `"hold budget"`, `"below the"` and `"expected"`, and the demos' results key `notExecuted` by the reason text. -4. Check the sim's forced-action contract in `sim/src/run/rt.ts` -> `createOptions` (`thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `requireDiagnosis: false`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`); it must still be able to force any action. -5. Mirror gate semantics or thresholds in `training/eval_runtime.py` (`THRESH`, `decision_metrics`) and the "Runtime gate" definition in `training/EVAL.md`. +4. Check the forced-action contracts: `sim/src/run/rt.ts` -> `createOptions` and `realapps/src/world/index.ts` both pass explicit `mode: "heal"` and `thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `requireDiagnosis: false`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`; they must still be able to force any action. Because they pass the mode explicitly, a default-mode change does not change their data. +5. Mirror gate semantics or thresholds in `training/eval_runtime.py` (`THRESH`, `decision_metrics`), `training/eval_gain.py` and the "Runtime gate" definition in `training/EVAL.md`. +6. A change to the default path (anything that can hold, delay or reorder app work without an explicit opt-in): run `default-mode.test.ts`, `no-reorder.test.ts`, `delivery.test.ts`, then propose a never-worse sweep (recipe 28) **[ask first]**. -**Tests.** `packages/runtime/test/`: `policy.test.ts` (thresholds, reasons, tiers, rate limit), `budget.test.ts` (hold budget 300 / 150 / 800 / adaptive; `timeoutMs` = budget + 2,000 for held writes; expired queued items never computed), `fetch.test.ts` (request and failure gates fail open at 300 ms; it imports `MAX_BODY` / `MAX_ENTRIES`), `review-fetch.test.ts` (64 × 256 KB buffer bound), `atoms.test.ts` (provider error codes fail open at once), `report.test.ts`, `batch3.test.ts` and `review-misc.test.ts` (a provider that never answers). Cache limits also appear in `docs/runtime/API.md` (`serve_cached` row) and CONTRACT §7. +**Tests.** `packages/runtime/test/`: `default-mode.test.ts` (no hold, delay or change in observe, even with a sure model or a model that never answers), `policy.test.ts`, `budget.test.ts` (hold budget 300 / 150 / 800 / adaptive), `fetch.test.ts` (gates fail open at 300 ms; imports `MAX_BODY` / `MAX_ENTRIES`), `review-fetch.test.ts`, `atoms.test.ts`, `delivery.test.ts`, `report.test.ts`, `batch3.test.ts` and `review-misc.test.ts` (a provider that never answers). Most tests run in guard because `test/helpers.ts` -> `setup` defaults `mode: "guard"`; tests of the hold pipeline add `policy: { holdWrites: true }`. -**Parity / retrain / release.** Class E for the model. Thresholds and budgets change eval comparability (tell TRAIN) and demo comparability. Triage thresholds are not policy: they are `neutral` expressions in `packages/runtime/src/situation/facts.ts` (recipe 2). +**Parity / retrain / release.** Class E for the model. Thresholds and budgets change eval comparability (tell TRAIN) and demo comparability. -**Gotchas.** The threshold applies to the summed probability of all permitted actions, at the candidate's tier. Thresholds of 0 run the first permitted action even at probability 0 (why the sim uses 0.5). The console hint "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" does nothing on a page where `GenClass.init` already ran. The auto hold budget is seeded from `status.warmupMs` until real latency samples exist. Several docs still say the hold budget default is 300 ms (CONTRACT §8, `demos/README.md`); the code default is `"auto"`. +**Gotchas.** The threshold applies to the summed probability of all permitted actions, at the candidate's tier. Thresholds of 0 run the first permitted action even at probability 0 (why SIM and REAL use 0.5). Observe mode still waits up to `BODY_WAIT_MS` (100 ms) for a conflicting delivery's body and runs XHR listeners outside the original dispatch (open finding: `default-mode.test.ts`'s "never holds" is not fully true for deliveries). The console hint "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" does nothing on a page where `GenClass.init` already ran. **See.** [decide-policy-actions.md](runtime/decide-policy-actions.md#configuration-and-constants), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely). -### 6. Change situation text, serialiser, budgets or questions +### 6. Change model-visible text under the situation-v2 freeze -**Goal.** Change anything the model reads: fact or timeline wording, state/stats/in-flight lines, section limits or character budgets, question headers, option descriptions, diagnosis labels, formatting or redaction helpers. +**Goal.** Change anything the model reads (fact or timeline wording, state/stats/in-flight lines, section limits or character budgets, question headers, option descriptions, trigger descriptions, diagnosis labels, formatting, redaction), or fix a defect in it, without silently splitting the training data. **Steps.** -1. Get the user's go-ahead first. Any such change invalidates SIM phase A/B data and the final training rounds (`situation-v1`). -2. Edit only `packages/runtime/src/situation/*` plus helpers in `packages/runtime/src/util.ts`; text that reaches the model from elsewhere: `packages/runtime/src/state/fields.ts` -> `changeText`, `ActionEffect.changed` strings, observer op details (recipe 1). -3. Find the code by section: +1. **Stop and ask.** Get the user's go-ahead and the colleague's coordination before editing (HANDOFF: "Any change to `packages/runtime/src/situation/*` changes the model's input, so it means a new tag and regenerated data. Coordinate before touching it."). SIM and REAL are generating v2 data on Azure with the frozen text right now. Agree on: whether the fix waits until after the current v2 generation and the first v2 model, or replaces them; the new tag name (`situation-v3`); who regenerates. +2. Batch the change. Each freeze costs a full regeneration and retrain, so collect every pending class A/B fix first. Candidates found by review at b435acb ([learn-situation-triage.md](runtime/learn-situation-triage.md#drift-and-open-issues), [training.md](training.md#drift-and-open-issues), [sim.md](sim.md#drift-and-open-issues)): the F2 redaction bypass (`content.ts` -> `contentFacts`), the leaf-based redactor no longer redacting numbers/arrays under secret-named containers (`util.ts` -> `isSensitivePath`), "…nor the value when #X started" asserted without checking, every successful POST counted as a create (`createdIds`), HTTP 502 in `NOT_PROCESSED` (`evidence.ts`), the SIM and realapps budget weights still sampling the v1 3,200-char budget 40% of the time (`sim/src/world/scenario.ts`, `realapps/src/harness/scenario.ts`; production never exceeds 2,400), and the `rt.py` divergences. +3. Edit only `packages/runtime/src/situation/*`, the helpers in `packages/runtime/src/util.ts`, `packages/runtime/src/state/fields.ts` (`changeText`, `stringDiff`), and the other class A sources listed in [the freeze table](#2-the-situation-v2-freeze). Find the code by section: | what | runtime | Python port (`training/curriculum/rt.py`) | |---|---|---| -| facts | `packages/runtime/src/situation/facts.ts` (recipe 2) | `*_facts`, `request_common`, `order` | -| subject sentence | `packages/runtime/src/situation/build.ts` -> `subjectOf` | `subject_sentence` | -| timeline lines | `packages/runtime/src/situation/describe.ts` -> `eventLine`, `opPhrase`; `packages/runtime/src/situation/build.ts` -> `timelineLines` | `event_lines`, `phrase` | -| state / stats / in-flight lines | `packages/runtime/src/situation/build.ts` -> `stateLines`, `statsLines`, `inFlightLines` | `state_lines`, `stats_lines`, `in_flight_lines` | -| budgets and shrink order | `packages/runtime/src/situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `sectionLimits`, `toJevState`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget` | `STATE_CHAR_BUDGET`, `LIMITS`, `section_limits`, `to_state`, `BUDGETS` | -| questions | `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `buildQuestions` | `ACTIONS`, `ACTION_INSTR`, `DIAG_INSTR`, `DIAGNOSES` | -| formatters | `packages/runtime/src/util.ts` -> `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe` | `secs`, `rel`, `fmt_num`, `ratio`, `truncate` | -| signatures | `packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`, `isSlugId` | `signature`, `is_id` | -| redaction | `packages/runtime/src/util.ts` -> `isSensitiveName`, `SECRET_WORDS`, `SECRET_PAIRS`, `defaultRedact` | | - - -4. Diagnosis labels: keep `expected` first and `transient` last (`batch3.test.ts` asserts `unusual`, `transient` are last). Also update `sim/src/types.ts` -> `DIAGNOSES`, `sim/src/world/scenario.ts` -> `DEFAULT_DIAGNOSES` and `DIAG_PARA`, `sim/src/oracle/diagnose.ts` (so the sim can emit the label), `training/curriculum/fmt.py` -> `DIAG_DESC` (canonical first). -5. Action descriptions and instructions: also `sim/src/run/transform.ts` -> `ACTION_PARA`, `training/curriculum/fmt.py` -> `ACTION_DESC` canonical first entries. Per-header calibration keys are `sha1(instructions)[:12]`, so a changed header orphans its `by_header` entry. -6. Budgets: also `sim/src/world/scenario.ts` -> `buildScenario` budget weights (3200/2000/1000 at 40/30/30), the JSDoc of `InitOptions.situation` in `packages/runtime/src/types.ts` (currently drifted), `docs/runtime/API.md`, and check token lengths against the model's `meta.max_len` (TRAIN measured about 2.4 chars/token). -7. Redaction: also `docs/runtime/API.md` "Privacy". - -**Tests.** `packages/runtime/test/`: `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `learn.test.ts`, `review-redaction.test.ts` (for redaction), `report.test.ts` / `atoms.test.ts` / `fetch.test.ts` (for `changed` text); then the full suite. Update the STATUS.md example blocks from the printed situations. **[ask first]** `sim/test/rows.test.ts`, `determinism.test.ts`, `oracle.test.ts` with `SIM_RUNTIME=real`; `training/tests/test_curriculum.py` both with and without `GC_P_RUNTIME=1` (the default run never exercises `rt.py`). - -**Parity / retrain / release (the full follow-up for any class A change).** -1. Re-port `training/curriculum/rt.py` and render a few rows per budget against `sim/samples/sample.jsonl`. -2. **[ask first]** Rebuild the runtime and regenerate SIM data (recipe 17) and `sim/samples/*`. -3. **[ask first]** Regenerate a curriculum replay set with `--p-runtime 0.8`, retrain, then evaluate, calibrate and export (recipe 18). -4. The lead tags a new freeze (the `situation-v1` convention; no v2 exists). Re-run the demos with the new model (recipe 22). - -**Gotchas.** `packages/runtime/src/situation/serialize.ts` -> `stateText` (public; `explain()`, devtools, STATUS) indents list items and is not the token text; the packer uses `packages/runtime/src/model/serialize.ts` -> `segmentText`. `COMPACT_BUDGET` (1,100, section sizes) and `COMPACT_QUESTIONS_BUDGET` (1,400, bare labels) are different constants; keep both. Situation building must stay deterministic and side-effect free, or the sim's prefix check drops trajectories. Python rows must print integral floats as ints (`training/curriculum/fmt.py` -> `js_numbers`). Known `rt.py` gaps: fact shortening floor 40 vs 60 chars, half-even vs half-up rounding on exact ties. Avoid plugin question ids `action` and `diagnosis`. - -**See.** [model-io-contract.md](model-io-contract.md#how-to-change-it-safely), [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [status-and-known-issues.md](status-and-known-issues.md#how-to-change-it-safely), [training.md](training.md#how-to-change-it-safely). +| facts | `situation/facts.ts`, `conflicts.ts`, `content.ts`, `evidence.ts` (recipe 2) | `*_facts`, `request_common`, `version_facts`, `content_facts`, `scope_facts`, `commit_ambiguity`, `repeat_evidence`, `cadence_fact`, `mark_facts`, `order` | +| delivery prediction text | `facts.ts` -> `predictedText`, `deliveryFacts`; `build.ts` -> `relatedInFlight` | `delivery_spec`, `predicted_text`, `related_in_flight`, `field_list_text` | +| subject sentence | `situation/build.ts` -> `subjectOf` | `subject_sentence` | +| timeline lines | `situation/describe.ts` -> `eventLine`, `opPhrase`; `build.ts` -> `timelineLines` | `event_lines` | +| state / stats / in-flight lines | `build.ts` -> `stateLines`, `statsLines`, `inFlightLines` | `state_lines`, `stats_lines`, `in_flight_lines` | +| change text | `state/fields.ts` -> `changeText`, `stringDiff` | `change_text`, `string_diff` | +| budgets and shrink order | `situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `sectionLimits`, `toJevState`; `runtime.ts` -> `RuntimeImpl.situationBudget` | `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `section_limits`, `to_state`, `BUDGETS` | +| questions | `situation/questions.ts` -> `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `TRIGGER_DESCRIPTIONS`, `COMPACT_QUESTIONS_BUDGET`, `buildQuestions` | `ACTIONS`, `TRIGGER_ACTIONS`, `ACTION_INSTR`, `DIAG_INSTR`, `DIAGNOSES`, `TRIGGER_DESCRIPTIONS`, `COMPACT_QUESTIONS_MAX` | +| formatters | `util.ts` -> `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe` | `secs`, `rel`, `fmt_num`, `ratio`, `plural`, `ordinal`, `truncate` | +| signatures | `util.ts` -> `normalizePath`, `normalizeFieldPath`, `isIdSegment` | `signature`, `is_id`, `normalize_field_path` | +| redaction | `util.ts` -> `isSensitiveName`, `isSensitivePath`, `defaultRedact` | (none: curriculum values are synthetic) | + +4. Mirrors outside the runtime: diagnosis labels (keep `expected` first and `transient` last) in `sim/src/types.ts` -> `DIAGNOSES`, `sim/src/world/scenario.ts` -> `DEFAULT_DIAGNOSES`, `DIAG_PARA`, `sim/src/oracle/diagnose.ts`, `training/curriculum/fmt.py` -> `DIAG_DESC`; action descriptions in `sim/src/run/transform.ts` -> `ACTION_PARA` and `fmt.py` -> `ACTION_DESC` (canonical first). Per-header calibration keys are `sha1(header)[:12]`, so a changed header orphans its `by_header` entry. Budgets: the SIM and realapps `buildScenario` budget weights, `rt.py` `BUDGETS`, `InitOptions.situation` JSDoc, API.md; check token lengths against `meta.max_len` (≈ 2.4 chars/token). Redaction: API.md "Privacy" and CONTRACT (it still documents the old substring rule). +5. Tests (local): `packages/runtime/test/` `situation.test.ts`, `budget.test.ts`, `delivery.test.ts`, `content.test.ts`, `batch3.test.ts`, `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts`, `review-redaction.test.ts`, `learn.test.ts`, `report.test.ts` / `atoms.test.ts` / `fetch.test.ts` (for `changed` text), then the full suite; `cd sim && SIM_RUNTIME=real npx vitest run` after a runtime build. Update the STATUS.md example blocks from the printed situations. +6. Re-port `training/curriculum/rt.py` ([training.md](training.md#how-to-change-it-safely), "Mirror a runtime situation/question wording change"): diff `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/state/fields.ts packages/runtime/src/util.ts`, update the matching functions, render rows at each budget and compare with SIM rows for the same situations. **[ask first]** `training/tests/test_curriculum.py` with and without `GC_P_RUNTIME=1` (the default run never exercises `rt.py`; `test_runtime_rows_situation_v2` is pure Python and should be renamed or extended for the new tag). +7. Commit, then **the user (or the lead) creates the freeze tag** (`git tag situation-v3 <commit>`; never create or push tags yourself) and records it in HANDOFF, CONTRACT §13 and [model-io-contract.md](model-io-contract.md#versioning-what-invalidates-the-trained-model). +8. **[ask first]** Regenerate SIM data from the tagged runtime (recipe 17): rebuild the runtime and sim `dist/`, rebuild the cluster bundle (`sim/scripts/cluster/bundle.sh`), new seed bases (never reuse a v2 base: gold 11e9, unlabeled 16e9, on-policy 22e9, checks 19e9 are taken), regenerate `sim/samples/*`. SIM rows carry only `meta.runtime: "real"`, not the tag: record the tag per batch in `training/NEEDS.md` and the run name. +9. **[ask first]** Regenerate realapps data from the tagged runtime: `TAG=situation-v3 realapps/scripts/cluster.sh setup <host>` (exports `git archive` of the tag and pins `RW_RUNTIME_SRC`/`RW_RUNTIME_TAG`), rerun the determinism and never-worse sweeps (recipe 28), a pilot plus `realapps/scripts/analyze.py`, then production batches with new seed ranges; fix the hard-coded `runtime` string in `realapps/src/harness/gen.ts` -> `manifest` first. Rows from different tags must never be mixed (filter REAL by `meta.runtime`). +10. **[ask first]** Regenerate a curriculum replay set with the new `rt.py` (`--p-runtime 0.8`, new seed and bucket), then retrain, evaluate, calibrate and export on the new data only (recipe 30), rerun the demos (recipe 22), and release model then runtime (recipes 20, 19). The published runtime and the model it loads must share one tag. + +**Gotchas.** `packages/runtime/src/situation/serialize.ts` -> `stateText` (public; `explain()`, devtools, STATUS) indents list items and is not the token text; the packer uses `packages/runtime/src/model/serialize.ts` -> `segmentText`. `COMPACT_BUDGET` (1,100, section sizes) and `COMPACT_QUESTIONS_BUDGET` (1,400, bare labels) are different constants; keep both. Situation building must stay deterministic and side-effect free, or the SIM/realapps prefix checks drop trajectories. Python rows must print integral floats as ints (`fmt.py` -> `js_numbers`) and round half-up like JS. Avoid plugin question ids `action` and `diagnosis`. A runtime fix that is "only a bug fix" (e.g. the F2 redaction leak) is still class A: it is a privacy defect worth shipping, but agree its timing with the user. + +**See.** [model-io-contract.md](model-io-contract.md#how-to-change-it-safely), [learn-situation-triage.md](runtime/learn-situation-triage.md#how-to-change-it-safely), [training.md](training.md#how-to-change-it-safely), [sim.md](sim.md#how-to-change-it-safely), [realapps.md](realapps.md#how-to-change-it-safely). ### 7. Change the state pipeline or invariants -**Goal.** Change how writes are proposed, held, applied, patched or reverted; fix the open user-write ordering risk (`demos/NEEDS.md` §1); add an invariant template; change flattening caps; handle dotted store names. +**Goal.** Change how writes are proposed, held, applied, patched, filtered or reverted; add an invariant template; change flattening caps; handle dotted store names. **Steps.** -1. **Bypass, hold and late-revert rules:** `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` (the `bypass` expression: user-sync writes unless `policy.holdUserWrites`, GenClass writes, stores with `hold: false`, and any write while paused or destroyed), `StoreHub.revertable`, and `packages/runtime/src/runtime.ts` -> `LATE_REVERT_MS`. These are policy-visible: update `docs/runtime/API.md` "State". -2. **User-write ordering fix (`demos/NEEDS.md` §1, open):** in `StoreHub.propose`, when a bypass write targets a store whose `queue` is non-empty, either apply the pending writes first in proposal order, or mark the overlapping held writes superseded and re-gate them. Add the regression test demos suggests (hold a functional write to `s.x`, make a user-sync write to `s.x`, release with `apply`, expect the user's value) and update `atoms.test.ts` "functional updates re-run against the value at apply time", which asserts the current order. -3. **Invariant template:** `packages/runtime/src/state/invariants.ts` -> extend `Tpl`, implement it in `InvariantMiner.holds` (null when not applicable), `nonTrivial`, `valuesText` and `propose` with a deterministic id and readable text; put per-array work in `ArrayStats` so it runs once per array version. -4. **Flattening caps or hashing:** `packages/runtime/src/state/fields.ts` -> `MAX_DEPTH`, `MAX_KEYS_EXPAND`, `MAX_FIELDS_PER_STORE`, and the sampling and hashing helpers. +1. **Know the two paths** (`packages/runtime/src/state/hub.ts` -> `StoreHub.propose`): + - **Default (`policy.holdWrites: false`):** every write commits synchronously in the caller's stack; a salient write that no delivery decision covers raises a non-holdable `mutation` trigger (`RuntimeImpl.observeWrite`, `covered`), and a gate-passing `discard` becomes a late revert (`StoreHub.revertable`, `LATE_REVERT_MS`). A delivery `discard` mark filters the chain's later writes (`StoreHub.applyFilter` via `RuntimeImpl.dropFilter`). + - **Opt-in (`holdWrites: true`):** the `bypass` expression (user-sync writes unless `holdUserWrites`, GenClass writes, stores with `hold: false`, not gating) and `hooks.mayHold`; held writes go through `gateAndQueue` / `RuntimeImpl.gateMutation`; any write that applies at once first calls `flushQueue`, so a hold never reorders a store's writes (the old `demos/NEEDS.md` §1 jump-back is fixed). + Keep "apply in the caller's stack, in order; observation never throws into the write" for the default path. These rules are policy-visible: update `docs/runtime/API.md` "State". +2. **Adapter stores:** `applyFilter` cannot drop individual fields of a redux/zustand whole-state write, so a delivery `discard` there is a silent no-op that is still recorded as a drop (open finding, [state-and-adapters.md](runtime/state-and-adapters.md#drift-and-open-issues)). A fix applies kept changes through the store's `io.set` or reports the drop honestly; it changes `changed` text (class A) and SIM/realapps labels for redux/zustand apps. +3. **Invariant template:** `packages/runtime/src/state/invariants.ts` -> extend `Tpl`, implement it in `InvariantMiner.holds` (null when not applicable), `nonTrivial`, `valuesText` and `propose` with a deterministic id and readable text; put per-array work in `ArrayStats`. +4. **Flattening caps or hashing:** `packages/runtime/src/state/fields.ts` -> `MAX_DEPTH`, `MAX_KEYS_EXPAND`, `MAX_FIELDS_PER_STORE`. 5. **Patch semantics:** `packages/runtime/src/state/fields.ts` -> `patchValue`; keep "removals first; never remove a path with a set beneath it". -6. **Dotted store names:** nothing enforces "no `.` in store names", and every path lookup splits on `.`. Either validate in `RuntimeImpl.atom` / `guard` / `adapter` (prefer a console warning and a sanitised name; throwing breaks apps) or pass the store explicitly instead of `path.split(".")[0]`. Fix the `packages/runtime/README.md` and `packages/runtime/src/adapters/react.ts` header examples (`"search.results"`). +6. **Dotted store names:** nothing enforces "no `.` in store names", and every path lookup splits on `.`. Either validate in `RuntimeImpl.atom` / `guard` / `adapter` (prefer a console warning and a sanitised name; throwing breaks apps) or pass the store explicitly. Fix the `packages/runtime/README.md` and `packages/runtime/src/adapters/react.ts` header examples (`"search.results"`). 7. **Settled points and snapshots:** `RuntimeImpl.settled`, `RuntimeImpl.busy`. -**Tests.** `packages/runtime/test/`: `atoms.test.ts`, `review-hub.test.ts`, `invariants.test.ts`, `adapter-seam.test.ts`, `adapters-react.test.ts`, `adapters-redux.test.ts`, `adapters-zustand.test.ts`, `review-perf.test.ts`, `review-precision.test.ts`, `situation.test.ts`, `batch3.test.ts`, `policy.test.ts`, `learn.test.ts`, `review-actions.test.ts`; then the full suite. A new template needs a learning test and a precision test (no false `inconsistency` on benign behaviour). +**Tests.** `packages/runtime/test/`: `atoms.test.ts`, `delivery.test.ts`, `no-reorder.test.ts`, `default-mode.test.ts`, `content.test.ts`, `review-hub.test.ts`, `invariants.test.ts`, `adapter-seam.test.ts`, `adapters-react.test.ts`, `adapters-redux.test.ts`, `adapters-zustand.test.ts`, `review-precision.test.ts`, `situation.test.ts`, `batch3.test.ts`, then `review-perf.test.ts` alone, then the full suite. A new template needs a learning test and a precision test (no false `inconsistency` on benign behaviour). -**Parity / retrain / release.** Template text, flattening and `changeText` output appear verbatim in situations: class A. Bypass/hold/ordering fixes change no text but change sim dynamics (class B): tell SIM and TRAIN. Re-run the demos' board trials to measure §1 (recipe 22). +**Parity / retrain / release.** Template text, flattening and `changeText` output appear verbatim in situations: class A. Bypass/hold/filter changes change no text but change SIM and realapps dynamics (class B): tell SIM and REAL. Any default-path change: never-worse sweep (recipe 28) **[ask first]**. -**Gotchas.** `review-perf.test.ts` asserts wall-clock budgets on 5,000-item stores (< 1 ms per keystroke write, < 16 ms per settled point); any O(n) per-write work (hashing, cloning, `JSON.stringify`) breaks them, and they can flake on a loaded machine. Updaters may run several times and must be pure. Rollback for `inconsistency` restores whole stores; error/transition rollback is field-precise. +**Gotchas.** `review-perf.test.ts` asserts wall-clock budgets on 5,000-item stores; any O(n) per-write work breaks them, and they can flake on a loaded machine (CI retries them twice). Updaters may run several times and must be pure. Read-your-writes (`StoreHub.pendingView`) reaches only the runtime's own `get()`, not `store.getState()` of a library. A held write applied early by `flushQueue` must not be reopened by a late verdict (`gateAndQueue`). **See.** [state-and-adapters.md](runtime/state-and-adapters.md#how-to-change-it-safely). @@ -312,16 +350,16 @@ A change is done when all of these hold. Say explicitly in your final report whi **Steps.** 1. Add `packages/runtime/src/adapters/<lib>.ts`. Call `runtime.adapter(name, { get, set?, subscribe? }, opts)` once per store (`packages/runtime/src/types.ts` -> `Runtime.adapter`, `AdapterIO`, `AdapterHandle`). -2. Route every app write through `handle.propose({ fn | value, commit })`. `commit(next)` must write to the library store synchronously; it runs later for held writes and never for discarded ones. Provide `set` if GenClass may write whole states (rollback, resync); without it the store is not writable. -3. Build and package: `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry` (keep the literal `"src/...ts"` strings: `packages/runtime/test/browser/build.mjs` finds them with a regex), the library in `external`; `packages/runtime/package.json` -> an `exports` subpath (`types` + `import`), an optional `peerDependencies` entry plus `peerDependenciesMeta`, and the library as a devDependency for tests. -4. If the demos use it: a shim in `demos/src/dev/runtime-shim/`, an alias in `demos/vite.config.ts`, a path in `demos/tsconfig.shim.json`. +2. Route every app write through `handle.propose({ fn | value, commit })`. `commit(next)` must write to the library store synchronously; on the default path it runs at once, under `holdWrites` later for held writes and never for discarded ones. Provide `set` if GenClass may write whole states (rollback, resync, a field-precise discard); without it the store is not writable. +3. Build and package: `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry` (keep the literal `"src/...ts"` strings: `packages/runtime/test/browser/build.mjs` finds them with a regex), the library in `external`; `packages/runtime/package.json` -> an `exports` subpath (`types` + `import`), an optional `peerDependencies` entry plus `peerDependenciesMeta`, and the library as a devDependency (then `npm install` at the root and commit the lockfile). +4. If the demos use it: a shim in `demos/src/dev/runtime-shim/`, an alias in `demos/vite.config.ts`, a path in `demos/tsconfig.shim.json`. If realapps should cover it: an alias in `realapps/build.mjs` and an app (recipe 29). 5. Changing an existing adapter: keep its contracts (commit exactly once on apply, never on discard; Redux reducer once per applied dispatch and inner enhancers see the original action; Zustand commits with `replace = true` and forwards extra `set()` arguments; React: one atom per (runtime, name), plain `useState` fallback without a runtime). Update the file's header comment and API.md "Adapters and devtools". -**Tests.** Model the new file on `packages/runtime/test/adapters-zustand.test.ts`: `MockRuntime` (`holdWrites`, `flushHeld`, `dropHeld`, `genclassWrite`) plus one test against the real runtime with `ManualDecider`. Run `adapter-seam.test.ts`, the `adapters-*.test.ts` files and `review-perf.test.ts`. Build with `npx tsup`. **[ask first]** `cd packages/runtime && bash test/smoke/smoke.sh` after adding an import of the new subpath to the `src/main.js` that `packages/runtime/test/smoke/smoke.sh` generates. +**Tests.** Model the new file on `packages/runtime/test/adapters-zustand.test.ts`: `MockRuntime` plus one test against the real runtime with `ManualDecider`. Run `adapter-seam.test.ts`, the `adapters-*.test.ts` files, `no-reorder.test.ts` and `review-perf.test.ts`. Build. **[ask first]** `cd packages/runtime && bash test/smoke/smoke.sh` after adding an import of the new subpath to the `src/main.js` that `smoke.sh` generates. -**Parity / retrain / release.** Class E. A new subpath is a public-surface change: update API.md, the package README and the "Extra public surface" bullet under STATUS "Deviations from the contract (and why)". +**Parity / retrain / release.** Class E. A new subpath is a public-surface change: API.md, the package README, the "Extra public surface" bullet under STATUS "Deviations from the contract (and why)". -**Gotchas.** Redux and Zustand capture `runtime` when the store is created, so `genclass(GenClass.runtime, …)` evaluated before `GenClass.init()` gets `null` and is never guarded. Store names are global per runtime across kinds: reusing a name re-registers the store and orphans old handles. A library listener that throws inside `commit` looks like a failed setter. +**Gotchas.** Redux and Zustand capture `runtime` when the store is created, so `genclass(GenClass.runtime, …)` evaluated before `GenClass.init()` gets `null` and is never guarded. Store names are global per runtime across kinds. A library listener that throws inside `commit` looks like a failed setter. **See.** [state-and-adapters.md](runtime/state-and-adapters.md#how-to-change-it-safely), [build-test-release.md](runtime/build-test-release.md#add-a-public-entry-point-new-subpath-export). @@ -330,21 +368,21 @@ A change is done when all of these hold. Say explicitly in your final report whi **Goal.** Extend the public surface of `@genclass/runtime`. **Steps.** -1. **Init option:** add the field with a JSDoc default to `packages/runtime/src/types.ts` -> `InitOptions` (or `CreateOptions` if headless-only); read it once in the `RuntimeImpl` constructor with an explicit default; check the four creation paths in `packages/runtime/src/index.ts` -> `initUnsafe` (browser, non-browser, kill-switch `off`) and the `GenClass.init` fallback, and decide whether the option survives each. Host-only model options: recipe 12. -2. **`Runtime` method:** add it to `packages/runtime/src/types.ts` -> `Runtime` and implement it in `packages/runtime/src/runtime.ts` -> `RuntimeImpl`. Update every other implementer by hand: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime` and `demos/src/dev/runtime-shim/index.ts` -> `ShimRuntime` (which already lacks `adapter`, `holdBudgetMs`, `situationBudget`). Add it to `sim/src/run/rt.ts` -> `RuntimeLike` only if the sim calls it. Keep it non-throwing if devtools will call it (devtools wraps calls in `safe()`). -3. **Changing an existing method or option:** find callers outside `src/`: the sim (loaded by module name via `GENCLASS_RUNTIME`, so a break shows only at sim run time), `MockRuntime`, `ShimRuntime`, `packages/runtime/src/devtools/index.ts`, `packages/runtime/src/adapters/react.ts` -> `useRuntimeList`. -4. **Event type:** add the key and payload to `packages/runtime/src/types.ts` -> `RuntimeEvents`, add a `Set` for it in `RuntimeImpl`'s `listeners` initializer (otherwise `on(newType)` throws), fire it with `RuntimeImpl.fire`. Update `packages/runtime/src/devtools/index.ts` -> `subscribe` and its unmount test list if the overlay should react. -5. **Error class:** runtime-level errors live in `packages/runtime/src/errors.ts`; model errors in recipe 12. Re-export from `packages/runtime/src/index.ts`. -6. **Subpath export:** `packages/runtime/package.json` -> `exports` (`"./<name>": { "types": "./dist/<name>.d.ts", "import": "./dist/<name>.js" }`), `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry`, externalise any new peer library; demos shim and aliases if demos use it (recipe 8 step 4). +1. **Init option:** add the field with a JSDoc default to `packages/runtime/src/types.ts` -> `InitOptions` (or `CreateOptions` if headless-only); read it once in the `RuntimeImpl` constructor with an explicit default; check the creation paths in `packages/runtime/src/index.ts` -> `initUnsafe` (browser, non-browser, kill-switch `off`) and the `GenClass.init` fallback. Host-only model options: recipe 12. +2. **`Runtime` method:** add it to `packages/runtime/src/types.ts` -> `Runtime` and implement it in `packages/runtime/src/runtime.ts` -> `RuntimeImpl`. Update every other implementer by hand: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime` and `demos/src/dev/runtime-shim/index.ts` -> `ShimRuntime`. Add it to `sim/src/run/rt.ts` -> `RuntimeLike` only if the sim calls it. Keep it non-throwing if devtools will call it. +3. **Changing an existing method or option:** find callers outside `src/`: the sim (loaded by module name via `GENCLASS_RUNTIME`, so a break shows only at sim run time), realapps (bundled from source; `realapps/src/world/{index,probe}.ts`, `apps/_shared/*`), `MockRuntime`, `ShimRuntime`, `packages/runtime/src/devtools/index.ts`, `packages/runtime/src/adapters/react.ts`. +4. **Event type:** add the key and payload to `packages/runtime/src/types.ts` -> `RuntimeEvents`, add a `Set` for it in `RuntimeImpl`'s `listeners` initializer (otherwise `on(newType)` throws), fire it with `RuntimeImpl.fire`. Update `packages/runtime/src/devtools/index.ts` -> `subscribe` if the overlay should react. +5. **Error class:** runtime-level errors in `packages/runtime/src/errors.ts`; model errors in recipe 12. Re-export from `packages/runtime/src/index.ts`. +6. **Subpath export:** `packages/runtime/package.json` -> `exports`, `packages/runtime/tsup.config.ts` -> `entry` and `dts.entry`, externalise any new peer library; demos shim and aliases if demos use it (recipe 8 step 4). 7. Time-dependent behaviour uses `this.clock.now()` / `this.clock.setTimeout` / `this.clock.afterTask`; store the handle and clear it in `RuntimeImpl.destroy`. -8. **Kill switch or init paths:** `packages/runtime/src/index.ts` -> `killSwitch`, `initUnsafe`; keep everything inside the try/catch of `GenClass.init`. **`destroy()`:** `RuntimeImpl.destroy` must stay idempotent, clear every new timer, uninstall observers in reverse order and dispose only a decider it created (`createRuntime` with `model: {...}` and no `decider`). -9. Docs: JSDoc in `packages/runtime/src/types.ts`, `docs/runtime/API.md`, `packages/runtime/README.md`, `packages/runtime/STATUS.md` ("Deviations" lists the public surface beyond CONTRACT §2), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). +8. **Kill switch or init paths:** `packages/runtime/src/index.ts` -> `killSwitch`, `initUnsafe`; keep everything inside the try/catch of `GenClass.init`. `RuntimeImpl.destroy` must stay idempotent, clear every new timer, uninstall observers in reverse order, dispose only a decider it created, and leave no active `discardMark` behind (open finding). +9. Docs: JSDoc in `packages/runtime/src/types.ts`, `docs/runtime/API.md`, `packages/runtime/README.md`, `packages/runtime/STATUS.md`, [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). -**Tests.** A test using `setup({ ...option })` from `packages/runtime/test/helpers.ts`. Lifecycle changes: `report.test.ts` ("GenClass.init and the kill switch"), `batch3.test.ts` ("lifecycle"), `dom.test.ts` / `fetch.test.ts` / `xhr.test.ts` (destroy restores globals), `review-misc.test.ts`. Build with `npx tsup` for export changes; **[ask first]** `cd packages/runtime && bash test/smoke/smoke.sh`. +**Tests.** A test using `setup({ ...option })` from `packages/runtime/test/helpers.ts` (note: it defaults `mode: "guard"`; use `GenClass.init` or pass no mode in a `createRuntime` call to test the real default, as `default-mode.test.ts` does). Lifecycle changes: `report.test.ts`, `batch3.test.ts`, `dom.test.ts` / `fetch.test.ts` / `xhr.test.ts`, `review-misc.test.ts`, `smoke.test.ts`. Build for export changes; **[ask first]** `bash test/smoke/smoke.sh`. -**Parity / retrain / release.** Only if the option alters situation text or decisions: then coordinate with SIM (`sim/src/run/rt.ts` -> `createOptions`) and treat it as class A/B. Public-surface changes go into the next release notes (recipe 19). +**Parity / retrain / release.** Only if the option alters situation text or decisions: then coordinate with SIM and REAL (`createOptions`, `realapps/src/world/index.ts`) and treat it as class A/B. Public-surface changes go into the next release notes (recipe 19). -**Gotchas.** `GenClass.init` is idempotent: later calls ignore their options. `createRuntime` can throw on malformed options; `GenClass.init` never does (inert fallback). Any non-`undefined` `decider` (including `null`) disables model creation. `on("status")` also fires on `setMode`. `decisions(0)` returns the whole buffer. +**Gotchas.** `GenClass.init` is idempotent: later calls ignore their options. `createRuntime` can throw on malformed options; `GenClass.init` never does (inert fallback). Any non-`undefined` `decider` (including `null`) disables model creation. `on("status")` also fires on `setMode`. **See.** [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#how-to-change-it-safely), [build-test-release.md](runtime/build-test-release.md#add-a-public-entry-point-new-subpath-export). @@ -354,17 +392,17 @@ A change is done when all of these hold. Say explicitly in your final report whi **Steps.** 1. Write a `Plugin` (`packages/runtime/src/types.ts` -> `Plugin`: `name`, `setup?(api)`, `facts?(sit)`, `actions?`, `questions?`, `diagnoses?`) and pass it as `GenClass.init({ plugins: [p] })` or `rt.use(p)`. Single pieces: `rt.action(def)`, `rt.question(def)`. Reference app: `demos/src/demos/decisions/plugin.ts` -> `backgroundWorkPlugin`. -2. **Custom action** (`ActionDef`): `name`, `description` (the model reads it), `on: TriggerKind[]`, `tier` (default `"heal"`), optional `applicable(sit)`, `run(ctx)`. In `run`, call `ctx.describe(changed)` with exactly what changed, `ctx.onUndo(fn)` if reversible, and `ctx.builtin("<name>")` to delegate to a built-in (re-checked against mode, policy and rate, not thresholds). The passive action runs afterwards unless a built-in took over. -3. **Standing question** (`StandingQuestion`): `id`, `on`, `question` (`{ type: "noul" | "choice" | "score", instructions, criteria }`), `always?` (ask even when triage finds nothing salient), `onAnswer(answer, ctx)` (runs before any action). -4. **Facts and signals:** `facts(sit)` returns strings (always neutral, ranked last, cut first by the budget). In `setup(api)`, use `api.clock`, `api.emit`, `api.recordOp` / `api.endOp` / `api.runInOp` for app ops, and return a cleanup function. +2. **Custom action** (`ActionDef`): `name`, `description` (the model reads it), `on: TriggerKind[]`, `tier` (default `"heal"`), optional `applicable(sit)`, `run(ctx)`. In `run`, call `ctx.describe(changed)` with exactly what changed, `ctx.onUndo(fn)` if reversible, and `ctx.builtin("<name>")` to delegate to a built-in. Nothing runs in the default `observe` mode: the app must opt in to `guard` (guard-tier custom actions) or `heal`. +3. **Standing question** (`StandingQuestion`): `id`, `on`, `question` (`{ type: "noul" | "choice" | "score", instructions, criteria }`), `always?`, `onAnswer(answer, ctx)`. A standing question on `delivery` is answered only when the delivery is held; in observe mode the background delivery decision is dropped and `onAnswer` never runs (open finding). +4. **Facts and signals:** `facts(sit)` returns strings (always neutral, ranked last, cut first by the budget). In `setup(api)`, use `api.clock`, `api.emit`, `api.recordOp` / `api.endOp` / `api.runInOp`, and return a cleanup function. 5. One-off questions: `rt.ask(question, { about, timeoutMs })` and `rt.decide(question, options)`. -6. Changing the plugin API itself (runtime side, CORE): `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`, `action`, `question`, `use`, `pluginApi`; offering in `packages/runtime/src/situation/build.ts` -> `buildSituation`. Tests: `plugins.test.ts`, `batch3.test.ts`, `review-misc.test.ts`. +6. Changing the plugin API itself (CORE): `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`, `action`, `question`, `use`, `pluginApi`; offering in `packages/runtime/src/situation/build.ts` -> `buildSituation`. Tests: `plugins.test.ts`, `ask.test.ts`, `batch3.test.ts`, `review-misc.test.ts`. -**Tests.** Pattern: `packages/runtime/test/plugins.test.ts` (custom action runs then passive, `ctx.builtin`, default heal tier, `applicable`, standing questions and `onAnswer`, `setup` cleanup, vocabulary overrides). In an app, verify with `rt.explain(id)` and the devtools overlay. +**Tests.** Pattern: `packages/runtime/test/plugins.test.ts`. In an app, verify with `rt.explain(id)` and the devtools overlay. -**Parity / retrain / release.** No retrain is needed: the model reads the description at runtime. Answer quality on custom actions and questions is unmeasured. +**Parity / retrain / release.** No retrain is needed: the model reads the description at runtime. Answer quality on custom actions and questions is unmeasured, and no v2 model exists yet. -**Gotchas.** Custom actions are gated at their own tier (default heal, so guard mode never runs them). At budgets ≤ 1,400 characters (`COMPACT_QUESTIONS_BUDGET`), custom descriptions are sent as `null` unless a `vocabulary.actions` override of ≤ 24 characters exists, so the model sees only the name. Avoid question ids `action` and `diagnosis`. A non-iterable `plugins`, `actions` or `questions` throws inside the constructor after observers were installed (`GenClass.init` then returns an inert runtime). Custom actions can hold a subject indefinitely. Nothing acts until a model is loaded (see recipe 25 step 1). +**Gotchas.** Custom actions are gated at their own tier. At budgets ≤ 1,400 characters (`COMPACT_QUESTIONS_BUDGET`), custom descriptions are sent as `null` unless a `vocabulary.actions` override of ≤ 24 characters exists. Avoid question ids `action` and `diagnosis`. A non-iterable `plugins`, `actions` or `questions` throws inside the constructor (`GenClass.init` then returns an inert runtime). Custom actions can hold a subject indefinitely. **See.** [decide-policy-actions.md](runtime/decide-policy-actions.md), [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), [`docs/runtime/API.md`](../runtime/API.md) "Plugins". @@ -373,21 +411,21 @@ A change is done when all of these hold. Say explicitly in your final report whi **Goal.** Change the overlay (`@genclass/runtime/devtools`): add a tab, show a new `Decision` / `ActionRecord` field, change report wording, add a mount option, change styling. **Steps.** -1. **New tab:** `packages/runtime/src/devtools/index.ts` -> extend `DevtoolsTab` and `TABS` (keep `interventions` and `detections` first: the counters read `tabBtns[0]` and `tabBtns[1]`), add a pane in the constructor's `panes` record. If it polls the runtime, gate it like `renderNow` (open, tab selected, not paused, not dead) and refresh it from `startTicking`. Widen the `tab` union in `demos/src/dev/runtime-shim/devtools.ts`. -2. **New field on cards or evidence:** render it in `card()` or `evidence()` with `h()` and `text` (no `innerHTML`). Add the field to `makeDecision` / `makeAction` in `packages/runtime/test/browser/ui/mock-runtime.ts` and set it in `packages/runtime/test/browser/ui/scenario.ts`. -3. **Mount option:** `DevtoolsOptions` with a JSDoc default, read in the `Devtools` constructor; mirror it in `demos/src/dev/runtime-shim/devtools.ts`. -4. **Report wording:** runtime sentences come from `packages/runtime/src/decide/report.ts` -> `interventionLine`, `detectionLine`. Keep `packages/runtime/src/devtools/ui.ts` -> `splitReport` regexes able to strip the `[GenClass]` prefix, the `(diag, p; action p)` tail, `Not acted on (…): …` and the `(×N …)` suffix; keep `packages/runtime/src/devtools/ui.ts` -> `LEAD` / `NOUN` aligned where the same wording is intended. -5. **Activity kinds and filters:** `packages/runtime/src/devtools/ui.ts` -> `KIND_LABEL`, `OP_LABEL`, `eventText`, `groupOf`; `packages/runtime/src/devtools/index.ts` -> `FILTERS`; badge rules in `packages/runtime/src/devtools/css.ts`. -6. **Styling:** edit `packages/runtime/src/devtools/css.ts` only; add tokens to both `LIGHT` and `DARK`; never add selectors for `html`, `body` or `:root`. -7. **New runtime event:** `packages/runtime/src/types.ts` -> `RuntimeEvents` (CORE), then `packages/runtime/src/devtools/index.ts` -> `subscribe` through the local `on()` wrapper; update the unmount test's listener list. -8. **Cards recorded before mount** (`packages/runtime/UI-NEEDS.md` item 3): in `card()`, when the report sentence is missing, fall back to `this.rt.explain(id)?.message` inside `safe()`; then update the "reports emitted before mounting are not replayed" assertion in `devtools.test.ts`, the `.cx` body expectations in `devtools-runtime.test.ts`, and add `message` to the explanations built in `packages/runtime/test/browser/ui/scenario.ts`. -9. **Runtime-side report wording** changes (`packages/runtime/src/decide/report.ts`) also need `report.test.ts`, `atoms.test.ts` (late-revert line) and `review-misc.test.ts` updated. +1. **New tab:** `packages/runtime/src/devtools/index.ts` -> extend `DevtoolsTab` and `TABS` (keep `interventions` and `detections` first: the counters read `tabBtns[0]` and `tabBtns[1]`), add a pane in the constructor's `panes` record. If it polls the runtime, gate it like `renderNow` and refresh it from `startTicking`. Widen the `tab` union in `demos/src/dev/runtime-shim/devtools.ts`. +2. **Mode labels:** f3636b2 relabelled the mode control "Observe (default)" / "Guard (opt-in)" / "Heal (experimental)" in `packages/runtime/src/devtools/index.ts`; keep them in sync with the runtime default. +3. **New field on cards or evidence:** render it in `card()` or `evidence()` with `h()` and `text` (no `innerHTML`). Add the field to `makeDecision` / `makeAction` in `packages/runtime/test/browser/ui/mock-runtime.ts` and set it in `packages/runtime/test/browser/ui/scenario.ts`. +4. **Mount option:** `DevtoolsOptions` with a JSDoc default, read in the `Devtools` constructor; mirror it in `demos/src/dev/runtime-shim/devtools.ts`. +5. **Report wording:** runtime sentences come from `packages/runtime/src/decide/report.ts` -> `interventionLine`, `detectionLine`. Keep `packages/runtime/src/devtools/ui.ts` -> `splitReport` regexes able to strip the `[GenClass]` prefix, the `(diag, p; action p)` tail, `Not acted on (…): …` and the `(×N …)` suffix; keep `ui.ts` -> `LEAD` / `NOUN` aligned (including the `delivery` noun). +6. **Activity kinds and filters:** `packages/runtime/src/devtools/ui.ts` -> `KIND_LABEL`, `OP_LABEL`, `eventText`, `groupOf`; `packages/runtime/src/devtools/index.ts` -> `FILTERS`; badge rules in `packages/runtime/src/devtools/css.ts`. +7. **Styling:** edit `packages/runtime/src/devtools/css.ts` only; add tokens to both `LIGHT` and `DARK`; never add selectors for `html`, `body` or `:root`. +8. **New runtime event:** `packages/runtime/src/types.ts` -> `RuntimeEvents` (CORE), then `packages/runtime/src/devtools/index.ts` -> `subscribe` through the local `on()` wrapper. +9. **Cards recorded before mount** (`packages/runtime/UI-NEEDS.md` item 3): fall back to `this.rt.explain(id)?.message` inside `safe()`; update the matching assertions in `devtools.test.ts` and `devtools-runtime.test.ts`. -**Tests.** `packages/runtime/test/`: `devtools.test.ts` (against `MockRuntime` + `loadScenario`) and `devtools-runtime.test.ts` (real runtime via `runStoreSession`); `dom.test.ts` if you touch the ignore attribute; the `adapters-*.test.ts` files if you touch `mock-runtime.ts`. **[ask first]** `npx playwright test --config test/browser/ui/playwright.config.ts` from `packages/runtime` regenerates the 18 PNGs in `test/browser/ui/screenshots/` (written, never compared); review and commit them only if intended. +**Tests.** `packages/runtime/test/`: `devtools.test.ts` (against `MockRuntime` + `loadScenario`) and `devtools-runtime.test.ts` (real runtime via `runStoreSession`, which passes an explicit `mode: "guard"`). **[ask first]** `npx playwright test --config test/browser/ui/playwright.config.ts` from `packages/runtime` regenerates the PNGs in `test/browser/ui/screenshots/` (written, never compared); commit them only if intended. -**Parity / retrain / release.** Class E, unless the field comes from a CORE change that alters situations. Bundle size matters (devtools ~68 KB unminified in the local build). +**Parity / retrain / release.** Class E, unless the field comes from a CORE change that alters situations. -**Gotchas.** The overlay uses only the public `Runtime` API; it must not import runtime internals. Tests are not type-checked, so `MockRuntime` drifts silently. `npm run test:browser` also runs the UI spec with different viewport settings and overwrites the screenshots: use the UI config. +**Gotchas.** The overlay uses only the public `Runtime` API. Tests are not type-checked, so `MockRuntime` drifts silently. `npm run test:browser` also runs the UI spec with different viewport settings and overwrites the screenshots: use the UI config. **See.** [devtools.md](runtime/devtools.md#how-to-change-it-safely). @@ -399,39 +437,39 @@ A change is done when all of these hold. Say explicitly in your final report whi **Steps.** 1. **Host option:** `packages/runtime/src/model/host.ts` -> `ModelHostOptions`; if it must reach the worker, also `packages/runtime/src/model/backend.ts` -> `BackendLoadOptions` (structured-cloneable values only) and the `Host` constructor's `loadOptions`; if apps set it through `GenClass.init`, also `packages/runtime/src/types.ts` -> `ModelOptions` and API.md. -2. **Plan order or device semantics:** `packages/runtime/src/model/loader.ts` -> `planOrder` (the ORT build choice follows). Keep `wasm` as the last plan for `"webgpu"`. +2. **Plan order or device semantics:** `packages/runtime/src/model/loader.ts` -> `planOrder`. Keep `wasm` as the last plan for `"webgpu"`. The device also sets the auto situation budget (`RuntimeImpl.situationBudget`). 3. **Worker protocol message:** `packages/runtime/src/model/protocol.ts`, the switch in `packages/runtime/src/model/worker.ts`, `packages/runtime/src/model/host.ts` -> `InlineTransport` (keep both transports identical) and the host's message handler. Every request gets exactly one `result`. -4. **Model error:** `packages/runtime/src/model/errors.ts` -> `ModelErrorCode`, the class, the `deserializeError` switch (otherwise it crosses the worker boundary as a plain `Error`); re-export from `packages/runtime/src/index.ts` and `packages/runtime/src/model/index.ts`. Special runtime handling: see the `max_tokens_exceeded` handler in the `RuntimeImpl` constructor. -5. **New graph input or head:** `packages/runtime/src/model/engine.ts` -> `FEEDS`, `OUTPUT_KIND`; `packages/runtime/src/model/packer.ts` -> `planInputs`, `unpackLogits`; `packages/runtime/src/model/serialize.ts` -> `BlockKind`, `questionBlock`; `packages/runtime/src/model/calibrate.ts` -> `calibrateLogits`, `buildAnswer`; the `Question` / `Answer` types in `packages/runtime/src/types.ts` (the CORE/MODEL seam, mirrored by `sim/src/types.ts`). This is also a training change (recipe 13). -6. **onnxruntime-web upgrade:** `packages/runtime/package.json` (`^1.30.0`), `packages/runtime/src/model/backend.ts` -> `ORT_FALLBACK_VERSION`, check `ORT_WASM_FILES` names exist in the new `dist/`, keep the externals, update the browser-test regex expecting `onnxruntime-web@1.30.x` and the pinned `onnxruntime-node` devDependency. -7. **CLI:** `packages/runtime/bin/genclass-runtime.mjs` (`fetch-model`, `info`); keep its `parseCard` in sync with `packages/runtime/src/model/loader.ts` -> `parseCard`. There are no automated CLI tests. -8. **Default model URL:** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` (recipe 20). Shipping a different architecture (R17 vs R32, a new export) needs no code change when the export follows the card format and `meta.json` declares `inputs`, `outputs`, `markers`, `cls_id`, `sep_id`, `max_len`, `max_total`; device-based model selection (OPEN_TASKS item 5) is not implemented and would need card support plus a `planOrder` change. -9. **Self-hosting (app integration):** `npx genclass-runtime fetch-model public/genclass-model --from <dir URL with model.json>` **[ask first]** (download); copy both `ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` from `node_modules/onnxruntime-web/dist/`; `GenClass.init({ model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`; serve COOP/COEP for WASM threads. +4. **Model error:** `packages/runtime/src/model/errors.ts` -> `ModelErrorCode`, the class, the `deserializeError` switch; re-export from `packages/runtime/src/index.ts` and `packages/runtime/src/model/index.ts`. Special runtime handling: the `max_tokens_exceeded` handler in the `RuntimeImpl` constructor (shrinks `budgetScale`). +5. **New graph input or head:** `packages/runtime/src/model/engine.ts` -> `FEEDS`, `OUTPUT_KIND`; `packages/runtime/src/model/packer.ts` -> `planInputs`, `unpackLogits`; `packages/runtime/src/model/serialize.ts` -> `BlockKind`, `questionBlock`; `packages/runtime/src/model/calibrate.ts`; the `Question` / `Answer` types in `packages/runtime/src/types.ts`. This is also a training change (recipe 13). +6. **onnxruntime-web upgrade:** `packages/runtime/package.json` (`^1.30.0`; update the lockfile), `packages/runtime/src/model/backend.ts` -> `ORT_FALLBACK_VERSION`, check `ORT_WASM_FILES` names exist in the new `dist/`, keep the externals, update the browser-test regex expecting `onnxruntime-web@1.30.x` and the pinned `onnxruntime-node` devDependency (CI skips its binary download with `ONNXRUNTIME_NODE_INSTALL=skip`). +7. **CLI:** `packages/runtime/bin/genclass-runtime.mjs` (`fetch-model`, `info`; committed as 100755); keep its `parseCard` in sync with `packages/runtime/src/model/loader.ts` -> `parseCard`. No automated CLI tests. +8. **Default model URL:** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` (recipe 20). Both 404 today. +9. **Self-hosting (app integration):** `npx genclass-runtime fetch-model public/genclass-model --from <dir URL with model.json>` **[ask first]** (download); copy both `ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` from `node_modules/onnxruntime-web/dist/`; `GenClass.init({ mode: "guard", model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`; serve COOP/COEP for WASM threads. There is no situation-v2 model to self-host yet: the round-1 R17 export reads v1 text and must not be loaded into this runtime. -**Tests.** Local, no model files needed: `packages/runtime/test/model/`: `host.test.ts` (fake worker: queue, timeouts, crash, WASM retry, inline fallback, errors across the boundary), `loader.test.ts` (card parsing, `planOrder` matrix, cache and sha256), `engine.test.ts` graph-contract test. **[ask first]** `npm run test:browser` (needs a model directory and Playwright Chromium; rebuilds `dist/`). +**Tests.** Local, no model files needed: `packages/runtime/test/model/`: `host.test.ts`, `loader.test.ts`, the `engine.test.ts` graph-contract test. **[ask first]** `npm run test:browser` (needs a model directory and Playwright Chromium; rebuilds `dist/`). **Parity / retrain / release.** Loading and transport changes are class E. Graph inputs and heads require a new export and retraining. -**Gotchas.** `evaluate()` never waits: before `ready` it rejects at once with `ModelNotReadyError`, and while the host is `loading` or `error` the runtime builds no situations. Keep `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` and the two `import("onnxruntime-web/webgpu")` / `import("onnxruntime-web/wasm")` literals verbatim: bundlers split on them and `packages/runtime/test/browser/build.mjs` fails without them. `packages/runtime/src/model/worker.ts` must stay inert in ORT's own worker threads (`em-pthread`, `ort-wasm-proxy-worker`). Downloads use the native fetch (`NATIVE_FETCH` or the worker realm), never the instrumented one. One inference at a time; a hung forward pass blocks the host (no watchdog). The WASM retry happens once per host lifetime. +**Gotchas.** `evaluate()` never waits: before `ready` it rejects at once with `ModelNotReadyError`, and while the host is `loading` or `error` the runtime builds no situations. Keep `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` and the two `import("onnxruntime-web/webgpu")` / `import("onnxruntime-web/wasm")` literals verbatim. Downloads use the native fetch, never the instrumented one. One inference at a time; no watchdog. **See.** [model-host.md](runtime/model-host.md#how-to-change-it-safely). ### 13. Change the packer, tokenizer, serializer or calibration -**Goal.** Change how a situation becomes token ids or how logits become calibrated answers. These TypeScript files are byte-exact ports of Python in `jev_local/`. +**Goal.** Change how a situation becomes token ids or how logits become calibrated answers. These TypeScript files are byte-exact ports of Python in `jev_local/`, unchanged since `situation-v1`. **Steps.** 1. Get the user's go-ahead (class C or D; class C requires retraining when the Python side changes). 2. Change both sides in the same change: `packages/runtime/src/model/{serialize,pyutil,tokenizer,packer}.ts` with `jev_local/serialize.py` and `jev_local/engine/encoder/tokenize_pack.py`; `packages/runtime/src/model/calibrate.ts` with `jev_local/engine/encoder/calibrate.py` and `jev_local/confidence.py`. -3. Keep v1 calibration files loadable; keep the documented Jev answer rows within ±0.01 (`jev_local/confidence.py`; tested by `tests/test_confidence.py`). +3. Keep v1 calibration files loadable; keep the documented Jev answer rows within ±0.01. 4. Regenerate the fixtures (recipe 14) and, for a token-id change, re-export a model so the export's own fixtures and `parity.json` reflect the new layout. -5. Recalibration only (no code change): `$PY training/eval_runtime.py --ckpt … --data … --fit-split dev --write-calibration cal.json`, then `$PY training/export_runtime.py … --calibration cal.json` **[ask first]** (recipe 18). +5. Recalibration only: `$PY training/eval_runtime.py --ckpt … --data … --fit-split dev --write-calibration cal.json`, then `$PY training/export_runtime.py … --calibration cal.json` **[ask first]** (recipe 18). -**Tests.** Local (fixtures committed): `packages/runtime/test/model/`: `serialize.test.ts`, `calibrate.test.ts` (7 of 8 run without model files), `packer.test.ts` and `engine.test.ts` parity need a model directory **[ask first]**. Python: `tests/test_encoder_pack.py`, `test_encoder_model.py`, `test_encoder_engine.py`, `test_serialize_w8.py`, `test_confidence.py`, `test_train_v2_engine.py` **[ask first]** (Python environment with torch). +**Tests.** Local (fixtures committed): `packages/runtime/test/model/` `serialize.test.ts`, `calibrate.test.ts` (7 of 8 run without model files); `packer.test.ts` and `engine.test.ts` parity need a model directory **[ask first]**. Python: `tests/test_encoder_pack.py`, `test_encoder_model.py`, `test_encoder_engine.py`, `test_serialize_w8.py`, `test_confidence.py`, `test_train_v2_engine.py` **[ask first]**. -**Parity / retrain / release.** Token-id changes invalidate trained weights: retrain and re-export (recipe 18), new freeze. Calibration changes alter intervention rates: re-run `training/eval_runtime.py` and compare FIR/precision before shipping. +**Parity / retrain / release.** Token-id changes invalidate trained weights: retrain and re-export, new freeze. Calibration changes alter intervention rates: re-run `training/eval_runtime.py` and compare FIR/precision before shipping. -**Gotchas.** JavaScript cannot print `25.0`; Python-generated rows must write integral floats as ints. Nothing about the vocabulary is hardcoded: marker, CLS and SEP ids come from `meta.json` / `tokenizer.json`; keep it that way. The runtime bounds state + longest branch (`meta.max_len`), the trainer bounds the whole question block: length semantics differ. The extension's JS copies (`extension/src/model/`) are the ancestors; the runtime TS copy is the maintained one. +**Gotchas.** JavaScript cannot print `25.0`; Python-generated rows must write integral floats as ints. Marker, CLS and SEP ids come from `meta.json` / `tokenizer.json`; keep it that way. The runtime bounds state + longest branch (`meta.max_len`), the trainer bounds the whole question block. **See.** [model-host.md](runtime/model-host.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#invariants-and-gotchas), [genclass-model-lineage.md](genclass-model-lineage.md#how-to-change-it-safely). @@ -440,108 +478,108 @@ A change is done when all of these hold. Say explicitly in your final report whi **Goal.** Refresh the Python-generated fixtures that pin the TypeScript model code to the Python reference. **Steps.** -1. **`py_fixtures.json`** (serialize, pruned tokenizer, calibration and confidence cases) **[ask first]**: needs the jev venv (`tokenizers`, `numpy`, `pydantic`) and the v0.1 tokenizer: - `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_py_fixtures.py --tokenizer <model dir>/tokenizer.json --out packages/runtime/test/fixtures/model/py_fixtures.json`. It also reads `<model dir>/calibration.json` when present. The script imports `jev_local` from the repo root (`ROOT = parents[5]`), so do not move it. -2. **`pack_fixtures.json` / `torch_fixtures.json`** are outputs of either v1 exporter, `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (both export the extension's v1 model, import torch and say "RUN ON THE AZURE VM ONLY"; their fixture-writing code in `main` is identical and does not depend on the int8 vs q8 ONNX export; which one produced the committed files is not recorded) **[ask first]**, copied from `extension/test/fixtures/` and re-serialised compactly (no whitespace). Never hand-edit them. Regenerate `requests50.json` from the same request set. -3. **An export's own fixtures:** `training/export_runtime.py` writes `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` and `parity.json` into the model directory; `packages/runtime/test/model/helpers.ts` uses them automatically when all three exist (`FIXTURES_FROM_MODEL`). -4. **WebGPU embedding variants** (outside the repo, used via `GENCLASS_WEBGPU_VARIANTS`) **[ask first]**: `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_webgpu_variants.py --src <runtime-card model dir with a q8 variant> --out <dir>` (needs `onnx`, `numpy`); writes `f32emb/` and `i8emb/`. +1. **`py_fixtures.json`** **[ask first]**: needs the jev venv (`tokenizers`, `numpy`, `pydantic`) and the v0.1 tokenizer: `~/jev/.venv/bin/python packages/runtime/test/fixtures/model/make_py_fixtures.py --tokenizer <model dir>/tokenizer.json --out packages/runtime/test/fixtures/model/py_fixtures.json`. It imports `jev_local` from the repo root; do not move it. +2. **`pack_fixtures.json` / `torch_fixtures.json`** are outputs of a v1 exporter (`scripts/genclass_export.py` or `extension/tools/genclass_export.py`) **[ask first]**, re-serialised compactly. Never hand-edit them. Regenerate `requests50.json` from the same request set. +3. **An export's own fixtures:** `training/export_runtime.py` writes `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` and `parity.json` into the model directory; `packages/runtime/test/model/helpers.ts` uses them automatically when all three exist (`FIXTURES_FROM_MODEL`). This is how a v2 export will be checked. +4. **WebGPU embedding variants** **[ask first]**: `make_webgpu_variants.py --src <q8 model dir> --out <dir>`. -**Tests.** `packages/runtime/test/model/` `serialize.test.ts`, `calibrate.test.ts`, `packer.test.ts`, `engine.test.ts` with `GENCLASS_MODEL_DIR` **[ask first]**. +**Tests.** `packages/runtime/test/model/` with `GENCLASS_MODEL_DIR` **[ask first]**. **Parity / retrain / release.** Fixtures only document parity; regenerating them never fixes a parity break. -**Gotchas.** The committed fixture JSON files are single-line (`wc -l` prints 0); compare parsed JSON, not hashes. The browser specs always read the v0.1 fixtures (`test/browser/model-helpers.ts`), so their parity assertions only hold for the v0.1 model. `pythonOnlyFloatRequests` needs Node ≥ 21. +**Gotchas.** The committed fixture JSON files are single-line; compare parsed JSON, not hashes. The browser specs always read the v0.1 fixtures, so their parity assertions only hold for the v0.1 model. `pythonOnlyFloatRequests` needs Node ≥ 21. **See.** [build-test-release.md](runtime/build-test-release.md#regenerate-model-fixtures). ## Recipes: sim -All sim runs are **[ask first]**. Before any sim change, read the matching test in `sim/test/`. Check-out sequence after the change: `npm run build` (runtime) then, in `sim/`, `npx tsup`, `SIM_RUNTIME=real npx vitest run`, `node dist/smoke.js --seeds 40` (check `internal errors` and correlation `*:none` counts), a small `gen.js` run and `python3 scripts/analyze.py <out>`. +Sim typecheck and `SIM_RUNTIME=real npx vitest run` are light local checks (build the runtime first). Everything that generates data is **[ask first]**, and cluster runs are operated by the colleague. Check-out sequence after a sim change: `npm run build -w @genclass/runtime`, then in `sim/`: `npx tsc -p tsconfig.json --noEmit`, `SIM_RUNTIME=real npx vitest run`, `npx tsup`; then **[ask first]** `node dist/smoke.js --seeds 40` (check `internal errors` and correlation `*:none` counts), a small `gen.js` run and `python3 scripts/analyze.py <out>`. ### 15. Add a sim feature module **Goal.** Add a feature combinator (a new kind of app behaviour with guards or injected defects), a domain, or a knob on an existing feature. **Steps.** -1. New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef` (`sim/src/app/feature.ts`); register it in `sim/src/app/features/index.ts` -> `FEATURES` and `FEATURE_WEIGHTS`. -2. Server routes via `srv.route(method, naming.route(...), handler, { feature, kind, idempotent, resource })`. Client state via `env.store(name, s.id, init, { weights, resync })`. Requests only via `Kit.op` + `Kit.call`; writes only via `Kit.write` with `role`, `intent`, `key`, `op` (`sim/src/app/kit.ts`). -3. Ground truth: set `dupOf` for accidental repeats, `anomaly: "partial"` on writes that skip derived fields, `classify` where `ContentBook` decides stale/conflict/duplicate; declare `relations()` for derived fields; surface failures with `kit.shownError()` or `kit.spawn(fn, "uncaught", …)`. -4. New data roles go into `sim/src/oracle/diagnose.ts` -> `DATA_ROLES`. Consider a held-out pattern in `sim/src/world/scenario.ts` -> `TEST_PATTERNS`. -5. Randomness only from the spec rng in `make`, `user.rng` in `session`, and keyed `env.rng.fork(<key>)` at run time. For a knob on an existing feature, append the draw at the end of `make()` (inserting one shifts every later knob). -6. Domain: append `D(...)` with two entities in `sim/src/app/vocab.ts` -> `DOMAINS`; optionally hold it out in `TEST_DOMAINS`. +1. New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef` (`sim/src/app/feature.ts`); register it in `sim/src/app/features/index.ts` -> `FEATURES` and `FEATURE_WEIGHTS` (46 features at b435acb). +2. Server routes via `srv.route(...)`. Client state via `env.store(...)`. Requests only via `kit.op` + `kit.call` (an `anomaly` on the op reaches the oracle); writes only via `kit.write` with `role`, `intent`, `key`, `op` (`sim/src/app/kit.ts`). Use `env.clientNow()`, `env.online`, `env.on(...)`, `env.channel(...)`, `env.busy(ms)` and `world.otherTab` instead of globals; declare `env()` for offline windows, socket drops and skew; honour `ctx.clean`. +3. Ground truth: `dupOf` for accidental repeats, `anomaly: "partial"` on writes that skip derived fields, `classify` where bookkeeping decides stale/conflict/duplicate; `relations()`; surface failures with `kit.shownError()` or `kit.spawn(fn, "uncaught", …)`. +4. New data roles go into `sim/src/oracle/diagnose.ts` -> `DATA_ROLES`. Consider `TEST_PATTERNS` or `TEST_FEATURES` in `sim/src/world/scenario.ts`. +5. Randomness only from the spec rng in `make`, `user.rng` in `session`, and keyed `env.rng.fork(<key>)` at run time. For a knob on an existing feature, append the draw at the end of `make()`. +6. Domain: append to `sim/src/app/vocab2.ts` (keep `vocab.ts` stable); optionally hold it out in `TEST_DOMAINS`. -**Tests.** `sim/test/oracle.test.ts` cases via `mini(kind, patch, opts)` from `sim/test/helpers.ts` (expected diagnosis, cheapest action); `rows.test.ts`, `determinism.test.ts` with `SIM_RUNTIME=real` **[ask first]**. +**Tests.** `sim/test/oracle.test.ts` cases via `mini(kind, patch, opts)` from `sim/test/helpers.ts`; `rows.test.ts`, `determinism.test.ts`, `latent.test.ts` with `SIM_RUNTIME=real` (local). Check `smoke.js --profile` cost **[ask first]**. **Parity / retrain / release.** Every seed's world changes (keyed picks depend on array lengths): regenerate all data and `sim/samples/*`; never mix rows from different sim versions under one seed range. -**Gotchas.** An `anomaly` passed to `Kit.op` is silently dropped (`OpInit` has no such field); the poll feature's `storm` anomaly never reaches the oracle for this reason. Error-message fields must have weight 0. The ideal run has no runtime and skips accidental steps, so `dupOf` / `accidental` must be right. +**Gotchas.** Error-message fields must have weight 0. The ideal run has no runtime and skips accidental steps, so `dupOf` / `accidental` must be right. **See.** [sim.md](sim.md#how-to-change-it-safely). ### 16. Change sim oracle, labelling, ask questions or splits -**Goal.** Change how rows are labelled (cost weights, label parameters, diagnosis rules), add an `ask` question generator, change chaos, budgets or splits. +**Goal.** Change how rows are labelled (cost weights, label parameters, diagnosis rules, S1, S2), add an `ask` question generator, change chaos, budgets or splits. **Steps.** -1. **Cost weights:** `sim/src/oracle/cost.ts` -> `W`; update `sim/test/oracle.test.ts` and the README formula; regenerate data. -2. **Label parameters only:** `sim/src/oracle/cost.ts` -> `LABEL` (premiums, tie rule, tau). These can be re-derived offline from `meta.cost_futures` with `actionLabel`, without re-simulating; re-apply option drops recorded in `meta.transform` (`drop:<action>`). -3. **Diagnosis rules:** `sim/src/oracle/diagnose.ts` -> `diagnose`, `diagnoseFailure`, or a feature's `classify`. Diagnosis also changes exploration, point sampling and `fake_diagnosis`, so action rows change too. -4. **Ask questions:** a generator in `sim/src/ask/questions.ts` -> `GENS` returning `{ qid, question, label, kind }`; check the evidence appears in the serialised state and skip borderline timings. -5. **Chaos and network:** `sim/src/world/scenario.ts` -> `makeNet` (parameters), `sim/src/net/network.ts` -> `Network` (mechanics). Keep every draw keyed and ideal-mode draw counts stable; keep `NetEntry.cause` / `slowCause` accurate (diagnoses read them). -6. **Budgets:** `buildScenario` budget weights; coordinate with per-budget eval in `training/eval_runtime.py` and the runtime's auto budgets. -7. **Splits:** `sim/src/world/scenario.ts` -> `TEST_DOMAINS`, `TEST_PATTERNS`, `familyHeldOut`, `splitOf` (and their salts). Moves whole trajectories between splits; old datasets become incomparable. -8. **Runtime contract** (option names, thresholds, hooks): `sim/src/run/rt.ts` -> `createOptions`, `RuntimeLike`, and `sim/src/types.ts`. +1. **Cost weights:** `sim/src/oracle/cost.ts` -> `W`; update `sim/test/oracle.test.ts` and the README formula; regenerate data. realapps imports `W` and the label rule, so its labels change too: tell REAL. +2. **Label parameters only:** `sim/src/oracle/cost.ts` -> `LABEL`; re-derivable offline from `meta.cost_futures` with `sim/scripts/relabel.py` (re-apply `drop:<action>` transforms) or `training/t1_relabel.py`. +3. **Diagnosis or S1 rules:** `sim/src/oracle/diagnose.ts` -> `diagnose`, `diagnoseFailure`; `sim/src/gen/trajectory.ts` -> `diagnosisFromOutcome`, `S1_GAP`; or a feature's `classify`. Affects exploration, point sampling and `fake_diagnosis`. Update the S1 assertion in `rows.test.ts`. Unlabeled rows (`unlabeledTrajectory`) hard-label `expected` diagnoses that S1 would relabel on gold rows (open finding): fix it here or drop those labels at import (recipe 30). +4. **S2 latent re-draws:** `sim/src/run/latent.ts` (`futureProfile`, `futureStepTimes`, `idealRepeatSkips`, `REPEAT_PRIOR`). Keep every draw keyed and ideal-mode draw counts stable; run `latent.test.ts` and `determinism.test.ts`. +5. **Ask questions:** a generator in `sim/src/ask/questions.ts` -> `GENS`; check the evidence appears in the serialised state and skip borderline timings. realapps reuses these generators. +6. **Chaos and network:** `sim/src/world/scenario.ts` -> `makeNet`, `sim/src/net/network.ts` -> `Network`; keep `NetEntry.cause` accurate. +7. **Budgets:** `buildScenario` budget weights (still `[[3200, 40], [2000, 30], [1000, 30]]`, the v1 device budgets; production auto budgets are 2,400 / 2,000…1,000 and `rt.py` `BUDGETS` uses them). Changing them is class B (recipe 6); keep realapps' copy in `realapps/src/harness/scenario.ts` in step. +8. **Splits:** `TEST_DOMAINS`, `TEST_PATTERNS`, `TEST_FEATURES`, `familyHeldOut`, `splitOf` and their salts. Old datasets become incomparable. +9. **Runtime contract** (option names, thresholds, hooks): `sim/src/run/rt.ts` -> `createOptions`, `RuntimeLike`, and `sim/src/types.ts`. -**Tests.** `sim/test/oracle.test.ts` (expected diagnoses and cheapest actions; 2 cases run only with `SIM_RUNTIME=real`), `rows.test.ts` (labels reference offered options, dists sum to 1, split counts over 400 seeds), `determinism.test.ts` **[ask first]**. +**Tests.** `sim/test/oracle.test.ts`, `rows.test.ts`, `latent.test.ts`, `determinism.test.ts`, `loop.test.ts` with `SIM_RUNTIME=real` (local). -**Parity / retrain / release.** Labels and targets change: regenerate data and retrain. Gate thresholds in `createOptions` must stay 0.5 with `requireDiagnosis: false`. +**Parity / retrain / release.** Labels and targets change: regenerate data and retrain. Gate thresholds in `createOptions` stay 0.5 with `requireDiagnosis: false`. -**Gotchas.** `x-request-id` is the sim's correlation header; it must stay in the runtime's volatile header list and never appear in a state (`rows.test.ts` asserts it). Correlation is synchronous: the runtime's `opCreated` / `mutationProposed` hooks must fire inside the sim's calls. +**Gotchas.** `x-request-id` must stay volatile in the runtime and never appear in a state. Correlation is synchronous: the runtime's `opCreated` / `mutationProposed` hooks must fire inside the sim's calls. `delivery` diagnoses are the verdict of the first write the delivered op/message makes. **See.** [sim.md](sim.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md). -### 17. Generate a data set +### 17. Generate a SIM data set -**Goal.** Produce CONTRACT-D rows (`{ id, split, family, state, questions, labels, meta }`) from the sim. **[ask first]** for every step: generation is CPU-heavy and the original team ran it only on the VM. +**Goal.** Produce CONTRACT-D rows (`{ id, split, family, state, questions, labels, meta }`) from the sim: gold (counterfactual labels), unlabeled (base runs; teacher labels later) or on-policy (DAgger). **[ask first]** for every step; large runs are Azure work operated by the colleague. **Steps.** -1. Build the runtime first (`npm run build` at the repo root; `sim` resolves `@genclass/runtime` through `packages/runtime/dist/`), then the sim: `cd sim && npx tsup`. +1. Build the runtime from the frozen tag, then the sim: `npm run build -w @genclass/runtime`, `cd sim && npx tsup`. A stale `dist/` silently produces old text. 2. Samples: `node dist/gen.js --sample --workers 8` writes `sim/samples/sample.jsonl`, `EXAMPLES.md` and `sample-stats.json`. -3. A custom run: `node dist/gen.js --rows <N> --out <dir> --seed <S> --workers <W>` (other flags: `--max-points`, `--test-keep`, `--explore`, `--no-ask`, `--parts`, `--chunk`, `--merge-only`; `--allow-fake` only for tests). Output: `<dir>/{train,dev,test}.jsonl` + `stats.json`. -4. Final datasets: `bash sim/scripts/final.sh a` (600k rows, seeds from 10,000,000, `sim/out/final-a`), `final.sh b` (1.4M rows, seeds from 50,000,000, resumable parts of 100 seeds), `final.sh merge-b`. Splitting across machines needs disjoint seed ranges. -5. Summarise: `python3 sim/scripts/analyze.py <dir>` (prefers merged files over `parts/`). +3. A local run: `node dist/gen.js --rows <N> --out <dir> --seed <S> --workers <W> [--unlabeled | --on-policy <export dir>]` (other flags: `--max-points`, `--test-keep`, `--explore`, `--no-ask`, `--parts`, `--chunk`, `--merge-only`; `--allow-fake` only for tests). Output: `<dir>/{train,dev,test}.jsonl` + `stats.json`. +4. Cluster runs (v2; [sim.md](sim.md#9-cluster-runs-simscriptscluster)): `sim/scripts/cluster/bundle.sh` on the train VM, then from the colleague's Mac `bigrun.sh gold RUN ROWS NODES…` (seed base 11e9) and `bigrun.sh unl RUN ROWS NODES…` (16e9), or `orchestrate.sh run RUN onpolicy:<model dir on the node> ROWS nodes…` with `SEED_BASE=22000000000`; each node `cNN` gets base + NN × 1e8. Collect with `python3 sim/scripts/cluster/collect.py RUN OUTDIR HOST…` (dedupe, test-first, gz shards ≤ 500k rows + `manifest.json`). Deallocate each node when its share is collected. +5. Summarise: `python3 sim/scripts/analyze.py <dir>`. Record location, rows per split, row type, runtime tag and held-out lists in `training/NEEDS.md` (item 11). +6. v1 history only: `sim/scripts/final.sh a|b|merge-b` built phase A/B on `situation-v1`; do not reuse it for v2. -**Tests.** Check `stats.json`: drops (phase A only had `diagnosis-not-in-vocab`), 0 errors, `subject_correlated` 100%, passive-best shares per trigger. +**Tests.** `stats.json`: drops (expect `info:latent-fallback` and a few `diagnosis-not-in-vocab`), 0 internal errors, `subject_correlated` 100%, passive-best shares per trigger comparable with the previous batch. -**Parity / retrain / release.** Data generated from a runtime whose situation code differs from the model's training data is not comparable; record the runtime commit with the data. +**Parity / retrain / release.** Data from a runtime whose situation code differs from the model's training data is not comparable. SIM rows do not carry the runtime tag (`meta.runtime` is `"real"`): keep tag-specific run names and seed bases. -**Gotchas.** `gen.js` uses the real runtime unless `--allow-fake`. A stale `dist/` from an older build silently produces old text: rebuild first. `sim`'s `build:runtime-core` writes only `dist/index.js` (+ chunks; no `.d.ts`, adapters, devtools or worker) and does not clean, so on an empty `dist/` it leaves the demos resolving files that do not exist; prefer the full build. +**Gotchas.** `gen.js` deletes `<out>/shards` at start in every mode. `sim`'s `build:runtime-core` writes only `dist/index.js` and does not clean; prefer the full runtime build. On-policy runs pin `mode: "heal"` (`createOptions`), not the shipped `observe` or the target `guard` (open finding). The trainer's stream reader reads `*.jsonl` and `*.jsonl.zst`, not the collected `.jsonl.gz` shards (recipe 30). **See.** [sim.md](sim.md#how-to-change-it-safely), [training.md](training.md). ## Recipes: training -### 18. Train, evaluate and export a model +### 18. Train, evaluate and export a model (mechanics) -**Goal.** Produce a model directory the runtime can load (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`, parity fixtures). Everything here runs on Azure VMs and costs money: **[ask first]** for every step. +**Goal.** The generic mechanics behind recipe 30: produce a model directory the runtime can load (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`, parity fixtures). Everything here runs on Azure VMs and costs money: **[ask first]** for every step. **Steps.** -1. Read `training/LOG.md`, `training/EVAL.md`, `training/NEEDS.md`. Note the script layout assumption: `training/*.sh` resolve `JEV="$HERE/../.."` and expect `jev_local/`, `scripts/` and `pyproject.toml` there, while in this monorepo they are one level up. -2. **Curriculum** (if needed; `$PY` is `~/jev/.venv/bin/python` as set by `training/node.sh`, see [training.md](training.md#configuration-and-constants)): `$PY training/curriculum/generate.py --out <dir> --n <N> --seed <new seed> --workers <W> --p-runtime 0.8`; shard train into a stream bucket (`split -n l/64 …` into `<stream root>/<bucket>/`). Use a new seed and bucket name; check `stats.json` (`bad` and `errors` 0, sane `passive_best_fraction`). -3. **Import SIM data:** `training/import_final.sh SIM_OUT_DIR NAME`. -4. **Mixture and launch:** copy a `training/configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly) and `training/launch_final1.sh` with a new run name, `--stream-cache`, `--out`, `--seed`. Rank 0 must be the node holding `--init-from`. Check `mixture_plan.json`: missing buckets are dropped silently. -5. **Evaluate and calibrate:** `$PY training/eval_runtime.py --ckpt models/M --data <set> --split test --fit-split dev --records-dir out/records --out out/eval/M-<set>.json --write-calibration out/cal/M.json`; SIM eval with `bash training/eval_sim.sh <NAME> M`; tables with `$PY training/report.py M=<json> --mode=kind`. Delete `out/records/M__*` first if `models/M` was retrained. -6. **Export:** `$PY training/export_runtime.py --ckpt models/M --out out/export-M --name genclass-runtime-<size> --version X.Y.Z --calibration <cal.json> --data-rows <jsonl list>`. Without `--calibration` the export ships all-1.0 temperatures. `final_post.sh MODEL NAME VERSION` automates eval, export and serving on a rank-0 node. -7. **Validate:** `node validate.mjs <export dir> q8 120`, run in a directory where `training/ortweb/package.json` is installed (onnxruntime-node and onnxruntime-web WASM vs the PyTorch fixtures); check `parity.json` (q8 argmax agreement, `embedding_q8.fp16_free: true`, q8 size ≤ 25 MB per CONTRACT §10). -8. **Runtime parity:** `cd packages/runtime && GENCLASS_MODEL_DIR=<export dir> npx vitest run test/model` (uses the export's own fixtures), then the browser specs (their parity assertions compare against the committed v0.1 fixtures, so they only hold for the v0.1 model; load, fallback and latency checks still apply to a new export). -9. **New curriculum scenario case:** add it to the builder's `rng.choices` list in `training/curriculum/scenarios.py`, `scen_ops.py` or `scen_state.py`; build the `Trace`, facts via `fmt.pick` templates (≥ 4 phrasings so one is held out), labels leaning passive when ambiguous, primitives (`training/curriculum/prims.py`) and a `spec` that `rt.py` can render (or `no_runtime: True`). Keep the passive-best share within 0.45–0.75 (`test_curriculum.py` asserts it). -10. Variants: change `max_len` with `--max-len N` at training (the export copies it into `meta.json`); change the vocabulary with `training/prune_vocab.py` (prune both bases, rerun `test_prune_vocab.py`, retrain; marker ids move). +1. Read `training/LOG.md`, `training/EVAL.md`, `training/NEEDS.md`, `training/PLAN-v1.md`. Script layout: `training/*.sh` resolve `JEV="$HERE/../.."` and expect `jev_local/`, `scripts/` and `pyproject.toml` there; in this monorepo they are one level up ([training.md](training.md#invariants-and-gotchas)). +2. Sync code: `training/node.sh HOST sync`. `$PY` is `~/jev/.venv/bin/python` on the nodes; `G=/home/azureuser/gcl-train`. +3. **Curriculum** (if needed): `$PY training/curriculum/generate.py --out <dir> --n <N> --seed <new seed> --workers <W> --p-runtime 0.8`; shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl <root>/<bucket>/shard`); check `stats.json` (`bad`, `errors` 0, sane `passive_best_fraction`). +4. **Mixture and launch:** copy a `training/configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly), then `training/launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra]` (ARCH `r17` / `r32` / `r68` / `t150`; 8 ranks × 10 threads per F80; rank 0 and master = the first node, which must hold `INIT`). Check `mixture_plan.json`: missing buckets are dropped silently. +5. **Evaluate and calibrate:** `bash training/eval_sim.sh <EVALSET> <M>` on the workbench (sharded logits over `data/<EVALSET>_t*`, `_d*`; dev-fitted temperatures to `out/cal/<M>-<EVALSET>.json`); tables with `$PY training/report.py M=<json> --mode=kind`. Delete `out/records/<M>__*` first if `models/<M>` changed (the cache is keyed by name only). +6. **Export:** `$PY training/export_runtime.py --ckpt models/M --out out/export-M --name genclass-runtime-r17 --version X.Y.Z --calibration <cal.json> --data-rows <dev jsonl list> --n-per-file 60`. Without `--calibration` the export ships all-1.0 temperatures. +7. **Validate:** `node validate.mjs <export dir> q8 120` in a directory with `training/ortweb/package.json` installed; check `parity.json` (q8 argmax agreement, `embedding_q8.fp16_free: true`, q8 ≤ 25 MB per CONTRACT §10) and `ortweb_report_q8.json` (no pass/fail: read `argmax_agree`, `max_abs_logit`, `error`). Deliver with `pull_on_train.sh` / `deliver_final.sh` (sha256 against `model.json`). +8. **Runtime parity:** `cd packages/runtime && GENCLASS_MODEL_DIR=<export dir> npx vitest run test/model` (uses the export's own fixtures); then the browser specs **[ask first]**. +9. **New curriculum scenario case:** add it to the builder's `rng.choices` list in `training/curriculum/scenarios.py`, `scen_ops.py` or `scen_state.py`, with ≥ 4 phrasings, labels leaning passive when ambiguous, primitives and a `spec` that `rt.py` can render (or `no_runtime: True`). Keep the passive-best share within 0.45–0.75. Use dotted field paths (`mut_live` still builds bracket paths the runtime never produces). -**Tests.** `training/tests/test_curriculum.py` (with and without `GC_P_RUNTIME=1`), `test_export_runtime.py` after touching graph surgery, `test_prune_vocab.py` after vocabulary work. +**Tests.** `training/tests/test_curriculum.py` (with and without `GC_P_RUNTIME=1`), `test_export_runtime.py` after touching graph surgery, `test_prune_vocab.py` after vocabulary work. All **[ask first]**. -**Parity / retrain / release.** The trained model must have been trained on text from the runtime it will ship with (`situation-v1` today). Shipping is recipe 20. +**Parity / retrain / release.** The trained model must have been trained on text from the runtime it will ship with: `situation-v2` today. Round-1 models (situation-v1) must not ship with this runtime. -**Gotchas.** `training/export_runtime.py` parity `gate08`/`gate09` are a single-max proxy, not the runtime's summed-mass gate. `training/eval_runtime.py --records-dir` reuses cached logits by name even after retraining. q8 must be fp16-free so `webgpu+q8` runs without `shader-f16`. Final round 1 has no results in the repo. +**Gotchas.** `export_runtime.py` parity `gate08`/`gate09` are a single-max proxy, not the runtime's summed-mass gate. q8 must be fp16-free so `webgpu+q8` runs without `shader-f16`. `final_post.sh` hard-wires the v1 eval set `simAe` (recipe 30). **See.** [training.md](training.md#how-to-change-it-safely), [model-io-contract.md](model-io-contract.md#recipes). @@ -549,84 +587,88 @@ All sim runs are **[ask first]**. Before any sim change, read the matching test ### 19. Publish @genclass/runtime -**Goal.** Release a new version of the library to npm. There is no publish script and no CI; the steps are reconstructed. Publishing is irreversible and public: the user approves it and runs `npm publish` from their own logged-in machine. Agents never run `npm login` or handle npm tokens. +**Goal.** Release a new version of the library to npm. Publishing is irreversible and public: the user approves it and runs `npm publish` / `npm dist-tag` with their npm 2FA. Agents prepare and check everything, never run `npm login`, never handle npm tokens, and never publish, push or tag without an explicit go-ahead in chat. The full procedure, with exact commands and expected outputs, is [`RELEASE.md`](../../RELEASE.md) at the repo root; this recipe is its summary. **Steps.** -1. Preconditions: decide with the user whether this release can act. With `DEFAULT_MODEL_BASE_URL` pointing at the unpublished `@genclass/runtime-model@0.1.0`, a default `GenClass.init()` observes only; OPEN_TASKS plans `@genclass/runtime-model` first, then `@genclass/runtime@0.1.0` without the alpha tag. -2. Checks (local): `npm install`, `cd packages/runtime && npx tsc -p tsconfig.json --noEmit`, `npx tsup`, the full unit suite with `NODE_OPTIONS=--expose-gc`, `npm pack --dry-run` (expect `dist`, `bin`, `README.md`, `LICENSE`, `package.json`). **[ask first]**: model tests with `GENCLASS_MODEL_DIR`, `npm run test:browser`, `bash test/smoke/smoke.sh` from `packages/runtime` (registry access; leaves a `.tgz` in `packages/runtime/` and a temp app). -3. Bump `version` in `packages/runtime/package.json` and the version strings in the READMEs and `OPEN_TASKS.md`. -4. Build immediately before publishing (`npm publish` packs whatever `dist/` holds; there is no `prepublishOnly`). -5. The user, from `packages/runtime`: `npm publish --access public` (scoped packages are restricted otherwise; add `--tag <prerelease>` for prereleases; the flags used for `0.1.0-alpha.0` are not recorded). Check `npm view @genclass/runtime dist-tags` before and after. -6. With the user's approval: `git tag -a vX.Y.Z -m "@genclass/runtime X.Y.Z (npm)"` and push it; move the item to "Done" in `OPEN_TASKS.md`. +1. **Decide with the user which release** (RELEASE.md A0, B0): + - **Part A, `0.1.0-alpha.1` (optional, now, no model):** the NaN fix plus the situation-v2 runtime and the `observe` default, published under dist-tag `alpha` (moving `latest` afterwards is the user's choice). Without a model it only observes, so the open review findings go into the release notes, not the blocker list. + - **Part B (after a situation-v2 model exists):** `@genclass/runtime-model@0.1.0` and its GitHub release first (recipe 20), then the demos eval (recipe 22), then `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. Part B treats the open findings as blockers. + - Which branch and commit: `mvp-v2` is unpushed; the colleague works on `origin/runtime`. The release commit must reach `origin` (the user decides how). +2. **Fix what the tarball ships** (RELEASE.md A1): `packages/runtime/README.md` is the npm page: check the README status line and version before packing, and commit any fix. +3. **Clean release worktree** (RELEASE.md A2): `git worktree add -b release/runtime-<version> ../GenClass-lib-release <commit>`; `git status --porcelain` must print nothing. The main checkout may hold other agents' uncommitted edits, and `tsup` bundles whatever is on disk. +4. **Pre-flight** in the worktree (the CI steps, recipe 21): `npm ci --no-audit --no-fund`, `npm run typecheck -w @genclass/runtime`, `npm run build -w @genclass/runtime`, the unit tests (40 + 1 files, 332 passed / 14 skipped at b435acb) and `review-perf` with `--retry=2`, `npm pack --dry-run` (26 files: `LICENSE`, `README.md`, `bin/genclass-runtime.mjs`, `package.json`, 22 under `dist/`). With the user's OK **[ask first]**: a never-worse sweep on the release commit (recipe 28), `bash test/smoke/smoke.sh` on the exact tarball, and for Part B the model tests and browser specs with `GENCLASS_MODEL_DIR`. +5. **Version bump** (RELEASE.md A4): `npm version <version> -w @genclass/runtime --no-git-tag-version` updates `packages/runtime/package.json` and the root lockfile together; commit both. Update the version strings in the READMEs, `OPEN_TASKS.md` and `HANDOFF.md`. +6. **Pack** from `packages/runtime`: `npm run build && npm pack` -> `genclass-runtime-<version>.tgz` (there is no `prepublishOnly`; `npm publish` packs whatever `dist/` holds). +7. **Give the user the exact command** (RELEASE.md A6): `npm publish genclass-runtime-<version>.tgz --access public --tag <tag>`. A prerelease needs `--tag` on npm 11 (HANDOFF's bare command fails for `0.1.0-alpha.1`); `0.1.0` needs none and becomes `latest`. Check `npm view @genclass/runtime dist-tags` before and after (RELEASE.md A8). +8. **After the publish, with the user's OK** (RELEASE.md A9, A10): tag `v<version>` and push it, a GitHub release if wanted, move the item to "Done" in `OPEN_TASKS.md`, update `HANDOFF.md` and [build-test-release.md](runtime/build-test-release.md#publish-history-from-git-and-the-registry). -**Tests.** As in step 2. +**Tests.** As in step 4. -**Parity / retrain / release.** The published runtime's situation code must match the model it loads (`situation-v1` for the current training round). +**Parity / retrain / release.** The published runtime's situation code must match the model it loads (`situation-v2` for the coming v2 model). The loader checks only the card format (`genclass-runtime-model/1`), not a situation version, so a mismatched model loads silently. A runtime that changed model text after the tag needs a new model first. -**Gotchas.** No root lockfile is committed, so dependency versions float within caret ranges. `packages/runtime/bin/genclass-runtime.mjs` is committed as 644; npm sets the executable bit on install. A failed tsup build leaves a half-empty `dist/` (`clean: true`). +**Gotchas.** A failed tsup build leaves a half-empty `dist/` (`clean: true`). `git push` of the release branch is itself a user decision (its CI then runs for the first time on GitHub). If `RELEASE.md` is missing on your checkout, follow `HANDOFF.md` "How to continue" and [build-test-release.md](runtime/build-test-release.md#cut-a-release-of-genclassruntime). -**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely). +**See.** [`RELEASE.md`](../../RELEASE.md), [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely), [status-and-known-issues.md](status-and-known-issues.md). ### 20. Publish @genclass/runtime-model and point the runtime at it -**Goal.** Make the default model URL serve a trained model so that `GenClass.init()` can act (OPEN_TASKS item 8). **[ask first]** throughout; publishing is the user's action. +**Goal.** Make the default model URL serve a trained situation-v2 model so that `GenClass.init({ mode: "guard" })` can act. **[ask first]** throughout; publishing is the user's action. Full procedure: [`RELEASE.md`](../../RELEASE.md) Part B (B0–B7). npm versions are immutable, so whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently. Blocked until recipe 30 produces a v2 model that meets the gates (PLAN-v1 §1, §8: ship guard only when guard FIR ≤ 0.1% on all held-out sets). **Steps.** -1. Choose the model with the user (R17 for WASM vs R32 for WebGPU; OPEN_TASKS item 5) and get its export directory (recipe 18). -2. Put the directory under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@<version>/files/`. Check it: `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files` (card rules, hashes, `needs: shader-f16` on fp16). -3. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, version, `files` including `files/`). It becomes a workspace automatically (`packages/*`). Confirm with `npm pack --dry-run` in that directory that `files/` is included. -4. The user publishes it (`npm publish --access public`) and attaches the same files to a GitHub release tagged `runtime-model-v<version>` (the CLI's `DEFAULT_FROM` is `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`). +1. Choose the model with the user (R17 default on every device per final round 1; R32 only if clearly better) and get its validated export directory (recipes 18, 30). +2. Put the directory under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@<version>/files/` (`DEFAULT_MODEL_BASE_URL`). Check it: `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files` (card rules, hashes, `needs: shader-f16` on fp16). Never publish the round-1 `files/r17/` (situation-v1). +3. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, version, `files` including `files/`). It becomes a workspace automatically (`packages/*`), so run `npm install` at the root and commit the lockfile, or CI's `npm ci` fails. Confirm with `npm pack --dry-run` in that directory that `files/` is included. +4. The user publishes it (`npm publish --access public`) and attaches the same files to a GitHub release tagged `runtime-model-v<version>` (the CLI's `DEFAULT_FROM`). 5. If the version is not 0.1.0, update `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`, then release the runtime (recipe 19). -6. Update `packages/runtime-model/MODEL_CARD.md` (it lacks `transient` and describes the old gate), `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, `packages/runtime/README.md` "Status", `OPEN_TASKS.md`. +6. Update `packages/runtime-model/MODEL_CARD.md` (it describes round 1), `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, both READMEs' "Status", `docs/runtime/RESULTS.md`, `OPEN_TASKS.md`, `HANDOFF.md`. **Tests.** No automated test covers the default URL end to end. **[ask first]** In a browser: `GenClass.init()` reaches `status.state === "ready"`, the console no longer prints "Model unavailable (...); observing only.", and `npm run test:browser` passes against the published directory. -**Parity / retrain / release.** The model must match the runtime's situation format. +**Parity / retrain / release.** The model must match the runtime's situation format (one tag for both). + +**Gotchas.** Cache Storage (`genclass-runtime-v1`) never evicts old versions. `model.json` is revalidated on every load. The demos' `?model=cdn` falls back to `DEFAULT_MODEL_BASE_URL`. -**Gotchas.** Cache Storage (`genclass-runtime-v1`) never evicts old versions. `model.json` is revalidated on every load. The demos' `?model=cdn` falls back to the runtime default (`DEFAULT_MODEL_BASE_URL`, which ends in `files/`). Only the `demos/README.md` example `GENCLASS_MODEL_URL=…@0.1.0/` lacks the `files/` suffix. +**See.** [RELEASE.md Part B](../../RELEASE.md#part-b-model-package-then-genclassruntime010-after-a-situation-v2-model-exists), [build-test-release.md](runtime/build-test-release.md), [model-host.md](runtime/model-host.md). -**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely), [model-host.md](runtime/model-host.md). +### 21. Change the CI workflow -### 21. Add a CI workflow +**Goal.** Change `.github/workflows/ci.yml` (added in b435acb; it has not run on GitHub yet because `mvp-v2` is unpushed and `origin/runtime` has no `.github/`). -**Goal.** Add the CI that OPEN_TASKS item 8 plans (none exists: no `.github/`). +**What it does.** One job `runtime` on `ubuntu-latest`, 15 min timeout, triggered by pushes to `main`, `runtime`, `mvp`, `mvp-v2`, by pull requests and by `workflow_dispatch`; `concurrency` cancels superseded runs; `permissions: contents: read`; env `ONNXRUNTIME_NODE_INSTALL: skip`. Steps: `actions/checkout@v4`; `actions/setup-node@v4` with `node-version: 22`, `cache: npm`; `npm ci --no-audit --no-fund`; `npm run typecheck -w @genclass/runtime`; `npm run build -w @genclass/runtime`; in `packages/runtime` with `NODE_OPTIONS: --expose-gc`: `npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then `npx vitest run test/review-perf.test.ts --retry=2`. **Steps.** -1. Add `.github/workflows/<name>.yml` running on Node 22 (≥ 22.12) or 24: vitest@5.0.3's `engines` excludes Node 20, 21, 23 and 25. -2. Steps: `npm install` (or have the user decide to commit a root `package-lock.json` and use `npm ci`), `npm run build`, `npm run typecheck -w @genclass/runtime`, `NODE_OPTIONS=--expose-gc npm test`. Expect 286 passed / 14 skipped without a model directory. -3. Keep root `npm run typecheck` out unless the demos typecheck works: it needs the full runtime build and the missing `demos/src/server/data/cities.ts`. It fails at this commit: `demos/tsconfig.json` includes `src/`, and three files import the missing `cities.ts` (inferred from code; not run). -4. Browser specs would need `npx playwright install --with-deps chromium` and a model directory; the smoke test needs registry access. Leave them out of a first workflow. -5. Pushing the workflow is the user's call. +1. Run the changed steps locally first (same commands; recipe 23). Keep Node within vitest@5.0.3's engines (22 ≥ 22.12, 24, ≥ 26; not 23 or 25). +2. Keep the root `npm run typecheck` out: it also typechecks `demos`, which needs the runtime `dist/` and the missing `demos/src/server/data/cities.ts` (recipe 22). Sim tests could be added after the build step: `cd sim && SIM_RUNTIME=real npx vitest run` (19 tests). +3. Browser specs would need `npx playwright install --with-deps chromium` and, for model specs, a model directory (a download: ask the user); the smoke test needs registry access. realapps needs Chromium and a VM-sized machine. Leave them out unless the user decides otherwise. +4. Never add a job that publishes, tags or pushes; changing triggers or adding secrets is the user's call. Pushing the workflow is the user's call. -**Tests.** Run the same commands locally first. +**Tests.** The workflow itself; locally the same commands. -**Gotchas.** `review-perf.test.ts` asserts wall-clock bounds and can flake on shared runners. The gc test passes silently without `--expose-gc`. +**Gotchas.** `review-perf.test.ts` asserts wall-clock bounds and flakes on shared runners (hence its own step with retries). The gc test passes silently without `--expose-gc`. A dependency change without a lockfile update fails `npm ci`. -**See.** [build-test-release.md](runtime/build-test-release.md#how-to-change-it-safely). +**See.** [build-test-release.md](runtime/build-test-release.md#ci-githubworkflowsciyml). ## Recipes: demos ### 22. Add or change a demo and re-run trials -**Goal.** Add a demo app or change a scenario, oracle, chaos knob or server route, and measure with trials. +**Goal.** Add a demo app or change a scenario, oracle, chaos knob or server route, and measure with trials. The HANDOFF order reruns all demos with the trained v2 model before `@genclass/runtime@0.1.0`. **Steps.** -1. **Prerequisite for any demos build:** recreate `demos/src/server/data/cities.ts` (missing from git; ignored by the root `.gitignore` pattern `data/`). It must export `searchCities(q: string)` returning `{ total, items: { id, name, country, population }[] }` and `TYPED_TARGETS: string[]`. Add a negation (`!demos/src/server/data/`) to the root `.gitignore` or rename the directory. -2. **New demo:** `demos/src/shared/protocol.ts` -> `DemoId`; a world `demos/src/server/worlds/<id>.ts` registered in `demos/src/server/sw.ts` -> `DEFS`; `demos/src/demos/<id>/{main,app,scenario,oracle}.ts` + `app.css`; `demos/<id>/index.html` (copy one; `gc-root` `../`); `demos/vite.config.ts` -> `PAGES`; `demos/e2e/eval.ts` -> `ALL_DEMOS`, `TITLES`, `SHOT_PRESET`; `demos/src/shared/demos.ts` -> `DEMOS`; `demos/src/site/art.ts` -> `ART`. `tsc` flags missing `DEFS`, `ART`, `TITLES`, `SHOT_PRESET` entries but not `DEMOS`, `PAGES`, `ALL_DEMOS`. -3. **Scenario or oracle threshold:** edit `demos/src/demos/<id>/scenario.ts` / `oracle.ts`; keep the scenario RNG label `"<demo>:<kind>:<seed>"`; update the `scored` copy in `demos/src/shared/demos.ts` and the README oracle table. -4. **Chaos knob:** `demos/src/shared/chaos.ts` -> `RouteChaos`, `CALM`, `describeChaos`; apply it in `demos/src/server/core.ts` -> `World.handle` (draw randomness from the request's rng up front); a slider in `demos/src/site/chaos-panel.ts` -> `SLIDERS`. -5. **Server route or world action:** a `Route` with a stable `key`; `w.rng` in handlers, `w.scriptRng` / `w.script` for scripted activity; oracle-relevant data in `snapshot`. -6. **GenClass init:** only `demos/src/shared/genclass.ts` -> `startGenClass`; app code never branches on mode. New runtime API: public API only, mirrored in `demos/src/dev/runtime-shim/*`. -7. **Trials** **[ask first]**: `GENCLASS_MODEL_FROM=<release dir url> bash demos/scripts/vm-eval.sh --tag <name>` (or `GENCLASS_MODEL_DIR` / `GENCLASS_MODEL_URL`), or, from `demos/`, `npm run build` then `npm run eval:fast -- --demos <id>` (`e2e/eval.ts` options include `--n`, `--clean`, `--modes`, `--workers`, `--model`, `--tag`, `--trace`, `--no-shots`). Tagged runs write `results-<tag>.*`; untagged runs replace the shipped `results.*` and the landing page numbers. -8. **Results schema or aggregation:** `demos/src/shared/aggregate.ts` -> `ModeSummary` feeds `demos/src/site/trials-panel.ts`, `demos/e2e/eval.ts` (Markdown and JSON reports) and `demos/src/site/landing.ts` (reads `results-summary.json`); keep the fields or update all three. -9. **World-clock offset (optional fix):** trial worlds start before Guard/Heal pages wait for the model, so scripted activity happens earlier relative to `t0` than in Off. Moving `link.hello(...)` in `demos/src/site/demo-page.ts` -> `bootTrial` after the `gc.ready` wait, or starting scripts from a world action sent at `demos/src/shared/harness.ts` -> `TrialHarness.begin`, removes it; either changes every seed's results. -10. **Hold-induced regressions** **[ask first]**: from `demos/`, `node --experimental-strip-types e2e/eval.ts --trace --demos board --modes off,guard,heal --tag <t>` plus an Off-only A/A run, then `node --experimental-strip-types e2e/trace-report.ts e2e/.out/traces-<t>.json [e2e/.out/traces-<offB>.json]`. +1. **Prerequisite for any demos build:** recreate `demos/src/server/data/cities.ts` (still missing from git at b435acb; ignored by the root `.gitignore` pattern `data/`). It must export `searchCities(q: string)` returning `{ total, items: { id, name, country, population }[] }` and `TYPED_TARGETS: string[]`. Add a negation (`!demos/src/server/data/`) to the root `.gitignore` or rename the directory. +2. **New demo:** `demos/src/shared/protocol.ts` -> `DemoId`; a world `demos/src/server/worlds/<id>.ts` registered in `demos/src/server/sw.ts` -> `DEFS`; `demos/src/demos/<id>/{main,app,scenario,oracle}.ts` + `app.css`; `demos/<id>/index.html`; `demos/vite.config.ts` -> `PAGES`; `demos/e2e/eval.ts` -> `ALL_DEMOS`, `TITLES`, `SHOT_PRESET`; `demos/src/shared/demos.ts` -> `DEMOS`; `demos/src/site/art.ts` -> `ART`. +3. **Scenario or oracle threshold:** `demos/src/demos/<id>/scenario.ts` / `oracle.ts`; keep the scenario RNG label `"<demo>:<kind>:<seed>"`; update the `scored` copy and the README oracle table. +4. **Chaos knob:** `demos/src/shared/chaos.ts` -> `RouteChaos`, `CALM`, `describeChaos`; apply it in `demos/src/server/core.ts` -> `World.handle`; a slider in `demos/src/site/chaos-panel.ts` -> `SLIDERS`. +5. **GenClass init:** only `demos/src/shared/genclass.ts` -> `startGenClass`, which passes explicit modes (off = observe without a model, guard, heal), so the default-mode change does not affect trials. Its header comment still calls guard "the default". The synthetic in-page driver needs `observe: { untrustedEvents: true }` to record user actions (open finding). +6. **Trials** **[ask first]**: `GENCLASS_MODEL_FROM=<release dir url> bash demos/scripts/vm-eval.sh --tag <name>` (or `GENCLASS_MODEL_DIR` / `GENCLASS_MODEL_URL`), or, from `demos/`, `npm run build` then `npm run eval:fast -- --demos <id>`. Tagged runs write `results-<tag>.*`; untagged runs replace the shipped `results.*` and the landing page numbers. Report bug rate per mode **and** clean-run false interventions; update `docs/runtime/RESULTS.md` §5. The pre-release eval (Off / Observe / Guard) and the code changes it needs first are in [`RELEASE.md`](../../RELEASE.md) B7. +7. **Results schema:** `demos/src/shared/aggregate.ts` -> `ModeSummary` feeds `demos/src/site/trials-panel.ts`, `demos/e2e/eval.ts` and `demos/src/site/landing.ts`; keep the fields or update all three. +8. **Hold-induced regressions** **[ask first]**: `node --experimental-strip-types e2e/eval.ts --trace --demos board --modes off,guard,heal --tag <t>` plus an Off-only A/A run, then `e2e/trace-report.ts`. -**Tests.** There are no unit tests in `demos/`; the oracles and the eval are the tests. Typecheck: `npm run typecheck -w @genclass/demos` (needs `packages/runtime/dist/*.d.ts`) or `npm run typecheck:shim -w @genclass/demos` (the shim lacks some `Runtime` methods, so it likely fails; unverified). +**Tests.** No unit tests in `demos/`; the oracles and the eval are the tests. Typecheck: `npm run typecheck -w @genclass/demos` (needs `packages/runtime/dist/*.d.ts` and `cities.ts`). -**Parity / retrain / release.** None for the model. Results are comparable only within the same scenario code, runtime build and model; re-run all modes after any scenario change. +**Parity / retrain / release.** None for the model. Results are comparable only within the same scenario code, runtime build and model. -**Gotchas.** Test-side code (oracles, driver, harness, site panels) must use the native timers from `demos/src/shared/native.ts` and control the mock server only through `postMessage`, never `fetch`, or GenClass observes test traffic. Request bodies and event keys must not contain timestamps or random ids (they would re-roll the network per mode). Oracles read `data-testid` / `data-*` attributes: renaming one silently changes scores. Do not fix the apps' latent bugs. The activity panel classifies decisions by runtime reason strings. +**Gotchas.** Test-side code must use the native timers from `demos/src/shared/native.ts` and control the mock server only through `postMessage`. Request bodies and event keys must not contain timestamps or random ids. Oracles read `data-testid` / `data-*` attributes. Do not fix the apps' latent bugs, and never let `sim/` or `realapps/` read the demos. **See.** [demos.md](demos.md#how-to-change-it-safely). @@ -634,26 +676,30 @@ All sim runs are **[ask first]**. Before any sim change, read the matching test ### 23. Run each test suite -| suite | where / command | prerequisites | expected | policy | +| suite | where / command | prerequisites | expected at b435acb | policy | |---|---|---|---|---| -| runtime typecheck | `cd packages/runtime && npx tsc -p tsconfig.json --noEmit` | `npm install` | clean | local | -| runtime build | `cd packages/runtime && npx tsup` (or `npm run build` at the root) | install | `dist/` with 6 entries | local | -| runtime unit tests | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (`npm test` is equivalent; the config already excludes `test/browser/**`) | install | 36 passed + 1 skipped files; 286 passed + 14 skipped tests | local | -| one file / one test | `cd packages/runtime && npx vitest run test/atoms.test.ts -t "late discard"` | install | | local | -| model unit tests incl. parity | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> NODE_OPTIONS=--expose-gc npx vitest run test/model` | a model directory from `node packages/runtime/bin/genclass-runtime.mjs fetch-model <dir> --from <url>` | all 62 MODEL tests run | **[ask first]** (download) | -| browser model specs | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> npm run test:browser` (add `--project chromium` or `swiftshader-webgpu`) | Playwright Chromium for `@playwright/test` 1.63.0, model dir; rebuilds `dist/`; also re-runs the UI spec | specs skip without `model.json` | **[ask first]** | -| devtools UI spec | `cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts` | root `npm install` (fonts from the demos workspace), Chromium | 5 tests; rewrites 18 screenshots | **[ask first]** | -| tarball smoke | `cd packages/runtime && bash test/smoke/smoke.sh` | registry access, Chromium in the Playwright cache | prints `SMOKE OK: <tgz>` | **[ask first]** | -| sim tests | `npm run build`, then `cd sim && SIM_RUNTIME=real npx vitest run` | runtime `dist/` | 17 tests (without `SIM_RUNTIME=real` the fake runtime is used and 2 oracle tests skip) | **[ask first]** | -| sim typecheck | `npm run typecheck -w @genclass/sim` | install | not run when these docs were written | local | -| demos typecheck | `npm run typecheck -w @genclass/demos` | runtime build, `cities.ts` (recipe 22) | not run when these docs were written | local | -| demos trials | recipe 22 step 7 | built site, model, Chromium | `results*.json/md` | **[ask first]** | -| training tests | on a VM: `PYTHONPATH=… python -m pytest -q training/tests/<file>` | jev venv, checkpoints for some tests | | **[ask first]** | -| legacy Python tests | `python -m pytest -q tests/<file>` (markers `model`, `slow`, `macos`) | Python env; 20 `tests/test_data_*.py` fail at collection because `jev_local/data` is missing | | **[ask first]** | -| export validation | `node validate.mjs <export dir> q8 [maxRequests]` in a directory with `training/ortweb/package.json` installed | an export dir | `ortweb_report_q8.json` | **[ask first]** | +| install | `npm ci` (repo root) | Node 22/24 (25 warns) | OK | local | +| runtime typecheck | `npm run typecheck -w @genclass/runtime` | install | clean | local | +| runtime build | `npm run build -w @genclass/runtime` | install | `dist/` with 6 entries | local | +| runtime unit tests | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` | install | 40 passed + 1 skipped files; 332 passed + 14 skipped tests | local | +| perf budgets | `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | install | 4 passed (flaky under load) | local | +| one file / one test | `cd packages/runtime && npx vitest run test/delivery.test.ts -t "<name>"` | install | | local | +| CI steps | the five steps of `.github/workflows/ci.yml` | fresh clone | pass | local | +| sim typecheck and tests | `npm run build -w @genclass/runtime`; `cd sim && npx tsc -p tsconfig.json --noEmit && SIM_RUNTIME=real npx vitest run` | runtime `dist/` | clean; 19 passed (5 files) | local | +| model unit tests incl. parity | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> NODE_OPTIONS=--expose-gc npx vitest run test/model` | a model directory (download) | the 14 skips run | **[ask first]** | +| browser model specs | `cd packages/runtime && GENCLASS_MODEL_DIR=<dir> npm run test:browser` | Playwright Chromium for `@playwright/test` 1.63.0, model dir; rebuilds `dist/` | specs skip without `model.json` | **[ask first]** | +| devtools UI spec | `cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts` | Chromium | rewrites the screenshots | **[ask first]** | +| tarball smoke | `cd packages/runtime && bash test/smoke/smoke.sh` | registry access, Chromium | prints `SMOKE OK: <tgz>` | **[ask first]** | +| sim smoke / generation | `node sim/dist/smoke.js --seeds 40`; recipe 17 | sim `dist/` | | **[ask first]** | +| realapps sweeps / generation | recipes 28, 29 | a VM with Chromium | | **[ask first]** | +| demos typecheck | `npm run typecheck -w @genclass/demos` | runtime build, `cities.ts` | fails without `cities.ts` | local | +| demos trials | recipe 22 step 6 | built site, model, Chromium | `results*.json/md` | **[ask first]** | +| training tests | `PYTHONPATH=… python -m pytest -q training/tests/<file>` | jev venv; checkpoints for some | | **[ask first]** | +| legacy Python tests | `python -m pytest -q tests/<file>` (markers `model`, `slow`, `macos`) | Python env | 20 `tests/test_data_*.py` fail at collection (`jev_local/data` missing) | **[ask first]** | +| export validation | `node validate.mjs <export dir> q8 [maxRequests]` in a dir with `training/ortweb/package.json` installed | an export dir | `ortweb_report_q8.json` | **[ask first]** | | extension | in `extension/` on a VM: `npm ci`, `npm test`, `npm run test:e2e` | release-assets ONNX files | | **[ask first]** | -Root scripts: `npm run build` and `npm test` run only in `@genclass/runtime`; `npm run typecheck` runs every workspace that has the script. +Root scripts: `npm run build` and `npm test` run only in `@genclass/runtime`; `npm run typecheck` runs every workspace that has the script (`packages/*`, `sim`, `demos`; `realapps` is not a workspace). **See.** [build-test-release.md](runtime/build-test-release.md#exact-commands), [build-test-release.md](runtime/build-test-release.md#tests). @@ -663,7 +709,7 @@ Root scripts: `npm run build` and `npm test` run only in `@genclass/runtime`; `n **Steps.** 1. Put it in `packages/runtime/test/<area>.test.ts` (`test/model/` for model code). Import with `.js` extensions (`./helpers.js`, `../src/...js`). -2. Use `packages/runtime/test/helpers.ts` -> `setup(opts)`: `createRuntime` with `FakeClock` (starts at t = 1000), `FakeServer` (`http://app.test/`, 50 ms latency, unknown route 404), `ScriptedDecider`, `report: "silent"` and only the fetch observer on. Useful options: `triage: "always"` to force consultation, `mode: "heal"` for heal-tier actions, `script: defaultScript({ mutation: { diagnosis: "stale", action: "discard", p } })`, `decider: new ManualDecider()` to control answer timing (`answer(script)` releases the oldest pending request). +2. Use `packages/runtime/test/helpers.ts` -> `setup(opts)`: `createRuntime` with `FakeClock` (starts at t = 1000), `FakeServer` (`http://app.test/`, 50 ms latency, unknown route 404), `ScriptedDecider`, `report: "silent"`, **`mode: "guard"`** (not the library default) and only the fetch observer on. Useful options: `triage: "always"`, `mode: "heal"` or `mode: "observe"`, `policy: { holdWrites: true }` for the held-write pipeline, `script: defaultScript({ delivery: { diagnosis: "stale", action: "discard", p } })`, `decider: new ManualDecider()` to control answer timing. 3. Drive the app with `rt.user(...)`, `rt.op(...)`, atoms and `fetch`; advance time with `await clock.advance(ms)`, `clock.flush()`, `clock.runAll()`. 4. Assert on `decider.calls[i].state`, `rt.decisions()`, `rt.interventions()`, `rt.history()`, `server.hits` / `server.log`. 5. Name the contract section in the `describe` (e.g. `"(CONTRACT §4)"`). A bug demonstration follows the `review-*.test.ts` style: header comment `// REVIEW: <area>. A failing test demonstrates a bug.`, `describe("review: ...")`, and a test name stating the required behaviour. @@ -675,20 +721,22 @@ import { describe, expect, it } from "vitest"; import { ManualDecider, defaultScript, setup } from "./helpers.js"; describe("my change (CONTRACT §4)", () => { - it("holds an async write until the model answers", async () => { + it("a write applies at once and a passing discard reverts it late", async () => { const manual = new ManualDecider(); - const { rt, clock } = setup({ decider: manual, triage: "always" }); + const { rt, clock } = setup({ decider: manual, triage: "always" }); // guard, holdWrites off const a = rt.atom("v", 0); void rt.op("save", () => a.set(5)); - expect(a.get()).toBe(0); // held - manual.answer(defaultScript({ mutation: { diagnosis: "expected", action: "apply" } })); + expect(a.get()).toBe(5); // never held by default + manual.answer(defaultScript({ mutation: { diagnosis: "stale", action: "discard", p: 0.99 } })); await clock.flush(); - expect(a.get()).toBe(5); + // assert on a.get(), rt.interventions()[0].late, ... }); }); ``` -**Gotchas.** Tests are not type-checked. Identical `(trigger, state, questions)` within 30 s are answered from the queue cache, so `ScriptedDecider.calls` does not grow: advance the clock past 30 s or vary the situation. Tests that use `GenClass.init` must call `GenClass.destroy()`. Unit tests import fixtures from `test/browser/ui/` (`mock-runtime.ts`, `scenario.ts`, `session.ts`); do not move them. +The example is a sketch: check the exact late-revert conditions in `atoms.test.ts` / `delivery.test.ts` before asserting values. + +**Gotchas.** Tests are not type-checked. Identical `(trigger, state, questions)` within 30 s are answered from the queue cache: advance the clock past 30 s or vary the situation. Tests that use `GenClass.init` must call `GenClass.destroy()`. Unit tests import fixtures from `test/browser/ui/`; do not move them. Delete temporary `zz-*` files before you finish. **See.** [build-test-release.md](runtime/build-test-release.md#write-a-new-unit-test-house-style). @@ -697,29 +745,29 @@ describe("my change (CONTRACT §4)", () => { **Goal.** Find out why GenClass changed an app's behaviour when it should not have, relieve the user, and fix the right layer without adding a rule. **Steps.** -1. **Confirm the runtime could act.** Check `GenClass.runtime.status` (`state`, `model`, `variant`) and `GenClass.runtime.mode`. With default options, `@genclass/runtime@0.1.0-alpha.0` cannot act: its model URL is unpublished, the status ends in `error` and the console says "Model unavailable (...); observing only.". An intervention therefore implies a self-hosted `model.baseUrl` or a custom `decider`. Guard mode runs only guard-tier actions: the built-ins `discard`, `defer`, `coalesce`, `delay`, and custom actions declared with `tier: "guard"`. -2. **Collect the evidence.** The console line `[GenClass] <Lead> <noun>: <fact> <changed> (<diagnosis>, p; <action> p)` and its collapsed group; `GenClass.runtime.interventions()` -> `ActionRecord` (`id` `a<n>`, `decisionId`, `action`, `tier`, `changed`, `ok`, `error`, `late`); `GenClass.runtime.explain("a<n>")` -> `Explanation` (`situationText`, `facts`, `timeline`, `answers`, and `decision` with `diagnosisProbabilities`, `probabilities`, `candidate`, `mass`, `tier`, `reason`). The devtools overlay shows the same evidence with a Copy button for the situation text. `GenClass.runtime.history(400)` gives the event log; `debug: true` logs swallowed errors. -3. **Relieve the user.** `ActionRecord.undo?.()` exists only for `discard`, late reverts, `rollback` and custom actions with `onUndo` (undo is unguarded and does not check whether state moved since). At the next page load: `GenClass.init({ policy: { deny: ["<action>"] } })`, or `mode: "observe"`, or `?genclass=observe` / `?genclass=off` / `localStorage.genclass = "off"`. The printed "Deny this action" hint does nothing on a page where `init` already ran. +1. **Confirm the runtime could act.** Check `GenClass.runtime.status` (`state`, `model`, `variant`) and `GenClass.runtime.mode`. In the default `observe` mode (this branch) nothing non-passive can run. With `@genclass/runtime@0.1.0-alpha.0` (default `guard`) the default model URL 404s, the status ends in `error` and the console says "Model unavailable (...); observing only.". So an intervention implies an explicit `mode: "guard" | "heal"` (or `setMode`, or `?genclass=guard|heal`) **and** a self-hosted `model.baseUrl` or a custom `decider`. Guard runs only guard-tier actions: `discard`, `defer`, `coalesce`, `delay`, and custom actions declared `tier: "guard"`. +2. **Collect the evidence.** The console line `[GenClass] <Lead> <noun>: <fact> <changed> (<diagnosis>, p; <action> p)`; `GenClass.runtime.interventions()` -> `ActionRecord` (`id` `a<n>`, `decisionId`, `action`, `tier`, `changed`, `ok`, `error`, `late`); `GenClass.runtime.explain("a<n>")` -> `Explanation` (`situationText`, `facts`, `timeline`, `answers`, and `decision` with `diagnosisProbabilities`, `probabilities`, `candidate`, `mass`, `tier`, `reason`). The devtools overlay shows the same evidence with a Copy button. `GenClass.runtime.history(400)` gives the event log; `debug: true` logs swallowed errors. +3. **Relieve the user.** `ActionRecord.undo?.()` exists only for `discard`, late reverts, `rollback` and custom actions with `onUndo`. At the next page load: `GenClass.init({ policy: { deny: ["<action>"] } })`, or drop the explicit mode (default observe), or `?genclass=observe` / `?genclass=off` / `localStorage.genclass = "off"`. A delivery `discard` mark keeps dropping that chain's writes for 10 s even after `pause()` or `setMode("observe")` (open finding): a reload is the reliable reset. 4. **Classify** (read the evidence against the code): - - **Gate:** did the decision pass `packages/runtime/src/decide/policy.ts` -> `gate` legitimately? `decision.mass` ≥ the threshold of `decision.tier` (0.9 guard / 0.8 heal unless overridden), top diagnosis ≠ `expected` (unless `requireDiagnosis: false`), the mode permits the tier. A wrong pass is a gate bug (test in `policy.test.ts`). - - **Applicability:** should the action have been offered at all? `packages/runtime/src/situation/build.ts` -> `builtinApplicable` (known: `retry` for non-idempotent POSTs, `demos/NEEDS.md` §5). Fixing it is class A (recipe 4). - - **Facts:** is any fact false (wrong order, version count, causal attribution, a redaction leak)? That is a trace or fact bug in `packages/runtime/src/situation/facts.ts`, `packages/runtime/src/trace/context.ts` or an observer; the fix is class A (recipes 1, 2). - - **Effect:** does `changed` describe what really happened; did it act on the right write or request? That is a controller bug (recipe 4 a). `late: true` means a late revert: check `StoreHub.revertable`. - - **Model:** the gate, offer, facts and effect are all correct and the model was confidently wrong. That is a precision problem for training: record the situation text and the expected passive outcome (e.g. a `training/NEEDS.md` or SIM scenario request). Do **not** add a runtime rule that maps this pattern to passive (CONTRACT §0 rule 1). - - **No `ActionRecord` at all**, but the app misbehaved: look at holds. Decisions with `reason` "the decision arrived after the hold budget expired", held writes reordered behind a newer user write (`demos/NEEDS.md` §1), added latency (§2). Mitigations: `StoreOptions.hold: false` for that store, `policy.holdBudgetMs`, observe mode. -5. **Reproduce headless.** Write a unit test (recipe 24) that recreates the trigger and forces the same model answer with `defaultScript`, then asserts the corrected gate, offer, fact or effect. The real model's probabilities can only be reproduced with model files **[ask first]**. -6. **Record.** Add the regression test; note the issue in `packages/runtime/STATUS.md` "Open issues" (or the owning NEEDS file); for precision cases, give TRAIN the situation text. + - **Gate:** did the decision pass `packages/runtime/src/decide/policy.ts` -> `gate` legitimately? `decision.mass` ≥ the tier threshold, top diagnosis ≠ `expected` (unless `requireDiagnosis: false`), the mode permits the tier. A wrong pass is a gate bug (`policy.test.ts`). + - **Applicability:** should the action have been offered? `packages/runtime/src/situation/build.ts` -> `builtinApplicable` (known: `retry` for non-idempotent POSTs). Fixing it is class A (recipes 4, 6). + - **Facts:** is any fact false (wrong order, version count, causal attribution, a "created" item that was a search result, "nor the value when #X started" when it was, a redaction leak)? A fact or trace bug in `packages/runtime/src/situation/*`, `packages/runtime/src/trace/context.ts` or an observer; the fix is class A (recipes 1, 2, 6). + - **Effect:** does `changed` describe what really happened; did it act on the right write, response or message? A controller bug (recipe 4 a). Known effect defects: a delivery `discard` mark also drops later fresh polls chained from the discarded op; a `discard` on redux/zustand stores changes nothing but is recorded as a drop; a held WS/SSE message is dispatched after `close()`; a delivery `defer` can hold a response or a whole push channel for up to 20 s (two 10 s defers). `late: true` means a late revert: check `StoreHub.revertable`. + - **Model:** the gate, offer, facts and effect are all correct and the model was confidently wrong. A precision problem for training: record the situation text and the expected passive outcome (a `training/NEEDS.md` or SIM scenario request). Do **not** add a runtime rule that maps this pattern to passive (CONTRACT §0 rule 1). + - **No `ActionRecord` at all**, but the app misbehaved: look at timing. Held deliveries (`delivery` decisions with a hold-budget reason), observe mode's up-to-100 ms wait for a conflicting delivery's body, XHR completion listeners run after the dispatch ended (`e.currentTarget === null`), request-time holds (the source of the 3/198 chaos differences in the realapps sweep), held writes under an opt-in `holdWrites`. +5. **Reproduce headless.** Write a unit test (recipe 24) that recreates the trigger and forces the same model answer with `defaultScript`, then asserts the corrected gate, offer, fact or effect. If the app is in the realapps corpus (or close to one), reproduce in a real browser with `debug.js --app <name> --seed <s> --mode guard|heal` **[ask first]** (recipe 28). The real model's probabilities can only be reproduced with model files **[ask first]**. +6. **Record.** Add the regression test; note the issue in `packages/runtime/STATUS.md` "Open issues" (or the owning NEEDS file) and in the subsystem doc's "Drift and open issues"; for precision cases, give TRAIN the situation text. **Gotchas.** Console reports are deduplicated in 60 s windows ("×N more"). Reason strings are parsed by devtools and the demos: do not reword them while debugging. `rt.situation(trigger)` returns the last situation built for that trigger, not a fresh rebuild. -**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md), [learn-situation-triage.md](runtime/learn-situation-triage.md), [state-and-adapters.md](runtime/state-and-adapters.md#drift-and-open-issues), [devtools.md](runtime/devtools.md). +**See.** [decide-policy-actions.md](runtime/decide-policy-actions.md), [learn-situation-triage.md](runtime/learn-situation-triage.md), [state-and-adapters.md](runtime/state-and-adapters.md#drift-and-open-issues), [observe-and-trace.md](runtime/observe-and-trace.md), [devtools.md](runtime/devtools.md). ### 26. Update these docs after a code change **Goal.** Keep `docs/agents/`, `AGENTS.md`, `CLAUDE.md` and the human docs true to the code after you change it. **Steps.** -1. Find every doc that cites what you changed: `grep -rn "<symbol or path>" docs/agents AGENTS.md CLAUDE.md docs/runtime packages/runtime/*.md packages/runtime/src/model/README.md sim/README.md training/README.md demos/README.md`. +1. Find every doc that cites what you changed: `grep -rn "<symbol or path>" docs/agents AGENTS.md CLAUDE.md HANDOFF.md OPEN_TASKS.md README.md docs/runtime packages/runtime/*.md packages/runtime/src/model/README.md sim/README.md realapps/README.md training/README.md demos/README.md`. 2. Update the owning agent doc (sections Files, Concepts, Configuration and constants, Invariants and gotchas, How to change it safely, Tests, Drift and open issues): | code | agent doc | @@ -728,11 +776,12 @@ describe("my change (CONTRACT §4)", () => { | `packages/runtime/src/observe/*`, `trace/*` | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) | | `packages/runtime/src/state/*`, `adapters/*` | [runtime/state-and-adapters.md](runtime/state-and-adapters.md) | | `packages/runtime/src/learn/*`, `situation/*` | [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md) and [model-io-contract.md](model-io-contract.md) | -| `packages/runtime/src/decide/*`, actions in `runtime.ts` | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | +| `packages/runtime/src/decide/*`, actions and delivery in `runtime.ts` | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md) | | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/` | [runtime/model-host.md](runtime/model-host.md) and [model-io-contract.md](model-io-contract.md) | | `packages/runtime/src/devtools/*` | [runtime/devtools.md](runtime/devtools.md) | -| package manifests, tsup, vitest, test infrastructure, `scripts/vm.sh`, publishing | [runtime/build-test-release.md](runtime/build-test-release.md) | +| package manifests, lockfile, tsup, vitest, test infrastructure, CI, `scripts/vm.sh`, publishing | [runtime/build-test-release.md](runtime/build-test-release.md) | | `sim/` | [sim.md](sim.md) | +| `realapps/` | [realapps.md](realapps.md) | | `training/` | [training.md](training.md) | | `demos/` | [demos.md](demos.md) | | `jev_local/` | [genclass-model-lineage.md](genclass-model-lineage.md) | @@ -740,10 +789,10 @@ describe("my change (CONTRACT §4)", () => { | status, ownership, open work | [status-and-known-issues.md](status-and-known-issues.md) | | new terms, moved paths, new recipes | [glossary.md](glossary.md), [repo-map.md](repo-map.md), this file | -3. Keep the conventions: pointers `path -> symbol`, no line numbers, "code wins". Update the "Verified against commit … (date)" line of each doc you re-verified. Remove drift rows you fixed; add new drift you found, with evidence. -4. Check every relative link you touched resolves from the linking file (`ls` the target) and that anchors still match headings. -5. Human docs: `packages/runtime/src/types.ts` JSDoc (safe to fix: no model input), `docs/runtime/API.md`, `packages/runtime/README.md`; `packages/runtime/STATUS.md` ("Updated:" line, "State" counts and commands, a batch section, "Deviations from the contract (and why)", "Open issues", example situations); `OPEN_TASKS.md` (Next -> In progress -> Done, with evidence). Fixing `BUILTIN_ACTIONS` descriptions is not a doc fix: it is model input. -6. Cross-workstream requests: add a numbered item to your own NEEDS file (addressee, status OPEN or ASK, evidence as file -> symbol, suggested fix, a regression-test sketch; `demos/NEEDS.md` §1 is the model). The requester flips it to DONE after verifying. Contract changes go to CONTRACT §13 (lead) or STATUS "Deviations" (owner); never diverge silently. +3. Keep the conventions: pointers `path -> symbol`, no line numbers, "code wins", "(unverified)" for what you could not check. Update the header line of each doc you re-verified (branch, commit, date). Remove drift rows you fixed; add new drift you found, with evidence. +4. Check every relative link you touched resolves from the linking file (`ls` the target) and that anchors still match headings. Other docs link to recipes 19 and 25 of this file by anchor: keep those headings. +5. Human docs: `packages/runtime/src/types.ts` JSDoc (safe to fix: no model input), `docs/runtime/API.md`, `packages/runtime/README.md` and the root `README.md`; `packages/runtime/STATUS.md` ("Updated:" line, counts and commands, a batch section, "Deviations", "Open issues", example situations); `docs/runtime/RESULTS.md` (every new measured result, FIR next to every recall); `OPEN_TASKS.md` and `HANDOFF.md` (items moving between Next, In progress, Done, with evidence). Fixing `BUILTIN_ACTIONS` or `TRIGGER_DESCRIPTIONS` text is not a doc fix: it is model input. +6. Cross-workstream requests: add a numbered item to the owning NEEDS file (addressee, status OPEN or ASK, evidence as file -> symbol, suggested fix, a regression-test sketch). The requester flips it to DONE after verifying. Contract changes go to CONTRACT §13 (lead) or STATUS "Deviations" (owner); never diverge silently. 7. Do not edit legacy jev-era docs (`docs/*.md` outside `docs/runtime/` and `docs/agents/`). **See.** [status-and-known-issues.md](status-and-known-issues.md#how-to-change-it-safely), [README.md](README.md). @@ -754,21 +803,114 @@ describe("my change (CONTRACT §4)", () => { **Steps.** 1. **`jev_local/` serialization, packing or calibration:** recipe 13 (TS and Python together, fixtures, retrain). -2. **Training losses or the stream reader** (`jev_local/train/`): add a `LossConfig` field defaulting to off so the v1 path stays bit-identical (`tests/test_train_v2_losses.py`); keep stream determinism and bump `INDEX_VERSION` if the row index layout changes; keep the trainer flags the `training/` launchers and `scripts/launch_run.sh` pass backward compatible. -3. **Extension harness logic** (`extension/src/core`): change `jev_local/harness/*.py` first (the Python is the reference), regenerate `extension/test/fixtures/*_py.json` with `extension/scripts/make_py_fixtures.py` (fix its `ROOT`/`OUT` paths first), run `npm test` in `extension/` on a VM **[ask first]**. `scripts/vm.sh` excludes `/extension/`. +2. **Training losses or the stream reader** (`jev_local/train/`): add a `LossConfig` field defaulting to off so the v1 path stays bit-identical (`tests/test_train_v2_losses.py`); keep stream determinism and bump `INDEX_VERSION` if the row index layout changes; keep the trainer flags the `training/` launchers and `scripts/launch_run.sh` pass backward compatible. The T1 gain head (`--gain-loss`) exists only in the colleague's parent-repo `jev_local`, not here. +3. **Extension harness logic** (`extension/src/core`): change `jev_local/harness/*.py` first, regenerate `extension/test/fixtures/*_py.json` with `extension/scripts/make_py_fixtures.py` (fix its `ROOT`/`OUT` paths first), run `npm test` in `extension/` on a VM **[ask first]**. 4. **Engine/packer/tokenizer bug in the extension:** fix the runtime TS copy first (`packages/runtime/src/model/`); port to the extension only if it is still released. -5. **Extension features and models** (browser-only intents, shipping a new model variant with card sha256 and parity fixtures): follow [extension-and-benchmarks.md](extension-and-benchmarks.md#how-to-change-it-safely) recipes 2 and 3; builds and e2e run on a VM **[ask first]**. -6. **Benchmarks:** benchmax specs need pinned upstream revisions and pure-Python tests; changing `bench/public/jev_published.json` or targets changes frozen hashes (re-freeze before any test read). Never run paid Jev/OpenRouter calls (`scripts/jevbench.py run-jev`) without the user's explicit approval and a funded key; `run-ours`, `score` and `report` score a checkpoint without paid calls. -7. **Ops scripts:** keep `scripts/vm.sh` rsync exclusions and `--delete` semantics; keep `scripts/launch_run.sh` positional arguments (`training/launch_s2.sh` and `launch_final1.sh` depend on them). Anything that calls `az vm create/start` needs the user's go-ahead. +5. **Extension features and models:** [extension-and-benchmarks.md](extension-and-benchmarks.md#how-to-change-it-safely); builds and e2e run on a VM **[ask first]**. +6. **Benchmarks:** benchmax specs need pinned upstream revisions; changing `bench/public/jev_published.json` or targets changes frozen hashes. Never run paid Jev/OpenRouter calls (`scripts/jevbench.py run-jev`) without the user's explicit approval and a funded key. +7. **Ops scripts:** keep `scripts/vm.sh` rsync exclusions and `--delete` semantics; keep `scripts/launch_run.sh` positional arguments (`training/launch_*.sh` depend on them). Anything that calls `az vm create/start` needs the user's go-ahead. -**Tests.** Python tests with markers `model`, `slow`, `macos` (`tests/conftest.py` skips `macos` off macOS) **[ask first]**. +**Tests.** Python tests with markers `model`, `slow`, `macos` **[ask first]**. **See.** [genclass-model-lineage.md](genclass-model-lineage.md#how-to-change-it-safely), [extension-and-benchmarks.md](extension-and-benchmarks.md#how-to-change-it-safely). +## Recipes: realapps and the v2 training pipeline + +### 28. Run and read a never-worse sweep (realapps) + +**Goal.** Check that a runtime build does not change correct apps when its model always answers passive ("never make a correct app worse"), and that the apps are deterministic, using `realapps/src/harness/debug.ts`. Run it after any runtime change on the default path, before a new freeze tag, and before a release. Everything here launches Chromium on a VM: **[ask first]**. + +**Steps.** +1. **Set up a VM slot** (the colleague's flow; [realapps.md](realapps.md#how-to-change-it-safely)): `scripts/vm.sh run real 'cd realapps && npm install --no-audit --no-fund --ignore-scripts && bash corpus/prepare_oss.sh && node build.mjs'`, or on a cluster node `TAG=<tag> realapps/scripts/cluster.sh setup <host>`. Without `RW_RUNTIME_SRC`, `build.mjs` bundles the working-tree runtime (`dist/runtime-tag.txt` = `working-tree`): right for testing an uncommitted change, wrong for data. The README's "Run it" exports `RW_RUNTIME_*` on the Mac, where they never reach the VM build (open finding): set them inside the remote command. +2. **Determinism first:** `node dist/harness/debug.js --det 1-3 [--app a,b]`. For each seed and app: an ideal run (for the pins), then the base run twice with the scenario's exploration. Output: one `MISMATCH app=<name> seed=<s> ok=<a>/<b> decisions=<n>/<m> err=…` line per difference and `determinism: n/N identical`. A nondeterministic app makes every later number meaningless: fix the app (recipe 29) before reading interference. +3. **Never-worse, clean runs:** `node dist/harness/debug.js --interference 1-6 --clean [--app a,b]`. For each seed and app: the ideal run, then the same scenario with `mode: "observe"` and with `mode: "heal"` under the probe's all-passive decider (no forced actions, ε 0). Output per app: `<app> x/n changed (dom a, server b) seed s: steps r/k vs r/k; dom L vs L lines`, then `interference: x/N runs changed by GenClass with an all-passive model`. +4. **With chaos:** the same without `--clean` (seeds 1–3 in the recorded runs). +5. **Read it against the baselines** (all on the 66 apps of fcb8189, situation-v2 runtime; STATUS.md "Never worse", `training/NEEDS.md` 16, RESULTS.md §4): clean 0/396 (seeds 1–6); chaos 3/198 (preact-likes ×2, vanilla-spreadsheet: request-time holds shifting a request by about 25 ms, which re-rolls chaos draws keyed on arrival order); `oss-react-redux-conduit` 0/30 clean and 0/30 chaos; determinism 198/198. Under situation-v1 it was 4/198 and the Conduit never rendered its feed. The corpus now has 91 apps: the 25 newer apps have no recorded sweep, so a full run is 546 clean runs for seeds 1–6, and new mismatches there are not necessarily regressions. +6. **Know what it does not measure** (open findings, [realapps.md](realapps.md#drift-and-open-issues)): it compares only the final visible DOM text and the server content (timestamps ignored). It does not compare requests or bodies, store values, error episodes, input values or run health (a run where both legs failed counts as unchanged), and it never compares observe mode against no runtime at all, so it cannot see damage the default mode itself does. Report it as "same final visible text and server content", and look at `ok=` and step counts in the notes. +7. **Investigate a changed run:** rerun the single scenario in both modes and compare: `node dist/harness/debug.js --app <name> --seed <s> [--clean] --mode observe --steps` and `--mode heal` (prints ideal/base `ok`, network correlation, triggers, diagnoses, final stores and final DOM); `--dom-at t1,t2` prints the ideal DOM at those times; `--twice` checks determinism of that seed. Then reproduce the mechanism in a runtime unit test (recipe 24) and fix the runtime, not the app. +8. **Record** the numbers with the runtime commit and the app list in `packages/runtime/STATUS.md` ("Never worse") and `docs/runtime/RESULTS.md` §4, and note sweep changes in [realapps.md](realapps.md#tests). + +**Tests.** The sweep is the test. Runtime-side companions, local: `packages/runtime/test/no-reorder.test.ts`, `default-mode.test.ts`, `delivery.test.ts`. + +**Gotchas.** `--interference` passes explicit modes, so the library's default mode never affects it; its "heal" leg uses the probe decider, which answers passive when nothing is forced. A crashed Chromium makes its worker fail every remaining seed instantly (open finding in `browser.ts` -> `Runner.run`): a sudden burst of failures is infrastructure, not the runtime. Outputs never go under `~/gcl/<slot>` (`vm.sh` syncs slots with `--delete`). The VM is shared with the colleague's batches: run one sweep at a time. + +**See.** [realapps.md](realapps.md#the-never-worse-and-determinism-sweeps-realappssrcharnessdebugts), [state-and-adapters.md](runtime/state-and-adapters.md#how-to-change-it-safely). + +### 29. Add a realapps app + +**Goal.** Add a real app (written for the corpus, or an open-source front-end) so REAL data and the never-worse sweep cover another framework, library or pattern. Building and checking it launches Chromium: **[ask first]**. + +**Steps.** +1. Read `realapps/apps/README.md` (hard rules, mock backend API, affordances, cost meaning, determinism do/don't, test loop) and two example apps of the same framework. It was written for the colleague's machine (absolute paths, branch `runtime`, "never run node on the Mac"); our run policy differs, but every check needs Chromium anyway. +2. **Written app:** `realapps/apps/<name>/manifest.ts` (default export `AppManifest`, `realapps/src/shared/manifest.ts`) plus source; integrate with one line through `apps/_shared/genclass.ts` (`rt = GenClass.init(window.__GENCLASS_INIT__ ?? {})`, `flag(name, default)`), and either put state in runtime stores (`integration: "stores"`: `rt.atom`, `useGenClassState`, `genclassEnhancer`, `genclass()` for Zustand, `rt.guard`, the `_shared/*-atom.ts` bridges) or observe only (`integration: "observe"`, scored on DOM text). Framework settings (JSX mode, Svelte, Vue compiler) go in `manifest.build`; a new library needs an alias or plugin in `realapps/build.mjs` and a devDependency in `realapps/package.json`. +3. **Open-source app:** an entry in `realapps/corpus/oss.json` (repo, pinned commit, build kind, deps, licence; MIT only per `corpus/LICENSES.md`), the integration a developer would add in `realapps/corpus/patch_oss.py`, a manifest (Conduit apps: `apps/_shared/conduit-manifest.ts` -> `conduitManifest`; set `domWeight: 2` yourself for observe-only), and a build through `corpus/prepare_oss.sh` (or `build.mjs` for kind `esbuild`). +4. **Manifest rules:** the first option of every `variants` entry is the correct/guarded default (clean runs use only first options; a buggy option first corrupts the clean-benign eval case and false-intervention numbers); `affordances` with stable selectors and intent keys; `weights` (error, loading and input fields low or 0); `relations` for derived values (`fields[0]` is the derived field); `external` events for other users; `errorSelector` if not `[role=alert]`. +5. **Determinism:** nothing on real time (IntersectionObserver/ResizeObserver logic, CSS transition/animation events, full page reloads, IndexedDB, FileReader, Workers, BroadcastChannel, EventSource, image/font gating, code splitting). Never read `demos/`. +6. **Hold-out decision:** add it to `TEST_APPS` or set `heldOut` in the manifest if it should be test-only; a framework in `TEST_FRAMEWORKS` (`lit`) is test-only automatically (`realapps/src/harness/scenario.ts` -> `splitOf`). +7. **Check on a VM** **[ask first]**: `node build.mjs <name>`; then for seeds 1–6 `node dist/harness/debug.js --app <name> --seed <s> --show 1 --twice --steps` (ideal/base `ok=true`, steps mostly run, network correlated N/N, triggers present, "first diff -1"); `--traj --show 2` (rows produced, `drops={}`); then `--det 1-6 --app <name>` and `--interference 1-6 --clean --app <name>` plus chaos (recipe 28). +8. **Record:** app counts in `realapps/README.md`, `HANDOFF.md`, `docs/runtime/RESULTS.md` §6 and [realapps.md](realapps.md); per-app sweep numbers. + +**Tests.** No unit tests, no typecheck (esbuild strips types; realapps is not a workspace and has no tsconfig): the debug checks are the tests. + +**Parity / retrain / release.** Data only. Adding an app changes the pool that `buildScenario` draws from (`R.fork("app").pick(apps)` over every manifest `build.mjs` found), so **every seed's app choice can change**. Never sync a new app to a node in the middle of a batch (a resumed batch would draw its remaining seeds from a different pool), record the app list (or its hash) per batch, and use a new seed range for the next batch. The production batches `v2b1`–`v2b3` may or may not include the 25 newest apps, depending on what was synced (unverified). + +**Gotchas.** Do not name a store `auth` (secret-word redaction; use `session`). Apps must not use EventSource (`netapi.ts` sets it undefined). Ideal runs are blind (observe mode, no observers, no decider); do not turn observers on there. realapps imports sim's cost and label code by relative path, so a sim change changes realapps labels too. `realapps` has no lockfile and `prepare_oss.sh` deletes each OSS app's lockfile, so nodes set up at different times can bundle different framework versions (open finding). + +**See.** [realapps.md](realapps.md#how-to-change-it-safely), `realapps/apps/README.md`. + +### 30. Run the v2 training pipeline (teacher, labels, distil, DAgger) + +**Goal.** Produce the first situation-v2 model the way the colleague runs training (`HANDOFF.md` "How to continue", `training/PLAN-v1.md` P1–P5, `training/LOG.md`): T150 teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> export. **Every step is [ask first].** It runs on Azure (`rg-jev-train`, nodes c01–c23 F80 plus `train` and `data`), costs money (PLAN-v1 estimates $3–4k; spend to date ≈ $400), and the colleague is operating the cluster now. Use this recipe to plan, review or hand over the work, not to start it on your own. + +**Preconditions.** +- v2 data collected and its locations listed in `training/NEEDS.md`: SIM gold and unlabeled under `train:/data/sim-out/v2-*` (gz shards + `manifest.json` from `collect.py`), REAL `v2b1`–`v2b3` copied to `train:/data/real-out/` with their eval set. +- Node claims recorded in `training/NEEDS.md` (TRAIN's plan: c01 workbench; teacher on c12–c23; students on c02–c11). +- The HANDOFF Azure rules: `az` calls one at a time, each wrapped in `timeout`; deallocate idle nodes; never delete VMs; the nightly shutdown schedules are disabled for the push and must be re-enabled when it ends. + +**Steps.** +1. **Sync code** to every node: `training/node.sh <host> sync`. Shell scripts assume the nested `jev/<checkout>/training` layout ([training.md](training.md#invariants-and-gotchas)). +2. **Import v2 data** to the workbench and stream roots. `training/import_final.sh` expects a plain `{train,dev,test}.jsonl` SIM dir and cannot read the v2 gz-shard layout (open finding); it also wipes `data/<NAME>` first and tars all of `data/s3`. Until a v2 importer exists: download the shards, verify them against `manifest.json`, decompress train shards into `data/s3/<bucket>/` (the stream reader reads `*.jsonl` and `*.jsonl.zst`, not `.gz`), and build an eval set from test/dev in the layout `eval_sim.sh` expects (`data/<EVALSET>/{test,dev}.jsonl` plus `data/<EVALSET>_t*/test.jsonl`, `data/<EVALSET>_d*/dev.jsonl`; e.g. `simv2e`). REAL train rows get their own bucket; build the REAL eval set with `python3 realapps/scripts/evalset.py <dirs> --out <dir> --splits test` (its default `test,dev,train` puts training rows into the eval set; it also ignores `delivery` rows: open findings). +3. **Decide data filters with the user** before training on them (open findings): rows at `meta.budget == 3200` (SIM and realapps still sample the v1 budget for 40% of trajectories; production never exceeds 2,400 chars); unlabeled rows whose hard `labels.diagnosis` is `expected` (S1 would relabel some of them; dropping that label lets the teacher label it); realapps `delivery` rows labelled `expected` although the user changed the field (`realapps/src/world/diagnose.ts`). +4. **Curriculum replay on v2:** `$PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --seed 6 --workers 72 --p-runtime 0.8` on the workbench; check `stats.json`; shard into `data/s3/cur5/`. +5. **Mixtures:** write new `training/configs/mix_v2_t150.json` and `mix_v2_distill.json` listing `buckets` explicitly (no v2 mixture exists; `mix_t150.json` names the v1 buckets `simA`, `cur4`). Gold dominates; curriculum replay 5–10% (PLAN P4). +6. **Teacher (P1):** `training/launch_student.sh t150-v2a t150 <passes> mix_v2_t150.json "c12 c13 … c23" <INIT>` (ettin-150m pruned base, 8 ranks × 10 threads; `launch_t150.sh` hard-codes `mix_t150.json`). Always pass `INIT` (e.g. `$G/models/base/ettin-150m-v16k` or the stopped v1 `t150-g1` checkpoint on c12 as a warm start, the user's call): without it the script fails under bash 3.2 after it has already pruned on every node, and with `-- extra` args the `--` is taken as `INIT` (open finding). Watch `~/jev/runs/<run>/rank0.out` and `$G/runs/<run>/log.jsonl` on rank 0; check `mixture_plan.json`. +7. **Teacher gate (P2):** copy the servable to the workbench (`training/pull_ckpt.sh t150-v2a <rank-0 node>`), `bash training/eval_sim.sh simv2e t150-v2a`, `$PY training/report.py t150-v2a=out/eval/t150-v2a-simv2e.json --mode=kind`. Check clear-case recall first: if a 150M teacher is also near 40% argmax on clear rows, the limit is the situation information, not model size, and the fix is in SIM/CORE (recipe 6), not in more training. +8. **Teacher labels (P3):** with the teacher's dev-fitted calibration, `training/label_cluster.sh c01 t150-v2a out/cal/t150-v2a-simv2e.json data/unlab/<set> <bucket> "<nodes>" [PROCS] [QIDS]`, or `$PY training/label_teacher.py --ckpt models/t150-v2a --in <shard> --out <out> --calibration <cal>` per shard. `label_cluster.sh` is untested (LOG) and has open defects: it touches the done marker even when labelling failed, cannot read `.jsonl.gz` shards, has no split filter (only `train` shards may be labelled into a training bucket) and does not gather outputs back to the workbench. Check per-shard line counts against the inputs before trusting `.label-<bucket>-done`, and gather the shards yourself. PLAN P3 labels a prioritised 5–10M-row subset (rows near the gate plus a uniform sample), not all 50M. +9. **Distil students (P4):** `training/launch_student.sh r17-v2 r17 <passes> mix_v2_distill.json "<nodes>" $G/runs/r17-s1c/ckpt` and the same for `r32` (final rounds restart from the stage-1c weights, as in LOG). New run names mean new stream caches and outputs. +10. **Evaluate, calibrate, export:** `final_post.sh` is wired to the v1 eval set `simAe` and does not stop on failures (open finding), so run the steps yourself on the rank-0 node or c01: `rm -f out/records/r17-v2__*` (cached logits are keyed by name only), `EVAL_THREADS=12 bash training/eval_sim.sh simv2e r17-v2`, the REAL eval set via `$PY training/eval_runtime.py --ckpt models/r17-v2 --data <real eval dir> …`, then `$PY training/export_runtime.py --ckpt models/r17-v2 --out out/export-r17-v2 --name genclass-runtime-r17 --version 0.1.0 --calibration out/cal/r17-v2-simv2e.json --data-rows data/simv2e/dev.jsonl,data/cur5/dev.jsonl --n-per-file 60 --threads 24`, then deliver and validate (recipe 18 steps 7–8). +11. **DAgger (P5):** export the students, run SIM on-policy generation with the export (`SEED_BASE=22000000000 sim/scripts/cluster/orchestrate.sh run <RUN> onpolicy:<export dir on the nodes> <ROWS> <nodes…>`; 1–5M rows per round), collect, import as a new bucket, retrain the students (refresh the teacher every second round). On-policy runs act in heal mode (open finding: guard-mode numbers on those rows do not describe guard deployment); evaluate DAgger and REAL rows for clear-case recall separately (PLAN-v1). +12. **Report every round** in `training/EVAL.md`, `training/LOG.md` (what ran where, cost) and `docs/runtime/RESULTS.md` (§1, §6, §7): action/diagnosis accuracy, guard/heal FIR, precision, recall and clear-case recall, ECE, per trigger and per budget, SIM held-out (incl. held-out features) and REAL eval; always FIR next to recall (HANDOFF). +13. **Ship:** only when the gates hold (guard FIR ≤ 0.1% on all held-out sets): recipe 20 (model package), recipe 22 (demos rerun), recipe 19 (`@genclass/runtime@0.1.0`). Deallocate every node, release claims in `training/NEEDS.md`, and re-enable the shutdown schedules (command in HANDOFF). + +**Tests.** `training/tests/test_curriculum.py` after curriculum changes, `test_export_runtime.py` after export changes; `validate.mjs` and runtime parity on every export. + +**Parity / retrain / release.** Train only on rows from one runtime tag (`situation-v2`); never mix v1 rows (phase A/B, `gold-r1x`, `cur1`–`cur4`, REAL pilots) into v2 training buckets. A runtime text change during the pipeline restarts it (recipe 6). + +**Gotchas.** Rank 0 must hold `--init-from`. A bucket named in a mixture but missing on disk is dropped silently. `label_teacher.py` keeps gold labels unless `--overwrite`. The eval logit cache, the shared `data/s3` tar and the done markers can each make a failed step look finished: verify outputs, not markers. The T1 expected-gain side track (`t1_relabel.py`, `eval_gain.py`, `t1_post.sh`) is optional and also wired to `simAe`. + +**See.** [training.md](training.md#how-to-change-it-safely), [sim.md](sim.md#9-cluster-runs-simscriptscluster), [realapps.md](realapps.md#how-it-feeds-training), [genclass-model-lineage.md](genclass-model-lineage.md). + +## Drift and open issues + +Open defects found by review at b435acb that change how the recipes above must be followed (details and suggested fixes in the subsystem docs' "Drift and open issues"): + +| area | defect | recipes affected | +|---|---|---| +| runtime, model text | F2 fact prints raw text of redacted fields (`situation/content.ts` -> `contentFacts`); leaf-based redactor misses numbers/arrays under secret containers (`util.ts` -> `isSensitivePath`); "…nor the value when #X started" unchecked; every successful POST counted as a create; 502 treated as "not processed" | 2, 6, 25 | +| runtime, delivery | discard mark drops later fresh chained writes for 10 s and survives `pause()`/observe; discard is a no-op on redux/zustand but recorded as a drop; observe mode still waits up to 100 ms for a conflicting body; background delivery decisions are always dropped (delivery standing questions never answered in observe); `defer` can stall a channel 20 s; held WS/SSE messages dispatched after `close()`; XHR listeners see `currentTarget === null` | 4, 5, 7, 10, 25 | +| sim / realapps | budget weights still sample the v1 3,200-char budget 40%; unlabeled SIM rows keep `expected` diagnoses S1 would relabel; realapps manifests say `situation-v1`; interference sweep compares only final DOM text and server content; evalset includes train rows and ignores `delivery`; 25 apps never swept | 6, 16, 17, 28, 29, 30 | +| training scripts | `import_final.sh` cannot import v2 shards; `label_cluster.sh` marks done unconditionally, no gz, no split filter, no gather; `final_post.sh` hard-wired to `simAe`; eval logit cache keyed by name; `launch_student.sh` breaks without `INIT`; `rt.py` diverges from the frozen renderer in several common cases | 18, 30 | +| docs | `HANDOFF.md` still says guard is the default; CONTRACT documents the old redaction rule | 5, 19, 20 | + +Other notes: +- `RELEASE.md` (repo root, added alongside this doc refresh) is the release procedure recipes 19 and 20 summarise; where they disagree, it and the code win. +- The test example in recipe 24 is illustrative; the exact late-revert conditions are in `atoms.test.ts` / `delivery.test.ts` (unverified as written). +- `status-and-known-issues.md` may still describe 654d822 in places; prefer HANDOFF and the subsystem docs for v2 status. + ## Related docs - [README.md](README.md) (index of agent docs), [overview.md](overview.md), [repo-map.md](repo-map.md), [glossary.md](glossary.md), [../../AGENTS.md](../../AGENTS.md) - [status-and-known-issues.md](status-and-known-issues.md), [model-io-contract.md](model-io-contract.md) - Runtime: [public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), [observe-and-trace.md](runtime/observe-and-trace.md), [state-and-adapters.md](runtime/state-and-adapters.md), [learn-situation-triage.md](runtime/learn-situation-triage.md), [decide-policy-actions.md](runtime/decide-policy-actions.md), [model-host.md](runtime/model-host.md), [devtools.md](runtime/devtools.md), [build-test-release.md](runtime/build-test-release.md) -- Other subsystems: [sim.md](sim.md), [training.md](training.md), [demos.md](demos.md), [genclass-model-lineage.md](genclass-model-lineage.md), [extension-and-benchmarks.md](extension-and-benchmarks.md) -- Human sources: [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md), [`docs/runtime/API.md`](../runtime/API.md), [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md), [`OPEN_TASKS.md`](../../OPEN_TASKS.md) +- Other subsystems: [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md), [demos.md](demos.md), [genclass-model-lineage.md](genclass-model-lineage.md), [extension-and-benchmarks.md](extension-and-benchmarks.md) +- Human sources: [`HANDOFF.md`](../../HANDOFF.md), [`docs/runtime/CONTRACT.md`](../runtime/CONTRACT.md), [`docs/runtime/API.md`](../runtime/API.md), [`docs/runtime/RESULTS.md`](../runtime/RESULTS.md), [`packages/runtime/STATUS.md`](../../packages/runtime/STATUS.md), [`OPEN_TASKS.md`](../../OPEN_TASKS.md), [`RELEASE.md`](../../RELEASE.md), `realapps/README.md`, `training/PLAN-v1.md` diff --git a/docs/agents/realapps.md b/docs/agents/realapps.md new file mode 100644 index 00000000..f7db4b8b --- /dev/null +++ b/docs/agents/realapps.md @@ -0,0 +1,404 @@ +# realapps/: real-browser training corpus and never-worse harness + +> **Scope:** `realapps/**`: `README.md`, `EXAMPLES.md`, `package.json`, `build.mjs`, `.gitignore`, `apps/**` (the +> app catalogue, `apps/README.md` authoring guide, `apps/_shared/**`), `corpus/**` (open-source apps), `src/world/**` +> (in-page world), `src/harness/**` (Node side), `src/shared/**`, `scripts/**`. Also the REAL sections of +> `training/NEEDS.md` (items 13–16) and the realapps parts of [RESULTS.md](../runtime/RESULTS.md) §4/§6 and +> `packages/runtime/STATUS.md` ("Never worse"). +> **Read this when:** you need to know what a REAL (`meta.source = "realapps"`) training row is and how it was +> labelled; you add or change an app, a harness rule, a cost term or a diagnosis rule; you rerun the determinism or +> interference ("never worse") sweeps after a runtime change; or you plan a real-browser generation batch. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. + +## TL;DR + +- `realapps/` (owner: REAL, the colleague's workstream) runs **real web apps built with real frameworks** in + **headless Chromium** (Playwright) with the **real `@genclass/runtime` bundled from source**, on fully virtualised + time and an in-page mock backend with chaos. It labels sampled runtime decisions by **counterfactual outcome** with + the **sim's own cost weights and label rule** (it imports them from `sim/src`), and writes **CONTRACT-D rows** in + the same shape as SIM rows. It closes the sim-to-real gap (React's MessageChannel scheduler, Vue/Svelte microtask + flushes, TanStack Query/SWR dedupe, XHR libraries, Redux middleware, the apps' own bugs). +- **Corpus at b435acb: 91 apps** (77 written for the corpus + 14 open-source RealWorld "Conduit" front-ends), + 23 distinct `framework` values. `realapps/README.md` and `HANDOFF.md` still say 66 apps and + `docs/runtime/RESULTS.md` §6 says "66 → ~96"; 25 apps were added after fcb8189 (24 in d73d20c, `preact-mappins` in + 74f17c0; see Drift). +- It is also the runtime's **"never make a correct app worse" harness**: `debug.js --interference` compares observe + mode with heal mode under an all-passive decider. Situation-v2 result (STATUS.md): **0/396 clean runs changed** + over all 66 apps then in the corpus, seeds 1–6; 3/198 changed under chaos (an open item per RESULTS.md §4). Under + situation-v1 the gothinkster React/Redux Conduit never rendered its feed. +- **Nothing here is in CI or the root workspaces, there are no tests and no tsconfig.** Every real step needs + Chromium, and generation runs on Azure F80 nodes. Under our run policy: **ask the user before running anything + in `realapps/`** that launches Chromium (`debug.js`, `gen.js`, `chromium_probe.mjs`), clones the OSS corpus + (`corpus/prepare_oss.sh`), or touches a VM (`scripts/vm.sh`, `realapps/scripts/cluster.sh`, `node_setup.sh`). +- Data status (from `training/NEEDS.md` 16, not verifiable from here): v2 production batches `v2b1`/`v2b2`/`v2b3` on + c01/c10/c11 (30k trajectories each, target ≥ 500k gold; [HANDOFF.md](../../HANDOFF.md)/[RESULTS.md](../runtime/RESULTS.md): about 495k), to be copied to `train:/data/real-out/`. No training + code in the repo reads realapps output by name yet; it is consumed as generic CONTRACT-D batches (see + [training.md](training.md)). + +## Files + +| Path | What it is | +|---|---| +| `realapps/README.md` | The design document: corpus, integration, determinism, labels, row kinds, splits, run commands, v1 pilot numbers, throughput, scaling plan, known limitations. Pilot sections describe situation-v1. | +| `realapps/EXAMPLES.md` | 13 audited rows from the v1 pilot `pilot4` (situation, labels, per-action and per-future costs, cost parts, verdict). Not re-audited on v2 (unverified). | +| `realapps/package.json` | `@genclass/realapps` 0.0.0, private. Scripts `build` (`node build.mjs`), `gen` (`node dist/harness/gen.js`), `build:runtime`. devDependencies: `playwright`/`@playwright/test` 1.63.0, esbuild, esbuild-svelte, and every framework/library the apps use (React 19, Redux/RTK, Zustand, Vue 3, Pinia, Solid, Preact, Lit, jQuery, MobX, TanStack Query, SWR, axios, Alpine, Jotai, Valtio, XState, effector, nanostores, redux-saga, ky, ofetch, wretch, superagent, React Router 7, vue-router, Mithril, Hyperapp, petite-vue, htm, RxJS, Backbone, Knockout...). | +| `realapps/.gitignore` | `node_modules/`, `dist/`, `src/harness/apps.gen.ts` (generated by `build.mjs`). | +| `realapps/build.mjs` | esbuild build of the world IIFE (`dist/world.js`), the harness entries (`dist/harness/{gen,worker,debug}.js`; it would also pick up `audit`/`evalset` entries, which do not exist), the manifest registry (`dist/manifests.mjs`) and every app whose manifest has no `build.vite`/`build.prebuilt` (`dist/apps/<name>/{index.html,bundle.js}`): the 77 written apps plus the 3 OSS apps of build kind `esbuild` (`oss-react-redux-conduit`, `oss-rtk-conduit`, `oss-mobx-conduit`, bundled from their `$RW_OSS_DIR` checkout). Writes `dist/runtime-tag.txt`. | +| `realapps/apps/<name>/manifest.ts` + source | One app: an `AppManifest` default export (Node side) plus the app source (entry = `manifest.entry`). OSS apps have only a manifest; their source is cloned by `corpus/prepare_oss.sh`. | +| `realapps/apps/README.md` | Authoring guide for app-writing agents: hard rules, mock backend API, affordance options, cost meaning, determinism do/don't, test loop. Written for the colleague's setup (absolute Mac path, branch `runtime`, "never run node on the Mac"). | +| `realapps/apps/_shared/genclass.ts` | The app's one-line integration: `rt = GenClass.init(window.__GENCLASS_INIT__ ?? {})` and `flag(name, default)` reading `window.__RW_VARIANT`. | +| `realapps/apps/_shared/{vue,svelte,solid,preact,lit}-atom.ts`, `lit-toast.ts`, `hyperapp-guard.ts`, `react-genclass-reducer.ts`, `w3-http.ts` | Bridges from framework state to runtime atoms/guards, and small shared helpers. | +| `realapps/apps/_shared/conduit-manifest.ts` | `conduitManifest(...)` and `conduitAffordances`: the shared manifest builder for the 14 OSS Conduit apps (title, domain, server `{ base: "/api", ext: ["conduit"] }`, affordances, external events, `errorSelector`, `sessionMs`, `startMs`). It does **not** set `domWeight`; each observe-only OSS manifest sets `domWeight: 2` itself. | +| `realapps/apps/_shared/onnx-stub.ts` | Stub aliased for `onnxruntime-web*`: the harness never loads a model. | +| `realapps/corpus/oss.json` | The 14 open-source apps: name, repo, pinned commit, build kind, deps, licence. | +| `realapps/corpus/LICENSES.md` | Licences of the OSS apps (all MIT per the README). | +| `realapps/corpus/prepare_oss.sh` | On a VM: clone each OSS app at its commit into `$RW_OSS_DIR` (default `~/gcl/real-cache/oss`), install deps and toolchain, apply `patch_oss.py`, build into `dist/apps/<name>/`. Build kinds: `esbuild` (left to `build.mjs`), `vite-*` (`vite.oss.config.mjs`), `angular`/`elm`/`ember`/`purescript` (own compiler then `rebundle.mjs`), `webcomponents`, `angularjs` (`build_angularjs.mjs`). Clones from GitHub. | +| `realapps/corpus/patch_oss.py` | The GenClass integration a developer would add to each OSS app (Redux apps: `genclassEnhancer`; others: one init import, observe-only). | +| `realapps/corpus/{rebundle.mjs,build_angularjs.mjs,vite.oss.config.mjs}` | OSS build helpers. | +| `realapps/src/world/index.ts` | The in-page world entry (an IIFE injected as an init script before any page script): installs the loop, network, server, user and probe; clears storage/cookies and applies the manifest's preloads; sets `window.__GENCLASS_INIT__` and `window.__RW_VARIANT`; prevents link/submit navigation; exposes `window.__RW.start()`, which schedules external events, WebSocket drops and the ask probes (`runtime.situation("ask")`, base run only) and runs the session. | +| `realapps/src/world/loop.ts` | Virtual time: timers, rAF, idle callbacks, MessageChannel, `scheduler.postTask`, `AbortSignal.timeout`, `Date`, `performance.now`, seeded randomness; real-macrotask yielding until native async work settles. | +| `realapps/src/world/net.ts`, `netapi.ts` | In-page `fetch` (a `Response` subclass from `makeResponseClass`), `XMLHttpRequest`, `WebSocket` on virtual time, with chaos draws. `netapi.ts` sets `window.EventSource = undefined`, so the runtime's v2 `eventsource` observer never installs. | +| `realapps/src/world/server.ts`, `ext/conduit.ts` | The mock backend (collections, CRUD, versions/409, `Idempotency-Key` replay, relative actions, bulk, docs, counters, auth with rotating refresh tokens, cart echoes, replica lag, live WebSocket topics) and the RealWorld API extension. | +| `realapps/src/world/user.ts` | The scripted user (user-event style untrusted events), intent pinning to the ideal run. | +| `realapps/src/world/probe.ts` | `Probe`: the recording `DecisionProvider` (forced actions by decision index, ε-exploration, simulated model latency, answers with confidence 1), runtime hooks, the store-snapshot plugin, DOM text snapshots, error episodes/writes, and the in-page diagnosis call. | +| `realapps/src/world/diagnose.ts` | In-page diagnosis rules from harness knowledge (scripted intents, server failure records, user writes, retries); handles situation-v2's `delivery` trigger. | +| `realapps/src/harness/scenario.ts` | `buildScenario(seed, apps, opts)`: app + flags, scripted session, chaos profile, external events, wording vocabulary, budget, exploration, split. Holds `TEST_FRAMEWORKS`, `TEST_APPS`, `TEST_PATTERNS`, `splitOf`. | +| `realapps/src/harness/trajectory.ts` | `generateTrajectory`: ideal run, base run, counterfactuals, prefix check, cost, labels, the four row kinds. Holds `PASSIVE` (from the bundled runtime), `RUNTIME_TAG`, `TRIGGER_W`, `OBSERVE`, `runConfig`. | +| `realapps/src/harness/cost.ts` | `runCost`, `states`, `serverDist`, `relationBroken`; `BLOCKED = 1.0`. Mirrors `sim/src/oracle/cost.ts`. | +| `realapps/src/harness/labels.ts` | `finishDiagnosis` (Node-side diagnosis finishing with the manifest's relations), `duplicateKeys`. | +| `realapps/src/harness/browser.ts` | `Runner`: one headless Chromium per worker, a fresh page per run, contexts recycled every 60 runs, apps served from memory at `ORIGIN = "https://app.example.com"`. | +| `realapps/src/harness/gen.ts`, `worker.ts` | The resumable generator (worker pool, per-split JSONL append, `done.txt`, `stats.json`, `manifest.json`) and its worker process. | +| `realapps/src/harness/debug.ts` | Inspection CLI: one scenario, `--twice`, `--traj`, `--force k:action`, `--det` (determinism sweep), `--interference` (never-worse sweep). | +| `realapps/src/shared/{manifest,types,routes}.ts` | `AppManifest`/`Affordance`/`Relation` types; `RunConfig`, `RunResult`, `ServerSpec`, `Step`...; `endpointsOf`. | +| `realapps/scripts/analyze.py` | Batch stats plus comparison with `sim/samples/stats-final-a.json` (the v1 sim final-A stats; `--sim`, `--json`). | +| `realapps/scripts/evalset.py` | Builds `<out>/real_eval.jsonl` plus a `manifest.json`, the unambiguous real-app eval set. | +| `realapps/scripts/examples.py` | Pretty-prints rows for audits (EXAMPLES.md drafts). | +| `realapps/scripts/chromium_probe.mjs` | Measures the Chromium event-loop facts the loop relies on (e.g. `Response.json()` settles in microtasks; tee'd `clone()` needs real tasks). | +| `realapps/scripts/node_setup.sh` | On a VM (idempotent): Node v22.22.0 linux-x64, `npm install --ignore-scripts`, Playwright's `chromium_headless_shell` (+ `install-deps` via `sudo -n` when libs are missing), pinned runtime from `~/gcl/real-cache/runtime/current`, `prepare_oss.sh`, `build.mjs`. | +| `realapps/scripts/cluster.sh` | Mac-side ssh/rsync helper for Azure nodes: `sync` (rsync `realapps/`, `packages/runtime/`, `sim/` to `HOST:~/gcl/real`, plus the `git archive $TAG` runtime export when `TAG` is set), `setup` (sync + `node_setup.sh`), `run` (detached `gen.js` into `~/gcl/real-out/<name>`; workers default to 3/4 of `nproc`), `status`, `stop`. Reads `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure` (the colleague's machine). | + +## Concepts and data structures + +- **App manifest** (`realapps/src/shared/manifest.ts` -> `AppManifest`): everything the harness knows about an app. + Key fields: `framework`, `libs`, `domain`, `entry`, `integration: "stores" | "observe"`, `server` (the + `ServerSpec` the in-page backend serves), `variants` (feature flags; **first option = correct default**), + `affordances` (what the scripted user can do), `external` (other users' events), `weights` (per store or + store.field divergence weight), `relations` (derived-field invariants; `fields[0]` is the derived field), + `domRoot` (default `body`), `errorSelector` (default `[role=alert]`), `domWeight` (default 1), `heldOut`, `source` + (OSS origin), `startMs`, `localStorage`/`cookies` preloads, `sessionMs` (default `[20000, 60000]`), `build` + (jsx/jsxMode/svelte/vueCompiler/vite/prebuilt...). The app code never sees the manifest except the server spec and + the chosen flags. +- **Affordance** (`Affordance`): `id`, `kind` (`StepKind`: click, dblclick, type, clear, select, check, key, hover), + CSS `sel` (`>>>` pierces shadow roots), `text`, `nth`, `values`, `weight`, `mode` (`replace` | `accumulate`), + `key`/`intent` (intent key), `clear`, `enter`, `dblclickP`, `impatientP`, `burst`, `after`, `waitMs`, `then`, + `sameNth`, `followOnly`, `resets`, `requires`, `requiresText`. +- **Integration kinds.** `stores`: the app puts state in runtime stores (`rt.atom`, `useGenClassState`, + `genclassEnhancer` for Redux/RTK, `genclass()` for Zustand, `rt.guard` for Pinia/MobX, atom bridges for + Vue/Svelte/Solid/Preact/Lit). `observe`: no stores (17 manifests at b435acb: the jQuery apps, `superagent-fleet` + and the non-Redux OSS Conduits); they still produce request, failure, stall and error rows, and their divergence is + measured on visible DOM text. "Observe-only" here is an integration style; the harness still runs these apps with + `mode: "heal"`. +- **Scenario** (`realapps/src/harness/scenario.ts` -> `Scenario`): one seed determines app, flags (`variant`, + `patterns`), chaos level (`calm | normal | flaky | degraded | storm`), `NetProfile`, scripted `steps`, `external` + events, `warmup`/`tUser`/`tEnd`, situation `budget` (3,200 / 2,000 / 1,000 chars at 40/30/30%), simulated + `modelMs` (6–25 ms), exploration ε (0 / 0.08 / 0.2 weighted 4/3/2; 0 on clean runs), wording `vocab`, `split`, + `epoch`, `askTimes` (1–3 probes). 8% of scenarios are **clean** (first flag options, calm network, no accidental + clicks). +- **Runs of one trajectory.** *Ideal* (zero latency, no chaos, no accidental clicks, exactly-once; runtime installed + but blind: `mode: "observe"`, `model: false`, `decider: null`, all observers off; the probe's hooks and plugin + still record stores). *Base* (real runtime, exploration, records every + decision). *Counterfactuals* (one action forced at decision `k`). +- **DecisionRec** (`realapps/src/shared/types.ts`): `k`, `t`, `trigger`, `actions`, `chosen`, `explored`, `fp` + (hash of trigger, state and questions, used for the prefix check), `subject`, `diagnosis`, `diagWhy`, + `diagTrace`, plus the `state`/`questions` the runtime handed the decider. +- **Intent pins** (`RunConfig.pins`): the ideal run records the identity words of the list item each step acted + on; other runs click the visible element whose item matches best (score ≥ 0.6), otherwise the step is skipped and + charged as a blocked intent. +- **Row** (`realapps/src/harness/trajectory.ts` -> `Row`): CONTRACT-D `{id, split, family, state, questions, + labels, meta}`. `state`/`questions` are exactly what the runtime handed the decider. Ids: + `real-<app>-<seed>-d<k>` (decision), `-a<i>` (ask), `-u<k>` (unlabeled), `-s<k>` (diagnosis-only). + `family = "<program family>/<trigger>"` (or `/ask`). + +## How it works + +### Build + +1. `node build.mjs [app1,app2]` (in `realapps/`) writes `src/harness/apps.gen.ts` (an import of every + `apps/*/manifest.ts` whose directory does not start with `_`). +2. It bundles `src/world/index.ts` into `dist/world.js` (IIFE) and the harness into `dist/harness/*.js` (ESM, Node + 22, `playwright` external). Alias `@rt/questions` -> `<RT>/situation/questions.ts`, so both the in-page probe + and `trajectory.ts` read the **runtime's own `PASSIVE` map** (the only symbol imported through it). +3. Every app without `build.vite`/`build.prebuilt` (the 77 written apps and the 3 `esbuild`-kind OSS apps, the + latter from their `$RW_OSS_DIR` checkout) is bundled by esbuild with aliases + `@genclass/runtime[/react|/redux|/zustand]` -> `<RT>/index.ts` / `<RT>/adapters/*.ts`, `@realapps/genclass` -> + `apps/_shared/genclass.ts`, `onnxruntime-web*` -> the stub, plus framework settings (JSX mode, Svelte plugin, Vue + template compiler). The other 11 OSS apps (`build.vite` or `build.prebuilt`) are built by + `corpus/prepare_oss.sh` and only reported by `build.mjs` ("NOT BUILT YET" when missing). +4. **Runtime pinning:** `RT = $RW_RUNTIME_SRC ?? ../packages/runtime/src` and `RT_TAG = $RW_RUNTIME_TAG ?? + "working-tree"`. For data, `RW_RUNTIME_SRC` is a `git archive <tag> packages/runtime/src` export + (`cluster.sh sync` with `TAG=...` does this into `~/gcl/real-cache/runtime/<tag>/src` and writes + `~/gcl/real-cache/runtime/current`; `node_setup.sh` exports both variables from it). The tag goes to + `dist/runtime-tag.txt` and from there (`trajectory.ts` -> `RUNTIME_TAG`, `"unknown"` when the file is missing) + into every row's `meta.runtime`. At b435acb, `packages/runtime/src` differs from `situation-v2` only by our + default-mode commit f3636b2, which realapps overrides with explicit modes; a working-tree build still stamps + `working-tree`, not `situation-v2`. + +### One run (`realapps/src/harness/browser.ts` -> `Runner.run`) + +- A fresh page in a shared context (viewport 1280×900, `en-US`, `UTC`, reduced motion, service workers blocked). + Chromium flags include `--host-resolver-rules=MAP * ~NOTFOUND` (except localhost), so every external host fails + DNS and images/fonts never load on real time. +- Init script: `window.__RW_CFG = <RunConfig>` followed by the world bundle. Requests to + `https://app.example.com/**` are fulfilled from `dist/apps/<app>/` (SPA fallback to `index.html`). +- After `load`, `window.__RW.start()` runs the whole session on virtual time and returns a JSON `RunResult` + (decisions, snapshots, network log, server state, error episodes, uncaught errors, steps run/skipped, asks). + Timeout 180 s per run. +- **Runtime options for non-ideal runs** (`realapps/src/world/index.ts`): `mode: cfg.mode ?? "heal"`, the probe's + decider, `report: "silent"`, `triage: "salient"`, `observe: OBSERVE` (fetch, xhr, user, errors, nav, storage, + websocket, timers, `untrustedEvents: true`; `perf: false` because long-task timing is real time), + `policy: { thresholds: { report: 0, guard: 0.5, heal: 0.5 }, holdBudgetMs: 1e9, maxActionsPerMinute: 1e9, + requireDiagnosis: false }`, `historySize: 500`, `situation: { budget }`, hooks, a probe plugin, and `vocabulary` + when the scenario rewords. The mode is always explicit, so **our default-mode change (f3636b2, default `observe`) + does not change any realapps run.** +- **Virtual time** (`realapps/src/world/loop.ts`): tasks run in (virtual time, phase, seq) order; user input runs in + a later phase than other tasks due at the same instant; after each task the loop yields real macrotasks through a + captured real `MessageChannel` until tracked native async work (body reads, stream reads) settles. Mock responses + clone without tee-ing. `ResizeObserver`, `IntersectionObserver` and `PerformanceObserver` are inert. +- **Randomness:** every draw for a request is keyed by (seed, future salt, request identity, occurrence), so forcing + an action at one decision never shifts unrelated draws. Item ids are content-derived. + +### One trajectory (`realapps/src/harness/trajectory.ts` -> `generateTrajectory`) + +1. `buildScenario(seed, pool, {clean?})`. Test-split trajectories are kept with probability `testKeep` (otherwise + `skipped = "test-subsample"`). +2. **Ideal run**; its states define the target and its `pins` define the user's intents. +3. **Base run** with exploration (ε on decisions whose in-page diagnosis is not `expected`, ε/4 elsewhere) and ask + probes (`runtime.situation("ask")`). +4. **Decision points:** `pickPoints` samples up to `maxPoints` (6) decisions with ≥ 2 actions, weighted by + `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2; anything + else, including `delivery`, 1) × 1.5 for a non-`expected` diagnosis. +5. For each point and each applicable action: a counterfactual with the base run's explored choices before `k`, + the action forced at `k`, passive after `k`, stopping at `min(tEnd, t_k + W.finalMs)`. Future 0 reuses the base + run as the passive counterfactual when the base run chose passive at `k` and explored nothing from `k` on. Futures 1..K-1 (K = `futures`, 3) run + only when some action beats passive by more than 0.05 in future 0 (`adaptive`); they re-seed draws after `t_k` + and rerun the ideal when external events fall after `t_k`. +6. **Prefix check:** the counterfactual's decisions `0..k` must have the base run's `fp` values, or the point is + dropped (`drops["prefix-mismatch"]`). Other drops: `ideal-error`, `base-error`, `cf-error`, + `ideal-future-error`. +7. **Cost** (`realapps/src/harness/cost.ts` -> `runCost`), sim's weights `W` term by term: divergence area over + `W.horizonMs`, final client divergence, server damage (content compare, timestamps and ids volatile), relation + violation area and final, shown errors (store apps: writes that put an error message into a store, counted when + proposed; observe apps: appearances of the `errorSelector` UI), uncaught errors, wasted requests, pending user + latency, plus the + realapps-only **blocked intents** term (`BLOCKED = 1.0` per user step whose element never appeared beyond the + ideal run's). Client state = registered stores (manifest weights) plus visible DOM text lines × `domWeight`. +8. **Action label:** sim's `actionLabel(costs, passive)` (tier premiums, tie pinning, `p ∝ exp(−gap/τ)`, + `τ = 0.1 + SE`), then sim's `transformQuestions` (option shuffles/drops, paraphrases). +9. **Diagnosis:** in-page rules (`diagnose.ts`) finished in Node by `finishDiagnosis` (relations, duplicate + entities, `delivery` handled like `mutation` for `rel-check`). The label is written only when the diagnosis is in + the row's (possibly reduced) vocabulary; otherwise counted in `notes` (`diagnosis-not-in-vocab`, + `diagnosis-uncorrelated`). `meta.diag_why`/`diag_trace` say which rule fired. +10. **Ask rows** from the base run's probes, using sim's `askQuestions` generators with exact answers. +11. **Unlabeled rows:** up to `unlabeled` (40) other base decisions with ≥ 2 actions; gold diagnosis only, + `meta.unlabeled: true`, `base_choice`; action left to the teacher. +12. **Diagnosis-only rows:** up to 3 single-action decisions with a diagnosis in the vocabulary. + +### Generation (`realapps/src/harness/gen.ts`) + +- Forks `--workers` worker processes (one Chromium each); seeds `seed .. seed+trajectories-1` minus those in + `done.txt`. Rows append to `{train,dev,test}.jsonl` and `unlabeled-{train,dev,test}.jsonl`; each finished seed + appends to `done.txt`. `stats.json` and `manifest.json` refresh every 30 s and at the end. Rerunning the same + command resumes. +- `stats.json`: per trigger (n, passive-best count, best actions, diagnoses, mean harm of non-passive actions on + passive-best points), per app, drops, notes, skipped, run counts and times, first 50 errors. +- `manifest.json` (for TRAIN, `training/NEEDS.md` 11): seeds, counts, file descriptions, `on_policy: false`, + held-out frameworks/apps/patterns, app list with OSS repo/commit/licence, options. Its `runtime` field is a + hard-coded string (see Drift). + +### Splits (`realapps/src/harness/scenario.ts` -> `splitOf`) + +- **test:** framework in `TEST_FRAMEWORKS` (`lit`), app in `TEST_APPS` (`swr-status`, `alpine-tasks`, + `xhr-autocomplete`), manifest `heldOut` (only `oss-rtk-conduit`), or a pattern in `TEST_PATTERNS` + (`react-search/guard:reqid`, `vue-editor/save:serialize`, `zustand-board/push:version-check`). +- **dev:** `hashAll("realapps-dev-v1", app, ...patterns) % 100 < 4`. +- **train:** everything else. Splits are per trajectory, so all rows of a trajectory share one split. + +### How it feeds training + +- Rows are CONTRACT-D like SIM's, with the same label semantics; TRAIN imports REAL batches the same way as SIM + batches (see [training.md](training.md); no repo script names `real-out` or `realapps`, so the exact import path + is unverified). Gold rows train the student/teacher; unlabeled rows get teacher labels (per NEEDS/HANDOFF; not + in code here). `real_eval.jsonl` rows keep their original split, and `evalset.py` reads `test,dev,train` unless + `--splits` narrows it, so an eval row can also be a row of some batch's `train.jsonl` (whether TRAIN excludes + eval ids is unverified). +- `meta` fields beyond the row: `source = "realapps"`, `seed`, `app`, `framework`, `libs`, `integration`, `domain`, + `program_family`, `family`, `patterns`, `chaos`, `clean`, `budget`, `runtime`, `browser = "chromium-headless"`, + `oss`; decision rows add `trigger`, `decision`, `t`, `explored_before`, `best`, `passive_best`, `passive`, + `costs`, `cost_futures`, `futures`, `adjusted`, `se`, `non_passive_mass`, `cost_parts`, `tiers`, `diagnosis`, + `diag_why`, `diag_trace`, `subject`, `transform`; ask rows add `kinds`; unlabeled rows add `unlabeled`, + `base_choice`; diagnosis-only rows add `diagnosis_only`. +- **Eval set** (`realapps/scripts/evalset.py <dirs> --out <dir> [--splits test,dev]`; default splits + `test,dev,train`): cases `stale-overwrite`, `duplicate-submit`, `clean-benign`, `benign-salient`, `genuine-break`, + each with `meta.eval_case` and `meta.eval_expect`, capped per case (`--per-case`, default 2000), original split + kept. It keeps its own `PASSIVE` copy (includes `delivery`). + +### The never-worse and determinism sweeps (`realapps/src/harness/debug.ts`) + +- `--det A-B [--app a,b]`: per seed and app, an ideal run (for the pins) then the base run twice with the + scenario's exploration; identical iff both runs are `ok` and decision `fp`s, snapshots, network log and server + state hash equal. Prints `determinism: n/N identical` (no `--clean` option here). +- `--interference A-B [--clean] [--app ...]`: per seed and app, an ideal run (for the pins), then the same scenario + with `mode: "observe"` and with + `mode: "heal"` under the all-passive base decider (no forced actions, explore 0); compares final DOM and server + content. Prints `interference: x/N runs changed by GenClass with an all-passive model`. This is the runtime's + "never make a correct app worse" check cited in `docs/runtime/RESULTS.md` §4 and `packages/runtime/STATUS.md`. +- Single-scenario modes (`--app`, `--seed`, `--clean`): default (ideal + base summary, triggers, diagnoses, network + correlation), `--twice`, `--traj` (runs `generateTrajectory` with `testKeep: 1`), `--show N`, `--steps`, + `--dom-at t1,t2`, `--force K:action` (DOM over time: ideal vs base vs forced), `--mode <mode>` for the base run. + +## Configuration and constants + +| Name | Where | Value / meaning | +|---|---|---| +| `RW_RUNTIME_SRC`, `RW_RUNTIME_TAG` | env, `realapps/build.mjs` | Runtime source and tag bundled into apps; default `../packages/runtime/src` and `working-tree`. | +| `RW_OSS_DIR` | env, `build.mjs`, `prepare_oss.sh` | OSS checkouts; default `~/gcl/real-cache/oss`. | +| `RW_PORT`, `RW_OPTS` | env, `gen.ts` -> `worker.ts` | Port (default 8790; passed to `new Runner(port)`, which does not use it: apps are served by request interception) and JSON `GenOptions` for workers. | +| `gen.js` flags | `realapps/src/harness/gen.ts` | `--out` (required), `--seed` (1), `--trajectories` (100), `--workers` (CPUs − 2), `--port`, `--max-points` (6), `--futures` (3), `--adaptive` (true), `--test-keep` (0.5), `--apps a,b`, `--clean`, `--unlabeled` (40). | +| `TRIGGER_W` | `trajectory.ts` | Decision-point sampling weights (above). | +| `OBSERVE` | `trajectory.ts` | Runtime observers for non-ideal runs (perf off, `untrustedEvents` on). | +| `BLOCKED` | `cost.ts` | 1.0 per blocked user intent. | +| `W` | `sim/src/oracle/cost.ts` | All other cost weights, `finalMs`, `horizonMs` (imported). | +| `TEST_FRAMEWORKS`, `TEST_APPS`, `TEST_PATTERNS` | `scenario.ts` | Held-out lists (above). | +| `ORIGIN` | `browser.ts` | `https://app.example.com`. | +| Context recycle | `browser.ts` -> `Runner.context` | New browser context every 60 runs. | +| Policy for non-ideal runs | `src/world/index.ts` | thresholds report 0 / guard 0.5 / heal 0.5, hold budget and action rate effectively unlimited, `requireDiagnosis: false`. | +| `epoch` | `scenario.ts` | `Date.UTC(2026, 3, 1, 9, 0, 0) + (seed % 1000)` days: the virtual wall clock. | +| Node / Chromium on VMs | `scripts/node_setup.sh` | Node v22.22.0, Playwright 1.63.0 `chromium_headless_shell`. | + +Throughput (README, measured on `train`, 64 vCPU): 28 workers ≈ 3.3 trajectories/s; 56 workers ≈ 4.6/s (≈ 29 gold + +37 unlabeled rows/s); expected F80 (≈ 70 workers) ≈ 35–40 gold rows/s, ≈ 130k gold + 170k unlabeled per node-hour. + +## Invariants and gotchas + +- **Never read `demos/`** from `realapps/` (independent evaluation; `HANDOFF.md`). No realapps code references it. +- **Flag order matters:** the first option of every `variants` entry is the correct/guarded default; clean runs use + only first options. Adding a buggy option first silently corrupts the clean-benign eval case and false-intervention + numbers. +- **Determinism is the contract.** Anything on real time breaks the prefix check: `IntersectionObserver`/ + `ResizeObserver` logic, CSS transition/animation events, full page reloads, IndexedDB, FileReader, Workers, + BroadcastChannel, EventSource, image/font gating, code splitting (`apps/README.md`). Run `--det` after any app + or world change. +- **Pin the runtime for data.** A `working-tree` build stamps `meta.runtime = "working-tree"`; production data must + be built from a `git archive` of a frozen tag (`situation-v2` = 6e5e86e). Rows from different runtime tags must not + be mixed: v1 pilot rows (`pilot4`, `pilot-all`) do not match the v2 situation format. +- **realapps depends on sim source by relative import** (`sim/src/oracle/cost.js`, `sim/src/rng.js`, + `sim/src/run/transform.js`, `sim/src/ask/questions.js`; vocabulary mirrored from `sim/src/world/scenario.ts`). + A change there changes realapps labels without touching `realapps/`. `cluster.sh sync` therefore rsyncs `sim/` + and `packages/runtime/` too. +- **Passive actions come from the bundled runtime's `PASSIVE`;** a trigger missing there (or mapped to `""`, as + `ask` is) falls back to the first offered action. `realapps/scripts/analyze.py` and `evalset.py` keep their own + copies of the map (both include `delivery`); update them if the runtime's map changes. +- **Secret-word redaction:** `apps/README.md` says not to name a store `auth` (use `session`). At b435acb the + runtime (`packages/runtime/src/util.ts` -> `isSensitivePath`) judges object fields by their leaf name, so + `auth.loading` or `auth.user.name` survive and only secret leaves (`auth.token`, `form.password`) or opaque + credential-like strings under `auth`/`session`/`cookie` are redacted; a string or number atom named `auth` is + still redacted whole. Keep following the guide's advice. +- **The ideal run's `ALL_OFF` (`src/world/index.ts`) and the other runs' `OBSERVE` (`trajectory.ts`) predate the v2 + `eventsource` observer** (neither lists it, so the + runtime's default "on" applies). It never installs because `netapi.ts` sets `window.EventSource = undefined`; + apps must not use EventSource anyway (`apps/README.md`). +- **Outputs never go under `~/gcl/<slot>`:** `scripts/vm.sh` syncs slots with `--delete`. Use `~/gcl/real-out/`. +- **The DOM term is coarse** (line multisets): an empty page and a page with different data can look alike. Store + weights and blocked intents carry most of the signal for store apps. +- **Observe-only OSS apps weigh the DOM ×2 via their own manifests** (each of the 12 sets `domWeight: 2`; + `conduitManifest` does not, so the two store-integrated OSS Conduits use 1); the jQuery and `superagent-fleet` + observe-only apps do not set it and use 1, although the README says 2 for all observe-only apps. +- **Ideal runs are blind but installed:** observe mode, every observer off, no decider. Do not turn observers on + there; the ideal must not depend on the runtime. +- **`debug.js --interference` compares explicit modes**, so it is unaffected by the library's default mode. Its + "heal" leg uses the probe decider, which answers passive when nothing is forced and ε = 0. + +## How to change it safely + +- **Add an app:** follow `realapps/apps/README.md` (manifest + source under `apps/<name>/`, integration via + `apps/_shared/genclass.ts`, flags with correct-first options, weights for error/loading/input fields, relations for + derived values). Then (with the user's OK, on a VM or a machine with Chromium): `node build.mjs <name>`, + `node dist/harness/debug.js --app <name> --seed 1 --show 1 --twice --steps` for seeds 1–6 (ideal/base `ok=true`, + network correlated N/N, `first diff -1`), and `--traj` (no drops). Decide whether it belongs in a test-only list. +- **Change the harness (world, cost, labels, scenario):** rerun `--det 1-3` and `--interference 1-3 --clean` over + all apps and a short pilot plus `analyze.py`; compare passive-best shares with the previous batch. Never change + label semantics in a way that diverges from `sim/src/oracle/cost.ts` without changing SIM too: the two sources are + trained together. +- **Runtime changed (new tag):** export the tag (`TAG=<tag> realapps/scripts/cluster.sh sync|setup <host>`), + rebuild, rerun determinism and interference sweeps and a pilot, re-audit `EXAMPLES.md`, and fix the hard-coded + `runtime` string in `gen.ts` -> `manifest`. +- **Generate:** `TAG=situation-v2 realapps/scripts/cluster.sh setup <host>`, then + `realapps/scripts/cluster.sh run <host> <batch> <first seed> <trajectories> [workers] [extra gen args]`, `status`, + `stop`, and deallocate the node. Use disjoint seed ranges per batch (1,000,000 apart). All of this is Azure work: + **ask the user first**, and remember the colleague is operating the cluster (c01, c10, c11 are REAL's). +- **Typecheck:** there is no `realapps/tsconfig.json` and realapps is not a root workspace, so `npm run typecheck` + and CI do not cover it; esbuild strips types without checking. Review type changes by reading. + +## Tests + +- **No unit tests and no CI coverage.** `realapps/` has no `test/` directory; `.github/workflows/ci.yml` builds and + tests `@genclass/runtime` only. +- Quality gates are the sweeps, run on a VM with Chromium (none run by us; all need the user's OK): + - determinism: `node dist/harness/debug.js --det 1-5 [--app a,b]`; + - never worse: `node dist/harness/debug.js --interference 1-3 --clean` (and without `--clean` for chaos); + - prefix check: `drops["prefix-mismatch"]` in `stats.json` should be 0; + - per-row audit: `python3 realapps/scripts/examples.py <dir> ...` (as in `EXAMPLES.md`). +- The runtime side has a regression test derived from this harness's v1 finding: + `packages/runtime/test/no-reorder.test.ts` (the realworld promise middleware through `genclassEnhancer` gives the + same dispatches and state in guard/heal as in observe). +- Recorded results: + - v1 pilot `pilot-all` (README, NEEDS 15): 500 trajectories, 66 apps, 3,403 gold + 3,789 unlabeled, 0 drops; + determinism 198/198; interference 4/198 clean runs changed (2 apps); eval set 366 rows. + - v1 `pilot4`: 230 trajectories, 26 apps, 1,654 gold + 2,325 unlabeled; audited in `EXAMPLES.md`; eval 213 rows. + - v2 (NEEDS 16): determinism 132/132, interference 0/132; `v2-pilot` 400 trajectories, 2,519 gold (135 `delivery`), + 2,397 unlabeled, 0 drops. + - v2 runtime batch 5 (STATUS.md): all 66 apps, seeds 1–6, clean: 0/396 changed; chaos seeds 1–3: 3/198 changed + (preact-likes ×2, vanilla-spreadsheet), from request-time holds shifting a request about 25 ms; Conduit 0/30; + determinism 198/198. + +## Drift and open issues + +- **App count.** 91 app manifests at b435acb against 66 at fcb8189: 24 added in d73d20c (e.g. `alpine-podcast`, + `react-ci`, `rtk-payroll`, `svelte-auction`, `vue-wiki`, `zustand-sequences`, `lit-dispatch`) and `preact-mappins` + in 74f17c0. The framework count stayed at 23. `realapps/README.md`, + [HANDOFF.md](../../HANDOFF.md) and the STATUS.md sweep say 66; [RESULTS.md](../runtime/RESULTS.md) §6 says "66 → ~96". The v2 sweeps above were over 66 + apps; whether v2b1–v2b3 include the new 25 depends on what was synced to the nodes (unverified). +- **`gen.ts` -> `manifest` hard-codes `runtime: "situation-v1 (packages/runtime/src bundled from source)"`.** v2 + batch `manifest.json` files therefore say situation-v1. The per-row `meta.runtime` is correct (read from + `dist/runtime-tag.txt`). Trust `meta.runtime`. +- **README is half v1:** the "Pilot" and "Runtime findings" sections, `EXAMPLES.md` and the `Run it` example + (`RW_RUNTIME_TAG=situation-v1`) describe situation-v1; the v2 results live only in `training/NEEDS.md` 16 and + STATUS.md. `analyze.py` compares against `sim/samples/stats-final-a.json` (v1 sim stats). +- **README says observe-only apps use DOM weight 2;** only the 12 observe-only OSS Conduit manifests set + `domWeight: 2`. +- **`TRIGGER_W` has no `delivery` entry** (weight 1 by default), so v2 `delivery` decisions are sampled like + mutations. Possibly intended; not documented. +- **Chaos interference 3/198** under v2 (request-time holds of ~25 ms change chaos draws keyed on arrival order): + recorded in STATUS.md and called an open item in [RESULTS.md](../runtime/RESULTS.md) §4. +- **`apps/README.md` is written for the colleague's machine** (absolute path `/Users/meharkhanna/...`, branch + `runtime`, "never run node on the Mac"). Our run policy differs (light local checks are fine), but every + realapps run needs Chromium or a VM, so ask first anyway. +- **Ingestion path into training is not in code:** no script under `training/` references `real-out` or + `realapps`; TRAIN's import of REAL batches is described only in `training/NEEDS.md` (unverified). +- **Data location and progress** of v2b1–v2b3 (c01/c10/c11 `~/gcl/real-out/`) and the v2 eval set ("rebuilt on v2" + per RESULTS.md) cannot be checked from the repo. +- **Known limitations (README):** untrusted synthetic input, some diagnoses unobservable from the situation, rare + stalls (need ≥ 5 latency samples per endpoint), constant `app.example.com` host in WebSocket URLs. + +## Related docs + +- [sim.md](sim.md): the simulator whose cost weights, label rule, question transform and ask generators realapps + imports; same CONTRACT-D rows. +- [training.md](training.md): how SIM/REAL batches are imported, the meta fields TRAIN reads, teacher labelling. +- [model-io-contract.md](model-io-contract.md): CONTRACT-D row format and the situation the rows contain. +- [runtime/](runtime/): the runtime being exercised (modes, `delivery` trigger, policy, hooks, `untrustedEvents`). +- [status-and-known-issues.md](status-and-known-issues.md): project status, model and npm state. +- [demos.md](demos.md): the independent evaluation realapps must never read. +- [extension-and-benchmarks.md](extension-and-benchmarks.md): `scripts/vm.sh`, which the README's run commands use. +- Source docs: `realapps/README.md`, `realapps/apps/README.md`, `realapps/EXAMPLES.md`, `training/NEEDS.md` 13–16, + [RESULTS.md](../runtime/RESULTS.md) §4 and §6, [HANDOFF.md](../../HANDOFF.md), `packages/runtime/STATUS.md` ("Never worse"). diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index 4b934dea..86395ed7 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -1,8 +1,8 @@ # Repository map (GenClass-lib) -> **Scope:** every tracked path (`git ls-files`: 749 files at 654d822), plus the generated and ignored paths that show up in a working copy. +> **Scope:** every tracked path (`git ls-files`: 1,082 files at b435acb, up from 749 at 654d822), plus the generated and ignored paths that show up in a working copy. > **Read this when:** you need to find where a file, symbol, constant, CLI command, env var or config key lives; decide whether a directory matters for `@genclass/runtime`; or want to know which paths are generated, ignored or too large to read in full. -> **Source of truth:** `git ls-files` and the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. Conventions: code pointers are `path/from/repo/root` -> `symbol`. Relevance to the runtime library: @@ -10,42 +10,62 @@ Conventions: code pointers are `path/from/repo/root` -> `symbol`. Relevance to t - **supporting**: builds, trains, tests or demonstrates the runtime. - **legacy**: the earlier GenClass project (Python model, Chrome extension, benchmarks). `docs/runtime/CONTRACT.md` §1 says: "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." Some legacy files are still reference implementations for the runtime; the notes say which. -Workstream names (lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW) and their edit rights are defined in [status-and-known-issues.md](status-and-known-issues.md) ("Workstreams and ownership"). The index of all agent docs is [README.md](README.md); how the parts fit together is in [overview.md](overview.md). Ground rules and what you may run: [../../AGENTS.md](../../AGENTS.md); terms: [glossary.md](glossary.md); step-by-step procedures: [playbooks.md](playbooks.md). +Workstream names (lead, CORE, MODEL, UI, SIM, REAL, DEMOS, TRAIN, REVIEW) and their edit rights are described in [status-and-known-issues.md](status-and-known-issues.md) ("Workstreams and ownership"); REAL (`realapps/`) is new since 654d822, see [glossary.md](glossary.md). The index of all agent docs is [README.md](README.md); how the parts fit together is in [overview.md](overview.md). Ground rules and what you may run: [../../AGENTS.md](../../AGENTS.md); terms: [glossary.md](glossary.md); step-by-step procedures: [playbooks.md](playbooks.md). + +**What changed since 654d822** (the commit the first version of this map described): `git log --oneline 654d822..b435acb` lists the NaN fix (ad24804), runtime batch 4 (fcd1e68: decisions at the network boundary), the `realapps/` corpus (fcb8189), runtime batch 5 and the `situation-v2` freeze (6e5e86e), `HANDOFF.md` and the v2 curriculum port (d73d20c), `docs/runtime/RESULTS.md` (74f17c0), then our three commits on `mvp-v2`: agent docs (7dab2b3), default mode `observe` (f3636b2) and CI plus the committed root lockfile (b435acb). Use `git diff --stat 654d822 b435acb -- <path>` to see what changed in a path. ## 1. Top-level directories | dir | tracked files | what | owner / workstream | doc | relevance | |---|---|---|---|---|---| -| `packages/runtime/` | 143 | `@genclass/runtime` 0.1.0-alpha.0, the npm library: `src/` (55), `test/` (79), `bin/genclass-runtime.mjs` CLI, package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | -| `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | -| `sim/` | 59 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows | SIM | [sim.md](sim.md) | supporting | -| `training/` | 43 | Python curriculum generator, runtime-text port (`curriculum/rt.py`), eval, ONNX export, Azure launch scripts for the R17/R32 runtime model | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | -| `demos/` | 132 | `@genclass/demos`: Vite site with six demo apps, a Service Worker chaos backend, Playwright trial eval and shipped results | DEMOS | [demos.md](demos.md) | supporting | -| `scripts/` | 26 | Ops scripts. `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | -| `jev_local/` | 136 | Python package `jev-local` 0.1.0: Jev-wire API, encoder engine, trainer, voice harness, benchmark harnesses | none of the runtime workstreams (pre-runtime GenClass) | [genclass-model-lineage.md](genclass-model-lineage.md) | legacy. `serialize.py`, `confidence.py`, `engine/encoder/{tokenize_pack,calibrate,heads}.py` are the parity references for `packages/runtime/src/model`; `train/` is used by `training/` | +| `packages/runtime/` | 154 | `@genclass/runtime` 0.1.0-alpha.0, the npm library: `src/` (61), `test/` (84), `bin/genclass-runtime.mjs` CLI (mode 100755 since b435acb), package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Lead (us, on `mvp-v2`): `test/default-mode.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished (npm 404). No situation-v2 model exists yet | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | +| `sim/` | 106 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows. Now 46 feature combinators, 115 domains, S1/S2 labels, gold / unlabeled / on-policy row modes, Azure cluster scripts, separability analysis | SIM | [sim.md](sim.md) | supporting | +| `realapps/` | 230 | `@genclass/realapps` (private, **not** a root workspace): 91 real web apps (77 written + 14 open-source Conduit front-ends) run in headless Chromium with the real runtime; counterfactual labels like the sim; the "never worse" interference and determinism sweeps | REAL | [realapps.md](realapps.md) | supporting | +| `training/` | 61 | Python curriculum generator, runtime-text port (`curriculum/rt.py`, frozen at `situation-v2`), eval, ONNX export, Azure launch scripts for R17/R32/R68 students and the T150 teacher, teacher labelling, T1 expected-gain scripts | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | +| `demos/` | 133 | `@genclass/demos`: Vite site with six demo apps, a Service Worker chaos backend, Playwright trial eval and shipped results (still the v0.1 model) | DEMOS | [demos.md](demos.md) | supporting | +| `scripts/` | 26 | Ops scripts (unchanged since 654d822). `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | +| `.github/` | 1 | `workflows/ci.yml`: the only CI (added in b435acb) | lead (us) | [runtime/build-test-release.md](runtime/build-test-release.md) | core | +| `jev_local/` | 136 | Python package `jev-local` 0.1.0: Jev-wire API, encoder engine, trainer, voice harness, benchmark harnesses | none of the runtime workstreams (pre-runtime GenClass) | [genclass-model-lineage.md](genclass-model-lineage.md) | legacy. `serialize.py`, `confidence.py`, `engine/encoder/{tokenize_pack,calibrate,heads}.py` are the parity references for `packages/runtime/src/model`; `train/` is used by `training/` (the gain head the T1 scripts need exists only in the parent repo on the nodes, not here) | | `extension/` | 104 | GenClass 0.1.0 MV3 voice-control Chrome extension. Its own npm package, not a workspace | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy. `src/core/{engine,packer,tokenizer,serialize,pyutil}.js` are the ancestors of the runtime's `src/model/*.ts` | | `bench/` | 5 | jevbench and benchmax pre-registrations, `public/` target and exclusion JSON | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | | `tests/` | 74 | pytest suites for `jev_local` (71 `test_*.py`, `conftest.py`, 2 fixtures) | none of the runtime workstreams | [genclass-model-lineage.md](genclass-model-lineage.md) ("Tests") | legacy | | `results/` | 3 | Benchmark write-ups (CU head-to-head, jevbench M0, Z-68m notes) | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | -| `docs/` | 15 tracked | `docs/runtime/` (3: CONTRACT, API, ARCHITECTURE: the runtime's human docs), `docs/benchmax-research/` (5), 7 legacy jev-local docs. `docs/agents/` (these docs) is untracked at 654d822 | `docs/runtime/CONTRACT.md`: lead. Rest: not recorded / legacy | [status-and-known-issues.md](status-and-known-issues.md) (doc drift tables) | `docs/runtime/`: core. Rest: legacy | +| `docs/` | 36 | `docs/runtime/` (4: CONTRACT, API, ARCHITECTURE, RESULTS: the runtime's human docs), `docs/agents/` (20 tracked: these docs; `realapps.md` is new, not yet committed), `docs/benchmax-research/` (5), 7 legacy jev-local docs | `docs/runtime/CONTRACT.md`: lead. `docs/agents/**`: lead (us). Rest: not recorded / legacy | [status-and-known-issues.md](status-and-known-issues.md) (doc drift tables) | `docs/runtime/`, `docs/agents/`: core. Rest: legacy | -Root files: +Root files (13): | file | what | relevance | |---|---|---| -| `package.json` | private `genclass-lib`, `"type": "module"`, workspaces `packages/*`, `sim`, `demos`; scripts `build` and `test` (runtime only), `typecheck` (all workspaces); devDep `typescript ~5.9.3`; `engines.node >=20` | core | +| `package.json` | private `genclass-lib`, `"type": "module"`, workspaces `packages/*`, `sim`, `demos` (not `realapps`, not `extension`, not `training/ortweb`); scripts `build` and `test` (runtime only), `typecheck` (all workspaces); devDep `typescript ~5.9.3`; `engines.node >=20` | core | +| `package-lock.json` | root lockfile, **committed in b435acb** (3,203 lines); CI runs `npm ci` from it. Update it only with a deliberate `npm install` | core | | `tsconfig.base.json` | shared TypeScript compiler options | core | | `.gitignore` | ignore rules (see [section 4](#4-generated-and-ignored-paths)) | core | -| `README.md` | repo landing page: status banner, install, repo map | core | -| `OPEN_TASKS.md` | project-level status: done, in progress, next, needs the user, known risks (owner inferred: lead) | core | +| `README.md` | repo landing page: status banner, install, repo map. Says `observe` is the default (Status box and Modes table) | core | +| [`HANDOFF.md`](../../HANDOFF.md) | the colleague's "read this first" for continuing sessions (d73d20c): current state table, repo map, hard rules for the 8 GB Mac and Azure, how to continue. Still says "guard (default)" | core | +| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | project-level status: done, in progress, next, needs the user, known risks (owner inferred: lead). Describes the situation-v2 pipeline under In progress/Next, items 1-14, CI listed as done | core | +| [`RELEASE.md`](../../RELEASE.md) | release procedure for `@genclass/runtime` and `@genclass/runtime-model` (new, not yet committed) | core | | `LICENSE` | Apache-2.0 | core | | `pyproject.toml` | Python package `jev-local` 0.1.0 (Python >=3.12,<3.14), console script `jev-local`, pytest config | legacy | | `BENCHMARKS.md` | public summary of GenClass 0.1 benchmark results | legacy | -| [`AGENTS.md`](../../AGENTS.md), [`CLAUDE.md`](../../CLAUDE.md) | agent entry points (untracked at 654d822, written with these docs) | — | +| [`AGENTS.md`](../../AGENTS.md), [`CLAUDE.md`](../../CLAUDE.md) | agent entry points (7dab2b3) | — | ## 2. Tree -One line per file for the code that matters most; one line per directory (with tracked-file counts) for legacy areas. Descriptions are summaries; the linked docs have the detail. +One line per file for the code that matters most; one line per directory (with tracked-file counts) for legacy areas. Descriptions are summaries; the linked docs have the detail. "(new)" marks files added since 654d822. + +### Repo root extras + +```text +.github/workflows/ci.yml (new) CI "@genclass/runtime: typecheck, build, unit tests": push to main/runtime/mvp/mvp-v2, + pull_request, workflow_dispatch; ubuntu-latest, Node 22, ONNXRUNTIME_NODE_INSTALL=skip, + npm ci, typecheck -w, build -w, vitest excluding test/browser/** and review-perf, + then review-perf alone with --retry=2 (NODE_OPTIONS=--expose-gc) +HANDOFF.md (new) colleague's continuation guide (state, rules, next steps) +package-lock.json (new) root lockfile for npm ci +docs/runtime/RESULTS.md (new) model stages compared, R17 vs R32, why round 1 was timid, never-worse design + comparison, demo baseline, data volume, training log summary +``` ### `packages/runtime/` package root (9 files) @@ -58,38 +78,44 @@ packages/runtime/ tsconfig.json typecheck project (include src only: tests are never type-checked) tsup.config.ts 6 ESM entries (index, adapters/react|redux|zustand, devtools/index, worker) -> dist/; .d.ts for all but worker vitest.config.ts unit tests: test/**/*.test.ts, excludes test/browser/**, env node, testTimeout 20000 - README.md npm package README - STATUS.md CORE status: test state, headless recipe, trigger table, example situations, deviations, open issues + README.md npm package README (observe default; notes no model is published yet) + STATUS.md CORE status: test state (41 files / 346 tests before default-mode.test.ts), never-worse sweep, + batch 4/5 notes, headless recipe, trigger table, example situations, deviations, open issues UI-NEEDS.md UI -> CORE request log (partly stale) LICENSE Apache-2.0 bin/genclass-runtime.mjs CLI (Node >= 20, no deps): fetch-model <dir> [--from] [--variant q8|fp16|all] [--force] [--quiet], info <dir> ``` -### `packages/runtime/src/` (55 files) +### `packages/runtime/src/` (61 files) ```text packages/runtime/src/ index.ts public facade: GenClass (init/runtime/destroy), createRuntime, re-exports; killSwitch, makeHost, NATIVE_FETCH, ALL_OFF - runtime.ts RuntimeImpl: wires every layer; installObservers, trigger (triage), onDecision, settled points, - rollback/revertChain/resync, explain, undo, destroy - types.ts every public and shared type: options, Runtime, RuntimeEvents, plugins, and the "model seam" - (JevState, Question, Answer, EvaluateRequest, DecisionProvider) mirrored by sim/src/types.ts + runtime.ts RuntimeImpl: wires every layer; default mode (o.mode ?? "observe"); installObservers, trigger (triage), + runDelivery (delivery gate), observeWrite / gateMutation, covered, dropFilter / writtenOver (discard + marks), noteResponse, onChannel, markWrites (F9), onDecision, settled points, rollback/revertChain/resync, + explain, undo, destroy + types.ts every public and shared type: options (PolicyOptions.holdWrites, observe.untrustedEvents), Runtime, + RuntimeEvents, plugins, and the "model seam" (JevState, Question, Answer, EvaluateRequest, DecisionProvider) + mirrored by sim/src/types.ts errors.ts GenClassUnavailableError clock.ts browserClock (timers captured at module load, afterTask) util.ts hashing (fnv1a, stableStringify, hashValue), URL signatures (normalizePath, isIdSegment, - requestSignature), formatting (secs, rel, fmtNum, truncate), redaction (defaultRedact) + requestSignature), formatting (secs, rel, fmtNum, truncate), redaction (defaultRedact, isSensitivePath: leaf-based) adapters/react.ts @genclass/runtime/react: GenClassProvider, useGenClass, useGenClassState, useAtom, useGenClassDecisions/Interventions/Status adapters/redux.ts @genclass/runtime/redux: genclassEnhancer, GENCLASS_REPLACE adapters/zustand.ts @genclass/runtime/zustand: genclass middleware - decide/decider.ts DeciderQueue: one request at a time, priority, 32-item cap, answer cache, PROVIDER_TIMEOUT_MS, fail-open - decide/exec.ts types only: Controller, ActionEffect, NetHost, TriggerOpts, EndOpts - decide/policy.ts policyConfig (thresholds), modeAllows, permittedActions, gate (summed-mass rule), RateLimiter, holdBudget + decide/decider.ts DeciderQueue: one request at a time, priority, 32-item cap, answer cache, stale drop, PROVIDER_TIMEOUT_MS, fail-open + decide/exec.ts types only: Controller, ActionEffect, NetHost (+ deliver, noteResponse), TriggerOpts, EndOpts + decide/policy.ts policyConfig (thresholds, holdWrites), modeAllows, permittedActions, gate (summed-mass rule), RateLimiter, holdBudget decide/report.ts Reporter (console sink, 60 s dedupe), interventionLine, detectionLine, decisionLine - devtools/index.ts @genclass/runtime/devtools: mountDevtools, Devtools class (shadow-root overlay, 4 views) + devtools/index.ts @genclass/runtime/devtools: mountDevtools, Devtools class (shadow-root overlay, 4 views; mode labels + "Observe (default)" / "Guard (opt-in)" / "Heal (experimental)") devtools/ui.ts DOM helper h(), icons, formatting, report-wording templates, activity-event classification devtools/css.ts CSS string with light/dark tokens, applied inside the shadow root learn/baselines.ts Baselines: per-signature latency, outcomes, failure streak, error EWMA, rate, identity gaps (fetch/XHR) - learn/profiles.ts Profiles: transition profiles and rarity check (MIN_COMPLETIONS 20, RARE 0.01) + learn/profiles.ts Profiles: transition profiles and rarity check (MIN_COMPLETIONS 20, RARE 0.01); also feeds the delivery prediction + learn/cadence.ts (new) Cadence, CadenceInfo: learned polling schedule or debounce per request signature (fact F6) model/README.md MODEL's internal notes: card format, load steps, parity results, measured latency and sizes model/host.ts createModelHost, ModelHost, DEFAULT_MODEL_BASE_URL; worker or inline transport, preload, queue, timeouts, WASM retry model/backend.ts ModelBackend: load phases (card, download, runtime, session, warmup) and evaluate; WARMUP_STATE @@ -105,69 +131,87 @@ packages/runtime/src/ model/errors.ts GenClassModelError + 11 subclasses (ModelNotReadyError, MaxTokensExceededError, ...), serializeError model/hash.ts pure-TS sha1/sha256; sha256Hex prefers WebCrypto model/index.ts internal barrel; nothing in src/ imports it; only test/browser/build.mjs's fallback build uses it - observe/fetch.ts installFetch: fetch ops, request identity, request gate, failure gate, stall controller - observe/xhr.ts installXHR: XMLHttpRequest.prototype patch; request gate (XHR failures/stalls are detection-only) + observe/fetch.ts installFetch: fetch ops, request identity, request gate, failure gate, stall controller; host.deliver for responses + observe/xhr.ts installXHR: XMLHttpRequest.prototype patch; request gate; delivery gate for async responses (wraps completion + listeners); XHR failures/stalls are detection-only + observe/messages.ts (new) MessageGate (per-channel ordered queue, re-dispatch of released messages), MsgHost, messageSummary + observe/websocket.ts installWebSocket: WebSocket subclass with a MessageGate; reports channel down/up + observe/eventsource.ts (new) installEventSource: EventSource subclass with a MessageGate (observer name "eventsource") observe/cache.ts ResponseCache (GET cache, coalescing table), makeResponse/blockedResponse (x-genclass header) - observe/dom-user.ts installDomUser (capture-phase user actions), describeElement, ignoredEvent (data-genclass-ignore) + observe/dom-user.ts installDomUser (capture-phase user actions; synthetic events only with observe.untrustedEvents), + describeElement, ignoredEvent (data-genclass-ignore); UserAction.clicks (MouseEvent.detail) observe/timers.ts installTimers: setTimeout/setInterval wrappers that carry the ambient op - observe/websocket.ts installWebSocket: WebSocket subclass observe/nav.ts installNav: history pushState/replaceState, popstate, hashchange observe/storage.ts installStorage: Storage.prototype setItem/removeItem/clear observe/errors.ts installErrors: error and unhandledrejection listeners observe/perf.ts installPerf: longtask PerformanceObserver situation/build.ts buildSituation: subject sentence, sections, applicable actions (builtinApplicable), questions, salience - situation/facts.ts computeFacts per trigger, orderFacts, MAX_FACTS (12) + situation/facts.ts computeFacts per trigger (incl. deliveryFacts), orderFacts, predictedText, MAX_FACTS (12) + situation/conflicts.ts (new) predictedWrites, matchFields, newerConflict, pendingConflict, conflictsOn, newerSameSignature, PENDING_WINDOW_MS + situation/content.ts (new) response/write content vs store: indexBody, parseJsonBody, analyzeBody, compareField, contentFacts (F1-F3), + pendingRevertFacts, createdIds, rywFacts (read-your-writes), RYW_WINDOW_MS + situation/evidence.ts (new) markFacts (F9), cadenceFact (F6), scopeFacts and commitAmbiguity (F5), failureOf, repeatEvidence (F7) situation/describe.ts opPhrase, opLabel, userPhrase, statusText, eventLine - situation/questions.ts BUILTIN_ACTIONS, TRIGGER_ACTIONS, PASSIVE, DEFAULT_DIAGNOSES, buildQuestions, COMPACT_QUESTIONS_BUDGET - situation/serialize.ts toJevState, sectionLimits, stateChars, STATE_CHAR_BUDGET / COMPACT_BUDGET / MIN_BUDGET - situation/env.ts SitEnv (read-only runtime view for situation code), SubjectSpec, ReqMeta, FailureInfo, Violation - state/hub.ts StoreHub: atom/guard/adapter stores, mutation pipeline, field versions and logs, late revert, snapshots - state/fields.ts flatten, diffLeaves, deltaOf, changeText, patchValue, cloneValue; MAX_DEPTH, MAX_FIELDS_PER_STORE - state/invariants.ts InvariantMiner (9 templates; LEARN_AFTER, LEARN_AFTER_NONNULL), expect() predicates - trace/ops.ts OpRegistry, OpRec + situation/questions.ts BUILTIN_ACTIONS, TRIGGER_ACTIONS (incl. delivery: deliver/discard/defer), PASSIVE, DEFAULT_DIAGNOSES, + buildQuestions, COMPACT_QUESTIONS_BUDGET + situation/serialize.ts toJevState, sectionLimits, stateChars, STATE_CHAR_BUDGET (2400) / COMPACT_BUDGET / MIN_BUDGET + situation/env.ts SitEnv (read-only runtime view for situation code), SubjectSpec (incl. DeliverySpec), ReqMeta, FailureInfo, Violation + state/hub.ts StoreHub: atom/guard/adapter stores, mutation pipeline (holdWrites opt-in), propose -> applyFilter (delivery + drop filter), flushQueue, field versions, stale marks and logs, late revert, snapshots + state/fields.ts flatten, diffLeaves, deltaOf, changeText, stringDiff (diff-centred previews), patchValue, cloneValue; + MAX_DEPTH, MAX_FIELDS_PER_STORE + state/invariants.ts InvariantMiner (9 templates + count-by-group; relation-quality rules (F8); LEARN_AFTER, LEARN_AFTER_NONNULL), expect() + trace/ops.ts OpRegistry, OpRec (+ delivery, discardMark) trace/context.ts Context (ambient op: run, stick, isUserSync), LazyOp trace/events.ts EventLog ring buffer ``` -Docs by folder: `index.ts`, `runtime.ts`, `types.ts`, `errors.ts`, `clock.ts`, `util.ts` -> [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md); `observe/`, `trace/` -> [runtime/observe-and-trace.md](runtime/observe-and-trace.md); `state/`, `adapters/` -> [runtime/state-and-adapters.md](runtime/state-and-adapters.md); `learn/`, `situation/` -> [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md); `decide/` -> [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md); `model/` -> [runtime/model-host.md](runtime/model-host.md); `devtools/` -> [runtime/devtools.md](runtime/devtools.md). Everything the model reads is frozen at tag `situation-v1`: [model-io-contract.md](model-io-contract.md). +Docs by folder: `index.ts`, `runtime.ts`, `types.ts`, `errors.ts`, `clock.ts`, `util.ts` -> [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md); `observe/`, `trace/` -> [runtime/observe-and-trace.md](runtime/observe-and-trace.md); `state/`, `adapters/` -> [runtime/state-and-adapters.md](runtime/state-and-adapters.md); `learn/`, `situation/` and the delivery gate -> [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md); `decide/` and the delivery actions -> [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md); `model/` -> [runtime/model-host.md](runtime/model-host.md); `devtools/` -> [runtime/devtools.md](runtime/devtools.md). Everything the model reads is frozen at tag `situation-v2` (6e5e86e): [model-io-contract.md](model-io-contract.md). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts`, `types.ts` and `devtools/index.ts` (the default-mode change). -### `packages/runtime/test/` (79 files) +### `packages/runtime/test/` (84 files) -Doc: [runtime/build-test-release.md](runtime/build-test-release.md) ("Tests" has one row per file with test counts). +Doc: [runtime/build-test-release.md](runtime/build-test-release.md) ("Tests" has one row per file with test counts). 36 top-level `*.test.ts` + 6 `model/*.test.ts` = 42 unit test files; the local run on b435acb excluding `review-perf` gave 40 passed + 1 skipped files, 332 passed + 14 skipped tests; `review-perf` alone 4 passed. ```text packages/runtime/test/ - helpers.ts core test kit: setup, FakeClock, FakeServer, ScriptedDecider, defaultScript, ManualDecider, makeGlobal, drain + helpers.ts core test kit: setup (defaults to mode "guard"; pass mode: undefined for the product default), + FakeClock, FakeServer, ScriptedDecider, defaultScript, ManualDecider, makeGlobal, drain adapter-seam.test.ts rt.adapter(...).propose: reducer preview, held async dispatch, discard, rollback only with io.set adapters-react.test.ts React hooks, with MockRuntime and the real runtime (happy-dom) adapters-redux.test.ts genclassEnhancer: hold/apply once, GENCLASS_REPLACE, replaceReducer adapters-zustand.test.ts genclass middleware: merge semantics, hold/drop, whole-state writes ask.test.ts ask()/decide() typed answers, GenClassUnavailableError without a model - atoms.test.ts mutation pipeline: user-sync never held, hold/apply, fail-open, late revert, defer - batch3.test.ts SIM requests a-f, ctx.builtin through the gate, GenClass.init never throws + atoms.test.ts mutation pipeline with holdWrites: user-sync never held, hold/apply, fail-open, late revert, defer + batch3.test.ts SIM requests a-f, ctx.builtin through the gate, GenClass.init never throws, auth-store redaction budget.test.ts situation budgets, compact questions, auto budget, hold budget; prints example situations + content.test.ts (new) F3 no-call-when-unchanged, F1 field/item cells, F2 diff preview, F9, F6, F5, F7, F8, read-your-writes context.test.ts causal context: cause/root through fetch, timers, rt.op + default-mode.test.ts (new, ours) product default is observe: nothing held or changed; guard/heal opt-in + delivery.test.ts (new) delivery salience and actions over fetch, XHR, WebSocket, EventSource (FakeWS, FakeES, makeXHR) devtools-runtime.test.ts overlay on the real runtime via runStoreSession (happy-dom) devtools.test.ts overlay vs MockRuntime + loadScenario (happy-dom) - dom.test.ts describeElement, DOM user observer, destroy restores globals (happy-dom) + dom.test.ts describeElement, DOM user observer (shadow DOM, nested labels), destroy restores globals (happy-dom) fetch.test.ts fetch observer: coalesce, block, serve_cached, delay, retry, hedge, cache limits invariants.test.ts InvariantMiner learning, inconsistency once per episode, rollback learn.test.ts Baselines and Profiles; transition trigger + nan.test.ts (new) no infinite recursion when a store value is NaN (ad24804; the 0.1.0-alpha.1 patch) + no-reorder.test.ts (new) realworld promise middleware through genclassEnhancer with an always-passive model: + guard/heal give the same dispatches, order and final state as observe plugins.test.ts plugin facts/diagnoses/actions, ctx.builtin, standing questions, vocabulary policy.test.ts gate(): summed mass, tiers, thresholds, deny/allow, rate limit, pause report.test.ts report line format, explain(id), ?genclass=off|heal review-actions.test.ts REVIEW regression (must pass unmodified): error-trigger rollback scope review-dom.test.ts REVIEW: passwords never recorded, programmatic click is not a user action - review-fetch.test.ts REVIEW: request identity, coalescing edge cases, buffer limits, keepalive + review-fetch.test.ts REVIEW: request identity, coalescing edge cases, buffer limits, keepalive (headless() passes mode "guard") review-hub.test.ts REVIEW: held patches, late-revert undo, deep changes review-misc.test.ts REVIEW: console summaries, read-only fetch, denied heal action, ask after destroy - review-perf.test.ts REVIEW: wall-clock cost budgets on 5,000-item stores + review-perf.test.ts REVIEW: wall-clock cost budgets on 5,000-item stores (run alone in CI; flaky under parallel load) review-precision.test.ts REVIEW: transition/inconsistency false positives review-redaction.test.ts REVIEW: custom redact applies to invariant facts review-timers.test.ts REVIEW: recursive timer loops; gc check needs NODE_OPTIONS=--expose-gc review-xhr.test.ts REVIEW: sync XHR never held, abort while held situation.test.ts one situation per trigger: key order and section limits; prints situations - smoke.test.ts atoms, context through real awaits, stale write discarded in guard mode + smoke.test.ts atoms, context through real awaits, stale delivery discarded in guard mode (explicit mode "guard") xhr.test.ts XHR op + cause, block, detection-only failures, destroy restores open/send model/helpers.ts model test kit: MODEL_DIR (GENCLASS_MODEL_DIR), FIXTURES_FROM_MODEL, fixture loaders model/calibrate.test.ts hashes and calibration vs Python/PyTorch (1 of 8 skips without model files) @@ -195,26 +239,9 @@ packages/runtime/test/ browser/ui/playwright.config.ts UI spec config (testMatch ui-*.spec.ts) browser/ui/mock-runtime.ts MockRuntime: scripted Runtime (also used by adapters-*.test.ts) browser/ui/scenario.ts loadScenario: scripted store story for MockRuntime - browser/ui/session.ts runStoreSession: real createRuntime under a VirtualClock with a rule-based SessionDecider + browser/ui/session.ts runStoreSession: real createRuntime (explicit mode "guard") under a VirtualClock with a rule-based SessionDecider browser/ui/page.ts fake "Acme" store page for the UI spec (window.__gc) - browser/ui/screenshots/activity-dark.png - browser/ui/screenshots/activity-light.png - browser/ui/screenshots/detections-dark.png - browser/ui/screenshots/detections-light.png - browser/ui/screenshots/evidence-answers-dark.png - browser/ui/screenshots/evidence-answers-light.png - browser/ui/screenshots/evidence-dark.png - browser/ui/screenshots/evidence-light.png - browser/ui/screenshots/interventions-dark.png - browser/ui/screenshots/interventions-light.png - browser/ui/screenshots/loading-dark.png - browser/ui/screenshots/loading-light.png - browser/ui/screenshots/now-dark.png - browser/ui/screenshots/now-light.png - browser/ui/screenshots/overlay-dark.png - browser/ui/screenshots/overlay-light.png - browser/ui/screenshots/pill-dark.png - browser/ui/screenshots/pill-light.png + browser/ui/screenshots/ 18 PNGs: {activity,detections,evidence-answers,evidence,interventions,loading,now,overlay,pill}-{dark,light}.png smoke/smoke.sh npm pack -> fresh Vite 8 app -> headless Chromium check (run from packages/runtime; ask first) ``` @@ -224,98 +251,179 @@ The 18 PNGs are written by `ui-devtools.spec.ts`; no README embeds them. ```text packages/runtime-model/ - MODEL_CARD.md model card for R17/R32 (sizes, stage-1c accuracy, limits); the package itself does not exist yet + MODEL_CARD.md model card for R17/R32 (sizes, final round 1 on situation-v1, limits); the package itself does not exist yet ``` -### `sim/` (59 files) +### `sim/` (106 files) Doc: [sim.md](sim.md). Row format: [model-io-contract.md](model-io-contract.md). ```text sim/ - package.json @genclass/sim (private); bin genclass-sim -> dist/gen.js; scripts build typecheck test gen sample build:runtime-core + package.json @genclass/sim (private); bin genclass-sim -> dist/gen.js; scripts build (tsup + build:model-host) typecheck + test gen sample build:runtime-core build:model-host (bundles the runtime's model host into dist/model-host/ + for --on-policy) tsconfig.json extends ../tsconfig.base.json, noEmit, src + test tsup.config.ts ESM, node22, @genclass/runtime external; entries gen, worker, index, smoke -> dist/ vitest.config.ts node env, pool forks, 120 s timeouts - README.md SIM README: commands, final datasets, known limitations + README.md SIM README: commands, row modes, datasets, known limitations NEEDS.md SIM -> CORE requests (relayed by the lead) - scripts/final.sh final datasets on the train VM: final.sh a | b | merge-b (ask first) - scripts/analyze.py dataset summary: python3 sim/scripts/analyze.py <dir> - samples/sample.jsonl 200 rows written by gen --sample + SEPARABILITY.md (new) why round-1 R17 recalls few clear cases; proposals T1, S1, S2, F1-F9; first v2 check (§8) + scripts/final.sh v1 final datasets on the train VM: final.sh a | b | merge-b (ask first) + scripts/analyze.py dataset summary (merged files or parts/), per subject feature, unlabeled diagnosis counts + scripts/relabel.py (new) re-derive gold action labels from meta.cost_futures (mirror of actionLabel) + scripts/separability.py (new) separability analysis, stage 1 (rows) + scripts/separability_probe.py (new) stage 2 (SIM_PROBE=1 probes) + scripts/separability_extra.py (new) extra tables + scripts/separability_gbdt.py (new) GBDT check + scripts/cluster/bundle.sh (new) train VM: tar Node 22, runtime dist, sim/dist (incl. model-host/), scripts for the nodes + scripts/cluster/orchestrate.sh (new) colleague's Mac: start/stop/status of node runs (one az call at a time); v1 seed bases + scripts/cluster/node_start.sh (new) on a node: fetch the bundle, run gen.js --parts --chunk 100 + scripts/cluster/bigrun.sh (new) v2 production: start, unl RUN ROWS NODES (16e9), gold RUN ROWS NODES (11e9) + scripts/cluster/collect.py (new) pull finished parts, dedupe globally, write gz shards + manifest + samples/sample.jsonl 200 rows written by gen --sample (v2) samples/EXAMPLES.md pretty-printed example rows (renderExamples) samples/sample-stats.json stats of the sample run - samples/stats-final-a.json stats of SIM final phase A (600,676 rows) + samples/stats-final-a.json stats of SIM v1 final phase A (600,676 rows) src/index.ts library re-exports (buildScenario, runScenario, generateTrajectory, runCost, ...) src/types.ts structural mirror of the runtime model seam + Row/Label (CONTRACT-D) src/rng.ts Rng (sfc32, keyed forks), hash32, hashAll src/loop.ts VirtualLoop: deterministic virtual event loop and clocks - src/gen.ts CLI: worker pool, shard merge, stats.json, --sample, --parts, --allow-fake - src/gen/trajectory.ts generateTrajectory, pointCosts: ideal + base + counterfactual runs -> rows - src/gen/worker.ts worker_threads worker: seeds -> rows -> shard/part files + src/gen.ts CLI: worker pool, shard merge, stats.json, --sample, --parts, --unlabeled, --on-policy <dir>, --allow-fake + src/gen/trajectory.ts generateTrajectory (gold / unlabeled / on-policy), unlabeledTrajectory, pointCosts, diagnosisFromOutcome (S1), S1_GAP + src/gen/worker.ts worker_threads worker: seeds -> rows -> shard/part files; loads loadModelDecider once in on-policy mode src/gen/examples.ts renderExamples (EXAMPLES.md) - src/net/network.ts Network (latency, chaos, push, fetch), IDEAL_PROFILE, SIM_OP_HEADER + src/net/network.ts Network (latency, chaos, offline windows, push, fetch, S2 latent re-draws), IDEAL_PROFILE, SIM_OP_HEADER src/net/server.ts VirtualServer, Db, API_STYLES src/app/env.ts AppEnv: what generated app programs see (fetch, stores, sockets, timers) src/app/feature.ts FeatureDef contract, UserModel, personas, relations src/app/kit.ts Kit: tagged ops, requests, writes, error surfacing src/app/naming.ts Naming: per-program route/store/field names - src/app/vocab.ts DOMAINS: 55 domain vocabularies - src/app/features/index.ts FEATURES, FEATURE_WEIGHTS + src/app/vocab.ts DOMAINS: 55 round-1 domain vocabularies + src/app/vocab2.ts (new) DOMAINS2: 60 round-2 domains + src/app/features/index.ts FEATURES (46), FEATURE_WEIGHTS src/app/features/common.ts shared feature helpers - src/app/features/auth.ts feature combinator (one FeatureDef each, 15 in total) - src/app/features/benign.ts - src/app/features/board.ts - src/app/features/bulk.ts - src/app/features/cart.ts - src/app/features/chat.ts - src/app/features/counter.ts - src/app/features/editor.ts - src/app/features/form.ts - src/app/features/list.ts - src/app/features/nav.ts - src/app/features/poll.ts - src/app/features/search.ts - src/app/features/settings.ts - src/app/features/toggle.ts - src/world/scenario.ts buildScenario(seed), splitOf, TEST_DOMAINS, TEST_PATTERNS, chaos profiles - src/run/rt.ts realRuntimeFactory (dynamic import of the real runtime), createOptions - src/run/runner.ts runScenario: one run (ideal or real), recording decider, correlation, snapshots + src/app/features/{auth,benign,board,bulk,cart,chat,counter,editor,form,list,nav,poll,search,settings,toggle}.ts + the 15 round-1 feature combinators (one FeatureDef each) + src/app/features/{badge,cascade,cdn,clockskew,countdown,etag,exportjob,facets,flags,graphql,infinite,inventory, + longtask,masterdetail,money,multitab,offline,payment,permissions,prefetch,presence,querycache, + ratelimit,reorder,saga,schemadrift,swcache,undo,upload,wizard,wsreconnect}.ts + (new) the 31 round-2 feature combinators + src/world/scenario.ts buildScenario(seed), splitOf, TEST_DOMAINS, TEST_PATTERNS, TEST_FEATURES, chaos profiles, budget sampling + src/run/rt.ts realRuntimeFactory (dynamic import of the real runtime), createOptions (mode "heal"; production for on-policy) + src/run/runner.ts runScenario: one run (ideal or real), recording / on-policy decider, correlation (incl. delivery), platform + src/run/latent.ts (new) S2: FutureSpec, S2 (env SIM_S2), futureProfile, futureStepTimes, REPEAT_PRIOR, idealRepeatSkips + src/run/onpolicy.ts (new) loadModelDecider(modelDir): the runtime's model host in Node on onnxruntime-web WASM (DAgger) src/run/fake-runtime.ts createFakeRuntime: test double only (rows marked meta.runtime "fake") src/run/transform.ts transformQuestions (shuffle/drop action options), ACTION_PARA - src/oracle/knowledge.ts Knowledge: ground-truth bookkeeping (intents, sim ops, sim writes) + src/oracle/knowledge.ts Knowledge: ground-truth bookkeeping (intents, sim ops, sim writes with verdicts) src/oracle/diagnose.ts diagnose, diagnoseFailure: diagnosis labels src/oracle/cost.ts W (cost weights), LABEL, TIER, runCost, actionLabel - src/ask/questions.ts askQuestions: 11 programmatic ask generators with exact labels + src/oracle/probe.ts (new) separability probes, analysis only (SIM_PROBE=1) + src/ask/questions.ts askQuestions: programmatic ask generators with exact labels src/dev/smoke.ts dev tool: base runs on many seeds, prints raw situations test/helpers.ts testFactory (SIM_RUNTIME=real -> real runtime, else fake), mini scenario builder test/loop.test.ts VirtualLoop ordering, Response bodies, rng forks test/determinism.test.ts same seed -> identical rows; replay reproduces every prefix test/rows.test.ts valid CONTRACT-D rows; splits and transform - test/oracle.test.ts diagnosis and cost/label cases (2 are real-runtime only) + test/oracle.test.ts diagnosis and cost/label cases (some are real-runtime only) + test/latent.test.ts (new) S2 latent re-draws ``` -### `training/` (43 files) +Check run on b435acb when these docs were written: `SIM_RUNTIME=real npx vitest run` in `sim/` gives 19 passed (5 files); `tsc` clean. + +### `realapps/` (230 files) + +Doc: [realapps.md](realapps.md). Not a root workspace, no tsconfig, no tests, not in CI; everything real needs Chromium (ask first). + +```text +realapps/ + package.json @genclass/realapps 0.0.0 (private); scripts build (node build.mjs), gen (node dist/harness/gen.js), build:runtime; + devDeps playwright 1.63.0, esbuild, esbuild-svelte and every framework the apps use + .gitignore node_modules/ dist/ src/harness/apps.gen.ts + build.mjs esbuild: world IIFE (dist/world.js), harness (dist/harness/{gen,worker,debug}.js), manifest registry, + every esbuild-built app; RW_RUNTIME_SRC / RW_RUNTIME_TAG pin the runtime (default: working tree, + tag "working-tree"); writes dist/runtime-tag.txt + README.md design document (corpus, integration, determinism, labels, row kinds, splits, run commands, v1 pilot numbers); + still says 66 apps + EXAMPLES.md 13 audited rows from the v1 pilot + apps/README.md authoring guide for app-writing agents (written for the colleague's Mac and branch runtime) + apps/_shared/ 12 files: genclass.ts (one-line integration: GenClass.init(window.__GENCLASS_INIT__ ?? {}), flag()), + {vue,svelte,solid,preact,lit}-atom.ts, lit-toast.ts, hyperapp-guard.ts, react-genclass-reducer.ts, + w3-http.ts, conduit-manifest.ts (conduitManifest for the 14 OSS apps), onnx-stub.ts (aliased for onnxruntime-web) + apps/<name>/ 91 apps: manifest.ts (AppManifest) + source (88 .ts/.tsx/.svelte files across the 77 written apps; + the 14 oss-*-conduit apps have a manifest only). Names: actions-comments, alpine-*, backbone-*, effector-iot, + htm-iot-dashboard, hyperapp-*, jotai-planner, jquery-*, knockout-*, ky-banking, lit-*, mithril-*, mobx-*, + nano-notifications, ofetch-clinic, oss-{angular,angularjs,elm,ember,halogen,mobx,react-redux,rescript,rtk, + solid,svelte,vue2,vue3,wc}-conduit, petite-*, pinia-*, preact-*, react-*, reducer-inbox, router-crm, rtk-*, + rtkq-helpdesk, rx-*, saga-chat, solid-*, superagent-*, svelte-*, swr-status, valtio-ledger, vanilla-*, + vue-*, wc-weather-alerts, wretch-pharmacy, xhr-autocomplete, xstate-checkout, zustand-* + corpus/oss.json the 14 open-source apps: repo, pinned commit, build kind, deps, licence + corpus/LICENSES.md OSS licences + corpus/prepare_oss.sh VM: clone + install + patch + build each OSS app into dist/apps/<name>/ ($RW_OSS_DIR, default ~/gcl/real-cache/oss) + corpus/patch_oss.py the GenClass integration added to each OSS app + corpus/rebundle.mjs, build_angularjs.mjs, vite.oss.config.mjs OSS build helpers + src/world/index.ts in-page world entry (IIFE injected before page scripts): loop, network, server, user, probe; window.__RW.start() + src/world/loop.ts virtual time (timers, rAF, MessageChannel, postTask, Date, performance.now, seeded randomness) + src/world/net.ts in-page fetch / XHR / WebSocket on virtual time with chaos draws + src/world/netapi.ts installs them; sets window.EventSource = undefined (the runtime's eventsource observer never installs) + src/world/server.ts mock backend (collections, versions/409, idempotency replay, auth, replica lag, live topics) + src/world/ext/conduit.ts RealWorld (Conduit) API extension + src/world/user.ts scripted user (untrusted events, intent pinning) + src/world/probe.ts Probe: recording DecisionProvider, hooks, store-snapshot plugin, DOM snapshots, in-page diagnosis call + src/world/diagnose.ts diagnose: in-page diagnosis rules (incl. the v2 delivery trigger) + src/harness/scenario.ts buildScenario(seed, apps, opts), splitOf, TEST_FRAMEWORKS, TEST_APPS, TEST_PATTERNS + src/harness/trajectory.ts generateTrajectory (ideal, base, counterfactuals, prefix check, labels, row kinds); OBSERVE, runConfig, RUNTIME_TAG + src/harness/cost.ts runCost, states, serverDist, relationBroken (mirrors sim/src/oracle/cost.ts) + src/harness/labels.ts finishDiagnosis, duplicateKeys + src/harness/browser.ts Runner: one headless Chromium per worker, fresh page per run, ORIGIN https://app.example.com + src/harness/gen.ts resumable generator (worker pool, per-split JSONL, done.txt, stats.json, manifest.json); --out required + src/harness/worker.ts worker process (RW_PORT, RW_OPTS) + src/harness/debug.ts inspection CLI: one scenario, --twice, --traj, --force k:action, --det (determinism sweep), + --interference (never-worse sweep), --clean + src/shared/manifest.ts AppManifest, Affordance, Relation + src/shared/types.ts RunConfig, RunResult, ServerSpec, Step, DecisionRec + src/shared/routes.ts endpointsOf + scripts/analyze.py batch stats + comparison with sim/samples/stats-final-a.json + scripts/evalset.py builds <out>/real_eval.jsonl + manifest.json (unambiguous real-app eval set) + scripts/examples.py row pretty-printer for audits + scripts/chromium_probe.mjs measures the Chromium event-loop facts the loop relies on + scripts/node_setup.sh VM setup: Node 22.22.0, npm install, Playwright chromium_headless_shell, pinned runtime, prepare_oss, build + scripts/cluster.sh Mac-side ssh/rsync helper: sync, setup, run (detached gen.js into ~/gcl/real-out/<name>), status, stop +``` + +### `training/` (61 files) Doc: [training.md](training.md). Every script here runs on Azure VMs; ask before running any of them. ```text training/ README.md overview and reproduce commands (partly stale) - LOG.md dated run log (what ran where, throughput, costs, decisions) - EVAL.md metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot) - NEEDS.md TRAIN requests to SIM / CORE / MODEL, MODEL -> TRAIN notes + PLAN-v1.md (new) the scaled program: targets, data, models R17/R32/R68/T150/T400, phases P0-P5, costs, eval, risks + LOG.md dated run log (what ran where, throughput, costs, decisions) up to the v2 freeze + EVAL.md metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot, final round 1) + NEEDS.md TRAIN requests to SIM / CORE / MODEL / REAL; node claims; v2 data locations prune_vocab.py prune/analyze: keep the first N BPE merges (16,000 -> 16,364 tokens) of a checkpoint or HF base eval_runtime.py accuracy, NLL/Brier/ECE, temperature fit (calibration.json), CONTRACT §8 gate metrics, SIM cost regret + eval_gain.py (new) T1 expected-gain evaluation of gate policies from cached logits export_runtime.py checkpoint -> q8/fp16 ONNX + model.json/meta.json/calibration.json/tokenizer.json + parity fixtures report.py Markdown tables for EVAL.md from eval reports + label_teacher.py (new) teacher soft-labelling of CONTRACT-D rows (calibrated dist labels, meta.teacher), resumable + label_cluster.sh (new) teacher labelling across nodes (serves teacher + shards on :8805); untested + t1_relabel.py (new) T1: expected-advantage action labels or gain targets from meta.cost_futures + collect_gain.py (new) logits + gain-head predictions; needs the parent-repo jev_local gain head + t1_post.sh, t1h_post.sh (new) post-run eval of T1 / gain-head runs on the rank-0 node configs/mix_s1.json mixture configs read by jev_local/train/stream.py MixConfig configs/mix_s1b.json configs/mix_s1c.json configs/mix_s2.json configs/mix_final1.json + configs/mix_t150.json (new) teacher (v1 buckets simA .9, cur4 .1) + configs/mix_r68.json (new) R68 student benchmark (never run) + configs/mix_t1a.json, mix_t1b.json, mix_t1h.json (new) T1 runs (simAg10 / simAg20 / simAh) curriculum/__init__.py package docstring curriculum/generate.py seeded parallel curriculum generator (CONTRACT-D jsonl + stats.json); --p-runtime -> GC_P_RUNTIME - curriculum/rt.py Python port of packages/runtime/src/situation/* (runtime-exact rows); must match the frozen text + curriculum/rt.py Python port of packages/runtime/src/situation/* (runtime-exact rows); "FROZEN at git tag situation-v2" curriculum/world.py explicit world model: ops, writes with versions, baselines; varied-style rendering curriculum/app.py App: per-row app instance (names, ids, routes, values) curriculum/vocab.py 62 app domains (13 held out: TEST_DOMAINS), UI/error vocab @@ -329,15 +437,20 @@ training/ ortweb/package.json onnxruntime-node + onnxruntime-web 1.30.0 for validate.mjs (not a workspace) ortweb/validate.mjs node validate.mjs <dir> [variant] [maxRequests]: WASM parity and latency of an export samples/runtime_samples.txt 75 hand-written runtime-like lines for prune_vocab.py analyze - tests/test_curriculum.py pytest (VM): curriculum validity, held-out splits, label consistency + tests/test_curriculum.py pytest: curriculum validity, held-out splits, label consistency, v2 runtime rows (pure Python part runs locally) tests/test_prune_vocab.py pytest (VM; GC_V1_CKPT, GC_BASE_32M): pruned tokenizer and logits parity tests/test_export_runtime.py pytest (VM; GC_R17_INIT): int8 embeddings, Gemm->MatMul, end-to-end export node.sh ssh/rsync wrapper for Azure hosts: node.sh HOST sync|'cmd'|get R L|put L R + node_init.sh (new) fresh node: pull the node kit tar, install ONNX tooling, check torch + cluster_expand.sh (new) create extra F80 nodes (c12-c23 on 2026-10-08), append to azure_hosts, Disabled shutdown schedule import_sim.sh pull a SIM run to c01 and shard it (stage 2) - import_final.sh pull a frozen SIM run, shard, build eval subsets, bundle for nodes + import_final.sh pull a frozen SIM run (plain jsonl; cannot read v2 gz shards), shard, build eval subsets, bundle for nodes launch_s2.sh launch stage-2 pilot runs (R32, R17) launch_final1.sh launch final round 1: launch_final1.sh R32_PASSES R17_PASSES - final_post.sh on a rank-0 node: SIM eval -> export -> serve tar on :8801 + launch_student.sh (new) generic DDP launcher: launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra] + launch_t150.sh (new) T150 teacher launcher + launch_r68.sh (new) R68 benchmark launcher + final_post.sh on a rank-0 node: SIM eval -> export -> serve tar on :8801 (hard-wired to the v1 simAe eval set) eval_sim.sh sharded logit collection + one SIM eval per model run_evals.sh stage-1 eval batch on c01 pull_ckpt.sh copy a servable checkpoint from a node to c01 @@ -345,7 +458,7 @@ training/ deliver_final.sh from the Mac: same delivery, driven remotely ``` -### `demos/` (132 files) +### `demos/` (133 files) Doc: [demos.md](demos.md). Non-`src` files: @@ -374,13 +487,13 @@ demos/ e2e/trace-report.ts analyses --trace runs (e2e/.out/traces*.json) into Markdown README.md human README: run, URL params, oracles, honesty rules NEEDS.md DEMOS -> CORE/MODEL/UI/lead issues with evidence - results.md latest results (v0.1 model, generated before batch 3) + results.md latest results (v0.1 model on the frozen situation-v1 runtime, 04a264f) results.json raw trials (large) results-summary.json summary shipped with the site - screenshots/ 30 PNGs (see below) + screenshots/ 31 PNGs (see below) ``` -`demos/src/` (76 files): +`demos/src/` (76 files, unchanged since 654d822): ```text demos/src/ @@ -390,7 +503,7 @@ demos/src/ shared/scenario-kit.ts typing rhythm (typeSteps), sampleChaos, CLEAN_CHAOS shared/types.ts GcMode, Step, Scenario, Score, TrialResult shared/demo-def.ts DemoDefinition, AppContext, OracleContext, Oracle - shared/driver.ts runSteps: synthetic in-page user + shared/driver.ts runSteps: synthetic in-page user (untrusted events: not recorded unless observe.untrustedEvents) shared/harness.ts TrialHarness (window.__trial) shared/aggregate.ts wilson, quantile, summarizeMode, summarizeDemo shared/trace.ts ?trace=1 investigation tracing via hooks.mutationProposed @@ -462,7 +575,7 @@ demos/src/ dev/runtime-shim/devtools.ts no-op mountDevtools; duplicates DevtoolsOptions (update when the options change) ``` -`demos/src/server/data/cities.ts` is imported but not in git (the root `.gitignore` rule `data/` matches it), so a fresh clone cannot build the Service Worker or the search demo. See [demos.md](demos.md) ("Drift and open issues"). +`demos/src/server/data/cities.ts` is imported but not in git (the root `.gitignore` rule `data/` matches it), so a fresh clone cannot build the Service Worker or the search demo. See [demos.md](demos.md) ("Drift and open issues"). The demos site creates the runtime with `startGenClass`, which passes an explicit mode, so the default-mode change does not affect it; its in-page synthetic driver dispatches untrusted events, which situation-v2 no longer records unless `observe.untrustedEvents` is set. ### `scripts/` (26 files) @@ -498,9 +611,24 @@ scripts/ demo_proof.sh offline mid-sentence proof (Mac only) ``` +### `docs/` (36 tracked files) + +```text +docs/ + runtime/CONTRACT.md binding runtime contract (lead); §13 records the default-mode change (f3636b2) + runtime/API.md public API reference (default mode observe since f3636b2) + runtime/ARCHITECTURE.md architecture overview + [runtime/RESULTS.md](../runtime/RESULTS.md) (new) results, comparisons and training-log summary; "update it with every result" (HANDOFF) + agents/ these docs: README, overview, repo-map, glossary, playbooks, status-and-known-issues, model-io-contract, + genclass-model-lineage, extension-and-benchmarks, demos, sim, training, runtime/ (8 docs); + realapps.md (new, not yet committed) + benchmax-research/ 5 planning notes (read-only background) + SPEC.md, CONTRACT.md, CONTRACT-v2.md, DEMO.md, GENCLASS.md, COMPARISON.md, PLAN-excel.md legacy jev-local docs +``` + ### Legacy directories (one line per directory) -Doc for `jev_local/`, `tests/` and `docs/` legacy files: [genclass-model-lineage.md](genclass-model-lineage.md). Doc for `extension/`, `bench/`, `results/`, `docs/benchmax-research/`: [extension-and-benchmarks.md](extension-and-benchmarks.md). +Doc for `jev_local/`, `tests/` and `docs/` legacy files: [genclass-model-lineage.md](genclass-model-lineage.md). Doc for `extension/`, `bench/`, `results/`, `docs/benchmax-research/`: [extension-and-benchmarks.md](extension-and-benchmarks.md). All unchanged since 654d822. ```text jev_local/ 136 Python package jev-local 0.1.0 @@ -527,21 +655,15 @@ extension/ 104 GenClass 0.1.0 MV3 Chrome extension tools/ 1 genclass_export.py (q8 export of the v0.1 model) bench/ 5 PREREG-jevbench.md, PREREG-benchmax.md, public/ (3: targets.json, jev_published.json, exclusions.json) tests/ 74 pytest for jev_local: conftest.py, fixtures/ (2), 71 test_*.py (20 test_data_*.py cannot import) -docs/ 15 tracked files: - docs/runtime/ 3 CONTRACT.md (binding runtime contract, lead), API.md, ARCHITECTURE.md - docs/benchmax-research/ 5 benchmax planning notes (read-only background) - (top level) 7 legacy jev-local docs: SPEC, CONTRACT (defines the CONTRACT-D row format), CONTRACT-v2, DEMO, - GENCLASS, COMPARISON, PLAN-excel - docs/agents/ - these agent docs (untracked at 654d822) results/ 3 genclass-vs-jev-computer-use.md, jevbench-m0.md, z68m-dev-notes.md -demos/screenshots/ 30 <demo>.png, <demo>-dark.png, <demo>-full.png and <demo>-page.png for board, checkout, - decisions, editor, status, search; index{,-dark,-full,-mobile}.png; search-mobile.png, - search-trials.png. Written by demos/e2e/eval.ts (npm run shots) +demos/screenshots/ 31 <demo>.png, <demo>-dark.png, <demo>-full.png and <demo>-page.png for board, checkout, + decisions, editor, status, search; decisions-heal.png (new); index{,-dark,-full,-mobile}.png; + search-mobile.png, search-trials.png. Written by demos/e2e/eval.ts (npm run shots) ``` ## 3. Where is X? -Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/runtime/src/runtime.ts` unless stated. +Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/runtime/src/runtime.ts` unless stated. ### Runtime public API, options and lifecycle @@ -549,21 +671,22 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r |---|---|---|---| | `GenClass` (browser singleton: `init`, `runtime`, `destroy`) | symbol | `packages/runtime/src/index.ts` -> `GenClass` | [public-api](runtime/public-api-and-lifecycle.md) | | `createRuntime` (headless entry point) | symbol | `packages/runtime/src/index.ts` -> `createRuntime` | [public-api](runtime/public-api-and-lifecycle.md) | +| **Default mode `observe`** (`o.mode ?? "observe"`, f3636b2) | code | `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `InitOptions.mode` (JSDoc); test `packages/runtime/test/default-mode.test.ts` | [public-api](runtime/public-api-and-lifecycle.md), [decide-policy](runtime/decide-policy-actions.md) | | Kill switch `?genclass=off\|observe\|guard\|heal` / `localStorage.genclass` | URL param, storage key | `packages/runtime/src/index.ts` -> `killSwitch` | [public-api](runtime/public-api-and-lifecycle.md) | | Owned model host built by `createRuntime` | symbol | `packages/runtime/src/index.ts` -> `makeHost` | [model-host](runtime/model-host.md) | | Un-observed fetch used for model downloads | constant | `packages/runtime/src/index.ts` -> `NATIVE_FETCH` | [observe-and-trace](runtime/observe-and-trace.md) | | All-observers-off map (inert runtime) | constant | `packages/runtime/src/index.ts` -> `ALL_OFF` | [public-api](runtime/public-api-and-lifecycle.md) | | `RuntimeImpl` (implements every `Runtime` method) | class | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` | [public-api](runtime/public-api-and-lifecycle.md) | -| `InitOptions` (`mode`, `model`, `decider`, `observe`, `policy`, `report`, `triage`, `settleMs`, `historySize`, `situation`, ...) | type | `packages/runtime/src/types.ts` -> `InitOptions` | [public-api](runtime/public-api-and-lifecycle.md) | +| `InitOptions` (`mode`, `model`, `decider`, `observe` incl. `untrustedEvents`, `policy`, `report`, `triage`, `settleMs`, `historySize`, `situation`, ...) | type | `packages/runtime/src/types.ts` -> `InitOptions` | [public-api](runtime/public-api-and-lifecycle.md) | | `CreateOptions` (adds `clock`, `global`, `app`, `hooks`) | type | `packages/runtime/src/types.ts` -> `CreateOptions` | [public-api](runtime/public-api-and-lifecycle.md) | | `ModelOptions` (`baseUrl`, `preload`, ...) | type | `packages/runtime/src/types.ts` -> `ModelOptions` | [model-host](runtime/model-host.md) | -| `PolicyOptions` (`thresholds`, `holdBudgetMs`, `allow`, `deny`, `holdUserWrites`, `requireDiagnosis`) | type | `packages/runtime/src/types.ts` -> `PolicyOptions` | [decide-policy](runtime/decide-policy-actions.md) | +| `PolicyOptions` (`thresholds`, `holdBudgetMs`, `allow`, `deny`, `holdUserWrites`, `holdWrites`, `requireDiagnosis`, `maxActionsPerMinute`) | type | `packages/runtime/src/types.ts` -> `PolicyOptions` | [decide-policy](runtime/decide-policy-actions.md) | | `Runtime` interface | type | `packages/runtime/src/types.ts` -> `Runtime` | [public-api](runtime/public-api-and-lifecycle.md) | | `RuntimeEvents` (decide, detect, act, report, event, status) | type | `packages/runtime/src/types.ts` -> `RuntimeEvents` | [public-api](runtime/public-api-and-lifecycle.md) | | `Plugin` / `PluginApi` | type | `packages/runtime/src/types.ts` -> `Plugin`, `PluginApi` | [public-api](runtime/public-api-and-lifecycle.md) | -| `Decision`, `ActionRecord` | type | `packages/runtime/src/types.ts` -> `Decision`, `ActionRecord` | [decide-policy](runtime/decide-policy-actions.md) | +| `Decision`, `ActionRecord` (incl. `dropped` for delivery discards) | type | `packages/runtime/src/types.ts` -> `Decision`, `ActionRecord` | [decide-policy](runtime/decide-policy-actions.md) | | `DecisionProvider`, `EvaluateRequest` (model seam) | type | `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest` | [model-io-contract](model-io-contract.md) | -| `JevState`, `TriggerKind` | type | `packages/runtime/src/types.ts` -> `JevState`, `TriggerKind` | [model-io-contract](model-io-contract.md) | +| `JevState`, `TriggerKind` (incl. `delivery`) | type | `packages/runtime/src/types.ts` -> `JevState`, `TriggerKind` | [model-io-contract](model-io-contract.md) | | `Clock` and the default real clock | type, constant | `packages/runtime/src/types.ts` -> `Clock`; `packages/runtime/src/clock.ts` -> `browserClock` | [public-api](runtime/public-api-and-lifecycle.md) | | `GenClassUnavailableError` | class | `packages/runtime/src/errors.ts` -> `GenClassUnavailableError` | [public-api](runtime/public-api-and-lifecycle.md) | | Observer install order and uninstall | method | `RuntimeImpl.installObservers` | [observe-and-trace](runtime/observe-and-trace.md) | @@ -575,20 +698,49 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | `SitEnv` implementation | method | `RuntimeImpl.makeEnv` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Chain revert (error/transition rollback) | method | `RuntimeImpl.revertChain` | [state-and-adapters](runtime/state-and-adapters.md) | | Late-revert window (2,000 ms) | constant | `packages/runtime/src/runtime.ts` -> `LATE_REVERT_MS` | [decide-policy](runtime/decide-policy-actions.md) | +| Background decision deadline (5 s) | constant | `packages/runtime/src/runtime.ts` -> `BACKGROUND_DEADLINE_MS` | [decide-policy](runtime/decide-policy-actions.md) | | In-flight age that blocks settled points (10 s) | constant | `packages/runtime/src/runtime.ts` -> `LONG_RUNNING_MS` | [state-and-adapters](runtime/state-and-adapters.md) | | Console line `[GenClass] Model unavailable (...); observing only.` | string | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (status subscription) | [status](status-and-known-issues.md) | +### Delivery decisions (situation-v2, batches 4 and 5) + +| X | kind | where | doc | +|---|---|---|---| +| **The delivery trigger / gate** (pre-filter, body read, hold, actions) | method | `RuntimeImpl.runDelivery` (public member) | [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy](runtime/decide-policy-actions.md) | +| Body wait for salience (100 ms) | constant | `packages/runtime/src/runtime.ts` -> `BODY_WAIT_MS` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Discard mark lifetime (10 s) and the drop filter | constant, method | `packages/runtime/src/runtime.ts` -> `DISCARD_MARK_MS`; `RuntimeImpl.dropFilter`, `RuntimeImpl.writtenOver`, `RuntimeImpl.onDropped`; `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` (calls the private `applyFilter`) | [decide-policy](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md) | +| Discard mark on the op (`discardMark`) and the delivery record (`delivery`) | type | `packages/runtime/src/trace/ops.ts` -> `OpRec` | [observe-and-trace](runtime/observe-and-trace.md) | +| Non-blocking `mutation` trigger (default) | method | `RuntimeImpl.observeWrite` | [decide-policy](runtime/decide-policy-actions.md) | +| Held `mutation` (opt-in `policy.holdWrites`) | method | `RuntimeImpl.gateMutation`; `packages/runtime/src/state/hub.ts` -> `StoreHub.holdWrites`, `StoreHub.flushQueue` | [state-and-adapters](runtime/state-and-adapters.md) | +| Writes covered by a delivery decision (no mutation trigger) | method | `RuntimeImpl.covered` | [decide-policy](runtime/decide-policy-actions.md) | +| Hold only if the model is fast enough | method | `RuntimeImpl.expectedLatency` (compared with `holdBudgetMs()` in `trigger`) | [decide-policy](runtime/decide-policy-actions.md) | +| Delivery `defer` waits | method | `RuntimeImpl.waitOps` | [decide-policy](runtime/decide-policy-actions.md) | +| Stale marks (F9) set on writes | method | `RuntimeImpl.markWrites`, `RuntimeImpl.onChannel` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Create responses recorded for read-your-writes | method | `RuntimeImpl.noteResponse` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Push-channel delivery gate (WebSocket/EventSource) | class | `packages/runtime/src/observe/messages.ts` -> `MessageGate`, `MsgHost`, `messageSummary` | [observe-and-trace](runtime/observe-and-trace.md) | +| EventSource observer (observer name `eventsource`) | function | `packages/runtime/src/observe/eventsource.ts` -> `installEventSource` | [observe-and-trace](runtime/observe-and-trace.md) | +| `DeliverySpec` (subject of a delivery trigger) | type | `packages/runtime/src/situation/env.ts` -> `DeliverySpec` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Predicted write set and conflicts (newer data, pending local change; 10 s window) | function, constant | `packages/runtime/src/situation/conflicts.ts` -> `predictedWrites`, `newerConflict`, `pendingConflict`, `conflictsOn`, `PENDING_WINDOW_MS` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Body vs store comparison, facts F1-F3, read-your-writes | function | `packages/runtime/src/situation/content.ts` -> `analyzeBody`, `compareField`, `contentFacts`, `pendingRevertFacts`, `createdIds`, `rywFacts` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Evidence facts F5, F6, F7, F9 | function | `packages/runtime/src/situation/evidence.ts` -> `scopeFacts`, `commitAmbiguity`, `cadenceFact`, `repeatEvidence`, `markFacts` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Learned cadence (schedule / debounce) | class | `packages/runtime/src/learn/cadence.ts` -> `Cadence`, `CadenceInfo` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Delivery facts and the trigger sentence's prediction text | function | `packages/runtime/src/situation/facts.ts` -> `computeFacts` (internal `deliveryFacts`), `predictedText` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Delivery actions `deliver` / `discard` / `defer` | constant | `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS.delivery`, `PASSIVE.delivery` | [decide-policy](runtime/decide-policy-actions.md) | +| Relation quality (F8) and count-by-group invariants | class | `packages/runtime/src/state/invariants.ts` -> `InvariantMiner` | [state-and-adapters](runtime/state-and-adapters.md) | +| Diff-centred string previews (F2, timeline, deltas) | function | `packages/runtime/src/state/fields.ts` -> `stringDiff`, `changeText` | [learn-situation-triage](runtime/learn-situation-triage.md) | + ### Observers and trace | X | kind | where | doc | |---|---|---|---| -| fetch wrapper, request/failure gates, stall controller | function | `packages/runtime/src/observe/fetch.ts` -> `installFetch` | [observe-and-trace](runtime/observe-and-trace.md) | +| fetch wrapper, request/failure gates, stall controller, response delivery | function | `packages/runtime/src/observe/fetch.ts` -> `installFetch` | [observe-and-trace](runtime/observe-and-trace.md) | | Max request body hashed for identity (64 KiB) | constant | `packages/runtime/src/observe/fetch.ts` -> `IDENTITY_BODY_MAX` | [observe-and-trace](runtime/observe-and-trace.md) | -| XHR patch | function | `packages/runtime/src/observe/xhr.ts` -> `installXHR` | [observe-and-trace](runtime/observe-and-trace.md) | +| XHR patch (request gate, delivery gate for async responses) | function | `packages/runtime/src/observe/xhr.ts` -> `installXHR` | [observe-and-trace](runtime/observe-and-trace.md) | | DOM user-action observer | function | `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | +| `observe.untrustedEvents` (default `false`: synthetic DOM events are not user actions) | option | `packages/runtime/src/types.ts` -> `InitOptions.observe`; read in `RuntimeImpl.installObservers`; applied in `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` | [observe-and-trace](runtime/observe-and-trace.md) | | `describeElement` (public helper) | function | `packages/runtime/src/observe/dom-user.ts` -> `describeElement` | [observe-and-trace](runtime/observe-and-trace.md) | | `data-genclass-ignore` attribute handling | attribute | `packages/runtime/src/observe/dom-user.ts` -> `ignoredEvent` | [devtools](runtime/devtools.md) | -| WebSocket, timers, nav, storage, errors, longtask observers | function | `packages/runtime/src/observe/{websocket,timers,nav,storage,errors,perf}.ts` -> `installWebSocket`, `installTimers`, `installNav`, `installStorage`, `installErrors`, `installPerf` | [observe-and-trace](runtime/observe-and-trace.md) | +| WebSocket, EventSource, timers, nav, storage, errors, longtask observers | function | `packages/runtime/src/observe/{websocket,eventsource,timers,nav,storage,errors,perf}.ts` -> `installWebSocket`, `installEventSource`, `installTimers`, `installNav`, `installStorage`, `installErrors`, `installPerf` | [observe-and-trace](runtime/observe-and-trace.md) | | GET cache and coalescing table | class | `packages/runtime/src/observe/cache.ts` -> `ResponseCache` | [observe-and-trace](runtime/observe-and-trace.md) | | Cache limits (`MAX_BODY` 256 KB, `MAX_ENTRIES` 64, `COALESCE_WINDOW_MS` 2000) | constant | `packages/runtime/src/observe/cache.ts` | [observe-and-trace](runtime/observe-and-trace.md) | | `x-genclass: blocked\|cached\|coalesced` response header | header | `packages/runtime/src/observe/cache.ts` -> `makeResponse`, `blockedResponse` | [observe-and-trace](runtime/observe-and-trace.md) | @@ -597,7 +749,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | Event ring buffer | class | `packages/runtime/src/trace/events.ts` -> `EventLog` | [observe-and-trace](runtime/observe-and-trace.md) | | Op signature normalisation (`GET /api/items/:id`) | function | `packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`, `requestSignature` | [observe-and-trace](runtime/observe-and-trace.md) | | Hashing | function | `packages/runtime/src/util.ts` -> `fnv1a`, `stableStringify` | [public-api](runtime/public-api-and-lifecycle.md) | -| Default redaction | constant | `packages/runtime/src/util.ts` -> `defaultRedact` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Default redaction (leaf-name based) | function | `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath` | [learn-situation-triage](runtime/learn-situation-triage.md) | ### State and adapters @@ -613,7 +765,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | Redux enhancer and replace action `"@@genclass/REPLACE"` | symbol | `packages/runtime/src/adapters/redux.ts` -> `genclassEnhancer`, `GENCLASS_REPLACE` | [state-and-adapters](runtime/state-and-adapters.md) | | Zustand middleware | function | `packages/runtime/src/adapters/zustand.ts` -> `genclass` | [state-and-adapters](runtime/state-and-adapters.md) | -### Learn, situation and questions (frozen at `situation-v1`) +### Learn, situation and questions (frozen at `situation-v2`) | X | kind | where | doc | |---|---|---|---| @@ -626,11 +778,11 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | Diagnosis vocabulary (10 labels) | constant | `packages/runtime/src/situation/questions.ts` -> `DEFAULT_DIAGNOSES` | [model-io-contract](model-io-contract.md) | | Standing-question builder; bare labels at <= 1,400 chars | function, constant | `packages/runtime/src/situation/questions.ts` -> `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | [model-io-contract](model-io-contract.md) | | Budget-shaped state | function | `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits` | [learn-situation-triage](runtime/learn-situation-triage.md) | -| Budgets 3,200 / 1,100 / 500 chars | constant | `packages/runtime/src/situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET` | [model-io-contract](model-io-contract.md) | +| Budgets 2,400 / 1,100 / 500 chars (full was 3,200 in v1) | constant | `packages/runtime/src/situation/serialize.ts` -> `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET` | [model-io-contract](model-io-contract.md) | | Read-only runtime view for situation code; trigger subjects | type | `packages/runtime/src/situation/env.ts` -> `SitEnv`, `SubjectSpec` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Op phrasing in situations and `changed` sentences | function | `packages/runtime/src/situation/describe.ts` -> `opPhrase` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Python port of the situation text | function | `training/curriculum/rt.py` -> `render` | [training](training.md) | -| Freeze marker | git tag | `situation-v1` (1a77558); check `git diff situation-v1 HEAD -- packages/runtime/src` | [model-io-contract](model-io-contract.md) | +| Freeze marker | git tag | `situation-v2` (6e5e86e; current); `situation-v1` (1a77558; old format). Check with `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/learn packages/runtime/src/util.ts packages/runtime/src/state/fields.ts` (empty at b435acb) | [model-io-contract](model-io-contract.md) | ### Decide, policy and reports @@ -640,6 +792,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | Runtime-side provider timeout (10 s) | constant | `packages/runtime/src/decide/decider.ts` -> `PROVIDER_TIMEOUT_MS` | [decide-policy](runtime/decide-policy-actions.md) | | Summed-mass gate (CONTRACT §8) | function | `packages/runtime/src/decide/policy.ts` -> `gate` | [decide-policy](runtime/decide-policy-actions.md) | | Default thresholds (report 0.6, guard 0.9, heal 0.8) | config | `packages/runtime/src/decide/policy.ts` -> `policyConfig` | [decide-policy](runtime/decide-policy-actions.md) | +| Mode -> permitted tiers | function | `packages/runtime/src/decide/policy.ts` -> `modeAllows`, `permittedActions` | [decide-policy](runtime/decide-policy-actions.md) | | Hold budget (auto: clamp 150-800 ms, fallback 300) | function, constant | `packages/runtime/src/decide/policy.ts` -> `holdBudget`, `HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS` | [decide-policy](runtime/decide-policy-actions.md) | | Rate limiter (`policy.maxActionsPerMinute`, default 60) | class | `packages/runtime/src/decide/policy.ts` -> `RateLimiter`, `policyConfig` | [decide-policy](runtime/decide-policy-actions.md) | | `Controller` / `NetHost` seams | type | `packages/runtime/src/decide/exec.ts` -> `Controller`, `NetHost` | [decide-policy](runtime/decide-policy-actions.md) | @@ -650,7 +803,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | X | kind | where | doc | |---|---|---|---| | Model host factory | function | `packages/runtime/src/model/host.ts` -> `createModelHost` | [model-host](runtime/model-host.md) | -| Default model URL (unpublished `@genclass/runtime-model@0.1.0`) | constant | `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | [model-host](runtime/model-host.md) | +| Default model URL (unpublished `@genclass/runtime-model@0.1.0`, 404) | constant | `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | [model-host](runtime/model-host.md) | | Host defaults (`DEFAULT_TIMEOUT_MS` 10 s, `DEFAULT_MAX_QUEUE` 32) | constant | `packages/runtime/src/model/host.ts` | [model-host](runtime/model-host.md) | | Worker URL literal `new Worker(new URL("./worker.js", import.meta.url), ...)` | code pattern | `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory` | [build-test-release](runtime/build-test-release.md) | | Load and evaluate (in the worker or inline) | class | `packages/runtime/src/model/backend.ts` -> `ModelBackend` | [model-host](runtime/model-host.md) | @@ -668,7 +821,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | sha256 integrity / sha1 header keys | function | `packages/runtime/src/model/hash.ts` -> `sha256Hex`, `sha1Hex` | [model-host](runtime/model-host.md) | | Host <-> worker messages | type | `packages/runtime/src/model/protocol.ts` -> `ToWorker`, `FromWorker` | [model-host](runtime/model-host.md) | | `genclass-runtime fetch-model <dir>` / `info <dir>` | CLI | `packages/runtime/bin/genclass-runtime.mjs` -> `fetchModel`, `info` | [model-host](runtime/model-host.md) | -| CLI default source (release `runtime-model-v0.1.0`, does not exist yet) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | +| CLI default source (release `runtime-model-v0.1.0`, 404) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | ### Devtools overlay @@ -676,29 +829,32 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r |---|---|---|---| | `mountDevtools` (`@genclass/runtime/devtools`) | function | `packages/runtime/src/devtools/index.ts` -> `mountDevtools` | [devtools](runtime/devtools.md) | | Alt+Shift+G toggle | key binding | `packages/runtime/src/devtools/index.ts` -> `Devtools` | [devtools](runtime/devtools.md) | +| Mode labels "Observe (default)" / "Guard (opt-in)" / "Heal (experimental)" | string | `packages/runtime/src/devtools/index.ts` -> `Devtools` | [devtools](runtime/devtools.md) | | Report sentence parsing | function | `packages/runtime/src/devtools/ui.ts` -> `splitReport` | [devtools](runtime/devtools.md) | | Stylesheet | constant | `packages/runtime/src/devtools/css.ts` -> `CSS` | [devtools](runtime/devtools.md) | -### Build, test and release +### Build, test, CI and release | X | kind | where | doc | |---|---|---|---| | Workspaces (`packages/*`, `sim`, `demos`) and root scripts `build`, `test`, `typecheck` | config | `package.json` -> `workspaces`, `scripts` | [build-test-release](runtime/build-test-release.md) | +| Root lockfile (committed) | file | `package-lock.json` | [build-test-release](runtime/build-test-release.md) | +| **CI** (typecheck, build, unit tests, perf budgets) | workflow | `.github/workflows/ci.yml` -> job `runtime` | [build-test-release](runtime/build-test-release.md) | | Subpath exports and `bin` | config | `packages/runtime/package.json` -> `exports`, `bin` | [build-test-release](runtime/build-test-release.md) | | Build entries and externals | config | `packages/runtime/tsup.config.ts` -> `entry`, `dts`, `external` | [build-test-release](runtime/build-test-release.md) | | Unit-test include/exclude | config | `packages/runtime/vitest.config.ts` | [build-test-release](runtime/build-test-release.md) | -| Typecheck: `npx tsc -p tsconfig.json --noEmit` (in `packages/runtime`) | command | `packages/runtime/package.json` -> `scripts.typecheck` | [build-test-release](runtime/build-test-release.md) | -| Unit tests: `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (in `packages/runtime`) | command | `packages/runtime/vitest.config.ts`; gc check in `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | +| Typecheck: `npx tsc -p tsconfig.json --noEmit` (in `packages/runtime`), or `npm run typecheck -w @genclass/runtime` | command | `packages/runtime/package.json` -> `scripts.typecheck` | [build-test-release](runtime/build-test-release.md) | +| Unit tests: `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then `npx vitest run test/review-perf.test.ts --retry=2` (in `packages/runtime`) | command | `packages/runtime/vitest.config.ts`; `.github/workflows/ci.yml`; gc check in `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | | Browser specs `npm run test:browser` (ask first) | command | `packages/runtime/package.json` -> `scripts.test:browser`; `packages/runtime/test/browser/playwright.config.ts` | [build-test-release](runtime/build-test-release.md) | | Smoke test `bash test/smoke/smoke.sh` (ask first) | command | `packages/runtime/test/smoke/smoke.sh` | [build-test-release](runtime/build-test-release.md) | -| Core test harness | function, class | `packages/runtime/test/helpers.ts` -> `setup`, `FakeClock`, `FakeServer`, `ScriptedDecider`, `ManualDecider` | [build-test-release](runtime/build-test-release.md) | +| Core test harness (`setup()` defaults to `mode: "guard"`) | function, class | `packages/runtime/test/helpers.ts` -> `setup`, `FakeClock`, `FakeServer`, `ScriptedDecider`, `ManualDecider` | [build-test-release](runtime/build-test-release.md) | | Scripted `Runtime` for UI/adapter tests | class | `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime` | [devtools](runtime/devtools.md) | | Real runtime under virtual time for UI tests | function | `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession` | [devtools](runtime/devtools.md) | | Scripted store story | function | `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario` | [devtools](runtime/devtools.md) | | Playwright global setup (rebuilds `dist/`) | function | `packages/runtime/test/browser/build.mjs` -> `buildLibrary` | [build-test-release](runtime/build-test-release.md) | | Model fixtures from an export instead of v0.1 | flag | `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL` | [build-test-release](runtime/build-test-release.md) | | VM helper `scripts/vm.sh sync\|run\|exec\|get SLOT ...` (Azure; ask first) | command | `scripts/vm.sh` | [build-test-release](runtime/build-test-release.md) | -| Release tags `v0.1.0-alpha.0` (654d822), `situation-v1` (1a77558) | git tag | `git tag -n1` | [build-test-release](runtime/build-test-release.md) | +| Release and freeze tags `v0.1.0-alpha.0` (654d822), `situation-v1` (1a77558), `situation-v2` (6e5e86e) | git tag | `git tag -n1` | [build-test-release](runtime/build-test-release.md) | ### Environment variables @@ -708,10 +864,18 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | `GENCLASS_WEBGPU_VARIANTS` | WebGPU spec variants | `packages/runtime/test/browser/model-webgpu.spec.ts` | [build-test-release](runtime/build-test-release.md) | | `GENCLASS_BENCH_MODELS`, `GENCLASS_OFFLINE` | browser model specs | `packages/runtime/test/browser/model.spec.ts` | [build-test-release](runtime/build-test-release.md) | | `NODE_OPTIONS=--expose-gc` | gc check in a REVIEW test | `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | +| `ONNXRUNTIME_NODE_INSTALL=skip` | CI: stops the dev-only `onnxruntime-node` from downloading CUDA binaries during `npm ci` | `.github/workflows/ci.yml` | [build-test-release](runtime/build-test-release.md) | | `SIM_RUNTIME=real` | sim tests use the real runtime | `sim/test/helpers.ts` -> `testFactory` | [sim](sim.md) | +| `SIM_S2` (`0` turns S2 latent re-draws off) | sim label futures | `sim/src/run/latent.ts` -> `S2` | [sim](sim.md) | +| `SIM_PROBE=1` | separability probes (analysis only) | `sim/src/oracle/probe.ts` -> `PROBE` | [sim](sim.md) | +| `SIM_FEATURE_HOLDOUT=off` | disables held-out features (train-on-everything runs) | `sim/src/world/scenario.ts` | [sim](sim.md) | +| `RW_RUNTIME_SRC`, `RW_RUNTIME_TAG` | realapps: pin the bundled runtime source and its tag (default the working tree, `working-tree`) | `realapps/build.mjs` | [realapps](realapps.md) | +| `RW_OSS_DIR` (default `~/gcl/real-cache/oss`) | realapps OSS checkouts | `realapps/build.mjs`, `realapps/corpus/prepare_oss.sh` | [realapps](realapps.md) | +| `RW_PORT`, `RW_OPTS` | realapps worker processes (set by the generator) | `realapps/src/harness/worker.ts` | [realapps](realapps.md) | | `GC_P_RUNTIME` (set from `--p-runtime`) | share of runtime-exact curriculum rows | `training/curriculum/generate.py` -> `P_RUNTIME` | [training](training.md) | | `GC_V1_CKPT`, `GC_BASE_32M` | prune tests | `training/tests/test_prune_vocab.py` | [training](training.md) | | `GC_R17_INIT` | export end-to-end test | `training/tests/test_export_runtime.py` | [training](training.md) | +| `RANKS`, `THREADS`, `GA_OVERRIDE`, `LR_OVERRIDE`, `HLR_OVERRIDE` | training launchers | `training/launch_student.sh` (and `RANKS`/`THREADS` in `launch_t150.sh`) | [training](training.md) | | `GENCLASS_SHIM` (`1` forces the runtime shim, `0` forbids it) | demos build | `demos/vite.config.ts` | [demos](demos.md) | | `VITE_GENCLASS_MODEL_URL` | demo model location (after `?model=`) | `demos/src/shared/settings.ts` -> `modelBaseUrl` | [demos](demos.md) | | `GENCLASS_MODEL_FROM`, `GENCLASS_MODEL_DIR`, `GENCLASS_MODEL_URL`, `GENCLASS_MODEL_VARIANT`, `ALLOW_BROKEN_RUNTIME`, `SKIP_EVAL` | demos VM pipeline | `demos/scripts/vm-eval.sh` | [demos](demos.md) | @@ -724,35 +888,63 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | X | kind | where | doc | |---|---|---|---| -| Scenario from a seed; split assignment; held-out domains | function, constant | `sim/src/world/scenario.ts` -> `buildScenario`, `splitOf`, `TEST_DOMAINS` | [sim](sim.md) | -| One run (ideal or real runtime) | function | `sim/src/run/runner.ts` -> `runScenario` | [sim](sim.md) | -| Trajectory -> rows; counterfactual costs | function | `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts` | [sim](sim.md) | +| Scenario from a seed; split assignment; held-out domains and features; budget sampling | function, constant | `sim/src/world/scenario.ts` -> `buildScenario`, `splitOf`, `TEST_DOMAINS`, `TEST_FEATURES` | [sim](sim.md) | +| One run (ideal or real) | function | `sim/src/run/runner.ts` -> `runScenario` | [sim](sim.md) | +| Trajectory -> rows (gold, unlabeled, on-policy); counterfactual costs | function | `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `unlabeledTrajectory`, `pointCosts` | [sim](sim.md) | +| **S1** diagnosis relabel (`S1_GAP` 1.0) | function, constant | `sim/src/gen/trajectory.ts` -> `diagnosisFromOutcome`, `S1_GAP` | [sim](sim.md) | +| **S2** latent re-draws in futures | function | `sim/src/run/latent.ts` -> `futureProfile`, `futureStepTimes`, `idealRepeatSkips`, `REPEAT_PRIOR`; `sim/src/net/network.ts` -> `Network` (`latent`) | [sim](sim.md) | +| On-policy (DAgger) decider: a real export in Node WASM | function | `sim/src/run/onpolicy.ts` -> `loadModelDecider`; flag `--on-policy <dir>` in `sim/src/gen.ts` | [sim](sim.md) | | Run cost, cost weights, soft action label, tier premiums | function, constant | `sim/src/oracle/cost.ts` -> `runCost`, `W`, `actionLabel`, `LABEL`, `TIER` | [sim](sim.md) | | Diagnosis labels | function | `sim/src/oracle/diagnose.ts` -> `diagnose` | [sim](sim.md) | | Ground-truth bookkeeping | class | `sim/src/oracle/knowledge.ts` -> `Knowledge` | [sim](sim.md) | +| Separability probes | constant, class | `sim/src/oracle/probe.ts` -> `PROBE`, `Probe` | [sim](sim.md) | | Virtual event loop | class | `sim/src/loop.ts` -> `VirtualLoop` | [sim](sim.md) | | Seeded RNG with keyed forks | class | `sim/src/rng.ts` -> `Rng`, `hashAll` | [sim](sim.md) | | Virtual network and ideal profile; sim op header | class, constant | `sim/src/net/network.ts` -> `Network`, `IDEAL_PROFILE`, `SIM_OP_HEADER` | [sim](sim.md) | | Virtual server | class | `sim/src/net/server.ts` -> `VirtualServer` | [sim](sim.md) | -| Feature combinators and weights | constant | `sim/src/app/features/index.ts` -> `FEATURES`, `FEATURE_WEIGHTS` | [sim](sim.md) | -| 55 domain vocabularies | constant | `sim/src/app/vocab.ts` -> `DOMAINS` | [sim](sim.md) | -| Loading the real runtime; `createRuntime` options | function | `sim/src/run/rt.ts` -> `realRuntimeFactory`, `createOptions` | [sim](sim.md) | +| Feature combinators (46) and weights | constant | `sim/src/app/features/index.ts` -> `FEATURES`, `FEATURE_WEIGHTS` | [sim](sim.md) | +| 55 + 60 domain vocabularies | constant | `sim/src/app/vocab.ts` -> `DOMAINS`; `sim/src/app/vocab2.ts` -> `DOMAINS2` | [sim](sim.md) | +| Loading the real runtime; `createRuntime` options (mode `heal`) | function | `sim/src/run/rt.ts` -> `realRuntimeFactory`, `createOptions` | [sim](sim.md) | | Fake runtime (test double; generator refuses it without `--allow-fake`) | function | `sim/src/run/fake-runtime.ts` -> `createFakeRuntime`; flag in `sim/src/gen.ts` | [sim](sim.md) | | Ask questions | function | `sim/src/ask/questions.ts` -> `askQuestions` | [sim](sim.md) | | Action-option shuffle/drop and paraphrases | function, constant | `sim/src/run/transform.ts` -> `transformQuestions`, `ACTION_PARA` | [sim](sim.md) | | CONTRACT-D row type | type | `sim/src/types.ts` -> `Row`, `Label` | [model-io-contract](model-io-contract.md) | -| `node sim/dist/gen.js --rows N --out DIR ...` (`--sample`, `--parts`) (ask first) | CLI | `sim/src/gen.ts` -> `main` | [sim](sim.md) | -| `bash sim/scripts/final.sh a\|b\|merge-b` (VM; ask first) | command | `sim/scripts/final.sh` | [sim](sim.md) | +| `node sim/dist/gen.js --rows N --out DIR ...` (`--sample`, `--parts`, `--unlabeled`, `--on-policy`) (ask first) | CLI | `sim/src/gen.ts` -> `main` | [sim](sim.md) | +| Re-derive action labels from `meta.cost_futures` | script | `sim/scripts/relabel.py` | [sim](sim.md) | +| Azure generation (`bigrun.sh gold\|unl`, `collect.py`) (Azure; ask first) | script | `sim/scripts/cluster/` | [sim](sim.md) | +| `bash sim/scripts/final.sh a\|b\|merge-b` (v1; VM; ask first) | command | `sim/scripts/final.sh` | [sim](sim.md) | + +### realapps + +| X | kind | where | doc | +|---|---|---|---| +| App manifest and affordance types | type | `realapps/src/shared/manifest.ts` -> `AppManifest`, `Affordance` | [realapps](realapps.md) | +| The app's one-line runtime integration | function | `realapps/apps/_shared/genclass.ts` | [realapps](realapps.md) | +| Shared manifest builder for the 14 OSS Conduits | function | `realapps/apps/_shared/conduit-manifest.ts` -> `conduitManifest` | [realapps](realapps.md) | +| Scenario from a seed; held-out apps/frameworks; split | function, constant | `realapps/src/harness/scenario.ts` -> `buildScenario`, `splitOf`, `TEST_APPS`, `TEST_FRAMEWORKS` | [realapps](realapps.md) | +| Trajectory -> rows; observer map; runtime tag | function, constant | `realapps/src/harness/trajectory.ts` -> `generateTrajectory`, `OBSERVE`, `runConfig`, `RUNTIME_TAG` | [realapps](realapps.md) | +| Run cost (mirrors the sim) | function | `realapps/src/harness/cost.ts` -> `runCost` | [realapps](realapps.md) | +| In-page diagnosis rules | function | `realapps/src/world/diagnose.ts` -> `diagnose`; Node side `realapps/src/harness/labels.ts` -> `finishDiagnosis` | [realapps](realapps.md) | +| Recording decider, hooks, snapshots | class | `realapps/src/world/probe.ts` -> `Probe` | [realapps](realapps.md) | +| Headless Chromium runner | class | `realapps/src/harness/browser.ts` -> `Runner` | [realapps](realapps.md) | +| Never-worse (`--interference`) and determinism (`--det`) sweeps (Chromium; ask first) | CLI | `realapps/src/harness/debug.ts` | [realapps](realapps.md) | +| Generator `node dist/harness/gen.js --out DIR ...` (Chromium; ask first) | CLI | `realapps/src/harness/gen.ts` | [realapps](realapps.md) | +| Real-app eval set | script | `realapps/scripts/evalset.py` | [realapps](realapps.md) | +| Azure batches (`cluster.sh sync\|setup\|run\|status\|stop`) (Azure; ask first) | script | `realapps/scripts/cluster.sh`, `realapps/scripts/node_setup.sh` | [realapps](realapps.md) | ### training and the Python reference | X | kind | where | doc | |---|---|---|---| +| Scaled training plan (P0-P5) | doc | `training/PLAN-v1.md` | [training](training.md) | | Curriculum row factory | function | `training/curriculum/generate.py` -> `make_row` | [training](training.md) | | Scenario result dataclass | class | `training/curriculum/scenarios.py` -> `Scen` | [training](training.md) | | Surface-variation templates | constant | `training/curriculum/fmt.py` -> `TEMPLATES`, `Style` | [training](training.md) | | Curriculum domains (13 held out) | constant | `training/curriculum/vocab.py` -> `DOMAINS`, `TEST_DOMAINS` | [training](training.md) | | Calibration fit and gate metrics | function | `training/eval_runtime.py` -> `fit_calibration`, `decision_metrics` | [training](training.md) | +| Teacher soft-labelling (one shard / across nodes) | script | `training/label_teacher.py` -> `main`; `training/label_cluster.sh` | [training](training.md) | +| Student / teacher launchers | script | `training/launch_student.sh`, `training/launch_t150.sh`, `training/launch_r68.sh` | [training](training.md) | +| T1 expected-gain relabel and eval | script | `training/t1_relabel.py` -> `relabel_row`, `gains_of`; `training/eval_gain.py` -> `evaluate`, `classify` | [training](training.md) | | q8 / fp16 export | function | `training/export_runtime.py` -> `make_q8`, `make_fp16` | [training](training.md) | | Vocabulary pruning | function | `training/prune_vocab.py` -> `prune_tokenizer_json` | [training](training.md) | | Export check in onnxruntime-web WASM: `node validate.mjs <dir> [variant] [maxRequests]` | CLI | `training/ortweb/validate.mjs` | [training](training.md) | @@ -762,7 +954,7 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r | Python packer (reference for `model/packer.ts`) | class | `jev_local/engine/encoder/tokenize_pack.py` -> `Packer` | [lineage](genclass-model-lineage.md) | | Python calibration lookup (reference for `model/calibrate.ts`) | function | `jev_local/engine/encoder/calibrate.py` -> `header_key`, `tau_for` | [lineage](genclass-model-lineage.md) | | Python answer math | function | `jev_local/confidence.py` -> `build_answer` | [lineage](genclass-model-lineage.md) | -| Decision heads | class | `jev_local/engine/encoder/heads.py` -> `DecisionHeads` | [lineage](genclass-model-lineage.md) | +| Decision heads (no gain head in this repo) | class | `jev_local/engine/encoder/heads.py` -> `DecisionHeads` | [lineage](genclass-model-lineage.md) | | Python inference engine | class | `jev_local/engine/encoder/engine.py` -> `FastEngine` | [lineage](genclass-model-lineage.md) | | ONNX graph definition (imported by the runtime exporter) | class | `scripts/genclass_export.py` -> `ExportModel` | [model-io-contract](model-io-contract.md) | | Jev-wire HTTP server | function | `jev_local/server/app.py` -> `create_app` | [lineage](genclass-model-lineage.md) | @@ -786,26 +978,29 @@ Verified with `grep` at 654d822. Methods are `RuntimeImpl.<name>` in `packages/r ## 4. Generated and ignored paths -Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitignore` and `packages/runtime/test/browser/.gitignore`. The root rules `data/`, `models/`, `runs/`, `dist/` and `node_modules/` have no leading slash, so they match at any depth. +Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitignore`, `realapps/.gitignore` and `packages/runtime/test/browser/.gitignore`. The root rules `data/`, `models/`, `runs/`, `dist/` and `node_modules/` have no leading slash, so they match at any depth. | path | ignored by | produced by | notes | |---|---|---|---| -| `node_modules/` (root) | root | `npm install` at the repo root (workspaces hoisted; about 134 packages) | `extension/` and `training/ortweb/` are not workspaces and need their own `npm install` | -| `package-lock.json` (root) | **not ignored** | `npm install` at the root | never committed; shows as untracked. Do not commit it unless asked | -| `packages/runtime/bin/genclass-runtime.mjs` mode change | — | `npm install` chmods it to 755 (committed mode 644) | shows as a modified file; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | +| `node_modules/` (root) | root | `npm ci` / `npm install` at the repo root (workspaces hoisted) | `extension/`, `realapps/` and `training/ortweb/` are not workspaces and need their own `npm install` | +| `package-lock.json` (root) | **tracked** since b435acb | `npm install` at the root rewrites it | CI uses `npm ci`, which fails if `package.json` and the lockfile disagree; commit lockfile changes only when you changed dependencies on purpose | +| `packages/runtime/bin/genclass-runtime.mjs` mode | — | committed as 100755 since b435acb | the old spurious "mode changed" diff after `npm install` is gone | | `packages/runtime/dist/` | root `dist/` | `npx tsup` / `npm run build` (in `packages/runtime`); also `sim`'s `build:runtime-core` script and `packages/runtime/test/browser/build.mjs` (Playwright global setup) rewrite it | `sim` and `demos` import the runtime through this `dist/`; a working copy may hold a stale one | -| `sim/dist/` | root `dist/` | `npm run build` in `sim` (tsup: `gen`, `worker`, `index`, `smoke`) | — | +| `sim/dist/` | root `dist/` | `npm run build` in `sim` (tsup: `gen`, `worker`, `index`, `smoke`; plus `build:model-host` -> `sim/dist/model-host/`) | — | +| `realapps/dist/`, `realapps/node_modules/` | root and `realapps/.gitignore` | `node build.mjs` in `realapps/` (world, harness, apps, `runtime-tag.txt`); `npm install` there | builds launch nothing, but the outputs are only useful with Chromium (ask first to run) | +| `realapps/src/harness/apps.gen.ts` | `realapps/.gitignore` | `realapps/build.mjs` (one import per `apps/*/manifest.ts`) | regenerate after adding an app | +| `~/gcl/real-cache/oss`, `~/gcl/real-out/<batch>` | outside the repo | `realapps/corpus/prepare_oss.sh` (`RW_OSS_DIR`); `gen.js --out` via `cluster.sh run` | VM paths | | `demos/dist/` | root and `demos/.gitignore` | `npm run build` in `demos` (`demos/scripts/build.mjs`) | — | | `extension/dist/` | root and `extension/.gitignore` | `extension/scripts/build.mjs` (`dist/genclass/`) | — | -| `sim/out/` | root | `sim/src/gen.ts` (default `--out sim/out/run`), `sim/scripts/final.sh` (`sim/out/final-a/`, `sim/out/final-b/parts/`) | training data; excluded from `scripts/vm.sh` syncs | -| `.cache-model/` | root | `node packages/runtime/bin/genclass-runtime.mjs fetch-model .cache-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` (ask first: download; without `--from` the CLI uses the unpublished `DEFAULT_FROM`) | default `GENCLASS_MODEL_DIR`; absent in a fresh clone, so 14 model tests skip | -| `packages/runtime-model/files/` | root | intended for `training/export_runtime.py` output (the planned `@genclass/runtime-model` package) | does not exist at 654d822 | +| `sim/out/` | root | `sim/src/gen.ts` (default `--out sim/out/run`), `sim/scripts/final.sh` (`sim/out/final-a/`, `sim/out/final-b/parts/`) | training data; excluded from `scripts/vm.sh` syncs. v2 production data lives on the train VM under `/data/sim-out/v2-*` and REAL's under `/data/real-out/` (per `training/NEEDS.md`; not checked) | +| `.cache-model/` | root | `node packages/runtime/bin/genclass-runtime.mjs fetch-model .cache-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` (ask first: download; without `--from` the CLI uses `DEFAULT_FROM`, which 404s) | default `GENCLASS_MODEL_DIR`; absent in a fresh clone, so 14 model tests skip. The v0.1 model is a parity fixture only; it does not match situation-v2 | +| `packages/runtime-model/files/` | root | intended for `training/export_runtime.py` output (the planned `@genclass/runtime-model` package) | does not exist at b435acb | | `demos/public/genclass-model/` | `demos/.gitignore` | `npm run fetch-model` in `demos` (`demos/scripts/fetch-model.sh`, v0.1 model) | — | | `packages/runtime/test/browser/.build/` | `packages/runtime/test/browser/.gitignore` | `packages/runtime/test/browser/build.mjs` | bundled test app and build info | | `test-results/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright (`packages/runtime/test-results/{browser,ui}`), model benchmarks (`packages/runtime/test-results/model-bench/`) | — | | `playwright-report/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright HTML reporter | — | | `demos/e2e/.out/` | `demos/.gitignore` | `demos/e2e/eval.ts` (`partial.json`, `traces*.json` with `--trace`) | input to `demos/e2e/trace-report.ts` | -| `*.tgz` | root | `npm pack` in `packages/runtime/test/smoke/smoke.sh` (left in `packages/runtime/`) | — | +| `*.tgz` | root | `npm pack` in `packages/runtime/test/smoke/smoke.sh` (left in `packages/runtime/`) | the alpha.1 patch tarball would also land here | | `.publish/` | root | no tracked script; added with the alpha publish (59c213f) | purpose not recorded | | `.vite/` | root | Vite cache directory (no config in the repo sets `cacheDir`; Vite's default is `node_modules/.vite`) | — | | `data/` (any depth) | root | not produced in this repo. Matches the missing `jev_local/data/` (data generators) and `demos/src/server/data/cities.ts`; Azure hosts keep training data under `$G/data/` | the rule hides source files that the code imports | @@ -814,11 +1009,11 @@ Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitign | `extension/release-assets/*.onnx` | `extension/.gitignore` | `extension/tools/genclass_export.py` | absent | | `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/` | root | Python venv, pytest, `pip install -e .` of `jev-local` | — | | `.DS_Store` | root, `extension/.gitignore` | macOS Finder | — | -| `docs/agents/`, `AGENTS.md`, `CLAUDE.md` | not ignored | these agent docs | untracked at 654d822 | +| `docs/agents/realapps.md` | not ignored | new, not yet committed | untracked at b435acb; commit it with the other doc refreshes | ## 5. Large files: do not read in full -Sizes from `wc -c` / `wc -l` at 654d822. "0 lines" means one line with no trailing newline: inspect it with `python3 -c` or `jq` (keys, lengths, one record) instead of opening it. +Sizes from `git ls-tree -l b435acb` / `wc -l`. "0 lines" means one line with no trailing newline: inspect it with `python3 -c` or `jq` (keys, lengths, one record) instead of opening it. | path | bytes | lines | what it is / how to read it | |---|---|---|---| @@ -827,9 +1022,9 @@ Sizes from `wc -c` / `wc -l` at 654d822. "0 lines" means one line with no traili | `extension/test/fixtures/policy_py.json` | 3,069,755 | 0 | Python-harness policy parity fixture | | `extension/test/fixtures/pack_fixtures.json` | 1,228,103 | 0 | Python packer output for the v0.1 requests | | `packages/runtime/test/fixtures/model/pack_fixtures.json` | 955,379 | 0 | compact copy of the extension's pack fixtures; read through `packages/runtime/test/model/helpers.ts` -> `packs` | -| `sim/samples/sample.jsonl` | 848,581 | 200 | 200 CONTRACT-D rows (about 4 KB each); read one line, or `sim/samples/EXAMPLES.md` | +| `demos/results.json` | 922,287 | 46,000 | raw demo trials; read `demos/results.md` or `demos/results-summary.json` instead | +| `sim/samples/sample.jsonl` | 896,221 | 200 | 200 CONTRACT-D rows (about 4.5 KB each, situation-v2); read one line, or `sim/samples/EXAMPLES.md` | | `bench/public/targets.json` | 785,218 | 30,045 | 549 benchmax targets | -| `demos/results.json` | 773,038 | 39,384 | raw demo trials; read `demos/results.md` or `demos/results-summary.json` instead | | `bench/public/jev_published.json` | 383,059 | 8,236 | 549 published Jev numbers | | `extension/test/fixtures/requests50.json` | 346,737 | 9,399 | the 50 harness requests with `gold` and `screen_type` | | `packages/runtime/test/fixtures/model/requests50.json` | 285,309 | 0 | the same 50 requests without `gold`/`screen_type` | @@ -838,19 +1033,33 @@ Sizes from `wc -c` / `wc -l` at 654d822. "0 lines" means one line with no traili | `extension/test/fixtures/questions_py.json` | 222,955 | 16,984 | Python-harness question fixtures | | `docs/benchmax-research/jev-published.md` | 217,513 | 2,206 | census of published Jev numbers | | `packages/runtime/test/fixtures/model/py_fixtures.json` | 167,629 | 0 | Python reference cases for serialize/tokenize/calibrate/confidence | +| `package-lock.json` | 105,864 | 3,203 | root lockfile; never edit by hand | | `jev_local/bench/registry.py` | 90,896 | 1,888 | jevbench dataset registry and exclusion rules (source; grep it) | +| `packages/runtime/src/runtime.ts` | 87,440 | 2,003 | `RuntimeImpl`; jump to methods by name (`trigger`, `runDelivery`, `onDecision`, `settled`) | | `docs/SPEC.md` | 84,347 | 1,131 | legacy jev-local rebuild spec | | `docs/benchmax-research/{PLAN,feasibility-targets,suite-reproduction-specs,train-data-and-supervised-ceilings}.md` | 72,630-93,641 each | 768-971 each | benchmax planning notes | -| `packages/runtime/src/runtime.ts` | 65,221 | 1,583 | `RuntimeImpl`; jump to methods by name (`trigger`, `onDecision`, `settled`) | +| `packages/runtime/STATUS.md` | 75,336 | 1,045 | CORE status; read "State", then the batch section you need | +| `sim/samples/EXAMPLES.md` | 68,211 | 1,484 | pretty-printed sim rows | +| `training/curriculum/rt.py` | 66,963 | 1,349 | Python port of the situation renderer; grep by function (`render`, `event_lines`, `content_facts`) | | `extension/test/fixtures/spans_py.json` | 59,806 | 5,458 | Python-harness span fixtures | | `bench/public/exclusions.json` | 59,101 | 2,297 | benchmax exclusion manifest | -| `sim/samples/EXAMPLES.md` | 52,713 | 1,345 | pretty-printed sim rows | | `scripts/benchmax_build_targets.py` | 52,170 | 671 | target/exclusion generator | | `extension/package-lock.json` | 50,300 | 1,506 | extension lockfile | -| `packages/runtime/src/devtools/index.ts` | 49,689 | 1,291 | `Devtools` class; read by method | +| `packages/runtime/src/devtools/index.ts` | 49,745 | 1,291 | `Devtools` class; read by method | | `jev_local/bench/benchmax/adapters_b/vendor/earino/val_indices.json` | 43,930 | 0 | vendored upstream indices | -| `docs/agents/*.md`, `docs/agents/runtime/*.md` (subsystem docs) | about 66,000-103,000 each | — | read the TL;DR, then the section you need | +| `docs/agents/*.md`, `docs/agents/runtime/*.md` (subsystem docs) | about 66,000-137,000 each | — | read the TL;DR, then the section you need | + +Binary files: 64 tracked PNGs (11,520,386 bytes in total: 18 devtools screenshots, 31 demo screenshots, 10 Chrome Web Store images, 5 extension icons) and 3 WAV clips under `extension/test/fixtures/audio/` (219,600 bytes). Model weights (`*.onnx`) are never tracked. + +Other source files over 25 KB that are better read by symbol than end to end: `packages/runtime/src/situation/facts.ts` (706 lines), `packages/runtime/src/state/hub.ts` (840), `packages/runtime/src/observe/fetch.ts` (654), `packages/runtime/src/model/host.ts` (752), `sim/src/run/runner.ts` (843), `jev_local/train/train.py` (1,059), `jev_local/train/stream.py` (917), `docs/runtime/CONTRACT.md` (525). + +## 6. Drift and open issues (map-level) -Binary files: 63 tracked PNGs (11,388,350 bytes in total: 18 devtools screenshots, 30 demo screenshots, 10 Chrome Web Store images, 5 extension icons) and 3 WAV clips under `extension/test/fixtures/audio/` (219,600 bytes). Model weights (`*.onnx`) are never tracked. +Doc-vs-code drift you will meet while navigating; the subsystem docs have the details. -Other source files over 25 KB that are better read by symbol than end to end: `packages/runtime/src/situation/facts.ts` (568 lines), `packages/runtime/src/model/host.ts` (752), `packages/runtime/src/observe/fetch.ts` (630), `packages/runtime/src/state/hub.ts` (734), `training/curriculum/rt.py` (829), `jev_local/train/train.py` (1,059), `jev_local/train/stream.py` (917), `docs/runtime/CONTRACT.md` (519), `packages/runtime/STATUS.md` (533). +- **Default mode**: code, `docs/runtime/API.md`, CONTRACT §13 and the devtools say `observe`; `README.md` and `packages/runtime/README.md` agree; only `HANDOFF.md` (and the published alpha.0) still say guard is the default. +- **`OPEN_TASKS.md`** now describes the v2 pipeline (items 1-14); see also [HANDOFF.md](../../HANDOFF.md) and [training.md](training.md). +- **App counts**: `realapps/README.md` and `HANDOFF.md` say 66 apps; the tree has 91 (25 added after the sweeps were run). The never-worse result 0/396 covers the 66 ([realapps.md](realapps.md)). +- **Sim budget**: `sim/src/world/scenario.ts` still samples situation budgets 3,200 / 2,000 / 1,000 (40/30/30), while the v2 runtime's full budget is 2,400 ([sim.md](sim.md)). +- **Test counts**: `packages/runtime/STATUS.md` says 41 files / 346 tests (before `default-mode.test.ts`); see [runtime/build-test-release.md](runtime/build-test-release.md) for the b435acb numbers. +- **realapps output**: batch `manifest.json` files hardcode `situation-v1` and `TRIGGER_W` has no `delivery` weight (`realapps/src/harness/gen.ts`, `realapps/src/harness/trajectory.ts`); see [realapps.md](realapps.md). diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index 794a1005..eed18986 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -1,24 +1,26 @@ # Build, test and release (@genclass/runtime and the monorepo) -> **Scope:** `package.json` (root), `tsconfig.base.json`, `.gitignore`, `packages/runtime/{package.json,tsconfig.json,tsup.config.ts,vitest.config.ts}`, `packages/runtime/test/**` (unit, model, browser, smoke, fixtures), `packages/runtime/STATUS.md` ("State" and "How to drive it headless"), `scripts/vm.sh`, `OPEN_TASKS.md` (packaging), `sim/package.json`, `demos/package.json`, `packages/runtime-model/`. -> **Read this when:** you need to build, typecheck or test the runtime; add or fix a test; regenerate fixtures; run the Playwright model/UI specs or the npm-pack smoke test; publish a version; add CI; or understand how `sim/` and `demos/` consume the runtime package. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `package.json` and `package-lock.json` (root), `tsconfig.base.json`, `.gitignore`, `.github/workflows/ci.yml`, `packages/runtime/{package.json,tsconfig.json,tsup.config.ts,vitest.config.ts}`, `packages/runtime/bin/genclass-runtime.mjs` (packaging only), `packages/runtime/test/**` (unit, model, browser, smoke, fixtures), `packages/runtime/STATUS.md` ("State" and "How to drive it headless"), `scripts/vm.sh`, `OPEN_TASKS.md` and `HANDOFF.md` (packaging, release), `sim/package.json`, `demos/package.json`, `realapps/package.json`, `packages/runtime-model/`. +> **Read this when:** you need to build, typecheck or test the runtime; add or fix a test; understand or change CI; regenerate fixtures; run the Playwright model/UI specs or the npm-pack smoke test; publish a version; or understand how `sim/`, `demos/` and `realapps/` consume the runtime package. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR -- npm workspaces monorepo: `packages/*`, `sim`, `demos`. Root scripts only touch the runtime: `npm run build` / `npm test` run in `@genclass/runtime`; `npm run typecheck` runs every workspace's `typecheck` (`--if-present`). -- **Team rule: the Mac only edits files.** Every `npm install`, build, typecheck, vitest, Playwright, smoke test and model run happens on the Azure `train` VM through `scripts/vm.sh` in your own *slot* (the original Mac had 8 GB RAM). Stated in `scripts/vm.sh` (header) and `docs/runtime/CONTRACT.md` §0 rule 5. -- **Lead policy for agents (2026-10-07):** on machines other than that 8 GB Mac, `npm install`, typecheck, build and unit tests are light and verified to work locally. Ask the user before running the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). See [Where to run things](#where-to-run-things) and [Verified locally (2026-10-07)](#verified-locally-2026-10-07). -- Build = `tsup` (`packages/runtime/tsup.config.ts`): ESM only, 6 entries (`index`, 3 adapters, `devtools/index`, `worker`), `.d.ts` for all but the worker, `clean: true`, `splitting: true`. Output goes to `packages/runtime/dist/`, which `package.json` `exports` points at. +- npm workspaces monorepo: `packages/*`, `sim`, `demos` (`realapps/` has its own `package.json` but is **not** a workspace). Root `npm run build` / `npm test` touch only `@genclass/runtime`; root `npm run typecheck` runs every workspace's `typecheck` (`--if-present`: runtime, `sim`, `demos`), and the demos part fails in this checkout (see gotchas). +- **A root `package-lock.json` is committed now** (b435acb, lockfileVersion 3), so `npm ci` works on a fresh clone and CI uses it. +- **CI exists**: `.github/workflows/ci.yml` (b435acb), one job on `ubuntu-latest`, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`: `npm ci` -> typecheck -> build -> unit tests (browser specs and `review-perf.test.ts` excluded) -> `review-perf.test.ts` alone with `--retry=2`. Triggers: push to `main`, `runtime`, `mvp`, `mvp-v2`; every `pull_request`; `workflow_dispatch`. It has not run on GitHub yet: `mvp-v2` is not pushed (`origin/runtime` = 74f17c0 has no `.github/`). +- **Run policy.** Mehar's team rule ("the Mac only edits files"; everything runs on the Azure `train` VM through `scripts/vm.sh`) exists because *his* Mac has 8 GB RAM (`HANDOFF.md` "Rules", `scripts/vm.sh` header, `docs/runtime/CONTRACT.md` §0 rule 5). For agents on other machines (lead policy, 2026-10-08): npm install/ci, tsc, tsup and the vitest unit tests are light and run locally; **ask the user first** before Playwright (including `test/smoke/smoke.sh`), the sim generator, training, realapps runs, the demos' eval, model downloads, anything on Azure, `git push` and `npm publish`. See [Where to run things](#where-to-run-things). +- Build = `tsup` (`packages/runtime/tsup.config.ts`, unchanged since situation-v1): ESM only, 6 entries (`index`, 3 adapters, `devtools/index`, `worker`), `.d.ts` for all but the worker, `clean: true`, `splitting: true`. Output goes to `packages/runtime/dist/`, which `package.json` `exports` points at. - Typecheck = `tsc -p tsconfig.json --noEmit` over `src/` only. **Test files are never type-checked.** -- Unit tests = vitest (`vitest run`), 37 files under `test/` and `test/model/`, 300 tests (UI 53, MODEL 62 per STATUS; the other 185 = CORE 142 + REVIEW 43). Default environment `node`; 5 files opt into `happy-dom` per file. Re-run on 2026-10-07 without a model directory: 286 passed, 14 skipped, about 2.4 s. +- Unit tests = vitest, **42 tracked files** (36 under `test/`, 6 under `test/model/`), **350 tests**. Default environment `node`; 5 files opt into `happy-dom` per file. Verified 2026-10-08 without a model directory: 336 passed + 14 skipped, split the way CI runs them (346 in the main run, 4 in `review-perf.test.ts`; see [Verified locally](#verified-locally-2026-10-08)). +- **Default mode is `observe`** in the product (f3636b2: `src/runtime.ts` -> `o.mode ?? "observe"`), but the test harness `test/helpers.ts` -> `setup()` passes `mode: "guard"` by default, and `smoke.test.ts`, `review-fetch.test.ts` -> `headless()` and `test/browser/ui/session.ts` -> `runStoreSession` pass `mode: "guard"` explicitly. Pass `mode: undefined` to `setup()` to get the product default (`test/default-mode.test.ts` does). +- **Store writes are not held by default** (situation-v2, `policy.holdWrites` off). Tests that exercise held store writes pass `policy: { holdWrites: true }` (`atoms.test.ts` wraps `setup()` to add it); default behaviour (delivery decisions at the network boundary, late reverts) is tested in `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts`. - Runtime unit tests run on a virtual clock (`test/helpers.ts` -> `FakeClock`), a virtual HTTP server (`FakeServer`) and a scripted model (`ScriptedDecider` / `ManualDecider`): no real time, no network, no model. Exceptions (wall-time perf checks, `loader.test.ts`'s real `browserClock`, model-file tests) are listed under gotchas. -- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). -- Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. -- `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. -- Released: `@genclass/runtime@0.1.0-alpha.0` on npm (org `genclass`, owner `meharpro`, dated 2026-10-08 in `OPEN_TASKS.md`), git tag `v0.1.0-alpha.0` on 654d822. No publish script, no `prepublishOnly`, **no CI workflow** (no `.github/`), and **no committed root `package-lock.json`** (only `extension/package-lock.json` is tracked). -- Planned: `@genclass/runtime-model@0.1.0` (the model files; the runtime's default CDN URL points at it) and then `@genclass/runtime@0.1.0`. `packages/runtime-model/` holds only `MODEL_CARD.md` today. -- `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. +- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. **No situation-v2 model exists yet**; the only fixtures and models are the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). +- Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. Not run in CI. +- `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. Not run in CI. +- Released: `@genclass/runtime@0.1.0-alpha.0` on npm, dist-tag `latest` (checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish <tgz> --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). Pending: `0.1.0-alpha.1` (NaN fix, `OPEN_TASKS.md` "Needs the user"), then `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. +- `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. `realapps` bundles `packages/runtime/src` directly with esbuild (see [../realapps.md](../realapps.md)). ## Files @@ -27,14 +29,15 @@ | `package.json` | root, private `genclass-lib`, `"type": "module"` | workspaces `packages/*`, `sim`, `demos`; scripts `build`, `test`, `typecheck`; devDep `typescript ~5.9.3`; `engines.node >=20`; license Apache-2.0 | | `tsconfig.base.json` | shared compiler options | see Configuration | | `.gitignore` | ignores build and model artefacts | "GenClass runtime" block: `node_modules/`, `dist/`, `.vite/`, `test-results/`, `playwright-report/`, `sim/out/`, `packages/runtime-model/files/`, `.cache-model/`, `.publish/`, `*.tgz` (the last two added in 59c213f). Older Python block: `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/`, `data/`, `models/`, `runs/`, `dist/`, `node_modules/`, `.DS_Store`. `data/`, `models/`, `runs/` are unanchored (match at any depth). `package-lock.json` is **not** ignored | -| `package-lock.json` (root) | **not tracked** | never committed (`git log --all -- package-lock.json` is empty). A root `npm install` creates one that shows as untracked; it records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }` | -| `packages/runtime/package.json` | the published package | name `@genclass/runtime`, version `0.1.0-alpha.0`, `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | +| `package-lock.json` (root) | committed lockfile (b435acb) | `lockfileVersion: 3`, 213 `packages` entries; records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }`. Resolved versions include `vitest 5.0.3`, `tsup 8.5.1`, `typescript 5.9.3`, `esbuild 0.27.7`, `happy-dom 20.14.5`, `onnxruntime-web`/`onnxruntime-node 1.30.0`, `@playwright/test 1.63.0`, `vite 8.3.3`. `npm ci` installs exactly this | +| `.github/workflows/ci.yml` | the only CI workflow (b435acb) | job `runtime`; see [CI](#ci-githubworkflowsciyml) | +| `packages/runtime/package.json` | the published package (unchanged since 654d822) | name `@genclass/runtime`, version `0.1.0-alpha.0`, `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | | `packages/runtime/tsconfig.json` | typecheck project | extends base; `rootDir: src`, `outDir: dist`, `jsx: react-jsx`, `types: []`, `include: ["src"]` | | `packages/runtime/tsup.config.ts` | build | entries, dts entries, externals | | `packages/runtime/vitest.config.ts` | unit-test runner config | include `test/**/*.test.ts`, exclude `test/browser/**`, env `node`, `testTimeout 20000` | -| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (not built); committed with mode 100644, and a root `npm install` makes it 755 (see [Verified locally](#verified-locally-2026-10-07)) | `fetch-model <dir> [--from] [--variant q8\|fp16\|all] [--force] [--quiet]`, `info <dir>`; `DEFAULT_FROM` | -| `packages/runtime/test/helpers.ts` | core test kit | `drain`, `FakeClock`, `choice`, `ScriptedDecider`, `defaultScript`, `FakeServer`, `makeGlobal`, `setup`, `ManualDecider` | -| `packages/runtime/test/*.test.ts` | 31 unit test files (CORE, UI, REVIEW) | see Tests | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (not built); committed as mode 100755 since b435acb (it was 100644, and every root `npm install` showed a mode change) | `fetch-model <dir> [--from] [--variant q8\|fp16\|all] [--force] [--quiet]`, `info <dir>`; `DEFAULT_FROM` | +| `packages/runtime/test/helpers.ts` | core test kit | `drain`, `FakeClock`, `choice`, `ScriptedDecider`, `defaultScript`, `FakeServer`, `makeGlobal`, `setup` (defaults `mode: "guard"` since f3636b2), `ManualDecider` | +| `packages/runtime/test/*.test.ts` | 36 tracked unit test files (CORE, UI, REVIEW, lead) | see Tests. New since 654d822: `content`, `delivery`, `no-reorder`, `nan`, `default-mode` | | `packages/runtime/test/model/helpers.ts` | model test kit | `PKG`, `FIX`, `MODEL_DIR`, `readJson`, `modelFile`, `hasModelFile`, `FIXTURES_FROM_MODEL`, `requests`, `packs`, `torch`, `exportParity`, `pyFixturesPath`, `pythonOnlyFloatRequests`, `questionsInPythonOrder`, `pruneTokenizer` (mirrors `prune_tokenizer()` in `make_py_fixtures.py`), `vocabDigest`, `isV01Tokenizer`; types `PackFixture`, `TorchFixture`, `RequestFixture` | | `packages/runtime/test/model/*.test.ts` | 6 model test files (MODEL) | see Tests | | `packages/runtime/test/fixtures/model/` | parity fixtures + their generators | see Fixtures | @@ -47,20 +50,22 @@ | `packages/runtime/test/browser/model-webgpu.spec.ts` | model host on SwiftShader WebGPU | adapter without `shader-f16` | | `packages/runtime/test/browser/ui-devtools.spec.ts` | devtools overlay in a real browser + screenshots | writes `ui/screenshots/*.png` | | `packages/runtime/test/browser/ui/playwright.config.ts` | UI specs config | `testMatch /ui-.*\.spec\.ts$/`, viewport 1280x800, DPR 2 | -| `packages/runtime/test/browser/ui/{mock-runtime,scenario,session,page}.ts` | UI fixtures, **also imported by unit tests** | `mock-runtime.ts`: `MockRuntime` (scripted `Runtime`, not the runtime), `MockClock`, `choice(probs)`, `makeDecision`, `makeAction`; `scenario.ts`: `loadScenario(rt, opts)`, `ScenarioOptions`; `session.ts`: `runStoreSession(opts)` (real `createRuntime` under virtual time), `Session`, `SessionOptions`, `VirtualClock`, `realTurn`, `READY` (a `ModelStatus`), `SessionDecider` (rule-based test decider); `page.ts`: `window.__gc` | +| `packages/runtime/test/browser/ui/{mock-runtime,scenario,session,page}.ts` | UI fixtures, **also imported by unit tests** | `mock-runtime.ts`: `MockRuntime` (scripted `Runtime`, not the runtime; `situationBudget()` returns `2400` since batch 4; a public `holdWrites = false` field that the `adapters-*` tests set to `true` to exercise hold paths), `MockClock`, `choice(probs)`, `makeDecision`, `makeAction`; `scenario.ts`: `loadScenario(rt, opts)`, `ScenarioOptions`; `session.ts`: `runStoreSession(opts)` (real `createRuntime` under virtual time, `mode: "guard"` explicitly), `Session`, `SessionOptions`, `VirtualClock`, `realTurn`, `READY` (a `ModelStatus`), `SessionDecider` (rule-based test decider; its `judge()` has a `delivery` case since batch 4); `page.ts`: `window.__gc` | | `packages/runtime/test/browser/ui/screenshots/` | 18 committed PNGs | `{pill,overlay,interventions,evidence,evidence-answers,detections,activity,now,loading}-{light,dark}.png` | | `packages/runtime/test/browser/.gitignore` | ignores `.build/` | build output of `build.mjs` | | `packages/runtime/test/smoke/smoke.sh` | npm-pack smoke test | run from `packages/runtime` | -| `packages/runtime/STATUS.md` | CORE status + headless recipe | last measured: 37 files / 300 tests passing | -| `packages/runtime-model/MODEL_CARD.md` | only file of the planned `@genclass/runtime-model` package | no `package.json` yet, so not a workspace | -| `scripts/vm.sh` | VM helper | `sync`, `run`, `exec`, `get` | -| `sim/package.json`, `demos/package.json` | consumers of the runtime | `"@genclass/runtime": "*"`; scripts listed under "How `sim` and `demos` consume the runtime" | +| `packages/runtime/STATUS.md` | CORE status + headless recipe + example situations | last measured (VM, with a model dir): 41 files / 346 tests passing; written before `default-mode.test.ts` (+1 file, +4 tests) | +| `packages/runtime-model/MODEL_CARD.md` | only file of the planned `@genclass/runtime-model` package | no `package.json` yet, so not a workspace. Status line now describes round 1 (situation-v1) R17; a v2 model is not trained yet | +| `scripts/vm.sh` | VM helper (Mehar's machine; needs his hosts file and key) | `sync`, `run`, `exec`, `get` | +| `sim/package.json`, `demos/package.json` | consumers of the runtime | `"@genclass/runtime": "*"`; scripts listed under "How `sim`, `demos` and `realapps` consume the runtime" | +| `realapps/package.json` | `@genclass/realapps` (private, not a workspace) | scripts `build:runtime` (`cd ../packages/runtime && npx tsup`), `build` (`node build.mjs`), `gen`; pins `@playwright/test`/`playwright` `1.63.0`. See [../realapps.md](../realapps.md) | +| `HANDOFF.md` | Mehar's handoff for continuing sessions (d73d20c) | npm/2FA publish recipe, tags, run rules, next steps | ## Concepts and data structures | term | meaning | |---|---| -| workstream | team role that owns files: lead, CORE (runtime core + most tests), MODEL (`src/model/**`, `bin/`, `test/model/`, model browser specs), UI (`src/devtools/**`, `src/adapters/**` per CONTRACT §13, their tests, `test/browser/ui/`), SIM, DEMOS, TRAIN, REVIEW (`test/review-*.test.ts`) | +| workstream | team role that owns files: lead, CORE (runtime core + most tests), MODEL (`src/model/**`, `bin/`, `test/model/`, model browser specs), UI (`src/devtools/**`, `src/adapters/**` per CONTRACT §13, their tests, `test/browser/ui/`), SIM, REAL (`realapps/`, real-browser data), DEMOS, TRAIN, REVIEW (`test/review-*.test.ts`). Mehar's sessions play all of these; on `mvp-v2` the lead (us) owns AGENTS.md, `docs/agents/**`, `default-mode.test.ts` and CI | | slot | your directory on the VM, `~/gcl/<SLOT>`; name must match `[a-zA-Z0-9_-]+`; conventional names `core`, `model`, `sim`, `demos` | | model directory | a folder with `model.json` (card format `genclass-runtime-model/1` or the v0.1 extension card), the ONNX variants, `tokenizer.json`, `calibration.json`, `meta.json`. Fetched with `genclass-runtime fetch-model`. Tests read it from `GENCLASS_MODEL_DIR` | | v0.1 fixture set | `test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests (ids like `cu-004219-f`) with the Python packer output and PyTorch logits of the **v0.1 GenClass model** | @@ -69,8 +74,13 @@ | review test | `test/review-*.test.ts`: written by REVIEW as bug demonstrations ("A failing test demonstrates a bug"); STATUS records they pass **unmodified** | | package build vs model-entries build | `build.mjs` -> `buildLibrary`: uses the real `npx tsup` output (`mode: "package"`) when every tsup entry file exists and `dist/index.js` mentions `createModelHost`; otherwise builds only `src/model/index.ts` + `src/model/worker.ts` into `.build/dist` (`mode: "model-entries"`) | | worker URL pattern | the literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `src/model/host.ts` -> `defaultWorkerFactory` that app bundlers key on (its sibling `defaultOrtLoader` holds the two literal calls `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`); `build.mjs` -> `WORKER_URL_RE` asserts it survives both builds | -| `situation-v1` | annotated git tag on 1a77558 ("Frozen runtime situation format for model training"); SIM training data was generated from it | -| `v0.1.0-alpha.0` | annotated git tag on 654d822 ("@genclass/runtime 0.1.0-alpha.0 (npm)") | +| `situation-v1` | annotated git tag on 1a77558 ("Frozen runtime situation format for model training"); round-1 SIM data and the R17/R32 round-1 models come from it. Superseded | +| `situation-v2` | annotated git tag on 6e5e86e ("Frozen runtime situation format v2", runtime batch 5). **The current frozen training format** (`HANDOFF.md`): SIM and REAL are generating v2 data from it; any change under `src/situation/*` means a new tag and regenerated data | +| `v0.1.0-alpha.0` | annotated git tag on 654d822 ("@genclass/runtime 0.1.0-alpha.0 (npm)"); a GitHub pre-release per `HANDOFF.md` | +| `delivery` trigger | situation-v2 (batch 4): the runtime decides at the network boundary (a response, WebSocket/EventSource message or XHR completion) instead of holding store writes; a `discard` drops only the response's stale field writes (`ActionRecord.dropped`). Tests: `delivery.test.ts`, `content.test.ts`, `smoke.test.ts`, `situation.test.ts` | +| `policy.holdWrites` | `PolicyOptions.holdWrites?` in `src/types.ts`, default off: store writes apply at once and a background `discard` becomes a late revert. `true` restores pre-v2 held writes; tests about held writes must opt in | +| default mode vs harness mode | product default `observe` (`src/runtime.ts` -> `o.mode ?? "observe"`, f3636b2); `test/helpers.ts` -> `setup()` defaults to `"guard"` so CORE tests keep exercising interventions | +| CI | `.github/workflows/ci.yml`: typecheck, build, unit tests and perf budgets of `@genclass/runtime` only (no sim, demos, realapps, Playwright, Python) | Test-kit types (exact names, `test/helpers.ts`): @@ -89,7 +99,7 @@ class ManualDecider implements DecisionProvider { status = { state: "ready", mod answer(script = defaultScript()): EvaluateRequest /* throws "nothing pending" */ } ``` -`setup()` spreads your options **after** its defaults, so `setup({ decider: manual })` replaces the decider passed to `createRuntime`, but the returned `decider` field is still the unused `ScriptedDecider`; keep your own reference to `manual`. `FakeServer.fetch` honours `init.signal` (rejects with `signal.reason`), reads only string bodies, and `error: "network"` rejects with `TypeError("Failed to fetch")`. +`setup()` spreads your options **after** its defaults (`mode: "guard"`, `report: "silent"`, an `observe` map with `fetch: true` and `xhr`, `user`, `errors`, `nav`, `storage`, `perf`, `websocket`, `timers` false; `eventsource` is not listed, so it stays at its default "on", a no-op on the fake global, which has no `EventSource`), so `setup({ mode: undefined })` gives the runtime's own default (`observe`) and `setup({ decider: manual })` replaces the decider passed to `createRuntime`, but the returned `decider` field is still the unused `ScriptedDecider`; keep your own reference to `manual`. `FakeServer.fetch` honours `init.signal` (rejects with `signal.reason`), reads only string bodies, and `error: "network"` rejects with `TypeError("Failed to fetch")`. Per-file fakes outside `test/helpers.ts` (copy these when testing the same area): @@ -103,6 +113,10 @@ Per-file fakes outside `test/helpers.ts` (copy these when testing the same area) | `makeFakeXHR(clock, handler)` / `makeXHR(clockRef, handler)` | `test/xhr.test.ts` / `test/review-xhr.test.ts` | an `XMLHttpRequest` class passed with `setup({ observe: ..., extraGlobal: { XMLHttpRequest } })`; both use `observe: { fetch: false, xhr: true }` (`XHR_ONLY` in `review-xhr.test.ts`); a passed `observe` replaces setup's map, so unlisted observers fall back to their defaults | | `timerWorld()` (global whose `setTimeout` queues callbacks run by hand) | `test/review-timers.test.ts` | the timers observer's host global | | `MockRuntime` / `runStoreSession` | `test/browser/ui/*` | the runtime (devtools and adapter tests) | +| `timers(holder)` (a global whose `setTimeout`/`clearTimeout` run on the `FakeClock`, passed via `extraGlobal`) + `searchApp` / `listApp` | `test/delivery.test.ts`, `test/content.test.ts` | debounced app timers seen by the timers observer; small apps that produce delivery situations | +| `FakeWS` / `FakeES` (`EventTarget` subclasses) + `board(s)`; `makeXHR(ref, handler)` | `test/delivery.test.ts` | WebSocket and EventSource channels for message delivery decisions; an `XMLHttpRequest` for XHR delivery holds | +| `PassiveDecider` (always the passive action with an alarming diagnosis, after `latency` virtual ms) | `test/no-reorder.test.ts` | a model that never acts, for "never worse" checks | +| `counterStore()` (minimal redux-like store) | `test/default-mode.test.ts` | an adapter store for `rt.adapter(...).propose` | Fixture record types (`test/model/helpers.ts`): @@ -134,28 +148,28 @@ Plus shared `chunk-*.js` files (code splitting) and `.map` files. `exports` also ### Unit tests (`npm test` -> `vitest run`) -1. vitest collects `test/**/*.test.ts` minus `test/browser/**` (37 files). It transpiles TS without type-checking. +1. vitest collects `test/**/*.test.ts` minus `test/browser/**` (42 tracked files; plus any untracked `*.test.ts` in your working copy). It transpiles TS without type-checking. 2. Each file runs in `node` unless its first line is `// @vitest-environment happy-dom` (`adapters-react`, `devtools`, `devtools-runtime`, `dom`, `review-dom`). -3. A typical test calls `setup()`: builds `FakeClock` + `FakeServer` + `makeGlobal(server)` + `ScriptedDecider`, then `createRuntime({ clock, global: g, decider, report: "silent", observe: { fetch: true, all others false }, ...rest })` and casts to `RuntimeImpl` (so tests can reach `rt.hub`, `rt.ops`, `rt.ctx`, `rt.cache`, `rt.miner`, `rt.internals`). +3. A typical test calls `setup()`: builds `FakeClock` + `FakeServer` + `makeGlobal(server)` + `ScriptedDecider`, then `createRuntime({ clock, global: g, decider, mode: "guard", report: "silent", observe: { fetch: true, xhr/user/errors/nav/storage/perf/websocket/timers: false }, ...rest })` (`eventsource` unlisted, so default on) and casts to `RuntimeImpl` (so tests can reach `rt.hub`, `rt.ops`, `rt.ctx`, `rt.cache`, `rt.miner`, `rt.internals`). 4. The test drives the app through `rt.user(...)`, `rt.op(...)`, atoms and `fetch`, then advances virtual time: `await clock.advance(ms)` runs due timers in order, each followed by `flush()`; `flush()` drains microtasks with 4 real `setImmediate` turns (`drain`), runs `afterTask` hooks, and repeats up to 50 times. 5. The decider answers at once (an already-resolved promise) from a script (`ScriptedDecider`, records `calls`; `script` can be reassigned mid-test) or when the test calls `ManualDecider.answer(script?)` (oldest pending first). -6. Assertions read `decider.calls[i].state` (the situation), `rt.decisions()`, `rt.interventions()`, `rt.history()`, `server.hits` / `server.log`. +6. Assertions read `decider.calls[i].state` (the situation), `decider.calls.filter((c) => c.trigger === "delivery")` (v2 network-boundary decisions), `rt.decisions()`, `rt.interventions()` (incl. `.late` for late reverts and `.dropped` for delivery discards), `rt.history()`, `server.hits` / `server.log`. `defaultScript()` takes any trigger key, e.g. `defaultScript({ delivery: { diagnosis: "stale", action: "discard" } })`. 7. Model tests (`test/model/`) read fixtures through `test/model/helpers.ts`; parts that need model files use `describe.skipIf(!hasModelFile(...))` / `it.skipIf`. The 14 model-file tests: `calibrate.test.ts` 1 (`calibration.json`), `engine.test.ts` 3 (`model.json` + `tokenizer.json` + the variant file), `packer.test.ts` 10 (`tokenizer.json`; the 2 HF edge-case tests also need `isV01Tokenizer`). The `py_fixtures.json` blocks skip only if that committed file is missing. ### Headless runtime recipe (STATUS "How to drive it headless") -What `setup()` does is the minimal form of the recipe SIM and tests use. `packages/runtime/STATUS.md` gives the full form; options are defined in `src/types.ts` -> `CreateOptions` / `InitOptions` (see [public-api-and-lifecycle.md](public-api-and-lifecycle.md)): +What `setup()` does is the minimal form of the recipe SIM and tests use. `packages/runtime/STATUS.md` gives the full form (updated for situation-v2); options are defined in `src/types.ts` -> `CreateOptions` / `InitOptions` (see [public-api-and-lifecycle.md](public-api-and-lifecycle.md)): ```ts createRuntime({ clock, global, decider, // injected Clock, instrumented global, DecisionProvider - observe: { fetch: true, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false }, - mode: "heal", triage: "salient", report: "silent", - policy: { thresholds: { report: 0, guard: 0, heal: 0 }, holdBudgetMs: 1e9, maxActionsPerMinute: 1e9, requireDiagnosis: false }, - situation: { budget: 1000 }, // sample budgets 1000/1333/2000/3200; <= 1400 = compact questions + observe: { fetch: true, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, eventsource: false, timers: false }, + mode: "heal", triage: "salient", report: "silent", // pass mode explicitly: the default is now "observe" + policy: { thresholds: { report: 0, guard: 0.5, heal: 0.5 }, holdBudgetMs: 1e9, maxActionsPerMinute: 1e9, requireDiagnosis: false }, + situation: { budget: 1000 }, // sample budgets 1000/1333/2000/2400; <= 1400 = compact questions hooks: { opCreated(op) {}, mutationProposed(m) {} }, vocabulary: { diagnoses: {}, actions: {} } }); ``` -Facts STATUS records for this mode (checked against `src/runtime.ts` -> `installObservers` / `consultable` / `trigger`): `global.fetch` is replaced at construction and `rt.destroy()` restores every wrapped global; `observe` defaults to every observer on except `timers`, which is on only when `global.document` exists (`src/runtime.ts`); the decider is consulted only while `status.state === "ready"`; `app` comes from `CreateOptions.app()` or `document.title` + `location.pathname` (hence `/search` in tests); same inputs give byte-identical situations at any budget. +Facts STATUS records for this mode: `global.fetch` (and WebSocket, EventSource, ...) is replaced at construction and `rt.destroy()` restores every wrapped global; `observe` defaults to every observer on except `timers`, which is on only when `global.document` exists, and synthetic DOM events count as user actions only with `observe.untrustedEvents: true`; the decider is consulted only while `status.state === "ready"`; holds (responses, messages, requests) are released only by the decision, the hold-budget timer or `defer`'s wait, all on the injected clock; forcing semantics: thresholds 0.5, `requireDiagnosis: false`, probability 1 on an action runs exactly that action when the mode permits it (tested for `delivery` too in `delivery.test.ts` "answers"); same inputs give byte-identical situations at any budget. `sim/src/run/rt.ts` -> `createOptions` (the options every sim run passes to the `createRuntime` that `realRuntimeFactory` loads) sets `mode: "heal"` explicitly, so the default-mode change does not affect SIM data. ### Browser model specs (`npm run test:browser`) @@ -178,24 +192,27 @@ Facts STATUS records for this mode (checked against `src/runtime.ts` -> `install 2. Creates a temp Vite app (`mktemp -d`/app) whose `src/main.js` calls `GenClass.init({ model: false, report: "console" })`, creates atom `search.results`, wires an input to a `data:` URL fetch, and calls `mountDevtools(rt)`. 3. `npm install` the tarball + `vite@8` + `@playwright/test@1.63.0` (needs registry access), `npx vite build`. 4. `check.mjs` serves `dist/` on port `4191` (plain `node:http`), opens it in Chromium (`chromium.launch()` from the app's `@playwright/test`), waits for `window.__smoke.ok`, `p.fill("#q", "rea")`, waits for `#out` to read `rea-1`, prints one JSON line `{ info: { status, events, devtools }, errs }`, and exits 1 unless there are no page errors / console errors, `genclass-devtools` exists, and `rt.history().length >= 3` (`status` is printed, not asserted). Then prints `SMOKE OK: <tgz>`. -5. Leftovers: the `.tgz` stays in `packages/runtime/` and the `mktemp -d` app is not deleted. The script never runs `playwright install`: Chromium for Playwright `1.63.0` must already be in the Playwright browser cache on the machine (how the VM got it is not recorded in the repo). +5. The script is unchanged since 59c213f. `GenClass.init({ model: false, report: "console" })` now starts in `observe` (default since f3636b2); nothing it asserts depends on the mode (unverified: not re-run on mvp-v2). +6. Leftovers: the `.tgz` stays in `packages/runtime/` and the `mktemp -d` app is not deleted. The script never runs `playwright install`: Chromium for Playwright `1.63.0` must already be in the Playwright browser cache on the machine (how the VM got it is not recorded in the repo). ### VM workflow (`scripts/vm.sh`) 1. Reads the `train` host IP from `~/.jev-local/azure_hosts` (line `train <ip>`), key `~/.ssh/jev_azure`, user `azureuser`, ssh options `StrictHostKeyChecking=accept-new`, `ConnectTimeout=20`, `ServerAliveInterval=30`, `ServerAliveCountMax=6`. Exits 2 if the host line is missing, the slot name has characters outside `[a-zA-Z0-9_-]`, or the subcommand is unknown. Every step is wrapped in GNU `timeout` (see Configuration). The sibling `scripts/azvm.sh HOST ...` uses the same hosts file and key for the other jev VMs (out of scope here). 2. `sync SLOT`: `ssh mkdir -p gcl/SLOT`, then `rsync -az --delete` the repo to `~/gcl/SLOT/`, excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out/`, `.cache-model/`. Excluded paths on the VM are kept (rsync does not delete excluded files without `--delete-excluded`), so `node_modules`, `dist` and model caches survive syncs. -3. `run SLOT 'cmd'` = sync + remote; `exec SLOT 'cmd'` = remote only; remote runs `export PATH=$HOME/node/bin:$PATH; cd ~/gcl/SLOT && cmd` (Node 22 per the header and CONTRACT §0 rule 6). +3. `run SLOT 'cmd'` = sync + remote (the script is unchanged since 654d822; it only works from a machine holding Mehar's hosts file and key); `exec SLOT 'cmd'` = remote only; remote runs `export PATH=$HOME/node/bin:$PATH; cd ~/gcl/SLOT && cmd` (Node 22 per the header and CONTRACT §0 rule 6). 4. `get SLOT REMOTE LOCAL`: `scp -r` from `~/gcl/SLOT/REMOTE`. -### How `sim` and `demos` consume the runtime +### How `sim`, `demos` and `realapps` consume the runtime -npm workspaces symlink `node_modules/@genclass/runtime` -> `packages/runtime`, so every import goes through `packages/runtime/package.json` `exports` -> `dist/`. +npm workspaces symlink `node_modules/@genclass/runtime` -> `packages/runtime`, so every workspace import goes through `packages/runtime/package.json` `exports` -> `dist/`. `realapps/` is not a workspace and bypasses `dist/` entirely. | consumer | dependency | how it resolves | build requirement | escape hatch | |---|---|---|---|---| | `sim` (`@genclass/sim`, private) | `"@genclass/runtime": "*"` | dynamic `import(process.env.GENCLASS_RUNTIME ?? "@genclass/runtime")` in `sim/src/run/rt.ts` -> `realRuntimeFactory`; `sim/tsup.config.ts` leaves `@genclass/runtime` external | `npm run build:runtime-core` (in `sim`: tsup of `src/index.ts` only, `--no-config --platform neutral`, no dts, into `packages/runtime/dist`) or the full runtime build | `SIM_RUNTIME=real` runs sim tests on the real runtime; otherwise they use the fake (`sim/test/helpers.ts`); `GENCLASS_RUNTIME=<specifier>` loads another build | | `demos` (`@genclass/demos`, private) | `"@genclass/runtime": "*"` plus `react`, `redux`, `zustand`, `@fontsource-variable/*` | Vite resolves `exports` -> `dist/` | full runtime build (`demos/scripts/vm-eval.sh` runs `npm run build -w @genclass/runtime` and stops if it fails) | `GENCLASS_SHIM=1` (or a missing `packages/runtime/dist/index.js`) aliases `demos/src/dev/runtime-shim/*` in `demos/vite.config.ts`; `GENCLASS_SHIM=0` forces the real one; `npm run typecheck:shim` | -| `packages/runtime` UI spec | demos' hoisted deps | `<repo>/node_modules/@fontsource-variable/*` | root `npm install` | none | +| `sim` on-policy runs | the model host only | `sim/src/run/onpolicy.ts` loads `sim/dist/model-host/host.js`, built by `npm run build:model-host` (tsup of `packages/runtime/src/model/host.ts`, `--platform neutral`, ORT external, into `sim/dist/model-host`); `sim`'s `build` now runs it after `tsup` | `npm run build` in `sim` | none | +| `realapps` (`@genclass/realapps`, private, **not** a workspace) | none in `package.json` | `realapps/build.mjs` aliases `@genclass/runtime` (+ `/react`, `/redux`, `/zustand`) to `packages/runtime/src/*.ts` and stubs `onnxruntime-web` (+ `/wasm`, `/webgpu`); esbuild bundles the source into each app | none (`dist/` is not used; `build:runtime` runs a full tsup anyway) | `RW_RUNTIME_SRC` = an exported `git archive <tag> packages/runtime/src` to pin a frozen tag, `RW_RUNTIME_TAG` = its name (written to `dist/runtime-tag.txt`); default: the working tree. See [../realapps.md](../realapps.md) | +| `packages/runtime` UI spec | demos' hoisted deps | `<repo>/node_modules/@fontsource-variable/*` | root `npm install` / `npm ci` | none | `sim` does **not** need `dist/` to typecheck: `sim/src/types.ts` is a structural mirror of the runtime's model seam and the only runtime import is the dynamic one in `sim/src/run/rt.ts`. `demos` typecheck does need `dist/*.d.ts` (or `typecheck:shim`, whose `demos/tsconfig.shim.json` maps `@genclass/runtime` and its `/react`, `/redux`, `/zustand`, `/devtools` subpaths to `src/dev/runtime-shim/{index,react,redux,zustand,devtools}.ts`; `/worker` is not mapped). @@ -205,9 +222,10 @@ Workspace scripts (verbatim from the `package.json` files): |---|---|---| | root | `build` / `test` / `typecheck` | `npm run build -w @genclass/runtime` / `npm test -w @genclass/runtime` / `npm run typecheck --workspaces --if-present` | | `@genclass/runtime` | `build` / `typecheck` / `test` / `test:browser` | `tsup` / `tsc -p tsconfig.json --noEmit` / `vitest run` / `playwright test --config test/browser/playwright.config.ts` | -| `@genclass/sim` (`0.0.0`, private, bin `genclass-sim` = `./dist/gen.js`) | `build`, `typecheck`, `test` | `tsup` (entries `gen`, `worker`, `index`, `smoke`; `node22`; `@genclass/runtime` external), `tsc -p tsconfig.json --noEmit`, `vitest run` | +| `@genclass/sim` (`0.0.0`, private, bin `genclass-sim` = `./dist/gen.js`) | `build`, `typecheck`, `test` | `tsup && npm run build:model-host` (tsup entries `gen`, `worker`, `index`, `smoke`; `node22`; `@genclass/runtime` external), `tsc -p tsconfig.json --noEmit`, `vitest run` | | | `gen` / `sample` | `node dist/gen.js` / `node dist/gen.js --sample` | | | `build:runtime-core` | `cd ../packages/runtime && tsup src/index.ts --no-config --format esm --target es2022 --platform neutral --out-dir dist --external onnxruntime-web --external onnxruntime-web/webgpu --sourcemap` | +| | `build:model-host` | `cd ../packages/runtime && tsup src/model/host.ts --no-config --format esm --target es2022 --platform neutral --out-dir ../../sim/dist/model-host --external onnxruntime-web --external onnxruntime-web/wasm --external onnxruntime-web/webgpu` | | `@genclass/demos` (`0.1.0`, private) | `dev` / `build` / `preview` | `vite` / `node scripts/build.mjs` / `node --experimental-strip-types e2e/serve.ts dist --base /genclass/ --port 4173` | | | `typecheck` / `typecheck:shim` | `tsc -p tsconfig.json` (or `tsconfig.shim.json`) `--noEmit && tsc -p tsconfig.sw.json --noEmit && tsc -p tsconfig.node.json --noEmit` | | | `fetch-model` | `bash scripts/fetch-model.sh public/genclass-model` | @@ -215,72 +233,78 @@ Workspace scripts (verbatim from the `package.json` files): Demos devDeps pin the same `@playwright/test` `1.63.0` as the runtime and use `vite ^8.3.3`. -Details: [../sim.md](../sim.md), [../demos.md](../demos.md). +Details: [../sim.md](../sim.md), [../demos.md](../demos.md), [../realapps.md](../realapps.md). ### Exact commands +Local (allowed for agents off the 8 GB Mac; what CI runs): + +```sh +npm ci --no-audit --no-fund # repo root; uses the committed lockfile (add ONNXRUNTIME_NODE_INSTALL=skip on Linux, as CI does) +npm run typecheck -w @genclass/runtime # or: cd packages/runtime && npx tsc -p tsconfig.json --noEmit +npm run build -w @genclass/runtime # tsup -> packages/runtime/dist +cd packages/runtime +NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts # CI "Unit tests" +NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # CI "Perf budgets" +npx vitest run test/atoms.test.ts -t "late discard" # one file / one test +npx vitest run test/situation.test.ts test/delivery.test.ts test/content.test.ts test/budget.test.ts # prints the STATUS example situations (console.log) +npm pack --dry-run # list tarball contents (files: dist, bin, README.md, LICENSE) +cd ../../sim && npx tsc -p tsconfig.json --noEmit && SIM_RUNTIME=real npx vitest run # sim tests on the real runtime (needs the runtime build); not the generator +``` + +Heavy (ask the user first; on Mehar's setup they go through his VM slot): + ```sh -# on the VM, through your slot (from the repo root on the Mac) -scripts/vm.sh run core 'npm install && npm run build' -scripts/vm.sh exec core 'npm run typecheck -w @genclass/runtime' # or: cd packages/runtime && npx tsc -p tsconfig.json --noEmit scripts/vm.sh exec core 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl/model/.cache-model NODE_OPTIONS=--expose-gc npx vitest run' -scripts/vm.sh exec core 'cd packages/runtime && npx vitest run test/atoms.test.ts -t "late discard"' # one file / one test scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx vitest run test/model' scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npm run test:browser' # add --project chromium | swiftshader-webgpu scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/browser/playwright.config.ts model.spec.ts -g "inline fallback"' # one spec / one test scripts/vm.sh exec core 'cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts' scripts/vm.sh exec core 'cd packages/runtime && bash test/smoke/smoke.sh' -scripts/vm.sh exec core 'cd packages/runtime && npm pack --dry-run' # list tarball contents (files: dist, bin, README.md, LICENSE) -scripts/vm.sh exec sim 'npm run build && cd sim && SIM_RUNTIME=real npx vitest run' # sim tests against the real runtime # one-time per machine (not in any repo script; unverified that the VM needed it): npx playwright install chromium # fetch the v0.1 model for the model tests (command from packages/runtime/src/model/README.md; default --variant all) scripts/vm.sh exec model 'node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/' ``` -The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runtime/STATUS.md` and `packages/runtime/src/model/README.md`; which of them exists on the VM is unverified. +The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runtime/STATUS.md` and `packages/runtime/src/model/README.md`; which of them exists on the VM is unverified. Both hold the v0.1 GenClass model (the parity fixtures' model), not a runtime model: no situation-v2 runtime model exists yet. ### Where to run things -- **Team rule** (`docs/runtime/CONTRACT.md` §0 rule 5, `scripts/vm.sh` header): the Mac only edits files; every build, test, browser and model run goes through `scripts/vm.sh` on the `train` VM. The reason is RAM: the original author's Mac has 8 GB. -- **Lead policy for agents (2026-10-07):** on any other machine, run these locally; they are light and were verified (next section): - - `npm install` at the repo root; - - typecheck and build of `packages/runtime`; - - the runtime unit tests (vitest, browser specs excluded). +- **Mehar's team rule** (`HANDOFF.md` "Rules", `docs/runtime/CONTRACT.md` §0 rule 5, `scripts/vm.sh` header): his Mac has 8 GB RAM and is near OOM, so on it nothing runs (npm, tsc, vitest, node, browsers, torch, models); builds and tests go through `scripts/vm.sh` on the `train` VM. +- **Lead policy for agents (2026-10-08):** on any other machine, run these locally; they are light and were verified (next section): + - `npm install` / `npm ci` at the repo root; + - typecheck (`tsc`) and build (`tsup`) of `packages/runtime`; + - the runtime unit tests (vitest, browser specs excluded), and the sim's unit tests with `SIM_RUNTIME=real`. - **Ask the user first** before running any of: - - the sim (`sim/` generation or tests, `sim/scripts/*`); - - training (`training/*.sh`, Python training or tests); - Playwright (`npm run test:browser`, the UI spec, `test/smoke/smoke.sh`, which also installs from the npm registry); - - model downloads (`genclass-runtime fetch-model`, `demos/scripts/fetch-model.sh`); + - the sim generator (`sim` `gen`, `sim/scripts/*`); + - training (`training/*.sh`, Python training or tests); + - realapps runs (`realapps` `build`/`gen`, its harness scripts); - the demos' eval (`demos/scripts/vm-eval.sh`, `npm run eval` in `demos`); - - any script that touches Azure (`scripts/*.sh`, including `scripts/vm.sh`). -- On the original 8 GB Mac, the team rule still applies. + - model downloads (`genclass-runtime fetch-model`, `demos/scripts/fetch-model.sh`); + - anything on Azure (`scripts/*.sh`, including `scripts/vm.sh`, `az`). Mehar is actively operating the cluster for v2 data generation; nobody on our side touches it; + - `git push` and `npm publish`. -### Verified locally (2026-10-07) +### Verified locally (2026-10-08) -These were run at 654d822, when these docs were written, on a macOS machine (16 GB RAM, 10 CPUs, Node v25.6.0, npm 11.8.0): +Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the lead (the per-file vitest counts in [Tests](#tests) were re-collected for this doc): -| step | command (directory) | result | time | -|---|---|---|---| -| install | `npm install` (repo root) | OK, 134 packages; one EBADENGINE warning (below) | ~18 s | -| typecheck | `npx tsc -p tsconfig.json --noEmit` (`packages/runtime`) | clean | ~1.6 s | -| build | `npx tsup` (`packages/runtime`) | 6 entries (`index`, `adapters/react`, `adapters/redux`, `adapters/zustand`, `devtools/index`, `worker`), `.d.ts` for all but `worker`; `dist/` ~1.6 MB including source maps; largest JS chunk ~258 KB and `dist/devtools/index.js` ~68 KB, both unminified | ~2.5 s | -| unit tests | `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"` (`packages/runtime`) | Test Files 36 passed \| 1 skipped (37); Tests 286 passed \| 14 skipped (300) | ~2.4 s | - -- **The 14 skipped tests** are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`), which did not exist on that machine: - - `test/model/packer.test.ts`: all 10 (the one fully skipped file); - - `test/model/engine.test.ts`: 3 of 4; - - `test/model/calibrate.test.ts`: 1 of 8. - - With a model directory present (as on the VM, per STATUS) all 300 pass. Getting one means a model download: ask the user first. -- **EBADENGINE warning.** `vitest@5.0.3` declares `engines.node` `^22.12.0 || ^24.0.0 || >=26.0.0`. Node 25 is outside that range, so npm warns, but the tests run. Node 22.x from 22.12, 24.x and 26+ are inside it; 23.x and 25.x are not. The VM runs Node 22, but the repo does not record its minor version. -- **Install side effects.** The root `npm install` changes two things git sees: - - It creates an untracked root `package-lock.json`, because the repo has never committed one. Do not commit it unless the lead decides to (see "No committed lockfile" under gotchas). Delete it, or leave it untracked. - - It chmods `packages/runtime/bin/genclass-runtime.mjs` to 755, so `git status` reports a mode change from the committed 100644. Revert it with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. -- **Not run in that pass:** - - Playwright browser specs (main and UI configs); - - `test/smoke/smoke.sh`; - - the sim, training, the demos, Python tests, model downloads, anything on Azure. -- **No CI** re-runs any of this: there is no `.github/` directory. +| step | command (directory) | result | +|---|---|---| +| install | `npm ci` (fresh clone, repo root) | OK from the committed lockfile; EBADENGINE warning from vitest on Node 25 (below) | +| typecheck | `npx tsc -p tsconfig.json --noEmit` (`packages/runtime`) | clean | +| build | `npx tsup` (`packages/runtime`) | OK, 6 entries, `.d.ts` for all but `worker` | +| unit tests | `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` (`packages/runtime`) | Test Files 40 passed \| 1 skipped (41); Tests 332 passed \| 14 skipped (346) | +| perf budgets | `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | 4 passed. In a full parallel run it once failed at 5.5 ms against its 2 ms bound (contention), hence CI's separate step with `--retry=2` | +| sim | `npx tsc --noEmit`; `SIM_RUNTIME=real npx vitest run` (`sim`) | clean; 19 passed (5 files) | +| CI steps | the five steps of `ci.yml`, in a fresh clone | pass | + +- **The 14 skipped tests** are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`), which did not exist on that machine: `test/model/packer.test.ts` all 10 (the one fully skipped file), `test/model/engine.test.ts` 3 of 4, `test/model/calibrate.test.ts` 1 of 8. With a model directory all 350 should pass (STATUS: 346 on the VM, before `default-mode.test.ts`). Getting one means a model download: ask the user first. +- **On `origin/runtime` (74f17c0) itself**, where the default mode is still `guard`: 331 passed + 1 flaky perf failure + 14 skipped = 346. +- **EBADENGINE warning.** `vitest@5.0.3` declares `engines.node` `^22.12.0 || ^24.0.0 || >=26.0.0`. Node 25 is outside that range, so npm warns, but the tests run. Node 22.x from 22.12, 24.x and 26+ are inside it; 23.x and 25.x are not. CI uses `node-version: 22` (latest 22.x). +- **Install side effects are gone**: the lockfile is committed and the CLI is committed as 100755, so a root `npm install` / `npm ci` leaves `git status` clean (unless dependencies changed). +- **Untracked test files.** Working copies used by parallel agents may contain untracked `test/zz-*.test.ts` files (`zz-review-*`, `zz-verify-*`; one appeared mid-run during this doc's check and lifted the count to 351); vitest collects them (`include` is `test/**/*.test.ts`) and some may fail. They are not part of the branch: check `git status` before trusting a red run, and count only tracked files. +- **Not run:** Playwright (main and UI configs), `test/smoke/smoke.sh`, realapps, the demos' eval, Python tests, training, model downloads, anything on Azure. ## Configuration and constants @@ -318,7 +342,17 @@ These were run at 654d822, when these docs were written, on a macOS machine (16 | `dependencies` | dep | `onnxruntime-web ^1.30.0` (only runtime dependency; CONTRACT §0 rule 6 forbids others without the lead) | `packages/runtime/package.json` | | | `peerDependencies` | peer | `react >=18`, `redux >=4`, `zustand >=4`, all optional | `packages/runtime/package.json` | | | `sideEffects` | pkg | `false` | `packages/runtime/package.json` | bundlers may drop unused imports | -| `engines.node` | pkg | `>=20` (root and runtime) | `package.json`s | VM runs Node 22 | +| `engines.node` | pkg | `>=20` (root and runtime) | `package.json`s | VM and CI run Node 22 | +| CI triggers | ci | push to `main`, `runtime`, `mvp`, `mvp-v2`; `pull_request` (any branch); `workflow_dispatch` | `.github/workflows/ci.yml` -> `on` | | +| CI `permissions` / `concurrency` | ci | `contents: read`; group `ci-${{ github.ref }}`, `cancel-in-progress: true` | `.github/workflows/ci.yml` | a new push cancels the running job of the same ref | +| CI runner / timeout / Node | ci | `ubuntu-latest`, `timeout-minutes: 15`, `actions/setup-node@v4` `node-version: 22`, `cache: npm` | `.github/workflows/ci.yml` -> `jobs.runtime` | | +| `ONNXRUNTIME_NODE_INSTALL` | env (CI) | `skip` | `.github/workflows/ci.yml` -> `jobs.runtime.env` | stops `onnxruntime-node` (dev-only, model parity tests) from downloading CUDA binaries on Linux; those tests skip anyway without a model dir | +| CI test env | ci | `NODE_OPTIONS: --expose-gc`, `working-directory: packages/runtime` | unit-test and perf steps | gc test really runs | +| perf retry | ci | `--retry=2` | "Perf budgets" step | `review-perf.test.ts` wall-clock bounds are noisy on shared runners | +| default `mode` | const | `"observe"` | `src/runtime.ts` -> `o.mode ?? "observe"` (f3636b2) | the product default; `?genclass=guard` / `heal` or `mode` opt in | +| `setup()` `mode` | test | `"guard"` | `test/helpers.ts` -> `setup` | override with `mode: undefined` for the product default | +| `policy.holdWrites` | option | `false` (unset) | `src/types.ts` -> `PolicyOptions.holdWrites` | tests about held store writes pass `true` | +| `MockRuntime.situationBudget()` | test | `2400` (was `3200`) | `test/browser/ui/mock-runtime.ts` | matches the v2 full budget | | `DEFAULT_MODEL_BASE_URL` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default model location = the unpublished package | | CLI `DEFAULT_FROM` | const | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | default `fetch-model --from` (planned release) | | test env vars | env | `GENCLASS_MODEL_DIR`, `NODE_OPTIONS=--expose-gc`, `GENCLASS_BENCH_MODELS="name=dir,..."`, `GENCLASS_WEBGPU_VARIANTS=<dir>`, `GENCLASS_OFFLINE=1` | test files | see Tests | @@ -334,28 +368,30 @@ These were run at 654d822, when these docs were written, on a macOS machine (16 ## Invariants and gotchas -- **Do not run builds or tests on the original 8 GB Mac.** That is the binding team rule. Elsewhere the run policy in AGENTS.md allows the light checks locally and requires the user's OK for everything heavier ([Where to run things](#where-to-run-things)). `vm.sh` needs `~/.jev-local/azure_hosts` (a `train` line) and `~/.ssh/jev_azure`, neither of which is in the repo. It also calls GNU `timeout` on the local machine, which macOS does not include by default. Without all three, `vm.sh` cannot reach a VM. If you have no VM, ask the user; do not quietly run heavy jobs locally. -- **`dist/` must exist before anything consumes the package.** `sim`, `demos` and demo typechecking resolve `@genclass/runtime` through `exports` -> `dist/`. Root `npm run typecheck` therefore needs `npm run build` first (demos' `typecheck` reads `dist/*.d.ts`; `typecheck:shim` avoids it). The demos typecheck (and `typecheck:shim`) also needs the missing `demos/src/server/data/cities.ts` (see [../demos.md](../demos.md#drift-and-open-issues) Drift 1): `demos/tsconfig.json`, `tsconfig.shim.json` and `tsconfig.sw.json` all include `src/server/worlds/search.ts`, which imports it, so the root `npm run typecheck` fails with a missing-module error in this checkout until that file is recreated (inferred from the configs; tsc was not run). +- **Do not run builds or tests on Mehar's 8 GB Mac.** That is the binding team rule there (`HANDOFF.md` "Rules"). Elsewhere the run policy in AGENTS.md allows the light checks locally and requires the user's OK for everything heavier ([Where to run things](#where-to-run-things)). `vm.sh` needs `~/.jev-local/azure_hosts` (a `train` line) and `~/.ssh/jev_azure`, neither of which is in the repo. It also calls GNU `timeout` on the local machine, which macOS does not include by default. Without all three, `vm.sh` cannot reach a VM. If you have no VM, ask the user; do not quietly run heavy jobs locally. +- **`dist/` must exist before anything consumes the package.** `sim`, `demos` and demo typechecking resolve `@genclass/runtime` through `exports` -> `dist/`. Root `npm run typecheck` therefore needs `npm run build` first (demos' `typecheck` reads `dist/*.d.ts`; `typecheck:shim` avoids it). The demos typecheck (and `typecheck:shim`) also needs the missing `demos/src/server/data/cities.ts` (see [../demos.md](../demos.md#drift-and-open-issues) Drift 1). It is not in git because the root `.gitignore`'s unanchored `data/` matches `demos/src/server/data/` (`git check-ignore -v` names that line). `src/server/worlds/search.ts`, `src/demos/search/scenario.ts` and `src/demos/search/oracle.ts` import it, so `tsc -p demos/tsconfig.json` and `tsconfig.shim.json` fail with TS2307 "Cannot find module ... cities.ts" (checked 2026-10-08 with `packages/runtime/dist/` built), and so does the root `npm run typecheck`. - **`clean: true` + a failed build = a half-empty `dist/`.** `demos/scripts/vm-eval.sh` refuses to measure after a failed runtime build for this reason (`ALLOW_BROKEN_RUNTIME=1` overrides). - **`npm run test:browser` rebuilds `packages/runtime/dist/`** (its global setup runs `npx tsup`). Do not run it in a slot where another job is reading `dist/`. - **Keep tsup entries as literal `"src/...ts"` strings.** `build.mjs` -> `fullBuildPossible` finds them with a regex over the config text. - **Keep the worker URL pattern and the two `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` literals.** Bundlers (Vite, webpack) recognise them; `build.mjs` fails if either disappears from the output. -- **Tests are not type-checked** (`tsconfig.json` `include: ["src"]`; vitest strips types). A test can drift from the public types and still pass; `MockRuntime` in particular is "not type-checked" (STATUS). +- **Tests are not type-checked** (`tsconfig.json` `include: ["src"]`; vitest strips types). A test can drift from the public types and still pass; `MockRuntime` (`implements Runtime`) in particular can fall behind the `Runtime` interface without any error (the situation-v1 STATUS said so explicitly; the current STATUS no longer mentions it). - **Unit tests import from `test/browser/ui/`** (`mock-runtime.ts`, `scenario.ts`, `session.ts`). The vitest exclude only stops test discovery there; moving or renaming those files breaks `adapters-*.test.ts`, `devtools*.test.ts`. - **Determinism.** Runtime code uses only the injected `Clock` (CONTRACT §0 rule 3). Tests assert byte-identical situations across runs (`situation.test.ts` "determinism", `budget.test.ts` "byte-identical"). Never use `Date.now`, `performance.now`, `Math.random` or the global `setTimeout` directly in `src/` (rule 3 names all of them); in tests use `FakeClock`, not real timers. Exceptions: wall-time measurements with `performance.now` in `review-perf.test.ts`, `test/model/engine.test.ts` and `test/model/packer.test.ts`, the real `browserClock` in `test/model/loader.test.ts`, and the 40 ms real `setTimeout` "frame" waits in `devtools.test.ts` / `devtools-runtime.test.ts`. -- **Wall-clock thresholds in `review-perf.test.ts`** (user write < 1 ms, async write < 2 ms, redux dispatch < 1 / < 2 ms, settled point < 16 ms on 5,000-item stores) can fail on a loaded machine. STATUS measured on the shared VM: keystroke write 0.14 ms, gated async write 0.19 ms, redux dispatch 0.68 ms (user) / 0.58 ms (async), settled point 0.2 ms (+1.4 ms with an unchanged 5,000-item adapter store). +- **Wall-clock thresholds in `review-perf.test.ts`** (user write < 1 ms, async write < 2 ms, redux dispatch < 1 / < 2 ms, settled point < 16 ms on 5,000-item stores) can fail on a loaded machine: the lead saw one 5.5 ms failure against the 2 ms bound in a full parallel run on 2026-10-08, and it passed alone. CI therefore runs it in its own step with `--retry=2`; run it alone locally too before calling it a regression. STATUS (batch 5, shared VM): keystroke write 0.22 ms, async write 0.14 ms, redux dispatch 0.71 ms (user) / 0.70 ms (async), settled point 0.3 ms (+2.3 ms with an unchanged 5,000-item adapter store). - **The gc test passes silently without `--expose-gc`.** `review-timers.test.ts` "a polling loop does not retain..." logs `[review] skipped: run with NODE_OPTIONS=--expose-gc` and returns. - **Review tests are a contract.** Never edit `test/review-*.test.ts` to make them pass; fix `src/`. -- **Situation wording is frozen at `situation-v1`.** `situation.test.ts`, `budget.test.ts` and `batch3.test.ts` assert exact fact sentences (regexes / `toContain`), and `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts` assert fact fragments; `report.test.ts`, `atoms.test.ts`, `fetch.test.ts`, `learn.test.ts` assert report / reason / `changed` wording. SIM training data was generated from that tag. The example situations in `packages/runtime/STATUS.md` are copied from the `console.log` output of `situation.test.ts` and `budget.test.ts`. Coordinate any wording change with SIM (STATUS "Open issues"). +- **Situation wording is frozen at `situation-v2`** (tag on 6e5e86e; `situation-v1` is superseded). `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `content.test.ts` and `delivery.test.ts` assert exact fact sentences (regexes / `toContain`), and `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts` assert fact fragments; `report.test.ts`, `atoms.test.ts`, `fetch.test.ts`, `learn.test.ts`, `devtools-runtime.test.ts` assert report / reason / `changed` / title wording. (`smoke.test.ts` prints a delivery situation but asserts only the decision, `dropped` and `subject.kind`, not wording.) SIM's ≥ 10M-row v2 data set and REAL's real-browser rows are being generated from that tag right now, and `training/curriculum/rt.py` mirrors the renderer (its header names `src/situation/{facts,conflicts,content,evidence,describe,build,serialize,questions}.ts` and `src/state/fields.ts` -> `changeText` / `stringDiff`). The example situations in `packages/runtime/STATUS.md` are copied from the `console.log` output of `budget.test.ts` (compact budgets) and `situation.test.ts`, `delivery.test.ts`, `content.test.ts` (full budget). Any change under `src/situation/*` (or to `changeText` / `stringDiff`) means a new tag and regenerated data: coordinate with Mehar (SIM, REAL, TRAIN) first (`HANDOFF.md` "Rules"). - **Browser parity fixtures are v0.1-only.** `test/browser/model-helpers.ts` always reads `test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`, so `model.spec.ts` parity assertions only hold when `GENCLASS_MODEL_DIR` is the v0.1 GenClass model. The unit tests switch to an export's own fixtures (`FIXTURES_FROM_MODEL`); the browser specs do not. - **The default Playwright config also runs `ui-devtools.spec.ts`.** Its `chromium` project matches every `*.spec.ts` except `*webgpu.spec.ts`, so `npm run test:browser` also re-runs the UI spec. That run uses Playwright's default viewport and device scale factor (the main config sets neither) and overwrites the committed screenshots. Use the UI config to regenerate screenshots. - **The UI spec needs the demos workspace installed** (fonts come from `@fontsource-variable/*`, dependencies of `demos`, hoisted to `<repo>/node_modules`). Run a root `npm install`, not one scoped to the runtime. -- **Node version.** `test/model/helpers.ts` -> `pythonOnlyFloatRequests` uses `JSON.parse` source-text access (Node >= 21). On Node 20 it finds nothing, so fixtures holding Python-only float literals such as `25.0` would not be skipped by the packer parity test. Use Node 22 as on the VM. Node 25.6.0 also ran the unit tests in the 2026-10-07 pass, with an EBADENGINE warning from vitest ([Verified locally](#verified-locally-2026-10-07)). -- **Global singletons in tests.** `report.test.ts` and `batch3.test.ts` use `GenClass.init`; always `GenClass.destroy()` (and delete `globalThis.location` if you set it). happy-dom tests patch `window` globals: `rt.destroy()` in `afterEach`. `review-hub.test.ts` swaps `process` `unhandledRejection` listeners and restores them in `finally`. +- **Node version.** `test/model/helpers.ts` -> `pythonOnlyFloatRequests` uses `JSON.parse` source-text access (Node >= 21). On Node 20 it finds nothing, so fixtures holding Python-only float literals such as `25.0` would not be skipped by the packer parity test. Use Node 22 as on the VM and in CI. Node 25.6.0 also ran the unit tests in the 2026-10-08 pass, with an EBADENGINE warning from vitest ([Verified locally](#verified-locally-2026-10-08)). +- **Global singletons in tests.** `report.test.ts`, `batch3.test.ts` and `default-mode.test.ts` use `GenClass.init`; always `GenClass.destroy()` (and delete `globalThis.location` if you set it). happy-dom tests patch `window` globals: `rt.destroy()` in `afterEach`. `review-hub.test.ts` swaps `process` `unhandledRejection` listeners and restores them in `finally`. - **Network-dependent steps:** `smoke.sh` (npm registry), `model.spec.ts` "default ORT wasm path" (jsDelivr; `GENCLASS_OFFLINE=1` skips it), `fetch-model` (GitHub). - **Fixture JSON files are single-line.** `wc -l` prints `0` for `pack_fixtures.json` (955,379 bytes), `py_fixtures.json` (167,629), `requests50.json` (285,309) and `torch_fixtures.json` (255,945): no trailing newline, not empty. Use `wc -c` or a JSON parser. - **No `prepublishOnly` and no `publishConfig`.** `npm publish` packs whatever `dist/` holds; build right before publishing. Scoped packages publish as restricted unless `--access public` is passed (npm behaviour). -- **No committed lockfile.** The root `package-lock.json` has never been in git, so `npm ci` fails on a fresh clone and dependency versions float within the `^` ranges (only `@playwright/test 1.63.0`, `onnxruntime-node 1.30.0` and `typescript ~5.9.3` are pinned tightly). A root `npm install` writes one, which shows up as untracked; committing it is a lead decision (it would fix CI reproducibility). +- **The root lockfile is committed; keep it in sync.** Since b435acb `package-lock.json` is tracked and CI runs `npm ci`, which fails when any workspace `package.json` (root, `packages/*`, `sim`, `demos`) no longer matches the lockfile. After changing a dependency, run `npm install` at the repo root and commit the updated lockfile in the same commit. `realapps/` is not a workspace and has no lockfile of its own. +- **Test harness mode is not the product mode.** `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so a test that does not pass `mode` exercises guard, while a real app (and `GenClass.init`, the smoke script, any package built from this branch; the published `0.1.0-alpha.0` still defaults to guard) starts in `observe`. To test default behaviour pass `mode: undefined`. New headless harnesses that build their own runtime (like `review-fetch.test.ts` -> `headless()`) must pass `mode` explicitly or they observe only. +- **Held store writes are opt-in.** Since batch 4 `policy.holdWrites` is off: an async `set()` applies at once and a model `discard` is a late revert (`interventions()[i].late`). A test that expects `a.get()` to stay unchanged until the model answers needs `policy: { holdWrites: true }`; otherwise assert on the `delivery` decision or the late revert. - **`sim`'s `build:runtime-core` leaves a partial `dist/`.** It writes only `dist/index.js` (+ chunks, maps; `--platform neutral`, no `.d.ts`, no adapters/devtools/worker) and does not clean (tsup CLI default), so whatever an earlier full build left stays. `demos/vite.config.ts` picks the real runtime whenever `dist/index.js` exists, so after this build on an empty `dist/` demos resolve `@genclass/runtime/react` etc. to files that do not exist (and the demos typecheck finds no `.d.ts`). Run the full `npm run build` before working on demos. - **vitest `exclude` replaces the defaults.** `vitest.config.ts` sets `exclude: ["test/browser/**"]` rather than extending vitest's default exclude list. Harmless while `include` is `test/**/*.test.ts`; use `[...configDefaults.exclude, "test/browser/**"]` if `include` is ever widened. - **A checkout may hold stale local artefacts.** `dist/`, `node_modules/`, `test/browser/.build/`, `test-results/` and `*.tgz` are ignored, so a working copy can contain a `dist/` built from older sources. Rebuild before trusting `dist/`, `sim` real-runtime runs or demo results. @@ -370,9 +406,9 @@ These were run at 654d822, when these docs were written, on a macOS machine (16 ### Write a new unit test (house style) 1. Put it in `packages/runtime/test/<area>.test.ts` (`test/model/` for model code). Import with `.js` extensions (`./helpers.js`, `../src/...js`). -2. Use `setup()` and drive time with `clock.advance` / `clock.flush`. Use `triage: "always"` to force a model consultation, `mode: "heal"` for heal-tier actions, `ManualDecider` to control answer timing. +2. Use `setup()` and drive time with `clock.advance` / `clock.flush`. Use `triage: "always"` to force a model consultation, `mode: "heal"` for heal-tier actions (`setup()` defaults to `"guard"`; `mode: undefined` for the product default `observe`), `ManualDecider` to control answer timing. To test held store writes add `policy: { holdWrites: true }`; for the default v2 behaviour drive a network response and assert on the `delivery` decision (copy the app helpers in `delivery.test.ts` -> `searchApp` or `content.test.ts` -> `listApp`). 3. Name the contract section in the `describe` (e.g. `"(CONTRACT §4)"`). For a bug demonstration, follow the `review-*.test.ts` files: a header comment `// REVIEW: <area>. A failing test demonstrates a bug.`, a `describe("review: ...")`, and a test name that states the required behaviour. -4. For DOM: first line `// @vitest-environment happy-dom`, then `createRuntime({ clock: new FakeClock(), global: window, decider, report: "silent", observe: { ...OFF, user: true } })` where `OFF` sets `fetch, xhr, errors, nav, storage, perf, websocket, timers` to `false` (copy it from `dom.test.ts`), and `rt.destroy()` in `afterEach`. +4. For DOM: first line `// @vitest-environment happy-dom`, then `createRuntime({ clock: new FakeClock(), global: window, decider, mode: "guard" /* if you need actions */, report: "silent", observe: { ...OFF, user: true } })` where `OFF` sets `fetch, xhr, errors, nav, storage, perf, websocket, timers` to `false` (copy it from `dom.test.ts`), and `rt.destroy()` in `afterEach`. 5. For model files: `describe.skipIf(!hasModelFile("model.json"))`. ```ts @@ -382,7 +418,7 @@ import { ManualDecider, defaultScript, setup } from "./helpers.js"; describe("my change (CONTRACT §4)", () => { it("holds an async write until the model answers", async () => { const manual = new ManualDecider(); - const { rt, clock } = setup({ decider: manual, triage: "always" }); + const { rt, clock } = setup({ decider: manual, triage: "always", policy: { holdWrites: true } }); // holds are opt-in since v2 const a = rt.atom("v", 0); void rt.op("save", () => a.set(5)); expect(a.get()).toBe(0); // held @@ -393,7 +429,7 @@ describe("my change (CONTRACT §4)", () => { }); ``` -Run it locally (`cd packages/runtime && npx vitest run test/<file>.test.ts`) or on the VM: `scripts/vm.sh run core 'cd packages/runtime && npx vitest run test/<file>.test.ts'` ([Where to run things](#where-to-run-things)). +Run it locally: `cd packages/runtime && npx vitest run test/<file>.test.ts` ([Where to run things](#where-to-run-things)). CI picks up any new `test/**/*.test.ts` automatically. ### Add a browser spec @@ -411,10 +447,12 @@ Run it locally (`cd packages/runtime && npx vitest run test/<file>.test.ts`) or ### Change situation text, facts or questions -1. Edit `src/situation/*` only (single implementation shared with `sim/`). -2. Update the exact-text assertions in `test/situation.test.ts`, `test/budget.test.ts`, `test/batch3.test.ts`, `test/invariants.test.ts`, `test/review-fetch.test.ts`, `test/review-hub.test.ts` (facts) and, for report wording, `test/report.test.ts`, `test/atoms.test.ts`, `test/fetch.test.ts`, `test/learn.test.ts` (search for the old sentence). Changing a `review-*` assertion conflicts with "Review tests are a contract" (gotchas): raise it rather than rewrite it silently. -3. Re-run `situation.test.ts` and `budget.test.ts`, paste their printed situations into the STATUS.md example sections. -4. Tell SIM: rows must be regenerated, and models trained on `situation-v1` data were trained on the old text. See [learn-situation-triage.md](learn-situation-triage.md) and [../model-io-contract.md](../model-io-contract.md). +The format is frozen at `situation-v2` and v2 training data is being generated from it now. Do not change it without Mehar's go-ahead. + +1. Edit `src/situation/*` (and, for change previews, `src/state/fields.ts` -> `changeText` / `stringDiff`) only: a single implementation shared with `sim/`; `realapps/` bundles the same source; `training/curriculum/rt.py` mirrors the renderer in Python and must be updated too. +2. Update the exact-text assertions in `test/situation.test.ts`, `test/budget.test.ts`, `test/batch3.test.ts`, `test/content.test.ts`, `test/delivery.test.ts`, `test/invariants.test.ts`, `test/review-fetch.test.ts`, `test/review-hub.test.ts` (facts) and, for report and title wording, `test/report.test.ts`, `test/atoms.test.ts`, `test/fetch.test.ts`, `test/learn.test.ts`, `test/devtools-runtime.test.ts`, and `SessionDecider` -> `judge()` regexes in `test/browser/ui/session.ts` (search for the old sentence). Changing a `review-*` assertion conflicts with "Review tests are a contract" (gotchas): raise it rather than rewrite it silently. +3. Re-run `situation.test.ts`, `delivery.test.ts`, `content.test.ts` and `budget.test.ts`, paste their printed situations into the STATUS.md example sections ("Example situations: compact budgets" from `budget.test.ts`; "full budget (2,400)" from the other three). +4. Cut a new frozen tag (`situation-v3`) only with the owner, and tell SIM, REAL and TRAIN: rows must be regenerated, and models trained on v2 data were trained on the old text. See [learn-situation-triage.md](learn-situation-triage.md), [../model-io-contract.md](../model-io-contract.md) and [../realapps.md](../realapps.md). ### Regenerate model fixtures @@ -427,72 +465,104 @@ Run it locally (`cd packages/runtime && npx vitest run test/<file>.test.ts`) or Writes `f32emb/` (fp32 embedding table: `Gather(fp32)`) and `i8emb/` (int8 table + per-row fp32 scale: `Gather(int8) -> Cast -> Mul(Gather(scale))`). - `pack_fixtures.json` / `torch_fixtures.json`: outputs of `scripts/genclass_export.py` or `extension/tools/genclass_export.py` (identical fixture code; which one produced the committed files is not recorded). Both export the extension's v1 computer-use model, import torch and say "RUN ON THE AZURE VM ONLY"; the fixtures are Python `Packer` output and PyTorch logits, so they do not depend on the int8 vs q8 ONNX variant. They were copied from `extension/test/fixtures/` and re-serialised compactly. Do not hand-edit them; the browser parity specs depend on them matching the v0.1 model. If you regenerate, re-serialise without whitespace to keep diffs comparable, and regenerate `requests50.json` from the same request set. -### Publish history (from git) +### Publish history (from git and the registry) -| when (commit time) | commit / tag | what | +| when | commit / tag | what | |---|---|---| -| 2026-10-07 19:19 -0400 | tag `situation-v1` -> 1a77558 | runtime fix batch 3; situation format frozen for SIM data | +| 2026-10-07 19:19 -0400 | tag `situation-v1` -> 1a77558 | runtime fix batch 3; situation format v1 frozen for SIM data | | 2026-10-07 20:09 -0400 | 59c213f | `version` `0.1.0` -> `0.1.0-alpha.0`, `packages/runtime/LICENSE` added, `test/smoke/smoke.sh`, `.gitignore` gains `.publish/` and `*.tgz` | -| between 59c213f and 654d822 | (npm) | `@genclass/runtime@0.1.0-alpha.0` published; OPEN_TASKS: "2026-10-08, `genclass` org, owner meharpro", smoke-tested first | -| 2026-10-07 20:15 -0400 (00:15 UTC 10-08) | 654d822, tag `v0.1.0-alpha.0` (tagged 20:15:12 -0400) | both READMEs get an npm badge (`/npm/v/@genclass/runtime/latest`), a license badge and an "alpha" status note (the `npm install @genclass/runtime` lines were already there); OPEN_TASKS moves publish to "Done" and rewrites item 8 | +| 2026-10-07 20:15 -0400 (00:15 UTC 10-08) | 654d822, tag `v0.1.0-alpha.0` | READMEs get npm and license badges and an "alpha" note; OPEN_TASKS moves publish to "Done" | +| 2026-10-08 00:14 / 00:18 UTC | (npm) | `@genclass/runtime@0.0.0-stage` (about one minute before 654d822's commit time) then `0.1.0-alpha.0` (about three minutes after it) published (`npm view @genclass/runtime time`); dist-tag `latest` = `0.1.0-alpha.0`. OPEN_TASKS: "2026-10-08, `genclass` org, owner meharpro", smoke-tested first | +| 2026-10-07 21:16 -0400 (01:16 UTC 10-08) | ad24804, ce27efd | fix infinite recursion on `NaN` in state (`test/nan.test.ts`); OPEN_TASKS asks the user to publish `0.1.0-alpha.1` (needs 2FA). **Not published** (`npm view` 2026-10-08) | +| 2026-10-07 22:31 / 23:26 -0400 | fcd1e68, 6e5e86e (tag `situation-v2`) | runtime batch 4 (delivery trigger, no store holds by default) and batch 5 (separability facts); situation format v2 frozen | +| 2026-10-08 00:15 -0400 | f3636b2, b435acb (`mvp-v2`, ours, not pushed) | default mode `observe`; CI workflow, committed root lockfile, CLI mode 100755 | + +`package.json` `version` is still `0.1.0-alpha.0` on `mvp-v2` (no bump for alpha.1 yet). What `.publish/` was used for is not recorded (unverified). + +### Cut a release of `@genclass/runtime` + +Full procedure: [RELEASE.md](../../../RELEASE.md) Part A. + +There is no publish script, no `prepublishOnly` and no `publishConfig`. The recorded procedure (`HANDOFF.md` "Current state": "Each publish needs the user's 2FA, so give them the exact `npm publish <tgz> --access public` command") is: the agent prepares and checks a tarball, the **user** publishes it. + +1. Locally: `npm ci`, `npm run typecheck -w @genclass/runtime`, `npm run build -w @genclass/runtime`, the unit tests and perf budgets as in CI (or a green CI run on the pushed branch). With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs and `bash test/smoke/smoke.sh`. +2. Bump `version` in `packages/runtime/package.json` (e.g. `0.1.0-alpha.1`), plus the version strings in READMEs, `OPEN_TASKS.md` and `HANDOFF.md`. Run `npm install` at the root so the lockfile's `packages/runtime` entry picks up the version, and commit both. +3. From `packages/runtime`: `npm run build && npm pack` -> `genclass-runtime-<version>.tgz`; check `npm pack --dry-run` lists only `dist/`, `bin/`, `README.md`, `LICENSE`, `package.json`. +4. Give the user the command to run (on a machine logged in to npm with publish rights on the `genclass` org, with their 2FA): `npm publish genclass-runtime-<version>.tgz --access public --tag <tag>`. **A prerelease needs `--tag`** on npm 11: `lib/commands/publish.js` in npm 11.8.0 throws "You must specify a tag using --tag when publishing a prerelease version." unless `--tag` (or `publishConfig.tag`, or `--force`) is given, so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. Use `--tag alpha` (or `next`) to leave `latest` on `0.1.0-alpha.0`, or `--tag latest` to move it (today `latest` = `0.1.0-alpha.0`; how alpha.0 got that tag, an older npm or an explicit `--tag latest`, is not recorded). A non-prerelease such as `0.1.0` needs no tag and becomes `latest`. Never run `npm publish` yourself without an explicit user go-ahead in chat. +5. After the publish: `git tag -a v<version> -m "@genclass/runtime <version> (npm)"` (push only with the user's OK); move the item to "Done" in `OPEN_TASKS.md`; check `npm view @genclass/runtime dist-tags`. -Before 654d822, OPEN_TASKS "Needs the user" listed the prerequisites: "an `@genclass` npm org and `npm login` on this machine (not logged in), or another scope name". The exact `npm publish` flags (dist-tag, `--access`) and what `.publish/` was used for are not recorded (unverified). +What a release built from `mvp-v2` would change for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model the runtime still only observes either way. -### Cut a release of `@genclass/runtime` (reconstructed; there is no script) +### Publish the model package (planned; OPEN_TASKS.md item 9; HANDOFF.md "How to continue") -1. Locally: `npm install`, `npm run build`, `npm run typecheck -w @genclass/runtime`, the unit tests with `--expose-gc`. With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs and `bash test/smoke/smoke.sh`, locally or on the VM ([Where to run things](#where-to-run-things)). -2. Bump `version` in `packages/runtime/package.json` (and the version strings in READMEs/OPEN_TASKS). -3. From `packages/runtime` on a machine logged in to npm with publish rights on the `genclass` org: `npm publish --access public` (add `--tag alpha` or similar for prereleases; the flags used for `0.1.0-alpha.0` are not recorded, unverified). -4. `git tag -a vX.Y.Z -m "@genclass/runtime X.Y.Z (npm)"` and push the tag. Update `OPEN_TASKS.md` "Done". -5. The user must approve any publish; it is an irreversible public action. +Full procedure: [RELEASE.md](../../../RELEASE.md) Part B. -### Publish the model package (planned, OPEN_TASKS item 8) +Blocked on training: no situation-v2 model exists (next per HANDOFF: 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL). The round-1 R17 (`files/r17/` per MODEL_CARD, situation-v1) does not match the v2 runtime and must not be published as the default. `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` both 404 today. 1. Put a model directory (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`) under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `DEFAULT_MODEL_BASE_URL`. Check it with `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files`. -2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`). +2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`), so run a root `npm install` and commit the lockfile change, or CI's `npm ci` fails. 3. Attach the same files to a GitHub release tagged `runtime-model-v0.1.0` (the CLI's `DEFAULT_FROM`). -4. Then publish `@genclass/runtime@0.1.0` without a prerelease tag. +4. Rerun the demos with the trained model, then publish `@genclass/runtime@0.1.0` without a prerelease tag (user, 2FA). -### Add CI (planned, OPEN_TASKS item 8) +### CI (`.github/workflows/ci.yml`) -No workflow exists (no `.github/`, no other CI config anywhere in the repo). A minimal one (`.github/workflows/*.yml`, Node 22 (≥ 22.12) or 24, inside vitest 5.0.3's engine range (23 and 25 are outside)) would run: `npm install` (or commit a root `package-lock.json` first and use `npm ci`; none is tracked today), `npm run build`, `npm run typecheck -w @genclass/runtime`, `NODE_OPTIONS=--expose-gc npm test`. Without a model directory the 14 model-file tests skip. The root `npm run typecheck` also typechecks `sim` (no build needed) and `demos` (needs the full build first, and fails until the missing `demos/src/server/data/cities.ts` is recreated; see [../demos.md](../demos.md#drift-and-open-issues) Drift 1). Browser specs would additionally need `npx playwright install --with-deps chromium` and a model directory; the smoke test needs registry access. Treat `review-perf.test.ts` wall-clock bounds as possibly flaky on shared runners. +One workflow, `CI`, one job `runtime` ("@genclass/runtime: typecheck, build, unit tests"), added in b435acb: + +| step | command | notes | +|---|---|---| +| checkout | `actions/checkout@v4` | | +| node | `actions/setup-node@v4`, `node-version: 22`, `cache: npm` | inside vitest 5's engine range | +| Install | `npm ci --no-audit --no-fund` | job env `ONNXRUNTIME_NODE_INSTALL: skip` | +| Typecheck | `npm run typecheck -w @genclass/runtime` | runtime only; the root `npm run typecheck` would also typecheck `sim` and `demos` (which needs `dist/` and the missing `demos/src/server/data/cities.ts`) | +| Build | `npm run build -w @genclass/runtime` | | +| Unit tests | `npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in `packages/runtime`, `NODE_OPTIONS: --expose-gc` | model parity tests skip (no `GENCLASS_MODEL_DIR`) | +| Perf budgets | `npx vitest run test/review-perf.test.ts --retry=2`, same env | | + +Not in CI: Playwright (model and UI specs), `smoke.sh`, model-dir tests, `sim`/`demos`/`realapps`, Python tests. It has not run on GitHub yet (the branch is unpushed; `origin/runtime` has no `.github/`). + +To change it: keep the runtime steps green locally first (same commands, [Exact commands](#exact-commands)). Adding the sim tests would need `npm run build -w @genclass/runtime` first and `SIM_RUNTIME=real`; adding browser specs needs `npx playwright install --with-deps chromium` and, for model specs, a model directory (a download: ask the user). Changing the trigger branches or adding jobs that publish is a user decision. ## Tests -Counts are `it(...)` cases (the `budget.test.ts` loop counts 3). The total of 300 matches STATUS (300 total, UI 53, MODEL 62) and the 2026-10-07 vitest run (300 tests: 286 passed, 14 model-file tests skipped; see [Verified locally](#verified-locally-2026-10-07)); the remaining 185 are CORE 142 + REVIEW 43. +Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder.test.ts` loop counts 4), collected with vitest's JSON reporter on b435acb. **Total 350 in 42 tracked files**: CORE 188, UI 53, MODEL 62, REVIEW 43, lead 4 (`default-mode.test.ts`). STATUS's "41 files, 346 tests" predates `default-mode.test.ts`. Without a model directory 14 MODEL tests skip (see [Verified locally](#verified-locally-2026-10-08)). Since 654d822: +5 files (`content` 14, `delivery` 16, `no-reorder` 6, `nan` 1, `default-mode` 4), and `atoms` +2, `batch3` +1, `dom` +4, `report` +1, `situation` +1. Tests that rely on held store writes now pass `policy: { holdWrites: true }` (`adapter-seam`, `adapters-*` real-runtime blocks, `plugins`, `report` (2 cases), `batch3` "ctx.builtin returns false ...", `review-hub` "in-place updater while held", `budget` hold-budget case, `no-reorder` last case; `atoms.test.ts` wraps `setup()` to always add it); the `adapters-*` `MockRuntime` blocks set `rt.holdWrites = true` on the mock instead. | test file | owner | env | tests | what it asserts | |---|---|---|---|---| -| `test/adapter-seam.test.ts` | CORE | node | 4 | `rt.adapter(name, io).propose({fn, commit})`: reducer preview, async dispatch held then committed, discard never commits, direct library changes recorded not held, rollback offered only when `io.set` exists | -| `test/adapters-react.test.ts` | UI | happy-dom | 9 | `useGenClassState` (one atom per name, held write shown only when applied, StrictMode-safe, plain-state fallback with one `console.info` "no runtime"), `useAtom`, `useGenClass` throws "No runtime", live `useGenClassDecisions/Interventions/Status`; with the real runtime: hold, discard, undo; user-handler writes never held | -| `test/adapters-redux.test.ts` | UI | node | 11 | `genclassEnhancer`: passthrough, hold/apply once (reducer runs once), re-run on moved state, drop, middleware/thunks see the action once, no-op actions, `replaceReducer`, inner enhancers see `GENCLASS_REPLACE` for GenClass writes, `null` runtime; real runtime hold/discard/undo | -| `test/adapters-zustand.test.ts` | UI | node | 6 | `genclass(rt, name)` middleware: merge semantics, hold/drop, replace/functional/no-op/extra `set` args, GenClass whole-state writes, `null` runtime; real runtime | +| `test/adapter-seam.test.ts` | CORE | node | 4 | `rt.adapter(name, io).propose({fn, commit})` with `holdWrites: true`: reducer preview, async dispatch held then committed, discard never commits, direct library changes recorded not held, rollback offered only when `io.set` exists | +| `test/adapters-react.test.ts` | UI | happy-dom | 9 | `useGenClassState` (one atom per name, held write shown only when applied, StrictMode-safe, plain-state fallback with one `console.info` "no runtime"), `useAtom`, `useGenClass` throws "No runtime", live `useGenClassDecisions/Interventions/Status`; with the real runtime (`holdWrites: true`): request, then a `delivery` decision, then the held `mutation`; hold, discard, undo; user-handler writes never held | +| `test/adapters-redux.test.ts` | UI | node | 11 | `genclassEnhancer`: passthrough, hold/apply once (reducer runs once), re-run on moved state, drop, middleware/thunks see the action once, no-op actions, `replaceReducer`, inner enhancers see `GENCLASS_REPLACE` for GenClass writes, `null` runtime; real runtime (`holdWrites: true`) hold/discard/undo | +| `test/adapters-zustand.test.ts` | UI | node | 6 | `genclass(rt, name)` middleware: merge semantics, hold/drop, replace/functional/no-op/extra `set` args, GenClass whole-state writes, `null` runtime; real runtime (`holdWrites: true`) | | `test/ask.test.ts` | CORE | node | 5 | `ask()` typed answers (choice/noul/score), trigger `ask`, `about` an op or store, `decide()`, `GenClassUnavailableError` without a model (status `off`), timeout reason `timeout` | -| `test/atoms.test.ts` | CORE | node | 16 | mutation pipeline: user-sync writes never held, async held then applied, fail-open at `holdBudgetMs` + late discard revert + undo, no late revert when superseded / after 2 s / same chain wrote again, late defer only recorded, provider errors (`not_ready`, `max_tokens_exceeded`, `timeout`, `busy`) fail open at once, proposal order, functional re-run, patch re-apply, discard + undo, defer max 2, `hold: false`, `guard()`, same-name atoms, field versions/writers | -| `test/batch3.test.ts` | CORE | node | 13 | SIM requests a–f (word-level redaction, kanban card values, no `= undefined` state lines, item change summaries, "changed twice ... back to 6", slug ids via `normalizePath`/`isIdSegment`, pending-local-change fact), `ctx.builtin` through the gate, rate-limit warning once per minute, `ask()` after destroy, read-only globals, `GenClass.init` never throws, never-answering provider, `transient` label last | -| `test/budget.test.ts` | CORE | node | 12 | `sectionLimits` at 500/1,100/2,000/3,200; budgets 1,000/1,100/2,000 shape every section; compact questions at <= 1,400; vocabulary overrides <= 24 chars kept; determinism; auto budget (webgpu 3,200; wasm 1,000/1,333/2,000; unknown 3,200; fixed 1,500); `max_tokens_exceeded` shrinks auto budget to 2,560; `holdBudget` auto = clamp(1.5 x median, 150, 800) else 300; held write `timeoutMs` = budget + 2,000; fetch `timeoutMs` = remaining budget. Prints example situations | +| `test/atoms.test.ts` | CORE | node | 18 | mutation pipeline **with `holdWrites: true`** (local `setup` wrapper): user-sync writes never held, async held then applied, fail-open at `holdBudgetMs` + late discard revert + undo, no late revert when superseded / after 2 s / same chain wrote again, a model slower than the hold budget means no hold at all, late defer only recorded, provider errors fail open at once, proposal order, a user write never overtakes an earlier held write of the same store (DEMOS regression), queued functional updates re-run, read-your-writes inside the writing chain, patch re-apply, discard + undo, defer re-decides after related ops settle (max 2), `hold: false`, `guard()`, same-name atoms, field versions/writers | +| `test/batch3.test.ts` | CORE | node | 14 | SIM requests a–f (word-level redaction, kanban card values, no `= undefined` state lines, item change summaries, "changed N times and is back to V", slug ids via `normalizePath`/`isIdSegment`, pending-local-change fact), `ctx.builtin` through the gate, rate-limit warning once per minute, `ask()` after destroy, read-only globals, `GenClass.init` never throws, never-answering provider, `transient` label last; batch 5: redaction by the leaf field, never by the store name (an `auth` store keeps status flags and user name) | +| `test/budget.test.ts` | CORE | node | 12 | `sectionLimits` at 500 (= 1,100)/1,100/1,750/2,400 (3,200 = 2,400); budgets 1,000/1,100/2,000 shape every section of a `delivery` situation; compact questions at <= 1,400; vocabulary overrides <= 24 chars kept; determinism; auto budget (webgpu 2,400; wasm 1,000/1,333/2,000; unknown 2,400; fixed 1,500); `max_tokens_exceeded` shrinks auto budget to 1,920; `holdBudget` auto = clamp(1.5 x median, 150, 800) else 300; held write `timeoutMs` = budget + 2,000; fetch `timeoutMs` = remaining budget. Prints example situations | +| `test/content.test.ts` | CORE | node | 14 | batch 5 situation-v2 facts from `sim/SEPARABILITY.md` §6, one per fact: F3 a response that changes nothing is not salient; F1 put back a value a newer operation replaced (field, item cells); F2 overwrites text the user typed (diff-centred preview); F9 provenance of known-stale values (incl. a live channel that was down); F6 learned cadence (polling, debounced save); F5 failure scope and commit ambiguity; F7 repeated user action evidence; F8 relation quality; read-your-writes. Prints STATUS example situations | | `test/context.test.ts` | CORE | node | 7 | causal context: fetch -> json -> set cause/root, concurrent chains, `rt.op` ambient in body and continuation, nested op causes, ambient cleared by `afterTask`, timers observer carries cause (`timer 300ms`), idle timers create no ops | -| `test/devtools-runtime.test.ts` | UI | happy-dom | 7 | overlay on the real runtime (`runStoreSession`): interventions, folded detections, evidence = `explain()`, activity timeline, Now view, undo, live report sentence | +| `test/default-mode.test.ts` | lead (f3636b2) | node | 4 | `createRuntime` without `mode` is `observe`; `GenClass.init` without `mode` is `observe`, `mode: "guard"` or `?genclass=guard` opt in; in observe nothing is held, delayed or changed even at p = 0.99 (decisions recorded, `executed` false, detections reported); with a never-answering model nothing waits (atom, adapter commit, fetch success and failure all immediate) | +| `test/delivery.test.ts` | CORE | node | 16 | situation-v2 network-boundary decisions: clean typeahead (in-order, loading flags, debounce) makes zero model calls; a stale out-of-order response gets a `delivery` decision and `discard` drops only its stale field writes; holding a response is only latency; no hold when the model cannot answer within the hold budget; store writes never held by default (read-after-write, late revert, slow model released at the budget, superseded queued decisions dropped); WebSocket messages (held only when they would put back a value a pending local change replaced, order kept), EventSource (custom event types as ops), XHR (held before any completion listener, abort during the hold); forced actions with probability 1 | +| `test/devtools-runtime.test.ts` | UI | happy-dom | 7 | overlay on the real runtime (`runStoreSession`, guard): interventions newest first ("Prevented a stale response", "Reverted a duplicate write", "Prevented a duplicate request", "Slowed down a failing request"), folded detections, evidence = `explain()` (trigger "The response to GET /api/search?q=rea"), activity timeline, Now view, undo, live report sentence | | `test/devtools.test.ts` | UI | happy-dom | 20 | overlay vs `MockRuntime` + `loadScenario`: mount/unmount (shadow root, `data-genclass-ignore`, no global CSS, listeners and plugin removed), no-op handle, theme/position, feeds, activity rows, typing bursts, evidence, undo and undo errors, live pill, folding, 200-card cap, policy reasons, pause/clear, Now view, mode switch, keyboard (Alt+Shift+G), empty states | -| `test/dom.test.ts` | CORE | happy-dom | 8 | `describeElement`; DOM user observer (clicks, typing bursts, passwords never recorded, submit/change/Enter, `[data-genclass-ignore]` incl. shadow roots, destroy); destroy restores fetch/XHR/history/Storage/WebSocket/timers; uncaught errors -> error trigger | +| `test/dom.test.ts` | CORE | happy-dom | 12 | `describeElement` (incl. batch 5: a control nested in its `<label>`, open shadow roots, `aria-labelledby`, slotted text); DOM user observer (clicks, typing bursts, passwords never recorded, submit/change/Enter, `[data-genclass-ignore]` incl. shadow roots, shadow-DOM targets described as the real element, synthetic `isTrusted: false` events only with `observe.untrustedEvents`, destroy); destroy restores fetch/XHR/history/Storage/WebSocket/timers; uncaught errors -> error trigger | | `test/fetch.test.ts` | CORE | node | 17 | fetch observer: plain traffic makes no model call, app body vs clone, coalesce (`x-genclass: coalesced`), block (503 `blocked`), guard never runs heal-tier, `serve_cached`, delay 250 ms first, retry backoff 200 ms, retry not offered for non-replayable bodies, network error delivered, failure/request gates fail open at 300 ms, hedge, abort, `TimeoutError` = failure, cache <= `MAX_ENTRIES` (64) and skips bodies > `MAX_BODY` (256 KB), destroy restores fetch | | `test/invariants.test.ts` | CORE | node | 6 | `InvariantMiner` learns len/sum/equality/unique relations, ignores unchanged fields and id-like keys; inconsistency once per episode + rollback + undo; unsettled transients ignored; `expect()` predicates | | `test/learn.test.ts` | CORE | node | 8 | `Baselines` (latency after 5 samples, EWMA 0.9 error rate, streaks, outcomes, rate vs usual, identity gaps); `Profiles` (write set < 1% of >= 20, value kind, status class); transition trigger + rollback | -| `test/plugins.test.ts` | CORE | node | 7 | plugin facts/diagnoses/custom actions, `ctx.builtin`, plugin actions default to heal tier, `applicable()`, standing questions + `onAnswer`, `setup()`/cleanup API, vocabulary overrides | +| `test/nan.test.ts` | CORE (ad24804) | node | 1 | a store holding `NaN` builds situations without infinite recursion (the alpha.0 crash; fix awaiting the `0.1.0-alpha.1` publish) | +| `test/no-reorder.test.ts` | CORE | node | 6 | "never worse": realworld's Redux promise-middleware pattern through `genclassEnhancer` with an always-passive model (`PassiveDecider`, 10 ms): observe baseline renders; guard and heal x triage salient and always give identical dispatches, order, pages and final state with 0 interventions; `holdWrites: true` never reorders a store's dispatches | +| `test/plugins.test.ts` | CORE | node | 7 | plugin facts/diagnoses/custom actions, `ctx.builtin` (with `holdWrites: true`), plugin actions default to heal tier, `applicable()`, standing questions + `onAnswer`, `setup()`/cleanup API, vocabulary overrides | | `test/policy.test.ts` | CORE | node | 14 | `gate()` summed mass, mode tiers, thresholds 0.9 guard / 0.8 heal, passive top, `requireDiagnosis`, deny/allow, pause, rate limit with 60 s sliding window, observe never holds, `setMode`, `pause()/resume()`, loading fails open without a record, detection threshold | -| `test/report.test.ts` | CORE | node | 7 | report line format, `explain(id)`, "Not acted on (would have done ...)", console group + "(×2 more in the last minute)", `on()` listeners, `GenClass.init` idempotent, `?genclass=off`, `?genclass=heal` | +| `test/report.test.ts` | CORE | node | 8 | report line format, `explain(id)`, without `holdWrites` a discarded write is applied at once, late-reverted and reported "Reverted a stale write ... (decided 0.00s after it applied)" with `late: true`, "Not acted on (would have done ...)", console group + "(×2 more in the last minute)", `on()` listeners, `GenClass.init` idempotent, `?genclass=off`, `?genclass=heal` | | `test/review-actions.test.ts` | REVIEW | node | 1 | error-trigger rollback only when the failing chain wrote state; user input survives | | `test/review-dom.test.ts` | REVIEW | happy-dom | 2 | unlabeled password never recorded; programmatic `click()` inside an op is not a user action | -| `test/review-fetch.test.ts` | REVIEW | node | 11 | request identity (Request bodies, Range), coalesce with opaque / streaming responses never hangs, buffers <= 64 x 256 KB, abort listener removed, no work after destroy, guard-mode failures not held, keepalive sent synchronously, "started after" direction, error-rate counts | -| `test/review-hub.test.ts` | REVIEW | node | 8 | held value write patched over user edit, queued nested object kept, late-revert undo, in-place push summary, in-place updater while held, versions past 16 history entries, deep change in 2,000-item array, throwing commit does not strand the queue | +| `test/review-fetch.test.ts` | REVIEW | node | 11 | request identity (Request bodies, Range), coalesce with opaque / streaming responses never hangs, buffers <= 64 x 256 KB, abort listener removed, no work after destroy, guard-mode failures not held, keepalive sent synchronously, "started after" direction, error-rate counts. Its local `headless()` passes `mode: "guard"` (f3636b2) | +| `test/review-hub.test.ts` | REVIEW | node | 8 | held value write patched over user edit, queued nested object kept, late-revert undo, in-place push summary, in-place updater while held (`holdWrites: true` since batch 4), versions past 16 history entries, deep change in 2,000-item array, throwing commit does not strand the queue | | `test/review-misc.test.ts` | REVIEW | node | 6 | console ×N summaries, rate-limit warning once, read-only `fetch`, `ctx.builtin` cannot run a denied heal-tier action, never-settling provider, `ask()` after destroy | -| `test/review-perf.test.ts` | REVIEW | node | 4 | wall-clock cost budgets on 5,000-item stores (see gotchas); logs numbers | +| `test/review-perf.test.ts` | REVIEW | node | 4 | wall-clock cost budgets on 5,000-item stores (see gotchas); logs numbers. Runs in its own CI step with `--retry=2` | | `test/review-precision.test.ts` | REVIEW | node | 4 | short last page is not a transition, keyed keys like `m21` are not, closing a selection is not an inconsistency, a lingering violation does not freeze snapshots | | `test/review-redaction.test.ts` | REVIEW | node | 1 | custom `redact` also applies to invariant facts | | `test/review-timers.test.ts` | REVIEW | node | 2 | 200,000-step recursive `setTimeout` loop does not throw; polling loop does not retain ops (registry prunes beyond 2,000; gc check needs `--expose-gc`) | | `test/review-xhr.test.ts` | REVIEW | node | 4 | sync XHR never held, abort while held means never sent, listeners added once per object, reuse after a blocked answer | -| `test/situation.test.ts` | CORE | node | 10 | one situation per trigger (mutation, request, failure, stall, inconsistency, transition, error): keys `app, trigger, facts, in_flight, timeline, state, stats`, facts <= 12, timeline <= 16, state <= 8, `stateChars <= STATE_CHAR_BUDGET`; `situation()` side-effect free; serializer drop order; determinism. Prints situations | -| `test/smoke.test.ts` | CORE | node | 3 | atoms apply synchronously when nothing is salient; context through real awaits; stale write discarded in guard mode (own local `setup()`) | +| `test/situation.test.ts` | CORE | node | 11 | one situation per trigger: `delivery` (a stale response about to overwrite newer results; in-order responses never ask), `mutation` (an older task's write over a newer task's, applied then late-reverted), request, failure, stall, inconsistency, transition, error, `ask` (side-effect free): keys `app, trigger, facts, in_flight, timeline, state, stats`, section limits, `stateChars <= STATE_CHAR_BUDGET`; serializer drop order; determinism. Prints situations | +| `test/smoke.test.ts` | CORE | node | 3 | atoms apply synchronously when nothing is salient; context through real awaits; in guard mode a stale out-of-order response gets one `delivery` decision, `discard` drops only `search.results` (`interventions()[0].dropped`), the app still sees the response (own local `setup()` with `mode: "guard"`) | | `test/xhr.test.ts` | CORE | node | 5 | XHR op + cause, block replays 503, failures detection-only, request gate fails open at 300 ms, destroy restores `open`/`send` | | `test/model/calibrate.test.ts` | MODEL | node | 8 | sha1 header keys vs Python, sha256 (TS and WebCrypto) at edge lengths; calibration vs PyTorch < 1e-9 (needs `calibration.json` in `MODEL_DIR`); v1/v2 calibration vs Python < 1e-12; confidence; `buildAnswer`; `tauFor`/`kBucket`/`parseCalibration` | | `test/model/engine.test.ts` | MODEL | node | 4 | ORT-node CPU q8 and fp16 parity vs PyTorch, ORT-web WASM q8 (12 requests, 1 thread) (all need model files); graph contract with a fake ORT (feeds exactly `meta.inputs`, `ModelUnsupportedError`) | @@ -520,31 +590,37 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3). The total of 30 Doc-vs-code mismatches (code wins): +- **`HANDOFF.md` "What this is"** says "Modes: observe -> guard (default; ...) -> heal". Since f3636b2 (on `mvp-v2` only) the default is `observe`; guard is opt-in and heal experimental. `HANDOFF.md` and `STATUS.md` were not updated by that commit. +- **`HANDOFF.md` "Current state"** gives the publish command as `npm publish <tgz> --access public`. With npm 11 that fails for any prerelease (`0.1.0-alpha.1`) unless `--tag` is added ([Cut a release](#cut-a-release-of-genclassruntime) step 4). +- **`.gitignore` `data/` hides `demos/src/server/data/cities.ts`**, which the demos import; see gotchas and [../demos.md](../demos.md). +- **Test counts.** `STATUS.md` "State" says "41 files, 346 tests" and `HANDOFF.md` "346 tests pass"; on `mvp-v2` it is 42 files, 350 tests (`default-mode.test.ts` added). +- **Branch header.** `OPEN_TASKS.md` says "Branch `runtime`"; `origin/main` is still 654d822, so "Merging `runtime` into `main`" ("Needs the user") is still open. - `packages/runtime/STATUS.md` "Open issues" says `react-dom` is not a devDependency of `@genclass/runtime`, and `packages/runtime/UI-NEEDS.md` item 2 (still under "Open") asks for `react-dom` and `@types/react-dom`. Both are devDependencies: `react-dom ^19.3.0`, `@types/react-dom ^19.0.0`. UI-NEEDS item 1 (ignore `[data-genclass-ignore]`) is also listed as open but is implemented and tested (`dom.test.ts`). -- `STATUS.md` "For UI" says `test/browser/ui/mock-runtime.ts` needs `holdBudgetMs()` and `situationBudget()`. Both exist (return `300` and `3200`). "Not type-checked" is still true. -- `STATUS.md` runs `vitest run --exclude "test/browser/**"`. The exclude is already in `vitest.config.ts`; plain `vitest run` / `npm test` is equivalent. -- `OPEN_TASKS.md` item 8 still lists "`npm pack` smoke test in a fresh Vite app" as to do. `test/smoke/smoke.sh` exists (commit 59c213f) and "Done" says it was run for the alpha. -- `OPEN_TASKS.md` header says "Status as of 2026-10-07 23:30 UTC. Branch `runtime`", but its publish entry is dated 2026-10-08. `main`, `origin/main` and `origin/runtime` all point at 654d822, so the "Merging `runtime` into `main`" item looks done on the remote. -- `packages/runtime/src/model/README.md` ("Bundling") says `dist/worker.js` imports `onnxruntime-web/webgpu`. The worker now imports either `onnxruntime-web/webgpu` or `onnxruntime-web/wasm` on demand (`src/model/worker.ts`), and `build.mjs` checks both. +- `packages/runtime/src/model/README.md` ("Bundling") says `dist/worker.js` imports `onnxruntime-web/webgpu`. The worker imports either `onnxruntime-web/webgpu` or `onnxruntime-web/wasm` on demand (`src/model/worker.ts`; the same README's file table says so), and `build.mjs` checks both. - `test/browser/model-helpers.ts` -> `saveResults` doc comment says it writes `test-results/browser/<name>.json`. The code writes `test-results/model-bench/<name>.json` (the model README is correct). - `test/browser/ui-devtools.spec.ts` calls its output "the README screenshots", but no README or doc references `test/browser/ui/screenshots/*.png`. -- `sim/README.md` says the runtime's full tsup config "fails until those [adapter] files exist". The adapters exist; the full build works (STATUS: "`tsup` build OK"). -- `docs/runtime/CONTRACT.md` §1 describes `packages/runtime-model/` as "model card + files for the CDN package". Only `MODEL_CARD.md` exists; `files/` is gitignored and there is no `package.json`. +- `sim/README.md` says the runtime's full tsup config "fails until those [adapter] files exist". The adapters exist; the full build works. +- `docs/runtime/CONTRACT.md` §1 describes `packages/runtime-model/` as "model card + files for the CDN package". Only `MODEL_CARD.md` is tracked; `files/` is gitignored (MODEL_CARD mentions a local `files/r17/`, situation-v1) and there is no `package.json`. - `packages/runtime-model/MODEL_CARD.md` lists 9 diagnoses (no `transient`); the runtime has 10 (`DEFAULT_DIAGNOSES` ends `unusual, transient`, asserted in `batch3.test.ts`). - Documented `GENCLASS_MODEL_DIR` locations differ: `~/gcl/model/.cache-model` (STATUS), `~/gcl-cache/model-v0.1` (model README), `~/gcl/models/genclass-v0.1` (demos `vm-eval.sh` default model dir). Unverified which exist on the VM. -- npm dist-tag of the alpha is ambiguous (unverified): `OPEN_TASKS.md` item 8 says publish `0.1.0` "without the alpha tag", while both READMEs say `npm install @genclass/runtime` (installs `latest`) and their badges query `/npm/v/@genclass/runtime/latest`. Whether `0.1.0-alpha.0` went out under `latest` or a prerelease tag is not recorded; check `npm view @genclass/runtime dist-tags` before relying on either. - `scripts/genclass_export.py` usage text passes `--requests extension/genclass/test/fixtures/requests50.json`; that path does not exist in this repo (the file is `extension/test/fixtures/requests50.json`; the script's own instructions say to run "from ~/jev on the VM"). -- Ownership: `docs/runtime/CONTRACT.md` §1 (layout) still lists `src/adapters/` and `src/devtools/` as owner CORE, but §13 (Additions) reassigns them to UI, which matches `STATUS.md` counting their tests (`adapters-*.test.ts`, `devtools*.test.ts`, 53) as UI's. §1 is stale; the Tests table follows §13 / STATUS. +- Ownership: `docs/runtime/CONTRACT.md` §1 (layout) still lists `src/adapters/` and `src/devtools/` as owner CORE, but §13 (Additions) reassigns them to UI, which matches `STATUS.md` counting their tests as UI's. §1 is stale; the Tests table follows §13 / STATUS. +- `test/browser/model-helpers.ts` and `model.spec.ts` parity still target the v0.1 GenClass model; nothing in the browser specs exercises a situation-v2 runtime model (none exists). + +Resolved since 654d822 (moved out): no CI and no committed lockfile (b435acb); the CLI's 100644 mode flip on install (b435acb); the npm dist-tag question (`latest` = `0.1.0-alpha.0` per `npm view`); `STATUS.md`'s stale "For UI" note about `MockRuntime.holdBudgetMs()/situationBudget()` and its redundant `--exclude "test/browser/**"` command (both gone from STATUS). -Open items in scope (from `OPEN_TASKS.md`, STATUS): +Open items in scope (from `OPEN_TASKS.md`, `HANDOFF.md`, `training/NEEDS.md`, STATUS): -- Packaging (item 8): publish `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, then `@genclass/runtime@0.1.0`; add a CI workflow (build, typecheck, unit tests). Until the model package exists, the default model URL has nothing to serve and the alpha only observes (README "Status"). -- Docs (item 7): dev-only lazy import of the devtools (52 KB min / 17 KB gz). -- The VM path (`scripts/vm.sh`) depends on a hosts file and SSH key from the original team's Mac. Without them the VM is unreachable: the light checks run locally under the run policy in AGENTS.md, and anything heavier (Playwright, smoke test, model runs) needs the user's go-ahead and a place to run it ([Where to run things](#where-to-run-things)). -- Any situation-wording change must be coordinated with SIM (STATUS "Open issues"). +- **`0.1.0-alpha.1`** (NaN fix, `nan.test.ts`): needs the user's 2FA (`OPEN_TASKS.md` "Needs the user"). Decide with the user whether it is cut from `origin/runtime` (default guard, situation-v2) or from `mvp-v2` (default observe), and which dist-tag it gets (npm 11 requires `--tag` for a prerelease); the version in `package.json` is not bumped yet. +- **Push and first CI run**: `mvp-v2` (with `.github/workflows/ci.yml`) is local only; pushing needs the user's OK. Until then CI has never run on GitHub (the `review-perf` retry and the `ONNXRUNTIME_NODE_INSTALL=skip` setting are verified only locally). +- **Model package**: blocked on v2 training (SIM v2 data on c02–c09 and c12–c23, REAL on c01, c10, c11, per `training/NEEDS.md`; then teacher, distillation, DAgger, EVAL). Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. +- Docs (item 13): dev-only lazy import of the devtools (52 KB min / 17 KB gz). +- The VM path (`scripts/vm.sh`) depends on Mehar's hosts file and SSH key. Without them the light checks run locally under the run policy in AGENTS.md; anything heavier needs the user's go-ahead. +- Any situation-wording change must be coordinated with SIM, REAL and TRAIN (frozen at `situation-v2`). +- Working copies may hold untracked `test/zz-*.test.ts` files from parallel review agents; vitest collects them. They are not part of `mvp-v2`. ## Related docs - Runtime docs (this set): [public-api-and-lifecycle.md](public-api-and-lifecycle.md), [observe-and-trace.md](observe-and-trace.md), [state-and-adapters.md](state-and-adapters.md), [learn-situation-triage.md](learn-situation-triage.md), [decide-policy-actions.md](decide-policy-actions.md), [model-host.md](model-host.md), [devtools.md](devtools.md) -- Cross-cutting: [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../training.md](../training.md), [../demos.md](../demos.md), [../genclass-model-lineage.md](../genclass-model-lineage.md), [../extension-and-benchmarks.md](../extension-and-benchmarks.md), [../status-and-known-issues.md](../status-and-known-issues.md), [../README.md](../README.md), [../overview.md](../overview.md), [../repo-map.md](../repo-map.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../../../AGENTS.md](../../../AGENTS.md) -- Existing sources: [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/API.md](../../runtime/API.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [packages/runtime/src/model/README.md](../../../packages/runtime/src/model/README.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md), [packages/runtime-model/MODEL_CARD.md](../../../packages/runtime-model/MODEL_CARD.md), [sim/README.md](../../../sim/README.md), [demos/README.md](../../../demos/README.md) +- Cross-cutting: [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../realapps.md](../realapps.md), [../training.md](../training.md), [../demos.md](../demos.md), [../genclass-model-lineage.md](../genclass-model-lineage.md), [../extension-and-benchmarks.md](../extension-and-benchmarks.md), [../status-and-known-issues.md](../status-and-known-issues.md), [../README.md](../README.md), [../overview.md](../overview.md), [../repo-map.md](../repo-map.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../../../AGENTS.md](../../../AGENTS.md) +- Existing sources: [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/API.md](../../runtime/API.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [packages/runtime/src/model/README.md](../../../packages/runtime/src/model/README.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md), [RELEASE.md](../../../RELEASE.md) (release procedure: Part A runtime, Part B model and 0.1.0), [HANDOFF.md](../../../HANDOFF.md), [docs/runtime/RESULTS.md](../../runtime/RESULTS.md), [training/NEEDS.md](../../../training/NEEDS.md), [.github/workflows/ci.yml](../../../.github/workflows/ci.yml), [packages/runtime-model/MODEL_CARD.md](../../../packages/runtime-model/MODEL_CARD.md), [sim/README.md](../../../sim/README.md), [demos/README.md](../../../demos/README.md) diff --git a/docs/agents/runtime/decide-policy-actions.md b/docs/agents/runtime/decide-policy-actions.md index 58fa9ab8..319c7305 100644 --- a/docs/agents/runtime/decide-policy-actions.md +++ b/docs/agents/runtime/decide-policy-actions.md @@ -1,76 +1,86 @@ -# @genclass/runtime: decision queue, policy gate, actions, reports, explain and undo +# @genclass/runtime: decision queue, policy gate, actions, delivery gate, reports, explain and undo > **Scope:** `packages/runtime/src/decide/decider.ts`, `packages/runtime/src/decide/exec.ts`, -> `packages/runtime/src/decide/policy.ts`, `packages/runtime/src/decide/report.ts`; the decision flow, action -> implementations, late revert, `explain`, undo and plugin action/question plumbing in -> `packages/runtime/src/runtime.ts`; `BUILTIN_ACTIONS` / `TRIGGER_ACTIONS` / `PASSIVE` / `DEFAULT_DIAGNOSES` in -> `packages/runtime/src/situation/questions.ts`; the request-side action controllers in -> `packages/runtime/src/observe/fetch.ts` and `packages/runtime/src/observe/xhr.ts` (followed only as far as the actions). -> **Read this when:** changing what happens after a trigger is built (queueing, deadlines, hold budget, fail-open), -> the policy gate or its defaults, any built-in action's mechanics or `changed` text, custom actions / standing -> questions, the console report wording, `Decision` / `ActionRecord` / `Explanation` shapes, `explain()` or undo. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> `packages/runtime/src/decide/policy.ts`, `packages/runtime/src/decide/report.ts`; the decision flow, the delivery +> gate, action implementations, late revert, `explain`, undo and plugin action/question plumbing in +> `packages/runtime/src/runtime.ts`; `BUILTIN_ACTIONS` / `TRIGGER_ACTIONS` / `PASSIVE` / `TRIGGER_DESCRIPTIONS` / +> `DEFAULT_DIAGNOSES` in `packages/runtime/src/situation/questions.ts`; the action and delivery controllers in +> `packages/runtime/src/observe/fetch.ts`, `packages/runtime/src/observe/xhr.ts` and +> `packages/runtime/src/observe/messages.ts` (followed only as far as the actions); the hub's drop filter in +> `packages/runtime/src/state/hub.ts`. +> **Read this when:** changing what happens after a trigger is built (queueing, deadlines, hold budget, expected +> latency, stale-item dropping, fail-open), the delivery gate, the policy gate or its defaults, any built-in action's +> mechanics or `changed` text, custom actions / standing questions, the console report wording, +> `Decision` / `ActionRecord` / `Explanation` shapes, `explain()` or undo. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR -- Every trigger goes through `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger(spec, ctl, opts)`: triage - first; if salient and the model is `ready`, the situation is submitted to a single-flight priority queue - (`DeciderQueue`), and the subject is **held** only if the trigger is holdable (`opts.hold`) **and** at least one - non-passive action is permitted by mode + policy. Otherwise the passive action runs at once and the decision is - still made in the background (detection only). +- **Default mode is `observe`** (`packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`, + commit f3636b2): it permits no non-passive action, so nothing is ever held, delayed or changed; decisions still + run in the background and detections are still reported. `guard` is opt-in; `heal` is experimental. +- **situation-v2 decides at the network boundary** (commit fcd1e68, frozen at tag `situation-v2` = 6e5e86e). A new + trigger `delivery` fires when a fetch/XHR response or a WebSocket/EventSource message is about to reach the app and + the fields its operation is predicted to write hold newer data that the body would change (any newer-data conflict + when the body cannot be read in 100 ms), or a pending local change / typed text the body would overwrite. Actions: `deliver` (passive), `discard` (guard: deliver, but drop that chain's writes over newer + data for 10 s), `defer` (guard: wait for related in-flight ops, decide again, ≤ 2). Holding a delivery is only + latency; channel order is kept. +- **Store writes are not held by default** (`policy.holdWrites: false`). A salient write that no delivery decision + covers raises a non-holdable `mutation` trigger (`runtime.ts` -> `observeWrite`); the write applies at once and a + gate-passing `discard` becomes a **late revert** (≤ 2 s after it applied, nothing overwrote it). `holdWrites: true` + restores held writes (`gateMutation`), which never reorder a store's writes. +- Every trigger goes through `runtime.ts` -> `RuntimeImpl.trigger(spec, ctl, opts)`: triage, then build, then the + single-flight priority queue (`DeciderQueue`). The subject is **held** only if the trigger is holdable + (`opts.hold`), at least one non-passive action is permitted by mode + policy, the runtime is not paused, **and** + the expected model latency fits the hold budget (`expectedLatency() <= holdBudgetMs()`). Otherwise the passive + action runs at once and the decision is still made in the background. - **Fail-open everywhere:** no provider, provider not `ready`, provider error (any `code`), queue overflow, expired - deadline, runtime-side timeout, hold budget expiry, a throwing action -> the passive action runs. A missing model - never blocks the app and never produces a `Decision`. + deadline, superseded subject (`Controller.stale`), runtime-side timeout, hold budget expiry, a throwing action -> + the passive action runs. A missing model never blocks the app and never produces a `Decision`. - **Hold budget** (`policy.holdBudgetMs`, default `"auto"`): clamp(round(1.5 × median of the last 20 provider latencies, or the model's `warmupMs` before any), 150, 800) ms; 300 ms when nothing is known (`packages/runtime/src/decide/policy.ts` -> `holdBudget`). -- **Policy gate** (`policy.ts` -> `gate`, CONTRACT §8): A = applicable non-passive actions permitted by the mode - (observe: none; guard: guard tier; heal: guard + heal) minus `deny` (only `allow` if set). Candidate = argmax of - probability over A. It runs only if: not paused; Σ p(A) ≥ the candidate's tier threshold (guard 0.9, heal 0.8); - the model's top diagnosis ≠ `expected` (unless `requireDiagnosis: false`); fewer than `maxActionsPerMinute` (60) - actions in the last 60 s; and, for holdable triggers (mutation, request, fetch failure), the decision arrived while - the subject was still held (else late-revert rules); non-holdable triggers (stall, inconsistency, transition, error, - XHR failure) skip this check. -- **Built-in actions** are generic capabilities defined in `situation/questions.ts` -> `BUILTIN_ACTIONS` (name, tier, - model-facing description) and implemented by per-subject `Controller`s (`decide/exec.ts`): mutation controller in - `runtime.ts` -> `gateMutation`; request/failure/stall controllers in `observe/fetch.ts` and `observe/xhr.ts`; - inconsistency/transition/error controllers in `runtime.ts` (`rollback`, `revertChain`, `resync`). -- Guard tier = withhold/deduplicate/slow down (`discard`, `defer`, `coalesce`, `delay`); heal tier = change what the - app receives or restore state (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions by - default). Passive per trigger (`PASSIVE`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, - inconsistency / transition / error `ignore`. -- **Custom actions** (`rt.action(def)`, `plugin.actions`) are offered next to the built-ins, gated at their own - tier (default `heal`), run inside a GenClass op, may call `ctx.builtin(name)` (re-checked against mode/policy/rate, - not thresholds), and are followed by the passive action unless a built-in took over. **Standing questions** - (`rt.question`, `plugin.questions`) add questions to the request; `onAnswer` gets the answer before any action. -- **Late revert:** a held write that applied because its budget expired can still be reverted by a gate-passing - `discard` that arrives within 2 s (`LATE_REVERT_MS`) of it applying, if nothing superseded it. -- Every model answer to a trigger produces a `Decision` (`d<n>`; `ask`/`decide` do not); every non-passive action attempt produces an `ActionRecord` - (`a<n>`, also when it failed). Both rings keep 200. `explain(id)` accepts either id. -- Reports (`decide/report.ts`): one line per detection (`[GenClass] Flagged …`) and per intervention - (`[GenClass] Prevented …`, `Reverted …`), console output deduplicated per 60 s window with a "×N more" summary. -- `ActionRecord.undo` exists only for reversible effects (discard, late revert, rollback, custom `onUndo`); it is - idempotent, runs inside a GenClass op named `undo` and is never gated (a discard's re-applied write is still - attributed to its original cause, see Drift 12). +- **Policy gate** (`policy.ts` -> `gate`, unchanged since situation-v1): A = applicable non-passive actions + permitted by the mode (observe: none; guard: guard tier; heal: guard + heal) minus `deny` (only `allow` if set). + Candidate = argmax of probability over A. It runs only if: not paused; Σ p(A) ≥ the candidate's tier threshold + (guard 0.9, heal 0.8); the model's top diagnosis ≠ `expected` (unless `requireDiagnosis: false`); fewer than + `maxActionsPerMinute` (60) actions in the last 60 s; and the subject has not already proceeded + (`Controller.proceeded`), except for a late-revert `discard` and for custom actions. +- **Built-in actions** are generic capabilities defined in `situation/questions.ts` -> `BUILTIN_ACTIONS` and + implemented by per-subject `Controller`s (`decide/exec.ts`): mutation (`runtime.ts` -> `mutationController`), + delivery (`runtime.ts` -> `runDelivery`), request/failure/stall (`observe/fetch.ts`, `observe/xhr.ts`), + inconsistency/transition/error (`runtime.ts` -> `rollback`, `revertChain`, `resync`). Guard tier: `discard`, + `defer`, `coalesce`, `delay`; heal tier: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom + actions by default. +- **Custom actions** (`rt.action(def)`, `plugin.actions`) are gated at their own tier (default `heal`), run inside a + GenClass op, may call `ctx.builtin(name)` (re-checked against mode/policy/rate and `proceeded`, not thresholds). + **Standing questions** (`rt.question`, `plugin.questions`) add questions; `onAnswer` gets the answer first. +- Every model answer to a trigger produces a `Decision` (`d<n>`); every non-passive action attempt produces an + `ActionRecord` (`a<n>`, also when it failed). Both rings keep 200. `explain(id)` accepts either id. Reports are + one line per detection (`Flagged …`) and per intervention (`Prevented …`, `Reverted …`), deduplicated per 60 s. ## Files | Path | Role | Key exports / entry points | |---|---|---| -| `packages/runtime/src/decide/decider.ts` | Single-flight priority queue in front of the `DecisionProvider`: deadlines, runtime-side timeout, answer cache, latency samples, fail-open | `DeciderQueue` (`submit`, `latencies`, `clear`, `dispose`, `length`), `DecideResult`, `PROVIDER_TIMEOUT_MS` | -| `packages/runtime/src/decide/exec.ts` | Types only: the seam between the decision flow and the subject of a trigger | `ActionEffect`, `Controller`, `TriggerOpts`, `EndOpts`, `NetHost` | +| `packages/runtime/src/decide/decider.ts` | Single-flight priority queue in front of the `DecisionProvider`: deadlines, superseded-item dropping, runtime-side timeout, answer cache, latency samples, stuck flag, fail-open | `DeciderQueue` (`submit`, `latencies`, `clear`, `dispose`, `length`, `waiting`, `computing`, `computingSince`, `stuck`), `DecideResult`, `PROVIDER_TIMEOUT_MS` | +| `packages/runtime/src/decide/exec.ts` | Types only: the seam between the decision flow and the subject of a trigger | `ActionEffect`, `Controller`, `TriggerOpts`, `EndOpts`, `NetHost` (incl. `deliver`, `noteResponse`) | | `packages/runtime/src/decide/policy.ts` | Policy config, mode/tier permission, the §8 gate, rate limiter, hold budget | `policyConfig`, `PolicyConfig`, `modeAllows`, `restriction`, `permittedActions`, `gate`, `GateInput`, `GateOutcome`, `RateLimiter`, `holdBudget`, `HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS` | | `packages/runtime/src/decide/report.ts` | Report sentences and console sink with dedupe | `interventionLine`, `detectionLine`, `decisionLine`, `Reporter` | -| `packages/runtime/src/runtime.ts` | Wiring: `trigger`, `onDecision`, `runCustom`, mutation controller (`gateMutation`, `waitRelated`), inconsistency/transition/error controllers (`raiseInconsistency`, `raiseTransition`, `reportError`), `watchStall`, `rollback`, `revertChain`, `resync`, `runAsGenClass`, `explain`, `decisions`, `interventions`, `holdBudgetMs`, `action`, `question`, `use`, `setMode`, `pause`, `resume`, `destroy`, `setReport`, `isPaused` | `RuntimeImpl` (exported publicly from `src/index.ts`, so its public members are reachable by apps) | -| `packages/runtime/src/situation/questions.ts` | Action catalogue and diagnosis vocabulary (model-facing wording, frozen at tag `situation-v1`) | `BuiltinAction`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | -| `packages/runtime/src/situation/build.ts` | Which actions are offered for a subject (applicability); custom action options | `buildSituation`, `ActionOption`, `BuiltSituation` (internal `builtinApplicable`, `revertableChain`) | -| `packages/runtime/src/observe/fetch.ts` | fetch controllers: request gate (`send`/`coalesce`/`delay`/`block`/`serve_cached`), failure gate (`deliver`/`retry`/`serve_cached`), stall (`wait`/`hedge`/`serve_cached`) | `installFetch` (internal `runRequest`, `failureGate`, `stallController`, `reqCtl`) | -| `packages/runtime/src/observe/xhr.ts` | XHR request gate (`send`/`delay`/`block`/`serve_cached`); XHR failures/stalls are passive-only | `installXHR` (internal `fake`, `passiveOnly`) | +| `packages/runtime/src/runtime.ts` | Wiring: `trigger`, `onDecision`, `runCustom`, `mutationController`, `gateMutation` (holdWrites), `observeWrite` (default), `covered`, `expectedLatency`, `runDelivery` (delivery gate), `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `noteResponse`, `onChannel`, `markWrites`, `waitRelated`, `raiseInconsistency`, `raiseTransition`, `reportError`, `watchStall`, `rollback`, `revertChain`, `resync`, `runAsGenClass`, `explain`, `decisions`, `interventions`, `holdBudgetMs`, `action`, `question`, `use`, `setMode`, `pause`, `resume`, `destroy`, `setReport`, `isPaused` | `RuntimeImpl` (exported publicly from `src/index.ts`; `runDelivery` is a public member) | +| `packages/runtime/src/situation/questions.ts` | Action catalogue and diagnosis vocabulary (model-facing wording, frozen at tag `situation-v2`) | `BuiltinAction`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | +| `packages/runtime/src/situation/build.ts` | Which actions are offered for a subject (applicability); delivery subject text and `SubjectRef` | `buildSituation`, `subjectOf`, `relatedInFlight`, `subjectRef`, `ActionOption`, `BuiltSituation` (internal `builtinApplicable`, `revertableChain`) | +| `packages/runtime/src/situation/conflicts.ts` | Delivery prediction and conflicts (salience inputs; see [learn-situation-triage.md](learn-situation-triage.md)) | `predictedWrites`, `matchFields`, `conflictsOn` | +| `packages/runtime/src/situation/content.ts` | Response-body analysis at delivery (does the body change / put back a value) | `analyzeBody`, `createdIds`, `vhash`, `parseJsonBody` | +| `packages/runtime/src/observe/fetch.ts` | fetch controllers: request gate (`send`/`coalesce`/`delay`/`block`/`serve_cached`), failure gate (`deliver`/`retry`/`serve_cached`), stall (`wait`/`hedge`/`serve_cached`); calls `host.deliver` for successful responses | `installFetch` (internal `runRequest`, `failureGate`, `stallController`, `reqCtl`, `jsonOfBuffered`) | +| `packages/runtime/src/observe/xhr.ts` | XHR request gate (`send`/`delay`/`block`/`serve_cached`); delivery gate for successful async responses (wraps the app's completion listeners); failures/stalls passive-only | `installXHR` (internal `arrive`, `gateCall`, `wrapHandlers`, `fake`, `passiveOnly`) | +| `packages/runtime/src/observe/messages.ts` | Delivery gate for push channels: per-channel ordered queue, re-dispatch of released messages | `MessageGate`, `MsgHost`, `messageSummary` | +| `packages/runtime/src/observe/websocket.ts`, `packages/runtime/src/observe/eventsource.ts` | Install a `MessageGate` per socket / event source; report channel down/up | `installWebSocket`, `installEventSource` | | `packages/runtime/src/observe/cache.ts` | Response buffers used by `coalesce` / `serve_cached` | `ResponseCache`, `makeResponse`, `blockedResponse`, `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS` | -| `packages/runtime/src/state/hub.ts` | Applies a mutation verdict (`apply`/`discard`/`defer`), late-revert checks and patches | `StoreHub.revertable`, `.revert`, `.reapply`, `.restoreFields`, `.commit`, `Verdict` | -| `packages/runtime/src/types.ts` | Public shapes | `Decision`, `Detection`, `ActionRecord`, `Report`, `Explanation`, `PolicyOptions`, `ActionDef`, `ActionContext`, `StandingQuestion`, `Plugin`, `EvaluateRequest`, `DecisionProvider`, `RuntimeEvents` | +| `packages/runtime/src/state/hub.ts` | Applies a mutation verdict (`apply`/`discard`/`defer`) when `holdWrites`; calls `observeWrite` otherwise; applies the delivery drop filter; late-revert checks and patches | `StoreHub.holdWrites`, `.revertable`, `.revert`, `.reapply`, `.restoreFields`, `.commit`, `.flushQueue`, `.pendingView`, `Verdict` (internal `applyFilter`) | +| `packages/runtime/src/types.ts` | Public shapes | `Decision`, `Detection`, `ActionRecord` (incl. `dropped`), `Report`, `Explanation`, `PolicyOptions` (incl. `holdWrites`), `ActionDef`, `ActionContext`, `StandingQuestion`, `Plugin`, `EvaluateRequest`, `DecisionProvider`, `RuntimeEvents`, `SubjectRef`, `SituationDraft` (incl. `delivery`) | | `packages/runtime/src/index.ts` | Re-exports `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` and `RuntimeImpl` publicly (not `decide/*`: `DeciderQueue`, `gate`, `policyConfig`, `PROVIDER_TIMEOUT_MS` etc. are internal) | — | -| `packages/runtime/test/helpers.ts` | Test doubles for this scope | `setup`, `ScriptedDecider`, `defaultScript`, `ManualDecider`, `choice`, `FakeClock`, `FakeServer`, `drain` | +| `packages/runtime/test/helpers.ts` | Test doubles for this scope; `setup()` defaults to `mode: "guard"` (the product default is observe) | `setup`, `ScriptedDecider`, `defaultScript`, `ManualDecider`, `choice`, `FakeClock`, `FakeServer`, `drain` | ## Concepts and data structures @@ -78,56 +88,98 @@ - **controller**: an object implementing `Controller` for one trigger subject; `passive()` lets it proceed unchanged, `run(action)` performs a built-in action and returns an `ActionEffect` (or throws/rejects when it cannot). -- **waits**: in `RuntimeImpl.trigger`, `opts.hold && permittedActions(...).length > 0 && !paused` — whether this - subject is actually held. A holdable trigger with no permitted action is not held. +- **waits**: in `RuntimeImpl.trigger`, `opts.hold && permittedActions(...).length > 0 && !paused && + expectedLatency() <= holdBudgetMs()` — whether this subject is actually held. +- **expected latency** (`runtime.ts` -> `expectedLatency`): `base × (1 + queue.waiting) + current`, where `base` is + the lower median of the queue's latency samples (else `status.warmupMs`, else 0) and `current` is + `max(base, now - computingSince)` while an evaluation is computing (else 0). `Infinity` while `queue.stuck`. +- **stuck** (`DeciderQueue.stuck`): the provider's last evaluation was abandoned by the runtime-side timeout and none + has answered since. While stuck nothing is held. +- **proceeded** (`Controller.proceeded`): the subject already went its way (write applied, request sent, failure or + response delivered). An action decided after that is late. Controllers without it fall back to + `hold && (expired || passiveRan)`. +- **stale** (`Controller.stale`): a queued decision about this subject is no longer worth computing; the queue drops + it before dispatch (resolves `null`). - **expired**: the hold-budget timer fired before the decision; the passive action already ran. - **candidate / mass**: the gate's argmax permitted action and Σ p over the permitted set (`GateOutcome`). - **detection**: a `Decision` whose diagnosis ≠ `expected` and whose diagnosis probability ≥ `thresholds.report`. - **intervention**: a non-passive action that ran (an `ActionRecord`). +- **delivery gate**: `runtime.ts` -> `runDelivery(o, release, defers)`: decides whether a response/message reaches the + app now (`release()`), after the model, or after related ops (defer). Sets `op.delivery = { patterns, known, + salient, decided, overNewer? }` on the subject op (`trace/ops.ts` -> `OpRec.delivery`). +- **covered write**: `runtime.ts` -> `covered(m)`: the write's causal chain (≤ 16 ancestors) passed a delivery gate + whose prediction was known and includes every changed path, and that delivery was not salient or was decided + before it proceeded. Covered writes raise no `mutation` trigger (never with `triage: "always"`). +- **discard mark / drop filter**: a delivery `discard` sets `op.discardMark = { protect, until, dropped, onDrop? }`; + for `DISCARD_MARK_MS` (10 s) `StoreHub.propose` asks `runtime.ts` -> `dropFilter(m)` which changes of each write in + that op's chain to drop (`hub.ts` -> `applyFilter`). - **GenClass op**: an instant op of kind `"genclass"` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause - `null`); writes and requests made inside it are never gated (`StoreHub.propose` bypasses `genclass` causes, - `NetHost.gated` is false for `op.genclass`) and are excluded from baselines and profiles. -- **sync verdict** (mutations only): the verdict `gateMutation` observed while `trigger` was still on the stack; + `null`); writes and requests made inside it are never gated, filtered or observed and are excluded from baselines + and profiles. +- **sync verdict** (held mutations only): the verdict `gateMutation` observed while `trigger` was still on the stack; `"apply"` there means the write is not held at all (see flow 1). `decide/decider.ts` consumes `types.ts` -> `EvaluateRequest { trigger; state: JevState; questions; priority?; subject?: SubjectRef; timeoutMs? }` (the runtime sets the first five; the queue adds `timeoutMs`). `situation/questions.ts` -> `BuiltinAction { name: string; tier: Tier; description: string }`; `Tier = "passive" | -"guard" | "heal"`, `Mode = "observe" | "guard" | "heal"` (`types.ts`). +"guard" | "heal"`, `Mode = "observe" | "guard" | "heal"`, `TriggerKind` = `mutation | request | delivery | failure | +stall | inconsistency | transition | error | ask` (`types.ts`). -Action helpers on `RuntimeImpl` (public members, used by the controllers; no other caller in the repo): +Action helpers on `RuntimeImpl` (public members, used by the controllers): ```ts runAsGenClass<T>(name: string, fn: () => T): T // run fn inside a GenClass op rollback(stores: string[], violationIds: string[] = [], beforeSeq?: number): ActionEffect // snapshot rollback revertChain(op: OpRec, why: string): ActionEffect // chain revert (transition/error) resync(stores: string[]): Promise<ActionEffect> // call StoreOptions.resync handlers +runDelivery(o: { op; channel: "response" | "websocket" | "eventsource"; req?; status?; message?; queuedAhead?; + body?: () => Promise<unknown> }, release: () => void, defers = 0): void // the delivery gate ``` `decide/exec.ts`: ```ts -interface ActionEffect { changed: string; undo?: () => void } // one sentence: exactly what GenClass altered +interface ActionEffect { + changed: string; // one sentence: exactly what GenClass altered + undo?: () => void; + onRecord?: (r: ActionRecord) => void; // gets the record once it exists (delivery discard) +} interface Controller { passive(): void; // must be idempotent in practice run(action: string): ActionEffect | Promise<ActionEffect>; // throw/reject => passive runs, record ok:false - revertable?(): string | null; // late revert (held writes only): null = can revert + revertable?(): string | null; // late revert (mutations): null = can revert revert?(): ActionEffect; + proceeded?(): boolean; // the subject already went its way + stale?(): boolean; // drop a queued decision about it } interface TriggerOpts { hold: boolean; priority: number } +// NetHost additions (fetch/XHR -> runtime): +deliver(o: { op; req; status; body?: () => Promise<unknown> }, release: () => void): void; // the delivery gate +noteResponse?(o: { op; req; status; body }): void; // created ids (read-your-writes facts) ``` +Which controllers implement `proceeded` / `stale`: + +| Controller | `proceeded()` | `stale()` | +|---|---|---| +| mutation (`runtime.ts` -> `mutationController`) | `m.state === "done"` | the write was discarded, or a field it applied was written again since | +| delivery (`runDelivery`) | released | released | +| fetch request gate (`reqCtl`) | `sent \|\| answered` | `!sent && signal.aborted` | +| fetch failure gate | `handled \|\| answered` | — | +| XHR request gate | `decided \|\| abortedWhileHeld` | `abortedWhileHeld` | +| fetch stall, XHR `passiveOnly`, inconsistency/transition/error | — (non-holdable: fallback false) | — | + `decide/decider.ts`: `DecideResult { answers; latencyMs /* provider time, 0 for cache hits */; waitMs; cached }`. -Internal `QueueItem { req; deadline?: number /* absolute clock ms */; resolve; seq; t0 }`. `submit()` resolves -`null` for every fail-open path, never rejects. +Internal `QueueItem { req; deadline?: number /* absolute clock ms */; stale?: () => boolean; resolve; seq; t0 }`. +`submit(req, deadline?, stale?)` resolves `null` for every fail-open path, never rejects. `decide/policy.ts`: ```ts interface PolicyConfig { thresholds: { report: number; guard: number; heal: number }; allow?: Set<string>; - deny: Set<string>; holdBudgetMs: number | "auto"; holdUserWrites: boolean; maxActionsPerMinute: number; - requireDiagnosis: boolean } + deny: Set<string>; holdBudgetMs: number | "auto"; holdUserWrites: boolean; holdWrites: boolean; + maxActionsPerMinute: number; requireDiagnosis: boolean } interface GateInput { actions: { name: string; tier: Tier }[] /* all offered, passive included */; probabilities: Record<string, number>; top: string /* model argmax over offered */; diagnosis: string; mode: Mode; paused: boolean; now: number } @@ -150,6 +202,7 @@ interface Decision { // id "d<n>"; Detection = Decision } interface ActionRecord { // id "a<n>" id; decisionId; action; tier; trigger; subject; at; ok; error?; changed; undo?: () => void; late?: boolean; + dropped?: string[]; // delivery discard: paths dropped so far (grows while the 10 s mark lasts) } interface Report { kind: "detect" | "intervene" | "status"; message: string; decision?: Decision; action?: ActionRecord } interface Explanation { message; decision; situationText; facts; timeline; answers; action?; changed? } @@ -160,12 +213,15 @@ interface ActionContext { trigger; decision; situation /* SituationDraft */; run builtin(name: string): Promise<boolean>; describe(changed: string): void; onUndo(fn: () => void): void } interface StandingQuestion { id; on: TriggerKind[]; question: Question; always?: boolean; onAnswer?(a: Answer, ctx: { decision; situation; runtime }): void } +// SubjectRef for delivery: { kind: "delivery", op, paths?, store? } (paths = conflicting fields, else matched predicted) +// SituationDraft.delivery?: { channel: "response" | "websocket" | "eventsource"; predicted: string[]; conflicts: string[] } ``` Internal `runtime.ts` -> `ExplainRec { decision; situationText /* stateText(situation.state) */; facts; timeline; answers; action? }`, stored in `explainMap` under both the decision id and (once it exists) the action id. -`state/hub.ts` -> `Verdict = "apply" | "discard" | "defer"` (what a held mutation's promise resolves to). +`state/hub.ts` -> `Verdict = "apply" | "discard" | "defer"` (what a held mutation's promise resolves to; held +mutations exist only with `holdWrites`). ### Action catalogue (`situation/questions.ts`) @@ -175,6 +231,7 @@ stored in `explainMap` under both the decision id and (once it exists) the actio |---|---|---| | `mutation` | `apply`, `discard`, `defer` | `apply` | | `request` | `send`, `coalesce`, `delay`, `block`, `serve_cached` | `send` | +| `delivery` | `deliver`, `discard`, `defer` | `deliver` | | `failure` | `deliver`, `retry`, `serve_cached` | `deliver` | | `stall` | `wait`, `hedge`, `serve_cached` | `wait` | | `inconsistency` | `ignore`, `rollback`, `resync` | `ignore` | @@ -183,9 +240,16 @@ stored in `explainMap` under both the decision id and (once it exists) the actio | `ask` | (none) | `""` | `ACTION_INSTRUCTIONS` (the `action` question's instructions): mutation "What should the runtime do with this write?", -request "… with this request?", failure "… with this failed request?", stall "… with this slow request?", -inconsistency "What should the runtime do about this inconsistent state?", transition "… about this unusual state -change?", error "… about this error?". `DIAGNOSIS_INSTRUCTIONS` = "What is happening here?". +request "… with this request?", delivery "What should the runtime do with this response or message?", failure "… +with this failed request?", stall "… with this slow request?", inconsistency "What should the runtime do about this +inconsistent state?", transition "… about this unusual state change?", error "… about this error?". +`DIAGNOSIS_INSTRUCTIONS` = "What is happening here?". + +`TRIGGER_DESCRIPTIONS` (new in v2) overrides built-in descriptions for one trigger; only `delivery` has entries: +`deliver` "pass it to the application now", `discard` "deliver it but drop the state changes it would make over +newer data", `defer` "hold it until the related in-flight operations finish, then decide again". +`actionDescription(name, vocab, custom?, trigger?)` resolves `vocab.actions[name]` → `custom` → +`TRIGGER_DESCRIPTIONS[trigger][name]` → `BUILTIN_ACTIONS[name].description` → `name`. `DEFAULT_DIAGNOSES` (order matters; `expected` is always first via `diagnosisVocabulary`): `expected`, `stale`, `conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, `overload`, `unusual`, `transient`. Descriptions are the @@ -203,8 +267,10 @@ Call sites and their `TriggerOpts`: | Raised by | trigger | hold | priority | |---|---|---|---| -| `runtime.ts` -> `gateMutation` (hub `gate` hook) | `mutation` | true | 2 | -| `observe/fetch.ts` -> `runRequest` request gate | `request` | true (`keepalive` requests raise no trigger at all: `gateRequest` is false and they are sent at once) | 2 | +| `runtime.ts` -> `observeWrite` (hub hook, default: `holdWrites` false) | `mutation` | false | 1 | +| `runtime.ts` -> `gateMutation` (hub `gate` hook, only with `holdWrites: true`) | `mutation` | true | 2 | +| `runtime.ts` -> `runDelivery` (from fetch, XHR, WebSocket, EventSource) | `delivery` | true | 2 | +| `observe/fetch.ts` -> `runRequest` request gate | `request` | true (`keepalive` requests raise no trigger: sent at once) | 2 | | `observe/fetch.ts` -> `failureGate` | `failure` | true | 2 | | `observe/xhr.ts` -> `wSend` (async XHR only) | `request` | true | 2 | | `observe/xhr.ts` -> `onEnd` | `failure` | false (passive-only controller) | 1 | @@ -213,11 +279,14 @@ Call sites and their `TriggerOpts`: | `runtime.ts` -> `raiseTransition` | `transition` | false | 0 | | `runtime.ts` -> `reportError` | `error` | false | 0 | -Network triggers are raised only when `NetHost.gated(op)` (not paused, not destroyed, not a GenClass op). -`watchStall` (registered by fetch with the stall controller and by async XHR with `passiveOnly`) fires once per op at -`max(4 × median, 2 × p95, STALL_MIN_MS 500)` ms, and only when the signature has a latency baseline -(`Baselines.latency`, ≥ 5 samples). Settled-point triggers (`inconsistency`, `transition`) are covered in -[state-and-adapters.md](state-and-adapters.md) and [learn-situation-triage.md](learn-situation-triage.md). +`observeWrite` and `gateMutation` both return early (no trigger) when `consultable()` is false or the write is +`covered(m)`; `observeWrite` also skips GenClass writes. The hub calls neither for writes that bypass gating (user-sync +writes without `holdUserWrites`, GenClass writes, stores with `hold: false`, `!gating`), that change nothing, that the +delivery drop filter dropped entirely, or (with `holdWrites`) that are unholdable because the updater mutated the +stored value in place (`hub.ts` -> `propose`). Network triggers are raised only when `NetHost.gated(op)` (not paused, not destroyed, not a +GenClass op). `watchStall` fires once per op at `max(4 × median, 2 × p95, STALL_MIN_MS 500)` ms, only with a latency +baseline (≥ 5 samples). Settled-point triggers are covered in [state-and-adapters.md](state-and-adapters.md) and +[learn-situation-triage.md](learn-situation-triage.md). Steps: @@ -228,23 +297,30 @@ Steps: 3. `buildSituation(...)` (a throw -> passive). Stored in `lastBuilt[trigger]` (what `rt.situation(trigger)` returns). 4. If `!built.salient && !built.forced` -> passive. 5. If the provider is not `"ready"` (i.e. `"off"`): read `this.ready` (starts the lazy load) and run passive. -6. `permitted = permittedActions(policy, mode, built.actions)`; `waits = opts.hold && permitted.length > 0 && !paused`. - If `!waits`, run passive **now** (the subject proceeds) and keep deciding in the background. +6. `permitted = permittedActions(policy, mode, built.actions)`; `waits = opts.hold && permitted.length > 0 && !paused + && expectedLatency() <= holdBudgetMs()`. If `!waits`, run passive **now** and keep deciding in the background. 7. `budget = holdBudgetMs()`. If `waits`, start a budget timer: on fire set `expired = true` and run passive. -8. Deadline: `waits` -> `t0 + budget + (ctl.revert ? LATE_REVERT_MS : 0)` (only mutation controllers have - `revert`); not waiting -> `t0 + BACKGROUND_DEADLINE_MS` (5,000). -9. `queue.submit({ trigger, state, questions, priority: waits ? opts.priority : min(opts.priority, 1), subject }, deadline)`. +8. Deadline: `waits` -> `t0 + budget + (ctl.revert ? LATE_REVERT_MS : 0)` (only a held mutation has `revert` and + waits); not waiting -> `t0 + BACKGROUND_DEADLINE_MS` (5,000), which includes default-mode background mutations. +9. `queue.submit({ trigger, state, questions, priority: waits ? opts.priority : min(opts.priority, 1), subject }, + deadline, ctl.stale)`. 10. On result: clear the budget timer; destroyed or `null` -> passive; else `onDecision(...)`. Any throw -> passive. The `passive` closure in `trigger` is guarded by `passiveRan`, so the controller's `passive()` runs at most once through that path. `t0` is read after the situation is built, so `Decision.latencyMs` excludes build time. -Mutation specifics (`gateMutation`): it returns `{}` (no hold) when `consultable()` is false. Otherwise it calls -`trigger` synchronously; if the controller's `passive()` ran during that call (steps 1–6: triage-neutral, not -salient, provider `"off"`, nothing permitted), the sync verdict is `"apply"` and it returns `{}`, so the hub applies -the write in the caller's stack with no microtask delay. Only otherwise does it return `{ held: Promise<Verdict> }`. -The hub's separate `mayHold` hook (`consultable() && mode !== "observe"`) only decides whether a hold-safe preview is -prepared ([state-and-adapters.md](state-and-adapters.md)). +Held-mutation specifics (`gateMutation`, `holdWrites` only): it calls `trigger` synchronously; if the controller's +`passive()` ran during that call (steps 1–6), the sync verdict is `"apply"` and it returns `{}`, so the hub applies +the write in the caller's stack. Otherwise it returns `{ held: Promise<Verdict> }`. The hub's `mayHold` hook +(`hub.holdWrites && consultable() && mode !== "observe"`) only decides whether a hold-safe preview is prepared. A later +write to the same store that applies at once (bypass, no change, unholdable) first flushes that store's held writes in +order (`StoreHub.flushQueue`); a later gated write queues behind them (`drain` applies in proposal order); and inside the +writing chain `get()` returns the pending value (`StoreHub.pendingView`) ([state-and-adapters.md](state-and-adapters.md)). + +Default-mode mutations (`observeWrite`): the hub calls it right before `commit`, so the situation is built as of the +proposal, then the write applies. The controller is `mutationController(m, null)`: `passive()` is a no-op and `run` +throws `the write was not held`; by the time the answer arrives `proceeded()` is true, so only the late-revert path +(flow 5) can act. ### 2. Queue (`decide/decider.ts` -> `DeciderQueue`) @@ -252,26 +328,27 @@ prepared ([state-and-adapters.md](state-and-adapters.md)). `null` (fail-open). 2. `pump` (while not busy): take the highest priority, oldest (`seq`) item. - `now >= deadline` -> `null` (never computed). + - `item.stale()` true (a throw counts as false) -> `null` (never computed). Asserted in `test/delivery.test.ts` + ("drops a queued background decision whose write was superseded"). - provider missing or not `"ready"` -> `null`. - cache key `fnv1a(trigger + "\0" + stableStringify(state) + "\0" + stableStringify(questions))` (`util.ts`; `subject` and `priority` are not part of it); a hit with `now - t <= CACHE_TTL` (30,000 ms) resolves with - `cached: true`, `latencyMs: 0` (no latency sample, no provider call). Hits are only served while the provider is - `"ready"` (checked first). + `cached: true`, `latencyMs: 0` (no latency sample, no provider call). - else `dispatch`. -3. `dispatch`: `busy = true`; runtime-side timer `limit = deadline ? max(1, deadline - t1) : PROVIDER_TIMEOUT_MS` - (10,000). The provider receives `timeoutMs = max(1, deadline - t1)` when a deadline exists. -4. Provider resolves an object -> cache it (insertion-order eviction beyond `CACHE_MAX` 64), push `t2 - t1` to the - latency ring (last `LATENCY_SAMPLES` 20), resolve. Sync throw, rejection, or timer fire -> `onError` + `null`; - a non-object answer -> `null` without `onError`. The timer passes `onError` an `Error("the decision provider did - not answer in time")` with `code: "timeout"`. `done` is idempotent; it clears `busy` and pumps the next item - (so after a runtime timeout the next request is dispatched while the abandoned call may still be running). +3. `dispatch`: `busy = true`, `since = t1`; runtime-side timer `limit = deadline ? max(1, deadline - t1) : + PROVIDER_TIMEOUT_MS` (10,000). The provider receives `timeoutMs = max(1, deadline - t1)` when a deadline exists. +4. Provider resolves an object -> `overdue = false`, cache it (insertion-order eviction beyond `CACHE_MAX` 64), push + `t2 - t1` to the latency ring (last `LATENCY_SAMPLES` 20), resolve. Sync throw, rejection, or timer fire -> + `onError` + `null`; a non-object answer -> `null` without `onError`. The timer sets `overdue = true` and passes + `onError` an `Error("the decision provider did not answer in time")` with `code: "timeout"`. `done` is + idempotent; it clears `busy` and pumps the next item. 5. `onError` in `runtime.ts`: `code === "max_tokens_exceeded"` shrinks automatic situation budgets - (`budgetScale = max(0.5, budgetScale × 0.8)`, never restored; only affects `situation.budget: "auto"`); every - error is logged (`console.debug`) only with `debug: true`. Model-host error codes (`model/errors.ts` -> - `ModelErrorCode`): `not_ready`, `max_tokens_exceeded`, `bad_request`, `unsupported`, `timeout`, `aborted`, `busy`, - `disposed`, `load_failed`, `integrity`, `inference_failed`; all fail open the same way. -6. `clear()` resolves every queued item `null`; `dispose()` (from `RuntimeImpl.destroy`) sets `disposed` (no more - pumping) and clears. + (`budgetScale = max(0.5, budgetScale × 0.8)`, never restored); every error is logged (`console.debug`) only with + `debug: true`. Model-host error codes (`model/errors.ts` -> `ModelErrorCode`) all fail open the same way. +6. `clear()` resolves every queued item `null`; `dispose()` (from `RuntimeImpl.destroy`) sets `disposed` and clears. + +Read-only getters used by `expectedLatency`: `waiting` (= `length`, queued items excluding the one computing), +`computing` (busy), `computingSince`, `stuck` (= `overdue`). `rt.ask()` / `rt.decide()` also use this queue: priority 1, deadline `now + timeoutMs` when given (else the 10 s runtime timeout). They bypass triage, the gate and `Decision` records (see @@ -290,23 +367,23 @@ runtime timeout). They bypass triage, the gate and `Decision` records (see 5. `rate.full(now)` -> `"rate limit: <N> actions in the last minute"`. 6. Else `run = candidate`. Reasons 1–3 are reported only when the model's own top choice was non-passive; 4–5 are always set. -3. Hold checks when `run` is set: held trigger that did not wait -> `"the subject was not held"`; held and - (`expired` or passive already ran) -> late-revert path (flow 5) for `discard` with `ctl.revert`, else - `"the decision arrived after the hold budget expired"`. Non-holdable triggers (`opts.hold` false) skip these - checks. "Not held" is only reachable when `setMode` widened the permitted set between trigger and answer - (`waits` is false only when nothing was permitted, the policy is fixed after construction, and a paused runtime - never reaches `submit`). These overrides never call `rate.take`. -4. A `rate limit` reason emits a status report at most once per 60,000 ms: +3. `proceeded = ctl.proceeded ? ctl.proceeded() : hold && (expired || passiveRan())`. For a `delivery` that has not + proceeded, set `op.delivery.decided = true` (this is what makes its chain's writes `covered`). +4. If `run` is a built-in and `proceeded`: `discard` with `ctl.revert`/`ctl.revertable` -> late-revert path (flow 5); + otherwise `run = null` with reason `"the decision arrived after the hold budget expired"` when the subject had + waited, else `"the subject was not held (decided in the background)"`. Custom actions are exempt (they run even + after the subject proceeded). These overrides never call `rate.take`. +5. A `rate limit` reason emits a status report at most once per 60,000 ms: `[GenClass] Rate limit reached (<N> actions/minute): running passive actions until it clears.` -5. Build `Decision` (`action = run ?? top`), push to `decisionsBuf` (keeps 200) and `explainMap` (after adding a - decision id, if the map holds more than 400 ids the single oldest entry is evicted; action ids share the map and - are added in `finish` without a size check), push an event-log entry `kind "decision"`, name = trigger, `data { id, diagnosis, action, executed }`. -6. Fire `decide`; if detected (`diagnosis !== "expected" && diagnosisConfidence >= thresholds.report`) fire `detect`. -7. Call each applicable standing question's `onAnswer(answers[q.id], { decision, situation: draft, runtime })` - (errors logged, never thrown). Applicable = `q.on` includes the trigger (`BuiltSituation.standing`); skipped when - the provider returned no answer for `q.id`. This runs before any action executes and also when nothing runs. -8. No `run`: passive; if detected, emit a `detect` report (`detectionLine`). Done. -9. `run`: `rate.take(now)`, then flow 4. +6. Build `Decision` (`action = run ?? top`), push to `decisionsBuf` (keeps 200) and `explainMap` (if the map holds + more than 400 ids after adding a decision id, the single oldest entry is evicted; action ids are added in + `finish` without a size check), push an event-log entry `kind "decision"`, name = trigger, `data { id, + diagnosis, action, executed }`. +7. Fire `decide`; if detected (`diagnosis !== "expected" && diagnosisConfidence >= thresholds.report`) fire `detect`. +8. Call each applicable standing question's `onAnswer(answers[q.id], { decision, situation: draft, runtime })` + (errors logged, never thrown); skipped when the provider returned no answer for `q.id`. Runs before any action. +9. No `run`: passive; if detected, emit a `detect` report (`detectionLine`). Done. +10. `run`: `rate.take(now)`, then flow 4. ### 4. Executing an action (`runtime.ts` -> `onDecision` -> `finish`) @@ -314,77 +391,108 @@ runtime timeout). They bypass triage, the gate and `Decision` records (see 2. Resolve -> `finish(effect)`. Throw/reject -> run passive, then `finish(null, err)`. 3. `finish` builds the `ActionRecord`: `ok = !err`; `changed = effect.changed` or, on error, `"Tried to <action> <subject> but it failed; the passive action ran instead."` (or `"Ran <action>."`); - `error` = message; `late: true` for late reverts; `undo` wrapper when the effect had one. + `error` = message; `late: true` for late reverts; then calls `effect.onRecord(record)`; `undo` wrapper when the + effect had one. 4. Push to `actionsBuf` (keeps 200), set `rec.action` and `explainMap[record.id]`, push event `kind "action"`, - name = action, `data { text: changed, id, decision, ok }`, fire `act`, emit an `intervene` report - (`interventionLine`). + name = action, `data { text: changed, id, decision, ok }`, fire `act`, emit an `intervene` report. `finish` runs when the effect settles, so `act` / the report arrive after the action's wait: `delay` ≤ 8 s, -`coalesce` ≤ 8 s (`COALESCE_MAX_WAIT_MS`), `retry` ≤ 5 s of backoff; `hedge` waits for the second request to settle -and `resync` for the store handlers, and a custom action until `def.run` resolves (no GenClass cap on those three). +`coalesce` ≤ 8 s, `retry` ≤ 5 s of backoff, delivery `defer` ≤ 10 s (`waitOps`); `hedge`, `resync` and custom +actions have no GenClass cap. Errors a controller throws (they become `ActionRecord.error`, `ok: false`, and `(failed: <error>)` in the line): | Thrown by | Message | |---|---| | any controller | `unsupported action <name>` | -| `gateMutation` -> `revert` | `the write could not be reverted` (`hub.revert` returned null) | +| `mutationController` -> `run` | `the write was not held` (default mode; normally unreachable because `proceeded` is checked first) | +| `mutationController` -> `revert` | `the write could not be reverted` (`hub.revert` returned null) | +| delivery (`runDelivery`) | `already delivered` | | fetch request gate | `the request was already sent`, `no Response constructor`, `no cached response`, `no identical request to share`, `the response of #<id> could not be shared; sent the request instead` | -| fetch failure gate | `the failure was already delivered`, `the request body cannot be replayed`, `no cached response`, `aborted` (app aborted during the retry backoff) | +| fetch failure gate | `the failure was already delivered`, `the request body cannot be replayed`, `no cached response`, `aborted` | | fetch stall | `already answered`, `no cached response`, `not hedgeable` | -| XHR request gate | `already decided` (also after the app aborted the held XHR), `no cached response` | -| XHR failure/stall (`passiveOnly`) | `<action> is not available for XMLHttpRequest` (never reached: only the passive action is offered) | +| XHR request gate | `already decided`, `no cached response` | +| XHR failure/stall (`passiveOnly`) | `<action> is not available for XMLHttpRequest` (never reached) | | `rollback` | `no consistent snapshot`, `nothing to restore: the affected stores already match the snapshot` | | `revertChain` | `the chain wrote nothing that can be restored`, `nothing to restore: the fields already hold their earlier values` | | `resync` | `no resync handler` (or the handler's own rejection) | | custom action | whatever `def.run` throws or rejects with | -### 5. Late revert (held mutations only) +### 5. Late revert (mutations) -1. Budget timer fires -> passive -> the hub applies the write (`MutationRec.appliedAt` set). -2. The queue keeps waiting until `t0 + budget + 2000`. -3. A decision with gate result `run === "discard"` -> `ctl.revertable()` in `gateMutation`: +Two ways a write reaches this path: (a) **default** (`holdWrites` off): every `mutation` decision arrives after the +write applied; (b) `holdWrites` on: the hold budget expired (or the write was not held because the model was not +expected in time) and the passive `apply` ran. + +1. The write applies (`MutationRec.appliedAt` set, `m.state === "done"`). +2. The queue keeps the item until its deadline: `t0 + budget + 2000` for a held write, `t0 + 5000` otherwise. +3. A decision with gate result `run === "discard"` -> `ctl.revertable()` in `mutationController`: `"the write has not applied yet"`; `"too late to revert: decided <secs> after the write applied"` (age > 2,000 ms; - a backstop: the queue deadline `t0 + budget + 2000` normally expires first, so an answer that late yields no - `Decision` at all, as `test/atoms.test.ts` asserts); then `StoreHub.revertable(m)`: `"the store is gone"`, `"the write was not applied"`, - `"<store> cannot be written by GenClass"`, `"the write changed nothing"`, - `"superseded: <path> changed again after the write applied"`, - `"the same operation chain wrote <paths> after this write applied; reverting only this write would leave them inconsistent"`. - Any string becomes `Decision.reason` and nothing runs. + reachable and recorded as `Decision.reason` for background decisions, asserted in `test/atoms.test.ts`); then + `StoreHub.revertable(m)`: `"the store is gone"`, `"the write was not applied"`, `"<store> cannot be written by + GenClass"`, `"the write changed nothing"`, `"superseded: <path> changed again after the write applied"`, + `"the same operation chain wrote <paths> after this write applied; reverting only this write would leave them + inconsistent"`. Any string becomes `Decision.reason` and nothing runs. 4. `null` -> `late = true`; `ctl.revert()` runs `hub.revert(m)` inside `runAsGenClass("revert")`: `changed` = `Reverted the write to <≤3 paths>[ and N more][ from <cause>] (decided <secs> after it applied)[; <path> is back to <value>…≤2].`; undo = `hub.reapply(m)`. Report lead is `Reverted`. -Any other late non-passive action (`defer`, or a custom action) or a late request/failure decision is recorded with -`"the decision arrived after the hold budget expired"` (`apply` is passive, so it is never a gate `run` and never -reaches this path). A late request/failure decision is rare: its queue deadline equals the budget, so the queue -abandons the item when the budget expires and usually no `Decision` is recorded. - -### 6. Custom actions and standing questions (`runtime.ts` -> `action`, `question`, `use`, `runCustom`) +Any other late built-in action (`defer`, a late request/failure/delivery decision) is recorded with a reason and does +nothing. A superseded write's queued decision is usually never computed (`stale`), so no `Decision` is recorded. + +### 6. Delivery gate (`runtime.ts` -> `runDelivery`) + +Entry points: fetch -> `NetHost.deliver` for a non-failure response (any status except 5xx/429/408, so 4xx included) +of the primary request while `gated` and not yet answered (body = parsed JSON of the buffered clone, when the request +has an identity and a `Response` constructor exists); XHR -> +`arrive()` on the first completion event of a successful async response (`readyState 4`, status not 0/5xx/429/408; +body = `xhrJson`); WebSocket/EventSource -> `MessageGate.decide` for each incoming message (body = +`parseJsonBody(data)`). `release()` delivers: fetch resolves the app's promise, XHR runs the queued app completion +listeners in order with the op ambient, `MessageGate` re-dispatches a cloned event (later messages and close/error +events wait behind a held one). + +1. Not consultable, paused, destroyed or a GenClass op -> release at once. +2. `predictedWrites` -> `matchFields` -> `conflictsOn` (`situation/conflicts.ts`) give the predicted paths, matched + live fields and conflicts (`kind: "newer" | "pending"`). `op.delivery = { patterns, known, salient: newer.length > + 0, decided: false }`. +3. No conflicts, no typed-into text field and not forced (`triage: "always"` or an `always` standing question on + `delivery`) -> release synchronously (no model call, no record). +4. With a body: wait at most `BODY_WAIT_MS` (100) for it, then `analyzeBody` decides salience: newer-data conflicts + whose incoming value differs, pending changes the body would put back (`vhash` of the value the user replaced), + typed text the body would replace. If every conflicting field is unchanged, an event `delivery.unchanged` is + pushed. No body / timeout / analysis error -> salient iff newer-data conflicts exist. (Salience details: + [learn-situation-triage.md](learn-situation-triage.md).) +5. Not salient and not forced -> release. Else `trigger(spec, ctl, { hold: true, priority: 2 })`. + +Delivery controller: `passive()` releases and, when the delivery was salient over conflicts, sets +`op.delivery.overNewer` (later writes of that chain get a field mark "delivered over newer data", `markWrites`); +`discard` and `defer` are below. In observe mode nothing is permitted, so a salient delivery is released at once and +decided in the background; its writes are then not `covered` (not decided in time), so they raise background +`mutation` decisions too. + +### 7. Custom actions and standing questions (`runtime.ts` -> `action`, `question`, `use`, `runCustom`) Registration: `rt.action(def)` / `rt.question(def)` append to `customActions` / `standing` and return an -unregister function (removes that exact object). `rt.use(plugin)` appends `plugin.actions` and `plugin.questions`, -runs `plugin.setup(pluginApi)` (a throw is logged; a returned function is the cleanup) and returns an unregister -function; calling `use` again with the same plugin object registers nothing. Unregister / `destroy()` removes the -plugin's actions and questions and runs its cleanup. `plugin.diagnoses` labels are appended after the base -vocabulary (never overriding a label) and `plugin.facts` add neutral facts, both read at every build -([learn-situation-triage.md](learn-situation-triage.md)). Standing questions with `always: true` bypass the -salient-triage early exit (flow 1 step 2/4); their answers are delivered in flow 3 step 7. +unregister function. `rt.use(plugin)` appends `plugin.actions` and `plugin.questions`, runs `plugin.setup(pluginApi)` +(a throw is logged; a returned function is the cleanup) and returns an unregister function; calling `use` again +with the same plugin object registers nothing. `plugin.diagnoses` labels are appended after the base vocabulary and +`plugin.facts` add neutral facts ([learn-situation-triage.md](learn-situation-triage.md)). Standing questions with +`always: true` bypass the salient-triage early exit (flow 1 step 2/4 and delivery step 3). 1. Offered (`build.ts`) when `def.on` includes the trigger, no earlier option has the same name, and `def.applicable(draft)` is true (a throw = false). Tier `def.tier ?? "heal"`; description `vocabulary.actions[name] ?? def.description`. -2. Gated like any action (its own tier's threshold), then `def.run(ctx)` runs inside `runAsGenClass(def.name)` on a - microtask, so its writes and requests are GenClass ops (never gated). +2. Gated like any action (its own tier's threshold), **not** blocked by `proceeded`; then `def.run(ctx)` runs inside + `runAsGenClass(def.name)` on a microtask. 3. `ctx.builtin(name)`: false unless `name` is a built-in **offered for this trigger**. The passive name calls - `ctl.passive()` and returns true. Otherwise false when paused, `restriction(...)` blocks it (mode tier, deny, - allow) or the rate limiter is full; else `rate.take` (a second slot), `await ctl.run(name)`, adopt its `changed` + `ctl.passive()` and returns true. Otherwise false when paused, `restriction(...)` blocks it, `ctl.proceeded()` is + true, or the rate limiter is full; else `rate.take` (a second slot), `await ctl.run(name)`, adopt its `changed` (if `describe` was not called yet) and `undo` (if `onUndo` was not called yet), return true. Thresholds and the diagnosis rule are **not** re-applied. -4. After `run` resolves: if no builtin took over, `ctl.passive()` runs (the held write applies, the request is - sent). `changed = describe text || "Ran the custom action <name>."`. +4. After `run` resolves: if no builtin took over, `ctl.passive()` runs. `changed = describe text || "Ran the custom + action <name>."`. -### 7. Reporting (`decide/report.ts`) +### 8. Reporting (`decide/report.ts`) Lines (exact templates): @@ -397,12 +505,15 @@ decisionLine: [GenClass] Checked <subject>: <diagnosis> (<pDiag>); ran <ran> - `lead`: `LEAD[action]` (`discard`/`coalesce` "Prevented", `defer` "Held back", `delay` "Slowed down", `block` "Stopped", `serve_cached`/`retry` "Recovered from", `hedge` "Worked around", `rollback`/`resync` "Repaired"), `"Reverted"` when `late`, `"Handled"` for custom actions. -- `noun`: `an(NOUN[trigger])` for `expected`; `"inconsistent state"` for inconsistency+inconsistent; else - `an("<diagnosis> <NOUN>")`. `NOUN`: write, request, request failure, slow request, state, state change, error, question. +- `noun`: `NOUN[trigger]` — write, request, **response** (delivery), request failure, slow request, state, state + change, error, question; a delivery whose `Decision.subject` does not start with `response` (a push message) uses + **message**. `an(noun)` for `expected`; `"inconsistent state"` for inconsistency+inconsistent; else + `an("<diagnosis> <noun>")`. +- `Decision.subject` for delivery (`build.ts` -> `subjectOf`): `response to <opLabel>` or `WebSocket message <path> + (#<id>) <summary>` / `server-sent message <path> (#<id>) <summary>`. - `topFact`: first fact not matching `/^This (write|request) (comes from|has no known cause)/`, with a trailing period. - Probabilities are `toFixed(2)`, `?` when undefined or not finite. The `Not acted on (…)` clause is added only when - `Decision.reason` is set and `executed` is false. `<x>` = `"<candidate> <mass> for permitted actions"` when the - candidate differs from `action` (and `mass` is set), else `"<action> <confidence>"`. + `Decision.reason` is set and `executed` is false. `Reporter.emit(r)`: @@ -416,34 +527,32 @@ decisionLine: [GenClass] Checked <subject>: <diagnosis> (<pDiag>); ran <ran> any), `Situation sent to the model:` + exact text, `Answers:`, and for actions `Changed:`, an undo hint (`GenClass.runtime.interventions().find(a => a.id === "<id>").undo()` or `Undo: not reversible`), a deny hint (`GenClass.init({ policy: { deny: ["<action>"] } })`), then `explain: GenClass.runtime.explain("<id>")`. - Without `groupCollapsed`: `warn` (intervene) / `info` (detect). Status lines emitted by `runtime.ts`: `[GenClass] Model ready (<model, device, variant>[, <secs>]). Mode: <mode>.`, `[GenClass] Model unavailable (<error>); observing only.`, `[GenClass] Mode set to <mode>.`, and the rate-limit line. -### 8. explain and undo +### 9. explain and undo - `explain(id)` (`runtime.ts` -> `RuntimeImpl.explain`): looks up `explainMap`; `message` = `interventionLine` if an action is attached, else `detectionLine` if detected, else `decisionLine`. Returns `null` for unknown/evicted ids. - `facts` are all ordered facts (≤ 12); `situationText` is the budget-limited text the model read. - `ActionRecord.undo()` wrapper: no-op after the first call; runs the effect's undo inside `runAsGenClass("undo")`; pushes event `kind "action"`, name `"undo"`, `data { text: "undid <action> (<id>)", id }`. - It fires no `act` event, no report, and does not mark the record. An exception from the effect's undo propagates - to the caller, after which the wrapper is already spent (`undone = true` is set first) and no event is pushed. -- `decisions(n = 200)` / `interventions(n = 200)` return the last `n` entries of the rings, oldest first - (`slice(-n)`); records are the live objects (mutating them affects later `explain` output). + It fires no `act` event, no report, and does not mark the record. An exception from the effect's undo propagates. +- `decisions(n = 200)` / `interventions(n = 200)` return the last `n` entries of the rings, oldest first; records are + the live objects (an `ActionRecord.dropped` array keeps growing while its discard mark lasts). - `holdBudgetMs()` (public on `Runtime`) returns the budget the next held trigger would use. -### 9. Mode, pause, resume, destroy (decision-side effects) +### 10. Mode, pause, resume, destroy (decision-side effects) | Call | Effect in this scope | |---|---| +| constructor | `mode = o.mode ?? "observe"`; `hub.holdWrites = policy.holdWrites`; `GenClass.init` also honours `?genclass=` / `localStorage.genclass` ([public-api-and-lifecycle.md](public-api-and-lifecycle.md)) | | `setMode(mode)` | ignored unless `"observe" \| "guard" \| "heal"`; sets the mode used by the next `trigger` / `gate` / `ctx.builtin`; emits status `[GenClass] Mode set to <mode>.` and fires `status` with the model status | -| `pause()` | `paused = true`, `hub.gating = false` (writes commit unheld), `NetHost.gated` false (no request/failure/stall triggers); `consultable()` false, so every other trigger runs passive with no record; decisions already queued still produce a `Decision` but never run (`gate` -> `"GenClass is paused"`, shown when the model's top was non-passive); tracing continues | +| `pause()` | `paused = true`, `hub.gating = false`, `NetHost.gated` false (no request/failure/stall/delivery triggers); `consultable()` false; decisions already queued still produce a `Decision` but never run (`"GenClass is paused"`) | | `resume()` | undoes `pause()` (no-op after `destroy`) | | `isPaused` | getter on `RuntimeImpl` only (not on `Runtime`) | -| `destroy()` | `destroyed = true`, `hub.gating = false`, `queue.dispose()` (pending decisions resolve `null` -> passive), `reporter.dispose()` (open dedupe windows are dropped: pending "×N more" summaries never print), observers uninstalled, plugins unregistered, an owned provider disposed | -| `setReport(sink)` | `RuntimeImpl` only (not on `Runtime`): swaps the report sink live (`Reporter.setSink`) | +| `destroy()` | `destroyed = true`, `hub.gating = false`, `queue.dispose()` (pending decisions resolve `null` -> passive, which releases held deliveries), `reporter.dispose()`, observers uninstalled, plugins unregistered, an owned provider disposed | +| `setReport(sink)` | `RuntimeImpl` only: swaps the report sink live (`Reporter.setSink`) | ### Events @@ -453,60 +562,55 @@ Status lines emitted by `runtime.ts`: `[GenClass] Model ready (<model, device, v | `detect` | `Decision` | diagnosis ≠ `expected` and p(diagnosis) ≥ `thresholds.report` (also when an action ran) | | `act` | `ActionRecord` | every non-passive action attempt, `ok` true or false, after its effect settled | | `report` | `Report` | every report (detect/intervene/status), before the sink, even when silent | -| `status` | `ModelStatus` | provider `onStatus`; also on `setMode` (payload is the model status, not the mode) | -| `event` | `RtEvent` | every event-log entry, including `decision`, `action` and `undo` entries | +| `status` | `ModelStatus` | provider `onStatus`; also on `setMode` | +| `event` | `RtEvent` | every event-log entry, including `decision`, `action`, `undo`, `dropped` and `delivery.unchanged` | -`action` (and `undo`) event-log entries appear in later situations' timelines as `<rel> GenClass <changed text>` -(`situation/describe.ts` -> `eventLine`, text truncated to 100 chars); `decision` entries are not rendered. +`action` event-log entries (including `undo` and `dropped`) appear in later situations' timelines as `<rel> GenClass +<text>` (`situation/describe.ts` -> `eventLine`, text truncated to 100 chars); `decision` entries are not rendered. Listener exceptions are caught and logged (`fire`), never thrown into the decision flow. -### 10. Built-in action reference +### 11. Built-in action reference -Tiers and descriptions come from `BUILTIN_ACTIONS`; applicability from `situation/build.ts` -> `builtinApplicable`. -`opLabel(op)` (`situation/describe.ts`) renders like `GET /api/x (#12)` (phrase truncated to 90 chars; `an earlier -operation` when missing); `secs(ms)` (`util.ts`) gives 2 decimals below 10 s (`0.30s`), 1 decimal below 1,000 s, -else whole seconds. +Tiers and descriptions come from `BUILTIN_ACTIONS` (delivery: `TRIGGER_DESCRIPTIONS`); applicability from +`situation/build.ts` -> `builtinApplicable`. `opLabel(op)` renders like `GET /api/x (#12)`; `secs(ms)` gives 2 +decimals below 10 s (`0.30s`). | action | tier | trigger(s) | offered when | mechanics (where) | `changed` (abridged) | undo | |---|---|---|---|---|---|---| -| `apply` | passive | mutation | always | verdict `apply`: hub applies now or at drain (`gateMutation` -> `passive`) | — | — | -| `discard` | guard | mutation | always | verdict `discard`: hub drops it, `set` caller not notified (`gateMutation`) | `Dropped the write to <paths>[ from <cause>]; <store> stays at version <v>.` | apply the write now on top of the current value (`hub.commit(st, { ...m, userSync: false, genclass: true, state: "resolved" }, false)`: functional updaters re-run, value writes patched; bypasses `propose`, so never gated); recorded with the original cause as writer (see Drift 12) | -| `defer` | guard | mutation | `m.defers < 2` | verdict `defer`: hub waits for related in-flight ops (`waitRelated`, cap `LONG_RUNNING_MS` 10,000), re-proposes the write (new trigger); after 2 defers it applies (`StoreHub.drain`/`defer`) | `Held the write to <paths> until the related in-flight operations finish, to decide again.` | — | +| `apply` | passive | mutation | always | default: no-op (already applying); `holdWrites`: verdict `apply` | — | — | +| `discard` | guard | mutation | always | default: late revert only (flow 5); `holdWrites`: verdict `discard`, hub drops the held write | held: `Dropped the write to <paths>[ from <cause>]; <store> stays at version <v>.`; late: `Reverted the write to …` | held: apply the write now (`hub.commit(st, { ...m, userSync: false, genclass: true, state: "resolved" }, false)`); late: `hub.reapply(m)` | +| `defer` | guard | mutation | `m.defers < 2` | `holdWrites` only: verdict `defer`, hub waits for related in-flight ops (`waitRelated`, cap 10 s) and re-proposes (new trigger); default: always late -> recorded with a reason only | `Held the write to <paths> until the related in-flight operations finish, to decide again.` | — | +| `deliver` | passive | delivery | always | `release()` (marks `overNewer` when it was salient over conflicts) | — | — | +| `discard` | guard | delivery | always | release now and set `op.discardMark` (protect = conflicting paths, 10 s): each later write of the op's chain drops its changes to protected paths or to paths a user action or newer op wrote since the op started (`dropFilter`, `writtenOver`); its other changes apply; a library-commit write (redux) cannot be applied in part and applies whole unless everything is dropped | `Delivered <the response to <op> \| message <op>> and dropped the state changes it makes over newer data[ (<≤3 protected paths>)].`; `ActionRecord.dropped` lists the dropped paths (filled via `onRecord`/`onDrop`) | end the mark and write the dropped values now (`hub.restoreFields`) | +| `defer` | guard | delivery | `defers < 2` and `relatedInFlight(env, op, matched)` is non-empty | wait for those ops (`waitOps`, cap `LONG_RUNNING_MS` 10 s), then `runDelivery(o, release, defers + 1)` decides again | `Held <what> for <secs> until <n> related operation(s) finished, then decided again.` | — | | `send` | passive | request | always | send now (`sendNow` / XHR `doSend`) | — | — | -| `coalesce` | guard | request | fetch only, and `cache.shareable(identity, op.id)`: an older identical fetch in flight or settled ≤ 2,000 ms ago | wait ≤ `COALESCE_MAX_WAIT_MS` 8,000 for its buffered response, answer a copy marked `x-genclass: coalesced` (opaque responses: unmarked clone), end op synthetic; unshareable -> send and throw | `Did not send <op>; reused the <status> response of the identical request #<id>[ (x-genclass: coalesced)].` | — | +| `coalesce` | guard | request | fetch only, and `cache.shareable(identity, op.id)` | wait ≤ 8 s for the identical request's buffered response, answer a copy marked `x-genclass: coalesced` | `Did not send <op>; reused the <status> response of the identical request #<id>[ (x-genclass: coalesced)].` | — | | `delay` | guard | request | always | wait `min(250 × 2^failStreak(signature), 8000)` ms, then send (fetch and XHR) | `Delayed <op> by <secs> before sending it.` | — | -| `block` | heal | request | always | do not send; 503 `Response`, statusText `Blocked by GenClass`, header `x-genclass: blocked`; op ends `blocked` (XHR: faked 503 + `load`/`loadend`) | `Did not send <op>; answered 503 (x-genclass: blocked).` | — | -| `serve_cached` | heal | request | GET and a cached good response exists (`cache.peek`) | answer the last good GET body (≤ 256 KB), `x-genclass: cached`; op ends `ok` synthetic (XHR: faked response) | `Did not send <op>; answered with the cached <status> response from <age> ago (x-genclass: cached).` | — | +| `block` | heal | request | always | do not send; 503 `Response`, statusText `Blocked by GenClass`, header `x-genclass: blocked` (XHR: faked 503) | `Did not send <op>; answered 503 (x-genclass: blocked).` | — | +| `serve_cached` | heal | request | GET and a cached good response exists | answer the last good GET body (≤ 256 KB), `x-genclass: cached` | `Did not send <op>; answered with the cached <status> response from <age> ago (x-genclass: cached).` | — | | `deliver` | passive | failure | always | hand the original `Response` / rejection to the app | — | — | -| `retry` | heal | failure | fetch, replayable body, `op.attempt < 4` | after `min(200 × 2^(attempt-1), 5000)` ms start a new fetch op (`attempt + 1`, cause = failed op) and send it; it passes through the failure gate again; the app gets that attempt's result | `Retried <op> after <secs> as attempt <n> (#<id>); the app will receive that attempt's result.` | — | +| `retry` | heal | failure | fetch, replayable body, `op.attempt < 4` | after `min(200 × 2^(attempt-1), 5000)` ms start a new fetch op (`attempt + 1`) | `Retried <op> after <secs> as attempt <n> (#<id>); the app will receive that attempt's result.` | — | | `serve_cached` | heal | failure | fetch, GET, cached | answer the cached response instead of the failure | `Replaced the failed response of <op> with the cached <status> response from <age> ago (x-genclass: cached).` | — | | `wait` | passive | stall | always | nothing | — | — | -| `hedge` | heal | stall | fetch, GET, idempotent, replayable | send a second identical request (op detail `(hedge)`, cause = original); first good answer wins | `Sent a second identical request #<id> for <op>; it answered first (<status>) and the app received it.` / `…; the original answered first.` / `…; it failed, so the app keeps waiting for the original.` | — | -| `serve_cached` | heal | stall | fetch, GET, cached | answer the cached response now; the original continues in the background | `Answered <op> with the cached <status> response from <age> ago instead of waiting (x-genclass: cached); the original request continues in the background.` | — | +| `hedge` | heal | stall | fetch, GET, idempotent, replayable | send a second identical request; first good answer wins | `Sent a second identical request #<id> for <op>; …` | — | +| `serve_cached` | heal | stall | fetch, GET, cached | answer the cached response now; the original continues | `Answered <op> with the cached <status> response from <age> ago instead of waiting (x-genclass: cached); …` | — | | `ignore` | passive | inconsistency, transition, error | always | nothing | — | — | -| `rollback` | heal | inconsistency | a consistent snapshot exists and an involved store is writable | `RuntimeImpl.rollback(stores, violationIds)`: write the last consistent snapshot (of ≤ 8 kept) back to the involved writable stores | `Restored <store (paths)>; … to the consistent state from <secs> ago.` | write back the pre-rollback values and mute those violation ids until they hold again | -| `rollback` | heal | transition, error | the op's chain wrote fields nobody overwrote since, with a known earlier value, in a writable store (error: an ambient op existed) | `RuntimeImpl.revertChain(op, why)`: restore exactly those fields to their values before the chain's first write | `Restored <≤4 paths>[ and N more] to their values before <root op> (the <why>'s chain wrote them).` (`why` = `transition` or `error`) | restore the replaced values | +| `rollback` | heal | inconsistency | a consistent snapshot exists and an involved store is writable | `RuntimeImpl.rollback(stores, violationIds)` | `Restored <store (paths)>; … to the consistent state from <secs> ago.` | write back the pre-rollback values and mute those violation ids | +| `rollback` | heal | transition, error | the op's chain wrote fields nobody overwrote since (error: an ambient op existed) | `RuntimeImpl.revertChain(op, why)` | `Restored <≤4 paths>[ and N more] to their values before <root op> (the <why>'s chain wrote them).` | restore the replaced values | | `resync` | heal | inconsistency, transition | an involved store has `StoreOptions.resync` | call each such store's `resync()` inside `runAsGenClass("resync")` | `Reloaded <stores> from its/their source (resync handler).` | — | Notes: +- Each dropped write (delivery `discard`) pushes an event `kind "action"`, name `dropped`, `data { text: "dropped the + write of <paths>[ by <cause op>] over newer data[ (its other changes applied)]", paths, op /* the marked op id or + null */, mutation }` (`onDropped`). + The drop filter skips GenClass and user-sync writes and searches ≤ 16 ancestors for an unexpired mark. - Other `changed` variants: coalesce when the app was answered meanwhile -> `Coalesced <op> with #<id>, but the app was already answered.`; retry when the app was answered during the backoff -> `Did not retry <op>: the request was - already answered.` (both `ok: true`). A retry whose signal aborted during the backoff rejects the app's promise with - the abort reason and records `ok: false`, error `aborted`. -- `defer`'s "related in-flight operations" (`runtime.ts` -> `waitRelated`): in-flight ops that are neither ancestors - nor descendants of the write's cause and either share the cause's name and kind or have a signature whose chains - have written this store before (`storeWriters`); none -> re-proposed at once. -- Store sets: inconsistency `rollback`/`resync` act on the first path segment of every violated field; transition - `resync` on the first segment of the op chain's written fields that are registered stores. `rollback` skips stores - that are unregistered, not writable or absent from the snapshot; snapshots are taken at settled points where - nothing newly broke (last 8 kept, `runtime.ts` -> `settled`). -- XHR: `coalesce`, `retry`, `hedge` and failure/stall `serve_cached` are never offered (transport check); - XHR failures and stalls use `passiveOnly()` and are detection only. Synchronous XHRs are never held. -- The response cache keeps the last good GET body per identity (`MAX_ENTRIES` 64 × `MAX_BODY` 256 KB, memory only); - coalescing buffers expire `COALESCE_WINDOW_MS` 2,000 ms after settling (≤ 64 entries, ≤ 4 MB); a body still - streaming after `BUFFER_WAIT_MS` 1,000 ms is not shareable (`observe/cache.ts`). Identity details: - [observe-and-trace.md](observe-and-trace.md). + already answered.` (both `ok: true`). +- XHR: `coalesce`, `retry`, `hedge` and failure/stall `serve_cached` are never offered; XHR failures and stalls are + detection only; synchronous XHRs are never held. An `abort()` while a delivery is held drops the response and fires + `abort` + `loadend` (event `xhr.aborted-while-held`). - `rollback`'s model-facing description says "last consistent snapshot" for every trigger, but transition/error rollback is a chain revert (see Drift). @@ -514,7 +618,7 @@ Notes: | Name | Type | Default / value | Defined in | Effect | |---|---|---|---|---| -| `mode` | `"observe" \| "guard" \| "heal"` | `"guard"` | `runtime.ts` constructor | which tiers are permitted (`policy.ts` -> `modeAllows`); `setMode` changes it live | +| `mode` | `"observe" \| "guard" \| "heal"` | `"observe"` (was `"guard"` before f3636b2) | `runtime.ts` constructor | which tiers are permitted (`policy.ts` -> `modeAllows`); `setMode` changes it live | | `policy.thresholds.report` | number | 0.6 | `policy.ts` -> `policyConfig` | min diagnosis probability for a detection | | `policy.thresholds.guard` | number | 0.9 | `policyConfig` | min Σ p(A) when the candidate is guard tier | | `policy.thresholds.heal` | number | 0.8 | `policyConfig` | min Σ p(A) when the candidate is heal tier | @@ -522,203 +626,208 @@ Notes: | `policy.deny` | `string[]` | `[]` | `policyConfig` | these never run | | `policy.holdBudgetMs` | `number \| "auto"` | `"auto"` | `policyConfig`, `holdBudget` | max hold; a number is used as `max(0, n)` | | `HOLD_MIN_MS` / `HOLD_MAX_MS` / `HOLD_FALLBACK_MS` | ms | 150 / 800 / 300 | `policy.ts` | auto budget clamp and no-data fallback | -| `policy.holdUserWrites` | boolean | false | `policyConfig` -> `StoreHub.holdUserWrites` | hold writes made synchronously in a user handler | +| `policy.holdWrites` | boolean | false | `policyConfig` -> `StoreHub.holdWrites` | true: salient store writes wait for the model (`gateMutation`); false: decided in the background (`observeWrite`) | +| `policy.holdUserWrites` | boolean | false | `policyConfig` -> `StoreHub.holdUserWrites` | gate writes made synchronously in a user handler | | `policy.maxActionsPerMinute` | number | 60 | `policyConfig`, `RateLimiter` | sliding 60,000 ms window of non-passive actions | | `policy.requireDiagnosis` | boolean | true | `policyConfig` | require top diagnosis ≠ `expected` | -| `report` | `"console" \| "silent" \| fn` | `"console"` | `runtime.ts` constructor; `setReport()` changes it | report sink | +| `report` | `"console" \| "silent" \| fn` | `"console"` | `runtime.ts` constructor; `setReport()` | report sink | | `MAX_QUEUE` | number | 32 | `decider.ts` | queue overflow drops lowest-priority, oldest | | `CACHE_MAX` / `CACHE_TTL` | number / ms | 64 / 30,000 | `decider.ts` | identical-situation answer cache | -| `LATENCY_SAMPLES` | number | 20 | `decider.ts` | provider latencies kept for the auto hold budget | +| `LATENCY_SAMPLES` | number | 20 | `decider.ts` | provider latencies kept for the hold budget and expected latency | | `PROVIDER_TIMEOUT_MS` | ms | 10,000 | `decider.ts` (exported) | runtime-side timeout when a request has no deadline | | `LATE_REVERT_MS` | ms | 2,000 | `runtime.ts` | late-revert window; also extends held-mutation deadlines | -| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `runtime.ts` | deadline of non-held decisions | +| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `runtime.ts` | deadline of non-held decisions (incl. default-mode mutations) | +| `DISCARD_MARK_MS` | ms | 10,000 | `runtime.ts` | how long a delivery `discard` keeps dropping its chain's writes | +| `BODY_WAIT_MS` | ms | 100 | `runtime.ts` | max wait for a delivery's body before deciding salience without it | | `DECISIONS_KEPT` | number | 200 (explainMap 400) | `runtime.ts` | `decisions()`, `interventions()`, explain retention | -| `LONG_RUNNING_MS` | ms | 10,000 | `runtime.ts` | cap on `defer`'s wait for related ops | +| `LONG_RUNNING_MS` | ms | 10,000 | `runtime.ts` | cap on mutation `defer` (`waitRelated`) and delivery `defer` (`waitOps`) waits | +| ancestor search depth | number | 16 | `runtime.ts` -> `covered`, `dropFilter`, `onDropped` (literals) | how far up a write's chain a delivery / discard mark is looked for | | `WINDOW_MS` | ms | 60,000 | `report.ts` | console dedupe window | | rate-limit warning interval | ms | 60,000 | `runtime.ts` -> `onDecision` (literal) | at most one rate-limit status line per minute | | `COALESCE_MAX_WAIT_MS` | ms | 8,000 | `observe/fetch.ts` | coalesce wait for the shared response | | delay backoff | ms | `min(250 × 2^streak, 8000)` | `fetch.ts` / `xhr.ts` (literal) | `delay` | | retry backoff | ms | `min(200 × 2^(attempt-1), 5000)` | `fetch.ts` (literal) | `retry` | | max retry attempt | number | offered while `attempt < 4` | `build.ts` -> `builtinApplicable` | at most 3 retries | -| max defers | number | 2 | `build.ts`, `hub.ts` -> `drain` (literals) | then the write applies | -| `COMPACT_QUESTIONS_BUDGET` / `COMPACT_DESC_MAX` | chars | 1,400 / 24 | `questions.ts` | compact questions drop descriptions (custom ones too) | -| `STALL_MIN_MS` | ms | 500 | `runtime.ts` | floor of the stall delay `max(4 × median, 2 × p95, 500)` | +| max defers | number | 2 | `build.ts` (mutation and delivery), `hub.ts` -> `drain` | then the write applies / the delivery is decided without `defer` | +| `COMPACT_QUESTIONS_BUDGET` / `COMPACT_DESC_MAX` | chars | 1,400 / 24 | `questions.ts` | compact questions drop descriptions | +| `STALL_MIN_MS` | ms | 500 | `runtime.ts` | floor of the stall delay | | `budgetScale` step / floor | factor | × 0.8 per `max_tokens_exceeded`, floor 0.5 | `runtime.ts` constructor (`onError`) | shrinks `"auto"` situation budgets | -| consistent snapshots kept | number | 8 | `runtime.ts` -> `settled` (literal) | how far back `rollback` (inconsistency) can restore | | `MAX_FACTS` | number | 12 | `situation/facts.ts` | `Decision.facts` / `explain().facts` length cap | | `debug` | boolean | false | `runtime.ts` constructor | `console.debug` of model errors, decisions, failed listeners/standing questions/passive actions | ## Invariants and gotchas - **No rules.** Nothing in this scope may map a fact pattern to a diagnosis or action (CONTRACT §0 rule 1). The gate - only filters what the model chose; triage only decides whether to ask. + only filters what the model chose; triage and delivery salience only decide whether to ask. +- **Holding is only latency.** A held delivery changes nothing about the response/event; a held request is only + sent later; `holdWrites` never reorders a store's writes (`test/no-reorder.test.ts`). The "never worse" sweep + (`docs/runtime/RESULTS.md`: 0/396 changed clean runs with an always-passive model) depends on this. - **Fail-open is total.** `submit()` never rejects; every failure is `null` -> passive. New code paths must keep calling the controller's `passive()` on every exit. Controllers must tolerate a second `passive()` call - (`runCustom` calls `ctl.passive()` directly, outside the `passiveRan` guard, from `ctx.builtin(<passive>)` and - after `run`). Existing ones do: the mutation `settle` resolves its promise once; fetch `sendNow`/`deliver` check - `sent`/`answered`/`handled`; the XHR request controller checks `decided`. -- **Model wording is frozen.** `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` order, `ACTION_INSTRUCTIONS`, - `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES` and `PASSIVE` are model input and are mirrored in - `training/curriculum/rt.py`, `training/curriculum/fmt.py`, `training/eval_runtime.py` and the sim. The scope - files are unchanged since tag `situation-v1` (`1a77558`). `ActionRecord.changed` is also model input: it appears in - later timelines. + (`runCustom` calls `ctl.passive()` outside the `passiveRan` guard). Existing ones do (`settle?.()`, `released`, + `sent`/`answered`/`handled`, `decided`). +- **Model wording is frozen** at tag `situation-v2` (6e5e86e): `BUILTIN_ACTIONS` descriptions, `TRIGGER_ACTIONS` + order, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `PASSIVE` are + model input and are mirrored in `training/curriculum/rt.py` (header "FROZEN at git tag `situation-v2`") and the + sim. `ActionRecord.changed` and the `dropped` event text are also model input (timelines). No file under + `situation/` or `decide/` changed between `situation-v2` and b435acb. +- **Default mode cannot act.** In observe mode `permittedActions` is empty, so `waits` is always false and no gate + `run` exists; only detections are reported. Tests that exercise actions get guard from `test/helpers.ts` -> + `setup()`; `test/default-mode.test.ts` asserts the product default. +- **No hold when the model is late.** `expectedLatency()` > budget (e.g. `warmupMs` 2,000 with an 800 ms max + budget, or a stuck provider) means nothing waits, even in guard mode (`test/delivery.test.ts` "does not hold when + the model is not expected to answer within the hold budget"). - **Threshold semantics:** the threshold is the candidate's tier's, applied to the mass of all permitted actions. - Guard (0.9) is stricter than heal (0.8). With `thresholds` of 0 the gate runs the first permitted action even at - probability 0 (`p(a) > p(candidate)` is strict); the sim therefore uses 0.5 (`sim/src/run/rt.ts`). + With `thresholds` of 0 the gate runs the first permitted action even at probability 0; the sim uses 0.5 + (`sim/src/run/rt.ts`). - **`Decision.action` may differ from the model's argmax** when a permitted candidate runs while a non-permitted - action (passive or restricted) was top (only reachable with lowered thresholds or many actions: with the 0.9 - guard threshold a passive top would need ≥ 9 permitted actions). `executed` is true when an action ran, - even if it then failed (`ok: false`). -- **Failed actions count:** `rate.take` happens before the effect, so failures consume rate slots; a custom action - that calls `ctx.builtin` consumes two. -- **Holds can outlast the budget after a decision:** the budget timer is cleared when the answer arrives; `coalesce` - (≤ 8 s), `delay` (≤ 8 s), `retry` backoff (≤ 5 s) and custom actions (unbounded) keep the subject waiting. -- **Runtime timeout does not cancel the provider.** After the timer fires the queue dispatches the next request; - a late answer from the abandoned call is still cached and its latency still enters the hold-budget samples - (code reading; the model host has its own queue and timeouts, see [model-host.md](model-host.md)). -- **Determinism:** only the injected `Clock` is used (timers, `now`); ids are counters (`d<n>`, `a<n>`). Do not add - `Date.now`/`setTimeout` here (CONTRACT §0 rule 3). -- **Precision / harm:** nothing is held when no action is permitted (observe mode; failures in guard mode), so the - default mode adds no latency for triggers it could not act on. Holding still delays salient writes/requests up to - the budget (OPEN_TASKS: hold-induced harm). + action was top. `executed` is true when an action ran, even if it then failed. +- **Failed actions count:** `rate.take` happens before the effect; a custom action that calls `ctx.builtin` + consumes two slots. +- **Holds can outlast the budget after a decision:** `coalesce`, `delay` (≤ 8 s), `retry` (≤ 5 s), delivery `defer` + (≤ 10 s, then a second decision) and custom actions (unbounded) keep the subject waiting. +- **Custom actions run late.** Unlike built-ins they are not nulled when the subject already proceeded (a custom + action may act after a write applied); only `ctx.builtin` refuses then. +- **Covered writes skip the mutation trigger** only when the delivery was decided before release; a delivery + released by budget expiry or in observe mode leaves its writes to background `mutation` decisions. +- **Runtime timeout does not cancel the provider.** A late answer from an abandoned call is still cached and its + latency still sampled; it also clears `stuck`. +- **Determinism:** only the injected `Clock` is used (timers, `now`, body wait, discard mark); ids are counters. Do + not add `Date.now`/`setTimeout` here (CONTRACT §0 rule 3). - **Console hints** reference `GenClass.runtime`, which is `null` for runtimes made with `createRuntime`. -- **Devtools mirrors report wording** (`src/devtools/ui.ts` -> `LEAD`, `NOUN`, `splitReport` regexes for - `Not acted on (…)` and `(diag, p; action p)`). Changing a line format can break the overlay. -- **Compact questions** (budget ≤ 1,400 chars) send custom action descriptions as `null` unless a vocabulary - override ≤ 24 chars exists, so the model sees only the custom action's name. -- **Answer cache in tests:** identical `(trigger, state, questions)` within 30 s are answered from the queue cache, - so `ScriptedDecider.calls` does not grow and a changed script does not apply to a repeated identical situation. - Advance the fake clock past 30 s or vary the situation. +- **Devtools mirrors report wording** (`src/devtools/ui.ts` -> `LEAD`, `NOUN`, `actTitle`, `splitReport`). Changing + a line format can break the overlay. +- **Answer cache in tests:** identical `(trigger, state, questions)` within 30 s are answered from the cache, so + `ScriptedDecider.calls` does not grow. Advance the fake clock past 30 s or vary the situation. - **Undo is unguarded:** `ActionRecord.undo()` ignores mode, pause, policy and the rate limit, and never checks - whether the state moved since (a discard's undo re-runs/patches the write over the current value; a rollback's - undo writes back whole pre-rollback store values). -- **Dead surface:** `RuntimeImpl.rollback`'s `beforeSeq` parameter is never passed (only the last consistent - snapshot is used); `RuntimeImpl.setReport` has no caller (Drift 13; devtools listens to `on("report")`). + whether the state moved since (a delivery discard's undo writes the dropped values over whatever is there now). +- **Dead surface:** `RuntimeImpl.rollback`'s `beforeSeq` is never passed; `RuntimeImpl.setReport` has no caller. ## How to change it safely -Run tests with `npm test` / `vitest run` in `packages/runtime`. The team ran them on the VM (CONTRACT §0 rule 5). -Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the unit tests locally (see -[build-test-release.md](build-test-release.md#where-to-run-things)). +Light local checks are allowed on this machine (see [build-test-release.md](build-test-release.md)): +`NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in +`packages/runtime` (lead's run at b435acb: 332 passed, 14 skipped), then `test/review-perf.test.ts` alone (flaky under +parallel load). CI (`.github/workflows/ci.yml`) runs the same split. Do not run Playwright, the sim, realapps or demos +eval without asking. 1. **Change a default threshold, budget or rate:** edit `policy.ts` -> `policyConfig` / `HOLD_*`; update the JSDoc - in `types.ts` -> `PolicyOptions`, `docs/runtime/API.md`, and assertions in `test/policy.test.ts`, - `test/budget.test.ts`, `test/fetch.test.ts` ("request gate fails open after the hold budget" expects 300 ms; the - failure-gate fail-open test also depends on the 300 ms fallback). -2. **Change gate logic:** edit `policy.ts` -> `gate` only; keep reason strings stable (asserted verbatim in - `test/policy.test.ts`, `test/report.test.ts`, and parsed by devtools). Check the sim's forced-action contract - (`sim/src/run/rt.ts` thresholds 0.5, `requireDiagnosis: false`). -3. **Change an action's mechanics:** edit its controller (table above). Keep: throw when it cannot run (passive then - runs); return an exact `changed` sentence; provide `undo` only if truly reversible; end synthetic ops with - `synthetic: true` so baselines ignore them. Coordinate `changed` wording with SIM (timeline input). Tests: - `test/fetch.test.ts`, `test/xhr.test.ts`, `test/atoms.test.ts`, `test/review-fetch.test.ts`, `test/review-xhr.test.ts`. -4. **Add a built-in action:** add to `BUILTIN_ACTIONS` and `TRIGGER_ACTIONS` (passive stays first), applicability in - `build.ts` -> `builtinApplicable`, implementation in the trigger's controller, `LEAD` in `report.ts` and - `devtools/ui.ts`. This changes model input: it needs a new freeze tag, sim + training mirrors, new data and a - retrained model. Do not do it inside the runtime alone. -5. **Change report wording:** `report.ts` templates; update `test/report.test.ts`, `test/atoms.test.ts` (late revert - line), `test/review-misc.test.ts`, and `src/devtools/ui.ts` + `test/devtools*.test.ts`. -6. **Change queue behaviour:** `decider.ts`; tests `test/budget.test.ts` (timeoutMs, expired items not computed), - `test/batch3.test.ts` and `test/review-misc.test.ts` (provider that never answers), `test/atoms.test.ts` - (provider error codes fail open with no time passing). -7. **Custom action / standing question API:** `runtime.ts` -> `runCustom`, `action`, `question`, `use`; `build.ts` - for offering; tests `test/plugins.test.ts`, `test/batch3.test.ts`, `test/review-misc.test.ts`. -8. **Write a test for this scope:** `test/helpers.ts` -> `setup({ mode, policy, script })` gives a headless - `RuntimeImpl` on a `FakeClock` with a `FakeServer` fetch, `report: "silent"` and only the fetch observer. - `defaultScript({ mutation: { diagnosis: "stale", action: "discard", p } })` answers per trigger (passive when the - action is not offered) via `choice(label, labels, p = 0.97)`, which puts `p` on the label and splits the rest - evenly. Use `ManualDecider` (`answer()` releases the oldest pending request) to control timing for budget - expiry / late-revert tests. Advance time with `clock.advance(ms)` / `clock.runAll()` and flush with `drain()`. -9. **Add a new trigger kind's controller:** implement `Controller` (`decide/exec.ts`), call `host.trigger(spec, - ctl, { hold, priority })`, and only add `revertable`/`revert` if the subject can be reverted exactly; a `revert` - on the controller extends the queue deadline by `LATE_REVERT_MS`, and `onDecision` only uses it for a late - `discard`. Adding the trigger kind itself changes model input (see 4). + in `types.ts` -> `PolicyOptions`, `docs/runtime/API.md`, and `test/policy.test.ts`, `test/budget.test.ts`, + `test/fetch.test.ts` (fail-open tests expect the 300 ms fallback). +2. **Change gate logic:** edit `policy.ts` -> `gate` only; keep reason strings stable (asserted in + `test/policy.test.ts`, `test/report.test.ts`, parsed by devtools). Check the sim's forcing contract (thresholds + 0.5, `requireDiagnosis: false`; `test/delivery.test.ts` "forced actions"). +3. **Change the hold decision** (`waits`, `expectedLatency`, `proceeded`/`stale`): `runtime.ts` -> `trigger`, + `onDecision`, `decider.ts`; tests `test/delivery.test.ts`, `test/atoms.test.ts`, `test/budget.test.ts`, + `test/default-mode.test.ts`. +4. **Change the delivery gate:** `runtime.ts` -> `runDelivery`, `dropFilter`, `writtenOver`, `onDropped`; channel + plumbing in `observe/fetch.ts`, `observe/xhr.ts`, `observe/messages.ts`; salience in `situation/conflicts.ts` / + `content.ts`. Salience changes alter which situations exist (sim/training data): coordinate with SIM/TRAIN. + Tests `test/delivery.test.ts`, `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts`. +5. **Change an action's mechanics:** edit its controller. Keep: throw when it cannot run; return an exact `changed` + sentence; provide `undo` only if truly reversible; end synthetic ops with `synthetic: true`. Coordinate `changed` + wording with SIM (timeline input). Tests: `test/fetch.test.ts`, `test/xhr.test.ts`, `test/atoms.test.ts`, + `test/delivery.test.ts`, `test/review-fetch.test.ts`, `test/review-xhr.test.ts`. +6. **Add a built-in action or trigger kind:** `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS` (passive first), `PASSIVE`, + `ACTION_INSTRUCTIONS`, maybe `TRIGGER_DESCRIPTIONS`, `build.ts` -> `builtinApplicable`, the controller, `LEAD` / + `NOUN` in `report.ts` and `devtools/ui.ts`. This changes model input: new freeze tag, sim + training mirrors, new + data and a retrained model (the `delivery` addition is the worked example: commit fcd1e68 + tag `situation-v2`). +7. **Change report wording:** `report.ts`; update `test/report.test.ts`, `test/atoms.test.ts`, + `test/review-misc.test.ts`, `src/devtools/ui.ts` + `test/devtools*.test.ts`. +8. **Change queue behaviour:** `decider.ts`; tests `test/budget.test.ts`, `test/batch3.test.ts`, + `test/review-misc.test.ts`, `test/atoms.test.ts`, `test/delivery.test.ts` (superseded item dropped). +9. **Custom action / standing question API:** `runtime.ts` -> `runCustom`, `action`, `question`, `use`; tests + `test/plugins.test.ts`, `test/batch3.test.ts`, `test/review-misc.test.ts`. +10. **Write a test for this scope:** `test/helpers.ts` -> `setup({ mode, policy, script })` gives a headless + `RuntimeImpl` on a `FakeClock` with a `FakeServer` fetch, `mode: "guard"` unless overridden, `report: "silent"` + and only the fetch observer. A passed `observe` object replaces the harness default wholesale (unlisted observers + fall back to the runtime defaults), so list what you need, as `test/delivery.test.ts` does: + `observe: { fetch: true, websocket: true }, extraGlobal: { WebSocket: FakeWS }` (EventSource and XHR likewise). Add + `policy: { holdWrites: true }` to test held writes (as `test/atoms.test.ts` does for every test). + `defaultScript({ delivery: { diagnosis: "stale", action: "discard" } })` answers per trigger; `ManualDecider` + (`answer()` releases the oldest pending request; `pending[i].req.trigger`) controls timing. Advance time with + `clock.advance(ms)` / `clock.flush()`. ## Tests | Test file | What it asserts (scope-relevant) | |---|---| -| `packages/runtime/test/policy.test.ts` | gate: mass split (discard 0.5 + defer 0.45 runs), mode tiers, thresholds 0.9/0.8 with exact reason text, no reason when top is passive, `requireDiagnosis`, deny/allow, pause, rate limit + sliding window, observe never holds, `setMode`, `pause/resume`, loading fails open with no record, detection threshold | -| `packages/runtime/test/report.test.ts` | intervention/detection line formats, `explain()` by action or decision id, console group contents, ×N summary at window end, `decide`/`detect`/`act`/`event` listeners | -| `packages/runtime/test/atoms.test.ts` | holds; fail-open at budget; late revert exact `changed` text, `Reverted` line and undo; refusals (superseded, same chain); an answer more than 2 s after the budget records no `Decision` (queue deadline); late `defer` only recorded; provider error codes `not_ready`/`max_tokens_exceeded`/`timeout`/`busy` fail open with no time passing; discard + undo; defer max 2 | -| `packages/runtime/test/budget.test.ts` | `holdBudget` auto values (300, 600, 800, 150, 345, fixed 50); adaptive budget from latencies; `timeoutMs` = budget + 2,000 for held writes and = budget for requests; expired queued items never computed; `max_tokens_exceeded` shrinks automatic situation budgets (queue `onError` path) | -| `packages/runtime/test/fetch.test.ts` | coalesce, block (heal), guard never runs heal, serve_cached, delay 250 ms, retry backoff 200 ms and attempts, retry not offered for streams, failure delivered, failure/request gates fail open at 300 ms, hedge | -| `packages/runtime/test/xhr.test.ts` | XHR block 503, failures detection-only, request gate hold and fail-open | -| `packages/runtime/test/review-fetch.test.ts` | coalesce never hangs (opaque, streaming), failure not held in guard mode, keepalive never held | -| `packages/runtime/test/review-hub.test.ts` | undo of a late revert restores the write exactly; a held in-place update is not visible before it applies, and `discard` really drops it | -| `packages/runtime/test/review-actions.test.ts` | error rollback offered only when the chain wrote state; other chains untouched | -| `packages/runtime/test/invariants.test.ts` | inconsistency rollback to snapshot, undo, one trigger per episode | -| `packages/runtime/test/learn.test.ts` | transition rollback restores the chain's fields (exact `changed`) | -| `packages/runtime/test/plugins.test.ts` | plugin facts/diagnoses/actions reach the model; custom action runs then passive; `ctx.builtin("discard")`; custom default heal tier; `applicable()`; standing question + `onAnswer`; vocabulary overrides | -| `packages/runtime/test/batch3.test.ts` | `ctx.builtin` obeys deny; rate-limit warning once; never-answering provider does not block; `transient` label | -| `packages/runtime/test/review-misc.test.ts` | every intervention reaches the console; rate warning once; denied heal builtin not run in guard; queue robustness; `ask()` after destroy | -| `packages/runtime/test/devtools-runtime.test.ts` | overlay undo applies a dropped write; report sentences in the overlay | -| `packages/runtime/test/smoke.test.ts` | end to end: held stale write discarded in guard mode; atoms apply synchronously when nothing is salient | -| `packages/runtime/test/review-xhr.test.ts` | sync XHR never held; an XHR the app aborts while held is never sent; XHR reused after a blocked answer shows the real state | -| `packages/runtime/test/adapters-react.test.ts`, `adapters-redux.test.ts`, `adapters-zustand.test.ts` | held async writes through adapters; `discard` drops them (no reducer/subscriber), recorded in `interventions()`; react undo | -| `packages/runtime/test/ask.test.ts` | `ask` sends a trigger-`ask` request with the single question `answer` and returns a typed answer; `decide` returns the label; `about` focuses the situation; no model -> rejects with `GenClassUnavailableError`; `timeoutMs` -> reason `timeout` | +| `packages/runtime/test/delivery.test.ts` | typeahead makes zero model calls; stale out-of-order response -> delivery `discard` drops only the stale field; hold is only latency; no hold when the model cannot answer in time; default: read-after-write, background late revert, slow model (released at budget, writes late-reverted), superseded queued decision dropped; WebSocket order + discard; EventSource custom types; XHR held before completion listeners, abort during hold; forced actions | +| `packages/runtime/test/default-mode.test.ts` | `createRuntime` / `GenClass.init` default to observe (`?genclass=guard` opts in); observe never holds or delays even with a sure model or a model that never answers; findings still reported | +| `packages/runtime/test/no-reorder.test.ts` | an always-passive model changes nothing in any mode/triage (same dispatches, order, state); `holdWrites` never reorders a store's dispatches | +| `packages/runtime/test/policy.test.ts` | gate: mass split, mode tiers, thresholds with exact reasons, `requireDiagnosis`, deny/allow, pause, rate limit, observe never holds, `setMode`, `pause/resume`, loading fails open | +| `packages/runtime/test/report.test.ts` | line formats (held discard with `holdWrites`; default -> `Reverted a stale write …` late revert), `explain()`, console groups, ×N summary, listeners | +| `packages/runtime/test/atoms.test.ts` | (all with `holdWrites: true`) holds, fail-open at budget, late revert text and undo, refusals incl. `too late to revert` recorded as a reason, user write never overtakes a held write, read-your-writes, provider error codes fail open, discard + undo, defer max 2 | +| `packages/runtime/test/budget.test.ts` | `holdBudget` values; adaptive budget; `timeoutMs` = budget + 2,000 for held writes and = budget for requests; expired items never computed; situation budget 2,400 (webgpu) | +| `packages/runtime/test/fetch.test.ts`, `xhr.test.ts`, `review-fetch.test.ts`, `review-xhr.test.ts` | request/failure/stall actions and fail-open; XHR block, sync XHR never held, abort while held | +| `packages/runtime/test/smoke.test.ts` | atoms apply synchronously; a stale response is held and its stale writes dropped in guard mode | +| `packages/runtime/test/review-hub.test.ts`, `review-actions.test.ts`, `invariants.test.ts`, `learn.test.ts` | late-revert undo; error/transition rollback; inconsistency rollback | +| `packages/runtime/test/plugins.test.ts`, `batch3.test.ts`, `review-misc.test.ts` | custom actions, `ctx.builtin` policy, standing questions, rate warning, never-answering provider | +| `packages/runtime/test/devtools-runtime.test.ts` | overlay undo; delivery intervention titles | +| `packages/runtime/test/adapters-{react,redux,zustand}.test.ts` | held writes through adapters (`holdWrites: true`); `discard` drops them | +| `packages/runtime/test/ask.test.ts` | `ask` / `decide` through the queue | ## Drift and open issues Doc-vs-code mismatches (code is authoritative): -1. `docs/runtime/CONTRACT.md` §8 says `holdBudgetMs` default 300; code default is `"auto"` (300 is only the no-data - fallback). `demos/README.md` ("held for at most `holdBudgetMs` (300 ms)") and the `demos/src/shared/settings.ts` - comment ("default: the runtime's 300 ms") repeat the stale number. -2. CONTRACT §7 retry backoff `min(200 ms · 2^attempt, 5 s)`; code `min(200 × 2^(attempt-1), 5000)` (STATUS deviation). -3. CONTRACT §7 `rollback` = "last consistent snapshot"; code does that only for `inconsistency`; transition/error - restore only the op chain's fields. The model-facing description is unchanged for all triggers. -4. CONTRACT §8 `Decision`/`ActionRecord`/`Explanation` field lists omit `tier`, `ran`, `answers`, `subjectRef`, - `candidate`, `mass`, `ActionRecord.late`, `Explanation.message`; `DecisionProvider.evaluate` omits `priority`, - `timeoutMs`. §9 `ActionDef` omits `tier`; `StandingQuestion` omits `always`. `ActionDef.risk` is unused. - (§13 does add `EvaluateRequest.subject` / `Decision.subjectRef` and `policy.requireDiagnosis`; STATUS - "Deviations" lists the rest as extra public surface.) -5. `types.ts` JSDoc vs code: `Decision.action` ("the action the model chose (highest probability)") is `run ?? top`; - `Decision.executed` ("true when `action` ran as chosen") is also true when the passive action was the top and when - the action ran but failed; `EvaluateRequest.priority` ("held writes/requests use 2, background 0") is 2 held, - `min(priority, 1)` when not held (1 for non-held mutation/request/failure/stall/inconsistency, 0 for - transition/error) and 1 for `ask`. +1. `docs/runtime/CONTRACT.md` has no `delivery` trigger, no `policy.holdWrites`, and §4 still describes salient + writes as held until a decision; §8 still says `holdBudgetMs` default 300 (code `"auto"`). The v2 contract deltas + exist only in `packages/runtime/STATUS.md` ("Contract deltas (batch 4)" and "Contract deltas (batch 5)": delivery + salience by body comparison, `NetHost.noteResponse`, `MsgHost.channel`). `docs/runtime/API.md` describes `delivery` + and `holdWrites`. + `demos/README.md` and `demos/src/shared/settings.ts` repeat "300 ms". +2. CONTRACT §7 retry backoff `min(200 ms · 2^attempt, 5 s)`; code `min(200 × 2^(attempt-1), 5000)`. +3. CONTRACT §7 `rollback` = "last consistent snapshot"; transition/error restore only the op chain's fields. +4. CONTRACT §8/§9 field lists omit `tier`, `ran`, `answers`, `candidate`, `mass`, `ActionRecord.late`, + `ActionRecord.dropped`, `Explanation.message`, `ActionDef.tier`, `StandingQuestion.always`; `ActionDef.risk` is + unused. +5. `types.ts` JSDoc vs code: `Decision.action` ("the action the model chose") is `run ?? top`; `Decision.executed` + ("true when `action` ran as chosen") is also true for a passive top and for failed actions; + `EvaluateRequest.priority` ("held writes/requests use 2, background 0") omits deliveries (2) and the + `min(priority, 1)` background rule (default-mode mutations 1). 6. CONTRACT §8 "summarised as ×N in the last minute"; code prints `(×N more in the last minute)` at window end and - only for the `"console"` sink. CONTRACT §0.5 / `packages/runtime/README.md` example lines ("Coalesced a - duplicate: …", "Flagged: …") do not match the real templates. -7. `packages/runtime/STATUS.md` and `sim/NEEDS.md` headless examples use thresholds `{ report: 0, guard: 0, heal: 0 }`; - the sim actually uses `guard`/`heal` 0.5 (`sim/src/run/rt.ts`) because 0 runs a zero-probability action. + only for the `"console"` sink. +7. `sim/NEEDS.md` headless example still uses thresholds `guard: 0`; the sim and `packages/runtime/STATUS.md` use 0.5. 8. `src/devtools/ui.ts` templates differ from `report.ts`: `NOUN.failure` "failed request" vs "request failure", - extra adjectives (`conflicting`, `excessive`), no `Reverted` lead. -9. CONTRACT §7 implies XHR parity; code never offers XHR `coalesce`/`retry`/`hedge` (STATUS deviation). -10. CONTRACT §7 calls guard-tier actions "minimal and reversible"; only `discard` (and a late revert) returns an - `undo`. `defer`, `coalesce` and `delay` have none (`Undo: not reversible` in the console group). -11. CONTRACT §8 says an `ActionRecord` is emitted "for every non-passive action that ran"; code also records failed - attempts (`ok: false`, `error`), and those consume a rate-limit slot. -12. `discard`'s undo builds a `MutationRec` with `genclass: true`, but `StoreHub.commit` writes under `m.cause` - (ambient and writer), and `StoreHub.write`/`record` never read `m.genclass`, so the re-applied write is recorded - as the original cause's write, not a GenClass op (code reading; no test asserts the writer). The comment in - `test/atoms.test.ts` ("the undo write is a GenClass write: never gated") is half right: it is never gated only - because `commit` bypasses `propose`. -13. `RuntimeImpl.setReport` JSDoc says "(devtools)", but nothing in the repo calls it; it is also absent from the - `Runtime` interface, as is `isPaused`. - -Open items (from `OPEN_TASKS.md`, `packages/runtime/STATUS.md`): - -- The published alpha takes no actions until the runtime model package is published. -- Hold-induced harm and triage sensitivity (OPEN_TASKS item 6, v0.1 model: the board demo had 9 bugs introduced in - guard mode with no interventions; search clean-run latency rose from 14 ms to 125 ms because salient writes were - held; typeahead was salient about 6 times per trial on clean runs). -- Known risk (OPEN_TASKS): slow single-thread WASM leads to more fail-open decisions. Note from code: late revert only - covers a `discard` of a held write; late request/failure decisions are never applied. -- Possible follow-ups seen in code reading (unverified at runtime): late provider answers after a runtime timeout - still feed the cache and latency samples; custom actions can hold a subject indefinitely. + extra adjectives (`conflicting`, `excessive`), and delivery is always "response" (the runtime says "message" for + push channels). The `Reverted` lead now exists in both. +9. CONTRACT §7 implies XHR parity; code never offers XHR `coalesce`/`retry`/`hedge`. +10. CONTRACT §7 calls guard-tier actions "minimal and reversible"; `defer`, `coalesce`, `delay` have no `undo`. +11. CONTRACT §8 says an `ActionRecord` is emitted "for every non-passive action that ran"; failed attempts are + recorded too and consume a rate slot. +12. `discard`'s held-write undo builds a `MutationRec` with `genclass: true`, but `StoreHub.commit` records it under + the original cause (code reading; no test asserts the writer). +13. `RuntimeImpl.setReport` JSDoc says "(devtools)", but nothing calls it; it and `isPaused` are not on `Runtime`. + +Open items (from `HANDOFF.md`, `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `docs/runtime/RESULTS.md`): + +- No situation-v2 model exists yet; until `@genclass/runtime-model@0.1.0` ships, the published alpha + (`@genclass/runtime` 0.1.0-alpha.0, default guard, no model) takes no actions, and R17-final1 (situation-v1) does + not match this runtime. SIM is generating v2 data on Azure (`training/NEEDS.md`). +- Hold-induced harm ([RESULTS.md](../../runtime/RESULTS.md) §5; rerun is OPEN_TASKS item 10) was measured with v0.1 on held store writes; v2 holds only deliveries, and the + never-worse sweep over 66 real apps changed 0/396 clean runs ([../realapps.md](../realapps.md), + [RESULTS.md](../../runtime/RESULTS.md)). Precision with a trained v2 model is unmeasured. +- Delivery salience (STATUS "SIM's v2 driver run: 45 of 65 stale deliveries had discard ≈ deliver") motivated + batch 5's body-comparison salience rules (already in the code: flow 6 step 4); SIM's further separability + proposals are in `sim/NEEDS.md` ("Situation-v2 fact proposals from the separability analysis"). Whether a trained + v2 model separates `discard` from `deliver` is unmeasured. +- Slow single-thread WASM: with `expectedLatency` over the budget nothing is held; writes rely on late revert + (≤ 2 s) and deliveries are decided too late to act. +- Code-reading follow-ups (unverified at runtime): late answers after a runtime timeout still feed the cache and + latency samples; custom actions can hold a subject indefinitely and can run after it proceeded. ## Related docs -- [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, options, kill switch, `ask`/`decide`. -- [observe-and-trace.md](observe-and-trace.md): fetch/XHR observers, request identity, ops and causality. -- [state-and-adapters.md](state-and-adapters.md): mutation pipeline, holds, defer, invariants, snapshots. -- [learn-situation-triage.md](learn-situation-triage.md): facts, triage, situation building, questions, budgets. +- [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, options, default mode, kill switch, `ask`/`decide`. +- [observe-and-trace.md](observe-and-trace.md): fetch/XHR/WebSocket/EventSource observers, request identity, ops and causality. +- [state-and-adapters.md](state-and-adapters.md): mutation pipeline, `holdWrites`, drop filter, invariants, snapshots. +- [learn-situation-triage.md](learn-situation-triage.md): facts, triage, delivery salience, situation building, questions, budgets. - [model-host.md](model-host.md): the default `DecisionProvider`, its queue, timeouts and error codes. - [devtools.md](devtools.md): overlay views, report parsing, undo button. -- [build-test-release.md](build-test-release.md): running tests on the VM. -- [../overview.md](../overview.md#4-walkthrough-a-typeahead-stale-write): trigger -> queue -> gate -> discard end to end. -- [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../training.md](../training.md). +- [build-test-release.md](build-test-release.md): running tests and CI. +- [../realapps.md](../realapps.md): the real-app corpus and the never-worse sweep. +- [HANDOFF.md](../../../HANDOFF.md), [RESULTS.md](../../runtime/RESULTS.md), [RELEASE.md](../../../RELEASE.md): live handoff, results log, release steps. +- [../overview.md](../overview.md), [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../training.md](../training.md). - [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md). -- Binding spec: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) §6–§9; human API: [../../runtime/API.md](../../runtime/API.md). +- Binding spec: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) §6–§9 (stale on delivery, see Drift 1); human API: [../../runtime/API.md](../../runtime/API.md). diff --git a/docs/agents/runtime/devtools.md b/docs/agents/runtime/devtools.md index 70361461..5c4770cb 100644 --- a/docs/agents/runtime/devtools.md +++ b/docs/agents/runtime/devtools.md @@ -2,13 +2,14 @@ > **Scope:** `packages/runtime/src/devtools/index.ts`, `packages/runtime/src/devtools/ui.ts`, `packages/runtime/src/devtools/css.ts`, `packages/runtime/UI-NEEDS.md`, `packages/runtime/test/devtools.test.ts`, `packages/runtime/test/devtools-runtime.test.ts`, `packages/runtime/test/browser/ui/*`, `packages/runtime/test/browser/ui-devtools.spec.ts` > **Read this when:** you mount or unmount the overlay in an app or demo; change what a view shows; add an option, view, chip or evidence section; change report wording, theming or CSS; touch undo or mode switching from the UI; change a public `Runtime` API, event or type that the overlay reads; update the UI test harness (mock runtime, scenario, session, page) or the overlay screenshots; review whether the overlay may ship in production (bundle size, lazy import). -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - `mountDevtools(runtime, options?)` from `@genclass/runtime/devtools` adds one `<genclass-devtools>` host element with an **open shadow root**. All UI and CSS live inside that shadow root. It returns a `DevtoolsHandle` with `open`, `close`, `toggle`, `unmount` and `element`. With no DOM or no runtime it returns a no-op handle whose `element` is `null`. The runtime is the value of `GenClass.init()` / `GenClass.runtime` (`src/index.ts`) or of `createRuntime()`; passing `GenClass.runtime` while it is still `null` gives the no-op handle. - It is **vanilla DOM** with no framework and no `innerHTML`: text is set with `textContent`, and SVG icons are built with `createElementNS` from constant markup, so it works under Trusted Types. It is a separate tsup entry, and the built bundle has **no runtime imports**: `../types.js` is imported for types only. - It uses **only the public `Runtime` API**. Every way it affects the runtime, in one place: Reads: `status`, `mode`, `decisions`, `interventions`, `history`, `explain`, `situation`, `inflight` and `on(decide | detect | act | report | event | status)`. Writes: `setMode` and `ActionRecord.undo()`, nothing else. It registers one setup-only plugin with `use()` to get the runtime's `Clock`. Its host element carries `data-genclass-ignore` (`packages/runtime/src/devtools/index.ts` → `Devtools` constructor), so `packages/runtime/src/observe/dom-user.ts` → `ignoredEvent` does not record overlay clicks or keys as user ops. It never reads `rt.ready` (reading it starts a lazy model load). +- **Mode radios:** `MODES` in `src/devtools/index.ts` labels them Observe, Guard and Heal, with tooltips "Observe (default)", "Guard (opt-in)" and "Heal (experimental)", matching the runtime default `mode: "observe"` (`src/runtime.ts` → `o.mode ?? "observe"`, commit f3636b2). If reading `rt.mode` throws, the overlay assumes `observe` (`Devtools.mode`). With the default mode and a ready model, an app sees an empty Interventions tab ("No interventions in observe mode"), and every reportable finding (diagnosis not `expected`, probability at or above `policy.thresholds.report`) appears under Detections: a non-passive model choice with a "Would have run … in <tier> mode." note (the observe-mode reason contains the word "mode"), a passive one with "The model chose …: nothing was changed.". - **Four views (tabs):** `interventions` (actions that ran), `detections` (findings GenClass did not act on), `activity` (the event log) and `now` (the live `runtime.situation()`). The collapsed state is a **pill** that shows the mode, the two counters, a model-status dot and a load progress bar. - **Card routing:** an executed non-passive decision becomes an intervention card, keyed by `ActionRecord.id`. A reportable decision that did not act becomes a detection card, keyed by decision id. When an `act` arrives for a decision that is already shown as a detection, the card moves to Interventions. Identical detections that come within 60 s of each other fold into one card marked `×N`. - **Evidence:** a card expands to show the facts, the model's answers (probability bars), the timeline, the exact situation text (`Explanation.situationText`, with a Copy button), and decision and action metadata. The data comes from `runtime.explain(id)`. When the explain buffer has dropped the entry, it falls back to the `Decision`. @@ -136,7 +137,7 @@ interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activi | intervention card | `article.card.act[data-id=<actionId>]` for an `ActionRecord`. | | detection card | `article.card.det[data-id=<decisionId>]` for a decision that was reported (`detect`) but did not run a non-passive action. | | repeat folding | Detections with the same `repeatKey` (trigger, diagnosis, action, and subject with digits normalised) within 60 s of the card's latest repeat become one card with a `×N` badge. | -| report sentence | `Report.message` from `on("report")`, e.g. `[GenClass] Prevented a stale write: <fact> <changed> (stale, 0.97; discard 0.98)`. The overlay splits it into a title and body. | +| report sentence | `Report.message` from `on("report")`, e.g. `[GenClass] Prevented a stale response: <fact> <changed> (stale, 0.97; discard 0.98)`. The overlay splits it into a title and body. | | templates | `actTitle` and `diagTitle` in `ui.ts`, used when no report sentence is known (anything recorded before mount). | | evidence | The expandable `.evd` block of a card. | | render bits | `STATUS=1`, `MODE=2`, `LISTS=4`, `EVENTS=8`, `ALL=15`. They are OR'ed into `bits` and flushed together. | @@ -187,8 +188,8 @@ interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activi | `mark()` | The brand tile SVG (gradient `#2f6cf2` → `#7b3cf0`, white trace, `#ffd166` dot). Each call gets a unique gradient id `gcm<n>` from the module counter `markN`. | | `pct(p)` | `Math.round(p*100)%`; `"–"` for `null`/non-finite. | | `dur(ms)` | `""` for negative or non-finite; see the constants table for formats. | -| `phrase(diagnosis, trigger)` | Noun from `NOUN[trigger]` (else the trigger, else `"event"`). No adjective for a missing or `expected` diagnosis. `failure` + `failing` → `"failing request"`. Adjective = `ADJ[diagnosis]` or the diagnosis with `_` → space, omitted when the noun already starts with it. | -| `actTitle(action, diagnosis, trigger)` | `` `${LEAD[action]} ${article(phrase)}` ``; `article` adds `a`/`an` except when the phrase ends in `state`. Unknown action → `Ran <action with _ → space>`. `LEAD`: `discard`/`coalesce` Prevented, `defer` Held back, `delay` Slowed down, `block` Stopped, `serve_cached`/`retry` Recovered from, `hedge` Worked around, `rollback`/`resync` Repaired. | +| `phrase(diagnosis, trigger)` | Noun from `NOUN[trigger]` (`mutation` write, `delivery` response, `request` request, `failure` failed request, `stall` slow request, and so on; else the trigger, else `"event"`). No adjective for a missing or `expected` diagnosis. `failure` + `failing` → `"failing request"`. Adjective = `ADJ[diagnosis]` or the diagnosis with `_` → space, omitted when the noun already starts with it. | +| `actTitle(action, diagnosis, trigger, late = false)` | `` `${lead} ${article(phrase)}` `` where `lead` is `"Reverted"` when `late` is true (the overlay passes `!!ActionRecord.late`), else `LEAD[action]`; `article` adds `a`/`an` except when the phrase ends in `state`. Unknown action → `Ran <action with _ → space>`. `LEAD`: `discard`/`coalesce` Prevented, `defer` Held back, `delay` Slowed down, `block` Stopped, `serve_cached`/`retry` Recovered from, `hedge` Worked around, `rollback`/`resync` Repaired. | | `diagTitle` | `cap(phrase(...))`. | | `topFact(facts)` | First fact not matching `/^This (write\|request) (comes from\|has no known cause)/`; falls back to `facts[0]`. | | `diagP(d)` | `d.diagnosisProbabilities?.[d.diagnosis] ?? d.diagnosisConfidence`. In the real runtime both are the same calibrated probability (`src/runtime.ts`). | @@ -219,7 +220,7 @@ interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activi 3. `backfill()`: 1. Calls `rt.decisions(200)`, sorts by `at`, and caches each decision in `decs`. 2. Calls `rt.interventions(200)`, sorts by `at`, and runs `addAct(a, false)` on each (no pulse). - 3. For each cached decision with `diagnosis !== "expected"` and `diagP(d) >= 0.6`, runs `addDet(d, false)`. + 3. For each cached decision with a non-empty `diagnosis`, `diagnosis !== "expected"` and `diagP(d) >= 0.6`, runs `addDet(d, false)`. 4. Runs `addEvent(e)` for each event of `rt.history(400)`. An `action`/`undo` event here marks an already backfilled card undone. ### 3. Data intake and card routing @@ -270,7 +271,7 @@ interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activi 2. Strips the `[GenClass]` prefix, a `(×N …)` suffix, the trailing `(diag, p; action p)` parenthetical, and any `Not acted on (…): …` tail. 3. Strips a trailing `changed`, because the note already shows it. 4. Splits at the first `": "` when it falls at index 3 to 63. Otherwise the whole text is the body. -4. **Title:** det cards always use `diagTitle(diagnosis, trigger)`, e.g. "Slow request" or "Unusual state change". Act cards use the report title, or `actTitle(action, diagnosis, trigger)`, e.g. "Prevented a stale write" or "Slowed down a failing request". +4. **Title:** det cards always use `diagTitle(diagnosis, trigger)`, e.g. "Slow request" or "Unusual state change". Act cards use the report title, or `actTitle(action, diagnosis, trigger)`, e.g. "Prevented a stale response" (a `delivery` discard), "Reverted a duplicate write" (a late `mutation` discard, `ActionRecord.late`) or "Slowed down a failing request". 5. **Body:** the report body, or else `topFact(d.facts)` (the first fact that is not `This write|request comes from|has no known cause…`), or else `a.subject`, or else `d.subject`. CSS clamps it to 3 lines. 6. **Chips:** - Diagnosis chip, coloured `t-<diagTone>`: `ok` for expected; `bad` for failing or inconsistent; `warn` for slow or overload; `brand` otherwise. It shows the diagnosis and `pct(diagP(d))`. @@ -361,7 +362,7 @@ interface OpRow { el: HTMLElement; x: HTMLElement; start: number } // an activi 2. `sit = rt.situation()` (no argument, so the real runtime builds a fresh `trigger: "ask"` "about now" situation each time; `src/runtime.ts` → `situation`). A throw becomes a `.note.fail` reading `situation() failed: <message>`, and then only the header and that note render. Next, `ops = safe(rt.inflight)`. `docs/runtime/CONTRACT.md` states `situation()` is side-effect free (no ids consumed, nothing recorded); the code comment on `RuntimeImpl.build` (`src/runtime.ts`) qualifies this as "apart from caching op.reads". 3. It renders, in order: - Header: `Live` or `Paused`, `state.app` or "What GenClass sees right now", and a `Copy state` button with the JSON of `sit.state`. - - Subject block: chips `trigger <sit.trigger>` and either `salient: the model would be asked` (warn) or `quiet: no model call needed` (ok), followed by `sit.subject`. + - Subject block: chips `trigger <sit.trigger>` and either `salient: the model would be asked` (warn) or `quiet: no model call needed` (ok), followed by `sit.subject` (or, when it is empty, the first line of `state.trigger`). - Facts: `sit.facts`, or else `linesOf(state.facts)`, or else `No notable facts.` - In flight (section title `In flight · N` when N > 0): from `inflight()` as `name` + `detail` (no space when `detail` starts with `?`) and a spinner with `kind · dur(now - start)`. Only when `inflight()` throws or returns `null`/`undefined` does it fall back to `state.in_flight` lines without `none` (an empty array shows `none`). - Timeline (`state.timeline`), State (`state.state`) and Stats (`state.stats` without `none`). @@ -396,7 +397,7 @@ Timing: 1. Build: `packages/runtime/tsup.config.ts` has the entry `"devtools/index": "src/devtools/index.ts"` (ESM, `target: "es2022"`, `splitting: true`, also listed in `dts.entry`). `packages/runtime/package.json` → `exports["./devtools"]` = `{ types: "./dist/devtools/index.d.ts", import: "./dist/devtools/index.js" }`; the package sets `"sideEffects": false`. 2. The entry imports only `type`s from `../types.js` plus its own `./css.js` and `./ui.js`, so `dist/devtools/index.js` is self-contained: it pulls no runtime chunk and no ONNX code. It does have module-load side effects (captures `rawRaf` / `rawSetTimeout`, module counters `instances` and `markN`, and the `D` document slot in `ui.ts`) but touches no DOM until `mountDevtools` runs. -3. Size: the README and `OPEN_TASKS.md` claim **52 KB minified / 17 KB gzip**. `tsup.config.ts` sets no `minify` option (it does set `sourcemap: true` and `treeshake: true`), so `dist/devtools/index.js` from `npm run build` is unminified and larger; the 52 KB figure presumably assumes the app's bundler minifies it (unverified). See Drift item 7 for the size of the unminified build. +3. Size: the README claims **52 KB minified / 17 KB gzip**. `tsup.config.ts` sets no `minify` option (it does set `sourcemap: true` and `treeshake: true`), so `dist/devtools/index.js` from `npm run build` is unminified and larger; the 52 KB figure presumably assumes the app's bundler minifies it (unverified). See Drift item 7 for the size of the unminified build. 4. Recommended loading (documentation only, `packages/runtime/README.md`): import lazily in development so production bundles never include it: ```ts @@ -406,7 +407,7 @@ Timing: } ``` - There is no `NODE_ENV` / `DEV` check inside the library (Drift item 8). `OPEN_TASKS.md` item 7 still lists this lazy-import documentation as to-do. + There is no `NODE_ENV` / `DEV` check inside the library (Drift item 8). `OPEN_TASKS.md` item 13 (**Docs**) now only says whether a dev-only lazy import is still needed is (unverified). 5. Mounting reads `rt.status` but never `rt.ready`. In the real runtime, reading `ready` starts a lazy model load (`src/runtime.ts` → `get ready`), so opening the overlay does not by itself download the model. 6. SSR: with no `document` (and no `options.container`), `mountDevtools` returns the no-op handle, so the call is safe in server code. Importing the module server-side is also safe because module load only reads `globalThis.requestAnimationFrame` / `setTimeout` optionally. @@ -444,7 +445,7 @@ Timing: | state paths shown | literal | 3 + `+N` | `ui.ts` → `eventText` | activity text for state events | | expanded data value | literal | 300 characters (299 + `…`) | `ui.ts` → `dataLines` | expanded activity rows | | `LEAD`, `NOUN`, `ADJ` | records | see source | `ui.ts` | title templates (`actTitle`, `diagTitle`, `phrase`) | -| `TABS`, `MODES`, `FILTERS`, `QLABEL` | arrays/records | 4 tabs; 3 modes with tooltips; 6 filter groups; `{diagnosis: "Diagnosis", action: "Action"}` | `index.ts` | labels | +| `TABS`, `MODES`, `FILTERS`, `QLABEL` | arrays/records | 4 tabs; 3 modes with tooltips ("Observe (default): never changes execution; …", "Guard (opt-in): … minimal actions (drop, defer, coalesce, delay)", "Heal (experimental): broader autonomous recovery …"); 6 filter groups; `{diagnosis: "Diagnosis", action: "Action"}` | `index.ts` | labels | | runtime: `DECISIONS_KEPT` | number | `200` | `src/runtime.ts` | size of `decisions()` / `interventions()` buffers; the explain map evicts its oldest entry when it exceeds `DECISIONS_KEPT * 2` = 400 (checked only when a decision is added) | | runtime: `historySize` | `InitOptions` (inherited by `CreateOptions`) | `500` | `src/runtime.ts` (`new EventLog(o.historySize ?? 500)`) | how far back `history()` can backfill | | runtime: `thresholds.report` | `PolicyOptions` | `0.6` | `src/decide/policy.ts` | when the runtime fires `detect` | @@ -455,7 +456,7 @@ Status strip strings (`renderStatus`): |---|---|---| | `ready` | `Model ready` | `WebGPU` or `WASM`, then `variant`, then `<mb(progress.total)> MB`, then `loaded in <dur(loadMs)>`, joined by ` · ` (only the parts that are present) | | `loading` | `Loading model` | `<loaded> / <total> MB · <pct>`, or `starting…` | -| `error` | `Model unavailable` | `observing only · <error>` | +| `error` | `Model unavailable` | `observing only · <error>`, or just `observing only` when `status.error` is unset | | `off` | `No model` | `observing only · no decisions` | The tooltip also shows `status.model`. @@ -470,6 +471,8 @@ Empty Interventions text (`renderEmpty`), checked in this order: | mode `heal` | `No interventions yet` (with the heal explanation) | | otherwise (guard) | `No interventions yet` (with the guard explanation) | +The mode comes from `Devtools.mode()`, which falls back to `observe` (the runtime default since f3636b2) when `rt.mode` throws. On a runtime created with no `mode`, the empty Interventions state is therefore `No interventions in observe mode`. + The Detections empty state is fixed: `Nothing flagged`. The Activity empty state is `Waiting for activity`. Theme tokens (`css.ts` → `LIGHT` on `.root`, `DARK` on `.root[data-theme=dark]`; there is no `@media (prefers-color-scheme)` in the sheet, the `theme` option drives `data-theme`): @@ -513,7 +516,8 @@ Animations (all disabled under `prefers-reduced-motion: reduce`): `ring` 1.5 s p - **The mode can change outside the overlay.** The `status` event updates the radios and the pill. Detection notes are refreshed only when the change came through the overlay's `setMode`, which marks det cards dirty. A console `rt.setMode()` leaves "Would have run … in X mode" notes stale until another update touches those cards (code reading). - **Arrow keys on mode radios switch the runtime mode immediately.** This is tested (`ArrowLeft` from guard calls `setMode("observe")`). Do not "fix" it without updating `devtools.test.ts` and `ui-devtools.spec.ts`. - **A failed action's body can repeat the failure.** `interventionLine` puts `(failed: …)` after `changed`. `splitReport` strips `changed` only when it is the exact suffix, so for a failed action with a live report sentence the body keeps `changed` plus `(failed: …)`, next to the `Action failed: …` note (code reading; no test). -- **`Decision.candidate`, `Decision.mass`, `ActionRecord.late`, `ModelStatus.phase`, `version` and `bytes` are not rendered.** A late revert shows as an ordinary intervention. Its title says "Reverted …" only when the live report sentence arrived. +- **Several v2 fields are not rendered.** `Decision.candidate`, `Decision.mass`, `Decision.subjectRef`, `ActionRecord.dropped`, `Situation.compact` / `budget`, and every `ModelStatus` field other than `state`, `progress`, `device`, `variant`, `model`, `loadMs` and `error` (for example `phase`, `version`, `bytes`, `fromCache`, `threads`, `warmupMs`, `worker`, `gpu`, `attempts`, `ort`) never appear in the overlay. `ActionRecord.late` is used only for the title: `card()` passes `!!a.late` to `actTitle`, so a late revert reads "Reverted …" both from the live report sentence and from the template. It has no badge or evidence row of its own. +- **Write discards are usually late reverts in situation-v2.** Since runtime batch 4 (fcd1e68) store writes are not held unless `policy.holdWrites` is set (`src/types.ts` → `PolicyOptions.holdWrites`, default false), so a `discard` of a write usually lands after the write applied (`ActionRecord.late`, title "Reverted …"). A stale response is decided earlier, at the network boundary, as a `delivery` decision (title "Prevented a stale response"). Its `ActionRecord.changed` reads `Delivered <what> and dropped the state changes it makes over newer data (<up to 3 conflicting paths>).`, and the paths actually dropped are collected in `ActionRecord.dropped` (`src/runtime.ts`, the delivery controller's `discard` branch), which the overlay does not show. Do not assume a stale-result intervention has trigger `mutation`. - **Activity decision rows show no percentage for the real runtime.** The runtime's `decision` event data is `{ id, diagnosis, action, executed }`, with no `confidence` (`src/runtime.ts`). Only the mock scenario includes `confidence`. - **CSS isolation rules:** - The stylesheet must never target `html`, `body` or `:root`. A regex test enforces this. @@ -531,7 +535,7 @@ Animations (all disabled under `prefers-reduced-motion: reduce`): `ring` 1.5 s p ## How to change it safely -The team runs builds and tests on the remote VM (see [build-test-release.md](./build-test-release.md)). The commands below are for that environment. Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the vitest commands locally. Ask the user before the Playwright UI spec ([where to run things](./build-test-release.md#where-to-run-things)). +Light local checks (`npm ci`, `tsc`, `tsup`, vitest unit tests) are fine on this machine; HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac. Ask the user before the Playwright UI spec ([where to run things](./build-test-release.md#where-to-run-things)). CI (`.github/workflows/ci.yml`, commit b435acb) runs both devtools vitest files on pushes to `main`, `runtime`, `mvp` and `mvp-v2`, on every pull request and on manual dispatch, but not the Playwright spec (its unit-test step passes `--exclude "test/browser/**"`). ### Add a mount option @@ -559,12 +563,12 @@ The team runs builds and tests on the remote VM (see [build-test-release.md](./b - the `(diag, p; action p)` tail - `Not acted on (…): …` - a `(×N …)` suffix -2. Keep `LEAD` and `NOUN` in `ui.ts` aligned with `report.ts` when you intend the same wording (the current differences are listed in Drift). +2. Keep `LEAD` and `NOUN` in `ui.ts` aligned with `report.ts` when you intend the same wording (the current differences are listed in Drift). A new `TriggerKind` in `src/types.ts` needs a `NOUN` entry in both files; without one, `phrase` falls back to the raw trigger name. 3. Update the expected titles in `devtools.test.ts` and `devtools-runtime.test.ts`. The latter's titles come from the templates, because the session runs before mount. ### Use the runtime sentence for cards recorded before mount (UI-NEEDS item 3) -In `card()`, when `msg` is undefined, fall back to `safe(() => this.rt.explain(id)?.message, undefined)` for the action id or decision id. Then update the assertion under the comment "reports emitted before mounting are not replayed" in the `devtools.test.ts` test "renders interventions, detections, status and counters from the runtime"; it currently expects the lead fact as the `.cx` body. Also re-check the title and `.cx` body expectations in `devtools-runtime.test.ts` (its first test matches the stale-write body against a regex). `MockRuntime.explain` returns `scenario.ts` explanations, which lack `message`. Add it there. +In `card()`, when `msg` is undefined, fall back to `safe(() => this.rt.explain(id)?.message, undefined)` for the action id or decision id. Then update the assertion under the comment "reports emitted before mounting are not replayed" in the `devtools.test.ts` test "renders interventions, detections, status and counters from the runtime"; it currently expects the lead fact as the `.cx` body. Also re-check the title and `.cx` body expectations in `devtools-runtime.test.ts` (its first test matches the body of the "Prevented a stale response" card against a regex). `MockRuntime.explain` returns `scenario.ts` explanations, which lack `message`. Add it there. ### Change styling or theme @@ -586,7 +590,7 @@ In `card()`, when `msg` is undefined, fall back to `safe(() => this.rt.explain(i ### Change the Now view -1. Edit `renderNow` in `index.ts`. Section sources are `Situation` fields (`trigger`, `salient`, `subject`, `facts`, `actions`) and `Situation.state` keys from `src/situation/serialize.ts` (`app`, `trigger`, `facts`, `in_flight`, `timeline`, `state`, `stats`). If those keys are renamed (a SIM-coordinated, `situation-v1`-relevant change, see [learn-situation-triage.md](./learn-situation-triage.md)), update `renderNow` and `scenario.ts`'s scripted `sit.state`. +1. Edit `renderNow` in `index.ts`. Section sources are `Situation` fields (`trigger`, `salient`, `subject`, `facts`, `actions`) and `Situation.state` keys from `src/situation/serialize.ts` (`app`, `trigger`, `facts`, `in_flight`, `timeline`, `state`, `stats`). If those keys are renamed (a SIM-coordinated change to the situation format, which is frozen at tag `situation-v2`; see [learn-situation-triage.md](./learn-situation-triage.md)), update `renderNow` and `scenario.ts`'s scripted `sit.state`. 2. Keep the gating: Now polls `situation()` only when open, on the Now tab, not paused and not dead. 3. Tests: "renders the Now view from runtime.situation() and reports failures" (`devtools.test.ts`) and "renders runtime.situation() in the Now view" (`devtools-runtime.test.ts`). @@ -599,19 +603,21 @@ In `card()`, when `msg` is undefined, fall back to `safe(() => this.rt.explain(i `MockRuntime implements Runtime`, but test files are not type-checked (`packages/runtime/tsconfig.json` has `include: ["src"]`). Update `mock-runtime.ts` and `demos/src/dev/runtime-shim/*` by hand, then run both devtools vitest files. -### Commands (on the VM, from `packages/runtime`) +### Commands (from `packages/runtime`) - Unit and integration: `npx vitest run test/devtools.test.ts test/devtools-runtime.test.ts`. Also run `test/dom.test.ts` if you touch the ignore attribute, and `test/adapters-*.test.ts` if you touch `mock-runtime.ts`. Plain `npm test` (`vitest run`, `include: ["test/**/*.test.ts"]`, `exclude: ["test/browser/**"]`) runs all of them. - Browser: from the repo root, `npx playwright test --config packages/runtime/test/browser/ui/playwright.config.ts`. `npm run test:browser` also picks up `ui-devtools.spec.ts`, because the main `test/browser/playwright.config.ts` matches every `*.spec.ts`. ## Tests +`npx vitest run test/devtools.test.ts test/devtools-runtime.test.ts` (from `packages/runtime`) passes on mvp-v2 at b435acb: 2 files, 27 tests (20 in `devtools.test.ts`: 4 mount, 12 feeds, 4 controls; 7 in `devtools-runtime.test.ts`), run 2026-10-08. The Playwright spec was not run. + | Test file | What it asserts | |---|---| | `test/devtools.test.ts`, "devtools: mount" | Host tag, parent and open shadow root. `data-genclass-ignore` is set. One listener each for `event` and `act` (the only two counted at mount) and one plugin. No `<style>`/`<link>` or stylesheet added to the document. Unmount removes the host, all 6 listeners and the plugin, `element` becomes `null`, and a second unmount is safe. Styles live only in the shadow root, and `CSS` never targets `html`, `body` or `:root`. The host is `fixed` with z-index `2147483646`. A null runtime gives a no-op handle. `theme: "dark"` and `position: "top-left"` give `data-theme`, `data-pos` and `top`/`left` of `16px`. | | `test/devtools.test.ts`, "devtools: feeds" | Counters (3 and 3), status "Model ready" with WebGPU. Intervention order `a3, a2, a1` and template titles. The body is the lead fact (pre-mount reports are not replayed). The diagnosis chip shows `stale 97%`. Undo is shown for discard and hidden for coalesce. Detection titles and "Would have run hedge in heal mode.". Activity pairing (row count = events − min(starts, ends)), `2001.82 s`, `#3`, an in-flight spinner, `← #n` on state rows, group and text filters, row expansion (`value: 3`, `op: #17`). A typing-burst re-emit updates a single row. Evidence content equals `explain("a1")` (facts, situation text, top answers, deny hint) and collapses. Undo calls `undo` once and shows Undone. A throwing undo shows `Undo failed: store gone`. A live act pulses the pill (`pa`), updates the counter and `aria-label`, and a later report sentence replaces the body minus `changed`. Detections fold ×3 with the passive note. An executed non-passive decision never becomes a detection. The 200-card cap holds while the panel is closed (newest `a210`, oldest `a11`). The policy-held note text. Pause shows `Feed paused · 1 new` while counters stay correct, and resume renders. Clear empties everything. The Now view comes from `situation()`, and a throw shows `situation() failed`. | | `test/devtools.test.ts`, "devtools: controls" | A click on the heal radio records `calls.setMode` = `["heal"]` and updates the radio and pill. The would-have note switches wording with the mode when no reason is given. Keyboard: the pill is a `<button>`, focus moves to the tab, ArrowRight and End work, ArrowLeft on the mode radio calls `setMode("observe")`, Escape closes and focuses the pill, Alt+Shift+G reopens. Empty-state text by model state: "Model loading", `4.8 / 19.1 MB · 25%` with the bar at 25%, then "No interventions yet" and `WASM · q8`. | -| `test/devtools-runtime.test.ts` | Mounted after `runStoreSession()` on the real runtime. Interventions are, newest first: Prevented a stale write, Prevented a duplicate write, Prevented a duplicate request, Slowed down a failing request. `.chg` equals `ActionRecord.changed`. Undo is present for discard and absent for coalesce. Detections are: Slow request, Unusual state change, Inconsistent state, Failing request ×3, with their notes. The detection count matches the runtime's decisions. Evidence equals `explain()` (situation text contains `trigger: A write to search.results`, top labels `stale`/`discard`). Activity has more than 60 rows, `2001.82 s`, the typing burst `= "react" (2 keystrokes)`, an in-flight spinner, `model` rows and error rows. The Now subject equals `situation().subject`, and "Acme Store" appears. Undo really applies the dropped write (results 4 → 8) and records an `action`/`undo` event. A new live stale-write intervention uses the runtime's report sentence without duplication. | +| `test/devtools-runtime.test.ts` | Mounted after `runStoreSession()` on the real runtime (explicit `mode: "guard"`). Interventions are, newest first: Prevented a stale response (the typeahead `delivery` decision, situation-v2), Reverted a duplicate write (late `mutation` discard), Prevented a duplicate request, Slowed down a failing request. The stale card's body matches `/^search\.results was written \w+ by other operations since its operation/` and its chip is `stale97%`. `.chg` equals `ActionRecord.changed`. Undo is present for discard and absent for coalesce. Detections are: Slow request, Unusual state change, Inconsistent state, Failing request ×3, with their notes. The detection count matches the runtime's decisions. Evidence equals `explain()` (situation text contains `trigger: The response to GET /api/search?q=rea`, top labels `stale`/`discard`). Activity has more than 60 rows, `2001.82 s`, the typing burst `= "react" (2 keystrokes)`, an in-flight spinner, `model` rows and error rows. The Now subject equals `situation().subject`, and "Acme Store" appears. Undo really applies the dropped write (results 4 → 8) and records an `action`/`undo` event. A new live stale intervention uses the runtime's report sentence (`[GenClass] Prevented a stale response: …`) without duplication. | | `test/browser/ui-devtools.spec.ts` | Real Chromium: style isolation (stylesheet count, app CTA background and body font unchanged; shadow root and ignore attribute present; only 2 `<style>` tags, fonts and app). Real keyboard flow (Enter on the pill, ArrowRight, End, ArrowRight on radios gives `heal`, Escape, Alt+Shift+G). Undo marks the card. Screenshots for light and dark: `pill`, `overlay`, `interventions`, `evidence`, `evidence-answers`, `detections`, `activity`, `now`, `loading`. They are written only, never compared. | | `test/dom.test.ts` (outside the scope, related) | Events inside `[data-genclass-ignore]`, including inside a `genclass-devtools` shadow root, are not recorded as user actions. | @@ -619,8 +625,8 @@ Harness details: - **`MockRuntime`** (`mock-runtime.ts`): - Test controls: `emitTo(type, v)`, `setStatus(s)` (emits `status`), `event(kind, name, {t, op, cause, data})` (emits `event`; `seq` auto-increments, `t` defaults to `clock.t`), `decision(d)` (emits `decide`, plus `detect` when `diagnosis !== "expected"` and `diagnosisProbabilities[diagnosis] ?? diagnosisConfidence` ≥ 0.6), `act(a)`, `report(r)`, `listenerCount(type)`. - - Inspectable fields: `plugins`, `calls.{setMode, situation, explain, sets}`, `explanations` (Map), `sit`, `ops`, `events`, `decs`, `acts`, `mode` (starts `"guard"`), `status` (starts `{ state: "off" }`). - - Runtime API behaviour: `situation()` throws `no situation scripted` while `sit` is `null` (how the "situation() failed" test is driven). `explain(id)` returns `explanations.get(id) ?? null`. `history(n=500)`, `decisions(n=200)`, `interventions(n=200)` slice the recorded arrays. `use()` calls `setup` synchronously with a `PluginApi` whose `clock` is the `MockClock`, and its disposer removes the plugin. `setMode` records and sets `mode` but does **not** emit `status` (unlike the real runtime). `ask()` rejects (`mock runtime: no model`), `decide()` resolves the first option, `holdBudgetMs()` → `300`, `situationBudget()` → `3200`, `destroy()` clears listeners. + - Inspectable fields: `plugins`, `calls.{setMode, situation, explain, sets}`, `explanations` (Map), `sit`, `ops`, `events`, `decs`, `acts`, `mode` (starts `"guard"`, unlike the real runtime's `observe` default, so the mock-based tests keep exercising guard wording), `status` (starts `{ state: "off" }`). + - Runtime API behaviour: `situation()` throws `no situation scripted` while `sit` is `null` (how the "situation() failed" test is driven). `explain(id)` returns `explanations.get(id) ?? null`. `history(n=500)`, `decisions(n=200)`, `interventions(n=200)` slice the recorded arrays. `use()` calls `setup` synchronously with a `PluginApi` whose `clock` is the `MockClock`, and its disposer removes the plugin. `setMode` records and sets `mode` but does **not** emit `status` (unlike the real runtime). `ask()` rejects (`mock runtime: no model`), `decide()` resolves the first option, `holdBudgetMs()` → `300`, `situationBudget()` → `2400` (equal to `STATE_CHAR_BUDGET` in `src/situation/serialize.ts`, the real webgpu/unknown-device default), `destroy()` clears listeners. - Store semantics for the adapter tests: `holdWrites` (hold every write made outside a synchronous `user()` handler unless `opts.hold === false`), `heldCount`, `flushHeld()` (apply in proposal order; functional updates re-run against the value at apply time), `dropHeld()` (the `discard` action: nothing applied, nobody notified), `genclassWrite(store, v)`, `subscribers(store)`. Applied writes emit a `state` event. - `MockClock`: mutable `t` (starts `0`; `now()` returns it), real `setTimeout`/`clearTimeout`, `afterTask` = `setTimeout(fn, 0)`. - `choice(probs)` returns a `ChoiceAnswer` whose `confidence` is `(k·p−1)/(k−1)` for k labels. @@ -635,14 +641,14 @@ Harness details: - Events: 48 scripted `RtEvent`s (nav, fetch op pairs with `data.kind "fetch"`, user, state with `data.paths`, decision events **with** `confidence`, action events, one `TypeError` error). `GET /api/search?q=rea` (#3) takes 2214 → 4031, i.e. the `2001.82 s` assertion is `200` + `1.82 s`. Op `#15` (`GET /api/recommendations?for=cart`, start 22100) never ends, so it shows a spinner. - The Now situation: `trigger "ask"`, `salient true`, 4 facts, `actions []`, `questions {}`, `state` with all seven `SituationParts` keys; `rt.ops` holds op `#15`. `rt.clock.t = now ?? 27_400` (so op #15 is `5.30 s` in flight). - **`runStoreSession(opts)`** (`session.ts`): - - Uses `createRuntime({ clock, global: { fetch: backend.fetch, Response, location }, decider, report: "silent", observe: OBSERVE, app: () => ({ title: "Acme Store", route }) })`. `OBSERVE` enables only `fetch` (`user`, `xhr`, `errors`, `nav`, `storage`, `perf`, `websocket`, `timers` are `false`), so user ops come only from explicit `rt.user()` calls and errors from `rt.reportError()`. + - Uses `createRuntime({ clock, global: { fetch: backend.fetch, Response, location }, decider, mode: "guard", report: "silent", observe: OBSERVE, app: () => ({ title: "Acme Store", route }) })`. `OBSERVE` sets `fetch: true` and `xhr`, `user`, `errors`, `nav`, `storage`, `perf`, `websocket`, `timers` to `false`. It does not list `eventsource`, which defaults to on, but the session's `global` object has no `EventSource`, so `installEventSource` installs nothing. User ops therefore come only from explicit `rt.user()` calls and errors from `rt.reportError()`. `mode: "guard"` is explicit since f3636b2 (the runtime default is now `observe`, which would act on nothing). - Stores (atoms): `session`, `search`, `cart`, `orders`, `status`, `recs`. - Warm-up (clock starts at `400`): `GET /api/session` and `GET /api/cart`, then 24 alternating cart add/remove ops 560 ms apart with a status poll every 4th and recommendations every 5th, so baselines, profiles and invariants are learned. - - Story: (1) 4 failing polls 2 s apart, then a held poll (`delay`); (2) a partial `POST /api/cart` response without `total` (unusual transition, broken total invariant); (3) double "Place order" 90 ms apart (`coalesce` and a duplicate write); (4) recommendations latency 9000 ms (stall → hedge, not run in guard); (5) typeahead `rea` (1820 ms) vs `react` (210 ms) (stale write → `discard`); (6) a `TypeError` reported from a `change input "Qty"` handler. + - Story: (1) 4 failing polls 2 s apart, then a held poll (`delay`); (2) a partial `POST /api/cart` response without `total` (unusual transition, broken total invariant); (3) double "Place order" 90 ms apart (`coalesce` and a duplicate write); (4) recommendations latency 9000 ms (stall → hedge, not run in guard); (5) typeahead `rea` (1820 ms) vs `react` (210 ms): the late `rea` response is a `delivery` decision (stale → `discard`, dropping its `search.results` write); (6) a `TypeError` reported from a `change input "Qty"` handler. - `SessionOptions`: `warmupOnly` (return after the warm-up; used by the `loading` page scenario), `status` (initial decider status, default `READY`), `turn` (task-boundary function, default `realTurn()`). - `Session`: `rt`, `clock` (`VirtualClock`), `backend` (knobs `statusDown`, `partialCart`, `recsLatency` default 300, `searchLatency` map with a 180 ms default, `cart`), `decider`, `stores.search`, `app.{typeSearch, placeOrder, poll}` to keep driving the app after the story (the last `devtools-runtime.test.ts` test does this). - `VirtualClock`: `setTimeout` queues by virtual time; `advance(ms)` runs due timers in `(at, id)` order and calls `settle()` after each; `settle()` runs up to 64 rounds of 4 real turns, then the queued `afterTask` hooks, until none remain. `realTurn()` uses `setImmediate` (Node) or a `MessageChannel` (browsers). - - `SessionDecider` (`DecisionProvider` test double): `judge(req)` maps `req.trigger` plus fact regexes to `[diagnosis, p, action, pa]`, e.g. `stall` → `slow 0.84 / hedge 0.71`, `transition` → `unusual 0.88 / rollback 0.64`, `inconsistency` → `inconsistent 0.9 / rollback 0.58`, stale write → `stale 0.97 / discard 0.98`. Remaining mass is spread over the other labels (62% of what is left each step, the last label takes the rest). It answers after `22 + (length of the facts joined with "\n") % 17` virtual ms (`factsOf(req).length`, a character count, not the number of facts). `READY` = `{ state: "ready", device: "webgpu", variant: "fp16", model: "genclass-runtime-0.1", loadMs: 1240, progress: 24_740_000 / 24_740_000 }`. + - `SessionDecider` (`DecisionProvider` test double): `judge(req)` maps `req.trigger` plus fact regexes to `[diagnosis, p, action, pa]`, e.g. `stall` → `slow 0.84 / hedge 0.71`, `transition` → `unusual 0.88 / rollback 0.64`, `inconsistency` → `inconsistent 0.9 / rollback 0.58`, stale `mutation` or `delivery` (facts match `by other operations since` and `later user action`) → `stale 0.97 / discard 0.98`; a `delivery` otherwise → `expected`. Remaining mass is spread over the other labels (62% of what is left each step, the last label takes the rest). It answers after `22 + (length of the facts joined with "\n") % 17` virtual ms (`factsOf(req).length`, a character count, not the number of facts). `READY` = `{ state: "ready", device: "webgpu", variant: "fp16", model: "genclass-runtime-0.1", loadMs: 1240, progress: { loaded: 24_740_000, total: 24_740_000 } }`. - **`page.ts`**: `window.__gc = { start(opts), rt?, dt?, undos }`. `start({ scenario?, mode?, status?, ...DevtoolsOptions })` unmounts the previous overlay, destroys the previous runtime, re-injects `<style id="app-css">` and the Acme HTML, builds the runtime, applies `mode` via `setMode`, and calls `mountDevtools(rt, opts)` (the whole options object is passed through). Scenarios: | `scenario` | Runtime | @@ -653,7 +659,7 @@ Harness details: | `empty` | `MockRuntime` with `clock.t = 2600` and one `GET /api/session` op (start 1130, end 1342) | `status` is applied only to the mock scenarios (`mock`, `empty`). The app CSS defines `--bg`, `--line`, `--fg`, `--fg2` (plus `--card`, `--accent`) on `:root`, the same names as overlay tokens (see Invariants). -- **`ui-devtools.spec.ts`**: `beforeAll` bundles `page.ts` with esbuild (`iife`, `es2022`, external `onnxruntime-web` and `onnxruntime-web/webgpu`) into one HTML string with Inter and JetBrains Mono woff2 inlined from `<repo>/node_modules/@fontsource-variable/*`. Its `start()` emulates the colour scheme **and `reducedMotion: "reduce"`**, waits for both fonts and two animation frames. `shotPanel` clips the host's box plus 28 px (24 px for the pill). Screenshot sources: `pill` (live, collapsed), `overlay` (live, full 1280×800 viewport), `interventions`, `evidence` and `evidence-answers` (live, stale-write card), `detections`, `activity`, `now` (live), `loading` (loading scenario). The keyboard and undo tests use `scenario: "mock"`. +- **`ui-devtools.spec.ts`**: `beforeAll` bundles `page.ts` with esbuild (`iife`, `es2022`, external `onnxruntime-web` and `onnxruntime-web/webgpu`) into one HTML string with Inter and JetBrains Mono woff2 inlined from `<repo>/node_modules/@fontsource-variable/*`. Its `start()` emulates the colour scheme **and `reducedMotion: "reduce"`**, waits for both fonts and two animation frames. `shotPanel` clips the host's box plus 28 px (24 px for the pill). Screenshot sources: `pill` (live, collapsed), `overlay` (live, full 1280×800 viewport), `interventions`, `evidence` and `evidence-answers` (live, stale card: in situation-v2 the "Prevented a stale response" delivery card; the tracked PNGs were last committed in a53dd38, before batch 4, so they still show the old stale-write card: Drift 17), `detections`, `activity`, `now` (live), `loading` (loading scenario). The keyboard and undo tests use `scenario: "mock"`. - **UI Playwright config**: - `testDir: ".."`, `testMatch: /ui-.*\.spec\.ts$/` - Chromium, viewport 1280×800, `deviceScaleFactor: 2` @@ -664,20 +670,23 @@ Harness details: | # | Item | Docs say | Code says | |---|---|---|---| -| 1 | DOM observer ignoring the overlay | `UI-NEEDS.md` lists it under **Open** (item 1) | Done. `src/observe/dom-user.ts` → `ignoredEvent` / `insideIgnored` checks `composedPath()[0]` and `target` across shadow roots. Tested in `test/dom.test.ts`. `STATUS.md` ("For UI") agrees it is done. | +| 1 | DOM observer ignoring the overlay | `UI-NEEDS.md` lists it under **Open** (item 1) | Done. `src/observe/dom-user.ts` → `ignoredEvent` / `insideIgnored` checks `composedPath()[0]` and `target` across shadow roots. Tested in `test/dom.test.ts`. (The rewritten `STATUS.md` "For UI" section no longer mentions it; it now notes that synthetic events need `observe.untrustedEvents: true`, which does not affect the ignore check.) | | 2 | `react-dom` devDependency | `UI-NEEDS.md` item 2 (Open). `packages/runtime/STATUS.md` "Open issues": "`react-dom` is not a devDependency" | `packages/runtime/package.json` devDependencies include `react-dom ^19.3.0` and `@types/react-dom ^19.0.0`. | | 3 | `Explanation.message` (UI-NEEDS item 3) | "Nice to have"; pre-mount items fall back to templates | CORE has implemented it (`src/types.ts` → `Explanation.message`, `src/runtime.ts` → `explain`). The **overlay still ignores it**: `card()` reads only `msgs` from `on("report")`. This is open UI work (recipe above). | -| 4 | Mock needs budget methods | `STATUS.md`: mock-runtime "needs `holdBudgetMs()` and `situationBudget()`" | Present in `MockRuntime` (return `300` and `3200`). | +| 4 | Mock budget methods | The old `STATUS.md` (654d822) said mock-runtime "needs `holdBudgetMs()` and `situationBudget()`"; the current `STATUS.md` "For UI" says batch 4's devtools items (NOUN `delivery`, "Reverted" for late reverts, mock budget) were done by the lead | Resolved: `MockRuntime` returns `300` and `2400` (the v2 default budget; it returned `3200` at 654d822). No open drift; kept for agents reading older notes. | | 5 | Ownership | `docs/runtime/CONTRACT.md` layout table: `src/devtools/` "owner: CORE" | The same CONTRACT's later rule and `UI-NEEDS.md` say UI owns `src/devtools/**`. | -| 6 | Templates "mirror" `report.ts` | `ui.ts` comment: templates "mirror the runtime's console wording" | Differences: failure noun `failed request` (UI) vs `request failure` (report). UI-only adjectives `conflict→conflicting` and `overload→excessive`, plus the special case `failing request`. An unknown action is `Ran <action>` (UI) vs `Handled` (report). UI ignores `late` (report: `Reverted`). Detection cards use `diagTitle` ("Slow request"), never the report's "Flagged …". | -| 7 | Bundle size | `packages/runtime/README.md`: "52 KB minified, 17 KB gzip"; `OPEN_TASKS.md` item 7: "52 KB min / 17 KB gz" | The 52/17 KB figures are unverified: `tsup.config.ts` sets no `minify` and no minified build is checked in. A `tsup` build of 654d822 gives an unminified `dist/devtools/index.js` of 69,191 bytes, 20,276 bytes gzip (about 20.3 KB). | -| 8 | "dev-only lazy import" | `OPEN_TASKS.md` item 7 (**Docs**, under "Next") lists "dev-only lazy import of the devtools" as still to do | The README already shows `if (import.meta.env.DEV) { … await import("@genclass/runtime/devtools") … }`. It is a documentation item only: there is no code-level dev guard in the library. | +| 6 | Templates "mirror" `report.ts` | `ui.ts` comment: templates "mirror the runtime's console wording" | Differences: failure noun `failed request` (UI) vs `request failure` (report). UI-only adjectives `conflict→conflicting` and `overload→excessive`, plus the special case `failing request`. An unknown action is `Ran <action>` (UI) vs `Handled` (report). Both now use `Reverted` for a late revert. `delivery` noun: UI always `response`; report uses `message` when the subject does not start with `response` (WebSocket / EventSource deliveries, `src/decide/report.ts` → `noun`), so a pre-mount WebSocket card reads "… stale response" where the console says "… stale message". Detection cards use `diagTitle` ("Slow request"), never the report's "Flagged …". | +| 7 | Bundle size | `packages/runtime/README.md`: "52 KB minified, 17 KB gzip" (`OPEN_TASKS.md` no longer quotes a size) | The 52/17 KB figures are unverified: `tsup.config.ts` sets no `minify` and no minified build is checked in. The `tsup` build in the working tree on 2026-10-08 (mvp-v2) gives an unminified `dist/devtools/index.js` of 69,260 bytes, 20,310 bytes gzip (about 20.3 KB); 654d822 gave 69,191 / 20,276. | +| 8 | "dev-only lazy import" | `OPEN_TASKS.md` item 13 (**Docs**, under "Next") questions whether a dev-only lazy import is still needed, marking it (unverified) | The README already shows `if (import.meta.env.DEV) { … await import("@genclass/runtime/devtools") … }`. It is a documentation item only: there is no code-level dev guard in the library. | | 9 | Folding "like the console's rate limiting" | comment in `addDet` | Sliding window (latest repeat) vs the `Reporter`'s fixed 60 s window from the first report. | | 10 | Detection threshold | Runtime uses `policy.thresholds.report` (default 0.6, configurable) | Overlay backfill hard-codes `0.6`. | | 11 | `scenario.ts` data shapes | `Situation` requires `compact` and `budget`; `Explanation` requires `message` (`src/types.ts`) | The scripted `sit` omits `compact`/`budget`, and the scripted explanations omit `message`. This compiles only because tests are not type-checked. | | 12 | Font dependency of the UI spec | n/a | `ui-devtools.spec.ts` reads `node_modules/@fontsource-variable/{inter,jetbrains-mono}`, which are declared only in `demos/package.json` and resolve through workspace hoisting (the same class of issue as UI-NEEDS item 2). | | 13 | "README screenshots" | `ui-devtools.spec.ts` header comment ("the README screenshots") and `session.ts` header comment ("the README screenshots") | No README or doc in the repo references `test/browser/ui/screenshots/*.png`: `git grep "screenshots/"` finds only the spec's own header comment plus unrelated `demos/` and `extension/` paths, and no file names `pill-light`, `overlay-light` or `interventions-light`. The 18 PNGs are tracked but unused by docs. | | 14 | Mock vs real `setMode` | `index.ts` → `subscribe` comment: "setMode() is announced as a status change too" | True for `RuntimeImpl.setMode` (fires `status` and a `status` report). `MockRuntime.setMode` emits nothing, so unit tests cover the overlay's own `renderMode` path, not the `on("status")` path for mode changes. | +| 15 | Default mode | `docs/runtime/CONTRACT.md` §13 and `docs/runtime/API.md` (updated in f3636b2) say observe is the default | Code agrees: `src/runtime.ts` → `o.mode ?? "observe"`, `MODES` tooltips, `Devtools.mode` fallback. Only the test doubles still start in guard on purpose: `MockRuntime.mode = "guard"` and `runStoreSession` passes `mode: "guard"`. Older text elsewhere (e.g. the published 0.1.0-alpha.0, whose default is guard) still describes guard as the default. | +| 16 | Guard empty-state wording | `renderEmpty` guard text: "minimal, reversible actions" | The guard tooltip now lists "drop, defer, coalesce, delay"; `coalesce` and `delay` have no `undo` (the Undo button is absent on those cards), so "reversible" is not true of every guard action. Wording only. | +| 17 | Screenshots after batch 4 | `ui-devtools.spec.ts` writes 18 PNGs | Tracked PNGs were last committed in a53dd38 (before fcd1e68, batch 4), so `interventions`/`evidence` images show "Prevented a stale write", not the current "Prevented a stale response". The spec was not re-run on mvp-v2 (Playwright needs the user's go-ahead). | Status of every `UI-NEEDS.md` item, verified against the code: @@ -697,6 +706,8 @@ Open UI behaviours found by code reading (no tests): ## Related docs +- [HANDOFF.md](../../../HANDOFF.md): the live handoff (current state and next steps) +- [../realapps.md](../realapps.md): the real-app corpus harness - [public-api-and-lifecycle.md](./public-api-and-lifecycle.md): `Runtime` API, `on()` events, `explain`, `situation`, `setMode`, `use()` - [observe-and-trace.md](./observe-and-trace.md): `RtEvent`, `EventLog` (`touch` for typing bursts), the DOM user observer and `data-genclass-ignore`, the timers observer - [decide-policy-actions.md](./decide-policy-actions.md): `Decision`, `ActionRecord.undo`, report sentences (`src/decide/report.ts`), thresholds, tiers diff --git a/docs/agents/runtime/learn-situation-triage.md b/docs/agents/runtime/learn-situation-triage.md index baad7fa4..f57155a1 100644 --- a/docs/agents/runtime/learn-situation-triage.md +++ b/docs/agents/runtime/learn-situation-triage.md @@ -1,101 +1,126 @@ -# @genclass/runtime: baselines, profiles, facts, triggers, triage and situation serialisation - -> **Scope:** `packages/runtime/src/learn/baselines.ts`, `packages/runtime/src/learn/profiles.ts`, -> `packages/runtime/src/situation/{build,facts,describe,env,questions,serialize}.ts`, the triage code in -> `packages/runtime/src/runtime.ts` (`RuntimeImpl.trigger`, `RuntimeImpl.settled`, `RuntimeImpl.situationBudget`, -> `RuntimeImpl.makeEnv`) and the text helpers they use in `packages/runtime/src/util.ts` and -> `packages/runtime/src/state/fields.ts` (`changeText`). Triage/salience lives only in `situation/facts.ts` -> (`neutral` flags), `situation/build.ts` (`salient`, `forced`) and `runtime.ts` -> `RuntimeImpl.trigger`; other -> hits for "salient" in `adapters/`, `observe/fetch.ts` and `devtools/index.ts` are comments or display. -> **Read this when:** you change any text the model reads (fact wording, timeline/state/stats lines, questions, -> action descriptions, diagnosis labels), the triage rule (what is salient), the situation budget or section limits, -> redaction, the latency/error/rate baselines, or transition profiles; or when you need to know why a trigger did or -> did not reach the model. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +# @genclass/runtime: baselines, profiles, cadence, facts, triggers, triage and situation serialisation + +> **Scope:** `packages/runtime/src/learn/{baselines,profiles,cadence}.ts`, +> `packages/runtime/src/situation/{build,facts,conflicts,content,evidence,describe,env,questions,serialize}.ts`, the +> triage and delivery-gate code in `packages/runtime/src/runtime.ts` (`RuntimeImpl.trigger`, `RuntimeImpl.runDelivery`, +> `RuntimeImpl.observeWrite`, `RuntimeImpl.gateMutation`, `RuntimeImpl.covered`, `RuntimeImpl.settled`, +> `RuntimeImpl.situationBudget`, `RuntimeImpl.makeEnv`, `RuntimeImpl.markWrites`, `RuntimeImpl.onChannel`, +> `RuntimeImpl.noteResponse`) and the text helpers they use in `packages/runtime/src/util.ts` and +> `packages/runtime/src/state/fields.ts` (`changeText`, `stringDiff`). Triage/salience lives in `situation/facts.ts`, +> `situation/content.ts`, `situation/conflicts.ts` (`neutral` flags and conflict rules), `situation/build.ts` +> (`salient`, `forced`), `runtime.ts` -> `RuntimeImpl.trigger` (cheap pass) and `runtime.ts` -> +> `RuntimeImpl.runDelivery` (the delivery pre-filter, which decides before any fact is computed); other hits for +> "salient" in `adapters/`, `observe/` and `devtools/` are comments or display. +> **Read this when:** you change any text the model reads (fact wording, timeline/state/stats lines, questions, action +> descriptions, diagnosis labels), the triage rule (what is salient), the delivery gate, the situation budget or +> section limits, redaction, the latency/error/rate/cadence baselines, or transition profiles; or when you need to know +> why a trigger did or did not reach the model. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR -- **Every byte here is model input.** The sim (`sim/`) generates training rows by running the real - `createRuntime` from `@genclass/runtime` and recording exactly the `state`/`questions` this code produces - (`sim/src/run/rt.ts` -> `realRuntimeFactory`). `training/curriculum/rt.py` is a hand-written Python port of the same - modules. Changing wording, ordering, thresholds, budgets or formatters changes model inputs: the final-round - training data (SIM phase A) is generated from the runtime frozen at git tag `situation-v1` (commit 1a77558), and - final round 1 of R17/R32 was launched on it (`training/LOG.md`; results still "(in progress)" in - `training/EVAL.md`, no model package published yet per `OPEN_TASKS.md`). `git diff situation-v1 HEAD -- - packages/runtime/src` is empty at 654d822. -- **Baselines** (`Baselines`): per op signature (`GET /api/items/:id`), for fetch/XHR only: last 64 non-failure - latencies (nearest-rank median/p95, needs >= 5 samples), last 20 outcomes, failure streak, EWMA error rate - (alpha 0.1; never read by facts, stats or devtools: only `Baselines.snapshot()` returns it, and nothing in `src/` - calls `snapshot()`), last 128 start times (rate: starts in the last 10 s vs the usual rate), and per request - identity the EWMA gap between identical requests. -- **Transition profiles** (`Profiles`): per op signature (user ops: `user <name>`), counts over completions of the - written-field set, value kind per field, status class, write-count bucket and duration bucket. A completion is - *unusual* when its set, a field's kind, its status class or its write count was seen in < 1% of >= 20 previous - completions (duration is recorded but never checked). -- **Triggers** (`TriggerKind`): `mutation`, `request`, `failure`, `stall`, `inconsistency`, `transition`, `error`, - `ask`. Each has a `SubjectSpec` (what the situation is about) and a `SubjectRef` (structured id for the sim/tests). -- **Facts** (`computeFacts`): uniform English sentences per trigger, each with a `kind` (ranked) and a `neutral` - flag. Ordered non-neutral first, then by kind rank, stable; capped at 12 (`MAX_FACTS`). -- **Triage**: with `triage: "salient"` (default) the model is consulted only if some fact has `neutral: false`, or a - standing question with `always: true` applies, or the trigger is `ask`. Otherwise the passive action runs with no - model call and no decision record. Triage is a cost filter only; it never picks a diagnosis or an action. -- **Situation** = Jev state object with keys in fixed order `app`, `trigger`, `facts`, `in_flight`, `timeline`, - `state`, `stats` (empty arrays become the string `"none"`), plus questions `diagnosis` (always, except `ask`) and - `action` (only when > 1 action applies). -- **Budget** in characters: `STATE_CHAR_BUDGET = 3200` (full), `COMPACT_BUDGET = 1100` (compact limits), linear in - between (`sectionLimits`); `MIN_BUDGET = 500`. Over budget: drop timeline (oldest first), then state, facts (keep - >= 1), in-flight, stats; then shorten facts and the trigger. Questions are compact (bare labels) at <= 1400 chars. -- **Device sizing** ("auto"): WebGPU or unknown device 3200; WASM `1000 + round((threads - 1) * 1000 / 3)` for - 1..4 threads (1000/1333/1667/2000); scaled by 0.8 per `max_tokens_exceeded`, floor 0.5. -- **Deterministic and side-effect free**: only the injected clock is read; the only write is caching field versions - in `op.reads`. Same inputs give byte-identical situations (tested at the default 3200 in `situation.test.ts` and at - 1100 in `budget.test.ts`). -- **Model text also comes from outside this folder**: action-effect sentences, hub write summaries (`changeText`) and - observer op details reach the model through the timeline (see Invariants). +- **Every byte here is model input, and the format is frozen.** The current training format is git tag + `situation-v2` (commit 6e5e86e, "Runtime batch 5 … freeze situation-v2"). `git diff situation-v2 b435acb -- + packages/runtime/src` touches only `runtime.ts` (default mode), `types.ts` and `devtools/index.ts`; nothing in + `src/situation/`, `src/learn/`, `util.ts` or `state/fields.ts` changed after the freeze. Producers of training rows + run this exact code: the sim (`sim/src/run/rt.ts` -> `realRuntimeFactory`), the real-browser corpus + ([realapps](../realapps.md)) and the hand-written Python port `training/curriculum/rt.py` (its docstring says + "FROZEN at git tag `situation-v2`"). No situation-v2 model exists yet ([HANDOFF.md](../../../HANDOFF.md), `training/NEEDS.md`); the old + `situation-v1` tag (1a77558) and its R17 checkpoint do not match this code. Any wording/threshold/budget change + means a new tag and regenerated data. +- **Decisions moved to the network boundary (batch 4).** New trigger `delivery`: a fetch/XHR response or a + WebSocket/EventSource message is about to reach the app. Store writes are **not held by default** + (`policy.holdWrites: false`): a salient write raises a non-blocking `mutation` that is decided in the background + (late revert is the only enforcement), and writes already covered by a delivery decision raise nothing. +- **Version conflicts** (`situation/conflicts.ts`): a field's version fact is non-neutral only for a **newer-data + conflict** (value changed since op X started, written by an op that started after X, outside X's chain, not itself + a user action, and no newer request of X's signature still in flight) or a **pending local change** (a user + action's chain wrote it in the last 10 s and an op of that chain with a different signature is still in flight). + "Inputs that moved" (M5) and "same-signature op in flight" (M6) are now always neutral. +- **Delivery salience** (`RuntimeImpl.runDelivery`): predicted write set P from the op's transition profile (else what + the last completion of its signature wrote, else unknown); salient iff a P field has a newer-data conflict that the + response would actually change, or a pending local change the response would revert (F1), or text the user typed + since the request started that the response would replace (F2). The body (a clone, JSON, <= 256 KB) is read only + for candidates, waiting at most 100 ms. +- **New evidence facts (batch 5, all neutral unless stated):** F1 put-back-an-older-value (salient), F2 replace typed + text (salient), F3 response changes nothing, F5 failure scope / offline / commit ambiguity, F6 learned cadence + (`learn/cadence.ts`), F7 repeated-user-action evidence, F9 stale marks, read-your-writes (salient). +- **Baselines** (`Baselines`, unchanged): per op signature, fetch/XHR only: last 64 non-failure latencies (median/p95 + from 5 samples), last 20 outcomes, failure streak, EWMA error rate (unused), start times (rate), identity gaps. +- **Transition profiles** (`Profiles`, unchanged): unusual when write set, a field's kind, status class or write + count was seen in < 1% of >= 20 previous completions. Profiles now also feed the delivery prediction. +- **Triggers** (`TriggerKind`): `mutation`, `request`, `delivery`, `failure`, `stall`, `inconsistency`, `transition`, + `error`, `ask`. +- **Triage**: with `triage: "salient"` (default) the model is consulted only if some fact is non-neutral, a standing + question with `always: true` applies, or the trigger is `ask`; `delivery` is additionally pre-filtered by + `runDelivery`. Triage is a cost filter only. +- **Budget** in characters: `STATE_CHAR_BUDGET = 2400` (was 3200), `COMPACT_BUDGET = 1100`, linear in between; + `MIN_BUDGET = 500`. "auto": WebGPU or unknown device 2400; WASM 1000/1333/1667/2000 for 1..4+ threads; x0.8 per + `max_tokens_exceeded`, floor 0.5 (2400 -> 1920 -> 1536 -> 1229 -> 1200). +- **Deterministic and almost side-effect free**: only the injected clock is read; the only write inside fact code is + `X.reads.set(path, vStart)` (the gate itself sets `op.delivery`, marks and buffers; see Invariants). ## Files | path | role | key exports / entry points | |---|---|---| -| `packages/runtime/src/learn/baselines.ts` | online per-signature latency, outcomes, failure streak, rate; identity gaps | `Baselines` (`start(sig, t, identity?)`, `end(sig, t, latency, ok, outcome, countsAsFailure)`, `noteIdentity`, `latency`, `rate(sig, now)`, `failureCounts`, `stats`, `identity`, `snapshot`; public maps `sigs`, `ids`), `SigStats`, `LatencyBaseline`, `RateBaseline`, `IdentityStats`, `isFailureOutcome`, `outcomeLabel` | +| `packages/runtime/src/learn/baselines.ts` | online per-signature latency, outcomes, failure streak, rate; identity gaps | `Baselines` (`start`, `end`, `noteIdentity`, `latency`, `rate`, `failureCounts`, `stats`, `identity`, `snapshot`), `SigStats`, `LatencyBaseline`, `RateBaseline`, `IdentityStats`, `isFailureOutcome`, `outcomeLabel` | | `packages/runtime/src/learn/profiles.ts` | transition profiles and rarity check | `Profiles` (`check`, `add`, `get`, `toJSON`, `load`), `shapeOf`, `kindLabel`, `writesBucket`, `durBucket`, `Profile`, `Shape`, `Unusual`, `MIN_COMPLETIONS`, `RARE` | -| `packages/runtime/src/situation/env.ts` | what situation code may read from the runtime; trigger subjects | `SitEnv`, `SubjectSpec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo`, `CachedInfo`, `ChainWriteInfo` | -| `packages/runtime/src/situation/facts.ts` | fact computation per trigger, ordering | `computeFacts`, `orderFacts`, `MAX_FACTS` | -| `packages/runtime/src/situation/describe.ts` | how ops and events are phrased | `userPhrase`, `opPhrase`, `opLabel`, `statusText`, `eventLine` | -| `packages/runtime/src/situation/build.ts` | subject sentence, sections, applicable actions, questions, salience | `buildSituation`, `subjectOf`, `subjectRef`, `isTrigger` (exported, not used anywhere in `src/` or `sim/src`), `BuildOptions`, `BuiltSituation`, `ActionOption`; internal `subjectOp`, `involvedStores`, `involvedFields`, `inFlightLines`, `timelineLines`, `stateLines`, `statsLines`, `builtinApplicable`, `revertableChain`, `appText` | -| `packages/runtime/src/situation/questions.ts` | action catalogue, per-trigger actions, instructions, diagnosis vocabulary, question building | `BUILTIN_ACTIONS`, `BuiltinAction` (`{ name, tier, description }`), `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | -| `packages/runtime/src/situation/serialize.ts` | budget-shaped Jev state | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS`, `SituationParts`, `SectionLimits` | -| `packages/runtime/src/runtime.ts` (parts) | owns the `Baselines`/`Profiles` instances, feeds them, implements `SitEnv`, runs triage | `RuntimeImpl.trigger`, `RuntimeImpl.settled`, `RuntimeImpl.situationBudget`, `RuntimeImpl.buildOpts`, `RuntimeImpl.makeEnv`, `RuntimeImpl.startOp`/`endOp`/`registerIdentity`/`onApplied`/`watchStall`, `RuntimeImpl.situation`, `normalizeError` | -| `packages/runtime/src/util.ts` (parts) | formatters and redaction used in every sentence | `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `defaultRedact`, `isSensitiveName`, `words`, `REDACTED`, `Redactor`, `kindOf`, `normalizeFieldPath`, `requestSignature`, `normalizePath`, `isIdSegment` | -| `packages/runtime/src/state/fields.ts` (parts) | change sentences used in facts and timeline write summaries (owned by [state-and-adapters](state-and-adapters.md)) | `changeText` (re-exported by `state/hub.ts`), `elementDiff`, `addedElements`, `normalizeLeafKind` | +| `packages/runtime/src/learn/cadence.ts` (new, batch 5) | learned schedule (polling) or debounce per request signature (F6) | `Cadence` (`note`, `get`), `CadenceInfo` | +| `packages/runtime/src/situation/env.ts` | what situation code may read; trigger subjects | `SitEnv`, `SubjectSpec`, `DeliverySpec`, `ReqMeta`, `FailureInfo`, `Violation`, `ErrorInfo`, `CachedInfo`, `ChainWriteInfo`, `CreateRec`, `OutcomeRec` | +| `packages/runtime/src/situation/conflicts.ts` (new, batch 4) | predicted write set, newer-data and pending-local-change conflicts | `predictedWrites`, `matchFields`, `newerConflict`, `pendingConflict`, `conflictsOn`, `newerSameSignature`, `Predicted`, `Conflict`, `PENDING_WINDOW_MS` | +| `packages/runtime/src/situation/content.ts` (new, batch 5) | response/write content vs store (F1-F3), read-your-writes | `indexBody`, `parseJsonBody`, `locate`, `compareField`, `analyzeBody`, `contentFacts`, `pendingRevertFacts`, `createdIds`, `rywFacts`, `vhash`, `Cmp`, `ItemCmp`, `ContentResult`, `Located`, `BodyIndex`, `RYW_WINDOW_MS` | +| `packages/runtime/src/situation/evidence.ts` (new, batch 5) | F9 stale marks, F6 cadence, F5 scope/commit ambiguity, F7 repeat evidence | `markFacts`, `cadenceFact`, `scopeFacts`, `commitAmbiguity`, `failureOf`, `hostOfSig`, `repeatEvidence` | +| `packages/runtime/src/situation/facts.ts` | fact computation per trigger, ordering | `computeFacts`, `orderFacts`, `predictedText`, `MAX_FACTS`; internal `versionFacts`, `movedFacts`, `concurrencyFacts`, `mutationFacts`, `deliveryFacts`, `requestCommon`, `failureFacts`, `stallFacts`, `inconsistencyFacts`, `transitionFacts`, `errorFacts`, `askFacts`, `netOf`, `storeLists` | +| `packages/runtime/src/situation/describe.ts` | how ops and events are phrased (unchanged) | `userPhrase`, `opPhrase`, `opLabel`, `statusText`, `eventLine` | +| `packages/runtime/src/situation/build.ts` | subject sentence, sections, applicable actions, questions, salience | `buildSituation`, `subjectOf`, `subjectRef`, `relatedInFlight` (new), `isTrigger` (unused), `BuildOptions`, `BuiltSituation`, `ActionOption`; internal `subjectOp`, `involvedStores`, `involvedFields`, `builtinApplicable`, `revertableChain`, section builders | +| `packages/runtime/src/situation/questions.ts` | action catalogue, per-trigger actions and descriptions, diagnosis vocabulary | `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS` (new), `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | +| `packages/runtime/src/situation/serialize.ts` | budget-shaped Jev state | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS` | +| `packages/runtime/src/runtime.ts` (parts) | owns `Baselines`/`Profiles`/`Cadence`, feeds them, implements `SitEnv`, runs the delivery gate and triage, sets stale marks | `RuntimeImpl.trigger`, `runDelivery`, `observeWrite`, `gateMutation`, `mutationController`, `covered`, `expectedLatency`, `noteResponse`, `onChannel`, `markWrites`, `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `settled`, `situationBudget`, `buildOpts`, `makeEnv`, `startOp`/`endOp`/`onApplied`/`watchStall` | +| `packages/runtime/src/util.ts` (parts) | formatters and redaction | `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `defaultRedact`, `isSensitivePath` (new), `isSensitiveName`, `words`, `REDACTED`, `Redactor`, `kindOf`, `normalizeFieldPath`, `requestSignature`, `normalizePath`, `isIdSegment`, `parseUrl` | +| `packages/runtime/src/state/fields.ts` (parts) | change sentences ([state-and-adapters](state-and-adapters.md) owns it) | `changeText`, `stringDiff` (new), `elementDiff`, `addedElements`, `normalizeLeafKind` | +| `packages/runtime/src/state/hub.ts` (parts) | stale marks on fields | `FieldState.mark`, `StaleMark`, `StoreHub.markField` (cleared by the next write) | | `packages/runtime/src/index.ts` | public re-exports from this area | `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` | -Public types used here live in `packages/runtime/src/types.ts`: `TriggerKind`, `Fact`, `FactKind`, `Situation`, -`SituationDraft`, `SubjectRef`, `JevState`, `Question`, `Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier`. +Delivery raise sites (see [observe-and-trace](observe-and-trace.md)): `observe/fetch.ts` and `observe/xhr.ts` call +`host.deliver(...)` (-> `runDelivery` with `channel: "response"`) and `host.noteResponse(...)` for non-GET/HEAD 2xx; +`observe/messages.ts` (used by `observe/websocket.ts` and `observe/eventsource.ts`) calls `host.deliverMessage(...)` +(-> `runDelivery`); `observe/websocket.ts` and `observe/eventsource.ts` themselves call `h.channel?.("down" | "up", +...)` (-> `RuntimeImpl.onChannel`). All of these are wired in `RuntimeImpl.wsHost` / the fetch-XHR host in `runtime.ts`. + +Public types in `packages/runtime/src/types.ts`: `TriggerKind` (now with `delivery`), `Fact`, `FactKind`, `Situation`, +`SituationDraft` (now with `delivery?: { channel, predicted, conflicts }`), `SubjectRef`, `JevState`, `Question`, +`Vocabulary`, `StandingQuestion`, `ActionDef`, `Tier`, `UserAction.clicks?` (MouseEvent.detail, read by F7). ## Concepts and data structures | term | meaning (code name) | |---|---| -| op signature | `requestSignature(method, where)` in `util.ts`: upper-cased method + path with id-like segments replaced by `:id` (`normalizePath`, `isIdSegment`). It is `op.name` for fetch/XHR ops and the key of `Baselines`; `Profiles` key fetch/XHR/task/ws ops by `op.name` and user ops by `user <op.name>`. | -| request identity | `ReqMeta.identity`: hash of method + URL + semantic headers + body (computed by the fetch/XHR observers). Identities starting `uniq:` never match anything. | -| outcome | string recorded per completion in `SigStats.outcomes`: HTTP code (`"200"`, `"503"`), `"timeout"`, `"network"`, or an op status; failures are stored with a `!` prefix (`"!503"`). `"aborted"` is never recorded. Facts print the label without `!` (`outcomeLabel`), and `network` as `network error` (`outcomesText` in `facts.ts`). | -| failure (for baselines) | a completion whose `EndOpts.failure` is true: network error, timeout, HTTP 5xx, 429 or 408 (`FAILURE_STATUS` in `observe/fetch.ts`; same set in `observe/xhr.ts`). A 404 is *not* a failure. | -| chain | an op and its causal descendants (shared `root`). "Same chain" in facts = one op is an ancestor-or-self of the other (`sameChain` in `facts.ts`). | -| chain write | `ChainWrite { kind, len0, len1 }` accumulated in `OpRec.chain` (keyed by **normalised** field path) for profiled ops; `ChainWriteInfo { path, count, lastIsChain, before? }` from `SitEnv.chainWrites(op)` (real paths) for facts and rollback applicability. | -| shape | `Shape { set, fields, kinds, status, writes, dur }`: one completion's transition, built by `shapeOf`. | -| unusual | `Unusual { component: "set" or "kind" or "status" or "writes", field?, seen, of, usual, usualCount, observed }` from `Profiles.check`. | -| subject | what a situation is about: `SubjectSpec` (internal, rich) and `SubjectRef` (public, ids only; `EvaluateRequest.subject`, `Decision.subjectRef`; never serialised into `state`). | -| fact | `Fact { text: string; kind: FactKind; neutral: boolean }`. `neutral: false` = makes the situation salient. | -| salient | `BuiltSituation.salient` / `Situation.salient`: `triage === "always"` or trigger `ask` or some fact non-neutral. | -| forced | `BuiltSituation.forced`: a standing question with `always: true` is registered for this trigger; consults even when not salient. | -| draft | `SituationDraft`: structured view handed to plugin `facts()` and `ActionDef.applicable()`. | -| parts | `SituationParts { app, trigger, facts[], in_flight[], timeline[], state[], stats[] }`: unbudgeted section lines. | -| state (Jev) | `JevState` = `Record<string, unknown>` produced by `toJevState(parts, budget)`; what the model reads (the model host packs it; see [model-io-contract](../model-io-contract.md)). | -| budget | situation size in characters as measured by `stateChars` (sum over keys of `key.length + 2 + text.length + 1`, arrays joined by `"\n"`). | -| compact questions | `Situation.compact` (budget <= 1400): option descriptions are `null` (bare labels), except vocabulary overrides of <= 24 chars. | -| settled point | `RuntimeImpl.settled()`: no op started < 10 s ago is in flight and no write is pending, `settleMs` (default 60 ms) after the last write/op end. Profiles and invariants learn here. | -| storeWriters | `Map<signature, Map<store, count>>` learned in `RuntimeImpl.onApplied`: how often each signature's chain (writer + up to 8 ancestors) wrote each store. Used by facts, timeline relevance, `involvedStores`. | +| op signature | `requestSignature(method, where)` in `util.ts`: upper-cased method + path with id-like segments replaced by `:id`. It is `op.name` for fetch/XHR ops and the key of `Baselines` and `Cadence`. Message ops are named `WS message <path>`, `SSE message <path>` or `SSE <type> <path>` (`observe/messages.ts`). `Profiles` key ops by `op.name`, user ops by `user <op.name>`. | +| request identity | `ReqMeta.identity`: hash of method + URL + semantic headers + body. `uniq:` identities never match. | +| outcome | string per completion in `SigStats.outcomes`: HTTP code, `"timeout"`, `"network"`, or a status; failures stored with a `!` prefix. `"aborted"` is never recorded. | +| failure (baselines) | a completion with `EndOpts.failure`: network error, timeout, HTTP 5xx, 429, 408. A 404 is not a failure. | +| chain | an op and its causal descendants. "Same chain" = one op is ancestor-or-self of the other (`sameChain` in `facts.ts`/`content.ts`, `inChain` in `conflicts.ts`). | +| predicted write set P | `Predicted { patterns, source: "profile" or "last" or "unknown", seen, of }` from `predictedWrites(env, op)`: the normalised fields in the signature's profile `wrote` map, else `SitEnv.lastChain(op.name)` (the normalised fields the latest chain of that signature wrote; `RuntimeImpl.lastChainMap`, overwritten in `onApplied` on every write of a non-user op's chain, so a chain still running counts too, although the `env.ts` comment says "last completed"), else unknown. | +| matched fields | concrete current leaf paths matching P (`matchFields`, at most 64). | +| newer-data conflict | `Conflict { kind: "newer" }` from `newerConflict(env, X, path)`: no newer same-signature fetch/XHR in flight (`newerSameSignature`), some write since X started by an op outside X's chain that is not a user op, not a user write, and started after X; and the value changed net (`netChanged`; unknown history counts as changed). | +| pending local change | `Conflict { kind: "pending" }` from `pendingConflict(env, X, path, now)`: in the last 10 s (`PENDING_WINDOW_MS`) a chain rooted at a user op (not X's root) wrote the field, and a non-user op of that root with a name different from X's is in flight (`x` null: any name). | +| delivery spec | `DeliverySpec { op, channel, req?, status?, message?, predicted, matched, conflicts, defers, queuedAhead, body?, content? }` (`env.ts`). | +| `op.delivery` | set by `runDelivery` on the op: `{ patterns, known, salient, decided, overNewer? }`; read by `covered` (skip `mutation` triggers for covered writes) and `markWrites` (F9 "delivered over newer data"). | +| covered write | `RuntimeImpl.covered(m)`: walking up to 16 causes from `m.cause`, the first op with `op.delivery`: covered iff P was known, every changed path is in P (raw or normalised), and the delivery was not salient or was decided in time. Never covered with `triage: "always"`. | +| content comparison | `Cmp` (`content.ts` -> `compareField`): incoming vs current value by value hash, the value when X started (if the 16-entry history covers it), other chains' writes since X, `revertOf` (newest such write whose replaced value equals the incoming one), typed-text writes (`user`), and `items` (`ItemCmp`, list joined on `id`/`_id`/`uuid`/`slug`/`key`). | +| stale mark | `StaleMark { t, op, why }` on `FieldState.mark`, set by `RuntimeImpl.markWrites` / `onChannel`, cleared on the next write; stated by F9 (`markFacts`). | +| cadence | `CadenceInfo`: `periodic { period, intervals, last, next }` or `debounced { delay, matching, of }` (`Cadence.get`). | +| creates | `CreateRec { op, t, status, ids, keys }`: ids returned by recent create responses (POST or 201), parsed in the background by `noteResponse` -> `createdIds`; read by `rywFacts`. | +| outcomes buffer | `OutcomeRec { t, sig, host, ok, outcome }` for every non-aborted fetch/XHR completion in the last 30 s (max 128), for F5 scope. | +| subject | `SubjectSpec` (internal) / `SubjectRef` (public ids only; never serialised into `state`). | +| fact | `Fact { text, kind: FactKind, neutral }`. `neutral: false` = makes the situation salient. | +| salient / forced | `BuiltSituation.salient` (`triage === "always"`, trigger `ask`, or a non-neutral fact) / `forced` (an `always` standing question for this trigger). | +| draft | `SituationDraft`: structured view for plugin `facts()` and `ActionDef.applicable()`. | +| parts / state (Jev) / budget | `SituationParts` (unbudgeted lines) -> `JevState` via `toJevState(parts, budget)`; budget measured by `stateChars`. | +| compact questions | `Situation.compact` (budget <= 1400): descriptions `null` except vocabulary overrides <= 24 chars. | +| settled point | `RuntimeImpl.settled()`: profiles and invariants learn here. | +| storeWriters | `Map<signature, Map<store, count>>` learned in `onApplied` (writer + up to 8 ancestors). Used by M7, `relatedInFlight`, timeline relevance, `involvedStores`. | ### Key types (abridged) @@ -104,6 +129,7 @@ Public types used here live in `packages/runtime/src/types.ts`: `TriggerKind`, ` type SubjectSpec = | { trigger: "mutation"; m: MutationRec } | { trigger: "request"; op: OpRec; req: ReqMeta } + | DeliverySpec // { trigger: "delivery"; op; channel; predicted; matched; conflicts; ... } | { trigger: "failure"; op: OpRec; req: ReqMeta; failure: FailureInfo } | { trigger: "stall"; op: OpRec; req: ReqMeta } | { trigger: "inconsistency"; violations: Violation[] } @@ -111,946 +137,779 @@ type SubjectSpec = | { trigger: "error"; error: ErrorInfo; op: OpRec | null } | { trigger: "ask"; about: "now" | number | string }; -// packages/runtime/src/types.ts -type FactKind = "provenance" | "versions" | "inputs" | "concurrency" | "repetition" | "outcome" | "baseline" - | "invariant" | "transition" | "error" | "delta" | "cache" | "request" | "plugin"; -interface Situation { trigger; subject: string; state: JevState; questions: Record<string, Question>; - actions: string[]; salient: boolean; facts: string[]; compact: boolean; budget: number } -``` - -`BuiltSituation` (`build.ts`) = `{ spec, draft, situation, actions: ActionOption[], facts: Fact[], parts, salient, -standing, forced, subjectRef }`. `ActionOption = { name, tier, description, custom? }`. +// packages/runtime/src/situation/conflicts.ts +interface Predicted { patterns: string[]; source: "profile" | "last" | "unknown"; seen: number; of: number } +interface Conflict { path; kind: "newer" | "pending"; writer?: OpRec; pendingOp?: OpRec; count: number; t: number } -```ts -// packages/runtime/src/learn/baselines.ts -interface SigStats { sig; count; failures; lat: number[]; starts: number[]; errEwma; failStreak; - outcomes: string[]; lastSuccess?; lastFailure?; firstStart } // firstStart is set but never read -interface LatencyBaseline { n; median; p95 } -interface RateBaseline { recent: number; usual?: number } // usual = starts per 10 s -interface IdentityStats { last; n; gapEwma? } - -// packages/runtime/src/learn/profiles.ts -interface Profile { sig; n; sets: Record<setKey, count>; kinds: Record<field, Record<kind, count>>; - wrote: Record<field, count>; status: Record<cls, count>; writes: Record<bucket, count>; dur: Record<bucket, count> } -interface Shape { set: string /* sorted fields joined "," ; "" = nothing */; fields: string[]; - kinds: Record<string, string>; status: string; writes: string; dur: string } -// packages/runtime/src/trace/ops.ts (accumulated on OpRec.chain) -interface ChainWrite { kind: string; len0: number /* -1 if not array */; len1: number } - -// packages/runtime/src/situation/env.ts -interface ReqMeta { method; url; signature; identity; idempotent; replayable; bodyBytes?; transport: "fetch" | "xhr" } -interface FailureInfo { kind: "network" | "timeout" | "http"; status?; statusText?; message?; durMs } -interface Violation { id; text; fields: string[]; values: string; held: number; developer? } -interface ErrorInfo { name; message; source?; raw: unknown; key } // built by runtime.ts -> normalizeError -interface CachedInfo { t; status } - -// packages/runtime/src/situation/build.ts -interface BuildOptions { vocab?; diagnoses: Record<string, string>; customActions: ActionDef[]; - questions: StandingQuestion[]; pluginFacts: { name; fn: (d: SituationDraft) => string[] }[]; - triage: "salient" | "always"; budget?: number /* default 3200 */ } - -// packages/runtime/src/situation/serialize.ts -interface SectionLimits { facts; in_flight; timeline; state; stats; - line: { app; trigger; facts; in_flight; timeline; state; stats } } +// packages/runtime/src/learn/cadence.ts +type CadenceInfo = + | { kind: "periodic"; period: number; intervals: number; last: number; next: number } + | { kind: "debounced"; delay: number; matching: number; of: number }; ``` -`SituationDraft` (`types.ts`): `{ trigger, subject, now, op?, root?, stores, mutation?: { id, store, changes }, -request?: { method, url, signature, identity, idempotent, replayable, identicalInFlight: number[], cached }, -failure?: { kind, status?, message? }, error?: { name, message, source? }, invariants?: { id, text }[], facts: Fact[], -inFlight: Op[] }`. `SubjectRef` (`types.ts`): `{ kind, op?, mutation?, store?, paths?, cause?, error?, invariant? }`. -`ErrorInfo.key` = `normalizeError` key: `<name>:<message with every digit run -> "n", first 120 chars>`. - -### SitEnv (read-only view of the runtime) - -`SitEnv` is implemented by `RuntimeImpl.makeEnv`. Members: `now()`, `ops` (`OpRegistry`), `hub` (`StoreHub`), -`base` (`Baselines`), `profiles`, `events` (`EventLog`), `redact` (`Redactor`), `app()` (`RuntimeImpl.appInfo`: -`CreateOptions.app()` when given, else `global.document.title` and `global.location.pathname`), `cached(identity)` -(GET cache peek, `ResponseCache.peek`), `identical(identity)` (ops with that identity started in the last 10 s or -still in flight; `registerIdentity` keeps at most 12 ops per identity and 512 identities, FIFO), -`lastConsistent()`, `consistentBefore(seq)` (from the last 8 consistent snapshots), `storeWriters`, -`recentErrors()` (last 10 s; at most 64 kept), `violations()` (current learned violations), `previewInvariants?(m)` -(invariants the pending write would break), `canCoalesce(identity, selfId)` (`ResponseCache.shareable`), -`resyncable(store)`, `writable(store)`, `chainWrites(op)` (`RuntimeImpl.chainWrites`: fields written by the op's -root chain since the root started). `writtenByChain?(a, h)` is declared in `env.ts` but not implemented by -`makeEnv` and not called anywhere. +`SitEnv` (implemented by `RuntimeImpl.makeEnv`) keeps every member listed before (`now`, `ops`, `hub`, `base`, +`profiles`, `events`, `redact`, `app`, `cached`, `identical`, `lastConsistent`, `consistentBefore`, `storeWriters`, +`recentErrors`, `violations`, `previewInvariants?`, `canCoalesce`, `resyncable`, `writable`, `chainWrites`; +`writtenByChain?` is still declared and never implemented) and adds `lastChain(sig)`, `creates()`, `cadence(sig, +now)`, `outcomes()`, `online()` (`navigator.onLine` when boolean, else undefined). + +`BuiltSituation` = `{ spec, draft, situation, actions, facts, parts, salient, standing, forced, subjectRef }`. +`BuildOptions.budget` doc comment now says "default 2,400" (the code default is `STATE_CHAR_BUDGET`). ### Triggers and subjects | trigger | raised by (file -> symbol) | hold | priority | subject sentence (`subjectOf`) | `SubjectRef` | |---|---|---|---|---|---| -| `mutation` | `runtime.ts` -> `gateMutation` (a non-bypassed write, see [state-and-adapters](state-and-adapters.md)) | yes | 2 | `A write to <paths>[ from <opLabel(cause)>] is about to be applied.` (> 3 paths: first 3 + `and N more`; no paths: store name; ` from …` only when there is a cause op) | `{kind, mutation, store, paths, cause?}` | +| `delivery` | `runtime.ts` -> `runDelivery` (from fetch/XHR `host.deliver`, messages `deliverMessage`), only when its pre-filter finds it salient (or `always`) | yes | 2 | response: `The response to <opLabel> arrived and is about to be delivered; <predictedText>.`; message: `A WebSocket message <path> (#id) arrived …` / `A server-sent message …` | `{kind, op, paths?, store?}` (paths = conflicting fields, else matched P fields) | +| `mutation` | default: `observeWrite` (hub hook `observeWrite`, `holdWrites` off); opt-in: `gateMutation` (`policy.holdWrites: true`). Not raised for bypassed writes (`StoreHub.propose`: synchronous user writes unless `holdUserWrites`, GenClass writes, stores with `hold: false`), unholdable writes, or covered writes | default no / opt-in yes | default 1 / opt-in 2 | `A write to <paths>[ from <opLabel(cause)>] is about to be applied.` | `{kind, mutation, store, paths, cause?}` | | `request` | `observe/fetch.ts`, `observe/xhr.ts` request gate | yes | 2 | `<opLabel(op)> is about to be sent.` | `{kind, op}` | -| `failure` | fetch `failureGate` (hold yes, priority 2); XHR (hold no, priority 1) | fetch yes | 2 / 1 | `<opLabel> failed (<HTTP <status>, timed out, or network error>) and the app has not seen the failure yet.` | `{kind, op}` | -| `stall` | `runtime.ts` -> `watchStall` timer at `max(4 x median, 2 x p95, 500 ms)`, only with a latency baseline | no | 1 | `<opLabel> has been waiting <secs> for a response.` | `{kind, op}` | -| `inconsistency` | `runtime.ts` -> `settled` -> `raiseInconsistency` (fresh violations) | no | 1 | `The relation <text>[ (and N more)] no longer holds now that the app is settled.` | `{kind, paths, store?, invariant?}` | -| `transition` | `runtime.ts` -> `settled` -> `raiseTransition` | no | 0 | `<opLabel> completed with a state change unlike its usual ones.` | `{kind, op, paths, store?}` (paths are normalised chain keys) | -| `error` | `runtime.ts` -> `reportError` (also from the errors observer) | no | 0 | `An uncaught <name> was thrown: <message <= 120>` | `{kind, error (raw), op?}` | -| `ask` | `runtime.ts` -> `ask()` / `decide()` / `situation()` (not through `trigger()`) | n/a | 1 | `The developer asks about <opLabel(op)>` / `the store <name>` / `the app right now.` | `{kind, op?, store?}` | - -The short `Situation.subject` string (`subjectOf(...).subject`; copied to `Decision.subject` and used by reports and -devtools; not part of `state`, except indirectly through the failed-action timeline text `Tried to <action> -<subject> but it failed; the passive action ran instead.` written by `RuntimeImpl`) is: mutation `write to <paths>[ from <opLabel>]` (e.g. -`write to search.results from GET /api/search?q=rea (#6)`); request `<opLabel>`; failure `<opLabel> (HTTP 503 | -timed out | network error)`; stall `<opLabel>, waiting <secs>`; inconsistency `relation <text>[ (and N more)]`; -transition `<opLabel> state change`; error `<name>: <message <= 80>`; ask `question about <opLabel>` / -`question about <store>` / `question about the app`. With no violation the inconsistency text uses `?`; an unknown -asked op prints `an earlier operation`. - -Stall details: the fetch observer (primary request only) and the XHR observer (async only) call -`host.watchStall` at send time when `host.gated(op)`; with no latency baseline yet (< 5 samples) no timer is armed, -so the first requests of a signature can never stall. The timer fires at most once per op (`op.triggered` gets -`"stall"`), and not if the op already ended. Transitions are likewise marked once per op (`op.triggered` gets -`"transition"`). - -The *subject op* (`subjectOp` in `build.ts`) is the -cause op for `mutation`, the request op for request/failure/stall/transition, the ambient op for `error`, the asked op -for `ask`, none for `inconsistency`. *Involved stores* (`involvedStores`): mutation -> its store; inconsistency -> -stores of violated fields; transition -> stores of chain keys; error -> stores changed since the op started; -request/failure/stall -> stores that this signature's chains wrote (`storeWriters`); ask -> the asked store. Only -registered stores are kept. +| `failure` | fetch `failureGate` (hold yes, 2); XHR (hold no, 1) | fetch yes | 2 / 1 | `<opLabel> failed (<HTTP n / timed out / network error>) and the app has not seen the failure yet.` | `{kind, op}` | +| `stall` | `watchStall` timer at `max(4 x median, 2 x p95, 500 ms)` | no | 1 | `<opLabel> has been waiting <secs> for a response.` | `{kind, op}` | +| `inconsistency` | `settled` -> `raiseInconsistency` | no | 1 | `The relation <text>[ (and N more)] no longer holds now that the app is settled.` | `{kind, paths, store?, invariant?}` | +| `transition` | `settled` -> `raiseTransition` | no | 0 | `<opLabel> completed with a state change unlike its usual ones.` | `{kind, op, paths, store?}` | +| `error` | `reportError` | no | 0 | `An uncaught <name> was thrown: <message <= 120>` | `{kind, error, op?}` | +| `ask` | `ask()` / `decide()` / `situation()` | n/a | 1 | `The developer asks about …` | `{kind, op?, store?}` | + +`predictedText(s)` (`facts.ts`): `its operation usually writes <fields>` (profile) / `its operation last wrote +<fields>` (last) / `no earlier completion shows which state it writes`; for messages `messages like it usually write +…` / `… last wrote …` / `no earlier message shows which state it writes`. Fields: up to 4, `a, b and c`, then +`(+N more)`; they are normalised patterns (`board.cards.:id`). + +Short `Situation.subject`: delivery response `response to <opLabel>`; message `<WebSocket|server-sent> message +<path> (#id) <summary>`; others as before (mutation `write to <paths>[ from <opLabel>]`, request `<opLabel>`, +failure `<opLabel> (HTTP 503 | timed out | network error)`, stall `<opLabel>, waiting <secs>`, inconsistency +`relation <text>…`, transition `<opLabel> state change`, error `<name>: <message <= 80>`, ask `question about …`). + +*Subject op* (`subjectOp`): the cause op for `mutation`; the op for request/delivery/failure/stall/transition; the +ambient op for `error`; the asked op for `ask`. *Involved stores*: delivery -> stores of P patterns; others as before +(mutation its store; inconsistency stores of violated fields; transition stores of chain keys; error stores changed +since the op started; request/failure/stall stores this signature's chains wrote; ask the asked store). +*Involved fields*: delivery -> conflicting paths, then matched fields; mutation -> changed paths; inconsistency -> +violated fields; transition -> chain keys. ## How it works ### 1. Baselines (fed by op start/end) -1. `RuntimeImpl.startOp`: for `fetch`/`xhr` ops not owned by GenClass -> `Baselines.start(name, t)` (push start time, - window 128). If the op has an identity -> `registerIdentity` -> `Baselines.noteIdentity(identity, op.start)` - (skipped for `uniq:` identities): first sighting stores `{last, n: 1}`; later sightings update - `gapEwma = gap` (first) then `0.8 * gapEwma + 0.2 * gap`. At most 1024 identities (FIFO eviction). -2. `RuntimeImpl.endOp`: for `fetch`/`xhr`, not synthetic (blocked/cached/coalesced answers), not GenClass -> - `Baselines.end(sig, t, latency, ok, outcome, countsAsFailure)` with `outcome = "aborted"` or `String(code)` or the - status, `ok = status "ok" and (code not a number or < 400)`, `countsAsFailure = !!EndOpts.failure`. -3. `Baselines.end`: returns early for `"aborted"` (the signature entry is still created). Otherwise `count++`, push - outcome (`"!"` prefix when failure; keep last 20). Failure: `failures++`, `failStreak++`, `lastFailure = t`, - `errEwma = errEwma * 0.9 + 0.1`. Non-failure: `failStreak = 0`, `lastSuccess = t` only if `ok`, - `errEwma *= 0.9`, push latency (keep last 64). Latency samples therefore never include failures/timeouts. -4. Reads: `latency(sig)` -> `undefined` below 5 samples, else `{ n, median, p95 }` by nearest rank on the sorted - window (`a[min(n-1, max(0, ceil(p*n) - 1))]`). `rate(sig, now)` -> `recent` = starts with `t > now - 10000`; - `usual = older / span * 10000` only when `older >= 3` and `span = (now - 10000) - oldestOlder >= 20000`. - `failureCounts(sig)` -> `{ failed, of }` over the last <= 20 outcomes (this is what facts and stats print). - `errEwma` is returned only by `snapshot()` (as `errorRate`); no code in `src/` (devtools included) calls - `snapshot()`, so the EWMA is currently unused (reachable only through `rt.internals.base`). -5. Signatures are capped at 1000 (FIFO by insertion, not LRU). Baselines are in memory only (never persisted). +Unchanged in behaviour (verify with `git diff 654d822 b435acb -- packages/runtime/src/learn/baselines.ts`: empty). +1. `RuntimeImpl.startOp`: for fetch/XHR not owned by GenClass -> `Baselines.start(name, t)`; with an identity -> + `registerIdentity` -> `noteIdentity` (gap EWMA `0.8 * old + 0.2 * gap`, 1024 identities FIFO). **New:** the same + branch calls `Cadence.note(name, t, { user, userDelay? })` (section 3). +2. `RuntimeImpl.endOp`: for fetch/XHR, not synthetic, not GenClass -> `Baselines.end(sig, t, latency, ok, outcome, + countsAsFailure)`. **New:** every non-aborted completion is also pushed to `outcomesBuf` (`{t, sig, host: + hostOfSig(sig), ok: !failure, outcome}`, max 128, 30 s). +3. `Baselines.end`: ignores `"aborted"`; pushes the outcome (`!` prefix on failure, last 20); failure: streak++, + `lastFailure`, `errEwma = errEwma * 0.9 + 0.1`; non-failure: streak 0, `lastSuccess` only if `ok`, latency pushed + (last 64). Latency samples never include failures. +4. Reads: `latency(sig)` from 5 samples, nearest rank; `rate(sig, now)` = starts in the last 10 s, `usual` per 10 s + only when `older >= 3` and the older span >= 20 s; `failureCounts(sig)` over the last <= 20 outcomes. `errEwma` + is only returned by `snapshot()`, which nothing in `src/` calls. +5. Signatures capped at 1000 (FIFO). In memory only. ### 2. Transition profiles (fed by writes, checked at settled points) -1. `RuntimeImpl.onApplied` (every applied write with a writer op): for the writer and up to 8 ancestors whose kind is - in `PROFILED` (`fetch`, `xhr`, `user`, `task`, `ws`; not `timer`, not GenClass) and not yet profiled: - `op.chainWrites += 1` per applied mutation, and for each changed path `op.chain.set(normalizeFieldPath(path), - { kind: normalizeLeafKind(c.afterLeaf), len0: first-seen before length (-1 if not an array), len1: latest after - length })` (`normalizeLeafKind` in `state/fields.ts` returns the leaf kind, or `"undefined"` for a removed field). It also bumps - `storeWriters[sig][store]` once per signature per write (cap 1000 signatures). -2. Ops are queued for profiling (`queueProfile`, cap 2000) on `endOp` (not aborted, not synthetic) or at creation for - instant ops. -3. `RuntimeImpl.settled()` (only when not busy): for each queued ended op not yet profiled: - `shape = shapeOf(op.chain, op.chainWrites ?? 0, statusClass(op), op.end - op.start)`; - `sig = op.kind === "user" ? "user " + op.name : op.name`; `unusual = profiles.check(sig, shape)` **then** - `profiles.add(sig, shape)` (the current completion is not part of "previous N"). Flag it if `unusual.length` and - no transition was raised for this op before. -4. "One anomaly, one trigger": a flagged op is skipped when another flagged op is its descendant (the most specific - op wins; tested in `situation.test.ts` transition case). Each survivor -> `raiseTransition` -> `trigger(...)` with - `hold: false`, priority 0. -5. `statusClass(op)`: numeric code -> `"<n>xx"` (`"2xx"`, `"5xx"`); `"timeout"`/`"network"`; else `op.status ?? "ok"`. -6. `Profiles.check(sig, s)` (returns `[]` while `p.n < 20`). `rare(seen, of) = of >= 20 && seen < 0.01 * of` - (up to and including 100 completions that means "never seen"): - - `set`: the sorted written-field set is rare **and** the most common set is not `""` (an op that usually writes - nothing may start writing: not flagged). - - `kind`: for each written field with `wrote[f] >= 20`, the observed kind is rare among that field's kinds. - - `status`: the status class is rare. - - `writes`: the write-count bucket is rare, the most common bucket is not `"0"`, and no `set` anomaly was found. - - `dur` is counted but never checked. - `usual`/`usualCount` come from `top()` (highest count; ties: lexicographically first key). -7. `Profiles.add`: increments counts; caps write sets at 64 and fields at 128 (drop least frequent, ties: oldest); - at most 2000 signatures (FIFO). Persisted to `localStorage["genclass.profiles.v1"]` only with - `learn: { persist: true }` (`saveProfilesSoon` saves 5000 ms after a settled point whose profile queue was - non-empty, with at most one save pending; loaded in the constructor; `Profiles.load` only checks `sig` and `n`). -8. `kindLabel`: arrays -> `"empty array"` / `"non-empty array"` (length change deliberately ignored), objects -> - `"object"`, else the leaf kind (`"string"`, `"number"`, `"boolean"`, `"null"`, `"undefined"`, `"map"`, `"set"`, - `"date"`, ...). `normalizeFieldPath`: every segment after the store name that is id-like or contains a digit - becomes `:id` (`chat.byId.m21` -> `chat.byId.:id`). - -### 3. Trigger -> triage -> situation (`RuntimeImpl.trigger`) - -1. Not consultable (paused, destroyed, no `DecisionProvider`, or provider state not `ready`/`off`) -> run passive, - build nothing. -2. Cheap pass: `facts = computeFacts(env, spec)`; `forced = standing.some(q => q.always && q.on.includes(trigger))`. - If `triage === "salient"` and not forced and **every fact is neutral** -> passive (no model call, no `Decision`, - `lastBuilt` untouched). -3. `buildSituation(env, spec, buildOpts(), facts)` (reuses the facts, adds plugin facts, builds sections). Any throw in - steps 2-3 -> logged (debug) and passive (fail open). -4. `lastBuilt[trigger] = built` (what `rt.situation(trigger)` returns later). If `!built.salient && !built.forced` -> - passive. -5. Provider not `ready` (lazy model) -> start loading (`this.ready`), run passive. -6. Otherwise submit `{ trigger, state, questions, priority, subject }` to the decider queue; hold/deadline/gate - handling is in [decide-policy-actions](decide-policy-actions.md). - -`ask` bypasses `trigger()`: `rt.ask(q, {about})` builds an `ask` situation and **replaces** its questions with -`{ answer: q }`. `rt.situation(trigger?)` returns `lastBuilt[trigger].situation` when one exists, else builds -`{ trigger: "ask", about: "now" }` and relabels it with the requested trigger. - -### 4. `buildSituation(env, spec, o, precomputed?)` step by step - -1. `budget = o.budget ?? STATE_CHAR_BUDGET`; `L = sectionLimits(budget)`; `subjectOf`, `subjectOp`, `involvedStores`. -2. Facts: `precomputed` or `computeFacts`. Draft: `{ trigger, subject, now, stores, facts, inFlight (non-user), - op?, root?, mutation?, request? (with identicalInFlight, cached), failure?, error?, invariants? }`. -3. Plugin facts: for each plugin with `facts(draft)`, every non-empty string -> `{ text: truncate(t.trim(), 240), - kind: "plugin", neutral: true }`; a throwing plugin is ignored. -4. `facts = orderFacts(facts).slice(0, 12)` (kept in `Situation.facts`, reports and `explain()`; the budget decides - how many reach the model). -5. Actions: `TRIGGER_ACTIONS[trigger]` filtered by `builtinApplicable` (table below), descriptions from - `actionDescription`; then custom `ActionDef`s whose `on` includes the trigger, whose name is new, and whose - `applicable(draft)` is true (throw = not applicable); tier default `"heal"`. -6. Questions: standing questions for this trigger -> `extra`; `compact = budget <= 1400`; - `buildQuestions(trigger, actions, o.diagnoses, extra, compact, o.vocab)`. -7. Sections (`parts`): `app` = `appText` (`"<title> — <route>"`, either alone, or `"unknown"`), `trigger` = subject - sentence, `facts` = texts, `in_flight` = `inFlightLines`, `timeline` = `timelineLines`, `state` = `stateLines`, - `stats` = `statsLines`. -8. `state = toJevState(parts, budget)`; `salient = o.triage === "always" || trigger === "ask" || facts.some(f => - !f.neutral)`. +Unchanged rules (`profiles.ts` has no diff). `RuntimeImpl.onApplied` accumulates `op.chain` for the writer and up to +8 PROFILED ancestors (`fetch`, `xhr`, `user`, `task`, `ws`). **New in batch 4:** a change without an `afterLeaf` +(a container that became expanded, or a removed field) is skipped (`if (!c.afterLeaf) continue`), and for non-user +ops `lastChainMap.set(op.name, [...chain keys])` (cap 1000) feeds `SitEnv.lastChain` (delivery prediction, F9 +channel marks). At settled points: `shape = shapeOf(...)`, `profiles.check` then `profiles.add`; descendants win +over ancestors; `raiseTransition` with hold false, priority 0. Rarity: `of >= 20 && seen < 0.01 * of`; `set` not +flagged when the usual set is `""`; `writes` not flagged when the usual bucket is `"0"` or a set anomaly exists; +`dur` never checked. Persistence with `learn: { persist: true }` under `localStorage["genclass.profiles.v1"]`. + +The profile is now model input twice: transition facts (T1) and the delivery prediction (`predictedWrites` reads +`Profile.wrote`, `Profile.sets[""]`, `Profile.n`), stated in the delivery trigger sentence and in fact D4. + +### 3. Cadence (`learn/cadence.ts`, F6) + +1. `Cadence.note(sig, t, { user, userDelay? })` from `startOp` for fetch/XHR: `user` = the op has a user ancestor + (`ops.userOf`); `userDelay = t - user.start` only when the direct cause is a `timer` op (a debounce). + Background starts (no user): keep the last 9 (`KEEP`). User starts with a delay: keep the last 8 delays. + `userStarts` is counted but never read. +2. `Cadence.get(sig, now)`: + - **periodic**: >= 4 background starts; median interval `m >= 250 ms` (`MIN_PERIOD_MS`); >= 75% of intervals + within +-25% (`TOLERANCE`) of `m`; and the last run is no older than `3 * m` (a stopped schedule is forgotten). + Returns `{ period: m, intervals, last, next: last + m }`. + - **debounced**: >= 3 delays; median `m >= 100 ms`; >= 75% within `max(50, 0.25 * m)`. +3. At most 500 signatures (FIFO). In memory only. WebSocket/EventSource ops are not noted. + +### 4. Trigger -> triage -> situation (`RuntimeImpl.trigger`) + +1. Not consultable (paused, destroyed, no `DecisionProvider`, provider state not `ready`/`off`) -> passive. +2. Cheap pass: `facts = computeFacts(env, spec)`; `forced` = an `always` standing question for the trigger. With + `triage: "salient"`, not forced and every fact neutral -> passive (no model call, no `Decision`, `lastBuilt` + untouched). +3. `buildSituation(env, spec, buildOpts(), facts)`. Throws in 2-3 -> logged, passive (fail open). +4. `lastBuilt[trigger] = built`. Not salient and not forced -> passive. +5. Provider not `ready` -> start the lazy load, passive. +6. **Hold only when it can help (batch 4):** `waits = opts.hold && permittedActions(...).length > 0 && !paused && + expectedLatency() <= holdBudgetMs()`. `expectedLatency` = median recent provider latency (warm-up time before + any) x (1 + decisions waiting) + the one computing (at least its elapsed time); `Infinity` while `queue.stuck`. + If not waiting, passive runs now and the decision is made in the background (deadline 5 s). In the default + `observe` mode (commit f3636b2, `o.mode ?? "observe"`) no action is permitted, so nothing is ever held; salient + situations are still built and decided in the background for detection, except `delivery`: its candidates still + wait up to `BODY_WAIT_MS` (100 ms) for the body (`runDelivery` ignores the mode), then `passive()` sets + `released`, and `DeciderQueue` drops the background decision as stale (`ctl.stale = () => released`), so in + observe mode delivery situations never reach the model and produce no detections (same in guard whenever a + delivery does not wait). +7. Submit to the decider queue with `ctl.stale` (queued decisions whose subject was superseded are dropped before + the model sees them). Gate/apply: [decide-policy-actions](decide-policy-actions.md). + +`ask` bypasses `trigger()`. `rt.situation(trigger?)` returns `lastBuilt[trigger]` or an "ask about now" situation +relabelled with the trigger. + +### 5. The delivery gate (`RuntimeImpl.runDelivery`) + +Called with `{ op, channel, req?, status?, message?, queuedAhead?, body? }` and a `release` callback (lets the +response/message through). Holding is only latency; the response object is unchanged. +1. Not consultable, paused, destroyed or a GenClass op -> release. +2. `predicted = predictedWrites(env, op)`, `matched = matchFields(env, predicted.patterns)`, `conflicts = + conflictsOn(env, op, matched, now)` (per field: newer conflict, else pending conflict; newer first). +3. `op.delivery = { patterns, known: source !== "unknown", salient: newer.length > 0, decided: false }`. +4. `typed` = matched string fields that a user write (outside the op's chain) changed since the op started. + `always` = `triage: "always"` or an `always` standing question on `delivery`. +5. No conflict, nothing typed, not `always` -> release (no body read, no latency). +6. No body reader -> salient iff a newer conflict exists. +7. Else read the body (`o.body()`: fetch's buffered clone or XHR text/response; messages' data), wait at most + `BODY_WAIT_MS = 100` (clock time; on timeout decide as in 6). With a body: `spec.content = analyzeBody(env, op, + body, matched)`, then salient iff + - a newer conflict whose field the body would change (`!cmp.same`; a field not located counts as changed), or + - a pending conflict whose field the body would set back to the value the user's change replaced (F1), or + - a typed field the body would change (F2). + All conflicts equal to the body -> custom event `delivery.unchanged` (shows in the timeline as `event + delivery.unchanged`). Analysis throw -> logged, decide as in 6. +8. Not salient and not `always` -> release. Else `trigger(spec, ctl, { hold: true, priority: 2 })` (which runs the + cheap pass again on `computeFacts`). + +Controller: `passive` releases; if released over salient conflicts it records `op.delivery.overNewer` (used by F9). +`discard`: releases now and sets `op.discardMark = { protect: conflicting paths, until: now + 10 s }`; while the mark +lasts, `dropFilter` drops each later write of the op's chain to a protected field or to a field written since the op +started by a user action or a newer op (`writtenOver`); other fields of the same write apply. Effect text: +`Delivered <the response to …> and dropped the state changes it makes over newer data (<paths>).`; each drop pushes +an `action` event `dropped the write of <paths> by <opLabel> over newer data[ (its other changes applied)]`; undo +restores the dropped values. `defer`: waits for `relatedInFlight` ops (max 10 s) then runs the gate again with +`defers + 1`; text `Held <what> for <secs> until N related operation(s) finished, then decided again.`. + +### 6. `buildSituation(env, spec, o, precomputed?)` + +1. `budget = o.budget ?? STATE_CHAR_BUDGET` (2400); `L = sectionLimits(budget)`; subject, subject op, stores. +2. Facts (precomputed or `computeFacts`). Draft adds `delivery: { channel, predicted: patterns, conflicts: paths }` + and, for a delivery with `req`, the `request` block. +3. Plugin facts: neutral, kind `plugin`, 240 chars; throwing plugins ignored. +4. `orderFacts(facts).slice(0, 12)`. +5. Actions: `TRIGGER_ACTIONS[trigger]` filtered by `builtinApplicable`, descriptions from `actionDescription(name, + vocab, undefined, trigger)` (vocabulary > custom > `TRIGGER_DESCRIPTIONS[trigger]` > built-in > name); then + custom `ActionDef`s. +6. Questions (`compact = budget <= 1400`), sections, `toJevState`, `salient`. #### Applicable built-in actions (`builtinApplicable`) | trigger | always | conditional | |---|---|---| -| mutation | `apply`, `discard` | `defer` iff `m.defers < 2` | -| request | `send`, `delay`, `block` | `coalesce` iff transport fetch and `canCoalesce(identity, op.id)`; `serve_cached` iff GET and a cached response exists | +| delivery | `deliver`, `discard` | `defer` iff `defers < 2` and `relatedInFlight(env, op, matched)` is non-empty (in-flight non-user ops outside the op's chain with the same name, or whose signature's chains wrote a store of the matched fields) | +| mutation | `apply`, `discard` | `defer` iff `m.defers < 2` (with `holdWrites` off a `defer` is recorded only: nothing is held) | +| request | `send`, `delay`, `block` | `coalesce` iff fetch and `canCoalesce`; `serve_cached` iff GET and cached | | failure | `deliver` | `retry` iff replayable, `attempt < 4`, fetch; `serve_cached` iff GET, cached, fetch | -| stall | `wait` | `hedge` iff idempotent, GET, replayable, fetch; `serve_cached` iff GET, cached, fetch | -| inconsistency | `ignore` | `rollback` iff `lastConsistent()` exists and some involved store is writable; `resync` iff some involved store has a resync handler | +| stall | `wait` | `hedge` iff idempotent GET, replayable, fetch; `serve_cached` iff GET, cached, fetch | +| inconsistency | `ignore` | `rollback` iff a consistent snapshot exists and an involved store is writable; `resync` iff a store has a resync handler | | transition | `ignore` | `rollback` iff `revertableChain(op)`; `resync` iff a chain store is resyncable | -| error | `ignore` | `rollback` iff an ambient op exists and `revertableChain(op)` | +| error | `ignore` | `rollback` iff an ambient op and `revertableChain(op)` | | ask | (none) | | -`revertableChain(op)` = some `chainWrites(op)` entry has `lastIsChain`, a known `before`, and a writable store. - -#### Section builders (`build.ts`) - -- **`inFlightLines`**: in-flight ops except user ops and the subject op; sorted by (same signature as subject = 0, - same root = 1, else 2), then start time; first `L.in_flight`. Line: `<opPhrase <= 80> (#id) <secs> so far[, by #cause]`. -- **`timelineLines`**: the last 96 events (`env.events.last(96)`), each rendered by `eventLine` (null lines dropped). - Relevant = `user`, `error`, `action`, `nav` events always; `state` events of involved stores; op events of the - subject or its ancestors, of the same signature, of the same root or a descendant of the subject, or of a - signature that wrote an involved store. Keep the last `L.timeline` relevant lines; if fewer, fill with the most - recent non-relevant lines; output in event order. -- **`stateLines`**: first the involved fields (mutation change paths, violated fields, transition chain keys), then - the fields of all involved stores pooled together, most recent write first; stops at `L.state`; paths with no current leaf are - skipped. Line: `<path> = <describe(value, path, redact, 90)> (v<v>[, by #writer] <secs> ago)` or `(v0)` when never - written. A store registered with `opts.describe` contributes one line `<store> = <describe() <= 110> (v<version>)` - instead of its fields. `ask` about `now` with nothing involved -> all fields of all stores by recency. -- **`statsLines`**: signatures = the subject op's (if fetch/xhr/ws/task) + every in-flight fetch/xhr; first - `L.stats` that have `count > 0`. Line: `<sig>: <count> done[, median <secs>, p95 <secs>], <failed> of last <of> - failed, <recent> in last 10s[ (usual <fmtNum>)]`. (Baselines only exist for fetch/xhr, so ws/task subjects - produce no line.) - -### 5. `describe.ts` phrasing (also used for action effect texts) - -`opLabel` is also imported by `runtime.ts`, `observe/fetch.ts` and `observe/xhr.ts` to write `ActionEffect.changed` -sentences (`Dropped the write to …`, `Retried … as attempt …`), which come back to the model as timeline `action` -lines. `decide/report.ts` and the devtools do not import `describe.ts`. - -- `userPhrase(op)` from `op.meta.action` and `op.detail` (already redacted/quoted by `rt.user`): `user clicked - <target or "the page">`, `user typed <value or "text">[ into <target>]`, `user changed <target or "a field">[ to - <value>]`, `user submitted <target or "a form">`, `user pressed <key or "a key">[ in <target>]`, `user navigated - to <target or value or "a page">` (kinds `nav` and `navigate`), else `user <kind or "action">[ <target>][ <value>]`. -- `opPhrase(op)`: user -> `userPhrase`; fetch/xhr -> `<signature><detail>` (detail is the observer's redacted query - or body summary, e.g. `?q=re`, ` {items: [1], cardNumber: [redacted]}`); timer, ws -> name; task -> `task <name>[ - <detail>]`; genclass -> `GenClass <name>`. -- `opLabel(op)` -> `<opPhrase truncated to 90> (#id)`, or `an earlier operation` when unknown. -- `statusText(op)` -> `aborted`, `blocked`, numeric code, `timed out`, `network error`, `error[ (<errorText <= 40>)]`, - else status or `pending`. -- `eventLine(e, now, op)` prefixes `rel(e.t - now)` (`-1.24s`; `-0.00s` for now): - -| event kind | line | -|---|---| -| `user` | `<t> <userPhrase> (#id)` or `(<n> keystrokes, #first–#last)` for a merged typing burst | -| `op.start` | `<t> start <opPhrase <= 80> (#id[, by #cause][, attempt n])` (user ops: none) | -| `op.end` | `<t> end <opPhrase <= 80> (#id): <statusText>[ in <secs>]` | -| `state` | `<t> write <summary <= 110>[ (by #op[, user])]` (summary = first 3 `path: changeText`, joined `; `) | -| `error` | `<t> error <message <= 100>[ (during #op)]` | -| `nav` | `<t> navigate <route <= 60>` | -| `storage` | `<t> <name>[ <key <= 40>]` | -| `perf` | `<t> <name>[ <ms>ms]` | -| `custom` | `<t> event <name <= 60>[ <summary <= 60>][ (#op)]` | -| `action` | `<t> GenClass <text <= 100>` (past GenClass actions are visible to the model: `ActionEffect.changed`, or `undid <action> (<id>)` for an undo) | -| `decision` | never shown | - -When the op is no longer in the registry: `user` prints the event name instead of the phrase, `op.start` is dropped, -`op.end` prints `<t> end <name>`. `rel` prints `+` for future times (not expected in practice). - -`changeText(c, redact)` (`state/fields.ts`; used by M15, I2 and the hub's timeline `write` summaries): same-length -arrays -> `N items, unchanged` / `N items, reordered` / `N items, K changed: {id: 3, qty: 1 → 2}[, and K-1 more]` (at -most half the items changed; `elementDiff` lists the id key and up to 3 changed keys, `+N more changed`), else the -full `before → after` when <= 90 chars, else `N items, K changed`; other arrays -> full `before → after` when <= 70 chars, else `B → A items: added -<first>[ and N more]; removed N item(s)`; objects compared by key hash -> `B → A entries: added k: v; changed k: -…; removed k1, k2[ and N more]`; anything else -> `<describe 36> → <describe 36>`. - -Formatters (`util.ts`): `secs` = 2 decimals below 10 s (`0.42s`), 1 decimal below 1000 s, else integer; -`fmtNum` = integers as is, else 1 decimal (>= 100), 2 (>= 1), 4 (< 1), trailing zeros dropped; `ratio(a, b)` = -`∞` if `b <= 0`, `<round>×` if >= 10, else `<1 decimal>×`; `times(n)` (facts.ts) = `once`, `twice`, `N times`; -`truncate(s, n)` cuts to `n - 1` chars + `…`. `plural(n, one)` = `<n> <one>` or `<n> <one>s`; `ordinal(n)` = -`1st`, `2nd`, `3rd`, `11th`. `describe(v, path, redact, max)`: strings quoted (48 chars, 24 -nested), arrays `N items [a, b, c, …]` (at most 3 elements, stopping before `max - 16` chars; nested `[N]`, empty -`0 items`), objects `{id: …, name: …, k: v, +N}` with -id-like keys first (`id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`), depth > 1 `{N keys}`, empty -`{}`, `Map(n)`, `Set(n)`, dates ISO (`Invalid Date`), bigint `<n>n`, `function`, `symbol`; the whole result is -truncated to `max`. - -### 6. Facts catalogue (`facts.ts` -> `computeFacts`) - -**Salient** = `neutral: false`. `C` = the write's cause op, `#C` its id; `<times>` = once/twice/N times; "other -chain" = writer not ancestor-or-self of `C` and vice versa. `<writer>` = `<opLabel(w)>, which started <secs> -after #C` (or `before #C`, or `started at the same time as #C`) + optional `, from the same user action (#u)`, -`, from a later user action (#u)`, `, from an earlier user action (#u)`; or `a user action` / `an operation that is no -longer tracked`. Provenance (shared helper `provenance`): `<What> comes from <opLabel(op)>, started <secs> ago[, -ended <secs> ago with <status>][; its chain began with <opLabel(root)>].` or `<What> has no known cause: no -operation was active when it started.` - -**mutation** (`mutationFacts`) +#### Section builders (`build.ts`, unchanged) -| id | kind | salient when | condition and text | -|---|---|---|---| -| M1 | provenance | never | always: provenance of `This write` | -| M2 | versions | always | `C` set, for each of the first 3 written paths written by another chain since `C` started: `<path> was written <times> by other operations since this write's cause (#C) started (version <vStart> → <vNow>), last <secs> ago by <writer>.` (counts from the 512-entry field log) | -| M3 | versions | never | only `C`'s own chain wrote it: `<path> was written <times> by this write's own chain since this write's cause (#C) started (version a → b).` | -| M4 | versions | never | untouched: `<path> has not changed since this write's cause (#C) started (version <v>).` Side effect for every one of the first 3 paths (M2, M3 or M4): `C.reads.set(path, vStart)` with `vStart = hub.versionAt(path, C.startSeq)` | -| M5 | inputs | field is in the **same store** as the write | up to 2 other existing fields changed by other chains since `C` started (order: same store, user-written, most recent): `<path> changed <times> since … started (now <v>)` (first write no longer in the 16-entry history), or `… changed since … started: <before> → <now>[ (<n> writes)]`, or `… changed <times> since … started and is back to <v>` (values described at 40 chars), then `, last by <opLabel(w)> <secs> after #C started.` (or `, last by an untracked writer.`) | -| M6 | concurrency | at least one listed op started **after** `C` | in-flight ops outside `C`'s chain with `C`'s name and kind: `<N> other <C.name> operation(s) is/are in flight (<k> newer than this write's cause (#C)): #id <detail> started …; …` (up to 3 listed) | -| M7 | concurrency | never | other in-flight ops whose signature's chains wrote this store: `<opLabel> is in flight and its chain wrote <store> <times> before[ (<n> more such ops in flight)].` | -| M8 | baseline | `lat > 3 × median` **and** `lat − median >= 100 ms` | `C` is an ended fetch/xhr with a latency baseline: `This write's cause (#C) took <secs>, <ratio> its usual <median> (p95 <p95>).` | -| M9 | outcome | never | `C` fetch/xhr ended with status error: `This write's cause (#C) failed (<status>) before this write.` | -| M10 | versions | always | for each of the first 3 written paths: a write in the last 10 s from another chain rooted in a user op whose non-user op is still in flight: `<path> has a pending local change: <opLabel(user)> wrote it <secs> ago and its <opLabel(pending)> is still in flight; this write comes from <opLabel(C)>, which started after (or before) that user action.` (or `has no known cause`) | -| M11 | outcome | never | `m.unholdable`: `This write could not be held: <reason>.` (appears unreachable, see Drift) | -| M12 | repetition | some change is **additive** (numeric delta `n:` or array add/remove `a:`) | same change key (sorted paths + deltas) applied in the last 10 s (`hub.recent`): `An identical change to <paths> (<delta>) was applied [<n> times in the last 10s, last ]<secs> ago by <opLabel(w)>[; both come from the same user action (#u)][; they come from separate user actions <secs> apart].` `<delta>` = `+N`/`-N`, `added N item(s) <first>`, `removed N item(s)`, or `set to <value>` (first change only) | -| M13 | concurrency | never | earlier queued writes on the store: `<N> earlier write(s) to <store> is/are still waiting for a decision.` | -| M14 | invariant | never | up to 2 learned relations the write would break (`previewInvariants`): `Applying this write would break the learned relation <text> (<values>); it held at <n> settled points.` | -| M15 | delta | never | first 3 changes: `This write would change <path>: <changeText>.` | -| M16 | outcome | never | `m.defers > 0`: `This write was already deferred <times>.` | - -**request / failure / stall common part** (`requestCommon`; `<self>` = `This request (#id)` for request, `The -request (#id)` otherwise) +- **`inFlightLines`**: in-flight non-user ops except the subject op, sorted by (same signature, same root, other), + then start; line `<opPhrase <= 80> (#id) <secs> so far[, by #cause]`. +- **`timelineLines`**: last 96 events through `eventLine`; relevant = user/error/action/nav, state events of + involved stores, op events of the subject's chain, signature or store writers; last `L.timeline` relevant lines, + topped up with recent non-relevant ones. +- **`stateLines`**: involved fields first, then involved stores' fields by recency; `<path> = <describe 90> (v<n>[, + by #w] <secs> ago)`; a store with `opts.describe` gives one line. +- **`statsLines`**: the subject op's signature (fetch/xhr/ws/task) + in-flight fetch/xhr; `<sig>: <count> done[, + median, p95], <failed> of last <of> failed, <recent> in last 10s[ (usual …)]`. -| id | kind | salient when | condition and text | -|---|---|---|---| -| R1 | provenance | never | provenance of `This request` (cause op) | -| R2 | outcome | never | `attempt > 1`: `<self> is attempt <n>: it was already retried <times>.` | -| R3 | repetition | **request only**: `close` | identical-identity ops (not this one, started <= 10 s ago, `attempt === 1`): `<N> identical <sig> request(s) in the last 10s: <items>` (or `(latest 3: <items>)` when N > 3; items, last 3 only, joined `; `: `#id in flight (started <secs> ago)` or `#id answered <statusText> <secs> ago` (status ok) / `#id ended <statusText> <secs> ago`) `; #<last> started <secs> after (or before) this one` + `, from the same user action (#u)` / `; they come from separate user actions <secs> apart` / `, neither from a user action` (nothing when only one side has a user action). `close` = one of them is in flight, or the start gap to the latest `< min(2000, 0.5 × gapEwma)` (gapEwma used only when the identity was seen more than 3 times; else `< 2000` ms) | -| R4 | concurrency | never | same signature, different identity, in flight: `<N> other <sig> request(s) with different input is/are in flight: #id <detail> (started …); …` | -| R5 | outcome | **request only**: `failStreak >= 2` | not on failure; `failStreak > 0`: `The last <N> <sig> request(s) failed in a row (<last 5 outcomes>); last success <secs> ago` (or `no success yet`) | -| R6 | outcome | never | stall with `failStreak 0` and `count > 0`: `Recent <sig> outcomes: <last 5>.` | -| R7 | baseline | `recent >= 5` **and** `recent >= 3 × usual` (any of the three triggers) | usual rate known, `recent >= 3`: `<sig> was requested <times> in the last 10s; usually <usual> per 10s (<ratio>).` | -| R8 | baseline | never | no usual rate yet, `recent >= 3`: `… (no usual rate learned yet).` | -| R9 | baseline | never | not stall, latency baseline exists: `<sig> usually answers in <median> (p95 <p95>, <n> samples); error rate <x>% over <of> request(s) (<failed> failed).` (`x = round(failed / of × 100)` over the last <= 20 outcomes; `no completed requests yet` when there are none) | -| R10 | cache | never | GET with a cached response: `A cached <status> response from <secs> ago exists for this request.` | -| R11 | request | never | always: `<METHOD> is idempotent` or `is not idempotent`, then `; its body (<n> bytes) can be replayed.` or `; its body cannot be replayed.` (no body clause for GET/HEAD) | - -**request** = R1-R11. **failure** = F1-F3 then R1-R11: +### 7. `describe.ts` phrasing and change texts + +`describe.ts` is unchanged (`opLabel`, `opPhrase`, `userPhrase`, `statusText`, `eventLine`; see the table in +[observe-and-trace](observe-and-trace.md) for event kinds). New timeline content reaching the model: message +events `event ws.message <summary> (#id)` / `event sse.message …`, `event delivery.unchanged (#id)`, and GenClass +`action` lines from delivery `discard`/`defer` and drops. + +`changeText(c, redact)` (`state/fields.ts`) gained one branch before the generic `<describe 36> → <describe 36>`: +two strings whose redaction leaves them unchanged and at least one longer than 30 chars use `stringDiff`: both sides +previewed from 14 chars before the first difference, 30 chars wide, plus `(removes "…")`, `(inserts "…")` or +`(replaces "…" with "…")` (each <= 28 chars). Example asserted in `test/content.test.ts`: `"…e sword shield market +lib" → "…e sword shield" (removes " market lib")`. This changes timeline write summaries, M15 deltas and I2 too. + +Formatters (`util.ts`) are unchanged: `secs` (2 decimals < 10 s, 1 < 1000 s, else integer), `fmtNum`, `ratio`, +`truncate` (`n - 1` chars + `…`), `plural`, `ordinal`, `describe` (strings quoted 48/24 chars, arrays `N items [a, +b, c, …]`, objects with id-like keys first). `describe` now compares the redactor result with `Object.is` (a `NaN` +value is no longer treated as redacted; the NaN fix, commit ad24804). + +### 8. Facts catalogue (`facts.ts` -> `computeFacts`) + +**Salient** = `neutral: false`. Helpers: `provenance` (`<What> comes from <opLabel>, started <secs> ago[, ended <secs> +ago with <status>][; its chain began with <opLabel(root)>].` or `… has no known cause: no operation was active when it +started.`), `writerOpText`, `times` (once/twice/N times). The F-numbers are SIM's separability proposals +(`sim/SEPARABILITY.md` §6) as named in `packages/runtime/STATUS.md`. + +#### Shared building blocks (used by mutation and delivery) + +`versionFacts(env, X, paths, ref, now)` (X = the write's cause or the delivering op; `ref` = `this write's cause +(#C)` / `its operation (#X)` / `this message (#X)`), per path (side effect `X.reads.set(path, vStart)`): | id | kind | salient when | text | |---|---|---|---| -| F1 | outcome | always | `The request #id failed: <HTTP <status>[ <statusText>] or timed out or network error[ (<msg <= 50>)]> after <secs>; the app has not seen the failure yet.` | -| F2 | outcome | never | only when the signature has baseline stats: `This is the <ordinal> <sig> failure in a row (recent outcomes: <last 5>; <last success <secs> ago or no success yet>); error rate <x>% over <of> request(s) (<failed> failed).` with `ordinal(max(1, failStreak))`. The failing op was already ended and recorded by `Baselines.end` before the trigger, so the streak, outcomes and counts include it (example C: 3rd, three 503s) | -| F3 | outcome | never | chain already wrote state (`chainWrites(op)` non-empty): `Before this failure its chain wrote <up to 4 paths>.` | +| V-pending | versions | always (emitted only for a pending conflict) | `<path> has a pending local change: <opLabel(user)> wrote it <secs> ago and its <opLabel(pending)> is still in flight; <ref> started after (or before) that user action.` | +| V-others (old M2) | versions | iff `newerConflict(env, X, path)` | `<path> was written <times> by other operations since <ref> started (version a → b), last <secs> ago by <writer>.` | +| V-own (old M3) | versions | never | `<path> was written <times> by <ref>'s own chain since it started (version a → b).` | +| V-none (old M4) | versions | never | `<path> has not changed since <ref> started (version v).` (omitted when V-pending was emitted) | -**stall** = S1, S2 then R1-R11 (R9 omitted): +`movedFacts` (old M5, **always neutral now**): up to 2 other fields (any store; fields of the given stores first, +then fields a user wrote, then the most recently written) changed by other chains since X started (`… changed since <ref> started: <before> → <now>[ (n writes)], last by <opLabel> <secs> after #X +started.` / `… changed <times> … (now v)` / `… and is back to v`). `concurrencyFacts` (**always neutral**, user ops +excluded): M6 `<N> other <X.name> operation(s) is/are in flight (<k> newer than <ref>): #id <detail> started …` and, +per store (up to 2), M7 `<opLabel> is in flight and its chain wrote <store> <times> before[ (n more such ops in +flight)].` -| id | kind | salient when | text | +#### mutation (`mutationFacts`), in emission order + +| id | kind | salient when | condition and text | |---|---|---|---| -| S1 | baseline | always | `The request #id has been in flight for <secs>; <sig> usually takes <median> (p95 <p95>, <n> samples), <ratio> the median.` (without baseline: `… has been in flight for <secs>.`) | -| S2 | concurrency | never | other same-name in-flight requests past `3 × median`: `<N> other <sig> request(s) is/are also running past 3× the usual latency.` | - -**inconsistency** (`inconsistencyFacts`), per violation (first 3): I1 (invariant, **always salient**) `The developer -invariant "<text>" no longer holds.` or `The learned relation <text> no longer holds: <values>. It held at <n> settled -points before.`; then I2 (versions, never) for the 2 latest writes to its fields since the last consistent snapshot: -`<path> was written <secs> ago by <opLabel(w)>[ (user)]: <changeText>.` After the loop: I3 (invariant, never) -`The last consistent state is <secs> old; <n> field write(s) happened since.` or `No consistent snapshot has been -recorded yet.`; I4 (concurrency, never) `<n> operation(s) is/are in flight.` or `No operations are in flight (the app -is settled).` - -**transition** (`transitionFacts`): T1 (transition, **always salient**), first 3 `Unusual` (`<sig>` = `op.name`, or -`opPhrase` for user ops): -- set: `In the previous <of> completions of <sig> its chain wrote <usual fields> (<usualCount> of <of> times); this - time it wrote [only ]<observed fields>[ (seen <times> before)].` (`only` when observed is a strict subset; - `nothing` for an empty set; fields joined `a, b and c`) -- kind: `In the previous <of> completions of <sig> that wrote <field>, it wrote a/an <usual> (<usualCount> of <of> - times); this time it wrote a/an <observed>.` -- status: `… it ended with <usual> (<usualCount> of <of> times); this time it ended with <observed>.` -- writes: `… its chain made <usual> write(s) (<usualCount> of <of> times); this time it made <observed>.` - -Then T2 (provenance, never) of `The completed operation #id` / `The completed user action #id` (cause op, or the op -itself when it has no cause); T3 (baseline, never, fetch/xhr) `It ended <secs> ago with <status> after <secs>[ -(usual <median>)].`; T4 (delta, never) for each of the first 3 chain keys (insertion order) that has a current value -or field record: `<field> is now <describe 60>.`; T5 (invariant, -never) `The last consistent state from before #<root> started is …` / `No consistent snapshot from before #<root> -started exists.` - -**error** (`errorFacts`): E1 (error, **always salient**) `Uncaught <name>: <message <= 120>[ (at <source <= 60>)].`; -with an ambient op: E2 (provenance) `It was thrown while <opLabel(op)> was active, <secs> after it started[; that -chain began with <opLabel(root)>].` and E3 (versions) `Its chain wrote <up to 4 paths> before the error[ (<k> of them -overwritten since by other operations)].` or `Its chain wrote no state before the error.`; without: E4 (provenance) -`No operation was active when it was thrown.`; E5 (repetition) `The same error happened <times> in the last 10s.` -when the error key (`normalizeError`: `<name>:<message with digits -> n, 120 chars>`) occurred more than once (the -current error is already in `recentErrors`, so "twice" means one earlier occurrence); E6 (invariant) last-consistent -fact relative to the op's root (`The last consistent state from before #<root> started is …` / `No consistent -snapshot from before #<root> started exists.`), or the plain `The last consistent state is …` / `No consistent -snapshot has been recorded yet.` when no op was active. E2-E6 never salient. - -**ask** (`askFacts`, all neutral; `ask` is salient anyway): about an op id -> `Operation #N is not known.` when -missing, else provenance of `Operation #id (<opPhrase <= 60>)`, `It has been in flight for <secs>.` or `It ended -<secs> ago with <status> after <secs>.`, `<name> usually takes <median> (p95 <p95>).`, `Its chain wrote <up to 5 -normalised keys>.`; about a store -> `Store <name> is not registered.` when missing, else up to 6 most recent fields -`<path> is at version <v>[, last written <secs> ago by <opLabel>]`; about now -> `<N> operation(s) is/are in flight; -the oldest is <opLabel> (<secs>).` or `No operations are in flight.`, `The last <N> <sig> request(s) failed in a row -(<outcomes>).` for streaks whose last failure is < 30 s old, `<N> error(s) happened in the last 10s.`, up to 2 -`The learned relation <text> does not hold: <values>.`, and `An identical change to <paths> was applied <times> in -the last 10s.` for change keys seen more than once in 10 s. - -**Ordering** (`orderFacts`): non-neutral first, then `RANK` (`invariant`, `transition`, `error` 0; `versions` 1; -`repetition` 2; `inputs` 3; `outcome` 4; `baseline` 5; `concurrency` 6; `provenance` 7; `request` 8; `cache` 9; -`delta` 10; `plugin` 11), then original position. - -### 7. Triage: exact salience conditions - -A trigger reaches the model iff the runtime is consultable, the provider is `ready` (otherwise the first salient -situation starts the lazy load and fails open), and one of: -1. `triage: "always"`; or -2. trigger is `ask`; or -3. a standing question with `always: true` lists the trigger (`forced`); or -4. at least one computed fact is non-neutral. Per trigger: - - **failure, stall, inconsistency, transition, error**: always (F1, S1, I1, T1, E1 are non-neutral). - - **mutation**: M2 (a written field was written by another chain since the cause started), M5 (a field of the - same store moved since then), M6 (a newer op with the cause's signature is in flight), M8 (the cause took - > 3× its median and >= 100 ms over it), M10 (a pending local change is being overwritten), M12 (an identical - additive change in the last 10 s). A write with no cause op can only be salient through M10 or M12. - - **request**: R3 with `close`, R5 with `failStreak >= 2`, R7 hot rate. - -Plugin facts are always neutral and are only computed after the cheap pass, so plugins can never make a trigger -salient. Because the sim runs with `triage: "salient"`, sim decision rows exist only for salient situations (its ask -probes come separately from `rt.situation("ask")`); changing triage changes the training distribution, not just -runtime cost. - -### 8. Questions (`questions.ts` -> `buildQuestions`) - -- `ask`: only standing questions registered for `ask` (and `rt.ask()` replaces them with `{ answer }`). -- `diagnosis` (always otherwise): `{ type: "choice", instructions: "What is happening here?", criteria }` over - `o.diagnoses` = `diagnosisVocabulary(vocab, pluginLabels)`: `vocab.diagnoses` replaces `DEFAULT_DIAGNOSES` - entirely, `expected` is re-added if missing and always first, plugin labels are appended if new. -- `action` (only when more than one action applies): instructions `ACTION_INSTRUCTIONS[trigger]`, one option per - applicable action in offer order (passive first), description from `actionDescription` = `vocab.actions[name]` ?? - custom description ?? built-in description ?? name. -- Compact (`budget <= COMPACT_QUESTIONS_BUDGET` = 1400): every description becomes `null` except a vocabulary - override of <= 24 chars (`COMPACT_DESC_MAX`); custom-action and plugin-label descriptions are dropped too. -- Standing questions are added under their ids unless the id is already used (`diagnosis`/`action` cannot be - overridden). - -| label (`DEFAULT_DIAGNOSES`, in order) | description | -|---|---| -| `expected` | normal behaviour, nothing is wrong | -| `stale` | outdated data or an older operation is about to replace newer state | -| `conflict` | concurrent operations are competing over the same state or resource | -| `duplicate` | the same change or request is happening again without a new intent | -| `inconsistent` | the state contradicts itself or relationships it normally keeps | -| `failing` | an operation keeps failing or its failures follow a pattern | -| `slow` | an operation is far slower than usual | -| `overload` | work is being triggered far more often than usual | -| `unusual` | this differs from how the same operation normally behaves | -| `transient` | a one-off failure that is likely to succeed if tried again | - -| trigger | `TRIGGER_ACTIONS` (passive first) | `PASSIVE` | `ACTION_INSTRUCTIONS` | +| M1 | provenance | never | provenance of `This write` | +| V-* | versions | see above | with a cause `C`: `versionFacts` over the first 3 written paths | +| F1/F3 (write) | versions / delta | F1 yes | `contentFacts(env, C, cmps, "This write")` over the first 6 changes that have an after-leaf (see content facts) | +| RYW | versions | always | `rywFacts` over array changes, loaded by `netOf(C)` (nearest fetch/xhr/ws op up the cause chain) | +| F6 | baseline | never | `cadenceFact` for `netOf(C)` when it is not a user op | +| M5 | inputs | never | `movedFacts(env, C, written, [m.store])` | +| M6, M7 | concurrency | never | `concurrencyFacts(env, C, [m.store])` | +| M8 | baseline | `lat > 3 x median` and `lat - median >= 100 ms` | `This write's cause (#C) took <secs>, <ratio> its usual <median> (p95 <p95>).` | +| M9 | outcome | never | `This write's cause (#C) failed (<status>) before this write.` | +| M10 | versions | always | **no cause only:** `pendingConflict(env, null, path)` for the first 3 paths: `… has a pending local change: …; this write has no known cause.` | +| M11 | outcome | never | `This write could not be held: <reason>.` (unreachable, see Drift) | +| F9 | versions | never | `markFacts(env, written)` (max 2) | +| F7 | repetition | never | before M12, when the two identical changes come from separate user actions: `repeatEvidence` | +| M12 | repetition | some change is additive | `An identical change to <paths> (<delta>) was applied …` | +| M13 | concurrency | never | `<N> earlier write(s) to <store> is/are still waiting for a decision.` (only with `holdWrites`) | +| M14 | invariant | never | `Applying this write would break the learned relation …` (2 max) | +| M15 | delta | never | `This write would change <path>: <changeText>.` (first 3) | +| M16 | outcome | never | `This write was already deferred <times>.` | + +#### delivery (`deliveryFacts`), in emission order + +| id | kind | salient | text | |---|---|---|---| -| mutation | apply, discard, defer | apply | What should the runtime do with this write? | -| request | send, coalesce, delay, block, serve_cached | send | What should the runtime do with this request? | -| failure | deliver, retry, serve_cached | deliver | What should the runtime do with this failed request? | -| stall | wait, hedge, serve_cached | wait | What should the runtime do with this slow request? | -| inconsistency | ignore, rollback, resync | ignore | What should the runtime do about this inconsistent state? | -| transition | ignore, rollback, resync | ignore | What should the runtime do about this unusual state change? | -| error | ignore, rollback | ignore | What should the runtime do about this error? | -| ask | (none) | `""` | `""` | - -Built-in action descriptions and tiers (`BUILTIN_ACTIONS`): apply (passive) "let this write update the state now"; -discard (guard) "drop this write and keep the current state"; defer (guard) "hold this write until the related -in-flight operations finish, then decide again"; send (passive) "send the request now"; coalesce (guard) "do not -send; reuse the result of the identical request that is in flight or just finished"; delay (guard) "wait before -sending, backing off so the service can recover"; block (heal) "do not send; fail this request immediately"; -serve_cached (heal) "answer with the last successful response for this request instead"; deliver (passive) "pass -the failure to the application as it is"; retry (heal) "retry the request after a short backoff"; wait (passive) -"keep waiting for the request"; hedge (heal) "send a second identical request and use whichever answers first"; -ignore (passive) "leave the state as it is"; rollback (heal) "restore the affected state to its last consistent -snapshot"; resync (heal) "reload the affected state from its source". Effects: [decide-policy-actions](decide-policy-actions.md). - -### 9. Serialiser (`serialize.ts` -> `toJevState(parts, budget)`) - -1. `b = max(500, round(budget))`; `L = sectionLimits(b)` with `r = clamp((b - 1100) / (3200 - 1100), 0, 1)` and - `lerp(a, z) = Math.round(a + (z - a) * r)`. -2. Pre-shape: `app` (or `"unknown"`) and `trigger` truncated to their line limits; `facts`, `in_flight`, `state`, - `stats` keep their **first** `L.<section>` lines, `timeline` keeps its **last** `L.timeline` lines; every line - truncated to `L.line.<section>` (`…` suffix). -3. Build the object with keys in order `app, trigger, facts, in_flight, timeline, state, stats`; empty arrays -> - `"none"`. -4. While `stateChars > b`: drop timeline lines from the start (oldest) down to 0, then state lines from the end to 0, - then facts from the end down to **1**, then in_flight from the end to 0, then stats from the end to 0. -5. Still over: shorten every fact by the excess (not below 60 chars), then the trigger (not below 60 chars). +| D1 | provenance | never | response: `The response to <opLabel(X)> arrived after <secs>[ (<status>)][ and was held <times> already]; the app has not seen it yet.`; message: `A WebSocket|server-sent message (#id) <summary> arrived on <path>[ and was held …]; the app has not seen it yet.` | +| D2 | provenance | never | response with a cause: provenance of `This request` | +| D3 | concurrency | never | message with `queuedAhead`: `<N> earlier message(s) of this channel is/are held ahead of it (order is kept).` | +| D4 | transition | never | profile prediction only: `In <of> earlier completions of <X.name> its chain wrote <fields> (<seen> of <of> wrote state).` | +| V-* | versions | see above | `versionFacts` over conflicting paths, then matched fields written since X started (first 3) | +| F1-pending | versions | always | `pendingRevertFacts` (max 2): `<The response|This message> has <path> = <v>, the value before <user op> changed it to <v'> <secs> ago (its <pending op> is still in flight); delivering it would undo the user's change.` | +| F1/F2/F3 | see content | | `contentFacts(env, X, content.cmps, subject, now, { fields: matched })` | +| RYW | versions | always | lists located in the body, `fromResponse` (`This response's list …`) | +| F9 | versions | never | `markFacts` over conflicting + matched fields | +| F6 | baseline | never | `cadenceFact(env, X.name)` | +| M5, M6, M7 | inputs / concurrency | never | `movedFacts` / `concurrencyFacts` over the stores of the matched fields | +| D5 | baseline | never | `<sig> usually answers in <median> (p95 <p95>).` (response with a latency baseline) | +| D6 | outcome | never | `The <N> <sig> request(s) before this one failed in a row.` (`failStreak > 0`) | + +Content facts need `spec.content` (or `spec.body`): the body is read only for candidates (a conflict, typed text or +`always`, see section 5), so a delivery that reaches the model without a body reader or after the 100 ms body +timeout has no F1-F3/RYW content facts. + +#### content facts (`content.ts`) + +`analyzeBody(env, X, body, fields)` indexes the body (`indexBody`: max 20,000 nodes, depth 8, 2,000 items per array, +at most 64 objects outside arrays) and locates each of the first 32 fields (`locate`): (1) by item id (a path segment, +searched from the leaf up, that equals the `id`/`_id`/`uuid`/`slug`/`key` value of a body object; the first segment +after the store name only when it is id-like or has a digit; all candidates must agree by value hash); (1b) a keyed update object +(`{card: "c1", col: "done"}` for `board.cards.c1`); (2) the longest key-path suffix outside arrays; (3) the one body +array of compatible items (same id key or >= 50% shared keys; most shared ids wins); (4) a primitive body for a +primitive store. Ambiguous or kind-incompatible -> not located (no fact). `noChange` = every field located and +equal. + +`contentFacts` (at most 3 shown, conflicts first; subject `The response` / `This message` / `This write`): + +| fact | kind | salient | text | +|---|---|---|---| +| F1 item cell | versions | yes | `<S> would put back <key> = <v> for item <id> of <path>[ and N more cells]: the store has <cur>, changed since #X started; delivering (applying) it would undo that change.` | +| item newer-same | versions | no | `The newer writes to <path> changed only N item(s) (<ids>); this response's copy of it/them equals the store.` | +| item join delta | delta | no | `Joined by <idKey> with <path>, <s> would change N cell(s) in M item(s), add …, remove ….` | +| F2 | versions | yes | `<S> would replace text the user typed into <path> after #X started (N user write(s), the last <secs> ago): <stringDiff text or a → b>.` | +| F1 field | versions | yes | `<S> has <path> = <v>, the value that <writer> replaced with <v'> <secs> ago[ (it started after/before #X)]; delivering (applying) it would put the older value back.` | +| third value | versions | no | `<S> has <path> = <v>: neither the current value <cur>[, nor the value when #X started].` | +| F3 | delta | no | `<S> matches the current values of everything it is predicted to write (<list>): delivering it changes nothing.` or `<S> has the current value of <list>.` | + +`rywFacts` (read-your-writes, max 2, creates of the last 10 s, `RYW_WINDOW_MS`, first 5 ids each, shape fit >= 40% +shared keys): `<path> contains item "<id>" twice|N times; <opLabel(create)> created item "<id>" <secs> ago (<status>).` +or `<path> was loaded by <opLabel>, which started <secs> after <opLabel(create)> created item "<id>" … , and does not +contain it.` Both salient. Also used by inconsistency and transition facts (`storeLists`). + +#### evidence facts (`evidence.ts`, all neutral) + +- **F9** `markFacts`: `<path> holds a value written <secs> ago <why>; nothing has rewritten it since.` Marks come from + `RuntimeImpl.markWrites` (on every applied write by a non-GenClass writer, checking the writer and 8 ancestors): + `by the response to <op>, which was delivered over newer data from|a pending local change of <writer>` (`by the + message <op>, …` when the op is a WebSocket/EventSource message); `by the response to <op>, which took <secs> (<ratio> its usual <median>)` (ok, `>= 5 x median` and `>= 300 ms` over it); + `after <op> failed (…), although the server may have applied it` (ambiguous commit). And from + `RuntimeImpl.onChannel` when a WebSocket/EventSource channel comes back up: fields last written by that channel's + messages before it went down get `by WebSocket|server-sent messages on <path>; the channel then was down for <secs> + (<how>), so updates sent meanwhile may be missing`. Used in mutation, delivery, inconsistency, transition, error. +- **F6** `cadenceFact`: `<sig> runs on a schedule: every <period> (last N intervals); the next run is due in <secs>|<secs> + overdue.` or `<sig> is usually sent <delay> after the user's last input (k of the last n): a later edit is followed + by a new request.` Used in mutation, delivery, failure, stall. +- **F5** `scopeFacts` (failure, stall): same host (`hostOfSig`: `same-origin` or the host of a cross-origin + signature), other signatures, last 10 s: `N other endpoint(s) of this origin|<host> failed in the last 10s (N + failure(s), latest: <sig> <outcome>, …)[; N other request(s) succeeded].` or `The other endpoints of … answered + normally in the last 10s (…).`; plus `The browser reports that it is offline (navigator.onLine is false).` + `commitAmbiguity` (failure, non-GET/HEAD/OPTIONS): 502/503/429/408 -> `… a status servers and gateways usually + return without processing the request.`; other 4xx -> none; 5xx or network/timeout faster than half the usual + latency -> `… well before its usual …`; otherwise `…: the server may have applied it before failing.` / + `…: the server may have received and applied it.` (ambiguous; also drives F9 marks). +- **F7** `repeatEvidence(env, u1, u2, firstReq?)`: `User actions #a and #b, <secs> apart: both are <kind>s on + <target>; the browser counted #b as click N of a multi-click (MouseEvent.detail); the request of #a (#r) was still + in flight at #b; between them the app wrote <fields> | the app changed no state between them.` Emitted next to R3 + (request/failure/stall) and M12 when the two come from separate user actions. + +#### request / failure / stall + +`requestCommon` (R1-R11) is unchanged except that R3, when the two requests come from separate user actions, is +preceded by an F7 fact. Salience: R3 on `request` only when `close`; R5 on `request` only when `failStreak >= 2`; R7 +when `recent >= 5` and `>= 3 x usual` (all three triggers). **failure** = F1 (outcome, salient), F2 streak, F3 +chain writes, then commit ambiguity, F5 scope/offline, F6 cadence, then R1-R11. **stall** = S1 (salient), S2, F5 +scope/offline, F6 cadence, then R1-R11 (R9 omitted). + +#### inconsistency, transition, error, ask + +- **inconsistency**: I1 (salient) and I2 per violation as before; then **new** F9 marks and RYW over the violated + fields; then I3 last consistent state, I4 in-flight count. +- **transition**: T1 (salient) per `Unusual`, T2 provenance, T3 baseline, T4 `is now`; **new** F9 marks and RYW over + the concrete fields matching the chain keys (`matchFields`); then T5. +- **error**: E1 (salient), E2/E3 (with ambient op; **new** F9 marks over the chain's written paths after E3) or E4, + E5, E6. +- **ask**: unchanged (all neutral). + +**Ordering** (`orderFacts`, unchanged): non-neutral first, then `RANK` (invariant/transition/error 0, versions 1, +repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), +then emission order. D4 has kind `transition` (rank 0), so among neutral delivery facts it comes first. + +### 9. Triage: exact salience conditions + +A trigger reaches the model iff the runtime is consultable, the provider is `ready`, and one of: `triage: +"always"`; trigger `ask`; a `forced` standing question; or a non-neutral fact. Per trigger: +- **delivery**: first the `runDelivery` pre-filter (section 5) must pass; then a non-neutral fact: V-others with a + newer conflict, V-pending, F1 (field, cell or pending revert), F2, RYW. A pending conflict whose body showed a third + value, or whose body could not be compared (no body reader, the 100 ms timeout, a non-JSON or > 256 KB body, an +analysis throw), is released by the pre-filter even though V-pending would be non-neutral; only newer-data +conflicts decide in those fallback cases. +- **mutation** (only when not covered): V-others with a newer conflict, V-pending (cause op present) or M10 (no + cause), F1 / F2 on the write's own value, RYW, M8, M12 additive. **No longer salient:** M5 inputs that moved, M6 + same-signature op in flight, a plain user write. +- **request**: R3 `close`, R5 streak >= 2, R7 hot rate. +- **failure, stall, inconsistency, transition, error**: always (F1, S1, I1, T1, E1). + +Plugin facts are always neutral and computed only after the cheap pass. The sim runs `triage: "salient"`, so sim +decision rows exist only for salient situations; changing triage changes the training distribution. + +### 10. Questions (`questions.ts`) + +- `diagnosis` (all triggers but `ask`): `What is happening here?` over `DEFAULT_DIAGNOSES` (expected, stale, + conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient; unchanged) or the vocabulary. +- `action` (only with > 1 applicable action): `ACTION_INSTRUCTIONS[trigger]`; descriptions via `actionDescription`. +- Compact (budget <= 1400): bare labels except vocabulary overrides <= 24 chars. + +| trigger | `TRIGGER_ACTIONS` (passive first) | `ACTION_INSTRUCTIONS` | +|---|---|---| +| mutation | apply, discard, defer | What should the runtime do with this write? | +| request | send, coalesce, delay, block, serve_cached | What should the runtime do with this request? | +| delivery | deliver, discard, defer | What should the runtime do with this response or message? | +| failure | deliver, retry, serve_cached | What should the runtime do with this failed request? | +| stall | wait, hedge, serve_cached | What should the runtime do with this slow request? | +| inconsistency | ignore, rollback, resync | What should the runtime do about this inconsistent state? | +| transition | ignore, rollback, resync | What should the runtime do about this unusual state change? | +| error | ignore, rollback | What should the runtime do about this error? | +| ask | (none) | `""` | + +`BUILTIN_ACTIONS` descriptions and tiers are unchanged (apply, discard, defer, send, coalesce, delay, block, +serve_cached, deliver, retry, wait, hedge, ignore, rollback, resync). `TRIGGER_DESCRIPTIONS.delivery` overrides +three of them for `delivery` only: deliver "pass it to the application now"; discard "deliver it but drop the state +changes it would make over newer data"; defer "hold it until the related in-flight operations finish, then decide +again". Tiers stay the built-in ones (deliver passive, discard guard, defer guard). + +### 11. Serialiser (`serialize.ts` -> `toJevState`) + +Algorithm unchanged; only the full budget moved from 3200 to 2400 (`r = clamp((b - 1100) / (2400 - 1100), 0, 1)`). +Over budget: drop timeline (oldest first), then state, facts (keep >= 1), in_flight, stats; then shorten facts and +the trigger (floor 60 chars). | budget | facts | in_flight | timeline | state | stats | line limits app / trigger / facts / in_flight / timeline / state / stats | |---|---|---|---|---|---|---| | 500-1100 | 6 | 2 | 3 | 3 | 1 | 60 / 180 / 220 / 90 / 100 / 100 / 110 | -| 1333 (WASM 2 threads) | 7 | 2 | 4 | 4 | 1 | 67 / 187 / 224 / 93 / 104 / 106 / 113 | -| 1400 (compact-questions edge) | 7 | 3 | 5 | 4 | 1 | 69 / 189 / 226 / 94 / 106 / 107 / 114 | -| 1667 (WASM 3 threads) | 8 | 3 | 7 | 4 | 2 | 76 / 196 / 231 / 98 / 111 / 114 / 118 | -| 2000 (WASM 4 threads) | 9 | 4 | 9 | 5 | 2 | 86 / 206 / 237 / 103 / 117 / 121 / 123 | -| 2560 (WebGPU after 1 overflow) | 10 | 5 | 12 | 6 | 3 | 102 / 222 / 248 / 111 / 128 / 135 / 131 | -| 3200+ (WebGPU) | 12 | 6 | 16 | 8 | 4 | 120 / 240 / 260 / 120 / 140 / 150 / 140 | - -(Counts at 1100/2000/3200 and the 500 = 1100 equivalence are asserted in `test/budget.test.ts`; the line limits and -the other rows are computed from the same formula, not tested.) A 1-line-per-section minimum does not exist: the -counts are maxima, sections may be `"none"`, and only `facts` keeps at least 1 line under shrinking. `stateText(state)` renders `key: value` or `key:` plus -two-space-indented lines; it is for logs, `explain()` and devtools. `stateChars` does not count that indentation. -What the model actually tokenises is produced from the `JevState` by the model host's packer -(`packages/runtime/src/model/serialize.ts`), see [model-io-contract](../model-io-contract.md). - -### 10. Redaction - -- `Redactor = (path, value) => unknown`; default `defaultRedact` returns `"[redacted]"` when **any dotted segment** - of the path names a secret by meaning: `isSensitiveName` splits camelCase/snake/kebab into lower-case words and - matches `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, - iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or `SECRET_PAIRS` (card + - number/num/no/cvc/cvv/code/security; credit card; cc + number/num/no/exp/csc; api key/secret; private key; access - key; secret key; session id/token/key; security code; one time; social security). `card`, `cards`, `author`, - `passengers`, `tokens`, `pinned`, `session`, `key` are not secrets. -- Situation code applies it through `describe(v, path, env.redact, max)` (state lines, inputs-moved values, deltas, - `is now` facts) and `changeText(c, redact)` (`state/fields.ts`; timeline write summaries are produced by the hub - with the same redactor). Nested object keys are checked at `path.key`. Op details (query strings, request bodies, - typed values) are redacted earlier by the observers and `rt.user`; invariant `values` by the invariant miner. -- A custom `redact` option replaces the default everywhere (tested for invariant facts in - `test/review-redaction.test.ts`). - -### 11. Device-sized situations (`RuntimeImpl.situationBudget`) - -`situation.budget` number -> used as is. `"auto"` (default): decider `status.device === "wasm"` -> -`1000 + round((min(4, max(1, threads)) - 1) * 1000 / 3)`; otherwise (webgpu or unknown) 3200; times -`budgetScale`, which starts at 1 and becomes `max(0.5, budgetScale * 0.8)` on each `max_tokens_exceeded` error from -the decider (`DeciderQueue` error callback in the constructor). Example: 3200 -> 2560 -> 2048 -> 1638 -> 1600 -(floor); WASM 1 thread 1000 -> 800 -> 640 -> 512 -> 500. The scale is per runtime instance, never resets, and does -not apply to a numeric `situation.budget`. `env.ts` holds no sizing logic. `Runtime.situationBudget()` is public -(`types.ts` -> `Runtime`) and is what `buildOpts()` passes as `BuildOptions.budget` on every build. The sim samples -budgets 3200/2000/1000 with weights 40/30/30 (`sim/src/world/scenario.ts`, `R.fork("budget")`) and passes them as a -fixed `situation.budget`; the Python curriculum samples the same three at 35/30/35 (`training/curriculum/rt.py` -> -`BUDGETS`, override env `GC_RT_BUDGET`). Neither generates 1333/1667 or overflow-scaled budgets: at runtime those -sizes are interpolations the model never saw in training. - -### 12. Annotated examples (copied from `packages/runtime/STATUS.md`, produced by the tests) - -**A. mutation at a 1000-char budget (compact, from `test/budget.test.ts`, 998 chars).** +| 1200 (auto floor after overflows) | 6 | 2 | 4 | 3 | 1 | 65 / 185 / 223 / 92 / 103 / 104 / 112 | +| 1333 (WASM 2 threads) | 7 | 3 | 5 | 4 | 2 | 71 / 191 / 227 / 95 / 107 / 109 / 115 | +| 1400 (compact-questions edge) | 7 | 3 | 6 | 4 | 2 | 74 / 194 / 229 / 97 / 109 / 112 / 117 | +| 1667 (WASM 3 threads) | 9 | 4 | 9 | 5 | 2 | 86 / 206 / 237 / 103 / 117 / 122 / 123 | +| 1750 (tested) | 9 | 4 | 10 | 6 | 3 | 90 / 210 / 240 / 105 / 120 / 125 / 125 | +| 1920 (WebGPU after 1 overflow) | 10 | 5 | 11 | 6 | 3 | 98 / 218 / 245 / 109 / 125 / 132 / 129 | +| 2000 (WASM 4 threads) | 10 | 5 | 12 | 6 | 3 | 102 / 222 / 248 / 111 / 128 / 135 / 131 | +| 2400+ (WebGPU) | 12 | 6 | 16 | 8 | 4 | 120 / 240 / 260 / 120 / 140 / 150 / 140 | + +`test/budget.test.ts` asserts the counts at 1100, 1750, 2400, 3200 (= 2400) and 500 (= 1100); the other rows and all +line limits are computed from the formula. A budget above 2400 keeps full section counts but allows more characters +(the sim and realapps still sample 3200, see Drift). + +### 12. Redaction + +`defaultRedact` now uses `isSensitivePath(path, value)` (`util.ts`), batch 5: +- Never secret: `null`, `undefined`, booleans; plain objects (judged key by key, never redacted whole). +- Not a dotted path (free text such as `input "Card number"`, header lines) -> `isSensitiveName` on its words. +- Array-index segments are skipped (`users.3.password`). The **leaf** segment decides (`isSensitiveName`), or a + secret pair across the last two segments (`payment.card.number`). +- A non-leaf container that names a secret: strings under it are secret if the container is not "broad"; under a + broad container (`auth`, `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: + >= 20 chars of letters, digits and `_-.+/=:`, containing both a letter and a digit) are secret. +- A store holding a primitive is judged by its name (its name is the leaf). The container rule above also covers the + store segment: a broad store name never redacts its fields (`auth.loading`, `auth.user.name` visible), but a + store or container named by a non-broad secret word (`token`, `secret`, `password`, ...) redacts every string leaf + under it (`credentials.password.value`). Numbers are only redacted by the leaf or pair rule. The code comment + ("never by the store's or a container's name alone") describes the broad case only. +`isSensitiveName` (word lists `SECRET_WORDS`, `SECRET_PAIRS`) is unchanged but now memoised (`nameCache`, cleared +above 4096 entries). `describe` and `redactSearch` compare with `Object.is`. A custom `redact` option replaces the +default everywhere; `opts.describe` output bypasses it. + +### 13. Device-sized situations (`RuntimeImpl.situationBudget`) + +Numeric `situation.budget` -> as is. `"auto"` (default): WASM `1000 + round((min(4, max(1, threads)) - 1) * 1000 / 3)`; +otherwise (webgpu or unknown) `STATE_CHAR_BUDGET` = 2400; times `budgetScale` (x0.8 per `max_tokens_exceeded`, +floor 0.5; per instance, never resets; not applied to numeric budgets). Examples: 2400 -> 1920 -> 1536 -> 1229 -> +1200; WASM 1 thread 1000 -> 800 -> 640 -> 512 -> 500. Training budgets: the sim samples 3200/2000/1000 at 40/30/30 +(`sim/src/world/scenario.ts`), realapps the same (`realapps/src/harness/scenario.ts`), the Python curriculum +2400/2000/1667/1333/1000 at 35/20/5/5/35 (`training/curriculum/rt.py` -> `BUDGETS`, override `GC_RT_BUDGET`). + +### 14. Annotated examples (copied from `packages/runtime/STATUS.md`, produced by the tests) + +**A. delivery at a 1000-char budget (compact; `test/budget.test.ts`, 951 chars).** ``` app: /search -trigger: A write to search.results from GET /api/search?q=rea (#6) is about to be applied. +trigger: The response to GET /api/search?q=rea (#6) arrived and is about to be delivered; its operation last wrote search.results. facts: - search.results was written once by other operations since this write's cause (#6) started (version 0 → 1), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). - search.query changed since this write's cause (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. - This write comes from GET /api/search?q=rea (#6), started 0.90s ago, ended 0.00s ago with 200; its chain began with user typed "rea" into input "Search" (#5). - This write would change search.results: 2 items ["reac-1", "reac-2"] → 2 items ["rea-1", "rea-2"]. + search.results was written twice by other operations since its operation (#6) started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later user action (#7). + The response has search.results = 2 items ["rea-1", "rea-2"]: neither the current value 2 items ["reac-1", "reac-2"], nor the value when #6 started. + search.query changed since its operation (#6) started: "rea" → "reac", last by user typed "reac" into input "Search" (#7) 0.09s after #6 started. + The response to GET /api/search?q=rea (#6) arrived after 0.90s (200); the app has not seen it yet. + This request comes from user typed "rea" into input "Search" (#5), started 0.90s ago. in_flight: none -timeline: - -0.00s end GET /api/search?q=rea (#6): 200 in 0.90s -state: - search.results = 2 items ["reac-1", "reac-2"] (v1, by #8 0.69s ago) - search.query = "reac" (v4, by #7 0.81s ago) +timeline: none +state: none stats: GET /api/search: 4 done, 0 of last 4 failed, 4 in last 10s questions: diagnosis: What is happening here? expected | stale | conflict | duplicate | inconsistent | failing | slow | overload | unusual | transient - action: What should the runtime do with this write? apply | discard | defer + action: What should the runtime do with this response or message? deliver | discard ``` -- Fact 1 is M2 (versions, salient: another chain wrote `search.results` after the cause started); fact 2 is M5 - (inputs, salient because `search.query` is in the same store). Non-neutral facts come first, then provenance - (rank 7) and delta (rank 10). -- The timeline limit at 1000 chars is 3 lines, but timeline is the first thing dropped when over budget, so only the - newest line survives. `in_flight` is empty -> `"none"`. -- `stats` has no median/p95: only 4 latency samples (< 5). Compact questions (budget <= 1400) carry bare labels - (every criterion is `null`); the `questions:` lines are the test's printout, the model receives the `questions` - object and the packer renders it. +- Typeahead: four keystrokes; the `rea` response (#6, 900 ms) arrives after the newer `reac` (#8). In-order + responses never asked (`situation.test.ts` asserts exactly one delivery call). P comes from `last` (the trigger + says `last wrote`, so no profile for the signature existed yet), hence no D4 fact. +- Fact 1 is V-others, salient: #8 started after #6, is outside #6's chain, no newer `GET /api/search` is in flight. + Fact 2 is the neutral third-value content fact (the body was read because the delivery was a candidate). Fact 3 is + M5 (neutral now). Then D1, D2 (provenance, rank 7). +- `defer` is not offered (nothing related in flight). Over budget, timeline and state were dropped entirely. -**B. request at the full budget (from `test/situation.test.ts`).** +**B. delivery: a WebSocket message that would revert a pending local change (full budget, `test/delivery.test.ts`).** ``` -app: /search -trigger: POST /api/orders {items: [1], cardNumber: [redacted]} (#4) is about to be sent. +trigger: A WebSocket message /live (#5) arrived and is about to be delivered; messages like it last wrote board.cards.:id. facts: - 1 identical POST /api/orders request in the last 10s: #2 in flight (started 0.12s ago); #2 started 0.12s before this one; they come from separate user actions 0.12s apart. - This request comes from user clicked button "Place order" (#3), started 0.00s ago. - POST is not idempotent; its body (52 bytes) can be replayed. -in_flight: - POST /api/orders {items: [1], cardNumber: [redacted]} (#2) 0.12s so far, by #1 -timeline: - -0.12s user clicked button "Place order" (#1) - -0.12s start POST /api/orders {items: [1], cardNumber: [redacted]} (#2, by #1) - -0.00s user clicked button "Place order" (#3) - -0.00s start POST /api/orders {items: [1], cardNumber: [redacted]} (#4, by #3) -state: none -stats: none -questions: - diagnosis (choice): What is happening here? - action (choice): What should the runtime do with this request? - send: send the request now - coalesce: do not send; reuse the result of the identical request that is in flight or just finished - delay: wait before sending, backing off so the service can recover - block: do not send; fail this request immediately + board.cards.c1 has a pending local change: user clicked button "Move c1 to done" (#3) wrote it 0.05s ago and its PATCH /api/cards/c1 {col: "done"} (#4) is still in flight; this message (#5) started after that user action. + This message has board.cards.c1 = "todo", the value before user clicked button "Move c1 to done" (#3) changed it to "done" 0.05s ago (its PATCH /api/cards/c1 {col: "done"} (#4) is still in flight); delivering it would undo the user's change. + A WebSocket message (#5) {n: 2, card: "c1", col: "todo"} arrived on /live; the app has not seen it yet. ``` -- R3 is salient because the identical request #2 is still in flight (`close`). `cardNumber` is redacted - (`card` + `number` pair) in the op detail by the fetch observer. `serve_cached` is not offered (not a GET); - `coalesce` is offered because `canCoalesce` found #2. No baseline facts yet (no completions). `state` is `"none"` - because no store has been written by this signature. +- The value was located by the keyed-update rule (`{card: "c1", col: "todo"}` for `board.cards.c1`). A message with a + third value (`"review"`) is released without a model call (the pending PATCH decides; second WebSocket test). P is + the normalised pattern `board.cards.:id`, so while `c1` is pending every message on this channel is a candidate + (c1's pending conflict is on a matched field): a message about `c2` only (#3 in the first WebSocket test) still + has its body read, `c1` is not located in it, and it is released with no decision. STATUS.md "Open issues" says + such a message "is salient too"; with the batch-5 body rule it only pays the body read. -**C. failure at the full budget (from `test/situation.test.ts`; `app`, `in_flight`, `timeline`, `state` and the -questions are omitted here, see STATUS.md for the full text).** +**C. mutation not covered by a delivery (full budget, `test/situation.test.ts`; facts only).** ``` -trigger: GET /api/status (#12) failed (HTTP 503) and the app has not seen the failure yet. +trigger: A write to profile.name from task load profile (#1) is about to be applied. facts: - The request #12 failed: HTTP 503 after 0.06s; the app has not seen the failure yet. - 4 identical GET /api/status requests in the last 10s (latest 3: #6 answered 200 6.00s ago; #8 ended 503 4.00s ago; #10 ended 503 2.00s ago); #10 started 2.00s before this one, neither from a user action. - This is the 3rd GET /api/status failure in a row (recent outcomes: 200, 200, 503, 503, 503; last success 6.00s ago); error rate 50% over 6 requests (3 failed). - GET /api/status was requested 5 times in the last 10s (no usual rate learned yet). - This request comes from task poll (#11), started 0.06s ago. - GET is idempotent. - A cached 200 response from 6.00s ago exists for this request. -stats: - GET /api/status: 6 done, 3 of last 6 failed, 5 in last 10s + profile.name was written once by other operations since this write's cause (#1) started (version 0 → 1), last 0.30s ago by task save profile (#2), which started 0.10s after #1. + This write has profile.name = "Ada (cached)": neither the current value "Grace", nor the value when #1 started. + profile.saved changed since this write's cause (#1) started: 0 → 1, last by task save profile (#2) 0.10s after #1 started. + This write comes from task load profile (#1), started 0.40s ago. + This write would change profile.name: "Grace" → "Ada (cached)". ``` -- F1 is the only salient fact; the rest follow `RANK`: repetition (2), outcome F2 (4), baseline R8 (5), - provenance (7), request R11 (8), cache (9). R3 is neutral on `failure`. R9 is absent and stats show no median: - only 3 non-failure latency samples. The error rate uses real counts over the last <= 20 outcomes, the outcome list - shows the last 5. +- Tasks are not network ops, so no delivery gate covers the write; with `holdWrites` off the write applies at once + and the model's `discard` becomes a late revert (the test asserts `late: true` and the final value `Grace`). -**D. transition at the full budget (from `test/situation.test.ts`; facts and stats only, see STATUS.md for the rest).** +**D. failure with F5 scope, commit ambiguity and F6 cadence (full budget, `test/content.test.ts`; facts only).** ``` -trigger: POST /api/cart {} (#46) completed with a state change unlike its usual ones. +trigger: POST /api/orders {} (#8) failed (HTTP 500) and the app has not seen the failure yet. facts: - In the previous 22 completions of POST /api/cart its chain wrote cart.items and cart.total (22 of 22 times); this time it wrote only cart.items. - The last consistent state from before #45 started is 0.40s old; 1 field write happened since. - It ended 0.06s ago with 200 after 0.08s (usual 0.08s). - The completed operation #46 comes from user clicked button "Add" (#45), started 0.14s ago. - cart.items is now 23 items [1, 2, 3, …]. -stats: - POST /api/cart: 23 done, median 0.08s, p95 0.08s, 0 of last 20 failed, 23 in last 10s + The request #8 failed: HTTP 500 after 0.60s; the app has not seen the failure yet. + This is the 1st POST /api/orders failure in a row (recent outcomes: 201, 201, 201, 201, 500; last success 0.80s ago); error rate 17% over 6 requests (1 failed). + This POST failed with HTTP 500 after 0.60s (usual 0.50s): the server may have applied it before failing. + 2 other endpoints of this origin failed in the last 10s (2 failures, latest: GET /api/a 500, GET /api/b 503). + The browser reports that it is offline (navigator.onLine is false). + POST /api/orders runs on a schedule: every 0.60s (last 5 intervals); the next run is due in 0.00s. + POST /api/orders was requested 6 times in the last 10s (no usual rate learned yet). + POST /api/orders usually answers in 0.50s (p95 0.50s, 5 samples); error rate 17% over 6 requests (1 failed). + This request has no known cause: no operation was active when it started. + POST is not idempotent; its body (2 bytes) can be replayed. +``` + +- Only F1 is salient; the outcome facts (F2, commit, scope, offline) follow in emission order (all rank 4), then + baselines (5), provenance (7), request (8). + +**E. request with F7 (full budget, `test/situation.test.ts`; facts only).** + +``` +trigger: POST /api/orders {items: [1], cardNumber: [redacted]} (#4) is about to be sent. +facts: + 1 identical POST /api/orders request in the last 10s: #2 in flight (started 0.12s ago); #2 started 0.12s before this one; they come from separate user actions 0.12s apart. + User actions #1 and #3, 0.12s apart: both are clicks on button "Place order"; the request of #1 (#2) was still in flight at #3; the app changed no state between them. + This request comes from user clicked button "Place order" (#3), started 0.00s ago. + POST is not idempotent; its body (52 bytes) can be replayed. ``` -- T1 (`set` component, salient) is first; `only` because `{cart.items}` is a strict subset of the usual set. The - profile had 22 previous completions (>= 20) and the observed set was seen 0 times (< 1% of 22). -- Neutral facts follow `RANK`: T5 invariant (0), T3 baseline (5), T2 provenance (7, cause = the user click #45), - T4 delta (10). T4 printed because `cart.items` has no id-like segment, so the normalised chain key is also a - real path. -- The click #45 is profiled too (key `user <name>`, its chain includes #46's writes) and is equally unusual, but it - is an ancestor of #46, so only #46 (the descendant) is raised; the test asserts exactly one transition call. -- `stats` shows `0 of last 20 failed` although 23 are done: outcomes keep only the last 20 (`OUTCOMES`). -- Actions offered: `ignore`, `rollback` (the chain's write is the latest and its previous value is known); no - `resync` because the test store has no resync handler. +STATUS.md also has full-budget examples for F1 item cells, F2 autosave over typed text, a polled failing endpoint, +stall, inconsistency, transition and error. ## Configuration and constants | name | type | value | defined in | effect | |---|---|---|---|---| -| `LAT_WINDOW` | const | 64 | `learn/baselines.ts` | latency samples kept per signature | -| `START_WINDOW` | const | 128 | `learn/baselines.ts` | start times kept per signature (rate) | -| `WINDOW_MS` | const | 10000 | `learn/baselines.ts` | "recent" window for `rate()` | -| `ERR_ALPHA` | const | 0.1 | `learn/baselines.ts` | EWMA weight of the error rate | -| `MIN_LAT_SAMPLES` | const | 5 | `learn/baselines.ts` | latency baseline exists from 5 samples (also gates stall watching) | -| `OUTCOMES` | const | 20 | `learn/baselines.ts` | outcomes kept; failure counts are over these, facts list the last 5 | -| `MAX_SIGS` | const | 1000 | `learn/baselines.ts` | signatures kept (FIFO) | -| identity cap / gap EWMA | inline | 1024 ids; `0.8 * old + 0.2 * gap` | `Baselines.noteIdentity` | identical-request gap baseline | -| usual-rate guard | inline | `older >= 3`, `span >= 20000` ms | `Baselines.rate` | when `usual` is reported | -| `MIN_COMPLETIONS` | const | 20 | `learn/profiles.ts` | completions before any profile anomaly; also per-field minimum for kind anomalies | -| `RARE` | const | 0.01 | `learn/profiles.ts` | rarity threshold (`seen < 0.01 * of`) | -| `MAX_SETS` / `MAX_FIELDS` | const | 64 / 128 | `learn/profiles.ts` | per-profile caps | -| profile signature cap | inline | 2000 | `Profiles.add` | profiles kept (FIFO) | -| write buckets | fn | `0`, `1`, `2`, `3-4`, `5+` | `writesBucket` | shape component | -| duration buckets | fn | `<50ms`, `50-200ms`, `0.2-1s`, `1-5s`, `>5s` | `durBucket` | recorded, never checked | -| `PROFILED` | const | fetch, xhr, user, task, ws | `runtime.ts` | op kinds that get profiles | -| `PROFILE_KEY` | const | `"genclass.profiles.v1"` | `runtime.ts` | localStorage key with `learn.persist` | -| `STALL_MIN_MS` | const | 500 | `runtime.ts` | stall fires at `max(4 × median, 2 × p95, 500)` ms | -| `LONG_RUNNING_MS` | const | 10000 | `runtime.ts` | in-flight ops older than this do not block settled points | -| `settleMs` | option | 60 ms | `InitOptions.settleMs` | quiet time before a settled point | -| `triage` | option | `"salient"` | `InitOptions.triage` | `"always"` consults on every trigger | -| `situation.budget` | option | `"auto"` | `InitOptions.situation` | situation size in chars | -| `learn.persist` | option | false | `InitOptions.learn` | persist transition profiles | -| `MAX_FACTS` | const | 12 | `situation/facts.ts` | facts kept after ordering | -| `WINDOW` | const | 10000 | `situation/facts.ts` | repetition / pending-local-change window | -| plugin fact length | inline | 240 | `buildSituation` | plugin fact truncation | -| timeline source | inline | last 96 events | `timelineLines` | events considered for the timeline | -| `STATE_CHAR_BUDGET` | const | 3200 | `situation/serialize.ts` | full budget; default when no budget given. The `serialize.ts` comment assumes ≈ 3.2 chars/token (≈ 1,000 tokens); TRAIN measured ≈ 2.4 (`training/NEEDS.md` item 6a), i.e. ≈ 1,300–1,400 tokens ([model-io-contract](../model-io-contract.md)) | -| `COMPACT_BUDGET` | const | 1100 | `situation/serialize.ts` | budget at and below which section limits are smallest | -| `MIN_BUDGET` | const | 500 | `situation/serialize.ts` | smallest budget honoured | -| `LIMITS` | const | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | full-budget section counts | -| compact counts | inline | facts 6, in_flight 2, timeline 3, state 3, stats 1 | `sectionLimits` | compact section counts | -| line limits | inline | compact -> full: app 60->120, trigger 180->240, facts 220->260, in_flight 90->120, timeline 100->140, state 100->150, stats 110->140 | `sectionLimits` | per-line truncation | -| fact/trigger shortening floor | inline | 60 chars | `toJevState` | last-resort shortening | -| `COMPACT_QUESTIONS_BUDGET` | const | 1400 | `situation/questions.ts` | compact questions at or below | -| `COMPACT_DESC_MAX` | const | 24 | `situation/questions.ts` | vocabulary overrides kept in compact questions | -| auto budget | fn | webgpu/unknown 3200; wasm 1000/1333/1667/2000 for 1/2/3/4+ threads | `RuntimeImpl.situationBudget` | device sizing | -| `budgetScale` | field | 1, `× 0.8` per `max_tokens_exceeded`, floor 0.5 | `RuntimeImpl` constructor | shrinks auto budgets | -| `REDACTED` | const | `"[redacted]"` | `util.ts` | redaction marker | -| `redact` | option | `defaultRedact` | `InitOptions.redact` | replaces the redactor for every situation sentence | -| `app` | option | `document.title` + `location.pathname` | `CreateOptions.app` (`RuntimeImpl.appInfo`) | source of the `app` section (`"<title> — <route>"`) | -| `vocabulary` | option | none | `InitOptions.vocabulary` | `diagnoses` replaces `DEFAULT_DIAGNOSES`; `actions` overrides descriptions | -| `historySize` | option | 500 | `InitOptions.historySize` (`EventLog`) | events kept; the timeline reads the last 96 of them | -| `HIST` / `LOG` | const | 16 / 512 per field | `state/hub.ts` | rich history (before/after, used by M5 before-values, M10, I2) / version log (M2/M3 counts, `versionAt`) | -| `RECENT_MS` / `RECENT_MAX` | const | 10000 ms / 256 | `state/hub.ts` | `hub.recent` window for identical-change facts (M12, ask) | -| identical-request registry | inline | 12 ops per identity, 512 identities | `RuntimeImpl.registerIdentity` | `SitEnv.identical`, R3 | -| recent errors | inline | 64 kept, 10 s window | `RuntimeImpl.reportError` / `makeEnv` | E5, ask | -| consistent snapshots | inline | 8 kept | `RuntimeImpl.settled` | `lastConsistent`, `consistentBefore`, I3/T5/E6, rollback | -| `storeWriters` caps | inline | 1000 signatures; writer + 8 ancestors | `RuntimeImpl.onApplied` | M7, timeline relevance, involved stores | -| profile queue | inline | 2000 ops | `RuntimeImpl.queueProfile` | ops waiting for a settled point | -| profile save delay | inline | 5000 ms | `RuntimeImpl.saveProfilesSoon` | with `learn.persist` | -| `defer` limit | inline | `m.defers < 2` | `builtinApplicable` | defer offered at most twice per write | -| `retry` limit | inline | `op.attempt < 4` | `builtinApplicable` | retry offered for attempts 1-3 | -| fact list caps | inline | M2-M4/M10/M15: first 3 paths; M5: 2 fields; M6: 3 ops listed; M14: 2; R3: last 3; R4: 3; F3/E3: 4 paths; I1: 3 violations, I2: 2 writes each; T1: 3; T4: 3; ask: 5 chain keys, 6 fields, 2 violations | `facts.ts` | sentence counts per trigger | -| per-sentence truncations | inline | `opLabel` 90; in-flight/timeline op phrase 80; error message 120 (subject, E1), 80 (short subject), 100 (timeline); error source 60; network message 50; `statusText` error text 40; op detail in M6/R4 30; plugin fact 240; store `describe()` 110 (90 when the store path itself is involved) | `describe.ts`, `facts.ts`, `build.ts` | applied before section line limits | +| `LAT_WINDOW` / `START_WINDOW` / `WINDOW_MS` | const | 64 / 128 / 10000 | `learn/baselines.ts` | latency samples, start times, rate window | +| `ERR_ALPHA` / `MIN_LAT_SAMPLES` / `OUTCOMES` / `MAX_SIGS` | const | 0.1 / 5 / 20 / 1000 | `learn/baselines.ts` | EWMA (unused), latency baseline minimum (also gates stalls), outcomes kept, signatures | +| `MIN_COMPLETIONS` / `RARE` / `MAX_SETS` / `MAX_FIELDS` | const | 20 / 0.01 / 64 / 128 | `learn/profiles.ts` | rarity rule and caps; 2000 profiles (inline) | +| `KEEP` / `MAX_SIGS` / `TOLERANCE` / `MIN_PERIOD_MS` | const | 9 / 500 / 0.25 / 250 | `learn/cadence.ts` | cadence history, signatures, interval fit, smallest period | +| cadence thresholds | inline | periodic >= 4 starts, >= 75% fit, stale after 3 periods; debounced >= 3 delays, median >= 100 ms, fit `max(50, 25%)` | `Cadence.get` | F6 | +| `PENDING_WINDOW_MS` | const | 10000 | `situation/conflicts.ts` | pending-local-change window | +| `MAX_MATCHED` | const | 64 | `situation/conflicts.ts` | matched fields per delivery | +| `ITEM_ID` | const | id, _id, uuid, slug, key | `situation/content.ts` | item id keys for joins/locating | +| `MAX_NODES` / `MAX_DEPTH` / `MAX_ITEMS` | const | 20000 / 8 / 2000 | `situation/content.ts` | body index bounds | +| `RYW_WINDOW_MS` | const | 10000 | `situation/content.ts` | creates considered by RYW | +| `parseJsonBody` max | default arg | 256 KB | `situation/content.ts` | bodies larger or non-JSON are ignored | +| analyzed fields / shown content facts | inline | 32 / 3 | `analyzeBody` / `contentFacts` | bounds | +| `SCOPE_MS` | const | 10000 | `situation/evidence.ts` | F5 window | +| `NOT_PROCESSED` | const | 502, 503, 429, 408 | `situation/evidence.ts` | statuses that mean "not applied" | +| `BODY_WAIT_MS` | const | 100 | `runtime.ts` | max wait for a delivery body | +| `DISCARD_MARK_MS` | const | 10000 | `runtime.ts` | how long a delivery `discard` keeps dropping writes | +| `LONG_RUNNING_MS` | const | 10000 | `runtime.ts` | also the max wait of delivery `defer` (`waitOps`) | +| `BACKGROUND_DEADLINE_MS` / `LATE_REVERT_MS` | const | 5000 / 2000 | `runtime.ts` | background decision deadline; late revert window | +| creates / outcomes buffers | inline | 16 entries, 30 s / 128 entries, 30 s | `noteResponse` / `endOp` | RYW, F5 | +| `lastChainMap` cap | inline | 1000 signatures | `onApplied` | `SitEnv.lastChain` | +| F9 slow mark | inline | ok, `>= 5 x median` and `>= 300 ms` over it | `markWrites` | stale mark | +| delivery `defer` limit | inline | `defers < 2` | `builtinApplicable` | at most two defers | +| covered walk | inline | 16 causes | `covered`, `dropFilter` | how far up the chain a delivery is looked for | +| `STALL_MIN_MS` / `PROFILED` / `PROFILE_KEY` | const | 500 / fetch, xhr, user, task, ws / `genclass.profiles.v1` | `runtime.ts` | unchanged | +| `MAX_FACTS` / `WINDOW` | const | 12 / 10000 | `situation/facts.ts` | facts kept; repetition window | +| `STATE_CHAR_BUDGET` | const | **2400** (was 3200) | `situation/serialize.ts` | full budget, default; comment: ≈ 2.4 chars/token measured, ≈ 1,000 tokens | +| `COMPACT_BUDGET` / `MIN_BUDGET` | const | 1100 / 500 | `situation/serialize.ts` | compact limits; smallest budget | +| `LIMITS` | const | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `situation/serialize.ts` | full counts | +| `COMPACT_QUESTIONS_BUDGET` / `COMPACT_DESC_MAX` | const | 1400 / 24 | `situation/questions.ts` | compact questions | +| auto budget | fn | webgpu/unknown 2400; wasm 1000/1333/1667/2000 | `RuntimeImpl.situationBudget` | device sizing | +| `budgetScale` | field | x0.8 per overflow, floor 0.5 | `RuntimeImpl` | shrinks auto budgets | +| `stringDiff` width | default arg | 30 chars, 14 before the difference, change text 28 | `state/fields.ts` | long string previews | +| `OPAQUE` / `WEAK_CONTAINER` | const | >= 20 credential-like chars / auth, authorization, cookie, session | `util.ts` | container redaction rules | +| `policy.holdWrites` | option | false | `PolicyOptions.holdWrites` | true restores held `mutation` triggers (`gateMutation`) | +| `mode` | option | `"observe"` (was guard; commit f3636b2) | `InitOptions.mode` (inherited by `CreateOptions`); default applied in the `RuntimeImpl` constructor | observe never holds or acts; decisions still made for detection | +| `triage`, `situation.budget`, `learn.persist`, `redact`, `vocabulary`, `historySize`, `settleMs`, `app` | options | as before | `InitOptions` / `CreateOptions` | see [public-api-and-lifecycle](public-api-and-lifecycle.md) | +| `observe.eventsource`, `observe.untrustedEvents` | options | on / false | `InitOptions.observe` | EventSource messages become delivery candidates; synthetic DOM events count as user actions | ## Invariants and gotchas -- **Train/runtime parity.** Any change to `src/situation/*`, `src/learn/*`, the formatters in `src/util.ts` - (`secs`, `rel`, `fmtNum`, `ratio`, `truncate`, `describe`, `normalizePath`), `changeText` in - `src/state/fields.ts`, or op details produced by observers changes model inputs. The final-round training data - comes from tag `situation-v1` (no model is deployed yet: the 0.1.0-alpha.0 runtime takes no actions until the model - package is published, per `OPEN_TASKS.md`); a change needs new sim data (`sim/`), an update of - `training/curriculum/rt.py` (Python port - of facts/describe/build/serialize/questions), retraining and new eval. Coordinate with SIM and TRAIN (STATUS.md: - "Any change to situation wording must be coordinated with SIM"). -- **Model input also lives outside `src/situation/`.** Timeline lines include `ActionEffect.changed` sentences - (`runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`, e.g. `Dropped the write to …; search stays at version 3.`), - the undo text `undid <action> (<id>)`, the failed-action text `Tried to <action> <subject> but it failed; …`, - hub write summaries (`changeText`), op details produced by observers (`redactSearch`, body summaries), and - `rt.user` target/value strings. Rewording any of these changes training inputs exactly like a fact change does. -- **What the sim exercises.** `sim/src/run/rt.ts` -> `createOptions` runs the real runtime with `model: false`, a - scripted `decider`, `mode: "heal"`, `triage: "salient"`, `historySize: 500`, observers `fetch`, `timers`, - `websocket` only (xhr, user DOM, errors, nav, storage, perf off), a fixed `situation.budget`, and the module named - by env `GENCLASS_RUNTIME` (default `@genclass/runtime`). User actions and errors are fed directly through - `runtime.user(...)` and `runtime.reportError(...)` (`sim/src/run/runner.ts`). XHR request/failure/stall - situations and `nav`/`storage`/`perf` timeline lines come only from disabled observers, so sim rows should not - contain them (inferred from `createOptions`; not checked against generated data). -- **Determinism.** Read time only from `env.now()` (injected clock). No `Date.now`, `Math.random`, locale formatting - or iteration over unordered structures. Sorts must be stable with explicit tie-breaks (as in `orderFacts`, - `inFlightLines`). Tests assert byte-identical situations. -- **Side-effect free.** Situation code must not create ops, push events or write stores. The single allowed write is - `C.reads.set(path, vStart)` in `mutationFacts`. (On the runtime side, the `SitEnv.recentErrors()` implementation in - `RuntimeImpl.makeEnv` also prunes entries older than 10 s from `RuntimeImpl.errorsRecent`; this only drops expired - entries.) The sim relies on `rt.situation()` not perturbing counterfactual replays (sim/NEEDS.md item 5). -- **Fail open.** Exceptions in `computeFacts`/`buildSituation` run the passive action; plugin `facts()` and - `applicable()` throws are swallowed. -- **Triage is cost, not policy.** A `neutral` flag must never encode "this is a bug". Making facts non-neutral - increases model calls and **holds** (writes/requests wait up to the hold budget): OPEN_TASKS lists hold-induced - latency (search clean-run latency 14 -> 125 ms with v0.1) and typeahead being salient about 6 times per clean trial. -- **Neutral is per trigger for R3/R5.** The same repetition/streak fact is salient on `request` but neutral on - `failure`/`stall`; R7 (hot rate) is salient on all three. +- **Train/runtime parity.** Any change to `src/situation/*`, `src/learn/*`, the formatters and redaction in + `src/util.ts`, `changeText`/`stringDiff` in `src/state/fields.ts`, the delivery gate rules in `runtime.ts` + (`runDelivery`, `covered`, `markWrites`, `onChannel`), message summaries (`observe/messages.ts`) or op details + changes model inputs or which rows exist. [HANDOFF.md](../../../HANDOFF.md): "The training format is frozen at `situation-v2` … + Coordinate before touching it." A change needs a new tag, regenerated sim/realapps data, an update of + `training/curriculum/rt.py` and retraining. +- **Delivery salience is decided twice.** `runDelivery` pre-filters (conflicts + body comparison) and only then + calls `trigger()`, whose cheap pass recomputes facts. Both must agree: a fact that is non-neutral when the + pre-filter released the delivery is never seen; a candidate whose facts are all neutral is released by the cheap + pass. When you change one rule, change both (`conflicts.ts`/`content.ts` and `runDelivery`). +- **Body reads are bounded and only for candidates.** Non-salient deliveries read nothing and add no latency; a + candidate waits at most 100 ms of clock time for its body. The app's own body is never consumed (fetch uses the + runtime's buffered clone). +- **No store holds by default.** `mutation` is non-blocking (priority 1, background, 5 s deadline); discard is a late + revert (<= 2 s, fields unchanged since). Writes covered by a delivery decision raise no `mutation` at all, except + with `triage: "always"`. M13 and `defer` only mean something with `holdWrites: true`. Caveat: delivery candidates + still wait up to 100 ms for the body, and in observe mode their background decision is dropped as stale before + reaching the model (see §4 step 6). +- **Newer same-signature request in flight neutralises newer-data conflicts** (`newerSameSignature`, fetch/XHR + only): in-order typeahead and autosave make zero model calls; the in-flight request is still stated (M6, neutral). +- **A plain user write is not a conflict.** Only a user-rooted write whose request of another signature is in flight + (pending) counts, and for delivery only when the body would revert it. Typed text counts only via F2. +- **Predicted sets are normalised patterns** (`board.cards.:id`): any message about the same collection becomes a + candidate while one item is pending (extra latency, never a wrong drop; `discard` drops only protected or + written-over fields). +- **Statements are about the response's content**, located heuristically; an app that transforms data can make + content facts uninformative but not false. Ambiguous bodies produce no content facts. +- **Side effects of the gate (outside fact code).** `runDelivery` sets `op.delivery` and, through the controller, + `op.discardMark`; `markWrites` and `onChannel` set field marks; `noteResponse` parses create bodies in the + background. Fact code itself still writes only `X.reads`. `rt.situation()` stays side-effect free (tested). +- **Determinism.** Read time only from `env.now()`; body reads and create parsing are promise-based but timed by the + injected clock (`BODY_WAIT_MS` uses `clock.setTimeout`). Tests assert byte-identical situations + (`situation.test.ts`, `budget.test.ts`). +- **Fail open.** Throws in `computeFacts`/`buildSituation` are logged and the passive path runs; an `analyzeBody` + throw is logged and the gate decides on newer-data conflicts alone; a `markWrites` throw is logged (the write has + already applied, it just gets no mark). +- **Triage is cost, not policy.** A `neutral` flag must never encode "this is a bug". - **Fact order matters beyond the model.** The budget keeps the first facts; `decide/report.ts` and devtools - `topFact` (`devtools/ui.ts`) pick the first fact not matching `^This (write|request) (comes from|has no known - cause)` as the headline. Renaming provenance wording breaks that regex. -- **Two fact lists.** `Situation.facts`/`Decision.facts`/`explain()` hold up to 12 ordered facts; `state.facts` - holds what fits the budget (at least 1). Plugin facts rank last and are the first to be cut. -- **No action question with a single action.** E.g. `error` without a revertable chain offers only `ignore`, so - `questions.action` is absent and the gate sees no action answer (passive). -- **Compact thresholds differ.** Section limits bottom out at 1100 chars; compact questions start at <= 1400. -- **Budget is characters, not tokens.** Overflow in the model host raises `max_tokens_exceeded`, which permanently - shrinks auto budgets for the runtime instance (fixed numeric budgets are not scaled). -- **`opts.describe` bypasses redaction.** A store's custom `describe()` output is printed as is in state lines. -- **Normalised chain keys.** `OpRec.chain` keys are normalised (`:id`), and transition `involvedFields`, - `transitionFacts` (T4) and `SubjectRef.paths` use them; such paths have no leaf, so their state lines and - `is now` facts are silently skipped. -- **Baselines cover fetch/XHR only.** WebSocket/task subjects get no stats line, and M8 (cause latency) is only - computed for fetch/XHR causes. - 4xx responses are non-failures (they reset the streak and add latency samples) but do not update `lastSuccess`. - Latency baselines never include failed/timed-out requests, so they underestimate slowness during outages. -- **Rarity needs `seen == 0` up to 100 completions** (`seen < 0.01 * of`). Profiles check before adding, and - descendants win over ancestors when both are unusual. -- **Eviction is FIFO** for baselines (1000 signatures), identities (1024), profiles (2000): a long-lived hot - signature can be evicted by many new ones. -- **`lastBuilt` only updates past the cheap pass**, so `rt.situation("mutation")` can return an old situation or a - relabelled "ask about now" one. -- **`rt.situation()` is always `salient: true`.** With no argument (or no stored situation for the trigger) it builds - an `ask` situation, and `ask` is salient by definition. The devtools Now view (`devtools/index.ts`, which calls - `rt.situation()`) therefore always shows the "salient: the model would be asked" chip. To judge triage of a real - trigger, check whether any fact is non-neutral (`computeFacts`) or use `rt.situation(trigger)` after that trigger - was built. -- **Facts are computed before the subject proceeds.** For `failure`, the failed op is already ended and in the - baselines (fetch and XHR call `endOp` before raising the trigger; streak/outcome counts include it); for `mutation`, the write is not yet applied (M15 describes the - pending change, state lines show the current value). -- **`Profiles.load` trusts its input.** It only checks `sig` (string) and `n` (number) per entry and does not apply - the 2000-signature cap; a corrupt `genclass.profiles.v1` entry with missing maps can throw later in `check`/`add` - (inside `settled()`, unguarded) (unverified: not tested). -- **Dead declarations.** `SigStats.firstStart` and `SigStats.failures` (lifetime failure count) are written but - never read; `SigStats.errEwma` is read only by `Baselines.snapshot()`, which nothing in `src/` calls; - `SitEnv.writtenByChain` is never implemented; `isTrigger` is never imported. Removing them changes no model input. -- **Past bugs fixed in batch 3 (keep fixed):** "started X after/before" uses the real direction - (`test/review-fetch.test.ts`); failure facts use real counts, not the EWMA; version counts come from the 512-entry - log, not the 16-entry history (`test/review-hub.test.ts`); "changed twice and is back to 6" instead of "6 → 6"; - parent paths never print `= undefined`; array kinds are empty/non-empty only (short last page is not unusual); - digit-containing entity keys normalise to `:id` (`test/review-precision.test.ts`); redaction by word meaning. + `topFact` skip provenance matching `^This (write|request) (comes from|has no known cause)`. D1 (`The response to … + arrived …`) is provenance-kind but does not match that regex, so it can become a report headline. +- **Budget is characters.** Full budget is now 2400; budgets above it give the same section counts but more room. +- **`opts.describe` bypasses redaction**; booleans/null are never redacted; store names never redact fields. +- **Normalised chain keys** have no leaf: their state lines and `is now` facts are skipped; transition F9/RYW use + `matchFields` to get concrete paths. +- **Baselines and cadence cover fetch/XHR only**; WebSocket/task subjects get no stats line. +- **Eviction is FIFO** for baselines (1000), identities (1024), profiles (2000), cadence (500), `lastChainMap` + (1000). +- **`rt.situation()` is always `salient: true`** when it falls back to an `ask` situation. +- **`Profiles.load` trusts its input** (unverified: a corrupt entry may throw later inside `settled()`). +- **Dead declarations.** `SigStats.firstStart`, `SigStats.failures`, `SigStats.errEwma` (only `snapshot()`), + `SitEnv.writtenByChain`, `isTrigger`, `SigCadence.userStarts`. +- **Past bugs fixed (keep fixed):** batch 3 items (direction of "started after/before", real failure counts, + 512-entry version log, "is back to", no `= undefined`, empty/non-empty array kinds, digit keys -> `:id`, word-level + redaction); NaN store values no longer recurse forever (commit ad24804, `test/nan.test.ts`). ## How to change it safely **Change a fact's wording or add a fact** -1. Edit the relevant function in `packages/runtime/src/situation/facts.ts`; pick `kind` (sets rank) and `neutral` - deliberately (see Triage). Keep numbers explicit and relations stated ("after", "newer", "in a row"). -2. Check consumers of the wording: `decide/report.ts` and `devtools/ui.ts` regex on provenance; tests that match - text (`grep -rn "state.facts" packages/runtime/test`). -3. Update the Python port `training/curriculum/rt.py` (same computation and ordering). -4. Update tests: `test/situation.test.ts`, `test/batch3.test.ts`, `test/budget.test.ts`, plus any review test - matching the text. Update the example blocks in `packages/runtime/STATUS.md`. -5. Run locally (lead policy, [where to run things](build-test-release.md#where-to-run-things)) or on the VM: `cd packages/runtime && npx vitest run test/situation.test.ts test/budget.test.ts - test/learn.test.ts test/batch3.test.ts test/review-*.test.ts` (then the full suite; see - [build-test-release](build-test-release.md)). -6. Flag the parity break: new sim data, retraining, a new freeze tag (after `situation-v1`). - -**Change a triage threshold** (e.g. 3× latency in M8, `close` in R3, hot rate in R7): edit the `neutral` expression -in `facts.ts`; add a test that a benign case stays quiet (pattern: `test/review-precision.test.ts`) and a positive -case reaches `decider.calls`; mirror in `training/curriculum/rt.py`; regenerate sim data (the set of rows changes). - -**Change budgets or section limits**: `serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `LIMITS`, the `lerp` -endpoints) and/or `RuntimeImpl.situationBudget`; update `test/budget.test.ts` expectations, `section_limits` / -`to_state` in `training/curriculum/rt.py`, sim budget sampling in `sim/src/world/scenario.ts`, the doc comment on -`InitOptions.situation` in `types.ts`, and `docs/runtime/API.md`. Check the model host's maximum sequence length. - -**Add a trigger kind**: `TriggerKind` (`types.ts`), `SubjectSpec` (`env.ts`), `subjectOf`, `subjectOp`, -`involvedStores`, `involvedFields`, `builtinApplicable`, `subjectRef` (`build.ts`), `computeFacts` (`facts.ts`), -`TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS` (`questions.ts`), a raise site with a `Controller` in -`runtime.ts`/observers, the sim and the Python port. `isTrigger` derives from `TRIGGER_ACTIONS`. - -**Add or reword a built-in action**: `BUILTIN_ACTIONS` (tier + description), `TRIGGER_ACTIONS` (order: passive -first), `builtinApplicable`, the controller's `run()` for that trigger in `runtime.ts`/observers, policy tiers -([decide-policy-actions](decide-policy-actions.md)), `ACTIONS`/`TRIGGER_ACTIONS` in `training/curriculum/rt.py`, the -fake runtime in `sim/src/run/fake-runtime.ts`, `TIER` in `sim/src/oracle/cost.ts`, `ACTION_PARA` in -`sim/src/run/transform.ts`, `PASSIVE` in `sim/src/types.ts` (passive actions), `ACTION_DESC`/`TRIGGER_ACTIONS`/`TIER` -in `training/curriculum/fmt.py`, `TIER`/`PASSIVE` in `training/eval_runtime.py`; full list: -[model-io-contract recipes](../model-io-contract.md#recipes). - -**Change the diagnosis vocabulary**: `DEFAULT_DIAGNOSES` (keep `expected` first; `test/batch3.test.ts` asserts -`unusual`, `transient` are last), `DEFAULT_DIAGNOSES` in `sim/src/world/scenario.ts` (the sim passes it explicitly -when the runtime lacks a label), `DIAG_PARA` in `sim/src/world/scenario.ts`, `DIAGNOSES` in `sim/src/types.ts`, the -rules in `sim/src/oracle/diagnose.ts`, `DIAGNOSES` in `training/curriculum/rt.py`, `DIAG_DESC` in -`training/curriculum/fmt.py`, CONTRACT §6; full list: [model-io-contract recipes](../model-io-contract.md#recipes). - -**Change baseline estimators or profile rarity**: `baselines.ts` / `profiles.ts`; update `test/learn.test.ts`, -`test/review-precision.test.ts`, `test/situation.test.ts` (stall timing depends on median/p95). Note that -`watchStall` timing and facts R7-R9, S1, M8 all read these values. - -**Change redaction**: `isSensitiveName`/`SECRET_WORDS`/`SECRET_PAIRS` in `util.ts`; update `test/batch3.test.ts` -(SIM a) and `test/review-redaction.test.ts`; `docs/runtime/API.md` "Privacy". - -**Add a fact kind**: `FactKind` in `types.ts`, its rank in `RANK` (`facts.ts`; typed `Record<FactKind, number>`, so -the compiler forces an entry), `RANK` in `training/curriculum/rt.py`. Rank decides which facts survive the budget, -and the report/devtools headline skips only provenance. - -**Change timeline or action-effect wording**: `eventLine` (`describe.ts`), the hub's write summary -(`state/hub.ts`, `changeText` in `state/fields.ts`), `ActionEffect.changed` strings (`runtime.ts`, -`observe/fetch.ts`, `observe/xhr.ts`), `event_lines` / `phrase` in `training/curriculum/rt.py`; update the STATUS.md -example blocks; treat it as a parity break like a fact change. - -**Change what `stats` or `in_flight` show**: `statsLines` / `inFlightLines` (`build.ts`). Keep the sort keys -explicit (score, then start time) for determinism; budget tests assert per-section maxima. +1. Edit the function in `situation/facts.ts`, `content.ts` or `evidence.ts`; pick `kind` (rank) and `neutral` + deliberately. For delivery, also check the `runDelivery` pre-filter. +2. Check consumers: `decide/report.ts` and `devtools/ui.ts` provenance regex; tests matching text + (`grep -rn "state.facts" packages/runtime/test`). +3. Mirror in `training/curriculum/rt.py` (facts, conflicts, content, evidence are ported there). +4. Update tests (`situation.test.ts`, `delivery.test.ts`, `content.test.ts`, `budget.test.ts`, `batch3.test.ts`, + review tests) and the example blocks in `packages/runtime/STATUS.md`. +5. Run: `cd packages/runtime && NODE_OPTIONS=--expose-gc npx vitest run test/situation.test.ts test/delivery.test.ts + test/content.test.ts test/budget.test.ts test/learn.test.ts test/batch3.test.ts test/review-*.test.ts`, then the + unit suite (see [build-test-release](build-test-release.md); light local runs are fine on the lead's machine). +6. Flag the parity break: a new freeze tag after `situation-v2`, new sim and realapps data, retraining. + +**Change the delivery gate or conflict rules**: `conflicts.ts` (`newerConflict`, `pendingConflict`, +`newerSameSignature`, `predictedWrites`), `RuntimeImpl.runDelivery` (pre-filter, body wait), `RuntimeImpl.covered` +(which writes skip `mutation`), `dropFilter`/`writtenOver` (what `discard` drops). Keep `test/delivery.test.ts` +typeahead cases at zero model calls, and `test/no-reorder.test.ts` passing (never-worse: same dispatch order and +final state as observe mode). Re-run the realapps never-worse sweep before freezing (needs the user's go-ahead; see +[realapps](../realapps.md)). + +**Change a triage threshold** (M8 3x latency, R3 `close`, R7 hot rate, F9 5x slow mark): edit the expression; add a +benign case that stays quiet (pattern: `test/review-precision.test.ts`) and a positive one that reaches +`decider.calls`; mirror in `rt.py`; regenerate data. + +**Change budgets or section limits**: `serialize.ts` and/or `RuntimeImpl.situationBudget`; update +`test/budget.test.ts`, `section_limits`/`to_state`/`BUDGETS` in `rt.py`, budget sampling in +`sim/src/world/scenario.ts` and `realapps/src/harness/scenario.ts`, the `InitOptions.situation` doc comment in +`types.ts`, `docs/runtime/API.md`, ARCHITECTURE.md and CONTRACT §6. Check the model host's maximum sequence length. + +**Add a trigger kind**: `TriggerKind`, `SubjectSpec`, `subjectOf`, `subjectOp`, `involvedStores`, `involvedFields`, +`builtinApplicable`, `subjectRef`, `computeFacts`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS` (and +`TRIGGER_DESCRIPTIONS` if wording differs), `buildSituation` draft, a raise site with a `Controller`, devtools +nouns, the sim, `rt.py`, `fmt.py`. `delivery` (batch 4) is the worked example: `git show fcd1e68 -- +packages/runtime/src/situation`. + +**Add or reword a built-in action**: `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `TRIGGER_DESCRIPTIONS`, +`builtinApplicable`, the controller's `run()`, policy tiers, and the sim/training lists +([model-io-contract recipes](../model-io-contract.md#recipes)). + +**Change the diagnosis vocabulary**: `DEFAULT_DIAGNOSES` (keep `expected` first) plus the sim and training copies +([model-io-contract recipes](../model-io-contract.md#recipes)). + +**Change baselines, profiles or cadence**: `baselines.ts` / `profiles.ts` / `cadence.ts`; update `test/learn.test.ts`, +`test/review-precision.test.ts`, `test/content.test.ts` (F6), `test/situation.test.ts` (stall timing). Profiles now +also drive delivery prediction (`predictedWrites`). + +**Change redaction**: `isSensitivePath`/`isSensitiveName`/`SECRET_WORDS`/`SECRET_PAIRS`/`WEAK_CONTAINER`/`OPAQUE` in +`util.ts`; update `test/batch3.test.ts` (auth store), `test/review-redaction.test.ts`, API.md "Privacy". + +**Change timeline or action-effect wording**: `eventLine` (`describe.ts`), `changeText`/`stringDiff` +(`state/fields.ts`), effect strings in `runtime.ts` (`runDelivery` discard/defer, `onDropped`) and observers, +`event_lines`/`phrase` in `rt.py`; treat as a parity break. ## Tests | test file | what it asserts | |---|---| -| `packages/runtime/test/situation.test.ts` | one situation per trigger (except `ask`): key order, <= 12 facts, <= 16 timeline, <= 8 state lines, `stateChars <= 3200`, `diagnosis` present; first-fact text for mutation (stale write, M2), stall (`has been in flight for …; GET /api/report/:id usually takes`), inconsistency (relation values), transition ("only cart.items") and error (`Uncaught TypeError: `); some fact matches for request (identical POST in flight) and failure (`3rd GET /api/status failure in a row`); the card number value `4242` never appears in the state; inconsistency offers exactly `ignore, rollback`; transition raised once (descendant wins); `situation()` side-effect free and `trigger: "ask"`; serializer: an over-budget input ends with `timeline: "none"`, an under-budget one keeps all 16 timeline lines and empty sections become `"none"`; byte-identical determinism at the default budget | -| `packages/runtime/test/learn.test.ts` | baselines: no latency before 5 samples, nearest-rank median/p95, EWMA, streak, `!` outcomes, aborted ignored, `rate` recent/usual, identity `gapEwma`; profiles: < 1% of >= 20, op that usually writes nothing, kind and status anomalies, end-to-end transition with chain rollback | -| `packages/runtime/test/budget.test.ts` | `sectionLimits` at 1100/2000/3200/500; budgets 1000/1100/2000 respected per section with the stale-write fact first; compact questions at <= 1400 and overrides <= 24 chars; determinism at 1100; auto budget by device/threads; `max_tokens_exceeded` -> 2560; hold budget | -| `packages/runtime/test/batch3.test.ts` | `isSensitiveName` positives/negatives; no `= undefined` state lines; item change summary; "changed twice … and is back to 6"; slug-id signatures; pending-local-change fact (M10) is first and salient; `transient` label last | -| `packages/runtime/test/review-precision.test.ts` | short last page and `m<n>` keys are not unusual transitions; closing a selection is not an inconsistency | -| `packages/runtime/test/review-redaction.test.ts` | a custom `redact` also applies to invariant facts | -| `packages/runtime/test/review-hub.test.ts` ("field versions in facts") | "written 20 times by other operations" and "(version 0 → 20)" past the 16-entry history | -| `packages/runtime/test/review-fetch.test.ts` ("request facts") | "started 0.10s after this one" direction; error-rate text matches listed outcomes | -| `packages/runtime/test/review-actions.test.ts` | "Its chain wrote no state before the error." and rollback not offered then | -| `packages/runtime/test/invariants.test.ts` | learned-relation fact values; developer invariant fact text | -| `packages/runtime/test/dom.test.ts` | error fact `Uncaught TypeError: boom (at app.js:12).` | -| `packages/runtime/test/plugins.test.ts` | plugin facts reach the model; vocabulary overrides; `applicable()` gating; standing questions | -| `packages/runtime/test/atoms.test.ts`, `smoke.test.ts`, `review-xhr.test.ts` | identical additive change is salient (held); nothing salient applies synchronously; identical XHR just sent is salient | -| `packages/runtime/test/ask.test.ts` | `ask()` sends trigger `ask` with questions replaced by `{ answer }` and trigger sentence `The developer asks about the app right now.`; `about: opId` -> `The developer asks about GET /api/x (#n).`, `about: "cart"` -> `The developer asks about the store cart.` | -| `packages/runtime/test/review-precision.test.ts` ("design risk") | a lingering benign violation must not freeze the latest consistent snapshot (snapshot `seq` keeps advancing) | -| `packages/runtime/test/devtools-runtime.test.ts` | the Now view renders `runtime.situation()`; evidence view shows `explain()` facts and situation text | +| `packages/runtime/test/situation.test.ts` | one situation per trigger: key order, <= 12 facts, <= 16 timeline, <= 8 state lines, `stateChars <= STATE_CHAR_BUDGET` (2400); delivery: exactly one call for the out-of-order typeahead response, the trigger sentence, the V-others text "written twice … (version 1 → 3)", `subject.kind === "delivery"`; mutation: older task over newer task, late `discard`; request, failure, stall, inconsistency, transition (descendant wins), error, ask; serializer; byte-identical determinism | +| `packages/runtime/test/delivery.test.ts` (16 cases, new) | typeahead zero calls (incl. a debounced search with its own loading flag); stale out-of-order response -> `discard` drops only the stale field; holding is only latency; no hold when the model cannot answer in time; read-after-write; late revert; slow model; superseded queued decision dropped; WebSocket order + pending revert vs third value; messages touching nothing pending; EventSource; XHR holds and `abort()`; forced actions | +| `packages/runtime/test/content.test.ts` (14, new) | F3 (no call when unchanged), F1 field and item cells, F2 salience and diff preview, F9 (over newer data, 5x slow, ambiguous failure, channel down), F6 schedule and debounce, F5 scope/offline/commit, F7, F8 relation quality, read-your-writes, STATUS.md example printouts | +| `packages/runtime/test/budget.test.ts` | `sectionLimits` at 1100/1750/2400/3200/500; budgets 1000/1100/2000 on the delivery situation; compact questions; determinism; auto budget 2400 / wasm 1000/1333/2000; `max_tokens_exceeded` -> 1920; hold budget | +| `packages/runtime/test/no-reorder.test.ts` (new) | realworld promise middleware through `genclassEnhancer` with an always-passive model: guard/heal x salient/always give the same dispatches, order and final state as observe (with `always`, `delivery` and `mutation` were consulted); `holdWrites: true` never reorders a store's dispatches | +| `packages/runtime/test/default-mode.test.ts` (new, commit f3636b2) | `createRuntime` and `GenClass.init` without a mode start in observe (guard via option or `?genclass=guard`); observe never holds writes or requests even when the model is sure, findings still reported; a model that never answers delays nothing | +| `packages/runtime/test/batch3.test.ts` | redaction (now incl. the `auth` store rules), no `= undefined`, item change summary, "is back to 6", slug ids, pending-local-change fact first and salient on a default (unheld, background) `mutation` (now worded "this write's cause (#n) started after that user action"), `transient` after `unusual`; only its plugin-gate case sets `holdWrites: true` | +| `packages/runtime/test/atoms.test.ts` | runs with `holdWrites: true`: held writes never reordered, read-your-writes | +| `packages/runtime/test/learn.test.ts` | baselines and profiles (unchanged) | +| `packages/runtime/test/review-precision.test.ts`, `review-redaction.test.ts`, `review-hub.test.ts`, `review-fetch.test.ts`, `review-actions.test.ts`, `invariants.test.ts`, `plugins.test.ts`, `ask.test.ts`, `dom.test.ts`, `devtools-runtime.test.ts`, `nan.test.ts` | as before (precision, custom redactor, version counts past 16 entries, direction texts, error facts, plugin facts, ask sentences, error fact text, devtools Now view); `dom.test.ts` adds `untrustedEvents` and shadow-DOM descriptions; `nan.test.ts` the NaN fix | + +Full unit run on mvp-v2 at b435acb (lead, 2026-10-08): 40 files passed + 1 skipped, 332 passed + 14 skipped, plus +`review-perf` alone 4 passed (see [build-test-release](build-test-release.md)). An uncommitted working-tree change +(`state/hub.ts` ignores a held-write verdict after the write is `done`, plus one test in `atoms.test.ts`) would make +it 333 + 14 once committed (see [state-and-adapters](state-and-adapters.md)). ## Drift and open issues -- **Auto budget doc comment** (`types.ts` -> `InitOptions.situation`): says "wasm 1,100 + 300 per extra thread up to - 4 threads: 2,000". Code (`RuntimeImpl.situationBudget`) and tests: `1000 + round((threads - 1) * 1000 / 3)` -> - 1000/1333/1667/2000. API.md and STATUS.md match the code. -- **Default redactor doc comment** (`types.ts` -> `InitOptions.redact`): says regex - `/pass|token|secret|card|cvv|ssn|auth/i`. Code uses word-level `isSensitiveName` (approved deviation; API.md is - correct; CONTRACT §2 still has the regex). -- **CONTRACT §4 transition profiles**: lists value kind with "length delta sign; null" and a duration bucket as part - of the shape. Code: arrays are only empty/non-empty (documented deviation in STATUS.md), duration is never checked, - and two precision rules are not in the contract (no `set` anomaly when the usual set is empty; no `writes` anomaly - when the usual bucket is `"0"` or a `set` anomaly exists). -- **CONTRACT §6 budget**: "≤ 1,000 tokens; truncate timeline first, then state, then facts". Code: characters - (3200 chars, ≈ 1,300–1,400 tokens at the measured 2.4 chars/token), device-sized, then in_flight, stats, and fact/trigger shortening. CONTRACT §6's - `runtime.situation()` shape omits `salient`, `facts`, `compact`, `budget`. -- **`rollback` description vs effect**: `BUILTIN_ACTIONS.rollback` says "restore the affected state to its last - consistent snapshot" for `inconsistency`, `transition` and `error`, but transition/error rollback restores only the - op chain's own writes (`RuntimeImpl.revertChain`). The model reads a description that does not match the effect on - 2 of 3 triggers; fixing it changes model inputs. -- **Unreachable fact M11**: `This write could not be held: …` is emitted only for `m.unholdable`, but - `StoreHub.propose` (`state/hub.ts`) commits unholdable writes immediately without calling `hooks.gate`, and - `RuntimeImpl.gateMutation` is the only place that raises `mutation` triggers. STATUS.md (batch 3) says such writes - apply "with a fact". -- **STATUS.md triage summary** says "cause latency > 3× median"; code also requires `lat − median >= 100 ms`. It says - identical requests within "min(2 s, half its usual gap)"; code uses the usual gap only after more than 3 sightings - of the identity. -- **ARCHITECTURE.md** lists diagnoses as "…failing, transient, slow, overload or unusual"; code order puts - `transient` last. Its fact example shows "(v0 → v1)"; code prints "(version 0 → 1)". -- **API.md** says plugin facts are "added to every situation": they are added only to situations that are built - (past the cheap triage pass, or `situation()`/`ask`), are neutral, rank last and may be cut by `MAX_FACTS` or the - budget. -- **sim/NEEDS.md** note "`transient` is not yet in `DEFAULT_DIAGNOSES`" is stale; it is (last). -- **CONTRACT §6 applicability footnote** is looser than `builtinApplicable`: `coalesce` also needs fetch transport - and a shareable in-flight/just-finished response (`canCoalesce`); `retry` needs replayable, `attempt < 4` and - fetch; `hedge` also needs GET and fetch; `serve_cached` on failure/stall needs fetch; error `rollback` needs an - ambient op whose chain write is still the latest with a known previous value in a writable store. XHR therefore - never gets `coalesce`/`retry`/`hedge` or failure/stall `serve_cached` (request-trigger `serve_cached` has no - transport check); STATUS.md "Deviations" states the XHR part. -- **CONTRACT §6 timeline** says "≤ 16 most recent relevant events"; `timelineLines` tops up with recent - non-relevant events when fewer relevant ones exist. -- **CONTRACT §6 triage examples** ("a baseline ratio beyond 3×", "written by another op") are coarser than code: - M8 also needs `lat − median >= 100 ms`, R7 needs `recent >= 5`, M2 counts other *chains* (not other ops), and - failure-streak/repetition facts are salient only on `request`. -- **API.md `rt.situation()`** lists `{ trigger, subject, state, questions, actions, salient, facts }`; the - `Situation` type also has `compact` and `budget`. -- **API.md / README "cheap facts are computed for every write and request"**: facts are computed only when the - runtime is consultable (a `DecisionProvider` exists, its state is `ready` or `off`, not paused or destroyed) and - only for gated writes/requests (GenClass-owned ops and bypassed writes never trigger). -- **Sim vs Python budget mix**: the sim samples 3200/2000/1000 at 40/30/30 (`sim/src/world/scenario.ts`), the - Python curriculum at 35/30/35 (`training/curriculum/rt.py` -> `BUDGETS`). Not a parity bug for a single row, but - the two data sources have different budget distributions. -- **Python port drift** (`training/curriculum/rt.py` -> `to_state`): last-resort fact shortening floor is 40 chars - (runtime 60) and the trigger is never shortened. Only reached when one fact or the trigger alone exceeds the - budget. Also: `secs`/`rel`/`fmt_num` round exact binary ties half-even (Python format) vs `toFixed` half-up - (125 ms -> `0.12s` vs `0.13s`); `secs` >= 1000 s and `ratio` >= 10× use Python `round()` vs `Math.round`; rt.py - `truncate` counts code points, `util.truncate` UTF-16 units (see - [model-io-contract gotchas](../model-io-contract.md#invariants-and-gotchas)). -- **`Situation.subject` doc comment** (`types.ts` -> `Situation`): says "One sentence naming the subject"; code - (`buildSituation`) fills it with the short subject phrase from `subjectOf` (e.g. `write to search.results from GET - /api/search?q=rea (#6)`), while the full sentence goes to `state.trigger`. -- **Open (OPEN_TASKS.md)**: "Next" item 6 lists hold-induced harm and triage sensitivity on naturally concurrent apps - (typeahead salient about 6 times per clean trial) to investigate with the trained model; "Known risks" lists thin - `conflict` and `transition` rows. +Resolved since 654d822 (removed from this list): the `InitOptions.situation` doc comment now matches the code +(webgpu 2,400; wasm 1,000-2,000); the `InitOptions.redact` doc comment now describes leaf-field redaction; the +`sim/NEEDS.md` `transient` note is no longer relevant. + +- **CONTRACT.md not updated for v2.** It never mentions `delivery`; the §6 trigger table still describes `mutation` + as "a state write about to apply (held)"; §6 still says "≤ 1,000 tokens; truncate timeline first, then state, then facts"; the batch-4/5 deltas exist only in + STATUS.md ("Contract deltas"). §2 still has the regex redactor; §4 still lists length-delta and duration in the + profile shape. +- **ARCHITECTURE.md** says "3,200 characters on WebGPU"; code 2400. Its diagnosis order and "(v0 → v1)" example + were already off. +- **Training budgets exceed the runtime's full budget.** `sim/src/world/scenario.ts` (comment "3,200 WebGPU") and + `realapps/src/harness/scenario.ts` sample 3200 at 40%; production auto budgets never exceed 2400. Sections are the + same (limits saturate at 2400) but rows can be up to 800 chars longer than anything the deployed runtime emits. + The Python port samples 2400/2000/1667/1333/1000. +- **STATUS.md "Open issues"** still says content comparison facts are "not implemented yet"; batch 5 implemented + them (F1-F3). +- **`rollback` description vs effect** (transition/error restore only the chain's writes) and **unreachable M11** + (`StoreHub.propose` commits unholdable writes without `observeWrite` or `hooks.gate`) are unchanged. +- **API.md**: plugin facts "added to every situation" (only built situations, neutral, may be cut); "computes cheap + facts for every write and request" (only when consultable, and covered/GenClass/user writes never trigger); + `rt.situation()` shape omits `compact` and `budget`. +- **`Situation.subject` doc comment** ("One sentence naming the subject") vs the short subject phrase in code. +- **STATUS.md triage summary** "cause latency > 3x median" omits the `>= 100 ms` condition; "identical request … + within min(2 s, half its usual gap)" omits the "> 3 sightings" condition. +- **Python port drift** (`training/curriculum/rt.py` -> `to_state`): fact shortening floor 40 (runtime 60), trigger + never shortened; Python rounding (`f"{x:.2f}"`, `round()`) vs `toFixed`/`Math.round` on exact ties; code points vs + UTF-16 in `truncate`. Its docstring also says it does not model learned cadence, stale marks, click counts, create + responses or list item joins (those come from optional `spec` keys or are absent). +- **Sim coverage**: `sim/src/run/rt.ts` -> `createOptions` enables `fetch`, `timers`, `websocket`, `storage` (storage + is new since 654d822) and disables `xhr`, `user`, `errors`, `nav`, `perf`; `eventsource` is left at its default + (on), but nothing in `sim/src` references `EventSource`. XHR/EventSource deliveries and DOM-derived evidence (F7 + click counts) therefore come only from realapps (inferred from options and a grep, not checked against data). +- **Open (OPEN_TASKS.md, [HANDOFF.md](../../../HANDOFF.md); release order in [RELEASE.md](../../../RELEASE.md))**: no situation-v2 model yet; the demo items "hold-induced harm" and "typeahead + salient about 6 times per trial" were measured with v0.1 store holds (situation-v1) and need re-measuring with a + v2 model; STATUS.md reports 0/396 clean real-app runs changed with an always-passive model. ## Related docs -- [public-api-and-lifecycle](public-api-and-lifecycle.md): `InitOptions` (`triage`, `situation.budget`, `learn`, - `redact`, `vocabulary`), `rt.situation()`, `rt.ask()`. -- [observe-and-trace](observe-and-trace.md): ops, signatures, identities, op details, events. -- [state-and-adapters](state-and-adapters.md): mutation pipeline (which writes are gated), invariant miner, - settled points, consistent snapshots. -- [decide-policy-actions](decide-policy-actions.md): what happens after a situation is submitted (queue, hold, - gate, actions, reports, explain). +- [RESULTS.md](../../runtime/RESULTS.md): §3 separability, §4 never-worse sweep. +- [public-api-and-lifecycle](public-api-and-lifecycle.md): `InitOptions` (`mode`, `triage`, `situation.budget`, + `learn`, `redact`, `vocabulary`, `observe`), `PolicyOptions.holdWrites`, `rt.situation()`, `rt.ask()`. +- [observe-and-trace](observe-and-trace.md): ops, signatures, identities, the delivery hooks in fetch/XHR/messages. +- [state-and-adapters](state-and-adapters.md): mutation pipeline (`observeWrite`, drop filter, `holdWrites`), marks, + invariant miner, settled points. +- [decide-policy-actions](decide-policy-actions.md): queue, hold, gate, late revert, actions, reports. - [model-host](model-host.md) and [model-io-contract](../model-io-contract.md): how the `JevState` and questions - become packed model input and calibrated answers. + become model input. - [devtools](devtools.md): where facts and situations are displayed. -- [sim](../sim.md), [training](../training.md): consumers of this exact output; parity and regeneration. +- [sim](../sim.md), [realapps](../realapps.md), [training](../training.md): producers and consumers of this exact + output; parity and regeneration. - [status-and-known-issues](../status-and-known-issues.md), [glossary](../glossary.md). -- Existing human docs: [CONTRACT.md](../../runtime/CONTRACT.md) §4-§7, [API.md](../../runtime/API.md), +- Human docs: [CONTRACT.md](../../runtime/CONTRACT.md) §4-§8 (pre-v2 in places), [API.md](../../runtime/API.md), [ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md) - (example situations per trigger). + (batches 4-5, example situations per trigger and per new fact), `sim/SEPARABILITY.md` §6 (F-numbers). diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md index 7a946401..2abfda4b 100644 --- a/docs/agents/runtime/model-host.md +++ b/docs/agents/runtime/model-host.md @@ -2,7 +2,9 @@ > **Scope:** `packages/runtime/src/model/*.ts` (backend, calibrate, engine, errors, hash, host, index, loader, packer, protocol, pyutil, serialize, tokenizer, worker), `packages/runtime/src/model/README.md` (internal notes), `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/MODEL_CARD.md`, the `worker` entry of `packages/runtime/tsup.config.ts`, and the model sections (§2 `model` options, §8 `DecisionProvider`, §10, §13) of `docs/runtime/CONTRACT.md`. > **Read this when:** you change how the model is downloaded, cached, verified or run; touch the worker or its message protocol; change WebGPU/WASM selection or onnxruntime-web settings; change the tokenizer, packer, Python-parity serializer or calibration; add or change a model error; work on the `genclass-runtime` CLI; debug "model unavailable", "observing only", stuck loads or slow decisions. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> +> **What changed since the previous verification (654d822 = v0.1.0-alpha.0, situation-v1 format; tag situation-v1 = 1a77558), in one line:** nothing under `packages/runtime/src/model/` changed. The changes that matter here are on the runtime side (`runtime.ts`, `decide/decider.ts`, `situation/*`): the default mode is `observe`, decisions moved to the network boundary (`delivery` trigger), store writes are no longer held by default, the automatic situation budget is 2,400 chars, and no trained model matches the v2 situation format yet. One new consumer of the host appeared outside the runtime: the sim's `--on-policy` (DAgger) mode loads it in Node (`sim/src/run/onpolicy.ts` -> `loadModelDecider`, 04a264f). ## TL;DR @@ -18,10 +20,11 @@ - **Plans:** `webgpu+fp16` (adapter has `shader-f16`) -> `webgpu+q8` -> `wasm+q8`. A failed WebGPU plan alone does not trigger a retry: the same worker moves on to the next plan. Only when a worker's whole load ends in an error status, a crash or a stall after a WebGPU attempt does the host retry **once** in a fresh worker with WASM only (`retryOnWasm`). - **Downloads** (`packages/runtime/src/model/loader.ts` -> `fetchFile`) go through Cache Storage `genclass-runtime-v1`. They are checked against the card's size and sha256 (WebCrypto, with a pure-TS fallback) and streamed with progress. The card itself is always revalidated from the network. A cached card is used only when the network fails. - **Engine** (`engine.ts`): `Packer` (`packer.ts`, `Tokenizer` from `tokenizer.ts`, text from `serialize.ts`) packs everything into int64 feeds. One ORT forward pass produces `choice_logits` / `score_logits` / `noul_logits`. Temperature or Platt calibration (`calibrate.ts`) then gives typed `Answer`s. -- **Python parity is the contract.** `serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts` and `calibrate.ts` are ports of `jev_local` Python. The model was trained on the Python rendering, so any change here is a model-format change. The situation format is frozen as `situation-v1`. -- **The trained runtime model is not published yet.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`, and OPEN_TASKS item 8 lists publishing it as future work. The card fetch therefore fails (expected HTTP 404; not checked against the live CDN), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). +- **Python parity is the contract.** `serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts` and `calibrate.ts` are ports of `jev_local` Python. The model was trained on the Python rendering, so any change here is a model-format change. The situation format (the text CORE builds in `packages/runtime/src/situation/*`, which this module then tokenizes) is frozen at tag `situation-v2` (6e5e86e); `situation-v1` is the old format. The model module itself is identical in v1 and v2. +- **No model exists for the current runtime, and none is published.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm (as of 2026-10-08). The only trained runtime model, R17-final1, was trained on `situation-v1` and lives only on the train VM / Mehar's Mac; it does **not** match the v2 runtime. The v2 model comes from the scaled program ([HANDOFF](../../../HANDOFF.md): 150M teacher -> distil R17/R32 -> DAgger -> EVAL -> `@genclass/runtime-model@0.1.0`). The card fetch therefore fails (HTTP 404), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). - **Status:** `off` -> `loading` (phases `card` / `download` / `runtime` / `session` / `warmup`) -> `ready` or `error`; `dispose()` -> `off`. See [Status lifecycle](#status-lifecycle-modelhoststatusstate). The runtime core reads only `state`, `device`, `threads`, `warmupMs`, `model`, `variant`, `loadMs` and `error` (the devtools overlay also shows `progress`); `status.latency` (p50/p90 of the last 20 evaluations) and `host.stats` are for tooling. -- **CLI** `genclass-runtime fetch-model <dir>` / `info <dir>` downloads and verifies a self-hostable model directory, with no dependencies. +- **Default mode `observe` (since f3636b2) still loads and consults the model.** `observe` permits no non-passive action, so nothing is ever held: every salient trigger except `delivery` is decided in the background (priority capped at 1, deadline 5 s), for detection and reports. `delivery` decisions never reach the host: `trigger()` runs `passive()` first, which marks them stale, so `DeciderQueue` drops them; `runDelivery` (no mode check) may still delay a candidate by up to `BODY_WAIT_MS` (100 ms) for the body read. Only `mode: "guard"`/`"heal"` can make the runtime wait for the host. +- **CLI** `genclass-runtime fetch-model <dir>` / `info <dir>` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is a 404 too, so pass `--from`. The file is now committed executable (mode 100755, b435acb). ## Files @@ -46,7 +49,7 @@ | `packages/runtime/tsup.config.ts` | Build. Entry `worker: "src/model/worker.ts"` -> `dist/worker.js` (not in `dts.entry`, so no `.d.ts`); `external: ["onnxruntime-web", "onnxruntime-web/webgpu", "react", "redux", "zustand"]`; ESM, `target: "es2022"`, `platform: "browser"`, `splitting: true` (the build output's `worker.js` imports `ModelBackend` from a chunk shared with `index.js`), sourcemaps | — | | `packages/runtime/package.json` | `exports["./worker"]` -> `./dist/worker.js`; `bin.genclass-runtime` -> `./bin/genclass-runtime.mjs`; dependency `onnxruntime-web ^1.30.0` | — | | `packages/runtime/bin/genclass-runtime.mjs` | CLI (Node >= 20, no deps): `fetch-model`, `info` | `main`, `fetchModel`, `info`, `parseCard` (JS copy), `scanOnnx` | -| `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. **The npm package itself does not exist yet** (no `package.json`, no `files/`) | — | +| `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. Its status line (fcd1e68) reports final round 1 on `situation-v1` and says the next rounds retrain on v2. **The npm package itself does not exist yet** (no `package.json`, no `files/` in git, although the card says "`files/r17/` here") | — | ## Concepts and data structures @@ -69,7 +72,8 @@ | **heads** | Graph outputs `choice_logits`, `score_logits`, `noul_logits` (`OUTPUT_KIND` in `engine.ts`). | | **tau / calibration** | Post-hoc temperature (or Platt affine for noul) per header, K-bucket or kind, read from `calibration.json`. | | **fail open** | On any provider error or not-ready state, the subject proceeds unchanged (the passive action). | -| **R17 / R32** | Runtime model candidates (MODEL_CARD). R17 = ettin-encoder-17m (d 256, 7 layers, 8.1M + 0.7M heads; q8 9.6 MB, fp16 13.6 MB). R32 = ettin-encoder-32m from GenClass 0.1 (d 384, 10 layers, 18.8M + 1.6M heads; q8 22.5 MB, fp16 34.8 MB). Both use a 16,364-token pruned vocabulary, with markers at ids 16359-16363. | +| **situation-v1 / situation-v2** | Git tags freezing the situation text format the model is trained on. v2 (6e5e86e, current) adds the `delivery` trigger, new generic facts (F1, F2, F3, F6, F9 in OPEN_TASKS) and a 2,400-char full budget (`STATE_CHAR_BUDGET`). A model trained on one format is not valid for the other. Nothing in `src/model/` encodes the version: `ModelCard` has no situation-format field, so (derived from the code, not tested) a v1 export loads into a v2 runtime and simply answers out of distribution. | +| **R17 / R32** | Runtime model candidates (MODEL_CARD). Final round 1 (v1 data): R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, clear-case recall about 5-8%; R32 no better. R17 is the chosen default on every device ([docs/runtime/RESULTS.md](../../runtime/RESULTS.md) §2). R17 = ettin-encoder-17m (d 256, 7 layers, 8.1M + 0.7M heads; q8 9.6 MB, fp16 13.6 MB). R32 = ettin-encoder-32m from GenClass 0.1 (d 384, 10 layers, 18.8M + 1.6M heads; q8 22.5 MB, fp16 34.8 MB). Both use a 16,364-token pruned vocabulary, with markers at ids 16359-16363. | | **v0.1 model** | The older GenClass 0.1 ONNX (`genclass-q8.onnx` 56,931,453 B; `genclass-fp16.onnx` 67,154,907 B) used for development. Its card is `extension/src/model/model.json` (the "v0.1 extension card": `bundled`, `default_base_url`, no `files`). | ### `ModelHost` API (`packages/runtime/src/model/host.ts`) @@ -190,15 +194,17 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty If construction throws, it uses `failedProvider`, a provider with `status: {state:"error"}` and no `onStatus` (so no console line and no `"status"` event). The runtime then owns the host (`ownsDecider`) and calls `dispose()` on `destroy()`. 4. `RuntimeImpl` (`packages/runtime/src/runtime.ts`) consumes the provider as follows: - - `onStatus`: re-fires as the runtime `"status"` event. On `ready` the reporter prints `[GenClass] Model ready (<model>, <device>, <variant>, <loadMs>). Mode: <mode>.`. On `error` it prints `[GenClass] Model unavailable (<error>); observing only.` Both go through `console.info` under `report: "console"`. - - `consultable()`: triggers are built only when `status.state` is `"ready"` or `"off"`. With `"loading"` or `"error"`, every trigger runs its passive action at once, and writes and requests are never held (`hub.hooks.mayHold` uses `consultable()`). + - `onStatus`: re-fires as the runtime `"status"` event. On `ready` the reporter prints `[GenClass] Model ready (<model>, <device>, <variant>, <loadMs>). Mode: <mode>.` (`<mode>` is `observe` unless the app chose otherwise: `o.mode ?? "observe"` in the `RuntimeImpl` constructor). On `error` it prints `[GenClass] Model unavailable (<error>); observing only.` Both go through `console.info` under `report: "console"`. + - `consultable()`: triggers are built only when `status.state` is `"ready"` or `"off"`. With `"loading"` or `"error"`, every trigger (including the delivery gate, `runDelivery`) runs its passive action at once and nothing is held. Store writes are held only under `policy.holdWrites: true` (opt-in): `hub.hooks.mayHold` = `hub.holdWrites && consultable() && mode !== "observe"`. By default a salient write goes to `observeWrite` and is decided in the background. - `trigger()`: if a situation is salient but `status.state !== "ready"`, it calls `void this.ready`, which starts a load (the effective "lazy" start), and runs the passive action. The public `rt.ready` getter calls `decider.ready()` once and caches the promise, so any read of `rt.ready` by the app, and any `rt.ask()`/`rt.decide()`, also starts the load regardless of `preload`. - - `priority` per request (the `trigger(...)` call sites in `runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`; `ask` submits directly): 2 for `mutation`, `request` (fetch and XHR) and fetch `failure`; 1 for `inconsistency`, `stall`, XHR `failure` and `ask`; 0 for `transition` and `error`. In `trigger`, a request that will not hold is capped at 1 (`waits ? priority : min(priority, 1)`). - - `situationBudget()`: reads `status.device` and `status.threads`. + - `priority` per request (the `trigger(...)` call sites in `runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`; `ask` submits directly): 2 for `delivery` (fetch/XHR responses, WebSocket and EventSource messages, via `runDelivery`), `request` (fetch and XHR), fetch `failure` and a held `mutation` (`gateMutation`, only with `holdWrites`); 1 for a background `mutation` (`observeWrite`, the default), `inconsistency`, `stall`, XHR `failure` and `ask`; 0 for `transition` and `error`. In `trigger`, a request that will not hold is capped at 1 (`waits ? priority : min(priority, 1)`). + - Holding: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`. In `observe` mode `permittedActions` is always empty, so nothing waits and every request except `delivery` reaches the host at priority <= 1 with the 5 s background deadline. `delivery` requests are dropped as stale by `DeciderQueue` before reaching the host (`passive()` runs first and sets `released`; the controller's `stale` is `() => released`), the same as any non-waiting delivery in guard; `runDelivery` may still delay a candidate by up to 100 ms (`BODY_WAIT_MS`) for the body read. `expectedLatency()` is `Infinity` while `DeciderQueue.stuck` (the provider's last evaluation timed out and none has answered since), and otherwise `base × (1 + waiting)` plus, while an evaluation is in flight, `max(base, the time it has taken so far)`, where `base` is the (lower) median of the queue's recent latencies, or `status.warmupMs` before any. A slow or wedged host therefore stops causing holds instead of delaying the app. + - `situationBudget()`: reads `status.device` and `status.threads`: webgpu (and unknown devices) `STATE_CHAR_BUDGET` = 2,400 chars (about 1,000 tokens); wasm `1000 + round((threads - 1) × 1000 / 3)` (1,000 at 1 thread to 2,000 at 4); then `× budgetScale`. - `holdBudgetMs()`: seeds from `status.warmupMs` until the decider queue has its own latency samples. - - `Decision.model`: comes from `status.model ?? status.variant`. - - Calls to `evaluate()` all go through `DeciderQueue` (`packages/runtime/src/decide/decider.ts`). It allows one in flight. It passes `timeoutMs = deadline - now` (the hold budget, plus 2 s when a late revert is possible, or 5 s for background decisions). It abandons the provider after that deadline (or 10 s when there is none). Any rejection triggers `onError` and the passive action. See [decide-policy-actions.md](./decide-policy-actions.md). + - `Decision.model`: comes from `status.model ?? status.variant ?? "custom"`. + - Calls to `evaluate()` all go through `DeciderQueue` (`packages/runtime/src/decide/decider.ts`). It allows one in flight. It passes `timeoutMs = deadline - now` (the hold budget, plus 2 s when a late revert is possible, or 5 s for background decisions). It abandons the provider after that deadline (or 10 s when there is none) and marks itself `stuck` until the next answer. Since batch 4 a queued item also carries a `stale()` check (e.g. a delivery already released): superseded items are dropped before they reach the host. Any rejection triggers `onError` and the passive action. See [decide-policy-actions.md](./decide-policy-actions.md). 5. The runtime does **not** use `measure`, `evaluateDetailed`, `stats` or `status.latency`. They exist for direct `createModelHost` users, the browser benchmarks and devtools-style tooling. +6. The other direct user is the sim's on-policy decider (`sim/src/run/onpolicy.ts` -> `loadModelDecider`, used by `node dist/gen.js --on-policy <modelDir>` via `sim/src/gen/worker.ts`). `npm run build:model-host` in `sim/` builds `packages/runtime/src/model/host.ts` unmodified into `sim/dist/model-host/`, and `loadModelDecider` calls `createModelHost({ baseUrl: "https://model.local/", worker: false, device: "wasm", preload: "eager", fetch: <reads the model directory and onnxruntime-web's dist/ from disk>, ortWasmPaths: "https://model.local/ort/", timeoutMs: 600_000, maxQueue: 10_000 })` and awaits `ready()`. So the inline transport, WASM plan, packer and calibration also run in Node for DAgger data. ### 2. Host start-up, preload and transports (`host.ts`) @@ -397,7 +403,7 @@ Lookup order: ### When the default model URL 404s (the alpha today) -The trained runtime model is not published. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/`, and OPEN_TASKS item 8 ("publish the trained model as `@genclass/runtime-model@0.1.0`") is still under "Next". The README of `packages/runtime` says the alpha "observes and records but does not act yet". Traced through the code, a default `GenClass.init()` in a browser does the following. The HTTP status itself is assumed, not fetched. +No runtime model is published, and none exists yet for `situation-v2`. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/` and is a 404 on the registry (checked by the lead, 2026-10-08); OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` is still open, behind the v2 data, teacher, distillation and EVAL steps in HANDOFF. The published `@genclass/runtime@0.1.0-alpha.0` defaults to `guard`; this branch defaults to `observe`, which changes nothing below because nothing can act without a model. The release procedure is in [RELEASE.md](../../../RELEASE.md). Traced through the code, a default `GenClass.init()` in a browser does the following. 1. The host is created with `preload: "idle"`, so the status is `off`. Until the idle start, triggers compute facts. A salient one calls `void this.ready`, which starts the load early, and runs the passive action. 2. The worker starts and posts `hello`. `doLoad` sets phase `card`, starts the WebGPU probe, and fetches `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json` (`cache:"no-cache"`). The probe is not cancelled when the card fails: on a WebGPU-capable browser it still requests an adapter and creates and destroys a device; its result is discarded. @@ -405,9 +411,9 @@ The trained runtime model is not published. The npm package `@genclass/runtime-m 4. The backend emits `{state:"error", error:"model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json", worker:true}`, with no `attempts` and no `gpu`. 5. Host: `retryOnWasm` returns false (no WebGPU attempt), so `setStatus(error)` runs and `ready()` waiters reject with `ModelLoadError`. The worker is **not** terminated; it stays idle until `dispose()`. 6. Runtime: the console shows `[GenClass] Model unavailable (model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json); observing only.` (via `console.info`, only with `report: "console"`), and a `"status"` event fires. The devtools overlay shows "Model unavailable" with `observing only · <error>` (`packages/runtime/src/devtools/index.ts` -> `renderStatus`). -7. From then on `consultable()` is false. Every trigger takes the passive action immediately; no situations, decisions or detections are produced, and nothing is held. Observers, tracing and baselines keep running. +7. From then on `consultable()` is false. Every trigger and every delivery takes the passive action immediately; no situations, decisions or detections are produced, and nothing is held. Observers, tracing and baselines keep running. 8. `rt.ask()` / `rt.decide()` reject with `GenClassUnavailableError("error", "the model failed to load: ...")`. Exception: with `opts.timeoutMs` set, `ask` awaits `Promise.race([wait, to])` without wrapping, so the raw `ModelLoadError` propagates instead. The runtime caches its `ready` promise and has no public reload. Only a direct `createModelHost` user can call `host.load()` to retry. The next page load tries the card again. -9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` release may not exist either (unverified), so pass `--from` explicitly. +9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` release is a 404 too, so pass `--from` explicitly. Only the v0.1 development model (`https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, whether it serves a CLI-readable `model.json` is unverified) and the situation-v1 R17-final1 export (train VM only) exist; neither is trained on `situation-v2`, so their decisions are not meaningful for this runtime. Use them to exercise the loading machinery, not to evaluate behaviour. ### CLI (`packages/runtime/bin/genclass-runtime.mjs`) @@ -464,7 +470,7 @@ genclass-runtime info <dir> | `probeWebGPU` `timeoutMs` | ms | 5000 each for `requestAdapter` and `requestDevice` | `loader.ts` | probe never throws | | `CARD_FORMAT` | string | `"genclass-runtime-model/1"` | `loader.ts`, CLI | card format tag | | cache headers | string | `x-genclass-sha256`, `x-genclass-tag` | `loader.ts` (`H_SHA`, `H_TAG`) | cache-entry validity | -| `meta.max_len` -> `Packer.maxPositions` | number | 1536 if absent | `engine.ts`, `packer.ts` | positions budget (final round 1 trains with `--max-len 2048`, `training/launch_final1.sh`; the stage-2 pilot used it too) | +| `meta.max_len` -> `Packer.maxPositions` | number | 1536 if absent | `engine.ts`, `packer.ts` | positions budget (final round 1 trained with `--max-len 2048`, `training/launch_final1.sh`; the scaled-program launch scripts `launch_t150.sh` (teacher), `launch_student.sh` and `launch_r68.sh` also pass `--max-len 2048`, so their exports should declare 2048) | | `meta.max_total` -> `Packer.maxTotal` | number | 8192 if absent | `engine.ts`, `packer.ts` | whole-sequence budget | | `Packer` `cacheSize` | number | 8192 texts (cleared when full) | `packer.ts` | encode cache | | `Tokenizer` `cacheSize` | number | 20000 words (cleared when full) | `tokenizer.ts` | BPE word cache | @@ -473,17 +479,18 @@ genclass-runtime info <dir> | `DEFAULT_NOUL_INSTR` / `DEFAULT_CHOICE_INSTR` / `DEFAULT_SCORE_INSTR` | string | `"Is the statement true of the state?"` / `"Which option best fits the state?"` / `"Which level best describes the state?"` | `serialize.ts` | header when instructions are empty | | `K_BUCKETS` / `BUCKET_CLAMP` | — | `[2,2],[3,5],[6,10],[11,30],[31,100],[101,255]` / `[0.5, 5.0]` | `calibrate.ts` | v2 calibration | | CLI `DEFAULT_FROM` | string | `"https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/"` | `bin/genclass-runtime.mjs` | `fetch-model` source | -| Runtime-side (context only) | — | `DeciderQueue` `PROVIDER_TIMEOUT_MS` 10_000, `MAX_QUEUE` 32, answer cache 64 entries / 30 s; `BACKGROUND_DEADLINE_MS` 5000; `LATE_REVERT_MS` 2000; hold budget clamp 150..800 ms (fallback 300) | `decide/decider.ts`, `runtime.ts`, `decide/policy.ts` | see [decide-policy-actions.md](./decide-policy-actions.md) | +| Runtime-side (context only) | — | default mode `"observe"` (`runtime.ts`, `o.mode ?? "observe"`); `DeciderQueue` `PROVIDER_TIMEOUT_MS` 10_000, `MAX_QUEUE` 32, answer cache 64 entries / 30 s (`CACHE_MAX`, `CACHE_TTL`); `BACKGROUND_DEADLINE_MS` 5000; `LATE_REVERT_MS` 2000; hold budget `HOLD_MIN_MS`..`HOLD_MAX_MS` = 150..800 ms (fallback `HOLD_FALLBACK_MS` 300); `STATE_CHAR_BUDGET` 2400, `COMPACT_BUDGET` 1100, `MIN_BUDGET` 500 (`situation/serialize.ts`) | `decide/decider.ts`, `runtime.ts`, `decide/policy.ts`, `situation/serialize.ts` | see [decide-policy-actions.md](./decide-policy-actions.md), [learn-situation-triage.md](./learn-situation-triage.md) | Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` are typed on `InitOptions.model` (`ModelOptions` in `types.ts`). `makeHost` spreads the object into `createModelHost`, so other `ModelHostOptions` keys pass through at runtime but are not typed for `GenClass.init`. ## Invariants and gotchas -- **Parity with Python is load-bearing.** The model was trained on text from `jev_local/serialize.py` (via the sim's JSON rows) and the Python `Packer`. Changing any of the following changes what the model sees and needs retraining plus a new `situation-v1`-style freeze. Coordinate with TRAIN and SIM (see [training.md](../training.md), [sim.md](../sim.md)): +- **Parity with Python is load-bearing.** The model was trained on text from `jev_local/serialize.py` (via the sim's JSON rows) and the Python `Packer`. Changing any of the following changes what the model sees and needs retraining plus a new situation tag (the current freeze is `situation-v2`; HANDOFF: "coordinate before touching it"). Coordinate with TRAIN and SIM (see [training.md](../training.md), [sim.md](../sim.md)): - rendering in `serialize.ts` or `pyutil.ts` (number formatting, whitespace, separators, `True`/`None`, `[SEP]` placement); - BPE behaviour; - the packer layout (position restarts, groups, marker choice). -- **Per-header calibration is keyed on the exact instruction text** (`sha1(header)[:12]`). Rewording a standing question in `packages/runtime/src/situation/questions.ts` silently falls back to bucket or kind temperatures. +- **Per-header calibration is keyed on the exact instruction text** (`sha1(header)[:12]`). Rewording a standing question in `packages/runtime/src/situation/questions.ts` silently falls back to bucket or kind temperatures. v2 added a new header, `ACTION_INSTRUCTIONS.delivery` ("What should the runtime do with this response or message?"), and per-trigger action descriptions (`TRIGGER_DESCRIPTIONS.delivery`): a v1 calibration file has no `by_header` entry for it. +- **The default mode does not reduce model traffic.** In `observe` (the default since f3636b2) every salient situation except `delivery` is still evaluated, in the background; it only never waits. `delivery` decisions are dropped as stale before reaching the host, and `runDelivery` may still delay a candidate by up to 100 ms for the body read. Turning the model off needs `model: false` or the kill switch. - **JS cannot emit Python float literals** like `25.0` (`pyNumber(25)` = `"25"`). That is why training/NEEDS.md item 8 asks the curriculum to write integral floats as ints. - **The public `stateText`** (`packages/runtime/src/situation/serialize.ts`, used by `explain()`) is a human rendering (indented list items). It is *not* the token text: the packer uses `model/serialize.ts` -> `segmentText` with `[SEP]` between segments. `model/serialize.ts` also has a `stateText`, which is internal. - **Nothing about the vocabulary is hardcoded.** Marker, CLS and SEP ids come from `meta.json` (checked) or `tokenizer.json`, so pruned vocabularies (16,364 tokens, markers 16359-16363) work unchanged. Keep it that way (CONTRACT §13). @@ -522,12 +529,12 @@ Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` ar - **Bundling:** - tsup keeps `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` verbatim; Vite and webpack 5 bundle that pattern. - Both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")` must stay **static string specifiers** so bundlers split them into separate chunks and a page downloads only one. - - `onnxruntime-web/wasm` is missing from `tsup.config.ts` `external`. It stays external only because `onnxruntime-web` is a `dependency` (tsup externalises dependencies including subpaths). A `tsup` build of 654d822 keeps both as dynamic `import()` calls in `dist/worker.js` and in the chunk `dist/index.js` loads. -- **Determinism:** the host uses the injected `Clock` for timers. `scheduleIdle` uses the global `requestIdleCallback` and `load` event. The sim never uses the model host (it plugs in its own `decider`), so this does not affect training parity. + - `onnxruntime-web/wasm` is missing from `tsup.config.ts` `external`. It stays external only because `onnxruntime-web` is a `dependency` (tsup externalises dependencies including subpaths). The local `packages/runtime/dist/` from the 2026-10-08 tsup build on this branch (untracked build output) keeps both `import('onnxruntime-web/webgpu')` and `import('onnxruntime-web/wasm')` as dynamic imports in `dist/worker.js` and in the chunk that `dist/index.js` re-exports `createModelHost` from (which also holds the `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` pattern). +- **Determinism:** the host uses the injected `Clock` for timers. `scheduleIdle` uses the global `requestIdleCallback` and `load` event. The sim's default modes plug in their own `decider` and never touch the host, but the `--on-policy` (DAgger) mode runs the real host inline in Node (`sim/src/run/onpolicy.ts`; it passes no `clock`, so the host's timers use `browserClock`, and `preload: "eager"` bypasses `scheduleIdle`). A change to `host.ts`, `backend.ts`, the loader, packer or calibration therefore also changes on-policy data generation; rebuild `sim/dist/model-host` (`npm run build:model-host` in `sim/`) after one. ## How to change it safely -The team runs all builds and tests on the remote VM (CONTRACT §0 rule 5). Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the build and unit tests locally. Ask the user before model downloads (`fetch-model`) and Playwright specs ([build-test-release.md](build-test-release.md#where-to-run-things)). Model-file tests read `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) and **skip** when it is absent. Unit tests with fakes always run. +Run policy: HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac. On other machines agents may run light local checks (`npm ci`, `tsc`, `tsup`, vitest unit tests, including `test/model/*`). Ask the user before model downloads (`fetch-model`), Playwright specs, `smoke.sh`, or anything on Azure ([build-test-release.md](build-test-release.md#where-to-run-things)). Model-file tests read `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) and **skip** when it is absent: these are the 14 skipped tests of the unit run (332 passed + 14 skipped, plus 4 in `review-perf.test.ts` run alone, pinned to b435acb; re-check after the uncommitted `state/hub.ts` held-write fix and its `atoms.test.ts` test land, expected 333 + 14). Unit tests with fakes always run, and CI (`.github/workflows/ci.yml`, b435acb) runs them on every push to `main`/`runtime`/`mvp`/`mvp-v2` and on pull requests, without a model directory and without Playwright, so CI never exercises a real ONNX model. ```sh node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/ @@ -537,16 +544,17 @@ GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/brow ``` (The commands come from `packages/runtime/src/model/README.md`. Whether that GitHub release serves a `model.json` the CLI can read is unverified.) -1. **Point at a published model / bump the model version.** +1. **Point at a published model / bump the model version.** (Release procedure: [RELEASE.md](../../../RELEASE.md).) - Edit `DEFAULT_MODEL_BASE_URL` in `host.ts` and `DEFAULT_FROM` in the CLI. - Update `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, `packages/runtime/README.md`, `packages/runtime-model/MODEL_CARD.md`. - New URLs or hashes refetch automatically; old cache entries remain. - Run `genclass-runtime info <dir>` on the published directory (card rule, hashes). - Tests: `test/model/host.test.ts` (uses its own base URL; no change expected), the browser specs against the new directory. 2. **Ship a different model architecture (R17 vs R32, new export).** No code change is needed if the export follows the card format and `meta.json` declares `inputs`, `outputs`, `markers`, `cls_id`, `sep_id`, `max_len`, `max_total`. - - Make sure `max_len` matches training (2048 for the stage-2 pilot and final round 1). + - Make sure `max_len` matches training (2048 for the stage-2 pilot, final round 1 and the scaled-program launch scripts). + - Make sure it was trained on `situation-v2` data (the card cannot tell; check `training/EVAL.md` / the export's provenance). - Keep the q8 embedding table int8 so `webgpu+q8` works without `shader-f16`. - - Device-based model selection (OPEN_TASKS item 5: R17 for WASM, R32 for WebGPU only if clearly more accurate, "Device-based model selection in the host card") is **not implemented**. It would need card support (e.g. variants per device) plus a `planOrder` change and tests in `loader.test.ts`. + - Device-based model selection (OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` (+ device-based selection): R17 for WASM, R32 for WebGPU only if clearly more accurate, "Device-based model selection in the host card") is **not implemented**. It would need card support (e.g. variants per device) plus a `planOrder` change and tests in `loader.test.ts`. 3. **Add a graph input or head.** - Add a builder to `FEEDS` (`engine.ts`), and a plan field in `planInputs` if needed. - For a new head, add it to `OUTPUT_KIND`, a `BlockKind`, `questionBlock`, `itemMarkers`, `unpackLogits`, `calibrateLogits` and `buildAnswer`, and the `Question`/`Answer` types in `types.ts`, which form the CORE<->MODEL seam ("change that section only together"). @@ -600,7 +608,8 @@ GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/brow | `packages/runtime/test/browser/build.mjs`, `server.mjs`, `playwright.config.ts`, `page/*` | Test infrastructure, no assertions of its own. `build.mjs` (Playwright global setup) builds the library with `npx tsup` (falls back to building `src/model/index.ts` + `worker.ts` alone into `.build/dist` when a tsup entry file is missing, the package build fails, or `dist/index.js` does not mention `createModelHost`), bundles a test app with esbuild, and throws unless a built file contains the `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` pattern, `worker.js` exists, and the worker code holds both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`. `server.mjs` serves the app, `/model/` (`GENCLASS_MODEL_DIR`), `/ort/` (onnxruntime-web's `dist/`, so both wasm files), extra models at `/m/<name>/`, and the same under `/coi/` with COOP/COEP headers for WASM-thread tests. | | `packages/runtime/test/smoke/smoke.sh` | npm tarball in a fresh Vite app. Uses `model: false`, so it does **not** exercise the model host. | | `packages/runtime/test/atoms.test.ts` (runtime side) | "provider errors (not ready, too many tokens, timeout, busy) fail open at once": a decider throwing an error with `code` `not_ready` / `max_tokens_exceeded` / `timeout` / `busy` lets the write apply immediately, with no decision and no hold. | -| `packages/runtime/test/budget.test.ts` (runtime side) | `"auto"` situation budget from the model status (webgpu 3,200; wasm 1,000 at 1 thread to 2,000 at 4 threads); `max_tokens_exceeded` shrinks later automatic budgets; hold budget = clamp(1.5 × median latency, or the warm-up time before any, 150, 800), else 300; held requests carry `timeoutMs` = the time left. | +| `packages/runtime/test/default-mode.test.ts` (runtime side, f3636b2) | `createRuntime()` and `GenClass.init()` without a mode start in `observe`; `guard` is opt-in (option or `?genclass=guard`); observe never holds writes or requests even when the model is sure, and with a decider that never answers nothing is delayed. `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so the other runtime tests keep testing guard behaviour. | +| `packages/runtime/test/budget.test.ts` (runtime side) | `"auto"` situation budget from the model status (webgpu 2,400; wasm 1,000 at 1 thread to 2,000 at 4 threads); section limits full at 2,400; `max_tokens_exceeded` shrinks later automatic budgets; hold budget = clamp(1.5 × median latency, or the warm-up time before any, 150, 800), else 300; held requests carry `timeoutMs` = the time left. | Environment variables of the model tests: `GENCLASS_MODEL_DIR` (model directory; default `<repo>/.cache-model`; model-file tests skip without it), `GENCLASS_WEBGPU_VARIANTS` (embedding variants for `model-webgpu.spec.ts`), `GENCLASS_BENCH_MODELS` (`name=dir,...`: extra model directories for the per-size latency bench and WebGPU tests), `GENCLASS_OFFLINE` (skips the test that loads the default ORT wasm from jsDelivr). @@ -610,29 +619,31 @@ No test covers the default-URL 404 end-to-end, the CLI, the runtime's reaction t Mismatches between docs and code (code wins): -- **The default model is not published.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@<pinned>`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, but `packages/runtime-model/` has no `package.json` or `files/`, and OPEN_TASKS item 8 lists publishing as future work. Result: observe-only (see the 404 flow above). +- **The default model is not published, and no model matches the runtime.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@<pinned>`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, but `packages/runtime-model/` has no `package.json` or `files/`, the npm package is a 404, and OPEN_TASKS "Next" (Model package `@genclass/runtime-model@0.1.0`) lists publishing as future work; see [RELEASE.md](../../../RELEASE.md). Result: observe-only (see the 404 flow above). The only trained export (R17-final1) is `situation-v1`; publishing it as-is would ship a model out of distribution for the v2 runtime. - **Three different default model sources:** - host: jsDelivr npm (`DEFAULT_MODEL_BASE_URL`); - CLI: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` (`DEFAULT_FROM`); - CONTRACT §10 and `src/model/README.md`: the dev v0.1 model at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. - `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. Whether the `runtime-model-v0.1.0` release exists is unverified; OPEN_TASKS item 8 lists "attach it to a GitHub release" as future work. + `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. The `runtime-model-v0.1.0` release URL is a 404 (lead, 2026-10-08); OPEN_TASKS "Next" (Model package) lists the GitHub release as future work. - CONTRACT §10 says "the worker imports `onnxruntime-web/webgpu`". The code imports `onnxruntime-web/wasm` when no WebGPU plan exists, and `/webgpu` otherwise (worker and inline). The same staleness is in `src/model/README.md` "Bundling" ("`dist/worker.js` imports `onnxruntime-web/webgpu`"; "the inline fallback's `import("onnxruntime-web/webgpu")`"). - CONTRACT §2 and `docs/runtime/API.md` list only `baseUrl`, `device`, `worker` and `preload` for `model`. `ModelOptions` in `types.ts` also has `ortWasmPaths` and `cacheName`. Host-only options (`timeoutMs`, `maxQueue`, `maxThreads`, `helloTimeoutMs`, `loadStallMs`, `warmup`) are untyped through `init`. - CONTRACT §8 `DecisionProvider.evaluate(req)` lists `{trigger, state, questions}`. `EvaluateRequest` also has `priority`, `subject` (§13) and `timeoutMs`, which the host honours. - `protocol.ts` comment: `hello` is "posted once when the worker module (and onnxruntime-web) finished loading". In fact ORT is imported later, on `load`. - `host.ts` comment on `recordLatency`: "for status.latency (adaptive hold budgets and situation sizes)". No runtime code reads `status.latency`. The hold budget uses `DeciderQueue.latencies()` and `status.warmupMs`, and the situation budget uses `status.device`/`threads`. -- `types.ts` comment on `situation.budget` says "wasm 1,100 + 300 per extra thread up to 4 threads: 2,000". `RuntimeImpl.situationBudget` computes `1000 + round((threads − 1) × 1000 / 3)` (1,000 / 1,333 / 1,667 / 2,000), which matches API.md and STATUS.md. - `MODEL_CARD.md`: - - It says the runtime acts "only when `p(action) ≥ 0.9` (guard tier) / `0.8` (heal tier)". The gate now uses the **summed** probability of the permitted actions (STATUS batch 3, CONTRACT §8). - - Its diagnosis list omits `transient`. + - Its status line says final round 1 is "delivered (`files/r17/` here ...)", but `packages/runtime-model/` in git holds only `MODEL_CARD.md` (no `files/`). The export is on the train VM (`~/gcl/train-out/final1/`), not in the repo. + - It says the runtime acts "only when `p(action) ≥ 0.9` (guard tier) / `0.8` (heal tier)". The gate uses the **summed** probability of the permitted actions (`decide/policy.ts`, CONTRACT §8). It also does not mention that the default mode is now `observe` (no action at all unless the app opts into `guard`). + - Its diagnosis list omits `transient`, and its action list omits the v2 `delivery` trigger (`deliver` / `discard` / `defer`). + - Its latency paragraph maps token counts to state budgets of 1,000 / 2,000 / 3,200 chars; the v2 full budget is 2,400 (`STATE_CHAR_BUDGET`). Its figures (R17 ≈ 190 / 340 / 610 ms, R32 ≈ 500 / 880 / 1,540 ms, "fitted over 184 requests") also differ from `docs/runtime/RESULTS.md` §2 (R17 177 / 323 / 589, R32 569 / 954 / 1,580). - It describes `calibration.json` as "per-kind temperatures", while the runtime also supports `by_header`, `by_bucket`, `tau_k` and `noul_platt`. +- HANDOFF.md "What this is" still says "observe -> guard (default; ...)". Since f3636b2 on this branch the default is `observe` (CONTRACT §13, `runtime.ts`). The published npm alpha.0 still defaults to `guard`. - CONTRACT §10 refers to `/Users/meharkhanna/jev/extension/genclass/src/` (another machine). In this repo the v0.1 card is `extension/src/model/model.json`. -- `packages/runtime/bin/genclass-runtime.mjs` is committed with mode 100644, not executable. A root `npm install` chmods it to 755, which git then reports as a mode change; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. - CONTRACT §2 comments `device` as "default auto (webgpu+fp16 if shader-f16, else wasm+q8)". `planOrder` also tries `webgpu+q8` between them, and `"auto"` skips software (fallback) adapters. - CONTRACT §2 says `preload: "lazy"` downloads "only when the first salient situation appears", and §10 says "on the first `evaluate`/`ready`". The host starts on the first `ready()`/`load()`/`evaluate()`/`measure()`; through the runtime that is the first salient trigger, `rt.ask`/`rt.decide`, or any read of `rt.ready`. - `src/model/README.md` "Self-hosting everything" copies only `ort-wasm-simd-threaded.asyncify.wasm` to `public/ort/`. When no WebGPU plan exists, the backend loads `onnxruntime-web/wasm` and fetches `ort-wasm-simd-threaded.wasm` from `ortWasmPaths`, which that recipe does not provide (code-derived; not tested). Serve both files. - `tokenizer.ts` header comment describes non-special added tokens as "split out first", with the normalizer applied to "the rest". The code normalizes the whole text first and then splits added tokens (`encode` -> `splitAdded(this.normalize(text))`). For the v0.1 tokenizer (`extension/src/model/tokenizer.json`: normalizer `NFC`, 109 non-special added tokens such as `[unusedN]` and space runs, all ASCII) the two orders give the same result; a tokenizer whose added tokens change under its normalizer could differ. The README parity table reports identical ids on the full and pruned vocabularies (unverified). +- `WARMUP_STATE` / `WARMUP_QUESTIONS` (`backend.ts`) are a v1-style mutation situation, and the warm-up diagnosis question reads "What is going on?" while the runtime's `DIAGNOSIS_INSTRUCTIONS` (`situation/questions.ts`) is "What is happening here?". Only the timing (`warmupMs`, the warm-up `status.latency`) is used, so this is cosmetic. - `src/model/index.ts` header comment says `Tokenizer`/`Packer`/`stateSegments` "are exported for token budgeting of situations". Nothing in `src/` imports `model/index.ts`, and situation budgets are in characters (`STATE_CHAR_BUDGET`), not tokens. Open items and TODOs relevant to this scope: @@ -644,27 +655,32 @@ Open items and TODOs relevant to this scope: - There is no automatic reload after a failed load: the runtime caches `ready` and has no public retry. The idle worker is kept after a load error. - Old Cache Storage entries are never evicted. - A hung forward pass blocks the host forever: there is no post-load watchdog. -- Device-based model selection (OPEN_TASKS item 5), publishing `@genclass/runtime-model@0.1.0` plus a GitHub release (item 8), and the shipping model from the final rounds (final round 1 has no results in the repo; training/EVAL.md) are open. -- training/NEEDS.md 6a: situations average about 2.4 characters per token, so `STATE_CHAR_BUDGET` 3200 gives about 1.3–1.4× the intended tokens. TRAIN suggests budgeting with the real tokenizer, which `host.measure` already provides but the runtime does not use. Final-round exports will set `meta.json` `max_len` 2048 (from `--max-len`, which `jev_local/train/train.py` stores in the checkpoint meta that `training/export_runtime.py` copies). -- demos/NEEDS.md §2: one-at-a-time decisions queue up during typing bursts (median 826 ms); the suggestions there concern CORE's queue and hold policy. -- Measured performance (MODEL's numbers in `src/model/README.md`, Chromium on the shared VM, not re-verified): - - v0.1 q8 cold load 1.56–1.94 s from localhost; - - single-thread WASM warm forward at ~1,000 state tokens: R32 1,647 ms, R17 625 ms; - - 4 WASM threads are about 3× faster. +- Device-based model selection and publishing `@genclass/runtime-model@0.1.0` plus a GitHub release (OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` (+ device-based selection); procedure in [RELEASE.md](../../../RELEASE.md)) are open. Final round 1 results are now in training/EVAL.md and docs/runtime/RESULTS.md (R17 chosen as the default on every device, which makes device-based selection less pressing), but they are `situation-v1` baselines. +- The v2 model itself ([HANDOFF](../../../HANDOFF.md) "How to continue" step 3): v2 data (SIM about 10M gold + 50M unlabeled on 20 Azure nodes, REAL about 495k (HANDOFF; training/NEEDS target ≥ 500k) real-browser gold rows; locations in training/NEEDS.md item 16 and its node-claims table) -> 150M teacher -> teacher labels -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. When it lands: update `DEFAULT_FROM`, MODEL_CARD, and check `meta.json` `max_len` 2048 and the calibration headers (including the new `delivery` action header). +- OPEN_TASKS "Needs the user": a `0.1.0-alpha.1` patch (crash on `NaN` in app state, fixed in `packages/runtime/src/util.ts` by ad24804, test `test/nan.test.ts`) needs the owner's 2FA. The model host was never affected (`toJsonValue` maps NaN to `null`). +- demos/NEEDS.md §2: one-at-a-time decisions queued up during typing bursts (median 826 ms, measured on v1). Batch 4/5 addressed the runtime side (no store-write holds, `expectedLatency` gate, `stale()` drop in `DeciderQueue`); the host is still one inference at a time. Not re-measured with a model on v2. +- Measured performance (not re-verified here): + - [docs/runtime/RESULTS.md](../../runtime/RESULTS.md) §2 (onnxruntime-web 1.30 WASM, 1 thread, q8): R17 177 / 323 / 589 ms and R32 569 / 954 / 1,580 ms at 500 / 780 / 1,170 sequence tokens; GenClass 0.1 about 900 ms at 780. A 2,400-char v2 situation is about 1,000 tokens (2.4 chars per token, training/NEEDS.md 6a). + - `src/model/README.md` (Chromium on the shared VM): v0.1 q8 cold load 1.56–1.94 s from localhost; 4 WASM threads are about 3× faster. - Single-thread WASM with the 32M model does not fit a 300 ms hold budget. + Single-thread WASM with R32 does not fit an 800 ms hold budget at full size; with R17 it does at about 1,000 tokens. Under the default `observe` mode this only affects how fast background findings arrive. ## Related docs +- [../../../RELEASE.md](../../../RELEASE.md): release procedure for `@genclass/runtime` and `@genclass/runtime-model`. +- [../../../HANDOFF.md](../../../HANDOFF.md): project state and "How to continue". +- [../../runtime/RESULTS.md](../../runtime/RESULTS.md): measured results (latency, model choice). + - [public-api-and-lifecycle.md](./public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, `InitOptions.model`, `ready`/`status`, kill switch. - [decide-policy-actions.md](./decide-policy-actions.md): `DeciderQueue`, hold budget, policy gate, late revert, fail-open handling of provider errors. - [learn-situation-triage.md](./learn-situation-triage.md): situation building, `STATE_CHAR_BUDGET` / `COMPACT_BUDGET`, `situationBudget`, standing questions. - [devtools.md](./devtools.md): how the overlay shows model status. -- [build-test-release.md](./build-test-release.md): tsup entries, VM test commands, npm publish. +- [build-test-release.md](./build-test-release.md): tsup entries, local and VM test commands, CI (`.github/workflows/ci.yml`), npm publish. - [../model-io-contract.md](../model-io-contract.md): situation text -> packed request -> heads -> calibrated answers (runtime, sim, training). - [../training.md](../training.md): R17/R32 training, `export_runtime.py` (writes `model.json`/`meta.json`), calibration fitting. - [../genclass-model-lineage.md](../genclass-model-lineage.md): `jev_local` Python originals of the serializer, packer and calibration. - [../status-and-known-issues.md](../status-and-known-issues.md): project-wide status and drift. -- [../sim.md](../sim.md): the sim plugs in its own decider and never uses the host. +- [../sim.md](../sim.md): the sim plugs in its own decider, except `--on-policy` (DAgger), which runs this host inline in Node (`sim/src/run/onpolicy.ts`). +- [../realapps.md](../realapps.md): the real-app corpus (91 apps at b435acb; the v2 never-worse sweep covered the 66 of the time) and its never-worse sweep; it plugs in its own recording decider (`realapps/src/world/probe.ts` -> `decider`, model `realapps-recorder`) or `model: false`, never the model host. - [../glossary.md](../glossary.md): shared terms. - Source notes: `packages/runtime/src/model/README.md`; model card: `packages/runtime-model/MODEL_CARD.md`; contract: `docs/runtime/CONTRACT.md` §2, §8, §10, §13. diff --git a/docs/agents/runtime/observe-and-trace.md b/docs/agents/runtime/observe-and-trace.md index 9a22d011..531df314 100644 --- a/docs/agents/runtime/observe-and-trace.md +++ b/docs/agents/runtime/observe-and-trace.md @@ -1,52 +1,56 @@ # @genclass/runtime: observers, ops and causality -> **Scope:** `packages/runtime/src/observe/*.ts` (fetch, xhr, dom-user, errors, nav, storage, perf, websocket, timers, cache), `packages/runtime/src/trace/*.ts` (events, ops, context), and the parts of `packages/runtime/src/runtime.ts` that install/uninstall observers and route their events (`installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `destroy`). Also the helpers they depend on in `packages/runtime/src/util.ts`, `packages/runtime/src/clock.ts` and `packages/runtime/src/decide/exec.ts`. -> **Read this when:** you change or debug how GenClass patches `fetch` / `XMLHttpRequest` / `WebSocket` / timers / DOM events / history / Storage / errors / long tasks; how requests are held, faked, coalesced or served from cache; how ops, op signatures, request identities and cause/root links are produced; how the ambient op is propagated across `await`; or what lands in the event ring buffer. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/observe/*.ts` (fetch, xhr, dom-user, errors, nav, storage, perf, websocket, eventsource, messages, timers, cache), `packages/runtime/src/trace/*.ts` (events, ops, context), and the parts of `packages/runtime/src/runtime.ts` that install/uninstall observers and route their events (`installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runDelivery` (only the observer-facing side), `noteResponse`, `onChannel`, `destroy`). Also the helpers they depend on in `packages/runtime/src/util.ts`, `packages/runtime/src/clock.ts` and `packages/runtime/src/decide/exec.ts`. +> **Read this when:** you change or debug how GenClass patches `fetch` / `XMLHttpRequest` / `WebSocket` / `EventSource` / timers / DOM events / history / Storage / errors / long tasks; how requests are held, faked, coalesced or served from cache; how a response or a pushed message is held at the delivery gate before the app sees it; how ops, op signatures, request identities and cause/root links are produced; how the ambient op is propagated across `await`; or what lands in the event ring buffer. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR -- Observers are installed by `RuntimeImpl`'s constructor (`packages/runtime/src/runtime.ts` -> `installObservers`). Each installer returns an uninstall function or `null` (API missing). Installers are wrapped in try/catch, so init never throws. `destroy()` runs the uninstalls in reverse order. -- Each wrapper keeps a `disabled` flag. After `destroy()` it is a pure pass-through. A global is restored only if it still holds GenClass's wrapper; if another library wrapped on top, GenClass leaves that library's wrapper in place. Exceptions: objects created *before* `destroy()` keep their per-instance hooks (a `GenClassWebSocket` keeps recording ops and events, a timer scheduled earlier still sticks a lazy op when it fires), see "After destroy: what still runs" under Invariants. -- Everything the app does async is an **op** (`OpRec` in `packages/runtime/src/trace/ops.ts`). An op has a sequential `id`, a `kind`, a `name` (= op signature, e.g. `GET /api/items/:id`), an optional `detail` (e.g. `?q=rea`), and `cause`/`root` links. User actions, WS messages and sends, timer ticks and GenClass actions are *instant* ops. -- The **ambient op** (`packages/runtime/src/trace/context.ts` -> `Context`) is the op whose work is running. `startOp` uses it as the `cause` and state writes use it as their writer. GenClass sets it in three ways. `run` sets it synchronously. `stick` sets it until `clock.afterTask` clears it at the end of the macrotask; `stick` happens when a wrapped fetch/XHR/Response body settles, a user action is recorded, a timer fires, a WS message arrives, or `rt.op` settles. GenClass does **not** propagate context through arbitrary promises. +- Observers are installed by `RuntimeImpl`'s constructor (`packages/runtime/src/runtime.ts` -> `installObservers`). Each installer returns an uninstall function or `null` (API missing). Installers are wrapped in try/catch, so init never throws. `destroy()` runs the uninstalls in reverse order. There are ten observers: `timers fetch xhr websocket eventsource user errors nav storage perf` (install order), plus the `observe.untrustedEvents` flag for the DOM observer. +- Each wrapper keeps a `disabled` flag. After `destroy()` it is a pure pass-through. A global is restored only if it still holds GenClass's wrapper; if another library wrapped on top, GenClass leaves that library's wrapper in place. Exceptions: objects created *before* `destroy()` keep their per-instance hooks (a `GenClassWebSocket` / `GenClassEventSource` keeps recording ops and gating messages, a timer scheduled earlier still sticks a lazy op when it fires), and `XMLHttpRequest.prototype.addEventListener/removeEventListener` stay installed as pass-throughs once any app listener was wrapped. See "After destroy: what still runs" under Invariants. +- Everything the app does async is an **op** (`OpRec` in `packages/runtime/src/trace/ops.ts`). An op has a sequential `id`, a `kind`, a `name` (= op signature, e.g. `GET /api/items/:id`), an optional `detail` (e.g. `?q=rea`), and `cause`/`root` links. User actions, WS/SSE messages, WS sends, timer ticks and GenClass actions are *instant* ops. +- The **ambient op** (`packages/runtime/src/trace/context.ts` -> `Context`) is the op whose work is running. `startOp` uses it as the `cause` and state writes use it as their writer. GenClass sets it in three ways. `run` sets it synchronously. `stick` sets it until `clock.afterTask` clears it at the end of the macrotask; `stick` happens when a wrapped fetch/Response body settles (or a held response is released), an XHR completes (or its held completion listeners run), a user action is recorded, a timer fires, a WebSocket/EventSource message is dispatched to the app, or `rt.op` settles. GenClass does **not** propagate context through arbitrary promises. - Timer callbacks get a **`LazyOp`**. It becomes a real `timer` op only when something calls `ctx.op()`. A `LazyOp`'s parent is always a real op or `null`, never another `LazyOp`, so recursive `setTimeout` loops never build a chain. -- fetch is the only fully *controllable* transport. Its request gate offers send / coalesce / delay / block / serve_cached; its failure gate offers deliver / retry / serve_cached; its stall watch offers wait / hedge / serve_cached. The app's promise always settles, and a failed action falls back to sending. -- XHR supports send / delay / block / serve_cached at the request gate (block and cached answers are faked onto the XHR). XHR failures and stalls are detection-only. Synchronous XHRs and `keepalive` fetches never raise a request trigger at all. +- **Four network gates** (situation-v2). fetch: request gate (send / coalesce / delay / block / serve_cached), failure gate (deliver / retry / serve_cached), stall watch (wait / hedge / serve_cached), and the **delivery gate** (deliver / discard / defer) for successful responses. XHR: request gate (send / delay / block / serve_cached), delivery gate, and detection-only failures and stalls. WebSocket and EventSource: the delivery gate for every incoming message (`packages/runtime/src/observe/messages.ts` -> `MessageGate`), keeping per-channel order. The app's promise or event always arrives; holding is only latency; a failed action falls back to the passive one. +- **Holds need a non-passive action permitted by the mode** (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`). The default mode is now `observe` (commit f3636b2), which permits no non-passive action, so by default nothing is held at the request/failure/delivery gates; decisions are made in the background. One exception from code reading: the delivery gate reads the body (≤ 100 ms) *before* asking, so while the runtime is consultable (provider state `ready` or `off`; the default model host starts `off` until its idle preload runs) a response or message with a conflict can arrive a little later even in observe mode (see Drift). +- Synchronous XHRs and `keepalive` fetches never raise a request trigger at all. - **Request identity** = FNV-1a of method + absolute URL + non-volatile headers + body content key. Bodies that cannot be read cheaply get a unique `uniq:N` key and so never match. - The response cache (`packages/runtime/src/observe/cache.ts` -> `ResponseCache`) has two parts: - a GET cache of the last good 2xx body per identity (≤ 256 KB each, ≤ 64 entries, LRU); - a coalescing table of in-flight or recently finished (≤ 2 s) requests (≤ 64 entries, ≤ 4 MiB). - The app always reads its own `Response`; GenClass reads a clone. + The app always reads its own `Response`; GenClass reads a clone. The same buffered clone feeds the delivery gate's JSON body. - Every response GenClass synthesises carries the header `x-genclass: blocked | cached | coalesced`. Opaque responses shared by coalescing are the exception: they are unmarked clones. -- The DOM observer records click / input (typing) / change / submit / Enter / Escape at the capture phase on `window`. It skips `[data-genclass-ignore]` subtrees (shadow roots included) and events dispatched by app code while a non-user op runs. It never records sensitive field values. -- Events go to a ring buffer (`packages/runtime/src/trace/events.ts` -> `EventLog`) of `historySize` entries (default 500, minimum 16). Op names, details and event names feed the situation text the model reads and the sim's training data. The format is frozen at tag `situation-v1`, so any wording change needs coordination with SIM and TRAIN. +- The DOM observer records click / input (typing) / change / submit / Enter / Escape at the capture phase on `window`. **Synthetic events (`isTrusted === false`) are dropped unless `observe.untrustedEvents: true`.** It describes the real target inside open shadow roots (`composedPath()[0]`) and adds `change`/`submit` listeners to open shadow roots. It skips `[data-genclass-ignore]` subtrees and events dispatched while app code of a non-user op runs. It never records sensitive field values. Clicks carry `clicks` (`MouseEvent.detail`). +- Events go to a ring buffer (`packages/runtime/src/trace/events.ts` -> `EventLog`) of `historySize` entries (default 500, minimum 16). Op names, details and event names feed the situation text the model reads and the sim's training data. The format is frozen at tag `situation-v2` (6e5e86e), so any wording change needs coordination with SIM, REAL and TRAIN. ## Files | Path | Role | Key exports / entry points | |---|---|---| -| `packages/runtime/src/observe/fetch.ts` | Wraps `global.fetch`: op creation, request identity, request gate, failure gate, stall controller, Response instrumentation | `installFetch`, `bodyInfo`, `headersKey`, `parseRequest`, `instrumentResponse`, `IDENTITY_BODY_MAX`, `ParsedRequest` | +| `packages/runtime/src/observe/fetch.ts` | Wraps `global.fetch`: op creation, request identity, request gate, failure gate, stall controller, delivery-gate hookup (`host.deliver`, `host.noteResponse`, module-private `jsonOfBuffered`), Response instrumentation | `installFetch`, `bodyInfo`, `headersKey`, `parseRequest`, `instrumentResponse`, `IDENTITY_BODY_MAX`, `ParsedRequest` | | `packages/runtime/src/observe/cache.ts` | GET response cache, coalescing table, bounded response buffering, synthetic responses | `ResponseCache`, `bufferResponse`, `makeResponse`, `blockedResponse`, `isOpaque`, `Buffered`, `RecentEntry`, `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS` | -| `packages/runtime/src/observe/xhr.ts` | Patches `XMLHttpRequest.prototype.{open,send,abort,setRequestHeader}` | `installXHR` | -| `packages/runtime/src/observe/dom-user.ts` | Capture-phase DOM user-action listeners and element descriptions | `installDomUser`, `describeElement` (public, re-exported from `packages/runtime/src/index.ts`), `isSensitiveField`, `ignoredEvent` | +| `packages/runtime/src/observe/xhr.ts` | Patches `XMLHttpRequest.prototype.{open,send,abort,setRequestHeader,addEventListener,removeEventListener}` and defines per-instance `on*` completion-handler properties; request gate and delivery gate | `installXHR` | +| `packages/runtime/src/observe/dom-user.ts` | Capture-phase DOM user-action listeners (window, plus `change`/`submit` on adopted open shadow roots) and element descriptions (shadow-DOM aware) | `installDomUser`, `describeElement` (public, re-exported from `packages/runtime/src/index.ts`), `isSensitiveField`, `ignoredEvent` | | `packages/runtime/src/observe/errors.ts` | `error` and `unhandledrejection` listeners | `installErrors` | | `packages/runtime/src/observe/nav.ts` | Wraps `history.pushState/replaceState` and listens to `popstate`/`hashchange` | `installNav` | | `packages/runtime/src/observe/storage.ts` | Wraps `Storage.prototype.{setItem,removeItem,clear}` | `installStorage` | | `packages/runtime/src/observe/perf.ts` | `PerformanceObserver` for `longtask` | `installPerf` | -| `packages/runtime/src/observe/websocket.ts` | Replaces `global.WebSocket` with a subclass | `installWebSocket`, `WsHost` | +| `packages/runtime/src/observe/websocket.ts` | Replaces `global.WebSocket` with a subclass; connect op, channel up/down, message gate, recorded sends | `installWebSocket`, `WsHost` (now an alias of `MsgHost`) | +| `packages/runtime/src/observe/eventsource.ts` | Replaces `global.EventSource` with a subclass; connect op, channel up/down, message gate for `message` and custom event types | `installEventSource` | +| `packages/runtime/src/observe/messages.ts` | The delivery gate for push channels: creates message ops inside the dispatch, holds/re-dispatches events in order; message summaries | `MessageGate`, `MsgHost`, `messageSummary` | | `packages/runtime/src/observe/timers.ts` | Wraps `setTimeout`/`setInterval` to carry context into callbacks | `installTimers`, `TimerHost` | | `packages/runtime/src/trace/events.ts` | Event ring buffer | `EventLog` | -| `packages/runtime/src/trace/ops.ts` | Op registry | `OpRegistry`, `OpRec`, `StartOpts`, `ChainWrite` | +| `packages/runtime/src/trace/ops.ts` | Op registry (plus the delivery fields `OpRec.delivery` and `OpRec.discardMark`) | `OpRegistry`, `OpRec`, `StartOpts`, `ChainWrite` | | `packages/runtime/src/trace/context.ts` | Ambient-op propagation | `Context`, `LazyOp`, `Ambient` | -| `packages/runtime/src/runtime.ts` | Wiring: installs observers, builds hosts, creates and ends ops, routes events and triggers | `RuntimeImpl.installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runAsGenClass`, `destroy` | -| `packages/runtime/src/decide/exec.ts` | Seam between observers and decisions | `NetHost`, `Controller`, `ActionEffect`, `EndOpts`, `TriggerOpts` | -| `packages/runtime/src/util.ts` | URL parsing, signature normalisation, hashing, redaction | `parseUrl`, `normalizePath`, `isIdSegment`, `requestSignature`, `redactSearch`, `fnv1a`, `stableStringify`, `IDEMPOTENT_METHODS`, `isSensitiveName`, `defaultRedact` | +| `packages/runtime/src/runtime.ts` | Wiring: installs observers, builds hosts, creates and ends ops, routes events and triggers, runs the delivery gate | `RuntimeImpl.installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runDelivery`, `noteResponse`, `onChannel`, `runAsGenClass`, `destroy` | +| `packages/runtime/src/decide/exec.ts` | Seam between observers and decisions | `NetHost` (incl. `deliver`, `noteResponse`), `Controller` (incl. `proceeded`, `stale`), `ActionEffect` (incl. `onRecord`), `EndOpts`, `TriggerOpts` | +| `packages/runtime/src/util.ts` | URL parsing, signature normalisation, hashing, redaction | `parseUrl`, `normalizePath`, `isIdSegment`, `requestSignature`, `redactSearch`, `fnv1a`, `stableStringify`, `IDEMPOTENT_METHODS`, `isSensitiveName`, `isSensitivePath`, `defaultRedact` | +| `packages/runtime/src/situation/content.ts` | JSON body parsing used by fetch, XHR and the message gate (out of scope; see [learn-situation-triage.md](learn-situation-triage.md)) | `parseJsonBody` | | `packages/runtime/src/clock.ts` | Real clock: timers captured at module load, `afterTask` | `browserClock` | -| `packages/runtime/src/types.ts` | Public types | `Op`, `OpKind`, `OpStatus`, `RtEvent`, `EventKind`, `UserAction`, `ObserverName`, `Clock`, `RuntimeHooks` | +| `packages/runtime/src/types.ts` | Public types | `Op`, `OpKind`, `OpStatus`, `RtEvent`, `EventKind`, `UserAction` (incl. `clicks`), `ObserverName` (incl. `eventsource`), `InitOptions.observe` (incl. `untrustedEvents`), `TriggerKind` (incl. `delivery`), `Clock`, `RuntimeHooks` | | `packages/runtime/src/situation/env.ts` | Request/failure subject types the observers fill in | `ReqMeta`, `FailureInfo`, `SubjectSpec`, `SitEnv` (`cached`, `identical`, `canCoalesce`) | | `packages/runtime/src/situation/describe.ts` | How ops are worded in situations and `ActionEffect.changed` sentences | `opPhrase`, `opLabel`, `userPhrase` (out of scope; see [learn-situation-triage.md](learn-situation-triage.md)) | -| `packages/runtime/src/index.ts` | Entry: kill-switch observe map and the model host's un-observed fetch | `ALL_OFF`, `NATIVE_FETCH` (module-private), re-export of `describeElement` | +| `packages/runtime/src/index.ts` | Entry: kill-switch observe map and the model host's un-observed fetch | `ALL_OFF`, `NATIVE_FETCH` (both module-private), re-export of `describeElement` | ## Concepts and data structures @@ -61,10 +65,13 @@ Terms specific to this doc (see also [../glossary.md](../glossary.md)): | running op | `Context.running`: set only while `Context.run(op, fn)` executes `fn` synchronously. The DOM observer uses it to detect programmatic events. | | lazy timer op | A `LazyOp` made for each wrapped timer callback. `materialize()` creates a real `timer` op on first use. | | request identity | `ReqMeta.identity` / `OpRec.identity`: the hash that defines "identical requests". `""` while the body is still being read. A key starting `uniq:` (or hashed from one) matches nothing. | -| held | A request or failure waiting for a decision (the request gate or failure gate with `hold: true`). It fails open after the hold budget. | +| held | A request, failure, or response/message at the delivery gate waiting for a decision (a trigger raised with `hold: true` whose mode/policy permits a non-passive action). It fails open after the hold budget. | | controller | A `Controller` from `packages/runtime/src/decide/exec.ts`. `passive()` lets the subject proceed. `run(action)` performs a built-in action and returns `ActionEffect.changed`, or throws, in which case passive runs instead. | | gated | `NetHost.gated(op)`: `!paused && !destroyed && !op.genclass`. fetch and XHR raise request/failure/stall triggers only for gated ops (the `error` trigger from `reportError` does not use `gated`). | | synthetic end | `endOp(..., { synthetic: true })`: the op was answered by GenClass (block, cache or coalesce). It is kept out of latency baselines and transition profiles. | +| delivery gate | `RuntimeImpl.runDelivery`: a successful fetch/XHR response or a WebSocket/EventSource message is about to reach the app. Observers hand it a `release` callback; the gate calls it at most once, synchronously when nothing is salient. Trigger `delivery`, actions `deliver` (passive) / `discard` / `defer` (see [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md) for salience). | +| message gate | `MessageGate` (`packages/runtime/src/observe/messages.ts`): one per socket/stream. Its `message` (and custom-type) listener is the first one on the target for that type (GenClass's own `open`/`error`/`close` bookkeeping listeners are registered just before its `close`/`error` ones); it creates the message op, asks the delivery gate, and if held stops the event and re-dispatches a clone later, queueing later messages and `close`/`error` events behind it. | +| channel down / up | `MsgHost.channel("down" \| "up", channel, path, code?)` -> `RuntimeImpl.onChannel`: a socket/stream that errored or closed (WebSocket: code ≠ 1000) and later re-opened on the same path marks the fields its messages wrote as possibly stale (F9). | `OpRec` (`packages/runtime/src/trace/ops.ts`; extends `Op` from `packages/runtime/src/types.ts`): @@ -73,7 +80,7 @@ Terms specific to this doc (see also [../glossary.md](../glossary.md)): | `id` | number | Sequential from 1 per `OpRegistry` (per runtime), never reused | | `kind` | `OpKind` = `"user" \| "fetch" \| "xhr" \| "ws" \| "task" \| "timer" \| "genclass"` | Creator | | `name` | string | Op signature | -| `detail?` | string | Query string or body summary (requests), quoted typed value (user), message summary (ws) | +| `detail?` | string | Query string or body summary (requests), quoted typed value (user), message/send summary (`ws` messages and sends, WebSocket and EventSource), `connect` (`ws` connect ops) | | `start`, `end?` | number (clock ms) | `start` at creation, `end` at `OpRegistry.end` (instant ops: `end = start`) | | `status?` | `"ok" \| "error" \| "aborted" \| "blocked"` | At end | | `code?` | number \| string | HTTP status, `"timeout"`, `"network"`, `"aborted"`, or a WS close code | @@ -81,7 +88,7 @@ Terms specific to this doc (see also [../glossary.md](../glossary.md)): | `attempt` | number | Default 1. A fetch retry gets `attempt + 1`; a hedge keeps the attempt | | `reads` | `Map<string, number>` | Always created empty; filled lazily by situation building | | `identity?` | string | Request identity (fetch/xhr) | -| `meta?` | object | User ops: `{ action: UserAction }` (value already redacted). Tasks: the `meta` passed to `rt.op` | +| `meta?` | object | User ops: `{ action: UserAction }` (value already redacted; clicks carry `clicks` = `MouseEvent.detail`, which `situation/evidence.ts` reads for repeated-action evidence). Tasks: the `meta` passed to `rt.op` | | `startSeq` | number | `hub.seq` (the global applied-mutation sequence) at start | | `method?`, `url?` | string | Requests | | `errorText?` | string | e.g. `HTTP 503`, the network error message | @@ -90,15 +97,17 @@ Terms specific to this doc (see also [../glossary.md](../glossary.md)): | `triggered?` | `Set<TriggerKind>` | Triggers already raised for this op. A stall is raised once per op | | `genclass?` | boolean | `kind === "genclass"`, or inherited from a cause that is `genclass`. Such ops are never gated, profiled, baselined or identity-registered | | `children` | number | Count of ops that name this op as `cause` (diagnostic) | +| `delivery?` | `{ patterns; known; salient; decided; overNewer? }` | Set by `runDelivery` for the op whose response/message is delivered: predicted write patterns, whether they are known, salience, and (`overNewer`) the fields it was delivered over newer data on | +| `discardMark?` | `{ protect; until; dropped; onDrop? }` | Set by the delivery `discard` action: writes of this op's chain to `protect` paths are dropped until `until` (10 s, `DISCARD_MARK_MS`); checked in `runtime.ts` when a write of the chain (≤ 16 cause hops) is applied | Op kinds as produced in practice: | kind | Created by | `name` format | Instant | Default cause | Pushes `op.start`? | Profiled (`PROFILED`) | Baselines + identity | |---|---|---|---|---|---|---|---| -| `user` | `RuntimeImpl.user` (DOM observer, `rt.user`, plugin `api.user`, the sim) | `${kind} ${target}` (or bare `kind` with no target), e.g. `click button "Add to cart"`, `type input "Search"`, `key input "Search"` (the key itself is only in `meta.action.key`) | yes | `null` (always a root) | no (has its own `user` event) | yes | no | +| `user` | `RuntimeImpl.user` (DOM observer, which is how the realapps harness records actions in its real browsers; `rt.user`; plugin `api.user`; the sim, which calls `runtime.user` directly) | `${kind} ${target}` (or bare `kind` with no target), e.g. `click button "Add to cart"`, `type input "Search"`, `key input "Search"` (the key itself is only in `meta.action.key`) | yes | `null` (always a root) | no (has its own `user` event) | yes | no | | `fetch` | `installFetch` (also retry and hedge ops) | `GET /api/items/:id` | no | ambient (retry and hedge: explicit) | yes | yes | yes, unless `genclass` | | `xhr` | `installXHR` | same as fetch | no | ambient | yes | yes | yes, unless `genclass` | -| `ws` | `installWebSocket` | `WS <path>` (connect), `WS message <path>`, `WS send <path>`; `<path>` is `host/path` for an absolute `ws(s):` URL on a page with a `location` (see WebSocket step 2) | message and send: yes | connect and send: ambient; message: `null` (root) | connect only (message and send push `custom` events) | yes | no | +| `ws` | `installWebSocket`, `installEventSource` (both through `wsHost`, kind fixed to `ws`) | WebSocket: `WS <path>` (connect), `WS message <path>`, `WS send <path>`. EventSource: `SSE <path>` (connect), `SSE message <path>`, `SSE <type> <path>` (custom event types). `<path>` is the bare pathname for same-host URLs and `host/path` for other hosts (see WebSocket step 2) | messages and sends: yes | connect and send: ambient; messages: `null` (root) | connect only (messages and sends push `custom` events) | yes | no | | `task` | `rt.op(name, fn, meta)`; plugin `api.recordOp(kind, …)` can create any kind | the given name | no | ambient | yes | yes | no | | `timer` | `LazyOp.materialize` via `RuntimeImpl.timerHost().lazyTimer` | `timer 300ms`, `timer 1.50s`, `interval 5.00s` | yes | the op that was ambient when the timer was scheduled (nearest real op) | yes (`data.instant: true`) | no | no | | `genclass` | `RuntimeImpl.runAsGenClass(name, fn)` | `undo`, `revert`, `rollback`, `resync`, or a custom action name | yes | `null` | no (has `action` events) | no | no | @@ -138,7 +147,7 @@ Request `detail` format (`fetch.ts` -> `parseRequest`): the redacted query strin | `nav` | nav observer | route (`pathname+search+hash`, ≤ 80 chars) | — | `{ route }` | | `perf` | perf observer | `long task` | — | `{ duration }` | | `storage` | `RuntimeImpl.onStorage` | `localStorage.setItem` / `sessionStorage.removeItem` / `storage.clear` … | ambient op | `{ key }` (`[redacted]` when the redactor changes it) | -| `custom` | `rt.emit` (data redacted per key plus `summary` ≤ 80 chars), `ws.message` / `ws.send` (`{ path, summary }`), `xhr.send-failed` (`{ error }`) via `NetHost.emit` | event name | ambient op / message op / xhr op | as listed | +| `custom` | `rt.emit` (data redacted per key plus `summary` ≤ 80 chars); `ws.message` / `sse.message` (`{ path, summary, type }`, `type` = the DOM event type) and `ws.send` (`{ path, summary }`) via `MsgHost.event`; `xhr.send-failed` (`{ error }`) and `xhr.aborted-while-held` (`{}`) via `NetHost.emit`; `delivery.unchanged` (`{ paths }`) from `runDelivery` when every conflict field would be unchanged by the body | event name | ambient op / message op / xhr op / delivered op | as listed | | `decision`, `action` | decision flow (see [decide-policy-actions.md](decide-policy-actions.md)) | trigger / action name | — | — | `EventLog` API (`packages/runtime/src/trace/events.ts`, exposed as `rt.internals.events`): @@ -163,7 +172,7 @@ type Buffered = interface RecentEntry { op: OpRec; body: Promise<Buffered | null>; settledAt?: number; bytes: number } ``` -`XhrState` (module-private in `packages/runtime/src/observe/xhr.ts`, kept in a module-level `WeakMap` keyed by XHR object): `{ method; url; async; headers: Map; op?; failed?: "error"|"timeout"|"abort"; held; abortedWhileHeld; faked: string[]; onEnd? }`. +`XhrState` (module-private in `packages/runtime/src/observe/xhr.ts`, kept in a module-level `WeakMap` keyed by XHR object): `{ method; url; async; headers: Map; op?; failed?: "error"|"timeout"|"abort"; held; abortedWhileHeld; faked: string[]; onEnd?; req?: ReqMeta; dlv: "none" | "held" | "open"; queue: (() => void)[] }`. `held` is the request gate (native `send` not called yet); `dlv`/`queue` are the delivery gate (the app's completion listener calls waiting for a decision). `BodyInfo` (module-private in `fetch.ts`, returned by the exported `bodyInfo`): `{ key?: string ("" = no body; undefined while pending); pending?: Promise<string>; bytes; replayable; summary }`. @@ -171,36 +180,37 @@ Host interfaces (what each installer receives; all built in `packages/runtime/sr | Interface | Defined in | Members | |---|---|---| -| `NetHost` (fetch, XHR) | `packages/runtime/src/decide/exec.ts` | `clock`, `ctx`, `global`, `cache`, `redact()`, `baseHref()`, `startOp(kind, name, o)`, `endOp(op, status, o?)`, `gated(op)`, `trigger(spec, ctl, opts)`, `watchStall(op, req, ctl)`, `failureStreak(sig)`, `emit(name, data?, op?)`, `uniqueId()`, `setIdentity(op, req, identity)` | +| `NetHost` (fetch, XHR) | `packages/runtime/src/decide/exec.ts` | `clock`, `ctx`, `global`, `cache`, `redact()`, `baseHref()`, `startOp(kind, name, o)`, `endOp(op, status, o?)`, `gated(op)`, `trigger(spec, ctl, opts)`, `watchStall(op, req, ctl)`, `failureStreak(sig)`, `emit(name, data?, op?)`, `deliver({ op, req, status, body? }, release)` (-> `runDelivery` with channel `response`), `noteResponse?({ op, req, status, body })` (read-your-writes: remembers ids returned by POST/201 responses), `uniqueId()`, `setIdentity(op, req, identity)` | | `TimerHost` | `packages/runtime/src/observe/timers.ts` | `global`, `ctx`, `lazyTimer(parent, label)` | -| `WsHost` | `packages/runtime/src/observe/websocket.ts` | `global`, `ctx`, `redact()`, `baseHref()`, `startOp(name, o)` (kind fixed to `ws`), `endOp(op, status, o?)`, `event(name, data, op?)` (a `custom` event) | -| `UserSink` (module-private) | `packages/runtime/src/observe/dom-user.ts` | `user(action, handler?)`, `ambientKind?()`, `runningKind?()` | +| `MsgHost` (= `WsHost`; WebSocket and EventSource) | `packages/runtime/src/observe/messages.ts` | `global`, `ctx`, `redact()`, `baseHref()`, `startOp(name, o)` (kind fixed to `ws`), `endOp(op, status, o?)`, `event(name, data, op?)` (a `custom` event), `deliverMessage({ op, channel, message: { path, summary }, queuedAhead, body? }, release)` (-> `runDelivery`), `channel?(state, channel, path, code?)` (-> `onChannel`) | +| `UserSink` (module-private) | `packages/runtime/src/observe/dom-user.ts` | `untrusted?` (= `observe.untrustedEvents`), `user(action, handler?)`, `ambientKind?()`, `runningKind?()` | | `ErrorSink` (module-private) | `packages/runtime/src/observe/errors.ts` | `reportError(error, info?)` (the `RuntimeImpl` itself is passed) | | nav / storage / perf | their files | plain callbacks: `onNav(route)`, `cb(area, op, key)`, `cb(name, duration)` | -Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passive(): void /* called at most once */; run(action): ActionEffect | Promise<ActionEffect> /* throw = passive runs */; revertable?(); revert?() /* held writes only */ }`, `ActionEffect { changed: string; undo? }`, `TriggerOpts { hold: boolean; priority: number }`, `EndOpts { code?; errorText?; failure? /* counts as a failure in baselines */; synthetic? }`. +Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passive(): void /* called at most once */; run(action): ActionEffect | Promise<ActionEffect> /* throw = passive runs */; revertable?(); revert?() /* held writes only */; proceeded?() /* the subject already went ahead: actions come too late */; stale?() /* a queued decision is no longer worth computing */ }`, `ActionEffect { changed: string; undo?; onRecord?(record) }`, `TriggerOpts { hold: boolean; priority: number }`, `EndOpts { code?; errorText?; failure? /* counts as a failure in baselines */; synthetic? }`. ## How it works ### 1. Install, route and uninstall (`packages/runtime/src/runtime.ts`) 1. The constructor creates `EventLog(o.historySize ?? 500)`, `Context(clock)`, `ResponseCache(clock)` and an `OpRegistry` (`clock = o.clock ?? browserClock`, `global = o.global ?? globalThis`). It wires `events.onEvent(e => fire("event", e))` and the decider's `onStatus` (its unsubscribe goes into the same `uninstall` list as the observers). It then calls `loadProfiles()` (only when `learn.persist` is set), then `installObservers(o.observe ?? {})`, then `use()` for each plugin. -2. `installObservers` reads each `observe[name]` flag. The default is `true`, except `timers`, which defaults to `typeof global.document === "object" && global.document !== null`. The install order is timers, fetch, xhr, websocket, user, errors, nav, storage, perf. Each install goes through `tryAdd`, which catches a throw (e.g. a read-only global) and logs it (only with `debug`). +2. `installObservers` reads each `observe[name]` flag. The default is `true`, except `timers`, which defaults to `typeof global.document === "object" && global.document !== null`. The install order is timers, fetch, xhr, websocket, eventsource, user, errors, nav, storage, perf. Each install goes through `tryAdd`, which catches a throw (e.g. a read-only global) and logs it (only with `debug`). The same map carries `untrustedEvents` (default `false`), passed to the DOM observer as `UserSink.untrusted`; it is not an observer and installs nothing. The mode does not affect which observers install: in the default `observe` mode every observer runs and every trigger is still decided (in the background). 3. Hosts: - `netHost()` (`NetHost`) serves fetch and XHR. It provides `gated`, `trigger` (`RuntimeImpl.trigger`), `watchStall`, `failureStreak(sig)` (= `base.stats(sig)?.failStreak ?? 0`), `uniqueId()` (= `uniq:${++n}`), `setIdentity` (updates `op.identity` and `req.identity`, then re-registers), `emit` (a `custom` event) and `baseHref()` (= `global.location.href`). - `timerHost()` provides `lazyTimer(parent, label)` = `new LazyOp(parent, cause => startOp("timer", label, { cause, instant: true }))`. - - `wsHost()` maps `startOp` to kind `ws` and `event` to a `custom` event. + - `netHost().deliver` calls `runDelivery({ ..., channel: "response" }, release)`; `noteResponse` remembers the ids a POST or 201 response returned (`createsBuf`, ≤ 16 entries, 30 s) for read-your-writes facts. + - `wsHost()` (a `MsgHost`, shared by WebSocket and EventSource) maps `startOp` to kind `ws`, `event` to a `custom` event, `deliverMessage` to `runDelivery`, and `channel` to `onChannel`. Its `baseHref()` returns `global.location?.href` without the string check `netHost` does. 4. Routing: - DOM user actions go to `RuntimeImpl.user`, with `ambientKind` and `runningKind` callbacks (a `LazyOp` reports as `"timer"`). - Errors go to `RuntimeImpl.reportError`. It creates an `error` event and raises the `error` trigger (`hold: false`, `priority: 0`). - Nav, perf and storage become events only. They never raise triggers. 5. `destroy()` sets `destroyed` and runs every uninstall in reverse order, then unregisters plugins and calls `ctx.clear()`. It does **not** clear `ResponseCache`. Full order (`RuntimeImpl.destroy`, idempotent): 1. `destroyed = true`, `hub.gating = false`; - 2. `queue.dispose()` (`packages/runtime/src/decide/decider.ts` -> `DeciderQueue`): every *queued* decision resolves `null`, so `RuntimeImpl.trigger` runs the controller's `passive()` (it checks `destroyed` first). The one decision already being evaluated ends when the provider answers or its deadline timer fires, and the hold-budget timer is not cleared by `destroy()`, so it also runs `passive()`. Either way a held fetch or XHR is **sent** (not dropped) and a held failure is delivered; + 2. `queue.dispose()` (`packages/runtime/src/decide/decider.ts` -> `DeciderQueue`): every *queued* decision resolves `null`, so `RuntimeImpl.trigger` runs the controller's `passive()` (it checks `destroyed` first). The one decision already being evaluated ends when the provider answers or its deadline timer fires, and the hold-budget timer is not cleared by `destroy()`, so it also runs `passive()`. Either way a held fetch or XHR is **sent** (not dropped), a held failure is delivered, and a held response or WebSocket/EventSource message is released to the app; 3. `reporter.dispose()`, clear the settle and persist timers; 4. run `uninstall` in reverse (observers, decider status listener); 5. `unuse` every plugin, `unsubscribeIO` every store, `ctx.clear()`, dispose the decider if the runtime owns it. - From then on `gated(op)` is false and `consultable()` is false, so any trigger an existing object still raises runs its passive action at once. + From then on `gated(op)` is false and `consultable()` is false, so any trigger an existing object still raises runs its passive action at once, and `runDelivery` releases at once (it checks `destroyed`). 6. `GenClass.init` (`packages/runtime/src/index.ts`) passes `observe: ALL_OFF` in three cases: outside a browser (no `window`/`document`), with the `?genclass=off` kill switch, and in the init-failure fallback. The model host downloads with `NATIVE_FETCH`, captured at module load (or `global.fetch` bound before the runtime wraps it), so GenClass never observes its own model download. ### 2. Op lifecycle (`RuntimeImpl.startOp` / `RuntimeImpl.endOp`) @@ -213,13 +223,13 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi It prunes when `byId.size > 2000`: the oldest non-in-flight ops are deleted until the size is ≤ 1500. 3. Back in `startOp`: - pushes `op.start` (see the event table); - - for non-`genclass` fetch/xhr ops, calls `base.start(name, t)` and `registerIdentity(op)`; + - for non-`genclass` fetch/xhr ops, calls `base.start(name, t)`, `registerIdentity(op)` (when it has an identity) and `cadence.note(...)` (learned cadence, F6: whether the request descends from a user action, and the user-to-request delay when its cause is a `timer` op); - queues instant ops of profiled kinds for profiling; - calls `hooks.opCreated(op)` synchronously. 4. `endOp(op, status, { code, errorText, failure, synthetic })` does nothing if the op has already ended. Otherwise it: - calls `ops.end` (sets `end`, `status`, `code`, `errorText`; notifies `onEnd` listeners); - pushes `op.end`; - - for non-synthetic, non-`genclass` fetch/xhr ops, calls `base.end(name, t, dur, ok, outcome, failure)`; + - for non-synthetic, non-`genclass` fetch/xhr ops, calls `base.end(name, t, dur, ok, outcome, failure)` and, unless aborted, appends to `outcomesBuf` (≤ 128 entries, 30 s; failure-scope facts F5); - queues profiled kinds that are neither aborted nor synthetic; - calls `scheduleSettle()`. 5. `registerIdentity(op)` skips `genclass` ops and identities starting with `uniq:`. It calls `base.noteIdentity` and keeps `identicalMap[identity]`: at most 12 ops, dropping entries that ended and started more than 10 s ago, across at most 512 identities (oldest identity evicted). Situations read it through `SitEnv.identical`. @@ -234,7 +244,7 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi - Any exception means `nativeFetch` with no op. 3. Body key: - `bodyKnown`: `bodyInfo(body, host)` (rules below). - - A `Request` with a body: `template = req.clone()` keeps a pristine copy for replays. If `content-length > 64 KB` or cloning failed, the key is `uniqueId()`. Otherwise a second clone's stream goes to `readKey`, which hashes ≤ 64 KB or falls back to `uniqueId()`; the key is then `pending`. + - A `Request` with a body: `template = req.clone()` keeps a pristine copy for replays. If `content-length > 64 KB` or cloning failed, the key is `uniqueId()`. Otherwise a second clone's stream goes to `readKey`, which hashes ≤ 64 KB or falls back to `uniqueId()`; the key is then `pending` (no readable stream on the copy: `uniqueId()` at once). The body summary is `<content-length> bytes`, or `body` without a `content-length` header; `replayable` is false only when cloning failed. 4. `parseRequest(host, method, rawUrl, b, headersKey(input, init))` returns `ReqMeta` (`transport: "fetch"`) plus `detail` and maybe `pendingIdentity`. 5. `host.startOp("fetch", req.signature, { detail, method, url, identity? })` runs **synchronously inside the `fetch()` call**. The cause is the ambient op. 6. `runRequest(op, parsed, input, init, template, gateRequest = !keepalive)` returns a **new Promise** owned by GenClass: @@ -243,7 +253,7 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi 7. Identity resolution. If the identity is pending and the request is not `keepalive`, `within(host, pendingIdentity, IDENTITY_READ_MS = 100, "")` waits for it (falling back to `uniqueId()` on timeout), then calls `setIdentity` and `gate()`. If the request is `keepalive`, it calls `setIdentity(uniqueId())` now, `gate()` at once, and the real identity later. 8. `gate()`: - If `!gateRequest` (keepalive) or `!host.gated(op)`, it calls `sendNow()` synchronously. **No request trigger is raised.** - - Otherwise it calls `host.trigger({ trigger: "request", op, req }, reqCtl, { hold: true, priority: 2 })`. `RuntimeImpl.trigger` runs the passive action (`sendNow`) synchronously in these cases: the runtime is not consultable, all facts are neutral (triage `salient`), the situation is not salient, the provider is not ready, or the mode/policy permits no non-passive action. In all those cases native fetch is called inside the `fetch()` call. The exception is a pending identity (step 7): then the gate runs only after the body read, so the send is always asynchronous. Otherwise the request is **held** until the decision arrives or `holdBudgetMs()` expires; on expiry the passive action runs (fail-open). + - Otherwise it calls `host.trigger({ trigger: "request", op, req }, reqCtl, { hold: true, priority: 2 })`. `RuntimeImpl.trigger` runs the passive action (`sendNow`) synchronously in these cases: the runtime is not consultable, all facts are neutral (triage `salient`), the situation is not salient, the provider is not ready, the mode/policy permits no non-passive action (always so in the default `observe` mode), or the model is not expected to answer within the hold budget (`expectedLatency() > holdBudgetMs()`: usual latency × (1 + decisions queued) + the decision being computed; infinite while the provider is not answering). In all those cases native fetch is called inside the `fetch()` call. The exception is a pending identity (step 7): then the gate runs only after the body read, so the send is always asynchronous. Otherwise the request is **held** until the decision arrives or `holdBudgetMs()` expires; on expiry the passive action runs (fail-open). 9. `send(sendOp, primary)`: - Each attempt is sent at most once (`WeakSet`). - `primary` sets `sent = true` and removes the abort listener; native fetch now owns the app's signal. @@ -254,8 +264,10 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi 10. On a response: - `failed = status >= 500 || 429 || 408`. - `tracked.settledAt = now`. `bufferResponse(res)` reads a **clone**. A `body` result for a non-failed, `res.ok` GET is put in the GET cache. The coalescing entry resolves to `null` if the request failed. - - `endOp(sendOp, failed ? "error" : "ok", { code: status, failure? })`. - - If failed and gated and not yet answered, `failureGate(...)`; else `answer(res)`. + - `endOp(sendOp, failed ? "error" : "ok", { code: status, failure? })`. The op ends when the headers arrive, before the delivery decision. + - If failed and gated and not yet answered, `failureGate(...)`. + - Else, if not failed, `gated(sendOp)` and not yet answered (primary sends only): for a non-GET/HEAD `res.ok` response with a tracked body, `host.noteResponse(...)`; then the **delivery gate** `host.deliver({ op: sendOp, req, status, body? }, () => answer(res))`. `body` (present only when the request was `cache.track`ed, i.e. had a non-empty identity and `Response` exists) resolves to `jsonOfBuffered(buffered clone)`: JSON when the content type is empty, JSON or `text/plain` and the text parses (`situation/content.ts` -> `parseJsonBody`), else `undefined`. The app's own body is never read. + - Otherwise `answer(res)` (not gated, failed but not gated, or already answered). 11. On a rejection: - `TimeoutError` (the error's name, or `signal.reason.name`) is a failure with `code: "timeout"`. - Any other `AbortError` or aborted signal gives `endOp(..., "aborted")` and rejects with the original error. @@ -293,7 +305,7 @@ identity = fnv1a(`${METHOD} ${absoluteHref} ${hdrKey} ` + bodyKey) // "" while detail = redactSearch(url.search, redact /*≤60 chars*/) + (body summary, only when method is not GET/HEAD) ``` -### 4. fetch actions: request gate, failure gate, stall +### 4. fetch actions: request gate, failure gate, stall, delivery Request gate (`reqCtl`; `passive` = `sendNow`, which sends unless the request was already answered, sent or aborted): @@ -313,7 +325,7 @@ Failure gate (`failureGate`: `host.trigger({ trigger: "failure", op: failedOp, r | `retry` | Requires `req.replayable`. Waits `min(200 · 2^(failedOp.attempt − 1), 5000)` ms, then starts `retryOp = startOp("fetch", sig, { attempt: failedOp.attempt + 1, cause: failedOp, … })`, reassigns the closure's `op = retryOp` and sends it as primary. The retry is **not** re-gated at the request gate; its own failure goes through the failure gate again. `situation/build.ts` offers `retry` only when `attempt < 4`, so there are at most 3 retries (backoffs 200, 400, 800 ms). From then on the closure's `op` is the retry op: `answer()` sticks it, the app's `Response` is instrumented with it, and the stall watch is re-armed for it. If the app's signal aborted during the backoff, the app gets `signal.reason` and the action rejects (`aborted`) | | `serve_cached` | Answer with the cached GET body (`x-genclass: cached`) | -Whether the failure is held depends on the policy. In `guard` mode no failure action is permitted, so the failure is delivered at once and the decision is made in the background (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0`). +Whether the failure is held depends on the mode and policy. In `observe` (the default) and `guard` modes no failure action is permitted (`retry` and `serve_cached` are heal-tier), so the failure is delivered at once and the decision is made in the background (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0`). Stall (`RuntimeImpl.watchStall`, armed by `send` for gated primary sends): - It needs a latency baseline (≥ 5 samples, `MIN_LAT_SAMPLES` in `packages/runtime/src/learn/baselines.ts`). @@ -323,6 +335,13 @@ Stall (`RuntimeImpl.watchStall`, armed by `send` for gated primary sends): - `serve_cached`: answers with the cached response; the original request keeps running in the background. - `hedge`: requires `replayable && idempotent`; `build.ts` additionally limits it to GET. It sends `hedgeOp` (cause `op`, same attempt) through `nativeFetch(replayInput)` directly; it is not `cache.track`ed, so its body never enters the GET cache or the coalescing table. It is still an ordinary `fetch` op: it gets `op.start`/`op.end` events, latency baselines and an `identicalMap` entry. If the hedge returns a non-failure first, the app gets it. Otherwise the app keeps waiting for the original. +Delivery gate (fetch side; the gate itself is `RuntimeImpl.runDelivery`, see [decide-policy-actions.md](decide-policy-actions.md)): +- Raised only for a primary send's non-failed response (status not ≥ 500/429/408), gated, not yet answered. 4xx responses pass through it too. Hedge answers, `block`/`serve_cached`/`coalesce` answers and failures do not. +- `release` = `answer(res)`: the app's `await fetch()` resolves (with the op stuck) only after the release. `runDelivery` releases synchronously when nothing is salient (no conflict on the op's predicted write fields, no text typed into those fields since the op started, triage not `always`), when the runtime is not consultable/paused/destroyed, or for `genclass` ops. +- With a conflict (or typed text, or triage `always`) and a `body` function, it first waits for the body (≤ `BODY_WAIT_MS` = 100 ms, `runtime.ts`), analyses it, and only then decides salience and raises the `delivery` trigger (`hold: true, priority: 2`). So the release is asynchronous for such responses whatever the mode. Without a `body` (an untracked fetch) it decides at once from newer-data conflicts only. When the body shows every conflicting field would be unchanged, it pushes a `custom` `delivery.unchanged` event and (unless triage is `always`) releases without asking. +- Actions: `deliver` (passive) releases (and marks `op.delivery.overNewer` when delivered over newer data); `discard` releases and sets `op.discardMark` so this chain's writes to the conflicting paths are dropped for 10 s (`ActionRecord.dropped` lists them; `undo` restores); `defer` waits for related in-flight ops, then runs `runDelivery` again (at most 2 defers). +- Request-gate controllers now also expose `proceeded()` (`sent || answered`) and `stale()` (not sent and the app's signal aborted), so a queued decision about a request the app already aborted is dropped before it reaches the model. The failure controller exposes `proceeded()` (`handled || answered`). + The app's promise always settles. Every action that throws or rejects makes `RuntimeImpl.onDecision` call the controller's `passive()`. Once a request has been sent, GenClass stops listening to the app's `AbortSignal`. A failure held at that point is delivered or retried at decision/budget time (retry checks `signal.aborted`). ### 5. Response cache and buffering (`packages/runtime/src/observe/cache.ts`) @@ -341,72 +360,95 @@ The app's promise always settles. Every action that throws or rejects makes `Run ### 6. XHR (`packages/runtime/src/observe/xhr.ts` -> `installXHR`) -1. `wOpen`: - - `stateOf(xhr)` creates the state and listeners **once per object**: `readystatechange` (readyState 4 sticks `s.op`), `error`/`timeout`/`abort` (set `failed`) and `loadend` (runs `onEnd` once). +1. Install patches six prototype methods: `open`, `send`, `abort`, `setRequestHeader`, and (new in batch 4) `addEventListener` / `removeEventListener`. If any assignment throws, the installer returns `null`. +2. `wOpen`: + - `stateOf(xhr)` creates the state and GenClass's own listeners **once per object** (added with the native `addEventListener`, never wrapped): `readystatechange` (at readyState 4: `arrive()` for async requests, then sticks `s.op`), `error`/`timeout`/`abort` (set `failed`) and `loadend` (runs `onEnd` once). It also calls `wrapHandlers(xhr)` once (step 4). - `unfake` deletes the properties faked by a previous answer. - - Records `method`, `url`, `async` (false only when the third argument is `false`) and resets per-request state, then calls the native `open`. -2. `wSetHeader` records lower-cased header names. A repeated name overwrites the earlier value; the identity does not see the comma-joined value the browser actually sends. -3. `wSend`: + - Records `method`, `url`, `async` (false only when the third argument is `false`) and resets per-request state (including `req`, `dlv = "none"`, `queue = []`), then calls the native `open`. +3. `wSetHeader` records lower-cased header names. A repeated name overwrites the earlier value; the identity does not see the comma-joined value the browser actually sends. +4. **App completion listeners go through a thin wrapper** (the delivery gate's hook): + - `wAdd`: for `readystatechange`, `progress`, `load`, `loadend` (`COMPLETION`) it registers a wrapper instead of the app's listener (cached per object, listener, type and capture flag, so `wRemove` finds it). Other types pass through. + - `wrapHandlers`: for `onreadystatechange`, `onprogress`, `onload`, `onloadend` it defines an own accessor property on the instance. The setter wraps the app's function and forwards the wrapper to the browser's native setter; the **getter returns the wrapper**, not the app's function (STATUS "Deviations": needed for XHR implementations that call `this.onload(e)` themselves). A handler set before the first `open()` is picked up and wrapped. + - The wrapper calls `gateCall`: for an async XHR at readyState 4 and a completion event, it runs `arrive()`; if the delivery is held, the app's call is queued; otherwise it runs now. +5. `wSend`: - With no state (send before `open`, `open` called before install, or any call after `destroy()`), it calls the native `send`. - `bodyInfo(body)`; a Blob key is never read for XHR, so a Blob body gets `uniqueId()`. - Headers are filtered by the `VOLATILE` regex. - - `parseRequest(...)` with `transport = "xhr"`, then `startOp("xhr", signature, { detail, identity, method, url })`. -4. `onEnd` (on `loadend`): + - `parseRequest(...)` with `transport = "xhr"`, then `startOp("xhr", signature, { detail, identity, method, url })`; stores `op` and `req`. +6. `arrive(xhr, st)` (the first completion event of a response, from the app's wrapper or GenClass's own `readystatechange` listener, whichever runs first; runs once per request): + - Returns without gating when there is no op/req, the op already ended, `failed` is set, status is 0, or status is a failure (≥ 500, 429, 408): failures are handled at `loadend` (step 7). + - Otherwise it **ends the op `ok` with the status now** (at readyState 4, before `loadend`) and sticks it. If not gated, done. + - If gated: for a non-GET/HEAD response with status < 300, `host.noteResponse(...)`; then `dlv = "held"` and `host.deliver({ op, req, status, body }, release)`. `body` is `xhrJson(xhr)`: `response` for `responseType` `json`, `parseJsonBody(responseText)` for `""`/`"text"`, else `undefined`. + - `release` sets `dlv = "open"`; if it came asynchronously, it sticks the op and runs the queued app calls in order (a throw is passed to `global.reportError`, else `console.error`). A release after an `abort()` is ignored. +7. `onEnd` (on `loadend`): + - Returns at once if the op already ended (the `arrive` path ended it). - `failed = "abort"` gives `aborted`. - `timeout`, `error` or status 0 give `error` with code `timeout`/`network`, plus a `failure` trigger. - Status ≥ 500, 429 or 408 gives `error` with the HTTP code, plus a `failure` trigger. - - Anything else is `ok`. + - Anything else is `ok` (synchronous XHRs, which never go through `arrive`). - Failure triggers use the `passiveOnly()` controller with `{ hold: false, priority: 1 }`: detection only, because the app already sees XHR failures directly. -5. Not gated, or synchronous: `doSend()` at once. **Synchronous XHRs raise no request trigger, are never held and get no stall watch.** `doSend()` arms the (detection-only) stall watch for gated async requests, then calls native `send`. If native `send` throws, it clears `onEnd`, ends the op `error` (`code: "network"`, `failure: true`) and rethrows. On this un-held path the app sees the exception exactly as without GenClass. -6. Otherwise `held = true` and `host.trigger({ trigger: "request", … }, ctl, { hold: true, priority: 2 })`: +8. Not gated, or synchronous: `doSend()` at once. **Synchronous XHRs raise no request trigger, are never held, get no stall watch and never reach the delivery gate** (`gateCall` and `arrive` require `async`). `doSend()` arms the (detection-only) stall watch for gated async requests, then calls native `send`. If native `send` throws, it clears `onEnd`, ends the op `error` (`code: "network"`, `failure: true`) and rethrows. On this un-held path the app sees the exception exactly as without GenClass. +9. Otherwise `held = true` and `host.trigger({ trigger: "request", … }, ctl, { hold: true, priority: 2 })`. `ctl.proceeded()` = decided or aborted-while-held; `ctl.stale()` = aborted-while-held. - `passive`: `doSend()`. A throw from native `send` becomes a `custom` event `xhr.send-failed`. - `block`: `fake(xhr, st, 503, "Blocked by GenClass", "", [["x-genclass","blocked"]])`; op ends `blocked`, synthetic. - `serve_cached`: uses only `body` buffers, decoded as UTF-8; headers are the cached ones plus `x-genclass: cached`. - `delay`: same formula as fetch. A throw from native `send` after the delay is swallowed (the op records it). - `coalesce` throws `unsupported action`; `situation/build.ts` only offers it for `transport === "fetch"`. -7. `fake()` defines own-property getters for `readyState` 4, `status`, `statusText`, `response` and (for `responseType` `""`/`"text"` only) `responseText`. `response` follows `responseType`: `json` gives parsed JSON or `null`; `arraybuffer` gives UTF-8 bytes; `blob` gives a `Blob`; `document` gives `null`. It also overrides `getResponseHeader`/`getAllResponseHeaders`, then dispatches `readystatechange`, `load` and `loadend` as plain `Event`s. No progress events are fired and `responseURL` is not faked. The `block` and `serve_cached` callers set `onEnd = undefined`, end the op as synthetic and call `ctx.stick(op)` *before* `fake()`, so the app's load handlers run with the op ambient. -8. `wAbort` while held: it sets `abortedWhileHeld`, ends the op `aborted`, dispatches `abort` and `loadend`, and **never calls native `send`** (a later decision or delay is ignored). When not held, it calls the native `abort`. The held-abort path dispatches plain `Event`s only: no `readystatechange`, and `readyState`/`status` keep their native values (`OPENED`, 0), unlike a real abort of a sent request. -9. XHR responses are never buffered: XHR never populates the GET cache or the coalescing table. XHR `serve_cached` can only replay a body that fetch cached under the same identity. Identities match across transports when method, URL, headers and body match. +10. `fake()` defines own-property getters for `readyState` 4, `status`, `statusText`, `response` and (for `responseType` `""`/`"text"` only) `responseText`. `response` follows `responseType`: `json` gives parsed JSON or `null`; `arraybuffer` gives UTF-8 bytes; `blob` gives a `Blob`; `document` gives `null`. It also overrides `getResponseHeader`/`getAllResponseHeaders`, then dispatches `readystatechange`, `load` and `loadend` as plain `Event`s. No progress events are fired and `responseURL` is not faked. The `block` and `serve_cached` callers set `onEnd = undefined`, end the op as synthetic and call `ctx.stick(op)` *before* `fake()`, so the app's load handlers run with the op ambient. The faked events pass through the app's wrappers, but `arrive` returns at once (the op has ended), so faked answers never reach the delivery gate. +11. `wAbort`: + - During a **delivery hold** (`dlv === "held"`): drops the queued app calls, emits `custom` `xhr.aborted-while-held`, calls native `abort`, then dispatches plain `abort` and `loadend` events. The op keeps its `ok` end (it ended in `arrive`). + - During a **request hold** (`held`): sets `abortedWhileHeld`, ends the op `aborted`, dispatches `abort` and `loadend`, and **never calls native `send`** (a later decision or delay is ignored). This path dispatches plain `Event`s only: no `readystatechange`, and `readyState`/`status` keep their native values (`OPENED`, 0), unlike a real abort of a sent request. + - Otherwise it calls the native `abort`. +12. XHR responses are never buffered: XHR never populates the GET cache or the coalescing table. XHR `serve_cached` can only replay a body that fetch cached under the same identity. Identities match across transports when method, URL, headers and body match. +13. Uninstall restores `open`/`send`/`abort`/`setRequestHeader` if they are still GenClass's. `addEventListener`/`removeEventListener` are restored only if no app listener was ever wrapped (`wrappedAny`); otherwise they stay installed as pass-throughs (`disabled` makes `wAdd` native), so `removeEventListener` still finds the wrappers. Per-instance `on*` accessors stay on objects that were opened while installed; their wrappers call `gateCall`, which checks `disabled` and then just calls the app's handler. ### 7. DOM user actions (`packages/runtime/src/observe/dom-user.ts` -> `installDomUser`) -1. Listeners are added on `global` if it has `addEventListener` (i.e. `window`), else on `document`, with `{ capture: true, passive: true }`, for `click`, `input`, `change`, `submit` and `keydown`. -2. Guard: an event is skipped when `ignoredEvent(e) || programmatic(e)`. +1. Returns `null` without a `global.document` that has `addEventListener`. Listeners are added on `global` if it has `addEventListener` (i.e. `window`), else on `document`, with `{ capture: true, passive: true }`, for `click`, `input`, `change`, `submit` and `keydown`. An extra `adopt` listener runs on `focusin`, `pointerdown`, `mousedown`, `click`, `input`, `keydown` (`ADOPT_ON`). +2. **Shadow roots.** `change` and `submit` are not composed, so they never reach `window` from inside a shadow root. `adopt` walks `e.composedPath()`; for each open shadow root not seen before it adds capture listeners for `change` and `submit` on that root (these skip `e.composed` events, which the window listener handles) and keeps a `WeakRef` so uninstall can remove them. A root is adopted only after a composed event came from inside it. +3. Guard: an event is skipped when `stopped || ignoredEvent(e) || programmatic(e)`. - `ignoredEvent`: `composedPath()[0]` (when `composedPath` exists) or `e.target` is inside an element with `data-genclass-ignore`; both are checked. The walk goes up `parentNode` and crosses shadow roots through `host`, for at most 1000 steps. - - `programmatic`: true if `runningKind()` is non-null and not `"user"`, i.e. app code running inside `ctx.run` of a task, GenClass, fetch or other op dispatched the event. Otherwise trusted events (`isTrusted !== false`) are kept. Untrusted events are dropped when the ambient kind (`peek`, where a `LazyOp` counts as `"timer"`) is non-null and not `"user"`. **Untrusted events with no ambient op, or with a user ambient op, are kept** (test drivers, `el.click()` inside a user handler). -3. Handlers: + - `programmatic` (batch 4): + 1. `runningKind()` is non-null and not `"user"` -> skipped (app code inside `ctx.run` of a task, GenClass, fetch or other op dispatched it), trusted or not. + 2. A trusted event (`isTrusted !== false`) -> kept. + 3. An untrusted event -> **skipped unless `observe.untrustedEvents` is true**; with the flag on it is skipped only when the ambient kind (`peek`, where a `LazyOp` counts as `"timer"`) is non-null and not `"user"`. + The realapps harness (`realapps/src/harness/trajectory.ts` -> `OBSERVE`) passes `untrustedEvents: true`; the sim never installs the DOM observer (it calls `runtime.user` directly). +4. The element described is `originOf(e)`: `composedPath()[0]` (the real target inside open shadow roots, not the retargeted host), else `e.target`; a text node maps to its parent element. +5. Handlers: | Event | Records | Value | |---|---|---| -| `click` | `{ kind: "click", target: describeElement(interactive(e.target)) }` | — | +| `click` | `{ kind: "click", target: describeElement(interactive(origin)), clicks? }`; `clicks` = `MouseEvent.detail` when it is a number > 0 | — | | `input` | text-like targets only: `textarea`, contenteditable, or `input` whose type is one of `text search email number tel url password date time datetime-local month week ""` | `""` if `isSensitiveField`, else `textContent` (contenteditable) or `value`; plus `sensitive` | | `change` | `select` (selected option text, ≤ 40 chars), checkbox/radio (`checked`/`unchecked`), range/color/file (`file` for file inputs) | sensitive -> `""` | | `submit` | `form "<aria-label \| name \| id \| first h1/h2/h3/legend text>"`, or `form` | — | | `keydown` | only `Enter` and `Escape`: `{ kind: "key", key, target }`. Auto-repeat is not filtered (`e.repeat` is not checked), so a held key records one user op per repeat | — | - `interactive(t)` uses the parent element for text nodes, then takes the closest element matching `button,a,input,select,textarea,summary,label,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=option],[role=switch],[contenteditable=''],[contenteditable=true]`, falling back to the element itself. -4. `RuntimeImpl.user(action, handler?)`: + `interactive(t)` takes the closest element matching `button,a,input,select,textarea,summary,label,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=option],[role=switch],[contenteditable=''],[contenteditable=true]`, crossing shadow boundaries through the host (`closestDeep`, ≤ 32 hops), falling back to the element itself. +6. `RuntimeImpl.user(action, handler?)`: - `kind` is `action.kind ?? action.action ?? "action"`. - - The value becomes `[redacted]` when `sensitive` is set or `redact(target, value) !== value`. - - `detail = JSON.stringify(truncate(value, 40))`. Only `detail` is truncated: `op.meta.action.value` keeps the whole (possibly redacted) value. + - The value becomes `[redacted]` when `sensitive` is set or `redact(target, value) !== value`. With the default redactor a free-text target such as `input "Card number"` is judged word by word (`util.ts` -> `isSensitivePath` falls back to `isSensitiveName` for non-path strings). + - `detail = JSON.stringify(truncate(value, 40))`. Only `detail` is truncated: `op.meta.action.value` keeps the whole (possibly redacted) value. `clicks` stays in `op.meta.action` only; it is not in the `user` event's `data`. - It creates an instant root op, `startOp("user", name, { cause: null, instant: true, detail, meta: { action } })`. - **Typing bursts:** a `type` action is merged into the previous `user` event when the target is the same, the gap is ≤ `TYPING_BURST_MS = 1000` ms since the last keystroke, and that event is still the latest user event. The merge updates `count`, `value`, `lastT` and `e.op` in place and calls `events.touch(e)`. Every keystroke still creates its own user op. - It then calls `ctx.stickUser(op)`, and runs `ctx.run(op, handler)` if a handler was given. The DOM observer passes none. Its capture listener on `window` runs before the app's handlers (except `window` capture listeners registered earlier), so they run with the user op ambient and recorded as the task's user op (`taskUser`). -5. `describeElement(el)` returns `'role "name"'`, or a bare role, or `page` for `null`. +7. `describeElement(el)` returns `'role "name"'`, or a bare role, or `page` for `null`. Ids and `label[for]` resolve in the element's own tree (`scopeOf`: its shadow root, else its document). - Name, first non-empty of: 1. `aria-label`; - 2. `aria-labelledby` texts; - 3. fields only (input/select/textarea): `labels[0]`, then `label[for=id]`, then the closest `label`; - 4. non-fields only: `innerText ?? textContent`; + 2. `aria-labelledby` texts (looked up in the element's own tree; rendered text, without nested form controls); + 3. fields only (input/select/textarea): `labels[0]`, then `label[for=id]`, then the closest `label`. A label's text excludes the options, values and captions of controls nested in it (`labelText`), so `<label>Stops <select>…</select></label>` gives `select "Stops"`; + 4. non-fields only: own text. When the element is in or hosts a shadow root, is a `label`, or contains `select,option,textarea,input,button,slot`, it is the flat-tree text (`flatText`: follows open shadow roots and slot assignments, skips `script/style/template/noscript` and nested controls, bounded to 400 nodes / 240 chars); otherwise `innerText ?? textContent`; 5. `placeholder`; 6. `title`; 7. `name`; 8. the `value` of an input of type button/submit/reset (never a typed value); - 9. `id`. + 9. for an element inside a shadow root: the host's `aria-label`, `label`, `title` or `placeholder` attribute (`<x-field label="Email">` names its inner `input`); + 10. `id`. - Each name has whitespace collapsed and is truncated to 40 chars. - Role: the `role` attribute; else `a` -> `link`; input button/submit/reset/image -> `button`; checkbox/radio/range/file/color -> that type; any other input -> `input`; else the tag name. - - Examples from `test/dom.test.ts`: `button "Place order"`, `input "Search"`, `link "Home"`, `checkbox "remember"`, `select "Size"`. -6. `isSensitiveField` is true for any of: `type=password`; `autocomplete` whose last token matches `/^(cc-|one-time-code$|current-password$|new-password$)/i`; or `name`/`id`/`aria-label`/`placeholder`/label text that `isSensitiveName` flags (word-level secret names in `packages/runtime/src/util.ts`). + - Examples from `test/dom.test.ts`: `button "Place order"`, `input "Search"`, `link "Home"`, `checkbox "remember"`, `select "Size"`; batch 5: `select "Stops"`, `checkbox "Remember me"`, `textarea "Note"`, `li "Sofia · Size exchange"` (inside a shadow root), `input "Email"` (named by its host), `button "Save draft"` (slotted text). +8. `isSensitiveField` is true for any of: `type=password`; `autocomplete` whose last token matches `/^(cc-|one-time-code$|current-password$|new-password$)/i`; or `name`/`id`/`aria-label`/`placeholder`/label text, or (inside a shadow root) the host's `label`/`name`/`aria-label`, that `isSensitiveName` flags (word-level secret names in `packages/runtime/src/util.ts`; `isSensitiveName` now caches up to 4,096 names). +9. Uninstall sets `stopped`, removes the window/document listeners and the `change`/`submit` listeners of every adopted shadow root still alive. ### 8. Timers and lazy timer ops (`packages/runtime/src/observe/timers.ts`, `packages/runtime/src/trace/context.ts`) @@ -424,8 +466,8 @@ The app's promise always settles. Every action that throws or rejects makes `Run | Mechanism | Sets `cur` to | Duration | Call sites | |---|---|---|---| -| `run(op, fn)` | `op` (also `running`) | Synchronously during `fn`; restores the previous `cur` and `running` in `finally` | `RuntimeImpl.user` (with handler), `RuntimeImpl.op` (body), `runAsGenClass`, plugin `runInOp`, the hub applying a held write (`ctx.run(m.cause, write)`) | -| `stick(op)` | `op` or a `LazyOp` | Until `clock.afterTask` runs. It clears `cur` only if `cur` is still that op (or the op it materialised into) | fetch `answer()` and body methods; XHR readyState 4 and fake answers; WS message; timer callbacks; `rt.op` settle; `stickUser` | +| `run(op, fn)` | `op` (also `running`) | Synchronously during `fn`; restores the previous `cur` and `running` in `finally` | `RuntimeImpl.user` (with handler), `RuntimeImpl.op` (body), `runAsGenClass`, plugin `runInOp`, and the hub applying **every** write (`packages/runtime/src/state/hub.ts` -> `StoreHub.commit`: `ctx.run(m.cause, write)`, immediate and held writes alike) | +| `stick(op)` | `op` or a `LazyOp` | Until `clock.afterTask` runs. It clears `cur` only if `cur` is still that op (or the op it materialised into) | fetch `answer()` (also when a held response is released) and body methods; XHR `arrive`, readyState 4, delivery release and fake answers; WebSocket/EventSource message dispatch (`MessageGate`: at once, or on the re-dispatched clone); timer callbacks; `rt.op` settle; `stickUser` | | `stickUser(op)` | `op`, plus `taskUser = op` | Until afterTask | `RuntimeImpl.user` | | `clear()` | `null` | — | `destroy()` | @@ -437,21 +479,40 @@ The app's promise always settles. Every action that throws or rejects makes `Run ### 10. WebSocket (`packages/runtime/src/observe/websocket.ts` -> `installWebSocket`) 1. `global.WebSocket = class GenClassWebSocket extends Native`. Instances made after destroy (through a kept reference) skip all tracing. -2. The path is `normalizePath(parseUrl(url, baseHref).where)`. An absolute `ws:`/`wss:` URL never has the same origin as an `http(s)` page (the scheme differs), so `where` is `host + pathname` and the op name includes the host, e.g. `WS message app.example.test/ws/board` (seen in `sim/samples`). Two exceptions follow from `parseUrl`: with no `global.location` (`baseHref()` undefined) every URL counts as same-origin, and a relative URL resolves against the page's `http(s)` origin; in both cases `where` is the bare `pathname` (e.g. `WS /ws`). -3. The connect op is `WS <path>` with detail `connect` and the ambient op as cause. It ends `ok` on `open`, `error` with `{ code: "network", failure: true }` on `error`, or `error` with `{ code: CloseEvent.code }` on `close`. Only the first of these counts. Errors and closes **after** `open` are not recorded at all (the connect op has already ended; there is no disconnect op or event). If the native constructor throws (bad URL), the exception reaches the app and nothing is recorded. -4. Each `message`: - - creates an instant **root** op `WS message <path>` (`cause: null`) whose detail is the summary; - - pushes a `custom` event `ws.message` `{ path, summary }`; - - calls `ctx.stick(m)`. The listener is registered in the constructor, before any app listener or `onmessage`, so the app's handlers run with the message op ambient. -5. `send` is replaced per instance (own property). It creates an instant op `WS send <path>` (ambient cause) and a `custom` event `ws.send`, then calls the original. -6. Summary: - - strings > 16 KB or blank: `<len> chars`; +2. The path is `normalizePath(parseUrl(url, baseHref).where)`. Since batch 4 (fcd1e68), `parseUrl` treats a `ws:`/`wss:` URL on the **page's own host** (`URL.host`, so the port must match too) as same-origin, so `where` is the bare pathname (`WS message /ws/board`). A `ws(s):` URL on another host keeps `host + pathname` (`WS message push.other.test/ws`). With no `global.location` (`baseHref()` undefined) every URL counts as same-origin, and a relative URL resolves against the page's origin; in both cases `where` is the bare pathname. +3. The connect op is `WS <path>` with detail `connect` and the ambient op as cause. GenClass's own listeners are added with the native `addEventListener` (`raw`), before the message gate and before any app listener: + - `open`: ends the connect op `ok`, then `channel("up", "websocket", path)`; + - `error`: ends it `error` with `{ code: "network", failure: true }` (if still open), then `channel("down", …, "network")`; + - `close`: ends it `error` with `{ code: CloseEvent.code }` (if still open); a close with code ≠ 1000 also calls `channel("down", …, code)`. + Only the first end counts. `channel("down")` is reported once per socket. Errors and closes after `open` create no op and no event, but now reach `onChannel`. If the native constructor throws (bad URL), the exception reaches the app and nothing is recorded. +4. `new MessageGate(this, h, "websocket", path, raw)`, then `gate.ensure("message")`, `ensure("close")`, `ensure("error")` (see §10b). +5. `send` is replaced per instance (own property). It creates an instant op `WS send <path>` (ambient cause) and a `custom` event `ws.send` `{ path, summary }`, then calls the original. Sends are never gated. +6. Summary (`messages.ts` -> `messageSummary`, shared with EventSource): + - strings > 16 KB (`PARSE_MAX`) or blank: `<len> chars`; - JSON (starts with `{` or `[`): `describe(parsed, "message", redact, 60)`; - other strings: `JSON.stringify(truncate(t, 40))`; - - Blob/ArrayBuffer: `<n> bytes`; + - Blob (anything with a numeric `size`)/ArrayBuffer: `<n> bytes`; - else `binary`. WS ops are neither baselined nor identity-registered. +### 10a. EventSource (`packages/runtime/src/observe/eventsource.ts` -> `installEventSource`) + +1. New in batch 4. Returns `null` when `global.EventSource` is not a function. `global.EventSource = class GenClassEventSource extends Native`; uninstall sets `disabled` and restores the global if still ours. Instances made after destroy skip tracing. +2. The connect op is `SSE <path>` (detail `connect`, ambient cause, kind `ws`). `open` ends it `ok` and reports `channel("up", "eventsource", path)`; every `error` ends it `error` (`network`, `failure`) if still open and reports `channel("down", …, "network")` (an EventSource reconnects by itself, so a later `open` reports `up` again). There is no `send`. +3. The gate intercepts `message` and `error` at construction. **Custom event types** (`event: update` in the stream) are intercepted when the app first calls `addEventListener(type, …)` on the instance (the override calls `gate.ensure(type)` before registering the app's listener), for any type except `open`/`error`. Op names: `SSE message <path>` for `message`, `SSE <type> <path>` for custom types; the `custom` event is `sse.message` with `{ path, summary, type }`. +4. `ObserverName` gained `eventsource`; it defaults to on. `ALL_OFF` in `packages/runtime/src/index.ts` includes it; `test/helpers.ts` -> `setup`, `sim/src/run/rt.ts` and `realapps/src/harness/trajectory.ts` -> `OBSERVE` do not list it, so it defaults to on everywhere: it installs in realapps' real browsers, and installs nothing on the test and sim virtual globals unless they provide an `EventSource` (`delivery.test.ts` passes a fake one). + +### 10b. Message gate (`packages/runtime/src/observe/messages.ts` -> `MessageGate`) + +1. `ensure(type)` registers the gate's listener once per type through `raw` (native `addEventListener`), so it runs before app listeners added later and before `on*` handlers set later. `message` and custom types get `intercept`; `close` and `error` get `orderOnly`. +2. `intercept(e)` for a fresh event: + - creates the message op **synchronously inside the dispatch**: instant, `cause: null` (a root), detail = summary, name per channel (§10/§10a). `hooks.opCreated` therefore fires before any app listener. It pushes the `ws.message`/`sse.message` `custom` event. A throw here leaves the event alone (tracing never breaks a channel); + - if messages are already queued, it stops the event (`stopImmediatePropagation`) and queues it behind them (order kept); + - else it asks the delivery gate (`deliverMessage`, `queuedAhead: 0`, `body` = `parseJsonBody(data)`). Released synchronously: it sticks the op and lets the event continue to the app's listeners. Not released yet: it stops the event and queues it. +3. `orderOnly(e)` (close/error): if anything is queued, stops the event and queues it (ready) so it keeps its place; otherwise does nothing. +4. `pump()` (on each asynchronous release) dispatches ready items in order. Each is a **clone** (`cloneEvent`: a new `MessageEvent` with `data`, `origin`, `lastEventId`, `ports`; a new `CloseEvent` with `code`, `reason`, `wasClean`; else a plain `Event`), built with the module's `globalThis` constructors. The clone is remembered (`mine`), so `intercept` only sticks its op and lets it through. When the next queued message reaches the head it gets its own decision. `queuedAhead` is computed as `first ? 0 : queue.indexOf(item)`, but a decision is only ever asked for a fresh message on an empty queue or for the queue's head, so in practice it is always 0. +5. Consequences for apps: a held message reaches the app as a different event object with `isTrusted === false` and no `source`; listeners on the socket see it in the original order relative to other messages and to `close`/`error`. Because the gate registers `message`/`close`/`error` in the constructor (and an EventSource custom type just before the app's first listener for it), every app listener and `on*` handler of the instance runs after it. GenClass's own `close`/`error` bookkeeping listeners run before the gate, so a close queued behind a held message is still recorded (and reported to `onChannel`) at once; only the app's view of it waits. + ### 11. errors, nav, storage, perf - **errors** (`installErrors`): @@ -466,7 +527,7 @@ The app's promise always settles. Every action that throws or rejects makes `Run ### 12. Signature normalisation (`packages/runtime/src/util.ts`) 1. `parseUrl(raw, base)` evaluates `new URL(raw, base ?? "http://localhost/")`. - - `sameOrigin = !base || base.origin === url.origin`. + - `sameOrigin = !base || base.origin === url.origin || (url is ws:/wss: && url.host === base.host)` (the WebSocket clause was added in batch 4, fcd1e68). - `where = sameOrigin ? pathname : host + pathname`. Query and fragment never enter the signature; the query goes to `detail`. - If parsing throws (including an invalid `base`), the fallback is `{ href: raw, where: raw before "?", search: raw from "?" (or ""), sameOrigin: true }`. - `base` comes from `NetHost.baseHref()` = `global.location.href` when it is a string, else `undefined`. `WsHost.baseHref()` returns `global.location?.href` without the string check. @@ -509,7 +570,8 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store | Name | Type | Default / value | Defined in | Effect | |---|---|---|---|---| -| `observe` (`ObserverName` = `fetch xhr user errors nav storage perf websocket timers`) | `Partial<Record<…, boolean>>` | all `true`; `timers` = `global.document` is a non-null object | `packages/runtime/src/runtime.ts` -> `installObservers` | Which observers install | +| `observe` (`ObserverName` = `fetch xhr user errors nav storage perf websocket eventsource timers`) | `Partial<Record<ObserverName \| "untrustedEvents", boolean>>` | all `true`; `timers` = `global.document` is a non-null object; `untrustedEvents` = `false` | `packages/runtime/src/runtime.ts` -> `installObservers` | Which observers install; whether synthetic DOM events are user actions | +| `mode` | `"observe" \| "guard" \| "heal"` | `"observe"` (commit f3636b2; was `"guard"`). `test/helpers.ts` -> `setup` still defaults to `"guard"` | `packages/runtime/src/runtime.ts` constructor | `observe` permits no non-passive action, so no gate in this doc ever holds (except the delivery gate's body read, see Drift) | | `historySize` | number | 500 (buffer min 16) | `packages/runtime/src/runtime.ts` constructor, `packages/runtime/src/trace/events.ts` -> `EventLog` | Ring-buffer size. The timeline reads the last 96 events (`situation/build.ts` -> `timelineLines`) | | `IDENTITY_BODY_MAX` | bytes | 65,536 | `packages/runtime/src/observe/fetch.ts` | Max Blob/ArrayBuffer/view/Request body hashed for identity | | `STRING_BODY_MAX` | chars | 1,048,576 (strings ≤ 256 chars are used verbatim) | `packages/runtime/src/observe/fetch.ts` | Longer string bodies get a unique identity | @@ -535,17 +597,26 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store | `TYPING_BURST_MS` | ms | 1,000 | `packages/runtime/src/runtime.ts` | Typing-burst merge window (from the last keystroke) | | `STALL_MIN_MS` | ms | 500 | `packages/runtime/src/runtime.ts` | Stall at `max(4×median, 2×p95, 500)` | | `MIN_LAT_SAMPLES` | count | 5 | `packages/runtime/src/learn/baselines.ts` | No stall watch before 5 latency samples | -| `LONG_RUNNING_MS` | ms | 10,000 | `packages/runtime/src/runtime.ts` | In-flight ops younger than this block settled points (`busy`) | +| `LONG_RUNNING_MS` | ms | 10,000 | `packages/runtime/src/runtime.ts` | In-flight ops younger than this block settled points (`busy`); also caps how long a delivery `defer` (`waitOps`) or held-write `defer` (`waitRelated`) waits | | `identicalMap` | count / ms | ≤ 12 per identity, 10 s, ≤ 512 identities | `packages/runtime/src/runtime.ts` -> `registerIdentity` | Identical-request facts | | hold budget | ms | `"auto"` = clamp(1.5 × median of the last 20 model latencies (else the model's `warmupMs`), `HOLD_MIN_MS` = 150, `HOLD_MAX_MS` = 800); `HOLD_FALLBACK_MS` = 300 when neither is known; a number `policy.holdBudgetMs` is used as is (≥ 0) | `packages/runtime/src/decide/policy.ts` -> `holdBudget` | How long a held request or failure waits | -| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `packages/runtime/src/runtime.ts` | Deadline for decisions on non-held triggers (stalls, XHR failures, failures in guard mode, errors) | +| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `packages/runtime/src/runtime.ts` | Deadline for decisions on non-held triggers (stalls, XHR failures, failures in guard mode, errors, anything in observe mode) | +| `BODY_WAIT_MS` | ms | 100 | `packages/runtime/src/runtime.ts` | The delivery gate waits at most this long for the JSON body before deciding salience without it | +| `DISCARD_MARK_MS` | ms | 10,000 | `packages/runtime/src/runtime.ts` | How long a delivery `discard` keeps dropping the chain's writes over newer data | +| `createsBuf` | count / ms | ≤ 16 entries, 30 s | `packages/runtime/src/runtime.ts` -> `noteResponse` | Read-your-writes memory of ids returned by creates (POST or 201) | +| delivery `defer` limit | count | 2 | `packages/runtime/src/situation/build.ts` (`defers < 2`) | `defer` is offered at most twice per delivery | +| `COMPLETION` / `HANDLERS` | sets | `readystatechange progress load loadend` / `onreadystatechange onprogress onload onloadend` | `packages/runtime/src/observe/xhr.ts` | XHR app listeners routed through the delivery gate | | `PROFILED` | `Set<OpKind>` | `fetch xhr user task ws` | `packages/runtime/src/runtime.ts` | Op kinds whose causal chains feed transition profiles (`timer` and `genclass` never) | | `errorsRecent` | count / ms | ≤ 64 entries; facts window 10,000 | `packages/runtime/src/runtime.ts` -> `reportError`, `makeEnv.recentErrors` | Recent-error facts | | error key | chars | `Name:` + message with digit runs -> `n`, message part ≤ 120 | `packages/runtime/src/runtime.ts` -> `normalizeError` | Groups repeated errors | | `uniq` counter | `uniq:N` | per runtime, from 1 | `packages/runtime/src/runtime.ts` -> `netHost().uniqueId` | Identity that matches nothing | | timer label | string | `timer ${ms<1000 ? round(ms)+"ms" : secs(ms)}`, `interval ${secs(ms)}` (`secs`: 2 decimals < 10 s, 1 decimal < 1000 s, else integer) | `packages/runtime/src/observe/timers.ts`, `util.ts` -> `secs` | Timer op names (situation text) | | `policy.holdUserWrites` | boolean | `false` | `packages/runtime/src/decide/policy.ts` | When false, user-sync writes are never held | -| WS JSON summary cap | chars | 16,384 | `packages/runtime/src/observe/websocket.ts` -> `summary` | Larger messages are summarised as `<len> chars` | +| `PARSE_MAX` (message JSON summary cap) | chars | 16,384 | `packages/runtime/src/observe/messages.ts` -> `messageSummary` | Larger WebSocket/EventSource messages (and sends) are summarised as `<len> chars` | +| `ADOPT_ON` | event types | `focusin pointerdown mousedown click input keydown` | `packages/runtime/src/observe/dom-user.ts` | Composed events whose path adopts open shadow roots for `change`/`submit` listeners | +| `flatText` budget | nodes / chars | 400 / 240 | `packages/runtime/src/observe/dom-user.ts` | Bound on flat-tree text for element names | +| `closestDeep` hops | count | 32 | `packages/runtime/src/observe/dom-user.ts` | Shadow-host hops when finding the interactive element | +| `isSensitiveName` cache | entries | 4,096 (cleared when exceeded) | `packages/runtime/src/util.ts` | Memoises secret-name checks | | element name length | chars | 40 | `dom-user.ts` -> `clean` | `describeElement` names | | user value in `detail` | chars | 40 | `runtime.ts` -> `user` | `detail` truncation | | nav route | chars | 80 | `nav.ts` | Route truncation | @@ -557,19 +628,20 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store **Safety. The app must never break.** - Every wrapper has to behave exactly like the native API when GenClass fails. - Parsing errors fall back to `nativeFetch`. - - Tracing code inside wrapped methods (nav `pushState`/`replaceState`, storage methods, WebSocket `message` listener and `send`, the WebSocket connect `startOp`) is wrapped in try/catch. The DOM-user, XHR-state and error listeners are **not**; they are separate listeners, so a throw there is reported as an uncaught error rather than stopping the app's own handlers. + - Tracing code inside wrapped methods (nav `pushState`/`replaceState`, storage methods, the message gate's op creation, WebSocket `send`, `channel` reports, the WebSocket/EventSource connect `startOp`) is wrapped in try/catch. A listener that throws during a gate re-dispatch (`MessageGate.pump`) is swallowed there (the platform reports it); a queued XHR completion call that throws goes to `global.reportError`. The DOM-user, XHR-state and error listeners are **not**; they are separate listeners, so a throw there is reported as an uncaught error rather than stopping the app's own handlers. - Installers that throw are skipped (`tryAdd`). - - The app's fetch promise always settles: every controller path ends in `answer`, `sendNow` or the original rejection. + - The app's fetch promise always settles: every controller path ends in `answer`, `sendNow` or the original rejection. Every delivery-gate path ends in exactly one `release` (passive, `discard`, a `defer` that re-runs the gate, the hold budget, or `destroy()`). + - **Holding is only latency.** The delivery gate never alters a response or message; it only decides when the app sees it, and keeps a channel's order (messages, then `close`/`error`). Never reorder or drop a message in the gate. - Keep these properties when you edit. **Pass-through after destroy.** -- Keep the `disabled` flag check in every wrapper (fetch, XHR, timers and the WebSocket constructor check it first; nav and storage call the native method first and then check it), and restore a global only if it still holds GenClass's wrapper. +- Keep the `disabled` flag check in every wrapper (fetch, XHR, timers and the WebSocket/EventSource constructors check it first; nav and storage call the native method first and then check it; the DOM observer checks `stopped`), and restore a global only if it still holds GenClass's wrapper. - `test/review-fetch.test.ts` checks that a fetch through an APM-style wrapper installed on top creates no ops and no cache entries after `destroy()`. **After destroy: what still runs** (from code reading; no test covers these). `RuntimeImpl.startOp`, `endOp`, `events.push` and `Context` do not check `destroyed`, so per-object hooks created earlier keep working: -- A `GenClassWebSocket` constructed before `destroy()` keeps its listeners and its own-property `send`: messages and sends still create `ws` ops and `custom` events, and messages still `stick`. Only sockets constructed afterwards (via a kept class reference) skip tracing. +- A `GenClassWebSocket` or `GenClassEventSource` constructed before `destroy()` keeps its listeners, its `MessageGate` and (WebSocket) its own-property `send`: messages and sends still create `ws` ops and `custom` events, and messages still `stick`. The gate still asks `deliverMessage`, but `runDelivery` releases at once after destroy, so nothing is held. Only instances constructed afterwards (via a kept class reference) skip tracing. - A timer callback scheduled before `destroy()` still calls `ctx.stick(lazyTimer(...))` when it fires; anything that then calls `ctx.op()` creates a `timer` op. -- An XHR object keeps its once-per-object listeners. After `destroy()` `open`/`send` are native again, so `st.op` is never refreshed, but a later readyState-4 still sticks that object's last op. +- An XHR object keeps its once-per-object listeners and its `on*` accessor properties. After `destroy()` `open`/`send` are native again, so `st.op` is never refreshed, but a later readyState-4 still sticks that object's last op. `XMLHttpRequest.prototype.addEventListener/removeEventListener` stay patched (as pass-throughs) if any app listener was ever wrapped. - Fetches already inside `runRequest` finish normally (held ones are released by `queue.dispose()`, see "Install, route and uninstall" step 5). New triggers from these objects run passive at once (`consultable()` is false). **Op registry.** @@ -588,8 +660,14 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store **Determinism and sim parity.** - Observers must use `host.clock`. No `Date.now`, `Math.random` or global timers. - Op ids and `uniq:N` counters are sequential, so identical inputs give byte-identical situations (`test/situation.test.ts` -> "determinism"). -- The sim runs the real `fetch`, `timers` and `websocket` observers on a virtual global (`sim/src/run/rt.ts` -> `createOptions`). It drives user actions through `runtime.user(act, handler)` (`sim/src/run/runner.ts`), with targets written in the same `role "name"` format that `describeElement` produces. -- Op names, details, event names, timer labels, signature normalisation and causal links all appear in situation text. Changing any of them changes training data. The format is frozen at tag `situation-v1`, and runtime `src` is unchanged since that tag. Coordinate with SIM and TRAIN (see [../model-io-contract.md](../model-io-contract.md)). +- The sim runs the real `fetch`, `timers` and `websocket` observers on a virtual global (`sim/src/run/rt.ts` -> `createOptions`; its map also sets `storage: true`, but that installs nothing because the virtual global from `sim/src/run/runner.ts` has a `localStorage` object and no `Storage` constructor; `eventsource` is unlisted and finds no `EventSource`). It drives user actions through `runtime.user(act, handler)` (`sim/src/run/runner.ts`), with targets written in the same `role "name"` format that `describeElement` produces. +- The realapps harness (`realapps/src/harness/trajectory.ts` -> `OBSERVE`) runs the real runtime in Playwright browsers with `fetch xhr user errors nav storage websocket timers` on, `eventsource` on by default (unlisted), `perf` off and `untrustedEvents: true` (see [../realapps.md](../realapps.md)). Its rows are training data too, so DOM-observer and `describeElement` output is now load-bearing for REAL as well as SIM. +- Op names, details, event names, timer labels, signature normalisation and causal links all appear in situation text. Changing any of them changes training data. The format is frozen at tag `situation-v2` (6e5e86e). Since that tag, runtime `src` changed only in f3636b2 (default mode `observe`: `runtime.ts`, `types.ts` JSDoc, devtools labels), which does not touch situation text. Coordinate with SIM, REAL and TRAIN (see [../model-io-contract.md](../model-io-contract.md)); HANDOFF.md says the training format is frozen at `situation-v2`. + +**DOM observer and test drivers.** +- Synthetic events (`isTrusted === false`) are dropped unless `observe.untrustedEvents: true`. In a real browser, script-dispatched events (`dispatchEvent`, `el.click()`) are untrusted, so in-page drivers must pass the flag (the realapps harness does). **happy-dom (the unit tests' DOM, v20) does not implement `isTrusted`**: it is `undefined`, which the filter treats as trusted, so `test/dom.test.ts` and `test/review-dom.test.ts` record dispatched events without the flag. The one test that checks the filter (`dom.test.ts` -> "synthetic (isTrusted false) events are user actions only with observe.untrustedEvents (test harnesses)") forces `isTrusted: false` with `Object.defineProperty`. `rt.user(...)` is unaffected. +- Events dispatched while app code of a non-user op runs (`ctx.running`) are dropped even when trusted. +- `change`/`submit` inside a shadow root are seen only after a composed event (`focusin`, `pointerdown`, `click`, …) came from that root; a programmatic `change` dispatched into a never-touched shadow root is missed. **No request trigger at all.** - `keepalive` fetches are sent synchronously inside `fetch()`, so they survive unload (`test/review-fetch.test.ts` -> keepalive). @@ -620,19 +698,25 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store **Cost.** - Every request with a non-empty identity has a clone of its response buffered: up to 256 KB and up to 1 s of streaming. - Each keystroke creates a user op, even though typing bursts share one event. -- In-flight ops (a connecting WebSocket, a long poll) delay settled points for up to 10 s each. +- In-flight ops (a connecting WebSocket or EventSource, a long poll) delay settled points for up to 10 s each. +- The delivery gate is cheap when nothing conflicts (synchronous release, no body read). With a conflict it parses the response/message JSON (fetch: from the buffered clone; XHR: `responseText`/`response`; messages: `data`). +- Every XHR completion listener and `on*` handler runs through a wrapper; every WebSocket/EventSource message gets an op and costs one ring-buffer event (the `custom` one; instant `ws` ops push no `op.start`). A chatty socket can therefore push older events out of the 500-event buffer. **XHR.** - Faked properties are own properties, and `unfake()` must remove them on the next `open()`. Otherwise a reused XHR shows the stale 503 (`test/review-xhr.test.ts`). - `abort()` while held must not call native `send`. -- An app `onreadystatechange` assigned *before* the first `open()` runs before GenClass's readyState-4 listener, so it does not see the XHR op ambient. Later listeners (`onload`, `loadend`) do. (unverified: follows from listener registration order; no test) +- An app `onreadystatechange` (or `addEventListener("readystatechange")`) registered *before* the first `open()` runs before GenClass's own readyState-4 listener. Since batch 4 it goes through the wrapper, whose `arrive()` ends and sticks the op for successful responses, so it sees the op ambient and is held with the others (`test/delivery.test.ts` -> "a stale response is held before any app completion listener runs…"). For a **failed** response (`arrive` returns early) such an early listener still runs before the op is stuck (unverified: from code reading; no test). +- XHR success ops now end at readyState 4 (`arrive`), not at `loadend`; failures, aborts and synchronous XHRs still end at `loadend`. +- The `on*` getters return GenClass's wrapper, not the app's function: `xhr.onload === myFn` is false while the observer is installed. +- A delivery hold queues the app's completion calls; `abort()` during it drops them and fires plain `abort`/`loadend`. Do not let a held completion run after an abort. - `states` is a module-level `WeakMap` shared by every runtime created from the same bundle. **Context.** - `stick` is last-writer-wins. - Context does not cross un-instrumented `await`s. - The afterTask clear runs in a posted task. A non-instrumented callback that runs before that task could see a stale ambient op. (unverified: depends on the browser's task ordering; no test) -- The hub applies held writes inside `ctx.run(m.cause, …)`. Subscribers therefore run with the write's cause as the *running* op, and the DOM observer treats events they dispatch as programmatic. +- The hub applies **every** write inside `ctx.run(m.cause, …)` (`StoreHub.commit`; immediate writes as well as writes held with `policy.holdWrites: true`). Store subscribers (React re-renders, redux listeners) therefore run synchronously with the write's cause as the *running* op, and the DOM observer drops events they dispatch as programmatic unless that cause is a `user` op or `null`. +- A WebSocket/EventSource message op is a root and is ambient while the app's handlers run, also when the message was held and re-dispatched later. **Signatures.** - With no `global.location` (headless runtimes without one), every URL counts as same-origin, so cross-origin hosts drop out of signatures. @@ -640,7 +724,8 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store - A `data:` URL puts its whole payload into the op name, because `pathname` is the data. (unverified: follows from `parseUrl` and WHATWG URL semantics; no test) **Privacy.** -- Sensitive field values are never recorded. This holds for unlabelled password inputs too (`test/review-dom.test.ts`). +- Sensitive field values are never recorded. This holds for unlabelled password inputs too (`test/review-dom.test.ts`; under happy-dom its dispatched events count as trusted, so the test does reach `isSensitiveField`). Inside shadow roots the host's `label`/`name`/`aria-label` also count. +- The default redactor is now by leaf field (`util.ts` -> `isSensitivePath`): `redactSearch` checks `query.<key>`, storage keys and `rt.emit` data keys are judged as paths, user targets (free text) word by word. - Values whose target name looks secret are redacted in `RuntimeImpl.user`. - Request query values go through `redactSearch`. - Nav routes are recorded and shown in timelines without redaction, and GenClass's own `learn.persist` writes (`localStorage.setItem("genclass.profiles.v1")`) appear as `storage` events. Both are also listed under open issues. @@ -664,22 +749,29 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store | A reused XHR showed the stale faked 503 | `unfake()` in `wOpen` | `review-xhr.test.ts` -> "after a blocked answer, reusing the same XHR shows the real state and response" | | Recursive `setTimeout` loops built lazy-op chains (stack overflow on the first write, retention) | `LazyOp` parent is always a real op; `materialize()` drops closures | `review-timers.test.ts` -> "a long idle loop (e.g. a clock/heartbeat) does not make the next state write throw", "a polling loop does not retain every past tick's op forever" (gc; needs `NODE_OPTIONS=--expose-gc`, otherwise it logs a skip and passes) | | An unlabelled password input's value was recorded | `isSensitiveField` (`type=password`) | `review-dom.test.ts` -> "never records a password field's value, even when the field has no label/placeholder/name" | -| `el.click()` by app code inside an op was recorded as a user action | `programmatic(e)` via `runningKind` | `review-dom.test.ts` -> "a programmatic element.click() made by app code inside an op is not recorded as a user action" | +| `el.click()` by app code inside an op was recorded as a user action | `programmatic(e)` via `runningKind` | `review-dom.test.ts` -> "a programmatic element.click() made by app code inside an op is not recorded as a user action" (exercises the `runningKind` rule: happy-dom's `click()` is not `isTrusted === false`); `dom.test.ts` -> "synthetic (isTrusted false) events are user actions only with observe.untrustedEvents (test harnesses)" covers the in-op case with the flag on | +| A stale out-of-order response overwrote newer data (batch 4 moved this decision from store writes to the network boundary) | delivery gate: `host.deliver` in `fetch.ts`, `arrive` in `xhr.ts`, `MessageGate` | `delivery.test.ts` -> "a stale out-of-order response gets a delivery decision; discard drops only the stale field writes"; `smoke.test.ts` -> "holds a stale response, asks the model and drops its stale writes in guard mode" | +| Clean typeahead asked the model on every keystroke | conflicts exclude moved inputs and same-signature newer requests | `delivery.test.ts` -> "clean typing (in-order responses, loading flags, debounce) makes zero model calls" | +| A held WebSocket message could be overtaken by later ones | `MessageGate` queue (messages and close/error) | `delivery.test.ts` -> "a message that would put back the value a pending local change replaced is held; later messages wait behind it (order kept); discard drops its write" | +| An XHR completion listener added before `open()` or as `on*` escaped the gate | `wAdd`, `wrapHandlers`, `gateCall` | `delivery.test.ts` -> "a stale response is held before any app completion listener runs (added before or after open, or on*), in order; discard drops only the stale field" | +| Clicks inside a custom element were described as the host | `originOf` (`composedPath()[0]`), `closestDeep`, shadow-root adoption | `dom.test.ts` -> "shadow DOM: clicks, typing and changes inside a custom element describe the real target, not the host" | +| A `<label>` around a `<select>` named it with every option's text | `labelText` / `flatText` skip nested controls | `dom.test.ts` -> "a control inside its <label>: the label's own text, without options, values or captions" | | Init threw on hardened pages with read-only globals | `tryAdd` | `review-misc.test.ts` -> "createRuntime does not throw when a global it would wrap is read-only (frozen/hardened pages)"; `batch3.test.ts` -> "createRuntime never throws on read-only globals (the observer is skipped)" | ## How to change it safely -1. **Add a new observer** (e.g. `EventSource`, `BroadcastChannel`). +1. **Add a new observer** (e.g. `BroadcastChannel`; `eventsource.ts` is the most recent worked example). - Create `packages/runtime/src/observe/<name>.ts` exporting `install<Name>(host)`. It returns an uninstall function, or `null` when the API is missing. - Use a `disabled` flag, restore the global only if it is still yours, wrap all tracing in try/catch, and use `host.clock`. - Register it in `RuntimeImpl.installObservers` via `tryAdd` and `on("<name>")`. - - Add the name to `ObserverName` in `packages/runtime/src/types.ts`, to `ALL_OFF` in `packages/runtime/src/index.ts`, and to the observe maps in `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts`, `packages/runtime/test/review-*.test.ts` (`ONLY_*` constants) and `sim/src/run/rt.ts` (set it explicitly to `false` unless SIM wants it). + - Add the name to `ObserverName` in `packages/runtime/src/types.ts` (and the `observe` line in `docs/runtime/API.md`), to `ALL_OFF` in `packages/runtime/src/index.ts`, and consider the observe maps in `packages/runtime/test/helpers.ts` -> `setup`, `packages/runtime/test/browser/ui/session.ts`, `packages/runtime/test/review-*.test.ts` (`ONLY_*` constants), `sim/src/run/rt.ts` and `realapps/src/harness/trajectory.ts` -> `OBSERVE` (unlisted names default to on; batch 4 did not add `eventsource` to any of these). + - A push channel should reuse `MessageGate` with a `MsgHost` (`wsHost()`): op creation inside the dispatch, delivery gate and ordering come for free. Report `channel("up" | "down")` so F9 staleness works. - Reuse an existing `OpKind` if you can. A new kind touches `OpKind`, `opPhrase` in `packages/runtime/src/situation/describe.ts`, `PROFILED` in `runtime.ts`, and situation text (which needs SIM/TRAIN sign-off). - Tests to add: install and record; `destroy()` restores the global; pass-through after destroy; a read-only global does not throw. - App-specific sources can instead use a plugin with `api.recordOp`, `api.endOp` and `api.runInOp` (`RuntimeImpl.pluginApi`). 2. **Change signature normalisation.** - Edit `isIdSegment`/`isSlugId` in `packages/runtime/src/util.ts`. - - Signatures key the baselines, `storeWriters`, the transition profiles persisted under `genclass.profiles.v1` (old keys stop matching), WS op names and situation text. (`identicalMap` is keyed by request identity, which hashes the full `href`, not the signature.) + - Signatures key the baselines, `storeWriters`, the transition profiles persisted under `genclass.profiles.v1` (old keys stop matching), the delivery gate's predicted write sets (`lastChainMap`, keyed by op name, also for `WS message …` / `SSE … …`), the learned cadence, WS/SSE op names and situation text. (`identicalMap` is keyed by request identity, which hashes the full `href`, not the signature.) - Update `packages/runtime/test/batch3.test.ts` (SIM e). Run the full runtime suite and the sim tests, and re-freeze the situation tag with SIM. 3. **Add a volatile header.** Add it to both `VOLATILE_HEADERS` in `fetch.ts` and `VOLATILE` in `xhr.ts`, so identities stay equal across transports. Update STATUS.md's identity line. 4. **Change cache or buffer limits.** @@ -695,18 +787,22 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store - Copy the timers pattern: capture `ctx.peek()` at schedule time, resolve a `LazyOp` to `.nearest`, and call `ctx.stick(lazyTimer(parent, label))` in the callback. - Never give a `LazyOp` a `LazyOp` parent, and never keep closures alive after materialisation. - Re-run `test/review-timers.test.ts`, including the gc test under `NODE_OPTIONS=--expose-gc`. +6a. **Touch a delivery-gate hookup** (fetch `host.deliver`, XHR `arrive`/`gateCall`, `MessageGate`). + - Keep: `release` runs at most once; synchronous release means the app sees the response/message in the same task as without GenClass; asynchronous release sticks the op before the app's code runs; order per channel/XHR is kept; abort during a hold drops the response (XHR) or the request (`stale()`). + - Failures, faked answers and hedges must not reach the delivery gate (they have their own gates). + - Run `test/delivery.test.ts`, `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts` and `test/default-mode.test.ts`. 7. **Change DOM recording.** - - Edit the handler table in `installDomUser`. Keep the `ignoredEvent(e) || programmatic(e)` guard, and the rule that sensitive fields record `""`. - - Run `test/dom.test.ts` and `test/review-dom.test.ts` (happy-dom). - - If `describeElement` output changes, coordinate with SIM: its synthetic targets mimic that format. + - Edit the handler table in `installDomUser`. Keep the `stopped || ignoredEvent(e) || programmatic(e)` guard, the `untrustedEvents` opt-in, `originOf` (composed path) for the target, and the rule that sensitive fields record `""`. + - Run `test/dom.test.ts` and `test/review-dom.test.ts` (happy-dom). happy-dom events have `isTrusted === undefined` and count as trusted, so these tests need `untrustedEvents` only to test the filter itself (set `isTrusted: false` with `Object.defineProperty`, as `dom.test.ts` does). Real-browser drivers that dispatch events need `observe: { user: true, untrustedEvents: true }`. + - If `describeElement` output changes, coordinate with SIM (its synthetic targets mimic that format) and REAL (realapps rows come from the real observer; see [../realapps.md](../realapps.md)). This is situation text frozen at `situation-v2`. 8. **Add an event kind or change an event's `data` keys.** - `EventKind` lives in `packages/runtime/src/types.ts` (public API). - Event `data` keys are load-bearing: `situation/describe.ts` -> `eventLine` reads `count`, `first` (user), `route` (nav), `key` (storage), `duration` (perf), `summary` (custom), `message` (error); `situation/build.ts` -> `timelineLines` decides relevance by `kind` (`user`, `error`, `action`, `nav` always relevant) and by `e.op` causality; `devtools/index.ts` and `devtools/ui.ts` switch on `kind`. - - Changing any of these changes situation text (`situation-v1`): coordinate with SIM and TRAIN. Re-run `test/situation.test.ts`, `test/dom.test.ts`, `test/devtools.test.ts` and `test/devtools-runtime.test.ts`. + - Changing any of these changes situation text (`situation-v2`): coordinate with SIM, REAL and TRAIN. Re-run `test/situation.test.ts`, `test/content.test.ts`, `test/dom.test.ts`, `test/devtools.test.ts` and `test/devtools-runtime.test.ts`. 9. **Change op names, `detail` or causality** (timer labels, WS names, user op names, the leading-space body summary, `cause: null` roots). - These strings reach the model through `opPhrase`/`eventLine`, are mirrored by the sim (`sim/src/run/runner.ts` calls `runtime.user(act, handler)` with `role "name"` targets; `sim/src/run/rt.ts` turns on the real fetch/timers/websocket observers), and key baselines and profiles. - - Re-run `test/context.test.ts`, `test/situation.test.ts`, `test/batch3.test.ts` and the sim's tests; re-freeze with SIM. -10. **Where to run tests.** The project contract (`docs/runtime/CONTRACT.md` §0 rule 5) says every build and test runs on the `train` VM via `scripts/vm.sh`. Under the 2026-10-07 run policy in AGENTS.md, agents on machines other than the original 8 GB Mac may run the build and unit tests locally. Ask the user before Playwright or the sim. The runtime unit tests run with `vitest run` (`npm test`) from `packages/runtime` (config `packages/runtime/vitest.config.ts`: `environment: "node"`, browser specs excluded). See [build-test-release.md](build-test-release.md). + - Re-run `test/context.test.ts`, `test/situation.test.ts`, `test/batch3.test.ts`, `test/delivery.test.ts` and the sim's tests; re-freeze with SIM (a new tag after `situation-v2`). +10. **Where to run tests.** HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac; on other machines agents may run `npm ci`, `tsc`, `tsup` and the vitest unit tests locally (see [../../../AGENTS.md](../../../AGENTS.md)). Ask the user before Playwright, `smoke.sh`, the sim generator, realapps runs, demos eval or training. From `packages/runtime`: `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then `test/review-perf.test.ts` alone (its timing bound flakes under parallel load). CI (`.github/workflows/ci.yml`, commit b435acb) runs the same split on Node 22. See [build-test-release.md](build-test-release.md). ## Tests @@ -714,22 +810,28 @@ All paths are under `packages/runtime/test/`. | Test file | What it asserts (this scope) | |---|---| -| `helpers.ts` | `FakeClock` (timers plus a macrotask/microtask/afterTask model), `FakeServer` (virtual fetch), `ScriptedDecider`, `ManualDecider`, and `setup()`, which turns only the fetch observer on | +| `helpers.ts` | `FakeClock` (timers plus a macrotask/microtask/afterTask model), `FakeServer` (virtual fetch), `ScriptedDecider`, `ManualDecider`, and `setup()`, which turns only the fetch observer on and defaults `mode: "guard"` (commit f3636b2; the product default is `observe`). Its observe map does not list `eventsource` (on, but `makeGlobal` has no `EventSource`) | +| `delivery.test.ts` (16 `it` blocks; STATUS.md says 14) | The delivery gate end to end: clean typeahead makes zero model calls; a stale out-of-order fetch response gets a `delivery` decision and `discard` drops only the stale field; holding is only latency; no hold when the model cannot answer within the budget; store writes are not held by default; superseded queued decisions are dropped; WebSocket messages held in order with `discard`; messages touching nothing pending deliver at once; EventSource custom event types; XHR completion listeners (before/after `open`, `on*`) held in order, op ambient, `removeEventListener` of a wrapped listener, `abort()` during the hold. Uses fake `WebSocket`/`EventSource` classes passed through `extraGlobal` | +| `content.test.ts` | Body-content salience (F1/F2/F3), F9 provenance (incl. "a live channel that was down: the fields its messages wrote may have missed updates", which exercises `channel` down/up), F5–F8, read-your-writes (`noteResponse`) | +| `no-reorder.test.ts` | An always-passive model in guard/heal gives the same dispatches, order and final state as observe mode | +| `default-mode.test.ts` | No `mode` means `observe`; observe never holds writes or requests and never waits for a model that never answers (fetch success and 500 both delivered at once). It does not cover the delivery gate with a conflict | | `fetch.test.ts` | Neutral traffic makes no model call. The app reads its own body while GenClass reads a clone. `coalesce` reuses an in-flight POST (`x-genclass: coalesced`). `block` returns 503 `blocked` in heal mode, and guard never runs heal actions. `serve_cached` works. `delay` = 250 ms at streak 0. `retry` backs off 200 ms and the app gets attempt 2. `retry` is not offered for stream bodies. A network error is delivered as the original `TypeError`. Failure and request gates fail open at 300 ms. `hedge` wins a stall. Abort before send records `aborted`. `TimeoutError` gives `code: "timeout"`. The GET cache keeps ≤ 64 entries and skips > 256 KB. `destroy()` restores fetch | -| `review-fetch.test.ts` | `Request` bodies are part of the identity. `Range` splits the identity. Coalescing with opaque or streaming responses settles. Buffer memory ≤ 64 × 256 KB. No abort-listener leak. No work after destroy even when wrapped on top. Failures are not held in guard mode (app sees the 503 at +50 ms). `keepalive` is sent synchronously. Identical-request "after/before" direction and error-rate facts | +| `review-fetch.test.ts` (its `headless()` now passes `mode: "guard"`) | `Request` bodies are part of the identity. `Range` splits the identity. Coalescing with opaque or streaming responses settles. Buffer memory ≤ 64 × 256 KB. No abort-listener leak. No work after destroy even when wrapped on top. Failures are not held in guard mode (app sees the 503 at +50 ms). `keepalive` is sent synchronously. Identical-request "after/before" direction and error-rate facts | | `xhr.test.ts` | Op name, detail and cause. The op is ambient in `onload` (the write is attributed to it). `block` fakes a 503 `blocked` without sending. A failure is observed with no action question. The request gate holds and fails open at 300 ms. `destroy()` restores `open`/`send` | | `review-xhr.test.ts` | A sync XHR is never held. `abort()` while held means never sent. A reused object does not accumulate listeners. Faked values are cleared on the next `open()` | | `context.test.ts` | user -> fetch -> json -> set gives cause = fetch and root = user. Concurrent chains keep their own causes. `rt.op` is ambient in its body and after it settles. Nested fetch causes. afterTask clears the ambient op. A debounce timer carries the cause (`timer 300ms`). Idle timers create no ops | | `review-timers.test.ts` | A 200,000-tick recursive `setTimeout` loop followed by a write does not throw. A polling loop does not retain past ticks' ops (gc test) | -| `dom.test.ts` (happy-dom) | `describeElement` names. Clicks are user writes and never held. Typing is one event per burst (`count: 3`, `value: "\"rea\""`). Passwords are never recorded. submit/change/Enter names. `[data-genclass-ignore]` is ignored, including in shadow roots. `destroy()` removes the listeners and restores fetch/XHR/history/Storage/WebSocket/timers. Nav and storage events are recorded. An `ErrorEvent` becomes an `error` trigger (`Uncaught TypeError: boom (at app.js:12).`) | -| `review-dom.test.ts` (happy-dom) | Unlabelled password values are never recorded. A programmatic `el.click()` inside `rt.op` is not a user action | -| `smoke.test.ts` | Context propagates through real awaits (user -> fetch -> json -> set) | +| `dom.test.ts` (happy-dom) | `describeElement` names, incl. nested labels and shadow DOM ("batch 5" in the test title and STATUS.md; the code landed in fcb8189, the realapps commit just before 6e5e86e). Shadow-DOM clicks, typing and non-composed `change`. Synthetic events only with `untrustedEvents` (and never inside an op). Clicks are user writes and never held. Typing is one event per burst (`count: 3`, `value: "\"rea\""`). Passwords are never recorded. submit/change/Enter names. `[data-genclass-ignore]` is ignored, including in shadow roots. `destroy()` removes the listeners and restores fetch/XHR/history/Storage/WebSocket/timers. Nav and storage events are recorded. An `ErrorEvent` becomes an `error` trigger (`Uncaught TypeError: boom (at app.js:12).`) | +| `review-dom.test.ts` (happy-dom) | Unlabelled password values are never recorded (`isSensitiveField`). A programmatic `el.click()` inside `rt.op` is not a user action (`programmatic` -> `runningKind`). Both run without `untrustedEvents`; that is fine because happy-dom leaves `isTrusted` undefined, so the untrusted filter does not drop their events | +| `smoke.test.ts` (explicit `mode: "guard"`) | Context propagates through real awaits (user -> fetch -> json -> set). A stale search response is held at the delivery gate and `discard` drops only `search.results` | | `batch3.test.ts` | SIM e slug normalisation cases; `createRuntime` never throws on a read-only `fetch` global (the observer is skipped); `GenClass.init` never throws (a plugin whose `setup` throws) | | `review-misc.test.ts` | `createRuntime` with a non-writable `fetch` does not throw | | `situation.test.ts` | Determinism: the same scripted inputs on a fake clock give identical situations (depends on sequential op ids and identities) | -| `review-perf.test.ts` | Cost of `rt.user` keystroke writes on large stores (< 1 ms/write) | +| `review-perf.test.ts` | Cost with 5,000-item stores: a user-sync keystroke write through `rt.user` (< 1 ms/write), an async gated write (< 2 ms), a redux-style dispatch (user < 1 ms, async < 2 ms), and a settled point. Run alone (CI: separate step with `--retry=2`); its bounds flake under parallel load | -Coverage gaps: there are no unit tests for WebSocket ops and causality, the perf observer, `sessionStorage` area detection, XHR `serve_cached`/`delay`, XHR `responseType` faking, or nav redaction. Also untested: stall `serve_cached`, interval-tick causality, what existing WebSockets/timers do after `destroy()`, two runtimes on one page, and `EventLog`/`OpRegistry` in isolation (they are exercised only through the runtime). The Playwright specs under `test/browser/` cover the model host and the devtools UI, not the observers. +Coverage gaps: there are no unit tests for WebSocket connect ops, causality of `WS send`, or close codes other than through `content.test.ts`'s channel case; the perf observer; `sessionStorage` area detection; XHR `serve_cached`/`delay`; XHR `responseType` faking; nav redaction; stall `serve_cached`; interval-tick causality; what existing WebSockets/EventSources/timers do after `destroy()`; two runtimes on one page; the delivery gate in `observe` mode with a conflict; the XHR `on*` getter returning the wrapper; cloned-event fidelity in `MessageGate`; and `EventLog`/`OpRegistry` in isolation (they are exercised only through the runtime). The Playwright specs under `test/browser/` cover the model host and the devtools UI, not the observers; the realapps harness exercises the observers in real browsers but is a data generator, not a test suite (see [../realapps.md](../realapps.md)). + +Last local run by the lead (2026-10-08, mvp-v2 at b435acb): 40 files passed + 1 skipped, 332 tests passed + 14 skipped, plus `review-perf` alone 4 passed. Not run: Playwright, smoke.sh, realapps. ## Drift and open issues @@ -737,55 +839,64 @@ Doc-vs-code mismatches (the code is right): | What | Doc says | Code does | |---|---|---| -| Trusted-event filtering | `docs/runtime/ARCHITECTURE.md`: "DOM user events (capture phase, trusted events only)" | Untrusted events are kept unless a non-user op is running or ambient (`dom-user.ts` -> `programmatic`); test drivers rely on this | +| Observe mode and the delivery gate | `types.ts` `InitOptions.mode` JSDoc (f3636b2) and `test/default-mode.test.ts` header: observe "never holds, delays or changes anything" | `runDelivery` does not check the mode. While the runtime is consultable (provider state `ready` or `off`), for a response or message with a conflict (or `triage: "always"`) it reads the body (≤ `BODY_WAIT_MS` = 100 ms) before calling `trigger`, which then runs passive at once. So in observe mode the app's `fetch` promise resolves, and XHR completion listeners run, asynchronously; a WebSocket/EventSource message is stopped and **re-dispatched as a clone** (`isTrusted` false, no `source`) after a microtask or more. From code reading; no test covers observe mode with a conflict (`test/default-mode.test.ts` runs with triage `always`, so its fetches do take the body-read path, but it only checks the status after advancing the clock 5 ms, not same-task delivery) | +| Untrusted DOM events | `packages/runtime/STATUS.md` ("Precision" list): untrusted events are not user actions only "while a non-user op is ambient" | Since batch 4 they are dropped unless `observe.untrustedEvents: true` (`dom-user.ts` -> `programmatic`). STATUS's batch-4 section, its `observe` defaults bullet (under "How to drive it headless") and API.md are correct | +| Trusted-event filtering | `docs/runtime/ARCHITECTURE.md`: "DOM user events (capture phase, trusted events only)" | Correct by default now; it omits the `untrustedEvents` opt-in, EventSource and timers | +| `observe` default | `types.ts`: two JSDoc blocks precede `InitOptions.observe`; the first still says "Default: all true (where the global supports them)" | The second block is right: all on, `timers` only with a document, `untrustedEvents` false | +| Observed sources list | `docs/runtime/API.md`: "The DOM, fetch, XHR, WebSocket and timers are observed automatically" | Also EventSource and long tasks (`perf`), and timers in browsers | +| Delivery test count | STATUS.md batch 4: `test/delivery.test.ts` (14) | 16 `it` blocks | | Signature normalisation | `docs/runtime/CONTRACT.md` §3: "numbers, uuids, long hex → `:id`" | Also long mixed tokens (≥ 16 chars) and short slug ids (`util.ts` -> `isIdSegment`, approved SIM e; STATUS.md records it) | | Body methods that propagate context | CONTRACT §3 lists `json, text, arrayBuffer, blob, formData` | Also `bytes`, and `clone()` returns an instrumented clone (`fetch.ts` -> `instrumentResponse`) | | Retry backoff | CONTRACT §7: `min(200 ms · 2^attempt, 5 s)` | `min(200 · 2^(attempt−1), 5000)`. STATUS "Deviations" and API.md are correct | -| What never matches | `docs/runtime/API.md`: "Bodies GenClass cannot read cheaply (streams, files, bodies over 64 KB) never match anything" | String bodies up to 1,048,576 chars are hashed and can match; the 64 KB limit applies only to Blob/ArrayBuffer/view/Request bodies (`fetch.ts` -> `bodyInfo`) | +| What never matches | `docs/runtime/API.md`: "Bodies GenClass cannot read cheaply (streams, files, bodies over 64 KB) never match anything" | String bodies up to 1,048,576 chars are hashed and can match; the 64 KB limit applies only to Blob/ArrayBuffer/view/Request bodies (`fetch.ts` -> `bodyInfo`). STATUS.md's identity line is correct | | Identity definition | CONTRACT §3 and the `Op.identity` comment in `types.ts`: "hash of method+url+body" | Also non-volatile headers (`headersKey`) | -| Keepalive / sync XHR | API.md and STATUS: "never held" | They raise no request trigger at all (no background decision); the failure gate still applies to keepalive fetches | -| Observe defaults | `types.ts` `InitOptions.observe` comment: "Default: all true" | `timers` defaults to true only when `global.document` is an object (STATUS.md is correct) | +| Keepalive / sync XHR | API.md and STATUS: "never held" | They raise no request trigger at all (no background decision); the failure gate still applies to keepalive fetches, and the delivery gate to keepalive responses | | Timer op materialisation | `timers.ts` header: "only materializes if the callback starts a request or writes state" | Also on `rt.emit`, `reportError`, storage writes, `rt.op`, WS send and plugin `recordOp`: anything that calls `ctx.op()` | -| `stick` call sites | `trace/context.ts` header: stick happens "after a wrapped fetch/XHR/body method settles, a user action is recorded, or a propagated timer fires" | Also on every WS message (`websocket.ts`) and when `rt.op` settles (`RuntimeImpl.op`) | -| `x-genclass` marking | `packages/runtime/README.md`: "Responses GenClass altered carry an `x-genclass` header" | Opaque responses shared by `coalesce` are unmarked clones. `retry`/`hedge` answers are real network responses (unmarked) | +| `stick` call sites | `trace/context.ts` header: stick happens "after a wrapped fetch/XHR/body method settles, a user action is recorded, or a propagated timer fires" | Also on every WebSocket/EventSource message dispatch (`messages.ts`), on a released delivery hold, and when `rt.op` settles (`RuntimeImpl.op`) | +| `x-genclass` marking | `packages/runtime/README.md`: "Responses GenClass altered carry an `x-genclass` header" | Opaque responses shared by `coalesce` are unmarked clones. `retry`/`hedge` answers are real network responses (unmarked); responses released by the delivery gate are unaltered | | UI request | `packages/runtime/UI-NEEDS.md` item 1 (ignore the devtools overlay) is listed as **Open** | Implemented: `ignoredEvent` crosses shadow roots; tested in `test/dom.test.ts` | -| Instrumented sources list | ARCHITECTURE.md omits timers | Timers are an observer (browser-like globals only by default) | -| Pass-through after destroy | `packages/runtime/STATUS.md` module table: observers "all pass through after destroy" | True for the patched globals and prototypes. WebSocket instances and timer callbacks created before `destroy()` keep tracing (`websocket.ts` constructor listeners, `timers.ts` callback wrapper) | -| `Op.code` values | `types.ts` `Op.code` comment: "HTTP status, or an error name such as "TypeError" / "timeout"" | Observers set only HTTP status numbers, `"timeout"`, `"network"`, `"aborted"` and WS close codes; no error names (`fetch.ts`, `xhr.ts`, `websocket.ts`). Only plugin `api.endOp` can set arbitrary codes | +| Pass-through after destroy | `packages/runtime/STATUS.md`: "`destroy()`: wrappers that another library may still call become pass-throughs" | True for the patched globals and prototypes. WebSocket/EventSource instances and timer callbacks created before `destroy()` keep tracing, and XHR `addEventListener/removeEventListener` stay patched once used | +| `Op.code` values | `types.ts` `Op.code` comment: "HTTP status, or an error name such as "TypeError" / "timeout"" | Observers set only HTTP status numbers, `"timeout"`, `"network"`, `"aborted"` and WS close codes; no error names. Only plugin `api.endOp` can set arbitrary codes | | `afterTask` mechanism | CONTRACT §3: `browserClock` uses "a `MessageChannel` for `afterTask`" | `clock.ts` -> `makeAfterTask`: `setImmediate` when there is no `window` (Node), else `MessageChannel`, else `setImmediate`, else `setTimeout(0)` | | Which timer callbacks get context | CONTRACT §3 and API.md: "timer callbacks scheduled while an op was ambient" / "inside timers scheduled during an operation" | Every wrapped timer callback gets a `LazyOp`; with no ambient op at schedule time it materialises as a root `timer` op (`timers.ts`) | | Abort-listener removal | STATUS "Memory": "the abort listener is removed when the request settles" | Removed when the request is **sent** (`send`, primary) or answered (`answer`), whichever comes first (`fetch.ts` -> `runRequest` -> `unlisten`) | -| Observed sources list | `packages/runtime/README.md`: "Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are observed automatically" | Also long tasks (`perf`) and, in browsers, timers | -Open issues (from code reading; none has a test): +Resolved since 654d822 (the situation-v1 version of this doc): WebSocket disconnects after `open` being invisible (they now reach `onChannel`, though still with no op or event); "an app `onreadystatechange` assigned before `open()` misses the ambient op" (now true only for failed responses, see Invariants). + +Open issues (from code reading; none has a test unless stated): +- Observe mode is not strictly zero-delay at the delivery gate (first row of the table). Either `runDelivery` should release before reading the body when the mode permits no delivery action, or the observe-mode promise should be reworded. Needs an owner decision; changing it does not touch situation text. +- `MessageGate` re-dispatches held messages as clones: `e.isTrusted` is false, `source` is lost, and the clone is built with the module's `globalThis` constructors rather than `host.global`'s. Apps that check event identity or `isTrusted` behave differently for held messages. +- The unit tests cannot catch a regression that drops genuinely untrusted events in the wrong place: happy-dom leaves `isTrusted` undefined (treated as trusted), so only `dom.test.ts`'s forced-`isTrusted: false` test exercises the untrusted branch. Real-browser behaviour is covered only by the realapps harness (a data generator, not a test). - Nav routes, including query strings and fragments, are not redacted. They go into `nav` events and are always "relevant" in situation timelines (`situation/build.ts` -> `timelineLines`). - `ResponseCache` is not cleared on `destroy()`. - `data:` URL fetches produce op names that contain the payload (unverified). -- XHR: an app `onreadystatechange` assigned before `open()` misses the ambient op (unverified). - Header parity between `VOLATILE_HEADERS` and `VOLATILE` is not exact (e.g. `x-datadog-tags` is volatile only for XHR). - `learn.persist` writes show up as `storage` events. -- Existing `GenClassWebSocket` instances and already-scheduled timer callbacks keep tracing after `destroy()` (see "After destroy: what still runs"). -- WebSocket disconnects after `open` (error or close) are invisible: no op, no event, no trigger. +- Existing `GenClassWebSocket`/`GenClassEventSource` instances and already-scheduled timer callbacks keep tracing after `destroy()` (see "After destroy: what still runs"). +- A WebSocket/EventSource going down after `open` still creates no op and no event; only F9 staleness marks appear once the channel comes back. - `setInterval` ticks all keep the scheduling op as their parent, so a long-running interval started inside a user action keeps attributing its writes to that action's causal chain. -- Hedge op detail for a GET without a query is `(hedge)`, so `opPhrase` prints `GET /api/x(hedge)` with no space (`.trim()` removes the separator). Changing it touches situation text (`situation-v1`). +- Hedge op detail for a GET without a query is `(hedge)`, so `opPhrase` prints `GET /api/x(hedge)` with no space (`.trim()` removes the separator). Changing it touches situation text (`situation-v2`). - Two runtimes on one page double-wrap every global (one op per runtime per request). - `wrappedFetch.__genclass = true` is set but never read anywhere in the repo. - Enter/Escape auto-repeat is not filtered, so holding Enter records many `key` user ops. -From STATUS.md / OPEN_TASKS.md (relevant here): -- The `situation-v1` freeze: OPEN_TASKS "Done" records runtime fix batch 3 as frozen at tag `situation-v1`, and STATUS "Open issues" says any change to situation wording must be coordinated with SIM. Op names, details and event names reach situation text (see "Determinism and sim parity"), so they fall under the same rule. -- OPEN_TASKS #6 "hold-induced harm": with model v0.1, search clean-run latency rose from 14 ms to 125 ms because salient *writes* were held. "Triage sensitivity on naturally concurrent apps": typeahead was salient about 6 times per trial on clean runs. Whether request-gate holds contribute is not stated there (unverified). -- Known risk: on slow devices, hold budgets expire more often (more fail-open decisions). +From STATUS.md / HANDOFF.md / OPEN_TASKS.md / training/NEEDS.md (relevant here): +- The `situation-v2` freeze (tag 6e5e86e): HANDOFF.md says any change to `packages/runtime/src/situation/*` changes the training format. Op names, details and event names, element descriptions and the `ws`/`sse` event names reach situation text, so they fall under the same rule. As of 2026-10-08 SIM is generating situation-v2 data on 20 Azure nodes and REAL on 3 (training/NEEDS.md), so a wording change now invalidates data being produced. +- No situation-v2 model exists yet (HANDOFF: teacher on v2 gold → distillation → DAgger → EVAL → `@genclass/runtime-model@0.1.0`). Until then the delivery gate and every other gate run passive in practice (the provider is not ready, so `trigger` runs passive). The delivery gate's body read still happens while the default model host is in state `off` (before its idle preload starts, or with `preload: "lazy"`), because `consultable()` accepts `off`; once the load fails (state `error`) everything releases synchronously. +- OPEN_TASKS.md: batch 4 (the delivery gate, EventSource, `untrustedEvents`) was the redesign answering "hold-induced harm" from the v0.1 demo eval (search clean-run latency 14 ms → 125 ms because salient *writes* were held; typeahead salient about 6 times per trial). Item 10 (demo rerun) lists triage sensitivity for re-investigation once a v2 model exists; the delivery tests claim zero model calls for clean typeahead. +- Known risk: on slow devices, hold budgets expire more often (more fail-open decisions); batch 4's "hold only when it can help" rule (`expectedLatency() <= holdBudgetMs()`) reduces holds that would only expire. ## Related docs - [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, options, kill switch, `destroy` - [state-and-adapters.md](state-and-adapters.md): how state writes use the ambient op (`StoreHub.propose`, user-sync bypass, held writes) - [learn-situation-triage.md](learn-situation-triage.md): baselines, identical-request facts, timeline lines from events, triage -- [decide-policy-actions.md](decide-policy-actions.md): `RuntimeImpl.trigger`, hold budget, policy gate, action records, late revert +- [decide-policy-actions.md](decide-policy-actions.md): `RuntimeImpl.trigger`, hold budget, policy gate, the delivery gate's actions (`deliver`/`discard`/`defer`), action records, late revert - [model-host.md](model-host.md): model download with the native `fetch` - [devtools.md](devtools.md): overlay under `data-genclass-ignore`; consumes `on("event")` - [build-test-release.md](build-test-release.md): where and how to run the tests +- [../realapps.md](../realapps.md): the real-browser corpus that runs these observers in Playwright (`untrustedEvents: true`) to produce training rows - [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md): parity of situation text and the sim's use of these observers - [../overview.md](../overview.md#3-runtime-data-flow-end-to-end) (where observers sit in the end-to-end flow), [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../repo-map.md](../repo-map.md), [../../../AGENTS.md](../../../AGENTS.md) +- [HANDOFF.md](../../../HANDOFF.md) (live handoff) and [RESULTS.md](../../runtime/RESULTS.md) (the never-worse and clean-typeahead numbers cited in Open issues) - Original specs: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) (§3, §6, §7), [../../runtime/API.md](../../runtime/API.md), [../../runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [../../../packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md) diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md index 092b7f7c..eec3c025 100644 --- a/docs/agents/runtime/public-api-and-lifecycle.md +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -1,14 +1,16 @@ # @genclass/runtime: public API, options and lifecycle -> **Scope:** `packages/runtime/src/index.ts`, `packages/runtime/src/runtime.ts` (wiring, construction, init/destroy, modes, kill switch, option resolution, events, plugins, introspection, settled points), `packages/runtime/src/types.ts`, `packages/runtime/src/errors.ts`, `packages/runtime/src/clock.ts`, `packages/runtime/src/util.ts`, `packages/runtime/package.json`. -> **Read this when:** you add or change an init option, a `Runtime` method, an event, a plugin hook or a subpath export; you touch `GenClass.init` / `createRuntime` / the kill switch / `destroy()`; you need the exact default of any option; you add timing or scheduling code; you wire a new subsystem into `RuntimeImpl`. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/index.ts`, `packages/runtime/src/runtime.ts` (wiring, construction, init/destroy, modes, kill switch, option resolution, events, plugins, introspection, settled points, the delivery gate and background write observation as seen from the facade), `packages/runtime/src/types.ts`, `packages/runtime/src/errors.ts`, `packages/runtime/src/clock.ts`, `packages/runtime/src/util.ts`, `packages/runtime/package.json`. +> **Read this when:** you add or change an init option, a `Runtime` method, an event, a plugin hook or a subpath export; you touch `GenClass.init` / `createRuntime` / the kill switch / `destroy()`; you need the exact default of any option (the default mode is now `observe`); you add timing or scheduling code; you wire a new subsystem into `RuntimeImpl`. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - Two entry points: `GenClass.init(options)` (browser facade: singleton, never throws, kill switch, loads the local model by default) and `createRuntime(options)` (headless: tests, sim, SSR; no model unless `decider` or `model: {...}` is passed). Both return a `RuntimeImpl` typed as `Runtime`. `createRuntime` can throw on malformed options; `GenClass.init` never throws (it falls back to an inert runtime). - `GenClass.init` is idempotent: a second call returns the first runtime and **ignores its new options**. Only `GenClass.destroy()` clears the singleton; `rt.destroy()` alone does not. -- Three modes: `observe` (never changes execution, nothing held), `guard` (default; guard-tier actions only), `heal` (guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. +- Three modes: `observe` (**default** on `mvp-v2` since f3636b2: `o.mode ?? "observe"` in `RuntimeImpl`'s constructor; never changes execution, nothing held, decisions still made in the background and reported), `guard` (opt-in; guard-tier actions only), `heal` (experimental; guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. The published `0.1.0-alpha.0` on npm still defaults to `guard`. +- The unit-test harness (`test/helpers.ts` -> `setup`) passes `mode: "guard"` explicitly, because most CORE tests exercise interventions; pass `setup({ mode: undefined })` to get the product default. +- Situation-v2 (batch 4/5): decisions about responses and push messages are taken at the **network boundary** (the `delivery` trigger, `RuntimeImpl.runDelivery`). Store writes are **never held by default**: a salient write not covered by a delivery decision is triaged when proposed and decided in the background (`observeWrite`); `policy.holdWrites: true` restores the old hold-the-write path (opt-in, never reorders a store's writes). - Kill switch: `?genclass=off` (URL wins) or `localStorage.genclass = "off"` gives an inert runtime; the values `observe|guard|heal` override `options.mode`. - The decider (`DecisionProvider`) is the only seam to the model. `createRuntime` builds a model host (`createModelHost`) only when `options.decider === undefined` and `options.model` is an object; the runtime then **owns** it and disposes it on `destroy()`. A caller-supplied decider is never disposed. - The runtime consults the decider only while its `status.state` is `"ready"` or `"off"` (lazy). `"loading"` and `"error"` mean every trigger fails open at once (passive action, nothing held, no decision recorded). @@ -16,14 +18,14 @@ - Construction order matters: core subsystems, then queue/reporter/env, hub hooks, event and status subscriptions, persisted profiles, observers (each wrapped in try/catch), then plugins. `destroy()` is idempotent and tears down in roughly reverse order. - A **settled point** is reached `settleMs` (default 60 ms) after the last op end / applied write / discarded write, when nothing younger than 10 s is in flight and no write is pending. Invariants and transition profiles are learned there and `inconsistency` / `transition` triggers are raised there. - Events: `detect`, `decide`, `act`, `event`, `status`, `report` via `rt.on(type, fn)`; listener exceptions are swallowed (logged with `debug: true`). -- `util.ts` helpers (`secs`, `fmtNum`, `describe`, `normalizePath`, `isSensitiveName`, ...) shape the situation text. Changing them changes the frozen `situation-v1` format and breaks train/runtime parity. +- `util.ts` helpers (`secs`, `fmtNum`, `describe`, `normalizePath`, `isSensitiveName`, `isSensitivePath`, ...) shape the situation text. Changing them changes the frozen `situation-v2` format (tag `situation-v2` = 6e5e86e) and breaks train/runtime parity. `situation-v1` (tag at 1a77558; `packages/runtime/src` is identical at 654d822 = the npm `0.1.0-alpha.0`) is superseded; the R17-final1 model trained on it does not match this runtime. ## Files | path | role | key exports / entry points | |---|---|---| | `packages/runtime/src/index.ts` | Public facade and root module | `GenClass` (also `default`), `createRuntime`, re-exports (see [Root module exports](#root-module-exports)); private `killSwitch`, `initUnsafe`, `makeHost`, `failedProvider`, `NATIVE_FETCH`, `MODES`, `ALL_OFF` | -| `packages/runtime/src/runtime.ts` | `RuntimeImpl`: wires trace, state, learn, situation, decide and observers; implements every `Runtime` method; actions that need runtime state (rollback, chain revert, resync, late revert); settled points | `RuntimeImpl`, `RuntimeInternals`, `normalizeError`, type re-exports `SituationDraft`, `BuiltSituation` | +| `packages/runtime/src/runtime.ts` | `RuntimeImpl`: wires trace, state, learn, situation, decide and observers; implements every `Runtime` method; actions that need runtime state (rollback, chain revert, resync, late revert); the delivery gate (`runDelivery`, discard marks, drop filter); background write observation (`observeWrite`, `covered`); write marks (`markWrites`, `onChannel`); settled points | `RuntimeImpl`, `RuntimeInternals`, `normalizeError`, type re-exports `SituationDraft`, `BuiltSituation` | | `packages/runtime/src/types.ts` | Every public and shared type. Header: CORE owns it; the "model seam" section (top) is shared with MODEL (`src/model/**`) and mirrored by `sim/src/types.ts` | `InitOptions`, `CreateOptions`, `ModelOptions`, `PolicyOptions`, `Runtime`, `RuntimeEvents`, `Plugin`, `PluginApi`, `DecisionProvider`, `Clock`, ... | | `packages/runtime/src/errors.ts` | The one runtime-level error class | `GenClassUnavailableError` | | `packages/runtime/src/clock.ts` | Real clock; captures timers at module load | `browserClock` | @@ -31,7 +33,7 @@ | `packages/runtime/package.json` | Package manifest: exports map, bin, deps, peer deps | `exports`, `bin.genclass-runtime` | | `packages/runtime/tsup.config.ts` | Build entries (one per subpath export, including `worker`) | `entry`, `dts.entry`, `external` | -Read-only neighbours this doc leans on: `src/decide/policy.ts` (`policyConfig`, `holdBudget`, `gate`), `src/decide/decider.ts` (`DeciderQueue`), `src/decide/report.ts` (`Reporter`), `src/model/host.ts` (`createModelHost`, `DEFAULT_MODEL_BASE_URL`), `src/situation/serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`), `src/trace/events.ts` (`EventLog`), `src/state/hub.ts` (`StoreHub`). +Read-only neighbours this doc leans on: `src/decide/policy.ts` (`policyConfig`, `holdBudget`, `gate`), `src/decide/decider.ts` (`DeciderQueue`, now with `waiting`, `computing`, `computingSince`, `stuck` and a per-item `stale` check), `src/decide/exec.ts` (`Controller` with new optional `proceeded()` / `stale()`, `ActionEffect.onRecord`, `NetHost.deliver` / `noteResponse`), `src/decide/report.ts` (`Reporter`), `src/model/host.ts` (`createModelHost`, `DEFAULT_MODEL_BASE_URL`), `src/situation/serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`), `src/trace/events.ts` (`EventLog`), `src/state/hub.ts` (`StoreHub`, `holdWrites`, hooks `observeWrite` / `filter` / `dropped`). New in batch 4/5 and wired by `RuntimeImpl`: `src/situation/conflicts.ts` (`predictedWrites`, `matchFields`, `conflictsOn`), `src/situation/content.ts` (`analyzeBody`, `createdIds`, `vhash`), `src/situation/evidence.ts` (`commitAmbiguity`, `failureOf`, `hostOfSig`), `src/learn/cadence.ts` (`Cadence`), `src/observe/eventsource.ts` (`installEventSource`), `src/observe/messages.ts` (shared WebSocket/EventSource message ops). Their internals are in [observe-and-trace.md](observe-and-trace.md), [learn-situation-triage.md](learn-situation-triage.md) and [decide-policy-actions.md](decide-policy-actions.md). ## Concepts and data structures @@ -45,10 +47,17 @@ Terms introduced in this doc: | consultable | `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists, and its `status.state` is `"ready"` or `"off"`. Triggers and holds happen only when consultable. | | lazy preload | When a salient trigger finds the decider not ready, the runtime reads `this.ready` (which calls `decider.ready()` once) and fails open for that trigger. | | budget scale | `RuntimeImpl.budgetScale`, starts at 1; multiplied by 0.8 (floor 0.5) each time the decider errors with `code === "max_tokens_exceeded"`; applied to the automatic situation budget only. | +| delivery gate | `RuntimeImpl.runDelivery`: a fetch/XHR response or a WebSocket/EventSource message is about to reach the app; it is salient when a field its signature writes has newer applied data (or, judged from its body, it would put back a value the user's pending change replaced, or replace text the user typed). Salient deliveries wait for the model (trigger `delivery`, held, priority 2); otherwise they are released at once. | +| covered write | `RuntimeImpl.covered(m)`: the write's causal chain (the cause op and up to 15 ancestors, 16 ops in all; the first op carrying `op.delivery` decides) went through the delivery gate, the gate knew which fields it would write, every changed path is among them, and (if salient) the decision was taken. Covered writes raise no `mutation` trigger. Never covered with `triage: "always"`. | +| background write observation | Default store-write path (`policy.holdWrites` false): `StoreHub.propose` calls `hooks.observeWrite(m)` -> `RuntimeImpl.observeWrite`, which triggers `mutation` with `hold: false, priority: 1`; the hub then commits the write at once. Not called for writes the hub never gates (no changes, user-sync writes without `holdUserWrites`, GenClass ops, `hold: false` stores, `hub.gating` false i.e. paused/destroyed). A later `discard` can only late-revert it (`LATE_REVERT_MS`). | +| `holdWrites` | `PolicyOptions.holdWrites` (default false), copied to `hub.holdWrites`. When true, salient writes are queued and gated (`gateMutation`), never reordering a store's writes, and `atom().get()` inside the writing chain sees its own pending value (`hub.pendingView`). | +| expected latency | `RuntimeImpl.expectedLatency()`: base × (1 + queued items) + (while one is computing) `max(base, its elapsed time)`, where base = the lower median of the queue's last 20 provider latencies, else `status.warmupMs`, else 0; `Infinity` while `queue.stuck` (last evaluation timed out). A holdable trigger waits only if this is `<=` the hold budget. | +| discard mark | `OpRec.discardMark`, set by a delivery `discard`: for `DISCARD_MARK_MS` (10 s) the op chain's writes to protected (newer-data) paths, or to paths written over by a newer op/user since it started, are dropped by `RuntimeImpl.dropFilter`; `ActionRecord.dropped` lists them; undo re-applies them. | +| write marks (F9) | `RuntimeImpl.markWrites` / `onChannel` call `hub.markField` on fields written by a response delivered over newer data, an unusually slow response, an ambiguous failed write, or messages of a live channel that was down; surfaced as facts. | ### Package exports (`packages/runtime/package.json`) -ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.0`, license Apache-2.0. +ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.0` (unchanged between 654d822 and b435acb; the published alpha.0 predates situation-v2, the NaN fix and the observe default), license Apache-2.0. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). | subpath | types | import | source entry (tsup) | documented in | |---|---|---|---|---| @@ -67,7 +76,7 @@ ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, - `devDependencies`: `@playwright/test 1.63.0`, `@types/react ^19.0.0`, `@types/react-dom ^19.0.0`, `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `react ^19.3.0`, `react-dom ^19.3.0`, `redux ^5.0.1`, `tsup ^8.5.1`, `typescript ~5.9.3`, `vitest ^5.0.3`, `zustand ^5.0.15`. - `files`: `dist`, `bin`, `README.md`, `LICENSE`. Scripts: `build` (tsup), `typecheck` (`tsc -p tsconfig.json --noEmit`), `test` (`vitest run`), `test:browser` (`playwright test --config test/browser/playwright.config.ts`). - `tsup.config.ts`: ESM only, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`. `worker` has no `.d.ts` (not in `dts.entry`). -- Git tags: `situation-v1` (situation-format freeze) and `v0.1.0-alpha.0` (the published alpha). +- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the current freeze) and `v0.1.0-alpha.0` (= 654d822, the published alpha; same `src` as `situation-v1`). ### Root module exports @@ -80,12 +89,12 @@ ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, | `GenClassUnavailableError` | class | `src/errors.ts` | | `createModelHost`, `DEFAULT_MODEL_BASE_URL`; types `ModelHost`, `ModelHostOptions`, `ModelHostStatus`, `ModelHostStats`, `ModelEvaluateRequest` | model host | `src/model/host.ts` | | `GenClassModelError`, `ModelNotReadyError`, `MaxTokensExceededError`, `ModelInputError`, `ModelUnsupportedError`, `ModelTimeoutError`, `ModelAbortedError`, `ModelBusyError`, `ModelDisposedError`, `ModelLoadError`, `ModelIntegrityError`, `ModelInferenceError`; types `ModelErrorCode`, `LoadAttempt` | model errors (each has `code`) | `src/model/errors.ts` | -| `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET` (3200), `COMPACT_BUDGET` (1100) | serializer | `src/situation/serialize.ts` | -| `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` | question vocabulary | `src/situation/questions.ts` | +| `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET` (2400; was 3200 in situation-v1), `COMPACT_BUDGET` (1100) | serializer | `src/situation/serialize.ts` | +| `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS` (now with `delivery: ["deliver", "discard", "defer"]`), `PASSIVE` (`delivery: "deliver"`), `DEFAULT_DIAGNOSES` | question vocabulary | `src/situation/questions.ts` | | `describeElement` | DOM element -> `'button "Place order"'` | `src/observe/dom-user.ts` | | `RuntimeImpl` | class (advanced; exposes internals) | `src/runtime.ts` | -Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/`holdBudget`/`gate`, `COMPACT_QUESTIONS_BUDGET` (1400). +Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/`holdBudget`/`gate`, `COMPACT_QUESTIONS_BUDGET` (1400), `TRIGGER_DESCRIPTIONS` and `ACTION_INSTRUCTIONS` (`situation/questions.ts`). The root export list itself did not change in batch 4/5 (the only `index.ts` change is `eventsource` in `ALL_OFF`). ### Modes and tiers @@ -93,9 +102,11 @@ Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/ | mode | permitted tiers | holds | notes | |---|---|---|---| -| `observe` | passive only | never (`trigger()` never waits because `permittedActions` is empty; `hub.hooks.mayHold` also returns false, so the hub does not protect live state from in-place updaters) | Decisions are still made in the background (deadline 5,000 ms) and recorded, so detections and reports work. | -| `guard` (default) | passive, guard (`discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions) | when a guard action is permitted for the trigger | | -| `heal` | passive, guard, heal (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (`rt.action` or plugins), which default to heal) | when any non-passive action is permitted | | +| `observe` (**default**, `o.mode ?? "observe"`) | passive only | never (`trigger()` never waits because `permittedActions` is empty; `hub.hooks.mayHold` also returns false) | Decisions are still made in the background (deadline 5,000 ms) and recorded, so `decide`/`detect`/report lines work; `interventions()` stays empty. Pinned by `test/default-mode.test.ts`. | +| `guard` (opt-in) | passive, guard (`discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions) | when a guard action is permitted for the trigger and `expectedLatency() <= holdBudgetMs()` | Store writes are held only with `policy.holdWrites: true`; otherwise writes apply at once and `discard` can only late-revert them. | +| `heal` (experimental) | passive, guard, heal (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (`rt.action` or plugins), which default to heal) | when any non-passive action is permitted (same latency and `holdWrites` conditions) | The sim runs in `heal`. | + +Ways to choose the mode: `GenClass.init({ mode })`, `createRuntime({ mode })`, `?genclass=guard` / `localStorage.genclass = "guard"` (facade only), `rt.setMode(...)`, or the devtools mode switch (`src/devtools/index.ts` -> `MODES`: buttons "Observe" / "Guard" / "Heal" whose tooltips start "Observe (default)", "Guard (opt-in)", "Heal (experimental)"). Threshold defaults (`policyConfig`): `report` 0.6, `guard` 0.9, `heal` 0.8. The full gate is in [decide-policy-actions.md](decide-policy-actions.md). @@ -105,19 +116,19 @@ Defaults below are what `RuntimeImpl`'s constructor applies, unless the row says | option | type | default | effect / where read | |---|---|---|---| -| `mode` | `Mode` | `"guard"` (`o.mode ?? "guard"`) | Initial mode; the kill switch overrides it in `GenClass.init`. Change later with `setMode`. | +| `mode` | `Mode` | `"observe"` (`o.mode ?? "observe"`, f3636b2; was `"guard"` up to origin/runtime 74f17c0 and in npm `0.1.0-alpha.0`) | Initial mode; the kill switch overrides it in `GenClass.init`. Change later with `setMode`. | | `model` | `ModelOptions \| false` | `GenClass.init` in a browser: `{}` (load the local model with defaults) unless `decider` is given or `model === false`. `createRuntime`: no model unless an object is passed. | Read only in `index.ts` -> `createRuntime`; `RuntimeImpl` never reads it. | | `decider` | `DecisionProvider \| null` | `undefined` | Any provider (test double, sim, custom). Wins over `model`. `null` means "no model" even if `model` is an object. | | `report` | `"console" \| "silent" \| (r: Report) => void` | `"console"` | Report sink (`Reporter`). `GenClass.init` defaults it to `"silent"` outside a browser. `on("report")` listeners get every report regardless of the sink. | -| `observe` | `Partial<Record<ObserverName, boolean>>` | every observer on, except `timers`, which is on only when `global.document` is a non-null object | `RuntimeImpl.installObservers`; unknown keys ignored. Forced to all-off outside a browser, by the kill switch and in the init fallback. | +| `observe` | `Partial<Record<ObserverName \| "untrustedEvents", boolean>>` | every observer on (now ten, including `eventsource`), except `timers`, which is on only when `global.document` is a non-null object; `untrustedEvents` false | `RuntimeImpl.installObservers`; unknown keys ignored. Forced to all-off outside a browser, by the kill switch and in the init fallback. `untrustedEvents: true` (batch 4) makes the `user` observer record synthetic DOM events (`isTrusted === false`) as user actions too, for in-page test harnesses such as `realapps/` ([../realapps.md](../realapps.md)); it is passed as `installDomUser(g, { untrusted })`. It is not an observer and is not in `ALL_OFF`. | | `triage` | `"salient" \| "always"` | `"salient"` | `"salient"`: ask only when some fact is non-neutral (or a standing question has `always: true`). `"always"`: build and ask for every consultable trigger (tests). | | `policy` | `PolicyOptions` | see [PolicyOptions](#policyoptions) | `policyConfig(o.policy)` once at construction (not changeable later). | -| `redact` | `(path: string, value: unknown) => unknown` | `util.ts` -> `defaultRedact` | Return something `!==` value to redact. Used by the hub, invariant miner, observers, `emit`, `user`, situation building. | +| `redact` | `(path: string, value: unknown) => unknown` | `util.ts` -> `defaultRedact` (leaf-field rule, `isSensitivePath`) | Return something not `Object.is`-equal to the value to redact (`describe` and `redactSearch` compare with `Object.is` since ad24804, so `NaN` no longer counts as redacted). Used by the hub, invariant miner, observers, `emit`, `user`, situation building. | | `plugins` | `Plugin[]` | `[]` | Installed with `use()` at the end of the constructor. | | `historySize` | `number` | `500` | `EventLog` ring buffer size; effective minimum 16 (`new Array(Math.max(16, size))` in `src/trace/events.ts` -> `EventLog`). `NaN`, or a non-integer of 16 or more, makes `new Array(...)` throw `RangeError` in the constructor (`createRuntime` throws; `GenClass.init` falls back to the inert runtime); a fraction below 16 is silently raised to 16. | | `debug` | `boolean` | `false` | `RuntimeImpl.log` -> `console.debug("[GenClass] ...")`: every decision, plus otherwise-silent failures (observer install, plugin setup, listener, model, passive/situation build errors). | | `learn` | `{ persist?: boolean }` | `persist: false` | Transition profiles to `global.localStorage` key `genclass.profiles.v1`: loaded at construction; a settled point that had queued ops to profile schedules one write 5,000 ms later (`saveProfilesSoon`; not a debounce: while a write is pending, later settled points do not reschedule it). | -| `vocabulary` | `Vocabulary` (`{ diagnoses?: Record<string,string>; actions?: Partial<Record<string,string>> }`) | `undefined` | `diagnoses` replaces `DEFAULT_DIAGNOSES`; `expected` is always kept (added from the defaults if missing, always first) and plugin labels are added only when the label is not already present (`situation/questions.ts` -> `diagnosisVocabulary`). `actions[name]` overrides the description of a built-in **or custom** action (`actionDescription`: vocabulary, then `ActionDef.description`, then built-in). Changes model input wording. | +| `vocabulary` | `Vocabulary` (`{ diagnoses?: Record<string,string>; actions?: Partial<Record<string,string>> }`) | `undefined` | `diagnoses` replaces `DEFAULT_DIAGNOSES`; `expected` is always kept (added from the defaults if missing, always first) and plugin labels are added only when the label is not already present (`situation/questions.ts` -> `diagnosisVocabulary`). `actions[name]` overrides the description of a built-in **or custom** action (`situation/questions.ts` -> `actionDescription`: vocabulary, then `ActionDef.description`, then the trigger-specific built-in wording in `TRIGGER_DESCRIPTIONS` (situation-v2: `delivery`'s `deliver`/`discard`/`defer`), then `BUILTIN_ACTIONS[name].description`). The override applies to every trigger an action appears on. Changes model input wording. | | `settleMs` | `number` | `60` | Quiet time before a settled point. | | `situation` | `{ budget?: number \| "auto" }` | `"auto"` | Situation size in characters. A number is used as is (no device sizing, no budget scale). See `situationBudget()`. | @@ -156,6 +167,7 @@ Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). | `deny` | `[]` | | `holdBudgetMs` | `"auto"`: `clamp(round(1.5 × median of the last 20 provider latencies, else status.warmupMs), 150, 800)`; 300 when neither is known (`HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS`). A number is used as `Math.max(0, n)` (no clamp to 150..800). | | `holdUserWrites` | `false` (copied to `hub.holdUserWrites`) | +| `holdWrites` | `false` (batch 4; copied to `hub.holdWrites`). false: store writes are never held, decisions are taken at the network boundary (`delivery`) and uncovered salient writes are decided in the background. true: salient writes wait for the model without reordering a store's writes. | | `maxActionsPerMinute` | `60` | | `requireDiagnosis` | `true` | @@ -204,6 +216,7 @@ Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). | `constructor(o: CreateOptions & { decider?, ownsDecider? } = {})` | Direct construction never reads `o.model` (no model host is created) and ignores the kill switch; use `createRuntime` unless you are resolving the decider yourself. | | `build(spec: SubjectSpec): BuiltSituation` | Build a situation for a subject spec without triggering. | | `trigger(spec, ctl, opts)` | Entry point for observers: triage, hold, queue, gate, act (see [decide-policy-actions.md](decide-policy-actions.md)). | +| `runDelivery(o, release, defers = 0)` | The delivery gate (declared without `private`; reached through the closures `netHost().deliver` (fetch/XHR) and `wsHost().deliverMessage` (WebSocket/EventSource)). Each call releases at most once (per-call `released` flag); a `defer` re-enters it with the same `release`. | | `startOp(kind, name, o?)`, `endOp(op, status, o?)` | Op creation/completion with events, baselines, profiling queue, `hooks.opCreated`, settle scheduling. | | `runAsGenClass(name, fn)` | Run `fn` inside an instant `"genclass"` op (`cause: null`): its writes and requests are never gated. | | `settled()` | Run a settled point now (normally called by the settle timer). | @@ -214,7 +227,7 @@ Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). | type | payload | fired from | when | |---|---|---|---| | `detect` | `Detection` (= `Decision`) | `RuntimeImpl.onDecision` | `decision.diagnosis !== "expected"` and `diagnosisConfidence >= policy.thresholds.report` (0.6), whether or not an action ran. Fired right after `decide`. | -| `decide` | `Decision` | `RuntimeImpl.onDecision` | Every model decision on a trigger (not for `ask`/`decide` calls, not while loading, not for triage-skipped triggers, and not when the queue returns no answer: deadline passed, queue overflow, provider error or timeout, runtime destroyed). | +| `decide` | `Decision` | `RuntimeImpl.onDecision` | Every model decision on a trigger (not for `ask`/`decide` calls, not while loading, not for triage-skipped triggers, and not when the queue returns no answer: deadline passed, queue overflow, subject already superseded (`ctl.stale`), provider no longer `ready` at dispatch, provider error or timeout, runtime destroyed). | | `act` | `ActionRecord` | `onDecision` -> `finish` | Every non-passive action that ran (also failed ones, `ok: false`), after its effect resolved. | | `event` | `RtEvent` | `EventLog.onEvent` / `EventLog.touch` | Every traced event; a typing burst re-fires the same (mutated) event object. | | `status` | `ModelStatus` | `decider.onStatus` subscription; `setMode` | Model status changes; also on every `setMode` call (devtools refreshes its mode view on it). | @@ -222,7 +235,9 @@ Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). Order inside one decision (`RuntimeImpl.onDecision`): `event` (an `RtEvent` of kind `"decision"`) -> `decide` -> `detect` (if detected) -> standing-question `onAnswer` callbacks -> either (no action runs: `ctl.passive()`, then a `report` detect line if detected) or (action runs: `rate.take`, the action, and once its effect resolves or fails: `event` (kind `"action"`) -> `act` -> `report` intervene line). A failed action (throw or rejection) runs the passive action first and records `ok: false`. -Trigger priorities (`EvaluateRequest.priority`, higher is served first by `DeciderQueue`): held `mutation` (`gateMutation`), `request` and fetch `failure` = 2; `stall`, `inconsistency`, XHR `failure`, `ask` = 1; `transition`, `error` = 0. A holdable trigger that does not actually wait is capped at 1 (`Math.min(priority, 1)` in `trigger`). +Trigger priorities (`EvaluateRequest.priority`, higher is served first by `DeciderQueue`): `delivery` (`runDelivery`), held `mutation` (`gateMutation`, only with `holdWrites`), `request` and fetch `failure` = 2; background `mutation` (`observeWrite`, the default write path), `stall`, `inconsistency`, XHR `failure`, `ask` = 1; `transition`, `error` = 0. A holdable trigger that does not actually wait is capped at 1 (`Math.min(priority, 1)` in `trigger`), which in the default `observe` mode is every trigger. + +Queued requests can be dropped before dispatch: `trigger` passes `ctl.stale` to `DeciderQueue.submit` as a third argument, and the queue resolves `null` (fail open) for an item whose subject was already delivered, overwritten or superseded. Status reports emitted by the runtime itself: `"[GenClass] Model ready (<model>, <device>, <variant>, <secs>). Mode: <mode>."`, `"[GenClass] Model unavailable (<error>); observing only."`, `"[GenClass] Mode set to <mode>."`, `"[GenClass] Rate limit reached (<n> actions/minute): running passive actions until it clears."` (at most once per 60,000 ms). @@ -297,16 +312,16 @@ Provider errors (`GenClassModelError` subclasses, `code` in `ModelErrorCode`) ne |---|---|---| | model seam | `JevState`, `Question`, `NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`, `Answer`, `AnswerOf`, `TriggerKind`, `ModelStatus`, `SubjectRef`, `EvaluateRequest`, `DecisionProvider` | [model-io-contract.md](../model-io-contract.md) | | clock | `Clock` | this doc | -| trace | `EventKind`, `RtEvent`, `OpKind`, `OpStatus`, `Op`, `UserAction` | [observe-and-trace.md](observe-and-trace.md) | +| trace | `EventKind`, `RtEvent`, `OpKind`, `OpStatus`, `Op`, `UserAction` (new `clicks?: number`, the browser click count) | [observe-and-trace.md](observe-and-trace.md) | | state | `StoreOptions`, `Atom`, `Guarded`, `StoreIO`, `AdapterIO`, `AdapterHandle`, `Change` | [state-and-adapters.md](state-and-adapters.md) | | options | `Mode`, `Tier`, `ObserverName`, `PolicyOptions`, `Vocabulary`, `RuntimeHooks`, `ModelOptions`, `InitOptions`, `CreateOptions` | this doc | | questions | `AskOptions` (`about?: "now" \| number /* op id */ \| string /* store */`, `timeoutMs?`) | this doc | -| situations | `FactKind`, `Fact`, `Situation`, `RequestInfo`, `SituationDraft` | [learn-situation-triage.md](learn-situation-triage.md) | -| decisions | `Decision`, `Detection`, `ActionRecord`, `Report`, `Explanation` | [decide-policy-actions.md](decide-policy-actions.md) | +| situations | `FactKind`, `Fact`, `Situation`, `RequestInfo`, `SituationDraft` (new `delivery?: { channel: "response" \| "websocket" \| "eventsource"; predicted; conflicts }`) | [learn-situation-triage.md](learn-situation-triage.md) | +| decisions | `Decision`, `Detection`, `ActionRecord` (new `dropped?: string[]` for delivery `discard`), `Report`, `Explanation` | [decide-policy-actions.md](decide-policy-actions.md) | | plugins | `ActionContext`, `ActionDef`, `StandingQuestionContext`, `StandingQuestion`, `PluginApi`, `Plugin` | this doc / [decide-policy-actions.md](decide-policy-actions.md) | | runtime | `RuntimeEvents`, `Runtime` | this doc | -Key literal unions: `TriggerKind = "mutation" | "request" | "failure" | "stall" | "inconsistency" | "transition" | "error" | "ask"`; `ObserverName = "fetch" | "xhr" | "user" | "errors" | "nav" | "storage" | "perf" | "websocket" | "timers"`; `ModelStatus.state = "off" | "loading" | "ready" | "error"`. +Key literal unions: `TriggerKind = "mutation" | "request" | "delivery" | "failure" | "stall" | "inconsistency" | "transition" | "error" | "ask"` (`delivery` new in batch 4; `SubjectRef.op` is the fetch op or the WebSocket/EventSource message op); `ObserverName = "fetch" | "xhr" | "user" | "errors" | "nav" | "storage" | "perf" | "websocket" | "eventsource" | "timers"`; `ModelStatus.state = "off" | "loading" | "ready" | "error"`. Adding a `TriggerKind` forces entries in every `Record<TriggerKind, ...>` (`TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `report.ts` -> `NOUN`), and the model seam is mirrored by `sim/src/types.ts`. ### `RuntimeImpl` state (private fields, `runtime.ts`) @@ -324,6 +339,11 @@ Key literal unions: `TriggerKind = "mutation" | "request" | "failure" | "stall" | `explainMap` | explain records keyed by `d<n>` and `a<n>` | soft: one oldest entry evicted per decision once over 400 (`DECISIONS_KEPT * 2`); action entries are never evicted on insert, so it grows by one per executed action | | `lastBuilt` | last built situation per trigger (for `situation(trigger)`) | 1 per trigger | | `storeWriters` | op signature -> store -> writes by its chains | 1,000 signatures | +| `lastChainMap` | non-user op signature -> normalised field paths its last chain wrote (predicted writes for the delivery gate, `env.lastChain`) | 1,000 signatures (oldest deleted) | +| `cadence: Cadence` | learned schedules / debounces per request signature (F6, `env.cadence`) | see `learn/cadence.ts` | +| `createsBuf` | create responses (POST or 201) with the ids they returned (read-your-writes, `env.creates`), filled by `noteResponse` | 16 entries, 30 s | +| `outcomesBuf` | completed non-aborted fetch/XHR outcomes across signatures (failure scope, F5, `env.outcomes`) | 128 entries, 30 s | +| `channelsDown` | `"<channel> <path>"` -> when and why a WebSocket/EventSource went down (F9 marks on reconnect) | one per channel | | `identicalMap` | request identity -> recent ops | 12 per identity, 512 identities, 10 s | | `errorsRecent` | recent error keys | 64, 10 s window | | `toProfile` | ops waiting for the next settled point | 2,000 | @@ -366,16 +386,16 @@ Field initialisers run first (`ops = new OpRegistry()`, `base = new Baselines()` 1. `clock = o.clock ?? browserClock`; `global = o.global ?? globalThis`. 2. `events = new EventLog(o.historySize ?? 500)`; `ctx = new Context(clock)`; `redactFn = o.redact ?? defaultRedact`. 3. `hub = new StoreHub(clock, ctx, events, () => redactFn)`; `miner = new InvariantMiner(() => redactFn)`; `cache = new ResponseCache(clock)`. -4. `policy = policyConfig(o.policy)`; `hub.holdUserWrites = policy.holdUserWrites`; `rate = new RateLimiter(() => policy.maxActionsPerMinute)`. -5. Scalars: `_mode`, `triage`, `vocab`, `hooks`, `settleMs` (60), `budgetOpt` (`"auto"`), `appFn`, `debug`, `persist`, `decider`, `ownsDecider`. +4. `policy = policyConfig(o.policy)`; `hub.holdUserWrites = policy.holdUserWrites`; `hub.holdWrites = policy.holdWrites`; `rate = new RateLimiter(() => policy.maxActionsPerMinute)`. +5. Scalars: `_mode` (`o.mode ?? "observe"`), `triage`, `vocab`, `hooks`, `settleMs` (60), `budgetOpt` (`"auto"`), `appFn`, `debug`, `persist`, `decider`, `ownsDecider`. 6. `queue = new DeciderQueue(clock, () => decider, onError)`; `onError` shrinks `budgetScale` on `max_tokens_exceeded` and logs. 7. `reporter = new Reporter(o.report ?? "console", clock, id => explain(id), r => fire("report", r))`. 8. `env = makeEnv()`. -9. `hub.hooks = { gate: gateMutation, mayHold: consultable() && mode !== "observe", appError: reportError, waitRelated, applied: onApplied, discarded: scheduleSettle, proposed: hooks.mutationProposed wrapper }`. +9. `hub.hooks = { gate: gateMutation, mayHold: hub.holdWrites && consultable() && mode !== "observe", observeWrite, filter: dropFilter, dropped: onDropped, appError: reportError, waitRelated, applied: onApplied, discarded: scheduleSettle, proposed: hooks.mutationProposed wrapper }`. 10. `events.onEvent(e => fire("event", e))`. 11. If `decider.onStatus` exists: subscribe (fire `status`; status reports on `ready`/`error`); push the unsubscribe into `uninstall`. 12. If `learn.persist`: `loadProfiles()` from `global.localStorage["genclass.profiles.v1"]` (errors ignored). -13. `installObservers(o.observe ?? {})`, in this order: `timers`, `fetch`, `xhr`, `websocket`, `user`, `errors`, `nav`, `storage`, `perf`. Each install is in `tryAdd` (a throwing installer is skipped and logged with `debug`); a non-null returned function is pushed into `uninstall`. +13. `installObservers(o.observe ?? {})`, in this order: `timers`, `fetch`, `xhr`, `websocket`, `eventsource` (shares `wsHost()` with WebSocket), `user` (with `untrusted: on("untrustedEvents", false)`), `errors`, `nav`, `storage`, `perf`. Each install is in `tryAdd` (a throwing installer is skipped and logged with `debug`); a non-null returned function is pushed into `uninstall`. 14. `for (const p of o.plugins ?? []) this.use(p)`. Constructing a `RuntimeImpl` immediately patches the instrumented globals (fetch, XHR, timers, history, Storage, WebSocket, DOM listeners). @@ -389,7 +409,20 @@ Constructing a `RuntimeImpl` immediately patches the instrumented globals (fetch ### 5. Trigger path (facade view) -Observers and the hub call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. In order: not consultable -> passive; `computeFacts`; with `triage: "salient"`, all facts neutral and no `always` standing question -> passive; `buildSituation`; not ready -> start lazy load, passive; hold only if `hold` and some non-passive action is permitted in this mode/policy and not paused; the hold budget timer runs passive on expiry; submit to `DeciderQueue` with deadline `t0 + holdBudget (+ 2,000 ms late-revert window when the controller can revert)` for held subjects, else `t0 + 5,000 ms` and priority `min(priority, 1)`; `onDecision` gates and acts. Full detail: [decide-policy-actions.md](decide-policy-actions.md). +Observers and the hub call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. In order: not consultable -> passive; `computeFacts`; with `triage: "salient"`, all facts neutral and no `always` standing question -> passive; `buildSituation`; not ready -> start lazy load, passive; hold only if `hold`, some non-passive action is permitted in this mode/policy, not paused, **and `expectedLatency() <= holdBudgetMs()`** (batch 4: never hold when the model is not expected to answer in time, or while the queue is `stuck`); the hold budget timer runs passive on expiry; submit to `DeciderQueue` with deadline `t0 + holdBudget (+ 2,000 ms late-revert window when the controller can revert)` for held subjects, else `t0 + 5,000 ms` and priority `min(priority, 1)`, plus `ctl.stale` so a superseded subject is dropped before dispatch; `onDecision` gates and acts. + +In `onDecision`, "too late" is now asked of the controller: `proceeded = ctl.proceeded ? ctl.proceeded() : hold && (expired || passiveRan)`. A built-in action on a subject that already proceeded is cancelled with reason "the decision arrived after the hold budget expired" (held) or "the subject was not held (decided in the background)", except a `discard` whose controller can late-revert (`revertable()` returns null). Custom actions skip that check, but `ctx.builtin(name)` (`RuntimeImpl.runCustom`) returns false when `ctl.proceeded()` is true (and when paused, restricted by mode/policy, or rate-limited). For `delivery` triggers that have not proceeded, `op.delivery.decided` is set (so the chain's writes are covered). Full detail: [decide-policy-actions.md](decide-policy-actions.md). + +### 5a. Delivery gate and write observation (situation-v2, batch 4/5) + +1. **Response/message about to reach the app.** `observe/fetch.ts` / `observe/xhr.ts` call `netHost().deliver(...)`; `observe/messages.ts` (WebSocket, EventSource) calls `wsHost().deliverMessage(...)`. Both land in `RuntimeImpl.runDelivery(o, release)`. Not consultable, paused, destroyed or a GenClass-internal op: `release()` at once. +2. Predicted writes (`predictedWrites` from the signature's last chain, `lastChainMap`), the store fields they match (`matchFields`) and conflicts (`conflictsOn`: `newer` applied data, `pending` local changes) are computed; `op.delivery = { patterns, known, salient, decided: false }` is recorded on the op. +3. No conflict, no typed-text field and not `always`: release at once. Without a body reader: salient iff a `newer` conflict exists. With one: wait up to `BODY_WAIT_MS` (100 ms) for the parsed body (a clone); `analyzeBody` then keeps a `newer` conflict only if the body would change the value (F3), a `pending` one only if the body puts back the value the user's change replaced (F1), and typed text only if the body would replace it (F2). Unchanged conflicts push a `custom` event `delivery.unchanged`. +4. Salient (or `always`): `trigger({ trigger: "delivery", ... }, ctl, { hold: true, priority: 2 })`. Controller: `passive` releases (and records `overNewer` for F9 marks when delivered over a conflict); `discard` releases and sets a `discardMark` for 10 s; `defer` waits for related in-flight ops (`relatedInFlight`, at most `LONG_RUNNING_MS`) then calls `runDelivery` again with `defers + 1`. +5. **Writes.** The hub calls `hooks.filter` (`dropFilter`: drop paths under an active discard mark), then, with `holdWrites` false, `hooks.observeWrite` (`observeWrite`: skip when not consultable, GenClass-internal or `covered(m)`; else a background `mutation` trigger with a controller whose `run` throws "the write was not held" except via late revert) and commits immediately. With `holdWrites` true, `gate` (`gateMutation`) holds as before, but also skips covered writes. +6. **Marks.** After each applied write, `onApplied` updates `lastChainMap` and calls `markWrites` (try/catch); `noteResponse` records created ids; `onChannel` marks fields of a live channel that was down when it comes back. + +Behavioural tests: `delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts`; design and fact text: [learn-situation-triage.md](learn-situation-triage.md), [decide-policy-actions.md](decide-policy-actions.md), `docs/runtime/RESULTS.md`. ### 6. `ask` and `decide` @@ -441,12 +474,16 @@ After destroy: listeners registered with `on()` stay attached and can still fire | name | type | value | defined in | effect | |---|---|---|---|---| | `MODES` | `readonly Mode[]` | `["observe", "guard", "heal"]` | `index.ts` | Kill-switch values accepted as modes. | -| `ALL_OFF` | `Record<ObserverName, boolean>` | all nine observers `false` | `index.ts` | Observer set for inert runtimes. Must list every `ObserverName` (type-enforced). | +| `ALL_OFF` | `Record<ObserverName, boolean>` | all ten observers `false` (`eventsource` added in batch 4) | `index.ts` | Observer set for inert runtimes. Must list every `ObserverName` (type-enforced). `untrustedEvents` is not listed (it defaults to false anyway). | | kill-switch key | string | URL param `genclass`, localStorage key `genclass` | `index.ts` -> `killSwitch` | `off` / `observe` / `guard` / `heal`; trimmed, case-insensitive; URL wins. | | `NATIVE_FETCH` | `typeof fetch \| undefined` | `globalThis.fetch.bind(globalThis)` at module evaluation | `index.ts` | Fetch used by an owned model host when no `global` is passed. | | `DECISIONS_KEPT` | number | `200` | `runtime.ts` | Size of `decisions()` / `interventions()` buffers; default `n`; the explain map evicts (one entry per decision) above `2 ×` this. | -| `LATE_REVERT_MS` | number | `2000` | `runtime.ts` | Late-revert window after a held write applied; extends the held-decision deadline. | -| `BACKGROUND_DEADLINE_MS` | number | `5000` | `runtime.ts` | Deadline for non-held decisions. | +| `LATE_REVERT_MS` | number | `2000` | `runtime.ts` | Late-revert window after a write applied (`mutationController` -> `revertable`): applies both to a held write whose budget expired and to a background (`observeWrite`) write, so a background `discard` decided more than 2 s after the write is refused ("too late to revert"). Only for held subjects whose controller can revert does it also extend the decision deadline. | +| `BACKGROUND_DEADLINE_MS` | number | `5000` | `runtime.ts` | Deadline for non-held decisions (all decisions in `observe`, and background `mutation`s). | +| `DISCARD_MARK_MS` | number | `10000` | `runtime.ts` | How long a delivery `discard` keeps dropping its chain's writes over newer data. | +| `BODY_WAIT_MS` | number | `100` | `runtime.ts` | Max wait for a salient delivery's body (a buffered clone) before deciding without it. | +| delivery / write-chain walk | number | `16` ops (the write's cause and up to 15 ancestors) | `runtime.ts` -> `covered`, `dropFilter`, `onDropped` | How far up the cause chain a write looks for a delivery decision or discard mark. | +| `markWrites` chain | number | writer + 8 ancestors | `runtime.ts` -> `markWrites` | Ops inspected for F9 marks; slow-response mark when duration `>= 5 ×` median and `>= median + 300 ms`. | | `STALL_MIN_MS` | number | `500` | `runtime.ts` | Stall timer at `max(4 × median, 2 × p95, 500)` ms of the signature's latency. | | `LONG_RUNNING_MS` | number | `10000` | `runtime.ts` | Ops older than this do not block settled points; `defer` waits at most this long. | | `PROFILED` | `Set<OpKind>` | `fetch`, `xhr`, `user`, `task`, `ws` | `runtime.ts` | Op kinds with transition profiles. | @@ -455,8 +492,8 @@ After destroy: listeners registered with `on()` stay attached and can still fire | profile save delay | number | `5000` ms | `runtime.ts` -> `saveProfilesSoon` | Delay of the single pending profile write (the first request schedules it; later ones are ignored until it runs). | | rate-warning throttle | number | `60000` ms | `runtime.ts` -> `onDecision` | Rate-limit status report at most once a minute. | | budget scale | number | start `1`, `× 0.8` per `max_tokens_exceeded`, floor `0.5` | `runtime.ts` constructor | Shrinks the automatic situation budget. | -| `situationBudget()` "auto" | number | WebGPU or unknown device: `STATE_CHAR_BUDGET` = 3200; WASM: `1000 + round((threads - 1) × 1000 / 3)` with threads clamped to 1..4 (1000, 1333, 1667, 2000); then `× budgetScale`, rounded | `runtime.ts` -> `situationBudget` | Size of situation text (`budget`). A numeric `situation.budget` is returned unchanged. | -| `STATE_CHAR_BUDGET`, `COMPACT_BUDGET` | number | `3200`, `1100` | `situation/serialize.ts` | Full and compact section limits. Compact questions at budget `<= 1400` (`COMPACT_QUESTIONS_BUDGET`, `situation/questions.ts`). | +| `situationBudget()` "auto" | number | WebGPU or unknown device: `STATE_CHAR_BUDGET` = 2400 (≈ 1,000 tokens at the measured 2.4 chars/token; was 3200 in situation-v1); WASM: `1000 + round((threads - 1) × 1000 / 3)` with threads clamped to 1..4 (1000, 1333, 1667, 2000); then `× budgetScale`, rounded | `runtime.ts` -> `situationBudget` | Size of situation text (`budget`). A numeric `situation.budget` is returned unchanged. | +| `STATE_CHAR_BUDGET`, `COMPACT_BUDGET` | number | `2400`, `1100` | `situation/serialize.ts` | Full and compact section limits (full at `>= 2400`, linear in between). Compact questions at budget `<= 1400` (`COMPACT_QUESTIONS_BUDGET`, `situation/questions.ts`). | | historySize floor | number | `16` | `trace/events.ts` -> `EventLog` | Minimum ring-buffer size. | | `MAX_OPS` / `KEEP_OPS` | number | `2000` / `1500` | `trace/ops.ts` | Op registry pruning (in-flight ops kept); `PluginApi.endOp` on a pruned id is a no-op. | | `STRINGIFY_CAP` | number | `65536` | `util.ts` | Default cap of `stableStringify`. | @@ -482,18 +519,19 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants | `ratio(a, b)` | `"∞"` when `b <= 0`; `"12×"` when `>= 10`; else `"1.5×"`. | | `plural(n, one, many?)`, `ordinal(n)` | `"3 items"`; `"1st"`, `"12th"`, `"23rd"`. | | `words(s)` | Split camelCase / snake_case / kebab-case / spaces, lowercased. | -| `isSensitiveName(name)` | True if any word is in `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or a pair in `SECRET_PAIRS` (card number/num/no/cvc/cvv/code/security, credit card, cc number/num/no/exp/csc, api key/secret, private key, access key, secret key, session id/token/key, security code, one time, social security). `"author"`, `"cards"`, `"passengers"`, a kanban `"card"` are not secrets. | -| `defaultRedact(path, value)` | `"[redacted]"` if any dot-separated segment `isSensitiveName`, else `value`. | -| `describe(v, path, redact, max = 80)` | One-line value summary used in situations (strings 48 chars top-level, 24 nested; arrays show at most 3 items, e.g. `"5 items [a, b, c, …]"` (the `, …` only when items were left out); objects list id-like keys first: `id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`). | +| `isSensitiveName(name)` | Results memoised in a module-level `Map` (cleared when it exceeds 4,096 names). True if any word is in `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or a pair in `SECRET_PAIRS` (card number/num/no/cvc/cvv/code/security, credit card, cc number/num/no/exp/csc, api key/secret, private key, access key, secret key, session id/token/key, security code, one time, social security). `"author"`, `"cards"`, `"passengers"`, a kanban `"card"` are not secrets. | +| `isSensitivePath(path, value?)` | New in batch 4/5. Decides by the **leaf** field, never by a store or container name alone: `null`/`undefined`/booleans never; non-path free text (e.g. `'input "Card number"'`) -> `isSensitiveName` of the whole text; numeric segments skipped (`users.3.password`); plain objects never redacted whole; leaf `isSensitiveName`, or a secret pair across the last two segments (`payment.card.number`); otherwise, for string/number values, under a container that names a secret, strings are secrets (`credentials.password.value`), and under a broad container (`auth`, `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: >= 20 chars, letters and digits, no spaces). `auth.loading`, `auth.user.name` are not secrets. | +| `defaultRedact(path, value)` | `"[redacted]"` if `isSensitivePath(path, value)`, else `value` (was: any segment `isSensitiveName`). | +| `describe(v, path, redact, max = 80)` | Compares the redactor's result with `Object.is` (ad24804: `!==` recursed forever on `NaN`). One-line value summary used in situations (strings 48 chars top-level, 24 nested; arrays show at most 3 items, e.g. `"5 items [a, b, c, …]"` (the `, …` only when items were left out); objects list id-like keys first: `id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`). | | `isIdSegment(seg)` | Digits, UUID, long hex (>= 8 with a digit), long token (>= 16 with letters and digits), conservative slug ids (`tasks-1cam`, `x7k2p`, `PPBqWA9`; not `sha256`, `oauth2`, `v1beta1`). | | `normalizePath(p)` | Id segments (after `decodeURIComponent`) -> `:id`. | | `normalizeFieldPath(p)` | Store path segments after the first that are ids or contain a digit -> `:id` (transition profiles). | -| `parseUrl(raw, base)` | `{ href, where, search, sameOrigin }`; `where` is the pathname (same origin) or `host + pathname`; base defaults to `http://localhost/`. | +| `parseUrl(raw, base)` | `{ href, where, search, sameOrigin }`; `where` is the pathname (same origin) or `host + pathname`; base defaults to `http://localhost/`. `ws:`/`wss:` URLs on the page's host count as same-origin. | | `requestSignature(method, where)` | `"GET /api/items/:id"` (the **op signature**). | -| `redactSearch(search, redact, max = 60)` | Query string (input capped at 4096 chars) with values whose `query.<key>` path is redacted replaced by `[redacted]`, truncated. | +| `redactSearch(search, redact, max = 60)` | Query string (input capped at 4096 chars) with values whose `query.<key>` path is redacted (not `Object.is`-equal) replaced by `[redacted]`, truncated. | | `type Redactor` | `(path: string, value: unknown) => unknown`: the shape of `InitOptions.redact` and `defaultRedact`. | | `interface ParsedUrl` | `{ href; where; search; sameOrigin }`, returned by `parseUrl`. | -| `REDACTED`, `IDEMPOTENT_METHODS` | Exported constants (values in the table above). `STRINGIFY_CAP`, `SECRET_WORDS`, `SECRET_PAIRS`, `ID_KEYS` and the id regexes are module-private. | +| `REDACTED`, `IDEMPOTENT_METHODS` | Exported constants (values in the table above). `STRINGIFY_CAP`, `SECRET_WORDS`, `SECRET_PAIRS`, `WEAK_CONTAINER`, `OPAQUE`, `PATH_LIKE`, `ID_KEYS`, the name cache and the id regexes are module-private. | `fmtNum` returns `String(n)` for non-finite numbers (`"NaN"`, `"Infinity"`). `stableStringify` prints an invalid `Date` as `"Invalid Date"` and slices any single string longer than the cap before quoting. `describe` nests at most two levels (`{N keys}` deeper, nested arrays as `[N]`, `Map(N)`, `Set(N)`) and appends `, +N` for keys that did not fit. @@ -515,12 +553,15 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants - **`inflight()` returns live `OpRec`s**; `situation()` returns the cached object for that trigger. Treat both as read-only. - **`atom(name)` reuse vs replacement.** Same name and kind `atom` reuses the store and ignores `initial`; `guard`/`adapter` (or `atom` over a non-atom store) replace the store and lose its field history. - **Determinism (CONTRACT §0 rule 3).** Inside `packages/runtime/src` no `Math.random`, `Date.now`, `performance.now` or global `setTimeout`/`setInterval`: use `this.clock` (or `api.clock` in plugins). Ids come from counters (`d<n>`, `a<n>`, `uniq:<n>`, op ids, event `seq`). The only `performance.now` uses are `clock.ts` and a default in `model/engine.ts` that `model/backend.ts` overrides with the injected clock (`now: () => this.env.clock.now()`). Exception outside the decision path: the devtools overlay (`src/devtools/index.ts`, owned by UI) captures the raw global `setTimeout` and `requestAnimationFrame` at module load for its own rendering. The model host's idle preload (`src/model/host.ts` -> `scheduleIdle`) also calls the global `requestIdleCallback`/`cancelIdleCallback` directly. None of these reaches situation text. `budget.test.ts` and `situation.test.ts` assert byte-identical situations for identical inputs. -- **Every timer the runtime arms must be cleared in `destroy()` or be harmless when it fires afterwards.** `destroy()` clears `settleTimer`, `persistTimer` and the reporter's de-dup windows. Hold-budget, stall and queue-dispatch timers are left to fire: `passive()` is idempotent, `watchStall` checks `destroyed`, and `trigger()`'s answer handler runs passive when `destroyed`. +- **Every timer the runtime arms must be cleared in `destroy()` or be harmless when it fires afterwards.** `destroy()` clears `settleTimer`, `persistTimer` and the reporter's de-dup windows. Hold-budget, stall and queue-dispatch timers are left to fire: `passive()` is idempotent, `watchStall` checks `destroyed`, and `trigger()`'s answer handler runs passive when `destroyed`. The batch-4 delivery timers are also left to fire: the `BODY_WAIT_MS` timer in `runDelivery` (it then decides without the body; `trigger` fails open because not consultable, and the body callback checks `destroyed`) and the `LONG_RUNNING_MS` cap in `waitOps` (a `defer` re-runs `runDelivery`, which releases at once when destroyed). Every delivery path is designed to end in `release()` (guarded by a per-call `released` flag), so a response or message is never swallowed; keep that property when you add a delivery action. A `defer` re-enters `runDelivery` with the same `release`, under a fresh flag (whether a failing `defer` effect can release twice is unverified; the fetch/XHR `release` callbacks would need to tolerate it). - **Captured natives.** `browserClock` captures timers and `index.ts` captures `fetch` at module evaluation. If another library patched `fetch` earlier, the model host downloads through that patch. Keep these captures at module top level; moving them into functions would make the runtime observe itself (its own timers through the timers observer, its model download through the fetch observer). -- **Parity and the `situation-v1` freeze.** `util.ts` formatting (`secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `normalizePath`, `isIdSegment`, `isSensitiveName`, `defaultRedact`) and the default `vocabulary` feed the text the model reads. The tag `situation-v1` froze it; `git diff situation-v1 HEAD -- packages/runtime/src` is empty at 654d822. Changing any of these requires SIM/TRAIN coordination and regenerated data ([model-io-contract.md](../model-io-contract.md)). +- **Parity and the `situation-v2` freeze.** `util.ts` formatting (`secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `normalizePath`, `isIdSegment`, `isSensitiveName`, `isSensitivePath`, `defaultRedact`), `STATE_CHAR_BUDGET` and the default `vocabulary` feed the text the model reads. The tag `situation-v2` (6e5e86e) froze it; `git diff situation-v2 b435acb -- packages/runtime/src` touches only `devtools/index.ts` (labels), `runtime.ts` (the `o.mode` default) and `types.ts` (JSDoc), none of which reaches situation text (mode is not part of the situation). SIM is generating situation-v2 data on the Azure cluster now (training/NEEDS.md); changing any of these invalidates that data. Coordinate with SIM/TRAIN first ([model-io-contract.md](../model-io-contract.md)). `situation-v1` (tag at 1a77558, same `src` as 654d822) is superseded. +- **Default mode is `observe`, but the test harness is `guard`.** `test/helpers.ts` -> `setup` defaults `mode: "guard"`; `smoke.test.ts`, `test/browser/ui/session.ts` and `review-fetch.test.ts` -> `headless()` pass `mode: "guard"` explicitly. A new test that expects interventions from `createRuntime` (not `setup`) must pass `mode: "guard"`; a test of the product default uses `setup({ mode: undefined })` as `default-mode.test.ts` does. +- **Writes are not held by default (even in guard).** With `policy.holdWrites` false, `mayHold` is false and `atom().set` / adapter `propose` apply in the caller's stack; a model `discard` of a `mutation` can only late-revert under the strict rules (within `LATE_REVERT_MS`, nothing overwrote it). Tests that rely on held writes set `policy: { holdWrites: true }` (`atoms.test.ts`, adapter tests; `MockRuntime` has its own `holdWrites` flag). +- **The sim's observer map omits `eventsource`.** `sim/src/run/rt.ts` -> `createOptions` passes an explicit `observe` map without `eventsource`, so the EventSource observer defaults on in sim runs. `installEventSource` returns `null` when `global.EventSource` is not a function, and nothing under `sim/src` mentions `EventSource`, so today it is a no-op there; if the sim ever adds an `EventSource` to its fake global, decide explicitly whether to observe it. The unit-test harness (`test/helpers.ts` -> `setup`, `review-fetch.test.ts` -> `ONLY_FETCH`) has the same gap. - **The model seam is shared.** The first section of `types.ts` is co-owned by MODEL, and `sim/src/types.ts` mirrors it structurally. Change all three together. - **Fail-open everywhere.** Not consultable, provider error, deadline missed, queue overflow, destroyed: the passive action runs. Never introduce a path where a missing answer blocks the app. -- **Option resolution is one-shot.** `policy`, `triage`, `vocabulary`, `settleMs`, `redact`, `report` (except via `setReport`) and `observe` are read in the constructor; only `mode` (via `setMode`) and pause state change afterwards. +- **Option resolution is one-shot.** `policy` (including `holdWrites`), `triage`, `vocabulary`, `settleMs`, `redact`, `report` (except via `setReport`) and `observe` are read in the constructor; only `mode` (via `setMode`) and pause state change afterwards. ## How to change it safely @@ -528,8 +569,8 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants 1. Add the field with a JSDoc default to `InitOptions` (or `CreateOptions` if headless-only) in `packages/runtime/src/types.ts`. 2. Read it once in `RuntimeImpl`'s constructor with an explicit default (`o.x ?? default`). Never read options lazily from `o` later. 3. Check the four creation paths in `index.ts` (`initUnsafe` browser, non-browser, kill-switch `off`, fallback) and decide whether the option should survive each. -4. If it changes situation text or decisions, coordinate with SIM (`sim/src/run/rt.ts` -> `createOptions`) and record it in `docs/runtime/API.md`. -5. Add a test using `setup({ ...option })` from `test/helpers.ts`; run `vitest run --exclude "test/browser/**"` in `packages/runtime`, locally or on the VM (`scripts/vm.sh run <slot> '...'`); see [build-test-release.md](build-test-release.md#where-to-run-things) for where to run what. +4. If it changes situation text or decisions, coordinate with SIM (`sim/src/run/rt.ts` -> `createOptions`) and record it in `docs/runtime/API.md`. A boolean that only tunes an observer (like `observe.untrustedEvents`) can ride in the `observe` map: widen the `observe` type in `types.ts` and read it with `on("<key>", false)` in `installObservers`; keep it out of `ObserverName` so `ALL_OFF` does not need it. +5. Add a test using `setup({ ...option })` from `test/helpers.ts` (remember it defaults to `mode: "guard"`); run `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in `packages/runtime` (light unit tests are fine on a 16 GB dev machine; HANDOFF.md's "never on the Mac" rule is about the colleague's 8 GB Mac), then `review-perf.test.ts` alone; CI (`.github/workflows/ci.yml`) runs the same split. See [build-test-release.md](build-test-release.md#where-to-run-things). **Add a `Runtime` method** 1. Add it to `Runtime` in `types.ts` and implement it in `RuntimeImpl`. @@ -537,9 +578,9 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants 3. Devtools wraps runtime calls in `safe()`; keep new methods non-throwing if devtools will use them. **Change an existing `Runtime` method or option (signature or semantics)** -1. Find every caller outside `src/`: the sim's structural `RuntimeLike` (`sim/src/run/rt.ts`) calls `atom`, `user`, `reportError`, `situation`, `on`, `destroy` and optionally `decisions`, `inflight`; its `createOptions` passes `clock`, `global`, `decider`, `model: false`, `mode: "heal"`, `report: "silent"`, an explicit `observe` map, `triage: "salient"`, `policy` (`thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`), `historySize: 500`, `app`, and optionally `vocabulary`, `hooks`, `situation.budget`. The sim loads the runtime by the module name in env var `GENCLASS_RUNTIME` (default `@genclass/runtime`), so it compiles without the runtime's types: a breaking change shows up only at sim run time. +1. Find every caller outside `src/`: the sim's structural `RuntimeLike` (`sim/src/run/rt.ts`) calls `atom`, `user`, `reportError`, `situation`, `on`, `destroy` and optionally `decisions`, `inflight`; its `createOptions` passes `clock`, `global`, `decider`, `model: false`, `mode: "heal"`, `report: "silent"`, an explicit `observe` map, `triage: "salient"`, `policy` (`thresholds { report: 0, guard: 0.5, heal: 0.5 }`, `holdBudgetMs: 1e9`, `maxActionsPerMinute: 1e9`, `requireDiagnosis: false`), `historySize: 500`, `app`, and optionally `vocabulary`, `hooks`, `situation.budget`; with `production: true` (on-policy runs) `policy` is replaced by `{ holdBudgetMs: 1e9, maxActionsPerMinute: 1e9 }` (default thresholds and diagnosis gate). It never sets `holdWrites`, so sim store writes are never held (decisions on writes are background ones). The sim loads the runtime by the module name in env var `GENCLASS_RUNTIME` (default `@genclass/runtime`), so it compiles without the runtime's types: a breaking change shows up only at sim run time. 2. Also update `MockRuntime` (`test/browser/ui/mock-runtime.ts`), `ShimRuntime` (`demos/src/dev/runtime-shim/index.ts`), devtools (`src/devtools/index.ts`) and the React adapter (`src/adapters/react.ts` -> `useRuntimeList`, which calls `decisions(limit)` / `interventions(limit)`). -3. Update `docs/runtime/API.md`, the JSDoc in `types.ts` and this doc. If the change alters situation text or decisions, it breaks the `situation-v1` freeze (see Invariants). +3. Update `docs/runtime/API.md`, the JSDoc in `types.ts` and this doc. If the change alters situation text or decisions, it breaks the `situation-v2` freeze (see Invariants). **Add an event type** 1. Add the key and payload to `RuntimeEvents` in `types.ts`. @@ -552,10 +593,11 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants 3. Decide the default (`on(k)` defaults to `true`; pass a second argument like `timers` does to make it conditional). 4. Add a "destroy restores the global" assertion next to `dom.test.ts` -> "browser globals are restored by destroy()". See [observe-and-trace.md](observe-and-trace.md). -**Change a default (mode, thresholds, settleMs, historySize, budgets)** -1. Change it where it is defined (table above), then update the JSDoc in `types.ts`, `docs/runtime/API.md`, `packages/runtime/README.md`. -2. Tests pinning values: `budget.test.ts` (budgets, hold budget), `policy.test.ts`, `report.test.ts` (report line regexes include thresholds), `batch3.test.ts`. -3. Thresholds and budgets affect training/eval comparability: tell TRAIN/SIM. +**Change a default (mode, thresholds, settleMs, historySize, budgets, holdWrites)** +1. Change it where it is defined (table above), then update the JSDoc in `types.ts`, `docs/runtime/API.md`, `docs/runtime/CONTRACT.md` (§2 and a dated §13 entry for a product decision), `packages/runtime/README.md`, and devtools labels if they name the default. +2. Tests pinning values: `budget.test.ts` (budgets, hold budget), `policy.test.ts`, `report.test.ts` (report line regexes include thresholds), `batch3.test.ts`, `default-mode.test.ts` (mode), `atoms.test.ts` / `no-reorder.test.ts` / adapter tests (`holdWrites`). +3. Worked example, the mode default (f3636b2): `runtime.ts` constructor `o.mode ?? "observe"`; `types.ts` JSDoc; devtools `MODES` tooltips and mode fallback; `test/helpers.ts` -> `setup` now passes `mode: "guard"` explicitly; explicit `mode: "guard"` in `smoke.test.ts`, `test/browser/ui/session.ts` and `review-fetch.test.ts` -> `headless()` (no assertion changed); new `default-mode.test.ts`; API/ARCHITECTURE/CONTRACT §13. +4. Thresholds and budgets affect training/eval comparability: tell TRAIN/SIM. **Change the kill switch or init paths** Edit `index.ts` -> `killSwitch` / `initUnsafe`; keep everything in try/catch; update `report.test.ts` -> "GenClass.init and the kill switch" and `batch3.test.ts` -> "lifecycle". @@ -571,25 +613,30 @@ Use `this.clock.now()` / `this.clock.setTimeout` / `this.clock.afterTask`; store ## Tests -All in `packages/runtime/test/` (vitest, `environment: "node"`, `testTimeout: 20000`, `test/browser/**` excluded; `dom.test.ts` uses `// @vitest-environment happy-dom`). Most use `setup()` from `helpers.ts`: `createRuntime` with `FakeClock`, `FakeServer`, `ScriptedDecider`, `report: "silent"` and only the fetch observer on. +All in `packages/runtime/test/` (vitest, `environment: "node"`, `testTimeout: 20000`, `test/browser/**` excluded; `dom.test.ts` uses `// @vitest-environment happy-dom`). Most use `setup()` from `helpers.ts`: `createRuntime` with `FakeClock`, `FakeServer`, `ScriptedDecider`, **`mode: "guard"`**, `report: "silent"` and only the fetch observer on (its explicit `observe` map omits `eventsource`, which therefore defaults on but installs nothing: the fake global from `makeGlobal` has no `EventSource`). Lead's run on `mvp-v2` at b435acb (2026-10-08, Node v25.6.0): unit tests without `test/browser/**` and `review-perf` -> 40 files passed, 1 skipped; 332 tests passed, 14 skipped (model parity); `review-perf.test.ts` alone 4 passed (it can flake under a full parallel run: 5.5 ms vs its 2 ms bound). With the uncommitted `hub.ts` held-write fix and its new `atoms.test.ts` test, the main run becomes 333 passed + 14 skipped (347). | test file | what it asserts (scope of this doc) | |---|---| +| `default-mode.test.ts` (f3636b2) | `createRuntime` and `GenClass.init` without a mode start in `observe`; `mode: "guard"` and `?genclass=guard` opt in; in observe, a sure model (p 0.99) records `mutation`/`request` decisions and detections but nothing is held, `executed` is false and `interventions()` is empty; a model that never answers delays nothing (atom write, adapter propose, fetch, failed fetch) while it is still asked in the background. | +| `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts` (batch 4/5) | The delivery gate (salience, `discard` drop marks and undo, `defer`), body analysis (F1/F2/F3, read-your-writes), and that held writes never reorder a store's writes. Owned by [decide-policy-actions.md](decide-policy-actions.md) / [learn-situation-triage.md](learn-situation-triage.md). | +| `nan.test.ts` (ad24804) | A store holding `NaN` builds a situation without recursing (`describe` uses `Object.is`). | | `report.test.ts` | `GenClass.init` idempotent, `GenClass.runtime`, `destroy` clears it; `?genclass=off` leaves `fetch` untouched, mode `observe`, exactly one `console.info`; `?genclass=heal` overrides `mode: "guard"`; `on("decide" \| "detect" \| "act" \| "event")` order and unsubscribe; report lines and console grouping/de-dup. | | `batch3.test.ts` | Lifecycle: `ask` after destroy rejects `"destroyed"`; `createRuntime` survives read-only `fetch`; `GenClass.init` with a throwing plugin `setup` does not throw; a provider that never answers does not block later decisions; rate-limit warning once per minute. | | `review-misc.test.ts` | Init robustness on frozen globals; `ask` after destroy (`reason: "destroyed"`); console reports reach the console as `×N` summaries; queue robustness. | | `ask.test.ts` | `ask` sends trigger `ask` with question id `answer`; typed answers (`expectTypeOf`); `decide` returns the label; `about` op id / store; no decider -> `GenClassUnavailableError`, `status.state === "off"`, `ready` resolves; `timeoutMs` -> reason `"timeout"`. | | `policy.test.ts` | `setMode` switches tiers at runtime; `pause()` stops consulting, `resume()` restores; loading status fails open with no record; observe mode never holds; detection threshold. | | `plugins.test.ts` | Plugin facts/diagnoses/actions reach the model; custom action runs; `ctx.builtin`; default heal tier; `applicable`; standing questions; `setup` receives `PluginApi` (`recordOp`, `runInOp`, `emit`, `on`, `endOp`) and cleanup runs on unregister; vocabulary overrides. | -| `budget.test.ts` | `situationBudget()` "auto" values (3200 / 1000 / 1333 / 2000, threads capped at 4, unknown device 3200, fixed number wins); `max_tokens_exceeded` -> 2560; hold budget `"auto"` (300 fallback, 150..800 clamp, adapts to measured latency); determinism at a fixed budget. | +| `budget.test.ts` | `situationBudget()` "auto" values (2400 / 1000 / 1333 / 2000, threads capped at 4, unknown device 2400, fixed number wins); `max_tokens_exceeded` -> 1920 (2400 × 0.8); hold budget `"auto"` (300 fallback, 150..800 clamp, adapts to measured latency); determinism at a fixed budget. | | `situation.test.ts` | `situation()` (ask about now) is side-effect free (no ops, no events); determinism of whole runs on a fake clock. | -| `smoke.test.ts` | Minimal `createRuntime` wiring: atoms apply synchronously when nothing is salient; causality through awaits; a stale write is held and discarded in guard mode. | -| `dom.test.ts` | `destroy()` restores `fetch`, XHR `open`, `history.pushState`, `Storage.prototype.setItem`, `WebSocket`, `setTimeout`, and removes DOM listeners; `describeElement`. | +| `smoke.test.ts` | Minimal `createRuntime` wiring (explicit `mode: "guard"`): atoms apply synchronously when nothing is salient; causality through awaits; a stale **response** is held at the delivery gate, the model is asked, and its stale writes are dropped in guard mode. | +| `dom.test.ts` | `destroy()` restores `fetch`, XHR `open`, `history.pushState`, `Storage.prototype.setItem`, `WebSocket`, `setTimeout`, and removes DOM listeners; `describeElement`; synthetic (`isTrusted` false) events become user actions only with `observe.untrustedEvents`. | | `fetch.test.ts`, `xhr.test.ts`, `review-fetch.test.ts` | `destroy()` restores fetch/XHR; after destroy GenClass does no work even when another library wrapped fetch on top. | | `review-timers.test.ts` | Uses `rt.internals` to check op pruning (timer loops do not retain ops). | | `test/smoke/smoke.sh` | (VM only) packs the tarball, builds a fresh Vite app with `GenClass.init({ model: false, report: "console" })` and `mountDevtools`, loads it in headless Chromium. | -Which `initUnsafe` branch the unit tests hit: vitest runs in `environment: "node"` (no `window`), so every `GenClass.init` call in `report.test.ts` and `batch3.test.ts` goes through the **non-browser** branch (or the kill-switch `off` branch); the mode override test passes through `...(mode ? { mode } : {})` there. The **browser** branch (`o.model = options.model ?? {}`) is exercised only by `test/smoke/smoke.sh` on the VM, and only with `model: false`. +Which `initUnsafe` branch the unit tests hit: vitest runs in `environment: "node"` (no `window`), so every `GenClass.init` call in `report.test.ts`, `batch3.test.ts` and `default-mode.test.ts` goes through the **non-browser** branch (or the kill-switch `off` branch); the mode override test passes through `...(mode ? { mode } : {})` there. The **browser** branch (`o.model = options.model ?? {}`) is exercised only by `test/smoke/smoke.sh` on the VM, and only with `model: false`. + +CI (`.github/workflows/ci.yml`, b435acb) runs typecheck, build, the unit tests without `test/browser/**` and `review-perf`, then `review-perf` alone with `--retry=2`, on pushes to `main`/`runtime`/`mvp`/`mvp-v2`, pull requests and manual dispatch. It does not run Playwright, `smoke.sh`, the sim or realapps. Untested in this scope: the `localStorage.genclass` path of the kill switch, the browser branch of `initUnsafe` with a default model, the outer `catch` fallback of `GenClass.init` (the throwing-plugin test is caught inside `use`, not by the fallback), `learn.persist`, `settleMs`, `historySize`, `setReport`, `isPaused`, `createRuntime({ model: {...} })` fetch selection and `failedProvider`, and the `ask` + `timeoutMs` + load-failure path. @@ -597,8 +644,11 @@ Untested in this scope: the `localStorage.genclass` path of the kill switch, the | what | docs say | code does | evidence | |---|---|---|---| -| Auto situation budget on WASM | `types.ts` JSDoc of `InitOptions.situation`: "wasm 1,100 + 300 per extra thread up to 4 threads: 2,000" (1100/1400/1700/2000) | `1000 + round((threads - 1) × 1000 / 3)`: 1000/1333/1667/2000 | `runtime.ts` -> `situationBudget`; `budget.test.ts` asserts 1000, 1333 and 2000. API.md, ARCHITECTURE.md and STATUS.md match the code. | -| Default redaction | `types.ts` JSDoc of `InitOptions.redact`, `docs/runtime/CONTRACT.md` §2 and `packages/runtime/README.md` ("fields matching `pass\|token\|secret\|card\|cvv\|ssn\|auth`"): substring regex | Word-level meaning (`isSensitiveName`); `"card"`, `"author"`, `"cards"` are not redacted | `util.ts` -> `defaultRedact`; STATUS.md lists it as an approved deviation; API.md matches the code. | +| Default mode | HANDOFF.md "Modes: observe → guard (default; ...)"; npm `0.1.0-alpha.0` | `o.mode ?? "observe"` on `mvp-v2` (f3636b2). API.md, ARCHITECTURE.md, CONTRACT §2/§13, `types.ts` JSDoc, devtools labels and both READMEs (README.md, packages/runtime/README.md) now say observe. origin/runtime 74f17c0 itself still defaults to guard. | `runtime.ts` -> `RuntimeImpl` constructor; `default-mode.test.ts` | +| Auto situation budget (WebGPU / unknown device) | `docs/runtime/ARCHITECTURE.md` ("3,200 characters on WebGPU"), STATUS.md's older line ("webgpu 3,200", followed by "(Batch 4: webgpu and unknown device 2,400.)") | `STATE_CHAR_BUDGET` = 2400 since batch 4; WASM 1000/1333/1667/2000 unchanged. `types.ts` JSDoc (fixed in batch 4), API.md, packages/runtime/README.md and `MockRuntime.situationBudget` (2400) match the code. | `situation/serialize.ts`; `runtime.ts` -> `situationBudget`; `budget.test.ts` | +| Default redaction | `docs/runtime/CONTRACT.md` §2 (`/pass\|token\|secret\|card\|cvv\|ssn\|auth/i`) | Leaf-field rule (`isSensitivePath`): `auth.loading` and `auth.user.name` visible, `auth.token` redacted; opaque strings under `auth`/`session`/`cookie` redacted. `types.ts` JSDoc, API.md and packages/runtime/README.md were updated in batch 4/5 and match. | `util.ts` -> `isSensitivePath`, `defaultRedact` | +| `observe` option JSDoc | `types.ts`: a leftover `/** Default: all true (where the global supports them). */` sits directly above the new JSDoc on `InitOptions.observe` (two doc comments; editors show the last one) | `timers` only with a document; `eventsource` included; `untrustedEvents` default false | `types.ts` -> `InitOptions.observe`; `runtime.ts` -> `installObservers` | +| CONTRACT §2 observer list | `observe?: Partial<Record<"fetch"\|...\|"websocket", boolean>>; // default all true` | Also `eventsource`, `timers` (document-only default) and the `untrustedEvents` flag. API.md lists all of them. | `types.ts` -> `ObserverName`, `InitOptions.observe` | | Non-browser `GenClass.init` | API.md: "returns an inert runtime: no observers, no model" | Observers off and no model host, but `options.decider`, `plugins`, `policy`, `mode` are kept; `report` defaults to `"silent"` | `index.ts` -> `initUnsafe` | | `GenClass.destroy()` | API.md: "uninstall observers, restore globals, terminate the model worker" | Terminates only a host the runtime created (`ownsDecider`); a global is restored only if it is still GenClass's wrapper, otherwise the wrapper becomes a pass-through | `runtime.ts` -> `destroy`; `observe/fetch.ts` uninstall | | `rt.ready` | API.md/types.ts: "resolves when the model is ready" | Also rejects (provider error, e.g. `ModelLoadError`) on load failure, and the rejected promise is memoised | `runtime.ts` -> `get ready` | @@ -606,7 +656,6 @@ Untested in this scope: the `localStorage.genclass` path of the kill switch, the | `on("status")` | API.md: "model loading progress and state" | Also fired by every `setMode` call | `runtime.ts` -> `setMode`; devtools relies on it | | `pause()` | API.md: "stops consulting the model" | Triggers stop, but `ask()`/`decide()` still query the model while paused | `runtime.ts` -> `ask` has no `paused` check | | `ModelOptions` | API.md options block lists `baseUrl`, `device`, `worker`, `preload` | Also `ortWasmPaths` and `cacheName` | `types.ts` -> `ModelOptions` | -| Default observers | `types.ts`: "Default: all true (where the global supports them)"; CONTRACT §2 `observe` list omits `timers` | `timers` defaults on only when `global.document` is a non-null object; all others default on | `runtime.ts` -> `installObservers` | | Hold budget fallback | API.md / `types.ts` describe only `clamp(1.5 × median, 150, 800)` | 300 ms when no latency sample and no `warmupMs` | `decide/policy.ts` -> `holdBudget`, `HOLD_FALLBACK_MS` | | `situation(trigger)` | CONTRACT §13: side-effect free | Returns the last situation built for that trigger when there is one; building caches `op.reads` | `runtime.ts` -> `situation`, `build`; acknowledged in STATUS.md "Deviations" | | Runtime surface | CONTRACT §2 `Runtime` | Also `mode`, `adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")` | STATUS.md "Extra public surface" acknowledges all of these except `mode`, which neither CONTRACT §2 nor STATUS.md lists | @@ -615,15 +664,16 @@ Untested in this scope: the `localStorage.genclass` path of the kill switch, the | `EvaluateRequest.priority` | `types.ts` JSDoc: "held writes/requests use 2, background 0" | Background triggers use 1 (`stall`, `inconsistency`, XHR `failure`, `ask`) or 0 (`transition`, `error`); a holdable trigger that does not wait is capped at 1 | `runtime.ts` -> `trigger`; see [Events](#events-runtimeevents) | | `RuntimeImpl.setReport` | JSDoc: "Report sink for a custom destination at runtime (devtools)" | No caller anywhere in the repo (devtools does not use it) | `git grep setReport` | | API.md shapes | `Situation` listed as `{ trigger, subject, state, questions, actions, salient, facts }`; `Op` without `meta` | `Situation` also has `compact` and `budget`; `Op` also has `meta` | `types.ts` -> `Situation`, `Op` | -| README observers | "Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are observed automatically" | Also `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | +| API.md observers | "The DOM, fetch, XHR, WebSocket and timers are observed automatically" (packages/runtime/README.md now lists them all) | Also `eventsource` (batch 4), `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | | Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | -| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr, so a default `init()` ends in status `error` until it is published (unverified whether the URL is live). The CLI's default source is a different URL (GitHub release `runtime-model-v0.1.0`). | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; OPEN_TASKS.md item 8 | +| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and the CLI's `DEFAULT_FROM` at the GitHub release `runtime-model-v0.1.0`; both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 9 | +| npm `0.1.0-alpha.0` vs this branch | npm "latest" | The published alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. OPEN_TASKS.md "Needs the user" lists a `0.1.0-alpha.1` patch for the NaN fix that needs the owner's 2FA; the release procedure is [RELEASE.md](../../../RELEASE.md). | `npm view @genclass/runtime` (per the lead, 2026-10-08); `nan.test.ts` | | Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | | `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a<n>` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | | Init with malformed `plugins` | `GenClass.init` "never throws" | It does not throw, but a non-iterable `plugins` / `plugin.actions` / `plugin.questions` throws inside `RuntimeImpl`'s constructor after the observers were installed; the fallback inert runtime is returned while the first instance's wrappers stay on the globals | `runtime.ts` -> constructor, `use`; `index.ts` -> `GenClass.init` | | `decisions(0)` / `interventions(0)` | | Return the whole buffer (`slice(-0)`), while `history(0)` returns `[]` | `runtime.ts` | -Open items from OPEN_TASKS.md relevant here: publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) and then `@genclass/runtime@0.1.0` without the alpha tag; add a CI workflow (build, typecheck, unit tests); write honest results into the READMEs. Until the model ships, `GenClass.init()` observes and records but never acts. +Open items relevant here (OPEN_TASKS.md, HANDOFF.md, training/NEEDS.md): the model path is 150M teacher on situation-v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) -> rerun the demos -> publish `@genclass/runtime@0.1.0` without the alpha tag. SIM is currently generating situation-v2 data on the Azure cluster, plus real-browser gold rows from `realapps/` ([../realapps.md](../realapps.md)). OPEN_TASKS.md item 12 (CI) is done on `mvp-v2` (b435acb); the `npm pack` smoke test in a fresh Vite app is not in CI. Why writes are no longer held (commit fcd1e68): store-write holds reordered in-app writes (held echoes overwrote newer user writes, read-after-write broke) and broke the unmodified RealWorld React/Redux app even with an always-passive model; the related "hold-induced harm" in the v0.1 demos is recorded in RESULTS.md §5 and OPEN_TASKS item 10 (demo rerun). Demo numbers with a v2 model are not measured yet. Until a v2 model ships, `GenClass.init()` observes and records but never acts (and with the observe default it would not act even with a model unless `mode: "guard"` is set). ## Related docs @@ -635,7 +685,8 @@ Open items from OPEN_TASKS.md relevant here: publish `@genclass/runtime-model@0. - [devtools.md](devtools.md): devtools overlay (consumer of this API) - [build-test-release.md](build-test-release.md): build, tests, VM workflow, publishing - [../overview.md](../overview.md#3-runtime-data-flow-end-to-end): end-to-end data flow and the stale-write walkthrough -- [../model-io-contract.md](../model-io-contract.md): situation text -> model -> answers; `situation-v1` +- [../model-io-contract.md](../model-io-contract.md): situation text -> model -> answers; `situation-v2` - [../sim.md](../sim.md): how the sim drives `createRuntime` deterministically +- [../realapps.md](../realapps.md): the real-browser corpus and harness (uses `observe.untrustedEvents`) - [../status-and-known-issues.md](../status-and-known-issues.md), [../glossary.md](../glossary.md), [../playbooks.md](../playbooks.md), [../README.md](../README.md) -- Original sources: [docs/runtime/API.md](../../runtime/API.md), [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [packages/runtime/README.md](../../../packages/runtime/README.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md) +- Original sources: [docs/runtime/API.md](../../runtime/API.md), [docs/runtime/CONTRACT.md](../../runtime/CONTRACT.md), [docs/runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md), [packages/runtime/README.md](../../../packages/runtime/README.md), [packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md), [docs/runtime/RESULTS.md](../../runtime/RESULTS.md), [OPEN_TASKS.md](../../../OPEN_TASKS.md), [HANDOFF.md](../../../HANDOFF.md), [RELEASE.md](../../../RELEASE.md) diff --git a/docs/agents/runtime/state-and-adapters.md b/docs/agents/runtime/state-and-adapters.md index 90422f9f..28113c37 100644 --- a/docs/agents/runtime/state-and-adapters.md +++ b/docs/agents/runtime/state-and-adapters.md @@ -1,39 +1,43 @@ # @genclass/runtime: state stores, mutation pipeline, invariants and framework adapters -> **Scope:** `packages/runtime/src/state/hub.ts`, `packages/runtime/src/state/fields.ts`, `packages/runtime/src/state/invariants.ts`, `packages/runtime/src/adapters/{react,redux,zustand}.ts`, and the store-related parts of `packages/runtime/src/runtime.ts` (`atom`, `guard`, `adapter`, `expect`, `gateMutation`, `waitRelated`, `onApplied`, settled points, rollback, chain revert, resync, pause/resume/destroy gating). -> **Read this when:** you change how state is registered, flattened, diffed, held, applied, patched, reverted or snapshotted; add or tune an invariant template; touch the React hooks, the Redux enhancer or the Zustand middleware; integrate another state library through `runtime.adapter`; debug "why was this write held / applied / dropped / not reverted"; or debug a missing or spurious `inconsistency` trigger. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/state/hub.ts`, `packages/runtime/src/state/fields.ts`, `packages/runtime/src/state/invariants.ts`, `packages/runtime/src/adapters/{react,redux,zustand}.ts`, and the store-related parts of `packages/runtime/src/runtime.ts` (`atom`, `guard`, `adapter`, `handle` (read-your-writes), `expect`, `gateMutation`, `observeWrite`, `covered`, `mutationController`, `dropFilter`/`writtenOver`/`onDropped` (delivery `discard` at the store), `markWrites`/`onChannel` (stale marks), `waitRelated`, `onApplied`, settled points, rollback, chain revert, resync, pause/resume/destroy gating). +> **Read this when:** you change how state is registered, flattened, diffed, held, applied, filtered, patched, reverted, marked or snapshotted; add or tune an invariant template; touch the React hooks, the Redux enhancer or the Zustand middleware; integrate another state library through `runtime.adapter`; debug "why was this write applied / dropped / reverted / held (with `holdWrites`)"; or debug a missing or spurious `inconsistency` trigger. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - Every store lives in one `StoreHub` (`packages/runtime/src/state/hub.ts` -> `StoreHub`), keyed by a **store name** that is global per runtime. There are three kinds: `atom` (GenClass owns the value), `guard` (the app owns the value behind `get`/`set`/`subscribe`), and `adapter` (a state library owns it and the adapter commits writes). The React hooks use atoms. The Redux enhancer and the Zustand middleware use `runtime.adapter`. -- A store value is **flattened** into dotted fields: `store.key.sub`, at most 4 key levels below the store name. A plain object is expanded only when it has 1 to 32 keys and expanding it keeps the store within 200 fields (a per-object check, so the cap is soft: see "Paths and leaves"). Arrays, plain objects with more than 32 keys, and non-plain objects are one field each. Each field has a version, its last writer op, a 16-entry history that keeps values, and a 512-entry write log. -- Every `set`/`dispatch` becomes a **proposal** (`MutationRec`), except Redux no-op dispatches, Zustand `set` calls made while the store is being created, and any write after `destroy()`. It is previewed, diffed against the stored leaves, and then either **bypasses** the pipeline (applied at once, in the caller's stack) or joins the store's FIFO queue and goes through the `mutation` **trigger**. -- These writes bypass: **user-sync** writes (made in the user handler's task; `policy.holdUserWrites` defaults to false), writes made by GenClass's own ops, stores registered with `hold: false`, any write while the runtime is paused or destroyed, no-op writes, and in-place updaters that cannot be detached. -- A queued write is **held** only when the trigger is salient, the model is ready, the mode is not `observe`, and some non-passive action is permitted. Otherwise the gate answers "apply" synchronously. Queued writes to one store apply in proposal order, so a write the gate cleared can still wait behind an earlier held write (bypass writes skip the queue; see Gotchas). Verdicts are `apply`, `discard` or `defer`. When the hold budget expires the write applies anyway (**fail-open**). -- At apply time a functional update **re-runs** against the current value. A value write is re-applied as a **patch** of the fields it changed (removals first). This keeps newer user input in other fields. -- **Late revert:** a `discard` that arrives after a fail-open apply reverts exactly that write. All of these must hold: at most 2,000 ms have passed since it applied, none of its fields changed since, and the same causal chain wrote nothing after it. -- Every applied change emits a `state` event and calls `HubHooks.applied` (`RuntimeImpl.onApplied`). That updates `storeWriters` and the transition-profile accumulators, notes the changed paths for the invariant miner, and (re)schedules a **settled point**, which is debounced by `settleMs` (60 ms). -- At a settled point (no op younger than 10 s in flight and no pending write), `InvariantMiner.observe` runs the 9 templates. A newly violated learned invariant raises one `inconsistency` trigger per episode. A consistent **snapshot** (up to 8 kept) is recorded whenever nothing newly broke. -- **App errors:** if the app's setter, reducer or subscriber throws on the synchronous path, the error reaches the `set()` caller just as it would without GenClass (subscriber errors are the exception: they are always reported, never thrown). If it throws later, when GenClass applies a held write, the error is reported through `reportError`, which raises an `error` trigger, and the store's queue keeps draining. -- **Parity:** flattening, hashes, deltas and `changeText` feed the situation text, so changing them changes training data (freeze tag `situation-v1`). This scope has not changed since that tag. +- A store value is **flattened** into dotted fields: `store.key.sub`, at most 4 key levels below the store name. A plain object is expanded only when it has 1 to 32 keys and expanding it keeps the store within 200 fields (a per-object check, so the cap is soft: see "Paths and leaves"). Arrays, plain objects with more than 32 keys, and non-plain objects are one field each. Each field has a version, its last writer op, a 16-entry history that keeps values, a 512-entry write log, and (situation-v2) an optional **stale mark**. +- Every `set`/`dispatch` becomes a **proposal** (`MutationRec`), except Redux no-op dispatches, Zustand `set` calls made while the store is being created, and any write after `destroy()`. It is previewed and diffed against the stored leaves. +- **Store writes are not held by default** (`policy.holdWrites`, default `false`, new in runtime batch 4). A write with changes that is not a bypass write is handed to `HubHooks.observeWrite` (`RuntimeImpl.observeWrite`: a `mutation` trigger with `hold: false`, i.e. a **background decision**, skipped when a delivery decision already **covers** the write) and is then applied **at once, in the caller's stack**. `set(x); get()` returns x. Default mode is now `observe` too (our commit f3636b2), where no action ever runs. +- In the default path a gate-passing `discard` from the background decision becomes a **late revert** of exactly that write, under the strict rules: decided at most 2,000 ms after it applied, none of its fields changed since, and the same causal chain wrote nothing after it. A `defer` is recorded only (nothing to hold). Background decisions have a 5,000 ms deadline. +- **Delivery `discard` acts at the store.** When the model chose `discard` for a response or push message (the `delivery` trigger, see [decide-policy-actions.md](decide-policy-actions.md)), the delivered op gets a **discard mark** for 10 s. `StoreHub.propose` asks `HubHooks.filter` (`RuntimeImpl.dropFilter`) which changes of each write in that chain land over newer data and drops exactly those; the rest of the write applies (`HubHooks.dropped` -> an `action`/`dropped` event and `ActionRecord.dropped`). Exception: a write with a library `commit` (Redux dispatch, Zustand `set`) that would be only partly dropped is applied whole (fail-open, flow 12). +- With `policy.holdWrites: true` (opt-in) the old pipeline applies: a queued write goes through `gateMutation` and is **held** only when the trigger is salient, the model is ready, some non-passive action is permitted, and the expected model latency fits the hold budget; otherwise it applies synchronously. Verdicts are `apply`, `discard` or `defer`; on budget expiry the write applies anyway (**fail-open**) and a later `discard` is a late revert. New since situation-v1: any write that applies at once (user-sync, GenClass, `hold: false`, paused, no-op or unholdable) first **flushes** the store's queued and held writes in proposal order (a hold never reorders a store's writes; their pending decisions can still late-revert them), and `atom.get()` inside the writing chain returns the pending value (**read-your-writes**, `StoreHub.pendingView`). +- These writes always bypass (no trigger, applied at once): **user-sync** writes (made in the user handler's task; `policy.holdUserWrites` defaults to false), writes made by GenClass's own ops, stores registered with `hold: false`, any write while the runtime is paused or destroyed, no-op writes, and (only with `holdWrites`) in-place updaters that cannot be detached. +- Every applied change emits a `state` event and calls `HubHooks.applied` (`RuntimeImpl.onApplied`). That updates `storeWriters` and the transition-profile accumulators, sets stale marks (`markWrites`), notes the changed paths for the invariant miner, and (re)schedules a **settled point**, debounced by `settleMs` (60 ms). +- At a settled point (no op younger than 10 s in flight and no pending write), `InvariantMiner.observe` runs the **10** templates (situation-v2 added count-by-group `a == count(B[*].k == v)` and tightened `eq`/`in`: relation quality, STATUS "F8"). A newly violated learned invariant raises one `inconsistency` trigger per episode. A consistent **snapshot** (up to 8 kept) is recorded whenever nothing newly broke. +- **App errors:** if the app's updater, setter, reducer or library listener throws on the synchronous path, the error reaches the `set()`/`dispatch` caller just as it would without GenClass (listeners registered with `Atom.subscribe` are the exception: their errors are always reported, never thrown). If it throws later, when GenClass applies a held write, the error is reported through `reportError`, which raises an `error` trigger, and the store's queue keeps draining. +- **Parity:** flattening, hashes, deltas, `changeText`/`stringDiff`, stale marks and invariant texts feed the situation text, so changing them changes training data. The current freeze tag is `situation-v2` (6e5e86e); `state/*` has not changed between that tag and b435acb. The later flush-then-expiry fix (an early return in `hub.ts` -> `gateAndQueue`, flow 7 step 3) is control flow only and changes no text. ## Files | path | role | key exports / entry points | |---|---|---| -| `packages/runtime/src/state/hub.ts` | Store registry, mutation pipeline (propose, gate, queue, drain, commit, record), field versions and write logs, recent changes, late-revert primitives, snapshots, query helpers | `StoreHub`, `StoreRec`, `MutationRec`, `FieldState`, `FieldHist`, `LogEntry`, `RecentChange`, `HubHooks`, `GateResult`, `Verdict`, `toChanges`, re-export `changeText` | -| `packages/runtime/src/state/fields.ts` | Incremental flattening into leaves, hashing, diff, delta signatures, one-line change summaries, patches, deep clone | `flatten`, `leafOf`, `diffLeaves`, `deltaOf`, `multisetDiff`, `addedElements`, `elementDiff`, `changeText`, `patchValue`, `cloneValue`, `normalizeLeafKind`, `Leaf`, `FieldChange`, `MAX_DEPTH`, `MAX_FIELDS_PER_STORE`, `MAX_KEYS_EXPAND` | -| `packages/runtime/src/state/invariants.ts` | Online invariant miner over the leaves of all stores; developer `expect()` predicates | `InvariantMiner` (`noteChanged`, `noteValues`, `addExpect`, `observe`, `preview`, `current`, `learned`, `candidates`), `numEq`, `LEARN_AFTER`, `LEARN_AFTER_NONNULL` | -| `packages/runtime/src/runtime.ts` (store parts) | Public store API, the gate hook, defer waiting, applied-write bookkeeping, settled points, snapshots, inconsistency trigger, rollback, chain revert, resync | `RuntimeImpl.atom`, `.guard`, `.adapter`, `.handle` (private), `.expect`, `.gateMutation` (private), `.waitRelated` (private), `.onApplied` (private), `.scheduleSettle` (private), `.busy` (private), `.settled`, `.raiseInconsistency` (private), `.chainWrites`, `.revertChain`, `.rollback`, `.resync`, `.makeEnv` (private), `.pause`/`.resume`/`.destroy`, `.runAsGenClass`, `.reportError` (target of `HubHooks.appError`), `.pluginApi` (private; builds `PluginApi.stores { names(), get(name) }`, read-only access to every store's current value), the private fields `snaps`, `episode`, `muted`, `storeWriters`, `settleTimer`; constants `LATE_REVERT_MS`, `LONG_RUNNING_MS` | +| `packages/runtime/src/state/hub.ts` | Store registry, mutation pipeline (propose, delivery drop filter, observe-or-gate, queue, drain, commit, record), field versions, write logs and stale marks, recent changes, late-revert primitives, read-your-writes view, snapshots, query helpers | `StoreHub`, `StoreRec`, `MutationRec`, `FieldState`, `StaleMark`, `FieldHist`, `LogEntry`, `RecentChange`, `HubHooks`, `GateResult`, `Verdict`, `toChanges`, re-export `changeText` | +| `packages/runtime/src/state/fields.ts` | Incremental flattening into leaves, hashing, diff, delta signatures, one-line change summaries, patches, deep clone | `flatten`, `leafOf`, `diffLeaves`, `deltaOf`, `multisetDiff`, `addedElements`, `elementDiff`, `changeText`, `stringDiff`, `StringDiff`, `patchValue`, `cloneValue`, `normalizeLeafKind`, `Leaf`, `FieldChange`, `MAX_DEPTH`, `MAX_FIELDS_PER_STORE`, `MAX_KEYS_EXPAND` | +| `packages/runtime/src/state/invariants.ts` | Online invariant miner over the leaves of all stores (10 templates, relation-quality filters); developer `expect()` predicates | `InvariantMiner` (`noteChanged`, `noteValues`, `addExpect`, `observe`, `preview`, `current`, `learned`, `candidates`), `numEq`, `LEARN_AFTER`, `LEARN_AFTER_NONNULL` | +| `packages/runtime/src/runtime.ts` (store parts) | Public store API, the gate hook (opt-in holds), background write decisions, delivery coverage, the delivery drop filter, stale marks, defer waiting, applied-write bookkeeping, settled points, snapshots, inconsistency trigger, rollback, chain revert, resync | `RuntimeImpl.atom`, `.guard`, `.adapter`, `.handle` (private; read-your-writes `get`), `.expect`, `.gateMutation` (private), `.observeWrite` (private), `.covered` (private), `.mutationController` (private), `.dropFilter` / `.writtenOver` / `.onDropped` (private), `.markWrites` / `.onChannel` (private), `.expectedLatency` (private), `.waitRelated` (private), `.onApplied` (private), `.scheduleSettle` (private), `.busy` (private), `.settled`, `.raiseInconsistency` (private), `.chainWrites`, `.revertChain`, `.rollback`, `.resync`, `.makeEnv` (private), `.pause`/`.resume`/`.destroy`, `.runAsGenClass`, `.reportError` (target of `HubHooks.appError`), `.pluginApi` (private; builds `PluginApi.stores { names(), get(name) }`, read-only access to every store's current value), the private fields `snaps`, `episode`, `muted`, `storeWriters`, `lastChainMap`, `settleTimer`; constants `LATE_REVERT_MS`, `LONG_RUNNING_MS`, `BACKGROUND_DEADLINE_MS`, `DISCARD_MARK_MS` | | `packages/runtime/src/adapters/react.ts` | React bindings (subpath `@genclass/runtime/react`) | `GenClassProvider`, `GenClassProviderProps`, `useGenClass`, `useGenClassState`, `useAtom`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus` | | `packages/runtime/src/adapters/redux.ts` | Redux store enhancer (subpath `@genclass/runtime/redux`) | `genclassEnhancer`, `GENCLASS_REPLACE`, `GenclassEnhancerOptions` | | `packages/runtime/src/adapters/zustand.ts` | Zustand middleware (subpath `@genclass/runtime/zustand`) | `genclass` | -| `packages/runtime/src/types.ts` | Public store types | `StoreOptions`, `Atom`, `Guarded`, `StoreIO`, `AdapterIO`, `AdapterHandle`, `Change`, `RuntimeHooks.mutationProposed`, `PolicyOptions.holdUserWrites`, `InitOptions.settleMs` (inherited by `CreateOptions`) | -| `packages/runtime/src/util.ts` | Helpers used here | `isPlainObject`, `kindOf`, `hashValue` (FNV-1a over `stableStringify`, capped at 65,536 chars), `fnv1a`, `isIdSegment`, `normalizeFieldPath`, `describe` | +| `packages/runtime/src/types.ts` | Public store types | `StoreOptions`, `Atom`, `Guarded`, `StoreIO`, `AdapterIO`, `AdapterHandle`, `Change`, `RuntimeHooks.mutationProposed`, `PolicyOptions.holdUserWrites`, `PolicyOptions.holdWrites`, `InitOptions.mode` (default `"observe"`), `InitOptions.settleMs` (inherited by `CreateOptions`), `ActionRecord.late`, `ActionRecord.dropped` | +| `packages/runtime/src/decide/policy.ts` | Policy config read by the hub setup | `policyConfig` (`holdUserWrites`, `holdWrites`, both default false) | +| `packages/runtime/src/trace/ops.ts` | Per-op fields this scope reads or sets | `OpRec.delivery` (`patterns`, `known`, `salient`, `decided`, `overNewer`), `OpRec.discardMark` (`protect`, `until`, `dropped`, `onDrop`) | +| `packages/runtime/src/util.ts` | Helpers used here | `isPlainObject`, `kindOf`, `hashValue` (FNV-1a over `stableStringify`, capped at 65,536 chars), `fnv1a`, `isIdSegment`, `normalizeFieldPath`, `describe`, `truncate` | | `packages/runtime/src/trace/context.ts` | The ambient op; user-sync detection | `Context.isUserSync`, `Context.run`, `Context.stickUser` | | `packages/runtime/src/situation/facts.ts`, `packages/runtime/src/situation/build.ts` | Consumers: mutation and inconsistency facts, state lines, action applicability | `mutationFacts`, `inconsistencyFacts`, `stateLines`, `builtinApplicable` (all module-private) | -| `packages/runtime/src/situation/env.ts` | The read-only view the situation builder gets of the store layer, built by `RuntimeImpl.makeEnv` | `Violation`, `SitEnv` (store-related members: `hub`, `lastConsistent()`, `consistentBefore(seq)`, `storeWriters`, `violations()`, `previewInvariants?(m)`, `resyncable(store)`, `chainWrites(op)`, `writable(store)`; the optional `writtenByChain?` is not set by `makeEnv`), `ChainWriteInfo { path, count, lastIsChain, before?: { value, removed } }` | +| `packages/runtime/src/situation/evidence.ts`, `packages/runtime/src/situation/content.ts`, `packages/runtime/src/situation/conflicts.ts` | Consumers added in situation-v2: stale-mark facts; diff-centred string previews in content facts; predicted write sets and conflicts used by delivery coverage | `markFacts` (reads `FieldState.mark`), `stringDiff` users in `content.ts`, `predictedWrites`, `matchFields`, `conflictsOn` | +| `packages/runtime/src/situation/env.ts` | The read-only view the situation builder gets of the store layer, built by `RuntimeImpl.makeEnv` | `Violation`, `SitEnv` (store-related members: `hub`, `lastConsistent()`, `consistentBefore(seq)`, `storeWriters`, `violations()`, `previewInvariants?(m)`, `resyncable(store)`, `chainWrites(op)`, `writable(store)`, `lastChain(sig)` (reads `lastChainMap`); the optional `writtenByChain?` is not set by `makeEnv`), `ChainWriteInfo { path, count, lastIsChain, before?: { value, removed } }` | | `packages/runtime/package.json`, `packages/runtime/tsup.config.ts` | Subpath exports `./react`, `./redux`, `./zustand`; `react`/`redux`/`zustand` are optional peer dependencies (`>=18`, `>=4`, `>=4`) and tsup externals | - | The state modules are **not** exported from the package index. Tests reach them through `RuntimeImpl.hub` / `.miner` (public readonly fields) or `RuntimeImpl.internals` (`RuntimeInternals { hub, ops, events, base, profiles, miner, ctx, clock }`), which is not part of the public `Runtime` type. @@ -59,7 +63,7 @@ interface AdapterIO<T> { get(): T; set?(v: T): void; subscribe?(fn: () => void): interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) => T; value?: T; commit: (next: T) => void }): void; dispose(): void } ``` -- `resync` lets the `resync` action reload this store. `describe` replaces the store's value in state lines with one line (`packages/runtime/src/situation/build.ts` -> `stateLines`). `hold: false` means writes are traced but never held. +- `resync` lets the `resync` action reload this store. `describe` replaces the store's value in state lines with one line (`packages/runtime/src/situation/build.ts` -> `stateLines`). `hold: false` means writes are traced but bypass the pipeline (no `mutation` trigger, never held). ### Paths and leaves (`packages/runtime/src/state/fields.ts`) @@ -102,13 +106,15 @@ interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) - Array, same length: no differing position gives `N items, unchanged`. If the multiset is unchanged, the result is `N items, reordered`. When K differing positions number at most `max(1, N/2)`, the result is `N items, K changed: <elementDiff of the first>`, plus `, and K-1 more` when K > 1. Otherwise the full `before → after` text is used when it fits in 90 chars, else `N items, K changed`. - Array, length changed: the full text if it fits in 70 chars, else `B → A items: added <first> and K more; removed N items`. - Collection: `B → A entries: added k: …; changed k: {…}; removed k1, k2 and K more`. + - Two strings, neither changed by the redactor, at least one longer than 30 chars (new in situation-v2): the **diff-centred** preview from `stringDiff(before, after)`. It finds the common prefix and suffix, shows both sides from 14 chars before the first difference in a 30-char window (with `…` markers), and names the edit: `removes "…"`, `inserts "…"` or `replaces "…" with "…"` (each at most 28 chars). Example: `"…sword shield market lib" → "…sword shield" (removes " market lib")`. `situation/content.ts` uses `stringDiff` too, for response-versus-current text. - Anything else: `<before> → <after>`, each part described in at most 36 chars. ### Field state, write logs, recent changes (`hub.ts`) | type | fields | bound | |---|---|---| -| `FieldState` | `path, v` (version, starts at 0), `writer` (op id or null), `t, seq` (global seq of last write), `hist: FieldHist[], log: LogEntry[]` | one per path ever seen (fields are created at registration for the initial leaves and on first write) | +| `FieldState` | `path, v` (version, starts at 0), `writer` (op id or null), `t, seq` (global seq of last write), `hist: FieldHist[], log: LogEntry[]`, `mark?: StaleMark` | one per path ever seen (fields are created at registration for the initial leaves and on first write) | +| `StaleMark` (situation-v2, STATUS "F9") | `t`, `op` (op id or null), `why` (a clause such as `by the response to GET /x (#6), which was delivered over newer data from …`) | at most one per field; set by `StoreHub.markField`, cleared by the field's next recorded write (`record` sets `f.mark = undefined`) | | `FieldHist` | `v, seq, writer, root` (root op of the writer's chain), `user` (user-sync), `t, delta, before, after, beforeLeaf?, afterLeaf?, mutation` (MutationRec id, 0 for non-pipeline writes) | last `HIST` = 16 per field | | `LogEntry` | `seq, v, t, writer, root, user, mutation` | last `LOG` = 512 per field | | `RecentChange` | `t, seq, store, paths` (sorted, comma-joined), `key` (paths + `path=delta` pairs, sorted), `writer, root, user, mutation` | the hub keeps those within `RECENT_MS` = 10,000 ms, and at most `RECENT_MAX` = 256 | @@ -117,6 +123,7 @@ interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) - Query helpers: `field`, `versionAt`, `logSince`, `writesSince`, `changedSince`, `pending`, `allLeaves`, `valueAt`, `leaf`, `describeValue`. The path-taking lookups (`field`, `versionAt`, `logSince`, `writesSince`, `valueAt`, `leaf`) resolve a path's store by `path.split(".")[0]`; `changedSince`, `pending` and `allLeaves` iterate all stores. - `versionAt(path, seq)`: binary search of the field's 512-entry log for the last entry with `entry.seq <= seq`. If `seq` is older than the oldest kept entry it returns `log[0].v - 1` (exact only when nothing was trimmed); with an empty log it returns the current `v`; for an unknown path, 0. - `changedSince(seq)` returns `{ path, hist, count }` for every field of every store with `f.seq > seq`: `hist` is limited to the 16-entry history, `count` comes from the 512-entry log. +- **Stale marks.** `RuntimeImpl.markWrites` (called from `onApplied` for non-GenClass writers) and `RuntimeImpl.onChannel` set them; `situation/evidence.ts` -> `markFacts` turns them into a `versions` fact ("`<path>` holds a value written Xs ago `<why>`; nothing has rewritten it since.") in later situations that involve the field. See flow 13. - `FieldState` records are never deleted. A removed path keeps its `FieldState` (so `field(path)` still answers) while `leaf(path)` / `valueAt(path)` return undefined. ### `MutationRec` (one proposal) @@ -135,11 +142,13 @@ interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) | `defers` | 0, 1 or 2 | | `state` | `queued` -> `held` -> `resolved` -> `done` | | `verdict?: Verdict` | `"apply" \| "discard" \| "defer"` | -| `outcome?` | `applied`, `discarded`, `deferred` or `failed` (the app's setter threw) | +| `outcome?` | `applied`, `discarded` (a `discard` verdict, or every change removed by the delivery drop filter), `deferred` or `failed` (the app's setter threw) | | `appliedAt?`, `appliedSeq?`, `applied?` | when it applied, its global seq, and the changes actually made. Late revert uses these | | `unholdable?` | why the write could not be held | -`StoreHub.mutations` (a `Map<id, MutationRec>`, trimmed from above 512 down to 256 by deleting `done` entries) is written but never read anywhere in `src/`. +When the delivery drop filter removes only some changes, `propose` rewrites the record in place: `changes`, `leaves` and `preview` become the patched remainder, `base` stays the proposal-time value, and `fn` is deleted so the write is re-applied as a patch if the store moved. + +`StoreHub.mutations` (a `Map<id, MutationRec>`, trimmed from above 512 down to 256 by deleting `done` entries) is written but never read anywhere in `src/`. Since batch 4 only queued writes (`holdWrites` on) and defer re-proposals are put in it; bypass and default-path writes are not. ### `StoreRec` and `HubHooks` @@ -152,19 +161,22 @@ interface AdapterHandle<T> { readonly name: string; propose(w: { fn?: (prev: T) | hook | runtime implementation | purpose | |---|---|---| -| `gate(m)` | `RuntimeImpl.gateMutation` | raise the `mutation` trigger; return `{}` (apply now) or `{ held: Promise<Verdict> }` | -| `mayHold(s)` | `consultable() && mode !== "observe"` | whether a write could be held, which decides whether live state must be protected from in-place updaters | +| `gate(m)` | `RuntimeImpl.gateMutation` | only with `holdWrites`: return `{}` when not consultable or `covered(m)`; otherwise raise the `mutation` trigger with `hold: true` and return `{}` (apply now) or `{ held: Promise<Verdict> }` | +| `observeWrite?(m)` | `RuntimeImpl.observeWrite` | default path (`holdWrites` off): called just before the write commits; raises the `mutation` trigger with `hold: false`, priority 1, unless not consultable, a GenClass write, or `covered(m)`. Errors are swallowed in `propose` | +| `filter?(m)` | `RuntimeImpl.dropFilter` | the paths of this write to drop because its chain carries a live delivery discard mark (see flow 12), or null | +| `dropped?(m, dropped, applied)` | `RuntimeImpl.onDropped` | records the dropped changes on the discard mark (for `ActionRecord.dropped` and its undo) and pushes an `action` event named `dropped` | +| `mayHold(s)` | `hub.holdWrites && consultable() && mode !== "observe"` | whether a write could be held, which decides whether live state must be protected from in-place updaters. Always false by default | | `waitRelated(m)` | `RuntimeImpl.waitRelated` | for `defer`: resolves when related in-flight ops end (at most `LONG_RUNNING_MS` = 10,000 ms) | | `applied(m, s, changes, writer)` | `RuntimeImpl.onApplied` | bookkeeping plus scheduling a settled point | | `discarded(m)` | `scheduleSettle()` | - | | `proposed?(m)` | calls `CreateOptions.hooks.mutationProposed({ id, store, paths, cause?, changes })` synchronously; errors are swallowed | tracing (sim, demos) | | `appError?(e, source)` | `RuntimeImpl.reportError(e, { source })` | app code threw while GenClass applied a write later | -`mayHold` ignores its store argument: `hold: false` stores never reach it because they already bypass in `propose`. +`mayHold` ignores its store argument: `hold: false` stores never reach it because they already bypass in `propose`. `observeWrite`, `filter` and `dropped` (new in batch 4) are optional in the type, as are `proposed` and `appError`; `RuntimeImpl` always installs all of them. ### `StoreHub` surface (`packages/runtime/src/state/hub.ts` -> `StoreHub`) -Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created once in the `RuntimeImpl` constructor. `hooks` is assigned right after. +Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created once in the `RuntimeImpl` constructor. `hooks` is assigned later in the same constructor (after the decider queue, reporter and `env` exist). | member | kind | used by / purpose | |---|---|---| @@ -174,6 +186,7 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created | `mutations: Map<number, MutationRec>` | readonly field | written, never read (see below) | | `hooks: HubHooks` | field | installed by `RuntimeImpl` | | `holdUserWrites` | field, default `false` | copied from `policy.holdUserWrites` once | +| `holdWrites` | field, default `false` | copied from `policy.holdWrites` once in the `RuntimeImpl` constructor; selects the opt-in hold pipeline | | `gating` | field, default `true` | `pause()`/`destroy()` set false, `resume()` sets true | | `register(name, kind, initial, opts, io?)` / `unregister(name)` | methods | flow 1. `unregister` unsubscribes `io` and drops the snapshot cache entry; its only caller is `AdapterHandle.dispose` | | `get(name)` / `read(s)` | methods | lookup; current value (`io.get()` or `s.value`) | @@ -182,14 +195,17 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created | `write(s, next, writer, m, commit?, rethrow = false, leaves?)` | method | flow 4; also called directly by `rollback`, its undo, and post-`destroy()` writes | | `external(s)` / `record(...)` / `notify(s)` | methods | flows 8 and 4 | | `revertable(m)` / `revert(m, writer)` / `reapply(m, writer)` | methods | late revert and its undo (flow 7) | -| `restoreFields(values, writer)` | method, returns restored paths | chain revert and its undo (flow 10) | +| `flushQueue(s)` | method | `holdWrites` only: resolve every not-yet-resolved queued/held write of the store as `apply` (a write already resolved keeps its verdict) and drain, before a write that applies at once (flow 2) | +| `pendingView(s, root)` | method | `holdWrites` only: the store value with the chain `root`'s own pending writes patched on top, or undefined (read-your-writes) | +| `markField(path, mark)` | method | sets a stale mark (flow 13) | +| `restoreFields(values, writer)` | method, returns restored paths | chain revert and its undo (flow 10); undo of a delivery `discard` (flow 12) | | `snapshot()` / `allLeaves()` | methods | settled points (flow 9) | | query helpers | methods | listed above | -| `previewOf`, `restoreInPlace`, `gateAndQueue`, `drain`, `defer`, `patched`, `mid`, `snapCache` | private | pipeline internals | +| `previewOf`, `restoreInPlace`, `applyFilter`, `gateAndQueue`, `drain`, `defer`, `patched`, `mid`, `snapCache` | private | pipeline internals | ### Invariant miner (`invariants.ts`) -- A candidate (`Cand`, private) has: `id`, `tpl`, `text`, the operands `a`/`b`/`B`/`f`/`g`, `watch` (the leaf paths whose change counts as "involved"), `held` (supporting settled points), `learned`, and `typeKind`. +- A candidate (`Cand`, private) has: `id`, `tpl`, `text`, the operands `a`/`b`/`B`/`f`/`g`, `watch` (the leaf paths whose change counts as "involved"), `held` (supporting settled points), `learned`, `typeKind`, and (situation-v2) `v` (the group value of a `count` candidate), `minDistinct` and `vals` (see relation quality below). - Templates: | tpl | id | text | proposed when (on the current leaves; paths under id-like segments skipped) | holds when | @@ -197,15 +213,20 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created | `type` | `type:<a>` | `typeof a stable` | every field whose kind is not null/undefined | kind == recorded kind (null/undefined: not applicable) | | `nonnull` | `nonnull:<a>` | `a != null` | the field was never seen null/undefined, including its initial value (`nullSeen`) | value not null/undefined | | `nonneg` | `nonneg:<a>` | `a >= 0` | number > 0 | number >= 0 (null/undefined: n/a) | -| `eq` | `eq:<a>:<b>` | `a == b` | two scalars (number/string) of the same kind, equal (`numEq` for numbers), value not 0 / `""` | equal (`numEq` for numbers, else `===`) | +| `eq` | `eq:<a>:<b>` | `a == b` | two scalars (number/string) of the same kind, equal (`numEq` for numbers), value not 0 / `""`; **not** proposed when the names are unrelated and either is version-like; needs 3 distinct values when the names are unrelated | equal (`numEq` for numbers, else `===`) | | `len` | `len:<a>:<B>` | `a == len(B)` | number a (≠ 0) equals the length of a non-empty array B | `a === B.len` | | `sum` | `sum:<a>:<B>:<f>` | `a == sum(B[*].f)` | B is a non-empty array of plain objects; f is a numeric column; `numEq(a, Σf)` | same; an empty B requires a ≈ 0 | | `sumprod` | `sumprod:<a>:<B>:<f>:<g>` | `a == sum(B[*].f * B[*].g)` | as `sum`, for column pairs with `f < g` (string order) | same | -| `in` | `in:<a>:<B>:<k>` | `a ∈ B[*].k` | scalar a (not under B, not `""`/0) is a value of column k | the value is in the column set (null/undefined/`""`: n/a) | +| `in` | `in:<a>:<B>:<k>` | `a ∈ B[*].k` | scalar a (not under B, not `""`/0) is a value of column k; for a **number** a, k must be an id column (`ID_COLUMN`) or have a related name, and neither a nor k may be version-like | the value is in the column set (null/undefined/`""`: n/a) | | `unique` | `unique:<B>:<k>` | `B[*].k unique` | B has at least 2 elements and column k has no duplicates | no duplicates among non-null values | - -- **Columns** come from the first 32 keys of element 0. The numeric columns are those numeric in every element; the scalar columns are those number-or-string in every element. Each list keeps at most `MAX_COLUMNS` = 8. Per-array statistics (`sums`, `prods`, `sets`, `unique`) are cached per `Leaf` object. -- **Non-trivial** (`nonTrivial`): a candidate is created, or gains support, only when it says something. `eq` needs a non-zero, non-empty, non-false value. `len` needs n > 0. `sum`/`sumprod` need n > 0 and a ≠ 0. `in`/`unique` need n >= 2. `nonneg` needs a value > 0. +| `count` (new in situation-v2) | `count:<a>:<B>:<k>:<v>` | `a == count(B[*].k == "v")` (v JSON-encoded) | B is a non-empty array of plain objects; a finite number a (not under B, not version-like) equals the number of items whose string/boolean column k (one of the first 8 keys of element 0) has value v, the column has 2 to 8 distinct values, and the group is non-empty; needs 3 distinct values of a unless a's name relates to k or to v | a is a number and equals the count of items with `o[k] === v` (a non-number a: n/a) | + +- **Columns** come from the first 32 keys of element 0. The numeric columns are those numeric in every element; the scalar columns are those number-or-string in every element. Each list keeps at most `MAX_COLUMNS` = 8. `count` uses the first 8 keys of element 0 directly. Per-array statistics (`sums`, `prods`, `sets`, `unique`, and since situation-v2 `groups`: value -> item count per string/boolean column, via `colGroups`, null when a column has more than 8 values) are cached per `Leaf` object. +- **Non-trivial** (`nonTrivial`): a candidate is created, or gains support, only when it says something. `eq` needs a non-zero, non-empty, non-false value. `len` needs n > 0. `sum`/`sumprod` need n > 0 and a ≠ 0. `in`/`unique` need n >= 2. `count` needs n >= 2 and a > 0. `nonneg` needs a value > 0. +- **Relation quality** (situation-v2, STATUS "F8"; module-private helpers in `invariants.ts`): + - `nameWords(path)` splits the last path segment on camelCase and non-alphanumerics, lowercases, and singularises (`ies` -> `y`, trailing `s` dropped). `relatedNames(a, b)` is true when the two last segments share a word outside `GENERIC_WORDS` (`value`, `data`, `n`, `num`, `number`, `state`, `current`, `item`, `items`, `list`, ...). `versionLike(path)` is true when any word matches `VERSION_WORDS` (`version`, `revision`, `rev`, `seq`, `offset`, `page`, `cursor`, `index`, `tick`, `epoch`, `nonce`, `timestamp`, `ts`, `time`, `updated`, `created`, `at`, `ms`, ...). `ID_COLUMN` matches `id`, `_id`, `uuid`, `key`, `slug`, `code` or a name ending in `Id`/`_id`/`ID`. + - A weakly supported candidate (`eq` between unrelated names, `count` without a related name) carries `minDistinct = 3`: it is learned only when `held >= need` **and** it held over at least 3 distinct hashes of `a` (`noteDistinct` collects them in `vals` whenever it gains support). Small-number coincidences and flags rarely get there. + - Effect, asserted by `content.test.ts` "F8": `board.counts.done == count(board.items[*].lane == "done")` is learned; `board.tally.approved ∈ board.items[*].days` and `board.meta.revision == board.meta.offset` are not. - `numEq(a, b)` is true when the values are equal, or within a relative 1e-6 (scaled by `max(1, |a|, |b|)`), or when they differ by less than 0.0051 and round to the same cents. - `Violation` (`packages/runtime/src/situation/env.ts`): `{ id, text, fields, values, held, developer? }`. `values` is redacted text such as `cart.count = 4, len(cart.items) = 5`. - **Developer expectations:** `rt.expect(name, pred)` -> `InvariantMiner.addExpect`. They are evaluated at every settled point from the start. A false or throwing predicate gives `{ id: "expect:<name>", text: <name>, fields: [], values: "the predicate returned false", held: 0, developer: true }`. `expect` returns a disposer that removes only that registration; calling `expect` again with the same name replaces the earlier predicate. @@ -223,6 +244,9 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created - **Episode:** the set of violation ids at the previous settled point (`RuntimeImpl.episode`). A violation is *fresh* only when it was not violated at the previous settled point. - **Muted:** violation ids whose rollback the developer undid. They are not raised again until they hold at a settled point. - **Chain revert:** the `rollback` used for `error`/`transition` triggers. It restores only the fields the op's causal chain wrote (see flow 10). +- **Background (observed) write:** the default path. The write applies at once; its `mutation` situation is built as of the proposal and decided in the background (`hold: false`, queue priority at most 1, deadline `BACKGROUND_DEADLINE_MS` = 5,000 ms). Any action then is late: `discard` becomes a late revert, `defer` is recorded with the reason `the subject was not held (decided in the background)`. +- **Covered write** (`RuntimeImpl.covered`): walking up to 16 causes, the first op with `OpRec.delivery` decides. The write is covered when that delivery's predicted write set is known, contains every changed path (raw or normalised with `normalizeFieldPath`), and the delivery was not salient or was decided in time. A covered write raises no `mutation` trigger, unless `triage: "always"`. +- **Discard mark** (`OpRec.discardMark`): set on the delivered op when a delivery `discard` runs. For `DISCARD_MARK_MS` (10,000 ms) the writes of its chain lose the changes that land on a conflicting path (`protect`) or on a field that a user action or a newer op outside the chain wrote since the op started (`writtenOver`). ## How it works @@ -241,8 +265,8 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created - **Replaces** any existing store with the same name (whatever its kind), unsubscribing the old one. - Flattens the initial value. - Creates a `FieldState` (v 0) per leaf. -5. Atom handle (`RuntimeImpl.handle`): - - `get()` -> `hub.read(s)`. +5. Atom handle (`RuntimeImpl.handle`), also returned by `guard`: + - `get()` -> `hub.read(s)`. With `holdWrites` on and a non-empty queue, it first asks `hub.pendingView(s, root)` for the ambient op's root (a lazy op resolves to its nearest real op): inside the writing chain it returns the value with that chain's pending writes patched on top (**read-your-writes**); elsewhere the applied value. - `set(next)` -> `hub.propose(s, { fn })` or `hub.propose(s, { value })`. After destroy it calls `hub.write` directly. - `update(fn)` = `set(fn)`. - `subscribe(fn)` adds to `s.subs` and returns an unsubscribe function. @@ -251,31 +275,34 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created 1. `cause = ctx.op()` (this materialises a lazy timer op), `base = read(s)`, `userSync = ctx.isUserSync(cause)`, `genclass = !!cause?.genclass`. 2. `bypass = (userSync && !holdUserWrites) || genclass || s.opts.hold === false || !gating`. `gating` is false after `pause()` or `destroy()`. -3. `guarded = !bypass && hooks.mayHold(s)`. +3. `guarded = !bypass && hooks.mayHold(s)`. `mayHold` is false unless `holdWrites` is on, so by default nothing is guarded. 4. `previewOf(s, w, base, guarded)`: - Value write: `preview = w.value`. - Functional write: `preview = w.fn(base)`. If the write is `guarded`, the hub checks whether the updater mutated the live value in place: it flattens `base` against the stored leaves. - If it did, the preview is **detached**: `cloneValue(preview)`, then `restoreInPlace` undoes the in-place edits using the recorded `beforeLeaf` values. - If cloning or the exact restore fails, the write is marked `unholdable` ("the update changed the stored value in place, so it could not be held"). -5. `changes = diffLeaves(s.leaves, previewLeaves)`. A `MutationRec` is built and `hooks.proposed(m)` fires. This happens for bypass writes too. -6. If `changes.length === 0 || bypass || unholdable`: `commit(s, m, rethrow = true)` runs **now**, in the caller's stack, and returns. -7. Otherwise the write is pushed onto `s.queue` and `gateAndQueue(s, m)` runs. - -### 3. Gate and hold (`StoreHub.gateAndQueue` -> `RuntimeImpl.gateMutation`) - -1. If `!consultable()` (paused, destroyed, no decider, or decider status not `ready`/`off`), the gate returns `{}`: the write is resolved as `apply` and the queue drains. -2. Otherwise it builds a `Controller` and calls `RuntimeImpl.trigger({ trigger: "mutation", m }, ctl, { hold: true, priority: 2 })`. The controller's methods: - - `passive` -> verdict `apply`. - - `run("discard")` -> verdict `discard`. Its effect text is "Dropped the write to … stays at version N". Its `undo` commits the original mutation as a GenClass write. +5. `changes = diffLeaves(s.leaves, previewLeaves)`. A `MutationRec` is built and `hooks.proposed(m)` fires. This happens for every write that reaches `propose`, including bypass writes and writes the filter later drops. +6. **Delivery drop filter** (new in batch 4): if there are changes, the write is not GenClass's, and `hooks.filter` exists, `applyFilter(s, m, base)` runs (flow 12). When it drops every change the write is finished here: `outcome = "discarded"`, nothing is committed, subscribers are not notified, and `propose` returns. +7. If `m.changes.length === 0 || bypass || unholdable`: with `holdWrites` on and a non-empty `s.queue`, `flushQueue(s)` first applies the store's earlier queued and held writes in proposal order (their pending decisions can still late-revert them). Then `commit(s, m, rethrow = true)` runs **now**, in the caller's stack, and returns. +8. **Default (`holdWrites` off):** `hooks.observeWrite(m)` runs (errors swallowed; it never blocks the write), then `commit(s, m, true)` applies the write now, in the caller's stack. The `mutation` situation is therefore built as of the proposal, before the write applies. +9. **Opt-in (`holdWrites` on):** the record goes into `StoreHub.mutations`, is pushed onto `s.queue`, and `gateAndQueue(s, m)` runs (flow 3). + +### 3. Gate and hold (`holdWrites` only: `StoreHub.gateAndQueue` -> `RuntimeImpl.gateMutation`) + +1. If `!consultable()` (paused, destroyed, no decider, or decider status not `ready`/`off`) or the write is `covered(m)`, the gate returns `{}`: the write is resolved as `apply` and the queue drains. +2. Otherwise it calls `RuntimeImpl.trigger({ trigger: "mutation", m }, mutationController(m, settle), { hold: true, priority: 2 })`. The controller (shared with the background path, where `settle` is null): + - `passive` -> `settle("apply")` (a no-op in the background path). + - `run("discard")` -> verdict `discard`. Its effect text is "Dropped the write to … stays at version N". Its `undo` commits the original mutation as a GenClass write. In the background path `run` throws `the write was not held`. - `run("defer")` -> verdict `defer`. + - `proceeded()` = `m.state === "done"`; `stale()` = the write was discarded, or one of its applied fields was written again since (a queued decision for it is then dropped before it reaches the model). - `revertable` / `revert` are used for late reverts (flow 7). 3. Inside `trigger`, see [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md): - - If the trigger is not salient, the model is not ready, or no non-passive action is permitted (always the case in `observe` mode), `passive()` runs **synchronously**. `gateMutation` sees `syncVerdict === "apply"` and returns `{}`. - - Otherwise the write is **held**. A timer fires after `holdBudgetMs()`: then `expired = true` and `passive()` runs (fail-open). - - The decision deadline is `t0 + budget + LATE_REVERT_MS`, because the mutation controller supports `revert`. - - When the write does not wait because no non-passive action is permitted, the decision is still requested in the background for detection (queue priority capped at 1). A non-passive answer is then only recorded: `gate` finds no permitted candidate, nothing runs, and `Decision.reason` is the restriction of the model's top choice (e.g. `observe mode never changes execution`) or `no action is permitted`, set only when that top choice was non-passive. `the subject was not held` appears only if `setMode` widened the permitted set between the trigger and the answer (see [decide-policy-actions.md](decide-policy-actions.md#3-gate-and-bookkeeping-runtimets---ondecision-policyts---gate)). + - If the trigger is not salient or the model is not ready, `passive()` runs **synchronously**. `gateMutation` sees `syncVerdict === "apply"` and returns `{}`. + - The write **waits** only when `hold` is set, some non-passive action is permitted (never in `observe` mode, the default), the runtime is not paused, and `expectedLatency() <= holdBudgetMs()` (new in batch 4: expected latency = median recent provider latency × (1 + decisions queued ahead) + the decision being computed; infinite while the provider is stuck). Otherwise `passive()` runs at once and the decision continues in the background (priority capped at 1). + - When it waits, a timer fires after `holdBudgetMs()`: then `expired = true` and `passive()` runs (fail-open). The decision deadline is `t0 + budget + LATE_REVERT_MS`, because the mutation controller supports `revert`. + - A background answer that is non-passive is handled as late: `discard` becomes a late-revert attempt; any other action is recorded with the reason `the subject was not held (decided in the background)` (or `the decision arrived after the hold budget expired` when it had waited). 4. `gateMutation` returns `{}` for a synchronous `apply`, otherwise the pending promise. It also has a defensive branch that wraps a synchronous `discard`/`defer` in `Promise.resolve(verdict)`; with the current `trigger`, actions only run in the queue's `.then` (`onDecision`), so only `apply` can be synchronous. -5. A held promise resolves to the verdict. If the gate throws, the result is treated as `{}`. If the held promise rejects, the verdict is `apply`. +5. A held promise resolves to the verdict. If the gate throws, the result is treated as `{}`. If the held promise rejects, the verdict is `apply`. If the write is already `done` when the verdict (or rejection) arrives, because a write that applied at once flushed it (flow 2, step 7), the verdict is ignored: the write stays `done`, so its decision sees `proceeded()` and can only late-revert it (flow 7). ### 4. Drain, commit, record @@ -306,11 +333,15 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created 6. `RuntimeImpl.onApplied(m, s, changes, writer)`: - `writer.wrote++` and `writer.storesWritten`. - For the writer and up to 8 ancestors (GenClass ops skipped): increment `storeWriters[opSignature][store]` (capped at 1,000 signatures, FIFO). Profiled op kinds (`fetch`, `xhr`, `user`, `task`, `ws`) that are not yet profiled also accumulate `op.chain[normalizeFieldPath(path)] = { kind, len0, len1 }` and `op.chainWrites` for transition profiles. + - Those accumulating ops, except `user` ops, also update `lastChainMap[signature]` (the normalised paths the signature's chain wrote; capped at 1,000 signatures, FIFO). Delivery prediction and `onChannel` read it. + - For a non-GenClass writer: `markWrites(changes, writer)` sets stale marks (flow 13; errors only logged). - `miner.noteChanged(paths)` and `miner.noteValues(...)`. - `scheduleSettle()`. ### 5. Defer (`StoreHub.defer`) +Only reachable with `holdWrites` on: by default a `mutation` `defer` arrives after the write applied and is recorded only. + 1. `hooks.waitRelated(m)` (`RuntimeImpl.waitRelated`) waits for the related in-flight ops. An op is related when it is not in the cause's own ancestry or descent and either has the cause's signature and kind, or its signature's chains have written this store before (`storeWriters`). The wait resolves when all of them end, or after 10,000 ms. 2. Then the write is re-proposed **at the end of the queue** with the same id, cause and intent: - `preview = m.fn ? m.fn(cloneValue(base)) : patched(s, m, base)`. If that throws, the old preview is used. @@ -321,7 +352,7 @@ Constructor: `new StoreHub(clock, ctx, events, redact: () => Redactor)`, created ### 6. Patches (`fields.ts` -> `patchValue`) -Used by `patched` (a held or queued value write applied over newer state), `revert`, `reapply` and `restoreFields`. +Used by `patched` (a held or queued value write applied over newer state), `revert`, `reapply`, `restoreFields`, `applyFilter` (the remainder of a partly dropped write) and `pendingView` (read-your-writes). 1. If a change targets the whole store (`path === store`), return its value. 2. If the current value is not a plain object, return `ok: false`. @@ -329,17 +360,20 @@ Used by `patched` (a held or queued value write applied over newer state), `reve 4. Apply all removals first, then all sets, with copy-on-write along each path. Missing intermediate objects are created for sets and ignored for removals. A non-plain-object intermediate gives `ok: false`. 5. When a patch fails: `patched` falls back to `m.preview`, `revert`/`reapply` return null, and `restoreFields` skips that store. -### 7. Late revert (hold budget expired, then `discard`) +### 7. Late revert (`discard` after the write applied) + +Three ways to get here: the default background decision (the write applied right after `observeWrite`), or, with `holdWrites`, a hold that expired (fail-open) before the answer came, or a held write that `flushQueue` applied early (flow 2, step 7). -1. In `RuntimeImpl.onDecision`, when `st.hold && (st.expired || passiveRan)` and the gate chose `discard`, the runtime calls `ctl.revertable()`. It returns null or a reason string: +1. In `RuntimeImpl.onDecision`, `proceeded = ctl.proceeded()` (`m.state === "done"`). When the gate chose `discard` and the write has proceeded, the runtime calls `ctl.revertable()`. It returns null or a reason string: - `the write has not applied yet`; - age > `LATE_REVERT_MS` (2,000 ms) -> `too late to revert: decided Xs after the write applied`; - `StoreHub.revertable(m)`: `the store is gone`; `the write was not applied`; `<store> cannot be written by GenClass`; `the write changed nothing`; - `superseded: <path> changed again after the write applied`, when for some applied path the field's last log entry is not this mutation; - `the same operation chain wrote <paths> after this write applied; …`, when a `RecentChange` with `seq > appliedSeq` has the same root and a different mutation id. Writes made synchronously by subscribers count, because they run under the write's cause. -2. If it is revertable: `runAsGenClass("revert", () => hub.revert(m, op))` patches `m.applied` back to the `before` values. The `ActionRecord` gets `late: true` and the text "Reverted the write to … (decided Xs after it applied); … is back to …". `undo` -> `hub.reapply(m)`. -3. Any other verdict that arrives after expiry is only recorded, with the reason "the decision arrived after the hold budget expired". -4. The decision deadline for a held write is `t0 + holdBudgetMs() + LATE_REVERT_MS`. A request still unanswered then is abandoned by the decider queue (`decide/decider.ts` -> `DeciderQueue`), so no decision is recorded at all (`atoms.test.ts` "a late discard does not revert … or after 2 s"). Because a held write cannot apply before its own budget expires, a decision that beats the deadline is at most 2 s after the apply, so the `too late to revert` branch is effectively unreachable (found by code reading). +2. If it is revertable: `runAsGenClass("revert", () => hub.revert(m, op))` patches `m.applied` back to the `before` values. The `ActionRecord` gets `late: true` and the text "Reverted the write to … from … (decided Xs after it applied); … is back to …". `undo` -> `hub.reapply(m)`. +3. Any other non-passive verdict after the write proceeded is only recorded, with the reason `the decision arrived after the hold budget expired` (it had waited) or `the subject was not held (decided in the background)`. + - Fixed defect (`holdWrites` only; present on b435acb): when a held write was applied early by `flushQueue` and its hold budget then expired, the expiry's `settle("apply")` resolved the held promise and `gateAndQueue`'s `.then` set `m.state = "resolved"` again over `"done"`. `proceeded()` was then false, so a later `discard` took the held-write path: `settle("discard")` was a no-op, nothing was reverted, and an `ActionRecord` "Dropped the write to … stays at version N" was still recorded (its undo would have committed the write a second time). Now `gateAndQueue`'s `.then`/`.catch` return early for a write that is already `done`, so the discard is a late revert under the rules of step 1, whether it arrives before or after the budget expires. `atoms.test.ts` "a held write applied early by a user write stays applied when its hold budget expires; a later discard reverts it" covers it. Side effect: such a write is no longer left `resolved` forever, so the `mutations` map trim (which removes only `done` records) can drop it. +4. Deadlines: a held write's decision must arrive by `t0 + holdBudgetMs() + LATE_REVERT_MS`; a background decision by `t0 + BACKGROUND_DEADLINE_MS` (5,000 ms). A request still unanswered then is abandoned by the decider queue (`decide/decider.ts` -> `DeciderQueue`) and no decision is recorded. With the 5 s background deadline the `too late to revert` branch is reachable again: `atoms.test.ts` "a late discard does not revert…" asserts it (the model's expected latency exceeds the hold budget, so the write is not held, and the answer comes 2.5 s after the apply). ### 8. External changes @@ -390,7 +424,7 @@ const [cart, setCart] = useAtom(cartAtom); // any Atom 1. Which runtime is used: `useRuntimeOrNull()` returns the nearest `<GenClassProvider runtime>` value. If there is no provider (context `undefined`), it returns `GenClass.runtime`. `runtime={null}` explicitly means no GenClass. 2. `useGenClassState(name, initial, opts?)`: - With a runtime, `atomFor` creates or reuses **one atom per (runtime, name)**, stored in a module `WeakMap<Runtime, Map<name, Atom>>`. The lazy `initial` is called once. `opts` only apply at creation. Creation is idempotent, which makes it safe under StrictMode. - - It reads with `useSyncExternalStore` over memoised wrappers of `atom.subscribe` and `atom.get` (the same getter for the server snapshot). The setter calls `atom.set`, so a held write shows up only when it applies and never when it is dropped. + - It reads with `useSyncExternalStore` over memoised wrappers of `atom.subscribe` and `atom.get` (the same getter for the server snapshot). The setter calls `atom.set`, so by default the new value renders at once; with `holdWrites` a held write shows up only when it applies and never when it is dropped. - Without a runtime it is plain `useState`, and it logs one `console.info` per module (`warned`). 3. `useAtom(atom)` is `useSyncExternalStore` over any `Atom`. `getGenClassAtom(rt, name)` returns a hook-created atom so code outside React can use it. It returns `undefined` for a store created with `rt.atom` directly, because it reads only the hook registry. - `atomFor` calls `rt.atom(name, …)`. If `name` is already an **atom**, that returns the existing store, merging `opts` when `resync`/`describe`/`hold` is given. If `name` is a **guard or adapter** store (for example a Redux store named `"cart"`), `rt.atom` re-registers it as an atom and replaces it (see Gotchas). @@ -417,7 +451,7 @@ Signature: `genclassEnhancer<S = unknown>(runtime: Runtime | null | undefined, o - A non-action (a thunk) passes straight to the inner dispatch. - Otherwise it computes `next = reducer(state, action)` once, as the preview. - If `next === state`, it is a plain dispatch: subscribers are notified and nothing is proposed. - - Otherwise `handle.propose({ fn: prev => prev === state ? next : reducer(prev, action), commit: v => dispatchKnown(action, v) })`, and it returns `action` synchronously, even while the write is held. + - Otherwise `handle.propose({ fn: prev => prev === state ? next : reducer(prev, action), commit: v => dispatchKnown(action, v) })`, and it returns `action` synchronously (with `holdWrites`, even while the write is held; by default the commit has already run). 5. `dispatchKnown` sets `ready` and calls the inner dispatch, so inner enhancers such as Redux DevTools, reducers and subscribers see the **original action exactly once**, at apply time. A dropped dispatch never reaches them. 6. `replaceReducer` swaps `current` and re-installs the wrapper. 7. Put the enhancer **last** in `compose()` (innermost). If it is outermost, the actions that thunks dispatch through the middleware API skip it; they are then only recorded as external changes and never held. @@ -440,27 +474,61 @@ Signature: `genclass(runtime: Runtime | null | undefined, name: string, opts?: S 4. Registration is `runtime.adapter(name, { get: () => api.getState() ?? initial, set: v => outer(v, true), subscribe }, opts)`. Zustand assigns its state after the creator returns, hence the `initial` fallback. The action functions in the state become fields of kind `function`. **Common to all adapters:** +- **Default path (`holdWrites` off):** `AdapterHandle.propose` commits synchronously in the caller's stack: a Redux `dispatch` reaches the reducer, inner enhancers and subscribers before it returns, and a Zustand `set` is visible at once. The model decides in the background. The hold paths described above (dispatch returns before the reducer runs, held writes invisible) apply only with `policy: { holdWrites: true }`, which is how the adapter tests exercise them. +- **Read-your-writes does not reach library reads.** Only the runtime's own atom/guard `get()` consults `pendingView`. With `holdWrites` on, `store.getState()` (for example inside Redux middleware) and Zustand `get()` keep returning the applied state while a write is held. Keep `holdWrites` off for such stores, or pass `hold: false` (STATUS "Open issues"; `no-reorder.test.ts`). +- **Delivery drop filter and library commits:** a dispatch whose changes are all dropped never reaches the library; one that is only partly dropped is committed whole (flow 12). - Neither the Redux enhancer nor the Zustand middleware ever calls (or exposes) `AdapterHandle.dispose()`, so their stores stay registered for the runtime's lifetime. Creating a second store with the same name (HMR, tests, two stores both named `"app"`) replaces the first hub record through `StoreHub.register`. The first store's GenClass subscription is dropped, and its handle keeps proposing to the orphaned record. - Packaging: `adapters/react.ts` imports `GenClass` from `../index.js`. `tsup.config.ts` builds every entry with `splitting: true`, so the singleton lives in a shared chunk: in the build output, `dist/adapters/react.js` imports `GenClass` from `../chunk-*.js`. Turning splitting off would give the React subpath its own `GenClass` copy, and `GenClass.init()` from the main entry would then be invisible to the hooks. That consequence is inferred from the build config, not tested. - `demos/` can run against development stand-ins in `demos/src/dev/runtime-shim/` (observe-only; the Redux and Zustand shims are identity wrappers), aliased by `demos/vite.config.ts` when `GENCLASS_SHIM=1`, or when `packages/runtime/dist/index.js` is missing and `GENCLASS_SHIM` is not `0`. Behaviour seen there is not the adapters' behaviour; see [../demos.md](../demos.md). +### 12. Delivery `discard` at the store (`StoreHub.applyFilter` -> `RuntimeImpl.dropFilter`) + +The `delivery` trigger itself (predicted write sets, conflicts, holding a response or message) is documented in [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md). This is the store side of its `discard`. + +1. `RuntimeImpl.runDelivery`'s `discard` sets `op.discardMark = { protect: <conflicting paths>, until: now + DISCARD_MARK_MS, dropped: [] }` on the delivered op, then releases the response or message to the app. +2. Each later `propose` with changes calls `dropFilter(m)`. It returns null for GenClass and user-sync writes. Otherwise it walks up to 16 causes for an op whose mark is still live (`until >= now`). For that op `x` it drops every change whose path is in `protect`, or that `writtenOver(x, path)`: since `x.startSeq` the field's log has an entry from an op outside `x`'s chain (neither ancestor nor descendant) that is user-sync, a `user` op, started after `x`, or whose root is a `user` op that started after `x`. +3. `applyFilter`: + - nothing to drop -> the write continues unchanged; + - every change dropped -> `state = "done"`, `outcome = "discarded"`, `hooks.dropped(m, dropped, false)`, nothing applied; + - some dropped and the write has a library `commit` (Redux dispatch, Zustand set) -> **fail-open**: the whole write continues (a library commit cannot be applied in part); + - some dropped otherwise -> `patchValue` builds the remainder over `base`; if the patch fails the whole write continues; else `preview`, `leaves` and `changes` are replaced, `fn` is deleted, and `hooks.dropped(m, dropped, true)` runs. +4. `RuntimeImpl.onDropped` appends `{ path, after, removed }` to the mark's `dropped` list, calls `mark.onDrop` (which extends `ActionRecord.dropped`), and pushes an `action` event named `dropped` with the text `dropped the write of <paths> by <op> over newer data[ (its other changes applied)]`. +5. Undo of the delivery `discard`: sets `mark.until = 0` (no more drops) and `hub.restoreFields` writes the dropped values now. + +`delivery.test.ts` "a stale out-of-order response gets a delivery decision; discard drops only the stale field writes" asserts the partial drop (`search.items` dropped, `search.loaded.a` applied). + +### 13. Stale marks (situation-v2, STATUS "F9") + +1. `RuntimeImpl.markWrites(changes, writer)` (from `onApplied`) walks the writer and up to 8 ancestors. For the first op that explains the write, it marks the written paths (removals excluded) with `{ t: now, op, why }`: + - its delivery was released over newer data or a pending local change without a decision to drop it (`OpRec.delivery.overNewer`, set by the delivery controller's `passive`): only the paths in that conflict set, `why` = `by the response to … / the message …, which was delivered over newer data from <op> | a pending local change of <op>`; + - a `fetch`/`xhr` that ended `ok` and took at least 5× its median latency and at least 300 ms more: `by the response to …, which took Xs (N× its usual Ys)`; + - a `fetch`/`xhr` that failed ambiguously (`situation/evidence.ts` -> `commitAmbiguity`): `after … failed (…), although the server may have applied it`. +2. `RuntimeImpl.onChannel("up", channel, path)`: when a WebSocket or EventSource channel comes back after being down, every field its message signatures wrote (from `lastChainMap`) whose last write is not newer than the outage start is marked `by WebSocket | server-sent messages on <path>; the channel then was down for Xs (…), so updates sent meanwhile may be missing`. +3. The next recorded write to the field clears the mark. `markFacts` states it in later situations (see the Field state section). Tests: `content.test.ts` "F9: provenance of values known to be stale". + ## Configuration and constants | name | type | default / value | defined in | effect | |---|---|---|---|---| -| `StoreOptions.hold` | boolean | `true` | `packages/runtime/src/types.ts` (read in `StoreHub.propose`) | `false`: writes are traced, never held | +| `StoreOptions.hold` | boolean | `true` | `packages/runtime/src/types.ts` (read in `StoreHub.propose`) | `false`: writes are traced and recorded but bypass the pipeline: never held, no `mutation` trigger (background or held). The delivery drop filter still applies | | `StoreOptions.resync` | function | none | `types.ts` | enables `resync` for the store | | `StoreOptions.describe` | `(v) => string` | none | `types.ts` (used in `situation/build.ts` -> `stateLines`) | one-line store description in state lines | -| `policy.holdUserWrites` | boolean | `false` | `packages/runtime/src/decide/policy.ts` -> `policyConfig`; copied once to `StoreHub.holdUserWrites` in the `RuntimeImpl` constructor | `true`: user-sync writes go through the gate too | +| `policy.holdUserWrites` | boolean | `false` | `packages/runtime/src/decide/policy.ts` -> `policyConfig`; copied once to `StoreHub.holdUserWrites` in the `RuntimeImpl` constructor | `true`: user-sync writes stop being bypass writes: they get a background `mutation` decision (default) or go through the gate (with `holdWrites`). The delivery drop filter still never touches them | +| `policy.holdWrites` | boolean | `false` | `packages/runtime/src/types.ts` `PolicyOptions.holdWrites`; `decide/policy.ts` -> `policyConfig`; copied once to `StoreHub.holdWrites` | `false`: writes apply at once and salient ones are decided in the background; `true`: the opt-in hold pipeline (queue, gate, flush before bypass writes, read-your-writes) | +| `InitOptions.mode` | `"observe" \| "guard" \| "heal"` | `"observe"` (our commit f3636b2; was `"guard"`) | `runtime.ts` constructor (`o.mode ?? "observe"`) | `observe` permits no action: no holds, no late reverts, no drops; decisions are still made and reported. `test/helpers.ts` -> `setup` defaults to `"guard"` | | `policy.holdBudgetMs` | number \| `"auto"` | `"auto"`: clamp(1.5 × median recent model latency, or warm-up time, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 when nothing is known | `decide/policy.ts` -> `holdBudget` | how long a held write waits before fail-open | | `InitOptions.settleMs` (also on `CreateOptions`) | number | `60` | `types.ts`; default in the `runtime.ts` constructor (`o.settleMs ?? 60`) | quiet time before a settled point | | `LATE_REVERT_MS` | const | `2000` | `runtime.ts` | late-revert window; extends the decision deadline for held writes | +| `BACKGROUND_DEADLINE_MS` | const | `5000` | `runtime.ts` | deadline of a decision that does not hold its subject (default-path writes) | +| `DISCARD_MARK_MS` | const | `10_000` | `runtime.ts` | how long a delivery `discard` keeps dropping its chain's writes over newer data | +| chain walk for coverage / discard marks | literal | `16` causes | `runtime.ts` -> `covered`, `dropFilter`, `onDropped` | how far up the cause chain a delivery is looked for | +| stale-mark thresholds | literal | ≥ 5× median latency and ≥ 300 ms over it; ancestors walked: 8 | `runtime.ts` -> `markWrites` | slow-response marks | | `LONG_RUNNING_MS` | const | `10_000` | `runtime.ts` | ops older than this do not block settled points; maximum wait for `defer` | | snapshots kept | literal | `8` | `runtime.ts` -> `settled` | consistent snapshots retained | | `storeWriters` cap | literal | 1,000 signatures | `runtime.ts` -> `onApplied` | FIFO eviction | | ancestors per write | literal | `8` | `runtime.ts` -> `onApplied` | depth for `storeWriters` and transition accumulators | | max defers | literal | `2` | `hub.ts` -> `drain`; `situation/build.ts` -> `builtinApplicable` | third `defer` verdict applies | -| mutation trigger priority | literal | `2` (inconsistency `1`) | `runtime.ts` | decider queue priority | +| mutation trigger priority | literal | `2` from `gateMutation` (a write that may be held), `1` from `observeWrite` (background); inconsistency `1`. `trigger` caps any non-waiting decision at `1` | `runtime.ts` -> `gateMutation`, `observeWrite`, `raiseInconsistency`, `trigger` | decider queue priority | | `HIST` / `LOG` | const | `16` / `512` | `hub.ts` | rich history / compact log per field | | `RECENT_MS` / `RECENT_MAX` | const | `10_000` ms / `256` | `hub.ts` | recent changes (repetition facts, late-revert chain check) | | `mutations` map trim | literal | > 512 -> 256 | `hub.ts` -> `propose` | bookkeeping only | @@ -476,6 +544,10 @@ Signature: `genclass(runtime: Runtime | null | undefined, name: string, opts?: S | `MAX_NUMERIC` / `MAX_SCALAR` / `MAX_ARRAYS` | const | `64` / `96` / `24` | `invariants.ts` | fields considered per settled point | | `MAX_COLUMNS` | const | `8` (from the first 32 keys) | `invariants.ts` | numeric/scalar columns per array | | `MAX_CANDIDATES` | const | `4000` | `invariants.ts` | no new candidates beyond this | +| `minDistinct` | literal | `3` | `invariants.ts` -> `propose` | distinct values of `a` needed for `eq` between unrelated names and for `count` without a related name | +| count groups | literal | 2 to 8 distinct values per column; first 8 keys of element 0 | `invariants.ts` -> `colGroups`, `propose` | count-by-group candidates | +| `GENERIC_WORDS` / `VERSION_WORDS` / `ID_COLUMN` | const | see "Relation quality" | `invariants.ts` | name-based relation filters | +| `stringDiff` width | param | `30` (window), 14 chars of context, 28-char edit text | `fields.ts` -> `stringDiff` | diff-centred string previews | | `MAX_DROPPED` | const | `50_000` | `invariants.ts` | the dropped set is **cleared** when full, so dropped ids can be proposed again | | `numEq` tolerance | fn | relative 1e-6, or < 0.0051 and equal in cents | `invariants.ts` | numeric equality in invariants | | `GENCLASS_REPLACE` | export const | `"@@genclass/REPLACE"` | `adapters/redux.ts` | action used for GenClass's whole-state writes | @@ -483,28 +555,31 @@ Signature: `genclass(runtime: Runtime | null | undefined, name: string, opts?: S ## Invariants and gotchas -**Pipeline semantics (break these and tests in `atoms.test.ts` / `review-hub.test.ts` fail):** -- **Proposal order per store.** `drain` only pops from the head. A write the gate cleared synchronously still waits behind an earlier held write to the same store. -- **Bypass writes skip the queue.** This is an open product risk (`demos/NEEDS.md` §1). A user-sync write applies at once even when an earlier async write to the same store is held. When the held write is released, its functional updater re-runs on top of the user's change and can overwrite it, which differs from the order the app would see without GenClass. `atoms.test.ts` "functional updates re-run against the value at apply time" asserts the current behaviour. Fixing it changes that test. -- **A held write must not change live state before the decision.** Only *functional* updaters are protected (detach and restore). A *value* write of an object the app already mutated in place (`v = a.get(); v.items.push(x); a.set(v)`) changes live state before the hold, and a `discard` cannot undo that. GenClass's leaves then disagree with live state until the next write. This was found by code reading; no test covers it. +**Pipeline semantics (break these and tests in `atoms.test.ts` / `review-hub.test.ts` / `delivery.test.ts` / `no-reorder.test.ts` fail):** +- **Never worse by default.** With `holdWrites` off, `set()` / `dispatch` / Zustand `set` apply in the caller's stack, in the order the app made them; `set(x); get()` returns x. `no-reorder.test.ts` asserts that guard and heal modes with an always-passive model leave a Redux promise-middleware app (realworld pattern) exactly as observe mode does. The realapps sweep (66 apps, see [../realapps.md](../realapps.md)) found 0/396 changed clean runs (HANDOFF.md; not re-run here). Do not add anything that delays or reorders a default-path write. +- **Proposal order per store (`holdWrites`).** `drain` only pops from the head. A write the gate cleared synchronously still waits behind an earlier held write to the same store. +- **A hold never reorders a store's writes (`holdWrites`).** Any write that applies at once (user-sync, GenClass, `hold: false`, paused, no-op, unholdable) first calls `flushQueue`: every earlier queued or held write of the store applies, in order, as `apply` (one already resolved as `discard`/`defer` keeps that verdict); their pending decisions can still late-revert them under the flow 7 rules, also after their hold budget expires. The expiry's fail-open verdict must not reopen a write that a flush already applied: `gateAndQueue` ignores any verdict for a `done` write (flow 7, step 3; `atoms.test.ts` "a held write applied early by a user write stays applied …"). This fixed the DEMOS jump-back risk (`demos/NEEDS.md` §1): `atoms.test.ts` "a user write never overtakes an earlier held write of the same store (DEMOS regression)". The price: a user write releases a pending hold early. +- **A held write must not change live state before the decision (`holdWrites`).** Only *functional* updaters are protected (detach and restore). A *value* write of an object the app already mutated in place (`v = a.get(); v.items.push(x); a.set(v)`) changes live state before the hold, and a `discard` cannot undo that. GenClass's leaves then disagree with live state until the next write. Found by code reading; no test covers it. In the default path nothing is held, so this protection is not used at all. - **Updaters may run more than once:** at proposal (preview), again at apply when the state moved, and on a clone for each defer. The same holds for Redux reducers and Zustand partial functions. They must be pure. - **Fallback to the stale preview.** If a re-run updater throws at apply time (not the synchronous path), or a patch is impossible, the hub applies `m.preview`, the value computed against the old state. That can overwrite newer fields. - **Error routing.** On the synchronous path (`commit(…, rethrow = true)`), updater and setter errors propagate to the caller. Subscriber errors are always reported, never thrown. On the later path, `appError` -> `RuntimeImpl.reportError` (source `applying a write to X`, `re-running an update of X`, `the setter of X` or `a subscriber of X`) **raises an `error` trigger**. The queue continues, so a throwing setter never strands later writes (`review-hub.test.ts` "a commit that throws"). -- **Reads while held:** `atom.get()`, `store.getState()` and Zustand `get()` return the pre-write state until the write applies. Redux `dispatch` returns the action immediately. -- **Discard means no notification:** app subscribers and React never see a discarded value (`atoms.test.ts`, the adapter tests). +- **Reads while held (`holdWrites`):** atom/guard `get()` returns the pending value inside the writing chain and the applied value elsewhere; library reads (`store.getState()`, Zustand `get()`) always return the applied state. Redux `dispatch` returns the action immediately. +- **Discard means no notification:** app subscribers and React never see a discarded or fully dropped value (`atoms.test.ts`, the adapter tests, `delivery.test.ts`). +- **The drop filter is narrow.** It never touches user-sync or GenClass writes and only drops paths that were in conflict or that a user or newer op wrote after the delivered op started. It runs whatever `holdWrites`, `hold: false` or `gating` say: a discard mark set before `pause()` keeps dropping for up to 10 s (found by code reading; no test covers it). - **`gating` is the only global switch.** `pause()` and `destroy()` set it to false, and every write then applies immediately but is still recorded. After `destroy()`, atom/guard `set` and `AdapterHandle.propose` skip `propose` entirely: they call `hub.write(…, writer = null, m = null)`, so no `mutationProposed` hook fires and no cause is recorded. `destroy()` also unsubscribes every `io.subscribe`, so external changes are no longer recorded, and `scheduleSettle` becomes a no-op. - **An updater that throws at proposal time always throws from `set()` / `dispatch` / `propose`.** `previewOf` runs `w.fn(base)` outside any try/catch, before the write is queued or recorded, so this happens whatever path the write would have taken. - **A library subscriber that throws inside `commit` looks like a failed setter.** Redux and Zustand update their state and then call listeners inside the same `dispatch`/`setState`. If a listener throws, `StoreHub.write` catches it as `the setter of X`: it rethrows on the synchronous path, or reports it with `outcome = "failed"` later. In both cases `record` is skipped and the hub's own listener was suppressed (`committing`), so the library holds the new state while GenClass's leaves, versions and `state` events miss it until the next recorded change. Found by code reading; no test covers it. +- **Background decisions are built before the write applies.** `observeWrite` runs before `commit`, so the `mutation` situation describes the store as of the proposal (like a held write). Facts that compare with the applied state would need the hook moved, which changes situation text (parity). **Store names and paths:** - **Store names must not contain `.`. Nothing enforces this.** Every lookup by path splits on `.` and takes segment 0 as the store name: `field`, `versionAt`, `logSince`, `writesSince`, `valueAt`, `leaf`, `restoreFields`, `snapshot` (top-level key = segment 1), `restoreInPlace` and `patchValue` (`segs = path.split(".").slice(1)`). For a store named `search.results`: - its fields never appear in state lines (only a `describe` one-liner can); - versions facts always say the field "has not changed", which defeats stale-write detection; - chain revert skips it, and inconsistency `rollback`/`resync` are never offered for it (`builtinApplicable` derives the store name `search`, which does not exist); - - the in-place-updater protection cannot restore it, so such updates are marked unholdable and apply at once; - - a patched held value write on an object-valued store writes under the wrong key (`value.results.x` instead of `value.x`); + - (with `holdWrites`) the in-place-updater protection cannot restore it, so such updates are marked unholdable and apply at once; + - a patched held value write (or a partly dropped write, flow 12) on an object-valued store writes under the wrong key (`value.results.x` instead of `value.x`); - `snapshot()` takes segment 1 (`results`) as the changed top-level key, so for an object-valued store it reuses stale clones of changed keys. - The README and the `react.ts` header use `useGenClassState("search.results", [])`. That is an array value, so the patch corruption does not happen there, but the lookups still fail. This was found by code reading; no test covers it. + `packages/runtime/README.md` ("State it can protect") and the `react.ts` header use `useGenClassState("search.results", [])`. That is an array value, so the patch corruption does not happen there, but the lookups still fail. This was found by code reading; no test covers it. - **Names are global per runtime across kinds.** `register` replaces any store with the same name. For example, `rt.atom("cart")` after `rt.guard("cart", …)` re-registers it as an atom, resetting versions and history, and old handles keep writing to the orphaned record. `rt.atom(name)` with an existing atom name returns the existing store and ignores `initial`. - **Path ids for invariants:** `dynamicPath` skips any path with an `isIdSegment` segment (numbers, uuids, long hex, long tokens, short slug ids such as `x7k2p`). `m21` is **not** an id segment there (3 chars), but `normalizeFieldPath` (transition profiles) does treat any key with a digit as `:id`. @@ -523,22 +598,22 @@ Signature: `genclass(runtime: Runtime | null | undefined, name: string, opts?: S - Developer `expect()` violations have `fields: []`, so they contribute no store: when they are the only violations in the trigger, neither `rollback` nor `resync` is offered and only `ignore` remains. - **Clones are not always faithful.** `cloneValue` (snapshots, rollback values, detached previews, defer re-runs) tries `structuredClone` first. That turns class instances into plain objects (their prototype is lost), so a `rollback` writes plain objects back into a store that held class instances. Values containing functions, such as Zustand state with actions, make `structuredClone` throw, and the manual fallback then keeps functions and class instances by reference and stops copying below depth 32. Found by code reading. -**Performance (budgets asserted in `test/review-perf.test.ts`; numbers measured on the shared VM, from `packages/runtime/STATUS.md`):** +**Performance (budgets asserted in `test/review-perf.test.ts`; numbers measured on the shared VM after batch 5, from `packages/runtime/STATUS.md`):** | scenario | budget (test) | measured | |---|---|---| -| user-sync write (keystroke) on an atom holding a 5,000-item array | < 1 ms/write | 0.14 ms | -| async gated write (facts computed) on the same store | < 2 ms/write | 0.19 ms | -| redux-style `adapter.propose` on 5,000 normalized entities (user / async) | < 1 ms / < 2 ms | 0.68 ms / 0.58 ms | -| settled point, 5,000-item atom changed / plus an unchanged 5,000-item adapter store | < 16 ms each | 0.2 ms / +1.4 ms | +| user-sync write (keystroke) on an atom holding a 5,000-item array | < 1 ms/write | 0.22 ms | +| async write (facts computed; default path: background decision) on the same store | < 2 ms/write | 0.14 ms | +| redux-style `adapter.propose` on 5,000 normalized entities (user / async) | < 1 ms / < 2 ms | 0.71 ms / 0.70 ms (0.67 / 0.66 in a later run) | +| settled point, 5,000-item atom changed / plus an unchanged 5,000-item adapter store | < 16 ms each | 0.3 ms / +2.3 ms (count-by-group candidates) | Fixtures: `shop(5000)` is `{ items: 5,000 × { id, sku, name, price, qty, stock, rating, weight }, filter, page, pageSize, total, selected, cartCount, cartTotal, maxPrice, minPrice, version }`, and each write replaces `filter` immutably. `entities(5000)` is `{ entities: { byId: 5,000 entries }, ui: { query } }`, so `byId` is a single collection field. The settled-point case first runs 6 learning writes, then times 10 iterations of `set` + `rt.settled()`. All cases use `setup()` from `test/helpers.ts` with `FakeClock`; the measured values are logged with a `[review]` prefix. -These numbers depend on reference-equality fast paths (`arrayLeaf`/`objectLeaf` returning the previous `Leaf`), the `WeakMap` statistics cache in the miner, and snapshot reuse (`snapCache` by version and reference). If you add per-write work that is O(n) in a store's size, such as hashing, cloning or `JSON.stringify`, these budgets break. +These numbers depend on reference-equality fast paths (`arrayLeaf`/`objectLeaf` returning the previous `Leaf`), the `WeakMap` statistics cache in the miner, and snapshot reuse (`snapCache` by version and reference). If you add per-write work that is O(n) in a store's size, such as hashing, cloning or `JSON.stringify`, these budgets break. `review-perf` is timing-sensitive: on 2026-10-08 it failed once in a full parallel vitest run (5.5 ms against its 2 ms bound) and passed alone; the CI workflow (`.github/workflows/ci.yml`) runs it alone with `--retry=2`. **Determinism and parity:** - Only the injected `Clock` is used (`this.clock.now()`), ids come from counters (`mid`, `seq`), and hashes are FNV-1a. There is no `Math.random`, `Date.now` or global `setTimeout` (CONTRACT §0 rule 3). -- The sim drives the real runtime through `rt.atom` (`sim/src/run/runner.ts`). Field paths, versions, deltas and `changeText` output appear verbatim in situation text. Any change to `fields.ts` or the version bookkeeping changes training data. Coordinate with the lead: a new freeze tag, and a data/sim regeneration. See [../model-io-contract.md](../model-io-contract.md) and [../sim.md](../sim.md). +- The sim drives the real runtime through `rt.atom` (`sim/src/run/runner.ts`), and REAL drives it in real browsers ([../realapps.md](../realapps.md)). Field paths, versions, deltas, `changeText`/`stringDiff` output, stale-mark clauses and invariant texts appear verbatim in situation text. Any change to `fields.ts`, `invariants.ts`, `markWrites` or the version bookkeeping changes training data. The format is frozen at tag `situation-v2` (6e5e86e) while the cluster generates v2 data (HANDOFF.md): coordinate with the lead before touching it (a new freeze tag and a data/sim regeneration). See [../model-io-contract.md](../model-io-contract.md) and [../sim.md](../sim.md). **Adapters:** - Zustand and Redux capture `runtime` when the store is created. `genclass(GenClass.runtime, …)` evaluated before `GenClass.init()` gets `null`, and that store is never guarded. React hooks resolve the runtime at render time. @@ -549,57 +624,66 @@ These numbers depend on reference-equality fast paths (`arrayLeaf`/`objectLeaf` ## How to change it safely -The team runs builds and tests on the VM, not on the Mac (CONTRACT §0 rule 5). Under the 2026-10-07 run policy in AGENTS.md, agents on other machines may run the build and these unit tests locally ([build-test-release.md](build-test-release.md#where-to-run-things)). From `packages/runtime`, the relevant suite is `vitest run test/atoms.test.ts test/review-hub.test.ts test/invariants.test.ts test/adapter-seam.test.ts test/adapters-react.test.ts test/adapters-redux.test.ts test/adapters-zustand.test.ts test/review-perf.test.ts test/review-precision.test.ts test/situation.test.ts test/batch3.test.ts`, then the full `vitest run --exclude "test/browser/**"`. Do not edit `test/review-*.test.ts` to make it pass: `packages/runtime/STATUS.md` records that every review test passes unmodified, so treat them as required behaviour. +Run policy (AGENTS.md §4 "Where to run things"): light local checks (npm ci, `tsc`, `tsup`, vitest unit tests) are fine on a developer machine; HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac. Ask the user before Playwright, `smoke.sh`, realapps runs, the sim generator or anything on Azure ([build-test-release.md](build-test-release.md#where-to-run-things)). From `packages/runtime`, the relevant suite is `NODE_OPTIONS=--expose-gc npx vitest run test/atoms.test.ts test/delivery.test.ts test/no-reorder.test.ts test/default-mode.test.ts test/content.test.ts test/review-hub.test.ts test/invariants.test.ts test/adapter-seam.test.ts test/adapters-react.test.ts test/adapters-redux.test.ts test/adapters-zustand.test.ts test/review-precision.test.ts test/situation.test.ts test/batch3.test.ts`, then `test/review-perf.test.ts` alone, then the full `npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` (on 2026-10-08 at b435acb: 40 files passed, 1 skipped; 332 tests passed, 14 skipped; review-perf alone 4 passed; with the flush-then-expiry fix and its regression test: 333 passed, 14 skipped, review-perf 4 passed). Do not edit `test/review-*.test.ts` to make it pass: `packages/runtime/STATUS.md` records that every review test passes unmodified, so treat them as required behaviour. Most CORE tests run in guard mode because `test/helpers.ts` -> `setup` defaults `mode: "guard"`; tests of the hold pipeline also pass `policy: { holdWrites: true }` (`atoms.test.ts` wraps `setup` to add it). 1. **Integrate another state library (MobX, Jotai, Valtio, …):** 1. Add `src/adapters/<lib>.ts`. Call `runtime.adapter(name, { get, set?, subscribe? }, opts)` once per store. 2. Route every app write through `handle.propose({ fn | value, commit })`. `commit(next)` must perform the write on the library store synchronously; it is called later for held writes and never for discarded ones. 3. Provide `set` if GenClass may write whole states (rollback, revert); without it the store is not writable. 4. Add tsup entries in `tsup.config.ts` (`entry` and `dts.entry`), the `exports` subpath and an optional peer dependency in `packages/runtime/package.json`, and add the library to `external`. - 5. Write tests modelled on `test/adapters-zustand.test.ts`: `MockRuntime` (`holdWrites`, `flushHeld`, `dropHeld`, `genclassWrite`) plus one test against the real runtime with `ManualDecider`. + 5. Write tests modelled on `test/adapters-zustand.test.ts`: `MockRuntime` (`holdWrites`, `flushHeld`, `dropHeld`, `genclassWrite`) plus one test against the real runtime with `ManualDecider` and `policy: { holdWrites: true }`, and one default-path test (write visible at once). 2. **Add an invariant template:** 1. Extend `Tpl`. 2. Implement it in `holds` (return null when not applicable), `nonTrivial`, `valuesText` and `propose`, with a deterministic `id` and readable `text`. The text is model-visible. 3. Compute per-array work at most once per array version: put it in `ArrayStats` (cached per `Leaf` in `statsCache`), as `sums`, `prods`, `sets` and `unique` do. - 4. Add a learning test and a precision test (no false inconsistency on benign behaviour) to `test/invariants.test.ts` / `test/review-precision.test.ts`. - 5. This changes situations, so it needs a new freeze tag and regenerated data. + 4. Decide its support rule: if it can hold by coincidence (small numbers, unrelated names), give it `minDistinct` (see `eq`/`count`) and filter version-like names with `versionLike`. + 5. Add a learning test and a precision test (no false inconsistency on benign behaviour) to `test/invariants.test.ts` / `test/review-precision.test.ts` / `test/content.test.ts` "F8". + 6. This changes situations, so it needs a new freeze tag (after `situation-v2`) and regenerated data. Re-run `review-perf` (count-by-group already added about 2 ms to the unchanged-adapter settled point). 3. **Change flattening caps or hashing** (`MAX_DEPTH`, `MAX_KEYS_EXPAND`, `MAX_FIELDS_PER_STORE`, `SAMPLES`, `primHash`): re-run `review-perf` and the "large arrays" test, and check the state lines in `test/batch3.test.ts` / `test/situation.test.ts`. This is parity-affecting. -4. **Change patch semantics** (`patchValue`): keep "removals first; never remove a path with a set beneath it". Run `review-hub.test.ts` (fill an empty object while held / queued / late-reverted / undone) and `atoms.test.ts` "held value writes are re-applied as patches". -5. **Fix the user-write ordering risk** (`demos/NEEDS.md` §1): in `StoreHub.propose`, when a bypass write targets a store whose `queue` is non-empty, either apply the pending writes first in proposal order, or mark the overlapping held writes superseded and re-gate them. Add the regression test that demos suggests: hold a functional write to `s.x`, make a user-sync write to `s.x`, release with `apply`, and expect the user's value. Then update `atoms.test.ts` "functional updates re-run…", which asserts the old order. -6. **Reject or support dotted store names:** either validate in `RuntimeImpl.atom`/`guard`/`adapter` (throwing would break apps, so prefer a console warning plus a sanitised name), or stop deriving the store from `path.split(".")[0]`. That would mean passing the store explicitly to `field`, `leaf`, `valueAt` and so on, and using `path.slice(store.length + 1)` in `patchValue`/`restoreInPlace`/`snapshot`. Fix the README and `react.ts` header examples as well. -7. **Change bypass, hold or late-revert rules** (`propose` `bypass`, `LATE_REVERT_MS`, `StoreHub.revertable`): these are policy-visible. Update `docs/runtime/API.md` "State", run `atoms.test.ts`, `policy.test.ts`, `review-hub.test.ts` and `batch3.test.ts` ("a provider that never answers…"), and coordinate with [decide-policy-actions.md](decide-policy-actions.md). -8. **Change what a settled point does** (`RuntimeImpl.settled`, snapshot policy): run `invariants.test.ts`, `review-precision.test.ts`, `learn.test.ts` (transition rollback) and `review-actions.test.ts`. -9. **Change an existing adapter** (`adapters/react.ts`, `redux.ts`, `zustand.ts`). Keep these contracts, which the adapter tests assert: +4. **Change patch semantics** (`patchValue`): keep "removals first; never remove a path with a set beneath it". Run `review-hub.test.ts` (a value write that fills an empty object next to a concurrent write; late revert of such a write and its undo) and `atoms.test.ts` "held value writes are re-applied as patches". +5. **Change the default (non-holding) path** (`StoreHub.propose` `!holdWrites` branch, `RuntimeImpl.observeWrite`, `covered`): keep "apply in the caller's stack, in order; observation never throws into the write". Run `delivery.test.ts` ("store writes are never held by default"), `no-reorder.test.ts`, `default-mode.test.ts` and `review-perf.test.ts`. Changing when the situation is built (before or after `commit`) changes situation text. The old user-write ordering fix (`demos/NEEDS.md` §1) is done: `flushQueue` before bypass writes under `holdWrites`, plus default no-holds; keep `atoms.test.ts` "a user write never overtakes…" green. +6. **Change the delivery drop filter** (`dropFilter`, `writtenOver`, `applyFilter`, `onDropped`, `DISCARD_MARK_MS`): keep "drop only conflicting or newer-written paths; never drop user-sync or GenClass writes; library commits fail open". Run `delivery.test.ts` (fetch, XHR, WebSocket discard cases), `smoke.test.ts` ("… drops its stale writes in guard mode") and `devtools-runtime.test.ts` ("undo applies the write GenClass dropped"); coordinate the delivery side with [decide-policy-actions.md](decide-policy-actions.md). +7. **Change stale marks** (`markWrites`, `onChannel`, `StaleMark`, `markFacts`): parity-affecting (fact wording). Run `content.test.ts` "F9" and `situation.test.ts`. +8. **Reject or support dotted store names:** either validate in `RuntimeImpl.atom`/`guard`/`adapter` (throwing would break apps, so prefer a console warning plus a sanitised name), or stop deriving the store from `path.split(".")[0]`. That would mean passing the store explicitly to `field`, `leaf`, `valueAt` and so on, and using `path.slice(store.length + 1)` in `patchValue`/`restoreInPlace`/`snapshot`. Fix the `packages/runtime/README.md`, `react.ts` header and `test/smoke/smoke.sh` examples as well. +9. **Change bypass, hold or late-revert rules** (`propose` `bypass`, `holdWrites`, `LATE_REVERT_MS`, `BACKGROUND_DEADLINE_MS`, `StoreHub.revertable`): these are policy-visible. Update `docs/runtime/API.md` "State" and `PolicyOptions.holdWrites` JSDoc, run `atoms.test.ts`, `delivery.test.ts`, `policy.test.ts`, `review-hub.test.ts` and `batch3.test.ts`, and coordinate with [decide-policy-actions.md](decide-policy-actions.md). +10. **Change what a settled point does** (`RuntimeImpl.settled`, snapshot policy): run `invariants.test.ts`, `review-precision.test.ts`, `learn.test.ts` (transition rollback) and `review-actions.test.ts`. +11. **Change an existing adapter** (`adapters/react.ts`, `redux.ts`, `zustand.ts`). Keep these contracts, which the adapter tests assert: - `commit` runs exactly once when a write applies and never for a discarded write. - Redux: the reducer runs once per applied dispatch (the `ready` handoff), and inner enhancers see the original action. Zustand: the commit is a whole-state `replace = true` write that forwards the extra `set()` arguments. - React: one atom per (runtime, name), and the hooks fall back to plain `useState` without a runtime. - - Run the adapter test files plus `adapter-seam.test.ts` and `review-perf.test.ts`. + - Default path: `propose` commits synchronously; do not add anything that delays a dispatch without `holdWrites` (`no-reorder.test.ts`). + - Run the adapter test files plus `adapter-seam.test.ts`, `no-reorder.test.ts` and `review-perf.test.ts`. - Update API.md "Adapters and devtools" and the header comment of the adapter file. - - The demos exercise each adapter: `demos/src/demos/editor/main.ts` (Redux), `demos/src/demos/board/store.ts` (Zustand), `demos/src/demos/checkout/app.tsx` (React). Check them on the VM; see [../demos.md](../demos.md). + - The demos exercise each adapter: `demos/src/demos/editor/main.ts` (Redux), `demos/src/demos/board/store.ts` (Zustand), `demos/src/demos/checkout/app.tsx` (React); the realapps corpus covers many more stacks ([../realapps.md](../realapps.md)). Running them needs the user's go-ahead; see [../demos.md](../demos.md). ## Tests -All paths are under `packages/runtime/test/`. Helpers: `helpers.ts` (`setup`, `ManualDecider`, `ScriptedDecider`, `defaultScript`, `FakeClock`, `FakeServer`) and `browser/ui/mock-runtime.ts` (`MockRuntime`, a scripted stand-in used by the adapter unit tests). +All paths are under `packages/runtime/test/`. Helpers: `helpers.ts` (`setup`, which defaults to `mode: "guard"` while the product default is `observe`; `ManualDecider`, `ScriptedDecider`, `defaultScript`, `FakeClock`, `FakeServer`) and `browser/ui/mock-runtime.ts` (`MockRuntime`, a scripted stand-in used by the adapter unit tests; its own `holdWrites` flag defaults to false). | test file | what it asserts (store scope) | |---|---| -| `atoms.test.ts` | user-sync writes never held; async writes held then applied; fail-open after `holdBudgetMs` plus late revert and its undo; no late revert when superseded, older than 2 s, or the same chain wrote again (subscriber-derived write); late defer/apply only recorded; provider errors fail open at once; proposal order per store; functional re-run on the current value; value writes patched over newer user input; discard drops without notification and undo applies; defer at most twice; `hold: false`; `guard()` writes through `io.set` and records external changes; `atom()` with an existing name; field versions, writers and history deltas | -| `review-hub.test.ts` | patching fills of empty objects while held/queued; undo of a late revert; in-place push summaries ("2 → 3 items"); a held in-place updater is invisible before apply and really dropped on discard; versions counted past the 16-entry history (512 log); a 2,000-item array change recorded once; a throwing setter does not strand later writes or settled points | +| `atoms.test.ts` | runs every case with `policy: { holdWrites: true }`: user-sync writes never held; async writes held then applied; fail-open after `holdBudgetMs` plus late revert and its undo; no late revert when superseded, or when the background decision arrives 2.5 s after the apply (`too late to revert`), or when the same chain wrote again (subscriber-derived write); late defer/apply only recorded; provider errors fail open at once; proposal order per store; a user write never overtakes an earlier held write (DEMOS regression); a held write flushed by a user write stays `done` when its budget expires, and a later discard late-reverts exactly it (undo re-applies); queued functional updates re-run on the current value; read-your-writes inside the chain; value writes patched over newer user input; discard drops without notification and undo applies; defer at most twice; `hold: false`; `guard()` writes through `io.set` and records external changes; `atom()` with an existing name; field versions, writers and history deltas | +| `delivery.test.ts` (new, batch 4) | store side: "store writes are never held by default" (read-after-write with a salient write; a background `discard` late-reverts within the strict rules; a slow model: response released at the budget, its writes decided in the background and late-reverted; a superseded queued background decision is dropped); delivery `discard` drops only the stale field writes (fetch, XHR, WebSocket), the rest of the write applies | +| `no-reorder.test.ts` (new, batch 4) | never worse: a Redux promise-middleware app with an always-passive model behaves identically in observe, guard and heal (both triage settings); with `holdWrites` subscribers still see dispatches in dispatch order | +| `default-mode.test.ts` (new, our commit f3636b2) | default mode `observe`: never holds writes or requests even when the model is sure (decisions recorded, nothing executed); with a model that never answers nothing is delayed, adapter writes commit at once | +| `content.test.ts` (new, batch 5) | store-related: "F8: relation quality" (count-by-group learned; no `in`/`eq` coincidences between unrelated small numbers or version counters); "F9" stale marks (delivered over newer data, 5× slow, ambiguous failure, channel down); long string changes previewed around the first difference (`stringDiff`) | +| `review-hub.test.ts` | unmodified since before batch 4, so only the in-place test passes `holdWrites: true`; the others now run on the default path, where their "held" comments no longer apply (the writes apply at once and the asserted final values are the same): a value write that fills an empty object survives a concurrent user write, and a value write that adds a nested object right after another write to the same store keeps it; undo of a late revert (here a background `discard` 150 ms after the apply); in-place push summaries ("2 → 3 items"); with `holdWrites`, a held in-place updater is invisible before apply and really dropped on discard; versions counted past the 16-entry history (512 log); a 2,000-item array change recorded as one write; a throwing setter does not strand later writes or settled points | | `invariants.test.ts` | learns `count == len(items)`, `total == sum(price*qty)`, `count == badge`, `items[*].id unique` after 3 settled changes; violation values text; nothing learned from unchanged fields; id-like keys skipped; inconsistency raised once per episode, rollback to the snapshot and its undo; transient between-write states ignored; `expect()` checked from the start | -| `adapter-seam.test.ts` | `runtime.adapter`: reducer preview, async writes held, commit through the library; discarded writes never committed; direct library changes recorded and never held; rollback offered only when `set` exists | -| `adapters-react.test.ts` (happy-dom) | one shared atom per name; held writes visible only on apply, never on drop; StrictMode (one atom, balanced subscriptions); plain `useState` fallback without a runtime; `useAtom`; `useGenClass` throws without a runtime; live decision/intervention/status feeds with stable snapshots; real runtime: hold, discard, undo; user-handler writes never held | -| `adapters-redux.test.ts` | pass-through when nothing is held (reducer runs once); held dispatch applied once (reducer not re-run, subscribers notified once); re-run on moved state; discard reaches no reducer or subscriber; middleware sees each action once and thunks pass; no-op dispatch; `replaceReducer`; inner enhancers see the real action, GenClass writes as REPLACE; no runtime = unchanged store; real runtime hold/discard/undo | -| `adapters-zustand.test.ts` | merge semantics and `setState` through the pipeline; held writes merged over newer state; drops; replace, functional, no-op, extra `set()` args (`[value, true, "counter/set"]`); GenClass whole-state writes; no runtime = unchanged; real runtime hold/discard | -| `review-perf.test.ts` | the 5,000-item budgets in the performance table | +| `adapter-seam.test.ts` | with `holdWrites: true`, `runtime.adapter`: reducer preview, async writes held, commit through the library; discarded writes never committed; direct library changes recorded and never held; rollback offered only when `set` exists | +| `adapters-react.test.ts` (happy-dom) | one shared atom per name; held writes visible only on apply, never on drop; StrictMode (one atom, balanced subscriptions); plain `useState` fallback without a runtime; `useAtom`; `useGenClass` throws without a runtime; live decision/intervention/status feeds with stable snapshots; real runtime with `holdWrites: true` (the delivery decision is answered first, then the mutation one): hold, discard, undo; user-handler writes never held | +| `adapters-redux.test.ts` | pass-through when nothing is held (reducer runs once); held dispatch applied once (reducer not re-run, subscribers notified once); re-run on moved state; discard reaches no reducer or subscriber; middleware sees each action once and thunks pass; no-op dispatch; `replaceReducer`; inner enhancers see the real action, GenClass writes as REPLACE; no runtime = unchanged store; real runtime (`holdWrites: true`) hold/discard/undo | +| `adapters-zustand.test.ts` | merge semantics and `setState` through the pipeline; held writes merged over newer state; drops; replace, functional, no-op, extra `set()` args (`[value, true, "counter/set"]`); GenClass whole-state writes; no runtime = unchanged; real runtime (`holdWrites: true`) hold/discard | +| `review-perf.test.ts` | the 5,000-item budgets in the performance table (timing-sensitive; CI runs it alone with `--retry=2`) | | `review-precision.test.ts` | closing a selection (null) is not an inconsistency (`!= null` needs 6); lingering violations do not freeze snapshots; transition-profile precision | -| `situation.test.ts` | mutation and inconsistency situations end to end (fact wording, `["ignore","rollback"]` offered) | -| `batch3.test.ts` | state lines never print `parent = undefined`; item-change summaries; "changed twice … and is back to 6"; pending-local-change fact; a provider that never answers does not block later decisions (held write plus a write queued behind it both apply; the runtime abandons the first request after budget + 2 s) | +| `situation.test.ts` | delivery, mutation ("an older task's write over a newer task's (no delivery decision covers it)") and inconsistency situations end to end (fact wording, `["ignore","rollback"]` offered) | +| `batch3.test.ts` | redaction of an `auth` store by leaf field (batch 5); state lines never print `parent = undefined`; item-change summaries; "changed twice … and is back to 6"; pending-local-change fact; a provider that never answers does not block later decisions (now on the default path: both writes apply at once and `a` ends at 2; the test comment about giving up after budget + 2 s describes the old hold path) | | `review-actions.test.ts` | error-trigger rollback offered only when the failing chain wrote state; never reverts other chains' writes | | `learn.test.ts` | transition trigger at a settled point; chain-revert rollback text "Restored list.items to their values before …" | | `policy.test.ts` | observe mode never holds; `pause()`/`resume()` gating; loading model fails open with no decision | -| `smoke.test.ts` | atoms apply synchronously when nothing is salient; causality user -> fetch -> json -> set; stale write discarded in guard mode | +| `smoke.test.ts` | atoms apply synchronously when nothing is salient; causality user -> fetch -> json -> set; "holds a stale response, asks the model and drops its stale writes in guard mode" (delivery `discard`, explicit `mode: "guard"`) | | `review-redaction.test.ts` | the custom `redact` applies to learned-invariant facts | | `review-timers.test.ts` | a state write after a 200,000-tick timer loop does not throw | +| `nan.test.ts` (commit ad24804, after situation-v1) | an atom holding `NaN` builds situations without infinite recursion (`util.ts` -> `describe` now compares the redactor's output with `Object.is`) | | `context.test.ts` | writer attribution of state writes: after fetch -> json -> `set`, the `state` event's `op` is the fetch op, whose cause and root are the user action; two concurrent click -> fetch -> `set` chains writing two atoms keep their own writers and roots | | `dom.test.ts` | writes made by the app's click handler are user writes and are never held | | `devtools-runtime.test.ts` | the devtools Interventions tab's undo button applies a write GenClass dropped (`search.results` goes from 4 to 8 items) | @@ -620,34 +704,45 @@ Doc-versus-code mismatches (the code is right): | `Runtime.adapter` | CONTRACT §2's `Runtime` interface lists only `atom`, `guard`, `expect` | `adapter()` is public (`types.ts` `Runtime.adapter`); API.md documents it | `types.ts` | | `holdBudgetMs` default | CONTRACT §8: 300 | `"auto"` (150 to 800 ms; 300 only when nothing is known) | `decide/policy.ts` -> `holdBudget` | | "could not be held" fact | STATUS.md: when an in-place update cannot be detached, "the write applies at once with a fact" | such a write is committed in `propose` without being gated, so `mutationFacts`' `m.unholdable` fact is never produced | `hub.ts` -> `propose`; `situation/facts.ts` | -| Example store names | README "State it can protect" and `react.ts` header: `useGenClassState("search.results", [])`; `test/smoke/smoke.sh`: `rt.atom("search.results", [])` | dotted names break path-to-store lookups (see Gotchas) | `hub.ts` -> `field`/`leaf`; `situation/build.ts` -> `stateLines` | -| UI-NEEDS item 2 | `packages/runtime/UI-NEEDS.md` asks for `react-dom` / `@types/react-dom` as devDependencies | both are already in `packages/runtime/package.json` devDependencies (stale request) | `package.json` | +| Example store names | `packages/runtime/README.md` "State it can protect" and `react.ts` header: `useGenClassState("search.results", [])`; `test/smoke/smoke.sh`: `rt.atom("search.results", [])` | dotted names break path-to-store lookups (see Gotchas) | `hub.ts` -> `field`/`leaf`; `situation/build.ts` -> `stateLines` | +| UI-NEEDS item 2 | `packages/runtime/UI-NEEDS.md` asks for `react-dom` / `@types/react-dom` as devDependencies; STATUS.md "Open issues" repeats it | both are already in `packages/runtime/package.json` devDependencies (stale request) | `package.json` | | Adapter signatures | API.md "Adapters and devtools": `genclassEnhancer(runtime, { name })`, `genclass(runtime, name)(stateCreator)` | both also take `StoreOptions` (`resync`, `hold`, `describe`): Redux through `GenclassEnhancerOptions<S> extends StoreOptions<S>`, Zustand through a third `opts` parameter. This is an omission, not a contradiction | `adapters/redux.ts`, `adapters/zustand.ts` | | `mutationProposed` coverage | `types.ts` `RuntimeHooks.mutationProposed`: "Called synchronously inside atom.set / guarded set / adapter writes, before gating" | not called for writes after `destroy()` (they go straight to `hub.write`) or for a deferred write's re-proposal | `runtime.ts` -> `handle`, `adapter`; `hub.ts` -> `defer` | | `MAX_FIELDS_PER_STORE` | the constant's name reads as a hard per-store limit | a per-object pre-check; a store can exceed 200 fields | `fields.ts` -> `flatten` | -| Code comments in scope | `fields.ts` `FieldChange.delta` comment gives the example `"n:+1"`; `hub.ts` `RecentChange.key` comment says "Hash of paths + deltas"; `situation/env.ts` `SitEnv.lastConsistent` says "Last snapshot at which all learned invariants held" | `deltaOf` emits `n:1` (no `+` sign; `Number(d.toPrecision(12))`); `key` is the plain string `paths\|path=delta;…`, not a hash; `lastConsistent` is the newest snapshot at which nothing *newly* broke | `fields.ts` -> `deltaOf`; `hub.ts` -> `record`; `runtime.ts` -> `settled`, `makeEnv` | +| Code comments in scope | `fields.ts` `FieldChange.delta` comment gives the example `"n:+1"`; `hub.ts` `RecentChange.key` comment says "Hash of paths + deltas"; `situation/env.ts` `SitEnv.lastConsistent` says "Last snapshot at which all learned invariants held" (`runtime.ts` `snaps` says "every learned invariant held"); `hub.ts` `StaleMark.why` example starts "written by the response …"; `runtime.ts` `LATE_REVERT_MS` mentions only a held write whose budget expired | `deltaOf` emits `n:1` (no `+` sign; `Number(d.toPrecision(12))`); `key` is the plain string `paths\|path=delta;…`, not a hash; `lastConsistent` is the newest snapshot at which nothing *newly* broke; `markWrites`/`onChannel` build `why` starting with "by …" or "after …" (`markFacts` supplies "written Xs ago"); the window also applies to background decisions on the default path | `fields.ts` -> `deltaOf`; `hub.ts` -> `record`; `runtime.ts` -> `settled`, `makeEnv`, `markWrites`, `mutationController` | +| `mutation` pipeline | CONTRACT §4: salient writes are **held** until a decision or the hold budget, then applied in proposal order | by default nothing is held: writes apply at once and are decided in the background (late revert ≤ 2 s); holds only with `policy.holdWrites: true`. API.md "State" and STATUS.md "Batch 4" agree with the code | `hub.ts` -> `propose`; `runtime.ts` -> `observeWrite`; `types.ts` `PolicyOptions.holdWrites` | +| Invariant templates | CONTRACT §4 lists 9 templates, all learned after ≥ 3 settled snapshots | 10 templates (`count` added); `eq` between unrelated names and unrelated `count` also need 3 distinct values; numeric `in` needs an id column or related names; version-like names are excluded (STATUS "F8") | `invariants.ts` -> `propose`, `supported` | +| `default-mode.test.ts` comment | "an async adapter write is committed at once (guard would hold it)" | guard does not hold store writes either unless `policy.holdWrites` is on | `hub.ts` -> `propose` | +| `batch3.test.ts` "a provider that never answers…" comment | "the runtime gives up on w1" after budget + 2 s | default path: `w1` is a background decision with a 5 s deadline, and both writes already applied | `runtime.ts` -> `trigger` (`BACKGROUND_DEADLINE_MS`) | +| `hub.ts` comment in `propose` | "a late revert under the strict rules" | correct, but the rules live in `RuntimeImpl.mutationController.revertable` + `StoreHub.revertable`, not in the hub branch | `runtime.ts` -> `mutationController` | Open issues relevant to this scope: -- **User writes overtaken by held writes** (`demos/NEEDS.md` §1, CORE, product risk): +56% visible jump-backs on the board demo in guard mode with zero actions executed. The proposed fix is in recipe 5. Still open at 654d822; the code is unchanged since `situation-v1`. -- **Hold latency** (`demos/NEEDS.md` §2): typeahead result writes are salient on clean runs (127 of 148 held, median 543 ms). Suggestions there: do not hold when recent decision latency exceeds the budget; drop superseded queued decisions. This belongs to the policy and decider side; see [decide-policy-actions.md](decide-policy-actions.md). -- **App-level snapshots miss held writes** (`demos/NEEDS.md` §1): the board demo's own whole-board rollback on a failed move (`demos/src/demos/board/main.ts`, `set({ cards: before })`) captures `before` while GenClass is holding writes, so restoring it erases more (cards stuck "syncing": 6 Off, 9 Guard, 10 Heal). This is the app's rollback, not GenClass's `rollback` action (Guard executed 0 actions in those runs), but it is another consequence of holding. -- Unverified-by-test findings above: the unreachable `too late to revert` branch, dotted store names, the stale snapshot of a top-level store with more than 32 keys, value writes of mutated-in-place objects, in-place value replacement in a large collection, library listeners throwing during commit, `structuredClone` prototype loss, and the unused `StoreHub.mutations` map. +- **Resolved since 654d822:** "user writes overtaken by held writes" (`demos/NEEDS.md` §1: +56% visible jump-backs on the board demo) is fixed twice over: store writes are not held by default, and with `holdWrites` a bypass write flushes the store's held writes first (`atoms.test.ts` DEMOS regression). `demos/NEEDS.md` itself still describes the old runs; the demos have not been re-run on this tree (HANDOFF: demos rerun comes after the v2 model). +- **Resolved after b435acb: flushed held write, then budget expiry (`holdWrites` only).** A later `discard` was recorded as executed but changed nothing (flow 7, step 3). `gateAndQueue`'s `.then`/`.catch` now ignore a verdict for a write that is already `done`; covered by `atoms.test.ts` "a held write applied early by a user write stays applied when its hold budget expires; a later discard reverts it". No situation text changed. +- **App-level snapshots miss held writes** (`demos/NEEDS.md` §1, board demo's own rollback capturing `before` while writes are held): moot by default (nothing held); still possible with `holdWrites: true`. +- **Hold latency** (`demos/NEEDS.md` §2): store writes no longer wait; responses and messages may (delivery holds, bounded by the hold budget and skipped when `expectedLatency()` exceeds it). See [decide-policy-actions.md](decide-policy-actions.md). +- **`holdWrites` and library reads** (STATUS "Open issues"): `store.getState()` in Redux middleware and Zustand `get()` do not see held writes. Default off; per-store `hold: false`. +- **Count-by-group cost** (STATUS "Open issues"): about +0.5 ms (STATUS) to +2.3 ms (perf note) per settled point with a large unchanged adapter store; bounded by 24 arrays × 8 columns × 8 values × 64 numbers. +- **No situation-v2 model exists yet** (HANDOFF / OPEN_TASKS): the R17 model on the train VM is situation-v1 and does not match this runtime; `@genclass/runtime-model` is not published. Store behaviour in guard mode with a real model is therefore untested end to end; the unit tests use scripted deciders. +- Unverified-by-test findings above: dotted store names, the stale snapshot of a top-level store with more than 32 keys, value writes of mutated-in-place objects (`holdWrites`), in-place value replacement in a large collection, library listeners throwing during commit, `structuredClone` prototype loss, discard marks outliving `pause()`, and the unused `StoreHub.mutations` map. - Dead or unused code paths: - `RuntimeImpl.rollback(stores, violationIds, beforeSeq?)`: no caller passes `beforeSeq`, so inconsistency rollback always uses the newest snapshot. `snapshotBefore` is used only for `SitEnv.consistentBefore` (facts). - `StoreHub.revertable`'s `the write changed nothing` is unreachable: `appliedSeq` is set only when a write changed something, and the earlier `the write was not applied` check already catches the other case. - - The mutation controller's `too late to revert` branch is effectively unreachable: the decision deadline (`t0 + budget + LATE_REVERT_MS`) passes before any held write can be more than 2 s past its apply (see flow 7). + - The `unholdable` fact in `situation/facts.ts` -> `mutationFacts` is never produced (unholdable writes commit in `propose` without a trigger, and by default `mayHold` is false so nothing is ever marked unholdable). - `RuntimeImpl.onApplied` takes `m` but ignores it (`void m`). -- `OPEN_TASKS.md` lists the runtime as frozen at `situation-v1`. Changes here affect the final data and training plan, so check with the lead first. + - No longer dead: the `too late to revert` branch (reachable for background decisions, 5 s deadline; asserted in `atoms.test.ts`). +- The training format is frozen at `situation-v2` (HANDOFF.md) while SIM and REAL generate v2 data on Azure; `OPEN_TASKS.md`'s Done section records `situation-v1` (batch 3, round 1) as history. Changes to text-producing code here affect that data, so check with the lead first. ## Related docs - [public-api-and-lifecycle.md](public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, options, pause/destroy. - [observe-and-trace.md](observe-and-trace.md): ops, the ambient op, `Context.isUserSync`, causality. - [learn-situation-triage.md](learn-situation-triage.md): mutation and inconsistency facts, triage, state lines, transition profiles. -- [decide-policy-actions.md](decide-policy-actions.md): the trigger/decision flow, policy gate, hold budget, actions, undo, reports. +- [decide-policy-actions.md](decide-policy-actions.md): the trigger/decision flow, the `delivery` trigger, policy gate, hold budget, expected latency, actions, undo, reports. - [devtools.md](devtools.md): the overlay (it uses the public API and the React feeds' sources). -- [build-test-release.md](build-test-release.md): the VM, vitest and the npm subpath exports. -- [../overview.md](../overview.md#4-walkthrough-a-typeahead-stale-write): a held mutation end to end +- [build-test-release.md](build-test-release.md): where to run things, vitest, CI and the npm subpath exports. +- [../realapps.md](../realapps.md): the real-browser corpus and the never-worse sweep that exercises the adapters on real stacks. +- [../overview.md](../overview.md#4-walkthrough-a-stale-typeahead-response-held-at-delivery-and-dropped): the typeahead stale-response walkthrough (in situation-v2 the stale response is a `delivery` decision, not a held mutation) - [../glossary.md](../glossary.md) - [../model-io-contract.md](../model-io-contract.md), [../sim.md](../sim.md), [../demos.md](../demos.md), [../status-and-known-issues.md](../status-and-known-issues.md). -- Existing specs: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) (§4 State, §7 actions), [../../runtime/API.md](../../runtime/API.md) ("State", "Adapters and devtools"), [../../runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md); [../../../packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md); [../../../demos/NEEDS.md](../../../demos/NEEDS.md). +- Existing specs: [../../runtime/CONTRACT.md](../../runtime/CONTRACT.md) (§4 State, §7 actions), [../../runtime/API.md](../../runtime/API.md) ("State", `policy.holdWrites`, "Adapters and devtools"), [../../runtime/ARCHITECTURE.md](../../runtime/ARCHITECTURE.md); [../../../packages/runtime/STATUS.md](../../../packages/runtime/STATUS.md); [../../../demos/NEEDS.md](../../../demos/NEEDS.md); [../../../HANDOFF.md](../../../HANDOFF.md). diff --git a/docs/agents/sim.md b/docs/agents/sim.md index 565b31ee..95a87f42 100644 --- a/docs/agents/sim.md +++ b/docs/agents/sim.md @@ -1,122 +1,151 @@ # sim/: the training-data simulator (@genclass/sim) -> **Scope:** `sim/README.md`, `sim/NEEDS.md`, `sim/package.json`, `sim/tsconfig.json`, `sim/tsup.config.ts`, -> `sim/vitest.config.ts`, `sim/src/**`, `sim/test/**`, `sim/scripts/**`, `sim/samples/**`. -> **Read this when:** you generate or regenerate training data; change a feature combinator, domain, chaos model, -> cost weight, label rule, ask question, split or budget; debug a dropped trajectory, a `prefix-mismatch`, a wrong -> diagnosis label or an odd action distribution; or need to know exactly what a CONTRACT-D row contains. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `sim/README.md`, `sim/NEEDS.md`, `sim/SEPARABILITY.md`, `sim/package.json`, `sim/tsconfig.json`, +> `sim/tsup.config.ts`, `sim/vitest.config.ts`, `sim/src/**`, `sim/test/**`, `sim/scripts/**` (incl. `cluster/`), +> `sim/samples/**`. +> **Read this when:** you generate or regenerate training data (gold, unlabeled or on-policy rows); change a feature +> combinator, domain, persona, chaos regime, cost weight, label rule (incl. S1/S2), ask question, split or budget; +> debug a dropped trajectory, a `prefix-mismatch`, a wrong diagnosis label or an odd action distribution; or need to +> know exactly what a CONTRACT-D row contains. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - The sim is a private Node package (`@genclass/sim`, ESM, Node 22) that builds **random web-app programs** from - 15 feature combinators x 55 domains, runs them with **simulated users** on a **simulated network and server** - inside a **deterministic virtual event loop**, and drives the **real runtime** (`createRuntime` from - `@genclass/runtime`, loaded dynamically) through it. Nothing in the runtime knows about the sim. + **46 feature combinators** (15 round-1 + 31 round-2) x **115 domains** (55 + 60), runs them with **simulated users** + (5 persona kinds) on a **simulated network and server** (8 chaos regimes, offline windows, socket drops, clock + skew, other tabs) inside a **deterministic virtual event loop**, and drives the **real runtime** (`createRuntime` + from `@genclass/runtime`, loaded dynamically) through it. Nothing in the runtime knows about the sim. +- The runtime is **situation-v2** (tag `situation-v2` = 6e5e86e): responses and WebSocket messages are decided at the + network boundary (trigger **`delivery`**: `deliver` / `discard` / `defer`), and `mutation` is non-blocking. The sim + correlates delivery subjects and labels them from the writes they cause. The sim is unchanged between that tag and + b435acb; our default-mode change does not affect it (the sim passes `mode: "heal"` explicitly). - Every time the runtime calls its `DecisionProvider.evaluate`, the sim's recording decider stores the request verbatim (`state`, `questions`); those bytes become a training row's model input. The sim never writes situation text itself. -- Labels come from **counterfactual outcomes**: for a sampled decision point *k*, the scenario is re-run once per - applicable action with that action forced at *k* (and passive afterwards), over up to **K = 3 paired futures**; - each run is scored by `runCost` against the **ideal run** (same intents, zero latency, no failures, no accidental - clicks, exactly-once). `actionLabel` turns costs into a soft `action` distribution (precision first: tier - premiums, ties pinned to passive). -- The `diagnosis` label is a hard label from the sim's own knowledge (`Knowledge`: intents, app ops, writes, error - tags) via `diagnose`, not from the runtime's text. Rows also include diagnosis-only rows and `ask` rows with exact - programmatic answers. -- Determinism rests on **keyed RNG forks** (`Rng.fork(label)` never depends on draw order), request draws keyed by - (seed, request identity, occurrence), **content-derived server ids**, and a replay check that every decision up - to *k* is byte-identical (`fp`) to the base run. -- Splits are per scenario: `test` = 10 held-out domains, or a held-out family hash (17%), or a held-out pattern; +- Three row types (`gen.js` mode): **gold** (default; counterfactual action labels), **unlabeled** (`--unlabeled`: + base run only, every decision point, gold diagnosis, no action label; README: ~150 vs ~4.4 rows/s per worker for gold), **on-policy** + (`--on-policy <export dir>`: a real model decides through the runtime's production gate; its points are + counterfactual-labelled, for DAgger). +- Gold labels come from **counterfactual outcomes**: for a sampled decision point *k*, the scenario is re-run once + per applicable action with that action forced at *k* (and passive afterwards), over **K = 2-3 paired futures**; + each run is scored by `runCost` against the **ideal run**. **S2** (`sim/src/run/latent.ts`): futures 1-2 also + re-draw what a runtime cannot observe (later user timing, remaining outage/offline/slow lengths, whether an + ambiguous failed write committed, remaining time of in-flight requests, accidental-vs-intended repeats), so a label + is the expected cost given the observable situation. `actionLabel` turns costs into a soft `action` distribution. +- The `diagnosis` label is a hard label from the sim's own knowledge (`diagnose`). **S1**: when a non-passive action + beats passive by >= 1 (`S1_GAP`) but the subject looks `expected`, the label names what the action repairs + (`diagnosisFromOutcome`; `meta.diagnosis_s1`). `delivery` diagnoses are the verdict of the first write the + delivered op/message makes. +- Determinism rests on **keyed RNG forks**, request draws keyed by (seed, request identity, occurrence), + **content-derived server ids**, and a replay check that every decision up to *k* is byte-identical (`fp`) to the base + run (a latent re-draw that breaks it falls back to a network-only future: `info:latent-fallback`). +- Splits are per scenario: `test` = 19 held-out domains, a held-out family hash (17%), a held-out pattern, or (new) + any program using one of 6 held-out round-2 features (`TEST_FEATURES`; `SIM_FEATURE_HOLDOUT=off` disables it); `dev` = 3% of remaining families; only 33% of test trajectories are kept (`--test-keep`). -- Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/` in phase B). Row shape: - `{id, split, family, state, questions, labels, meta}` (CONTRACT-D). -- **Where to run.** The original team ran sim builds, tests and generation only on the VM (`scripts/vm.sh run|exec - sim '...'`; CONTRACT §0 rule 5, the author's Mac has 8 GB). Under the 2026-10-07 run policy in AGENTS.md, the runtime's - install, typecheck, build and unit tests run locally, but ask the user before running the sim's vitest suites, - `gen.js` or `sim/scripts/*` ([where to run things](runtime/build-test-release.md#where-to-run-things)). - Committed samples in `sim/samples/`; the frozen-runtime phase A (600,676 rows) stats are in - `sim/samples/stats-final-a.json`. +- Output: `<out>/{train,dev,test}.jsonl` + `stats.json` (or resumable `parts/`). Row shape: + `{id, split, family, state, questions, labels, meta}` (CONTRACT-D). Large runs go through the Azure cluster + scripts (`sim/scripts/cluster/`), dedupe + gz shards via `collect.py`. +- **Data on disk is mostly situation-v1.** Phase A (600,676 rows) and phase B (1,415,344 rows) were generated on the + situation-v1 runtime and 15 features; they do not match the v2 runtime. Per [HANDOFF.md](../../HANDOFF.md)/training/NEEDS the v2 runs + (>= 10M gold + >= 50M unlabeled, seeds 11e9 / 16e9 + NN x 1e8) are being generated on Azure into + `train:/data/sim-out/v2-*` by the colleague; nobody on our side touches Azure. +- **Where to run.** Light local checks are fine on this machine: `cd sim && npx tsc -p tsconfig.json --noEmit` and + `SIM_RUNTIME=real npx vitest run` (both were run when these docs were written, on 2026-10-08: tsc clean, 19 tests passed in 5 files; needs + the runtime built first). **Ask the user** before `gen.js`, `smoke.js`, anything in `sim/scripts/` (incl. the cluster + scripts and separability analysis) and anything touching Azure + ([where to run things](runtime/build-test-release.md#where-to-run-things)). - Any change to the runtime's situation text (`packages/runtime/src/situation/*`) invalidates all data: rebuild the - runtime, regenerate everything. Any change to sim scenario generation changes every seed's world. -- Vitest suites default to a crude **fake runtime** (`createFakeRuntime`); set `SIM_RUNTIME=real` to test against the - real one (2 oracle tests run only then). `gen.js` uses the real runtime unless `--allow-fake`. + runtime, regenerate everything. Any change to scenario generation changes every seed's world. +- Vitest suites default to a crude **fake runtime** (`createFakeRuntime`, no `delivery` trigger); set + `SIM_RUNTIME=real` to test against the real one. `gen.js` uses the real runtime unless `--allow-fake`. ## Files | path | role | key exports / entry points | |---|---|---| -| `sim/package.json` | private package `@genclass/sim` v0.0.0, `bin: genclass-sim -> dist/gen.js` | scripts `build` (tsup), `typecheck`, `test` (vitest run), `gen`, `sample`, `build:runtime-core`; dep `@genclass/runtime: "*"` | +| `sim/package.json` | private package `@genclass/sim` v0.0.0, `bin: genclass-sim -> dist/gen.js` | scripts `build` (`tsup && npm run build:model-host`), `typecheck`, `test` (vitest run), `gen`, `sample`, `build:runtime-core` (runtime `src/index.ts` only), `build:model-host` (runtime `src/model/host.ts` -> `sim/dist/model-host/`); dep `@genclass/runtime: "*"` | | `sim/tsup.config.ts` | ESM bundle, target node22, `@genclass/runtime` external | entries `gen`, `worker`, `index`, `smoke` -> `dist/{gen,worker,index,smoke}.js` | | `sim/tsconfig.json` | extends `../tsconfig.base.json`, `noEmit`, includes `src`, `test` | - | | `sim/vitest.config.ts` | node env, `pool: "forks"`, test/hook timeout 120000 ms | - | | `sim/src/index.ts` | library re-exports | `buildScenario`, `splitOf`, `runScenario`, `generateTrajectory`, `actionLabel`, `runCost`, `COST_WEIGHTS` (= `W`), `LABEL_PARAMS` (= `LABEL`), `transformQuestions`, `ACTION_PARA`, `createFakeRuntime`, `VirtualLoop` | -| `sim/src/types.ts` | structural mirror of the runtime model seam + row types | `JevState`, `Question`, `NoulAnswer`/`ChoiceAnswer`/`ScoreAnswer`/`Answer`, `TriggerKind`, `ModelStatus`, `SubjectInfo`, `EvaluateRequest`, `DecisionProvider`, `Clock`, `PASSIVE`, `DIAGNOSES`, `Diagnosis`, `Row`, `Label` | -| `sim/src/rng.ts` | seeded PRNG (sfc32, splitmix32 init, 12 warm-up draws) with keyed forks | `hash32` (FNV-1a + murmur3 finalizer), `hashAll`, `Rng` (`fork`, `next`, `int`, `float`, `bool`, `pick`, `weighted`, `weightedKey`, `normal`, `lognormal`, `shuffle`, `sample`, `token`), `u01`/`keyedLognormal` (unused) | -| `sim/src/loop.ts` | virtual event loop | `VirtualLoop` (`schedule`, `at`, `cancel`, `afterTask`, `clockFor`, `settle`, `runUntil`, `pending`, `nextTime`, `stop`; fields `onSettled`, `onAppError`, `internalErrors`, `tasksRun`), `TaskOwner` (`app net runtime user sim`), `LoopError` | -| `sim/src/net/server.ts` | virtual server: DB + routed endpoints + idempotency keys | `Db`, `VirtualServer`, `API_STYLES`/`ApiStyle`, `canonical`, `clone`, `ServerSnapshot`, `ServerRequest`, `ServerResponse`, `Handler`, `RouteMeta`, `ServerLogEntry`, `Collection`, `Doc`, `Item`, `Json`, `IdStyle` | -| `sim/src/net/network.ts` | virtual network: latency, chaos, push channel, `fetch` | `Network`, `NetProfile`, `IDEAL_PROFILE`, `BASE_URL`, `NetEntry`, `NetCause`, `Win`, `Outage`/`OutageMode`, `SlowPeriod`, `ServerBug`/`BugKind`, `Lat`, `PushSub`, `SIM_OP_HEADER`, `simOpHeaderValue`, `parseSimOpHeader`, `makeResponse` | -| `sim/src/app/vocab.ts` | 55 domain vocabularies (2 entities each) | `DOMAINS`, `Domain`, `Entity`, `ROUTE_WORDS` (unused) | -| `sim/src/app/naming.ts` | per-program naming: route prefix/casing, store names, field synonyms | `Naming` (`field`, `word`, `store`, `route`, `owner`), `Casing`, `cased`, `camel`, `title`, `splitWords` | -| `sim/src/app/feature.ts` | feature contract, user model, personas, relations | `FeatureDef`, `FeatureCtx`, `FeatureClient`, `UserStep`, `StepIntent`, `UiKind`, `WorldCtx`, `ExternalEvent`, `Relation`, `rel`, `Persona`, `randomPersona`, `UserModel` (`think`, `key`, `type`, `click`), `itemName`, `numIn`, `round2` | -| `sim/src/app/env.ts` | what app programs see: global, stores, sockets, uncaught errors | `AppEnv` (`fetch`, `store`, `socket`, `subscribe`, `setRoute`, `uncaught`, `snapshot`, timers), `PlainBackend`, `SimGlobal`, `Store`, `StoreOpts`, `WriteMeta`, `StoreBackend`, `AtomLike`, `RegisteredStore` | -| `sim/src/app/kit.ts` | feature building blocks: tagged ops, requests, writes, error surfacing | `Kit` (`op`, `call`, `write`, `shownError`, `spawn`), `OpInit`, `CallOpts`, `CallResult`, `HttpError`, `errorFor`, `sleepJitter` (unused) | -| `sim/src/app/features/index.ts` | registry and frequency weights | `FEATURES`, `FEATURE_WEIGHTS` | +| `sim/src/types.ts` | structural mirror of the runtime model seam + row types | `JevState`, `Question`, `Answer` types, `TriggerKind` (now incl. `delivery`), `EvaluateRequest`, `DecisionProvider`, `Clock`, `PASSIVE` (`delivery: "deliver"` added), `DIAGNOSES`, `Row`, `Label` | +| `sim/src/rng.ts` | seeded PRNG (sfc32, splitmix32 init, 12 warm-up draws) with keyed forks | `hash32`, `hashAll`, `Rng` (`fork`, `next`, `int`, `float`, `bool`, `pick`, `weighted`, `weightedKey`, `normal`, `lognormal`, `shuffle`, `sample`, `token`), `u01` (used by round-2 servers), `keyedLognormal` (unused) | +| `sim/src/loop.ts` | virtual event loop | `VirtualLoop` (`schedule`, `at`, `cancel`, `afterTask`, `clockFor`, `settle`, `runUntil`, `hold` (real async work, e.g. model inference, finishes before virtual time moves), `advance` (long task: jumps virtual time), ...), `TaskOwner`, `LoopError` | +| `sim/src/net/server.ts` | virtual server: DB + routed endpoints + idempotency keys | `Db`, `VirtualServer`, `API_STYLES`, `canonical`, `clone`, `ServerSnapshot`, `RouteMeta`, ... | +| `sim/src/net/network.ts` | virtual network: latency, chaos, offline windows, push channel, `fetch`, S2 latent re-draws | `Network` (fields `future`, `latent`), `NetProfile` (+ `offline`, `socketDrops`), `IDEAL_PROFILE`, `BASE_URL`, `NetEntry`, `NetCause` (+ `offline`), `Win`, `Outage`, `SlowPeriod`, `ServerBug`, `Lat`, `SIM_OP_HEADER`, `simOpHeaderValue`, `parseSimOpHeader`, `makeResponse` | +| `sim/src/app/vocab.ts` | 55 round-1 domain vocabularies; the `D`/`E` builders are now exported | `DOMAINS` (55 only), `D`, `E`, `Domain`, `Entity`, `ROUTE_WORDS` (unused) | +| `sim/src/app/vocab2.ts` | 60 round-2 domains | `DOMAINS2` | +| `sim/src/app/naming.ts` | per-program naming | `Naming`, `Casing`, `cased`, `camel`, `title`, `splitWords` | +| `sim/src/app/feature.ts` | feature contract, user model, personas, relations | `FeatureDef` (+ optional `env()`), `FeatureCtx` (+ `clean`), `WorldCtx` (+ `otherTab`), `UserStep`, `Relation`, `rel`, `Persona` (+ `kind`, `keyboard`, `tabSwitchPerMin`), `randomPersona`, `UserModel` | +| `sim/src/app/env.ts` | what app programs see | `AppEnv` (`fetch`, `store`, `socket`, `subscribe`, `setRoute`, `uncaught`, `snapshot`, timers, `clientNow` (skewed clock, `EPOCH` = 2026-10-07 14:00 UTC), `busy` (long task), `on` (global events), `online`, `channel` (BroadcastChannel)), `PlainBackend`, `SimGlobal` (+ EventTarget methods, `navigator`, `localStorage`, `document.visibilityState`), `pushIds`, `pushIdsByData` | +| `sim/src/app/kit.ts` | feature building blocks | `Kit` (`op`, `call`, `write`, `shownError`, `spawn`), `OpInit` (now has `anomaly`), `HttpError`, `errorFor` | +| `sim/src/app/features/index.ts` | registry and frequency weights | `FEATURES` (46), `FEATURE_WEIGHTS` | | `sim/src/app/features/common.ts` | shared helpers | `ContentBook`, `idsKey`, `seedItems`, `weightsOf`, `queryWords`, `errMsg`, `apiOf` | -| `sim/src/app/features/{search,editor,form,cart,toggle,counter,poll,board,chat,settings,nav,list,bulk,auth,benign}.ts` | the 15 combinators | one `FeatureDef` each (see [Feature combinators](#feature-combinators-and-the-bugs-they-create)) | -| `sim/src/world/scenario.ts` | seed -> scenario; splits; vocab randomisation; chaos profile | `buildScenario`, `BuildOptions` (`kinds`, `chaos`, `duration`, `domain`: tests only), `Scenario`, `FeatureInst` (`kind`, `id` = `f<i>`, `route`, `spec`, `pattern`), `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `familyHeldOut`, `DEFAULT_DIAGNOSES`, `Chaos` | -| `sim/src/run/rt.ts` | runtime slice the sim uses; `createRuntime` options; loader | `RuntimeLike`, `RuntimeOptions`, `RuntimeFactory`, `RuntimeHooksLike`, `SituationLike`, `AtomLike`, `createOptions`, `realRuntimeFactory` | -| `sim/src/run/runner.ts` | runs one scenario (ideal or real), recording decider, correlation, snapshots | `runScenario`, `RunOptions`, `RunResult`, `Snapshot`, `DecisionRec`, `AskRec`, `AskFacts`, `ExplorePolicy` | -| `sim/src/run/fake-runtime.ts` | **test double** of the runtime (crude text); rows marked `meta.runtime: "fake"` | `createFakeRuntime` (see [Fake runtime](#fake-runtime-test-double)) | -| `sim/src/run/transform.ts` | per-row action-option shuffle/drop; action paraphrases | `transformQuestions`, `Transformed` (`questions`, `dist`, `variant`), `ACTION_PARA` | -| `sim/src/oracle/knowledge.ts` | ground truth bookkeeping | `Knowledge`, `Intent`, `Mode`, `SimOp`, `SimWrite`, `ErrorTag`, `sigOf` | -| `sim/src/oracle/diagnose.ts` | diagnosis labels | `diagnose`, `diagnoseFailure`, `Subject`, `DiagCtx`, `fieldRefs`, `relationMatches` (unused) | -| `sim/src/oracle/cost.ts` | divergence, run cost, soft labels | `W`, `LABEL`, `TIER`, `runCost`, `CostBreakdown`, `actionLabel`, `ActionLabel`, `clientDist`, `serverDist`, `divergenceArea`, `relationViolation`, `valueDist` | -| `sim/src/ask/questions.ts` | programmatic `ask` questions with exact answers | `askQuestions`, `AskQ` (`qid`, `question`, `label`, `kind`); 11 generators in `GENS` (see [Ask questions](#ask-questions-simsrcaskquestionsts)) | -| `sim/src/gen/trajectory.ts` | one trajectory = ideal + base + counterfactuals -> rows | `generateTrajectory`, `pointCosts`, `GenOptions`, `PointStat`, `TrajectoryOut` | -| `sim/src/gen/worker.ts` | `worker_threads` worker: seeds -> rows -> shard/part files | (message protocol, see flow 1) | -| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample`, parts mode | `main`, `mergeParts` | +| `sim/src/app/features/{search,editor,form,cart,toggle,counter,poll,board,chat,settings,nav,list,bulk,auth,benign}.ts` | round-1 combinators (unchanged since 654d822) | one `FeatureDef` each | +| `sim/src/app/features/{infinite,upload,offline,wsreconnect,undo,reorder,querycache,graphql,saga,wizard,etag,presence,badge,facets,masterdetail,clockskew,longtask,cascade,exportjob,payment,inventory,prefetch,multitab,ratelimit,cdn,swcache,countdown,money,permissions,flags,schemadrift}.ts` | round-2 combinators | one `FeatureDef` each (see [Round-2 combinators](#round-2-combinators)) | +| `sim/src/world/scenario.ts` | seed -> scenario; splits; chaos regimes; clean runs | `buildScenario`, `BuildOptions` (`kinds`, `clean`, `chaos`, `duration`, `domain`), `Scenario` (+ `skewMs`, `windowEvents`, `clean`), `DOMAINS` (115 = `vocab.ts` + `vocab2.ts`), `splitOf`, `TEST_DOMAINS`, `TEST_PATTERNS`, `TEST_FEATURES`, `familyHeldOut`, `Chaos` | +| `sim/src/run/rt.ts` | runtime slice; `createRuntime` options; loader | `RuntimeLike`, `RuntimeOptions` (+ `production`), `createOptions`, `realRuntimeFactory` | +| `sim/src/run/runner.ts` | runs one scenario (ideal or real): recording decider, on-policy decider, correlation (incl. delivery), platform (storage, BroadcastChannel, offline, tab switches, socket drops) | `runScenario`, `RunOptions` (+ `onPolicy`, `future: FutureSpec`), `RunResult` (+ `firedSteps`), `DecisionRec` (+ `modelProbs`, `modelChoice`, `modelDiagnosis`, `ran`, `feature`, `diagFrom`, `probe`), `AskRec`, `ExplorePolicy` | +| `sim/src/run/latent.ts` | **S2**: futures re-draw unobservable latents | `FutureSpec`, `S2` (env `SIM_S2`), `futureProfile`, `futureStepTimes`, `REPEAT_PRIOR`, `repeatPrior`, `repeatOfIndex`, `idealRepeatSkips` | +| `sim/src/run/onpolicy.ts` | on-policy decider: the runtime's own model host in Node on onnxruntime-web WASM | `loadModelDecider(modelDir)` | +| `sim/src/run/fake-runtime.ts` | **test double** of the runtime (crude text, no `delivery`); rows marked `meta.runtime: "fake"` | `createFakeRuntime` | +| `sim/src/run/transform.ts` | per-row action-option shuffle/drop; action paraphrases | `transformQuestions`, `ACTION_PARA` | +| `sim/src/oracle/knowledge.ts` | ground truth bookkeeping | `Knowledge` (+ `onWrite`, `probe`, `currentPush`, `deliveringPush`, `rtPushOps`, `nextPush`), `SimOp`, `SimWrite` (+ `diag`, `push`), `sigOf` | +| `sim/src/oracle/diagnose.ts` | diagnosis labels | `diagnose` (+ `delivery` -> `undefined`, filled after the run), `diagnoseFailure` (+ `offline` -> failing), `Subject` (+ kind `push`) | +| `sim/src/oracle/cost.ts` | divergence, run cost, soft labels | `W`, `LABEL`, `TIER` (incl. `deliver` passive), `runCost`, `actionLabel`, `clientDist`, `serverDist`, `clientDivergenceAt`, `divergedFieldsAt` | +| `sim/src/oracle/probe.ts` | separability probes (analysis only, `SIM_PROBE=1`) | `PROBE`, `Probe`, `ProbeState`, `cellDiff`, `probeDecision`, `probeAfter` | +| `sim/src/ask/questions.ts` | programmatic `ask` questions with exact answers | `askQuestions`, `AskQ`; 11 generators | +| `sim/src/gen/trajectory.ts` | one trajectory -> rows (gold / unlabeled / on-policy) | `generateTrajectory`, `pointCosts`, `diagnosisFromOutcome`, `S1_GAP`, `metaOf`, `GenOptions` (+ `mode`, `model`, `maxUnlabeled`), `costMs`/`resetCostMs` (profiling), `latentFallbacks` | +| `sim/src/gen/worker.ts` | `worker_threads` worker | loads `loadModelDecider` once in on-policy mode | +| `sim/src/gen.ts` | CLI: worker pool, shard merge, `stats.json`, `--sample`, parts mode, row modes | no exports; internal `parse`, `main`, `mergeParts` (entry point `dist/gen.js`) | | `sim/src/gen/examples.ts` | `EXAMPLES.md` renderer | `renderExamples` | -| `sim/src/dev/smoke.ts` | dev tool: base runs on many seeds, print raw situations | CLI `dist/smoke.js [--seeds 40] [--from 1] [--fake] [--show <trigger\|all\|ask>] [--cf]`; prints decisions by trigger, correlation `trigger:how`, diagnoses, mutation subject roles, push writes, internal errors; `--cf` also runs `generateTrajectory` (maxPoints 4) on up to 20 seeds | -| `sim/scripts/final.sh` | final datasets on the train VM | `final.sh a \| b \| merge-b` | -| `sim/scripts/analyze.py` | dataset summary (works on merged files or `parts/`) | `python3 sim/scripts/analyze.py <dir>` | -| `sim/test/*.ts` | vitest suites (17 tests) | see [Tests](#tests) | -| `sim/samples/` | `sample.jsonl` (200 rows), `EXAMPLES.md` (16 rows), `sample-stats.json`, `stats-final-a.json` | - | -| `sim/NEEDS.md` | SIM -> CORE requests (all DONE per STATUS) | - | +| `sim/src/dev/smoke.ts` | dev tool | `dist/smoke.js [--seeds 40] [--from 1] [--fake] [--show <trigger\|all\|ask>] [--cf]`; `--cf` now runs `generateTrajectory` (maxPoints 6) on all `--seeds` and prints the slowest seeds and `runCost` time; `--profile [--per 4]` (ms/tasks/decisions per feature kind); `--repeat-prior N` (measures `REPEAT_PRIOR` on the fake runtime) | +| `sim/scripts/final.sh` | situation-v1 final datasets | `final.sh a \| b \| merge-b` | +| `sim/scripts/analyze.py` | dataset summary (merged files or `parts/`); now also per subject feature and unlabeled diagnosis counts | `python3 sim/scripts/analyze.py <dir>` | +| `sim/scripts/relabel.py` | re-derive gold action labels from `meta.cost_futures` (mirror of `actionLabel`) | `relabel.py IN OUT [--tau0 --se-mul --guard --heal --tie-eps --tie-penalty]` | +| `sim/scripts/separability*.py` | separability analysis (stage 1 rows; stage 2 probes; extra tables; GBDT check) | see `sim/SEPARABILITY.md` §9 | +| `sim/scripts/cluster/{bundle.sh,node_start.sh,orchestrate.sh,bigrun.sh,collect.py}` | distributed generation on Azure F80 nodes | see [flow 9](#9-cluster-runs-simscriptscluster) | +| `sim/test/*.ts` | vitest suites (19 tests in 5 files) | see [Tests](#tests) | +| `sim/samples/` | `sample.jsonl` (200 rows), `EXAMPLES.md` (16 rows), `sample-stats.json` (regenerated on a `delivery`-era runtime), `stats-final-a.json` (phase A, v1) | - | +| `sim/NEEDS.md` | SIM -> CORE requests | see [Drift](#drift-and-open-issues) | +| `sim/SEPARABILITY.md` | why R17 recalls few clear cases; the S1/S2/T1/F1-F9 proposals; first v2 check | - | ## Concepts and data structures | term | meaning (code) | |---|---| -| **scenario** | `Scenario` (`sim/src/world/scenario.ts`): one program (domain, 1-3 features + optional `benign`, naming, API envelope style `api`, `idStyle`), one user session (`steps: UserStep[]`), one network profile (`net: NetProfile`, `chaos`), `external: ExternalEvent[]`, timing (`warmup`, `tUser`, `tEnd`), `askTimes`, vocabulary overrides (`diagnoses`, `actionWords`), `modelMs`, `budget`. Fully determined by `seed`. | -| **trajectory** | one scenario processed by `generateTrajectory`: 1 ideal run + 1 base run + counterfactual runs -> rows. Rows of a trajectory share one split. | -| **feature / combinator** | `FeatureDef<S>`: `make(ctx) -> spec`, `pattern(spec)`, `server(spec, srv, db)`, `client(spec, env, kit) -> FeatureClient`, `session(spec, user, win)`, optional `external(...)`, `relations(spec)`. | -| **spec** | the per-program knob values a feature's `make` picks (guards vs defects). | -| **pattern** | variant tags from `pattern(spec)`, stored prefixed with the kind (e.g. `search/guard:none`). Used for held-out test patterns and `meta.patterns`. | -| **family** | program family = sorted unique feature kinds joined by `+` (e.g. `cart+search`). A row's `family` is `<program family>/<trigger>`. | -| **intent** | `Intent` in `Knowledge`: one user step; `key` = slot it targets, `mode` `replace` (newer replace-intents on the same key **supersede** older ones, `Knowledge.superseded`) or `accumulate`; `accidental` = double click / impatient re-click with `repeatOf`. | -| **sim op** | `SimOp`: an app-level request with `role`, `intent`, `key`, `idempotent`, `attempt`, `retryOf`, `dupOf` (repeat of another op), `anomaly` (typed `partial \| shape \| empty \| benign-change \| string`, but never set on ops in practice: `Kit.op` does not copy an `anomaly` field, so poll's `anomaly: "storm"` is dropped; features set `partial`, `shape` and `benign-change` on writes instead), `background`, `handled`, `classify()`, `rtOp` (runtime op id), `net` (network entry ids). Not the runtime's op. | -| **sim write** | `SimWrite`: one store write with `role`, `op`, `intent`, `key`, `fields` (top-level fields changed), `anomaly`, `classify()`, `rtMutation`. | -| **classify** | feature-provided closure on an op/write evaluated at decision time; returns a diagnosis (`stale`, `conflict`, `duplicate`, `expected`) or `undefined`, typically from content bookkeeping (`ContentBook` in search/cart: which intent the shown data reflects; editor keeps its own text map, board/poll compare versions/ranges). A returned label takes precedence in `diagnose`. | -| **relation** | `Relation {fields, desc, check(stores)}`: an invariant the app intends to keep (count = len(items), total = sum price*qty, badge = cart count, per-column/per-status counts). Ground truth for `inconsistent` and a cost term. | -| **ideal run** | `runScenario(scn, {ideal: true})`: no runtime (`PlainBackend` atoms), `IDEAL_PROFILE` network (0 latency, no failures/chaos, 0 push latency, 0 ms socket connect), accidental and conditional (`when`) steps skipped, app-generated duplicates (`dupOf`) share the original's result (`Kit.call`). The **intended outcome**. | -| **base run** | real runtime, recording decider, exploration policy, ask probes; `record: true`. | -| **counterfactual (cf) run** | real runtime, `forced` map (explored choices before *k*, action *a* at *k*, passive after), `fpUpTo: k`, `tStop: t_k + 15000`, optional `future`. | -| **decision point** | `DecisionRec` (`k` = 0-based index of `evaluate` calls in the run, `t`, `trigger`, `state`, `questions`, `actions` = keys of `questions.action.criteria`, `chosen`, `explored`, `diagnosis`, `subject`, `fakeDiagnosis`, `fp`). | -| **fp** | fingerprint `JSON.stringify([trigger, state, questions])`; cf runs must reproduce `fp` for every decision `<= k` or the point is dropped (`prefix-mismatch`). | -| **future** | `RunOptions.future = {k, salt, t}`. Future 0 = no salt (same draws as base). Futures 1..K-1 re-seed the draws made after the decision for network latency/failures/replica lag, push latency, model latency for `idx > k` and external events (+U(0,600) ms jitter) with a salt shared by all actions (common random numbers). App-code draws (`env.rng`) and the user session are not re-seeded. | -| **subject correlation** | mapping `EvaluateRequest.subject` (runtime ids) to sim knowledge: `Subject.kind` in `write`, `op`, `error`, `invariant`, `chain`, `unknown`; `DecisionRec.subject.how` in `subject`, `sync`, `chain`, `delivered`, `last`, `text`, `none`. | +| **scenario** | `Scenario` (`sim/src/world/scenario.ts`): one program (domain, 1-3 features + optional `benign`, naming, API envelope style, `idStyle`), one user session (`steps`, `persona`, `windowEvents`), one network profile (`net`, `chaos`), `external` events, timing (`warmup`, `tUser`, `tEnd`), `askTimes`, vocabulary overrides, `modelMs`, `budget`, `skewMs`, `clean`. Fully determined by `seed`. | +| **trajectory** | one scenario processed by `generateTrajectory`. Gold: 1 ideal run + 1 base run + counterfactual runs (+ re-seeded ideal runs). Unlabeled: 1 base run. Rows of a trajectory share one split. | +| **row mode** | `GenOptions.mode` / `gen.js` flag: `gold` (default), `unlabeled` (`--unlabeled`), `onpolicy` (`--on-policy <dir>`). | +| **feature / combinator** | `FeatureDef<S>`: `make(ctx) -> spec`, `pattern(spec)`, `server`, `client`, `session`, optional `external`, `relations`, and (new) `env(spec, rng, win)` returning `offline` windows, `socketDrops` windows and `skewMs` merged into the scenario. | +| **clean run** | `Scenario.clean` (5%, `R.fork("clean")`): chaos forced `calm`; spikes, transients, network errors, outages, slow periods, bugs, rate limits, capacity and replica lag removed; no feature `env()` conditions; persona `doubleClickP = impatientP = 0`; `FeatureCtx.clean` makes round-2 features pick correct guards. `meta.clean: true`; any non-passive answer there is a false positive. | +| **persona** | `Persona.kind` weighted casual 5, power 2, mobile 2, keyboard 1, novice 1 (`randomPersona`); kinds override typing/think/double-click/impatience/typo/tab-switch ranges. Keyboard personas activate controls with `key` steps (`Enter` p 0.8, else `Space`). `meta.persona`. | +| **chaos regime** | `"calm" \| "normal" \| "flaky" \| "degraded" \| "storm" \| "mobile" \| "peak" \| "deploy"`. `mobile`/`peak`/`deploy` start from the flaky/degraded/normal base profile and add their own conditions (`makeNet`). | +| **delivery** | situation-v2 trigger: a fetch response or WebSocket message about to reach the app; passive `deliver`, guard `discard` / `defer`. Subject = the runtime's fetch op or WebSocket *message* op. | +| **push id** | `Knowledge.nextPush`: every message the virtual socket dispatches gets an id (`pushIds` by event, `pushIdsByData` by payload); `know.deliveringPush` is ambient during dispatch so `opCreated` maps the runtime's `ws` message op -> push id (`know.rtPushOps`), and `know.currentPush` tags the writes the app handler makes (`SimWrite.push`). | +| **write verdict** | `SimWrite.diag`: every write is diagnosed with the `mutation` rules at proposal time (`know.onWrite` in `runScenario`). Used for `delivery` diagnoses and S1 rule a. | +| **pattern / family / intent / sim op / sim write / classify / relation** | as before: pattern tags `<kind>/<tag>`; family = sorted unique kinds joined by `+` (row `family` = `<program family>/<trigger>`); `Intent` with `key`, `mode`, `accidental`, `repeatOf`; `SimOp` with `role`, `intent`, `key`, `idempotent`, `dupOf`, `anomaly` (now really set: `Kit.op` copies it), `rtOp`, `net`; `SimWrite` with `fields`, `anomaly`, `rtMutation`; `classify()` closures; `Relation {fields, desc, check}`. | +| **ideal run** | `runScenario(scn, {ideal: true})`: no runtime, `IDEAL_PROFILE` (0 latency, no failures, no offline/socket drops), no clock skew, accidental and conditional steps skipped (in an S2 future: per `idealRepeatSkips`), app duplicates share the original result. | +| **base run** | gold/unlabeled: real runtime, recording decider, exploration, ask probes; on-policy: the model decides through the production gate, no exploration, no ask probes. | +| **counterfactual (cf) run** | real runtime, `forced` map (explored/ran choices before *k*, action *a* at *k*, passive after), `fpUpTo: k`, `tStop: t_k + 15000`, optional `future`. | +| **decision point** | `DecisionRec` (`k`, `t`, `trigger`, `state`, `questions`, `actions`, `chosen`, `explored`, `diagnosis`, `subject {kind, how, ref}`, `feature` (subject's feature kind), `diagFrom` (delivery), `fakeDiagnosis`, `fp`; on-policy: `modelProbs`, `modelChoice`, `modelDiagnosis`, `ran`; probe: `probe`). | +| **fp** | `JSON.stringify([trigger, state, questions])`; cf runs must reproduce `fp` for every decision `<= k` or the point is dropped (`prefix-mismatch`). | +| **future** | `RunOptions.future: FutureSpec = {k, salt, t, noLatent?, fired?}`. Future 0 = no salt. Futures 1..K-1 re-seed network/push/model-latency draws after the decision and external-event timing (+U(0,600) ms) with a salt shared by all actions, and with S2 on (default) also the latents below. | +| **S2 latents** | `futureProfile` (outage/slow/bug/offline/socket-drop windows: a running window's remaining length x lognormal(1, 0.7), min 200 ms; a later window's start offset x lognormal(1, 0.5), same length), `futureStepTimes` (steps after *t*: tempo lognormal(1, 0.15) x per-gap lognormal(1, 0.2), order kept), `Network.latent` (in-flight responses arriving after *t*: remaining time x lognormal(1, 0.5); server-side draws of requests arriving after *t*; whether an ambiguous failed write committed: 500 on a write with posterior `pc/(pc + (1-pc)/3)`, network error after processing 0.5), `idealRepeatSkips` (repeats before *t* within 3 s: accidental with `REPEAT_PRIOR(gap)`; only the ideal run changes). | +| **latent fallback** | a re-seeded future whose latent re-draw changed an observed prefix is re-run with `noLatent: true` (network/timing only); counted as drop key `info:latent-fallback`. | +| **S1** | `diagnosisFromOutcome`: rules a-e (see [flow 5](#5-cost-labels-and-s1-simsrcoraclecostts-simsrcgentrajectoryts)). | +| **subject correlation** | `Subject.kind` in `write`, `op`, `error`, `invariant`, `chain`, `push`, `unknown`; `DecisionRec.subject.how` in `subject`, `sync`, `chain`, `delivered`, `last`, `text`, `push`, `none`. | | **D(t)** | weighted client divergence of the real run's stores from the ideal run's at the same time (`clientDist`). | -| **tier** | `TIER` in `cost.ts`: passive (`apply send deliver wait ignore`), guard (`discard defer coalesce delay`), heal (`block serve_cached retry hedge rollback resync`). Drives the label premium. | -| **chaos** | `"calm" \| "normal" \| "flaky" \| "degraded" \| "storm"`, picks network parameters (`makeNet`). | -| **diagnosis-only row** | a decision with < 2 applicable actions (runtime omits the `action` question); only a `diagnosis` label; no counterfactuals; <= 3 per trajectory. | -| **ask row / ask probe** | at `scn.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records `AskFacts`; `askQuestions` attaches 1-3 questions with exact labels. | -| **budget** | `situation.budget` passed to the runtime per scenario: 3200 / 2000 / 1000 characters (runtime uses compact questions at <= 1400). Recorded in `meta.budget`. | -| **passive** | `PASSIVE` (`sim/src/types.ts`): mutation `apply`, request `send`, failure `deliver`, stall `wait`, inconsistency `ignore`, transition `ignore`, error `ignore`. Fallback everywhere: the first offered action. | -| **user model** | `UserModel` (`feature.ts`): `think(mul)` = max(120, lognormal(thinkMs x mul, 0.5)); `key()` = max(25, lognormal(keyMs, keySigma)); `type()` emits one `type` step per keystroke (value = full input text), typo + backspace with p = typoP/6 per non-space char, pause U(150,700) ms after a space with p 0.3; `click()` adds an accidental double click U(45,190) ms later with p `doubleClickP` (or `opts.doubleP`), and, when `pendingCond` is given, with p `impatientP` 1-3 impatient re-clicks starting at impatienceMs x U(0.7,1.4), spaced U(300,1500) ms, each guarded by `when: pendingCond` (runs only while `client.cond(name)` is true). Accidental steps carry `repeatOf: -1`; the runner resolves the real intent it repeats. | -| **session window** | per feature *i*: `cover = U(0.45, 1)`, length `tUser x cover`, start `U(0, tUser - len)` (`R.fork("session", i)`); steps at `>= tUser` are dropped; all steps sorted by `t`. | +| **tier** | `TIER`: passive (`apply send deliver wait ignore`), guard (`discard defer coalesce delay`), heal (`block serve_cached retry hedge rollback resync`). | +| **diagnosis-only row** | a decision with < 2 applicable actions; only a `diagnosis` label; <= 3 per gold trajectory. | +| **ask row / ask probe** | at `scn.askTimes` the base run calls `runtime.situation("ask")` and records `AskFacts`; `askQuestions` attaches 1-3 questions with exact labels. | +| **budget** | `situation.budget`: 3200 / 2000 / 1000 characters (compact questions at <= 1400). `meta.budget`. | +| **passive** | `PASSIVE`: mutation `apply`, request `send`, delivery `deliver`, failure `deliver`, stall `wait`, inconsistency/transition/error `ignore`. Now also in `meta.passive` on decision, diagnosis-only and unlabeled rows. | +| **user model** | `UserModel`: `think`, `key`, `type` (typo with p typoP/6 per non-space char), `click` (accidental double click U(45,190) ms later with p `doubleClickP`, forced 0 when the persona's `doubleClickP` is 0; impatient re-clicks guarded by `when: pendingCond`). The runner adds `act.clicks` (browser click count: consecutive clicks on the same target within 500 ms) to `runtime.user`. | +| **tab switches** | `Scenario.windowEvents`: `round(tabSwitchPerMin x tUser/60000 x U(0.5,1.5))` blur/focus pairs at U(warmup x 0.5, tUser - 1000), focus 0.5-20 s later; dispatched as `visibilitychange` + `blur`/`focus` on the global (owner `sim`). | | **transform variant** | `meta.transform`: `default`, `shuffle`, `drop:<action>`, or `drop:<action>,shuffle`. | -| **NetCause** | why a request ended (`NetEntry.cause`): `ok transient outage overload ratelimit spike slow-period gateway-timeout bug replica-lag neterr aborted notfound`; plus `slowCause` `spike \| slow-period \| overload`. Diagnoses read these. | +| **NetCause** | `offline ok transient outage overload ratelimit spike slow-period gateway-timeout bug replica-lag neterr aborted notfound`; `slowCause` `spike \| slow-period \| overload`. | Row (`sim/src/types.ts` -> `Row`, CONTRACT-D): @@ -129,695 +158,554 @@ type Label = {type:"choice"; label:string} | {type:"choice"; dist:Record<string, | row kind | `id` | `labels` | `meta` fields (beyond `meta0`) | |---|---|---|---| -| decision | `sim-<seed>-d<k>` | `action: {type:"choice", dist}` (after transform), `diagnosis: {type:"choice", label}` when correlated and the label is in the offered vocabulary | `trigger`, `decision` (k), `t` (virtual ms), `explored_before`, `best`, `passive_best`, `costs` (mean per action, 4 dp), `cost_futures` (per-future totals), `futures`, `adjusted` (gap to best), `se`, `non_passive_mass`, `cost_parts` (future 0 breakdown: `area`, `final_client`, `final_server`, `relation_s`, `relation_final`, `errors`, `uncaught`, `wasted`, `latency_s`), `tiers`, `diagnosis` (or null), `subject`, `transform`, optional `fake_diagnosis: true` | -| diagnosis-only | `sim-<seed>-s<k>` | `diagnosis` | `trigger`, `decision`, `t`, `diagnosis`, `diagnosis_only: true`, `subject` | -| ask | `sim-<seed>-a<i>` | `q_*` per question (noul `p` 0/1, choice `label`, score `level`) | `trigger: "ask"`, `t`, `kinds` | +| gold decision | `sim-<seed>-d<k>` | `action: {type:"choice", dist}` (after transform), `diagnosis: {type:"choice", label}` when correlated and in the offered vocabulary | `trigger`, `passive`, `subject_feature`, `decision`, `t`, `explored_before`, `best`, `passive_best`, `costs`, `cost_futures`, `futures`, `adjusted`, `se`, `non_passive_mass`, `cost_parts`, `tiers`, `diagnosis` (or null), S1 only: `diagnosis_s1` (`a-write \| b-repeat \| c-twin \| d-diverged \| e-other`) + `diagnosis_subject`, `subject`, `transform`, optional `fake_diagnosis`, optional `probe` (`SIM_PROBE=1`) | +| on-policy decision | `p-<seed>-d<k>` | as gold | gold fields + `on_policy: true`, `model_probs`, `model_choice`, `model_diagnosis`, `ran`, `false_intervention` (ran non-passive and passive best), `miss` (ran passive, passive not best, non-passive mass >= 0.9) | +| diagnosis-only | `sim-<seed>-s<k>` (prefix `sim-` in on-policy runs too) | `diagnosis` | `trigger`, `passive`, `subject_feature`, `decision`, `t`, `diagnosis`, `diagnosis_only: true`, `subject` | +| unlabeled decision | `u-<seed>-d<k>` | `diagnosis` only when correlated and in vocabulary, else `{}` | `unlabeled: true`, `trigger`, `passive`, `subject_feature`, `decision`, `t`, `diagnosis`, `actions`, `ran` (= chosen), `explored`, `subject`, `transform` | +| ask | `sim-<seed>-a<i>` / `u-<seed>-a<i>` | `q_*` per question | `trigger: "ask"`, `t`, `kinds` (+ `unlabeled: true` in unlabeled mode) | -`meta0` (every row): `seed`, `domain`, `family` (program family), `chaos`, `budget`, `runtime` (`"real"` or `"fake"`), -`features` (kinds), `patterns`. Situation `state` sections seen in samples: `app`, `trigger`, `facts`, `in_flight`, -`timeline`, `state`, `stats` (produced by the runtime; see [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md)). +`meta0` (every row, `metaOf`): `seed`, `domain`, `family` and `program_family` (both the program family), `chaos`, +`clean`, `persona` (kind), `budget`, `runtime` (`"real"` or `"fake"`), `features` (kinds), `patterns`. Situation +`state` sections are produced by the runtime ([runtime/learn-situation-triage.md](runtime/learn-situation-triage.md)). Random streams (every one is a keyed `Rng`; changing a key or the order of draws *within* one stream changes data): | stream | key | used for | |---|---|---| -| scenario root `R` | `Rng(hashAll("scenario-v1", seed))` | forks `domain`, `program` (-> `naming`, `api`, `ids`, `kinds`, `feature,i,kind` -> `make`), `timing`, `chaos`, `net`, `persona`, `session,i` (-> `user`), `external,i`, `ask`, `vocab`, `action-vocab`, `model`, `budget` (`buildScenario`) | -| trajectory `R` | `Rng(hashAll("traj", seed))` | forks `testkeep`, `explore`, `points`, `transform,k`, `single`, `ask,i` (`generateTrajectory`) | +| scenario root `R` | `Rng(hashAll("scenario-v1", seed))` | forks `domain`, `program` (-> `naming`, `api`, `ids`, `kinds`, `feature,i,kind` -> `make`), `clean`, `timing`, `persona`, `mobile-net`, `chaos`, `net`, `feature-env,i`, `session,i`, `external,i`, `window`, `ask`, `vocab`, `action-vocab`, `model`, `budget` (`buildScenario`) | +| trajectory `R` | `Rng(hashAll("traj", seed))` | forks `testkeep`, `explore`, `points`, `transform,k`, `single`, `ask,i`, `unl` (`generateTrajectory`) | | server ids | `hashAll("db-<seed>", collection, createKey, n, salt)` | `Db.makeId` | | network | `hashAll(hashAll("net", seed), [salt,] identity, occurrence)`; push `(.., "push", topic, n)`; replica lag `(.., "lag", identity, occurrence)` | `Network.send`, `publish`, `process` | -| app | `Rng(hashAll("app", seed))` = `env.rng` | run-time draws inside feature code (always `env.rng.fork(<key>)`) | -| exploration | `Rng(hashAll("explore", seed)).fork(k)` | per-decision explore draw (`runScenario` decider) | -| model latency | `hashAll("model-latency", seed, idx[, salt])` | decider delay `lognormal(modelMs, 0.35)` | +| S2 network | `hashAll("late", salt, identity, occ)`, `hashAll("latent-commit", salt, identity, occ)`, `hashAll(netSeed, salt, identity, occ, "arrive")` | `Network.late`, `latentCommit`, arrival draws after *t* | +| S2 windows / steps / intent | `hashAll("future-windows", salt)`, `hashAll("future-steps", salt)`, `hashAll("future-gap", salt, i)`, `hashAll("future-intent", salt, i)` | `latent.ts` | +| app | `Rng(hashAll("app", seed))` = `env.rng` | run-time draws inside feature code | +| exploration | `Rng(hashAll("explore", seed)).fork(k)` | per-decision explore draw | +| model latency | `hashAll("model-latency", seed, idx[, salt])` | decider delay `lognormal(modelMs, 0.35)` (also delays the on-policy answer) | | external jitter | `hashAll("ext-jitter", salt, i)` | +U(0,600) ms for external events after `future.t` | -| futures | `hashAll("future", seed, k, j)` | salt of future *j* at point *k* (`pointCosts`) | +| futures | `hashAll("future", seed, k, j)` | salt of future *j* at point *k* | ## How it works ### 1. CLI and workers (`sim/src/gen.ts`, `sim/src/gen/worker.ts`) 1. `gen.ts` -> `parse` reads flags (table in [Configuration](#configuration-and-constants)); unknown flags throw. -2. Non-parts mode: deletes `<out>/shards`, spawns `--workers` `Worker(dist/worker.js)` with `workerData {id, out, - fake, maxPoints, askRows, testKeep (1 when --sample), exploreScale}`; feeds each idle worker 2 consecutive seeds - (`batch = 2`) from `--seed` upward until `produced >= target` (target = `--rows`, or 900 with `--sample`), then - sends `{stop: true}`. Workers already fed finish their batch, so the run overshoots slightly and the exact - last seeds depend on scheduling. -3. Worker: loads the factory once (`realRuntimeFactory()`, or `createFakeRuntime` with `--allow-fake`), then per - seed `generateTrajectory(seed, opts)`; appends rows to `shards/<split>.w<id>.jsonl`; posts a `traj` message with - compact stats. Exceptions -> `error` message (counted as drop `trajectory-exception`); a failed runtime import -> - `fatal` (aborts the run). Messages: `ready`, `idle`, `traj`, `error`, `fatal`, `part-done`. -4. When all workers exit: shards are concatenated per split (sorted by file name) into `<out>/{train,dev,test}.jsonl`, - `shards/` is removed, `stats.json` is written. -5. Parts mode (`--parts`): part *i* = seeds `[seed + i*chunk, seed + (i+1)*chunk)`. The worker writes - `parts/part-NNNNNN.<split>.jsonl.tmp`, renames them when the part is complete and writes `part-NNNNNN.json` - `{part, seeds:[first,last], rows}`. On start, `*.tmp` files are deleted and parts with a `.json` marker are skipped - and their rows counted toward `--rows`. Writes `stats.session.json` (see table below), not `stats.json`. - `--merge-only` concatenates `parts/*.<split>.jsonl` into `<out>/<split>.jsonl` (parts kept). -6. `--sample`: output to `sim/out/sample-tmp`, then writes `sim/samples/sample.jsonl` (200 rows, round-robin over - groups `trigger|diagnosis|act-or-passive`), `sim/samples/EXAMPLES.md` (`renderExamples`: 12 targeted kinds, then - distinct `trigger|best|diagnosis` up to 13, one diagnosis-only, two ask rows) and `sim/samples/sample-stats.json`. -7. Progress is logged at most every 15 s, checked when a `traj` message arrives (`[gen] <produced>/<target> rows, - ...`). `--merge-only` implies `--parts`. - -Output files of one `gen.js` run (`<out>` = `--out`, resolved against the cwd; `final.sh` first `cd`s into `sim/`): - -| file | written by | content | -|---|---|---| -| `<out>/shards/<split>.w<id>.jsonl` | worker (non-parts) | per-worker rows; merged then deleted | -| `<out>/{train,dev,test}.jsonl` | `main` merge / `mergeParts` | final rows (one JSON `Row` per line) | -| `<out>/stats.json` | `main` (non-parts only) | aggregate stats (keys below) | -| `<out>/parts/part-NNNNNN.<split>.jsonl[.tmp]` | worker (parts) | rows of one part; `.tmp` until the part is complete | -| `<out>/parts/part-NNNNNN.json` | worker (parts) | `{part, seeds:[first,last], rows:{split:n}}` completion marker | -| `<out>/stats.session.json` | `main` (parts) | `{note, rows, seconds, rowsBySplitTrigger, drops, errors}`; all but `rows` cover this session only (`rows` also counts the rows of parts finished in earlier sessions) | - -`stats.json` keys (`gen.ts` -> `main`): `args`, `rows` (per split), `rows_by_split_trigger`, `trajectories`, `runs`, -`decisions_seen`, `seconds`, `rows_per_sec_total`, `diagnosis_by_split_trigger`, `best_action_by_split_trigger`, -`passive_best_by_split_trigger` (`{rows, passive_best, frac}` per `split|trigger`), -`harm_of_non_passive_when_passive_best` (per trigger/action `{n, mean, p10, median, frac_harmful}`, harmful = cost -increase > 0.05), `gain_of_best_over_passive_when_not_passive`, `by_budget` (`rows`, `state_chars` and -`token_estimate` p50/p90/max, `passive_best_by_trigger`), `label_sharpness` (per trigger: passive-best rows with -passive mass >= 0.9; intervene-best rows with non-passive mass >= 0.95 / >= 0.9 / < 0.6; `points_with_3_futures` = -share of points with > 1 future), `ask_question_kinds`, `ask_labels` (`<qid>=<value>` counts), `token_estimate` (chars/3.6 of state+questions -JSON: p50/p90/p99/max), `subject_correlated` (`yes`/`no` per labelled point), `exploration` (`on-passive-path` / -`after-exploration`), `drops`, `skipped` (reason prefix before `:`), `domains`, `families` (count), `features`, -`errors` (first 20). Stats count only decision points (`PointStat`) for label statistics; row counts include -diagnosis-only and ask rows. + `--unlabeled` sets `mode: "unlabeled"`; `--on-policy <dir>` sets `mode: "onpolicy"` and `modelDir`. +2. Deletes `<out>/shards` (in every mode), spawns `--workers` `Worker(dist/worker.js)` with `workerData {id, out, + fake, maxPoints, askRows, testKeep (1 with --sample), exploreScale, mode, modelDir}`. Non-parts mode feeds each + idle worker 2 consecutive seeds from `--seed` upward (parts mode: one whole part of `--chunk` seeds) until + `produced >= target`, then `{stop: true}` (slight overshoot). +3. Worker: loads the factory once (`realRuntimeFactory()`, or `createFakeRuntime` with `--allow-fake`); in on-policy + mode also `loadModelDecider(modelDir)` once. Per seed `generateTrajectory(seed, opts)`; rows to + `shards/<split>.w<id>.jsonl`; messages `ready`, `idle`, `traj`, `error`, `fatal`, `part-done`. +4. When all workers exit: shards concatenated per split into `<out>/{train,dev,test}.jsonl`, `stats.json` written. +5. Parts mode (`--parts`): part *i* = seeds `[seed + i*chunk, seed + (i+1)*chunk)`, `.tmp` until complete, then a + `part-NNNNNN.json` marker; restart skips finished parts. Writes `stats.session.json`. `--merge-only` concatenates. + All cluster runs use parts mode. +6. `--sample`: output to `sim/out/sample-tmp`, then `sim/samples/{sample.jsonl (200 rows), EXAMPLES.md, + sample-stats.json}`. + +Output files and `stats.json` keys are as in round 1 (`args` now includes `mode` and `modelDir`; `drops` includes +`info:latent-fallback`). Label statistics count only counterfactual-labelled decision points (`PointStat`: gold and +on-policy); unlabeled trajectories contribute rows and drops but no points. ### 2. One trajectory (`sim/src/gen/trajectory.ts` -> `generateTrajectory`) -1. `buildScenario(seed)`; `split = splitOf(scn)`; trajectory rng `R = Rng(hashAll("traj", seed))`. -2. If `split === "test"` and `R.fork("testkeep").next() >= testKeep`: return `skipped: "test-subsample"` (no runs). +1. `buildScenario(seed)`; `split = splitOf(scn)`; `R = Rng(hashAll("traj", seed))`; test subsample by `--test-keep`. +2. **Unlabeled mode** (`unlabeledTrajectory`): one base run with exploration x 1.5 and ask probes always on (ignores + `--no-ask`); every decision becomes a row (at most `maxUnlabeled` = 40, sampled with `R.fork("unl")`), including + decisions with < 2 actions; questions transformed (`transformQuestions` with no dist); ask rows as in gold. Done. 3. Ideal run (`ideal: true, serverTimeline: true`). Internal errors -> drop `ideal-internal-error`. -4. Exploration: `eps = R.fork("explore").weighted([[0,4],[0.08,3],[0.2,2]]) * exploreScale`. Per decision that - offers a non-passive action, probability `eps` if the sim's diagnosis is set and not `expected`, else `eps/4`, to - pick a uniformly random non-passive action (`explorePolicy`). Draws use `Rng(hashAll("explore", seed)).fork(k)`. -5. Base run (real runtime, `record: true`, `probeAsk`, explore). Internal errors -> drop `base-internal-error`, - `skipped: "base-error: ..."`. -6. `pickPoints(base.decisions, maxPoints, R.fork("points"))`: candidates have >= 2 actions; weighted sampling - without replacement with `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, - transition 3, error 2.2) x 1.5 when the diagnosis is set and not `expected`; sorted by `k` (all candidates are - kept when there are at most `maxPoints`). -7. For each point: `pointCosts` (flow 4) -> `actionLabel(futures, passive)` (flow 5) -> `transformQuestions(..., - R.fork("transform", k))` -> labels. `diagnosis` label only if the diagnosis is in the offered criteria and - `subject.kind !== "unknown"`; otherwise drop counters `diagnosis-not-in-vocab` / `diagnosis-uncorrelated`. -8. Diagnosis-only rows: decisions with < 2 actions, a diagnosis and a known subject; `R.fork("single").sample(.., 3)`; - a sampled decision is skipped (not replaced) when its label is not among the offered diagnosis criteria. -9. Ask rows (unless `--no-ask`, which also turns off the base run's ask probes: `probeAsk = askRows`): for each - `base.asks[i]`, `askQuestions(a, R.fork("ask", i))`; a probe that yields no question produces no row. +4. Base run: gold = exploration (`eps = weighted([[0,4],[0.08,3],[0.2,2]]) x exploreScale`; per decision `eps` when + the sim's diagnosis is set and not `expected`, `eps/2` for `delivery` (its diagnosis is only known after the run), + else `eps/4`) + ask probes (unless `--no-ask`); on-policy = `onPolicy: {model}`, no exploration, no ask probes. +5. Points: gold `pickPoints` (>= 2 actions and `k < DENSE_K` = 600; all candidates when there are at most + `--max-points`, else weighted with `TRIGGER_W` mutation 1, delivery 1.2, request 1, failure 1.6, stall 2.2, + inconsistency 3, transition 3, error 2.2, x 1.5 non-`expected`); on-policy `pickOnPolicy` (>= 2 actions, no + `DENSE_K` cap; weight 4 if the gate ran a non-passive action, 3 if the model chose one, 2 if the sim sees a + problem, else 1). +6. For each point: `pointCosts` (flow 4) -> `actionLabel` -> `transformQuestions` -> S1 check -> labels; the + `diagnosis` label only if in the offered criteria and `subject.kind !== "unknown"` (else drop counters + `diagnosis-not-in-vocab` / `diagnosis-uncorrelated`). +7. Diagnosis-only rows (< 2 actions, a diagnosis, a known subject; <= 3 via `R.fork("single")`). +8. Ask rows (gold only, unless `--no-ask`; never in on-policy mode). ### 3. One run (`sim/src/run/runner.ts` -> `runScenario`) -1. New `VirtualLoop`, `Db(scn.idStyle, "db-<seed>")`, `VirtualServer`; each feature's `server()` registers routes and - seeds data; `relations()` collected. -2. `Network(loop, server, ideal ? IDEAL_PROFILE : scn.net, hashAll("net", seed))`; `makeGlobal` builds `SimGlobal`: - `fetch` = `network.fetch`, timers on the loop (owner `app`), `location` at `https://app.example.test/`, - `document.title`, and a `WebSocket` class (`makeWebSocketClass`) over the push channel - (`wss://<host>/ws/<topic>`, connect delay `40 + (topic.length % 7) * 10` ms, 0 in the ideal run; `send` not modelled). -3. Real runs: `factory(RuntimeOptions)` -> `createRuntime(createOptions(...))` with the recording decider, - `loop.clockFor("runtime")`, vocabulary overrides, `budget`, `hooks`, `app: () => ({title, route})`. Stores are - runtime atoms (`rt.atom(name, initial, {resync})`); ideal runs use `PlainBackend`. -4. `AppEnv` + one `Kit` per feature; `client()` per feature; initial route = first feature's route. -5. Schedules: `init()` of every client at t = 0; every user step at `st.t` (owner `user`; skipped if `when` is false; - real runs wrap `client.handle` in `runtime.user(act, handler)` with `know.callingIntent` set); external events - (owner `sim`; in a re-seeded future, events later than `future.t` are delayed by U(0,600) ms); ask probes (real - runs with `probeAsk`, i.e. base runs only). - Each executed step creates a `Knowledge.intent`; an accidental step's `repeatOf` resolves to the latest - non-accidental intent with the same `feature|action|intent.key`. `act` = `{kind: ui.kind, target, value?}`. - Ask probes call `runtime.situation("ask")` (a throw is an internal error) and record `AskRec {t, state, - facts}`. -6. `loop.onSettled` pushes a client snapshot after every settled macrotask that changed a store (`env.dirty`) and, - with `serverTimeline`, a server snapshot after every DB write. -7. `loop.settle()`, `loop.runUntil(min(tEnd, tStop))`, then collect `RunResult` (snapshots, final, server, decisions, - asks, know, netLog, error counts/times, `userOpMs`, internal errors, weights, relations) and `runtime.destroy()`. +1. New `VirtualLoop`, `Db`, `VirtualServer`; features register routes and relations. +2. `Network(loop, server, ideal ? IDEAL_PROFILE : futureProfile(scn.net, future), hashAll("net", seed))`; with a + re-seeded future and S2 on, `network.latent = {salt, t}`. +3. `makeGlobal`: `fetch`, timers (owner `app`), `location`, `document {title, visibilityState, hidden}`, a global + `EventTarget` (`addEventListener`/`dispatchEvent`), `navigator {onLine, userAgent}`, `localStorage` + (`MemStorage`), `WebSocket` (`makeWebSocketClass`: connect delay `40 + (topic.length % 7) * 10` ms; during a + `socketDrops` window connections fail with `error` + `close` code 1006 and an open socket is closed at the window + start; each dispatched message gets a push id), and `BroadcastChannel` (`makeBroadcast`: messages from "other + tabs" arrive 1 ms later; this tab's own posts reach no one). +4. `Knowledge` with `know.onWrite` = diagnose every write with the `mutation` rules (`SimWrite.diag`); probe state if + `SIM_PROBE=1` on a recorded real run. +5. Real runs: `createRuntime(createOptions(...))` (`production: true` for on-policy) with the decider, hooks + `opCreated` (also maps `ws` message ops to `know.deliveringPush`) and `mutationProposed`. On-policy also listens to + `rt.on("decide")` to record what the gate actually ran (`rec.ran`, and sets `rec.chosen`/`rec.explored` so + replays force it). +6. `AppEnv` (+ `skewMs` from the scenario, 0 in the ideal run; `blocker` = `loop.advance`), `WorldCtx` (+ `otherTab` + `setItem`/`removeItem` (dispatch a `storage` event) and `broadcast`). +7. Schedules: offline windows flip `navigator.onLine` and dispatch `offline`/`online` (real runs, owner `sim`); tab + switches; `init()`; user steps at `futureStepTimes(...)` (ideal runs skip per `idealRepeatSkips` or the default + accidental/conditional rule; fired conditional steps recorded in `firedSteps`); external events; ask probes. +8. `loop.settle()`, `loop.runUntil(min(tEnd, tStop))`; then delivery decisions get `diagnosis` = `diag` of the first + write whose `op` (fetch delivery) or `push` (message delivery) matches, else the decision's own diagnosis, else + `expected`; probes are completed; collect `RunResult`. ### 4. Counterfactuals (`sim/src/gen/trajectory.ts` -> `pointCosts`) -1. `forcedPrefix` = `{d.k: d.chosen}` for explored base decisions before *k* (non-explored ones were passive, which is - the cf default). -2. For future `j = 0..K-1` (K = `GenOptions.futures ?? 3`): with `adaptive` (default true), stop after future 0 - unless some non-passive action beats passive by > 0.05 there. -3. Future `j >= 1`: `salt = hashAll("future", seed, k, j)`; if any external event is after `t_k`, re-run the ideal - world with that salt (`future.k = -1`) so external timing matches. -4. For each action: `runScenario(scn, {forced: prefix + {k: a}, fpUpTo: k, tStop: t_k + W.finalMs, future})`. - Exception -> drop `cf-exception`; internal error -> `cf-internal-error`; decisions `<= k` must equal the base run's - `fp` -> else `prefix-mismatch`. -5. `runCost(cf, idealJ, t_k, scn.tEnd).total` (4 dp) per action per future; `cost_parts` and `results` from future 0. - -### 5. Cost and labels (`sim/src/oracle/cost.ts`) - -1. `stop = min(tEnd, t_k + 15000, run.tStop)`. -2. `area` = `divergenceArea` over `[t_k, min(stop, t_k + 10000)]` (seconds) of `clientDist(real, ideal)`. - `clientDist`: per store/field weight from `env.store(..., {weights})` (default 1, weight <= 0 skipped); lists compare - as multisets of content with volatile keys ignored (`id version rev revision etag updatedAt updated_at clientId - pending seq`); numbers 0/1; objects averaged per key (depth < 3). The first field of every violated relation - adds its full weight even if it equals the ideal value. -3. `finalClient` = `clientDist` at `stop`; `finalServer` = `serverDist(real.server, ideal server at stop)`: - `25 x min(5, extra/missing items) + 6 x min(5, changed items)` per collection, `6 x min(3, differing fields)` per - doc, `6 x min(3, |delta|)` per counter (counters named `*beats` ignored); volatile server fields stripped. -4. Error terms: shown-error episodes and uncaught errors in `[t_k, stop]` beyond the ideal run's count; `wasted` = - per-signature server arrivals in `[t_k, stop]` beyond the ideal run's; `latencyS` = seconds non-background ops - were pending in `[t_k, stop]` (absolute, not relative to ideal); relation-violation area over the 10 s horizon and - count at `stop`. -5. `total = 1.0*area + 4.0*finalClient + finalServer + 1.5*shownErrors + 1.0*uncaught + 0.08*wasted + 0.25*latencyS - + 0.8*relationArea + 2.0*relationFinal`. -6. `actionLabel(costs, passive)`: per-future costs paired by index (K = min length). Non-passive action whose mean - is within `tieEps` 0.05 of passive's -> adjusted = passive's costs + `exactTie` 1.5; else cost + tier premium - (passive 0, guard 0.25, heal 0.5). `best` = argmin mean adjusted (ties keep passive). `gap_a = max(0, mean(adj_a - - adj_best))`, `tau_a = 0.10 + 1.0 * SE_a` (SE of the paired difference, 0 with one future), `p_a ∝ exp(-gap_a/tau_a)`, - rounded to 4 dp. +1. `forcedPrefix` = `{d.k: d.chosen}` for explored (or, on-policy, gate-ran non-passive) decisions before *k*. +2. For future `j = 0..K-1` (K = 3): with `adaptive` (default) and S2 on, future 1 always runs; future `j >= 2` runs + only if some non-passive action beat passive by > 0.05 in a future seen so far. (S2 off: stop after future 0 + unless a gain > 0.05 there.) +3. Future `j >= 1`: `salt = hashAll("future", seed, k, j)`; the ideal run is re-run with that salt + (`future.k = -1`, `fired` = base conditional steps that fired at or before *t*) whenever an external event lies + after `t_k`, or S2 is on and this is not a `noLatent` fallback. +4. Per action: `runScenario(scn, {forced, fpUpTo: k, tStop: t_k + 15000, future})`; exception -> `cf-exception`; + internal error -> `cf-internal-error`; prefix differs -> `prefix-mismatch`, except for a re-seeded future with S2 + on, which is retried once with `noLatent: true` (counted `info:latent-fallback`). +5. `runCost(...).total` (4 dp) per action per future; `cost_parts` and results from future 0. + +### 5. Cost, labels and S1 (`sim/src/oracle/cost.ts`, `sim/src/gen/trajectory.ts`) + +1. Cost: unchanged from round 1. `total = 1.0*area + 4.0*finalClient + finalServer + 1.5*shownErrors + 1.0*uncaught + + 0.08*wasted + 0.25*latencyS + 0.8*relationArea + 2.0*relationFinal` over `[t_k, min(tEnd, t_k + 15000, + tStop)]`, area/relation area over the 10 s horizon; `serverDist` caps (5 extra/missing + 5 changed items per + collection, 3 fields per doc, 3 units per counter, `*beats` counters ignored). +2. `actionLabel`: tier premium (passive 0, guard 0.25, heal 0.5); non-passive within `tieEps` 0.05 of passive -> + passive's costs + 1.5; `best` = argmin mean adjusted; `p_a ∝ exp(-gap_a / (0.10 + 1.0 x SE_a))`. +3. **S1** (`S1_GAP = 1.0`): if the diagnosis is undefined or `expected`, the subject is known, passive is not best and + passive's adjusted gap >= 1, then `diagnosisFromOutcome(base, ideal, p, best)`: + a) fields already wrong at *t* vs the ideal run (`divergedFieldsAt`, incl. first fields of violated relations): + the `diag` of the latest non-`expected` last write to such a field (`a-write`); + b) the subject's intent is accidental / a repeat, or the op has `dupOf` -> `duplicate` (`b-repeat`); + c) request trigger, best `coalesce`/`block`, and an identical op (method, url, body) started earlier and still in + flight or ended within 10 s -> `duplicate` (`c-twin`); + d) fields diverged with no named cause -> `inconsistent` (inconsistency/transition) or `stale` (`d-diverged`); + e) otherwise `unusual` (`e-other`). + `rows.test.ts` asserts no gold `expected` row has passive's adjusted gap >= 1. ### 6. A request through the world (correlation) -1. Feature code: `kit.op({role, method, url, intent, key, ...})` -> `Knowledge.beginOp` (sim op id). -2. `Kit.callNet` adds `x-request-id: req-<hash>-<opId base36>` (`SIM_OP_HEADER`, `simOpHeaderValue`), app timeout via - `AbortController` with a `TimeoutError` reason, then `AppEnv.fetch` sets `know.callingOp` and calls - `G.fetch` (runtime-instrumented). -3. The runtime creates its fetch op synchronously -> `hooks.opCreated` maps runtime op -> sim op (`know.rtOps`, - `op.rtOp`), records causal parents (`know.rtParents`), and maps runtime user ops to intents (`know.rtUserOps`). - The runtime treats `x-request-id` as a volatile tracing header (not part of request identity, never serialized). -4. If the runtime lets it through, `Network.fetch` strips the header (`parseSimOpHeader` -> `NetEntry.simOp`), draws - latency keyed by `(netSeed, [salt,] identity, occurrence)`, and `onSend` appends the entry id to `op.net`. -5. Arrival after `0.35 x latency`; checks in order: outage -> capacity (non-latency mode) -> per-endpoint rate limit -> - random transient (`transientP`; non-GET commits first with `postCommitP`, then 500) -> network error (`netErrP`, 50% - commit) -> normal processing (server bug mutation, replica lag) -> gateway timeout 504 if the response would land - after `t0 + gatewayMs`. A normal response is delivered `(0.05 + 0.6) x latency` after arrival (fast-fail paths - such as outages and 429s use shorter offsets); bodies are real undici `Response` objects (`makeResponse`). - Exact failure shapes: outage `neterr` -> `TypeError("Failed to fetch")`; `hang` -> 504 at `t0 + gatewayMs`; - `empty` -> GETs processed with the `empty-list` bug (2xx, cause `outage`), writes 503; `503/500/502` -> that - status. Capacity (`load` = arrivals in the last 1000 ms > `perSec`): 429 with `retry-after: 1` or 503; in - `latency` mode the latency is multiplied by `1 + (load - perSec)/perSec` at send time instead. Rate limit: - 429, `retry-after: 1|2` when enabled. Random transient: post-commit -> 500, else one of 500/502/503. Server bug - mutations (`mutateForBug`) apply only to responses < 400: `drop-field`/`null-field` on `field` of every item - (depth <= 3), `empty-list` empties arrays and zeroes numeric `count|total` keys, `html` replaces the body with - `text/html`. Replica lag swaps the resource (`RouteMeta.resource`, GET only) to its value before the earliest - write in `(t - lagMs, t]` for the duration of the handler. In ideal mode the request is processed on arrival with - no checks (latency 0, two dummy draws keep the stream aligned). -6. Server (`VirtualServer.handle`): routes match by method + segment count (`:param` segments capture); no match -> - 404 `{error:"not_found"}`; a throwing handler -> 500 `{error:"internal"}`. `Idempotency-Key` responses are - remembered per `signature|key` when status < 500 and replayed (logged `note: "idempotent-replay"`, - `committed: false`). `committed` in the server log = not a replay and status < 400; the network only counts - non-GET commits. Every DB write increments `Db.writes` and stores a pre-write snapshot per resource key (`c:`, - `d:`, `n:`; last 64) for replica lag. `snapshot()` strips `version updatedAt updated_at rev etag seq`. -7. `Kit` classifies the outcome (`ok`, `http-error`, `neterr`, `aborted`, `timeout`, `parse-error` for HTML/invalid - JSON) and calls `Knowledge.endOp` (updates the per-signature failure `streak`: reset on `ok`, unchanged on - `aborted`, +1 otherwise; signature = `sigOf`). `Kit.op` defaults `idempotent` to true for GET/PUT/DELETE and - false for POST/PATCH unless the feature passes it; `Kit.callNet` also sets `accept: application/json` and, with a - body, `content-type: application/json`. Outcome mapping of a rejected fetch: app timeout fired -> `timeout`; - `AbortError`/`TimeoutError` -> `aborted`; anything else -> `neterr`. A 2xx whose body is not JSON (bug `html`) - becomes `parse-error` with a synthetic `SyntaxError`. -8. Writes: `env.store(...).set(next, meta)` records a `SimWrite` (changed top-level fields; `input` role updates - `userFieldTime`) and sets `know.writing` during `atom.set`, so `hooks.mutationProposed` maps runtime mutation -> - sim write (`know.rtMutations`). +Unchanged from round 1 except: `Kit.op` now copies `anomaly`; offline windows make `Network.send` fail at once +(`cause: "offline"`, `TypeError("Failed to fetch")` after U(2,12) ms, no server processing); S2 re-draws in +re-seeded futures (`late`, `latentCommit`, arrival rng `r2`). Flow: `kit.op` -> `Knowledge.beginOp`; `Kit.callNet` +adds `x-request-id: req-<hash>-<opId base36>` and calls `AppEnv.fetch`, which sets `know.callingOp` around the +runtime-instrumented global fetch; +`opCreated` maps runtime op -> sim op; `Network.fetch` strips the header, draws latency keyed by identity and +occurrence, then outage -> capacity -> rate limit -> transient (500 on a write may commit first) -> network error +(50% commit) -> processing (bugs, replica lag) -> gateway 504; `Kit` classifies `ok/http-error/neterr/aborted/ +timeout/parse-error` and updates the per-signature failure `streak`. ### 7. A decision (recording decider in `runScenario`) -1. `evaluate(req)`: `idx = k++`; actions = keys of `req.questions.action.criteria`; `correlate(req)` -> `Subject`: - mutation via `subject.mutation` (else ambient `know.writing`); request/failure/stall/transition via `subject.op` - (runtime retries/hedges map through causal parents up to 6 hops); transition on a user/timer op -> the chain of - app ops descending from it (8 hops); request fallback ambient `know.callingOp` (`how: "sync"`); failure fallback - `network.lastDelivered`; error via `subject.error` (else last - uncaught error); inconsistency via `subject.invariant` + `paths` (else trigger/facts text). -2. `diagnose(trigger, subject, {know, network, relations, now, stores})` (flow 8). -3. Choice: `forced.get(idx)` -> else exploration -> else passive (`PASSIVE[trigger]`). A forced or explored action - that is not among the offered actions falls back to passive (or the first offered action). `DecisionRec.subject` - = `{kind, how, ref?}` where `ref` is the sim op/write id. -4. Answers: action = probability 1 on the chosen action; diagnosis = the sim's label, but if a non-passive action - is chosen and the label is `expected`, answer `unusual` (or the first non-`expected` key) and set - `fakeDiagnosis`; other noul questions 0.5, score level 0. -5. Records a `DecisionRec` (`record`, or `idx <= fpUpTo` with state/questions blanked). At `idx === future.k` the - network switches to the future salt; model latency `lognormal(scn.modelMs, 0.35)` keyed by `(seed, idx[, salt])`. -6. Runtime policy (from `createOptions`): thresholds guard/heal 0.5 with `requireDiagnosis: false` -> exactly the - forced action runs (the summed non-passive mass is 1 or 0). - -Error paths into the runtime's `error` trigger: `Kit.spawn(fn, "uncaught", tag)` tags the rejection -(`Knowledge.tagError`, default tag `{cause:"unhandled", diagnosis:"failing"}`) and calls `env.uncaught(e, -"unhandledrejection")`; a throw inside an `app`/`user` loop task is tagged `{cause:"handler-threw", -diagnosis:"failing"}` (if untagged) and reported as `window.onerror`. `env.uncaught` -> `runtime.reportError(err, -{source})`. `benign` noise errors are tagged `expected`. +1. `evaluate(req)`: `idx = k++`; `correlate(req)`. New for `delivery`: `subject.op` -> sim op via `know.rtOps` (or + causal parents) -> `{kind: "op", how: "subject"}`; else `know.rtPushOps` -> `{kind: "push", how: "push", ref: + pushId}`; else unknown. `diagFrom` = `{op}` or `{push}`. +2. `diagnose(...)` (`delivery` returns `undefined`; filled after the run). +3. Choice: forced -> exploration -> passive; answers: action = probability 1 on the chosen action; diagnosis = the + sim's label (or `expected`), replaced by `unusual` (or another non-`expected` key) with `fakeDiagnosis` when a + non-passive action is chosen on `expected`. A `delivery` diagnosis is always undefined at decision time, so every + forced or explored non-passive delivery answer is fake-diagnosed (`fakeDiagnosis`, `meta.fake_diagnosis`). +4. On-policy: the model's `evaluate` promise is registered with `loop.hold` (real inference time is held out of + virtual time); its `action` probabilities/choice and `diagnosis` choice are recorded, and the answer is released + after the scenario's virtual model latency. +5. Runtime policy (`createOptions`): `mode: "heal"`, thresholds guard/heal 0.5, `requireDiagnosis: false` -> exactly + the forced action runs. On-policy (`production`): `policy = {holdBudgetMs: 1e9, maxActionsPerMinute: 1e9}` only, + i.e. the runtime's default thresholds and diagnosis gate. + +Error paths into the `error` trigger are unchanged (`Kit.spawn` tags; `handler-threw`; `env.uncaught` -> +`runtime.reportError`). ### 8. Diagnosis rules (`sim/src/oracle/diagnose.ts` -> `diagnose`, first match wins) | trigger | rules | |---|---| -| mutation | `write.classify()`; `anomaly === "partial"` -> inconsistent; `shape`/`empty`, server bug, or outage-emptied data with status < 400 -> unusual; op `dupOf` or accidental intent -> duplicate; replica lag -> stale; data role (`DATA_ROLES`) of a superseded intent -> stale; non-input write over fields the user changed after the op started -> stale; `push` write while a non-background op on the same key is in flight -> conflict; else expected | -| request | `op.classify()`; `dupOf`/accidental -> duplicate; non-idempotent retry whose original committed -> duplicate; `anomaly: "storm"` (dead branch, see sim op) or >= 6 req/s to that signature (2 s window) -> overload; non-background superseded intent -> stale; streak >= 2 -> failing; else expected | -| failure | `diagnoseFailure`: outage -> failing; timeout/504/`TimeoutError`: slow period or overload -> slow, else streak >= 2 -> slow, else transient; 429/503 shedding or rate limit: client >= 3 req/s (signature of the entry, 2 s window) or storm -> overload, else failing; bug -> unusual; storm -> overload; streak >= 2 -> failing; else transient. Both storm checks read `op.anomaly`, which is never set, so they never fire | -| stall | request inside an outage window -> failing; `slowCause === "overload"` -> overload; else slow | -| inconsistency | `inconsistent` only if a relation is violated in the current client snapshot and its fields overlap the invariant's `store.field` refs (`fieldRefs`); else expected | -| transition | a network entry of the op(s) with cause bug or replica lag, or cause outage with status < 400 or no status (outage-emptied 2xx, and also `neterr`-mode outages, which carry no status) -> unusual; a write with `partial`/`shape` anomaly for the op or chain intent -> unusual; failed op -> `diagnoseFailure`; else expected | -| error | untagged error -> expected; tag `expected` -> expected; tagged op with `parse-error` -> unusual; tagged op -> `diagnoseFailure`; else the tag's diagnosis | - -Details: `diagnose` returns `undefined` (no label, drop counter `diagnosis-uncorrelated`) when the subject is -missing (mutation without a write, request without an op, stall with neither entry nor op, transition with neither -op nor chain). A failure always gets a label (`diagnoseFailure` falls back to `transient`), but the row still loses it -because `subject.kind` is `unknown`. In `diagnoseFailure`, `streak` = `know.streak[sigOf(op)] + 1`. For a `failure` -trigger the op has usually not ended yet (the `+1` stands for the current failure), so "streak >= 2" means at least -one earlier consecutive failure. For `error` and `transition` callers the op has already ended (`Knowledge.endOp` -counted it), so unless a later op of the same signature reset the streak, the `+1` counts the current failure twice -and a first failure already yields `failing` (or `slow` for a timeout). Error tags without an `op` (form, poll, nav -and cart-checkout spawns, `handler-threw`) return the tag's own `failing`. Both are consistent with phase A train -`error` points (94.8% `failing`, 0.1% `transient`). The request rule uses the raw `know.streak >= 2`. Client rates (`clientRate`) count -`NetEntry`s with the same route signature sent in the last 2000 ms, divided by 2. `DATA_ROLES` = `results echo -refetch poll-result view-data append data load confirm created push cache resync conflict-refetch bulk-result -presence swr-cache clear placed`. +| mutation | `write.classify()`; `anomaly === "partial"` -> inconsistent; `shape`/`empty`, server bug, or outage-emptied data with status < 400 -> unusual; op `dupOf` or accidental intent -> duplicate; replica lag -> stale; data role (`DATA_ROLES`) of a superseded intent -> stale; non-input write over fields the user changed after the op started -> stale; `push` write while a non-background op on the same key is in flight -> conflict; else expected. Also run on every write at proposal time (`SimWrite.diag`). | +| delivery | `undefined` at decision time; after the run: `diag` of the first write of the delivered op / push message, else `expected` | +| request | `op.classify()`; `dupOf`/accidental -> duplicate; non-idempotent retry whose original committed -> duplicate; `anomaly: "storm"` (set through `kit.op` by poll, prefetch, multitab, wsreconnect, clockskew, exportjob, and assigned on the op by countdown, graphql, presence, ratelimit) or >= 6 req/s to that signature (counted over the last 2 s) -> overload; non-background superseded intent -> stale; streak >= 2 -> failing; else expected | +| failure | `diagnoseFailure`: outage or **offline** -> failing; timeout/504/`TimeoutError`: slow period or overload -> slow, else streak >= 2 -> slow, else transient; 429/503 shedding or rate limit: client >= 3 req/s or storm -> overload, else failing; bug -> unusual; storm -> overload; streak >= 2 -> failing; else transient | +| stall | outage window -> failing; `slowCause === "overload"` -> overload; else slow | +| inconsistency | `inconsistent` only if a relation is violated in the current client snapshot and overlaps the invariant's refs; else expected | +| transition | bug / replica lag / outage-emptied entries -> unusual; `partial`/`shape` write for the op or chain -> unusual; failed op -> `diagnoseFailure`; else expected | +| error | untagged -> expected; tag `expected` -> expected; tagged op with `parse-error` -> unusual; tagged op -> `diagnoseFailure`; else the tag's diagnosis | + +S1 can then override an `expected`/missing diagnosis on gold rows (flow 5). The streak details of round 1 still hold +(`streak = know.streak[sigOf(op)] + 1`; error/transition callers count the current failure twice). +`DATA_ROLES` is unchanged (`results echo refetch poll-result view-data append data load confirm created push cache +resync conflict-refetch bulk-result presence swr-cache clear placed`); several round-2 data roles are not in it (see +Drift). + +### 9. Cluster runs (`sim/scripts/cluster/`) + +1. `bundle.sh` (train VM): tars Node 22, the runtime dist, `sim/dist` (incl. `model-host/`), `sim/scripts` and the + needed `node_modules` into `~/xfer-sim/simbundle.tgz` (~100 MB), served on `10.0.0.4:8810`. `DIST=` picks the + built sim dir. +2. `orchestrate.sh` (colleague's Mac; strictly one `az` call at a time, each with a timeout): `start`, `start-nowait`, + `run RUN MODE ROWS_PER_NODE nodes...`, `status`, `kill`, `stop` (deallocate). Seed base per mode: gold 1e9, + unlabeled 3e9, on-policy 5e9 (v1); v2 runs pass `SEED_BASE` (gold 11e9, unlabeled 16e9, on-policy 22e9, checks + 19e9). Node `cNN` gets base + NN x 1e8 (`data` = 12). +3. `node_start.sh` (on a node): fetches the bundle (`REFRESH=1` re-fetches), runs `gen.js --parts --chunk 100` with + `nproc - 4` workers and `--max-old-space-size=8192`, mode `gold | unlabeled | onpolicy:<dir>`, serves + `~/simgen/out` on `<private ip>:8811`; `SIM_FEATURE_HOLDOUT` defaults to `on`. +4. `bigrun.sh` (v2): `start`, `unl RUN ROWS NODES` (16e9, refreshes the bundle), `gold RUN ROWS NODES` (11e9), + `wait`, `ips`. +5. `collect.py RUN OUTDIR HOST...` (or `--local DIR...`): pulls finished parts only (re-runnable), dedupes globally + over sha1(state + questions) processing test, then dev, then train (no leakage), writes + `{train,dev,test}-NNNNN.jsonl.gz` (<= 500k rows each) + `manifest.json`. + +These scripts hard-code the colleague's paths (`/Users/meharkhanna/jev/scripts/azvm.sh`) and Azure resource group +`rg-jev-train`. **Do not run them** (no Azure from our side). ### Feature combinators and the bugs they create -`FEATURE_WEIGHTS` (`sim/src/app/features/index.ts`): search 10, editor 9, poll 9, form 8, cart 8, board 7, nav 7, -list 7, toggle 6, chat 6, counter 5, settings 5, bulk 4, auth 3, benign 4 (benign is never drawn by weight; it is -added with p 0.3). +`FEATURE_WEIGHTS` (`sim/src/app/features/index.ts`), round 1: search 8, editor 7, form 7, cart 7, poll 7, board 6, +nav 6, list 6, toggle 5, chat 5, counter 4, settings 4, bulk 4, auth 4, benign 4 (benign never drawn by weight; added +with p 0.3). Round 2: querycache 6, masterdetail 6; infinite, offline, wsreconnect, undo, reorder, wizard, etag, +badge, facets, cascade, payment, inventory, multitab, swcache, money 5; upload, graphql, saga, presence, clockskew, +longtask, exportjob, prefetch, ratelimit, cdn, countdown, schemadrift 4; permissions, flags 3. Program size 1:35, +2:45, 3:20 features. + +The round-1 table below is unchanged since 654d822 (the feature files did not change). -| feature | knobs -> pattern tags | bug opportunities (what the runtime should catch) | relations / external | +| feature | knobs -> pattern tags | bug opportunities | relations / external | |---|---|---|---| -| `search` (typeahead) | `guard:none\|abort\|reqid\|check` (4/2/2/2), `debounce` (0 or 120-450 ms), `cache` (0.25), `err:show\|silent\|throw`, `timeout` (2.5-9 s); minLen 0-2 | no guard -> out-of-order results overwrite newer ones (stale mutation); per-keystroke requests; `err:throw` -> unhandled rejection | - | -| `editor` (autosave + echo) | `save:debounce\|interval\|button`, `overlap:allow\|serialize`, `echo:always\|if-unchanged\|version-only`, `vcheck:refetch\|overwrite\|show` or `novcheck`, `live:blind\|if-clean` or `nolive`, `retry:none\|once\|backoff` | overlapping saves; echo of an older save over newer typing (stale); 409 conflicts; blind live edits during local edits (conflict); retry of old text (stale) | external: 0-2 random collaborator edits; plus (live only) for the first 3 of the user's save steps (and about 4% of edit keystrokes), each with p 0.5, a conflicting edit 20-900 ms later | -| `form` (create) | `disable`, `idem`, `retry:none\|same-key\|no-key`, `retry-on:timeout\|5xx`, `ok:append\|refetch`, `optimistic+rollback\|optimistic-norollback\|pessimistic`, `count\|count-partial\|nocount` | double submit; retry without key after a committed timeout -> duplicate item (server damage); optimistic append without rollback; count not kept on refetch/rollback (`anomaly: partial`); 25% intentional identical re-creates (benign) | count == len(list) | -| `cart` | `mode:optimistic\|server\|echo`, `rollback`, `recompute:always\|skip-rollback\|skip-echo\|items-only-qty`, `addguard`, `co-disable`, `co-idem`, `co-retry:*`, `badge` | non-idempotent add POST + double click; full-cart echo stale with several updates in flight; totals not recomputed (partial); checkout double submit / retry without key -> duplicate orders | total = sum price*qty (abs diff < 0.011); count = sum qty; badge = cart count | -| `toggle` | `ep:absolute\|relative`, `rollback`, `echo`, `pending-guard\|noguard`, `count\|count-partial\|nocount` | relative (non-idempotent) toggle + double click flips back; echo flip-back (stale); no rollback; partial count | flagged count | -| `counter` | `ep:increment\|absolute`, `echo:always\|latest-only\|none`, `retry:none\|retry` | non-idempotent increment + retries/double clicks over-count; stale echo after rapid clicks | - | -| `poll` (dashboard) | `mode:interval\|chain`, `skip-inflight\|overlap`, `fail:backoff\|tight\|ignore\|throw`, `seq\|noseq`, `timeout` | overlapping polls (`dupOf`); tight retry loop (50 ms sleep after each failed response, up to 30 consecutive fails); it passes `anomaly: "storm"` to `kit.op`, which drops it, so these retries are `overload` only through the >= 6 req/s rate rule; throw after 2 failures; stale range responses | external: 2-8 metric changes | -| `board` (kanban + live) | `push:blind\|version\|skip-pending`, `echo`, `rollback`, `counts\|counts-partial\|nocounts`, `vcheck` | blind push over a pending local move (conflict); out-of-date push (stale); counts not updated on push (partial); 409 on version mismatch | per-column counts; external: 1-5 random moves + 30% of user moves followed by a conflicting move 30-700 ms later | -| `chat` | `optimistic\|pessimistic`, `dedupe:id\|clientId\|none`, `resp:replace\|append\|ignore`, `disable`, `unread` | duplicate messages (response + own push); pessimistic send clears a draft typed meanwhile; double send; 15% intentional repeats | external: 0-4 incoming messages | -| `settings` | `echo:full\|key\|none`, `seq\|noseq`, `serialize\|parallel`, `rollback` | full-object echo reverts a newer toggle (stale) | - | -| `nav` (views) | `mode:all\|allSettled\|chain`, `route-guard\|noguard`, `abort\|noabort`, `err:throw\|banner\|partial`, `swr` | previous view's data written into the current view (stale); `err:throw` unhandled rejection; partial render (`anomaly: benign-change`) | - | -| `list` (filters + infinite scroll) | `guard:none\|reqid\|abort`, `more-guard\|more-noguard` | stale page after filter/sort change; duplicate page appends from repeated scroll events (`doubleP` 0.35) | - | -| `bulk` | `assume-all\|per-result`, `counts\|counts-partial\|nocounts`, `disable` | assume all succeeded although locked items failed (207/409; `anomaly: shape` -> unusual); partial counts | per-status counts | -| `auth` (expiring tokens) | `single-flight\|per-request-refresh` | one refresh per 401 -> second refresh uses the rotated token -> 401 -> forced logout; duplicate refresh request | - | -| `benign` | `beacon-timer\|beacon-user`, `noise:0\|1\|2` | none by design: heartbeats (identical POSTs), beacons with ignored failures, config prefetch, harmless uncaught errors (`ResizeObserver loop...`, `Script error.`, ...). All ops/writes classify `expected`. | - | - -Exact negative tags emitted by `pattern()` (needed when editing `TEST_PATTERNS`): search `nodebounce nocache -notimeout`; form `nodisable noidem`; cart `norollback noaddguard co-nodisable co-noidem nobadge`; toggle -`norollback noecho`; poll `notimeout` (positive `timeout`); board `noecho norollback novcheck`; chat `nodisable -nounread`; settings `norollback`; nav `noswr`; bulk `nodisable`. Tags are stored as `<kind>/<tag>`. - -Knob draws in each feature's `make()` (weights `a:w`, probabilities `p`): - -| feature | draws | -|---|---| -| search | guard none:4 abort:2 reqid:2 check:2; debounce 0:4 / int(120,450):4; cache p 0.25; minLen 0/1/2 equal; loadingFlag p 0.7; totalField p 0.6; onError show:5 silent:2 throw:2; timeout 0:3 / int(2500,9000):2; 12-40 seeded items; pageSize 10/20/25 | -| editor | save debounce:5 (300-1500 ms) / interval:2 (1500-5000 ms) / button:3; overlap allow:5 serialize:4; echo always:5 if-unchanged:3 version-only:2; versionCheck p 0.4; onConflict refetch:2 overwrite:1 show:2; live p 0.4 (blind:1 if-clean:1); retry none:3 once:2 backoff:2; timeout 0:3 / int(3000,10000):2; method PUT p 0.7 else PATCH; externalEdits 0:3 1:2 2:1 | -| form | retry none:4 same-key:2 no-key:3; idemKey = same-key or p 0.25; disable p 0.45; retryOn timeout:1 5xx:1; timeout (retry none: 0:2 / int(2000,6000):1, else int(1500,6000)); onSuccess append:3 refetch:1; optimistic p 0.35; rollback p 0.6; countField p 0.7; countOnAllPaths p 0.4; onError show:4 throw:1; 2-8 seeded items | -| cart | mode optimistic:3 server:3 echo:3; rollback p 0.6; recompute always:3 skip-rollback:4 skip-echo:2 items-only-qty:1; addGuard p 0.4; badge store p 0.5; checkout disable p 0.5, retry none:3 same-key:2 no-key:2, idem = same-key or p 0.3, timeout 0:2 / int(2000,7000):3; 4-10 products | -| toggle | endpoint absolute:3 relative:2; rollback p 0.6; echo p 0.5; pendingGuard p 0.35; countField p 0.65; countPartial p 0.5; 4-12 items | -| counter | endpoint increment:3 absolute:2; echo always:3 latest-only:2 none:1; retry none:3 retry:2; 3-8 items | -| poll | intervalMs 800:2 1000:3 1500:3 2000:2 3000:1 5000:1; mode interval:3 chain:3; skipIfInflight p 0.5; onFail backoff:3 tight:2 ignore:3 throw:1; timeout 0:3 / int(1500,6000):2; seqGuard p 0.35; 2-8 metric changes; 2-4 metrics | -| board | push blind:4 version:3 skip-pending:2; echo p 0.5; rollback p 0.6; countsField p 0.7; countsOnPush p 0.4; versionInBody p 0.3; 5-12 cards; 1-5 external moves | -| chat | optimistic p 0.6; dedupe id:2 clientId:2 none:3; onResponse replace:3 append:2 ignore:1; disable p 0.3; unread p 0.5; 0-4 incoming | -| settings | 2-3 keys; echo full:4 key:2 none:2; seqGuard p 0.3; serialize p 0.25; rollback p 0.5 | -| nav | 2-4 views x 2-3 resources (later resources depend on the first with p 0.3); mode all:4 allSettled:2 chain:2; routeGuard p 0.45; abortOnNav p 0.3; onError throw:2 banner:3 partial:2; swr p 0.3 | -| list | guard none:4 reqid:3 abort:2; moreGuard p 0.5; 15-45 items; pageSize 5/8/10 | -| bulk | applyAll p 0.45; countsField p 0.7; countsPartial p 0.5; disable p 0.5; 6-14 items, each `locked` p 0.2 | -| auth | ttlMs int(2500,9000); singleFlight p 0.5; 2 resources under `me/<entity>` | -| benign | heartbeatMs 2000/3000/5000; beaconOnTimer 0/2500/4000 ms; noise errors at U(500,14000) ms (count: see gotchas) | - -The network adds failure-mode opportunities independent of features: random 5xx, network errors, latency spikes, -slow periods, outages (`503 500 502 neterr hang empty`), capacity overload (`503 429 latency`), rate limits with or -without `retry-after`, replica lag, and server bugs (`drop-field null-field empty-list stale-replica html`). - -### Domains and naming (`sim/src/app/vocab.ts`, `sim/src/app/naming.ts`) - -- `DOMAINS` (55, in array order; **bold** = `TEST_DOMAINS`): commerce, chat, docs, project, finance, health, - travel, iot, games, media, crm, hr, education, maps, analytics, social, support, inventory, logistics, banking, - calendar, food, realestate, **music**, news, email, notes, todo, fitness, **weather**, rides, events, **hotel**, - library, **legal**, insurance, energy, **farm**, fleet, pharmacy, devops, code, marketing, **survey**, nonprofit, - **permits**, sports, photos, jobs, **pets**, **auction**, wiki, procurement, **payroll**, invoicing. -- A `Domain` has `name`, `titles` (app titles), `entities` (2 x `Entity {s, p, name, words, nums, status, flags, - create}`), `docs` (`[noun, textFields]`), `metrics`, `topics`, `settings`, `bulk` verbs, `people`. Built with the - string helpers `D(...)` / `E(...)` (nums as `field=lo-hi-decimals`). -- `Naming` per program (`rP.fork("naming")`): route casing kebab:5 snake:2 camel:1; route prefix `/api`:5 - `/api/v1`:3 `/api/v2`:1 `/v1`:2 `/rest`:1 `/svc/<app-title-kebab>`:1 none:1; store names camelCase p 0.8 else - snake_case (unique: suffix `2`, `3`, ... or `_2`, `_3`, ... in snake case); field names camelCase p 0.82 else snake_case. `field(role, scope)` - picks once per `(role, scope)` from the synonym pool `SYN` (e.g. `list`: items results rows list entries - records data hits; `loading`: loading isLoading pending busy fetching inFlight). `route(...)` prefixes a scope - word (`shop admin team my app store hub desk`, chosen by a hash of the owning feature id) when a path could - match another feature's route, so features never share an endpoint. -- Each feature's view route (`FeatureInst.route`) is `/<kebab of entity plural | "editor" | app|home|workspace>`; - the program starts on the first feature's route (`runScenario` -> `env.setRoute`), except that a `nav` feature's - `init()` switches to its own first view route, and its navigation steps change the route later. +| `search` | `guard:none\|abort\|reqid\|check`, `debounce`, `cache`, `err:show\|silent\|throw`, `timeout` | out-of-order results overwrite newer ones (stale, now mostly a `delivery` decision); per-keystroke requests; unhandled rejection | - | +| `editor` | `save:debounce\|interval\|button`, `overlap:allow\|serialize`, `echo:always\|if-unchanged\|version-only`, `vcheck:*`/`novcheck`, `live:blind\|if-clean`/`nolive`, `retry:*` | overlapping saves; older echo over newer typing; 409s; blind live edits; retry of old text | external collaborator edits | +| `form` | `disable`, `idem`, `retry:none\|same-key\|no-key`, `retry-on:*`, `ok:append\|refetch`, optimistic variants, `count\|count-partial\|nocount` | double submit; duplicate create after committed timeout; no rollback; partial count | count == len(list) | +| `cart` | `mode:optimistic\|server\|echo`, `rollback`, `recompute:*`, `addguard`, `co-*`, `badge` | non-idempotent add + double click; stale full-cart echo; totals not recomputed; duplicate orders | total, count, badge | +| `toggle` | `ep:absolute\|relative`, `rollback`, `echo`, `pending-guard\|noguard`, count variants | relative toggle + double click; echo flip-back; partial count | flagged count | +| `counter` | `ep:increment\|absolute`, `echo:*`, `retry:*` | over-count; stale echo | - | +| `poll` | `mode:interval\|chain`, `skip-inflight\|overlap`, `fail:backoff\|tight\|ignore\|throw`, `seq\|noseq`, `timeout` | overlapping polls; tight retry loop (now `anomaly: "storm"` -> overload); throw after 2 failures | external metric changes | +| `board` | `push:blind\|version\|skip-pending`, `echo`, `rollback`, counts variants, `vcheck` | blind push over a pending local move (conflict); stale push; partial counts; 409 | per-column counts; external moves | +| `chat` | `optimistic\|pessimistic`, `dedupe:*`, `resp:*`, `disable`, `unread` | duplicate messages; draft cleared; double send | incoming messages | +| `settings` | `echo:full\|key\|none`, `seq\|noseq`, `serialize\|parallel`, `rollback` | full-object echo reverts a newer toggle | - | +| `nav` | `mode:all\|allSettled\|chain`, `route-guard\|noguard`, `abort\|noabort`, `err:*`, `swr` | previous view's data in the current view; unhandled rejection; partial render | - | +| `list` | `guard:none\|reqid\|abort`, `more-guard\|more-noguard` | stale page after filter change; duplicate page appends | - | +| `bulk` | `assume-all\|per-result`, counts variants, `disable` | assume all succeeded (`shape` -> unusual); partial counts | per-status counts | +| `auth` | `single-flight\|per-request-refresh` | rotated-token second refresh -> forced logout; duplicate refresh | - | +| `benign` | `beacon-timer\|beacon-user`, `noise:0\|1\|2` | none by design (heartbeats, ignored beacons, harmless uncaught errors); all `expected` | - | + +Exact negative tags and per-feature `make()` draws of the round-1 features are as documented for 654d822 (unchanged +files; read each `make()` and `pattern()`); `TEST_PATTERNS` still names only round-1 patterns. + +### Round-2 combinators + +All 31 honour `FeatureCtx.clean` (correct guards in clean runs). Pattern tags from each `pattern()`; files hold the +full knob descriptions in their header comments. + +| feature | pattern tags | defects / risky variants | env / relations / external | +|---|---|---|---| +| `infinite` (cursor infinite scroll) | `guard:inflight\|none`, `reset:*`, `dedupe\|nodedupe`, `cursor:*`, `count:*` | duplicate page appends; old-filter page lands in the new list and hijacks the cursor; offset overlap | relation; external inserts | +| `upload` (queue with progress/cancel) | `retry:*`, `idem\|noidem`, `cancel:*`, `retry-guard\|retry-noguard`, `conc:*`, `totals:*` | duplicate file after committed timeout; orphan after cancel; Retry restarts running rows; partial totals | relation | +| `offline` (outbox) | `replay:*`, `idem\|noidem`, `reconcile\|noreconcile`, `queue:*`, `persist\|memory`, `done\|done-partial\|nodone` | temp-id 404s; racing replays; duplicate create on replay; partial done-count | `env()` offline windows; relation | +| `wsreconnect` (managed live feed) | `backoff:*`, `gap:*`, `seqcheck`, `dedupe`, `ticket`, `unread-*` | reconnect storm; missed events (stale feed); duplicate events | `env()` socket drops; external | +| `undo` (optimistic delete + toast) | `mode:*`, `fail:*`, count variants; `mode:immediate` adds `restore:*`, `await-delete\|race-delete`, `toast-once\|toast-stays`, `filter-pending\|nofilter`, other modes `flush-prev\|per-item-timers` | restore before delete (409); double restore; refresh resurrects item | relation; external | +| `reorder` (drag reorder) | `send:*`, `echo:*`, `serialize\|parallel`, `push:*`, `vcheck`, `retry`, `ui:*`, `head*` | relative PATCH retried twice; old echo reverts a newer reorder; blind push conflict | relation; correlated external | +| `querycache` (React-Query style) | `dedupe`, `retry:*`, `invalidate:*`, optimistic variants, `stale:*`, `interval`, `focus`, `observers:*`, `total*` | duplicate queries; invalidation refetch before commit; revalidation over optimistic update | relation; external | +| `graphql` (batched queries) | `batch:*`, `retry:*`, `ferr:*`, `seq`, `addguard`, `refresh` | request storms; whole-batch retry re-runs the mutation; null over good data; out-of-order batches | external | +| `saga` (reserve -> charge -> confirm) | `compensate`, `derive\|derive-partial`, `idem`, `retry:*`, `disable`, `cancel:*` | half-done server state; double charge; partial derived count | relation; external | +| `wizard` (async validation) | `vguard:*`, `nav:*`, `disable`, `idem` | stale validity; double click skips a step; duplicate submit | correlated external (name taken -> 422, benign) | +| `etag` (If-Match autosave) | `if-match\|blind`, `412:*`, `echo:*`, `serialize\|overlap` | lost updates; older echo over newer typing; overlapping 412s | correlated external | +| `presence` (carets) | `throttle\|every-event`, `backoff\|hammer`, `ttl\|no-ttl`, `count\|count-partial` | request storm into 429/503; ghosts; partial count | relation; external | +| `badge` (notifications + unread) | `all:*`, `dec:*`, `poll:*`, `rollback`, `badge-store\|badge-inline` | mark-all clobbers unseen; lagging replica count overwrites badge; partial badge | relation; correlated external | +| `facets` (faceted search) | `guard:*`, `update:*`, `url:*`, `debounce` | stale facet response; split/partial updates; URL drift | relation; external | +| `masterdetail` | `guard:*`, `echo:*`, `switch:*`, `disable` | A's detail under B; A's saved values into B's form | relation; external | +| `clockskew` (server timestamps vs skewed clock) | `fresh:*`, `token:*`, `check:tight\|normal` | refetch loop; premature token refresh; expired data shown; 401 | `env()` skew; external | +| `longtask` (main-thread blocking) | `render:*`, `input:*`, `reqid`, `busy-guard`, `autorefresh` | late timers; re-clicks during the block; swallowed clicks | uses `env.busy` -> `loop.advance` | +| `cascade` (dependent selects) | `guard:*`, `clear`, `validate`, `depth:*` | old parent's options land late; invalid child kept | relation (child in parent's options) | +| `exportjob` (async job + polling) | `dedupe:*`, `retry:*`, `poll:fast\|normal`, `backoff`, `stop-done`, `cleanup`, `maxwait` | duplicate jobs; fast polling (overload); polling after done/close | - | +| `payment` (intent flow) | `disable`, `create-idem`, `confirm-idem`, `retry:*`, `on409:*`, `server:*`, `poll:*`, `status:*` | double charge (server damage); 409 as failure; older status over `succeeded` | - | +| `inventory` (stock-limited reserve) | `optimistic:*\|pessimistic`, `on409:*`, `refresh`, `addguard`, `idem` | phantom reservations; partial rollback; 409 storm on stale stock | relation; correlated external | +| `prefetch` (hover prefetch) | `trigger:*`, `dedupe`, `ttl`, `vguard` | hover storm; duplicate in-flight request; old copy over newer | correlated external | +| `multitab` (localStorage / BroadcastChannel) | `kind:*`, `via:*`, `apply:*`, `persist:*`, `server:*`, `patch\|full`, `echo-*`, `refetch-*` | other tab clobbers unsaved local changes (conflict) or older over newer (stale); refetch storms | correlated external via `otherTab` | +| `ratelimit` (strict quota) | `on429:*`, `fanout:*`, `auto`, `strict-window\|lenient-window` | immediate retry loop (storm); fan-out over quota | external | +| `cdn` (edge cache) | `after:*`, `invalidate:*`, `auto` | stale CDN copy over a fresh echo (purge race) | external | +| `swcache` (SW-style cache) | `strategy:*`, `key-guard`, `persist\|memory` | cache-first keeps broken responses; slow fetch for the previous tab overwrites the current one | relation; external | +| `countdown` (auctions vs skew) | `mode:*`, `clock:*`, `on409:*`, `retry:*`, `live\|poll`, `skew\|noskew` | closes too early / stays open; bid storm; optimistic bid kept | `env()` skew; external | +| `money` (derived money fields) | `round:*`, `recompute:*`, `echo:*`, `save:*`, `rollback` | totals not recomputed (partial); older echo over newer edits | relation | +| `permissions` (role downgrade) | `on403:*`, optimistic variants, `live`, `poll` | repeated 403s; stale `canEdit` (partial); no rollback | relation; correlated external | +| `flags` (feature-flag rollout) | `v2:*`, `flags:*`, `fallback`, `validate` | broken v2 (`anomaly: "shape"` -> unusual); total silently 0 | relation; external | +| `schemadrift` (deploy changes schema) | `drift:*`, `client:*`, `deploy-rollback\|deploy-stays` | NaN / garbage totals (`shape`); uncaught `toFixed`/parse errors | relation; external | + +`TEST_FEATURES` (test only): swcache, presence, cascade, saga, prefetch, permissions. + +The network adds failure modes independent of features: random 5xx, network errors, latency spikes, slow periods, +outages (`503 500 502 neterr hang empty`), capacity overload, rate limits, replica lag, server bugs, and (round 2) +offline windows and socket drops. + +### Domains and naming (`sim/src/app/vocab.ts`, `vocab2.ts`, `naming.ts`) + +- `DOMAINS` in `scenario.ts` = the 55 of `vocab.ts` followed by the 60 of `vocab2.ts` (115). Round-2 domains: + dental, triage, lims, trials, genomics, journaling, construction, architecture, manufacturing, quality, mining, + oilgas, ports, airline, railways, transit, parking, evcharging, solar, water, waste, city311, elections, courts, + dispatch, childcare, schooladmin, admissions, language, recruiting, salon, pos, printfarm, dealership, portfolio, + taxes, mortgage, marina, skiresort, themepark, museum, cinema, podcast, esports, wedding, volunteer, hoa, + homeservices, mdm, secops, observability, featureflags, datawarehouse, mlops, labeling, translation, ediscovery, + patents, gardening, genealogy. +- `TEST_DOMAINS` (19/115): weather, legal, pets, auction, farm, permits, music, hotel, payroll, survey, dental, + mining, railways, water, elections, admissions, marina, mlops, genealogy. +- Two round-1 vocab edits since 654d822: weather `station.temp` range now `0-40` (was `-20-40`), devops `deploy` name + field `release` (was `version`). +- Naming, routes and view routes are unchanged from round 1 (route casing kebab:5 snake:2 camel:1; prefixes `/api`, + `/api/v1`, `/api/v2`, `/v1`, `/rest`, `/svc/<app>`, none; synonym pools `SYN`; scope words avoid route clashes). ### Fake runtime (test double) -`sim/src/run/fake-runtime.ts` -> `createFakeRuntime` implements `RuntimeLike` crudely so tests run without the real -runtime (default when `SIM_RUNTIME` is unset; `gen.js --allow-fake`). It wraps `global.fetch`, calls -`hooks.opCreated` / `hooks.mutationProposed`, and emits only these triggers: `request` (when an identical request -was sent in the last 3 s or the endpoint has a failure streak; actions `send [coalesce] delay block -[serve_cached]`), `failure` (`deliver retry`, plus `serve_cached` for an HTTP failure of a cached GET), `stall` (after max(1000 ms, 4 x median) once >= 3 latency samples -exist; `wait [hedge]`), `mutation` (an async fetch-caused write to a store written by another op since it started; -`apply discard defer`, defer = re-apply after 300 ms) and `error` (`ignore` only, so error rows are diagnosis-only). -No `inconsistency`/`transition` triggers. Situation sections: `app`, `trigger`, `facts`, `in_flight`, `timeline`. -Rows from it carry `meta.runtime: "fake"` and must never be used for training. +`createFakeRuntime` is unchanged: triggers `request`, `failure`, `stall`, `mutation`, `error` only (no `delivery`, +`inconsistency`, `transition`), crude text, `meta.runtime: "fake"`; never for training. The oracle tests that look +for `delivery` decisions need `SIM_RUNTIME=real`. ### Ask questions (`sim/src/ask/questions.ts`) -`askQuestions(a, rng)` shuffles the 11 generators, wants `rng.int(1, 3)` questions, and keeps the first that do -not return `null`; each generator gets `rng.fork(name)`. `text` = `JSON.stringify(a.state)`. Facts come from -`AskFacts` (`runner.ts` -> `askFacts`): network entries in flight / delivered in the last 15 s, last user intent -time, longest pending non-background sim op, last `save`-role op, current route. - -| qid | type | label | skip (returns null) when | -|---|---|---|---| -| `q_write_inflight` | noul | any non-GET network entry in flight | never | -| `q_any_inflight` | noul | any entry in flight | never | -| `q_pending` | score (4 options) | `min(3, in-flight count)` | > 6 in flight | -| `q_last_failed` | choice `e1..e3` + `none` | latest failed entry (HTTP >= 400 or neterr) in the last 12 s, else `none` | < 2 distinct signatures; the failed endpoint's last literal path segment is not in `text` | -| `q_recent_failure` | noul | a failure in the last 5 or 10 s | a failure is within 1 s of the window edge | -| `q_fail_count` | score | `min(3, failures in 10 s)` | count differs between 9 s and 11 s windows | -| `q_user_waiting` | noul | longest pending non-background op > N s (N in 1,2,3,5) | within 400 ms of N s | -| `q_user_recent` | noul | last user intent < N s ago (N in 1,2,3) | within 300 ms of N s | -| `q_last_save` | noul | last finished `save` op was `ok` | no finished save | -| `q_route` | choice `r1..r3` | current route among 2 decoys | route not in `text` | -| `q_slowest` | choice `o1..o4` | oldest in-flight request | < 2 in flight (age > 0); top two within 300 ms or same signature; the last literal path segment of any in-flight request is missing from `text` | +Unchanged: 11 generators (`q_write_inflight`, `q_any_inflight`, `q_pending`, `q_last_failed`, `q_recent_failure`, +`q_fail_count`, `q_user_waiting`, `q_user_recent`, `q_last_save`, `q_route`, `q_slowest`), 1-3 per probe; only +`last_failed`, `route` and `slowest` check that their evidence appears in the serialized state. ## Configuration and constants | name | type | default / value | defined in | effect | |---|---|---|---|---| -| `--rows` | number | 1000 (900 with `--sample`) | `gen.ts` -> `parse` | target rows (parts mode: total across sessions) | -| `--out` | path | `sim/out/run` (relative to cwd) | `gen.ts` | output dir; `--sample` ignores it (`sim/out/sample-tmp`) | -| `--seed` | number | 1 | `gen.ts` | first scenario seed | -| `--workers` | number | 4 (`final.sh`: `WORKERS` env, 56) | `gen.ts`, `scripts/final.sh` | worker threads | -| `--max-points` | number | 6 | `gen.ts` | labelled decision points per trajectory | -| `--test-keep` | number | 0.33 (1 with `--sample`) | `gen.ts` | fraction of test trajectories kept | -| `--explore` | number | 1 | `gen.ts` | multiplies exploration eps | -| `--no-ask` / `--allow-fake` / `--sample` | flags | off | `gen.ts` | no ask rows / fake runtime (never for training) / sample mode | -| `--parts`, `--chunk`, `--merge-only` | flag, number, flag | off, 100, off | `gen.ts` | resumable parts of `chunk` seeds; merge only | -| `batch` | const | 2 seeds per worker message | `gen.ts` | non-parts feeding | -| `SIM_RUNTIME` | env | unset (fake) | `sim/test/helpers.ts` -> `testFactory` | `real` runs tests on the real runtime | -| `SIM_DEBUG` | env | unset | `sim/test/oracle.test.ts` | prints state, cost parts and snapshots in the real-only invariant test | -| `TIMEOUT` | env (s) | 1800 | `scripts/vm.sh` | every `vm.sh run/exec` command is wrapped in `timeout`; phase A took 2,444 s, so long `gen.js` runs need a larger `TIMEOUT` (how phase A was launched is unverified) | -| scenario root key | string | `"scenario-v1"` | `scenario.ts` -> `buildScenario` | salt of every scenario draw; changing it re-rolls every seed | -| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` -> `realRuntimeFactory` | module specifier to import | -| runtime options | object | `model:false, mode:"heal", report:"silent", observe{fetch,timers,websocket: true; xhr,user,errors,nav,storage,perf: false}, triage:"salient", policy{thresholds{report 0, guard 0.5, heal 0.5}, holdBudgetMs 1e9, maxActionsPerMinute 1e9, requireDiagnosis false}, historySize 500` | `rt.ts` -> `createOptions` | forced-action contract with the runtime | -| feature count | weighted | 1:35, 2:45, 3:20; +benign p 0.3 | `scenario.ts` -> `buildScenario` | program size | -| `idStyle` | weighted | num 4, uuid 2, prefixed 2, slug 1 | `scenario.ts` | server id format (`Db.makeId`): num = `1000 + h % 899000`; uuid v4-shaped; prefixed = `<3-letter noun>_<digit><letter><12 chars>`; slug = `<noun[:6]>-<4 base36 chars>`. The runtime normalises a slug id in signatures only when `isSlugId` (`packages/runtime/src/util.ts`) accepts it: the 4-char suffix must start with a digit or alternate letters/digits at least twice (`k2x9`, `1cam`); all-letter, all-digit and single-transition suffixes (`abc1`, `a123`) stay literal. The sim's own `sigOf` never normalises slugs | -| API style | uniform | `items`, `data`, `bare`, `results` | `server.ts` -> `API_STYLES` | response envelopes | -| `tUser` | ms | 15%: U(120000, 300000); else U(20000, 75000) | `scenario.ts` | user session length | -| `warmup` | ms | `tUser x U(0.3, 0.6)` | `scenario.ts` | earliest start of outages/slow periods/bugs; ask probes from `warmup x 0.5` | -| `tEnd` | ms | `tUser + U(2500, 5000)` | `scenario.ts` | run end | -| chaos | weighted | calm 2, normal 3, flaky 3, degraded 3, storm 1 | `scenario.ts` | network profile | -| latency multiplier `m` | number | calm 0.5, normal 1, flaky 1.5, degraded/storm 2 | `scenario.ts` -> `makeNet` | scales medians: read U(50,220)m, write U(90,380)m, auth U(80,300)m, upload U(300,1500)m, bulk U(200,900)m; 25% of endpoints get U(100,1200)m | -| `spikeP`, `spikeMul` | number | calm 0.005; normal U(0.01,0.04); else U(0.01,0.1); mul [3, U(6,25)] | `makeNet` | latency spikes | -| `transientP`, `postCommitP` | number | calm 0; normal U(0,0.015); else U(0.02,0.12); post-commit U(0.2,0.7) | `makeNet` | random 5xx (some after commit) | -| `netErrP` | number | calm 0; normal U(0,0.004); else U(0,0.03) | `makeNet` | network errors (50% commit) | -| `gatewayMs` | ms | int(8000, 30000) | `makeNet` | 504 after this time in flight | -| outages | windows | degraded/storm, or flaky p 0.4: 1-2, length U(1500,9000), modes 503:4 500:2 502:2 neterr:2 hang:1 empty:2, endpoints `*` (p 0.4) or 1-3 | `makeNet` | outage failures | -| slow period | window | non-calm, p 0.25 (normal) / 0.6: length U(2000,10000), mul U(3,15) | `makeNet` | slow responses | -| capacity | object | storm, or degraded p 0.4: perSec int(4,14), mode 503:2 429:2 latency:1 | `makeNet` | overload shedding | -| rate limit | object | non-calm p 0.25: one endpoint, perSec int(2,6), `retry-after` p 0.6 | `makeNet` | 429s | -| replica lag | object | non-calm p 0.15: ms int(300,2500), p U(0.1,0.5) | `makeNet` | stale reads | -| server bug | window | p 0.05 calm / 0.18: a read endpoint, length U(2000,8000), kinds drop-field 2, null-field 2, empty-list 3, stale-replica 1 (2500 ms lag), html 1 | `makeNet` | malformed responses | -| push latency | lognormal | median U(20,150), sigma U(0.2,0.8); in order per topic | `makeNet`, `Network.publish` | live updates | -| persona | object | keyMs U(70,210), keySigma U(0.25,0.6), thinkMs U(500,2600), doubleClickP 0:3 0.06:3 0.18:2 0.4:1, impatientP 0:3 0.3:3 0.7:2, impatienceMs U(900,3500), typoP U(0,0.25) | `feature.ts` -> `randomPersona` | user behaviour | -| ask times | ms | 1-3 at U(warmup x 0.5, tEnd - 200) | `scenario.ts` | ask probes | -| `diagnoses` vocab | object/null | 50% default; else 30% drop 1-2 of `conflict slow overload unusual inconsistent duplicate transient`, each label paraphrased p 0.6 (`DIAG_PARA`) | `scenario.ts` -> `diagVocab` | runtime `vocabulary.diagnoses` | -| `actionWords` vocab | object/null | 50% default; else each action paraphrased p 0.6 (`ACTION_PARA`) | `scenario.ts` -> `actionVocab` | runtime `vocabulary.actions` | -| `modelMs` | ms | U(6, 25); latency `lognormal(modelMs, 0.35)` | `scenario.ts`, `runner.ts` | decider latency | -| `budget` | chars | 3200:40, 2000:30, 1000:30 | `scenario.ts` | runtime `situation.budget` | -| `TEST_DOMAINS` | set | weather, legal, pets, auction, farm, permits, music, hotel, payroll, survey | `scenario.ts` | held-out domains (10/55) | -| `TEST_PATTERNS` | set | `search/guard:check`, `settings/serialize`, `toggle/pending-guard`, `list/guard:abort`, `cart/recompute:items-only-qty`, `editor/echo:version-only`, `poll/fail:throw` | `scenario.ts` | held-out patterns | -| family hold-out | hash | `hashAll("family-split-v1", family) % 100 < 17` | `scenario.ts` -> `familyHeldOut` | test families | -| dev split | hash | `hashAll("dev-split-v1", family) % 100 < 3` | `scenario.ts` -> `splitOf` | dev families | -| `TRIGGER_W` | weights | mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2 (x1.5 non-expected) | `trajectory.ts` | point sampling | -| futures K / adaptive gain | number | 3 / > 0.05 | `trajectory.ts` -> `pointCosts` | extra futures | -| `W` | object | area 1.0, horizonMs 10000, finalMs 15000, finalClient 4.0, serverItem 25, serverField 6, shownError 1.5, uncaught 1.0, relation 0.8, relationFinal 2.0, wasted 0.08, latency 0.25 | `cost.ts` | cost weights | -| `LABEL` | object | tier {passive 0, guard 0.25, heal 0.5}, exactTie 1.5, tieEps 0.05, tau0 0.1, seMul 1.0 | `cost.ts` | soft labels; an action missing from `TIER` gets the heal premium and `meta.tiers` value `heal`; `adjusted`/`se` rounded to 3 dp, `dist` to 4 dp | -| cost volatile keys | set | client: `id version rev revision etag updatedAt updated_at clientId pending seq`; server snapshot: `version updatedAt updated_at rev etag seq` | `cost.ts` (`VOLATILE`), `server.ts` (`VOLATILE`) | ignored when comparing list items / server items | -| server history | number | 64 pre-write snapshots per resource key | `server.ts` -> `Db.recordWrite` | replica-lag lookback | -| arrival windows | number | global list <= 512 (oldest 256 dropped when exceeded), per signature <= 256 (oldest 128 dropped); load window 1000 ms | `network.ts` -> `noteArrival` | capacity and rate-limit counting | -| transform | probs | 50% unchanged; else drop one non-passive non-best action p 0.12 (needs >= 3 options), shuffle p 0.5 | `transform.ts` | option order/subsets | -| diagnosis-only rows | count | <= 3 per trajectory | `trajectory.ts` | - | -| ask questions | count | 1-3 per probe, 11 generators | `ask/questions.ts` | - | -| loop limits | number | 2,000,000 tasks per `runUntil`; 1000 `afterTask` re-arms | `loop.ts` | `LoopError` -> trajectory exception | -| `BASE_URL` | string | `https://app.example.test` | `network.ts` | app origin | -| app timeouts | ms | cart add/qty 8000, toggle 8000, counter 6000, board 8000, settings 8000, chat 10000, bulk 10000, list 9000, nav 10000, auth 8000, beacon 5000, heartbeat 4000 | feature files | `timeout` outcomes | +| `--rows`, `--out`, `--seed`, `--workers`, `--max-points`, `--test-keep`, `--explore` | | 1000 (900 sample), `sim/out/run`, 1, 4, 6, 0.33 (1 sample), 1 | `gen.ts` -> `parse` | as round 1 | +| `--no-ask` / `--allow-fake` / `--sample` | flags | off | `gen.ts` | `--no-ask` is ignored in unlabeled mode | +| `--parts`, `--chunk`, `--merge-only` | flag, number, flag | off, 100, off | `gen.ts` | resumable parts | +| `--unlabeled` | flag | off | `gen.ts` | `mode: "unlabeled"` | +| `--on-policy <dir>` | path | - | `gen.ts`, `worker.ts` | `mode: "onpolicy"`; TRAIN export dir read from disk; needs `sim/dist/model-host/host.js` (`npm run build`) and `onnxruntime-web` resolvable | +| `SIM_RUNTIME` | env | unset (fake) | `sim/test/helpers.ts` | `real` = tests on the real runtime | +| `SIM_DEBUG` | env | unset | `sim/test/oracle.test.ts` | debug prints in a real-only test | +| `SIM_S2` | env | on | `latent.ts` -> `S2` | `0` turns S2 off (futures re-draw network/timing only) | +| `SIM_PROBE` | env | off | `probe.ts` -> `PROBE` | `1` adds `meta.probe` (analysis only; never changes labels) | +| `SIM_FEATURE_HOLDOUT` | env | on | `scenario.ts` | `off` disables the `TEST_FEATURES` hold-out | +| `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `rt.ts` -> `realRuntimeFactory` | module specifier | +| runtime options | object | `model:false, mode:"heal", report:"silent", observe{fetch,timers,websocket,storage: true; xhr,user,errors,nav,perf: false}, triage:"salient", policy{thresholds{report 0, guard 0.5, heal 0.5}, holdBudgetMs 1e9, maxActionsPerMinute 1e9, requireDiagnosis false}, historySize 500`; on-policy `policy {holdBudgetMs 1e9, maxActionsPerMinute 1e9}` | `rt.ts` -> `createOptions` | forced-action contract; `storage` observer is new | +| scenario root key | string | `"scenario-v1"` | `buildScenario` | unchanged key, but the 115-domain list and new weights already changed every seed's world vs phase A/B | +| clean run | p | 0.05 | `buildScenario` | see Concepts | +| persona | weighted | casual 5, power 2, mobile 2, keyboard 1, novice 1; base keyMs U(70,210), keySigma U(0.25,0.6), thinkMs U(500,2600), doubleClickP 0:3/0.06:3/0.18:2/0.4:1, impatientP 0:3/0.3:3/0.7:2, impatienceMs U(900,3500), typoP U(0,0.25), tabSwitchPerMin U(0,1.5); kind overrides in `randomPersona` | `feature.ts` | user behaviour | +| chaos | weighted | calm 2, normal 3, flaky 3, degraded 3, storm 1, mobile 1, peak 1, deploy 1; mobile persona -> `mobile` with p 0.7; clean -> calm | `buildScenario` | network profile | +| `mobile` regime | - | flaky base; latencies x U(1.5,3), sigma U(0.6,1.0); netErrP >= U(0.01,0.05); 1-2 offline windows (1.5-8 s, + p 0.4 a 1-4 s one); a socket drop (0.8-5 s) | `makeNet` | - | +| `peak` regime | - | degraded base; capacity perSec int(3,9) (503/429/latency 2:2:2); up to 3 endpoints rate-limited perSec int(1,4), retry-after p 0.7; a global slow period 3-15 s x U(2,8) | `makeNet` | - | +| `deploy` regime | - | normal base; a global 502 outage 0.8-3 s; up to 2 read-endpoint bugs (2-10 s); replica lag int(500,3000) ms, p U(0.2,0.6) | `makeNet` | - | +| other network params | | `m`, spikes, transients, `netErrP`, `gatewayMs`, outages, slow periods, capacity, rate limits, replica lag, server bugs, push latency: as round 1 (on the base regime) | `makeNet` | - | +| offline failure | ms | U(2,12) then `TypeError` | `Network.send` | `cause: "offline"` | +| `tUser`, `warmup`, `tEnd`, ask times, `modelMs`, `budget`, `idStyle`, API style, vocab randomisation | | as round 1 (15% long sessions U(120,300) s else U(20,75) s; budget 3200:40 2000:30 1000:30) | `scenario.ts` | - | +| `TEST_DOMAINS` / `TEST_PATTERNS` / `TEST_FEATURES` | sets | 19 domains / 7 round-1 patterns / 6 features | `scenario.ts` | held-out splits | +| family hold-out / dev | hash | `hashAll("family-split-v1", family) % 100 < 17` / `hashAll("dev-split-v1", family) % 100 < 3` | `scenario.ts` | - | +| `TRIGGER_W` | weights | mutation 1, delivery 1.2, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2 (x1.5 non-expected) | `trajectory.ts` | point sampling | +| `DENSE_K` | number | 600 | `trajectory.ts` | gold: only decisions `k < 600` are labelled (replay cost); `pickOnPolicy` does not apply it | +| exploration | weights | eps 0:4, 0.08:3, 0.2:2 x scale; `eps`, `eps/2` (delivery), `eps/4`; unlabeled scale x 1.5 | `trajectory.ts` -> `explorePolicy` | - | +| `maxUnlabeled` | number | 40 | `GenOptions` | unlabeled rows per trajectory | +| futures K / adaptive gain | number | 3 / > 0.05 (future 1 always with S2) | `pointCosts` | - | +| `S1_GAP` | number | 1.0 | `trajectory.ts` | S1 threshold on passive's adjusted gap | +| `REPEAT_PRIOR` | table | gap <= 100 ms 0.74, <= 200 0.67, <= 500 0.17, <= 1000 0.23, <= 2000 0.2, <= 3000 0.06 | `latent.ts` | P(accidental \| gap) | +| `W` / `LABEL` | objects | as round 1 (area 1.0, horizon 10 s, final 15 s, finalClient 4.0, serverItem 25, serverField 6, shownError 1.5, uncaught 1.0, relation 0.8, relationFinal 2.0, wasted 0.08, latency 0.25; premiums 0/0.25/0.5, exactTie 1.5, tieEps 0.05, tau0 0.1, seMul 1.0) | `cost.ts` | - | +| transform | probs | 50% unchanged; else drop one non-passive non-best action p 0.12 (>= 3 options), shuffle p 0.5 | `transform.ts` | - | +| loop limits | number | 2,000,000 tasks per `runUntil`; 1000 `afterTask` re-arms | `loop.ts` | - | +| `pushIdsByData` cap | number | 2000 entries (oldest dropped) | `runner.ts` | payload fallback for push ids | +| cluster seed bases | numbers | v1 gold 1e9 / unlabeled 3e9 / on-policy 5e9; v2 gold 11e9 / unlabeled 16e9 / on-policy 22e9 / checks 19e9; + NN x 1e8 | `orchestrate.sh`, `bigrun.sh` | disjoint ranges | ## Invariants and gotchas -- **Never use unkeyed randomness or real time in world code.** No `Math.random`, `Date.now` or `performance.now` - inside a run (`performance.now` is only for trajectory/smoke timing stats, `Date.now` only for the CLI's timing - and progress log). Use the - spec rng in `make`, `user.rng` in `session`, the `rng` passed to `external`, and at run time - `env.rng.fork(<key derived from the intent>)` (e.g. idempotency keys `env.rng.fork("idem", ref)`). A draw whose - order depends on the forced action shifts unrelated draws and breaks futures or the prefix check. -- **Request draws are keyed by `(seed, identity, occurrence)`** (`identity = method + path + search + body`). Two - requests with identical identity share an occurrence counter; adding a request in a cf run only shifts later - occurrences of the same identity. -- **Server ids are content-derived** (`Db.makeId`: hash of the `db-<seed>` salt, collection, create key (the - canonical/JSON body or a feature-chosen key such as `seed:<name>` or `line:<productId>`), and how many identical - keys were created before). The same intent gets the same id in every run; a duplicate gets a new one. Changing - a create body format changes ids. -- **`runtime.situation()` must stay side-effect free**: ask probes run only in the base run; if a probe consumed - runtime ids, every cf prefix would mismatch (NEEDS item 5). -- **Correlation is synchronous.** `know.callingOp` / `know.writing` / `know.callingIntent` are set only around the - synchronous `fetch` / `atom.set` / `runtime.user` call; the runtime's `opCreated` / `mutationProposed` hooks must - fire inside those calls. If a correlation fails, `subject.kind` is `unknown` and the row loses its diagnosis label. - Phase A: 100% correlated (`subject_correlated`). -- **`x-request-id` is the correlation channel.** The runtime ignores it for identity and never prints it; - `sim/test/rows.test.ts` asserts no `x-request-id` / `req-xxxxxxxx-` text appears in any `state`. Changing the - header requires it to remain in the runtime's volatile header list. -- **Gate thresholds must stay 0.5** with `requireDiagnosis: false`: the decider puts probability 1 on the forced - action; with 0 the gate would run the argmax non-passive action even when passive is forced. -- **Task owners matter.** Exceptions in `app`/`user` tasks become app uncaught errors (`window.onerror`, reported via - `runtime.reportError`); exceptions in `net`/`runtime`/`sim` tasks (and in `afterTask` hooks) are internal errors and - drop the trajectory (ideal or base run) or the decision point (cf run). -- **The ideal run has no runtime** and skips accidental and `when`-conditional steps; app-generated duplicates - (`dupOf`) share the original result. Features must set `dupOf`/`accidental` correctly or the ideal world contains - the duplicate. -- **Store weights shape the oracle.** Set per feature with `weightsOf` in `env.store(...)`. Error-message fields are - always 0 (errors are charged as episodes; a branch must never win by hiding a message); typical values: data lists - 1, totals/placed 0.8, counts 0.4-0.6, inputs/drafts/filters/view 0.3-0.5, saved flag 0.3, loading/busy flags 0.1-0.12, - versions 0. A field missing from the weights counts 1. -- **`DATA_ROLES`** (`diagnose.ts`) gates the "superseded intent -> stale" rule for mutations. A new feature role that - applies server data must be added there. -- **Calm warm-up is partial.** Only outages, slow periods and server bugs start after `warmup`; random transients, - spikes, network errors, capacity, rate limits and replica lag apply from t = 0. -- **Compact questions at budget 1000.** The runtime prints bare labels/names (null descriptions) when the budget is - <= 1400 and keeps a vocabulary override only if it is <= 24 characters; every diagnosis paraphrase and most action - paraphrases are longer (a few, e.g. `send it now`, are not), so wording randomisation mostly affects 2000/3200 rows - (label subsets still apply). -- **Scenario changes ripple to every seed.** Adding a domain, a feature, a weight or an rng draw in `buildScenario` - changes the keyed picks (e.g. `R.fork("domain").pick(DOMAINS)` depends on the array length), so the same seed yields - a different program. Do not mix rows from different sim versions under the same seed range. Splits stay - consistent across machines and versions only while `TEST_DOMAINS`, `TEST_PATTERNS` and the hash salts - (`family-split-v1`, `dev-split-v1`) are unchanged; every seed's world also depends on `scenario-v1` and the other - stream keys listed under [Concepts](#concepts-and-data-structures). -- **`stats.json` is per run**; parts mode writes `stats.session.json`; use `scripts/analyze.py` for totals. -- **The VM path.** The team never ran the sim on the 8 GB Mac (`scripts/vm.sh` header); agents ask the user before - running sim tests or generation. `scripts/vm.sh` needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure`, which are - not in the repo. `scripts/vm.sh run sim` rsyncs with `--delete` but - excludes `/sim/out/` and `dist/`, so outputs survive and builds must be redone on the VM. On the VM the repo is at - `~/gcl/sim`, so outputs land in `~/gcl/sim/sim/out/...` (the paths `training/import_*.sh` use). -- Exploration answers a fake diagnosis (`meta.fake_diagnosis: true`) when forcing a non-passive action on an - `expected` situation; later rows of that trajectory can contain the effects of explored actions - (`meta.explored_before`). -- **Non-parts vs parts determinism.** Non-parts mode hands out 2-seed batches on demand, so which seeds near the end - are included depends on worker scheduling. Parts mode uses fixed seed ranges (`seed + i*chunk`), so finished - parts are reproducible; only how many parts finish before `--rows` is reached varies. -- **`analyze.py` prefers merged files.** It reads `<dir>/<split>.jsonl` when present and only falls back to - `parts/part-*.<split>.jsonl`; after a `merge-b`, newer parts are ignored until you merge again. -- **`benign` noise count quirk.** `make()` loops `for (i = 0; i < rng.int(0, 2); i++)`, re-drawing the bound every - iteration, so `noise:0/1/2` occur with p 1/3, 4/9, 2/9 (not uniform). Fixing it changes every benign world. -- **Slug-id programs (idStyle slug, weight 1/9).** The sim's `sigOf` keeps slug ids literal, so for those programs - failure `streak`s are per item and the request rule's `clientRate(network, sigOf(op))` (compared against route - signatures with `:id`) never matches item URLs; since `anomaly: "storm"` never reaches an op, such item requests are - never diagnosed `overload` by the request rule. -- **Ideal run and futures.** The ideal run has no decider, so `future.k = -1` only moves external events; ideal - network draws are trivially 0. The ideal run is re-done per future only when an external event lies after `t_k`. -- **The cost's initial state** for both runs is the *real* run's first snapshot (`runCost`), and the window ends at - `min(tEnd, t_k + 15000, real.tStop)`; relation areas and `area` use the 10 s horizon, finals use `stop`. +- **Never use unkeyed randomness or real time in world code.** No `Math.random`, `Date.now`, `performance.now` + inside a run (`performance.now` only for timing stats such as `costMs`). Wall-clock values come from + `AppEnv.clientNow()` (`EPOCH` + virtual time + skew). A draw whose order depends on the forced action shifts + unrelated draws. +- **S2 must keep the prefix byte-identical.** Latent re-draws only touch things after *t* or unobserved by the client + (server-side commit, ideal run). If you add a latent, key it by the future salt, apply it only when `t >= L.t` or + server-side, and expect `info:latent-fallback` to count violations (~6% of re-seeded futures per the README). + `SIM_S2=0` reproduces round-1 futures. +- **Request draws are keyed by `(seed, identity, occurrence)`; server ids are content-derived; `situation()` must stay + side-effect free** (as round 1). +- **Correlation is synchronous**, now including WebSocket messages: `know.deliveringPush` is set only while the + virtual socket dispatches, so the runtime must create its `ws` message op (and fire `opCreated`) inside that + dispatch; `know.currentPush` is set only while the app's handler runs (`AppEnv.socket`). STATUS states both hold + for batch 4+. +- **Module-level state.** `knowRef`, `pushIds`, `pushIdsByData` are module globals: never run two `runScenario` + calls concurrently in one process (the generator awaits them sequentially). +- **`x-request-id` is the correlation channel** (volatile header in the runtime; `rows.test.ts` asserts it never + appears in a state). +- **Gate thresholds must stay 0.5** with `requireDiagnosis: false` and `mode: "heal"` set explicitly. The runtime's new + default mode (`observe`, our commit f3636b2) does not apply because `createOptions` passes `mode`. +- **Mutation is non-blocking in v2.** Per STATUS, without `policy.holdWrites` a `mutation` decision's `defer` is + recorded only and `discard` is a late revert; the sim does not set `holdWrites`, so forced mutation `defer` costs + the same as `apply` (then pinned to passive by the tie rule). Most stale-write cases now surface as `delivery`. +- **Delivery salience is narrow.** The runtime asks on a delivery only when the response would replace newer, already + applied data with no newer same-signature request in flight, the body changes something, and (for a pending local + change) it puts back the replaced value (STATUS batch 5). Benign concurrency usually raises no question. +- **Clean runs only fix guards in round-2 features.** Round-1 `make()` functions ignore `ctx.clean`, so a clean run can + still contain a round-1 defect; it gets a calm network and no accidental clicks. +- **Task owners matter; the ideal run has no runtime; store weights shape the oracle; `DATA_ROLES` gates the + superseded-intent rule; calm warm-up is partial; compact questions at budget 1000** (all as round 1). +- **Scenario changes ripple to every seed.** v2 added `vocab2` domains, 31 features, new weights, regimes, personas + and draws; the same seed now yields a different world than in phase A/B. Never mix rows of different sim versions + under one seed range (the cluster scripts use separate v1/v2 seed bases). +- **Unlabeled mode** ignores `--no-ask`, explores 1.5x more, and keeps decisions with < 2 actions. Its `meta.ran` is + the sim's chosen action (passive or explored), not a model's. +- **On-policy** rows have no ask rows and no exploration; replays force `rec.ran` (what the gate ran). Matching a + `decide` event to its decision uses `trigger|JSON(subjectRef without error)`; an unmatched decision keeps + `ran` undefined (recorded as passive in `meta.ran`). +- **`mini()` test scenarios** keep the seed-4242 persona's `windowEvents` and its `clean` draw; they reset steps, + external events, ask times, vocab, chaos and network. +- **The VM path** (`scripts/vm.sh`, `~/gcl/sim`) is the colleague's; `sim/out` on the train VM is a symlink to + `/data/sim-out`, which `vm.sh` sync deletes (NEEDS FYI). Not for us. +- `benign` noise-count quirk, slug-id `sigOf` behaviour, ideal-run futures and the cost's initial state: as round 1. ## How to change it safely -Before any change: read the matching test in `sim/test/`. After it (ask the user first; -[where to run things](runtime/build-test-release.md#where-to-run-things)), the team ran on the VM: -`npm run build:runtime-core && npx tsup`, `SIM_RUNTIME=real npx vitest run`, `node dist/smoke.js --seeds 40` (check `internal errors`, correlation -`*:none` counts), then a small `gen.js` run and `analyze.py`. - -1. **Add a feature combinator.** New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef`; register in - `FEATURES` and `FEATURE_WEIGHTS`. Server routes via `srv.route(method, naming.route(...), handler, {feature, kind, - idempotent, resource})` (resource `c:`/`d:`/`n:` keys enable replica lag). Client: `env.store(name, s.id, init, - {weights, resync})`, requests only via `kit.op` + `kit.call`, writes only via `kit.write` with `role`, `intent`, - `key`, `op`; set `dupOf` for accidental repeats, `anomaly: "partial"` on writes of paths that skip derived fields - (an `anomaly` passed to `kit.op` is silently dropped: `OpInit` has no such field; add it to `OpInit` and `Kit.op` - if an op-level anomaly is needed), `classify` - where content bookkeeping (`ContentBook`) decides stale/conflict/duplicate; declare `relations()` for derived - fields; `cond()` for `pendingCond` re-clicks. Surface failures with `kit.shownError()` (charged as an error - episode) or `kit.spawn(fn, "uncaught", {cause, diagnosis, op})` (becomes an `error` trigger); use `"swallow"` for - handled background work. Add new data roles to `DATA_ROLES`. Consider adding a held-out pattern to - `TEST_PATTERNS`. Every seed's world changes: regenerate all data and samples. - - *Adding a knob to an existing feature:* append the draw at the end of `make()` if you can: draws come from one - stream (`rf.fork("make")`), so inserting one in the middle shifts every later knob of that feature. A new - `naming.field(role, scope)` call draws from the program-wide naming stream (`rP.fork("naming")`, shared by all - features of the program), so it also changes field names picked later by other features. New tags in - `pattern()` change `meta.patterns` and possibly the test split (via `TEST_PATTERNS`). -2. **Add or edit a domain.** Append `D(...)` in `sim/src/app/vocab.ts` (2 entities via `E(...)`); hold it out via - `TEST_DOMAINS` if desired. Changes every seed's domain pick. -3. **Change cost weights (`W`).** Totals change; regenerate data. Re-check `sim/test/oracle.test.ts` and the README - formula. Changing only `LABEL` (premiums, tie, tau) can be re-derived offline from `meta.cost_futures` with - `actionLabel` (same pairing), without re-simulating; re-apply any option drop recorded in `meta.transform` - (`drop:<action>`), because `cost_futures` keeps every offered action. -4. **Change a diagnosis rule.** Edit `diagnose`/`diagnoseFailure` or a feature's `classify`; diagnosis does not - affect costs, but it affects exploration (`eps` vs `eps/4`), point sampling (x1.5) and `fake_diagnosis`, so action - rows can change too. Update oracle tests' expected diagnoses. -5. **Change chaos or network behaviour.** `makeNet` (parameters) and `Network.send` (mechanics). Keep every draw - keyed (`Rng(hashAll(seed, [salt,] ...))`), keep ideal-mode draw counts stable, and keep `NetEntry.cause` / - `slowCause` accurate: diagnoses read them. -6. **Add an ask question.** Add a generator to `GENS` in `sim/src/ask/questions.ts` returning `{qid, question, label, - kind}`; check the evidence appears in `text` (the serialized state) and skip borderline timings; labels must be - valid for the question type (`rows.test.ts` checks this). -7. **Change budgets.** `budget` weights in `buildScenario`; keep `meta.budget`; coordinate with TRAIN (per-budget - eval in `training/eval_runtime.py`) and the runtime's auto budgets. -8. **Change the runtime contract** (option names, thresholds, hooks). Edit `createOptions` and the structural types - in `rt.ts`/`types.ts`; run `SIM_RUNTIME=real` tests (the two real-only oracle tests and the determinism suite). -9. **After any runtime situation change** (`packages/runtime/src/situation/*`): rebuild the runtime core, regenerate - all datasets and `sim/samples/*` (`node dist/gen.js --sample --workers 8`), tell TRAIN (and update - `training/curriculum/rt.py` mirrors). Data trained so far uses tag `situation-v1`. -10. **Produce final data.** `bash sim/scripts/final.sh a` (600k rows, seeds from 10,000,000, `out/final-a`); - `bash sim/scripts/final.sh b` (1.4M rows, seeds from 50,000,000, parts of 100 seeds, resumable after the 03:00 UTC - VM shutdown); `final.sh merge-b`. To split across machines give disjoint seed ranges (phase A: about 5.8 rows - per seed, counting test-subsampled seeds). -11. **Change splits.** Edit `TEST_DOMAINS`, `TEST_PATTERNS`, or the salts/percentages in `familyHeldOut` / `splitOf`. - This moves whole trajectories between splits, so previously generated datasets become incomparable; rerun - `rows.test.ts` (split counts over 400 seeds) and regenerate. +Before any change: read the matching test in `sim/test/`. After it: `cd sim && npx tsc -p tsconfig.json --noEmit` and +`SIM_RUNTIME=real npx vitest run` locally (light checks; build the runtime first). Then **ask the user** before +`node dist/smoke.js --seeds 40` (check `internal errors`, correlation `*:none`), a small `gen.js` run and `analyze.py`. + +1. **Add a feature combinator.** New `sim/src/app/features/<kind>.ts` exporting a `FeatureDef`; register in `FEATURES` + and `FEATURE_WEIGHTS`. Requests only via `kit.op` + `kit.call` (an `anomaly` on the op now reaches the oracle), + writes only via `kit.write` with `role`, `intent`, `key`, `op`; `dupOf` for repeats, `anomaly: "partial"` on paths + that skip derived fields, `classify` where bookkeeping decides; `relations()`; `cond()`; honour `ctx.clean` (pick + correct guards); declare `env()` for offline windows / socket drops / skew; use `env.clientNow()`, `env.online`, + `env.on(...)`, `env.channel(...)`, `env.busy(ms)` and `world.otherTab` instead of globals. Add new data roles to + `DATA_ROLES`. Consider `TEST_PATTERNS` / `TEST_FEATURES`. Check `smoke.js --profile` cost. Regenerate all data. +2. **Add or edit a domain.** Append to `vocab2.ts` (keep `vocab.ts` stable); every seed's domain pick changes. +3. **Change cost weights (`W`).** Regenerate. Changing only `LABEL` can be re-derived offline with + `sim/scripts/relabel.py` from `meta.cost_futures` (re-apply `drop:<action>` transforms). +4. **Change a diagnosis or S1 rule.** `diagnose`/`diagnoseFailure`, `diagnosisFromOutcome`, `S1_GAP`, or a feature's + `classify`; affects exploration, point sampling and `fake_diagnosis`. Update oracle tests and the S1 assertion in + `rows.test.ts`. +5. **Change chaos, regimes or S2.** `makeNet` (parameters), `Network.send` (mechanics), `latent.ts` (re-draws). Keep + every draw keyed and ideal-mode draw counts stable; keep `NetEntry.cause` accurate; run `latent.test.ts` and + `determinism.test.ts`. Re-measure `REPEAT_PRIOR` with `smoke.js --repeat-prior` if the user model changes. +6. **Add an ask question.** As round 1 (`GENS`, evidence in text, skip borderline timings). +7. **Change budgets.** `budget` weights; coordinate with TRAIN and the runtime's auto budgets. +8. **Change the runtime contract.** `createOptions` and the structural types in `rt.ts`/`types.ts`; run + `SIM_RUNTIME=real` tests. A new trigger needs `PASSIVE`, `TRIGGER_W`, `TIER` (and `relabel.py`/`analyze.py` maps). +9. **After any runtime situation change** (`packages/runtime/src/situation/*`): rebuild, regenerate all datasets and + `sim/samples/*`, tell TRAIN. Current tag: `situation-v2`. +10. **Produce data.** v1 final data: `final.sh a|b|merge-b` (historical). v2 data: cluster scripts (flow 9), operated + by the colleague. Never reuse a seed base across sim versions. +11. **Change splits.** Edit `TEST_DOMAINS`, `TEST_PATTERNS`, `TEST_FEATURES` or the salts; rerun `rows.test.ts`; + regenerate. ## Tests -(Ask the user first; [where to run things](runtime/build-test-release.md#where-to-run-things).) The team ran on the -VM: `cd sim && SIM_RUNTIME=real npx vitest run` (17 tests; without `SIM_RUNTIME=real` the suites use the -fake runtime and the two real-only tests are skipped). +`cd sim && SIM_RUNTIME=real npx vitest run`: 19 tests in 5 files (lead, 2026-10-08: all passed). Without +`SIM_RUNTIME=real` the fake runtime is used and the two real-only tests are skipped, and `oracle.test.ts` fails: +checked on 2026-10-08 (`npx vitest run test/oracle.test.ts`, fake runtime): 3 failed, 5 passed, 2 skipped. The two +stale-overwrite tests find no `delivery` decision, and the outage-streak test gets `expected` instead of `failing`. +So a plain `npm test` in `sim/` is red by design; always set `SIM_RUNTIME=real`. | test file | test | what it asserts | |---|---|---| -| `sim/test/loop.test.ts` | orders macrotasks / drains microtasks | (time, seq) order; microtask chains and `afterTask` hooks run before the next macrotask; `now` ends at `tEnd` | -| | Response bodies within one macrotask | `Response.clone().json()` settles before the next macrotask | -| | keyed rng forks | `fork(label)` independent of prior draws | -| `sim/test/determinism.test.ts` | same seed -> identical rows | seeds 11-13: identical rows, 0 `prefix-mismatch`, identical final client/server state and `fp` lists | -| | replay reproduces every prefix | seeds 100-129, skipping bases with < 2 decisions (no new seed once >= 12 checks): forcing each action at decision indices 0, mid and last reproduces all `fp <= k`; asserts > 5 checks | -| `sim/test/rows.test.ts` | valid CONTRACT-D rows | 40 trajectories: no base errors, no prefix mismatch, > 40 rows, ask + >= 2 other triggers, labels reference offered options, dists sum to 1, no `x-request-id` text, passive best on > 20% of decision rows | -| | splits and transform | 400 seeds: > 40 test, > 150 train; transform keeps passive and best, renormalises the dist over remaining options | -| `sim/test/oracle.test.ts` | stale overwrite | search without guard: diagnosis `stale`, `discard` cheapest and label best | -| | one stale write among later stale writes | discarding one write still cheaper than apply; best in `discard`/`defer` | -| | intentional double add | counter increment: request diagnosis `expected`, `send` cheapest, `coalesce` > send + 1 | -| | duplicate POST after committed timeout | form retry without key: `duplicate`; `block`/`coalesce` beat `send` | -| | outage failure streak | poll during 503 outage: request diagnosis `failing`; `delay`/`serve_cached` beat `send` | -| | benign concurrency | cart server mode, two adds: `expected`, best `apply` | -| | label sharpness | `actionLabel`: sharp (> 0.95 non-passive) when futures agree, soft (passive > 0.15) when they disagree, passive > 0.9 when interventions slightly harmful | -| | exact ties | ties -> passive (> 0.95); dist sums to 1 | -| | (real only) partial-update invariant break | cart `skip-rollback` + outage: inconsistency diagnosis `inconsistent`; `rollback`/`resync` beat `ignore` | -| | (real only) duplicate token refresh | auth per-request refresh: request `duplicate`; `coalesce` beats `send` | - -Helpers (`sim/test/helpers.ts`): `testFactory`, `mini(kind, patch, opts)` (one-feature calm scenario with exact -latencies via `latencyFn`, optional outages), `step`, `runBoth`, `argmin`, `find`. `mini` = `buildScenario(4242, -{kinds:[kind], chaos:"calm", duration: opts.duration ?? 6000, domain: opts.domain ?? "commerce"})` with `patch` -merged into the spec, scripted steps (feature `f0`), no external events / ask probes / vocabulary overrides, -`tEnd = duration + 3000`, latencies read 80 / write 120 / auth 80 / upload 300 / bulk 200 ms with sigma 0, and no -spikes, transients, network errors, slow periods, bugs, rate limits, capacity or replica lag. Trajectory tests use -`maxPoints` 3 (determinism) or 4 (rows), `askRows: true`, `testKeep: 1`, `exploreScale: 1`. - -### Sample stats (`sim/samples/`) - -- `stats-final-a.json` (phase A, frozen runtime, seeds from 10,000,000, 56 workers): 600,676 rows (train 448,420 / - dev 14,613 / test 137,643), 104,116 trajectories (32,729 skipped by test-subsample), 2,401,160 runs, 2,443.8 s, - 245.8 rows/s, 937 families, drops only `diagnosis-not-in-vocab` 4,219, 0 errors. -- Trigger mix: ask 23.8%, mutation 23.3%, request 17.2%, failure 14.7%, stall 9.1%, inconsistency 5.5%, error 3.6%, - transition 2.8%. Most stall/error and a third of transition rows are diagnosis-only. -- Passive best (train): mutation 88.1%, request 74.3%, failure 70.4%, stall 64.0%, inconsistency 83.8%, transition - 85.9%, error 99.0%. -- Train diagnoses: mutation expected 49.8 / stale 17.5 / duplicate 14.1 / conflict 9.7 / inconsistent 8.4 / unusual - 0.5%; failure transient 53.6 / failing 39.1 / slow 5.8 / overload 1.5%; inconsistency expected 90.7 / inconsistent - 9.3%; stall slow 90.7 / failing 9.2%; request expected 70.9 / duplicate 16.9 / failing 10.0 / overload 1.4 / - stale 0.8%; transition expected 43.9 / failing 30.0 / transient 13.5 / unusual 6.1 / slow 6.1 / overload 0.3%; - error failing 94.8 / overload 4.1 / slow 0.7%. -- Per budget (state chars p50/max): 1000 -> 994/1069; 2000 -> 1854/2132; 3200 -> 2438/3387. Token estimate - (chars/3.6 of state+questions) p50 726, p99 1206, max 1262 (an estimate only: TRAIN measured ≈ 2.4 chars/token - with the runtime's pruned tokenizer, training/NEEDS.md 6a, so real counts are ≈ 1.5× higher). Rows per budget: 1000: 180,010; 2000: 180,232; - 3200: 240,434. -- Labelled points: 389,393 (all correlated), 29.9% after exploration; 3,464,871 decisions seen in base runs. - Points with 3 futures (adaptive): failure 43%, request 54%, stall 66%, mutation 19%, inconsistency 22%, - transition 26%, error 2%. Label sharpness (`label_sharpness`): passive-best rows with passive mass >= 0.9: - mutation 93%, request 68%, failure 87%, stall 71%; intervene-best rows with non-passive mass >= 0.95: mutation - 57%, request 32%, failure 60%, stall 52%, inconsistency 66%. -- Ask questions asked (phase A): `write_inflight` 33,851, `route` 33,826, `pending_count` 33,576, `any_inflight` - 33,559, `user_waiting` 32,773, `user_recent` 30,993, `recent_failure` 30,314, `fail_count` 27,996, `last_failed` - 22,409, `last_save` 4,271, `slowest` 1,835. -- `sample-stats.json` (`--sample`, seed 1000, 8 workers): 994 rows (train 630, test 364; no dev), 116 trajectories. +| `sim/test/loop.test.ts` | 3 tests | macrotask/microtask ordering, `Response` bodies within one macrotask, keyed rng forks | +| `sim/test/determinism.test.ts` | same seed -> identical rows | seeds 11-13: identical rows, 0 `prefix-mismatch`, identical states and `fp` lists | +| | replay reproduces every prefix | seeds 100-129: forcing each action at indices 0, mid, last reproduces all `fp <= k` | +| `sim/test/latent.test.ts` (new) | re-draws only what lies after the decision | `futureProfile`: windows over before *t* unchanged, running ones keep start and end after *t*, later ones move with same length, `noLatent` returns the profile; `futureStepTimes` keeps prefix times and order, differs per salt | +| | hidden intent of earlier repeats | `repeatPrior` thresholds; `idealRepeatSkips` skips an 80 ms accidental repeat before *t* in 60-90% of 400 salts, never touches steps after *t* | +| `sim/test/rows.test.ts` | valid CONTRACT-D rows | 40 trajectories: no base errors, no prefix mismatch, labels reference offered options, dists sum to 1, no `x-request-id`, passive best on > 20%; **S1**: no `expected` row with passive's adjusted gap >= 1 | +| | splits and transform | 400 seeds: > 40 test, > 150 train; transform keeps passive and best | +| `sim/test/oracle.test.ts` | stale overwrite | search without guard: a **`delivery`** decision, diagnosis `stale`, `discard` cheapest and label best (passive `deliver`) | +| | one stale response among later stale ones | `discard` cheaper than `deliver`; best in `discard`/`defer` | +| | intentional double add | counter: request `expected`, `send` cheapest | +| | duplicate POST after committed timeout | `duplicate`; `block`/`coalesce` beat `send` | +| | outage failure streak | poll during 503 outage: `failing`; `delay`/`serve_cached` beat `send` | +| | benign concurrency | cart server mode, two adds: no `delivery`/`mutation` question at all, or passive best with `expected` | +| | label sharpness / exact ties | `actionLabel` unit checks | +| | (real only) partial-update invariant break | `inconsistent`; `rollback`/`resync` beat `ignore` | +| | (real only) duplicate token refresh | `duplicate`; `coalesce` beats `send` | + +Helpers (`sim/test/helpers.ts`): `testFactory`, `mini(kind, patch, opts)` (one-feature calm scenario from seed 4242, +exact latencies via `latencyFn`), `step`, `runBoth`, `argmin`, `find`. + +### Data and sample stats + +- **Phase A** (`stats-final-a.json`; situation-v1, 15 features, 55 domains, seeds from 10,000,000): 600,676 rows + (train 448,420 / dev 14,613 / test 137,643), 937 families, 245.8 rows/s on 56 workers; trigger mix ask 23.8%, + mutation 23.3%, request 17.2%, failure 14.7%, stall 9.1%, inconsistency 5.5%, error 3.6%, transition 2.8%. Round 1 + (R17) trained on it. Per-trigger diagnoses, passive-best shares and budget lengths are in the file; they describe + v1 only. +- **Phase B** (training/NEEDS): 1,415,344 rows (train 1,056,383 / dev 35,269 / test 323,692), 2,454 parts, + `train:/data/sim-out/final-b/parts/`; same code/runtime as A. +- **gold-r1x** (v1 runtime, 115 domains + round-2 personas/regimes/clean runs, original 15 features): 832,279 rows, + `data:~/simdata/gold-r1x/`. +- **v2 checks**: `train:/data/sim-out/v2chk-{gold,unl}` (one F80: 41.7k gold rows in 211 s, 265k unlabeled in 24 s, + batch-4 runtime); `v2b5-100k` (batch-5 runtime, S1 + S2; SEPARABILITY §8). Probe rows `probe-150k` (v1, analysis + only). +- **`sample-stats.json`** (now regenerated: `--sample`, seed 1, 32 workers, mode gold, a runtime with `delivery`): + 1,325 rows (train 560 / dev 49 / test 716), 154 trajectories, 80 domains, 143 families, all 46 features present; + drops `info:latent-fallback` 68, `diagnosis-not-in-vocab` 18. `sample.jsonl` (200 rows) mixes request 41, + delivery 34, failure 28, transition 27, mutation 23, inconsistency 16, stall 14, error 12, ask 5; all `runtime: + "real"`. Exact runtime commit unverified. +- Throughput (README): gold ~4.4 rows/s per worker (~200-250 rows/s per F80), unlabeled ~150 rows/s per worker + (~11-13k rows/s per F80), on-policy ~0.1 rows/s per worker (WASM inference). ## Drift and open issues -- **README limitation 5 is stale.** It says `conflict` rows are under 1% of mutation rows because the runtime does - not flag a remote write over a pending local change (NEEDS f). The runtime now has the pending-local-change fact - (`packages/runtime/src/situation/facts.ts`; STATUS "SIM requests a-f: DONE") and phase A has `conflict` on 9.7% of - train mutation rows. -- **`sim/NEEDS.md` is stale.** Observations a-f are still listed as ASK (STATUS: all done in batch 3); the note that - `transient` is missing from the runtime's `DEFAULT_DIAGNOSES` is false (it is there, last), so the fallback in - `realRuntimeFactory` is inactive. Its header's `createRuntime` options (no `websocket`, thresholds 0) differ from - `createOptions` (websocket on, guard/heal 0.5, `model: false`, `historySize: 500`). -- **README "every [ask] generator checks that its evidence appears in the situation text"**: only `last_failed`, - `route` and `slowest` check the text; `recent_failure`, `fail_count`, `user_waiting`, `user_recent` skip - borderline timings; `write_inflight`, `any_inflight`, `pending_count` (skips > 6), `last_save` check nothing. -- **README "calm warm-up of 30-60%"**: only windowed chaos respects it (see gotchas). -- **README limitation 6** ("genuine relation breaks ... about 4% of mutation rows"): phase A has 8.4% of train - mutation rows labelled `inconsistent` (from `anomaly: "partial"` writes, not a relation check). -- **README cost formula omits the caps** in `serverDist` (5 extra/missing and 5 changed items per collection, 3 - fields per doc, 3 units per counter, `*beats` counters ignored). It also does not say that the latency term is - absolute (unlike the error and wasted-request terms, it is not relative to the ideal run). +- **No v2 data or model is final yet.** Phase A/B and gold-r1x are situation-v1 and do not match the runtime at + b435acb. The v2 runs (`train:/data/sim-out/v2-*`) are in progress on Azure (colleague-operated; [HANDOFF.md](../../HANDOFF.md), + training/NEEDS). On-policy (DAgger) rows need a v2 model export that does not exist yet. +- **`sim/NEEDS.md` is stale in several places.** Item g (NaN recursion in `describe()`) is marked OPEN but the runtime + now uses `Object.is(r, v)` (`packages/runtime/src/util.ts` -> `describe`); the "Batch 4 / situation-v2" needs and the + separability fact proposals (F1-F9) are marked OPEN/ASK but STATUS lists them DONE (batch 4 and batch 5); the old + a-f "ASK" items and the `transient`/`DEFAULT_DIAGNOSES` note are also done; its header's `createRuntime` options + differ from `createOptions`. +- **README drift.** "Every row also has `meta.passive`": ask rows have no `passive`. "Clean runs ... correct guards": + only round-2 features honour `clean`. Limitation 5 (few conflicts, NEEDS f) and limitation 6 percentages describe + v1. The flag list omits `--parts/--chunk/--merge-only`. "Every generator checks that its evidence appears in the + situation text" (only three do). The README's on-policy description is accurate but no v2 export exists. +- **`gen.ts` header comment** still shows `--test-keep 0.5`, "~12" examples and omits `--parts`, `--unlabeled`, + `--on-policy`. - **Code comments:** `rt.ts` header says the fake runtime lives in `test/fake-runtime.ts` (it is - `src/run/fake-runtime.ts`); `NetEntry.simOp` mentions an `x-sim-op` header (renamed to `x-request-id` after - `situation-v1`); `gen.ts` header shows `--test-keep 0.5` and "~12" examples (defaults 0.33 and up to 16) and omits - `--parts/--chunk/--merge-only`; the `diagnoseFailure` comment says a spike-caused timeout is `transient` (code: - any timeout outside a slow period/overload is `slow` once streak >= 2, else `transient`); `Persona.typoP` says - "per word" (code: `typoP/6` per non-space character). -- **Slug ids:** the `server.ts` comment in `Db.makeId` ("the runtime does not treat it as an id") and NEEDS - observation e predate batch 3; the runtime's `isSlugId` (`packages/runtime/src/util.ts`) now normalises slug ids - whose suffix starts with a digit or alternates letters/digits twice (STATUS "e"), so only part of the sim's - slug-id programs keep per-item signatures. -- **Poll `storm` anomaly never reaches the oracle (code bug).** `sim/src/app/features/poll.ts` passes - `anomaly: "storm"` to `kit.op` for tight retries, but `sim/src/app/kit.ts` -> `Kit.op` copies only the `OpInit` - fields, so `SimOp.anomaly` is never set. The README ("overload (storm code path, ...)"), the `diagnoseFailure` - comment and the three `anomaly === "storm"` checks in `diagnose.ts` assume it is. Fixing it changes diagnoses (and, - through exploration and point sampling, action rows) of tight-poll programs: regenerate data. -- **`RunOptions.explore` doc comment** in `runner.ts` ("Decisions >= this index take the passive action") describes - counterfactual futures, not the exploration policy it annotates. -- **README flag list** omits `--parts`, `--chunk`, `--merge-only` (only `final.sh b` mentions parts mode) and says - "about 5.7 rows per trajectory" (phase A: 5.77 rows per seed incl. test-subsampled seeds, 8.4 per simulated - trajectory). -- **CONTRACT §11** asks to randomise diagnosis paraphrases/subsets "per row"; the sim does it per trajectory - (scenario) through the runtime's `vocabulary`, and only option order/subset is per row (`transformQuestions`). -- **`docs/runtime/ARCHITECTURE.md`** lists "uploads" among the 15 combinators; there is no upload feature (`upload` - is only a latency kind no route uses). -- **CONTRACT §11** calls the ideal world "serial"; the sim's ideal run is zero-latency and failure-free, not - explicitly serialised. -- **training/NEEDS.md item 3** (marked DONE there) asks for `meta.passive`, `meta.program_family`, `meta.action_names`; the sim emits - `meta.family` (program family) and `meta.tiers`, no `passive` (derive from `PASSIVE`), no `action_names` (option - keys are never renamed). Item 4 (clean-run rows, `meta.clean`) is not implemented. -- **Budgets:** the runtime's auto budget also yields 1,333 / 1,667 (2-3 WASM threads); the sim samples only 1000 / - 2000 / 3200. -- **Sim changed after the freeze tag:** `git diff situation-v1 HEAD -- sim/src` shows the header rename, thresholds - 0 -> 0.5, budget 1100 -> 1000, parts mode. `packages/runtime/src` is unchanged since the tag (only the runtime's - README, package.json, LICENSE and a smoke test changed). `stats-final-a.json` `args` lack - the parts keys, so phase A ran on a `gen.js` before parts mode (exact commit unverified). -- **Dead code:** `u01`, `keyedLognormal` (`rng.ts`), `relationMatches` (`diagnose.ts`), `searchLabel`, `listKey`, - `sleepJitter`, `ROUTE_WORDS`, `Network.committedBefore`, `Knowledge.inflight`, `Knowledge.appliedReadStart`; - `Knowledge.localChange` and `errorList` are written but never read; `runCost` has a no-op ternary - (`real.tStop <= stop ? real.server : real.server`). -- **Label-quality limitations** (README "Known limitations", still accurate unless noted above): only K = 3 futures - (noisy SE; `meta.cost_futures` allows re-derivation); the failure-free ideal can be unreachable after a real - failure; diagnosis and action are labelled independently (e.g. `expected -> coalesce`, kept passive by the - runtime gate); `defer` is scored as defer-then-apply; thin classes (transitions about 3% of rows); token lengths - are estimates; ask labels are imbalanced (phase A: `q_user_waiting` 92% "no", `q_write_inflight` 71% "no"). -- **Open work (OPEN_TASKS.md):** phase B (1.4M rows) in progress, resumable; training round 2 uses phase A + B. + `src/run/fake-runtime.ts`); `NetEntry.simOp` mentions `x-sim-op` (now `x-request-id`); `diagnoseFailure`'s comment + says a spike-caused timeout is `transient` (code: `slow` once streak >= 2); `Persona.typoP` says "per word"; + `RunOptions.explore` comment describes counterfactual futures; `Db.makeId` slug comment predates the runtime's + `isSlugId`. +- **`DATA_ROLES` was not extended for round 2** (unchanged since 654d822). Most round-2 data writes reuse existing + roles (`results`, `echo`, `refetch`, `data`, `load`, `push`, `cache`, ...), but some data-carrying write roles are + not in the set: `list` (prefetch), `sorted` (longtask), `status` (payment, wsreconnect), `restored` (undo), + `synced` (offline), `flags` (flags), `step`/`finish` (saga). For those writes the "data of a superseded intent -> + stale" mutation rule never fires (impact on labels unverified; S1 can still relabel clear cases). Roles such as + `detail`, `products`, `refresh`, `reconcile` and `restore` are op roles (`kit.op`), which this rule does not read. +- **Mutation `defer` is a no-op** under the sim's options (no `holdWrites`); mutation rows can only distinguish + `apply` vs `discard` (late revert). Whether that is intended for training is undecided (unverified). +- **Discard reach on deliveries** (NEEDS, 03:20 UTC): before S2, 45 of 65 stale deliveries had `discard` within 0.5 + of `deliver`; CORE responded by narrowing delivery salience (STATUS batch 5) rather than widening discard. +- **CONTRACT §11** still says "≥ 40 domains", per-row paraphrase randomisation and a "serial" ideal world; the sim + randomises diagnosis/action wording per trajectory (`diagVocab`, `actionVocab`; only the action option shuffle/drop + is per row) and its ideal run is zero-latency and failure-free, not serialised. + **`docs/runtime/ARCHITECTURE.md`** still says 55 domains and 15 combinators (now 115 and 46; an `upload` feature now + exists). +- **Budgets:** since batch 4 the runtime's full budget is 2,400 characters (`STATE_CHAR_BUDGET` in + `packages/runtime/src/situation/serialize.ts`; auto budget: webgpu and unknown device 2,400, wasm 1,000-2,000 by + threads, i.e. also 1,333 / 1,667), and section limits stop growing at 2,400. The sim still samples 3,200 (40%), + 2,000 and 1,000 (`buildScenario`), and the `Scenario.budget` comment still says "3,200 WebGPU". So 40% of rows use + a budget the runtime never picks on its own (impact on training unverified). +- **Fake runtime lags v2:** no `delivery`, no storage observation; the delivery oracle tests need the real runtime. +- **Dead code:** `keyedLognormal`, `relationMatches`, `searchLabel`, `sleepJitter`, `ROUTE_WORDS`, + `Network.committedBefore`, `Knowledge.inflight()`, `Knowledge.appliedReadStart`; `localChange`/`errorList` + written but not read; the no-op ternary in `runCost`; `latentFallbacks` (module counter, never reported). (`u01` + is now used by round-2 servers; the poll `storm` anomaly bug is fixed: `Kit.op` copies `anomaly`.) +- **Label-quality limitations** (README "Known limitations"): K <= 3 futures (`meta.cost_futures` allows + re-derivation with `relabel.py`); the failure-free ideal can be unreachable after a real failure; `defer` scored as + defer-then-apply; thin classes; token lengths are estimates; ask labels imbalanced. SEPARABILITY §8: after S1/S2 and + batch 5, look-alike rates dropped and failure/request/inconsistency recall at 1% FIR rose on 100k v2 rows, but + mutation, stall and transition had too few clear test rows to judge. +- **Open proposals not implemented in the sim:** S3 (split the area term into immediate vs later divergence) and the + S2 "alternative next actions" part (only timing is re-drawn; order and content are kept). T1 (expected-advantage + target) is TRAIN's. ## Related docs - [model-io-contract.md](model-io-contract.md): row -> packed request -> heads -> calibrated answers. -- [training.md](training.md): how rows are imported (`training/import_final.sh`), trained on and evaluated. +- [training.md](training.md): how rows are imported, trained on (teacher, distillation, DAgger) and evaluated. +- [realapps.md](realapps.md): the real-browser corpus (REAL), same CONTRACT-D label semantics as the sim. - [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): the facts, triage and serializer that - produce every `state` the sim records. -- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): the gate the forced actions pass through. -- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): ops, `opCreated`, causality used for correlation. -- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `createRuntime` options. -- [runtime/build-test-release.md](runtime/build-test-release.md): VM workflow, how `sim` consumes the runtime build. + produce every `state` the sim records (situation-v2, batch 5 facts). +- [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): the gate, `delivery` holds and actions. +- [runtime/observe-and-trace.md](runtime/observe-and-trace.md): ops, `opCreated`, WebSocket message ops, causality. +- [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md): `createRuntime` options and default mode. +- [runtime/build-test-release.md](runtime/build-test-release.md): where to run things, how `sim` consumes the build. - [demos.md](demos.md): the independent external test (never modelled by the sim). - [status-and-known-issues.md](status-and-known-issues.md), [glossary.md](glossary.md), [repo-map.md](repo-map.md). - Source docs: [../../sim/README.md](../../sim/README.md), [../../sim/NEEDS.md](../../sim/NEEDS.md), - [../runtime/CONTRACT.md](../runtime/CONTRACT.md) §11 and §13. + [../../sim/SEPARABILITY.md](../../sim/SEPARABILITY.md), [../runtime/CONTRACT.md](../runtime/CONTRACT.md) §11 and §13, + [../../packages/runtime/STATUS.md](../../packages/runtime/STATUS.md) (batch 4/5, SIM requests), [../../HANDOFF.md](../../HANDOFF.md), + [../runtime/RESULTS.md](../runtime/RESULTS.md) (§3 format v1 vs v2, §6 data volume). diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index d1378a67..cb44efbd 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -1,642 +1,665 @@ # Project status, ground rules, open work, known issues and doc drift -> **Scope:** `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `demos/NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, -> `packages/runtime/UI-NEEDS.md`, `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md`, `README.md`, -> `packages/runtime/README.md`, git history and tags, code TODO markers. Cross-checked against -> `packages/runtime/src/**`, `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime/package.json`, -> `training/{LOG,EVAL}.md`, `sim/README.md`, `sim/samples/stats-final-a.json`, `demos/results.md`. -> **Read this when:** you land in the repo cold and need to know what is shipped, what is in flight and who owns it; -> before any change that could break a binding rule (situation text, determinism, dependencies, where to run builds); -> before trusting `docs/runtime/*.md` or a README over the code; when you finish work and must update STATUS/NEEDS/OPEN_TASKS. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `HANDOFF.md`, `OPEN_TASKS.md`, `docs/runtime/RESULTS.md`, `packages/runtime/STATUS.md`, `demos/NEEDS.md`, +> `sim/NEEDS.md`, `training/NEEDS.md`, `training/PLAN-v1.md`, `training/LOG.md`, `packages/runtime/UI-NEEDS.md`, +> `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md`, `README.md`, `packages/runtime/README.md`, `realapps/README.md`, +> `.github/workflows/ci.yml`, git history and tags, code TODO markers, and the 2026-10-08 review of the situation-v2 +> work. Cross-checked against `packages/runtime/src/**`, `packages/runtime/bin/genclass-runtime.mjs`, +> `packages/runtime/package.json`, `sim/src/**`, `realapps/**` and `training/**`. +> **Read this when:** you land in the repo cold and need to know what is shipped, what runs on Azure right now, what +> comes next and who owns it; before any change that could break a binding rule (situation text, determinism, +> dependencies, where to run things); before trusting a human doc over the code; when you pick up one of the review +> findings; when you finish work and must update STATUS/NEEDS/OPEN_TASKS/HANDOFF. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR Path convention in this doc: `src/…`, `test/…` and `bin/…` are relative to `packages/runtime/`; bare runtime module -paths (`runtime.ts`, `types.ts`, `util.ts`, `index.ts`, `state/hub.ts`, `situation/build.ts`, `decide/policy.ts`, +paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.ts`, `decide/policy.ts`, `model/host.ts`, …) are relative to `packages/runtime/src/`. Every other path is from the repo root. -- **Shipped:** `@genclass/runtime@0.1.0-alpha.0` on npm (per `OPEN_TASKS.md`; registry not re-checked). Runtime core, - model host, devtools and adapters are built and tested (STATUS: 37 files, 300 tests passing on the VM). Re-run - on 2026-10-07 without a model directory: typecheck clean, `tsup` build OK, 286 tests passed and the 14 - model-file tests skipped (see [Gotchas](#gotchas)). -- **Not shipped:** the trained runtime model. `DEFAULT_MODEL_BASE_URL` (`src/model/host.ts`) points at - `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, a package that does not exist yet - (`packages/runtime-model/` holds only `MODEL_CARD.md`). A default `GenClass.init()` therefore ends with model status - `error`, prints `[GenClass] Model unavailable (...); observing only.`, and from then on never consults the model or - takes an action (only while the status is still `off`, before the idle preload starts, are salient situations built, - and those fail open). It still traces, learns baselines/invariants/profiles and answers `rt.situation()`. No runtime - test covers this default path. -- **Frozen:** the situation format is frozen at tag `situation-v1` (commit 1a77558). `git diff situation-v1 HEAD -- - packages/runtime/src` is empty at 654d822. The final training data (SIM phase A, 600k rows) was generated from it. - Any change to text the model reads breaks parity with that data. Only the runtime source is frozen: sim, training - and demos changed after the tag (59c213f, 654d822). -- **In flight at 654d822:** SIM phase B data (1.4M rows), TRAIN final round 1 (R17 and R32 on phase A), DEMOS screenshot - tour. **Next:** choose R17 and/or R32, publish `@genclass/runtime-model@0.1.0` and a GitHub release, then - `@genclass/runtime@0.1.0`, add CI, then re-run the demos with the trained model. -- **Binding rules** (CONTRACT §0, §0.5): no hardcoded bug rules (facts and triage only; the model decides), one - situation implementation shared with the sim, determinism via the injected `Clock`, sim and demos never read each - other, builds/tests/models run only on the `train` VM (the 2026-10-07 run policy in AGENTS.md relaxes this for - light checks on other machines; see [ground rule 5](#ground-rules-binding-contract-0-and-05-restated) (Mac safety, - CONTRACT §0 rule 5; current policy in [../../AGENTS.md](../../AGENTS.md) §4)), no new runtime dependency besides - `onnxruntime-web`, precision first. -- **Workstreams:** lead, CORE, MODEL, UI, SIM, DEMOS, TRAIN, REVIEW. They talk through `STATUS.md` (CORE's state) and - per-workstream `NEEDS.md` files (requests with OPEN / ASK / DONE status; sim/NEEDS and training/NEEDS say they are - "relayed by the lead"). -- **Biggest open product risks:** holding writes can reorder them behind a newer user write (board demo: +56% visible - jump-backs with zero actions, `demos/NEEDS.md` §1); holds add latency to typeahead-like apps (§2); `retry` is offered - for non-idempotent POSTs (§5). All three are open in code. -- **Docs drift a lot.** CONTRACT.md was last edited in a53dd38, before batch 3 landed (it already specifies the - summed-mass §8 gate and `transient`, but none of STATUS's deviations); READMEs, STATUS, UI-NEEDS and sim/NEEDS each - have stale items. The full list with evidence is in [Drift and open issues](#drift-and-open-issues). There are - **no** TODO/FIXME/XXX/HACK comments in code. +- **Branches.** `mvp-v2` (this doc) = `origin/runtime` 74f17c0 (the colleague Mehar's latest: runtime batches 4 and + 5, situation-v2, `realapps/`, v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus three local + commits: 7dab2b3 (AGENTS.md, CLAUDE.md, `docs/agents/**`), f3636b2 (default mode `observe`), b435acb (CI workflow, + committed root `package-lock.json`, `bin/genclass-runtime.mjs` as 100755). `mvp-v2` is **not pushed** + (`git branch -vv`: "ahead 3" of `origin/runtime`). The local branch `mvp` (b15415b, based on 654d822 = + situation-v1) is superseded. `main` and `origin/main` are still 654d822. +- **Shipped on npm:** `@genclass/runtime@0.1.0-alpha.0` (`latest`, git tag `v0.1.0-alpha.0` = 654d822). It predates + situation-v2, defaults to `guard`, has no model, and predates the NaN fix (ad24804: `util.ts` -> `describe` + recursed forever on a `NaN` store value). A `0.1.0-alpha.1` patch waits on the owner's 2FA (`OPEN_TASKS.md` + "Needs the user"). `@genclass/runtime-model` is **not published** (404). +- **Runtime on `mvp-v2`:** situation-v2, decisions at the network boundary (`delivery` trigger, + `RuntimeImpl.runDelivery`), no store-write holds by default (`policy.holdWrites` false), default mode `observe` + (`runtime.ts` -> `o.mode ?? "observe"`). Verified when these docs were written, on 2026-10-08 (macOS, Node v25.6.0): `tsc` clean, + `tsup` OK, unit tests 40 files passed + 1 skipped (41), 332 tests passed + 14 skipped, plus `review-perf` alone + 4 passed: **350 tests, 14 model-parity skips**. CI (`.github/workflows/ci.yml`) exists but has never run on + GitHub (branch not pushed). +- **Frozen:** the model's input format is frozen at tag **`situation-v2`** (annotated tag → commit 6e5e86e, + "Frozen runtime situation format v2"). `git diff situation-v2 b435acb -- packages/runtime/src` touches only + `runtime.ts`, `types.ts` and `devtools/index.ts` (f3636b2's default-mode change); `situation/` is identical. + `situation-v1` (1a77558) is superseded: R17-final1 and every other checkpoint trained so far do **not** match this + runtime. +- **Running on Azure now** (lead's read-only portal look, 04:14 UTC 2026-10-08, resource group `rg-jev-train`): + `vm-jev-c01`…`c23` (F80) and `vm-jev-train` running, `vm-jev-data` deallocated. Per `training/NEEDS.md`, SIM is + generating situation-v2 data on 20 nodes (c02–c09, c12–c23: ≥ 10M gold + ≥ 50M unlabeled into + `train:/data/sim-out/v2-*`) and REAL real-browser gold rows on c01, c10, c11 (≥ 500k target; batches + `v2b1`/`v2b2`/`v2b3`). Mehar operates the cluster. **Nobody on our side touches Azure.** +- **No situation-v2 model exists.** Next (HANDOFF "Current state"): 150M teacher (T150) on v2 gold → teacher labels + on unlabeled rows → distil R17 (default) and R32 → DAgger via SIM `--on-policy` → EVAL → + `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0` (owner's 2FA). +- **Default install today:** `GenClass.init()` starts in `observe`, tries the unpublished model URL, ends in model + status `error` and logs `[GenClass] Model unavailable (<error>); observing only.` From then on it traces and learns + but never builds a situation or decides. No test covers this path. +- **Binding rules** (CONTRACT §0, §0.5, §13): no hardcoded bug rules; one situation implementation (frozen at + situation-v2); determinism through the injected `Clock`; sim/realapps never read demos; one runtime dependency; + precision first, default `observe`. Our run policy replaces CONTRACT §0 rule 5 for this machine (light checks + local; ask before anything heavier, Azure, `git push`, `npm publish`). +- **Coordination files:** `HANDOFF.md` (start here for Mehar's sessions), `OPEN_TASKS.md`, `docs/runtime/RESULTS.md` + (results and comparisons; "update it with every result"), `packages/runtime/STATUS.md` (CORE), per-workstream + `NEEDS.md` (`training/NEEDS.md` also holds Azure node claims and data locations). +- **Review of the situation-v2 work (2026-10-08): 52 confirmed findings, none left uncertain.** The worst: the F2 + fact prints raw text of redacted fields (`situation/content.ts` -> `contentFacts`); a delivery `discard` is a + silent no-op on redux/zustand stores (`state/hub.ts` -> `StoreHub.applyFilter`); unlabeled SIM rows hard-label + `expected` diagnoses that S1 would relabel; SIM still samples the v1 3,200-char budget for 40% of trajectories + while v2 data is generated. Several touch model-visible text or the live data run: coordinate with the user (and + through them Mehar) before fixing. Full list: [Review of the situation-v2 work](#review-of-the-situation-v2-work-2026-10-08). +- **Docs drift.** `HANDOFF.md` still says `guard` is the default (both READMEs and `OPEN_TASKS.md` are fixed in the + working tree, pending commit); `CONTRACT.md` has no `delivery` trigger + and its §13 default-mode entry still says situation-v1 data "stays valid"; `docs/runtime/ARCHITECTURE.md` + still says 3,200 chars. Tables in [Doc drift](#doc-drift-project-and-coordination-files). No TODO/FIXME/XXX/HACK + markers in code. ## Files | path | role | key content | |---|---|---| -| `OPEN_TASKS.md` | Project-level status (owner inferred: lead) | Done / In progress (1–2) / Next (3–8) / Needs the user / Known risks | -| `packages/runtime/STATUS.md` | CORE's status, read by SIM, DEMOS, UI, MODEL | test state, batch 3 changes, headless recipe, trigger table, example situations, **Deviations from the contract**, **Open issues** | -| `docs/runtime/CONTRACT.md` | Binding build contract (lead) | §0 ground rules, §0.5 product principles, §1 layout and owners, §2–§12 spec, §13 approved additions | -| `docs/runtime/API.md` | Public API reference | options, state, ops, ask, events, triggers/actions, policy, reports, plugins, headless, types | -| `docs/runtime/ARCHITECTURE.md` | Design overview | principles, data flow, training and evaluation summary | -| `packages/runtime/UI-NEEDS.md` | UI → CORE requests | Open (1–2), Nice to have (3), Done | -| `sim/NEEDS.md` | SIM → CORE requests and observations | Requests 1–5 (DONE), observations a–f (marked ASK), SIM notes | -| `training/NEEDS.md` | TRAIN's needs from SIM, CORE, MODEL; MODEL → TRAIN notes | items 1–10, 6a; TRAIN status for frozen data | -| `demos/NEEDS.md` | DEMOS → CORE/MODEL/UI/lead | §1–§8 evidence-backed product issues from traced Playwright runs | -| `README.md` | Repo landing page | install, status banner, repo map, how it works | -| `packages/runtime/README.md` | npm package README | status banner, modes, adapters, privacy, limits | -| `packages/runtime-model/MODEL_CARD.md` | Model card for the unpublished `@genclass/runtime-model` (lead) | R17/R32 sizes, stage-1c accuracy, limits | -| `training/LOG.md`, `training/EVAL.md` | TRAIN's dated log and results | stage 1c, stage-2 pilot, final round 1 launch (EVAL final section "(in progress)") | -| `demos/results.md`, `demos/results.json`, `demos/results-summary.json` | Demo trial results with the **v0.1** model (generated 2026-10-07T19:30Z) | bug rate, false interventions, latency per demo and mode | -| `training/README.md`, `sim/README.md`, `demos/README.md`, `src/model/README.md` | Per-workstream READMEs | owner lines ("Owner: TRAIN", "Owner: MODEL"), sim "Known limitations" 1–8, demos "Honesty rules", MODEL measurements | -| `sim/samples/stats-final-a.json` | Stats of SIM final phase A | rows per split/trigger, diagnosis counts, passive-best fractions | -| `scripts/vm.sh` | The team's way to build/test per CONTRACT §0 rule 5 (`sync`, `run`, `exec`, `get` per SLOT); light checks may run locally under the run policy in AGENTS.md ([ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)) | needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure` (not in repo) | +| `HANDOFF.md` | Mehar's hand-off for continuing Claude sessions (updated 2026-10-08) | current state table (npm, git, runtime, model, data, training), repo map, hard-won rules (8 GB Mac, Azure, zsh, freeze, licensing, commits), "How to continue" | +| `OPEN_TASKS.md` | Project status (owner inferred: lead) | Done / In progress / Next (stale, see Drift) / Model quality / Needs the user / Known risks | +| `docs/runtime/RESULTS.md` | Results, comparisons and training log (Mehar, 2026-10-08) | §1 model stages, §2 R17 vs R32, §3 v1 vs v2 separability, §4 never-worse sweep, §5 demos (v0.1 baseline), §6 data volume, §7 training log; FIR next to every recall number | +| `packages/runtime/STATUS.md` | CORE's status (batch 5, 2026-10-08) | State (VM test counts, perf, never-worse sweep), batch 5 and batch 4 changes with "Contract deltas", batch 3, headless recipe, trigger table, example situations, **Deviations**, **Open issues** | +| `docs/runtime/CONTRACT.md` | Binding build contract (lead) | §0 ground rules, §0.5 product principles, §1 layout, §2–§12 spec, §13 approved additions (now incl. default `observe`) | +| `docs/runtime/API.md` | Public API reference | updated for v2 (delivery, `holdWrites`, `untrustedEvents`, 2,400 budget) and for the observe default | +| `docs/runtime/ARCHITECTURE.md` | Design overview | principles (now observe default), data flow, training summary | +| `training/NEEDS.md` | TRAIN's needs; MODEL → TRAIN notes; **Azure node claims; SIM/REAL data locations** | items 1–16, cluster-expansion claim table, SIM → TRAIN scaled data, REAL → TRAIN (13–16) | +| `training/PLAN-v1.md` | Scaled training plan (teacher → students → DAgger) | targets, data inventory, models (R17/R32/R68/T150/T400), phases P0–P5, eval, infra, risks | +| `training/LOG.md`, `training/EVAL.md` | TRAIN's dated log and results | final round 1 (situation-v1) results, T1 runs stopped at the v2 freeze, spend | +| `sim/NEEDS.md` | SIM → CORE requests | requests 1–5 DONE, g (NaN crash, still marked OPEN), observations, batch-4 needs, v2 fact proposals, batch-4 integration notes | +| `sim/SEPARABILITY.md` | Why round 1 was timid; the F-facts and S1/S2 label fixes | evidence behind situation-v2 | +| `demos/NEEDS.md` | DEMOS → CORE/MODEL/UI/lead | §1–§8, written against batch 3 (stale for v2, see Drift) | +| `packages/runtime/UI-NEEDS.md` | UI → CORE requests | Open 1–2 and Nice-to-have 3 (stale, see Drift) | +| `realapps/README.md`, `realapps/EXAMPLES.md` | REAL's corpus, harness and audit | see [realapps.md](realapps.md) | +| `README.md`, `packages/runtime/README.md` | Repo landing page; npm README | say `observe` is the default (working tree, pending commit) | +| `packages/runtime-model/MODEL_CARD.md` | Model card for the unpublished `@genclass/runtime-model` | status "final round 1 on the frozen runtime (situation-v1)"; the only tracked file in `packages/runtime-model/` | +| `.github/workflows/ci.yml` | CI (b435acb) | Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci`, typecheck and build of `@genclass/runtime`, unit tests without `test/browser/**` and `review-perf`, then `review-perf` with `--retry=2` | +| `package-lock.json` (root) | committed in b435acb | CI runs `npm ci` from it; keep it in sync | +| `AGENTS.md`, `CLAUDE.md`, `docs/agents/**` | Agent docs (7dab2b3, refreshed for v2) | run policy, commands, ground rules, subsystem docs | +| `scripts/vm.sh` | Mehar's way to build/test on the `train` VM (`sync`, `run`, `exec`, `get` per SLOT) | needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure` (not in repo); we do not use it without asking | | `packages/runtime/test/review-*.test.ts` | REVIEW's regression tests (10 files) | must pass unchanged | -| `packages/runtime/test/smoke/smoke.sh` | npm tarball smoke test (Vite app, headless Chromium) | runs with `model: false` | +| `packages/runtime/test/smoke/smoke.sh` | npm tarball smoke test (Vite app, headless Chromium) | runs with `model: false`; ask before running | | `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/SPEC.md`, … | **Legacy jev-local docs**, not the runtime contract | CONTRACT §1: "stays as is. Do not edit it." | +[RELEASE.md](../../RELEASE.md) at the repo root (untracked in the working tree, not in b435acb) is the release +procedure: Part A for `0.1.0-alpha.1`, Part B for the model and `0.1.0`. `extension/RELEASE.md` is the legacy +Chrome-extension release note. + ## Concepts and data structures -### Workstreams and ownership +### People, workstreams and ownership + +Every commit up to 74f17c0 is by Mehar Khanna (messages prefixed "Mehar commit: …"); he ran the original +multi-agent team (lead, CORE, MODEL, UI, SIM, REAL, DEMOS, TRAIN, REVIEW) and operates the Azure cluster and the npm +org (`genclass`, owner meharpro). 7dab2b3, f3636b2 and b435acb are by Karan (this repo's user). The roles below belong +to the original team: where a doc says "ask the lead", **ask the user**. | workstream | owns (edit rights) | writes | reads / serves | |---|---|---|---| -| **lead** (also "LEAD", "coordinator") | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`; `training/` per CONTRACT §1; `OPEN_TASKS.md` (inferred: the file has no owner line) | contract changes (§13 "Additions (approved …)"), approvals of deviations and dependencies, merges, publishing | relays sim/NEEDS and training/NEEDS (titles say "relayed by the lead"); reads demos/NEEDS ("Read by CORE, MODEL, UI and the lead"); answers UI-NEEDS 2 | -| **CORE** | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; owns `src/situation/*` wording and `src/types.ts` | `packages/runtime/STATUS.md`, `docs/runtime/API.md` (inferred: CONTRACT §1 names no owner for API.md; it was last changed in CORE's batch 3) | sim/NEEDS, UI-NEEDS, demos/NEEDS, training/NEEDS (CORE → TRAIN) | -| **MODEL** | `packages/runtime/src/model/**`, `bin/genclass-runtime.mjs`; co-owns the "model seam" section at the top of `src/types.ts` | `src/model/README.md`; MODEL → TRAIN entries in training/NEEDS | training/NEEDS (MODEL items) | -| **UI** | `src/devtools/**`, `src/adapters/**` (CONTRACT §13; §1's table still says CORE) | `packages/runtime/UI-NEEDS.md` | STATUS "For UI" | -| **SIM** | `sim/` | `sim/NEEDS.md`, `sim/README.md`, data under `sim/out/` (gitignored) | STATUS, training/NEEDS (SIM → TRAIN) | -| **DEMOS** | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*.{md,json}` | STATUS | -| **TRAIN** | `training/` (`training/README.md`: "Owner: TRAIN") | `training/NEEDS.md`, `LOG.md`, `EVAL.md` | sim output, MODEL card format | -| **REVIEW** | `packages/runtime/test/review-*.test.ts` | 34 findings (all fixed in batch 3) | runtime code | - -Separation rule (CONTRACT §0 rule 4): SIM and DEMOS are built by different people who do not read each other's code. +| **lead** | `docs/runtime/CONTRACT.md`, `packages/runtime-model/`, `OPEN_TASKS.md`, `HANDOFF.md`, `docs/runtime/RESULTS.md` (inferred: Mehar's commits, no owner lines) | contract changes (§13), approvals, node-claim arbitration, merges, publishing | relays sim/NEEDS and training/NEEDS | +| **CORE** | `packages/runtime/**` except `src/model/**`, `src/devtools/**`, `src/adapters/**`; owns `src/situation/*` wording and `src/types.ts` | `packages/runtime/STATUS.md`, `docs/runtime/API.md` (inferred) | sim/NEEDS, UI-NEEDS, demos/NEEDS, training/NEEDS | +| **MODEL** | `src/model/**`, `bin/genclass-runtime.mjs` | `src/model/README.md`, MODEL → TRAIN notes | training/NEEDS | +| **UI** | `src/devtools/**`, `src/adapters/**` (CONTRACT §13) | `packages/runtime/UI-NEEDS.md` | STATUS "For UI" | +| **SIM** | `sim/` | `sim/NEEDS.md`, `sim/README.md`, `sim/SEPARABILITY.md`, data under `train:/data/sim-out/` | STATUS, training/NEEDS | +| **REAL** (new since 654d822) | `realapps/` | `realapps/README.md`, `realapps/EXAMPLES.md`, training/NEEDS items 13–16, data under `~/gcl/real-out/` on the generating VM, then `train:/data/real-out/` | STATUS ("REAL reads this file"); imports the sim's cost weights and label rule from `sim/src` | +| **DEMOS** | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*` | STATUS | +| **TRAIN** | `training/` | `training/NEEDS.md`, `LOG.md`, `EVAL.md`, `PLAN-v1.md` | SIM/REAL output | +| **REVIEW** | `packages/runtime/test/review-*.test.ts` | regression tests | runtime code | + +Separation rule (CONTRACT §0 rule 4): SIM and DEMOS do not read each other's code. REAL also never reads demos (it +imports from `sim/src`, which is allowed). ### Communication file conventions -- **`STATUS.md` (CORE).** Header `Updated: <date> (<batch>). Owner: CORE. SIM, DEMOS, UI and MODEL read this file.` - Sections: State (VM test command and counts), the latest batch's changes grouped by origin (REVIEW findings, SIM - requests, contract changes), "How to drive it headless", per-consumer notes ("For UI"), trigger/triage table, - example situations copied from tests, **Deviations from the contract (and why)**, **Open issues**. -- **`NEEDS.md` files.** Live in the *requester's* directory (exception: `UI-NEEDS.md` lives in `packages/runtime/`; - training/NEEDS also carries MODEL's answers and notes to TRAIN, "MODEL → TRAIN (from MODEL)"). - Title states direction ("SIM → CORE requests", "What the demos need from @genclass/runtime", "TRAIN needs"). Status - legend (sim, training): **OPEN** (needed), **ASK** (would help), **DONE** (landed; verified by the requester), plus - **INFO** in training/NEEDS. UI-NEEDS uses sections Open / Nice to have / Done. demos/NEEDS uses numbered sections with - the addressee in parentheses ("(CORE, product risk)") and evidence (traces, seeds, tables). -- **Contract changes.** A workstream that needs the contract changed tells the lead ("do not silently diverge"). Approved - additions are appended to CONTRACT §13; accepted divergences are listed in STATUS "Deviations". §13 ("Additions - (approved 2026-10-07)") holds seven items: `EvaluateRequest.subject` (exposed as `Decision.subjectRef`), - `createRuntime({ hooks })`, `policy.requireDiagnosis`, `vocabulary`, side-effect-free `situation(trigger)` (since - softened by a STATUS deviation), the pruned 16,364-token vocabulary with marker ids read from files, and UI ownership - of `src/devtools/**` and `src/adapters/**`. -- **Batches.** CORE ships in numbered batches: batch 1 (SIM requests 1–5), batch 2 ("model integration, latency, UI - requests" per the a53dd38 STATUS: `situation: { budget }`, `sectionLimits`, auto hold budget, late revert, provider - errors fail open; 239 tests), batch 3 (REVIEW's 34 findings, SIM a–f, summed-mass §8 gate, `transient`, compact - questions) = commit 1a77558. -- **VM slots.** Each workstream builds in its own directory on the `train` VM: `scripts/vm.sh run <SLOT> '<cmd>'` with - SLOT such as `core`, `model`, `sim`, `demos` (`~/gcl/<SLOT>`; slot names `[a-zA-Z0-9_-]` only). `run`/`exec` - commands are wrapped in `timeout $TIMEOUT` (default 1800 s); the sync and `get` steps use fixed 300/600 s timeouts. - `sync`/`run` use `rsync -az --delete` (excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, - `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out/`, `.cache-model/`), - so files created in a slot outside those paths are deleted by the next sync. Use - `scripts/vm.sh get <SLOT> <remote> <local>` to bring results back. - -### Git history (all 13 commits; author Mehar Khanna, every message prefixed "Mehar commit: …") - -| commit | date (−04:00) | what | relevance now | -|---|---|---|---| -| 7a7ff6d, 72ec517 | 2026-10-04 01:58–02:00 | README, Apache-2.0 licence, GenClass vs Jev benchmarks | legacy | -| 3b2121f | 2026-10-04 02:07 | Open-source GenClass: `jev_local/`, server, voice harness, training, benchmarks, `docs/*.md` | legacy content; CONTRACT §1 says do not edit | -| c2ddfa5, 666080e, 58d0f66 | 2026-10-04 09:44–10:59 | Chrome extension v0.1.0 and two store-listing fixes | legacy; holds the v0.1 model card (`extension/src/model/model.json`) | -| 353b0a4 | 2026-10-07 14:18 | WIP runtime core, model host, sim, demos, training scaffolding | first runtime commit; CONTRACT.md created | -| a53dd38 | 2026-10-07 19:02 | Runtime core, model host, devtools, adapters, sim, training, demos (WIP) + `OPEN_TASKS.md` | **last change to CONTRACT.md, UI-NEEDS.md, sim/NEEDS.md** | -| c14151c | 2026-10-07 19:05 | Runtime-first README, package README, ARCHITECTURE.md | only commit touching ARCHITECTURE.md; message understates scope: also changes `packages/runtime/src` (`decide/policy.ts`, `decide/decider.ts`, `situation/{facts,build,questions,env}.ts`, …) and adds `docs/GENCLASS.md` | -| 1a77558 | 2026-10-07 19:19 | Runtime fix batch 3 (34 REVIEW findings, summed-mass gate, `transient`, compact questions) | tag `situation-v1`; last change to STATUS.md, API.md, training/NEEDS.md, `packages/runtime-model/MODEL_CARD.md` and to `packages/runtime/src` | -| 501cec7 | 2026-10-07 19:20 | OPEN_TASKS: runtime frozen, final data and training plan | | -| 59c213f | 2026-10-07 20:09 | Runtime LICENSE, tarball smoke test; also sim (gate thresholds 0.5, 1,000-char WASM budget, op header `x-request-id`, resumable parts, `stats-final-a.json`), training final-round scripts, demos tracing (`demos/e2e/trace-report.ts`, common random numbers) | message understates scope: 59 files | -| 654d822 | 2026-10-07 20:15 | Publish `0.1.0-alpha.0`; READMEs, OPEN_TASKS, demos/NEEDS rewritten (also `training/LOG.md`, two demos files) | HEAD; tag `v0.1.0-alpha.0` | - -The freeze covers `packages/runtime/src` only: `git diff --stat situation-v1 HEAD` lists 65 changed files (demos 27, -training 16, sim 15, `packages/runtime/{LICENSE,README.md,package.json,test/smoke/smoke.sh}`, root `README.md`, -`OPEN_TASKS.md`, `.gitignore`; nothing under `docs/`). The sim changes in 59c213f are, by inference, the code that -produced phase A (`stats-final-a.json` lands in the same commit and its `by_budget` has 1000-char rows). +- **`HANDOFF.md`** is the entry point for a new Mehar-side session: read it, then `OPEN_TASKS.md`, `training/LOG.md` + (tail) and `training/NEEDS.md`; check running VMs; pick the next unfinished item. Its rules (8 GB Mac, `az` calls one + at a time in `timeout`, push to `origin runtime` as you go) describe Mehar's setup, not ours. +- **`docs/runtime/RESULTS.md`**: every result goes here, with the false-intervention rate (FIR) next to every recall + or fix-rate number (HANDOFF "How to continue" step 4). +- **`STATUS.md` (CORE).** Header `Updated: <date> (<batch>). Owner: CORE. SIM, DEMOS, UI, REAL and MODEL read this + file.` Sections per batch, each with a **"Contract deltas"** list; then "Deviations from the contract (and why)" and + "Open issues". Since batch 4 the contract changes live there, not in CONTRACT.md (see Drift). +- **`NEEDS.md` files** live in the requester's directory (exception: `UI-NEEDS.md` in `packages/runtime/`). Status + legend OPEN / ASK / DONE (+ INFO in training/NEEDS). `training/NEEDS.md` additionally holds **node-claim tables** + ("Claim nodes in `training/NEEDS.md`. Never delete VMs.", HANDOFF) and **data locations** per batch. +- **Contract changes.** Approved additions go to CONTRACT §13; accepted divergences to STATUS "Deviations"; batch + contract deltas to STATUS. "Do not silently diverge." +- **Batches.** CORE ships numbered batches: 1 (SIM requests 1–5), 2 (model integration, latency, UI requests), 3 (34 + REVIEW findings, summed gate, `transient`; tag `situation-v1`), 4 (fcd1e68: `delivery` trigger, no store-write + holds, `eventsource`, `untrustedEvents`, budget 2,400), 5 (6e5e86e: REAL's text fixes, SIM's separability facts + F1–F9, leaf redaction; tag `situation-v2`). +- **Freeze tags.** A change to model-visible text gets a new `situation-vN` tag and regenerated data. Rows carry + `meta.runtime` (SIM and REAL) so batches can be filtered by format. +- **VM slots** (Mehar): `scripts/vm.sh run <SLOT> '<cmd>'` builds in `~/gcl/<SLOT>` on the `train` VM with + `rsync -az --delete`; outputs never live under a slot (they go to `/data`). `sim/NEEDS.md` notes that the sync's + `--exclude '/sim/out/'` deletes the `sim/out` symlink on every sync. + +### Git history since 654d822 + +| commit | author, time (−04:00) | what | +|---|---|---| +| ad24804 | Mehar, 10-07 21:16 | Fix infinite recursion on a `NaN` store value (`util.ts` -> `describe` uses `Object.is`; `test/nan.test.ts`) | +| ce27efd | Mehar, 21:16 | OPEN_TASKS: alpha.1 patch release for the NaN fix | +| 04a264f | Mehar, 21:27 | Demos: frozen-runtime results, hold-reordering investigation, tracing tools | +| fcd1e68 | Mehar, 22:31 | **Runtime batch 4**: decide at the network boundary, never reorder app writes | +| 82db331 | Mehar, 22:39 | OPEN_TASKS: round-1 results and separability findings | +| fcb8189 | Mehar, 22:50 | `realapps/`: real-browser corpus (66 apps, 23 stacks) and deterministic harness | +| 6e5e86e | Mehar, 23:26 | **Runtime batch 5**; tag `situation-v2` | +| bac4409 | Mehar, 23:27 | STATUS: batch 5 perf numbers and never-worse sweep | +| 7dab2b3 | Karan, 23:27 | AGENTS.md, CLAUDE.md, `docs/agents/**` (written against 654d822) | +| f3636b2 | Karan, 23:30 | Default mode `observe`; guard opt-in, heal experimental | +| d73d20c | Mehar, 10-08 00:07 | HANDOFF.md; v2 curriculum port; realapps (+24 apps) and training updates | +| 74f17c0 | Mehar, 00:09 | `docs/runtime/RESULTS.md` (= `origin/runtime`) | +| b435acb | Karan, 00:15 | CI workflow, root lockfile, CLI mode 100755 | + +`git diff --stat 654d822 b435acb`: 451 files, +90,715 / −20,699. Earlier history (13 commits from 7a7ff6d to +654d822, all Mehar's) is legacy GenClass content, the runtime build-up and batch 3 / `situation-v1`. ### Version markers -| marker | value at 654d822 | meaning | +| marker | value at b435acb | meaning | |---|---|---| -| `main`, `origin/main`, `origin/runtime` | all 654d822 | OPEN_TASKS still calls the branch `runtime` and asks to merge it into `main` | -| tag `situation-v1` | → 1a77558, message "Frozen runtime situation format for model training" | freeze point for situation text; SIM final data and TRAIN final rounds use it | -| tag `v0.1.0-alpha.0` | → 654d822, message "@genclass/runtime 0.1.0-alpha.0 (npm)" | the published alpha | -| `packages/runtime/package.json` `version` | `0.1.0-alpha.0` | | -| `@genclass/runtime-model@0.1.0` | not created (no `package.json`, `files/` gitignored) | default model location | -| GitHub release `runtime-model-v0.1.0` | no such tag in the repo | the CLI's default `--from` | -| v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** trained for runtime decisions; used by demos and model tests | -| R17 / R32 | 17M / 32M runtime candidates, pruned 16,364-token vocab, int8 (q8) exports 9.58 / 22.47 MB | `training/EVAL.md` | - -### Status at 654d822 +| `mvp-v2` | b435acb, not pushed | this branch | +| `origin/runtime`, local `runtime` | 74f17c0 | Mehar's line; HANDOFF says "push to `origin runtime` as you go" | +| `main`, `origin/main` | 654d822 | not updated since the alpha | +| `mvp` (local) | b15415b on 654d822 | superseded | +| tag `situation-v1` | → 1a77558 | v1 format; superseded | +| tag `situation-v2` | annotated tag object 75df720 → commit 6e5e86e | **current frozen training format** | +| tag `v0.1.0-alpha.0` | → 654d822 | the published alpha | +| `packages/runtime/package.json` `version` | `0.1.0-alpha.0` | not bumped | +| `@genclass/runtime-model@0.1.0` | not published (404); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | +| GitHub release `runtime-model-v0.1.0` | no such tag in the repo; the CLI's default `--from` 404s (per the lead) | | +| v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** a runtime model; used by demos and model tests | +| R17-final1 / R32-final1 | situation-v1; on the `train` VM (`~/gcl/train-out/final1/`) and Mehar's Mac (`packages/runtime-model/files/r17/`, gitignored) | baseline only; does not match the v2 runtime | + +### Status at b435acb | item | state | owner | evidence | |---|---|---|---| -| Runtime core, model host, devtools, adapters | done, frozen | CORE, MODEL, UI | `OPEN_TASKS.md` Done; `git diff situation-v1 HEAD -- packages/runtime/src` empty | -| Runtime fix batch 3 (34 REVIEW findings, summed gate, `transient`, compact questions, word-level redaction) | done | CORE | commit 1a77558; `test/review-*.test.ts`, `test/batch3.test.ts` | -| npm alpha `0.1.0-alpha.0` | published 2026-10-08 (npm org `genclass`, owner meharpro) | lead | OPEN_TASKS Done; tag `v0.1.0-alpha.0` | -| Tarball smoke test | done | lead | `test/smoke/smoke.sh` (commit 59c213f) | -| SIM final phase A | done: train 448,420 / dev 14,613 / test 137,643 rows | SIM | `sim/samples/stats-final-a.json`, `training/LOG.md` | -| SIM final phase B (1.4M rows, seeds from 50,000,000, resumable parts) | in progress | SIM | OPEN_TASKS item 1; `sim/README.md` | -| Stage 1c (curriculum) R17/R32 | done: held-out `rt1` action 98.0 / 98.2%, diagnosis 98.3 / 98.4%, 0 false interventions | TRAIN | `training/EVAL.md`, `MODEL_CARD.md` | -| Stage-2 pilot (pre-freeze SIM r300k) | done: action 77.5 / 78.3% (R32 / R17), diagnosis 90.8 / 91.1%, heal FIR 0.06 / 0.08% but heal recall 1.3 / 1.4% | TRAIN | `training/EVAL.md` "Stage 2 pilot" | -| Final round 1 (phase A) | launched 2026-10-08 00:06–00:12 UTC, training ETA ≈ 01:28–01:30 UTC; eval, calibration and export "by about 02:40 UTC" (OPEN_TASKS 3) by an autonomous tail (`training/final_post.sh` on c02/c09, `training/pull_on_train.sh` on the VM) | TRAIN | `training/LOG.md`; EVAL final section "(in progress)" | -| Final round 2 (phase A + B, longer) | next, after the 03:00 UTC VM shutdown | TRAIN | OPEN_TASKS item 3 | -| Demos (6), Service Worker backend, Playwright harness | built; numbers only with v0.1; `demos/src/server/data/cities.ts` missing (see [demos.md](demos.md#drift-and-open-issues)) | DEMOS | `demos/results.md` (2026-10-07) | -| Choose shipping model(s), device-based selection | next | lead, MODEL | OPEN_TASKS item 5 | -| Publish runtime model + release, then `@genclass/runtime@0.1.0`; CI | next | lead | OPEN_TASKS item 8; no `.github/` directory exists | -| Honest-results docs, model card numbers, dev-only lazy import of the devtools (52 KB min / 17 KB gz) | next | lead | OPEN_TASKS item 7 (the package README already shows the `import.meta.env.DEV` dynamic-import pattern) | -| Public demo hosting (GitHub Pages) | waiting on the user | lead | OPEN_TASKS "Needs the user" | +| Runtime batches 4 and 5 (situation-v2) | done, frozen | CORE | fcd1e68, 6e5e86e; STATUS; `test/delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts` | +| Default mode `observe` | done on `mvp-v2` only (not on `origin/runtime`, not on npm) | us (f3636b2) | `runtime.ts` -> `RuntimeImpl` constructor; `test/default-mode.test.ts`; CONTRACT §13 | +| CI | workflow committed; never run on GitHub | us (b435acb) | `.github/workflows/ci.yml` | +| NaN fix | in code since ad24804; **not on npm** | CORE | `util.ts` -> `describe`; `test/nan.test.ts`; `sim/NEEDS.md` g still says OPEN | +| npm `0.1.0-alpha.0` | published (guard default, no model, v1) | lead | tag `v0.1.0-alpha.0` | +| npm `0.1.0-alpha.1` (NaN fix) | waiting on the owner's 2FA | user | OPEN_TASKS "Needs the user" | +| SIM v1 phase A / B | done (600,676 / 1,415,344 rows); superseded | SIM | training/NEEDS "SIM → TRAIN: scaled data" | +| Final round 1 (situation-v1) | done: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE 0.009; guard recall on clear stale/duplicate 7.7% | TRAIN | `training/EVAL.md`, RESULTS §1 | +| T1 runs and v1 teacher `t150-g1` | stopped at the v2 freeze, no results | TRAIN | `training/LOG.md` 01:13–03:35 | +| SIM v2 gold + unlabeled | **generating** on 20 nodes (≥ 10M + ≥ 50M) | SIM | HANDOFF; training/NEEDS claim table | +| REAL v2 production | **generating** on c01, c10, c11 (`v2b1`–`v2b3`, 30k trajectories each, ≥ 500k gold target); v2 pilot done (2,519 gold incl. 135 `delivery`) | REAL | training/NEEDS 16 | +| v2 teacher, students, DAgger, EVAL | not started | TRAIN | PLAN-v1 P1–P5 | +| `@genclass/runtime-model@0.1.0`, then `@genclass/runtime@0.1.0` | not started | lead / user | HANDOFF "How to continue" step 3 | +| Demos with a trained model | not started (numbers are v0.1 only) | DEMOS | RESULTS §5 | +| Public demo hosting; merge into `main` | waiting on the user | user | OPEN_TASKS "Needs the user" | ## How it works -### 1. What a default install does today (model unpublished) - -1. App calls `GenClass.init()` in a browser. `src/index.ts` -> `initUnsafe` reads the kill switch (URL `?genclass=`, else - `localStorage.genclass`; `off` installs nothing). Otherwise it sets `model: {}` and calls `createRuntime`. -2. `createRuntime` -> `makeHost` -> `createModelHost` with `baseUrl = DEFAULT_MODEL_BASE_URL`, `preload: "idle"` - (`src/model/host.ts`). Status starts as `{ state: "off" }`. -3. Observers install (`RuntimeImpl.installObservers`). Tracing, field versions, baselines, invariant mining and - transition profiles run from now on, whatever the model state (`RuntimeImpl.settled` has no model check). -4. After `load` + idle (≤ 2 s idle timeout, ≤ 5 s load wait), the host fetches `<baseUrl>model.json` - (`src/model/loader.ts` -> `fetchCard`). The package does not exist, so the fetch fails (expected HTTP 404; not checked - against the live CDN) and no cached card exists: `ModelLoadError("model card download failed: …")`; status becomes `error`. -5. `RuntimeImpl` constructor's `onStatus` listener emits a status report: `[GenClass] Model unavailable (<error>); - observing only.` (`console.info` with `report: "console"`; always delivered to `on("report")`). -6. From now on `RuntimeImpl.consultable()` is false (it is true only for `ready` or `off`): `trigger()` runs the passive - action without building a situation, `gateMutation` never holds. No `Decision`, `Detection` or `ActionRecord` is ever recorded. -7. `rt.ready` rejects with the load error (memoised); `rt.ask()`/`decide()` reject with - `GenClassUnavailableError` (`reason: "error"`), or with the raw provider error when `timeoutMs` is set. -8. There is no automatic retry: the runtime memoises `ready`; `ModelHost.load()` would retry but nothing calls it. - -Before step 4: while status is `off` (idle preload not started), a salient trigger is built, fails open at once -(`trigger()` -> `provider.status.state !== "ready"`) and starts the load (`void this.ready`); while `loading`, -`consultable()` is false and triggers are skipped. To see decisions today, self-host the **v0.1** model with -`npx genclass-runtime fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` and pass -`model: { baseUrl }`. Without `--from` the CLI uses `DEFAULT_FROM` (the unpublished release), which is expected to -fail (not checked against GitHub). v0.1 answers -`unusual` almost always (`demos/NEEDS.md` §8), so its decisions only exercise the pipeline. +### 1. What a default install does today + +1. The app calls `GenClass.init()`. `index.ts` -> `initUnsafe` reads the kill switch (URL `?genclass=`, else + `localStorage.genclass`; `off` installs nothing; `observe|guard|heal` override the mode). Otherwise it sets + `model: {}` and calls `createRuntime`. +2. `RuntimeImpl`'s constructor sets `this._mode = o.mode ?? "observe"`: **observe** unless the app asks for guard. + (The npm alpha.0 still defaults to guard.) +3. `createModelHost` gets `baseUrl = DEFAULT_MODEL_BASE_URL` + (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`) and `preload: "idle"`; status starts `off`. +4. Observers install. Tracing, field versions, baselines, invariants, transition profiles and cadence learning run + whatever the model state. +5. After `load` + idle, the host fetches `<baseUrl>model.json`; the package does not exist, so status becomes + `error` and the runtime emits `[GenClass] Model unavailable (<error>); observing only.` (`runtime.ts`, the + `onStatus` listener in the constructor). +6. From then on `RuntimeImpl.consultable()` is false (true only for `ready` or `off`): `runDelivery` releases every + response and message at once, `trigger()` runs the passive action without building a situation, writes are never + observed for decisions. No `Decision`, `Detection` or `ActionRecord` is recorded. `rt.ready` rejects (memoised); + `ask`/`decide` reject. Nothing retries the load. +7. Before step 5 (status `off`), a salient trigger builds a situation, fails open and starts the load. A salient + delivery can wait up to `BODY_WAIT_MS` (100 ms) for its body even then (review finding DL-3). + +Even with a model, `observe` takes no action: decisions are made in the background and reported +(`test/default-mode.test.ts`). The only way to see decisions today is to self-host a model: no model matches +situation-v2, the v0.1 model only exercises the pipeline (`npx genclass-runtime fetch-model <dir> --from +https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`; a model download, so ask the user first). ### 2. How a request moves between workstreams -1. The requester writes an item in its NEEDS file with evidence and a status (OPEN or ASK), addressed to an owner. -2. The lead relays it (and, for a contract change, approves it into CONTRACT §13 or rejects it). -3. The owner lands it in a batch and records it in its status file (CORE: STATUS.md batch section; deviations under - "Deviations from the contract (and why)"). -4. The requester verifies it on the VM and flips the item to DONE with a verification note (example: sim/NEEDS 1–5 - "Verified: 100% of decisions in a 20k-row run correlate…"). -5. If the change alters situation text, SIM and TRAIN regenerate data (STATUS: "Fact and question wording changed again - in batch 3 … regenerate rows"). - -Step 4 is often skipped: several items are implemented but still marked OPEN/ASK (see Drift). - -### 3. How a runtime change reaches the shipped model - -1. CORE changes `packages/runtime/src/situation/*` (or anything that changes the text: `util.ts` formatting, vocab, - op/event names). -2. The lead freezes it with a tag (`situation-v1`). -3. SIM generates rows by driving that exact runtime (`sim/src/run/rt.ts`, `npm run build:runtime-core`). -4. TRAIN mirrors the wording in the curriculum (`training/curriculum/rt.py`), imports SIM rows, trains, calibrates on - dev, evaluates on held-out test, exports q8/fp16 (`training/export_runtime.py`, `training/ortweb/validate.mjs`). -5. MODEL checks parity of the TS packer/engine against the export's `parity.json` (an export artefact, not in the - repo; training/NEEDS, MODEL → TRAIN 7). -6. The lead publishes the model directory as `@genclass/runtime-model@0.1.0` (jsDelivr serves `files/`) plus GitHub - release `runtime-model-v0.1.0`, then publishes `@genclass/runtime@0.1.0`. +1. The requester writes a NEEDS item with evidence and a status (OPEN or ASK), addressed to an owner. +2. The lead relays it (contract changes: approve into CONTRACT §13, or reject). +3. The owner lands it in a batch and records it (CORE: STATUS batch section with "Contract deltas"; deviations). +4. The requester verifies it and flips the item to DONE. This step is often skipped (sim/NEEDS g, UI-NEEDS 1/3, + demos/NEEDS §1/§2/§6 are implemented but not flipped; see Drift). +5. If the change alters situation text: new freeze tag, SIM and REAL regenerate, TRAIN mirrors `rt.py` and retrains. + +### 3. How a runtime change reaches the shipped model (situation-v2 pipeline) + +1. CORE changes `packages/runtime/src/situation/*` (or other model-visible text: `util.ts` formatting and + redaction, fact/question/action wording, op/event names) and the lead tags it (`situation-v2` = 6e5e86e). +2. **SIM** drives that exact runtime in a deterministic virtual world (`sim/src/run/rt.ts` -> `realRuntimeFactory`, + pinned to `mode: "heal"` in `createOptions`, so the observe default does not affect SIM data): gold rows + (counterfactual costs, S1 diagnosis relabelling, S2 re-drawn latents), unlabeled rows (every decision point of a + base run) and, later, on-policy rows. Details: [sim.md](sim.md). +3. **REAL** bundles the runtime from source at a pinned tag into real apps in headless Chromium and labels with the + sim's cost weights: [realapps.md](realapps.md). +4. **TRAIN** mirrors the wording in `training/curriculum/rt.py` (ported to situation-v2 in d73d20c), imports + SIM/REAL rows, trains the T150 teacher on gold, soft-labels unlabeled rows (`label_teacher.py`, + `label_cluster.sh`), distils R17/R32 (`launch_student.sh`), runs DAgger rounds, evaluates + (`eval_sim.sh`, `eval_runtime.py`, `final_post.sh`), calibrates on dev and exports q8/fp16 + (`export_runtime.py`, `ortweb/validate.mjs`). Details: [training.md](training.md). +5. **MODEL** checks TS packer/engine parity against the export's `parity.json`. +6. The lead publishes `@genclass/runtime-model@0.1.0` (jsDelivr serves `files/`) and a GitHub release + `runtime-model-v0.1.0`, the demos are rerun, then `@genclass/runtime@0.1.0` is published (owner's 2FA). + +### 4. Where the v2 data and compute are now + +- **Cluster** (HANDOFF "Rules"): `rg-jev-train`, eastus, quota 2,048 vCPU; nodes c01–c23 (F80 variants; c12–c23 added + 2026-10-08 by `training/cluster_expand.sh`) plus `train` (1 TB `/data` disk, bundle server) and `data`. **The + nightly auto-shutdown schedules are disabled** for the training push and must be re-enabled when it ends. +- **Claims** (training/NEEDS "Cluster expansion and claims"): SIM c02–c09 + c12–c23 for the v2 runs, each node + deallocated when its share is collected; REAL c01, c10, c11 until its batches finish; TRAIN holds no node; TRAIN + plans the teacher on c12–c23, students on c02–c11 and the workbench on c01 once v2 data lands. +- **Data locations:** SIM `train:/data/sim-out/v2-*` (check run: `v2chk-{gold,unl}`); REAL `c01:~/gcl/real-out/v2b1/`, + `c10:…/v2b2/`, `c11:…/v2b3/` (copied to `train:/data/real-out/` when done), v2 pilot `train:/data/real-out/v2-pilot/`. + All from training/NEEDS; not checkable from here. +- **Spend:** about $400 to date (RESULTS §7); PLAN-v1 estimates $3–4k for P0–P5. ## Configuration and constants Status-relevant values only; the subsystem docs list the rest. -| name | type | value | defined in | effect | -|---|---|---|---|---| -| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default `model.baseUrl`; unpublished → status `error`, observe only | -| `DEFAULT_FROM` | string | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | `fetch-model` default source; no `runtime-model-v0.1.0` tag in the repo (GitHub releases not checked) | -| v0.1 model URL | string | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | `demos/scripts/fetch-model.sh`, CONTRACT §10 | the only model that exists publicly | -| runtime `dependencies` | — | `onnxruntime-web ^1.30.0` only; optional peers `react >=18`, `redux >=4`, `zustand >=4` | `packages/runtime/package.json` | dependency policy (CONTRACT §0 rule 6) | -| `engines.node` | — | `>=20` (VM runs Node 22) | `packages/runtime/package.json`, root `package.json` | | -| `policy.thresholds` | numbers | report 0.6, guard 0.9, heal 0.8 | `src/decide/policy.ts` -> `policyConfig` | precision-first gate | -| `policy.requireDiagnosis` | boolean | `true` | `policyConfig` | non-passive needs top diagnosis ≠ `expected` | -| `policy.holdBudgetMs` | number \| "auto" | "auto" = clamp(1.5 × median of last 20 latencies (else warm-up), 150, 800); 300 if nothing known | `decide/policy.ts` -> `holdBudget`, `HOLD_MIN_MS`/`HOLD_MAX_MS`/`HOLD_FALLBACK_MS` | how long holds last | -| `policy.maxActionsPerMinute` | number | 60 | `policyConfig` | rate limit | -| `LATE_REVERT_MS` | ms | 2000 | `src/runtime.ts` | late `discard` window | -| `PROVIDER_TIMEOUT_MS` | ms | 10,000 | `src/decide/decider.ts` | runtime-side provider abandonment | -| `STATE_CHAR_BUDGET` | chars | 3200 (comment: "≈ 3.2 chars per token") | `src/situation/serialize.ts` | full situation budget; TRAIN measured 2.4 chars/token (training/NEEDS 6a) | -| `COMPACT_BUDGET` | chars | 1100 | `situation/serialize.ts` | floor of `sectionLimits` interpolation (not the compact-questions switch) | -| `COMPACT_QUESTIONS_BUDGET` | chars | 1400 | `src/situation/questions.ts` | at or below: bare labels/names in questions | -| auto situation budget | chars | webgpu 3200; wasm `1000 + round((threads − 1) × 1000 / 3)` with threads clamped to 1–4 (1000/1333/1667/2000); unknown device 3200; all × `budgetScale` (1, × 0.8 per `max_tokens_exceeded`, floor 0.5) | `RuntimeImpl.situationBudget` | device sizing; a numeric `situation.budget` wins | -| `DEFAULT_DIAGNOSES` | labels | expected, stale, conflict, duplicate, inconsistent, failing, slow, overload, unusual, transient | `situation/questions.ts` | frozen vocabulary order | -| kill switch | URL / localStorage | `genclass=off\|observe\|guard\|heal` (URL wins) | `src/index.ts` -> `killSwitch` | rule GenClass out while debugging | +| name | value at b435acb | defined in | effect | +|---|---|---|---| +| default mode | `"observe"` | `runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | no actions unless `mode: "guard"`/`"heal"`, `?genclass=guard`, or `setMode` | +| test-harness mode | `"guard"` | `test/helpers.ts` -> `setup` | CORE tests exercise interventions; `setup({ mode: undefined })` gives the product default | +| `DEFAULT_MODEL_BASE_URL` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | unpublished → status `error`, observe only | +| `DEFAULT_FROM` | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | `fetch-model` default source; 404 | +| `STATE_CHAR_BUDGET` | 2400 (was 3200 in v1) | `situation/serialize.ts` | full situation budget (≈ 1,000 tokens at the measured 2.4 chars/token) | +| `COMPACT_BUDGET` / `COMPACT_QUESTIONS_BUDGET` | 1100 / 1400 | `situation/serialize.ts` / `situation/questions.ts` | section-limit floor / bare-label questions | +| auto situation budget | webgpu and unknown device 2,400; wasm `1000 + round((threads − 1) × 1000 / 3)`, threads clamped 1–4; × `budgetScale` (× 0.8 per `max_tokens_exceeded`, floor 0.5) | `RuntimeImpl.situationBudget` | device sizing; a numeric `situation.budget` wins | +| SIM budget sampling | `[[3200, 40], [2000, 30], [1000, 30]]` | `sim/src/world/scenario.ts` (`budget`) | **still v1** (finding SIT-2); `rt.py` `BUDGETS` uses 2400/2000/1667/1333/1000 | +| `policy.holdWrites` | `false` | `decide/policy.ts` -> `policyConfig`; `state/hub.ts` -> `StoreHub.holdWrites` | store writes apply at once; opt-in holds never reorder a store's writes | +| `policy.thresholds` | report 0.6, guard 0.9, heal 0.8 | `decide/policy.ts` -> `policyConfig` | summed-mass gate + `requireDiagnosis` | +| hold budget | "auto" = clamp(1.5 × median latency, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800), `HOLD_FALLBACK_MS` 300 | `decide/policy.ts` | a trigger holds only if `expectedLatency() <= holdBudgetMs()` | +| `BODY_WAIT_MS` | 100 | `runtime.ts` | a salient delivery waits this long for its body clone | +| `DISCARD_MARK_MS` | 10,000 | `runtime.ts` | a delivery `discard` keeps dropping the chain's writes over newer data this long | +| `LONG_RUNNING_MS` | 10,000 | `runtime.ts` (`waitOps`) | a delivery `defer` waits at most this per defer (≤ 2 defers) | +| `BACKGROUND_DEADLINE_MS` | 5,000 | `runtime.ts` | non-held decisions | +| `LATE_REVERT_MS` | 2,000 | `runtime.ts` | late `discard` window | +| `PROVIDER_TIMEOUT_MS` | 10,000 | `decide/decider.ts` | runtime-side provider abandonment | +| `observe.untrustedEvents` | `false` | `runtime.ts` -> `installObservers`; `observe/dom-user.ts` | synthetic DOM events are not user actions unless enabled | +| `NOT_PROCESSED` | `502, 503, 429, 408` | `situation/evidence.ts` | statuses called "usually returned without processing the request" (finding SIT-11) | +| runtime `dependencies` | `onnxruntime-web` only; optional peers react, redux, zustand | `packages/runtime/package.json` | CONTRACT §0 rule 6 | +| CI Node | 22 (`engines.node` `>=20`) | `.github/workflows/ci.yml`, `package.json` | | +| kill switch | `genclass=off\|observe\|guard\|heal` (URL wins over `localStorage`) | `index.ts` -> `killSwitch` | rule GenClass out while debugging | ## Invariants and gotchas -### Ground rules (binding; CONTRACT §0 and §0.5, restated) - -CONTRACT: "This file binds every workstream. If something here is wrong, tell the lead; do not silently diverge." - -1. **No hardcoded bugs, patterns, recoveries or demo rules in the runtime (§0 rule 1).** The runtime may compute generic, - uniform facts (happens-before order, versions, repetition counts, failure streaks, latency vs learned baselines, - learned invariants, value deltas) and may decide whether a situation is worth asking the model about (triage). It - must never map a fact pattern to a diagnosis or an action with an if/then. Diagnoses and actions come from the model. - If the model is unavailable, the runtime observes only and always takes the passive action. - *In code:* triage is `facts.every((f) => f.neutral)` in `RuntimeImpl.trigger`; actions are chosen only by - `decide/policy.ts` -> `gate` from model probabilities; report templates (`decide/report.ts`) are reporting only. - Applicability checks (`situation/build.ts` -> `builtinApplicable`) only say whether an action *can* run. -2. **Train/runtime parity (§0 rule 2).** The sim drives the real runtime code (same trace, facts, serializer, questions) in a - deterministic virtual world. There is exactly one implementation of situation building and serialization: - `packages/runtime/src/situation/*`. *In code:* `sim/package.json` depends on `@genclass/runtime` and builds it with - `build:runtime-core`. Wording changes after `situation-v1` invalidate the final data. -3. **Determinism (§0 rule 3).** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly, and never - schedules with the global `setTimeout`; it uses the injected `Clock` (`src/clock.ts` -> `browserClock` captures - real timers at module load). IDs come from counters. Same inputs give byte-identical situations - (`test/budget.test.ts`, `test/situation.test.ts`). *Exceptions found:* `src/model/engine.ts` defaults `now` to - `performance.now()` (timing only), `src/model/host.ts` -> `scheduleIdle` calls `requestIdleCallback` for preload, and - the devtools render with a `requestAnimationFrame` captured at module load (`src/devtools/index.ts`; UI only, never - situation text). No `Math.random` or `Date.now` anywhere in `packages/runtime/src`. -4. **Honest evaluation (§0 rule 4).** `demos/` and `sim/` are built by different people who do not read each other's code. - The sim never models a demo. Demos contain no hints beyond a normal integration (stores, optional `resync` - handlers, custom actions/questions only in the extensibility demo). `demos/README.md` "Honesty rules" restates this. -5. **Mac safety (§0 rule 5).** The Mac only edits files. Every build, test, browser and model run happens on the `train` VM - via `scripts/vm.sh` in your own slot. Never run `npm install`, `tsc`, `vitest`, Playwright or a model locally. - *Lead policy for agents (2026-10-07):* the rule exists because the original author's Mac has 8 GB RAM. On other - machines `npm install`, typecheck, build and the runtime unit tests are light and verified to work locally. Ask - the user before running the sim, training, Playwright (including `test/smoke/smoke.sh`), model downloads, the demos' - eval, or any script that touches Azure (`scripts/*.sh`, `training/*.sh`, `sim/scripts/*`). Details and the verified - commands: [runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things). -6. **Language and dependencies (§0 rule 6).** TypeScript, strict mode (`tsconfig.base.json` `"strict": true`), ESM only, - Node 22 on the VM. No new runtime dependency besides `onnxruntime-web` without asking the lead. -7. **Do not edit legacy content (§1).** "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is." - This covers the pre-runtime GenClass content: `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, the legacy - `docs/*.md` (jev-local contracts and specs), `docs/benchmax-research/` and the legacy scripts in `scripts/`. It does - not cover `docs/runtime/`, `docs/agents/` or `scripts/vm.sh` (added by the runtime team in 353b0a4). - -**Product principles (§0.5, "from the user, 2026-10-07; binding").** Claim: *install one library; find and prevent -runtime failures automatically, with low false positives.* - -1. **False positives.** Default mode takes only minimal, reversible guard actions at very high calibrated confidence; a - non-passive action also requires the model's diagnosis to say something is wrong; the false-intervention rate on - clean runs is a first-class metric in the sim test split and in every demo. -2. **Performance.** Tiered detection: facts and baselines always on and nearly free; the model only for salient - situations, in a worker, loaded at idle or lazily, cached. Target model: pruned vocabulary + int8 embeddings, ≤ 25 MB q8. -3. **Observability.** One plain-English console line per detection/intervention with collapsible evidence, `explain(id)`, - undo for reversible actions, `x-genclass` response marks, kill switch `?genclass=off`. - -Adoption path: `observe` → `guard` (default) → `heal`. CONTRACT §11 adds **precision first** for training data: benign -but salient-looking situations must be well represented, and the sim reports per trigger the passive-best fraction and -the harm of each non-passive action on passive-best rows. +### Ground rules (binding; CONTRACT §0, §0.5 and §13, restated for mvp-v2) + +CONTRACT: "If something here is wrong, tell the lead; do not silently diverge." For us, the lead is the user. + +1. **No hardcoded bugs, patterns or recoveries in the runtime (§0 rule 1).** Generic facts and triage only; the model + chooses diagnoses and actions. *In code:* triage is `facts.every((f) => f.neutral)` in `RuntimeImpl.trigger` + (plus delivery salience in `RuntimeImpl.runDelivery`: newer-data and pending-change conflicts, F2 typed text, + F3 unchanged bodies); actions are chosen only by `decide/policy.ts` -> `gate`; `situation/build.ts` -> + `builtinApplicable` only says whether an action *can* run. Model unavailable → observe only, passive action. +2. **Train/runtime parity, frozen at situation-v2 (§0 rule 2).** One implementation of situation building: + `packages/runtime/src/situation/*`. SIM drives it, REAL bundles it, `training/curriculum/rt.py` ports it. **Any + change to model-visible text** (situation code, fact/question/action/diagnosis wording, `util.ts` formatting and + redaction, op/event names) needs a new tag, regenerated SIM and REAL data, an `rt.py` mirror and retraining. + Data is being generated from this code right now: never make such a change without the user's go-ahead. + Behaviour-only runtime fixes (most delivery findings) do not change wording but do change SIM/REAL dynamics and + therefore labels: coordinate them too. +3. **Determinism (§0 rule 3).** No `Math.random`, `Date.now`, `performance.now` or global `setTimeout` in runtime + code; the injected `Clock`; ids from counters. Re-checked at b435acb: the only hits are `model/engine.ts` + (default `now = performance.now()`, timing only), `model/host.ts` (`requestIdleCallback` for preload) and + `clock.ts` itself (`browserClock`). The devtools capture `requestAnimationFrame`/`setTimeout` at module load. +4. **Honest evaluation (§0 rule 4).** `demos/` is never read or modelled by `sim/` or `realapps/`; demos are never + tuned. +5. **Where to run things (§0 rule 5, superseded for us).** CONTRACT and HANDOFF say the Mac only edits files and every + build/test runs on the `train` VM: that is Mehar's 8 GB Mac. **Our run policy (2026-10-08):** light local checks + (`npm install`/`npm ci`, `tsc`, `tsup`, vitest unit tests) are fine on this machine. **Ask the user first** before + Playwright, `test/smoke/smoke.sh`, the sim generator, training, realapps runs, the demos' eval, model downloads, + anything on Azure, `git push`, `npm publish`. See [../../AGENTS.md](../../AGENTS.md) §4. +6. **Language and dependencies (§0 rule 6).** TypeScript strict, ESM only; `onnxruntime-web` is the only runtime + dependency; ask before adding one. Keep the root `package-lock.json` in sync (CI uses `npm ci`). +7. **Do not edit legacy content (§1):** `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, legacy `docs/*.md`, + `docs/benchmax-research/`, legacy `scripts/`. Not covered: `docs/runtime/`, `docs/agents/`, `scripts/vm.sh`. +8. **REVIEW tests are a contract.** Never edit `test/review-*.test.ts` to make them pass. +9. **Licensing (HANDOFF):** train only from v1 `jev-local-fast` or MIT ettin bases plus synthetic/sim/realapps data; + never v2/Z/S checkpoints or benchmark datasets. + +**Product principles (§0.5, binding).** Claim: *install one library; find and prevent runtime failures automatically, +with low false positives.* (1) False positives: since f3636b2 / CONTRACT §13 the **default mode is `observe`** (reports +only); `guard` is opt-in (minimal guard-tier actions at summed probability ≥ 0.9 with a non-`expected` diagnosis); +`heal` is experimental; FIR on clean runs is a first-class metric. (2) Performance: facts always on and cheap, the +model only for salient situations, in a worker. (3) Observability: one console line per detection/intervention, +`explain(id)`, undo, `x-genclass` marks, kill switch. Product principle from HANDOFF: "never make a correct app worse". ### Gotchas -- **Code wins over every doc here.** CONTRACT.md was last changed in a53dd38, before batch 3. STATUS.md was last - changed in 1a77558, UI-NEEDS and sim/NEEDS in a53dd38. Check the Drift tables before relying on them. -- **The runtime is frozen.** Do not change situation text, fact wording, action/diagnosis descriptions, `util.ts` - formatting (`secs`, `rel`, `describe`, `normalizePath`, `isSensitiveName`, …) or op/event names without the lead, - SIM and TRAIN. Pipeline-only fixes (e.g. demos §1 ordering) do not change text but still change sim dynamics. -- **REVIEW tests are a contract.** STATUS: "including every `test/review-*.test.ts` (no review test was modified)". Fix - code, not these tests. -- **No CI and no type-checking of tests.** There is no `.github/` directory. `packages/runtime/tsconfig.json` includes - only `src`, so test files (and `test/browser/ui/mock-runtime.ts`) are not type-checked. -- **No VM access by default.** `scripts/vm.sh` needs `~/.jev-local/azure_hosts` (a `train` line) and `~/.ssh/jev_azure`, - neither in the repo, plus GNU `timeout` on the local `PATH`. Without them the VM is unreachable. Run the light checks - locally (lead policy, [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)) and ask the - user before anything heavier. Gitignored `node_modules/` and - `packages/runtime/dist/` in a working copy may be stale; rebuild before trusting them. -- **Test counts.** STATUS reports 37 files / 300 tests passing on the VM with a model directory. The lead re-ran the - unit tests on 2026-10-07 at 654d822: macOS, Node v25.6.0, no model directory, `packages/runtime`, - `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**"`. Result: Test Files 36 passed | 1 skipped (37), - Tests 286 passed | 14 skipped (300), about 2.4 s. That confirms STATUS's file and test totals and the 286 tests that - need no model. The 14 skips are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default - `<repo>/.cache-model`): `test/model/packer.test.ts` all 10, `engine.test.ts` 3 of 4, `calibrate.test.ts` 1 of 8. - That those 14 pass comes from STATUS's VM run. The same pass confirmed STATUS's "`tsc --noEmit` clean" and "`tsup` - build OK". It did not run the Playwright specs or `test/smoke/smoke.sh`. A static count of `it(`/`test(` call sites - is lower than 300 because some tests are generated in loops. -- **The shipped default path is untested.** No file under `packages/runtime/test/` references `DEFAULT_MODEL_BASE_URL` - or the "Model unavailable … observing only." line, and no `RuntimeImpl` test drives a provider whose status is - `error` (`test/model/host.test.ts` and `test/model/loader.test.ts` cover the host's own `error` status only); the - tarball smoke test uses `model: false`. What a default `init()` does today (How it works §1) is verified by code - reading only. -- **No committed lockfile at the root.** Only `extension/package-lock.json` is tracked; root `npm install` resolves - caret ranges (`onnxruntime-web ^1.30.0`, `vitest ^5.0.3`, …) fresh each time. A root `npm install` also leaves two - changes git sees: an untracked root `package-lock.json` (do not commit it unless the lead decides to), and - `bin/genclass-runtime.mjs` chmodded from the committed 100644 to 755, a mode change. Revert the mode with - `git checkout -- packages/runtime/bin/genclass-runtime.mjs`. -- **Two "compact" constants.** `COMPACT_BUDGET` = 1100 shapes section sizes; `COMPACT_QUESTIONS_BUDGET` = 1400 - switches to bare labels. Do not merge them; both are frozen. -- **`docs/CONTRACT.md` is not the runtime contract.** The runtime contract is `docs/runtime/CONTRACT.md`. -- **Demo numbers measure the harness, not the product.** `demos/results.md` used the v0.1 model. -- **`OPEN_TASKS.md` mixes time zones and dates.** The header says "as of 2026-10-07 23:30 UTC" while its Done entry is - dated 2026-10-08; commit 654d822 is 2026-10-08 00:15 UTC. +- **Code wins over every doc.** CONTRACT.md does not describe batch 4/5 (no `delivery` trigger); the deltas live in + STATUS "Contract deltas". HANDOFF still says guard is the default. +- **Two defaults in the wild.** `mvp-v2` defaults to `observe`; `origin/runtime` and npm alpha.0 default to `guard`. + The tests' `setup()` defaults to `guard` on purpose. +- **"Observe never changes execution" is not quite true yet**: a salient delivery can wait up to 100 ms for its body + and XHR completion listeners run outside the original dispatch (finding DL-3). +- **The runtime is frozen.** See ground rule 2. `git diff situation-v2 HEAD -- packages/runtime/src/situation` must stay + empty unless the user approved a new format. +- **R17-final1 is a v1 model.** Do not load it into this runtime, ship it, or compare v2 numbers against it as if the + formats matched. +- **Tests are not type-checked.** `packages/runtime/tsconfig.json` includes only `src`. +- **Test counts differ by branch.** STATUS and HANDOFF say 41 files / 346 tests (origin/runtime, on the VM with a + model dir). On `mvp-v2`: 42 files, 350 tests (f3636b2 added `test/default-mode.test.ts`); without a model dir 14 + model-parity tests skip. `review-perf` can flake in a parallel run (5.5 ms vs its 2 ms bound once); run it alone. +- **The shipped default path is untested.** No test references `DEFAULT_MODEL_BASE_URL` or "observing only"; the smoke + test uses `model: false`. +- **`demos/src/server/data/cities.ts` is not in git** (root `.gitignore` rule `data/`), so a fresh clone cannot build + or typecheck the demos, and root `npm run typecheck` (all workspaces) fails. CI typechecks only `@genclass/runtime`. +- **v1 artefacts look current.** `training/NEEDS.md` "SIM → TRAIN: scaled data" says "Runtime tag `situation-v1`" + for the v1 batches; realapps batch manifests hardcode `situation-v1` even for v2 batches (finding RA-8). Filter on + `meta.runtime` in the rows, not on manifests. +- **`docs/CONTRACT.md` is not the runtime contract** (`docs/runtime/CONTRACT.md` is). +- **Demo numbers measure the harness, not the product** (v0.1 model; RESULTS §5). +- **Time zones.** Commit times are −04:00; HANDOFF, LOG and NEEDS use UTC. ## How to change it safely -**Record status after landing a runtime change (CORE)** -1. Update `packages/runtime/STATUS.md`: "Updated:" line, State (VM command and counts), a batch section, Deviations - (with the reason) and Open issues. -2. If the public surface changed, update `docs/runtime/API.md` and the JSDoc in `src/types.ts` in the same change. -3. Move the item in `OPEN_TASKS.md` (Next → In progress → Done), with evidence. -4. Ask the requester to flip its NEEDS item to DONE after verifying. Do not close or rewrite another workstream's items - yourself; owners may add answers under their own heading in the requester's file, as MODEL did in `training/NEEDS.md` - ("MODEL → TRAIN (from MODEL, 2026-10-07)"). - -**Propose a contract change or deviation** -1. Write the request with evidence in your NEEDS file (or tell the lead directly). -2. After approval, the lead appends it to CONTRACT §13 or the owner lists it in STATUS "Deviations from the contract (and why)". -3. Never diverge silently. A deviation without a STATUS entry is a bug. - -**Change anything the model reads (after `situation-v1`)** -1. Get the user's go-ahead: it invalidates SIM phase A/B data and the final training rounds. -2. Change only `packages/runtime/src/situation/*` (one implementation) plus `util.ts` helpers if needed. Update example - situations in STATUS from `test/situation.test.ts` / `test/budget.test.ts` output. -3. Tell SIM (regenerate) and TRAIN (`training/curriculum/rt.py` mirror; per-header calibration in `calibration.json` is - keyed on exact instruction text, training/NEEDS 5). Expect a new freeze tag (convention suggested by `situation-v1`; no v2 exists). -4. Run locally or on the VM in your slot (STATUS "State"; where to run: - [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated)): `npm install` at the repo root, then in `packages/runtime` - `npx tsc --noEmit` and `GENCLASS_MODEL_DIR=~/gcl/model/.cache-model NODE_OPTIONS=--expose-gc npx vitest run` - (model tests need the v0.1 model directory; the gc test needs `--expose-gc`). Exact commands: - [runtime/build-test-release.md](runtime/build-test-release.md). +**Record status after landing a runtime change (CORE role)** +1. Update `packages/runtime/STATUS.md` ("Updated:" line, State, a batch section with "Contract deltas", Deviations, + Open issues) and `docs/runtime/API.md` / `types.ts` JSDoc if the public surface changed. +2. Move the item in `OPEN_TASKS.md`, update `HANDOFF.md` "Current state" if it changes the picture, and add results + to `docs/runtime/RESULTS.md` with FIR next to recall. +3. Ask the requester to flip its NEEDS item to DONE; do not rewrite another workstream's items. + +**Fix a review finding** +1. Classify it first: (a) runtime model-visible text (needs a new freeze tag, regenerated data and an `rt.py` + mirror: SIT-1, SIT-3, SIT-8, SIT-10, SIT-11); (b) runtime behaviour (DL-*: wording unchanged but SIM/REAL dynamics + and therefore labels change); (c) curriculum port only (`rt.py`/`scenarios.py`: SIT-4…SIT-7, SIT-9, SIT-12, + SIT-13; no v2 curriculum set exists yet, per [training.md](training.md)); (d) data/infra scripts (SIT-2, ST-*, + RA-*), which affect the live Azure runs; (e) docs (PD-*, SIT-14). +2. For (a)–(c), get the user's go-ahead and agree with Mehar whether it lands before or after the current v2 + generation. For (d), edit freely (docs owned by the right workstream). +3. Add the regression test the finding suggests, in a new or existing non-review test file. + +**Change anything the model reads (after `situation-v2`)** +1. Get the user's go-ahead (it invalidates the v2 data being generated). +2. Change only `src/situation/*` plus `util.ts` helpers if needed; update STATUS example situations. +3. Tell SIM, REAL (regenerate) and TRAIN (`rt.py` mirror; per-header calibration keyed on exact instruction text, + training/NEEDS 5). Expect a new tag (`situation-v3`). +4. Run the light checks locally (commands in [runtime/build-test-release.md](runtime/build-test-release.md)). **Fix doc drift** -1. Confirm the behaviour in code first. Code wins; do not change code to match a doc unless the lead decides the doc is the spec. -2. Edit the doc owned by the right workstream: CONTRACT (lead), STATUS/API (CORE), UI-NEEDS (UI), sim/NEEDS (SIM), etc. -3. Fixing JSDoc in `src/types.ts` is safe (no situation text). Fixing `BUILTIN_ACTIONS` descriptions is **not** (model input). - -**File a cross-workstream request** -1. Add a numbered item to your NEEDS file: addressee, status (OPEN or ASK), evidence (trace, seeds, row ids, file -> symbol), a - suggested fix and, for CORE, a regression test sketch (demos/NEEDS §1 is the model). - -**Run checks** (where to run: [ground rule 5 (Mac safety)](#ground-rules-binding-contract-0-and-05-restated) and [runtime/build-test-release.md](runtime/build-test-release.md#where-to-run-things)) -- Runtime unit tests (local or VM): in `packages/runtime`, `NODE_OPTIONS=--expose-gc npx vitest run` (`vitest.config.ts` - already excludes `test/browser/**`; without `--expose-gc`, `test/review-timers.test.ts` logs "[review] skipped: run with - NODE_OPTIONS=--expose-gc" and passes without checking anything). -- Tarball smoke (ask the user first; Playwright Chromium and npm registry): `bash test/smoke/smoke.sh` from `packages/runtime`. -- Sim tests (ask the user first): from the repo root, `npm run build && cd sim && SIM_RUNTIME=real npx vitest run` (the sim - imports `@genclass/runtime` through `packages/runtime/dist`, `sim/src/run/rt.ts` -> `realRuntimeFactory`, so build first). +1. Confirm the behaviour in code first; code wins. +2. Edit the doc owned by the right workstream (CONTRACT: lead; STATUS/API: CORE; NEEDS: requester). +3. JSDoc in `types.ts` is safe; `BUILTIN_ACTIONS` descriptions and `DEFAULT_DIAGNOSES` are model input (frozen). + +**Run checks** (local, per our run policy) +- `npm ci` at the root; in `packages/runtime`: `npx tsc -p tsconfig.json --noEmit`, `npx tsup`, + `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then + `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts`. +- Sim: `npm run build` at the root, then in `sim/` `SIM_RUNTIME=real npx vitest run` (19 tests, 5 files). +- Ask first: `bash test/smoke/smoke.sh`, Playwright, realapps, demos eval, Python/training. ## Tests | test file | what it asserts (status-relevant) | |---|---| -| `test/review-actions.test.ts` | error-trigger `rollback` offered only when the failing chain wrote state; never reverts other chains' writes | -| `test/review-hub.test.ts` | held value writes re-applied as patches; late-revert undo; in-place updaters while held; versions past the 16-entry history; 2,000-item arrays; throwing commits do not strand queues | -| `test/review-dom.test.ts` | password values never recorded; programmatic `el.click()` inside an op is not a user action | -| `test/review-fetch.test.ts` | request identity (Request bodies, Range); coalesce never hangs; memory bounds (64 × 256 KB); destroy pass-through; no holds in guard mode for failures; keepalive never held; failure/error-rate fact wording | -| `test/review-xhr.test.ts` | sync XHR never held; abort while held; listeners once per object; reuse after block | -| `test/review-timers.test.ts` | recursive `setTimeout` loops: no stack overflow, no retention | -| `test/review-precision.test.ts` | short last page not unusual; `m21`-style keys; null selection not an inconsistency; lingering violation does not freeze `lastConsistent` | -| `test/review-redaction.test.ts` | custom `redact` applies to invariant facts | -| `test/review-misc.test.ts` | console ×N summaries; rate-limit warning once; init robustness on read-only globals; `ctx.builtin` cannot bypass policy; never-settling provider; `ask` after destroy rejects `destroyed` | -| `test/review-perf.test.ts` | cost with 5,000-item stores; asserts per-write < 1 ms (keystroke), < 2 ms (gated async write), redux dispatch < 1 ms (user) / < 2 ms (async), settled point < 16 ms (STATUS measured 0.14, 0.19, 0.68/0.58, 0.2 ms) | -| `test/batch3.test.ts` | SIM a–f (redaction by meaning, state lines, "back to V", item diffs, slug ids, pending-local-change fact); `transient` after `unusual`; lifecycle guarantees | -| `test/budget.test.ts` | section limits (1,100: 6/2/3/3/1, 2,000: 9/4/9/5/2, 3,200: 12/6/16/8/4; 500 = 1,100); compact questions (≤ 24-char overrides kept); byte-identical determinism; auto budgets webgpu 3,200, wasm 1,000 / 1,333 / 2,000 at 1 / 2 / 4 threads (16 threads → 2,000), unknown device 3,200, a fixed number wins; `max_tokens_exceeded` shrink; hold-budget formula and `timeoutMs` of held requests | -| `test/situation.test.ts` | one situation per trigger (the STATUS examples); side-effect-free `ask` situation; shrink order; identical situations on a fake clock | -| `test/policy.test.ts` | §8 gate: summed mass, tiers, thresholds, deny/allow, pause, rate limit, observe never holds, fail-open while loading, detection threshold | -| `test/smoke.test.ts` | atoms apply synchronously when not salient; context through awaits; stale write held and discarded in guard mode | -| `test/smoke/smoke.sh` | packed tarball installs into Vite 8, builds, loads in headless Chromium with devtools, ≥ 3 events, no console errors (`model: false`) | +| `test/default-mode.test.ts` | no `mode` → `observe` (`createRuntime` and `GenClass.init`); `?genclass=guard` / `mode: "guard"` opt in; never holds writes or requests even when the model is sure; findings still reported | +| `test/delivery.test.ts` | typeahead zero calls; stale out-of-order response → `discard` drops only the newer-data field; holding is only latency; no hold when the model cannot answer in time; WebSocket order; EventSource; XHR holds and `abort()`; salience rules | +| `test/no-reorder.test.ts` | realworld's promise middleware through `genclassEnhancer` with an always-passive model: guard/heal give the same dispatches and final state as observe | +| `test/content.test.ts` | F1, F2 (diff preview), F3, F5, F6, F7, F8, F9, read-your-writes | +| `test/atoms.test.ts` | runs with `holdWrites: true`: a user write never overtakes an earlier held write; read-your-writes | +| `test/nan.test.ts` | a `NaN` store value no longer recurses forever | +| `test/review-*.test.ts` (10) | REVIEW's batch-3 findings; must pass unchanged. `review-perf` times 5,000-item stores (run alone; CI retries it twice) | +| `test/batch3.test.ts`, `budget.test.ts`, `situation.test.ts`, `policy.test.ts`, `smoke.test.ts` | redaction by meaning, section limits and auto budgets (2,400 on WebGPU), one situation per trigger, the §8 gate, smoke paths (explicit `mode: "guard"`) | +| `test/model/*.test.ts` | 14 model-parity tests skip without `GENCLASS_MODEL_DIR` | +| `test/smoke/smoke.sh` | packed tarball in a Vite app in headless Chromium with `model: false` (ask before running) | +| `sim` (`SIM_RUNTIME=real npx vitest run`) | 19 tests, 5 files, against the built runtime | +| `training/tests/test_curriculum.py` | the v2 curriculum test (passes per the situation reviewer; not run by the lead) | + +Not run by us: Playwright specs, `smoke.sh`, realapps sweeps, demos eval, Python tests, training. `realapps/` has no +tests at all. ## Drift and open issues -### Open issues by owner (as of 654d822, verified in code where marked) - -| owner | issue | source | state in code | -|---|---|---|---| -| CORE | **Held writes land after a newer user write.** User-sync writes bypass the store queue and apply at once; an earlier held write later re-runs its updater on top and overwrites the user's change. Board: jump-backs 3.07 → 4.80 per session, 0 actions | demos/NEEDS §1 | open: `state/hub.ts` -> `StoreHub.propose` (`bypass` → `commit` immediately) | -| CORE | **Holds cost latency** when the model is slower than the budget; decision requests queue one at a time; superseded requests are not dropped | demos/NEEDS §2 | open: `RuntimeImpl.trigger` holds whenever an action is permitted; `DeciderQueue` has no supersede logic | -| CORE | **`retry` offered for non-idempotent requests** (duplicate orders after a 502/504 that committed) | demos/NEEDS §5 | open: `builtinApplicable` → `replayable && attempt < 4 && fetch` (no idempotency check). `req.idempotent` (from `util.ts` -> `IDEMPOTENT_METHODS` = GET, HEAD, OPTIONS, PUT, DELETE, TRACE, set in `observe/fetch.ts`) gates only `hedge` among actions; the model sees it only as the request fact "POST is not idempotent; …", and the `retry` description says nothing about idempotency | -| CORE | Observe `EventSource`/`BroadcastChannel` messages as ops | demos/NEEDS §6 | open: no reference in `src/` | -| CORE | Keep observing synthetic DOM events | demos/NEEDS §7 | satisfied (no `isTrusted` filter), except: any event while a non-user op's code is running, untrusted events while a non-user op is ambient (`observe/dom-user.ts` -> `programmatic`), and events inside `[data-genclass-ignore]` (`ignoredEvent`) | -| CORE | In-place mutation detection is best effort (8 sampled elements/values) | STATUS Open issues | open by design | -| CORE | Situation budget assumes 3.2 chars/token; measured 2.4 | training/NEEDS 6a | open: `STATE_CHAR_BUDGET` = 3200 unchanged; TRAIN trains with `max_len` 2048 | -| CORE | `rollback` description ("last consistent snapshot") does not match transition/error effect (chain revert) | code reading | open; fixing it changes model input | -| CORE | Fact "could not be held: the update changed the stored value in place" is unreachable (unholdable writes commit in `propose` without gating) | code reading | open | -| MODEL | Device-based model selection in the host card | OPEN_TASKS 5 | not started: `model/loader.ts` -> `parseCard` reads one model's variants (`q8`/`fp16`) per card; `planOrder` picks only variant and device | -| UI | Overlay ignores `Explanation.message` | UI-NEEDS 3 | CORE side done (`types.ts` -> `Explanation.message`, `runtime.ts` -> `explain`); the overlay still takes lines only from `on("report")` (`devtools/index.ts` -> `addReport`) and otherwise falls back to its own templates. See [runtime/devtools.md](runtime/devtools.md) | -| SIM | Phase B (1.4M rows) | OPEN_TASKS 1 | in progress | -| SIM | Phase A is below TRAIN's stated volume: train 448,420 (asked ≥ 1M, target 1–2M) and **dev 14,613 (asked ≥ 20k)**; test 137,643 meets ≥ 40k | training/NEEDS 1 (still OPEN) | phase B should cover train; whether dev grows is not recorded | -| SIM | Clean-run rows flagged `meta.clean: true` | training/NEEDS 4 (ASK) | not found in `sim/src` | -| TRAIN | Final rounds 1 and 2, calibration, export, parity, EVAL.md per trigger and budget | OPEN_TASKS 3–4 | round 1 running at commit time | -| DEMOS | Screenshot tour and README; evaluation with the trained model (bug rate Off/Guard/Heal, clean-run false interventions) | OPEN_TASKS 2, 6 | v0.1 numbers only | -| DEMOS | **`demos/src/server/data/cities.ts` is missing from git** (root `.gitignore` line `data/` ignores it). `demos/src/server/worlds/search.ts`, `demos/src/demos/search/scenario.ts` and `demos/src/demos/search/oracle.ts` import it, and `demos/tsconfig.json` includes `src`, so it blocks the demos build, the demos typecheck (and with it the root `npm run typecheck`, which runs every workspace's `typecheck`; inferred from the code, `tsc` not run) and the Service Worker bundle | [demos.md](demos.md#drift-and-open-issues) Drift 1 | open: `demos/src/server/data/` does not exist | -| lead | Publish `@genclass/runtime-model@0.1.0` + release `runtime-model-v0.1.0`, then `@genclass/runtime@0.1.0`; CI (build, typecheck, unit tests); honest-results docs; model card numbers; dev-only lazy devtools import | OPEN_TASKS 7–8 | not done | -| CORE / lead | A test for the shipped default path (model card 404 → status `error` → observe only, status report printed) | code reading (see Gotchas) | none exists | +### Open work (aligned with HANDOFF, OPEN_TASKS and the release recipe) -### Known risks - -- **Single-thread WASM speed** (OPEN_TASKS): hold budgets cap at 800 ms, so slow devices fail open more. Measured - (Node, 1 thread, q8): R17 188 / 339 / 608 ms and R32 499 / 879 / 1,539 ms at 500 / 780 / 1,170 tokens (`training/EVAL.md`). -- **Training-label noise** (OPEN_TASKS): costs come from K = 3 sampled futures (`sim/README.md` limitation 1); "66% of - passive-best request rows put ≥ 0.9 on passive" (in OPEN_TASKS since a53dd38, so a pre-freeze figure; phase A - `label_sharpness.request.passive_mass_ge_0_9` = 0.676, and only 0.379 of intervene-best request rows put ≥ 0.9 on - non-passive actions; `label_sharpness` is not split by train/dev/test). Diagnosis and action are labelled independently: - "expected → coalesce" is about 11% of request rows (`sim/README.md` limitation 3); the runtime's diagnosis gate - keeps those passive. -- **Thin classes** (OPEN_TASKS): in SIM phase A train, `diagnosis_by_split_trigger` counts `conflict` 10,204 and - `unusual` 1,049 of 291,031 diagnosis labels, and `transition` is 12,360 of 341,204 non-`ask` rows - (`sim/samples/stats-final-a.json`). -- **Hold-induced harm and triage sensitivity** (OPEN_TASKS 6, demos/NEEDS §1–§2), all with v0.1: - - Board, guard mode, no interventions: OPEN_TASKS and `demos/results.md` say 9 bugs introduced vs 1 fixed. demos/NEEDS - §4 attributes most of that to the mock server's single random stream. The corrected traced run (common random - numbers) shows 5 introduced / 3 fixed and +56% visible jump-backs (§1). - - Search, clean runs: `demos/results.md` user-latency p50 14 ms (Off) → 125 ms (Guard); demos/NEEDS §2 (final - results, calm typist, 15 seeds) 6 ms → 389 ms, with 127 of 148 result writes held (median 543 ms). - - Typeahead is salient about 6 times per clean trial (OPEN_TASKS 6). -- **v0.1 is not a runtime model**: `unusual` for 6,328 of 6,386 decisions, never `expected`; 0 false interventions only - because it rarely clears thresholds in time (demos/NEEDS §8). -- **Paired demo results with v0.1** (`demos/results.md` summary table, 30 chaos seeds, fixed / introduced vs Off): - Guard: search 0/0, editor 1/1, checkout 0/2, status 2/0, board 1/9, decisions 3/5; Heal: 0/0, 0/1, 0/2, 0/0, 2/9, - 2/5. False interventions on clean runs: 0 in every demo and mode. These predate the mock-server fix (demos/NEEDS §4). -- **Stage 1 does not transfer to SIM labels**: zero-shot on SIM's 123-row sample ≈ 50% action accuracy and 18–34% - heal-mode false interventions (`MODEL_CARD.md`, `training/LOG.md`); the shipping model must come from the final rounds. -- **R17 vs R32 precision off the runtime-exact format**: on varied surface styles (`cur1/test`) heal FIR is 1.70% - for R17 (stall 11.5%) vs 0.60% for R32 (`training/EVAL.md`). Relevant to OPEN_TASKS 5 (ship R17 for WASM). -- **Stage-2 pilot was precise but timid**: heal recall 1.3% (R32) / 1.4% (R17) on pre-freeze soft labels; final rounds - use sharper labels. +| owner | item | state | +|---|---|---| +| SIM (Mehar) | v2 gold ≥ 10M and unlabeled ≥ 50M on 20 nodes | running; budget skew (SIT-2) and unlabeled `expected` labels (ST-1) affect it | +| REAL (Mehar) | v2 production `v2b1`–`v2b3` (≥ 500k gold), copy to `train:/data/real-out/` with the eval set | running; see RA-* before using the data | +| TRAIN | import v2 SIM/REAL data (`import_final.sh` cannot read the v2 gz-shard layout, ST-8), T150 teacher on gold (PLAN P1), teacher eval as the separation gate (P2), soft-label unlabeled rows (P3), distil R17/R32 (P4), DAgger ×3 (P5), EVAL per trigger/budget/held-out set, calibration, export, parity | not started; several scripts untested (ST-2 to ST-7) | +| lead / user | `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`; rerun demos; `@genclass/runtime@0.1.0` without the alpha tag | after EVAL | +| user | publish `0.1.0-alpha.1` (2FA; npm 11 needs `--tag` for a prerelease per build-test-release.md). Decide which tree it is cut from: the NaN fix alone, or `mvp-v2` with situation-v2 and the observe default | waiting | +| user | push `mvp-v2` (first CI run), merge into `runtime`/`main`; public demo hosting | waiting | +| Mehar / user | re-enable the Azure auto-shutdown schedules when the push ends; deallocate idle nodes | open | +| CORE | review findings DL-1…DL-12 (behaviour) and SIT-1, SIT-3, SIT-8, SIT-10, SIT-11 (model-visible text) | open; see [How to change it safely](#how-to-change-it-safely) | +| SIM / REAL | SIT-2 (budget weights), ST-1, ST-6, ST-9…ST-11, RA-1…RA-12 | open | +| TRAIN | `rt.py` parity SIT-4…SIT-7, SIT-9, SIT-12, SIT-13; scripts ST-2…ST-5, ST-7, ST-8 | open | +| CORE | `retry` still offered for non-idempotent POSTs (heal tier; `builtinApplicable` checks only `replayable && attempt < 4 && fetch`) | open (demos/NEEDS §5); SIT-11 makes it worse for 502 | +| CORE | `rollback` description ("last consistent snapshot") vs chain revert; unreachable fact "This write could not be held: …" (`StoreHub.propose` commits unholdable writes without observing them) | open; the first is model input | +| CORE / lead | a test for the shipped default path (model 404 → `error` → observe only) | none exists | +| MODEL | device-based model selection in the host card | not started | +| UI | overlay ignores `Explanation.message` (`devtools/index.ts` has no `.message` use) | open | +| DEMOS | rerun with the trained v2 model (Off/Observe/Guard/Heal, clean-run FIR); commit `cities.ts`; pass `untrustedEvents` for the synthetic driver (DL-11) | open | +| docs | HANDOFF default mode, CONTRACT v2 deltas and redaction rule, ARCHITECTURE budget, stale NEEDS items (SIT-14, table below) | open | ### Decisions waiting on the user / repo owner -Recorded in `OPEN_TASKS.md` "Needs the user": -1. **Public demo hosting** (GitHub Pages on this repo): OK to publish? Open. -2. **Merging `runtime` into `main`.** `main`, `origin/main` and `origin/runtime` already point at 654d822, so this looks - done; the owner should confirm and remove the item. +1. `0.1.0-alpha.1`: publish (2FA) and from which tree. +2. Push `mvp-v2`, merge into `runtime` and `main` (`main` is still 654d822; the old "looks merged" note no longer holds). +3. Public demo hosting (GitHub Pages). +4. Which review fixes land before vs after the running v2 generation (SIT-2, ST-1 and DL-2 affect data being produced + now), and whether text-changing fixes justify `situation-v3`. +5. Shipping models: R17 default on every device (RESULTS §2 decision for v1); R32 for WebGPU only if clearly better. -Pending lead/owner decisions inferred from NEEDS and OPEN_TASKS (not recorded as user questions): -3. Ship R17 only, or R32 for WebGPU "only if clearly more accurate" (OPEN_TASKS 5). -4. Whether to change the frozen runtime for demos §1/§2 (behaviour only) or §5/§6 and the `rollback` description - (model-visible text, so new data and retraining). -5. Whether to rebudget situations by real tokens (training/NEEDS 6a). -6. VM access (hosts file, SSH key) for new agents. Partly settled on 2026-10-07: the lead allows the light checks (install, - typecheck, build, runtime unit tests) locally on other machines. Heavy jobs still need the user's go-ahead and a place - to run: sim, training, Playwright, model runs, demo eval. +### Known risks -### Doc drift: `docs/runtime/API.md` vs `src/types.ts`, `src/index.ts`, runtime +- **The v2 data run carries known defects.** SIM samples budget 3,200 for ~40% of trajectories (SIT-2); unlabeled rows + keep `expected` labels that S1 would flip (ST-1, fixable by a relabel pass); delivery-discard semantics under review + (DL-1, DL-2) shape the counterfactual costs. Filtering or relabelling is cheaper than regenerating; decide before + training starts. +- **The teacher may not separate the cases.** PLAN-v1: if T150 is also near 40% argmax on clear rows, the bottleneck + is the situation information, not model size. v1 → v2 separability improved but is far from solved (RESULTS §3: + linear recall at 1% FIR 6% → 11% on failure, 11% → 15% on request). +- **Targets not met by any model yet:** diagnosis ≥ 95% (v1: 90.5%) and clear-case recall ≥ 80% (v1: 7.7% guard on + clear stale/duplicate). Guard FIR ≤ 0.1% and ECE ≤ 0.02 were met in v1. +- **Curriculum ≠ runtime.** `rt.py` is called runtime-exact but diverges on several common cases (SIT-4…SIT-7, + SIT-9, SIT-12, SIT-13). +- **Never-worse evidence is narrower than claimed.** The 0/396 sweep compares final visible text and server content + only, covers 66 of 91 apps, and never compares observe against no runtime (RA-1, RA-6, RA-10). Under chaos, 3/198 + runs changed from request-time holds (RESULTS §4). +- **Single-thread WASM speed**: R17 ≈ 177 / 323 / 589 ms at 500 / 780 / 1,170 tokens (RESULTS §2); hold budgets cap at + 800 ms, so slow devices fail open more. +- **Label noise**: costs come from K = 3 sampled futures; S2 re-draws unobservable latents but not for impatient + re-clicks (ST-6). +- **Cost and operations**: auto-shutdown disabled; label/eval scripts can mark work done after failures (ST-2, ST-4); + a crashed Chromium drains a REAL worker's queue (RA-2). +- **Stale npm alpha**: users who install today get guard default, v1 situations and the NaN crash. +- **Privacy**: the F2 fact leaks redacted text (SIT-1) and the leaf redactor regressed on numbers/arrays under + secret containers (SIT-3 in the table, "low"). + +### Review of the situation-v2 work (2026-10-08) + +Five reviewers checked `git diff 654d822 b435acb` by area (delivery, situation, sim-train, realapps, project docs), +with adversarial verification; findings marked "test" in their summaries were reproduced with temporary vitest files +(deleted) or pure-Python probes. No source file was edited by the review. **52 confirmed findings; the uncertain list +is empty** (one confirmed finding, DL-12, was not verified in a real browser). Area verdicts in one line each: + +- **Delivery:** the common path is sound (uncontended deliveries released synchronously, channel order kept, atom + discards drop only the stale field); the edges are weak. +- **Situation:** deterministic; the worst problems are two redaction regressions and the SIM budget; `rt.py` + diverges from the frozen renderer in several common cases. +- **Sim-train:** RNG streams, commit posterior and prefix check hold; the sim pins `heal`, so the observe default does + not affect it; labelling/eval scripts can report success after failures. +- **Realapps:** virtual time, keyed draws and labels mirror the sim; headline sweep claims say more than the code + measures; eval-set and manifest problems. +- **Project docs:** HANDOFF says guard is the default. + +#### Delivery (runtime network-boundary path) + +| id | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| DL-1 | high | `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter` | Delivery `discard` is a silent no-op on redux/zustand stores, but the `ActionRecord` claims the writes were dropped. Guard, redux `{items, loading}`: a newer op writes `items=['pushed-newer']`, the stale response dispatches `LOADED {items:['v2']}`; final state `['v2']`, record says "dropped the state changes it makes over newer data (list.items)" with `dropped: []`, and no mutation decision follows. The atom variant ends correctly with `['pushed-newer']`. | Apply the kept changes as a patched whole value through the store's `io.set` (redux `GENCLASS_REPLACE`, zustand `outer(v, true)`); else report honestly (ok:false or a reason, `op.delivery.overNewer`, leave `decided` false so the mutation trigger can decide or late-revert). Build `changed` from `mark.dropped` after the fact. Add redux and zustand variants of the discard test. | +| DL-2 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter` / `RuntimeImpl.writtenOver` | A discard mark drops the fresh writes of later ops chained from the discarded op (polling chains, sagas) for 10 s. Guard: stale poll p2 is discarded, its handler schedules the next poll; p4 (cause chain p4 → timer → p2) returns fresh `v=103` and is dropped ("dropped the write of doc.v by GET /api/doc?slow=0&p=4 (#10) over newer data"); `loading`/`status` fields can stick. | Scope the mark to the discarded response's own writes: stop the cause walk at the first op with its own `delivery` record (`if (x.delivery && !x.discardMark) return null`), or compute `writtenOver` against the nearest network op. Regression test with a `setTimeout`-chained poll. Decide with Mehar whether it lands before or after the current v2 generation. | +| DL-3 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` | Observe mode (the new default) still holds deliveries: up to 100 ms waiting for the body, and XHR/WS listeners run outside the original dispatch. Measured: network answered at +500 ms, the app's fetch resolved at +600 ms, same as guard; an observe-mode XHR `readystatechange` ran with `inDispatch=false` and `load` saw `currentTarget=null`. | At the top of `runDelivery`, check whether a hold is possible (`permittedActions(this.policy, this._mode, TRIGGER_ACTIONS.delivery).length > 0 && this.expectedLatency() <= this.holdBudgetMs()`); if not, `rel()` synchronously first and do body analysis and the background trigger (F9 marks, detection) without holding. Default-mode tests for fetch and XHR with a conflicting delivery and a slow body. | +| DL-4 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` / `runDelivery` `ctl.stale` | Background (non-held) delivery decisions are always dropped as stale: delivery standing questions are never answered in observe mode, and every salient delivery's situation is built for nothing. `rt.question({ on: ["delivery"], always: true })` + one fetch: 0 answers in observe, 1 in guard; with triage `always`, observe decisions are `request`/`mutation`, never `delivery`. | Pass `stale` only for held submissions (`waits ? stale : undefined`), or skip building the situation when it will not be held and no standing question forces it. If background delivery decisions are kept, mark the writes covered when the decision lands. Correct "every trigger is decided" wording in docs/agents. | +| DL-5 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` `ctl.run('defer')` / `waitOps` | `defer` can hold a response, or a whole WS/SSE channel, for 20 s regardless of the hold budget (`waitOps` waits up to `LONG_RUNNING_MS` = 10 s per defer, at most 2 defers). Guard, WS `/live`, a long-poll `GET /api/feed` in flight, model answers `defer`: message delivered at +20,000 ms; every later message on the socket waits too. | Bound a delivery defer by the hold budget (`waitOps(related, Math.min(LONG_RUNNING_MS, k * this.holdBudgetMs()))`); offer defer only when related ops are expected to finish soon; for push channels do not offer it while messages are queued behind (`queuedAhead`), or cap it more tightly. | +| DL-6 | medium | `packages/runtime/src/observe/messages.ts` -> `MessageGate.pump` | Held WebSocket/EventSource messages are dispatched after the app called `close()`. Guard, triage `always`: held message, app calls `ws.close()` (readyState 2), decision releases it: the listener receives `{"n":1}` with readyState 2. | Before dispatching a queued `MessageEvent`, check `readyState`: drop when a WebSocket is not OPEN (1) or an EventSource is CLOSED (2); end/emit the op as dropped; still dispatch queued close/error events. Or wrap `close()` to flush or drop the queue. | +| DL-7 | medium | `packages/runtime/src/state/hub.ts` -> `StoreHub.gateAndQueue` / `StoreHub.flushQueue` | `holdWrites` (opt-in): a held write applied early by `flushQueue` flips back to state `resolved`; a late discard is then recorded as a drop while the write stays applied. Policy `{holdWrites:true, holdBudgetMs:100}`: record reads "Dropped the write to a.v from task bg (#1); a stays at version 2." with nothing reverted. | In `gateAndQueue`'s `held.then` and its `catch`, return early when `m.state === "done"`; make `proceeded` robust with `m.outcome !== undefined`. | +| DL-8 | low | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter` (via `StoreHub.propose` -> `applyFilter`) | Discard marks keep dropping app writes after `rt.pause()` and `setMode("observe")`. Guard: stale response discarded, its handler applies data 500 ms later; pause (or observe) in between: the write is still dropped. | Return null from `dropFilter` when `this.paused \|\| this.destroyed \|\| this._mode === "observe"` (or call `applyFilter` only when gating); clear active `discardMark`s in `pause()`, `destroy()` and `setMode("observe")`. | +| DL-9 | low | `packages/runtime/src/observe/eventsource.ts` -> `installEventSource` / `MessageGate.ensure` | EventSource `open` is not order-kept behind held messages, and the re-dispatched error clone reports a spurious channel "down". Triage `always`: open, message (held), error (queued), open: the app saw `open, open, message, error`. | Queue `open` with the orderOnly handler (like close/error); in the raw open/error/close listeners ignore the gate's own re-dispatched copies (expose `gate.isMine(e)`). | +| DL-10 | low | `packages/runtime/src/observe/xhr.ts` -> `installXHR` -> `gateCall` / `arrive` | XHR completion listeners run after the event's dispatch ended (`e.currentTarget === null`): `(e) => JSON.parse(e.currentTarget.responseText)` throws a TypeError for a held XHR (guard) or in observe mode with a conflict. | Invoke queued listeners with an event whose `currentTarget` is the xhr (Proxy, or `Object.defineProperty(ev, "currentTarget", { value: xhr, configurable: true })` plus `eventPhase` 2), or re-dispatch fresh events as `MessageGate` does. | +| DL-11 | low | `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` -> `programmatic` | `untrustedEvents` defaults to false, so the demos site's in-page synthetic driver now records no user actions; decisions diverge from the Playwright driver for the same script (regresses demos/NEEDS §7). | Pass `observe: { untrustedEvents: true }` from the demos' `startGenClass` when the synthetic driver is used (or always on the demo site); update the `programmatic` comment. | +| DL-12 | low | `packages/runtime/src/observe/messages.ts` -> `MessageGate.intercept` | (Not verified in a browser.) A capture-phase WS/SSE message listener (`addEventListener('message', h, { capture: true })`) sees a held message twice: at arrival and at release. | Register the interceptor with `{ capture: true }` (it still runs first), or wrap `addEventListener` for message types as `xhr.ts` does. | + +#### Situation format, redaction and the curriculum port + +| id | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| SIT-1 | high | `packages/runtime/src/situation/content.ts` -> `contentFacts` | The F2 fact prints the raw text of redacted fields (bypass via `stringDiff`). Store `settings = {apiKey: "sk_live_AAAA…"}`, an autosave PUT in flight, the user types into the key field: every other section shows `settings.apiKey = [redacted]`, but the first fact quotes `"…AAAAAAAAAAAAAA SECRET99" → "…AAAAAAAAAAAAAA" (removes " SECRET99")`. Same with a custom redactor hiding a PII free-text field. | Use `stringDiff` only when both values pass the redactor unchanged (`Object.is(env.redact(c.path, c.current), c.current) && Object.is(env.redact(c.path, c.incoming), c.incoming)`), or route through `changeText({path, before, after}, env.redact)`. Tests with a sensitive key and a custom redactor. Changes model-visible text only for redacted fields. | +| SIT-2 | medium | `sim/src/world/scenario.ts` -> `budget` | SIM still samples the v1 3,200-char budget for 40% of trajectories while v2 data is generated on Azure (`[[3200, 40], [2000, 30], [1000, 30]]`). Measured: `toJevState(p, 3200)` 3,010 chars vs `toJevState(p, 2400)` 2,198 for identical parts; ~35% more tokens in teacher labelling and distillation, and R17/R32 train on longer sections than production shows. | Use the v2 device budgets, e.g. `[[2400, 35], [2000, 20], [1667, 5], [1333, 5], [1000, 35]]` (= `rt.py` `BUDGETS`), fix the JSDoc, tell Mehar before more v2 shards are produced; existing shards can be filtered by `meta.budget == 3200`. Optionally clamp `toJevState` to `STATE_CHAR_BUDGET × budgetScale`. | +| SIT-3 | low | `packages/runtime/src/util.ts` -> `isSensitivePath` / `defaultRedact` | The new leaf-based default redactor no longer redacts numbers or arrays under secret-named containers (regression vs 654d822): `defaultRedact("payment.cvv.value", 123)` → 123, `("login.otp.code", 123456)` → 123456, `("lock.pin.value", 1234)` → 1234; `account.password.history` arrays likewise. They then appear in state lines, deltas, timeline and facts. | Under a strong (non-broad) secret container, redact every non-boolean, non-null value (strings, numbers, bigint, arrays) before the early return that should only short-circuit the broad-container opaque test. Add the cases to `test/review-redaction.test.ts`. Model-visible. | +| SIT-4 | medium | `training/curriculum/rt.py` -> `request_common` | `rt.py` adds a "Recent … outcomes" fact to every failure situation; the runtime never emits it for failures. Probe over 3,000 seeds: 479 of 479 runtime-style failure rows, e.g. "Recent GET /api/v2/listings outcomes: 500, 503, 503, 503, 503." | `elif outs and trigger == "stall":`; add a parity assertion to `test_runtime_rows_situation_v2` that failure rows have no such fact. | +| SIT-5 | medium | `training/curriculum/rt.py` -> `compare_field` / `change_text` / `_json_str` | Long-text summaries skip the runtime's F2 and diff-centred paths, so autosave rows get F1 "put back" wording instead (68 of ~6,000 delivery and 25 of ~3,000 mutation rows); timeline lines show `A → B` instead of the diff preview. The model trains on the wrong wording for the main F2 case. | Let long-text scenarios carry the real strings so summaries are JSON string literals and `string_diff` runs (mirror `describe(…, 48/40)` truncation); at minimum treat summaries starting with `"` as strings in `compare_field`. | +| SIT-6 | medium | `training/curriculum/rt.py` -> `event_lines` / `to_state` / `in_flight_lines` | `rt.py` keeps the last N timeline events; the runtime keeps relevant events first (and orders mutation in-flight lines by the cause). Probe: in 549 of 2,949 runtime-style rows (~19%) a relevant event (often the causing user action) was dropped while an irrelevant noise request was kept. | Return `(line, relevant)` pairs with the runtime's relevance rule (user, error, subject chain, same sig, same root, signatures that wrote the involved stores), select relevant-first with a seq re-sort, pass `spec['cause']` as the in-flight subject for mutations. | +| SIT-7 | medium | `training/curriculum/rt.py` -> `event_lines` / `mutation_facts` / `content_facts` | `rt.py` renders no-op writes (`A → A`) the runtime never logs or gates: 224 of 2,949 rows (7.6%) have a no-op timeline write; 43 mutation rows have an F3 "has the current value" fact with `X → X`; 33 have "is back to" facts driven by no-op writes. | Skip writes whose summary equals `value_before` (timeline, moved facts, version counts); `render()` returns None for a mutation whose `after` equals the current value of every path (F3 "changes nothing" belongs to delivery only). | +| SIT-8 | medium | `packages/runtime/src/situation/content.ts` -> `contentFacts` / `compareField` | "…nor the value when #X started" is asserted without checking it; false when X's own chain wrote first. `card.status = "idle"`; Refresh starts a slow fetch, the handler sets "loading", op `push` sets "ready", the response has "idle": fact says "neither the current value "ready", nor the value when #4 started", but it was "idle" then. | Append the clause only when `vhash(c.start.value) !== vhash(c.incoming)`; otherwise say ", the value it had when #X started". Mirror in `rt.py` `content_facts`; add the repro as a test. Model-visible. | +| SIT-9 | low | `training/curriculum/rt.py` -> `request_common` / `stats_lines` / `secs` / `ratio` | `rt.py` rounds the usual request rate to 2 decimals; the runtime's `fmtNum` prints 4 below 1 ("usually 0.33 per 10s" vs "0.3333"), in 102 of 598 request rows and 15 failure rows, plus "(usual 0.33)" stats; also JS/Python tie-rounding differences. | Drop `round(usual, 2)` in both places; optionally round half-up (`decimal` `ROUND_HALF_UP` or `floor(x*10^d + 0.5)`) to match JS `toFixed`/`Math.round`. | +| SIT-10 | low | `packages/runtime/src/situation/content.ts` -> `createdIds` / `rywFacts` (fed by `runtime.ts` -> `noteResponse`) | Every successful POST JSON response is recorded as a "create": `POST /api/search` returning items makes a later paginated `GET /api/products` get the non-neutral fact "… created item "7" …, and does not contain it", pushing toward inconsistent/resync. | Count as a create only a 201, or a POST whose single returned object's id is not already in any store; drop the array case unless 201; or word it "returned item". Model-visible. | +| SIT-11 | low | `packages/runtime/src/situation/evidence.ts` -> `commitAmbiguity` / `NOT_PROCESSED` | The commit-ambiguity fact says HTTP 502 is "usually returned without processing the request". A proxy 502 after the app server committed an order pushes toward `retry` and a duplicate order; 500/504 are correctly ambiguous. | Remove 502 from `NOT_PROCESSED` in `evidence.ts` and `rt.py` (falls through to the 5xx "may have applied it" branch), or weaken the wording. Model-visible. | +| SIT-12 | low | `training/curriculum/scenarios.py` -> `mut_live` | The live-update scenario uses bracket paths the runtime never produces: ~3.4% of runtime-style rows show `board.cards[46095] = …` and "messages like it last wrote board.:id." | Use dotted paths (`f"{store}.{coll}.{cid}"`) in `mut_live` and any other scenario that builds bracket paths. | +| SIT-13 | low | `training/curriculum/rt.py` -> `state_lines` | `rt.py` prints `(vN)` with no writer or age for initialised fields (~2% of rows, e.g. `current.value = {id: pedalshare-518} (v1)`); the runtime always adds the age. | Give `init_field` a timestamp (and optionally a writer) and render ` (v{v} {secs(now - t0)} ago)` or ` (v{v}, by #{op} …)`. | +| SIT-14 | low | `docs/runtime/CONTRACT.md` -> `redact` option (§2) | CONTRACT still documents the old substring redaction rule; an integrator assumes `cardInfo.digits` is redacted (it is not: words "card", "info", leaf "digits" do not match) and ships without a custom redactor. | Describe the leaf-name/word rule, secret pairs, strong vs broad containers and the opaque-string rule in CONTRACT (and docs/agents); recommend a custom redactor for app-specific secrets. | + +#### Sim labelling and training scripts + +| id | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| ST-1 | high | `sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`; `training/label_teacher.py` -> `main` | Unlabeled rows hard-label `expected` diagnoses that S1 would relabel, and `label_teacher` keeps them, undoing S1 on 5× more data. A stale overwrite where `discard` wins: gold says `stale`, five unlabeled look-alikes say `expected`; the distilled student pushes P(expected) up and the guard/heal gate (`requireDiagnosis`) refuses to fire. | S1 only turns `expected` into non-`expected`, so in unlabeled mode omit the hard diagnosis label when it is `expected` (keep it in `meta.diagnosis`) so the teacher labels it; or add `--overwrite-qids diagnosis` to `label_teacher.py`. No regeneration needed: a one-line relabel pass over the collected shards can drop `labels.diagnosis` where it is `expected`. | +| ST-2 | medium | `training/label_cluster.sh` (remote `/tmp/label-$OUT.sh`) | Touches the done marker unconditionally and cannot read the collected `.jsonl.gz` shards: every node labels 0 rows but `.label-<OUT>-done` appears within minutes; students then launch on a missing/empty bucket. A teacher-tar 404 also ends "done" after nodes were billed. | `set -euo pipefail`; fail if the teacher tar or model dir is missing; per-shard `.ok` on exit 0 and the done marker only when every assigned shard has one; accept `*.jsonl.gz` (gzip streaming in `label_teacher.py`, or `zcat`) with one pattern for list and glob. | +| ST-3 | medium | `training/label_cluster.sh` | No split filter and no gather step: test/dev shards of an unlabeled run get teacher labels and stream as training data (held-out feature/domain metrics contaminated); students on c02–c09 stream an OUT bucket that holds only their own node's shards, or none. | Select only `train-*` shards (assert `split == "train"` per row in `label_teacher.py`); add a gather step that pulls `data/s3/$OUT/*` from every node to the workbench and redistributes, or document that SRC_DIR must hold train shards only. | +| ST-4 | medium | `training/final_post.sh`; `training/eval_sim.sh` | `final_post.sh` hard-wires the situation-v1 eval set (`eval_sim.sh simAe`, `out/cal/<M>-simAe.json`) and skips failures, so a v2 model would be calibrated and exported on v1 situations; a crashed shard eval leaves partial merged records. | Make the eval-set name a required argument (EVAL=simv2e) and assert the eval rows' situation version; `set -euo pipefail`; check each shard record file exists and is non-empty before merging; no `.post-done` or served tar unless the export's card and sha256 check pass. | +| ST-5 | medium | `training/eval_runtime.py` -> `get_records` / `main` (tag) | Cached eval logits are keyed only by checkpoint and data names: a step-1,000 progress eval of `r17-v2` is reused after training finishes, so final metrics, dev-fitted temperatures and the exported calibration come from stale logits. | Add a checkpoint fingerprint (step, or mtime/sha of the weights) and a data fingerprint (row count + hash of the first ids) to the cache key or record header and invalidate on mismatch; at minimum have `eval_sim.sh` delete `out/records/${M}__${NAME}*` before collecting. | +| ST-6 | medium | `sim/src/run/latent.ts` -> `idealRepeatSkips`; `sim/src/run/runner.ts` -> `runScenario` | The S2 hidden-intent re-draw has no effect on impatient (conditional) re-clicks: the ideal run's `cond` is always false. A re-click 1.2 s after a pending submit (`REPEAT_PRIOR(1200)` = 0.2 accidental): ~80% of futures draw "intended", yet the ideal run still skips the click, so `coalesce`/`block` looks free and S1 rule b labels `duplicate`. | In ideal runs bypass the `cond` check for steps whose idealSkip entry is false (they fired in the base run); add a `latent.test.ts` case that an intended conditional re-click changes the ideal run. | +| ST-7 | medium | `training/launch_student.sh` (argument parsing / `INIT_ARGS`) | Fails whenever INIT is omitted: under bash 3.2 (Mac) the empty array is unbound (`INIT_ARGS[@]: unbound variable`) after the prune loop already ran over ssh on 12 nodes; with `-- --gain-loss 1.0` and no INIT, `--` is taken as INIT and every rank dies on `--init-from --`. (Reproduced locally with bash 3.2.) | Parse positionals up to `--` explicitly (INIT = 6th positional only if it is not `--`); expand with `${INIT_ARGS[@]+"${INIT_ARGS[@]}"}`; optionally `#!/usr/bin/env bash` and a version check. | +| ST-8 | low | `training/import_final.sh` | Cannot import the v2 SIM layout and is destructive on failure: it wipes `data/simv2`, the `train.jsonl` curl 404s, nothing is imported; the FILES override is broken; the tar duplicates all of `data/s3` and can fill the workbench disk, leaving a truncated tar served on :8799. | A v2 importer: pull gz shards (verify against `manifest.json`), stream train shards into `data/s3/<NAME>/`, sample eval sets from test/dev; download to a temp dir and swap on success; tar only `data/s3/$NAME` or let nodes pull per bucket. | +| ST-9 | low | `sim/src/gen/trajectory.ts` -> `generateTrajectory` (diagnosis-only rows) | On-policy diagnosis-only rows reuse the gold id prefix and carry no `on_policy` flag: ~3 per on-policy trajectory are counted as gold-policy rows, and id-keyed joins (`eval_gain` loads rows by id) can pick the wrong row. | Use the same `${onp ? "p" : "sim"}` prefix and add `on_policy: true` to their meta in on-policy mode. | +| ST-10 | low | `sim/src/run/rt.ts` -> `createOptions` | On-policy (DAgger) runs act in heal mode while the shipped default is observe and the precision target is guard: 1–5M rows per round follow heal-tier actions guard users never trigger, so guard FIR/recall on them do not reflect the guard deployment. | Add `--on-policy-mode guard\|heal` to `gen.js` (default guard) and record `meta.policy_mode`. | +| ST-11 | low | `sim/src/run/runner.ts` -> `makeWebSocketClass` | Re-drawn socket-drop windows can be reordered, and the socket schedules only the first later window in array order: with A re-drawn to t+9 s and B to t+5 s, only A closes the socket while offline/online and the server act as if B had, so websocket-reconnect labels in that future come from an inconsistent world. | Sort re-drawn windows by start in `futureProfile`, or schedule the earliest `w.start > now`. | + +#### Realapps (REAL corpus and never-worse harness) + +| id | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| RA-1 | medium | `realapps/src/harness/debug.ts` -> `--interference` block | The interference sweep does not compare requests, bodies, stores, errors or run health, so "0/396 (same requests, bodies, server state and DOM)" overstates what was measured: a held delivery that resets an `<input>`, an extra GET, a flashed alert, or both runs hitting an internal error (`ok=false`, empty DOM and server) all count as unchanged. | Count a run as changed if `!obs.ok \|\| !heal.ok`, or if the net sequence `[method,url,bodyKey,status,outcome]`, final stores, error episodes/writes/uncaught counts, `skippedAt` or input values (add a form-value snapshot) differ. Rerun the sweep, or reword STATUS/RESULTS/HANDOFF to "same final visible text and server content". | +| RA-2 | medium | `realapps/src/harness/browser.ts` -> `Runner.run` / `Runner.context`; `gen.ts` worker message loop | A crashed Chromium makes its worker drain the whole remaining seed queue as instant failures: an OOM-killed `headless_shell` 2 h into a 30k batch fails ~20k seeds in under a minute, `gen.js` prints "done", the node keeps running (billed) with most of the batch missing. Failed seeds are not in `done.txt`, so a rerun recovers them, but nobody is alerted. | Move `context`/`newPage` inside the try; on failure or `!browser.isConnected()` relaunch the browser and retry once; in `gen.ts` re-fork a worker after N consecutive failures and log a loud failure count to `gen.log`. | +| RA-3 | medium | `realapps/scripts/evalset.py` -> `main` (splits default) | `evalset.py` draws eval rows from `["test", "dev", "train"]` by default, so eval rows are training rows and real-app precision/recall are inflated. | Default to `test` (or test,dev); refuse `train` without `--allow-train`; regenerate existing eval sets and check the `splits` field in `manifest.json`. | +| RA-4 | medium | `realapps/scripts/evalset.py` -> `classify` | The eval set ignores the situation-v2 `delivery` trigger: none of the v2 pilot's 135 delivery rows reach `real_eval.jsonl`, so it cannot measure the network-boundary decisions v2 is built around. | Accept `t in ('mutation','delivery')` for stale-overwrite (expect discard/defer); add delivery to genuine-break and duplicate cases; report per-trigger counts in `manifest.json`. | +| RA-5 | medium | `realapps/src/world/diagnose.ts` -> `diagnose` (case `delivery` / default) | The `delivery` diagnosis has no "user changed the same field after the read started" rule: in vue-editor the autosave GET lands after the user typed in the title, discard is best, but the label is `expected` (the bucket TRAIN may down-weight), so the model learns `expected` for real stale overwrites. | For delivery, compute the chain start (min `op.start` over `p.chain(opId)`); if a user write after it touches the response's predicted paths (or, when unknown, any store the op's prior writes touched), label `stale` with why `user-changed-before-delivery`; apply the mutation branch's pending-write/read-before-write rule; re-audit `EXAMPLES.md` delivery rows. | +| RA-6 | medium | `realapps/README.md` -> APPS (`build.mjs` `apps.gen.ts`) | The sweep claims (66 apps, 0/396, 198/198 or 132/132) do not cover the current corpus: 25 wave-3 apps added afterwards (91 now) have no recorded determinism or interference sweep, yet the docs cite the numbers as covering the data. | Before a production batch includes them, run `debug.js --det 1-3 --app <25 apps>` and `--interference 1-6 --clean --app <25 apps>` (ask the user first: Chromium); update README/HANDOFF/STATUS to 91 apps with per-set numbers; record the app list (or a hash) in `manifest.json`. | +| RA-7 | medium | `realapps/src/harness/gen.ts` -> `record` / stats resume | Resume can duplicate rows and under-count stats: a node deallocated mid-batch and resumed duplicates up to ~70 trajectories (one per in-flight worker) whose rows were flushed but not marked done; `manifest.json` reports fewer gold rows than the files hold. | Append `done.txt` first with a pending marker, or dedupe rows by id on resume (ids are deterministic: `real-<app>-<seed>-dK`); recompute counts from the jsonl files for the final manifest. | +| RA-8 | low | `realapps/src/harness/gen.ts` -> `manifest` | Batch `manifest.json` hardcodes `runtime: "situation-v1 (packages/runtime/src bundled from source)"` for every batch, including v2 production, so TRAIN filtering by manifest excludes every v2 batch or mixes v1 pilot data in. | Import `RUNTIME_TAG` from `./trajectory.js` and write `runtime: RUNTIME_TAG`; patch existing manifests on c01/c10/c11 and `train:/data` (Mehar's call). | +| RA-9 | low | `realapps/src/harness/debug.ts` -> `--det` block | The determinism check only reruns the base run inside one browser context; counterfactual, future-salted and cross-worker runs are never checked, so noisy post-k behaviour (untracked native work under 70-worker load) inflates SE and softens labels unseen. | Add `--det-cf`: for a sampled decision k, run the forced counterfactual with a `future` twice on two Runner instances (separate browsers) and compare snapshots, net and server. | +| RA-10 | low | `realapps/src/harness/debug.ts` -> `--interference` block | No sweep measures whether observe mode itself (the new default) changes app behaviour: "never worse" is heal relative to observe, so an observer wrapper that changes Response timing or notification order in some framework is invisible. | Add an "off" run mode (no `__GENCLASS_INIT__`, or probe hooks only) and report off vs observe as the never-worse figure for the default. | +| RA-11 | low | `realapps/corpus/prepare_oss.sh` (`npm install` after `rm -f package-lock.json`); `node_setup.sh` | Unpinned dependencies: realapps has no lockfile and OSS apps' lockfiles are deleted, so nodes set up at different times can bundle different framework versions; `v2b1` and `v2b3` rows for the same app/seed may differ and cannot be reproduced. | Commit `realapps/package-lock.json` and use `npm ci` in `node_setup.sh`; keep upstream lockfiles or commit generated ones under `corpus/locks/<name>.json`; record `npm ls --depth=0` per app in the manifest. | +| RA-12 | low | `realapps/README.md` -> "Run it (on a VM)" | The README pins the runtime through env vars exported on the Mac, which never reach the VM build, so rows get `meta.runtime='working-tree'` (now including f3636b2's runtime changes): the leak the pinning was meant to prevent. | Put the exports inside the quoted remote command (or have `build.mjs` read `~/gcl/real-cache/runtime/current` as `node_setup.sh` does); change the example tag to `situation-v2`; make `gen.js` refuse `working-tree` unless `--allow-unpinned`. | + +#### Project docs + +| id | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| PD-1 | resolved in the working tree (pending commit) | `README.md` -> Modes / "How it works" 5; `packages/runtime/README.md` -> Modes | Both READMEs still say guard is the default; a user reading the npm README after the next publish expects guard protection from `GenClass.init()` and gets observe, which takes no action. | Mark observe as the default and guard as opt-in (heal experimental) in both, change the example to `GenClass.init({ mode: "guard" })`, add a note on the change. | +| PD-2 | resolved in the working tree (pending commit) | `OPEN_TASKS.md` -> In progress / Next | The body is stale and contradicts HANDOFF: "Final data, phase A" and "Final training round 1 on phase A" read as current work (following them spends Azure compute on v1 training), batch 4 sits under Next though done, and items 3 and 4 appear twice. | Move batches 4 and 5 to Done; replace phase A / round 1 with the v2 pipeline from HANDOFF; renumber. | +| PD-3 | resolved in the working tree (pending commit): the Loading bullet now says there is no model for this runtime yet | `packages/runtime/README.md` -> Status note | Tells users to self-host with `npx genclass-runtime fetch-model`; there is no v2 model, so they get a 404, or load a v1 model into the v2 runtime and get wrong decisions. | Remove the suggestion until `@genclass/runtime-model@0.1.0` is published, or say no compatible model exists yet. | -| # | API.md says | code does | evidence | -|---|---|---|---| -| 1 | Self-host with `npx genclass-runtime fetch-model public/genclass-model` | Default `--from` is the unpublished release `runtime-model-v0.1.0`; today it needs an explicit `--from` (e.g. the v0.1 URL) | `bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | -| 2 | `baseUrl` default "jsDelivr CDN" | Correct URL, but the package is unpublished: default init observes only | `model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | -| 3 | `model` options: `baseUrl`, `device`, `worker`, `preload` | Also `ortWasmPaths`, `cacheName` | `types.ts` -> `ModelOptions` | -| 4 | `rt.ready` resolves when ready (immediately with no model) | Rejects with the provider's error on load failure; memoised | `runtime.ts` -> `get ready` | -| 5 | `ask`/`decide` reject with `GenClassUnavailableError` | With `timeoutMs` and a failed load the raw provider error propagates; `timeoutMs` applies to the load wait and the answer wait separately | `runtime.ts` -> `ask` | -| 6 | `pause()` stops consulting the model | `ask`/`decide` still query it (no `paused` check) | `runtime.ts` -> `ask` | -| 7 | Kill switch: `localStorage.genclass = "off"`; URL `?genclass=observe\|guard\|heal` | localStorage also accepts `observe\|guard\|heal`; URL wins | `index.ts` -> `killSwitch`, `initUnsafe` | -| 8 | Outside a browser `init()` returns an inert runtime: no observers, no model | Observers off and no host, but `options.decider` is kept; `report` defaults to `"silent"` | `index.ts` -> `initUnsafe` | -| 9 | `holdBudgetMs: "auto"` = clamp(1.5 × median, 150, 800) | Plus 300 ms fallback when no latency and no `warmupMs` | `decide/policy.ts` -> `holdBudget` | -| 10 | Bodies over 64 KB never match | String bodies up to 1 MB are hashed and can match; 64 KB applies to Blob/ArrayBuffer/view/Request bodies | `observe/fetch.ts` -> `STRING_BODY_MAX`, `IDENTITY_BODY_MAX` | -| 11 | Report example "(v0 → v1)" | "(version 0 → 1)" | `situation/facts.ts`; STATUS examples | -| 12 | `situation()` returns `{ trigger, subject, state, questions, actions, salient, facts }` | Also `compact`, `budget`; returns the last situation built for that trigger if any, else the "ask about now" situation relabelled with that trigger (so `actions` is empty) | `types.ts` -> `Situation`; `runtime.ts` -> `situation` | -| 13 | Plugin facts are "added to every situation" | Only to built situations (after triage), always neutral, ranked last, may be cut | `situation/build.ts` -> `buildSituation` | -| 14 | `on("status")`: model loading progress and state | Also fired by every `setMode` | `runtime.ts` -> `setMode` | -| 15 | Type listings | Omit `UserAction.data`, `Op.meta`, `ActionDef.risk` (unused) | `types.ts` | -| 16 | Exports | Undocumented: `browserClock`, `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES`, `describeElement`, `RuntimeImpl`, default export, model errors beyond the five named (`GenClassModelError`, `ModelInputError`, `ModelUnsupportedError`, `ModelAbortedError`, `ModelDisposedError`, `ModelIntegrityError`, `ModelInferenceError`), host types; `./worker` subpath; React `GenClassProvider`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus`; Redux `GENCLASS_REPLACE`; Zustand `genclass(runtime, name, opts?)` | `index.ts`, `package.json` `exports`, `src/adapters/*.ts` | -| 17 | `observe` defaults not stated | `timers` on only when `global.document` is a non-null object; others on | `runtime.ts` -> `installObservers` | -| 18 | Trigger/action tables do not distinguish fetch from XHR | XHR: no `coalesce`; failure `retry`/`serve_cached` and stall `hedge`/`serve_cached` are fetch-only, so XHR failures and stalls are detection-only; XHR requests can still get `delay`, `block`, `serve_cached` | `situation/build.ts` -> `builtinApplicable`; STATUS deviation 2 | -| 19 | Types section lists `Decision`, `ActionRecord`, `Explanation`, `RtEvent`, `Op` | Public types a plugin or provider author needs are not listed: `SituationDraft` (input of `facts()`, `applicable()`, `ActionContext.situation`), `Fact`/`FactKind`, `RequestInfo`, `SubjectRef`, `EvaluateRequest`, full `ModelStatus` (`model`, `loadMs`, `version`, `bytes`, `fromCache`, `warmupMs`, `worker`, `workerError`, `gpu`, `attempts`, `ort`), `ChoiceAnswer.confidence` = (k·max p − 1)/(k − 1), `AdapterIO`/`AdapterHandle`, `RuntimeHooks.mutationProposed` payload, `StandingQuestionContext` | `types.ts` | - -API.md is otherwise accurate for batch 3 (summed gate, `candidate`/`mass`, `transient`, compact questions, retry -backoff `min(200 · 2^(attempt−1), 5000)`, word-level redaction, `data-genclass-ignore`). +**Uncertain findings:** none (the reviewers' uncertain list is empty). -### Recorded contract deviations (STATUS "Deviations from the contract (and why)") +### Doc drift: project and coordination files -These are accepted by CORE and listed in STATUS; CONTRACT.md was not updated. Each also appears in the table below. +| file | stale statement | reality at b435acb | +|---|---|---| +| `HANDOFF.md` ("Modes: observe → guard (default; …)") | guard is the default | `observe` (`runtime.ts`) | +| `HANDOFF.md` "Current state" | "346 tests pass"; "66 real apps"; "Push to `origin runtime` as you go" | 350 tests on `mvp-v2`; 91 apps in `realapps/` ([realapps.md](realapps.md)); our policy: ask before pushing | +| `docs/runtime/CONTRACT.md` | no `delivery` trigger (§6); §4 mutations "held until a decision arrives"; §6 budget "≤ 1,000 tokens"; §8 `holdBudgetMs` "default 300"; §2 redaction regex and observer list without `eventsource`/`untrustedEvents`; §13 default-mode entry: "`situation-v1` training data stays valid" | batch 4/5 deltas exist only in STATUS; no store-write holds by default; 2,400-char budget; "auto" hold budget; leaf-field redaction (SIT-14); the entry should say situation-v2 (mode does not change situation text: `src/situation/*` has no mode dependency) | +| `docs/runtime/ARCHITECTURE.md` | "3,200 characters on WebGPU, 2,000 with WASM threads"; redaction regex | 2,400 on WebGPU and unknown devices, 2,000 only at 4 threads (`STATE_CHAR_BUDGET`); leaf-field rule | +| `docs/runtime/API.md` | mostly current for v2; still advises `fetch-model` without `--from`; "observe … nothing is held" | the default model 404s; observe can still wait up to 100 ms on a salient delivery (DL-3). Full API drift: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#drift-and-open-issues) | +| `packages/runtime/STATUS.md` | Open issues: "`react-dom` is not a devDependency"; "Content comparison facts … not implemented yet"; never-worse "same requests, bodies, server state and DOM"; 41 files / 346 tests | `react-dom ^19.3.0` is a devDependency; F1/F2/F3 shipped in batch 5 (`situation/content.ts`); the sweep compares less (RA-1); 42 files / 350 tests on `mvp-v2` | +| `docs/runtime/RESULTS.md` §4, §6 | "0/396" never-worse; "66 → ~96 apps" | covers 66 of 91 apps and final text/server content only (RA-1, RA-6) | +| `packages/runtime-model/MODEL_CARD.md` | "`files/r17/` here"; clear-case recall "≈ 5%" | `files/` is gitignored (only `MODEL_CARD.md` is tracked); EVAL.md gives guard 4.2% on all clear rows, 7.7% on clear stale/duplicate, heal 6.1% | +| `sim/NEEDS.md` g | NaN crash OPEN | fixed in ad24804 (`util.ts` -> `describe` uses `Object.is`; `test/nan.test.ts`) | +| `demos/NEEDS.md` | "Runtime: frozen batch 3"; §1 holds reorder writes, §2 hold latency, §6 EventSource not observed, §7 synthetic events recorded | batch 4: no store-write holds by default and opt-in holds never reorder; holds only when the model can answer in time, superseded decisions dropped; `observe/eventsource.ts`; synthetic events now need `untrustedEvents` (DL-11). §5 (`retry` on POST) is still open | +| `packages/runtime/UI-NEEDS.md` | Open 1 (ignore the overlay), Open 2 (`react-dom`), Nice-to-have 3 (`Explanation.message`) | 1 done (`observe/dom-user.ts` -> `ignoredEvent`); 2 done (devDependency); 3 done on the CORE side, the overlay still ignores it | +| `training/NEEDS.md` 10 | quota "1,024 vCPU … exactly the whole cluster" | HANDOFF / RESULTS: raised to 2,048 vCPU, c12–c23 added | +| `realapps/README.md` | 66 apps; "Run it" env-var pinning; `situation-v1` example tag | 91 apps; RA-12 | -| # | deviation | why (STATUS) | code | -|---|---|---|---| -| 1 | `retry` backoff `min(200 ms · 2^(attempt−1), 5 s)` (first retry waits 200 ms) | — | `observe/fetch.ts` (failure handler) | -| 2 | `coalesce` not offered for XHR; XHR failures/stalls detection-only | the app receives XHR events directly | `situation/build.ts` -> `builtinApplicable` | -| 3 | Transition profiles compare array kinds as empty / non-empty only (no length-delta sign) | precision: a short last page or a removal is ordinary | `learn/profiles.ts` -> `kindLabel` | -| 4 | Error/transition `rollback` restores only the fields the op's own chain wrote; inconsistency uses the snapshot | the snapshot would also revert other chains' writes (e.g. user input) | `runtime.ts` -> `revertChain`; `situation/build.ts` -> `revertableChain` | -| 5 | Default redaction by word-level secret names, not the §2 regex | approved SIM request a | `util.ts` -> `defaultRedact`, `isSensitiveName` | -| 6 | `situation(trigger)` returns the last situation built for that trigger | — | `runtime.ts` -> `situation` | -| 7 | Extra public surface (`adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")`, extra `Situation`/`Decision`/`ActionRecord`/`Explanation`/option fields) | additive | `types.ts` | +### Recorded contract deviations (STATUS "Deviations from the contract (and why)") -### Doc drift: `docs/runtime/CONTRACT.md` vs implementation +Accepted by CORE and listed in STATUS; CONTRACT.md was not updated. -| § | CONTRACT says | code does | -|---|---|---| -| 1 | `src/observe/` = fetch, xhr, dom-user, errors, nav, storage, perf, websocket | Also `timers.ts` and `cache.ts` (response cache); extra top-level `src/util.ts`, `src/errors.ts`; `situation/` also has `build.ts`, `describe.ts`, `env.ts` | -| 2 | Kill switch: `localStorage.genclass = "off"`; adapters: React `useGenClassState`, `useAtom`, `useGenClass` | localStorage also accepts `observe\|guard\|heal`; adapters also export `GenClassProvider`, `getGenClassAtom`, `useGenClassDecisions`, `useGenClassInterventions`, `useGenClassStatus`, Redux `GENCLASS_REPLACE`; Redux `genclassEnhancer` and Zustand `genclass` accept a null runtime and pass through, React `useGenClassState` falls back to plain `useState`, but `useGenClass()` throws without a runtime (`src/adapters/*.ts`) | -| 4 | Mutations "applied in proposal order per store (a later-decided mutation waits for earlier ones on the same store)" | Only for queued writes: user-sync writes (unless `holdUserWrites`), GenClass writes, `hold: false` stores and paused runtimes bypass the queue and commit at once, overtaking held writes (`state/hub.ts` -> `StoreHub.propose`; demos/NEEDS §1) | -| 6 | `hedge` applicable when the body is replayable and the method idempotent | Also GET only and fetch only (`builtinApplicable`) | -| 1 | `src/plugins.ts`; `state/` "atom, guard, diff/summaries, invariant miner, snapshots"; `decide/` "built-in actions, executor"; `learn/` baselines only | No `plugins.ts` (plugins in `runtime.ts`); `state/{hub,fields,invariants}.ts`; action catalogue in `situation/questions.ts`, `decide/exec.ts` is only the `Controller` seam; `learn/profiles.ts` exists | -| 1 | adapters/devtools owner CORE; `training/` owner LEAD; `runtime-model/` "model card + files"; CLI "fetch-model" | §13 and UI-NEEDS: UI; training/README: TRAIN; only `MODEL_CARD.md`; CLI also has `info <dir>` | -| 2 | `redact` default `/pass\|token\|secret\|card\|cvv\|ssn\|auth/i` | Word-level `isSensitiveName` (approved SIM a) — `util.ts` -> `defaultRedact` | -| 2 | `InitOptions` listing without `decider`, `learn`, `vocabulary`, `settleMs`, `situation`, `observe.timers` (§4 mentions `settleMs` and `learn: { persist }`, §13 approves `vocabulary`); `Runtime` without `mode`, `adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")` | All exist (STATUS "Extra public surface") | -| 2 | `device: auto` = webgpu+fp16 if shader-f16, else wasm+q8 | Plans webgpu+fp16 → webgpu+q8 → wasm+q8; auto skips software adapters (`model/loader.ts` -> `planOrder`) | -| 3 | `Op` fields; identity = hash of method+url+body; ids normalised: numbers, uuids, long hex; body methods `json,text,arrayBuffer,blob,formData` | Adds `Op.meta`; identity adds non-volatile headers; also long mixed tokens and short slug ids (`util.ts` -> `isIdSegment`); also `bytes` | -| 4 | Hub records snapshots; every template (incl. `a != null`) is learned after ≥ 3 settled snapshots; profile kind includes length delta sign; duration bucket in the shape | `RuntimeImpl.settled` records them (≤ 8, lingering violations do not block); `state/invariants.ts`: `LEARN_AFTER` = 3 but `LEARN_AFTER_NONNULL` = 6 for `a != null`; array kinds empty/non-empty only (STATUS deviation); `dur` recorded but never raises a transition (`learn/profiles.ts` -> `Profiles.check`) | -| 4 | Settled = no in-flight ops | No in-flight op younger than 10 s **and** no pending write (`RuntimeImpl.busy`) | -| 6 | Budget ≤ 1,000 tokens; truncate timeline, then state, then facts; `situation()` returns `{trigger, subject, state, questions, actions}` | Character budget, device-sized; then in-flight/stats and fact shortening; extra `salient/facts/compact/budget` | -| 6 | Triage example "baseline ratio beyond 3×" | Cause latency > 3× median **and** ≥ 100 ms over it; rate ≥ 3× usual **and** ≥ 5 in 10 s (`situation/facts.ts`) | -| 7 | `retry` backoff `min(200 ms · 2^attempt, 5 s)` | `min(200 · 2^(attempt−1), 5000)` (STATUS deviation) | -| 7 | `rollback` writes the snapshot back | Snapshot only for `inconsistency`; error/transition revert only the chain's fields (STATUS deviation) | -| 7 | Implied XHR parity | XHR: no `coalesce`, `retry`, `hedge`, failure/stall `serve_cached` (STATUS deviation) | -| 8 | `holdBudgetMs` default 300 | `"auto"` (150–800; 300 only as fallback) | -| 8 | `Decision`/`ActionRecord`/`Explanation`/`DecisionProvider` field lists | Add `tier`, `ran`, `answers`, `subjectRef`, `candidate`, `mass`, `late`, `message`, `priority`, `timeoutMs` | -| 8 | Repeats "summarised as ×N in the last minute" | `(×N more in the last minute)` printed at window end, console sink only | -| 9 | `ActionDef` without `tier`; `StandingQuestion` without `always`; PluginApi without `runInOp`, `runtime` | All exist; `risk` is declared but unused | -| 10 | Worker imports `onnxruntime-web/webgpu`; reference engine at `/Users/meharkhanna/jev/...` | Imports `/wasm` or `/webgpu` on demand (`model/worker.ts`); path is another machine (v0.1 card is `extension/src/model/model.json` here) | -| 13 | `situation(trigger)` is side-effect free | Returns the cached last-built situation; building caches `op.reads` (STATUS deviation) | -| 0.5 | Console examples "Coalesced a duplicate: …", "Flagged: …" | Templates: `[GenClass] <Lead> a/an <diagnosis> <noun>: <top fact> <changed> (<diag>, p; <action> p)`; coalesce lead is "Prevented", late reverts "Reverted", actions without a `LEAD` entry (plugin actions) "Handled"; detections "Flagged a/an …" (`decide/report.ts` -> `interventionLine`, `detectionLine`) | - -### Other doc drift - -| file | stale statement | code / repo reality | +| # | deviation | code | |---|---|---| -| `packages/runtime/README.md` | Privacy: "fields matching `pass\|token\|secret\|card\|cvv\|ssn\|auth` are redacted" | Word-level redaction; "card", "cards", "author" kept (`util.ts` -> `isSensitiveName`) | -| `packages/runtime/README.md` (status banner and "Self-hosting" bullet) | "self-host a model with `npx genclass-runtime fetch-model`" | Needs `--from` (see API #1). The root `README.md` does not mention `fetch-model` | -| `packages/runtime/README.md`, `docs/runtime/ARCHITECTURE.md` | "2,000 with WASM threads" | 2,000 only at 4 threads (1,333 at 2, 1,667 at 3) | -| `packages/runtime/README.md`, `README.md`, CONTRACT §0.5 | Console example lines | Real format differs (see CONTRACT §0.5 row); API.md's example is close | -| `packages/runtime/README.md`, OPEN_TASKS | ORT WASM 2.7 MB br (no WebGPU) / 4.7 MB | Not a real conflict: `src/model/README.md` measures 2.69 / 4.69 MB at brotli q9 and notes jsDelivr serves the wasm at 3.07 / 5.53 MB, the figures `model/worker.ts`'s comment rounds to 3.1 / 5.5 MB | -| `README.md` "How it works" 5 | guard acts "when the model is ≥ 90% sure" | Summed probability of the permitted non-passive actions ≥ 0.9 **and** top diagnosis ≠ `expected` (`decide/policy.ts` -> `gate`); the package README's wording ("very sure (≥ 0.9) that acting beats doing nothing") is accurate | -| `packages/runtime/UI-NEEDS.md` 3 | `Explanation.message` is "Nice to have" | Implemented by CORE (`types.ts` -> `Explanation.message`, `runtime.ts` -> `explain`; API.md documents it); only the overlay's use of it is missing | -| `packages/runtime/STATUS.md` Open issues; UI-NEEDS 2 | `react-dom` is not a devDependency | `react-dom ^19.3.0`, `@types/react-dom ^19.0.0` are devDependencies | -| `packages/runtime/STATUS.md` For UI | mock-runtime needs `holdBudgetMs()`/`situationBudget()` | Present in `test/browser/ui/mock-runtime.ts` | -| `packages/runtime/STATUS.md` batch 3 | Unholdable in-place write "applies at once with a fact" | Applies at once without gating, so no fact (`state/hub.ts` -> `StoreHub.propose`) | -| `packages/runtime/STATUS.md`, sim/NEEDS header | Headless thresholds `{ report: 0, guard: 0, heal: 0 }` | The sim uses guard/heal 0.5 (`sim/README.md`) | -| `packages/runtime/UI-NEEDS.md` 1 | Ignore the devtools overlay: Open | Done: `observe/dom-user.ts` -> `ignoredEvent`; STATUS "For UI" agrees | -| `sim/NEEDS.md` a–f | ASK | DONE in batch 3 (STATUS; `test/batch3.test.ts`) | -| `sim/NEEDS.md` Notes | `transient` not yet in `DEFAULT_DIAGNOSES` | It is, last (`situation/questions.ts`) | -| `sim/README.md` limitation 5 | Triage does not flag a remote write over a pending local change | It does (`situation/facts.ts` "has a pending local change"; SIM f) | -| `training/NEEDS.md` | "Still to mirror when CORE's fix batch lands" | Done per `training/LOG.md` 23:05–23:35 (`rt.py` re-ported; MODEL NEEDS 8 fixed) | -| `OPEN_TASKS.md` item 8 | `npm pack` smoke test is next | Done (`test/smoke/smoke.sh`, Done list) | -| `OPEN_TASKS.md` item 7 | "ARCHITECTURE.md are written; still to do: … ARCHITECTURE.md" | Self-contradictory; the to-do is "honest results" content | -| `OPEN_TASKS.md` item 6, `demos/results.md` | Board: 9 bugs introduced in guard mode | Superseded by demos/NEEDS §1/§4 (5 introduced / 3 fixed after the mock-server fix) | -| `OPEN_TASKS.md` risks | Thin classes "until the batch-3 runtime facts land" | Batch 3 landed before phase A; see Known risks for counts | -| `docs/runtime/ARCHITECTURE.md` | DOM events "trusted events only"; sources omit timers; diagnosis order "…failing, transient, slow…"; fact "(v0 → v1)" | Untrusted events kept unless a non-user op is running or ambient (`observe/dom-user.ts` -> `programmatic`); timers observer exists; `transient` last; "(version 0 → 1)" | -| `packages/runtime-model/MODEL_CARD.md` | 9 diagnoses; acts when `p(action) ≥ 0.9/0.8`; q8 is "for onnxruntime-web WASM"; status "stage 2 piloted" | 10 (with `transient`); summed probability of permitted actions; MODEL verified q8 also runs on the WebGPU EP without shader-f16 (training/NEEDS, MODEL → TRAIN 7); final round 1 is running | -| `sim/README.md` limitation 8, `stats-final-a.json` `token_estimate` | Token counts estimated as characters / 3.6 | TRAIN measured 2.4 chars/token with the runtime tokenizer (training/NEEDS 6a), so SIM's token estimates are ≈ 1.5× low | -| `src/types.ts` JSDoc | `InitOptions.redact` regex; `InitOptions.situation` auto wasm budget "1,100 + 300 per extra thread"; `Decision.action` "The action the model chose (highest probability)"; `InitOptions.observe` "Default: all true" | word-level; `1000 + round((t−1)·1000/3)`; `run ?? top` in `runtime.ts` (the action that ran, else the model's choice); timers conditional | -| `src/situation/serialize.ts` comment | `STATE_CHAR_BUDGET` ≈ 3.2 chars per token | Measured 2.4 (training/NEEDS 6a) | -| `packages/runtime/bin/genclass-runtime.mjs` | — | Committed as mode 100644 (not executable). A root `npm install` chmods it to 755 (observed with npm 11.8.0 on 2026-10-07), which git reports as a mode change; revert with `git checkout -- packages/runtime/bin/genclass-runtime.mjs` | +| 1 | `retry` backoff `min(200 ms · 2^(attempt−1), 5 s)` | `observe/fetch.ts` (failure handler) | +| 2 | `coalesce` not offered for XHR; XHR failures/stalls detection-only | `situation/build.ts` -> `builtinApplicable` | +| 3 | Transition profiles compare array kinds as empty / non-empty only | `learn/profiles.ts` | +| 4 | Error/transition `rollback` restores only the chain's fields; inconsistency uses the snapshot | `runtime.ts` -> `revertChain` | +| 5 | Default redaction by word-level secret names and (batch 5) by the leaf field with container rules; booleans and null never redacted | `util.ts` -> `defaultRedact`, `isSensitivePath` (see SIT-3) | +| 6 | `situation(trigger)` returns the last situation built for that trigger | `runtime.ts` -> `situation` | +| 7 | Batch 4 salience: a user action that changed a field is not, by itself, a version conflict; XHR `on*` getters return GenClass's wrapper | `runtime.ts` -> `runDelivery`; `observe/xhr.ts` | +| 8 | With `holdWrites` off, `mutation` `defer` is recorded only | `runtime.ts` -> `observeWrite` | +| 9 | Extra public surface (`adapter`, `inflight`, `holdBudgetMs`, `situationBudget`, `on("report")`, `ActionRecord.dropped`, `PolicyOptions.holdWrites`, `observe.untrustedEvents`, `SituationDraft.delivery`, …) | `types.ts` | ### Code TODOs -None. `grep -rn "TODO\|FIXME\|HACK\|XXX"` over the repo (excluding `node_modules`, `.git`, `dist`) matches only -vocabulary entries in `extension/**/tokenizer.json` and prose in agent docs. Open work lives in the NEEDS, -STATUS and OPEN_TASKS files instead. - -Comments that act like TODOs or temporary workarounds (found by grepping `packages/runtime/src`, `sim/src`, -`demos/src`, `training` for "until", "not yet", "for now", "stub", "workaround"): - -| where | what it says | state at 654d822 | -|---|---|---| -| `sim/src/run/rt.ts` -> `realRuntimeFactory` | "Until the runtime's default vocabulary has every contract label, pass the contract's defaults explicitly"; also "CORE's API is in flux" and the error "does not export createRuntime yet" | Inert: runtime `DEFAULT_DIAGNOSES` has all 10 labels, so `missing` is false; the wording is stale | -| `sim/src/run/fake-runtime.ts` | "TEST DOUBLE ONLY": rows it produces are marked `meta.runtime = "fake"` and "must never be used for training" | Guarded: `sim/src/gen.ts` uses it only with `--allow-fake` | -| `src/model/backend.ts` -> `WARMUP_STATE`, `WARMUP_QUESTIONS` | Hand-copied situation and question wording for the warm-up pass ("What is going on?" vs the runtime's `DIAGNOSIS_INSTRUCTIONS` "What is happening here?") | Harmless: used only for the warm-up pass in `ModelBackend` load (also re-exported from `model/index.ts`); never a decision. Do not treat it as a wording reference | -| `src/types.ts` JSDoc, `src/situation/serialize.ts` comment | Stale values (see Other doc drift) | Safe to fix (no model-visible text) | +None. `git grep -E "TODO|FIXME|XXX|HACK"` over `packages/runtime/src`, `sim/src`, `realapps/src`, `demos/src` and +the `training` scripts at b435acb finds nothing. Open work lives in HANDOFF, OPEN_TASKS, STATUS and the NEEDS files. ### Subsystem drift tracked elsewhere -The tables above cover the human docs (API.md, CONTRACT.md, READMEs, STATUS, NEEDS, MODEL_CARD) against the runtime -code. Each subsystem doc has its own Drift section with more detail: [public API](runtime/public-api-and-lifecycle.md), -[observe](runtime/observe-and-trace.md), [state](runtime/state-and-adapters.md), -[situation](runtime/learn-situation-triage.md), [decide](runtime/decide-policy-actions.md), -[model host](runtime/model-host.md), [devtools](runtime/devtools.md), [build](runtime/build-test-release.md), -[model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md), [demos.md](demos.md) (e.g. -Drift 1, the missing `cities.ts`), [genclass-model-lineage.md](genclass-model-lineage.md) and -[extension-and-benchmarks.md](extension-and-benchmarks.md). +Each refreshed subsystem doc has its own Drift section with more detail: +[public API](runtime/public-api-and-lifecycle.md#drift-and-open-issues), [observe](runtime/observe-and-trace.md), +[state](runtime/state-and-adapters.md), [situation](runtime/learn-situation-triage.md), +[decide](runtime/decide-policy-actions.md), [model host](runtime/model-host.md), [devtools](runtime/devtools.md), +[build, test and release](runtime/build-test-release.md), [model-io-contract.md](model-io-contract.md), +[sim.md](sim.md#drift-and-open-issues), [training.md](training.md#drift-and-open-issues), +[realapps.md](realapps.md#drift-and-open-issues), [demos.md](demos.md), +[genclass-model-lineage.md](genclass-model-lineage.md), [extension-and-benchmarks.md](extension-and-benchmarks.md). ## Related docs - Agent docs: [README.md](README.md), [overview.md](overview.md), [repo-map.md](repo-map.md), [glossary.md](glossary.md), - [playbooks.md](playbooks.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [training.md](training.md), - [demos.md](demos.md), [genclass-model-lineage.md](genclass-model-lineage.md), - [extension-and-benchmarks.md](extension-and-benchmarks.md), [../../AGENTS.md](../../AGENTS.md) + [playbooks.md](playbooks.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), + [realapps.md](realapps.md), [training.md](training.md), [demos.md](demos.md), + [genclass-model-lineage.md](genclass-model-lineage.md), [extension-and-benchmarks.md](extension-and-benchmarks.md), + [../../AGENTS.md](../../AGENTS.md) - Runtime agent docs: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md), [runtime/observe-and-trace.md](runtime/observe-and-trace.md), [runtime/state-and-adapters.md](runtime/state-and-adapters.md), [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [runtime/model-host.md](runtime/model-host.md), [runtime/devtools.md](runtime/devtools.md), [runtime/build-test-release.md](runtime/build-test-release.md) -- Sources: [OPEN_TASKS.md](../../OPEN_TASKS.md), [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md), +- Sources: [HANDOFF.md](../../HANDOFF.md), [OPEN_TASKS.md](../../OPEN_TASKS.md), [RELEASE.md](../../RELEASE.md), + [docs/runtime/RESULTS.md](../runtime/RESULTS.md), [packages/runtime/STATUS.md](../../packages/runtime/STATUS.md), [docs/runtime/CONTRACT.md](../runtime/CONTRACT.md), [docs/runtime/API.md](../runtime/API.md), - [docs/runtime/ARCHITECTURE.md](../runtime/ARCHITECTURE.md), [demos/NEEDS.md](../../demos/NEEDS.md), - [sim/NEEDS.md](../../sim/NEEDS.md), [training/NEEDS.md](../../training/NEEDS.md), - [packages/runtime/UI-NEEDS.md](../../packages/runtime/UI-NEEDS.md), [training/EVAL.md](../../training/EVAL.md), - [training/LOG.md](../../training/LOG.md), [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), - [demos/results.md](../../demos/results.md), [sim/README.md](../../sim/README.md), [scripts/vm.sh](../../scripts/vm.sh) + [docs/runtime/ARCHITECTURE.md](../runtime/ARCHITECTURE.md), [training/NEEDS.md](../../training/NEEDS.md), + [training/PLAN-v1.md](../../training/PLAN-v1.md), [training/LOG.md](../../training/LOG.md), + [training/EVAL.md](../../training/EVAL.md), [sim/NEEDS.md](../../sim/NEEDS.md), + [sim/SEPARABILITY.md](../../sim/SEPARABILITY.md), [demos/NEEDS.md](../../demos/NEEDS.md), + [packages/runtime/UI-NEEDS.md](../../packages/runtime/UI-NEEDS.md), [realapps/README.md](../../realapps/README.md), + [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), + [.github/workflows/ci.yml](../../.github/workflows/ci.yml) diff --git a/docs/agents/training.md b/docs/agents/training.md index 4aa11827..e89a8ddb 100644 --- a/docs/agents/training.md +++ b/docs/agents/training.md @@ -1,30 +1,33 @@ # training/: the GenClass runtime model (curriculum, training, export, eval) -> **Scope:** `training/` (README.md, LOG.md, EVAL.md, NEEDS.md, `prune_vocab.py`, `eval_runtime.py`, `export_runtime.py`, `report.py`, every `*.sh`, `curriculum/**`, `configs/*.json`, `ortweb/**`, `tests/**`, `samples/**`), plus the parts of `jev_local/train/{train,stream,eval}.py`, `jev_local/engine/encoder/{engine,calibrate,tokenize_pack}.py`, `scripts/genclass_export.py` and `scripts/launch_run.sh` that `training/` calls. -> **Read this when:** you regenerate or change the stage-1 curriculum; mirror a runtime situation/question wording change into `curriculum/rt.py`; change mixtures or launch a training round on Azure; evaluate a checkpoint, fit calibration or read EVAL.md numbers; export a model directory (q8/fp16 ONNX, `model.json`, `meta.json`, `calibration.json`) or validate it with onnxruntime-web; change the vocabulary; pick between R17 and R32. -> **Source of truth:** the code. Verified against commit 654d822 (2026-10-07). If this doc and the code disagree, the code wins. +> **Scope:** `training/` (README.md, PLAN-v1.md, LOG.md, EVAL.md, NEEDS.md, `prune_vocab.py`, `eval_runtime.py`, `eval_gain.py`, `export_runtime.py`, `report.py`, `label_teacher.py`, `t1_relabel.py`, `collect_gain.py`, every `*.sh`, `curriculum/**`, `configs/*.json`, `ortweb/**`, `tests/**`, `samples/**`), plus the parts of `jev_local/train/{train,stream,eval}.py`, `jev_local/engine/encoder/{engine,calibrate,heads,tokenize_pack}.py`, `scripts/genclass_export.py` and `scripts/launch_run.sh` that `training/` calls. +> **Read this when:** you regenerate or change the curriculum; mirror a runtime situation/question wording change into `curriculum/rt.py` (now frozen at `situation-v2`); change mixtures or launch a training round on Azure (students, the T150 teacher, distillation, DAgger); soft-label rows with a teacher; run the T1 expected-gain experiments; evaluate a checkpoint, fit calibration or read EVAL.md numbers; export a model directory (q8/fp16 ONNX, `model.json`, `meta.json`, `calibration.json`) or validate it with onnxruntime-web; change the vocabulary; pick between R17 and R32; add cluster nodes. +> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - `training/` builds the model behind `@genclass/runtime`: a Jev-style typed-decision encoder (one forward pass reads a *situation* and answers typed *questions*: choice / noul / score). Owner workstream: TRAIN (CONTRACT §1 says LEAD). -- Two **model candidates**, both with a pruned 16,364-token vocabulary: **R17** (`jhu-clsp/ettin-encoder-17m`, d 256, 7 layers, fresh heads) and **R32** (GenClass 0.1 `jev-local-fast` = ettin-32m, d 384, 10 layers, v1 heads). Plan: R17 for WASM, R32 for WebGPU only if clearly more accurate (OPEN_TASKS item 5). +- Two **model candidates**, both with a pruned 16,364-token vocabulary: **R17** (`jhu-clsp/ettin-encoder-17m`, d 256, 7 layers, fresh heads) and **R32** (GenClass 0.1 `jev-local-fast` = ettin-32m, d 384, 10 layers, v1 heads). Final-round-1 decision: R17 on every device (R32 matched it at 3× the latency and size; EVAL.md, RESULTS.md §2). PLAN-v1 adds R68 (student benchmark) and the never-shipped T150 teacher, same vocabulary. - Pipeline: `prune_vocab.py` (keep first 16,000 BPE merges) → **stage 1** on a synthetic curriculum (`curriculum/`, exact labels, ~55% passive-best decision rows) → **stage 2 / final round** on SIM rows from `sim/` (counterfactual-cost labels) plus curriculum replay → `eval_runtime.py` (product metrics + temperature fit) → `export_runtime.py` (fp16-free int8 **q8** ONNX for WASM, fp16 ONNX for WebGPU) → `ortweb/validate.mjs`. -- `curriculum/rt.py` is a Python port of `packages/runtime/src/situation/*` so a share of curriculum rows are **runtime-exact** (byte-identical format to what the runtime sends). Any wording change in the runtime situation code must be mirrored there (and is frozen as tag `situation-v1`). -- Training itself is `jev_local/train/train.py` in stream mode (DDP over torchrun/gloo on CPU) launched with `scripts/launch_run.sh`; all heavy work runs on Azure VMs (`c01` workbench, `c02`–`c11` F80 training nodes, `train` VM), never on the Mac. +- `curriculum/rt.py` is a Python port of `packages/runtime/src/situation/*` (+ `state/fields.ts` `changeText`/`stringDiff`) so a share of curriculum rows are **runtime-exact** (byte-identical format to what the runtime sends). It now mirrors the frozen tag **`situation-v2`** (6e5e86e): the new `delivery` trigger (response / WebSocket message about to be delivered), conflict-driven version facts, content facts F1–F3, evidence facts F5–F7/F9, diff-centred string changes, the **2,400-char** full budget and the v2 "auto" device budgets. Any wording change in the runtime situation code must be mirrored there and needs a new freeze tag. +- **Everything trained so far is situation-v1.** All `cur*`/`rt1` sets, SIM phase A (`simA`) and every checkpoint (stage 1c, final round 1, the stopped T150 and T1 runs) predate v2. No v2 curriculum set, no imported v2 SIM/REAL data and **no v2 model exist in the repo or LOG** at this commit; v2 data is being generated on Azure by SIM/REAL (NEEDS). +- The scaled program (`training/PLAN-v1.md`): **T150 teacher** (ettin-150m) on v2 gold → `label_teacher.py` / `label_cluster.sh` soft-label a prioritised subset of the ≥ 50M unlabeled rows (PLAN P3: 5–10M rows near the gate plus a uniform sample) → distil students R17 (default) / R32 (/ R68 benchmark) with `launch_student.sh` → **DAgger** rounds on SIM `--on-policy` rows → EVAL → `@genclass/runtime-model@0.1.0`. A **T1** side track (`t1_relabel.py`, `eval_gain.py`, gain head) trains on expected-advantage targets from SIM `meta.cost_futures` (sim/SEPARABILITY.md §7). +- Training itself is `jev_local/train/train.py` in stream mode (DDP over torchrun/gloo on CPU) launched with `scripts/launch_run.sh`; all heavy work runs on Azure VMs (`c01` workbench, `c02`–`c23` F80 nodes (c12–c23 added by `cluster_expand.sh` on 2026-10-08), `train` VM, `data` VM), never on the Mac. Per the lead's portal look at 2026-10-08 04:14 UTC and training/NEEDS, SIM holds c02–c09 + c12–c23 and REAL holds c01, c10, c11 for v2 generation (NEEDS); TRAIN holds no node. - Data mixes (`configs/mix_*.json` → `jev_local/train/stream.py` → `MixConfig`) weight **buckets** = the parent directory names of train shards found under the `--stream` roots; weights are renormalised over the buckets present, so a missing bucket is silently dropped. - The eval **gate** mirrors CONTRACT §8: candidate = argmax over permitted non-passive actions *A*; fire iff Σ_{a∈A} p(a) ≥ tier threshold (guard 0.9, heal 0.8) and top diagnosis ≠ `expected`. Headline metric: **FIR** (false-intervention rate on passive-best rows). - Trained checkpoints ship with all-1.0 temperatures; the real `calibration.json` comes from `eval_runtime.py --write-calibration` and must be passed to `export_runtime.py --calibration`. -- Status at this commit: stage 1c final (rt1 action/diagnosis ≈ 98%, FIR 0%); stage-2 pilot on pre-freeze SIM was precise but almost never acted (recall ≈ 1.3%); **final round 1** (frozen `situation-v1`, SIM phase A) was launched 2026-10-08 00:06 UTC and has **no results in the repo** (EVAL.md says "(in progress)"). +- Status at this commit: **final round 1** (situation-v1, SIM phase A) is done and is the baseline: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE ≈ 0.01, but guard recall on clear stale/duplicate cases only 7.7% (EVAL.md); R32 is no better, so **R17 is the default on every device**. The v1 teacher `t150-g1` (stopped at step 69) and the T1 runs (`r17-t1g10`, `r17-t1g20`, `r17-t1h`, stopped at ≈ 1,000–1,350 of 2,168 steps) were halted when situation-v2 was frozen; none has results. The final1 exports exist only on the train VM / Mehar's Mac (`packages/runtime-model/files/` is gitignored); they do not match the v2 runtime. Spend to 01:56 UTC ≈ $390 (LOG). - Shell scripts assume a nested checkout: `JEV="$HERE/../.."` must contain `jev_local/`, `scripts/` and `pyproject.toml` (the original `/Users/meharkhanna/jev/<checkout>/training` layout). In this monorepo those live at the repo root, one level up (see Gotchas). ## Files | Path | Role | Key entry points | |---|---|---| -| `training/README.md` | Overview and reproduce commands (partly stale, see Drift) | — | -| `training/LOG.md` | Dated run log 2026-10-07/08: what ran where, throughput, costs, decisions | — | -| `training/EVAL.md` | Metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot) | — | -| `training/NEEDS.md` | Requests to SIM / CORE / MODEL (OPEN/ASK/DONE) | — | +| `training/README.md` | Overview and reproduce commands (unchanged since situation-v1; partly stale, see Drift) | — | +| `training/PLAN-v1.md` | The scaled program: targets, data inventory, models R17/R32/R68/T150/T400, phases P0–P5 with cost estimates, eval protocol, infra work, node claims, risks | — | +| `training/LOG.md` | Dated run log 2026-10-07/08 up to 03:35 UTC: what ran where, throughput, costs, decisions (final1, cluster expansion, T150, T1, v2 freeze) | — | +| `training/EVAL.md` | Metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot, **final round 1 = v1 baseline**) | — | +| `training/NEEDS.md` | Requests to SIM / CORE / MODEL / REAL (OPEN/ASK/DONE), node-claim table, SIM and REAL data locations (items 10–16) | — | | `training/prune_vocab.py` | First-N-merges BPE pruning of a checkpoint or HF base; inflation analysis | `prune_tokenizer_json`, `vocab_layout`, `prune_checkpoint`, `prune_hf_dir`, `slice_weights`, `remap_model_config` (+ `CONFIG_ID_KEYS`), `remap_tokenizer_config`, `iter_texts`, `analyze`, `main` (`prune` / `analyze` subcommands) | | `training/curriculum/__init__.py` | Package docstring only | — | | `training/curriculum/generate.py` | Parallel, seeded generator of CONTRACT-D jsonl (train/dev/test) + `stats.json` | `make_row`, `work`, `_validate`, `main`; `TRIGGERS`, `KINDS`, `TRAIN_DOMAINS`, `HELD_DOMAINS`, `P_RUNTIME` | @@ -36,17 +39,29 @@ | `training/curriculum/scen_ops.py` | Request / failure / stall scenarios | `request`, `failure`, `stall` | | `training/curriculum/scen_state.py` | Inconsistency / transition / error scenarios | `inconsistency`, `transition`, `error`, `ERR_MSGS` (5 entries) | | `training/curriculum/prims.py` | Primitive questions with exact labels over a `Trace` | `noul`, `choice`, `score`, `temporal`, `causal`, `versions`, `identity`, `streak_q`, `latency_q`, `failure_q`, `failure_kind`, `ratio_level`, `RATIO_LEVELS`, `RETRYABLE`, `FAILURE_KIND_DESC` | -| `training/curriculum/rows.py` | Assemble rows: situation state, standing questions, primitives | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `add_prims`, `RENAMES` | +| `training/curriculum/rows.py` | Assemble rows: situation state, standing questions, primitives. `decision_row` passes an `info` dict to `rt.render` and takes the rendered trigger and the scenario-action → runtime-action map from it (a mutation rendered as a v2 `delivery`) | `decision_row`, `ask_row`, `situation_state`, `action_question`, `diagnosis_question`, `add_prims`, `RENAMES` | | `training/curriculum/standalone.py` | Non-situation primitive families | `json_invariants`, `http_semantics`, `js_errors`, `described_options`, `DECIDE` (12), `HTTP_CASES` (15), `JS_ERRS` (9), `JS_KIND_DESC` (8 kinds) | -| `training/curriculum/rt.py` | Runtime-exact rendering (port of runtime `situation/{facts,describe,build,serialize,questions}.ts`) | `render`, `to_state`, `section_limits`, `size_chars`, `signature`, `is_id`, `mutation_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`, `subject_sentence`, `event_lines`, `in_flight_lines`, `state_lines`, `stats_lines`, `order`, `provenance`, `started_rel`, `user_relation`, `failure_text`, `failure_counts`, `error_rate_text`; ports of `util.ts` `truncate`, `secs`, `rel`, `fmt_num` (`fmtNum`), `ratio`, `plural`, `ordinal`, plus `times` (a local helper of `facts.ts`); constants `DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `TRIGGER_ACTIONS`, `ACTION_INSTR`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `COMPACT_QUESTIONS_MAX`, `BUDGETS`, `RANK`, `LIMITS`, `WINDOW`. `LINE` and `err_rate` are defined but unused. | +| `training/curriculum/rt.py` | Runtime-exact rendering, frozen at `situation-v2` (port of runtime `situation/{facts,conflicts,content,evidence,describe,build,serialize,questions}.ts` and `state/fields.ts` `changeText`/`stringDiff`) | `render(sc, app, rng, info=None)`, `to_state`, `section_limits`, `size_chars`, `signature`, `is_id`; facts: `mutation_facts`, `delivery_facts`, `request_common`, `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`; v2 shared builders `version_facts`, `moved_facts`, `concurrency_facts`; conflicts `newer_conflict`, `pending_conflict`, `conflicts_on`, `newer_same_signature`; content `compare_field`, `content_facts`, `pending_revert_facts`; evidence `scope_facts`, `commit_ambiguity`, `repeat_evidence`, `cadence_fact`, `mark_facts`; delivery `delivery_spec`, `related_in_flight`, `predicted_text`, `field_list_text`; text `change_text`, `string_diff`, `normalize_field_path`, `value_at` (unused); sections `subject_sentence`, `event_lines`, `in_flight_lines`, `state_lines`, `stats_lines`, `order`, `provenance`, `started_rel`, `user_relation`, `failure_text`, `failure_counts`, `error_rate_text`, `net_of`, `host_of_sig`; ports of `util.ts` `truncate`, `secs`, `rel`, `fmt_num`, `ratio`, `plural`, `ordinal`, plus `times`; constants `DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `TRIGGER_DESCRIPTIONS`, `TRIGGER_ACTIONS`, `ACTION_INSTR`, `STATE_CHAR_BUDGET` (2400), `COMPACT_BUDGET`, `MIN_BUDGET`, `COMPACT_QUESTIONS_MAX`, `BUDGETS`, `RANK`, `LIMITS`, `WINDOW`, `PENDING_WINDOW_MS`, `NOT_PROCESSED`, `P_DELIVERY`, `DELIVERY_ACTION`. `LINE` and `err_rate` are defined but unused. | | `training/eval_runtime.py` | Evaluation: accuracy, NLL/Brier/ECE, temperature fit, gate metrics, SIM cost regret | `collect`, `get_records` (+ `dump_records`, `load_records`), `fit_calibration`, `fit_tau`, `fit_tau_noul`, `probs`, `group_of`, `canonical`, `softmax`, `ece`, `question_metrics`, `decision_metrics`, `load_rows`, `main`; `TIER`, `PASSIVE`, `THRESH`, `N_BINS` | -| `training/report.py` | Markdown tables (for EVAL.md) from eval reports | `main` (`name=path ... [--mode=kind\|raw\|group\|header]`) | +| `training/report.py` | Markdown tables (for EVAL.md) from eval reports, incl. a clear-case recall table | `main` (`name=path ... [--mode=kind\|raw\|group\|header]`) | +| `training/eval_gain.py` | T1 expected-gain evaluation of gate policies from cached logits (SIM classes clear / benign / mild) | `main` (`--rows`, repeatable `--model name=records.jsonl:cal.json[:t1_tau]`, `--out`), `evaluate`, `classify`, `load_recs`, `softmax`; `PREM`, `PERMIT` | +| `training/t1_relabel.py` | T1 relabelling: expected-advantage action labels (or added `gain` targets) from SIM `meta.cost_futures` | `main` (`--in`, `--out`, `--tau`, `--workers 16`, `--keep-dist`), `relabel_row`, `gains_of`, `work`; `PREM`, `CLIP` | +| `training/collect_gain.py` | Raw action/diagnosis logits + gain-head predictions (`gain_pred`) in `eval_runtime` record format | `main` (`--ckpt`, `--in`, `--out`, `--batch 32`, `--threads 16`, `--max-len 2048`). Needs a `jev_local` with the gain head (not this repo's; see Gotchas) | +| `training/label_teacher.py` | Teacher soft-labelling of CONTRACT-D rows (calibrated probabilities as `dist` labels, `meta.teacher`), resumable | `main` (`--ckpt`, `--in`, `--out`, `--calibration`, `--qids`, `--batch 32`, `--threads 16`, `--max-len 2048`, `--overwrite`, `--limit`); `PASSIVE` | | `training/export_runtime.py` | ONNX export, q8/fp16 graph surgery, parity, model directory | `main`, `make_q8`, `make_fp16`, `quantize_embedding`, `gemm_to_matmul`, `requests_from_rows`; `CARD_FORMAT`, `OUTPUTS` | | `training/ortweb/validate.mjs`, `package.json` | onnxruntime-node + onnxruntime-web 1.30.0 (WASM in Node) parity and latency check | CLI `node validate.mjs <dir> [variant=q8] [maxRequests=60]` | -| `training/configs/mix_*.json` | Mixture configs (`jev_local/train/stream.py` → `MixConfig`) | `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` | +| `training/configs/mix_*.json` | Mixture configs (`jev_local/train/stream.py` → `MixConfig`) | `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1`, `mix_t150` (teacher), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs) | | `training/node.sh` | ssh/rsync wrapper for Azure hosts | `node.sh HOST sync\|'cmd'\|get R L\|put L R` | +| `training/cluster_expand.sh` | Create extra F80 nodes in `rg-jev-train` (same VNet/subnet/NSG/PPG/image/key; retries without PPG), append to `~/.jev-local/azure_hosts`, add a **Disabled** DevTestLab 03:00 shutdown schedule | `cluster_expand.sh NAME:SIZE ...` (e.g. `c12:Standard_F80ads_v7`) | +| `training/node_init.sh` | Run on a fresh node: pull the node kit tar (cloned venv, ettin bases, pruned bases, TRAIN data), install ONNX tooling, check torch, touch `~/.node_init_ok` | `bash node_init.sh http://<ip>:8801/kit.tar` | | `training/import_sim.sh` | Pull a SIM run to c01, shard train (stage 2) | `import_sim.sh SIM_OUT_DIR NAME` | -| `training/import_final.sh` | Pull a frozen SIM run, shard, build eval subsets, bundle for nodes | `import_final.sh SIM_OUT_DIR NAME` | +| `training/import_final.sh` | Pull a frozen SIM run, shard, build eval subsets, bundle for nodes; env `WB` (workbench, default c01), `FILES` (default `train dev test`), `PORT` (train-VM port, default 8802) | `[WB=.. FILES=.. PORT=..] import_final.sh SIM_OUT_DIR NAME` | +| `training/launch_student.sh` | Generic DDP launcher for r17 / r32 / r68 / t150 (per-arch base, lr, grad-accum defaults) over `data/s3 data/s1` | `launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra trainer args]`; env `RANKS`, `THREADS`, `GA_OVERRIDE`, `LR_OVERRIDE`, `HLR_OVERRIDE` | +| `training/launch_t150.sh` | Teacher T150 launcher (`mix_t150.json`, stream `data/s3` only) | `launch_t150.sh RUN PASSES "nodes" MASTER_IP [extra args]`; env `RANKS` (8), `THREADS` (10) | +| `training/launch_r68.sh` | R68 student benchmark launcher (`mix_r68.json`) | `launch_r68.sh RUN PASSES "nodes" MASTER_IP [extra args]` | +| `training/label_cluster.sh` | Teacher soft-labelling across nodes (serves teacher + shards from the workbench on :8805, runs `label_teacher.py` per shard); untested per LOG | `label_cluster.sh WB TEACHER CAL SRC_DIR OUT_BUCKET "nodes" [PROCS_PER_NODE=8] [QIDS=action,diagnosis]` | +| `training/t1_post.sh` | On a T1 run's rank-0 node: wait for `final`, `eval_sim.sh simAe`, then `eval_gain.py` with the label τ | `bash training/t1_post.sh RUN TAU` → `out/eval/gain-RUN.json`, marker `out/.t1-done-RUN` | +| `training/t1h_post.sh` | Same for the gain-head run: plus `collect_gain.py` on every `data/simAe_t*` shard in parallel | `bash training/t1h_post.sh RUN` | | `training/launch_s2.sh` | Launch stage-2 pilot runs (R32, R17) | no args | | `training/launch_final1.sh` | Launch final round 1 | `launch_final1.sh R32_PASSES R17_PASSES` | | `training/final_post.sh` | On a rank-0 node: SIM eval → export → serve tar on :8801 | `final_post.sh MODEL NAME VERSION` | @@ -60,7 +75,7 @@ ## Concepts and data structures -Terms beyond the shared [glossary](glossary.md) (op, situation, questions, diagnosis, action, passive, mode, tier, budget, R17/R32, q8, `situation-v1`): +Terms beyond the shared [glossary](glossary.md) (op, situation, questions, diagnosis, action, passive, mode, tier, budget, R17/R32, q8, `situation-v1` / `situation-v2`): | Term | Meaning here | |---|---| @@ -78,10 +93,16 @@ Terms beyond the shared [glossary](glossary.md) (op, situation, questions, diagn | Bucket | A mixture group = the parent directory name of a shard file (`jev_local/train/stream.py` → `_names`), e.g. `data/s3/simA/shard07.jsonl` → bucket `simA`. A top-level `bucket` field in a row would override it (`_row_fields`); curriculum and SIM rows have none. | | Pass / `pass_tokens` | One draw of the mixture; bucket token budget = weight × `pass_tokens`. `--passes` may be fractional. | | Servable checkpoint vs trainer state | `--out models/<M>` (`backbone/`, `heads.safetensors`, `calibration.json`, `meta.json` with `final`) vs `runs/<run>/ckpt` (weights + optimizer, used by `--resume` and as `--init-from`). | -| Stage 1 / 1c / 2 / final round | s1: curriculum `cur1` + v1 `gen`/`cu` replay (`mix_s1`); s1c: continuation with runtime-exact `cur2` (`mix_s1c`); s2: pilot on pre-freeze SIM `r300k` (`mix_s2`); final1: frozen SIM phase A + replay (`mix_final1`). | +| Stage 1 / 1c / 2 / final round | s1: curriculum `cur1` + v1 `gen`/`cu` replay (`mix_s1`); s1c: continuation with runtime-exact `cur2` (`mix_s1c`); s2: pilot on pre-freeze SIM `r300k` (`mix_s2`); final1: frozen situation-v1 SIM phase A + replay (`mix_final1`), done, the v1 baseline. PLAN-v1 phases P0 (final1) … P5 (DAgger) replace "round 2". | | FIR | False-intervention rate = gate fires on passive-best rows ÷ passive-best rows (per mode). | | Replay | Curriculum/v1 buckets mixed into SIM training (`cur*`, `gen`, `cu`). | -| Hosts | `train` VM (10.0.0.4; SIM runs, delivery, MODEL's node_modules), `c01` (10.0.0.6; TRAIN workbench: prune, generate, eval, export, data hub), `c02`–`c11` (F80 training nodes; c02 = 10.0.0.7 is R32 rank 0, c09 = 10.0.0.14 is R17 rank 0). F80 ≈ $5.46/h (LOG). | +| Hosts | `train` VM (10.0.0.4; SIM runs, delivery, MODEL's node_modules; SIM outputs on its 1 TB `/data` disk since 02:01 UTC), `data` VM (SIM generation; deallocated per the lead's portal look at 2026-10-08 04:14 UTC and training/NEEDS), `c01` (10.0.0.6; TRAIN workbench: prune, generate, eval, export, data hub), `c02`–`c11` (F80 nodes; c02 = 10.0.0.7 was R32 rank 0, c09 = 10.0.0.14 R17 rank 0), `c12`–`c23` (added 00:40–01:13 UTC 2026-10-08: c12–c15 F80ams_v7 with 629 GB RAM, c16–c19 F80amds_v7, c20–c23 F80ads_v7; shutdown schedule Disabled). Quota 2,048 vCPU (raised from 1,024). F80 ≈ $5.46/h (LOG). Claims live in NEEDS.md. | +| situation-v2 | The frozen runtime format (tag `situation-v2` = 6e5e86e). Decisions happen at the network boundary: a new `delivery` trigger (a fetch response or WebSocket message about to reach the app; actions deliver / discard / defer), store writes are not held by default. Facts added: newer-data / pending-local-change conflicts (only these make a version fact non-neutral), F1–F3 content (put-back of a replaced value, overwriting user typing, "changes nothing"), F5 failure scope / commit ambiguity, F6 cadence, F7 repeat-action evidence, F9 stale marks. Full budget 2,400 chars. | +| Delivery row (curriculum) | A mutation scenario whose cause is a completed OK fetch or a WS op, rendered as `delivery` with probability `P_DELIVERY` = 0.5 (`rt.render`). Actions map `apply → deliver`, `discard → discard`, `defer → defer`; `defer` is dropped when no related op is in flight or `defers ≥ 2`; if the gold action is no longer offered the row stays a mutation. `meta.trigger = "delivery"`, family `cur/delivery/<case>`, `meta.action_names` = that map, `meta.action_canonical` keeps the scenario name. | +| Clear case | A decision row whose gold puts ≥ 0.9 on one permitted non-passive action (`eval_runtime.py` → `decision_metrics`: `recall_clear`, and `recall_clear_stale_dup` when the gold diagnosis is `stale` or `duplicate`). `eval_gain.py` uses SIM's different definition (`classify`: mean gain over futures ≥ 2, every future's gap > 0, same best action in every future); `benign` = no future gains, `mild` = the rest. | +| Teacher / distillation | A large never-shipped model (T150 = ettin-150m, pruned vocab, fresh heads) trained on gold; its calibrated probabilities become `dist` labels on unlabeled rows (`label_teacher.py`), and students are trained on gold + teacher-labelled rows (PLAN P3/P4). | +| DAgger | Exported students run as SIM's policy (`--on-policy`); SIM labels the states the student actually visits (`meta.on_policy`, `meta.model_probs`, ...); students retrain on them (PLAN P5). No DAgger script exists in `training/` yet. | +| T1 / gain | Expected-advantage target (sim/SEPARABILITY.md §7): gain(a) = mean_f cost(passive, f) − mean_f cost(a, f) − premium(tier) (guard 0.25, heal 0.5), passive 0, clipped ±30. Either the action label becomes softmax(gain/τ) (`r17-t1g10` τ 1, `r17-t1g20` τ 2) or SIM's label is kept and gains feed a regression **gain head** (`r17-t1h`, `--gain-loss`). | | `Op` (curriculum) | `world.py` → `Op{id, kind (user\|fetch\|timer\|ws\|task\|load), start, method, url, sig, body, end, status (ok\|error\|aborted), code, err ("timeout"\|"network error"\|""), cause, root, action, target, value, attempt}`; properties `req`, `identity` (`"{method} {url} {body}"`), `idempotent` (GET/HEAD/PUT/DELETE/OPTIONS). Ids start at `rng.randint(3, 400)` and advance by 1/1/1/2/3. `root` is inherited from `cause` at creation. | | `Trace` API | Builders `user`, `timer`, `fetch`, `finish` (status `ok` iff code < 400 and no err), `abort`, `init_field`, `write` (version = previous + 1), `extra`, `baseline`; queries `version(path, t)`, `writes_between`, `last_write`, `value`, `in_flight(t)` (fetches with `start < t`, so a `request` subject created at `now` is not in flight), `requests`, `users`, `root_of`, `root_desc`. `scenarios.cap_now` turns fetches ending after `now` back into in-flight ops. | @@ -97,7 +118,17 @@ Model candidates (README, EVAL.md, LOG; embedding arithmetic from the verified r | Pruned start point | `models/base/ettin-17m-v16k` (HF base; markers appended by `init_model`) | `models/r32-v16k` (pruned fast-engine checkpoint) | | `--base` in launches | `$G/models/base/ettin-17m-v16k` | `$G/models/r32-v16k/backbone` | | q8 / fp16 export (stage 1c) | 9.58 MB / 13.57 MB | 22.47 MB / 34.79 MB | -| Intended use | WASM default | WebGPU, only if clearly more accurate | +| Intended use | **Default on every device** (final1 decision, EVAL.md) | WebGPU, only if clearly more accurate (final1: it is not) | + +Scaled-program models (PLAN-v1 §3, LOG; all on the same pruned 16,364-token vocabulary, MIT ettin bases pruned to `models/base/ettin-{68m,150m}-v16k` by `prune_vocab.py`): + +| id | base | non-emb params (PLAN) | role | throughput per F80 node (8 ranks × 10 threads) | `launch_student.sh` defaults (lr / head-lr / grad-accum) | +|---|---|---|---|---|---| +| R17 | ettin-17m | 4.6M | WASM default student | 80–90k tok/s | 2e-4 / 1e-3 / 2 | +| R32 | ettin-32m via GenClass 0.1 | 14M | WebGPU student | ≈ 42k tok/s | 1e-4 / 4e-4 / 3 | +| R68 | ettin-68m | 42M | candidate student (benchmark, never run) | ≈ 19k tok/s (probe) | 2e-4 / 1e-3 / 2 (`launch_r68.sh`: 3e-4 / 1e-3 / 2) | +| T150 | ettin-150m | 111M | teacher, never shipped | ≈ 9.4k tok/s (probe; 16.5 GB RSS per rank) | 2e-4 / 1e-3 / 2 | +| T400 | ettin-400m | ≈ 350M | teacher only if T150 clearly beats R68 | ≈ 1.3k tok/s (est.) | — | `models/r17-v16k-init` (random heads, used by `test_export_runtime.py` and MODEL's latency runs) also exists on c01; the command that created it is not recorded (`jev_local/train/train.py` has `--init-only`, which writes an untrained servable with meta `trained: false`; unverified that it was used). @@ -137,7 +168,11 @@ Remote layout (scripts and LOG; `G=/home/azureuser/gcl-train`): | every node | `$G/cache/<round>/` | stream index cache (`--stream-cache`) | | c01 / rank-0 nodes | `$G/out/{eval,cal,records,export-<M>}/`, `$G/logs/` | eval reports, calibration files, cached logits, exports, job logs | | c01 / nodes | `~/xfer/` | tars served by `python3 -m http.server` (ports below) | -| train VM | `~/gcl/sim/sim/out/<run>/` | SIM outputs (`r300k`, `final-a`) | +| train VM | `/data/sim-out/<run>/` (old path `~/gcl/sim/sim/out` is now a symlink to it) | SIM outputs: `final-a` (v1 phase A), `final-b/parts/` (v1 phase B, 1,415,344 rows), `sep/`, `probe-150k/` (analysis only), `v2chk-{gold,unl}` (v2 pipeline check), `v2b5-100k` (first v2 + batch-5 + S1/S2 check, 64,754 decision rows; sim/SEPARABILITY.md §8), `v2-*` (v2 production, in progress) | +| train VM | `/data/real-out/<batch>/` | REAL (realapps) batches: `pilot4`, `pilot-all` (v1 audit), `v2-pilot`; v2 production `v2b1`–`v2b3` is still on c01/c10/c11 `~/gcl/real-out/` until copied (NEEDS 14–16; see [realapps.md](realapps.md)) | +| data VM | `~/simdata/<run>/` | SIM distributed batches (gz shards + `manifest.json`), e.g. `gold-r1x` (v1, 832,279 rows) | +| workbench (`WB`) | `~/xfer/label/` | `label_cluster.sh` teacher tar (`teacher-<TEACHER>.tar`) and the `src-<OUT_BUCKET>` symlink to `SRC_DIR`, served on `<WB private IP>:8805` | +| labelling nodes | `$G/data/label-src-<OUT_BUCKET>/`, `$G/data/s3/<OUT_BUCKET>/`, `/tmp/label-<OUT_BUCKET>.sh`, `$G/.label-<OUT_BUCKET>-done` | downloaded source shards, labelled output shards, the detached job script, the completion marker | | train VM | `~/gcl/train-out/<round>/<sub>/`, `~/gcl/train-out/ortweb/` | delivered exports; validation dir (`node_modules` → `~/gcl/model/node_modules`, Node at `$HOME/node/bin`) | Stream-root contents (which bucket lives under which root). Only `data/s2/<NAME>` and `data/s3/<NAME>` are created by scripts; the rest is inferred from launch flags and mixtures (unverified): @@ -147,7 +182,7 @@ Stream-root contents (which bucket lives under which root). Only `data/s2/<NAME> | `data/s1` | `cur1`, `gen`, `cu` (stage 1); also streamed in s2 and final1 | | `data/s1b` | `cur2` (streamed from s1c on) | | `data/s2` | `sim1` (`import_sim.sh`), `cur3` (README) | -| `data/s3` | `simA` (`import_final.sh`); `cur4` must also sit under `data/s3` or `data/s1` for `mix_final1.json` to find it (no script puts it there; see Gotchas) | +| `data/s3` | `simA` (`import_final.sh`); `cur4` must also sit under `data/s3` or `data/s1` for `mix_final1.json` to find it (no script puts it there; see Gotchas); `simAg10` / `simAg20` / `simAh` (`t1_relabel.py --out data/s3/<bucket>`); teacher-labelled buckets from `label_cluster.sh` (`data/s3/<OUT_BUCKET>`) | Datasets referenced by configs and scripts (sizes from LOG/EVAL; generator flags marked unverified where not in a script): @@ -157,13 +192,18 @@ Datasets referenced by configs and scripts (sizes from LOG/EVAL; generator flags | `cur2` | 400k / ? / 8k | seed 2, `--p-runtime 0.6` | 60% of decision rows runtime-exact, rendered by the first `rt.py` port (pre-freeze wording, 3,200-char budget only) | | `rt1` | — / 6k / 12k | `--p-runtime 1.0` (seed unverified) | runtime-style eval/calibration set, same pre-freeze port as `cur2`. Only decision rows are rendered runtime-style (and `failure/offline` falls back to varied); ask and standalone rows are varied. 12,000 test rows hold 6,583 decision rows (EVAL.md). | | `cur3` | 300k | seed 4, `--p-runtime 0.8` | stage-2 replay; adds coincidental-invariant cases; budgets 3,200 / 2,000 / 1,100 at 40/35/25% (before `transient`, compact questions and the 1,000 budget, LOG 18:41–19:02); at `data/s2/cur3` | -| `cur4` | 300k | seed 5, `--p-runtime 0.8` | final replay, frozen `situation-v1` wording (current `rt.py`); the raw set is `data/cur4/{train,dev,test}.jsonl` | +| `cur4` | 300k | seed 5, `--p-runtime 0.8` | final1 replay, frozen `situation-v1` wording (the `rt.py` of 654d822; today's `rt.py` renders v2); the raw set is `data/cur4/{train,dev,test}.jsonl` | | `gen`, `cu` | — | GenClass 0.1 v1 synthetic data (`data/gen` all, slice of `data/cu`) | replay only | | `sim1` | 224,051 / 7,426 / 68,790 | SIM `r300k` (pre-freeze) via `import_sim.sh` | `sim1e/test.jsonl` = 20k random test rows | | `simA` | 448,420 / 14,613 / 137,643 | SIM `final-a` (frozen) via `import_final.sh` | `simAe` = 8k dev / 20k test random rows | | `simsample` | 200 (123 decision rows) | `sim/samples/sample.jsonl` | zero-shot check in `run_evals.sh` | +| `simAg10`, `simAg20` | phase-A train shards, 291k of 448k rows relabelled | `t1_relabel.py --in data/s3/simA --tau 1.0 / 2.0` | T1 softmax(gain/τ) action labels + `meta.egain` (`mix_t1a`, `mix_t1b`) | +| `simAh` | same rows | `t1_relabel.py --keep-dist` (τ required but unused) | SIM labels kept, `labels.action.gain` + `meta.egain` added (`mix_t1h`) | +| v2 SIM / REAL | target ≥ 10M gold + ≥ 50M unlabeled (SIM), ≥ 500k gold (REAL) | `train:/data/sim-out/v2-*`, REAL `v2b1`–`v2b3` | **not imported yet**; no v2 bucket, mixture or curriculum set exists in `training/` | -Row `meta` written by the curriculum (`rows.py` → `decision_row`): `kind="decision"`, `trigger`, `case`, `domain`, `passive_best`, `action_gold` (shown name), `action_canonical`, `passive` (shown passive name), `diag_gold`, `action_names` (canonical → shown), `prims`, `heldout_templates_possible`, `soft_action`, `style`. Ask rows (`ask_row`): `kind="ask"`, `trigger="ask"`, `source_trigger`, `case`, `domain`, `prims`. Standalone: `kind="prim"`, `family`, `domain` (+ `code`, `err` for HTTP). Families: `cur/<trigger>/<case suffix>` (builder name dropped, see below), `cur/ask/<trigger>`, `cur/prim/{json_invariants,http,js_errors,decide}`. Curriculum rows carry **no `meta.budget`**. +Row `meta` written by the curriculum (`rows.py` → `decision_row`): `kind="decision"`, `trigger`, `case`, `domain`, `passive_best`, `action_gold` (shown name), `action_canonical`, `passive` (shown passive name), `diag_gold`, `action_names` (canonical → shown), `prims`, `heldout_templates_possible`, `soft_action`, `style`. Ask rows (`ask_row`): `kind="ask"`, `trigger="ask"`, `source_trigger`, `case`, `domain`, `prims`. Standalone: `kind="prim"`, `family`, `domain` (+ `code`, `err` for HTTP). Families: `cur/<trigger>/<case suffix>` (builder name dropped, see below; `<trigger>` is the rendered one, so `delivery` for mutation scenarios rendered as deliveries), `cur/ask/<trigger>`, `cur/prim/{json_invariants,http,js_errors,decide}`. Curriculum rows carry **no `meta.budget`**. + +SIM / REAL row `meta` fields TRAIN reads (NEEDS 11/14; see [sim.md](sim.md), [realapps.md](realapps.md)): `trigger`, `passive`, `best`, `passive_best`, `costs`, `cost_futures` (per action, one cost per sampled future; T1 uses it), `tiers`, `non_passive_mass`, `diagnosis`, `budget`, `transform`, `diagnosis_only`; gold vs `unlabeled: true` (gold `labels.diagnosis` only) vs `on_policy: true` (`model_probs`, `model_choice`, `ran`, `false_intervention`, `miss`); `clean`; REAL adds `source = "realapps"`, `app`, `framework`, `libs`, `integration`, `patterns`, `oss`, `runtime`, and its eval set `real_eval.jsonl` carries `eval_case` / `eval_expect`. `label_teacher.py` adds `meta.teacher`; `t1_relabel.py` adds `meta.egain`. ## How it works @@ -183,7 +223,7 @@ Result used everywhere: N = 16,000 merges → vocab **16,364** = 245 + 16,000 + 1. `main` builds jobs of `--chunk` (default 5000) rows per split; dev default = max(2000, n/50), test default = max(4000, n/25). Workers run `work(split, chunk, n, seed, out)` with `random.Random(f"{seed}:{split}:{chunk}")`, so output is independent of `--workers` but depends on `--chunk`. 2. `make_row`: test split draws a domain from `TEST_DOMAINS`, else from train domains; builds `App` and `Style.make(rng, test)`; picks a kind from `KINDS` = decision 0.58, ask 0.14, json 0.10, http 0.08, js 0.04, decide 0.06. 3. Decision/ask: pick a trigger from `TRIGGERS` (mutation 0.26, request 0.20, failure 0.18, stall 0.12, inconsistency 0.09, transition 0.08, error 0.07), run its builder → `Scen`, then `rows.decision_row(sc, app, st, rng, P_RUNTIME)` or `rows.ask_row`. -4. `decision_row`: if `p_runtime > 0` and `rng.random() < p_runtime`, call `rt.render`; on success emit runtime-exact state/questions (labels restricted to offered actions, 0–2 primitives: choice of (0,0,1,2), `style="runtime"`). Otherwise varied: `situation_state` (≤ 12 facts, shuffled 25%; ≤ 8 state lines; timeline ≤ 16; in-flight ≤ 6; 15% drop one of in_flight/stats/state; 10% shuffle key order; key names from `Style`), `action_question` (10%: rename via `RENAMES`; 15%: insert 1–2 `DISTRACTOR_ACTIONS`; 50% shuffle; descriptions canonical or paraphrased; 10% bare names), `diagnosis_question` (20%: subset keeping gold + `expected` + 2–5 others; 50% shuffle; 10% bare labels), 15% question order swapped, `action` removed if < 2 actions, 0–3 primitives (choice of (0,1,2,2,3)). +4. `decision_row`: if `p_runtime > 0` and `rng.random() < p_runtime`, call `rt.render(sc, app, rng, info=rinfo)`; on success emit runtime-exact state/questions (trigger and action names from `rinfo`, so a mutation may become a `delivery` row with `apply` relabelled `deliver`; labels restricted to offered actions, 0–2 primitives: choice of (0,0,1,2), `style="runtime"`). Otherwise varied: `situation_state` (≤ 12 facts, shuffled 25%; ≤ 8 state lines; timeline ≤ 16; in-flight ≤ 6; 15% drop one of in_flight/stats/state; 10% shuffle key order; key names from `Style`), `action_question` (10%: rename via `RENAMES`; 15%: insert 1–2 `DISTRACTOR_ACTIONS`; 50% shuffle; descriptions canonical or paraphrased; 10% bare names), `diagnosis_question` (20%: subset keeping gold + `expected` + 2–5 others; 50% shuffle; 10% bare labels), 15% question order swapped, `action` removed if < 2 actions, 0–3 primitives (choice of (0,1,2,2,3)). 5. `_validate` runs `jev_local.serialize.state_segments`, `question_block` and the trainer's `parse_target` on every label; invalid rows are counted in `stats["bad"]`, generator exceptions in `stats["errors"]`; neither is emitted. Each chunk tries at most 3n times. 6. Valid rows get id `cur-{split}-{chunk:05d}-{i:06d}`; `fmt.js_numbers` is applied to `state` and `questions` (integral floats → ints, NEEDS item 8). Chunks are concatenated into `{train,dev,test}.jsonl`; `stats.json` has per-split counters and `passive_best_fraction` per trigger. @@ -211,15 +251,20 @@ Offered actions (`Scen.actions`, which become the `action` criteria): mutation a Measured passive-best shares of `cur1` train decision rows: mutation 0.50, request 0.51, failure 0.54, stall 0.63, inconsistency 0.42, transition 0.70, error 0.66 (LOG; generated before the `coincidental` and `transient` changes). -### 3. Runtime-exact rendering (`training/curriculum/rt.py` → `render`) - -1. Returns `None` (row falls back to varied style) when `sc.spec` is empty or `spec["no_runtime"]` (currently `failure/offline`: CORE cannot produce an offline fact). -2. Per trigger builds facts as `(text, kind, neutral)` tuples with CORE's computations: `mutation_facts` (provenance, per-path versions with same-chain vs other-writer logic and `started_rel` "started 0.09s after #6", inputs moved incl. "is back to", concurrency, baseline, failed cause, pending local change, repetition, delta), `request_common` (provenance, attempt, identical requests in the last 10 s, other same-signature requests, failure streak, rate vs usual, baseline with `error_rate_text`, cache, idempotency), `failure_facts`, `stall_facts`, `inconsistency_facts`, `transition_facts`, `error_facts`. -3. `order` sorts non-neutral first, then by `RANK` (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), stable; identical to `packages/runtime/src/situation/facts.ts` → `RANK`. -4. Sections: `subject_sentence`, `in_flight_lines`, `event_lines` (timers omitted, like CORE), `state_lines`, `stats_lines` ("F of last N failed" over ≤ 20 outcomes via `failure_counts`). -5. Budget: `GC_RT_BUDGET` env (analysis) or `spec["budget"]` or a draw from `BUDGETS` = 3200 (0.35) / 2000 (0.30) / 1000 (0.35). `to_state` applies `section_limits` (linear between `COMPACT_BUDGET` 1100 and `STATE_CHAR_BUDGET` 3200, `MIN_BUDGET` 500) then shrinks timeline (oldest first) → state → facts (floor 1) → in_flight → stats until `size_chars` ≤ budget; mirrors `packages/runtime/src/situation/serialize.ts` → `toJevState`. -6. Questions: `diagnosis` always, with `DIAG_INSTR` "What is happening here?" and `DIAGNOSES` (10 labels); `action` only if ≥ 2 of `TRIGGER_ACTIONS[trigger]` are in `sc.actions`, with `ACTION_INSTR[trigger]`. At budget ≤ `COMPACT_QUESTIONS_MAX` (1400) every criterion is `null` (bare labels), as in `questions.ts` → `buildQuestions`. -7. Details that matter for byte parity: `app` = `"{app.title} — {app.route()}"`; an empty list section becomes the string `"none"`; `size_chars(state)` = Σ over keys of `len(key) + 2 + len(text) + 1`, where `text` is `"\n".join(value)` for a list and `str(value)` otherwise (= `serialize.ts` → `stateChars`); `failure_text` prints `HTTP <code>` and appends the `world.STATUS_TEXT` reason phrase for a deterministic ≈ 30% of ops (`(op.id * 2654435761) % 10 < 3`), because `Response.statusText` is usually empty in browsers and in SIM. Spec keys `extra_facts` (rendered as `plugin`-kind facts) and `budget` are read by `render` but no scenario sets them, so the budget is always drawn from `BUDGETS` (or `GC_RT_BUDGET`). Mutation rows add `spec["state_extra"]` paths (e.g. the query field) to the state section. +### 3. Runtime-exact rendering (`training/curriculum/rt.py` → `render`, frozen at `situation-v2`) + +1. Returns `None` (row falls back to varied style) when `sc.spec` is empty or `spec["no_runtime"]` (still only `failure/offline`: the curriculum never sets the `online: false` spec key that would let `scope_facts` render the v2 offline fact). +2. **Delivery choice (v2).** For a mutation scenario, `spec.get("delivery", rng.random() < P_DELIVERY)` (one RNG draw per mutation row) and `delivery_spec` succeeds (cause = completed OK fetch, or a `ws` op) → the row is rendered as `delivery` if the gold action survives the mapping (see Concepts → Delivery row). `delivery_spec` builds the v2 `DeliverySpec`: channel `response` / `websocket`, predicted writes (`source` `profile` when the signature has a baseline, else `last`; patterns via `normalize_field_path`), `matched` paths, `conflicts_on`, `defers` (spec, default 0), `queued_ahead` 0, `incoming` = `spec["after"]`. When `info` is passed, `render` writes `info["trigger"]` and `info["action_map"]`; `rows.decision_row` relabels with them. +3. Per trigger builds facts as `(text, kind, neutral)` tuples with CORE's computations: + - `mutation_facts`: provenance; `version_facts` on ≤ 3 paths (non-neutral **only** for a newer-data conflict (`newer_conflict`) or a pending local change (`pending_conflict`), a v2 change from v1 where any other-writer write was non-neutral); `content_facts` when `spec["after"]` exists (F1 "would put the older value back", F2 "would replace text the user typed", F3 "matches the current values ... changes nothing"); `cadence_fact`; `moved_facts` and `concurrency_facts` (both always neutral in v2); cause baseline / failure; `mark_facts`; repetition with `repeat_evidence` (F7) for separate user actions; delta via `change_text` (diff-centred `string_diff` for long strings). + - `delivery_facts` (new): arrival line ("The response to … arrived after …; the app has not seen it yet." or the WS message line), cause provenance, predicted-writes profile, `version_facts` (conflicted paths first), `pending_revert_facts` + `content_facts` against `incoming`, `mark_facts`, `cadence_fact`, `moved_facts`, `concurrency_facts`, usual latency, preceding failure streak. + - `request_common` (adds `repeat_evidence`), `failure_facts` (adds F5 `commit_ambiguity` for methods other than GET/HEAD/OPTIONS: a "usually return without processing" sentence for `NOT_PROCESSED` = {502, 503, 429, 408}, a "may have applied it" / "well before its usual" sentence for other 5xx, timeouts and network errors, nothing for other 4xx; `scope_facts` over other endpoints of the same origin in the last 10 s, `cadence_fact`), `stall_facts` (adds `scope_facts`, `cadence_fact`), `inconsistency_facts` / `transition_facts` / `error_facts` (add `mark_facts`; inconsistency writes use `change_text`). + - Inputs the curriculum Trace does not model come from optional spec keys that **no scenario sets**: `marks` (F9), `cadence` (F6), `online`, `clicks` (F7 multi-click), `defers`, `message_summary`, `delivery` (force). So F6/F9 facts, the offline fact and multi-click evidence never appear in curriculum rows; read-your-writes and list-item joins are not modelled at all. +4. `order` sorts non-neutral first, then by `RANK` (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), stable; identical to `packages/runtime/src/situation/facts.ts` → `RANK`. +5. Sections: `subject_sentence` (v2 delivery: "The response to … arrived and is about to be delivered; <predicted_text>." / "A WebSocket message … arrived and is about to be delivered; …"), `in_flight_lines`, `event_lines` (timers omitted, like CORE; write lines use `change_text`), `state_lines`, `stats_lines` ("F of last N failed" over ≤ 20 outcomes via `failure_counts`). +6. Budget: `GC_RT_BUDGET` env (analysis) or `spec["budget"]` or a draw from `BUDGETS` = 2400 (0.35) / 2000 (0.20) / 1667 (0.05) / 1333 (0.05) / 1000 (0.35), i.e. WebGPU/unknown 2,400 and WASM 1–4 threads 1,000 / 1,333 / 1,667 / 2,000 (`packages/runtime/src/runtime.ts` → `situationBudget`). `to_state` applies `section_limits` (linear between `COMPACT_BUDGET` 1100 and `STATE_CHAR_BUDGET` **2400**, `MIN_BUDGET` 500) then shrinks timeline (oldest first) → state → facts (floor 1) → in_flight → stats until `size_chars` ≤ budget; mirrors `packages/runtime/src/situation/serialize.ts` → `toJevState`. +7. Questions: `diagnosis` always, with `DIAG_INSTR` "What is happening here?" and `DIAGNOSES` (10 labels); `action` only if ≥ 2 of `TRIGGER_ACTIONS[trigger]` are among the (mapped) offered actions, with `ACTION_INSTR[trigger]` (delivery: "What should the runtime do with this response or message?") and descriptions from `TRIGGER_DESCRIPTIONS[trigger]` first, else `ACTIONS` (= `questions.ts` → `actionDescription`). At budget ≤ `COMPACT_QUESTIONS_MAX` (1400) every criterion is `null` (bare labels), as in `questions.ts` → `buildQuestions`. +8. Details that matter for byte parity: `app` = `"{app.title} — {app.route()}"`; an empty list section becomes the string `"none"`; `size_chars(state)` = Σ over keys of `len(key) + 2 + len(text) + 1`, where `text` is `"\n".join(value)` for a list and `str(value)` otherwise (= `serialize.ts` → `stateChars`); `failure_text` prints `HTTP <code>` and appends the `world.STATUS_TEXT` reason phrase for a deterministic ≈ 30% of ops (`(op.id * 2654435761) % 10 < 3`), because `Response.statusText` is usually empty in browsers and in SIM. Spec keys `extra_facts` (rendered as `plugin`-kind facts) and `budget` are read by `render` but no scenario sets them. Mutation and delivery rows add `spec["state_extra"]` paths (e.g. the query field) to the state section. ### 4. Training (stage 1, stage 2, final round) @@ -227,7 +272,7 @@ Measured passive-best shares of `cur1` train decision rows: mutation 0.50, reque 2. Data must be sharded (the stream index/length cache is built per file in parallel: one 1.8 GB file took minutes, 64 shards 24 s). The import scripts use `split -n l/64`. 3. From the Mac, a launch script calls `scripts/launch_run.sh RUN MASTER_IP NPROC THREADS "nodes" -- <train.py args>`. For each node (in order, node rank = position) it ssh-es and starts `python -m torch.distributed.run --nnodes N --nproc-per-node NPROC --node-rank R --master-addr MASTER --master-port 29500 -m jev_local.train.train --ddp --threads THREADS --run-name RUN ...` detached (`setsid nohup nice -n 5`, from `~/jev` with `.venv/bin/python`), with `OMP_NUM_THREADS=THREADS`, `GLOO_SOCKET_IFNAME=eth0`, `JEV_ENCODER=banded`, `TOKENIZERS_PARALLELISM=false`, `HF_HUB_OFFLINE=1`; stdout/stderr go to `~/jev/runs/RUN/rank<R>.out` while the trainer's own state and `log.jsonl` go to `--runs-dir` (`$G/runs/RUN/`). 4. `jev_local/train/train.py` → `train`: `init_model(--base)`; rank 0 alone loads `runs/<run>/ckpt` if `--resume` and it exists, else `--init-from` (servable dir or trainer-state dir, weights only, fresh optimizer/schedule), then broadcasts. So **rank 0 must be the node holding the `--init-from` path**. -5. Stream mode builds `MixConfig.from_json(--mixture, **CLI overrides)` over `--stream` roots; `stream.py` → `discover` walks each root recursively (`<root>/raw/**` if present, else `<root>/**`; `*.jsonl` and `*.jsonl.zst`; hidden dirs skipped), buckets come from the shard's parent directory name (`_names`), and rows are filtered by their `split` field (default `("train",)`), so dev/test files under a root are ignored. Weights merge over `DEFAULT_BUCKET_WEIGHTS` (the v2 `b1_*`…`s0_families` table, irrelevant here); buckets absent from `bucket_weights` get `OTHER_BUCKET_WEIGHT` = 0.04 unless `buckets` restricts them; weights are renormalised over the buckets actually present, so a missing bucket silently drops out; unknown JSON keys raise. +5. Stream mode builds `MixConfig.from_json(--mixture, **CLI overrides)` over `--stream` roots; `stream.py` → `discover` walks each root recursively (`<root>/raw/**` if present, else `<root>/**`; `*.jsonl` and `*.jsonl.zst`; hidden dirs skipped), buckets come from the shard's parent directory name (`_names`), and rows are filtered by their `split` field (default `("train",)`), so dev/test files under a root are ignored. Weights merge over `DEFAULT_BUCKET_WEIGHTS` (jev's own PLAN §2.1 table `b1_tasksource_jev`…`s0_families`, unrelated to situation-v2 and irrelevant here); buckets absent from `bucket_weights` get `OTHER_BUCKET_WEIGHT` = 0.04 unless `buckets` restricts them; weights are renormalised over the buckets actually present, so a missing bucket silently drops out; unknown JSON keys raise. 6. Checkpoints every `--ckpt-every` steps to `runs/<run>/ckpt` and the servable `--out` (meta adds `base`, `max_len`, `run`, `trained`, `step`, `final`); `final: true` only when step ≥ total. `calibration.json` in the servable is the default (all temperatures 1.0). 7. Stop cleanly with `pkill -TERM -f "run-name r32-s1[c] "` on the rank-0 node (bracket trick so pkill does not match itself); ranks agree to drop the partial step and rank 0 checkpoints. @@ -241,16 +286,19 @@ Runs as executed (LOG; `G=/home/azureuser/gcl-train`). The s1c, s2 and final1 co | `r17-s1c` | c09–c11, master 10.0.0.14 | `mix_s1c` | `runs/r17-s1/ckpt` | 2.5e-4 / 1.5e-3 | 2 | 1536 | 1 pass, 1,092 steps / 39 min | | `r32-s2` (`launch_s2.sh`) | c02–c05 | `mix_s2`; `data/s2 data/s1b data/s1`, seed 2 | `runs/r32-s1c/ckpt` | 1e-4 / 4e-4 | 3 | 2048 | 1.5, 625 steps | | `r17-s2` | c09 c10 c11 c06 c07 c08 | `mix_s2` | `runs/r17-s1c/ckpt` | 2e-4 / 1e-3 | 2 | 2048 | 4, 1,664 steps | -| `r32-final1` (`launch_final1.sh`) | c02–c07 | `mix_final1`; `data/s3 data/s1`, seed 3, cache `cache/final1` | `runs/r32-s1c/ckpt` | 1e-4 / 4e-4 | 3 | 2048 | 2.4 × 498M tokens (in progress) | -| `r17-final1` | c09 c10 c11 c08 | `mix_final1` | `runs/r17-s1c/ckpt` | 2e-4 / 1e-3 | 2 | 2048 | 3.0 (in progress) | +| `r32-final1` (`launch_final1.sh`) | c02–c07 | `mix_final1`; `data/s3 data/s1`, seed 3, cache `cache/final1` | `runs/r32-s1c/ckpt` | 1e-4 / 4e-4 | 3 | 2048 | 2.4 × 498M tokens, 771 steps, 1 h 25 min (done 01:36) | +| `r17-final1` | c09 c10 c11 c08 | `mix_final1` | `runs/r17-s1c/ckpt` | 2e-4 / 1e-3 | 2 | 2048 | 3.0, 2,168 steps, 1 h 12 min (done 01:20) | +| `t150-g1` (teacher, `launch_t150.sh` presumably; exact command unrecorded) | c12–c23 (12 × 8 ranks × 10 threads) | `mix_t150` (simA .9, cur4 .1); `data/s3` | ettin-150m pruned, fresh heads | 2e-4 / 1e-3 | 2 | 2048 | 2 passes (≈ 940M tokens) at ≈ 106k tok/s; **stopped at step 69** (after the lead's 01:30 situation-v2 note; c10–c23 deallocated 01:35); checkpoint kept on c12's disk | +| `r17-t1g10` / `r17-t1g20` (T1, command unrecorded) | c09 c10 c11 c08 / c02–c05 | `mix_t1a` / `mix_t1b` | `r17-s1c` | as r17-final1 (LOG) | | | 3 passes planned; **stopped** at ≈ step 1,350 / 2,168 (03:32), resumable, no result | +| `r17-t1h` (gain head, `--gain-loss 1.0`) | c01 c06 c07 c12 | `mix_t1h` | `r17-s1c` | as r17-final1 | | | 3 passes planned; **stopped** at ≈ 1,000; gain loss 0.98 → 0.85 vs trivial predictors 0.97–1.01 | -Measured throughput (LOG): `r32-s1` ≈ 215k tok/s (5 s/step), falling to 134k with the 4 × 20 layout; `r17-s1` 165–210k; 1-node R17 pilot 68–70k (4 × 20) vs 93–95k (8 × 10); `r32-s2` ≈ 168k, `r17-s2` ≈ 449k; `r32-final1` ≈ 253k, `r17-final1` ≈ 322–333k tok/s. Stage-1 loss 0.28 / 0.27 at steps 60 / 140; first stage-2 step 0.76 (R32) / 0.80 (R17). Stage 1c logged no dropped questions and no bad labels. +Measured throughput (LOG): `r32-s1` ≈ 215k tok/s (5 s/step), falling to 134k with the 4 × 20 layout; `r17-s1` 165–210k; 1-node R17 pilot 68–70k (4 × 20) vs 93–95k (8 × 10); `r32-s2` ≈ 168k, `r17-s2` ≈ 449k; `r32-final1` ≈ 253k, `r17-final1` ≈ 322–333k tok/s; per-node probes R68 ≈ 19k, T150 ≈ 9.4k tok/s. Stage-1 loss 0.28 / 0.27 at steps 60 / 140; first stage-2 step 0.76 (R32) / 0.80 (R17). Stage 1c logged no dropped questions and no bad labels. Final rounds deliberately restart from the stage-1c weights (the s2 pilots saw pre-freeze text). Layout rule from LOG: 8 ranks × 10 threads per F80 node; 4 × 20 left ranks idle ≈ 45% of each step (per-micro-batch Python overhead dominates for these small models). ### 5. Final-round pipeline (frozen data) -1. `training/import_final.sh /home/azureuser/gcl/sim/sim/out/final-a simA` (from the Mac): train VM serves the SIM dir on `10.0.0.4:8802`; c01 downloads `{train,dev,test}.jsonl` (+ `stats.json`) into `data/simA/`, splits train into `data/s3/simA/shardNN.jsonl` (64), builds `data/simAe/test.jsonl` (`shuf -n 20000`, random source `yes 7`) and `data/simAe/dev.jsonl` (8000, `yes 8`), shards them into `data/simAe_t{0..3}/test.jsonl` and `data/simAe_d{0,1}/dev.jsonl`, tars `data/s3 data/simAe data/simAe_* data/cur4 training` into `~/xfer/final_simA.tar` (2.57 GB) and serves `~/xfer` on `10.0.0.6:8799`. +1. `training/import_final.sh /home/azureuser/gcl/sim/sim/out/final-a simA` (from the Mac; env `WB` = workbench host, default c01, its private IP is looked up in `azure_hosts`; `FILES` = splits to download, default `train dev test`; `PORT` = train-VM port, default 8802, one per source dir): train VM serves the SIM dir on `10.0.0.4:$PORT`; the workbench downloads `{train,dev,test}.jsonl` (+ `stats.json`) into `data/simA/`, splits train into `data/s3/simA/shardNN.jsonl` (64), builds `data/simAe/test.jsonl` (`shuf -n 20000`, random source `yes 7`) and `data/simAe/dev.jsonl` (8000, `yes 8`), shards them into `data/simAe_t{0..3}/test.jsonl` and `data/simAe_d{0,1}/dev.jsonl`, tars `data/s3 data/simAe data/simAe_* data/cur4 training` into `~/xfer/final_simA.tar` (2.57 GB) and serves `~/xfer` on `<WB private IP>:8799` (10.0.0.6 for c01). The script always splits `train.jsonl` and builds the `e` subsets from `test`/`dev`, so a `FILES` list without all three fails under `set -e`; it always bundles `data/cur4`. 2. Start c02–c11, `node.sh <node> sync`, pull and untar `final_simA.tar` from `10.0.0.6:8799` on each node (manual step). `mix_final1.json` needs a `cur4` bucket, i.e. `cur4` train shards under `data/s3/cur4/` or `data/s1/cur4/`; `import_final.sh` bundles the whole `data/s3` and the raw `data/cur4/`, but no script in the repo shards `cur4` into a stream root (presumably done by hand on c01; unverified). If it is missing, the trainer silently renormalises over `simA`, `cur1`, `gen`. 3. `training/launch_final1.sh <R32 passes> <R17 passes>`. 4. On each rank-0 node a detached waiter (not in the repo) waits for `models/<M>/meta.json` `"final": true`, then runs `training/final_post.sh <M> <name> <version>` (example in the script: `r17-final1 genclass-runtime-r17 1.0.0-rc1`): `EVAL_THREADS=12 eval_sim.sh simAe <M>` → `out/eval/<M>-simAe.json` + `out/cal/<M>-simAe.json`; `export_runtime.py --calibration out/cal/<M>-simAe.json --data-rows data/simAe/dev.jsonl,data/cur4/dev.jsonl --n-per-file 60 --threads 24` → `out/export-<M>/`; markers `out/.post-done-<M>`, `out/.served-<M>`; tar without `ref/` → `~/xfer/export-<M>.tar`, served on `<hostname -I first IP>:8801`. The script runs with `set -u` but not `-e`: a failed eval still runs the export (which then fails on the missing calibration file) and the markers are touched anyway, so check `logs/final-eval-<M>.log` and `logs/final-export-<M>.log`. Its first redirect writes `logs/final-eval-<M>.log` before `eval_sim.sh` creates `logs/`, so `~/gcl-train/logs/` must already exist on the node. @@ -262,11 +310,11 @@ Final rounds deliberately restart from the stage-1c weights (the s2 pilots saw p 2. `get_records` → `collect` calls `jev_local/train/eval.py` → `collect` (banded encoder, `max_len` from ckpt meta, default 2048) and keeps one record per supervised question `{id, qid, kind, labels, logits, target, header}`; `header` is `sha1(header)[:12]`. With `--records-dir`, raw logits are cached as `<ckpt.name>__<data.name>__<split>.jsonl` and **reused whenever the file exists**. 3. Calibration: `--calibration file` loads `noul/choice/score/by_header` (action and diagnosis use `choice`). `--fit-split dev` instead fits: `fit_tau` (golden section on log τ in [0.2, 5], 40 iterations, soft-target NLL) for `choice` (all choice questions incl. standing ones), `score`, `action`, `diagnosis`; `fit_tau_noul` (61-point log grid in [0.2, 5]); `by_header` for standing-question headers with ≥ 300 records. A split-half check fits on even `crc32(id)` and scores odd ids. 4. For each mode in raw/kind/group/header (only raw without temperatures): `question_metrics` (per group `action`, `diagnosis`, `choice`, `score`, `noul`, `all`: n, acc, NLL, Brier, ECE with 15 bins) and `decision_metrics`. -5. `decision_metrics` (rows with both `action` and `diagnosis`): maps shown names back with `meta.action_names`; passive-best = gold == `PASSIVE[trigger]` (fallback `meta.passive` for unknown triggers) or `TIER[gold] == "passive"`; per mode guard (guard tier) / heal (guard + heal): *A* = offered actions whose tier is permitted (unknown names default to heal), candidate = argmax p over *A*, fire iff Σ p(A) ≥ `THRESH[tier(candidate)]` and top diagnosis ≠ `expected`. Counts FIR, precision (candidate == gold), recall (on rows whose gold is a permitted non-passive action), and with `meta.costs`: mean cost of policy / always-passive / oracle and harm on passive rows. Breakdowns `by_trigger`, `by_case`, `by_style`, `by_budget`; `sweep` at 0.5/0.6/0.7/0.8/0.9/0.95 (heal set); `diag_confusion`; top-30 `false_fires_detail` (`mode:trigger:cand<-gold`). +5. `decision_metrics` (rows with both `action` and `diagnosis`): maps shown names back with `meta.action_names` (`canonical`; for curriculum delivery rows `deliver` maps back to `apply`); passive-best = gold == `PASSIVE[trigger]` (fallback `meta.passive` for triggers not in `PASSIVE`, which includes v2 `delivery`) or `TIER[gold] == "passive"` (`deliver` is passive, so SIM delivery rows work); per mode guard (guard tier) / heal (guard + heal): *A* = offered actions whose tier is permitted (unknown names default to heal), candidate = argmax p over *A*, fire iff Σ p(A) ≥ `THRESH[tier(candidate)]` and top diagnosis ≠ `expected`. Counts FIR, precision (candidate == gold), recall (on rows whose gold is a permitted non-passive action), and with `meta.costs`: mean cost of policy / always-passive / oracle and harm on passive rows. Breakdowns `by_trigger`, `by_case`, `by_style`, `by_budget`; `sweep` at 0.5/0.6/0.7/0.8/0.9/0.95 (heal set); `diag_confusion`; top-30 `false_fires_detail` (`mode:trigger:cand<-gold`). 6. `primitive_acc` per qid family (trailing digits stripped). Report JSON to `--out`; `--write-calibration` writes `{noul, choice, score, by_header, _fit}` (`by_header` only with `--header-calibration`, else `{}`). The fitted `action` / `diagnosis` temperatures are only recorded in `_fit.taus`: the shipped file applies `choice` to the standing questions unless `--header-calibration` adds their exact headers (lookup is by header, then by kind, with optional `by_bucket` / `tau_k` / `noul_platt` steps in between that these files never contain; there is no per-qid key: `packages/runtime/src/model/calibrate.ts`, `jev_local/engine/encoder/calibrate.py` → `calibrate_logits` / `tau_for`). If both `--calibration` and `--fit-split` are given, the fit wins. Console prints the `kind` mode summary. -7. Report layout: `ckpt, data, split, n_rows, n_questions, taus, calibration_from | calibration_fit_on, split_half{taus_even, odd_raw, odd_with_even_taus_{kind,group,header}}, questions_<mode>{<group>: {n, acc, nll, brier, ece}}, decisions_<mode>{n, action_acc, diag_acc, modes{guard,heal}, by_trigger, by_case, by_style, by_budget, sweep, diag_confusion, false_fires_detail}, primitive_acc`. Each `modes.<m>` = `{false_intervention_rate, false_fires, passive_rows, precision, fires, recall, active_rows[, mean_cost{policy, always_passive, oracle, rows, harm_on_passive_rows}]}`. +7. Report layout: `ckpt, data, split, n_rows, n_questions, taus, calibration_from | calibration_fit_on, split_half{taus_even, odd_raw, odd_with_even_taus_{kind,group,header}}, questions_<mode>{<group>: {n, acc, nll, brier, ece}}, decisions_<mode>{n, action_acc, diag_acc, modes{guard,heal}, by_trigger, by_case, by_style, by_budget, sweep, diag_confusion, false_fires_detail}, primitive_acc`. Each `modes.<m>` = `{false_intervention_rate, false_fires, passive_rows, precision, fires, recall, active_rows, recall_clear, clear_rows, recall_clear_stale_dup, clear_stale_dup_rows[, mean_cost{policy, always_passive, oracle, rows, harm_on_passive_rows}]}`. Clear rows (added for PLAN-v1's recall target): not passive-best, gold permitted in the mode, and the gold target's max probability ≥ 0.9; a hit = the gate fires with the gold action; the `_stale_dup` pair restricts to gold diagnosis `stale` or `duplicate`. 8. Batch drivers: `run_evals.sh TAG M...` (stage 1, per model in parallel): `rt1` test with `rt1` dev fit → `out/cal/<M>.json`, then SIM sample (`data/simsample/test.jsonl`, how it was created from `sim/samples/sample.jsonl` is not scripted) with that calibration; `cur1` test with its own dev fit; `cur2` test raw. `eval_sim.sh NAME M...`: for every shard dir `data/NAME_t*` (test) and `data/NAME_d*` (dev) it runs `eval_runtime.py --records-dir out/records --batch 32 --threads $EVAL_THREADS` in parallel only to fill the logit cache, concatenates `out/records/<M>__NAME_t*__test.jsonl` → `<M>__NAME__test.jsonl` (same for dev), then one `eval_runtime.py --data data/NAME --split test --fit-split dev --write-calibration out/cal/<M>-NAME.json` reads the merged cache. -9. `training/report.py name=report.json ... [--mode=kind]` (default `kind`; falls back to `raw` when the report has no `decisions_<mode>`) prints the EVAL.md tables (main table, SIM cost table when `mean_cost` exists, per trigger, per budget, sweep, taus + split-half NLL/ECE). +9. `training/report.py name=report.json ... [--mode=kind]` (default `kind`; falls back to `raw` when the report has no `decisions_<mode>`) prints the EVAL.md tables (main table, clear-case recall table (guard/heal × all/stale+duplicate, with row counts), SIM cost table when `mean_cost` exists, per trigger, per budget, sweep, taus + split-half NLL/ECE). ### 7. Export (`training/export_runtime.py` → `main`) @@ -288,6 +336,29 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th 3. Per backend: `missing_inputs` (`meta.json` `inputs` absent from the session), `max_abs_logit`, `argmax_agree/argmax_total` (questions with > 1 logit), `ms_p50/p90`, `tokens_p50`, `runtime_sized` (requests ≥ 400 tokens), and `est_ms_at_seq_tokens` at 500 / 780 / 1170 tokens (≈ 330 / 600 / 1,000-token states plus the standing questions) from a least-squares fit `ms ≈ a + bL + cL²`. Writes `<dir>/ortweb_report_<variant>.json` (`{dir, variant, file, bytes, results[]}`). 4. It has no pass/fail: a backend error is caught and recorded as `{backend, error}` (the process still exits 0; only unreadable `model.json`/fixtures crash it). There are no thresholds; read `max_abs_logit`, `argmax_agree` and `error` yourself (the delivery scripts print them). +### 9. Teacher, soft-labelling and distillation (PLAN-v1 P1–P4; prepared, not yet run on v2) + +1. **Teacher training:** `training/launch_t150.sh RUN PASSES "nodes" MASTER_IP` (or `launch_student.sh RUN t150 ...`). Every listed node first prunes `ettin-encoder-150m` to `models/base/ettin-150m-v16k` if missing; then `scripts/launch_run.sh` with `--stream $G/data/s3` only, `mix_t150.json`, `--max-len 2048 --batch-tokens 8192 --grad-accum 2 --ckpt-every 25 --seed 4 --lr 2e-4 --head-lr 1e-3 --resume`. `mix_t150.json` names v1 buckets (`simA`, `cur4`); a v2 teacher needs a new mixture over the imported v2 gold buckets. +2. **Generic launcher:** `training/launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra]`. `ARCH` picks base / lr / head-lr / grad-accum (table in Concepts; all 8 ranks × 10 threads); rank 0 and master = the first node (private IP from `azure_hosts`); before launching it makes sure every node has the pruned 68m and 150m bases (for every arch); fixed flags `--stream $G/data/s3 $G/data/s1 --stream-cache $G/cache/$RUN --max-len 2048 --batch-tokens 8192 --balance --amp --no-grad-ckpt --device cpu --log-every 10 --ckpt-every 25 --seed 7 --resume`, plus `--init-from INIT` when given (must exist on the first node). `MIX` is a file name under `training/configs/` (the header's example `mix_v2_distill.json` does not exist yet). +3. **Soft-labelling one shard:** `$PY training/label_teacher.py --ckpt models/T --in shard.jsonl --out labelled.jsonl [--calibration cal.json] [--qids action,diagnosis]`. `load_checkpoint(..., encoder="banded")`, packs with `Packer(tok, max_len, buckets=train_buckets(max_len))` and `encode_example` (same packing as training), runs the heads, applies `calibrate_logits(kind, header_key(header), z, calib)` (the checkpoint's `calibration.json` unless `--calibration`), and writes per question: choice → `{"type":"choice","dist":{label:p}}`, score → `{"type":"score","dist":[...]}`, noul → `{"type":"noul","p":p}`. Existing (gold) labels are kept unless `--overwrite`; SIM/REAL unlabeled rows carry a gold `labels.diagnosis` (NEEDS), so with the default `QIDS=action,diagnosis` only `action` gets a teacher label there (the teacher's diagnosis probabilities still go into `meta.teacher`). `meta.teacher` = `{ckpt, <qid>: {top, margin[, non_passive_mass]} | {p}}` (`non_passive_mass` for `action`, over labels not in `PASSIVE` = apply/send/deliver/wait/ignore). Resumable: an existing `--out` is continued after its last complete line (a torn last line is dropped). Prints `{rows, resumed_after, seconds, tokens_per_s}`. Tested by LOG: R17 labelled 64 SIM rows at 11.5k tok/s on 16 threads. +4. **Across nodes:** `training/label_cluster.sh WB TEACHER CAL SRC_DIR OUT_BUCKET "nodes" [PROCS=8] [QIDS]` tars `models/TEACHER` + `CAL` on the workbench, symlinks `SRC_DIR` into `~/xfer/label/src-OUT_BUCKET`, serves `~/xfer/label` on `<WB IP>:8805`, assigns shards round-robin (`NR % nodes`), and on each node writes and detaches `/tmp/label-OUT.sh`: download the teacher and its shards, `xargs -P PROCS` one `label_teacher.py --batch 32 --threads 80/PROCS` per shard into `data/s3/OUT_BUCKET/`, then touch `~/gcl-train/.label-OUT_BUCKET-done`. Logs `logs/label-OUT-<shard>.log`. Re-running skips downloaded shards and resumes each output. Untested (LOG); it does **not** gather the outputs back to the workbench (the header says "then are gathered on WB"): copy them yourself. +5. **Distil:** train students with `launch_student.sh` on a mixture of gold + teacher-labelled buckets + 5–10% curriculum replay (PLAN P4). No distillation mixture exists yet. +6. **DAgger (P5):** export students → SIM `--on-policy` generation (owned by SIM, see [sim.md](sim.md)) → import → retrain. Not scripted in `training/`. + +### 10. T1 expected-gain experiments (`t1_relabel.py`, `eval_gain.py`, `collect_gain.py`) + +1. `$PY training/t1_relabel.py --in data/s3/simA --out data/s3/simAg10 --tau 1.0 [--workers 16] [--keep-dist]`: per `*.jsonl` shard in parallel; for each row with an `action` question and label, `gains_of(meta, offered)` uses `meta.cost_futures` (falls back to `meta.costs` as single futures), `meta.tiers` and `meta.passive` (falls back to the passive-tier action); gain per offered action with costs = mean passive cost − mean action cost − `PREM[tier]` (unknown tier = heal 0.5), clipped to ±`CLIP` (30); passive = 0. Rows without costs or with < 2 gains are copied unchanged. Default: action label = softmax(gain/τ) over offered actions that have costs (an offered action without costs gets no mass); `--keep-dist`: keep SIM's label and add `labels.action.gain` (ignored by this repo's `parse_target`). Both write `meta.egain`. Prints `{files, rows, relabelled, tau}`. +2. Train on the new bucket (`mix_t1a` / `mix_t1b` / `mix_t1h`); the gain-head run adds trainer flag `--gain-loss W` (smooth-L1, β 2, on `labels.action.gain`), which exists only in the parent-repo `jev_local` (LOG 03:00), not in this monorepo. +3. `t1_post.sh RUN TAU` / `t1h_post.sh RUN` (detached on the run's rank-0 node): wait for `models/RUN/meta.json` `final`, `EVAL_THREADS=12 eval_sim.sh simAe RUN`, (gain head: `collect_gain.py` per `data/simAe_t*` shard with 12 threads, concatenated to `out/records/RUN__simAe__test.gain.jsonl`), then `eval_gain.py`. +4. `eval_gain.py --rows data/simAe/test.jsonl --model name=records:cal[:tau]`: per mode (guard = guard-tier actions; heal = guard + heal), per row `classify` (clear / benign / mild over futures, see Concepts), oracle = Σ max(0, best gain). Policies: `gate@t` for t ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 0.95} (CONTRACT §8 summed-mass gate with the `expected` diagnosis veto; probabilities at the calibration's `choice` τ), `gate@t-nodiag` (no veto; t ∈ {0.5, 0.7, 0.8, 0.9, 0.95}, no 0.6), `gain>m` for T1 models (ĝ(a) = τ·(z_a − z_passive) on raw logits, m ∈ {0, 0.5, 1, 2, 3, 4}), `head>m` and `head>m+diag` for records with `gain_pred`. Metrics: `fired_share`, `recall_clear`, `benign_fired`, `harmful_share` (fired true gain < −1), `gain_captured` (÷ oracle), `net_gain_per_row`, `fir_label` (passive-label rows fired). +5. Baseline (LOG 02:40, R17-final1, heal, 12,901 test decision rows, 912 clear, 9,720 benign, oracle 0.91 gain/row): gate@0.8 captures 6.7% of the oracle gain (recall on clear 8.1%, harmful 0.09%); gate@0.5 31% (recall 38%, harmful 1.3%, label-FIR 5.1%). With τ = 1 the soft labels put ≥ 0.5 non-passive mass on 64% of rows, so a summed-mass gate is the wrong rule for gain-shaped probabilities (T1 needs a per-action gate). + +### 11. Cluster expansion (`cluster_expand.sh`, `node_init.sh`) + +1. From the Mac (needs `az` logged in): `training/cluster_expand.sh c24:Standard_F80ads_v7 ...`. Skips names already in `~/.jev-local/azure_hosts`; `az vm create` in `rg-jev-train` (Ubuntu 24.04, user `azureuser`, key `~/.ssh/jev_azure.pub`, VNet `vm-jev-trainVNET` / subnet `vm-jev-trainSubnet`, NSG `nsg-jev-train`, 256 GB Premium OS disk, accelerated networking, tags `project=jev-local purpose=train-cluster`), first with `--ppg ppg-jev`, then without on failure (900 s timeout each); appends `NAME PUB PRIV SIZE`; creates `shutdown-computevm-vm-jev-NAME` (DevTestLab, 03:00 UTC, **Disabled**). +2. Serve a node kit tar from an existing node (how it is built is not scripted; LOG: served by c10; the port 8801 comes from the script's example URL `http://10.0.0.15:8801/kit.tar`) and run `bash node_init.sh http://<ip>:8801/kit.tar` on the new node: apt `rsync zstd pigz`, untar into `~`, create `~/gcl-train/{logs,out,runs}` and `~/jev/runs`, pip-install `onnx==1.23.1 onnxruntime==1.30.0 onnxscript==0.7.2 onnxconverter_common==1.16.0`, print torch/transformers versions, touch `~/.node_init_ok`. Then `node.sh NAME sync`. +3. Policy (HANDOFF): never delete VMs; deallocate idle nodes; claim nodes in NEEDS.md; run `az` calls one at a time, each in `timeout`; the nightly DevTestLab shutdown schedules are Disabled for the training push and must be re-enabled when it ends (`az resource update ... --set properties.status=Enabled`, command in HANDOFF). Our side does not touch Azure at all without the user's go-ahead. + ## Configuration and constants | Name | Type | Value / default | Defined in | Effect | @@ -306,12 +377,17 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th | `Style.make(canonical=)` | float | 0.55 | `fmt.py` | share of canonical-style rows | | `held_count` | fn | max(1, round(0.2 n)) if n ≥ 4 else 0 | `fmt.py` | held-out template tail | | `TEST_DOMAINS` | set | 13 of 62 | `vocab.py` | test-only domains (test asserts 15–30%) | -| `STATE_CHAR_BUDGET` | int | 3200 | `rt.py` (= `serialize.ts`) | full-size situation | +| `STATE_CHAR_BUDGET` | int | 2400 (situation-v2; was 3200) | `rt.py` (= `serialize.ts`) | full-size situation; WebGPU / unknown-device auto budget | | `COMPACT_BUDGET`, `MIN_BUDGET` | int | 1100, 500 | `rt.py` (= `serialize.ts`) | section-limit interpolation floor; smallest budget | | `COMPACT_QUESTIONS_MAX` | int | 1400 | `rt.py` (= `questions.ts` `COMPACT_QUESTIONS_BUDGET`) | bare-label standing questions at ≤ this budget | -| `BUDGETS` | (chars, weight) | (3200, .35), (2000, .30), (1000, .35) | `rt.py` | budget draw; mirrors runtime "auto" budgets (WASM 1 thread 1000 … 4 threads 2000; else 3200: `packages/runtime/src/runtime.ts` → `situationBudget`) | +| `BUDGETS` | (chars, weight) | (2400, .35), (2000, .20), (1667, .05), (1333, .05), (1000, .35) | `rt.py` | budget draw; mirrors runtime "auto" budgets (WASM `1000 + round((threads-1)·1000/3)` for 1–4 threads; else 2400: `packages/runtime/src/runtime.ts` → `situationBudget`) | | `LIMITS` | dict | facts 12, in_flight 6, timeline 16, state 8, stats 4 | `rt.py` | full-budget section sizes | -| `section_limits` | fn | facts 6→12, in_flight 2→6, timeline 3→16, state 3→8, stats 1→4; line caps app 60→120, trigger 180→240, facts 220→260, in_flight 90→120, timeline 100→140, state 100→150, stats 110→140 | `rt.py` | linear in budget between 1100 and 3200 | +| `section_limits` | fn | facts 6→12, in_flight 2→6, timeline 3→16, state 3→8, stats 1→4; line caps app 60→120, trigger 180→240, facts 220→260, in_flight 90→120, timeline 100→140, state 100→150, stats 110→140 | `rt.py` (= `serialize.ts` → `sectionLimits`) | linear in budget between 1100 and 2400 | +| `P_DELIVERY` | float | 0.5 | `rt.py` | share of eligible mutation scenarios rendered as v2 `delivery` (`spec["delivery"]` forces; never set) | +| `DELIVERY_ACTION` | dict | apply→deliver, discard→discard, defer→defer | `rt.py` | action map for delivery rows | +| `TRIGGER_DESCRIPTIONS` | dict | delivery: deliver / discard / defer descriptions | `rt.py` (= `questions.ts`) | trigger-specific action descriptions | +| `PENDING_WINDOW_MS` | ms | 10,000 | `rt.py` (= `conflicts.ts`) | pending-local-change lookback | +| `NOT_PROCESSED` | set | 502, 503, 429, 408 | `rt.py` (= `evidence.ts`) | statuses reported as "usually return without processing" in commit ambiguity | | `WINDOW` | ms | 10,000 | `rt.py` (= `facts.ts`) | "in the last 10s" windows | | mixture `max_repeat` default | float | 2.0 | `jev_local/train/stream.py` → `MixConfig` | per-pass repeat cap per group | | `OTHER_BUCKET_WEIGHT` | float | 0.04 | `stream.py` | weight of buckets not named in `bucket_weights` | @@ -320,11 +396,17 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th | `mix_s1c.json` | mixture | cur2 .55, cur1 .37, gen .03, cu .05; 520M; cur2 1.5, cur1 1.0 | `configs/` | stage 1c | | `mix_s2.json` | mixture | sim1 .76, cur3 .12, cur2 .05, cur1 .03, gen .01, cu .03; 420M; sim1 1.5 | `configs/` | stage-2 pilot | | `mix_final1.json` | mixture | simA .85, cur4 .12, cur1 .02, gen .01; `buckets` = those 4; 500M; `*` 2.0, simA 1.3 | `configs/` | final round 1 | +| `mix_t150.json` | mixture | simA .9, cur4 .1; `buckets` = those 2; 470M; `*` 2.0, simA 1.2 | `configs/` | teacher `t150-g1` (v1) | +| `mix_r68.json` | mixture | simA .8, cur4 .12, cur1 .07, gen .01; 520M; simA 1.3 | `configs/` | R68 benchmark (never run) | +| `mix_t1a.json` / `mix_t1b.json` / `mix_t1h.json` | mixture | as `mix_final1` with `simA` replaced by `simAg10` / `simAg20` / `simAh` | `configs/` | T1 runs | | `--max-len` | int | trainer default 1536; 1536 in stage 1c (s1 command unrecorded); 2048 stage 2/final (SIM packed p95 1,523, max 1,761) | `jev_local/train/train.py`, README, launch scripts | written to servable/exported `meta.json` `max_len` | | `--batch-tokens` | int | 8192 | launch scripts | micro-batch token budget | | `--ckpt-every` | int | trainer default 500; launch scripts pass 50 | `jev_local/train/train.py` | checkpoint cadence (a SIGKILL loses at most this many steps) | | `MAX_TRAIN_LEN` | int | 8192 | `jev_local/train/train.py` | upper bound for `--max-len` | -| `--seed` | int | s1c 1, s2 2, final1 3 | launch scripts | mixture/shuffle seed | +| `--seed` | int | s1c 1, s2 2, final1 3, `launch_t150.sh` 4, `launch_r68.sh` 5, `launch_student.sh` 7 | launch scripts | mixture/shuffle seed | +| `--ckpt-every` (new launchers) | int | 25 | `launch_student.sh`, `launch_t150.sh`, `launch_r68.sh` | checkpoint cadence (PLAN: ≤ 10 min) | +| label defaults | args | `--batch 32`, `--threads 16`, `--max-len 2048`; cluster `PROCS` 8 (threads 80/PROCS), `QIDS` `action,diagnosis` | `label_teacher.py`, `label_cluster.sh` | teacher labelling | +| `PREM` / `CLIP` | dict / float | passive 0, guard 0.25, heal 0.5 / 30 | `t1_relabel.py`, `eval_gain.py` (`PREM` duplicated) | T1 gain premium and clip (SIM's definitions) | | `DEFAULT_CALIBRATION` | dict | `{noul: 1.0, choice: 1.0, score: 1.0, by_header: {}}` | `jev_local/engine/encoder/calibrate.py` | what every trainer-written servable ships | | `node.sh` remote env | env | `PYTHONPATH=$HOME/jev:$HOME/gcl-train/training`, `PY=$HOME/jev/.venv/bin/python`, `HF_HUB_OFFLINE=1`, `TOKENIZERS_PARALLELISM=false`, cwd `~/gcl-train` | `node.sh` | environment of `node.sh HOST 'cmd'` (also set by `eval_sim.sh`, `run_evals.sh`, `final_post.sh`) | | torchrun master port | int | 29500 | `scripts/launch_run.sh` | DDP rendezvous | @@ -343,7 +425,7 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th | `meta.json` `max_len` / `max_total` | int | ckpt meta `max_len` or 1536 / 8192 | `export_runtime.py` | runtime packer limits | | ortweb versions | str | onnxruntime-node 1.30.0, onnxruntime-web 1.30.0 | `ortweb/package.json` | validation runtime | | validate defaults | args | variant q8, 60 requests (delivery scripts pass 120) | `validate.mjs` | — | -| ports | int | 8798 (train VM → c01 one-off v1 tar), 8799 (c01 data bundles, 10.0.0.6), 8801 (node → c01/train VM tars), 8802 (train VM SIM dir, 10.0.0.4) | scripts, LOG | `python3 -m http.server` transfers on the private network | +| ports | int | 8798 (train VM → c01 one-off v1 tar), 8799 (workbench data bundles, 10.0.0.6 for c01), 8801 (node → c01/train VM tars; node kit), 8802 (train VM SIM dir, 10.0.0.4; `import_final.sh` `PORT`), 8805 (workbench → nodes, `label_cluster.sh`), 8810 (train VM SIM bundle server, NEEDS) | scripts, LOG, NEEDS | `python3 -m http.server` transfers on the private network | | `TIMEOUT` | env s | 900 | `node.sh` | per-call ssh/scp timeout for `'cmd'`/`get`/`put` (`sync` uses fixed 120 s / 600 s timeouts; `scripts/azvm.sh` and therefore `scripts/launch_run.sh` ignore it) | Model directory files (`export_runtime.py`): @@ -360,33 +442,40 @@ Model directory files (`export_runtime.py`): ## Invariants and gotchas -- **Runtime parity of `rt.py` is load-bearing.** Constants and wording (`DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR`, `TRIGGER_ACTIONS`, `RANK`, `LIMITS`, budgets, `secs`/`rel`/`ratio`/`fmt_num`, `signature`/`is_id`) must equal `packages/runtime/src/situation/{questions,serialize,facts,describe,build}.ts` and `src/util.ts`. They match at this commit (runtime situation code is unchanged since tag `situation-v1` = 1a77558; `rt.py` was re-ported after it). Per-header calibration keys are `sha1(instructions)[:12]`, so any instruction text change silently orphans `by_header` temperatures. +- **Runtime parity of `rt.py` is load-bearing.** Constants and wording (`DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR`, `TRIGGER_ACTIONS`, `RANK`, `LIMITS`, budgets, `secs`/`rel`/`ratio`/`fmt_num`, `signature`/`is_id`) must equal `packages/runtime/src/situation/{questions,serialize,facts,conflicts,content,evidence,describe,build}.ts`, `src/state/fields.ts` (`changeText`/`stringDiff`) and `src/util.ts`. `rt.py` was ported against tag `situation-v2` (6e5e86e); `git diff 6e5e86e b435acb -- packages/runtime/src/situation packages/runtime/src/state/fields.ts` is empty (the only later runtime change, the default mode `observe` in `runtime.ts`, does not touch the situation). Spot-checked at b435acb: `STATE_CHAR_BUDGET` 2400, `COMPACT_BUDGET` 1100, `MIN_BUDGET` 500, `COMPACT_QUESTIONS_BUDGET` 1400, `RANK`, `sectionLimits`, `situationBudget`, `TRIGGER_DESCRIPTIONS`, delivery instruction and `DEFAULT_DIAGNOSES` match; a full byte-parity check against runtime output was not run (unverified). Per-header calibration keys are `sha1(instructions)[:12]`, so any instruction text change silently orphans `by_header` temperatures. - **Known small parity gaps** in `rt.py`: `to_state`'s last-resort shortening truncates facts to max(40, …) and never shortens the trigger, while `toJevState` uses max(60, …) and then shortens the trigger; Python `round()` (banker's) vs JS `Math.round` in `secs` (≥ 1000 s) and `ratio` (≥ 10×); Python format specs (`f"{x:.2f}"`, half-even on exact binary ties) vs JS `toFixed` (ties up) in `secs`/`rel`/`fmt_num`, e.g. `secs(125)` is `0.12s` in Python and `0.13s` in JS; `truncate` counts code points (Python `len`) vs UTF-16 code units (JS `length`), so text with astral characters such as emoji is cut at different points. Rare, but they produce text the runtime never sends. - **Numbers as JS prints them.** `fmt.js_numbers` turns integral floats into ints in `state` and `questions` (not in `labels`/`meta`); without it the model trains on `25.0`, which the JS runtime never emits (NEEDS item 8). Keep it when adding new emit paths. -- **Determinism** is per code version: `random.Random(f"{seed}:{split}:{chunk}")`, sorted iteration where sets are involved. Changing any generator code, `--chunk`, or `--p-runtime` from 0 to > 0 (it adds an RNG draw) changes the rows; `cur1`/`cur2` cannot be regenerated byte-identically from the current code (the generator gained `transient`, `coincidental`, budgets and compact questions since). +- **Determinism** is per code version: `random.Random(f"{seed}:{split}:{chunk}")`, sorted iteration where sets are involved. Changing any generator code, `--chunk`, or `--p-runtime` from 0 to > 0 (it adds an RNG draw) changes the rows; `cur1`/`cur2`/`cur3`/`cur4` cannot be regenerated byte-identically from the current code (the generator gained `transient`, `coincidental`, budgets and compact questions, and v2 adds a `P_DELIVERY` draw per runtime-rendered mutation row and different facts/budgets). - **Held-out integrity:** test rows only use `TEST_DOMAINS` and may use held-out templates; train/dev never do. `test_curriculum.py` asserts both. Do not add a domain to `DOMAINS` without deciding its split. - **Precision first:** decision rows must keep a large passive-best share (test bound 0.45–0.75); soft labels for ambiguous cases lean passive. SIM's passive-best shares are much higher (pre-freeze SIM sample: 70–96% per EVAL.md; phase A train: 64% stall to 99% error, `sim/samples/stats-final-a.json`, see [sim.md](sim.md)), which is why stage 2 is required. - **Single-action rows** have no `action` question/label (runtime behaviour). `eval_runtime.py` skips them in `decision_metrics`, so `diag_acc` there covers only rows that also have an `action` question. - **Calibration must be shipped explicitly.** A trained servable's `calibration.json` is all 1.0; `export_runtime.py` without `--calibration` ships uncalibrated temperatures. The runtime gate thresholds assume calibrated probabilities. - **Stale logit cache:** `eval_runtime.py --records-dir` reuses `<ckpt.name>__<data.name>__<split>.jsonl` if present, even after the checkpoint changed. Delete `out/records/<M>__*` before re-evaluating a retrained model with the same name. `eval_sim.sh` concatenates shard records by this naming. - **q8 must be fp16-free.** Onnxruntime's WebGPU Gather on an fp16 table requires `shader-f16` ("Program Gather requires f16"); the int8 table + fp32 row scales runs on WebGPU without it (MODEL confirmed in Chromium/SwiftShader). `make_q8` raises on any fp16 tensor or cast; keep the `gemm_to_matmul` rewrite (without it the noul head stays fp32, +2.9 MB). -- **Rank 0 holds the init.** Only rank 0 reads `--resume` state or `--init-from`; the first node in the launcher list must have `runs/<model>-s1c/ckpt` (c02 for R32, c09 for R17). `--resume` wins over `--init-from` when `runs/<run>/ckpt/trainer.json` exists, so reusing a run name resumes instead of re-initialising. -- **Mixture buckets are directory names.** Put shards in `<stream root>/<bucket>/`. Without a `buckets` list, any extra bucket dir under a stream root silently gets weight 0.04 (`OTHER_BUCKET_WEIGHT`); `mix_final1.json` is the only config that lists `buckets`. +- **Rank 0 holds the init.** Only rank 0 reads `--resume` state or `--init-from`; the first node in the launcher list must hold the init (for final1: `runs/<model>-s1c/ckpt`, c02 for R32, c09 for R17; the stopped `t150-g1` checkpoint is only on c12's disk). `--resume` wins over `--init-from` when `runs/<run>/ckpt/trainer.json` exists, so reusing a run name resumes instead of re-initialising. +- **Mixture buckets are directory names.** Put shards in `<stream root>/<bucket>/`. Without a `buckets` list, any extra bucket dir under a stream root silently gets weight 0.04 (`OTHER_BUCKET_WEIGHT`); `mix_final1.json` and the newer `mix_t150`, `mix_r68`, `mix_t1a/b/h` list `buckets`; `mix_s1*`/`mix_s2` do not. - **Marker ids moved.** With the pruned vocab, `[Q] [O] [L] [T] [F]` are 16359–16363; runtime, sim tooling and tests must read them from `tokenizer.json` / `meta.json` (CONTRACT §10). With 16k merges, keys like `trigger`, `facts`, `apply`, `defer` split into several tokens (harmless; trained on the pruned tokenizer). -- **Token budget vs characters:** the runtime's 3200-char budget assumes ≈ 3.2 chars/token, measured ≈ 2.4 (NEEDS 6a), so situations are ≈ 1.3–1.4× the intended 1,000 tokens; 3.9% of SIM `r300k` packed rows exceed 1,536 tokens, hence `max_len` 2048 for stage 2 (LOG). The smaller 1,000/2,000-char WASM budgets were adopted for latency (LOG 19:00 coordinator/MODEL note). -- **Script path layout:** `node.sh`, `import_*.sh`, `deliver_final.sh`, `launch_*.sh` resolve `JEV="$HERE/../.."` (or `cd "$(dirname "$0")/../.."`) and expect `jev_local/`, `scripts/launch_run.sh`, `scripts/azvm.sh`, `pyproject.toml` there. In this monorepo they are at the repo root (`$HERE/..`), so run them from a checkout nested inside a jev tree or adjust the path (unverified). `~/.jev-local/azure_hosts` columns: name, public IP ($2, used for ssh), private IP ($3); key `~/.ssh/jev_azure`, user `azureuser`. Mac-side scripts use GNU `timeout`. Only the Mac-side `.sh` files are committed executable (git mode 100755); `run_evals.sh`, `eval_sim.sh` and all `.py` files are 100644, so invoke them via `bash` / `$PY`. +- **Token budget vs characters:** the v1 runtime's 3200-char budget assumed ≈ 3.2 chars/token, measured ≈ 2.4 (NEEDS 6a), so situations are ≈ 1.3–1.4× the intended 1,000 tokens; 3.9% of SIM `r300k` packed rows exceed 1,536 tokens, hence `max_len` 2048 for stage 2 (LOG). The smaller 1,000/2,000-char WASM budgets were adopted for latency (LOG 19:00 coordinator/MODEL note); situation-v2 lowered the full budget to 2,400 (≈ 1,000 tokens, per the `situationBudget` comment). +- **Script path layout:** `node.sh`, `import_*.sh`, `deliver_final.sh`, `launch_*.sh` (incl. `launch_student.sh`, `launch_t150.sh`, `launch_r68.sh`) and `label_cluster.sh` (via `node.sh`) resolve `JEV="$HERE/../.."` (or `cd "$(dirname "$0")/../.."`) and expect `jev_local/`, `scripts/launch_run.sh`, `scripts/azvm.sh`, `pyproject.toml` there. In this monorepo they are at the repo root (`$HERE/..`), so run them from a checkout nested inside a jev tree or adjust the path (unverified). `~/.jev-local/azure_hosts` columns: name, public IP ($2, used for ssh), private IP ($3); key `~/.ssh/jev_azure`, user `azureuser`. Mac-side scripts use GNU `timeout`. `label_cluster.sh` only calls `node.sh HOST 'cmd'`, whose command mode does not use `JEV` (only `node.sh sync` rsyncs `$JEV/{jev_local,scripts,pyproject.toml}`); `cluster_expand.sh` and `node_init.sh` have no path assumption. File modes: `run_evals.sh`, `eval_sim.sh`, `t1_post.sh`, `t1h_post.sh` and all `.py` files are 100644 (invoke them via `bash` / `$PY`); every other `.sh` is 100755, including the VM-side `final_post.sh` and `pull_on_train.sh`. - **Python import paths:** `export_runtime.py`, `eval_runtime.py`, `generate.py`, `prune_vocab.py analyze` and the tests insert `~/jev` (and `~/jev/scripts`) into `sys.path`; elsewhere set `PYTHONPATH=<repo>:<repo>/scripts:<repo>/training`. -- **`azvm.sh` ignores `TIMEOUT`** (only `node.sh` honours it), so `TIMEOUT=... scripts/azvm.sh` lines in `import_sim.sh`/`deliver_final.sh` and `TIMEOUT=300 scripts/launch_run.sh` in `launch_*.sh` have no timeout. `import_final.sh` deliberately has no `pkill` (a self-killing `pkill` was a past bug: the remote shell's command line matched the pattern); stop the train VM's :8802 server with `pkill -f "http.server 880[2]"` in a command that does not itself contain `http.server 8802`. `import_sim.sh`'s first remote command still has the old pattern (its `pkill` runs only when :8802 is already listening, and the same command line later contains `http.server 8802 --bind`, so it can kill its own shell); stop any running server first or reuse `import_final.sh`'s logic. +- **`azvm.sh` ignores `TIMEOUT`** (only `node.sh` honours it), so `TIMEOUT=... scripts/azvm.sh` lines in `import_sim.sh`/`deliver_final.sh` and `TIMEOUT=300 scripts/launch_run.sh` in `launch_*.sh` have no timeout. `import_final.sh` deliberately has no `pkill` (a self-killing `pkill` was a past bug: the remote shell's command line matched the pattern); stop the train VM's :8802 server with `pkill -f "http.server 880[2]"` in a command that does not itself contain `http.server 8802` (the script's closing comment prints that pattern even when `PORT` is not 8802; bracket the last digit of the port you used). `import_sim.sh`'s first remote command still has the old pattern (its `pkill` runs only when :8802 is already listening, and the same command line later contains `http.server 8802 --bind`, so it can kill its own shell); stop any running server first or reuse `import_final.sh`'s logic. - **`pull_on_train.sh` expects `validate.mjs` already in `~/gcl/train-out/ortweb`** (it does not copy it; `deliver_final.sh` does). - **Bug (curriculum):** `standalone.json_invariants` writes the `count` invariant check as `j_count` and then overwrites `questions["j_count"]`/`labels["j_count"]` with the "price above threshold" score question, so the count==len check never reaches the data. Rows stay valid. -- **Tests do not exercise `rt.py` by default.** `generate.make_row` reads the module global `P_RUNTIME` (from `GC_P_RUNTIME`, default 0), and `test_curriculum.py` calls `make_row` directly, so runtime-exact rendering is only tested with `GC_P_RUNTIME=1` in the environment. Run it both ways after touching `rt.py`. Setting `GC_P_RUNTIME` has no effect on a `generate.py` CLI run; there, `--p-runtime` wins. -- **`rt1` and `cur2` predate the freeze.** They were rendered by the first `rt.py` port (3,200-char budget, pre-`situation-v1` fact wording, no `transient`, no compact questions), so the stage-1c `rt1` numbers measure the old runtime format. Only `cur4` (and SIM `final-a`) use the frozen wording. Regenerating `rt1` with today's code gives a different set. -- **Runtime budgets between the drawn ones.** The runtime's auto budget is `1000 + round((threads - 1) * 1000 / 3)` on WASM (1,000 / 1,333 / 1,667 / 2,000 for 1–4 threads), else 3,200, and either is multiplied by `budgetScale` (starts at 1; × 0.8 per `max_tokens_exceeded` model error, floor 0.5); a numeric `budget` option overrides all of it (`packages/runtime/src/runtime.ts` → `situationBudget`). `rt.BUDGETS` only draws 1,000 / 2,000 / 3,200; intermediate budgets rely on `section_limits` interpolation generalising. +- **Tests do not exercise `rt.py` by default.** `generate.make_row` reads the module global `P_RUNTIME` (from `GC_P_RUNTIME`, default 0), and `test_curriculum.py` calls `make_row` directly, so the five older tests only exercise runtime-exact rendering with `GC_P_RUNTIME=1` in the environment. The new `test_runtime_rows_situation_v2` calls `decision_row(..., 1.0)` directly and covers v2 always. Run the suite both ways after touching `rt.py`. Setting `GC_P_RUNTIME` has no effect on a `generate.py` CLI run; there, `--p-runtime` wins. An exported-but-empty `GC_P_RUNTIME=` makes `import generate` raise `ValueError` (seen on this machine). +- **Every existing data set predates situation-v2.** `rt1` and `cur2` were rendered by the first `rt.py` port (3,200-char budget, pre-`situation-v1` wording); `cur3`/`cur4`, SIM `final-a`/`final-b`/`gold-r1x` and the REAL pilots use situation-v1. None has `delivery` rows, the v2 facts or the 2,400 budget. Every mixture in `configs/` names only v1 buckets, and every checkpoint (incl. `r17-final1`) reads v1 text. A v2 replay set (`generate.py --p-runtime 0.8` with the current code) and v2 SIM/REAL imports are prerequisites for any v2 round; the only v2 data at this commit is on Azure (`train:/data/sim-out/v2-*`, REAL `v2-pilot`, `v2b1`–`v2b3`). +- **Runtime budgets between the drawn ones.** The runtime's auto budget is `1000 + round((threads - 1) * 1000 / 3)` on WASM (1,000 / 1,333 / 1,667 / 2,000 for 1–4 threads), else 2,400 (v2), and either is multiplied by `budgetScale` (starts at 1; × 0.8 per `max_tokens_exceeded` model error, floor 0.5); a numeric `budget` option overrides all of it (`packages/runtime/src/runtime.ts` → `situationBudget`). v2 `rt.BUDGETS` now draws all five device budgets (1,333 and 1,667 at 5% each), but scaled budgets (× 0.8, …) and app-configured budgets still rely on `section_limits` interpolation generalising. - **Missing mixture buckets are silent.** `stream.py` renormalises weights over the buckets it finds, so a typo in a bucket dir or a forgotten `cur4` shard dir trains on a different mix without an error. Check the plan before or at launch: `python -m jev_local.train.stream <roots...> --mixture <mix.json>` prints it, and the trainer writes `$G/runs/<run>/mixture_plan.json` (corpus summary + pass-0 plan; LOG's "cur1 93.1%, cu 6.2%, gen 0.7%" for `mix_s1` is this kind of realised share). - **`merges_kept: null` in exported `meta.json`** for every trainer-written checkpoint (see Export). Nothing reads it today; `vocab_size` and `markers` are always set. - **Dead code in `rt.py`:** `LINE` (superseded by `section_limits`' line caps) and `err_rate` (EWMA emulation, superseded by `failure_counts`) are unused; edit `section_limits` / `failure_counts` instead. +- **The gain head is not in this repo.** `collect_gain.py` reads `HeadOut.gain`, `t1h_post.sh` depends on it, and the `r17-t1h` run used trainer flag `--gain-loss`; all three exist only in the parent-repo `jev_local` on the nodes (`~/jev`, LOG 03:00: `DecisionHeads(gain_head=…)`, `add_gain_head()`, `HeadOut.gain`). This monorepo's `jev_local/engine/encoder/heads.py` → `HeadOut` has only `choice`, `score`, `noul`, so `collect_gain.py` raises `AttributeError` against it. Port the head before relying on these scripts outside the cluster. +- **Curriculum delivery rows are only as rich as the Trace.** No scenario sets `marks`, `cadence`, `online`, `clicks`, `defers` or `message_summary`, so the v2 facts F6, F9, offline and multi-click never appear in curriculum rows, and `queued_ahead` is always 0. SIM/REAL rows are the source for those facts. +- **`launch_t150.sh` header vs code:** the header says "6 ranks × 13 threads per node"; the code defaults to `RANKS=8`, `THREADS=10` (what `t150-g1` used, 16.5 GB RSS per rank). Pass `RANKS=6 THREADS=13` explicitly on smaller-RAM nodes. +- **`launch_student.sh` prunes the 68m and 150m bases on every node for every arch** (cheap when present; minutes on a fresh node), and always streams `data/s3 data/s1` (unlike `launch_t150.sh`, which streams only `data/s3`). +- **`label_cluster.sh` leaves outputs on the labelling nodes** (`data/s3/<OUT_BUCKET>/` on each); its `.label-*-done` marker only means the `xargs` finished, not that every shard succeeded (check `logs/label-<OUT>-<shard>.log`). Untested end to end (LOG). +- **`eval_runtime.PASSIVE` has no `delivery` key.** Passive detection still works through `meta.passive` and `TIER["deliver"] == "passive"`, but `decision_metrics`' `by_trigger` breakdown will show `delivery` as its own trigger; keep `TIER`/`PASSIVE` in sync with the runtime when adding triggers. +- **T1 labels and the §8 gate do not mix.** softmax(gain/τ) labels put ≥ 0.5 summed non-passive mass on 64% of phase-A rows (LOG), so evaluate T1 models with `eval_gain.py`'s `gain>m` / `head>m` policies, not only `eval_runtime.py`'s summed-mass gate. - **Past bugs recorded in LOG:** typeahead requests could start out of keystroke order (fixed with a per-app debounce in `mut_typeahead`); noul head Gemm left fp32 (fixed by `gemm_to_matmul`); Python float literals in rows (fixed by `js_numbers`). -- **Licensing hygiene:** no TRAIN script reads `jev-local-fast-v2`, `meharsjev-68m-z`, `z-cal-*`, `z-mid*` or any benchmark/third-party dataset (verified by grep at this commit). Keep it that way; the model card claims Apache-2.0 synthetic-only data. +- **Licensing hygiene:** no TRAIN script reads `jev-local-fast-v2`, `meharsjev-68m-z`, `z-cal-*`, `z-mid*` or any benchmark/third-party dataset (re-verified by grep at b435acb, incl. the new scripts). Keep it that way; the model card claims Apache-2.0 synthetic-only data. ## How to change it safely @@ -397,7 +486,7 @@ Model directory files (`export_runtime.py`): 4. Stage 1 (`r*-s1`, exact command not in the repo) then stage 1c: the `launch_run.sh r32-s1c ...` / `r17-s1c ...` commands in `training/README.md` §3. 5. Stage 2 / final: `import_sim.sh` + `launch_s2.sh`, or `import_final.sh` + distribute the tar + `launch_final1.sh P32 P17`. 6. Copy servables to c01 if needed (`pull_ckpt.sh <M> <node>`), evaluate (`run_evals.sh` for curriculum sets, `eval_sim.sh <NAME>e <M>` for SIM), tabulate with `report.py`. -7. Export with the fitted calibration, validate with `ortweb/validate.mjs`, deliver with `pull_on_train.sh` / `deliver_final.sh` (or `final_post.sh` on the rank-0 node for the automated tail). +7. Export with the fitted calibration, validate with `ortweb/validate.mjs`, deliver with `pull_on_train.sh` / `deliver_final.sh` (or `final_post.sh` on the rank-0 node for the automated tail). Publishing the export to npm follows [RELEASE.md](../../RELEASE.md). **Regenerate a curriculum set** (on c01, after `node.sh c01 sync`): ``` @@ -406,16 +495,28 @@ $PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --see Then shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl <root>/<bucket>/shard`) under a stream root, add the bucket to a mixture, and check `stats.json` (`bad`, `errors` = 0; `passive_best_fraction` sane). Use a new seed and bucket name; never overwrite a set a run is training on. **Mirror a runtime situation/question wording change** (CORE changed `packages/runtime/src/situation/*`): -1. Diff the runtime files since the last port and update the matching `rt.py` function (`*_facts`, `subject_sentence`, `event_lines`, `state_lines`, `stats_lines`, `to_state`/`section_limits`, constants). +1. Diff the runtime files since the last port (`git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/state/fields.ts packages/runtime/src/util.ts`) and update the matching `rt.py` function (`*_facts`, `version_facts`/`content_facts`/evidence builders, `delivery_spec`, `subject_sentence`, `event_lines`, `state_lines`, `stats_lines`, `to_state`/`section_limits`, `BUDGETS`, constants). 2. If an instruction or description changed, also update `fmt.py` canonical first entries (`ACTION_DESC[a][0]`, `DIAG_DESC[d][0]`) and expect `by_header` calibration to be re-fitted. 3. Render a few rows at each budget and compare with SIM rows (`sim/samples/sample.jsonl`) for the same situations. -4. Regenerate the replay set (`cur*` with `--p-runtime 0.8`), retrain, re-evaluate. Coordinate a new freeze tag with the lead (SIM data must match). Run `test_curriculum.py`. +4. Regenerate the replay set (`cur*` with `--p-runtime 0.8`), retrain, re-evaluate. Coordinate a new freeze tag with the lead (SIM and REAL data must match; HANDOFF: any change to `packages/runtime/src/situation/*` means a new tag and regenerated data). Run `test_curriculum.py` (incl. `test_runtime_rows_situation_v2`, which asserts budget, label ⊆ criteria, passive offered, actions ⊆ `TRIGGER_ACTIONS`, and that both `delivery` and `mutation` rows occur). **Add a scenario case:** add it to the builder's `rng.choices` list in `scenarios.py`/`scen_ops.py`/`scen_state.py`, build the `Trace`, facts (via `fmt.pick` templates with ≥ 4 phrasings so one is held out), labels (soft dist leaning passive when ambiguous), primitives (`prims.*`) and a `spec` that `rt.py` can render (or `no_runtime: True`). Keep the passive-best share within 0.45–0.75 and run `test_curriculum.py` (validity, determinism, label consistency, version semantics). **Add a diagnosis label or a built-in action:** it must exist in the runtime first (`questions.ts` `DEFAULT_DIAGNOSES` / `BUILTIN_ACTIONS` / `TRIGGER_ACTIONS`). Then update `fmt.DIAG_DESC` (canonical first) or `fmt.ACTION_DESC`, `fmt.TRIGGER_ACTIONS`, `fmt.TIER`, `rows.RENAMES` (optional), `rt.DIAGNOSES`/`rt.ACTIONS`/`rt.TRIGGER_ACTIONS`, and `eval_runtime.TIER`/`PASSIVE` (unknown actions default to heal tier in eval). Add scenarios that use it. -**Change a mixture / launch a new round:** copy a `configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly), copy `launch_final1.sh` with a new run name, `--stream-cache`, `--out`, `--seed`, and keep rank 0 = the node holding `--init-from`. Use 8 ranks × 10 threads per F80 node. Make sure every bucket named in the mixture has train shards under one of the `--stream` roots (check `mixture_plan.json`). Watch `~/jev/runs/<run>/rank0.out` and `$G/runs/<run>/log.jsonl` on the rank-0 node; deallocate idle nodes. +**Change a mixture / launch a new round:** copy a `configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly), prefer `launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT]` (new run name ⇒ new `--stream-cache`/`--out`; it resumes when `runs/RUN/ckpt` exists), or copy `launch_final1.sh`; keep rank 0 = the node holding `--init-from`. Use 8 ranks × 10 threads per F80 node. Make sure every bucket named in the mixture has train shards under one of the `--stream` roots (check `mixture_plan.json`). Watch `~/jev/runs/<run>/rank0.out` and `$G/runs/<run>/log.jsonl` on the rank-0 node; deallocate idle nodes. + +**Prepare the first situation-v2 round** (Azure; ask the user before anything runs there; PLAN-v1 P1): +1. Generate a v2 replay set on the workbench: `$PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --seed 6 --workers 72 --p-runtime 0.8`, check `stats.json`, shard into `data/s3/cur5/`. +2. Import v2 SIM gold per batch with `import_final.sh` (`PORT` per source dir, `WB` = the workbench; batches are gz shards + `manifest.json` under `train:/data/sim-out/v2-*` or `data:~/simdata/<run>/`, so they may need unpacking/merging into `{train,dev,test}.jsonl` first; unverified). Import REAL v2 batches the same way (see [realapps.md](realapps.md)); keep `real_eval.jsonl` test-only. +3. Write new mixtures (e.g. `mix_v2_t150.json`, `mix_v2_distill.json`) listing `buckets` explicitly; check `mixture_plan.json` at launch. +4. Teacher: `launch_t150.sh` (or `launch_student.sh RUN t150 ...`) on v2 gold; evaluate with `eval_sim.sh` + `report.py` and check clear-case recall first (PLAN P2 gate: if the teacher is also near 40% argmax on clear rows, the bottleneck is the situation information, not model size). +5. Label: fit the teacher's calibration on v2 dev, then `label_cluster.sh WB t150-v2 out/cal/<cal>.json data/unlab/<set> <bucket> "nodes"`; gather the outputs. +6. Distil: `launch_student.sh r17-v2 r17 <passes> mix_v2_distill.json "nodes" $G/runs/r17-s1c/ckpt` (and r32); evaluate, export, validate as below. Then DAgger with SIM `--on-policy` rows from the exported students. + +**Run a T1 experiment:** `t1_relabel.py --in data/s3/<gold> --out data/s3/<gold>g10 --tau 1.0` (or `--keep-dist` for the gain head, which needs the parent-repo `jev_local`), add a mixture with the new bucket, launch from `r17-s1c` (or the v2 equivalent), then `bash training/t1_post.sh <run> <tau>` detached on rank 0; compare `out/eval/gain-<run>.json` with the baseline via `eval_gain.py --model` (one flag per model). + +**Add cluster nodes:** only with the user's OK; `cluster_expand.sh cNN:SIZE ...`, serve a node kit, `node_init.sh`, `node.sh cNN sync`, record the claim in NEEDS.md, deallocate when idle. **Evaluate a checkpoint and fit calibration:** ``` @@ -440,15 +541,15 @@ Check `parity.json` (q8 argmax agreement, `embedding_q8.fp16_free: true`, q8 siz ## Tests -All tests run on a VM (`cd ~/gcl-train && PYTHONPATH=~/jev[:~/gcl-train/training] ~/jev/.venv/bin/python -m pytest -q training/tests/<file>`); none run in the npm/vitest suites. +Tests were written for a VM (`cd ~/gcl-train && PYTHONPATH=~/jev[:~/gcl-train/training] ~/jev/.venv/bin/python -m pytest -q training/tests/<file>`); none run in the npm/vitest suites or in `.github/workflows/ci.yml`. Python tests are listed as not run in the lead's mvp-v2 verification. | Test file | What it asserts | |---|---| -| `training/tests/test_curriculum.py` (5 tests) | `test_all_rows_valid_and_deterministic`: 400 train rows from the same seed have identical `state` across two runs (only `state` is compared) and all pass `_validate`; `test_test_split_uses_only_heldout_domains`: train never / test always in `TEST_DOMAINS`, held-out share 15–30%; `test_heldout_templates_never_in_train_picks`; `test_decision_labels_consistent`: action label/dist ⊆ offered criteria, dist sums to 1, diagnosis gold offered, passive offered, passive-best share 0.45–0.75, no `action` label when not asked; `test_stale_vs_benign_versions_semantics`: `v_newer` true for `typeahead|detail/stale`, false for `fresh`, `older_between`, `same_root`, `moved_inflight` | +| `training/tests/test_curriculum.py` (6 tests) | `test_runtime_rows_situation_v2` (new, pure Python): 1,500 rows built with `decision_row(..., p_runtime=1.0)` over `TRAIN_DOMAINS`; for runtime-style rows `size_chars(state) ≤ STATE_CHAR_BUDGET` (2400), action label ∈ criteria, `meta.passive` ∈ criteria, criteria ⊆ `rt.TRIGGER_ACTIONS[trigger]`, delivery rows' trigger text contains "about to be delivered", and at least one `delivery` and one `mutation` row; `test_all_rows_valid_and_deterministic`: 400 train rows from the same seed have identical `state` across two runs (only `state` is compared) and all pass `_validate`; `test_test_split_uses_only_heldout_domains`: train never / test always in `TEST_DOMAINS`, held-out share 15–30%; `test_heldout_templates_never_in_train_picks`; `test_decision_labels_consistent`: action label/dist ⊆ offered criteria, dist sums to 1, diagnosis gold offered, passive offered, passive-best share 0.45–0.75, no `action` label when not asked; `test_stale_vs_benign_versions_semantics`: `v_newer` true for `typeahead|detail/stale`, false for `fresh`, `older_between`, `same_root`, `moved_inflight` | | `training/tests/test_prune_vocab.py` (6 tests; need `GC_V1_CKPT`, `GC_BASE_32M`) | ettin layout (243 base ids 2–244, merges from 245); pruned tokenizer at 4k/8k/16k encodes random unicode/control text, ids in range, decodes to the same text, never fewer tokens, ids < 245+N unchanged, specials/markers kept and special, markers in user text not matched; logits identical (< 1e-4) to the unpruned v1 model when tokenisation is unchanged (`vocab_new` = 245+N+119); HF-base prune → `init_model` appends markers at V..V+4 and runs a forward pass | | `training/tests/test_export_runtime.py` (3 tests; e2e needs `GC_R17_INIT`, default `~/gcl-train/models/r17-v16k-init`) | int8 embedding error ≤ scale/2 and zero rows survive; Gemm→MatMul+Add preserves outputs; end-to-end export: card format, bytes/sha256 of every file, `meta.markers`/`cls_id`/`sep_id` match `tokenizer.json`, parity fp32 < 1e-3, q8/fp16 < 0.5 (random heads), R17 q8 < 12 MB | -Last recorded runs (LOG): `test_prune_vocab.py` 6/6, `test_curriculum.py` 5/5 on c01. No run of `test_export_runtime.py` is recorded. +Last recorded runs (LOG): `test_prune_vocab.py` 6/6, `test_curriculum.py` 5/5 on c01 (before the v2 test existed). No run of `test_export_runtime.py` is recorded. Run for this doc in the mvp-v2 checkout on macOS (Python 3.14.7, no pytest, no `jev_local` deps; each test function called directly from `training/tests` with `training/curriculum` and the repo root on `sys.path`), with `GC_P_RUNTIME` unset and with `GC_P_RUNTIME=1`: 5 of 6 pass both ways, incl. `test_runtime_rows_situation_v2`; `test_all_rows_valid_and_deterministic` needs `jev_local`'s deps (`pydantic`) and was not run. Test inputs and skips: `test_curriculum.py` needs `~/jev` on `sys.path` (it imports `jev_local` for `_validate`) and covers only the varied style unless `GC_P_RUNTIME` is set (see Gotchas). `test_prune_vocab.py`: `GC_V1_CKPT` (default `~/jev/models/jev-local-fast`; 5 tests skip without `backbone/tokenizer.json`) and `GC_BASE_32M` (default `~/jev/models/base/ettin-encoder-32m`; the HF-base test prunes it to 8,000 merges and skips without it). `test_export_runtime.py`: the two graph-surgery tests are self-contained (tiny ONNX graphs); the end-to-end test skips unless `GC_R17_INIT/backbone` exists and runs `export_runtime.py` as a subprocess on 6 hand-written requests. @@ -466,7 +567,8 @@ Results and status (from EVAL.md / LOG.md; held-out data, temperatures fitted on | SIM sample (123) | R32-s1c / R17-s1c | 51.2 / 49.6; 48.0 / 43.9 | 13.6%; 9.7% | 34.0%; 18.4% | 19.1%; 22.2% | stage 1 does not transfer to SIM labels | | SIM `r300k` test (20k) | R32-s2-pilot | 77.5 / 90.8 | 0.02% | 0.06% (6/10,234) | 75.5 (49) / 1.3% | cost policy 33.99 vs passive 34.03 vs oracle 32.88 | | SIM `r300k` test (20k) | R17-s2-pilot | 78.3 / 91.1 | 0.00% | 0.08% (8/10,234) | 65.5 (58) / 1.4% | cost 33.97 / 34.03 / 32.88 | -| SIM phase A | R32/R17-final1 | — | — | — | — | launched 00:06 UTC 2026-10-08, ETA ≈ 01:30; no results in repo | +| SIM phase A test (20k; 12,901 decision rows) | **R17-final1** | 81.9 / 90.5 | **0.05%** (5/10,224), precision 80.8 (26), recall 1.8% | **0.24%** (24/10,224) | 79.0 (152) / 4.5% | ECE 0.009 / 0.010; clear recall guard 4.2% of 429 (clear stale/dup 7.7% of 220), heal 6.1% of 1,193; cost 33.35 vs passive 33.40 vs oracle 32.38 | +| SIM phase A test | R32-final1 | 81.8 / 89.7 | 0.05%, precision 78.3 (23), recall 1.5% | 0.22% (23/10,224) | 77.1 (157) / 4.5% | ECE 0.008 / 0.012; clear 3.5% / 6.8% / 5.9%; cost 33.34 | Size/latency (stage 1c exports): R17 q8 **9.58 MB** / fp16 13.57 MB, WASM 1-thread 188 / 339 / 608 ms at 500 / 780 / 1,170 tokens, ORT CPU 1-thread 39 / 71 / 132 ms; R32 q8 22.47 / fp16 34.79 MB, 499 / 879 / 1,539 ms, 93 / 163 / 289 ms. q8 vs PyTorch agreement (argmax / gate@0.8 / gate@0.9): R17 99.5 / 99.4 / 98.8%, R32 100 / 97.0 / 99.4%. Calibration: τ choice 0.71, score 0.59–0.66, noul 0.85–1.0. Cost to 23:05 UTC ≈ $215. @@ -476,13 +578,14 @@ More numbers from EVAL.md / LOG (same sources): - SIM sample mean cost (heal policy / always passive / oracle): R32-s1c 23.26 / 23.61 / 22.36, R17-s1c 23.24 / 23.61 / 22.36. - Stage-2 pilot: guard fires 2 (R32) / 4 (R17); ECE action/diag 0.24 / 0.012 and 0.26 / 0.017; per trigger action/diag ≈ error 94.5 / 93, failure 71 / 85, inconsistency 85 / 97, mutation 84–86 / 90, request 72 / 95, stall 64–68 / 87–89, transition 83–85 / 89–90; heal sweep: at 0.8 130 / 173 fires with 70% / 66% precision, at 0.9 21 / 27 fires with 81% / 93%. Gated policy saves ≈ 0.05 of the 1.15 cost units available per decision. Pre-freeze SIM action labels were soft (≈ temperature 2 over costs), hence the low recall. - Packed sequence length by state budget (pruned tokenizer, ≈ 2.4–2.5 chars/token): 1,000–1,100 chars ≈ 600 tokens, 2,000 ≈ 1,000, 3,200 → SIM `r300k` mean 1,108 / p95 1,523 / max 1,761; standing questions add ≈ 185 tokens. At ≈ 600 tokens R17 decides in ≈ 0.25 s and R32 in ≈ 0.65 s (WASM, 1 thread). MODEL measured R32 at 780 tokens in Chromium at 837–940 ms, and ≈ 3× faster with 4 threads in a crossOriginIsolated page (Node shows no speed-up). -- Final round 1 sizes: SIM `final-a` train 448,420 / dev 14,613 / test 137,643; `r32-final1` 2.4 passes × 498M tokens on 48 ranks, `r17-final1` 3.0 passes on 32 ranks, ETA ≈ 01:28–01:30 UTC; c01 deallocated 00:12. +- Final round 1 (EVAL.md, the v1 baseline): SIM `final-a` train 448,420 / dev 14,613 / test 137,643; temperatures per kind fitted on 8,000 dev rows (split-half NLL 0.332 → 0.331, ECE 0.013 → 0.009). Per trigger (R17 action / diagnosis, heal FIR, heal precision): mutation 90.3 / 89.7, 0.10%, 83%; request 75.0 / 94.5, 0.20%, 70%; failure 75.9 / 85.3, 0.55%, 83%; inconsistency 85.3 / 94.7, 0.30%, 60%; stall 67.0 / 91.2, 0.50%, 67%; transition 86.5 / 87.0, 0%; error 94.3 / 98.9, 0%. Per budget: 1,000 chars 82.1 / 87.9, 2,000 81.9 / 91.0, 3,200 81.8 / 91.9. Heal sweep: 0.5 → 1,440 fires at 56%; 0.8 → 206 at 77%; 0.9 → 87 at 85%; 0.95 → 39 at 97%. On the 1,216 clear actionable rows R17's argmax equals gold only 41% (failure 51, mutation 48, stall 54, request 30, inconsistency 14, transition 5%); non-passive mass median 0.48 on clear rows vs p90 0.42 / p99 0.71 on passive-best rows. PLAN targets: guard FIR, heal FIR and ECE met; diagnosis ≥ 95% and clear stale/dup recall ≥ 80% not met. Diagnosis of the gap: sim/SEPARABILITY.md (62–82% of clear cases have a benign twin with identical visible facts; 24% of clear rows mislabelled `expected`), which motivated situation-v2's facts and SIM's S1/S2 label fixes. +- Final round 1 exports (fp16-free q8): R17 9.58 / 13.57 MB, R32 22.47 / 34.79 MB; q8 vs PyTorch argmax 100%, gate agreement 99.5% @0.8 / 100% @0.9 (233 questions); onnxruntime-web 1.30 WASM 1 thread R17 ≈ 177 / 323 / 589 ms, R32 ≈ 569 / 954 / 1,580 ms at 500 / 780 / 1,170 tokens (SIM rows ≈ 380 / 780 / 1,100 tokens at the 1,000 / 2,000 / 3,200-char budgets). Delivered to `train:~/gcl/train-out/final1/{r17,r32}/` (sha256 verified, 233/233 decisions) and R17 to `packages/runtime-model/files/r17/` on Mehar's Mac (gitignored, not in the repo). The first R17 post-processing served an empty tar after a failed export (ONNX tooling missing on c02/c09, now installed by `node_init.sh`). -NEEDS items not listed below: 2 (row format) and 3 (meta) DONE on `sim/samples/sample.jsonl`; 6 DONE (card format `genclass-runtime-model/1`, `meta.json` fields); 7 answered by MODEL: the int8-embedding q8 runs under onnxruntime-web 1.30 WebGPU on an adapter without shader-f16, while the v0.1 q8 with an fp16 table fails with "Program Gather requires f16"; MODEL's TS packer reproduces `export-r32-v1pruned/parity.json` (q8 450/454 decisions, fp16 453/454; 89/90 requests pack bit-exactly); 9 INFO: `genclass-runtime info <dir>` enforces "any fp16 tensor → `needs: shader-f16`"; 10 INFO: MODEL's single-thread WASM latency R17 177 / 245 / 360 / 625 ms vs R32 458 / 601 / 908 / 1,647 ms at ≈ 300 / 400 / 600 / 1,000 state tokens. +NEEDS items not listed below: 2 (row format) and 3 (meta) DONE on `sim/samples/sample.jsonl`; 6 DONE (card format `genclass-runtime-model/1`, `meta.json` fields); 7 answered by MODEL: the int8-embedding q8 runs under onnxruntime-web 1.30 WebGPU on an adapter without shader-f16, while the v0.1 q8 with an fp16 table fails with "Program Gather requires f16"; MODEL's TS packer reproduces `export-r32-v1pruned/parity.json` (q8 450/454 decisions, fp16 453/454; 89/90 requests pack bit-exactly); 9 INFO: `genclass-runtime info <dir>` enforces "any fp16 tensor → `needs: shader-f16`"; the first item 10 (INFO, MODEL section; NEEDS reuses 10 for node claims): MODEL's single-thread WASM latency R17 177 / 245 / 360 / 625 ms vs R32 458 / 601 / 908 / 1,647 ms at ≈ 300 / 400 / 600 / 1,000 state tokens. Doc-vs-code drift: - `training/README.md` §2 says diagnosis has "9 labels"; code has 10 (`transient` added; `fmt.DIAG_DESC`, `rt.DIAGNOSES`). -- `training/README.md` §4 describes the old gate ("non-passive top action, p ≥ 0.9 / 0.8"); `eval_runtime.py` uses the summed-mass gate over permitted actions (EVAL.md is current). `packages/runtime-model/MODEL_CARD.md` has the same old gate wording, omits `transient`, and its status line ("stage 1c final") predates final round 1. +- `training/README.md` §4 describes the old gate ("non-passive top action, p ≥ 0.9 / 0.8"); `eval_runtime.py` uses the summed-mass gate over permitted actions (EVAL.md is current). `packages/runtime-model/MODEL_CARD.md` has the same old gate wording ("`p(action) ≥ 0.9` (guard tier) / `0.8`") and omits `transient`; its status line was updated to final round 1 (resolved) but still describes situation-v1 and a `files/r17/` directory that is gitignored. - `export_runtime.py` parity metrics `gate08`/`gate09` still use the single-max-probability gate, not the summed-mass gate. - `training/README.md` §3 points at `/Users/meharkhanna/jev/scripts/launch_run.sh`; in this repo it is `scripts/launch_run.sh`, and the `.sh` scripts resolve jev code at `$HERE/../..` rather than the repo root. - `prune_vocab.py` module docstring shows `analyze --texts a.jsonl b.txt`; the CLI takes `--group name=path1,path2`. @@ -501,23 +604,42 @@ Doc-vs-code drift: - `training/README.md` §2 says ask rows carry "2–5 primitive questions only" and decision rows "0–3"; runtime-exact decision rows draw 0–2 (`rows.decision_row`: `rng.choice((0, 0, 1, 2))`). - `curriculum/rt.py` module docstring says "Scenario facts that CORE cannot compute are dropped; scenarios whose label would then be unjustifiable return None"; the only such scenario is `failure/offline` via `spec["no_runtime"]`. -Open items relevant to this scope: -- Final round 1 evaluation, calibration, export and delivery (OPEN_TASKS 3–4); EVAL.md "Final round 1" is empty. Round 2 on SIM phase A + B with longer schedules. -- Choose shipping models (OPEN_TASKS 5) and publish `@genclass/runtime-model@0.1.0` (OPEN_TASKS 8). -- NEEDS 1 (OPEN): stage 2 wants ≥ 1M SIM train rows; phase A gave 448k. NEEDS 4 (ASK): clean-run SIM rows (`meta.clean`) for a direct FIR on clean traffic. NEEDS 5 (ASK): keep instructions/descriptions stable. NEEDS 6a (ASK): budget with the real tokenizer (≈ 2.4 chars/token). -- Stage-2 pilot lesson: soft pre-freeze SIM action labels gave recall ≈ 1%; frozen SIM uses sharper uncertainty-based labels (≥ 0.95 on clear cases), which final round 1 trains on. Re-check q8 parity on trained models and consider MatMulNBits block 16 (+1.8 MB for R32) if gate agreement is low (LOG). -- Known risks (OPEN_TASKS): label noise from few sampled futures; thin `conflict` and `transition` classes. +- New with the v2 / scaled-program commits: + - `training/README.md` was not updated for situation-v2 (still "Final rounds (frozen runtime `situation-v1`)", no `delivery`, no teacher/T1 scripts); this doc and PLAN-v1/LOG are current. + - `training/NEEDS.md` "SIM → TRAIN: scaled data" still says "Runtime tag `situation-v1`" and item 10 says "the quota (1,024 vCPU) is exactly the whole cluster"; LOG (00:40) and HANDOFF say the quota is 2,048 and the v2 production batches are situation-v2. The node-claim table mixes past and current rows; HANDOFF/the lead's Azure look (2026-10-08 04:14 UTC): c01–c23 and `train` running, `data` deallocated, SIM on c02–c09 + c12–c23, REAL on c01, c10, c11. + - `training/NEEDS.md` numbers two different items "7." and two "10." (MODEL INFO latency and the PLAN-v1 node claims). + - `launch_t150.sh` header "6 ranks × 13 threads per node" vs code default 8 × 10 (see Gotchas). PLAN-v1 §3 also says "use 6 ranks or grad-ckpt" on the 160 GB nodes. + - `launch_student.sh` header example `mix_v2_distill.json` does not exist; header says "checkpoints every 25 steps" (true). + - `label_cluster.sh` header: labelled shards "are gathered on WB"; nothing gathers them. + - `t1_relabel.py` docstring: the gate "becomes an expected-gain gate (≈ gain ≥ τ·ln 4 / τ·ln 9 for one dominant action)"; LOG 02:40 found the summed-mass gate is the wrong rule for these labels (64% of rows ≥ 0.5 mass). + - LOG 03:00 describes the gain head in "the parent repo" `jev_local`; this monorepo's `jev_local` has none, so `collect_gain.py` / `t1h_post.sh` / `--gain-loss` do not work from this checkout. + - LOG 01:13 lists "`eval_sim.sh` + clear-case recall" among prepared pieces; `eval_sim.sh` is unchanged since 654d822 and the clear-case recall lives in `eval_runtime.py` / `report.py`. + - `docs/runtime/RESULTS.md` §1 reports final1 "recall" as 7.7% (the guard clear stale/duplicate figure); EVAL.md's plain recall is 1.8% guard / 4.5% heal, MODEL_CARD says "≈ 5%". Same data, different definitions. RESULTS' R32 row puts 5.9% in the same "clear stale/duplicate" column, but 5.9% is R32's heal clear-case recall; its guard clear stale/duplicate figure is 6.8% (EVAL.md). + - `training/PLAN-v1.md` still has situation-v1 details: §1/§5 report ECE "per budget 1,000 / 2,000 / 3,200" (v2 budgets top out at 2,400); §6.1 says `meta.teacher` holds "margin, entropy" (`label_teacher.py` writes `top`, `margin` and, for `action`, `non_passive_mass`; no entropy); §7 says the quota is 1,024 vCPU and proposes c02–c09 for TRAIN (quota is 2,048; NEEDS' later claim table supersedes it). + - `collect_gain.py` docstring says "Resumable by line count"; `main` opens `--out` with `"w"` and starts over. + +Open items relevant to this scope (HANDOFF, OPEN_TASKS, PLAN-v1, NEEDS): +- **No situation-v2 model exists.** Next per HANDOFF: import v2 gold (SIM ≥ 10M, REAL ≈ 495k (NEEDS target ≥ 500k)) → T150 teacher on v2 gold (P1) → teacher eval incl. clear-case separation (P2) → teacher labels on the unlabeled rows (P3: a prioritised 5–10M-row subset of the ≥ 50M) → distil R17 (default) and R32 (P4) → DAgger via SIM `--on-policy` (P5) → EVAL → `@genclass/runtime-model@0.1.0` (release steps: [RELEASE.md](../../RELEASE.md); the runtime's `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` 404 until then; `@genclass/runtime-model` is 404 on npm) → demos rerun → `@genclass/runtime@0.1.0`. A v2 curriculum replay set, v2 mixtures and a distillation mixture still have to be written. +- R17-final1 (situation-v1) exists only on the train VM / Mehar's Mac and does not match the v2 runtime: do not package it as the v2 default. +- T1 on v2 data (rerun `r17-t1g10`/`t1g20`/`t1h` on v2 gold; the gain head must be ported into this repo's `jev_local` first). The v1 T1 runs are resumable but superseded. +- Cost: PLAN-v1 estimates ≈ $3–4k in total (P0–P5 plus per-round eval); ≈ $390 spent to 01:56 UTC (LOG), ≈ $400 (RESULTS.md). Every Azure action needs the user's OK on our side. +- NEEDS 4 (ASK): clean-run rows (`meta.clean`, now produced by SIM/REAL) for a direct FIR on clean traffic. NEEDS 5 (ASK): keep instructions/descriptions stable (by_header calibration keys are `sha1(header)`). NEEDS 6a (ASK): budget with the real tokenizer (≈ 2.4 chars/token; the v2 2,400 budget targets ≈ 1,000 tokens). +- Re-check q8 parity on every trained model and consider MatMulNBits block 16 (+1.8 MB for R32) if gate agreement drops (LOG). +- Known risks (OPEN_TASKS, PLAN-v1 §8): label noise from few sampled futures (benign request rows softest); thin `conflict` and `transition` classes; teacher too slow on CPU (fallback: R68 as teacher); over-intervention on real apps (ship guard only when guard FIR ≤ 0.1% on all held-out sets). - `standalone.json_invariants` `j_count` overwrite (see Gotchas). ## Related docs -- [glossary.md](glossary.md): shared term list (stage 1 / 1c / 2, final round 1 / 2, phase A / B, bucket, `COMPACT_BUDGET` vs `COMPACT_QUESTIONS_BUDGET`). +- [glossary.md](glossary.md): shared term list (stage 1 / 1c / 2, final round 1, phase A / B, bucket, `situation-v1` / `situation-v2`, `COMPACT_BUDGET` vs `COMPACT_QUESTIONS_BUDGET`). - [model-io-contract.md](model-io-contract.md): situation text → packed request → heads → calibrated answers (shared by runtime, sim and training). -- [sim.md](sim.md): the SIM generator that produces the rows for the stage-2 pilot (`r300k`) and the final rounds (phase A/B): `meta.costs`, `meta.budget`, splits. +- [sim.md](sim.md): the SIM generator that produces the rows for the stage-2 pilot (`r300k`), the v1 final rounds (phase A/B) and the v2 gold / unlabeled / on-policy (DAgger) batches: `meta.costs`, `meta.cost_futures`, `meta.budget`, splits, held-out features. +- [realapps.md](realapps.md): the REAL corpus (91 real apps at b435acb (READMEs/HANDOFF still say 66) in headless Chromium) that produces real-browser gold rows and the test-only `real_eval.jsonl` set. +- [RELEASE.md](../../RELEASE.md): release procedure for `@genclass/runtime` (alpha.1) and `@genclass/runtime-model@0.1.0` (never publish round-1 R17 as 0.1.0; npm 11 needs `--tag` for prereleases). +- `sim/SEPARABILITY.md`: why final1 recall is low (benign twins, label fixes S1/S2, T1 proposal in §7). - [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): the runtime situation code that `curriculum/rt.py` mirrors. - [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md): the runtime gate and action tiers that `eval_runtime.py` reproduces. - [runtime/model-host.md](runtime/model-host.md): how the exported model directory is loaded, verified and run (card format, `meta.json`, calibration lookup). - [genclass-model-lineage.md](genclass-model-lineage.md): `jev_local/` (trainer, engine, packer) and GenClass 0.1 (the R32 init). - [demos.md](demos.md): demo trials that will evaluate the trained model. - [status-and-known-issues.md](status-and-known-issues.md), [runtime/build-test-release.md](runtime/build-test-release.md). -- Source docs: [../../training/README.md](../../training/README.md), [../../training/EVAL.md](../../training/EVAL.md), [../../training/LOG.md](../../training/LOG.md), [../../training/NEEDS.md](../../training/NEEDS.md), [../runtime/CONTRACT.md](../runtime/CONTRACT.md) (§8 gate, §10 model, §11 SIM), [../../packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), [../../OPEN_TASKS.md](../../OPEN_TASKS.md). +- Source docs: [../../training/README.md](../../training/README.md), [../../training/EVAL.md](../../training/EVAL.md), [../../training/LOG.md](../../training/LOG.md), [../../training/NEEDS.md](../../training/NEEDS.md), [../../training/PLAN-v1.md](../../training/PLAN-v1.md), [../../HANDOFF.md](../../HANDOFF.md) (cluster rules, next steps), [../runtime/RESULTS.md](../runtime/RESULTS.md) (results summary and training log), [../runtime/CONTRACT.md](../runtime/CONTRACT.md) (§8 gate, §10 model, §11 SIM), [../../packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), [../../OPEN_TASKS.md](../../OPEN_TASKS.md). diff --git a/packages/runtime/README.md b/packages/runtime/README.md index ca195fd8..535a72bb 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -3,12 +3,14 @@ [![npm](https://img.shields.io/npm/v/@genclass/runtime/latest?label=npm)](https://www.npmjs.com/package/@genclass/runtime) [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) -**Install one library. Find and prevent runtime failures automatically.** +**A runtime that watches your web app from the inside and, with a small local model, flags (and optionally +prevents) stale responses, races, duplicate requests, inconsistent state and failure storms.** -GenClass Runtime watches your web app from the inside: user actions, async operations, network requests, state -changes, errors, timing and causality. When something looks risky, it asks a small model that runs locally in the -browser (WebGPU or WASM, cached after the first load) what is happening and what to do. It then reports what it -saw, or prevents the failure with a minimal, reversible action. Nothing leaves the browser. +GenClass Runtime records what your app does: user actions, async operations and their causes, fetch/XHR/WebSocket/ +EventSource traffic, store writes with per-field versions, errors and timing. It computes generic facts about each +write, request and response. When a situation looks risky, a small GenClass model running in the browser (WebGPU or +WASM, in a Web Worker) answers two questions: what is happening, and which of the available actions is best. The +runtime has no list of known bugs: triage picks the situations, the model decides. ```bash npm install @genclass/runtime @@ -17,119 +19,207 @@ npm install @genclass/runtime ```ts import { GenClass } from "@genclass/runtime"; -GenClass.init(); +GenClass.init(); // observe mode: reports only, never takes an action (see Known limitations) ``` -> **Status: alpha (`0.1.0-alpha.0` on npm).** The runtime, model host, devtools and adapters work and are -> tested. The runtime-specialist model is still in training and not yet published, so this alpha observes and -> records but does not act yet: until the model ships, the runtime fails open and takes the passive action. To -> try decisions now, self-host a model with `npx genclass-runtime fetch-model`. Remaining work is listed in -> [OPEN_TASKS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/OPEN_TASKS.md). +> **Status: alpha. No trained model is published yet, so today the runtime finds nothing.** +> +> - The runtime, model host, devtools overlay and React/Redux/Zustand adapters are built and unit-tested. +> - The model for this runtime's situation format (`situation-v2`) is still in training. +> `@genclass/runtime-model` is not on npm, so the default model URL returns 404. A default `GenClass.init()` +> prints `[GenClass] Model unavailable (...); observing only.`, consults no model, records no detections and takes +> no actions. It still traces, learns baselines and answers `rt.situation()`; `rt.ask()` / `rt.decide()` reject +> with `GenClassUnavailableError`. +> - The only trained models so far (round 1) read the previous format (`situation-v1`) and do not match this +> runtime. Do not self-host them with this version. +> - `0.1.0-alpha.0`, the first version on npm, is the older v1 runtime: guard by default, holds store writes, and +> can crash when app state contains `NaN` (fixed since). Use a later version. +> +> Progress: [OPEN_TASKS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/OPEN_TASKS.md) · +> measured results: [RESULTS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/RESULTS.md). + +## Contents + +[Modes](#modes) · [What it looks for](#what-it-looks-for) · [State it can protect](#state-it-can-protect) · +[Ask it questions](#ask-it-questions) · [Observability](#observability) · [Extend it](#extend-it) · +[Model quality](#model-quality) · [Performance](#performance) · [Privacy](#privacy) · +[Known limitations](#known-limitations) · [API reference](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/API.md) ## What it looks like -Run your app as usual. The console starts saying things like this (example output): +Run your app as usual. When the model flags something, the console gets one plain-English line per detection or +intervention, followed by a collapsed group with the evidence. This is real output of the runtime in guard mode for +an out-of-order search response. A scripted stand-in decider supplied the answer (`stale`, `discard`, 0.97), since no +trained model exists yet: ``` -[GenClass] Prevented a stale write: GET /api/search?q=rea (started 1.8 s ago) would have overwritten - search.results written 0.4 s ago by a newer GET /api/search?q=react. Dropped it. (stale, 0.97) -[GenClass] Coalesced a duplicate: POST /api/orders was sent again 90 ms after an identical one from the - same click. Reused the first response. (duplicate, 0.95) -[GenClass] Flagged: POST /api/cart usually writes cart.items and cart.total (317 of 317 times); this time it - wrote only cart.items. (unusual, 0.88) +[GenClass] Prevented a stale response: search.results was written once by other operations since its operation (#4) +started (version 1 → 2), last 0.40s ago by GET /api/search?q=react (#6), which started 1.30s after #4, from a later +user action (#5). Delivered the response to GET /api/search?q=rea (#4) and dropped the state changes it makes over +newer data (search.results). (stale, 0.97; discard 0.97) ``` -Each line expands into the evidence: the facts, the timeline, the exact text the model read, its answer -probabilities, exactly what GenClass changed, and how to undo it. +In observe mode the response is delivered without waiting for the model, and the write it causes is judged in the +background instead: -## What it handles - -The runtime has no list of known bugs. It computes generic facts about every write and request: what caused it, -which versions it was based on, what happened in between, repeats, failure streaks, latency against learned -baselines, broken learned relations, and unusual transitions. The model decides what is going on. - -| situation | example | what GenClass can do | -|---|---|---| -| stale overwrite | an old response lands after a newer one | drop or defer the write | -| race / conflict | two operations write the same state | defer, drop, roll back | -| duplicate | a double click sends the same order twice | coalesce with the first request | -| inconsistent state | `total` no longer equals the sum of the lines | roll back or resync (heal) | -| failure patterns | an endpoint fails 5 times in a row | back off, serve cached (heal) | -| transient failure | a one-off 503 | retry (heal) | -| slow / overload | a request is 8× slower than usual; a render loop floods an API | hedge, delay | -| unusual behaviour | an operation writes different fields than its last 300 runs | flag, roll back (heal) | -| your own questions | "is now a good moment to start the upload?" | `ask` / `decide` | +``` +[GenClass] Flagged a stale write: search.results was written once by other operations since this write's cause (#4) +started (version 1 → 2), … Not acted on (would have done discard 0.97): observe mode never changes execution. (stale, 0.97) +``` ## Modes -| mode | behaviour | -|---|---| -| `observe` | Finds and reports anomalies. Never changes execution. | -| `guard` (default) | Also prevents failures with guard-tier actions only (`discard`, `defer`, `coalesce`, `delay`). These withhold, deduplicate or slow something down, and only run when the model is very sure (≥ 0.9) that acting beats doing nothing. | -| `heal` | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions (≥ 0.8). | +| mode | what it does | non-passive actions | gate | +|---|---|---|---| +| `observe` (**default**) | Reports what it sees and what it would have done. Never holds a request, never runs an action. | none | n/a | +| `guard` (opt-in) | Also prevents failures with guard-tier actions: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down. | guard tier | summed probability of the permitted actions ≥ 0.9, and the top diagnosis is not `expected` | +| `heal` (**experimental**) | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions. | guard + heal tier | guard actions ≥ 0.9, heal actions ≥ 0.8, diagnosis not `expected` | ```ts -GenClass.init({ mode: "observe" }); +GenClass.init({ mode: "guard" }); +``` + +In every mode, a decision is reported as a detection when its diagnosis is not `expected` at confidence ≥ 0.6. Actions +are also limited to 60 per minute (`policy.maxActionsPerMinute`). A held decision that misses the hold budget runs +the passive action; a background write decision can still revert the write late. Thresholds and the `allow` / `deny` +lists are in `policy`. Switch at runtime with `rt.setMode(mode)`, or stop consulting the model with `rt.pause()` / `rt.resume()`. + +**The default changed.** Earlier versions defaulted to `guard`. Now `GenClass.init()` with no `mode` observes only; +pass `mode: "guard"` to let it act. + +**Kill switch.** Append `?genclass=off` to the URL, or set `localStorage.genclass = "off"`, and nothing is installed. +`?genclass=observe|guard|heal` (or the same localStorage value) overrides the mode. + +`GenClass.init()` never throws, and a second call returns the first runtime (its options are ignored). Outside a +browser (SSR, Node) it returns a runtime with no observers and no model. For tests and headless use, call +`createRuntime(options)` instead. + +## What it looks for + +The runtime decides at nine **triggers**. Only salient ones (a conflict, a repeat, a failure, an anomaly, a broken +relation, an error) reach the model; everything else is a cheap fact computation. + +| trigger | when | passive action | other actions (tier) | +|---|---|---|---| +| `delivery` | a fetch/XHR response or a WebSocket/EventSource message is about to reach the app | `deliver` | `discard` (guard): deliver, but drop the writes it makes over newer data · `defer` (guard): wait for related in-flight work, then decide again | +| `request` | a request is about to be sent | `send` | `coalesce`, `delay` (guard) · `block`, `serve_cached` (heal) | +| `failure` | a request failed (network error, timeout, 5xx/429/408) | `deliver` | `retry`, `serve_cached` (heal) | +| `stall` | a request is far slower than usual | `wait` | `hedge`, `serve_cached` (heal) | +| `mutation` | a salient store write that no delivery decision covered | `apply` | `discard`, `defer` (guard), decided in the background | +| `inconsistency` | a learned relation (`total == sum(items[*].price × qty)`) broke at a settled point | `ignore` | `rollback`, `resync` (heal) | +| `transition` | an operation wrote different fields than it usually does | `ignore` | `rollback`, `resync` (heal) | +| `error` | an uncaught error or rejection | `ignore` | `rollback` (heal) | +| `ask` | your own question (`rt.ask`, `rt.decide`) | | | + +The model also gives a diagnosis: `expected`, `stale`, `conflict`, `duplicate`, `inconsistent`, `failing`, `slow`, +`overload`, `unusual` or `transient`. + +**Delivery decisions (the main change in this version).** GenClass decides about responses and messages *at the +network boundary*, before the app sees them, and never holds or reorders the app's store writes. A delivery is +salient only when: + +- a field the response is predicted to write already holds **newer applied data** (an operation that started later + wrote it since) and no newer request of the same kind is still in flight; +- or it would **revert a pending local change** (an optimistic update whose request is still in flight) to the value + the user's change replaced; +- or it would **replace text the user typed** after the request started. + +The runtime predicts the write set from what the same operation wrote before. For salient candidates it reads the +response body (a clone, at most 256 KB of JSON, waiting at most 100 ms). A response equal to the current values is not +salient. The model then reads facts such as these (real output from the example above): + +``` +The response has search.results = 1 item ["rea-1"]: neither the current value 1 item ["react-1"], nor the value when #4 started. +In 1 earlier completions of GET /api/search its chain wrote search.results (1 of 1 wrote state). +The response to GET /api/search?q=rea (#4) arrived after 1.80s (200); the app has not seen it yet. +This request comes from user typed "rea" into input "Search" (#3), started 1.80s ago. ``` -**Kill switch:** append `?genclass=off` to the URL, or set `localStorage.genclass = "off"`, to rule GenClass out -while debugging. `?genclass=observe` switches to observe mode. +Clean in-order typeahead and autosave make no model calls and hold nothing (covered by the unit tests). Other facts +cover: + +- repeats and multi-clicks; +- failure streaks and failure scope (other endpoints, `navigator.onLine`); +- whether a failed POST may have been applied; +- learned cadences (polling, debounced saves); +- latency against learned baselines; +- values known to be stale; +- read-your-writes. ## State it can protect -Fetch, XHR, WebSocket, DOM events, errors, navigation and storage are observed automatically. To let GenClass -hold, drop or roll back writes, create state through it, or wrap the store you already have: +Fetch, XHR, WebSocket, EventSource, DOM user events, errors, navigation, storage, long tasks and timers are observed +automatically. Store writes are traced (and can be dropped or reverted) only when the store goes through GenClass: ```ts -const rt = GenClass.init(); +const rt = GenClass.init({ mode: "guard" }); // Built-in atom const cart = rt.atom("cart", { items: [], total: 0 }, { resync: () => loadCart() }); cart.set((c) => ({ ...c, items: [...c.items, item] })); -// React +// React (uses GenClass.runtime, or the runtime from <GenClassProvider runtime={…}>; plain useState without one) import { useGenClassState } from "@genclass/runtime/react"; -const [results, setResults] = useGenClassState("search.results", []); +const [results, setResults] = useGenClassState("searchResults", []); -// Redux +// Redux / Redux Toolkit (put the enhancer last in compose()) import { genclassEnhancer } from "@genclass/runtime/redux"; const store = createStore(reducer, genclassEnhancer(rt, { name: "app" })); // Zustand import { genclass } from "@genclass/runtime/zustand"; -const useStore = create(genclass(rt, "board")((set) => ({ cards: [], move: () => set(/* … */) }))); +const useBoard = create(genclass(rt, "board")((set) => ({ cards: [], move: () => set(/* … */) }))); -// Any store with get/set/subscribe +// Any store with get/set (and optionally subscribe) const prefs = rt.guard("prefs", { get: () => store.prefs, set: (v) => store.setPrefs(v) }); ``` -`resync` is optional. It tells GenClass how to reload a store from its source, which enables the `resync` -recovery action. +What each kind of protection needs: + +| protection | how | works with | +|---|---|---| +| delivery `discard` | the response is delivered; its chain's writes to the protected fields are dropped synchronously inside each write, and its other fields (loading flags, counts) apply | atoms, `rt.guard`, React state. Redux/Zustand: only when every change of a dispatch is dropped (see [limitations](#known-limitations)) | +| late revert | a background `mutation` decision to `discard` reverts the write if it is at most 2 s old, its fields are unchanged since, and no later write of the same chain followed | any GenClass-aware store | +| `rollback` (heal) | restores the last settled snapshot where every learned relation held | stores GenClass can write (atoms, `rt.guard`, Redux and Zustand adapters) | +| `resync` (heal) | calls your `resync` handler | stores registered with `{ resync }` | + +`{ hold: false }` on a store keeps its writes out of the opt-in write holds (`policy.holdWrites: true`, off by +default). The default never holds a store write: `set(x); get()` always returns `x`. ## Ask it questions -The model answers typed questions about what is happening right now, using the same request shape as Jev's -System One API: +The model answers typed questions about what is happening now (the request shape of Jev's System One API): ```ts const busy = await rt.ask({ type: "noul", instructions: "Is a save in flight or failing?" }); -// { type: "noul", noul: 0.91 } +// { type: "noul", noul: <calibrated P(true)> } -const mode = await rt.decide("Which upload strategy fits what is happening now?", { +const when = await rt.decide("Which upload strategy fits what is happening now?", { now: "start the upload immediately", later: "wait until the network is calm and the user is idle", }); -// "later" +// "now" | "later" ``` +Without a model (today, or with `model: false`) both reject with `GenClassUnavailableError` (`reason`: `off`, +`error`, `timeout` or `destroyed`). `{ timeoutMs }` bounds the wait. + +Standing questions ride along with built-in decisions: `rt.question({ id, on: ["failure"], question, onAnswer })`. + ## Observability -- **Console:** one plain-English line per detection and per intervention, with collapsible evidence. -- **Events:** `rt.on("detect" | "decide" | "act" | "event" | "status" | "report", fn)`. -- **`rt.explain(id)`:** the situation text, facts, timeline, answers and what changed. -- **`rt.interventions()`:** every non-passive action that ran, with `undo()` where the action is reversible. -- **Devtools overlay:** interventions, detections, a live activity log, and a "what GenClass sees now" view. Load it - in development only (52 KB minified, 17 KB gzip): +- **Console:** one line per detection and per intervention, with the evidence collapsed below it. Identical repeats + within a minute are summarised. `report: "silent"` or `report: (r) => …` to route them yourself. +- **Events:** `rt.on("detect" | "decide" | "act" | "event" | "status" | "report", fn)` returns an unsubscribe function. +- **`rt.explain(id)`:** the exact situation text the model read, its facts and timeline, every answer with + probabilities, and what changed. +- **`rt.decisions()`, `rt.interventions()`, `rt.history()`, `rt.inflight()`, `rt.situation()`** for introspection. +- **Undo, where it exists:** `ActionRecord.undo()` is set for `discard` (delivery and write), late reverts, + `rollback` and chain reverts, plus custom actions that register `onUndo`. `defer`, `coalesce`, `delay`, `block`, + `serve_cached`, `retry`, `hedge` and `resync` cannot be undone; their record says what changed. +- **Altered responses** carry an `x-genclass` header: `coalesced`, `cached` or `blocked`. +- **Devtools overlay:** interventions, detections, a live activity log and a "what GenClass sees now" view, with + evidence and undo. About 52 KB minified / 17 KB gzip, so load it in development only: ```ts if (import.meta.env.DEV) { @@ -138,8 +228,6 @@ if (import.meta.env.DEV) { } ``` -Responses GenClass altered carry an `x-genclass` header: `coalesced`, `cached` or `blocked`. - ## Extend it ```ts @@ -155,45 +243,134 @@ rt.use({ description: "pause background sync until the page is visible again", on: ["failure", "stall"], tier: "heal", - run: () => sync.pause(), + run: (ctx) => { sync.pause(); ctx.describe("Paused background sync."); ctx.onUndo(() => sync.resume()); }, }], }); ``` -Plugins can add observers, facts, actions, standing questions and diagnosis labels. The model reads each action's -description, so new actions work without retraining when the description is clear. - -## Model, performance, privacy - -- **Local inference:** a GenClass encoder running in a Web Worker on WebGPU when available, otherwise WASM. The - model downloads at idle after page load (`model.preload: "idle"`) and is cached in Cache Storage. -- **Size:** the runtime models use a pruned vocabulary and int8 weights. Preview exports are 9.6 MB (17M - parameters) and 22.5 MB (32M parameters). The ONNX Runtime WASM is about 2.7 MB brotli without WebGPU and 4.7 MB - with it. -- **Tiered:** normal traffic never reaches the model. Cheap facts are computed for every write and request, and - the model is asked only about salient situations. What it reads is sized to the device: 3,200 characters on - WebGPU, 2,000 with WASM threads, 1,000 on single-thread WASM. -- **Latency:** held writes and requests wait at most the adaptive hold budget (150–800 ms), then proceed - unchanged. A write GenClass decides about too late can still be reverted within 2 s if nothing has touched it - since. On single-thread WASM the 17M model takes about 0.2 s per decision on a 500-token situation (preview - build, measured in Node). -- **Threads:** serving your page with `Cross-Origin-Opener-Policy: same-origin` and - `Cross-Origin-Embedder-Policy: require-corp` enables WASM threads, about 3× faster. -- **Self-hosting:** `npx genclass-runtime fetch-model public/genclass-model`, then - `GenClass.init({ model: { baseUrl: "/genclass-model/" } })`. -- **Privacy:** nothing is sent anywhere. Values of password and payment fields are never recorded, and fields - matching `pass|token|secret|card|cvv|ssn|auth` are redacted. Pass `redact` to add your own rules. - -## Limits - -- Causality across `await` is tracked by instrumenting fetch, XHR, timers and Response bodies. This is best - effort; wrap important work in `rt.op(name, fn)` for exact attribution. -- Only writes that go through GenClass-aware stores can be held, dropped or rolled back. Other state is observed - through its effects. -- The model is trained on a large simulated space of apps. It is not a substitute for tests, and it can be wrong. - That is why the default mode only takes reversible actions at very high confidence, and every action is logged - and undoable. +Plugins can add observers (`setup`), facts, actions, standing questions and diagnosis labels. The model reads each +action's description. The goal is that clearly described actions work without retraining; this has not been +measured. + +## Model quality + +There are no numbers yet for a model that matches this runtime. + +**Round 1 (previous format, `situation-v1`)**, R17 on held-out simulated apps: + +| metric | value | +|---|---| +| diagnosis accuracy | 90.5% | +| action accuracy | 81.9% | +| guard false-intervention rate | 0.05% | +| heal false-intervention rate | 0.24% | +| calibration error | 0.009 | +| recall on clear stale/duplicate cases | 7.7% | + +R17 was precise but timid. The analysis found the limit was in the situation text and the labels, not the model +size: many clear cases had benign twins with identical visible facts, and some labels were wrong. + +**Round 2 (`situation-v2`, this runtime)** adds measured facts aimed at those twins, plus relabelled data. It is +being generated and trained now (~10M simulated rows, ~50M unlabeled rows for teacher labelling, ~0.5M rows from +real apps in headless Chromium). Results will be published with the model package. + +The "never make a correct app worse" check uses an always-passive model in heal mode, compared against observe mode, +on 66 real apps (6 seeds each). **0 of 396 clean runs** changed, measured on final page text (inputs and alerts +excluded) and server state. The check does not compare request timing or store contents, and it does not compare +observe mode against running without GenClass. With network chaos, 3 of 198 runs differed: a request held about +25 ms changed the simulated network's draws. Details: +[RESULTS.md §4](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/RESULTS.md). + +## Performance + +- **Most work never reaches the model.** Facts are computed for every write and request. Measured by the perf tests + on a shared VM: + + | operation | time | + |---|---| + | keystroke write into a store holding a 5,000-item array | 0.22 ms | + | Redux-style dispatch on 5,000 entities | about 0.7 ms | + | settled-point check | 0.3 ms | + +- **Bundle:** the main entry is about 240 KB minified / 83 KB gzip, measured with esbuild and onnxruntime-web + external. ONNX Runtime Web (the only dependency) is loaded by the model worker on demand: about 2.7 MB brotli for + the WASM-only path, 4.7 MB with WebGPU. +- **Model size:** the round-1 R17 export (pruned 16k vocabulary, int8) is 9.6 MB. On single-thread WASM it took about + 0.18 s per decision on a 500-token situation, measured in Node. +- **Holds are bounded.** A held response or request waits at most the hold budget, then proceeds unchanged. The + default `"auto"` budget is 1.5 × the median of the last 20 model latencies, clamped to 150–800 ms; it is 300 ms + before any latency is known. + - A hold happens only if the model is expected to answer within the budget. + - Reading a response body for salience adds at most 100 ms. + - Background (non-held) decisions have a 5 s deadline. +- **Situation size by device:** 2,400 characters on WebGPU; on WASM, 1,000 (1 thread) to 2,000 (4 threads). + Override with `situation: { budget }`. +- **Threads:** serving the page with `Cross-Origin-Opener-Policy: same-origin` and + `Cross-Origin-Embedder-Policy: require-corp` enables WASM threads. +- **Loading:** the model loads at idle after page load (`model.preload: "idle"`). It is cached in Cache Storage and + checked with sha256. `model: { baseUrl }` points at a self-hosted model directory (`npx genclass-runtime fetch-model + <dir>` downloads one); there is none for this runtime yet. + +## Privacy + +- **No app data leaves the browser.** No telemetry, and the model runs locally. The default configuration downloads + the model files (and ONNX Runtime's WASM when the model loads) from cdn.jsdelivr.net. `model.baseUrl` and + `model.ortWasmPaths` self-host them; `model: false` loads nothing. +- **Inputs:** typed values of password fields, `cc-*` / `one-time-code` / password autocomplete fields, and fields + whose name or label names a secret are never recorded. +- **Redaction:** the default redactor (`redact` option) works by the leaf field's meaning, not by substring. + - Redacted: `auth.token`, `form.password`, `users.3.password`, `payment.card.number`, `settings.apiKey`, and + opaque credential-like strings under `auth` / `session` / `cookie`. + - Visible: `auth.loading`, `auth.user.name`, and a kanban `card`. + - Booleans and null are never redacted. + - Query parameters are redacted by the same rule. + - Pass your own `redact(path, value)` for app-specific secrets or PII. The default has gaps (see below). + +## Known limitations + +**Today.** Without a published model nothing is detected or prevented (see Status). The bullets below matter once a +model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. + +- **Redaction gaps (all modes with a model).** These values reach the situation text, `explain()`, the console + evidence and devtools, though never the network: + - The "would replace text the user typed" fact prints a diff of the raw strings, even for a field the redactor + hides. + - The default redactor does not redact numbers or arrays under a secret-named container, for example + `payment.cvv.value = 123` or `login.otp.code`. + + Pass a custom `redact`, and avoid keeping secrets in observed stores. +- **Redux/Zustand discard.** If a stale response's dispatch also changes other fields, a delivery `discard` applies + the whole dispatch. The `ActionRecord` still reports the stale fields as dropped. Atoms and `rt.guard` stores drop + only the stale fields, as intended. +- **The discard mark lasts 10 s.** After a `discard`, writes by operations chained from the discarded one (a + `setTimeout`-driven poll, a saga) to the protected fields are also dropped for 10 s, even when they carry fresh + data. The marks also outlive `rt.pause()` and `setMode("observe")`. +- **`defer` can wait long.** A delivery may be deferred twice, each time until the related operations finish or + 10 s pass. A deferred WebSocket/EventSource message holds back the messages queued behind it. +- **Held messages after `close()`.** A WebSocket/EventSource message held for a decision is still dispatched if + the app closed the socket meanwhile. EventSource `open` events are not kept in order behind held messages. +- **XHR listeners of a held response** run after the original dispatch, so `e.currentTarget` is `null`. Use the + `xhr` object itself. +- **Observe mode with a model.** A conflicting delivery whose body is read can still be delayed up to 100 ms. + Delivery decisions are not made in observe mode (the resulting write is judged instead), so standing questions on + `delivery` are not answered there. +- **`retry` (heal) does not check idempotency.** It is offered for any replayable fetch, POST included. The model + sees whether the method is idempotent and whether the failed request may have been applied. HTTP 502 is + described as usually not processed, which is not always true behind proxies. +- **Transport coverage.** `coalesce`, `retry`, `hedge` and failure/stall `serve_cached` are fetch-only. XHR + failures and stalls are detection-only. +- **Synthetic events.** DOM events with `isTrusted === false` (`el.click()`, `dispatchEvent`, in-page test + drivers) are not user actions unless you pass `observe: { untrustedEvents: true }`. +- **`policy.holdWrites: true` (opt-in).** A held write that a later write flushed early can be recorded as dropped + while it stays applied. +- **Causality** across `await` is tracked by instrumenting fetch, XHR, timers, message events and Response bodies. + This is best effort; wrap important work in `rt.op(name, fn)` for exact attribution. +- **Store state** is visible and protectable only through GenClass-aware stores. Other state is seen only through + its effects. +- **The model can be wrong.** It is trained on simulated apps and real apps driven in a headless browser. It is not + a substitute for tests. That is why the default only observes, guard acts only at ≥ 0.9, and every action is + logged. ## License -Apache-2.0. The model weights are trained only on synthetic data from the GenClass project. +Apache-2.0. The model package, once published, comes with its own model card. From 6ac473779fd6a4735935dc120be68eaca67b4ec1 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 01:26:02 -0400 Subject: [PATCH 05/25] docs: READMEs name 0.1.0-alpha.1 as the current npm version Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 4 ++-- packages/runtime/README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 434de7cd..3c3bfbd8 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ which available action is best. There is no list of known bugs in the code. > - **No model is published for this format yet.** `@genclass/runtime-model` is not on npm, so a default > `GenClass.init()` prints `[GenClass] Model unavailable (...); observing only.` and finds nothing. > - **Round 1 models** (format `situation-v1`) exist but do not match this runtime. -> - **`@genclass/runtime@0.1.0-alpha.0` on npm** is the older v1 runtime. It defaults to guard, holds store writes, -> and has a `NaN` crash that has since been fixed. +> - **On npm:** `@genclass/runtime@0.1.0-alpha.1` is this runtime. `0.1.0-alpha.0` is the older v1 runtime: it +> defaults to guard, holds store writes, and has a `NaN` crash that alpha.1 fixes. > > What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: > start at [AGENTS.md](AGENTS.md). diff --git a/packages/runtime/README.md b/packages/runtime/README.md index 535a72bb..473b44f2 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -32,7 +32,7 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known > with `GenClassUnavailableError`. > - The only trained models so far (round 1) read the previous format (`situation-v1`) and do not match this > runtime. Do not self-host them with this version. -> - `0.1.0-alpha.0`, the first version on npm, is the older v1 runtime: guard by default, holds store writes, and +> - This is `0.1.0-alpha.1`. `0.1.0-alpha.0`, the first version on npm, is the older v1 runtime: guard by default, holds store writes, and > can crash when app state contains `NaN` (fixed since). Use a later version. > > Progress: [OPEN_TASKS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/OPEN_TASKS.md) · From 806a296dd457628f41d79f2dfbf4e74559836ddc Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 01:27:02 -0400 Subject: [PATCH 06/25] release: @genclass/runtime 0.1.0-alpha.1 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- package-lock.json | 2 +- packages/runtime/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7b016fe5..408774aa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3140,7 +3140,7 @@ }, "packages/runtime": { "name": "@genclass/runtime", - "version": "0.1.0-alpha.0", + "version": "0.1.0-alpha.1", "license": "Apache-2.0", "dependencies": { "onnxruntime-web": "^1.30.0" diff --git a/packages/runtime/package.json b/packages/runtime/package.json index e1b95fba..02ba5572 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@genclass/runtime", - "version": "0.1.0-alpha.0", + "version": "0.1.0-alpha.1", "description": "A client-side AI runtime for web apps: a local GenClass model watches user actions, async work, network, state and errors, and prevents stale writes, races, duplicates, inconsistent state and failure storms in real time.", "type": "module", "license": "Apache-2.0", From c16a3b00877ef7aa575dc14252bb46165ef930bc Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 01:36:33 -0400 Subject: [PATCH 07/25] docs: record the @genclass/runtime 0.1.0-alpha.1 publish alpha.1 is on npm as latest (2026-10-08, from 806a296, shasum 9e3e82bc, 26 files); local tag v0.1.0-alpha.1. OPEN_TASKS, HANDOFF, RELEASE, AGENTS.md and docs/agents updated: alpha.0 is the older v1 build, the alpha.1 patch is done, pushing mvp-v2 and the tag needs an account with write access. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 13 +++---- HANDOFF.md | 2 +- OPEN_TASKS.md | 16 +++++---- RELEASE.md | 9 ++--- docs/agents/README.md | 6 ++-- docs/agents/glossary.md | 10 +++--- docs/agents/model-io-contract.md | 2 +- docs/agents/overview.md | 12 +++---- docs/agents/playbooks.md | 4 +-- docs/agents/repo-map.md | 8 ++--- docs/agents/runtime/build-test-release.md | 23 ++++++------ docs/agents/runtime/decide-policy-actions.md | 4 +-- docs/agents/runtime/model-host.md | 4 +-- .../runtime/public-api-and-lifecycle.md | 6 ++-- docs/agents/status-and-known-issues.md | 35 ++++++++++--------- 15 files changed, 82 insertions(+), 72 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ae0b5dda..aa966f96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,8 +29,9 @@ Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current b ## 2. Status in brief (2026-10-08) - **Branches.** `mvp-v2` (here) = `origin/runtime` 74f17c0 (Mehar's latest: runtime batches 4 and 5, situation-v2, `realapps/`, - v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus three local commits: 7dab2b3 (these agent docs), - f3636b2 (default mode `observe`), b435acb (CI, committed root lockfile, CLI mode 100755). Not pushed. The local + v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus six local commits: 7dab2b3 (these agent docs), + f3636b2 (default mode `observe`), b435acb (CI, committed root lockfile, CLI mode 100755), b561244 and 6ac4737 (docs), + 806a296 (release commit, `packages/runtime` version `0.1.0-alpha.1`; the head). Not pushed. The local branch `mvp` is based on situation-v1 (654d822) and is superseded. - **Runtime:** situation-v2, frozen at tag `situation-v2` (6e5e86e). Since that tag, `packages/runtime/src` changed only in f3636b2 (`runtime.ts`, `types.ts`, `devtools/index.ts`); `git diff situation-v2 HEAD -- packages/runtime/src/situation` is empty. @@ -39,13 +40,13 @@ Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current b DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. - **Data is being generated now on Azure by Mehar** (per `training/NEEDS.md`): SIM situation-v2 gold and unlabeled rows on 20 nodes, REAL real-browser gold rows on 3 nodes. Nobody on our side touches Azure. -- **npm:** `@genclass/runtime@0.1.0-alpha.0` is `latest`. It predates situation-v2, defaults to `guard`, and has no model. +- **npm:** `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296: NaN fix, situation-v2, + default `observe`). `0.1.0-alpha.0` predates situation-v2 and defaults to `guard`. Neither has a model. `@genclass/runtime-model` is not published, so `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` 404: a default `GenClass.init()` ends with model status `error` and logs - `[GenClass] Model unavailable (...); observing only.` A `0.1.0-alpha.1` patch (NaN fix) waits on the owner's 2FA - (`OPEN_TASKS.md` "Needs the user"). Release plan: [RELEASE.md](RELEASE.md) (see also + `[GenClass] Model unavailable (...); observing only.` Release plan: [RELEASE.md](RELEASE.md) (see also [build-test-release](docs/agents/runtime/build-test-release.md) "Cut a release"). -- **Stale human docs:** `HANDOFF.md` ('Modes: observe → guard (default; ...)') and the published `0.1.0-alpha.0` still +- **Stale human docs:** `HANDOFF.md` ('Modes: observe → guard (default; ...)') and the older published `0.1.0-alpha.0` still say guard is the default; both READMEs now say observe. Test counts in STATUS/HANDOFF are older. Drift tables: [status-and-known-issues](docs/agents/status-and-known-issues.md). - **Open defects found by review at b435acb** (details and fixes in the subsystem docs' "Drift and open issues"): the F2 content fact can print the raw text of redacted fields (`situation/content.ts` -> `contentFacts`); a delivery diff --git a/HANDOFF.md b/HANDOFF.md index 406760d6..97eb3ae8 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -26,7 +26,7 @@ generic action. It has no hardcoded bug rules. | piece | state | |---|---| -| npm | `@genclass/runtime@0.1.0-alpha.0` published (org `genclass`, owner meharpro). The alpha takes no actions: it has no published model yet. Each publish needs the user's 2FA, so give them the exact `npm publish <tgz> --access public` command. | +| npm | `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296; NaN fix, situation-v2, default `observe`); `0.1.0-alpha.0` is the older v1 build (org `genclass`, owner meharpro). The alphas take no actions: there is no published model yet. Each publish needs the user's 2FA, so give them the exact `npm publish <tgz> --access public` command. | | git | Branch `runtime` (also fast-forwarded into `main` once). Tags: `situation-v1` (old format), `situation-v2` (**current frozen training format**, commit 6e5e86e), `v0.1.0-alpha.0` (GitHub pre-release). | | runtime | Batch 5 done; 346 tests pass. Decisions happen at the network boundary (`delivery` trigger). Store writes are never held by default. The never-worse sweep over 66 real apps with an always-passive model changed 0/396 clean runs. | | model | Round 1 (v1 data): R17 9.6 MB, guard false-intervention rate (FIR) 0.05%, recall on clear cases only ~8%. The cause is analysed in `sim/SEPARABILITY.md`; the fixes are in v2. **No v2 model trained yet.** | diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 1055e321..9f0ffc3b 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -9,6 +9,11 @@ The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). No sit ## Done +- **Published `@genclass/runtime@0.1.0-alpha.1` to npm** (published 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff). It ships the NaN fix (ad24804), the + situation-v2 runtime (decisions at the network boundary via the `delivery` trigger; store writes not held by default), + EventSource observed, synthetic DOM events ignored unless `observe: { untrustedEvents: true }`, default mode `observe` + (guard opt-in, heal experimental) and refreshed docs. No model is published, so it only observes. The first attempt + got a 403 because the publishing account had no 2FA; with 2FA enabled it went through browser-based 2FA approval. - **Published `@genclass/runtime@0.1.0-alpha.0` to npm** (2026-10-08, `genclass` org, owner meharpro). The tarball was smoke-tested in a fresh Vite app in headless Chromium (`packages/runtime/test/smoke/smoke.sh`). The alpha takes no actions: `@genclass/runtime-model` is not published, so the default model URL returns 404. @@ -142,14 +147,13 @@ package → demos rerun → runtime release. ## Needs the user -- **2FA publishes:** patch release `0.1.0-alpha.1` (fixes a crash when app state contains `NaN`, ad24804, found - after alpha.0 was published), later `@genclass/runtime-model@0.1.0` and `@genclass/runtime@0.1.0`. Agents - prepare the tarball and the exact command per [RELEASE.md](RELEASE.md) (alpha.1: `npm publish - genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha`); nothing is packed yet. +- **2FA publishes:** `@genclass/runtime-model@0.1.0` and `@genclass/runtime@0.1.0` (`0.1.0-alpha.1` is done). Agents + prepare the tarball and the exact command per [RELEASE.md](RELEASE.md). +- **Push** `mvp-v2` (head = release commit 806a296) and tag `v0.1.0-alpha.1` to origin (needs an account with write access). - **Public demo hosting** (GitHub Pages on this repo): OK to publish? - **Merging into `main`**: `runtime` and/or `mvp-v2` when ready. -- **Default mode decision:** `mvp-v2` defaults to `observe` (f3636b2); HANDOFF.md and the published alpha - say `guard`. Pick one before 0.1.0. +- **Default mode decision:** `mvp-v2` defaults to `observe` (f3636b2); HANDOFF.md and the older published + `0.1.0-alpha.0` say `guard` (`0.1.0-alpha.1`, now `latest`, defaults to `observe`). Pick one before 0.1.0. - **Re-enable the Azure auto-shutdown schedules when the training push ends** (disabled with the user's OK at 00:35 UTC; command in HANDOFF.md). Spend so far about $400 (RESULTS.md §7). diff --git a/RELEASE.md b/RELEASE.md index 8fa206f6..73a2ea87 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -7,11 +7,12 @@ ## TL;DR - **Two releases, in this order.** - - **Part A (now, no model).** An optional `@genclass/runtime@0.1.0-alpha.1` from `mvp-v2`, published under dist-tag `alpha`. It ships the NaN fix (ad24804), the situation-v2 runtime (batch 4 fcd1e68, batch 5 6e5e86e), the `observe` default (f3636b2) and updated docs. + - **Part A (done 2026-10-08, no model).** `@genclass/runtime@0.1.0-alpha.1` from `mvp-v2` (release commit 806a296), planned for dist-tag `alpha` but published under `latest`. It ships the NaN fix (ad24804), the situation-v2 runtime (batch 4 fcd1e68, batch 5 6e5e86e), the `observe` default (f3636b2) and updated docs. - **Part B (after a situation-v2 model exists).** First `@genclass/runtime-model@0.1.0` plus the GitHub release `runtime-model-v0.1.0`. Then a demos eval (Off / Observe / Guard). Last, `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. - **Who runs what.** Agents prepare and check everything: worktree, install, typecheck, build, unit tests, `npm pack`, the exact commands. **Only the user publishes** (`npm publish` and `npm dist-tag` need their npm 2FA). The user also approves every `git push`, tag push and `gh release`. Agents must ask before Playwright and `smoke.sh`, model downloads, demos eval, and anything that touches training or Azure. Those runs belong to Mehar's setup (`HANDOFF.md`). -- **Registry today** (`npm view`, 2026-10-08): - - `@genclass/runtime` has versions `0.0.0-stage` and `0.1.0-alpha.0`, with `latest` = `0.1.0-alpha.0`. That build is situation-v1, defaults to `guard`, still has the NaN crash, and has no model. +- **Part A was done** on 2026-10-08: `@genclass/runtime@0.1.0-alpha.1` published 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. It went to `latest` rather than `alpha`. The first attempt got a 403 (the account had no 2FA); after enabling 2FA it went through browser-based 2FA approval. The procedure below is kept for reference and for later releases. +- **Registry today** (`npm view`, 2026-10-08, before Part A): + - `@genclass/runtime` had versions `0.0.0-stage` and `0.1.0-alpha.0`, with `latest` = `0.1.0-alpha.0`. That build is situation-v1, defaults to `guard`, still has the NaN crash, and has no model. Since Part A, `latest` = `0.1.0-alpha.1`. - `@genclass/runtime-model` is **404**. - The npm org `genclass` has two members: `meharpro` (owner) and `karanvir1729` (developer). Both have read-write access to `@genclass/runtime`. - **The default model URL is pinned.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. Both 404 today. npm versions are immutable, so **whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently**. Validate before publishing. @@ -22,7 +23,7 @@ | path | role in a release | |---|---| -| `packages/runtime/package.json` | `@genclass/runtime`, `version` `0.1.0-alpha.0` on `mvp-v2`. `files`: `dist`, `bin`, `README.md`, `LICENSE`. No `prepublishOnly`, no `publishConfig`, no publish script | +| `packages/runtime/package.json` | `@genclass/runtime`, `version` `0.1.0-alpha.1` on `mvp-v2` (bumped in release commit 806a296, now the head of `mvp-v2`). `files`: `dist`, `bin`, `README.md`, `LICENSE`. No `prepublishOnly`, no `publishConfig`, no publish script | | `package-lock.json` (root) | committed (b435acb). Records the workspace versions, so a version bump changes it. CI's `npm ci` fails if it is out of sync | | `packages/runtime/README.md` | the npm page. Packed into the tarball, so it must be correct **before** packing | | `packages/runtime/LICENSE` | Apache-2.0. Packed | diff --git a/docs/agents/README.md b/docs/agents/README.md index cb4adc8d..bfd07548 100644 --- a/docs/agents/README.md +++ b/docs/agents/README.md @@ -23,7 +23,7 @@ Five facts change how you should read every other doc: - **The situation format is frozen at tag `situation-v2`** (6e5e86e, runtime batch 5). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts` (the default mode), `types.ts` (its JSDoc) and `devtools/index.ts` (mode labels); no model-visible code changed. The old tag `situation-v1` (1a77558) is the format of all data and models trained so far, so **no trained model matches the current runtime**. Any change to text the model reads needs the user's go-ahead (coordinate with the colleague who runs SIM/REAL/TRAIN), a new tag, regenerated SIM and realapps data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). - **Decisions happen at the network boundary.** situation-v2 adds the `delivery` trigger (a fetch/XHR response or a WebSocket/EventSource message about to reach the app; actions `deliver` / `discard` / `defer`) and no longer holds store writes by default (`policy.holdWrites: false`). Older docs and the human docs often still describe held store writes. See [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md). -- **The default mode is `observe`** on `mvp-v2` (our commit f3636b2: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`). `guard` is opt-in and `heal` experimental. The published `@genclass/runtime@0.1.0-alpha.0` (situation-v1 code) still defaults to `guard`, and so does `HANDOFF.md` (both READMEs now say `observe`). The unit-test harness (`packages/runtime/test/helpers.ts` -> `setup`) passes `mode: "guard"`. See [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). +- **The default mode is `observe`** on `mvp-v2` (our commit f3636b2: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`). `guard` is opt-in and `heal` experimental. The published `@genclass/runtime@0.1.0-alpha.1` (`latest`) also defaults to `observe`; the older `0.1.0-alpha.0` (situation-v1 code) defaults to `guard`, and so does `HANDOFF.md` (both READMEs now say `observe`). The unit-test harness (`packages/runtime/test/helpers.ts` -> `setup`) passes `mode: "guard"`. See [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). - **No model is published, so every install only observes.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which is a 404 on npm, as is the CLI's `DEFAULT_FROM`. A default `GenClass.init()` ends in model status `error` and never decides. The situation-v2 model comes from the scaled program in [training.md](training.md) (teacher -> distillation -> DAgger -> EVAL -> export). See [runtime/model-host.md](runtime/model-host.md). - **Run policy for agents** (set by the lead for this machine; `HANDOFF.md`'s "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac): - You may run `npm install` / `npm ci`, typecheck, the tsup build and the vitest unit tests locally. All of them were run when these docs were written, on 2026-10-08 (350 tests: 336 passed, 14 model-parity skips). @@ -99,7 +99,7 @@ Each row names the doc to read, and then any further docs to check. "Ask first" | Change the CI workflow (`.github/workflows/ci.yml`: Node 22, `npm ci`, typecheck, build, unit tests, `review-perf` alone with retries) | [runtime/build-test-release.md](runtime/build-test-release.md) ("CI") | — | | Add a public entry point (subpath export) | [runtime/build-test-release.md](runtime/build-test-release.md) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | | Run the Playwright specs or the npm-pack smoke test (ask first) | [runtime/build-test-release.md](runtime/build-test-release.md) | — | -| Prepare the `0.1.0-alpha.1` patch (NaN fix; the user publishes with 2FA, and npm 11 needs `--tag` for a prerelease) | [../../RELEASE.md](../../RELEASE.md) (Part A); [runtime/build-test-release.md](runtime/build-test-release.md) ("Cut a release") | [status-and-known-issues.md](status-and-known-issues.md), [playbooks.md](playbooks.md) ("Publish @genclass/runtime") | +| Cut a release of `@genclass/runtime` (the user publishes with 2FA, and npm 11 needs `--tag` for a prerelease) | [../../RELEASE.md](../../RELEASE.md); [runtime/build-test-release.md](runtime/build-test-release.md) ("Cut a release") | [status-and-known-issues.md](status-and-known-issues.md), [playbooks.md](playbooks.md) ("Publish @genclass/runtime") | | Publish `@genclass/runtime-model@0.1.0`, then `@genclass/runtime@0.1.0` (only after a situation-v2 model passes EVAL) | [../../RELEASE.md](../../RELEASE.md) (Part B); [runtime/build-test-release.md](runtime/build-test-release.md) ("Publish the model package") | [training.md](training.md) (export), [runtime/model-host.md](runtime/model-host.md) (card format), [playbooks.md](playbooks.md) | ### Sim, realapps, the v2 training program and demos @@ -199,6 +199,6 @@ The agent docs are derived from the code. They cite the human docs mainly to rec - `docs/runtime/API.md` is the public API reference for library users. If you change the public surface, update API.md and the JSDoc in `packages/runtime/src/types.ts` in the same change, then the agent doc. - `docs/runtime/ARCHITECTURE.md` is the design overview for humans. [docs/runtime/RESULTS.md](../runtime/RESULTS.md) holds the measured comparisons and the training log (HANDOFF asks for an update with every result). Their known drift is listed in [status-and-known-issues.md](status-and-known-issues.md). - [HANDOFF.md](../../HANDOFF.md) is the colleague's entry point for a new session (state, rules, how to continue). Its run rules are for his 8 GB Mac and the Azure cluster; our agents follow `AGENTS.md`. -- [RELEASE.md](../../RELEASE.md) at the repo root is the release procedure: Part A for `0.1.0-alpha.1`, Part B for the model and `0.1.0`. +- [RELEASE.md](../../RELEASE.md) at the repo root is the release procedure: Part A for `0.1.0-alpha.1` (done 2026-10-08), Part B for the model and `0.1.0`. - The workstream status files (`packages/runtime/STATUS.md`, `packages/runtime/UI-NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, `OPEN_TASKS.md`) are how the team coordinates. Follow the process in [status-and-known-issues.md](status-and-known-issues.md), and do not close or rewrite another workstream's items: the requester flips an item to DONE after verifying (owners may add answers under their own heading). REAL has no NEEDS file of its own; its requests and node claims live in `training/NEEDS.md`. - The legacy jev-local docs (`docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`) and `docs/benchmax-research/` are not the runtime contract. CONTRACT §1 says this earlier GenClass content "stays as is". They are summarised in [genclass-model-lineage.md](genclass-model-lineage.md) and [extension-and-benchmarks.md](extension-and-benchmarks.md). diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md index e8d1749e..8305dbaa 100644 --- a/docs/agents/glossary.md +++ b/docs/agents/glossary.md @@ -174,7 +174,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **GenClass op**: An instant op of kind `genclass` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause `null`) for undo, revert, rollback, resync and custom actions. Writes and requests inside it are never gated and are excluded from baselines and profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runAsGenClass`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **genclass-<size> / meharsjev-<size>**: Model ids allowed for benchmax runs (`genclass-<size>`, legacy `meharsjev-<size>`); `jev-*` and `typesafe/*` ids are rejected (W10). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **genclass-runtime (CLI)**: The package's bin: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info <dir>` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`. Doc: [model-host](runtime/model-host.md). -- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.0` is the latest published version: it predates batches 4–5 and the observe default (its default is `guard`), and with no published model it takes no actions. A `0.1.0-alpha.1` patch with the NaN fix needs the owner's 2FA (`OPEN_TASKS.md` "Needs the user"); `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) +- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.1` is the latest published version (`latest`, 2026-10-08, release commit 806a296): NaN fix, situation-v2, default `observe`; with no published model it takes no actions. The older `0.1.0-alpha.0` predates batches 4–5 and the observe default (its default is `guard`). `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) - **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0 (npm 404). Only `packages/runtime-model/MODEL_CARD.md` exists. 0.1.0 must be a situation-v2 model, which does not exist yet. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **`@genclass/sim` / `@genclass/demos` / `@genclass/realapps`**: The private packages `sim/` and `demos/` (root workspaces) and `realapps/` (not a workspace). `sim` and `demos` depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first; `realapps/build.mjs` bundles the runtime from source instead (`RW_RUNTIME_SRC`, default the working tree). Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). - **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `<repo>/.cache-model`, filled with `genclass-runtime fetch-model <dir> --from <v0.1 release URL>` (ask first; the default `--from` is unpublished)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). @@ -246,7 +246,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **MessageGate**: The batch-4 delivery gate for push channels: one per WebSocket or EventSource, intercepting `message` events, queueing them per channel in arrival order, asking `runDelivery` for each and re-dispatching released messages to the app's listeners, so a held message delays later ones instead of being overtaken. Review findings: held messages can be dispatched after the app called `close()`, a capture-phase listener can see a held message twice, and EventSource `open` is not kept in order. Code: `packages/runtime/src/observe/messages.ts` -> `MessageGate`, `MsgHost`; installed by `packages/runtime/src/observe/websocket.ts` -> `installWebSocket` and `packages/runtime/src/observe/eventsource.ts` -> `installEventSource`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **mix_* (mixture config)**: `training/configs/mix_*.json`: bucket weights for a training round, read as `MixConfig`. Round-1 era: `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` (simA 0.85, cur4 0.12, cur1 0.02, gen 0.01). Added since: `mix_t150` (teacher: simA 0.9, cur4 0.1), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs on `simAg10` / `simAg20` / `simAh`). All name v1 buckets; no v2 or distillation mixture exists yet. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). - **MockRuntime / loadScenario / runStoreSession**: The devtools and adapter UI test harness: `MockRuntime` is a scripted `Runtime`; `loadScenario` scripts a store story with 3 interventions and 3 detections; `runStoreSession` drives the real `createRuntime` with a virtual clock, a fake backend and the rule-based `SessionDecider`. Code: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`; `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario`; `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession`. Doc: [devtools](runtime/devtools.md). -- **mode**: `observe | guard | heal`, which action tiers may run. **Default `observe`** since f3636b2 on `mvp-v2` (`o.mode ?? "observe"`; it was `guard` up to and including `0.1.0-alpha.0` and origin/runtime). `observe` permits passive only: it never runs an action or holds a request or write, but while a model is consultable a conflicting delivery can still wait up to 100 ms (`BODY_WAIT_MS`) for its body read and WebSocket/EventSource messages are re-dispatched as clones (see [observe-and-trace](runtime/observe-and-trace.md) Drift); but triggers are still built and decided in the background so detections and reports work (review finding: background `delivery` decisions are dropped as stale, so delivery detections and delivery standing questions never answer in observe mode). `guard` (opt-in) adds guard-tier actions; `heal` (experimental) adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`; devtools labels them "Observe (default)", "Guard (opt-in)", "Heal (experimental)". The test harness `setup()` still defaults to `guard`, and the sim and realapps pass `heal` explicitly. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `Mode`, `InitOptions.mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`; test `packages/runtime/test/default-mode.test.ts`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **mode**: `observe | guard | heal`, which action tiers may run. **Default `observe`** since f3636b2 on `mvp-v2` (`o.mode ?? "observe"`; it was `guard` up to and including `0.1.0-alpha.0` and origin/runtime; `0.1.0-alpha.1` on npm defaults to `observe`). `observe` permits passive only: it never runs an action or holds a request or write, but while a model is consultable a conflicting delivery can still wait up to 100 ms (`BODY_WAIT_MS`) for its body read and WebSocket/EventSource messages are re-dispatched as clones (see [observe-and-trace](runtime/observe-and-trace.md) Drift); but triggers are still built and decided in the background so detections and reports work (review finding: background `delivery` decisions are dropped as stale, so delivery detections and delivery standing questions never answer in observe mode). `guard` (opt-in) adds guard-tier actions; `heal` (experimental) adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`; devtools labels them "Observe (default)", "Guard (opt-in)", "Heal (experimental)". The test harness `setup()` still defaults to `guard`, and the sim and realapps pass `heal` explicitly. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `Mode`, `InitOptions.mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`; test `packages/runtime/test/default-mode.test.ts`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **MODEL (workstream)**: Owns `packages/runtime/src/model/**` and `packages/runtime/bin/genclass-runtime.mjs`, and co-owns the "model seam" section of `packages/runtime/src/types.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). - **model card**: `model.json` in format `genclass-runtime-model/1`: `name`, `version`, `variants` (`q8`, `fp16`: file, bytes, sha256, provider, needs) and `files` (`tokenizer`, `calibration`, `meta`). `parseCard` also accepts the v0.1 extension card. Code: `packages/runtime/src/model/loader.ts` -> `parseCard`, `CARD_FORMAT`. Doc: [model-host](runtime/model-host.md). - **model directory**: A folder or URL holding `model.json` plus the ONNX variants, `tokenizer.json`, `calibration.json` and `meta.json`; produced by `training/export_runtime.py`, fetched with `genclass-runtime fetch-model`, passed as `model: { baseUrl }`, read by tests from `GENCLASS_MODEL_DIR`. Downloads are cached in Cache Storage `genclass-runtime-v1`. Doc: [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md). @@ -259,7 +259,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## N -- **NaN fix / 0.1.0-alpha.1**: Commit ad24804 fixed infinite recursion when a store value is `NaN` (`packages/runtime/src/util.ts`, test `test/nan.test.ts`), found after `0.1.0-alpha.0` was published. The planned `0.1.0-alpha.1` patch release needs the owner's npm 2FA; it is not published. Doc: [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) +- **NaN fix / 0.1.0-alpha.1**: Commit ad24804 fixed infinite recursion when a store value is `NaN` (`packages/runtime/src/util.ts`, test `test/nan.test.ts`), found after `0.1.0-alpha.0` was published. It shipped in `0.1.0-alpha.1`, published 2026-10-08 under `latest` from release commit 806a296. Doc: [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) - **native timers (demos)**: Timers captured before `GenClass.init` wraps the globals; all test code (driver, oracle) uses them, so the runtime never sees test ops. Code: `demos/src/shared/native.ts`. Doc: [demos](demos.md). - **NATIVE_FETCH**: `globalThis.fetch` captured when `index.ts` is evaluated; an owned model host downloads with it, so GenClass never observes its own model download. Code: `packages/runtime/src/index.ts` -> `NATIVE_FETCH`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exception `packages/runtime/UI-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). @@ -332,7 +332,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **realapps**: The real-browser corpus in `realapps/` (fcb8189): 91 apps at b435acb (77 written for it + 14 open-source RealWorld "Conduit" front-ends; READMEs still say 66) across 23 frameworks, run in headless Chromium with the real runtime bundled from source, on virtual time with an in-page mock backend and chaos. It labels decisions by counterfactual outcome with the sim's cost weights and label rule and writes CONTRACT-D rows (`meta.source = "realapps"`, ids `real-<app>-<seed>-…`), and hosts the *never-worse* and *determinism* sweeps. Not a workspace, not in CI, no tests; everything real needs Chromium or Azure (ask first). Doc: [realapps](realapps.md). - **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when `isSensitivePath(path, value)` holds: since fcb8189 the rule looks at the leaf field name by meaning (words and secret pairs such as password, token, card number, api key, ...), with container rules (a strong secret container redacts strings beneath it, a broad one only opaque-looking strings), never at the store's name. Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Review findings: numbers and arrays under a secret container are no longer redacted, the F2 diff preview can print redacted text, and `docs/runtime/CONTRACT.md` still describes the old substring rule; use a custom redactor for app-specific secrets. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **relation (sim)**: An app-declared executable invariant (`Relation { fields, desc, check(stores) }`, e.g. count = len(items), total = Σ price × qty, badge = cart count); ground truth for the `inconsistent` diagnosis and a cost term. Code: `sim/src/app/feature.ts` -> `Relation`. Doc: [sim](sim.md). -- **RELEASE.md**: Repo-root release procedure (untracked at b435acb; commit it with docs that link it): Part A `0.1.0-alpha.1` under dist-tag `alpha`; Part B `@genclass/runtime-model@0.1.0` (plus the `runtime-model-v0.1.0` GitHub release), then the runtime. Only the user publishes. Doc: [RELEASE.md](../../RELEASE.md). +- **RELEASE.md**: Repo-root release procedure (untracked at b435acb, committed in b561244): Part A `0.1.0-alpha.1` (planned under dist-tag `alpha`, published under `latest` on 2026-10-08); Part B `@genclass/runtime-model@0.1.0` (plus the `runtime-model-v0.1.0` GitHub release), then the runtime. Only the user publishes. Doc: [RELEASE.md](../../RELEASE.md). - **render bits (devtools)**: Dirty flags `STATUS=1, MODE=2, LISTS=4, EVENTS=8` (ALL=15) OR'ed by `mark()` and flushed once per animation frame; LISTS and EVENTS are deferred while the panel is closed or paused. Doc: [devtools](runtime/devtools.md). - **repeat folding (devtools)**: Detections with the same `repeatKey` (trigger, diagnosis, action and subject, digits normalised) within 60 s of a card's latest repeat fold into one card with a `×N` badge. Code: `packages/runtime/src/devtools/ui.ts` -> `repeatKey`. Doc: [devtools](runtime/devtools.md). - **replay (training)**: Curriculum (`cur1`–`cur4`) and GenClass 0.1 (`gen`, `cu`) buckets mixed into SIM-based rounds. Doc: [training](training.md). @@ -452,7 +452,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **v0.1 fixture set**: `packages/runtime/test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests with the Python packer output and PyTorch logits of the v0.1 GenClass model. Doc: [build-test-release](runtime/build-test-release.md). - **v0.1 model**: See *GenClass 0.1 (v0.1 model)*. -- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, still the latest on npm (checked 2026-10-08). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, the first published alpha; since 2026-10-08 `latest` is `0.1.0-alpha.1` (tag `v0.1.0-alpha.1` on 806a296, local only). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **v2b1 / v2b2 / v2b3 (REAL batches)**: REAL's situation-v2 production batches on c01, c10 and c11 (30k trajectories each, about 495k gold rows in total per HANDOFF/RESULTS; NEEDS target ≥ 500k), to be copied to `train:/data/real-out/` (`training/NEEDS.md` item 16; not verifiable from the repo). Their `manifest.json` still says `situation-v1` (hardcoded in `realapps/src/harness/gen.ts`). Doc: [realapps](realapps.md). - **variant (jevbench)**: Request flavour per item: `main` (the only one counted), `shuffle` (option-order rotation), `bare` (no descriptions), `choice` (SST-2 only). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **variant (model)**: One ONNX file of a model, keyed in `card.variants`: `q8` (meant for WASM) or `fp16` (meant for WebGPU with `shader-f16`). See *q8*, *plan*. Doc: [model-host](runtime/model-host.md). diff --git a/docs/agents/model-io-contract.md b/docs/agents/model-io-contract.md index 24a50381..d67c3bc1 100644 --- a/docs/agents/model-io-contract.md +++ b/docs/agents/model-io-contract.md @@ -627,7 +627,7 @@ Since `situation-v2`, `packages/runtime/src/situation`, `util.ts`, `state/` and ## Drift and open issues -- **No situation-v2 model; npm default URL 404.** R17-final1 is `situation-v1` and exists only on the train VM / Mehar's Mac. `@genclass/runtime-model` is not published, so `DEFAULT_MODEL_BASE_URL` (and the CLI default) return 404; `@genclass/runtime@0.1.0-alpha.0` ships no model (and still defaults to `guard`; a 0.1.0-alpha.1 NaN-fix patch needs the owner's 2FA, OPEN_TASKS.md). Plan per HANDOFF: T150 teacher on v2 gold → teacher labels on unlabeled rows → distil R17 (default) and R32 → DAgger via `--on-policy` → EVAL → `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0`. Release procedure: [RELEASE.md](../../RELEASE.md) (Part A alpha.1, Part B model packaging and validation). +- **No situation-v2 model; npm default URL 404.** R17-final1 is `situation-v1` and exists only on the train VM / Mehar's Mac. `@genclass/runtime-model` is not published, so `DEFAULT_MODEL_BASE_URL` (and the CLI default) return 404; `@genclass/runtime@0.1.0-alpha.1` (`latest`, published 2026-10-08) ships no model, nor did the older `0.1.0-alpha.0` (which also defaults to `guard`). Plan per HANDOFF: T150 teacher on v2 gold → teacher labels on unlabeled rows → distil R17 (default) and R32 → DAgger via `--on-policy` → EVAL → `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0`. Release procedure: [RELEASE.md](../../RELEASE.md) (Part A alpha.1, done; Part B model packaging and validation). - **SIM scenario budgets still 3,200 / 2,000 / 1,000** (`scenario.ts`, comment "3,200 WebGPU"; sim/README.md says the same), while the runtime's webgpu/unknown auto budget is 2,400 and section limits saturate at 2,400. SIM v2 data never renders the production webgpu budget exactly, and its 3,200 rows are longer than anything a v2 runtime sends by default. `rt.py` `BUDGETS` uses 2,400. `training/PLAN-v1.md` ECE targets and MODEL_CARD latency still quote 3,200. - **Sim action paraphrases on delivery** (gotchas): `ACTION_PARA` is keyed by action name, so paraphrased trajectories give delivery `deliver`/`discard`/`defer` failure- or write-flavoured descriptions; there is no delivery-specific paraphrase set. - **`collect_gain.py` needs a gain head the repo does not have:** it reads `o.gain` from `heads(...)`, but `jev_local/engine/encoder/heads.py` -> `HeadOut` defines no `gain` field. The gain-head code (`r17-t1h`, `training/LOG.md` 03:00–03:12) presumably lives in the VM's `~/jev` (unverified). No T1 result exists on v1; T1 is to be rerun on v2 (`training/LOG.md` 03:32). diff --git a/docs/agents/overview.md b/docs/agents/overview.md index b7cfb3bc..75b214d4 100644 --- a/docs/agents/overview.md +++ b/docs/agents/overview.md @@ -42,7 +42,7 @@ Path convention: every code pointer is `path/from/repo/root` -> `symbol`. Runtim - Fail open everywhere: no model, a loading or failed model, a timeout or any error means the passive action runs; the runtime holds only when a non-passive action is permitted **and** the model is expected to answer within the hold budget (at most 800 ms with the default `"auto"`). -- **Where it stands:** `@genclass/runtime@0.1.0-alpha.0` (situation-v1 code, default `guard`) is on npm; no model is +- **Where it stands:** `@genclass/runtime@0.1.0-alpha.1` (situation-v2, NaN fix, default `observe`) is `latest` on npm; no model is published (`@genclass/runtime-model` is a 404), so any install only observes. No situation-v2 model exists. The colleague is generating v2 data on Azure (SIM ~10M gold + ~50M unlabeled rows on 20 nodes; REAL ~0.5M real-browser gold rows on 3 nodes); next comes the 150M teacher, distillation into R17/R32, DAgger, EVAL, the model package, a @@ -123,7 +123,7 @@ Adoption path: `observe` (default) -> `guard` -> `heal`. | Decide | `packages/runtime/src/decide/*`, controllers in `runtime.ts` | queue (stale drop, deadlines), hold budget, policy gate, actions, reports, explain, undo | frozen at `situation-v2` | [decide-policy-actions](runtime/decide-policy-actions.md) | | Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | unchanged since `situation-v1`; no model to load | [model-host](runtime/model-host.md) | | Devtools | `packages/runtime/src/devtools/*` | shadow-DOM overlay on the public API | mode labels "Observe (default)", "Guard (opt-in)", "Heal (experimental)" | [devtools](runtime/devtools.md) | -| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}`, root `package-lock.json`, `.github/workflows/ci.yml` | tsup ESM build (6 entries), vitest (351 tests), Playwright, smoke test, CI | alpha.0 published; lockfile and CI committed (CI not yet run on GitHub: `mvp-v2` is not pushed) | [build-test-release](runtime/build-test-release.md) | +| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}`, root `package-lock.json`, `.github/workflows/ci.yml` | tsup ESM build (6 entries), vitest (351 tests), Playwright, smoke test, CI | alpha.1 published (`latest`; alpha.0 before it); lockfile and CI committed (CI not yet run on GitHub: `mvp-v2` is not pushed) | [build-test-release](runtime/build-test-release.md) | | Model I/O contract | runtime `situation/*` + `model/*`, `sim/`, `realapps/`, `training/` | situation text -> packed request -> heads -> calibrated answers; row kinds and labels | format `situation-v2` | [model-io-contract](model-io-contract.md) | | Model package | `packages/runtime-model/` | planned home of the published model directory | only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | | Sim | `sim/` (`@genclass/sim`) | training-data generator driving the real runtime in a virtual world: 46 feature combinators × 115 domains; gold, unlabeled and on-policy rows; S1/S2 labels | v1 data on disk (phase A 600,676, phase B 1,415,344 rows); v2 runs in progress on Azure | [sim](sim.md) | @@ -409,8 +409,8 @@ guard 0.9, heal 0.8. Default: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` Also: `policy.allow` / `policy.deny` narrow the permitted set; `policy.holdWrites: true` re-enables held store writes (opt-in, never reorders a store's writes); `pause()` stops gating and triggers while tracing continues; `setMode` applies to the next gate. Passive actions per trigger: mutation `apply`, request `send`, delivery `deliver`, failure -`deliver`, stall `wait`, inconsistency/transition/error `ignore`. The published alpha.0 and HANDOFF.md still say -`guard` is the default; the unit-test harness passes `mode: "guard"`. Details: +`deliver`, stall `wait`, inconsistency/transition/error `ignore`. The older published alpha.0 and HANDOFF.md still say +`guard` is the default (alpha.1 says `observe`); the unit-test harness passes `mode: "guard"`. Details: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). ## 7. With no model: fail open, observe only @@ -463,11 +463,11 @@ update the relevant STATUS/NEEDS entry when you change behaviour they describe. | item | state | |---|---| -| Branches | `mvp-v2` = origin/runtime 74f17c0 + our three commits (not pushed). The local branch `mvp` (based on 654d822, situation-v1) is superseded. Tags: `situation-v1` (1a77558), `situation-v2` (6e5e86e, current format), `v0.1.0-alpha.0` (654d822). | +| Branches | `mvp-v2` = origin/runtime 74f17c0 + our six commits, head = release commit 806a296 (not pushed). The local branch `mvp` (based on 654d822, situation-v1) is superseded. Tags: `situation-v1` (1a77558), `situation-v2` (6e5e86e, current format), `v0.1.0-alpha.0` (654d822), `v0.1.0-alpha.1` (806a296, local only). | | Runtime | batches 4 and 5 done: decisions at the network boundary, no store holds by default, EventSource observer, F1–F9 facts, leaf-based redaction, 2,400-char full budget; default mode `observe` (ours). | | Tests | lead's run on `mvp-v2` (macOS, Node v25.6.0): `tsc` clean, `tsup` OK, vitest 351 tests = 337 passed + 14 model-parity skips (333 + 14 in the main run, counting the uncommitted `atoms.test.ts` test, 4 in `review-perf.test.ts` alone; it flaked once at 5.5 ms vs its 2 ms bound under parallel load). sim: `tsc` clean, `SIM_RUNTIME=real npx vitest run` 19 passed in 5 files. Not run: Playwright, `smoke.sh`, realapps, demos eval, Python tests, training. | | CI | `.github/workflows/ci.yml` (Node 22, `npm ci`, typecheck, build, unit tests, then `review-perf` with `--retry=2`); its steps pass in a fresh clone; it has not run on GitHub yet. | -| npm | `@genclass/runtime@0.1.0-alpha.0` is `latest` (situation-v1 code, default `guard`, no model). Pending with the user's 2FA: `0.1.0-alpha.1` (NaN fix, `OPEN_TASKS.md` "Needs the user"). `@genclass/runtime-model` is a 404. Release procedure: [RELEASE.md](../../RELEASE.md). | +| npm | `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296; NaN fix, situation-v2, default `observe`, no model). The older `0.1.0-alpha.0` is situation-v1 code with default `guard`. `@genclass/runtime-model` is a 404. Release procedure: [RELEASE.md](../../RELEASE.md). | | Model | no situation-v2 model. R17-final1 (situation-v1) is the baseline only (section 5.3). | | Data | SIM v2 (≥ 10M gold + ≥ 50M unlabeled) on c02–c09 and c12–c23; REAL v2 (≥ 500k gold) on c01, c10, c11; the colleague is operating the cluster (a read-only portal look at 04:14 UTC showed c01–c23 and `vm-jev-train` running, `vm-jev-data` deallocated). Nobody on our side touches Azure. | | Never worse | realapps sweep, v2 runtime, all-passive model: 0/396 clean runs changed, 3/198 with chaos (request-time holds shifting chaos draws; open), determinism 198/198, conduit 0/30 (STATUS.md). These cover the 66 apps at the time, not the 25 added since, and compare final visible text and server content only ([realapps](realapps.md)). | diff --git a/docs/agents/playbooks.md b/docs/agents/playbooks.md index 77d62b7f..ea008ee0 100644 --- a/docs/agents/playbooks.md +++ b/docs/agents/playbooks.md @@ -258,7 +258,7 @@ A change is done when all of these hold. Say explicitly in your final report whi | default | value | defined in | |---|---|---| -| `mode` | `"observe"` (f3636b2; `"guard"` before, and still in `0.1.0-alpha.0` on npm) | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | +| `mode` | `"observe"` (f3636b2; `"guard"` before, and still in the older `0.1.0-alpha.0` on npm) | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | | `settleMs`, `historySize` | 60, 500 | same constructor | | `policy.thresholds` report / guard / heal | 0.6 / 0.9 / 0.8 | `packages/runtime/src/decide/policy.ts` -> `policyConfig` | | `policy.holdBudgetMs` | `"auto"`: clamp(round(1.5 × median latency), `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800); `HOLD_FALLBACK_MS` 300 with no data | `policyConfig`, `holdBudget` | @@ -591,7 +591,7 @@ Sim typecheck and `SIM_RUNTIME=real npx vitest run` are light local checks (buil **Steps.** 1. **Decide with the user which release** (RELEASE.md A0, B0): - - **Part A, `0.1.0-alpha.1` (optional, now, no model):** the NaN fix plus the situation-v2 runtime and the `observe` default, published under dist-tag `alpha` (moving `latest` afterwards is the user's choice). Without a model it only observes, so the open review findings go into the release notes, not the blocker list. + - **Part A, `0.1.0-alpha.1` (done 2026-10-08, no model):** the NaN fix plus the situation-v2 runtime and the `observe` default, published under dist-tag `latest` from release commit 806a296 (the plan was dist-tag `alpha`). Without a model it only observes, so the open review findings go into the release notes, not the blocker list. - **Part B (after a situation-v2 model exists):** `@genclass/runtime-model@0.1.0` and its GitHub release first (recipe 20), then the demos eval (recipe 22), then `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. Part B treats the open findings as blockers. - Which branch and commit: `mvp-v2` is unpushed; the colleague works on `origin/runtime`. The release commit must reach `origin` (the user decides how). 2. **Fix what the tarball ships** (RELEASE.md A1): `packages/runtime/README.md` is the npm page: check the README status line and version before packing, and commit any fix. diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index 86395ed7..2e821bd6 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -18,7 +18,7 @@ Workstream names (lead, CORE, MODEL, UI, SIM, REAL, DEMOS, TRAIN, REVIEW) and th | dir | tracked files | what | owner / workstream | doc | relevance | |---|---|---|---|---|---| -| `packages/runtime/` | 154 | `@genclass/runtime` 0.1.0-alpha.0, the npm library: `src/` (61), `test/` (84), `bin/genclass-runtime.mjs` CLI (mode 100755 since b435acb), package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Lead (us, on `mvp-v2`): `test/default-mode.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/runtime/` | 154 | `@genclass/runtime` 0.1.0-alpha.1 (since release commit 806a296), the npm library: `src/` (61), `test/` (84), `bin/genclass-runtime.mjs` CLI (mode 100755 since b435acb), package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Lead (us, on `mvp-v2`): `test/default-mode.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | | `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished (npm 404). No situation-v2 model exists yet | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | | `sim/` | 106 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows. Now 46 feature combinators, 115 domains, S1/S2 labels, gold / unlabeled / on-policy row modes, Azure cluster scripts, separability analysis | SIM | [sim.md](sim.md) | supporting | | `realapps/` | 230 | `@genclass/realapps` (private, **not** a root workspace): 91 real web apps (77 written + 14 open-source Conduit front-ends) run in headless Chromium with the real runtime; counterfactual labels like the sim; the "never worse" interference and determinism sweeps | REAL | [realapps.md](realapps.md) | supporting | @@ -73,7 +73,7 @@ Doc: [runtime/build-test-release.md](runtime/build-test-release.md), [runtime/pu ```text packages/runtime/ - package.json @genclass/runtime 0.1.0-alpha.0; exports . ./react ./redux ./zustand ./devtools ./worker; bin genclass-runtime; + package.json @genclass/runtime 0.1.0-alpha.1 (806a296); exports . ./react ./redux ./zustand ./devtools ./worker; bin genclass-runtime; dep onnxruntime-web ^1.30.0; optional peers react/redux/zustand; scripts build typecheck test test:browser tsconfig.json typecheck project (include src only: tests are never type-checked) tsup.config.ts 6 ESM entries (index, adapters/react|redux|zustand, devtools/index, worker) -> dist/; .d.ts for all but worker @@ -1000,7 +1000,7 @@ Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitign | `test-results/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright (`packages/runtime/test-results/{browser,ui}`), model benchmarks (`packages/runtime/test-results/model-bench/`) | — | | `playwright-report/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright HTML reporter | — | | `demos/e2e/.out/` | `demos/.gitignore` | `demos/e2e/eval.ts` (`partial.json`, `traces*.json` with `--trace`) | input to `demos/e2e/trace-report.ts` | -| `*.tgz` | root | `npm pack` in `packages/runtime/test/smoke/smoke.sh` (left in `packages/runtime/`) | the alpha.1 patch tarball would also land here | +| `*.tgz` | root | `npm pack` in `packages/runtime/test/smoke/smoke.sh` (left in `packages/runtime/`) | a release tarball (`genclass-runtime-<version>.tgz`) also lands here | | `.publish/` | root | no tracked script; added with the alpha publish (59c213f) | purpose not recorded | | `.vite/` | root | Vite cache directory (no config in the repo sets `cacheDir`; Vite's default is `node_modules/.vite`) | — | | `data/` (any depth) | root | not produced in this repo. Matches the missing `jev_local/data/` (data generators) and `demos/src/server/data/cities.ts`; Azure hosts keep training data under `$G/data/` | the rule hides source files that the code imports | @@ -1057,7 +1057,7 @@ Other source files over 25 KB that are better read by symbol than end to end: `p Doc-vs-code drift you will meet while navigating; the subsystem docs have the details. -- **Default mode**: code, `docs/runtime/API.md`, CONTRACT §13 and the devtools say `observe`; `README.md` and `packages/runtime/README.md` agree; only `HANDOFF.md` (and the published alpha.0) still say guard is the default. +- **Default mode**: code, `docs/runtime/API.md`, CONTRACT §13 and the devtools say `observe`; `README.md` and `packages/runtime/README.md` agree; only `HANDOFF.md` (and the older published alpha.0) still say guard is the default. - **`OPEN_TASKS.md`** now describes the v2 pipeline (items 1-14); see also [HANDOFF.md](../../HANDOFF.md) and [training.md](training.md). - **App counts**: `realapps/README.md` and `HANDOFF.md` say 66 apps; the tree has 91 (25 added after the sweeps were run). The never-worse result 0/396 covers the 66 ([realapps.md](realapps.md)). - **Sim budget**: `sim/src/world/scenario.ts` still samples situation budgets 3,200 / 2,000 / 1,000 (40/30/30), while the v2 runtime's full budget is 2,400 ([sim.md](sim.md)). diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index eed18986..5458012e 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -19,7 +19,7 @@ - Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. **No situation-v2 model exists yet**; the only fixtures and models are the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). - Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. Not run in CI. - `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. Not run in CI. -- Released: `@genclass/runtime@0.1.0-alpha.0` on npm, dist-tag `latest` (checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish <tgz> --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). Pending: `0.1.0-alpha.1` (NaN fix, `OPEN_TASKS.md` "Needs the user"), then `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. +- Released: `@genclass/runtime@0.1.0-alpha.1` on npm, dist-tag `latest`, 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. Before it: `@genclass/runtime@0.1.0-alpha.0` (was `latest`; checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish <tgz> --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). Pending: `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. - `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. `realapps` bundles `packages/runtime/src` directly with esbuild (see [../realapps.md](../realapps.md)). ## Files @@ -31,7 +31,7 @@ | `.gitignore` | ignores build and model artefacts | "GenClass runtime" block: `node_modules/`, `dist/`, `.vite/`, `test-results/`, `playwright-report/`, `sim/out/`, `packages/runtime-model/files/`, `.cache-model/`, `.publish/`, `*.tgz` (the last two added in 59c213f). Older Python block: `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/`, `data/`, `models/`, `runs/`, `dist/`, `node_modules/`, `.DS_Store`. `data/`, `models/`, `runs/` are unanchored (match at any depth). `package-lock.json` is **not** ignored | | `package-lock.json` (root) | committed lockfile (b435acb) | `lockfileVersion: 3`, 213 `packages` entries; records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }`. Resolved versions include `vitest 5.0.3`, `tsup 8.5.1`, `typescript 5.9.3`, `esbuild 0.27.7`, `happy-dom 20.14.5`, `onnxruntime-web`/`onnxruntime-node 1.30.0`, `@playwright/test 1.63.0`, `vite 8.3.3`. `npm ci` installs exactly this | | `.github/workflows/ci.yml` | the only CI workflow (b435acb) | job `runtime`; see [CI](#ci-githubworkflowsciyml) | -| `packages/runtime/package.json` | the published package (unchanged since 654d822) | name `@genclass/runtime`, version `0.1.0-alpha.0`, `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | +| `packages/runtime/package.json` | the published package | name `@genclass/runtime`, version `0.1.0-alpha.1` (bumped in release commit 806a296, the head of `mvp-v2`; it was `0.1.0-alpha.0` from 59c213f to b435acb), `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | | `packages/runtime/tsconfig.json` | typecheck project | extends base; `rootDir: src`, `outDir: dist`, `jsx: react-jsx`, `types: []`, `include: ["src"]` | | `packages/runtime/tsup.config.ts` | build | entries, dts entries, externals | | `packages/runtime/vitest.config.ts` | unit-test runner config | include `test/**/*.test.ts`, exclude `test/browser/**`, env `node`, `testTimeout 20000` | @@ -188,7 +188,7 @@ Facts STATUS records for this mode: `global.fetch` (and WebSocket, EventSource, ### Smoke test (`bash test/smoke/smoke.sh`, from `packages/runtime`) -1. `npm run build`, then `npm pack` -> `<pkg>/genclass-runtime-0.1.0-alpha.0.tgz` (name from npm's scoped-package convention; gitignored as `*.tgz`). +1. `npm run build`, then `npm pack` -> `<pkg>/genclass-runtime-<version>.tgz` (today `genclass-runtime-0.1.0-alpha.1.tgz`) (name from npm's scoped-package convention; gitignored as `*.tgz`). 2. Creates a temp Vite app (`mktemp -d`/app) whose `src/main.js` calls `GenClass.init({ model: false, report: "console" })`, creates atom `search.results`, wires an input to a `data:` URL fetch, and calls `mountDevtools(rt)`. 3. `npm install` the tarball + `vite@8` + `@playwright/test@1.63.0` (needs registry access), `npx vite build`. 4. `check.mjs` serves `dist/` on port `4191` (plain `node:http`), opens it in Chromium (`chromium.launch()` from the app's `@playwright/test`), waits for `window.__smoke.ok`, `p.fill("#q", "rea")`, waits for `#out` to read `rea-1`, prints one JSON line `{ info: { status, events, devtools }, errs }`, and exits 1 unless there are no page errors / console errors, `genclass-devtools` exists, and `rt.history().length >= 3` (`status` is printed, not asserted). Then prints `SMOKE OK: <tgz>`. @@ -390,7 +390,7 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the - **Fixture JSON files are single-line.** `wc -l` prints `0` for `pack_fixtures.json` (955,379 bytes), `py_fixtures.json` (167,629), `requests50.json` (285,309) and `torch_fixtures.json` (255,945): no trailing newline, not empty. Use `wc -c` or a JSON parser. - **No `prepublishOnly` and no `publishConfig`.** `npm publish` packs whatever `dist/` holds; build right before publishing. Scoped packages publish as restricted unless `--access public` is passed (npm behaviour). - **The root lockfile is committed; keep it in sync.** Since b435acb `package-lock.json` is tracked and CI runs `npm ci`, which fails when any workspace `package.json` (root, `packages/*`, `sim`, `demos`) no longer matches the lockfile. After changing a dependency, run `npm install` at the repo root and commit the updated lockfile in the same commit. `realapps/` is not a workspace and has no lockfile of its own. -- **Test harness mode is not the product mode.** `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so a test that does not pass `mode` exercises guard, while a real app (and `GenClass.init`, the smoke script, any package built from this branch; the published `0.1.0-alpha.0` still defaults to guard) starts in `observe`. To test default behaviour pass `mode: undefined`. New headless harnesses that build their own runtime (like `review-fetch.test.ts` -> `headless()`) must pass `mode` explicitly or they observe only. +- **Test harness mode is not the product mode.** `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so a test that does not pass `mode` exercises guard, while a real app (and `GenClass.init`, the smoke script, any package built from this branch, including the published `0.1.0-alpha.1`; only the older `0.1.0-alpha.0` defaults to guard) starts in `observe`. To test default behaviour pass `mode: undefined`. New headless harnesses that build their own runtime (like `review-fetch.test.ts` -> `headless()`) must pass `mode` explicitly or they observe only. - **Held store writes are opt-in.** Since batch 4 `policy.holdWrites` is off: an async `set()` applies at once and a model `discard` is a late revert (`interventions()[i].late`). A test that expects `a.get()` to stay unchanged until the model answers needs `policy: { holdWrites: true }`; otherwise assert on the `delivery` decision or the late revert. - **`sim`'s `build:runtime-core` leaves a partial `dist/`.** It writes only `dist/index.js` (+ chunks, maps; `--platform neutral`, no `.d.ts`, no adapters/devtools/worker) and does not clean (tsup CLI default), so whatever an earlier full build left stays. `demos/vite.config.ts` picks the real runtime whenever `dist/index.js` exists, so after this build on an empty `dist/` demos resolve `@genclass/runtime/react` etc. to files that do not exist (and the demos typecheck finds no `.d.ts`). Run the full `npm run build` before working on demos. - **vitest `exclude` replaces the defaults.** `vitest.config.ts` sets `exclude: ["test/browser/**"]` rather than extending vitest's default exclude list. Harmless while `include` is `test/**/*.test.ts`; use `[...configDefaults.exclude, "test/browser/**"]` if `include` is ever widened. @@ -473,11 +473,12 @@ The format is frozen at `situation-v2` and v2 training data is being generated f | 2026-10-07 20:09 -0400 | 59c213f | `version` `0.1.0` -> `0.1.0-alpha.0`, `packages/runtime/LICENSE` added, `test/smoke/smoke.sh`, `.gitignore` gains `.publish/` and `*.tgz` | | 2026-10-07 20:15 -0400 (00:15 UTC 10-08) | 654d822, tag `v0.1.0-alpha.0` | READMEs get npm and license badges and an "alpha" note; OPEN_TASKS moves publish to "Done" | | 2026-10-08 00:14 / 00:18 UTC | (npm) | `@genclass/runtime@0.0.0-stage` (about one minute before 654d822's commit time) then `0.1.0-alpha.0` (about three minutes after it) published (`npm view @genclass/runtime time`); dist-tag `latest` = `0.1.0-alpha.0`. OPEN_TASKS: "2026-10-08, `genclass` org, owner meharpro", smoke-tested first | -| 2026-10-07 21:16 -0400 (01:16 UTC 10-08) | ad24804, ce27efd | fix infinite recursion on `NaN` in state (`test/nan.test.ts`); OPEN_TASKS asks the user to publish `0.1.0-alpha.1` (needs 2FA). **Not published** (`npm view` 2026-10-08) | +| 2026-10-07 21:16 -0400 (01:16 UTC 10-08) | ad24804, ce27efd | fix infinite recursion on `NaN` in state (`test/nan.test.ts`); OPEN_TASKS asks the user to publish `0.1.0-alpha.1` (needs 2FA); published later, see below | | 2026-10-07 22:31 / 23:26 -0400 | fcd1e68, 6e5e86e (tag `situation-v2`) | runtime batch 4 (delivery trigger, no store holds by default) and batch 5 (separability facts); situation format v2 frozen | | 2026-10-08 00:15 -0400 | f3636b2, b435acb (`mvp-v2`, ours, not pushed) | default mode `observe`; CI workflow, committed root lockfile, CLI mode 100755 | +| 2026-10-08 ~05:33 UTC | 806a296, local tag `v0.1.0-alpha.1` (not pushed) | `@genclass/runtime@0.1.0-alpha.1` published by karanvir1729 under `latest` (26 files, 486.8 kB, shasum 9e3e82bc...); first attempt 403 (no 2FA on the account), then browser-based 2FA approval | -`package.json` `version` is still `0.1.0-alpha.0` on `mvp-v2` (no bump for alpha.1 yet). What `.publish/` was used for is not recorded (unverified). +`package.json` `version` is `0.1.0-alpha.1` on `mvp-v2`: release commit 806a296 is now the head of `mvp-v2` (fast-forwarded). What `.publish/` was used for is not recorded (unverified). ### Cut a release of `@genclass/runtime` @@ -488,10 +489,10 @@ There is no publish script, no `prepublishOnly` and no `publishConfig`. The reco 1. Locally: `npm ci`, `npm run typecheck -w @genclass/runtime`, `npm run build -w @genclass/runtime`, the unit tests and perf budgets as in CI (or a green CI run on the pushed branch). With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs and `bash test/smoke/smoke.sh`. 2. Bump `version` in `packages/runtime/package.json` (e.g. `0.1.0-alpha.1`), plus the version strings in READMEs, `OPEN_TASKS.md` and `HANDOFF.md`. Run `npm install` at the root so the lockfile's `packages/runtime` entry picks up the version, and commit both. 3. From `packages/runtime`: `npm run build && npm pack` -> `genclass-runtime-<version>.tgz`; check `npm pack --dry-run` lists only `dist/`, `bin/`, `README.md`, `LICENSE`, `package.json`. -4. Give the user the command to run (on a machine logged in to npm with publish rights on the `genclass` org, with their 2FA): `npm publish genclass-runtime-<version>.tgz --access public --tag <tag>`. **A prerelease needs `--tag`** on npm 11: `lib/commands/publish.js` in npm 11.8.0 throws "You must specify a tag using --tag when publishing a prerelease version." unless `--tag` (or `publishConfig.tag`, or `--force`) is given, so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. Use `--tag alpha` (or `next`) to leave `latest` on `0.1.0-alpha.0`, or `--tag latest` to move it (today `latest` = `0.1.0-alpha.0`; how alpha.0 got that tag, an older npm or an explicit `--tag latest`, is not recorded). A non-prerelease such as `0.1.0` needs no tag and becomes `latest`. Never run `npm publish` yourself without an explicit user go-ahead in chat. +4. Give the user the command to run (on a machine logged in to npm with publish rights on the `genclass` org, with their 2FA): `npm publish genclass-runtime-<version>.tgz --access public --tag <tag>`. **A prerelease needs `--tag`** on npm 11: `lib/commands/publish.js` in npm 11.8.0 throws "You must specify a tag using --tag when publishing a prerelease version." unless `--tag` (or `publishConfig.tag`, or `--force`) is given, so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. Use `--tag alpha` (or `next`) to leave `latest` where it is, or `--tag latest` to move it (today `latest` = `0.1.0-alpha.1`). A non-prerelease such as `0.1.0` needs no tag and becomes `latest`. Never run `npm publish` yourself without an explicit user go-ahead in chat. 5. After the publish: `git tag -a v<version> -m "@genclass/runtime <version> (npm)"` (push only with the user's OK); move the item to "Done" in `OPEN_TASKS.md`; check `npm view @genclass/runtime dist-tags`. -What a release built from `mvp-v2` would change for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model the runtime still only observes either way. +What `0.1.0-alpha.1` (built from `mvp-v2`) changed for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model the runtime still only observes either way. ### Publish the model package (planned; OPEN_TASKS.md item 9; HANDOFF.md "How to continue") @@ -546,7 +547,7 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder. | `test/fetch.test.ts` | CORE | node | 17 | fetch observer: plain traffic makes no model call, app body vs clone, coalesce (`x-genclass: coalesced`), block (503 `blocked`), guard never runs heal-tier, `serve_cached`, delay 250 ms first, retry backoff 200 ms, retry not offered for non-replayable bodies, network error delivered, failure/request gates fail open at 300 ms, hedge, abort, `TimeoutError` = failure, cache <= `MAX_ENTRIES` (64) and skips bodies > `MAX_BODY` (256 KB), destroy restores fetch | | `test/invariants.test.ts` | CORE | node | 6 | `InvariantMiner` learns len/sum/equality/unique relations, ignores unchanged fields and id-like keys; inconsistency once per episode + rollback + undo; unsettled transients ignored; `expect()` predicates | | `test/learn.test.ts` | CORE | node | 8 | `Baselines` (latency after 5 samples, EWMA 0.9 error rate, streaks, outcomes, rate vs usual, identity gaps); `Profiles` (write set < 1% of >= 20, value kind, status class); transition trigger + rollback | -| `test/nan.test.ts` | CORE (ad24804) | node | 1 | a store holding `NaN` builds situations without infinite recursion (the alpha.0 crash; fix awaiting the `0.1.0-alpha.1` publish) | +| `test/nan.test.ts` | CORE (ad24804) | node | 1 | a store holding `NaN` builds situations without infinite recursion (the alpha.0 crash; fixed in the published `0.1.0-alpha.1`) | | `test/no-reorder.test.ts` | CORE | node | 6 | "never worse": realworld's Redux promise-middleware pattern through `genclassEnhancer` with an always-passive model (`PassiveDecider`, 10 ms): observe baseline renders; guard and heal x triage salient and always give identical dispatches, order, pages and final state with 0 interventions; `holdWrites: true` never reorders a store's dispatches | | `test/plugins.test.ts` | CORE | node | 7 | plugin facts/diagnoses/custom actions, `ctx.builtin` (with `holdWrites: true`), plugin actions default to heal tier, `applicable()`, standing questions + `onAnswer`, `setup()`/cleanup API, vocabulary overrides | | `test/policy.test.ts` | CORE | node | 14 | `gate()` summed mass, mode tiers, thresholds 0.9 guard / 0.8 heal, passive top, `requireDiagnosis`, deny/allow, pause, rate limit with 60 s sliding window, observe never holds, `setMode`, `pause()/resume()`, loading fails open without a record, detection threshold | @@ -607,11 +608,11 @@ Doc-vs-code mismatches (code wins): - Ownership: `docs/runtime/CONTRACT.md` §1 (layout) still lists `src/adapters/` and `src/devtools/` as owner CORE, but §13 (Additions) reassigns them to UI, which matches `STATUS.md` counting their tests as UI's. §1 is stale; the Tests table follows §13 / STATUS. - `test/browser/model-helpers.ts` and `model.spec.ts` parity still target the v0.1 GenClass model; nothing in the browser specs exercises a situation-v2 runtime model (none exists). -Resolved since 654d822 (moved out): no CI and no committed lockfile (b435acb); the CLI's 100644 mode flip on install (b435acb); the npm dist-tag question (`latest` = `0.1.0-alpha.0` per `npm view`); `STATUS.md`'s stale "For UI" note about `MockRuntime.holdBudgetMs()/situationBudget()` and its redundant `--exclude "test/browser/**"` command (both gone from STATUS). +Resolved since 654d822 (moved out): no CI and no committed lockfile (b435acb); the CLI's 100644 mode flip on install (b435acb); the npm dist-tag question (`latest` was `0.1.0-alpha.0` per `npm view`; since 2026-10-08 it is `0.1.0-alpha.1`); `STATUS.md`'s stale "For UI" note about `MockRuntime.holdBudgetMs()/situationBudget()` and its redundant `--exclude "test/browser/**"` command (both gone from STATUS). Open items in scope (from `OPEN_TASKS.md`, `HANDOFF.md`, `training/NEEDS.md`, STATUS): -- **`0.1.0-alpha.1`** (NaN fix, `nan.test.ts`): needs the user's 2FA (`OPEN_TASKS.md` "Needs the user"). Decide with the user whether it is cut from `origin/runtime` (default guard, situation-v2) or from `mvp-v2` (default observe), and which dist-tag it gets (npm 11 requires `--tag` for a prerelease); the version in `package.json` is not bumped yet. +- **`0.1.0-alpha.1`**: published 2026-10-08 from `mvp-v2` (806a296) under `latest`. 806a296 is now the head of `mvp-v2`. Still open: push `mvp-v2` and tag `v0.1.0-alpha.1` to origin (needs an account with write access). - **Push and first CI run**: `mvp-v2` (with `.github/workflows/ci.yml`) is local only; pushing needs the user's OK. Until then CI has never run on GitHub (the `review-perf` retry and the `ONNXRUNTIME_NODE_INSTALL=skip` setting are verified only locally). - **Model package**: blocked on v2 training (SIM v2 data on c02–c09 and c12–c23, REAL on c01, c10, c11, per `training/NEEDS.md`; then teacher, distillation, DAgger, EVAL). Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. - Docs (item 13): dev-only lazy import of the devtools (52 KB min / 17 KB gz). diff --git a/docs/agents/runtime/decide-policy-actions.md b/docs/agents/runtime/decide-policy-actions.md index 319c7305..fc0d6eb7 100644 --- a/docs/agents/runtime/decide-policy-actions.md +++ b/docs/agents/runtime/decide-policy-actions.md @@ -802,8 +802,8 @@ Doc-vs-code mismatches (code is authoritative): Open items (from `HANDOFF.md`, `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `docs/runtime/RESULTS.md`): -- No situation-v2 model exists yet; until `@genclass/runtime-model@0.1.0` ships, the published alpha - (`@genclass/runtime` 0.1.0-alpha.0, default guard, no model) takes no actions, and R17-final1 (situation-v1) does +- No situation-v2 model exists yet; until `@genclass/runtime-model@0.1.0` ships, the published alphas + (`@genclass/runtime` 0.1.0-alpha.1 = `latest`, default observe; the older 0.1.0-alpha.0, default guard; neither has a model) take no actions, and R17-final1 (situation-v1) does not match this runtime. SIM is generating v2 data on Azure (`training/NEEDS.md`). - Hold-induced harm ([RESULTS.md](../../runtime/RESULTS.md) §5; rerun is OPEN_TASKS item 10) was measured with v0.1 on held store writes; v2 holds only deliveries, and the never-worse sweep over 66 real apps changed 0/396 clean runs ([../realapps.md](../realapps.md), diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md index 2abfda4b..708d8bd2 100644 --- a/docs/agents/runtime/model-host.md +++ b/docs/agents/runtime/model-host.md @@ -637,7 +637,7 @@ Mismatches between docs and code (code wins): - Its diagnosis list omits `transient`, and its action list omits the v2 `delivery` trigger (`deliver` / `discard` / `defer`). - Its latency paragraph maps token counts to state budgets of 1,000 / 2,000 / 3,200 chars; the v2 full budget is 2,400 (`STATE_CHAR_BUDGET`). Its figures (R17 ≈ 190 / 340 / 610 ms, R32 ≈ 500 / 880 / 1,540 ms, "fitted over 184 requests") also differ from `docs/runtime/RESULTS.md` §2 (R17 177 / 323 / 589, R32 569 / 954 / 1,580). - It describes `calibration.json` as "per-kind temperatures", while the runtime also supports `by_header`, `by_bucket`, `tau_k` and `noul_platt`. -- HANDOFF.md "What this is" still says "observe -> guard (default; ...)". Since f3636b2 on this branch the default is `observe` (CONTRACT §13, `runtime.ts`). The published npm alpha.0 still defaults to `guard`. +- HANDOFF.md "What this is" still says "observe -> guard (default; ...)". Since f3636b2 on this branch the default is `observe` (CONTRACT §13, `runtime.ts`). The older published npm alpha.0 defaults to `guard`; alpha.1 (`latest`) defaults to `observe`. - CONTRACT §10 refers to `/Users/meharkhanna/jev/extension/genclass/src/` (another machine). In this repo the v0.1 card is `extension/src/model/model.json`. - CONTRACT §2 comments `device` as "default auto (webgpu+fp16 if shader-f16, else wasm+q8)". `planOrder` also tries `webgpu+q8` between them, and `"auto"` skips software (fallback) adapters. - CONTRACT §2 says `preload: "lazy"` downloads "only when the first salient situation appears", and §10 says "on the first `evaluate`/`ready`". The host starts on the first `ready()`/`load()`/`evaluate()`/`measure()`; through the runtime that is the first salient trigger, `rt.ask`/`rt.decide`, or any read of `rt.ready`. @@ -657,7 +657,7 @@ Open items and TODOs relevant to this scope: - A hung forward pass blocks the host forever: there is no post-load watchdog. - Device-based model selection and publishing `@genclass/runtime-model@0.1.0` plus a GitHub release (OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` (+ device-based selection); procedure in [RELEASE.md](../../../RELEASE.md)) are open. Final round 1 results are now in training/EVAL.md and docs/runtime/RESULTS.md (R17 chosen as the default on every device, which makes device-based selection less pressing), but they are `situation-v1` baselines. - The v2 model itself ([HANDOFF](../../../HANDOFF.md) "How to continue" step 3): v2 data (SIM about 10M gold + 50M unlabeled on 20 Azure nodes, REAL about 495k (HANDOFF; training/NEEDS target ≥ 500k) real-browser gold rows; locations in training/NEEDS.md item 16 and its node-claims table) -> 150M teacher -> teacher labels -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. When it lands: update `DEFAULT_FROM`, MODEL_CARD, and check `meta.json` `max_len` 2048 and the calibration headers (including the new `delivery` action header). -- OPEN_TASKS "Needs the user": a `0.1.0-alpha.1` patch (crash on `NaN` in app state, fixed in `packages/runtime/src/util.ts` by ad24804, test `test/nan.test.ts`) needs the owner's 2FA. The model host was never affected (`toJsonValue` maps NaN to `null`). +- The crash on `NaN` in app state (fixed in `packages/runtime/src/util.ts` by ad24804, test `test/nan.test.ts`) shipped in `0.1.0-alpha.1`, published 2026-10-08 under `latest` (release commit 806a296). The model host was never affected (`toJsonValue` maps NaN to `null`). - demos/NEEDS.md §2: one-at-a-time decisions queued up during typing bursts (median 826 ms, measured on v1). Batch 4/5 addressed the runtime side (no store-write holds, `expectedLatency` gate, `stale()` drop in `DeciderQueue`); the host is still one inference at a time. Not re-measured with a model on v2. - Measured performance (not re-verified here): - [docs/runtime/RESULTS.md](../../runtime/RESULTS.md) §2 (onnxruntime-web 1.30 WASM, 1 thread, q8): R17 177 / 323 / 589 ms and R32 569 / 954 / 1,580 ms at 500 / 780 / 1,170 sequence tokens; GenClass 0.1 about 900 ms at 780. A 2,400-char v2 situation is about 1,000 tokens (2.4 chars per token, training/NEEDS.md 6a). diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md index eec3c025..fbcecf68 100644 --- a/docs/agents/runtime/public-api-and-lifecycle.md +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -57,7 +57,7 @@ Terms introduced in this doc: ### Package exports (`packages/runtime/package.json`) -ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.0` (unchanged between 654d822 and b435acb; the published alpha.0 predates situation-v2, the NaN fix and the observe default), license Apache-2.0. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). +ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.1` on `mvp-v2` (bumped in release commit 806a296, now the head of `mvp-v2`, and published as `latest` on 2026-10-08; it was `0.1.0-alpha.0` from 654d822 through b435acb, and the published alpha.0 predates situation-v2, the NaN fix and the observe default), license Apache-2.0. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). | subpath | types | import | source entry (tsup) | documented in | |---|---|---|---|---| @@ -76,7 +76,7 @@ ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, - `devDependencies`: `@playwright/test 1.63.0`, `@types/react ^19.0.0`, `@types/react-dom ^19.0.0`, `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `react ^19.3.0`, `react-dom ^19.3.0`, `redux ^5.0.1`, `tsup ^8.5.1`, `typescript ~5.9.3`, `vitest ^5.0.3`, `zustand ^5.0.15`. - `files`: `dist`, `bin`, `README.md`, `LICENSE`. Scripts: `build` (tsup), `typecheck` (`tsc -p tsconfig.json --noEmit`), `test` (`vitest run`), `test:browser` (`playwright test --config test/browser/playwright.config.ts`). - `tsup.config.ts`: ESM only, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`. `worker` has no `.d.ts` (not in `dts.entry`). -- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the current freeze) and `v0.1.0-alpha.0` (= 654d822, the published alpha; same `src` as `situation-v1`). +- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the current freeze), `v0.1.0-alpha.0` (= 654d822, the first published alpha; same `src` as `situation-v1`) and `v0.1.0-alpha.1` (= 806a296, the current npm `latest`; local only, not pushed). ### Root module exports @@ -667,7 +667,7 @@ Untested in this scope: the `localStorage.genclass` path of the kill switch, the | API.md observers | "The DOM, fetch, XHR, WebSocket and timers are observed automatically" (packages/runtime/README.md now lists them all) | Also `eventsource` (batch 4), `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | | Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | | Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and the CLI's `DEFAULT_FROM` at the GitHub release `runtime-model-v0.1.0`; both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 9 | -| npm `0.1.0-alpha.0` vs this branch | npm "latest" | The published alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. OPEN_TASKS.md "Needs the user" lists a `0.1.0-alpha.1` patch for the NaN fix that needs the owner's 2FA; the release procedure is [RELEASE.md](../../../RELEASE.md). | `npm view @genclass/runtime` (per the lead, 2026-10-08); `nan.test.ts` | +| npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from this branch (806a296), is `latest` since 2026-10-08; procedure in [RELEASE.md](../../../RELEASE.md). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | | Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | | `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a<n>` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | | Init with malformed `plugins` | `GenClass.init` "never throws" | It does not throw, but a non-iterable `plugins` / `plugin.actions` / `plugin.questions` throws inside `RuntimeImpl`'s constructor after the observers were installed; the fallback inert runtime is returned while the first instance's wrappers stay on the globals | `runtime.ts` -> constructor, `use`; `index.ts` -> `GenClass.init` | diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index cb44efbd..93a3c698 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -19,15 +19,17 @@ paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.t `model/host.ts`, …) are relative to `packages/runtime/src/`. Every other path is from the repo root. - **Branches.** `mvp-v2` (this doc) = `origin/runtime` 74f17c0 (the colleague Mehar's latest: runtime batches 4 and - 5, situation-v2, `realapps/`, v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus three local + 5, situation-v2, `realapps/`, v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus six local commits: 7dab2b3 (AGENTS.md, CLAUDE.md, `docs/agents/**`), f3636b2 (default mode `observe`), b435acb (CI workflow, - committed root `package-lock.json`, `bin/genclass-runtime.mjs` as 100755). `mvp-v2` is **not pushed** - (`git branch -vv`: "ahead 3" of `origin/runtime`). The local branch `mvp` (b15415b, based on 654d822 = + committed root `package-lock.json`, `bin/genclass-runtime.mjs` as 100755), then b561244 and 6ac4737 (docs) and + 806a296 (release commit for `0.1.0-alpha.1`, the head). `mvp-v2` is **not pushed** + (`git rev-list --count origin/runtime..mvp-v2` = 6). The local branch `mvp` (b15415b, based on 654d822 = situation-v1) is superseded. `main` and `origin/main` are still 654d822. -- **Shipped on npm:** `@genclass/runtime@0.1.0-alpha.0` (`latest`, git tag `v0.1.0-alpha.0` = 654d822). It predates +- **Shipped on npm:** `@genclass/runtime@0.1.0-alpha.1` (`latest`, 2026-10-08, release commit 806a296, local tag + `v0.1.0-alpha.1` not pushed): NaN fix, situation-v2, default `observe`, no model. Before it, + `@genclass/runtime@0.1.0-alpha.0` (git tag `v0.1.0-alpha.0` = 654d822). That one predates situation-v2, defaults to `guard`, has no model, and predates the NaN fix (ad24804: `util.ts` -> `describe` - recursed forever on a `NaN` store value). A `0.1.0-alpha.1` patch waits on the owner's 2FA (`OPEN_TASKS.md` - "Needs the user"). `@genclass/runtime-model` is **not published** (404). + recursed forever on a `NaN` store value). `@genclass/runtime-model` is **not published** (404). - **Runtime on `mvp-v2`:** situation-v2, decisions at the network boundary (`delivery` trigger, `RuntimeImpl.runDelivery`), no store-write holds by default (`policy.holdWrites` false), default mode `observe` (`runtime.ts` -> `o.mode ?? "observe"`). Verified when these docs were written, on 2026-10-08 (macOS, Node v25.6.0): `tsc` clean, @@ -174,16 +176,17 @@ imports from `sim/src`, which is allowed). ### Version markers -| marker | value at b435acb | meaning | +| marker | value (2026-10-08, `mvp-v2` at 806a296) | meaning | |---|---|---| -| `mvp-v2` | b435acb, not pushed | this branch | +| `mvp-v2` | 806a296 (release commit for `0.1.0-alpha.1`, fast-forwarded), not pushed | this branch | | `origin/runtime`, local `runtime` | 74f17c0 | Mehar's line; HANDOFF says "push to `origin runtime` as you go" | | `main`, `origin/main` | 654d822 | not updated since the alpha | | `mvp` (local) | b15415b on 654d822 | superseded | | tag `situation-v1` | → 1a77558 | v1 format; superseded | | tag `situation-v2` | annotated tag object 75df720 → commit 6e5e86e | **current frozen training format** | -| tag `v0.1.0-alpha.0` | → 654d822 | the published alpha | -| `packages/runtime/package.json` `version` | `0.1.0-alpha.0` | not bumped | +| tag `v0.1.0-alpha.0` | → 654d822 | the first published alpha | +| tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1; local only, not pushed | +| `packages/runtime/package.json` `version` | `0.1.0-alpha.1` on `mvp-v2` | bumped in release commit 806a296 (now the head of `mvp-v2`) | | `@genclass/runtime-model@0.1.0` | not published (404); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | | GitHub release `runtime-model-v0.1.0` | no such tag in the repo; the CLI's default `--from` 404s (per the lead) | | | v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** a runtime model; used by demos and model tests | @@ -194,11 +197,11 @@ imports from `sim/src`, which is allowed). | item | state | owner | evidence | |---|---|---|---| | Runtime batches 4 and 5 (situation-v2) | done, frozen | CORE | fcd1e68, 6e5e86e; STATUS; `test/delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts` | -| Default mode `observe` | done on `mvp-v2` only (not on `origin/runtime`, not on npm) | us (f3636b2) | `runtime.ts` -> `RuntimeImpl` constructor; `test/default-mode.test.ts`; CONTRACT §13 | +| Default mode `observe` | done on `mvp-v2` and in npm `0.1.0-alpha.1` (not on `origin/runtime`, not in `0.1.0-alpha.0`) | us (f3636b2) | `runtime.ts` -> `RuntimeImpl` constructor; `test/default-mode.test.ts`; CONTRACT §13 | | CI | workflow committed; never run on GitHub | us (b435acb) | `.github/workflows/ci.yml` | -| NaN fix | in code since ad24804; **not on npm** | CORE | `util.ts` -> `describe`; `test/nan.test.ts`; `sim/NEEDS.md` g still says OPEN | +| NaN fix | in code since ad24804; on npm since `0.1.0-alpha.1` | CORE | `util.ts` -> `describe`; `test/nan.test.ts`; `sim/NEEDS.md` g still says OPEN | | npm `0.1.0-alpha.0` | published (guard default, no model, v1) | lead | tag `v0.1.0-alpha.0` | -| npm `0.1.0-alpha.1` (NaN fix) | waiting on the owner's 2FA | user | OPEN_TASKS "Needs the user" | +| npm `0.1.0-alpha.1` (NaN fix, situation-v2, observe default) | published 2026-10-08, `latest` | karanvir1729 | OPEN_TASKS "Done" | | SIM v1 phase A / B | done (600,676 / 1,415,344 rows); superseded | SIM | training/NEEDS "SIM → TRAIN: scaled data" | | Final round 1 (situation-v1) | done: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE 0.009; guard recall on clear stale/duplicate 7.7% | TRAIN | `training/EVAL.md`, RESULTS §1 | | T1 runs and v1 teacher `t150-g1` | stopped at the v2 freeze, no results | TRAIN | `training/LOG.md` 01:13–03:35 | @@ -355,7 +358,7 @@ model only for salient situations, in a worker. (3) Observability: one console l - **Code wins over every doc.** CONTRACT.md does not describe batch 4/5 (no `delivery` trigger); the deltas live in STATUS "Contract deltas". HANDOFF still says guard is the default. -- **Two defaults in the wild.** `mvp-v2` defaults to `observe`; `origin/runtime` and npm alpha.0 default to `guard`. +- **Two defaults in the wild.** `mvp-v2` and npm alpha.1 (`latest`) default to `observe`; `origin/runtime` and npm alpha.0 default to `guard`. The tests' `setup()` defaults to `guard` on purpose. - **"Observe never changes execution" is not quite true yet**: a salient delivery can wait up to 100 ms for its body and XHR completion listeners run outside the original dispatch (finding DL-3). @@ -446,7 +449,7 @@ tests at all. | REAL (Mehar) | v2 production `v2b1`–`v2b3` (≥ 500k gold), copy to `train:/data/real-out/` with the eval set | running; see RA-* before using the data | | TRAIN | import v2 SIM/REAL data (`import_final.sh` cannot read the v2 gz-shard layout, ST-8), T150 teacher on gold (PLAN P1), teacher eval as the separation gate (P2), soft-label unlabeled rows (P3), distil R17/R32 (P4), DAgger ×3 (P5), EVAL per trigger/budget/held-out set, calibration, export, parity | not started; several scripts untested (ST-2 to ST-7) | | lead / user | `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`; rerun demos; `@genclass/runtime@0.1.0` without the alpha tag | after EVAL | -| user | publish `0.1.0-alpha.1` (2FA; npm 11 needs `--tag` for a prerelease per build-test-release.md). Decide which tree it is cut from: the NaN fix alone, or `mvp-v2` with situation-v2 and the observe default | waiting | +| user | publish `0.1.0-alpha.1` (cut from `mvp-v2`, 806a296) | done 2026-10-08 (`latest`) | | user | push `mvp-v2` (first CI run), merge into `runtime`/`main`; public demo hosting | waiting | | Mehar / user | re-enable the Azure auto-shutdown schedules when the push ends; deallocate idle nodes | open | | CORE | review findings DL-1…DL-12 (behaviour) and SIT-1, SIT-3, SIT-8, SIT-10, SIT-11 (model-visible text) | open; see [How to change it safely](#how-to-change-it-safely) | @@ -462,7 +465,7 @@ tests at all. ### Decisions waiting on the user / repo owner -1. `0.1.0-alpha.1`: publish (2FA) and from which tree. +1. ~~`0.1.0-alpha.1`: publish (2FA) and from which tree.~~ Done 2026-10-08 from `mvp-v2` (806a296), dist-tag `latest`. 2. Push `mvp-v2`, merge into `runtime` and `main` (`main` is still 654d822; the old "looks merged" note no longer holds). 3. Public demo hosting (GitHub Pages). 4. Which review fixes land before vs after the running v2 generation (SIT-2, ST-1 and DL-2 affect data being produced From 10e5c3b239d2d6405bf325d78432975215aa61f3 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 02:09:36 -0400 Subject: [PATCH 08/25] chore: sync lockfile after merging origin/runtime Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- package-lock.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/package-lock.json b/package-lock.json index 408774aa..287d8976 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1781,6 +1781,10 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/genclass-runtime": { + "resolved": "packages/genclass-runtime", + "link": true + }, "node_modules/global-agent": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-4.1.3.tgz", @@ -3138,6 +3142,19 @@ } } }, + "packages/genclass-runtime": { + "version": "0.1.0-alpha.1", + "license": "Apache-2.0", + "dependencies": { + "@genclass/runtime": "0.1.0-alpha.1" + }, + "bin": { + "genclass-runtime": "cli.mjs" + }, + "engines": { + "node": ">=20" + } + }, "packages/runtime": { "name": "@genclass/runtime", "version": "0.1.0-alpha.1", From 054da3808b8ac001104e9a177793ee06c136c494 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 02:47:38 -0400 Subject: [PATCH 09/25] runtime: observe mode never holds or delays deliveries; background delivery decisions are recorded In observe mode a response delivery (fetch, XHR, postMessage/observe paths) is now passed to the app immediately, never held behind the delivery gate or a pending model call. The delivery decision is still computed in the background and recorded in decisions() (executed: false, reason "observe mode"), with a detect event, so observe telemetry covers deliveries as well as mutations and requests. Tests: test/observe-delivery.test.ts (new); default-mode and policy tests now expect the delivery decision alongside mutation and request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/runtime/src/observe/messages.ts | 11 +- packages/runtime/src/observe/xhr.ts | 5 +- packages/runtime/src/runtime.ts | 204 ++++++-- packages/runtime/test/default-mode.test.ts | 10 +- .../runtime/test/observe-delivery.test.ts | 452 ++++++++++++++++++ packages/runtime/test/policy.test.ts | 11 +- 6 files changed, 652 insertions(+), 41 deletions(-) create mode 100644 packages/runtime/test/observe-delivery.test.ts diff --git a/packages/runtime/src/observe/messages.ts b/packages/runtime/src/observe/messages.ts index 6fc729f7..09cd1f05 100644 --- a/packages/runtime/src/observe/messages.ts +++ b/packages/runtime/src/observe/messages.ts @@ -18,8 +18,14 @@ export interface MsgHost { startOp(name: string, o: Omit<StartOpts, "startSeq" | "t">): OpRec; endOp(op: OpRec, status: OpStatus, o?: EndOpts): void; event(name: string, data: Record<string, unknown>, op?: OpRec): void; - /** The delivery gate (runtime): `release` delivers the message, synchronously when nothing is salient. */ - deliverMessage(o: { op: OpRec; channel: "websocket" | "eventsource"; message: { path: string; summary: string }; queuedAhead: number; body?: () => Promise<unknown> }, release: () => void): void; + /** + * The delivery gate (runtime): `release` delivers the message, synchronously when nothing is salient or nothing + * can be held. `bodyNow` is the parsed message itself (in memory), for an analysis before the app's listeners run. + */ + deliverMessage( + o: { op: OpRec; channel: "websocket" | "eventsource"; message: { path: string; summary: string }; queuedAhead: number; body?: () => Promise<unknown>; bodyNow?: () => unknown }, + release: () => void, + ): void; /** A live channel went down (closed or errored after it was open) or came up (opened). */ channel?(state: "down" | "up", channel: "websocket" | "eventsource", path: string, code?: number | string): void; } @@ -141,6 +147,7 @@ export class MessageGate { message: { path: this.path, summary: item.summary }, queuedAhead: first ? 0 : this.queue.indexOf(item), body: () => Promise.resolve(parseJsonBody((item.ev as MessageEvent).data as string)), + bodyNow: () => parseJsonBody((item.ev as MessageEvent).data as string), }, () => { if (sync) { diff --git a/packages/runtime/src/observe/xhr.ts b/packages/runtime/src/observe/xhr.ts index 80e51e14..23c755ce 100644 --- a/packages/runtime/src/observe/xhr.ts +++ b/packages/runtime/src/observe/xhr.ts @@ -169,7 +169,10 @@ export function installXHR(host: NetHost): (() => void) | null { host.endOp(op, "ok", { code: status }); host.ctx.stick(op); if (!host.gated(op)) return; - const body = () => Promise.resolve(xhrJson(xhr)); + // the response is in memory: `body.now` reads it synchronously (when the delivery cannot be held, the gate + // releases it at once and analyzes it before the app's listeners run, for detection only) + const json = () => xhrJson(xhr); + const body = Object.assign(() => Promise.resolve(json()), { now: json }); if (st.req.method !== "GET" && st.req.method !== "HEAD" && status < 300) host.noteResponse?.({ op, req: st.req, status, body }); st.dlv = "held"; let sync = true; diff --git a/packages/runtime/src/runtime.ts b/packages/runtime/src/runtime.ts index 74507a88..5d4b10b4 100644 --- a/packages/runtime/src/runtime.ts +++ b/packages/runtime/src/runtime.ts @@ -59,7 +59,7 @@ import type { ChainWriteInfo, CreateRec, DeliverySpec, ErrorInfo, OutcomeRec, Re 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 } from "./situation/questions.js"; +import { BUILTIN_ACTIONS, diagnosisVocabulary, PASSIVE, TRIGGER_ACTIONS } from "./situation/questions.js"; import { STATE_CHAR_BUDGET, stateText } from "./situation/serialize.js"; import { DeciderQueue } from "./decide/decider.js"; import { gate, holdBudget, permittedActions, policyConfig, RateLimiter, restriction, type PolicyConfig } from "./decide/policy.js"; @@ -188,6 +188,10 @@ export class RuntimeImpl implements Runtime { 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>(); constructor(o: CreateOptions & { decider?: DecisionProvider | null; ownsDecider?: boolean } = {}) { this.clock = o.clock ?? browserClock; @@ -231,6 +235,7 @@ export class RuntimeImpl implements Runtime { applied: (m, s, changes, writer) => this.onApplied(m, s, changes, writer), discarded: () => this.scheduleSettle(), proposed: (m) => { + if (this.deliveryAnalysis.size) this.finalizeDeliveries(m.cause); try { const h: { id: number; store: string; paths: string[]; cause?: number; changes: ReturnType<typeof toChanges> } = { id: m.id, @@ -323,7 +328,11 @@ export class RuntimeImpl implements Runtime { watchStall: (op, req, ctl) => this.watchStall(op, req, ctl), failureStreak: (sig) => this.base.stats(sig)?.failStreak ?? 0, uniqueId: () => `uniq:${++this.uniq}`, - deliver: (o, release) => this.runDelivery({ op: o.op, channel: "response", req: o.req, status: o.status, ...(o.body ? { body: o.body } : {}) }, release), + deliver: (o, release) => { + // an observer whose body is already in memory (XHR) exposes it synchronously as `body.now` + const now = (o.body as { now?: () => unknown } | undefined)?.now; + this.runDelivery({ op: o.op, channel: "response", req: o.req, status: o.status, ...(o.body ? { body: o.body } : {}), ...(typeof now === "function" ? { bodyNow: now } : {}) }, release); + }, noteResponse: (o) => this.noteResponse(o), setIdentity: (op, req, identity) => { if (op.identity === identity) return; @@ -352,8 +361,10 @@ export class RuntimeImpl implements Runtime { startOp: (name: string, o: Omit<StartOpts, "startSeq" | "t">) => this.startOp("ws", name, o), endOp: (op: OpRec, status: OpStatus, eo?: EndOpts) => this.endOp(op, status, eo), event: (name: string, data: Record<string, unknown>, op?: OpRec) => this.events.push(this.clock.now(), "custom", name, { ...(op ? { op: op.id } : {}), data }), - deliverMessage: (o: { op: OpRec; channel: "websocket" | "eventsource"; message: { path: string; summary: string }; queuedAhead: number; body?: () => Promise<unknown> }, release: () => void) => - this.runDelivery(o, release), + deliverMessage: ( + o: { op: OpRec; channel: "websocket" | "eventsource"; message: { path: string; summary: string }; queuedAhead: number; body?: () => Promise<unknown>; bodyNow?: () => unknown }, + release: () => void, + ) => this.runDelivery(o, release), channel: (state: "down" | "up", channel: "websocket" | "eventsource", path: string, code?: number | string) => this.onChannel(state, channel, path, code), }; } @@ -526,6 +537,16 @@ export class RuntimeImpl implements Runtime { // Never hold when nothing could be done, or when the model is not expected to answer within the hold budget // (decide in the background instead: detection, late revert) const waits = opts.hold && permitted.length > 0 && !this.paused && this.expectedLatency() <= this.holdBudgetMs(); + // A delivery that does not wait while its chain's writes can still be discarded or late-reverted by their own + // decisions (guard, heal: it was not held only because the model would not answer in time): those writes are + // decided on their own, as before, and the delivery itself only when a question forces it (covering nothing). + const writesAct = !waits && spec.trigger === "delivery" && this.writesCanAct(); + if (writesAct && !built.forced && this.triage !== "always") return passive(); + // Otherwise (observe, no permitted action) it is decided in the background: while that decision is pending, its + // chain's predicted writes are covered by it (no second, mutation decision about the same writes). Registered + // before the passive action, which may run the app's listeners (and their writes) synchronously. + const background = !waits && spec.trigger === "delivery" && !writesAct ? spec.op : null; + if (background) this.deliveryPending.add(background); if (!waits) passive(); let expired = false; let budgetTimer: unknown = null; @@ -541,20 +562,30 @@ export class RuntimeImpl implements Runtime { // shortly after it applied); background decisions within a few seconds const lateOk = waits && !!ctl.revert; const deadline = waits ? t0 + budget + (lateOk ? LATE_REVERT_MS : 0) : t0 + BACKGROUND_DEADLINE_MS; + // A delivery's controller is stale once the delivery was released: that only makes a queued decision useless + // when the delivery waits for it. A delivery released without waiting is still decided (detection, reports, + // standing questions); the decision cannot act any more (see onDecision). + const stale = ctl.stale && (waits || spec.trigger !== "delivery") ? () => !!ctl.stale!() : undefined; this.queue .submit( { trigger: spec.trigger, state: built.situation.state, questions: built.situation.questions, priority: waits ? opts.priority : Math.min(opts.priority, 1), subject: built.subjectRef }, deadline, - ctl.stale ? () => !!ctl.stale!() : undefined, + stale, ) .then((res) => { if (budgetTimer !== null) this.clock.clearTimeout(budgetTimer); - if (this.destroyed) return passive(); - if (!res) return passive(); - this.onDecision(built, res.answers, this.clock.now() - t0, ctl, passive, { waits, expired, passiveRan: () => passiveRan, hold: opts.hold }); + try { + if (this.destroyed) return passive(); + if (!res) return passive(); + this.onDecision(built, res.answers, this.clock.now() - t0, ctl, passive, { waits, covers: background !== null, expired, passiveRan: () => passiveRan, hold: opts.hold }); + } finally { + // decided (onDecision marked the delivery decided) or dropped (its later writes are decided on their own) + if (background) this.deliveryPending.delete(background); + } }) .catch((e) => { this.log("decision failed", e); + if (background) this.deliveryPending.delete(background); passive(); }); } @@ -565,7 +596,7 @@ export class RuntimeImpl implements Runtime { latencyMs: number, ctl: Controller, passive: () => void, - st: { waits: boolean; expired: boolean; passiveRan: () => boolean; hold: boolean }, + st: { waits: boolean; covers: boolean; expired: boolean; passiveRan: () => boolean; hold: boolean }, ): void { const trigger = built.spec.trigger; const passiveName = PASSIVE[trigger]; @@ -584,12 +615,16 @@ export class RuntimeImpl implements Runtime { let late = false; // the subject already went its way (write applied, response delivered, request sent): an action now is late const proceeded = ctl.proceeded ? ctl.proceeded() : st.hold && (st.expired || st.passiveRan()); - if (trigger === "delivery" && !proceeded) { + // a delivery decided while held, or decided in the background when it covers its chain's writes (see trigger): + // its chain's predicted writes are covered by this decision (a held delivery released at its budget is not: its + // writes are decided on their own) + if (trigger === "delivery" && (!proceeded || st.covers)) { const op = (built.spec as DeliverySpec).op; if (op.delivery) op.delivery.decided = true; } const custom = run ? built.actions.find((a) => a.name === run)?.custom : undefined; - if (run && proceeded && !custom) { + // a delivery that was already released can only take the passive action (custom actions included) + if (run && proceeded && (!custom || trigger === "delivery")) { if (run === "discard" && ctl.revert && ctl.revertable) { // late revert: the write already applied; revert exactly that write when nothing depends on it const why = ctl.revertable(); @@ -856,7 +891,10 @@ export class RuntimeImpl implements Runtime { this.trigger({ trigger: "mutation", m }, this.mutationController(m, null), { hold: false, priority: 1 }); } - /** The write's causal chain went through the delivery gate, which predicted these fields and decided in time. */ + /** + * The write's causal chain went through the delivery gate, which predicted these fields and decided in time (or + * is deciding in the background: the delivery did not wait for its decision). + */ private covered(m: MutationRec): boolean { if (this.triage === "always") return false; // every trigger is asked let op: OpRec | undefined = m.cause ?? undefined; @@ -865,7 +903,7 @@ export class RuntimeImpl implements Runtime { if (d) { if (!d.known) return false; const all = m.changes.every((c) => d.patterns.has(c.path) || d.patterns.has(normalizeFieldPath(c.path))); - return all && (!d.salient || d.decided); + return all && (!d.salient || d.decided || this.deliveryPending.has(op)); } op = this.ops.get(op.cause); } @@ -896,9 +934,27 @@ export class RuntimeImpl implements Runtime { * signature writes has newer data or a pending local change; then the delivery waits for the model (only extra * latency). discard: deliver, but drop the writes X's chain makes over newer data; defer: wait for the related * in-flight operations, then decide again (twice at most). + * + * When no hold is possible (observe mode, no permitted action, the model not ready or not expected to answer within + * the hold budget), the delivery is released synchronously, before any body read: the app gets it exactly as + * without GenClass. The content analysis and the decision follow in the background (detection, reports, standing + * questions), still on the state the delivery was released into: a body already in memory (`bodyNow`: XHR, + * WebSocket, EventSource) is analyzed right away, before the app's listeners run; a body still being read (fetch) + * is not waited for past the first write of the delivery's chain (decided without it then). In guard or heal mode + * (the model too slow to hold for), the chain's writes keep their own decisions (late revert) instead: see trigger(). */ runDelivery( - o: { op: OpRec; channel: "response" | "websocket" | "eventsource"; req?: ReqMeta; status?: number; message?: { path: string; summary: string }; queuedAhead?: number; body?: () => Promise<unknown> }, + o: { + op: OpRec; + channel: "response" | "websocket" | "eventsource"; + req?: ReqMeta; + status?: number; + message?: { path: string; summary: string }; + queuedAhead?: number; + body?: () => Promise<unknown>; + /** The same body, synchronously, when it is already in memory. */ + bodyNow?: () => unknown; + }, release: () => void, defers = 0, ): void { @@ -925,14 +981,18 @@ export class RuntimeImpl implements Runtime { if (o.status !== undefined) spec.status = o.status; if (o.message) spec.message = o.message; const what = o.channel === "response" ? `the response to ${opLabel(op)}` : `message ${opLabel(op)}`; + /** + * Delivered over newer data (or a pending local change) without a decision to drop it: its chain's writes to + * those fields are marked as possibly stale (F9). + */ + const markOverNewer = () => { + if (!conflicts.length || !op.delivery?.salient) return; + const c0 = conflicts[0]; + op.delivery.overNewer = { paths: new Set(conflicts.map((c) => c.path)), by: c0.writer ? opLabel(c0.writer) : "a newer operation", kind: c0.kind }; + }; const ctl: Controller = { passive: () => { - // delivered over newer data (or a pending local change) without a decision to drop it: its chain's writes - // to those fields are marked as possibly stale (F9) - if (!released && conflicts.length && op.delivery?.salient) { - const c0 = conflicts[0]; - op.delivery.overNewer = { paths: new Set(conflicts.map((c) => c.path)), by: c0.writer ? opLabel(c0.writer) : "a newer operation", kind: c0.kind }; - } + if (!released) markOverNewer(); rel(); }, proceeded: () => released, @@ -970,31 +1030,33 @@ export class RuntimeImpl implements Runtime { throw new Error(`unsupported action ${action}`); }, }; - const go = () => { - if (!released) this.trigger(spec, ctl, { hold: true, priority: 2 }); - }; // text fields the user typed into after this op started: salient only if the body would replace that text (F2) const typed = matched.filter((p) => typeof this.hub.valueAt(p) === "string" && this.hub.writesSince(p, op.startSeq).some((h) => h.user && !this.inChainOf(op, h.writer))); const always = this.triage === "always" || this.standing.some((q) => q.always && q.on.includes("delivery")); + if (!conflicts.length && !typed.length && !always) return rel(); + // No hold is possible: deliver now, before any body read; analyze and decide in the background (see above) + const background = !this.deliveryHoldable(op, matched, defers); + if (background) rel(); /** Decide without (more) content: newer applied data is salient; pending changes and typed text need the body. */ const settle = (salient: boolean) => { if (op.delivery) op.delivery.salient = salient; + if (background) { + // already delivered: the passive action, then the decision for detection only (it cannot act) + markOverNewer(); + if (salient || always) this.trigger(spec, ctl, { hold: false, priority: 2 }); + return; + } if (!salient && !always) return rel(); - go(); + if (!released) this.trigger(spec, ctl, { hold: true, priority: 2 }); }; - if (!conflicts.length && !typed.length && !always) return rel(); if (!o.body) return settle(newer.length > 0); - // read the body first (a clone, bounded in time) let done = false; - const timer = this.clock.setTimeout(() => { - if (done) return; - done = true; - settle(newer.length > 0); - }, BODY_WAIT_MS); + let timer: unknown = null; const finish = (body: unknown) => { if (done) return; done = true; - this.clock.clearTimeout(timer); + if (timer !== null) this.clock.clearTimeout(timer); + if (background) this.deliveryAnalysis.delete(op); if (body === undefined || this.destroyed) return settle(newer.length > 0); try { spec.body = body; @@ -1021,6 +1083,35 @@ export class RuntimeImpl implements Runtime { return settle(newer.length > 0); } }; + if (background && o.bodyNow) { + // the body is in memory: analyze it now, before the app's listeners run (and never break the delivery) + let body: unknown; + try { + body = o.bodyNow(); + } catch { + body = undefined; + } + try { + finish(body); + } catch (e) { + this.log("background delivery analysis failed", e); + } + return; + } + // read the body first (a clone, bounded in time) + timer = this.clock.setTimeout(() => finish(undefined), BODY_WAIT_MS); + // the delivery's chain is about to write: decide now, without the body (see finalizeDeliveries). Without newer + // data, only the body could tell whether it puts back what a pending local change replaced or replaces typed + // text (F1/F2): the delivery is not decided then, and its chain's writes are decided on their own (mutation + // triggers: covered() never covers a salient, undecided delivery's writes) + if (background) + this.deliveryAnalysis.set(op, () => { + if (newer.length || always) return finish(undefined); + if (done) return; + done = true; + if (timer !== null) this.clock.clearTimeout(timer); + if (op.delivery) op.delivery.salient = true; + }); let p: Promise<unknown>; try { p = o.body(); @@ -1030,6 +1121,54 @@ export class RuntimeImpl implements Runtime { p.then(finish, () => finish(undefined)); } + /** + * Whether a delivery could wait for its decision at all (what trigger() requires before holding): never in observe + * mode or while paused, nor while the model is not ready, nor when mode and policy permit no non-passive delivery + * action, nor when the model is not expected to answer within the hold budget. + */ + private deliveryHoldable(op: OpRec, matched: string[], defers: number): boolean { + if (this._mode === "observe" || this.paused || this.decider?.status.state !== "ready") return false; + const permitted = (name: string, tier: Tier) => tier !== "passive" && restriction(this.policy, this._mode, { name, tier }) === null; + let any = false; + for (const name of TRIGGER_ACTIONS.delivery) { + const b = BUILTIN_ACTIONS[name]; + if (!b || !permitted(name, b.tier)) continue; + // defer is offered only when related work is in flight (and twice at most) + if (name === "defer" && (defers >= 2 || !relatedInFlight(this.env, op, matched).length)) continue; + any = true; + break; + } + // custom actions: their applicable() needs the situation, so a permitted one counts as possible + if (!any) any = this.customActions.some((d) => d.on.includes("delivery") && permitted(d.name, d.tier ?? "heal")); + return any && this.expectedLatency() <= this.holdBudgetMs(); + } + + /** Whether a write's own decision could still change it (discard while held, late revert once applied). */ + private writesCanAct(): boolean { + return !this.paused && restriction(this.policy, this._mode, BUILTIN_ACTIONS.discard) === null; + } + + /** + * A write is about to apply: deliveries in its causal chain that were released without a hold and whose content + * analysis still waits for the body are decided now, without it, so the situation shows the state they were + * delivered into (not their own writes). + */ + private finalizeDeliveries(cause: OpRec | null): void { + let op: OpRec | undefined = cause ?? undefined; + for (let n = 0; op && n < 16; n++) { + const cut = this.deliveryAnalysis.get(op); + if (cut) { + this.deliveryAnalysis.delete(op); + try { + cut(); + } catch (e) { + this.log("background delivery analysis failed", e); + } + } + op = this.ops.get(op.cause); + } + } + private inChainOf(x: OpRec, writer: number | null): boolean { const w = writer === null ? undefined : this.ops.get(writer); return !!w && (this.ops.isAncestorOrSelf(x, w) || this.ops.isAncestorOrSelf(w, x)); @@ -1919,6 +2058,7 @@ export class RuntimeImpl implements Runtime { this.destroyed = true; this.hub.gating = false; this.queue.dispose(); + this.deliveryAnalysis.clear(); this.reporter.dispose(); if (this.settleTimer !== null) this.clock.clearTimeout(this.settleTimer); if (this.persistTimer !== null) this.clock.clearTimeout(this.persistTimer); diff --git a/packages/runtime/test/default-mode.test.ts b/packages/runtime/test/default-mode.test.ts index d7315aff..2d2fabcf 100644 --- a/packages/runtime/test/default-mode.test.ts +++ b/packages/runtime/test/default-mode.test.ts @@ -47,7 +47,11 @@ describe("default mode is observe (MVP)", () => { const { rt, clock, server, fetch } = setup({ mode: undefined, triage: "always", - script: defaultScript({ mutation: { diagnosis: "stale", action: "discard", p: 0.99 }, request: { diagnosis: "overload", action: "block", p: 0.99 } }), + script: defaultScript({ + mutation: { diagnosis: "stale", action: "discard", p: 0.99 }, + request: { diagnosis: "overload", action: "block", p: 0.99 }, + delivery: { diagnosis: "stale", action: "discard", p: 0.99 }, + }), }); const detections: Detection[] = []; rt.on("detect", (d) => detections.push(d)); @@ -63,10 +67,10 @@ describe("default mode is observe (MVP)", () => { await clock.flush(); expect(a.get()).toBe(1); const ds = rt.decisions(); - expect(ds.map((d) => d.trigger).sort()).toEqual(["mutation", "request"]); + expect(ds.map((d) => d.trigger).sort()).toEqual(["delivery", "mutation", "request"]); // the response too (not held) expect(ds.every((d) => !d.executed)).toBe(true); expect(rt.interventions()).toEqual([]); - expect(detections.map((d) => d.diagnosis).sort()).toEqual(["overload", "stale"]); + expect(detections.map((d) => `${d.trigger} ${d.diagnosis}`).sort()).toEqual(["delivery stale", "mutation stale", "request overload"]); }); it("never waits for the model: with a model that never answers, nothing is delayed", async () => { diff --git a/packages/runtime/test/observe-delivery.test.ts b/packages/runtime/test/observe-delivery.test.ts new file mode 100644 index 00000000..2a16b678 --- /dev/null +++ b/packages/runtime/test/observe-delivery.test.ts @@ -0,0 +1,452 @@ +// Observe mode (and any delivery that cannot be held): the delivery reaches the app exactly as without GenClass, +// synchronously and before any body read (fetch resolves at the network time; XHR, WebSocket and EventSource +// listeners run inside the original dispatch). The body analysis and the delivery decision still run, in the +// background and on the state the delivery was released into, for detection, reports and standing questions; such a +// decision never acts and never double-reports the delivery's own writes as mutations. Guard mode still holds and +// discards as before. +import { describe, expect, it } from "vitest"; +import type { Answer, Detection } from "../src/types.js"; +import { FakeClock, ManualDecider, defaultScript, setup, type Setup } from "./helpers.js"; + +const stale = defaultScript({ delivery: { diagnosis: "stale", action: "discard" }, mutation: { diagnosis: "stale", action: "discard" } }); + +interface Route { + body: unknown; + /** Time to the response headers (the fetch promise). */ + latency: number; + /** Time from the headers to the body (0: the body comes with the headers). */ + bodyDelay?: number; +} + +/** A fetch on the fake clock whose response body can arrive after the headers (a streamed body). */ +function streamingFetch(ref: { clock?: FakeClock }, route: (url: URL) => Route) { + return (input: unknown): Promise<Response> => { + const url = new URL(String(input), "http://app.test/"); + const r = route(url); + const clock = ref.clock!; + return new Promise<Response>((resolve) => { + clock.setTimeout(() => { + const bytes = new TextEncoder().encode(JSON.stringify(r.body)); + const stream = new ReadableStream<Uint8Array>({ + start(c) { + const send = () => { + c.enqueue(bytes); + c.close(); + }; + if (r.bodyDelay) clock.setTimeout(send, r.bodyDelay); + else send(); + }, + }); + resolve(new Response(stream, { status: 200, headers: { "content-type": "application/json" } })); + }, r.latency); + }); + }; +} + +/** The out-of-order search: "a" is slow (its body possibly slower still), "ab" answers first; "a" is then stale. */ +function searchSetup(opts: Parameters<typeof setup>[0] & { bodyDelay?: number }) { + const ref: { clock?: FakeClock } = {}; + const { bodyDelay = 0, ...rest } = opts ?? {}; + const fetchFn = streamingFetch(ref, (url) => { + const q = url.searchParams.get("q") ?? ""; + return { body: { q, items: [`${q}-1`] }, latency: q === "a" ? 600 : 100, bodyDelay: q === "a" ? bodyDelay : 0 }; + }); + const s = setup({ ...rest, extraGlobal: { ...(rest.extraGlobal ?? {}), fetch: fetchFn } }); + ref.clock = s.clock; + const st = s.rt.atom("search", { status: 0, items: [] as string[] }); + /** When each query started and when its fetch promise resolved (the response reached the app). */ + const started = new Map<string, number>(); + const resolved = new Map<string, number>(); + const load = (q: string, statusFirst = false) => + s.rt.user({ kind: "type", target: 'input "Search"', value: q }, () => { + started.set(q, s.clock.now()); + void (async () => { + const res = await s.fetch(`/api/search?q=${q}`); + resolved.set(q, s.clock.now()); + if (statusFirst) st.set((v) => ({ ...v, status: res.status })); // a write before the body is read + const d = (await res.json()) as { q: string; items: string[] }; + st.set((v) => ({ ...v, status: res.status, items: d.items })); + })(); + }); + return { ...s, st, load, resolved, started }; +} + +/** z (learns the write set) at 1000; a (slow) at 1300; ab at 1320, answering first. a arrives at 1900. */ +async function outOfOrder(x: ReturnType<typeof searchSetup>, statusFirst = false) { + x.load("z", statusFirst); + await x.clock.advance(300); + x.load("a", statusFirst); + await x.clock.advance(20); + x.load("ab", statusFirst); +} + +const deliveryCalls = (s: Setup) => s.decider.calls.filter((c) => c.trigger === "delivery"); + +describe("observe mode: fetch responses are never held", () => { + it("a conflicting response with a slow body resolves at the network time; the background decision is recorded and reported, its writes are not decided again", async () => { + const x = searchSetup({ mode: "observe", script: stale, bodyDelay: 300 }); + const detections: Detection[] = []; + x.rt.on("detect", (d) => detections.push(d)); + await outOfOrder(x); + await x.clock.advance(1000); + // the response reached the app when it arrived (600 ms), not after waiting up to 100 ms for its body + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(600); + // observe never changes anything: the stale result applied, as without GenClass + expect(x.st.get().items).toEqual(["a-1"]); + expect(x.rt.interventions()).toEqual([]); + // the delivery was decided in the background (not dropped as stale), without its body (it came too late) + expect(deliveryCalls(x)).toHaveLength(1); + expect(deliveryCalls(x)[0].state.trigger).toMatch(/^The response to GET \/api\/search\?q=a \(#\d+\) arrived and is about to be delivered/); + const ds = x.rt.decisions(); + expect(ds.map((d) => d.trigger)).toEqual(["delivery"]); // the stale write is covered by it: no mutation decision + expect(ds[0]).toMatchObject({ diagnosis: "stale", action: "discard", executed: false }); + expect(ds[0].reason).toMatch(/observe mode never changes execution/); + expect(detections.map((d) => d.trigger)).toEqual(["delivery"]); + // delivered over newer data without a decision to drop it: the stale value is marked (F9), as before + expect(x.rt.internals.hub.field("search.items")!.mark?.why).toMatch(/^by the response to GET \/api\/search\?q=a \(#\d+\), which was delivered over newer data from /); + }); + + it("the background decision is built on the state the response was delivered into, not on its own writes", async () => { + const x = searchSetup({ mode: "observe", script: stale }); + await outOfOrder(x); + await x.clock.advance(1000); + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(600); + expect(x.st.get().items).toEqual(["a-1"]); + const [req] = deliveryCalls(x); + expect(req).toBeDefined(); + const text = JSON.stringify(req.state); + expect(text).toContain("ab-1"); // search.items still holds the newer result + expect(text).not.toContain('a-1\\"]'); + expect(x.rt.decisions().map((d) => d.trigger)).toEqual(["delivery"]); + }); + + it("when the app writes before the body is read, the delivery is decided at that write, not after the body wait", async () => { + const x = searchSetup({ mode: "observe", script: stale, bodyDelay: 300 }); + await outOfOrder(x, true); + await x.clock.advance(580); // "a" arrives at 1900 and the app writes its status at once + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(600); + expect(deliveryCalls(x)).toHaveLength(1); + await x.clock.advance(1000); + expect(x.st.get().items).toEqual(["a-1"]); + expect(deliveryCalls(x)).toHaveLength(1); + expect(x.rt.decisions().map((d) => d.trigger)).toEqual(["delivery"]); // neither write is decided again + }); + + it("a response that puts back what a pending local change replaced, written by the app before its body was analyzed: its write is still decided (F1 is not lost)", async () => { + const s = setup({ mode: "observe", script: stale }); + s.server.on("PATCH", "/api/cards/c1", { body: { ok: true }, latency: 800 }); + let n = 0; + s.server.on("GET", "/api/board", () => ({ body: { cards: { c1: "todo", c2: n++ ? "review" : "doing" } }, latency: 50 })); + const b = s.rt.atom("board", { cards: { c1: "", c2: "" } as Record<string, string> }); + let resolvedAt = -1; + const load = () => + s.rt.op("load", async () => { + const res = await s.fetch("/api/board"); + resolvedAt = s.clock.now(); + const d = (await res.json()) as { cards: Record<string, string> }; + b.set({ cards: d.cards }); // the usual app: the write follows its own body read at once + }); + void load(); // learns what GET /api/board writes + await s.clock.advance(100); + s.rt.user({ kind: "click", target: 'button "Move c1 to done"' }, () => { + b.set((v) => ({ cards: { ...v.cards, c1: "done" } })); + void s.fetch("/api/cards/c1", { method: "PATCH", body: '{"col":"done"}' }); + }); + await s.clock.advance(50); + const t0 = s.clock.now(); + void load(); // its response has c1 = "todo", the value the user's pending move replaced + await s.clock.advance(1000); + expect(resolvedAt - t0).toBe(50); // not held + expect(b.get().cards.c1).toBe("todo"); // observe: the app's write applied + // without the body, the delivery cannot tell (F1): it is not decided as a delivery, and its write is decided on + // its own instead of being covered by a delivery that was never decided (exactly one decision either way) + const ds = s.rt.decisions().filter((d) => d.trigger !== "request"); + expect(ds).toHaveLength(1); + expect(ds[0]).toMatchObject({ diagnosis: "stale", executed: false }); + expect(ds[0].facts[0]).toMatch(/^board\.cards\.c1 has a pending local change: user clicked button "Move c1 to done" \(#\d+\)/); + expect(s.rt.interventions()).toEqual([]); + }); + + it("standing questions on delivery are answered (salient deliveries; every delivery with always)", async () => { + const x = searchSetup({ mode: "observe", script: stale }); + const asked: { id: string; subject: string; answer: Answer }[] = []; + x.rt.question({ id: "dup", on: ["delivery"], question: { type: "noul", instructions: "Is this response a duplicate?" }, onAnswer: (a, c) => asked.push({ id: "dup", subject: c.decision.subject, answer: a }) }); + await outOfOrder(x); + await x.clock.advance(1000); + expect(asked).toEqual([{ id: "dup", subject: expect.stringMatching(/^response to GET \/api\/search\?q=a /), answer: { type: "noul", noul: 0.9 } }]); + expect(x.st.get().items).toEqual(["a-1"]); + + const y = searchSetup({ mode: "observe" }); + const every: string[] = []; + y.rt.question({ id: "seen", on: ["delivery"], always: true, question: { type: "noul", instructions: "Did the app need this response?" }, onAnswer: (_a, c) => every.push(c.decision.subject) }); + y.load("z"); + await y.clock.advance(100); + expect(y.resolved.get("z")! - y.started.get("z")!).toBe(100); // asked, not held + await y.clock.flush(); + expect(every).toEqual([expect.stringMatching(/^response to GET \/api\/search\?q=z /)]); + }); +}); + +/** An XMLHttpRequest stand-in (as in delivery.test.ts): state behind getters, events dispatched on the object. */ +function makeXHR(ref: { clock?: FakeClock }, handler: (method: string, url: string) => { status: number; body: string; latency: number }) { + return class FakeXHR extends EventTarget { + #rs = 0; + #status = 0; + #text = ""; + #m = "GET"; + #u = ""; + #sending = false; + responseType = ""; + /** The type of the event being dispatched right now ("" outside a dispatch). */ + dispatching = ""; + onload: ((e: Event) => void) | null = null; + onreadystatechange: ((e: Event) => void) | null = null; + get readyState() { + return this.#rs; + } + get status() { + return this.#status; + } + get statusText() { + return this.#status === 200 ? "OK" : ""; + } + get responseText() { + return this.#text; + } + get response() { + return this.#text; + } + open(m: string, u: string) { + this.#m = m; + this.#u = u; + this.#rs = 1; + this.#status = 0; + this.#text = ""; + this.#sending = false; + } + send() { + this.#sending = true; + const r = handler(this.#m, this.#u); + ref.clock!.setTimeout(() => { + if (!this.#sending) return; + this.#sending = false; + this.#rs = 4; + this.#status = r.status; + this.#text = r.body; + for (const t of ["readystatechange", "load", "loadend"]) { + const e = new Event(t); + this.dispatching = t; + this.dispatchEvent(e); + this.dispatching = ""; + const h = (this as unknown as Record<string, unknown>)[`on${t}`]; + if (typeof h === "function") h.call(this, e); + } + }, r.latency); + } + abort() { + if (this.#rs === 4) { + this.#rs = 0; + this.#status = 0; + } + } + setRequestHeader() {} + getResponseHeader(): string | null { + return null; + } + getAllResponseHeaders(): string { + return ""; + } + }; +} + +describe("observe mode: XMLHttpRequest", () => { + it("a conflicting response: the app's listeners run inside the original dispatch (currentTarget set); the body is analyzed before they run", async () => { + const ref: { clock?: FakeClock } = {}; + const XHR = makeXHR(ref, (_m, url) => { + const q = new URL(url, "http://app.test/").searchParams.get("q") ?? ""; + return { status: 200, body: JSON.stringify({ q, items: [`${q}-1`] }), latency: q === "a" ? 600 : 100 }; + }); + const s = setup({ mode: "observe", script: stale, observe: { fetch: false, xhr: true }, extraGlobal: { XMLHttpRequest: XHR } }); + ref.clock = s.clock; + const st = s.rt.atom("search", { items: [] as string[] }); + const log: string[] = []; + const load = (q: string) => + s.rt.user({ kind: "type", target: 'input "Search"', value: q }, () => { + const x = new (s.g.XMLHttpRequest as typeof XHR)(); + x.addEventListener("readystatechange", (e) => x.readyState === 4 && log.push(`done ${q} ${x.dispatching === e.type}`)); // before open() + x.open("GET", `/api/search?q=${q}`); + x.addEventListener("load", (e) => { + // the first "load" listener: e.currentTarget is reliable there (Node clears it after each listener) + log.push(`load ${q} ${x.dispatching === e.type} ${e.currentTarget === x} ${deliveryCalls(s).length}`); + st.set({ items: (JSON.parse(x.responseText) as { items: string[] }).items }); + }); + x.addEventListener("loadend", (e) => log.push(`end ${q} ${x.dispatching === e.type}`)); + x.send(); + }); + load("z"); + await s.clock.advance(300); + load("a"); // slow + await s.clock.advance(20); + load("ab"); // fast: answers first + await s.clock.advance(1000); + // every listener ran inside the dispatch; the delivery decision of "a" was asked before its load listener ran + expect(log).toEqual(["done z true", "load z true true 0", "end z true", "done ab true", "load ab true true 0", "end ab true", "done a true", "load a true true 1", "end a true"]); + expect(st.get().items).toEqual(["a-1"]); + const del = deliveryCalls(s); + expect(del).toHaveLength(1); + // the body was analyzed on the state before the app's write (a content fact about the incoming value) + expect((del[0].state.facts as string[]).some((f) => /^The response has search\.items = .*a-1.*: neither the current value .*ab-1/.test(f))).toBe(true); + expect(s.rt.decisions().map((d) => d.trigger)).toEqual(["delivery"]); + expect(s.rt.interventions()).toEqual([]); + }); +}); + +// ------------------------------------------------------------------------------------------- push channels + +class FakeWS extends EventTarget { + static all: FakeWS[] = []; + /** Inside a dispatch of an incoming message. */ + dispatching = false; + constructor(public url: string) { + super(); + FakeWS.all.push(this); + } + send() {} + emit(data: unknown) { + this.dispatching = true; + this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(data) })); + this.dispatching = false; + } +} + +class FakeES extends EventTarget { + static all: FakeES[] = []; + dispatching = false; + constructor(public url: string) { + super(); + FakeES.all.push(this); + } + emit(type: string, data: unknown, id: string) { + this.dispatching = true; + this.dispatchEvent(new MessageEvent(type, { data: JSON.stringify(data), lastEventId: id })); + this.dispatching = false; + } +} + +describe("observe mode: push channels", () => { + it("a WebSocket message that would put back the value a pending local change replaced is delivered synchronously, inside the dispatch; decided in the background with its content", async () => { + const s = setup({ mode: "observe", script: stale, observe: { fetch: true, websocket: true }, extraGlobal: { WebSocket: FakeWS } }); + s.server.on("PATCH", "/api/cards/c1", { body: { ok: true }, latency: 800 }); + const b = s.rt.atom("board", { cards: { c1: "todo", c2: "todo" } as Record<string, string> }); + const seen: string[] = []; + const ws = new (s.g.WebSocket as typeof FakeWS)("ws://app.test/live"); + ws.addEventListener("message", (e) => { + const m = JSON.parse((e as MessageEvent).data as string) as { n: number; card: string; col: string }; + seen.push(`${m.n} ${ws.dispatching}`); + b.set((v) => ({ cards: { ...v.cards, [m.card]: m.col } })); + }); + const socket = FakeWS.all[FakeWS.all.length - 1]; + socket.emit({ n: 1, card: "c2", col: "doing" }); // learn what these messages write + await s.clock.advance(50); + s.rt.user({ kind: "click", target: 'button "Move c1 to done"' }, () => { + b.set((v) => ({ cards: { ...v.cards, c1: "done" } })); + void s.fetch("/api/cards/c1", { method: "PATCH", body: '{"col":"done"}' }); + }); + await s.clock.advance(50); + socket.emit({ n: 2, card: "c1", col: "todo" }); // older server state for c1: guard would hold it + expect(seen).toEqual(["1 true", "2 true"]); // delivered at once, inside the dispatch + expect(b.get().cards.c1).toBe("todo"); // observe: the app's write applied + const del = deliveryCalls(s); + expect(del).toHaveLength(1); // asked before the listener ran (the body is in memory) + expect((del[0].state.facts as string[])[0]).toMatch(/^board\.cards\.c1 has a pending local change: user clicked button "Move c1 to done" \(#\d+\) wrote it 0\.05s ago/); + await s.clock.flush(); + expect(s.rt.decisions().map((d) => d.trigger)).toEqual(["delivery"]); + expect(s.rt.decisions()[0]).toMatchObject({ diagnosis: "stale", executed: false }); + expect(s.rt.interventions()).toEqual([]); + // delivered over the pending local change without a decision to drop it: marked (F9), as before + expect(s.rt.internals.hub.field("board.cards.c1")!.mark?.why).toMatch(/^by the message WS message \/live \(#\d+\), which was delivered over a pending local change of /); + await s.clock.advance(1000); + }); + + it("EventSource messages asked about (triage always) are delivered synchronously, in order; each is still decided", async () => { + const manual = new ManualDecider(); + const s = setup({ mode: "observe", decider: manual, triage: "always", observe: { fetch: true, eventsource: true }, extraGlobal: { EventSource: FakeES } }); + const st = s.rt.atom("feed", { last: 0 }); + const got: string[] = []; + const es = new (s.g.EventSource as typeof FakeES)("http://app.test/stream"); + es.addEventListener("update", (e) => { + const d = JSON.parse((e as MessageEvent).data as string) as { n: number }; + got.push(`${d.n} ${es.dispatching}`); + st.set({ last: d.n }); + }); + const src = FakeES.all[FakeES.all.length - 1]; + src.emit("update", { n: 1 }, "e1"); + src.emit("update", { n: 2 }, "e2"); + expect(got).toEqual(["1 true", "2 true"]); // nothing waits for the model, which has not answered yet + expect(st.get().last).toBe(2); + while (manual.pending.length) { + manual.answer(defaultScript()); + await s.clock.flush(); + } + expect(s.rt.decisions().filter((d) => d.trigger === "delivery")).toHaveLength(2); + }); +}); + +describe("guard mode is unchanged", () => { + it("a stale response is held until its decision; discard drops the stale write", async () => { + const manual = new ManualDecider(); + const x = searchSetup({ mode: "guard", decider: manual }); + await outOfOrder(x); + await x.clock.advance(580); // "a" arrives at 1900: held for its delivery decision + expect(manual.pending.map((p) => p.req.trigger)).toEqual(["delivery"]); + await x.clock.advance(50); + expect(x.resolved.has("a")).toBe(false); // the app has not seen it yet + manual.answer(stale); + await x.clock.flush(); + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(650); + expect(x.st.get().items).toEqual(["ab-1"]); // the stale result was dropped + expect(x.rt.interventions().map((r) => [r.action, r.dropped])).toEqual([["discard", ["search.items"]]]); + expect(x.rt.decisions().map((d) => [d.trigger, d.executed])).toEqual([["delivery", true]]); + }); + + it("a delivery that cannot be held in guard mode (the model too slow) is released at once; its stale write is still decided on its own and late-reverted, as before", async () => { + const manual = new ManualDecider(); + const x = searchSetup({ mode: "guard", decider: manual, bodyDelay: 300 }); + manual.status = { state: "ready", warmupMs: 2000 }; // expected ~2 s; the auto budget tops out at 800 ms + await outOfOrder(x); + await x.clock.advance(580); + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(600); // not held, not even for its body + await x.clock.advance(1000); // the body arrives at 2200 and the app writes the stale result + expect(x.st.get().items).toEqual(["a-1"]); + // the write is not covered by a delivery decision that could not act: it gets its own (no delivery decision) + expect(manual.pending.map((p) => p.req.trigger)).toEqual(["mutation"]); + manual.answer(stale); + await x.clock.flush(); + expect(x.st.get().items).toEqual(["ab-1"]); // late revert + expect(x.rt.interventions().map((r) => [r.trigger, r.action, r.late])).toEqual([["mutation", "discard", true]]); + expect(x.rt.decisions().map((d) => d.trigger)).toEqual(["mutation"]); + }); + + it("guard mode with a slow model and a standing question that always asks about deliveries: the delivery is decided without acting, its write still on its own", async () => { + const manual = new ManualDecider(); + const x = searchSetup({ mode: "guard", decider: manual }); + manual.status = { state: "ready", warmupMs: 2000 }; + const asked: string[] = []; + x.rt.question({ id: "seen", on: ["delivery"], always: true, question: { type: "noul", instructions: "Did the app need this response?" }, onAnswer: (_a, c) => asked.push(c.decision.subject) }); + await outOfOrder(x); + await x.clock.advance(1000); + expect(x.resolved.get("a")! - x.started.get("a")!).toBe(600); + expect(x.st.get().items).toEqual(["a-1"]); + while (manual.pending.length) { + manual.answer(stale); + await x.clock.flush(); + } + expect(asked).toEqual(["z", "ab", "a"].map((q) => expect.stringMatching(new RegExp(`^response to GET /api/search\\?q=${q} `)))); + const del = x.rt.decisions().find((d) => d.trigger === "delivery" && /q=a /.test(d.subject))!; + expect(del).toMatchObject({ action: "discard", executed: false, reason: "the subject was not held (decided in the background)" }); + // the stale write of "a" got its own decision, which reverted it + expect(x.rt.decisions().filter((d) => d.trigger === "mutation")).toHaveLength(1); + expect(x.st.get().items).toEqual(["ab-1"]); + expect(x.rt.interventions().map((r) => [r.trigger, r.action, r.late])).toEqual([["mutation", "discard", true]]); + }); +}); diff --git a/packages/runtime/test/policy.test.ts b/packages/runtime/test/policy.test.ts index 227c7c0b..4d55d7c1 100644 --- a/packages/runtime/test/policy.test.ts +++ b/packages/runtime/test/policy.test.ts @@ -104,8 +104,12 @@ describe("policy gate (CONTRACT §8)", () => { expect(rt.decisions().filter((d) => d.trigger === "request").pop()!.executed).toBe(true); }); - it("observe mode never holds: writes and requests proceed while decisions are still reported", async () => { - const { rt, clock, server, fetch } = setup({ mode: "observe", triage: "always", script: defaultScript({ mutation: { diagnosis: "stale", action: "discard" }, request: { diagnosis: "overload", action: "block" } }) }); + it("observe mode never holds: writes, requests and responses proceed while decisions are still reported", async () => { + const { rt, clock, server, fetch } = setup({ + mode: "observe", + triage: "always", + script: defaultScript({ mutation: { diagnosis: "stale", action: "discard" }, request: { diagnosis: "overload", action: "block" }, delivery: { diagnosis: "stale", action: "discard" } }), + }); server.on("GET", "/api/x", { body: 1, latency: 5 }); const a = rt.atom("a", 0); void rt.op("w", () => a.set(1)); @@ -116,7 +120,8 @@ describe("policy gate (CONTRACT §8)", () => { await p; expect(server.log[0].t).toBe(t0); const ds = rt.decisions(); - expect(ds.length).toBe(2); + // the response's delivery is decided in the background too (it was not held) + expect(ds.map((d) => d.trigger).sort()).toEqual(["delivery", "mutation", "request"]); expect(ds.every((d) => !d.executed && /observe mode/.test(d.reason ?? ""))).toBe(true); expect(rt.interventions().length).toBe(0); }); From f10701350de3934023555fba1bf2e7ff55856683 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 02:47:38 -0400 Subject: [PATCH 10/25] runtime: redact F2 diffs and numeric/array secrets under secret containers F2 ("would replace text the user typed") diffed raw strings, so its preview printed characters of a redacted field. contentFacts now uses the shared redactedStringDiff helper (src/state/fields.ts, also used by changeText): a diff only when the redactor leaves both values unchanged, otherwise both sides render through describe(). The default redactor now also hides numbers, bigints and arrays under a strong secret-named container (payment.cvv.value = 123, login.otp.code, lock.pin.value, account.password.history). Booleans/null stay visible; broad containers (auth, session, cookie) are unchanged. Tests: test/redaction-v2.test.ts. STATUS.md documents the fix, the curriculum follow-up and known gaps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/runtime/STATUS.md | 33 ++++- packages/runtime/src/situation/content.ts | 4 +- packages/runtime/src/state/fields.ts | 16 ++- packages/runtime/src/util.ts | 9 +- packages/runtime/test/redaction-v2.test.ts | 135 +++++++++++++++++++++ 5 files changed, 186 insertions(+), 11 deletions(-) create mode 100644 packages/runtime/test/redaction-v2.test.ts diff --git a/packages/runtime/STATUS.md b/packages/runtime/STATUS.md index 96608d13..3ee89d6d 100644 --- a/packages/runtime/STATUS.md +++ b/packages/runtime/STATUS.md @@ -39,6 +39,36 @@ observe mode on the same scenario (`debug.js --interference`): | decide | `src/decide/*.ts` | queue (deadlines, stale drop, runtime-side timeout, cache, latency samples), §8 gate, reports | | runtime | `src/runtime.ts` | wiring, delivery gate, actions (snapshot rollback, chain revert, resync, late revert, undo), settled points, plugins | +## Fix after 0.1.0-alpha.1: two redaction leaks (privacy) + +Model-visible text changes only for values the redactor hides; everything else renders byte-for-byte as before. +- F2 ("would replace text the user typed"): `src/situation/content.ts` -> `contentFacts` diffed the raw strings, so + the diff-centred preview printed characters of a redacted field. It now uses the shared helper + `src/state/fields.ts` -> `redactedStringDiff` (also used by `changeText`): a diff only when both values pass the + redactor unchanged (`Object.is(redact(path, v), v)`), otherwise both sides render through `describe()` + (`[redacted] → [redacted]`, or a custom redactor's replacement). +- Default redactor (`src/util.ts` -> `isSensitivePath` / `defaultRedact`): under a strong (non-broad) secret-named + container, numbers, bigints and arrays are now redacted as well as strings (`payment.cvv.value = 123`, + `login.otp.code = 123456`, `lock.pin.value = 1234`, `account.password.history = [...]`). Booleans, null and + undefined stay visible, plain objects are still judged key by key, and broad containers (`auth`, `session`, + `cookie`) still redact only opaque credential-looking strings. Side effect: numbers under a container whose name + is a secret word in another sense are hidden too (`map.pin.lat`, `boarding.pass.seat`), as their strings already + were. +- Tests: `test/redaction-v2.test.ts` (F2 on a secret field with the default and a custom redactor, an unredacted + field keeps its diff, the container cases above). +- Training data: SIM rows are rendered by the runtime itself and follow automatically. The curriculum's Python + port (`training/curriculum/rt.py` -> `content_facts`, `string_diff`, `change_text`) has the F2 diff but no + redactor anywhere (every fact prints the scenario's value summaries), so it was not changed: gating only F2 would + not make it match the runtime. Secret names there (`training/curriculum/vocab.py` -> `DOMAINS`): the banking + domain's `iban` text field, and the nouns `pin` (maps) and `pass` (bike sharing), which become store names + through `training/curriculum/app.py` -> `App.item` (`pin.total`, `pass.content`, ...); the runtime renders + values under those as `[redacted]` (strings before this fix, now numbers and arrays too), the curriculum prints + them. Porting `isSensitivePath` or renaming those words is a curriculum follow-up. +- Known gaps, not changed here (they would change other model-visible text): a container named by a secret + word pair (`cardNumber`, `apiKey`, `creditCard`) counts as broad, so `payment.cardNumber.value = "4111 1111 ..."` + (or a number) is still shown; and the "changed since X started ... is back to V" fact (`src/situation/facts.ts`) + compares rendered text, so two different redacted values read as "back to [redacted]". + ## Fix after batch 5: situation() purity (REAL report, oss-svelte-conduit) - New regression test `test/situation-purity.test.ts`: a mixed app raises every trigger kind (triage "always": @@ -1031,7 +1061,8 @@ questions: - Error/transition `rollback` restores only the fields the op's own chain wrote (the contract's "last consistent snapshot" would also revert other chains' writes, e.g. user input); inconsistency rollback uses the snapshot. - Default redaction is by word-level secret names (approved SIM request a), not the §2 regex, and (batch 5) by the - leaf field only, with the container rules above; booleans and null are never redacted. + leaf field only, with the container rules above; booleans and null are never redacted. After 0.1.0-alpha.1, a + strong secret-named container hides numbers, bigints and arrays too, and F2 never diffs a redacted value. - `situation(trigger)` returns the last situation built for that trigger (an "ask about now" one otherwise). - Batch 4 salience: a user action that changed a field is not, by itself, a version conflict (see Batch 4, contract deltas). XHR `on*` getters return GenClass's wrapper of the app's handler (needed so XHR implementations that call diff --git a/packages/runtime/src/situation/content.ts b/packages/runtime/src/situation/content.ts index 000350c2..6e2538e6 100644 --- a/packages/runtime/src/situation/content.ts +++ b/packages/runtime/src/situation/content.ts @@ -12,7 +12,7 @@ import type { Fact } from "../types.js"; import type { FieldHist } from "../state/hub.js"; -import { leafOf, stringDiff } from "../state/fields.js"; +import { leafOf, redactedStringDiff } from "../state/fields.js"; import type { OpRec } from "../trace/ops.js"; import { describe, isIdSegment, isPlainObject, kindOf, plural, secs } from "../util.js"; import { opLabel } from "./describe.js"; @@ -391,7 +391,7 @@ export function contentFacts(env: SitEnv, x: OpRec, cmps: Cmp[], subject: "The r continue; } if (c.user) { - const d = typeof c.current === "string" && typeof c.incoming === "string" ? stringDiff(c.current, c.incoming) : null; + const d = redactedStringDiff(c.path, c.current, c.incoming, env.redact); const change = d ? d.text : `${show(env, c.path, c.current)} → ${show(env, c.path, c.incoming)}`; const last = c.user.last; out.push(fact(`${subject} would replace text the user typed into ${c.path} after #${x.id} started (${plural(c.user.n, "user write")}, the last ${secs(now - last.t)} ago): ${change}.`, "versions", false)); diff --git a/packages/runtime/src/state/fields.ts b/packages/runtime/src/state/fields.ts index 8eef11f1..cede3bb7 100644 --- a/packages/runtime/src/state/fields.ts +++ b/packages/runtime/src/state/fields.ts @@ -362,10 +362,8 @@ export function changeText(c: Pick<FieldChange, "before" | "after" | "path"> & { if (removedK.length) parts.push(`removed ${removedK.slice(0, 2).join(", ")}${removedK.length > 2 ? ` and ${removedK.length - 2} more` : ""}`); return `${b.len} → ${a.len} entries${parts.length ? `: ${parts.join("; ")}` : ""}`; } - if (typeof c.before === "string" && typeof c.after === "string" && Object.is(redact(c.path, c.after), c.after) && Object.is(redact(c.path, c.before), c.before)) { - const d = stringDiff(c.before, c.after); - if (d) return d.text; - } + const d = redactedStringDiff(c.path, c.before, c.after, redact); + if (d) return d.text; return `${describe(c.before, c.path, redact, 36)} → ${describe(c.after, c.path, redact, 36)}`; } @@ -398,6 +396,16 @@ export function stringDiff(before: string, after: string, width = 30): StringDif return { removed, added, text: `${win(before)} → ${win(after)} (${what})` }; } +/** + * stringDiff of two values at `path`, only when both are strings the redactor leaves unchanged: a diff-centred + * preview would otherwise print the characters the redactor hides. Null otherwise (callers fall back to describe()). + */ +export function redactedStringDiff(path: string, before: unknown, after: unknown, redact: Redactor): StringDiff | null { + if (typeof before !== "string" || typeof after !== "string") return null; + if (!Object.is(redact(path, after), after) || !Object.is(redact(path, before), before)) return null; + return stringDiff(before, after); +} + // ------------------------------------------------------------------------------------------------ patches /** diff --git a/packages/runtime/src/util.ts b/packages/runtime/src/util.ts index 4e3cb4a1..812f38fb 100644 --- a/packages/runtime/src/util.ts +++ b/packages/runtime/src/util.ts @@ -245,8 +245,9 @@ const PATH_LIKE = /^[^\s."']+(\.[^\s."']+)*$/; * Whether the value at `path` is a secret, decided by the leaf field's name, never by the store's or a container's * name alone: `auth.token`, `form.password`, `payment.card.number` (a secret pair across the last two segments) are * secrets; `auth.loading`, `auth.user.name` are not. Array indices are skipped (`users.3.password`). Plain objects - * are never redacted whole: their keys are judged one by one. Under a container whose name means a secret, string - * values are redacted too (`credentials.password.value`), and under a broad one (`auth`, `session`, `cookie`) only + * are never redacted whole: their keys are judged one by one. Under a container whose name means a secret, strings, + * numbers, bigints and arrays are redacted too (`credentials.password.value`, `payment.cvv.value = 123`, + * `login.otp.code`, `account.password.history = [...]`), and under a broad one (`auth`, `session`, `cookie`) only * opaque credential-looking strings (`auth.tokens.access = "eyJ…"`). Booleans, null and undefined are never secrets. * Free text (an element description, a header line) is a secret when any of its words names one. */ @@ -263,11 +264,11 @@ export function isSensitivePath(path: string, value?: unknown): boolean { const b = words(leaf); if (a.length && b.length && isSecretPair(a[a.length - 1], b[0])) return true; } - if (typeof value !== "string" && typeof value !== "number") return false; + if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint" && !Array.isArray(value)) return false; for (let i = 0; i < segs.length - 1; i++) { if (!isSensitiveName(segs[i])) continue; const broad = words(segs[i]).every((w) => WEAK_CONTAINER.has(w) || !SECRET_WORDS.has(w)); - if (!broad && typeof value === "string") return true; + if (!broad) return true; if (typeof value === "string" && OPAQUE.test(value)) return true; } return false; diff --git a/packages/runtime/test/redaction-v2.test.ts b/packages/runtime/test/redaction-v2.test.ts new file mode 100644 index 00000000..57ea0e8e --- /dev/null +++ b/packages/runtime/test/redaction-v2.test.ts @@ -0,0 +1,135 @@ +// Redaction leaks fixed after 0.1.0-alpha.1: (1) the F2 fact ("would replace text the user typed") diffed raw strings, +// printing characters of a value the redactor hides; (2) under a strong secret-named container (`cvv`, `otp`, `pin`, +// `password`), numbers, bigints and arrays were shown (only strings were redacted). +import { describe as group, expect, it } from "vitest"; +import { changeText, redactedStringDiff } from "../src/state/fields.js"; +import type { EvaluateRequest } from "../src/types.js"; +import { REDACTED, defaultRedact, describe, isSensitivePath, type Redactor } from "../src/util.js"; +import { setup, type Setup } from "./helpers.js"; + +const factsOf = (r: EvaluateRequest | undefined) => ((r?.state.facts as string[] | undefined) ?? []).join("\n"); +const deliveries = (s: Setup) => s.decider.calls.filter((c) => c.trigger === "delivery"); + +const SECRET_A = "correct horse battery staple tango"; +const SECRET_B = "correct horse battery staple tango foxtrot"; + +/** + * An autosave of `<store>.<field>` that echoes the saved text back after 400 ms while the user keeps typing: the + * delivery would replace text the user typed (F2). Returns the facts of the first delivery request. + */ +async function f2Facts(opts: { store: string; field: string; redact?: Redactor }): Promise<string> { + const s = setup(opts.redact ? { redact: opts.redact } : {}); + s.server.on("PUT", "/api/save", ({ body }) => { + const sent = JSON.parse(body ?? "{}") as Record<string, string>; + return { body: { [opts.field]: sent[opts.field].trim() }, latency: 400 }; + }); + const st = s.rt.atom(opts.store, { [opts.field]: `${SECRET_A} ` } as Record<string, string>); + const save = () => + void s.rt.op("autosave", async () => { + const d = (await (await s.fetch("/api/save", { method: "PUT", body: JSON.stringify({ [opts.field]: st.get()[opts.field] }) })).json()) as Record<string, string>; + st.set({ [opts.field]: d[opts.field] }); + }); + save(); // teaches the signature's write set (the server trims the trailing space) + await s.clock.advance(600); + save(); + await s.clock.advance(100); + for (const t of [`${SECRET_A} f`, `${SECRET_A} foxt`, SECRET_B]) { + s.rt.user({ kind: "type", target: `input "${opts.field}"`, value: t }, () => st.set({ [opts.field]: t })); + await s.clock.advance(80); + } + await s.clock.advance(1000); + const req = deliveries(s)[0]; + expect(req).toBeDefined(); + return factsOf(req); +} + +group("F2 on a field the redactor hides", () => { + it("default redactor: a secret-named field shows [redacted] on both sides, never a diff of the raw text", async () => { + const facts = await f2Facts({ store: "vault", field: "passphrase" }); + expect(facts).toMatch(/The response would replace text the user typed into vault\.passphrase after #\d+ started \(3 user writes, the last [\d.]+s ago\): \[redacted\] → \[redacted\]\./); + expect(facts).not.toContain("foxtrot"); + expect(facts).not.toContain("staple"); + }); + + it("custom redactor: a field it hides is rendered with its replacement, not diffed", async () => { + const redact: Redactor = (p, v) => (p === "doc.body" ? "<hidden>" : v); + const facts = await f2Facts({ store: "doc", field: "body", redact }); + expect(facts).toMatch(/would replace text the user typed into doc\.body after #\d+ started \(3 user writes, the last [\d.]+s ago\): <hidden> → <hidden>\./); + expect(facts).not.toContain("foxtrot"); + }); + + it("a field the redactor leaves alone keeps the diff-centred preview (model-visible text unchanged)", async () => { + const facts = await f2Facts({ store: "doc", field: "body" }); + expect(facts).toMatch(/would replace text the user typed into doc\.body after #\d+ started \(3 user writes, the last [\d.]+s ago\): "…y staple tango foxtrot" → "…y staple tango" \(removes " foxtrot"\)\./); + }); + + it("redactedStringDiff diffs only values both sides of which pass the redactor unchanged", () => { + const id: Redactor = (_p, v) => v; + expect(redactedStringDiff("doc.body", SECRET_B, SECRET_A, id)?.text).toBe('"…y staple tango foxtrot" → "…y staple tango" (removes " foxtrot")'); + expect(redactedStringDiff("form.password", SECRET_B, SECRET_A, defaultRedact)).toBeNull(); + // only one side hidden (a custom redactor that hides by value) is still not diffed + const byValue: Redactor = (_p, v) => (typeof v === "string" && v.includes("foxtrot") ? REDACTED : v); + expect(redactedStringDiff("doc.body", SECRET_B, SECRET_A, byValue)).toBeNull(); + expect(redactedStringDiff("doc.body", 1, 2, id)).toBeNull(); + expect(changeText({ path: "form.password", before: SECRET_B, after: SECRET_A }, defaultRedact)).toBe("[redacted] → [redacted]"); + expect(changeText({ path: "doc.body", before: SECRET_B, after: SECRET_A }, byValue)).toBe(`[redacted] → ${JSON.stringify(SECRET_A)}`); + }); +}); + +group("default redactor under a strong secret-named container", () => { + it("redacts numbers, bigints and arrays as well as strings", () => { + const r = defaultRedact; + expect(r("payment.cvv.value", 123)).toBe(REDACTED); + expect(r("login.otp.code", 123456)).toBe(REDACTED); + expect(r("lock.pin.value", 1234)).toBe(REDACTED); + expect(r("lock.pin.value", 1234n)).toBe(REDACTED); + expect(r("account.password.history", ["hunter1", "hunter2"])).toBe(REDACTED); + expect(r("account.password.history", [111, 222])).toBe(REDACTED); + expect(r("credentials.password.value", "hunter2")).toBe(REDACTED); // unchanged + expect(r("users.3.password.attempts.0", 7)).toBe(REDACTED); // array indices are skipped + }); + + it("keeps booleans, null and undefined visible, and plain objects are still judged key by key", () => { + const r = defaultRedact; + expect(r("login.otp.sent", true)).toBe(true); + expect(r("lock.pin.value", null)).toBe(null); + expect(r("lock.pin.value", undefined)).toBe(undefined); + expect(r("payment.cvv", { length: 3 })).toEqual({ length: 3 }); + expect(isSensitivePath("account.password", { history: [1] })).toBe(false); + }); + + it("keeps the broad-container behaviour: only opaque credential-looking strings are redacted", () => { + const r = defaultRedact; + expect(r("auth.expiresAt", 1767225600000)).toBe(1767225600000); + expect(r("auth.retries", 3)).toBe(3); + expect(r("auth.roles", ["admin", "editor"])).toEqual(["admin", "editor"]); + expect(r("session.user.id", 42)).toBe(42); + expect(r("auth.tokens.kind", "bearer")).toBe("bearer"); + expect(r("auth.tokens.access", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ")).toBe(REDACTED); + }); + + it("is unchanged outside secret-named containers", () => { + const r = defaultRedact; + expect(r("cart.items.3.qty", 2)).toBe(2); + expect(r("board.cards", ["a"])).toEqual(["a"]); + expect(r("map.pins", [1, 2])).toEqual([1, 2]); + expect(r("trip.passengers.count", 4)).toBe(4); + expect(r("auth.loading", 0)).toBe(0); + }); + + it("a number change under a strong container renders [redacted] in change text, in place of the digits", () => { + expect(changeText({ path: "lock.pin.value", before: 1234, after: 5678 }, defaultRedact)).toBe(`${REDACTED} → ${REDACTED}`); + expect(changeText({ path: "cart.items.3.qty", before: 1, after: 2 }, defaultRedact)).toBe("1 → 2"); + }); + + it("describe() of a store hides those values", () => { + // describe() prints two levels of keys, so these objects are shallow enough for the values to be rendered. + expect(describe({ value: 1234, set: true }, "lock.pin", defaultRedact, 400)).toBe(`{value: ${REDACTED}, set: true}`); + expect(describe({ cvv: { value: 123 } }, "payment", defaultRedact, 400)).toBe(`{cvv: {value: ${REDACTED}}}`); + expect(describe({ history: [111, 222], hint: "x" }, "account.password", defaultRedact, 400)).toBe(`{history: ${REDACTED}, hint: ${REDACTED}}`); + expect(describe({ pin: { value: 1234 } }, "lock", (_p, v) => v, 400)).toBe("{pin: {value: 1234}}"); // the same shape, unredacted + expect(describe(1234, "lock.pin.value", defaultRedact)).toBe(REDACTED); + expect(describe(["hunter1", "hunter2"], "account.password.history", defaultRedact)).toBe(REDACTED); + expect(describe(true, "lock.pin.set", defaultRedact)).toBe("true"); + }); +}); From 7dda2ce8fd58b791eb09391d1f268c3e4dcee704 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 03:11:51 -0400 Subject: [PATCH 11/25] docs: READMEs and RELEASE.md for the next release (0.1.0-beta.0 with the model) READMEs: drop the limitations fixed by 054da38 (observe-mode delivery delay, no delivery decisions in observe) and f107013 (F2 diff of redacted text, numbers/arrays under secret containers); list the remaining redaction gaps and the confirmed install/CDN review findings; the observe console example now shows the delivery decision (reproduced); status says what is not on npm yet. RELEASE.md: describe the next release. 0.1.0-alpha.1 is taken; propose 0.1.0-beta.0 (model-backed, after r17-v2a is validated with fitted gates from batch 6) or 0.1.0-alpha.2 (without the model); blockers from the install review; bump-then-rebuild (the global build bakes the version); format drift since situation-v2; alpha.1 kept as a record. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 16 +- RELEASE.md | 679 +++++++++++++++++++------------------ packages/runtime/README.md | 72 +++- 3 files changed, 416 insertions(+), 351 deletions(-) diff --git a/README.md b/README.md index 3c3bfbd8..0b250ea8 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,13 @@ which available action is best. There is no list of known bugs in the code. > - **No model is published for this format yet.** `@genclass/runtime-model` is not on npm, so a default > `GenClass.init()` prints `[GenClass] Model unavailable (...); observing only.` and finds nothing. > - **Round 1 models** (format `situation-v1`) exist but do not match this runtime. -> - **On npm:** `@genclass/runtime@0.1.0-alpha.1` is this runtime. `0.1.0-alpha.0` is the older v1 runtime: it -> defaults to guard, holds store writes, and has a `NaN` crash that alpha.1 fixes. +> - **On npm:** `@genclass/runtime@0.1.0-alpha.1` (`latest`) is this runtime. `0.1.0-alpha.0` is the older v1 +> runtime: it defaults to guard, holds store writes, and has a `NaN` crash that alpha.1 fixes. +> - **In this repository, not yet on npm:** the one-command install (`npx @genclass/runtime init`), the +> `@genclass/runtime/auto` entries and the script tag; observe mode never holding or delaying a response; and +> two redaction fixes. They ship in the next release: `0.1.0-beta.0` with the model, or `0.1.0-alpha.2` if a +> release without the model goes out first ([RELEASE.md](RELEASE.md)). The install path still has known issues, +> listed under the runtime README's known limitations. > > What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: > start at [AGENTS.md](AGENTS.md). @@ -90,7 +95,7 @@ All numbers are on held-out data, with each recall reported next to its false-in | [`packages/runtime`](packages/runtime) | `@genclass/runtime`, the library. Observers, causality, stores and adapters, learned baselines/relations/profiles, facts, triage, policy gate, actions, model host (Web Worker, ONNX Runtime Web on WebGPU/WASM), devtools overlay. [README](packages/runtime/README.md) · [STATUS](packages/runtime/STATUS.md) | | [`packages/runtime-model`](packages/runtime-model) | Model card for the not-yet-published `@genclass/runtime-model` | | [`sim`](sim) | Training-data simulator: random apps run on the real runtime in a deterministic virtual world, labelled by counterfactual outcomes | -| [`realapps`](realapps) | About 90 real apps (written for the corpus, plus open-source ones) run with the real runtime in headless Chromium, labelled the same way; the never-worse sweep covered the first 66. [README](realapps/README.md) | +| [`realapps`](realapps) | 128 real apps (written for the corpus, plus open-source ones) run with the real runtime in headless Chromium, labelled the same way; the never-worse sweep covered the first 66. [README](realapps/README.md) | | [`training`](training) | Vocabulary pruning, curriculum (`curriculum/rt.py` mirrors the runtime's renderer), multi-node CPU training on Azure, int8 ONNX export, evaluation | | [`demos`](demos) | Six demo apps (typeahead, autosave, checkout, flaky dashboard, live kanban, real-time decisions) with a Service Worker chaos backend and Playwright trials | | [`docs/runtime`](docs/runtime) | [Results](docs/runtime/RESULTS.md) · [Architecture](docs/runtime/ARCHITECTURE.md) · [Build contract](docs/runtime/CONTRACT.md) · [API](docs/runtime/API.md) | @@ -113,8 +118,9 @@ NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # t The same steps run in CI ([.github/workflows/ci.yml](.github/workflows/ci.yml), Node 22) on pushes to `main`, `runtime`, `mvp` and `mvp-v2`, on pull requests, and on manual dispatch. -Last full local run (2026-10-08): 336 tests passed and 14 skipped. The skips are model-parity tests, which need -`GENCLASS_MODEL_DIR`. The perf tests time a 5,000-item store and can fail under parallel load. +Last full local run (2026-10-08, branch `mvp-v2-merge` at f107013): 375 tests passed and 14 skipped, plus the 4 +perf tests run alone. The skips are model-parity tests, which need `GENCLASS_MODEL_DIR`. The perf tests time a +5,000-item store and can fail under parallel load. Releasing: [RELEASE.md](RELEASE.md). diff --git a/RELEASE.md b/RELEASE.md index 73a2ea87..24fd3fca 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,449 +1,472 @@ # Release procedure: `@genclass/runtime` and `@genclass/runtime-model` -> **Scope:** publishing `@genclass/runtime` (`packages/runtime`) and the planned `@genclass/runtime-model` (`packages/runtime-model`) to npm, their git tags and GitHub releases, and the checks before and after each publish. +> **Scope:** the next release. That is a model-backed `@genclass/runtime` (proposed `0.1.0-beta.0`) carrying the one-command install, published after the first situation-v2 model as `@genclass/runtime-model@0.1.0`. It also covers git tags, GitHub releases, and the checks before and after each publish. The `0.1.0-alpha.1` publish is kept as a record at the end. > **Read this when:** you are asked to cut a release, prepare a tarball for the user to publish, or package a trained model. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified 2026-10-08 (~07:00 UTC) against branch `mvp-v2-merge` at f107013. That branch is `mvp-v2` (release commit 806a296), merged with origin/runtime eff18cb (dabbce2), plus the two runtime fixes 054da38 and f107013. Newer commits on origin/runtime (up to 5bc40c9) were read with `git show` and are not merged on this branch. If this doc and the code disagree, the code wins. ## TL;DR -- **Two releases, in this order.** - - **Part A (done 2026-10-08, no model).** `@genclass/runtime@0.1.0-alpha.1` from `mvp-v2` (release commit 806a296), planned for dist-tag `alpha` but published under `latest`. It ships the NaN fix (ad24804), the situation-v2 runtime (batch 4 fcd1e68, batch 5 6e5e86e), the `observe` default (f3636b2) and updated docs. - - **Part B (after a situation-v2 model exists).** First `@genclass/runtime-model@0.1.0` plus the GitHub release `runtime-model-v0.1.0`. Then a demos eval (Off / Observe / Guard). Last, `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. -- **Who runs what.** Agents prepare and check everything: worktree, install, typecheck, build, unit tests, `npm pack`, the exact commands. **Only the user publishes** (`npm publish` and `npm dist-tag` need their npm 2FA). The user also approves every `git push`, tag push and `gh release`. Agents must ask before Playwright and `smoke.sh`, model downloads, demos eval, and anything that touches training or Azure. Those runs belong to Mehar's setup (`HANDOFF.md`). -- **Part A was done** on 2026-10-08: `@genclass/runtime@0.1.0-alpha.1` published 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. It went to `latest` rather than `alpha`. The first attempt got a 403 (the account had no 2FA); after enabling 2FA it went through browser-based 2FA approval. The procedure below is kept for reference and for later releases. -- **Registry today** (`npm view`, 2026-10-08, before Part A): - - `@genclass/runtime` had versions `0.0.0-stage` and `0.1.0-alpha.0`, with `latest` = `0.1.0-alpha.0`. That build is situation-v1, defaults to `guard`, still has the NaN crash, and has no model. Since Part A, `latest` = `0.1.0-alpha.1`. - - `@genclass/runtime-model` is **404**. - - The npm org `genclass` has two members: `meharpro` (owner) and `karanvir1729` (developer). Both have read-write access to `@genclass/runtime`. -- **The default model URL is pinned.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. Both 404 today. npm versions are immutable, so **whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently**. Validate before publishing. -- **Never publish the round-1 R17 (`situation-v1`) as `0.1.0`.** The loader does not check a situation version: `packages/runtime/src/model/loader.ts` checks only the card format `genclass-runtime-model/1`. A v1 model would therefore load into the v2 runtime without any error and decide on text it was never trained on. -- **npm 11 refuses to publish a prerelease without `--tag`.** npm 11.8.0 `lib/commands/publish.js` throws "You must specify a tag using --tag when publishing a prerelease version.", so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. A non-prerelease needs no tag: the first one (`0.1.0`) becomes `latest`, because prereleases are left out of npm's "higher version" check. +- **Versions.** + - `0.1.0-alpha.1` is **taken**: our publish (05:33 UTC, dist-tag `latest`). It has the NaN fix, the situation-v2 runtime, the `observe` default and the docs. It does **not** have Mehar's one-command install. + - **Proposed:** `0.1.0-beta.0` for the model-backed release, or `0.1.0-alpha.2` if a release without the model goes out first. Both carry the install features. + - The tree still says `0.1.0-alpha.1` (`packages/runtime/package.json`, `packages/genclass-runtime/package.json`). Bump before any build or pack (step C3). +- **Order.** + 1. Validate the `r17-v2a` export, with gate thresholds fitted (B0–B2). + 2. Publish `@genclass/runtime-model@0.1.0` and the GitHub release `runtime-model-v0.1.0` (B3–B6). + 3. Run the demos eval: Off / Observe / Guard (B7). + 4. Publish `@genclass/runtime@0.1.0-beta.0` and move `latest` to it (Part C). +- **The model needs batch 6, which is not on this branch.** + - `r17-v2a`'s results are in origin/runtime 416e374 (`docs/runtime/RESULTS.md`). On held-out sim (`sim2e`): diagnosis 84.4%, action 77.9%, guard FIR 0.00%, heal FIR 0.46%. On the real-app eval set (16,600 rows): guard and heal FIR 0.00%. But at the fixed 0.9 / 0.8 gates it almost never acts: real-app recall is 0.6% for duplicates and 1.0% for stale. + - origin/runtime 5bc40c9 ("Runtime batch 6", tag `situation-v2.1`) makes the runtime use the gate thresholds in the model's `meta.json` (`gate`). TRAIN fits them with `training/fit_gates.py --write-meta`. + - So the beta needs 5bc40c9 merged, and an export whose `meta.json` has a fitted `gate`. Without batch 6 the runtime ignores `gate` and keeps 0.9 / 0.8. + - A local branch `mvp-v2-b6` (merge commit 4e95373) merges 5bc40c9 onto f107013. It was not checked here. +- **Format drift since the model's training data.** `r17-v2a` trained on situation-v2 data (tag `situation-v2` = 6e5e86e). Since then, two things change what the runtime sends the model: + - f107013, on this branch: redacted values. The F2 fact prints `[redacted] → [redacted]` instead of a diff. Numbers and arrays under a secret-named container are now `[redacted]` (STATUS.md: curriculum store names such as `pin.total` and `pass.content` hit this). + - 5bc40c9: one new fact on stalls without a latency baseline (additive, `situation-v2.1`). + + The user and Mehar decide whether to accept this drift for the beta or tag a new format and regenerate (`HANDOFF.md`, "The training format is frozen"). +- **Install blockers.** The 2026-10-08 install review is listed under [Blockers](#blockers-for-the-runtime-release). The high-severity one: `init --mode guard` writes the observe import. +- **Dist-tag.** The README tells users to run `npx @genclass/runtime init` and to use the unversioned script tag `https://cdn.jsdelivr.net/npm/@genclass/runtime`. Both resolve `latest`. So the new version must become `latest`; until it does, users get alpha.1, which has no `init` and no script-tag build. +- **Who runs what.** + - Agents prepare and check everything: worktree, install, typecheck, build, unit tests, `npm pack`, the exact commands. + - **Only the user publishes.** `npm publish` and `npm dist-tag` need their npm 2FA. The user also approves every `git push`, tag push and `gh release`. + - Agents ask first before Playwright, `smoke.sh`, the install end-to-end runs, model downloads, the demos eval, and anything that touches training or Azure. Mehar runs Azure (`HANDOFF.md`). +- **Registry** (`npm view`, 2026-10-08 ~07:00 UTC): + - `@genclass/runtime`: versions `0.0.0-stage`, `0.1.0-alpha.0`, `0.1.0-alpha.1`; `latest` = `0.1.0-alpha.1`, no other dist-tags. + - `@genclass/runtime-model`: **404**. + - `genclass-runtime` (unscoped alias): **404**, so the name is unregistered. +- **The default model URL is pinned.** + - `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. + - `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. + - npm versions are immutable, so **whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently.** That includes alpha.1, which is `latest` today: it starts loading the model the moment the package exists (in observe mode, so it only reports). +- **Never publish a round-1 (`situation-v1`) model as `0.1.0`.** `packages/runtime/src/model/loader.ts` checks only the card format `genclass-runtime-model/1`, never a situation version. A v1 model would load into the v2 runtime without any error. +- **npm 11 refuses to publish a prerelease without `--tag`.** npm 11.8.0 `lib/commands/publish.js` throws "You must specify a tag using --tag when publishing a prerelease version." A non-prerelease (`0.1.0`) needs no tag and becomes `latest`. + +## Versions + +| package | on npm | next | why | +|---|---|---|---| +| `@genclass/runtime` | `0.1.0-alpha.1` (`latest`), `0.1.0-alpha.0`, `0.0.0-stage` | **`0.1.0-beta.0`** with the model; `0.1.0-alpha.2` if released before the model | `alpha.1` is taken by our publish, which has no install features | +| `@genclass/runtime-model` | none | **`0.1.0`** (no other choice) | pinned by `DEFAULT_MODEL_BASE_URL` and `DEFAULT_FROM` | +| `genclass-runtime` (alias, `packages/genclass-runtime`) | none | same version as `@genclass/runtime`, if published at all | its `dependencies` pins `@genclass/runtime` **exactly** (today `0.1.0-alpha.1`, which has no `init`), so it must be bumped together | + +Later: `@genclass/runtime@0.1.0` (no prerelease tag; OPEN_TASKS.md "Next"). Proposed: only after the beta has run on a real app (OPEN_TASKS.md, "Install on Polar Parts"). + +## What the next runtime release contains (since 806a296) + +From `git log 806a296..f107013` and `git diff 806a296 f107013 -- packages/runtime packages/genclass-runtime`: + +- **One-command install** (f3a9dd1, Mehar; owner INSTALL, `packages/runtime/INSTALL-NEEDS.md`): + - `init` / `remove` in `packages/runtime/bin/lib/{init,plan,detect,edit,ui}.mjs`; + - the `./auto`, `./auto/observe`, `./auto/guard` and `./auto/heal` exports (`src/auto.ts`, `src/cdn/auto-*.ts`); + - the script-tag build (`src/cdn/*`): `dist/genclass.global{,.min}.js` plus `dist/cdn/{worker,ort-wasm,ort-webgpu}.js`, from extra configs in `packages/runtime/tsup.config.ts`; + - the `sideEffects` list, and `unpkg` / `jsdelivr` fields pointing at `dist/genclass.global.min.js`; + - the unscoped alias `packages/genclass-runtime`; + - tests in `packages/runtime/test/install/*`. +- **Observe mode never holds or delays a delivery** (054da38). See `packages/runtime/src/runtime.ts`: + - `RuntimeImpl.deliveryHoldable` returns false in observe mode; + - `RuntimeImpl.runDelivery` then releases the delivery before any body read; + - the decision is still made in the background and recorded (`executed: false`, reason "observe mode never changes execution"); + - standing questions on `delivery` are answered; + - the delivery's own writes are not decided a second time (`RuntimeImpl.covered`). + + Tests: `packages/runtime/test/observe-delivery.test.ts`. +- **Redaction fixes** (f107013): + - `src/situation/content.ts` -> `contentFacts` uses `src/state/fields.ts` -> `redactedStringDiff`; + - `src/util.ts` -> `isSensitivePath` redacts numbers, bigints and arrays under a strong secret-named container. + + Tests: `packages/runtime/test/redaction-v2.test.ts`. Remaining gaps are in `packages/runtime/STATUS.md` and the runtime README's known limitations. +- A `situation()` purity regression test (29b7f28), the rewritten npm README (d05abc1), and more real apps (the eff18cb tree has 128 app manifests). +- **To merge first (not on this branch):** origin/runtime ca08174 (realapps wave 4), 6d6eb00 (REAL v2 data done), 416e374 (`r17-v2a` results) and 5bc40c9 (batch 6: model gate thresholds, no-baseline stall fallback, `runtime.gates()`, `training/fit_gates.py`). + +## Blockers for the runtime release + +From the 2026-10-08 install review (each finding was reproduced by a second reviewer). Most are user-visible and are listed in the runtime README's known limitations until fixed. + +| severity | where (`path` -> `symbol`) | problem | fix proposed by the review | +|---|---|---|---| +| high | `packages/runtime/bin/lib/plan.mjs` -> `AUTO`, `scriptTag`; `bin/lib/init.mjs` USAGE and the "Mode" row | `AUTO` and `scriptTag` treat `guard` as the default, but the runtime default is `observe` (`src/runtime.ts`: `o.mode ?? "observe"`). `init --mode guard` prints "Mode guard" and writes the bare `/auto` import (observe); the script tag gets no `data-mode`. `test/install/INSTALL-README-SNIPPET.md` still says guard is the default | `AUTO = (mode) => mode ? "@genclass/runtime/auto/" + mode : "@genclass/runtime/auto"`; emit `data-mode` whenever a mode is set; say `observe (default)`; add `cli.test.ts` cases for `--mode guard` and for no flag | +| medium | `packages/runtime/package.json` `version`; `packages/runtime/CHANGELOG.md` | The tree is `0.1.0-alpha.1`. A build bakes that into the global build (`tsup.config.ts` -> `globalBuild`, `__GENCLASS_VERSION__`), so `src/cdn/global.ts` -> `assetBase` and `bin/lib/plan.mjs` -> `scriptTag` point at alpha.1 on the CDN. That version has no `dist/cdn/*` and no global build. `init` would install `^0.1.0-alpha.1`, which has no `./auto` export. The CHANGELOG lists the install features under `0.1.0-alpha.1` | Step C3: bump, then rebuild; move those CHANGELOG bullets to the new version's section | +| medium | `packages/runtime/bin/lib/edit.mjs` -> `removeMarked` | A formatter that rewraps an inserted line (the dev-only devtools line; the one-line Next.js layout form) makes `remove` leave code that does not compile | start/end markers around multi-line insertions; `remove` checks its result and refuses if it looks broken | +| medium | `packages/runtime/package.json` `exports` | No `typesVersions`, so TypeScript with `"moduleResolution": "node"` (CRA TypeScript) cannot find the types of `/auto`, `/devtools` or `/react` (TS2307) after `init` | add `typesVersions` for every subpath; add a node10-resolution check | +| medium | `packages/runtime/bin/lib/detect.mjs` -> `detectProject` | Any esbuild, rollup, parcel or webpack dependency means "browser app", so `init` edits Node server and library entries | require evidence of a browser app (an HTML entry), else `manualHelp` | +| medium | `packages/runtime/bin/lib/plan.mjs` -> `integrityFor` | `--cdn <url>` gets the SRI hash of the CLI's own dist file whatever version the URL names, so the browser blocks the script | add SRI only for the default URL or one pinned to exactly this version; list `--no-sri` in USAGE | +| low | `bin/lib/edit.mjs` -> `removeMarked`; `bin/lib/init.mjs` -> `remove` | `remove` deletes user code inside marked blocks and created files, everything after a start marker whose end is lost, and any line containing `genclass:init` | hash created blocks; treat an unclosed block as an error; match markers exactly | +| low | `bin/lib/detect.mjs` -> `walkSources`; `bin/lib/init.mjs` -> `remove` | `remove` uninstalls the package while dot-folders (`.storybook`), `tmp`, `out` or `build` still import it, or when the user installed it before `init` | uninstall only what `init` installed; scan dot-folders | +| low | `packages/runtime/package.json` `sideEffects` | `./dist/worker.js` (the public `./worker` export, side effects only) is missing, so a bare `import "@genclass/runtime/worker"` bundles to nothing | **add** `./dist/worker.js` and **keep** `./src/model/worker.ts`; removing that entry empties `dist/cdn/worker.js` (reproduced by the reviewer) | +| low | `packages/runtime/src/cdn/config.ts` -> `readMetaConfig`; `bin/lib/plan.mjs` -> `integrityFor` | Every `<meta name="genclass">` in the document is read, including the body, and may set `ort` / `model` URLs. SRI covers only the loader, not the worker, ONNX glue or devtools it loads | read only `head > meta`; no remote URLs from meta; document what SRI covers | +| low | `bin/lib/init.mjs` -> `init`; `src/index.ts` -> `GenClass.init` | Re-running `init` with another `--mode` prints "Nothing to do"; a later `GenClass.init(options)` after `/auto` is silently ignored | compare the existing import with `AUTO(o.mode)` (after the `AUTO` fix); warn once on differing options | + +Also decide (INSTALL-NEEDS.md item 1): publish the `genclass-runtime` alias with this release, or drop `npx genclass-runtime` from the docs. The name is unregistered on npm. Until it is published by us, anyone can register it, and `npx genclass-runtime init` would then run their code. + +Runtime review findings still open (2026-10-08 review; see [Drift and open issues](#drift-and-open-issues)): the Redux/Zustand discard no-op, the 10 s discard mark, long `defer` on push channels, held WS/SSE messages after `close()`, and 502 described as "not processed". None of them affects observe mode, the default. Fix or accept them with the user and Mehar before the beta. The observe-mode holds and the two redaction leaks from the same review are fixed (054da38, f107013). ## Files | path | role in a release | |---|---| -| `packages/runtime/package.json` | `@genclass/runtime`, `version` `0.1.0-alpha.1` on `mvp-v2` (bumped in release commit 806a296, now the head of `mvp-v2`). `files`: `dist`, `bin`, `README.md`, `LICENSE`. No `prepublishOnly`, no `publishConfig`, no publish script | -| `package-lock.json` (root) | committed (b435acb). Records the workspace versions, so a version bump changes it. CI's `npm ci` fails if it is out of sync | -| `packages/runtime/README.md` | the npm page. Packed into the tarball, so it must be correct **before** packing | -| `packages/runtime/LICENSE` | Apache-2.0. Packed | -| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (`fetch-model`, `info`) and used here to validate model directories. Mode 100755 | -| `packages/runtime/test/smoke/smoke.sh` | packs the tarball, installs it into a fresh Vite 8 app, builds it, and loads it in headless Chromium (Playwright 1.63.0) | -| `packages/runtime/test/model/helpers.ts` | `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`, gitignored). `FIXTURES_FROM_MODEL` switches the parity fixtures to the model directory's own `requests.json`, `pack_fixtures.json` and `torch_fixtures.json` | -| `packages/runtime-model/MODEL_CARD.md` | the only tracked file of the model package. It still describes round 1 (situation-v1) | -| `packages/runtime-model/files/` | gitignored (`.gitignore` line `packages/runtime-model/files/`). Holds the model directory to pack. **Does not exist in this checkout**. `training/LOG.md` says round 1 R17 sits in `files/r17/` on Mehar's Mac only | -| `training/final_post.sh`, `training/export_runtime.py`, `training/pull_on_train.sh`, `training/deliver_final.sh`, `training/ortweb/validate.mjs` | TRAIN's eval -> export -> delivery -> onnxruntime-web check chain (Part B, step B1) | -| `demos/scripts/vm-eval.sh`, `demos/e2e/eval.ts`, `demos/src/shared/{types,genclass}.ts` | demos eval (Part B, step B6) | -| `.gitignore` | ignores `*.tgz` and `.publish/`, so packed tarballs never get committed | +| `packages/runtime/package.json` | `@genclass/runtime`, `version` `0.1.0-alpha.1` (not bumped since 806a296). `files`: `dist`, `bin`, `README.md`, `LICENSE`. `bin`: `genclass-runtime` only. No `prepublishOnly`, no `publishConfig` | +| `packages/genclass-runtime/package.json` | unscoped alias `genclass-runtime`, `version` `0.1.0-alpha.1`, `dependencies` `"@genclass/runtime": "0.1.0-alpha.1"` (exact). `bin` `genclass-runtime` -> `cli.mjs`, which imports `@genclass/runtime`'s `bin/genclass-runtime.mjs` | +| `package-lock.json` (root) | committed. Records both workspace versions and the alias's dependency, so a bump changes it. CI's `npm ci` fails if it is out of sync | +| `packages/runtime/README.md` | the npm page. Packed, so it must be correct **before** packing | +| `packages/runtime/CHANGELOG.md` | not packed. Its `0.1.0-alpha.1` section wrongly lists the install features | +| `packages/runtime/tsup.config.ts` | four configs: the main ESM build, the global build twice (plain and `.min`, with `__GENCLASS_VERSION__` from `package.json`), and `dist/cdn/*` | +| `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime/bin/lib/*.mjs` | CLI: `init`, `remove`, `fetch-model`, `info`. `bin/lib/init.mjs` reads the version from `package.json` at run time and hashes the local `dist/genclass.global*.js` for SRI | +| `packages/runtime/test/smoke/smoke.sh` | packs, installs the tarball into a fresh Vite 8 app, builds it, loads it in headless Chromium (Playwright 1.63.0) with `model: false`. It does not exercise `init`, `/auto` or the script tag | +| `packages/runtime/test/install/run-all.sh`, `cdn-check.mjs`, `frameworks.mjs`, `scaffold.sh` | install end-to-end: build, pack, CLI tests, script-tag and `/auto` checks in Chromium, real scaffolds through `init` / build / browse / `remove`. Runs on Mehar's VM ("the Mac never runs this"). Last run: against `0.1.0-alpha.0` (`test/install/RESULTS.md`), when `/auto` defaulted to guard | +| `packages/runtime/test/model/helpers.ts` | `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`, gitignored). `FIXTURES_FROM_MODEL` switches the parity fixtures to the export's own `requests.json`, `pack_fixtures.json`, `torch_fixtures.json` | +| `packages/runtime-model/MODEL_CARD.md` | the only tracked file of the model package. Still describes round 1 (situation-v1) | +| `packages/runtime-model/files/` | gitignored; holds the model directory to pack. Does not exist in this checkout | +| `training/v2_post.sh` (6d6eb00 on origin/runtime adds the real-app evals; this branch has the eff18cb version), `training/fit_gates.py` and `training/collect_gate_set.sh` (5bc40c9; not on this branch), `training/export_runtime.py`, `training/pull_on_train.sh`, `training/ortweb/validate.mjs` | TRAIN's eval -> export -> gates -> delivery -> onnxruntime-web check chain (B1) | +| `demos/scripts/vm-eval.sh`, `demos/e2e/eval.ts`, `demos/src/shared/{types,genclass}.ts` | demos eval (B7) | +| `.gitignore` | ignores `*.tgz` and `.publish/` | ## Concepts | term | meaning | |---|---| -| dist-tag | npm label pointing at one version. `latest` is what `npm i @genclass/runtime` installs. `alpha` and `beta` are opt-in: `npm i @genclass/runtime@alpha` | -| prerelease | a version with a `-` suffix (`0.1.0-alpha.1`, `0.1.0-beta.0`). npm 11 requires `--tag` to publish one | -| release worktree | a clean `git worktree` of the commit being released. The main checkout may hold other agents' uncommitted edits (on 2026-10-08 it had the uncommitted DL-7 fix in `packages/runtime/src/state/hub.ts` plus a new `test/atoms.test.ts` test; it ships only if committed before A2), and `tsup` bundles whatever is on disk | -| model export | the directory `training/export_runtime.py` writes: `model.json` (card `genclass-runtime-model/1`, with `bytes` and `sha256`), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU, `needs: shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, plus the parity files `parity.json`, `requests.json`, `pack_fixtures.json` and `torch_fixtures.json`. The fp32 reference in `ref/` is left out of the delivered tar | -| `ortweb_report_q8.json` | written into the export by `training/ortweb/validate.mjs <dir> q8 <n>`. It holds onnxruntime-web (WASM in Node) and onnxruntime-node logits compared with PyTorch, per backend: `argmax_agree`, `argmax_total`, `max_abs_logit`, `est_ms_at_seq_tokens`, `error` | +| dist-tag | npm label pointing at one version. `latest` is what `npm i @genclass/runtime`, `npx @genclass/runtime` and the unversioned jsDelivr URL resolve. `alpha` and `beta` are opt-in | +| prerelease | a version with a `-` suffix (`0.1.0-alpha.2`, `0.1.0-beta.0`). npm 11 requires `--tag` to publish one | +| release worktree | a clean `git worktree` of the commit being released. Other checkouts hold other agents' uncommitted edits (on 2026-10-08 this one had uncommitted `docs/agents/*` edits), and `tsup` bundles whatever is on disk | +| model export | the directory `training/export_runtime.py` writes: `model.json` (card `genclass-runtime-model/1`, with `bytes` and `sha256`), `<name>-q8.onnx` (WASM), `<name>-fp16.onnx` (WebGPU, `needs: shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, plus the parity files `parity.json`, `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`. `ref/` is left out of the delivered tar | +| `gate` (meta.json) | `{ report?, guard: { default, byTrigger? }, heal: { default, byTrigger? } }`, written by `training/fit_gates.py --write-meta <export>`, which also rewrites the card's sha256 for `meta.json`. Read only by a runtime with batch 6 (5bc40c9: `src/decide/policy.ts` -> `parseGate`, `effectiveGates`) | +| `ortweb_report_q8.json` | written into the export by `training/ortweb/validate.mjs <dir> q8 <n>`: onnxruntime-web (WASM in Node) and onnxruntime-node logits compared with PyTorch per backend (`argmax_agree`, `argmax_total`, `max_abs_logit`, `est_ms_at_seq_tokens`, `error`) | -Step markers used below: **[agent]** is light and allowed locally. **[ask first]** needs the user's OK in chat. **[user only]** is run by the user with their npm 2FA, or by Mehar on his Azure setup. +Step markers: **[agent]** is light and allowed locally. **[ask first]** needs the user's OK in chat. **[user only]** is run by the user with their npm 2FA, or by Mehar on his Azure setup. -## Part A: `@genclass/runtime@0.1.0-alpha.1` (now, no model) +## Part B: `@genclass/runtime-model@0.1.0` (first, once `r17-v2a` is validated) -### A0. Decisions for the user (before any work) - -1. **Publish alpha.1 at all?** It is optional (`OPEN_TASKS.md` "Needs the user" asks for it only for the NaN fix). Without a model it observes only. Nothing it decides can change an app. -2. **Dist-tag.** `--tag alpha` leaves `latest` on `0.1.0-alpha.0`. That build has the NaN crash, is situation-v1 and defaults to `guard`. To make plain `npm i @genclass/runtime` get the fix, the user can also move `latest` after the publish (step A7). -3. **Which commit and branch.** `mvp-v2` (b435acb plus the doc commits) is not pushed. Mehar's working branch is `origin/runtime` (74f17c0). The release commit and tag must reach `origin`, and the user picks the branch: push `mvp-v2`, or merge into `runtime` with Mehar. -4. **Known open issues.** The 2026-10-08 review found several issues; see [Drift and open issues](#drift-and-open-issues). None of them can change app behaviour in alpha.1, because no model exists and the default is `observe`. They go into the release notes, not the blocker list. Part B treats them as blockers. - -### A1. Fix what the tarball ships (docs) **[agent, edits owned by the docs task]** +### B0. Gates before packaging anything -The npm README is packed, so these must be committed before packing: +- **EVAL for the model being shipped.** `r17-v2a`'s numbers are in `docs/runtime/RESULTS.md` on origin/runtime (416e374), with FIR next to every recall. They must also go into `training/EVAL.md` (`HANDOFF.md` rule "Report honestly"). Targets (RESULTS.md §1): guard FIR ≤ 0.1% (met by `r17-v2a` on every set). Heal FIR ≤ 0.5%: met on `sim2e` (0.46%) and on the real-app set (0.00%), missed on `sim2f`, held-out app features (0.75%). Diagnosis ≥ 95% and clear-case recall ≥ 80%: not met. These are at the fixed 0.9 / 0.8 gates; fitted gates change FIR and recall, so measure again at them. +- **Fitted gates in the export.** `training/collect_gate_set.sh r17-v2a`, then `training/fit_gates.py ... --write-meta out/export-r17-v2a` (TRAIN, Azure). Check that `meta.json` has a `gate` object, and record the FIR and recall at those gates on the test sets. +- **Which model.** `r17-v2a` is the first situation-v2 R17. It was not distilled from a teacher and saw no real-app gold (`mix_v2a`: sim2 0.86, cur5 0.11, cur1 0.02, gen 0.01). The 150M teacher `t150-v2a` (ETA ≈ 08:30 UTC) and distillation come later. **Decision for the user and Mehar:** ship `r17-v2a` as the permanent `0.1.0`, or wait for the distilled model. Either way, only one model can ever be `0.1.0`. +- **Format.** Accept or resolve the drift listed in the TL;DR (f107013, 5bc40c9) before publishing. +- **Calibration source.** `training/v2_post.sh` calibrates on `sim2e` (`--calibration out/cal/$M-sim2e.json`), not the v1 set `simAe` that `training/final_post.sh` is tied to. Confirm that the export was made by `v2_post.sh`. `training/eval_runtime.py` caches logits by checkpoint and data *name*, so confirm that no stale cache was reused. +- **Version fields.** The npm package must be exactly `0.1.0` (pinned URL). The card's `version` is not checked by the runtime; `loader.ts` -> `cardId` (`name@version`) uses it as a cache key. Make it `0.1.0` anyway. `v2_post.sh`'s header example passes `2.0.0-rc1`, and the version actually used for `r17-v2a` is unverified. -- `packages/runtime/README.md`: - - status line: `0.1.0-alpha.0` becomes `0.1.0-alpha.1`; - - "Modes" table: already says `observe` is the default (matches `packages/runtime/src/runtime.ts`: `o.mode ?? "observe"`); re-check only the status/version text; - - it mentions `npx genclass-runtime fetch-model`; confirm the "none for this runtime yet" caveat is still present before packing (`DEFAULT_FROM` 404s and no v2 model exists). -- Root `README.md`: re-check the status box and alpha version (the default-mode text already says `observe`). +### B1. Get the export **[user only (Mehar) for the Azure side; ask first to copy it here: model download]** -Check: +1. On the model's rank-0 node, `training/v2_post.sh <M> <NAME> <VER>` (origin/runtime version) waits for the final checkpoint and then: + - evaluates `sim2e` and `sim2f`, the expected gain (`eval_gain.py`) and the real-app sets (`eval_real_sets.sh`, added in 6d6eb00); + - runs `export_runtime.py --ckpt models/<M> --out out/export-<M> --name <NAME> --version <VER> --calibration out/cal/<M>-sim2e.json`; + - tars `out/export-<M>` without `ref/` into `~/xfer/export-<M>.tar` and serves it on port 8801. -```sh -grep -n "(default)\|alpha\|fetch-model" packages/runtime/README.md README.md -``` + For `r17-v2a` it runs detached on c09. +2. Gates (B0) are written into the export, so they must come before the tar that is delivered. If the tar was made first, rebuild it. +3. On the `train` VM, `training/pull_on_train.sh <IP> <M> <ROUND> <SUB>` unpacks into `~/gcl/train-out/<ROUND>/<SUB>/`, checks every sha256 against `model.json`, and runs `ortweb/validate.mjs <dir> q8 120`. Round 1 used `~/gcl/train-out/final1/{r17,r32}/`. The v2 directory name is not decided (unverified). +4. Copy it to the release machine as `<repo>/.cache-model/` (gitignored; the model tests' default `GENCLASS_MODEL_DIR`). On Mehar's setup, `scripts/vm.sh get train-out <ROUND>/<SUB> .cache-model` should work (unverified). -### A2. Clean release worktree **[agent]** +Expected contents: `model.json`; `<NAME>-q8.onnx` and `<NAME>-fp16.onnx`; `tokenizer.json`, `calibration.json`, `meta.json` (with `gate`); `parity.json`, `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, `ortweb_report_q8.json`. -```sh -cd /Users/karanvirkhanna/GenClass-lib # the main checkout -git status --short # note other agents' edits; they must not be in the release -git worktree add -b release/runtime-0.1.0-alpha.1 ../GenClass-lib-release mvp-v2 -cd ../GenClass-lib-release -git log --oneline -1 # the commit being released (must include A1) -git status --porcelain # must print nothing -``` +### B2. Validate **[agent once the directory is here; ask first where marked]** -### A3. Pre-flight checks **[agent]** (all in the release worktree; same steps as `.github/workflows/ci.yml`) +Run in a worktree that has batch 6 merged, so the runtime reads `gate`: ```sh -npm ci --no-audit --no-fund # committed lockfile; on Linux prefix ONNXRUNTIME_NODE_INSTALL=skip as CI does -npm run typecheck -w @genclass/runtime # tsc -p tsconfig.json --noEmit over src/ -npm run build -w @genclass/runtime # tsup -> packages/runtime/dist (6 entries) +node packages/runtime/bin/genclass-runtime.mjs info .cache-model +node -e "const c=require('./.cache-model/model.json'); console.log(c.format, c.name, c.version, Object.keys(c.variants))" +node -e "console.log(JSON.stringify(require('./.cache-model/meta.json').gate))" cd packages/runtime -NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts -NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 -npm pack --dry-run +GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run test/model +GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts ``` -Expected at b435acb, with no `.cache-model`: +- **`info`** must exit 0: every file `sha256 ok`; `fp16*` marked "needs a WebGPU feature"; no `WARNING` lines; card `genclass-runtime-model/1` with variants `q8` and `fp16`. +- **Model unit tests.** With the export's fixtures, `FIXTURES_FROM_MODEL` is true, and the packer, engine and calibration tests compare the TypeScript side with the export's own PyTorch fixtures and `parity.json`. Without a model directory they skip (14 skips at f107013). Which tests still skip with a v2 export has not been checked (unverified). Read failures before dismissing them. +- **`ortweb_report_q8.json`:** for every backend, `argmax_agree` equals `argmax_total`, and there is no `error`. Note `est_ms_at_seq_tokens` for the model card. To re-run here **[ask first; installs onnxruntime-node/web in `training/ortweb`]**: `cd training/ortweb && npm install && node validate.mjs ../../.cache-model q8 120`. +- **Gates reach the runtime:** batch 6's `test/gates.test.ts` covers this with a stub. With the real model, check that `GenClass.runtime.gates()` reports `source.guard === "model"` in a page (next step). +- **Browser model specs [ask first; Playwright]:** `GENCLASS_MODEL_DIR=$PWD/../../.cache-model npm run test:browser`. `test/browser/model-helpers.ts` always loads the v0.1 fixtures from `test/fixtures/model/`, so the parity part of the first `model.spec.ts` test is expected to fail on a v2 model. The other specs do not depend on the model. -- the unit run reports "Test Files 40 passed | 1 skipped (41)" and "Tests 332 passed | 14 skipped (346)" at b435acb; if the release commit includes the `packages/runtime/src/state/hub.ts` DL-7 fix and its new `test/atoms.test.ts` test, expect "Tests 333 passed | 14 skipped (347)"; -- the perf run reports 4 passed; -- `npm pack --dry-run` lists 26 files: `LICENSE`, `README.md`, `bin/genclass-runtime.mjs`, `package.json` and 22 files under `dist/`. +### B3. Package **[agent]** -The 14 skips are model-parity tests that need a model directory. If counts differ, check for untracked `test/zz-*.test.ts` files from parallel agents; a fresh worktree has none. Node 25 prints an EBADENGINE warning for vitest 5, which is harmless. CI uses Node 22. +1. Fill `packages/runtime-model/files/` with **only** the card's files, flat (`model.json` directly in `files/`; `loader.ts` fetches `<baseUrl>model.json`): -### A4. Version bump **[agent]** - -```sh -cd ../GenClass-lib-release # repo root of the worktree -npm version 0.1.0-alpha.1 -w @genclass/runtime --no-git-tag-version -git diff --stat # expect packages/runtime/package.json and package-lock.json only -``` + ```sh + rm -rf packages/runtime-model/files && mkdir -p packages/runtime-model/files + cp .cache-model/{model.json,tokenizer.json,calibration.json,meta.json,<NAME>-q8.onnx,<NAME>-fp16.onnx} packages/runtime-model/files/ + node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files + cp packages/runtime/LICENSE packages/runtime-model/LICENSE + ``` -`npm version -w` updates both the workspace `package.json` and the root lockfile's `packages/runtime` entry. This was checked with npm 11.8.0 on a scratch monorepo. Nothing in `src/`, `dist/` or `bin/` embeds the version, so no rebuild is needed for the bump. Commit: +2. Create `packages/runtime-model/package.json`: -```sh -git add packages/runtime/package.json package-lock.json -git commit -m "release: @genclass/runtime 0.1.0-alpha.1 + ```json + { + "name": "@genclass/runtime-model", + "version": "0.1.0", + "description": "The GenClass runtime model for @genclass/runtime (situation-v2): q8 ONNX for WASM, fp16 ONNX for WebGPU, tokenizer, calibration and gate thresholds. Loaded from jsDelivr as the runtime's default model.", + "license": "Apache-2.0", + "repository": { "type": "git", "url": "git+https://github.com/daybot-solutions-inc/GenClass-lib.git", "directory": "packages/runtime-model" }, + "homepage": "https://github.com/daybot-solutions-inc/GenClass-lib#readme", + "files": ["files/", "MODEL_CARD.md"] + } + ``` -Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" -``` + `files/` stays gitignored but is packed: listing it in `files` overrides the ignore rule (checked with npm 11.8.0 on a scratch monorepo). +3. The new `package.json` makes it a workspace (root `workspaces: ["packages/*", "sim", "demos"]`). Run `npm install --no-audit --no-fund` to add it to `package-lock.json`, then `cd packages/runtime-model && npm pack --dry-run` (expect `LICENSE`, `MODEL_CARD.md`, `package.json` and the 6 `files/` entries). +4. Rewrite `MODEL_CARD.md` for the v2 model: numbers from `training/EVAL.md`, FIR next to every recall, the gates and what they were fitted on, sizes and latency from `parity.json` and `ortweb_report_q8.json`. +5. Commit `packages/runtime-model/{package.json,LICENSE,MODEL_CARD.md}` and `package-lock.json`. Never commit `files/`. Round 1's R17 was 9.58 MB (q8) plus 13.57 MB (fp16) (`training/LOG.md`). -### A5. Pack, and smoke-test the exact tarball +### B4. Publish the model **[user only]** ```sh -cd packages/runtime -bash test/smoke/smoke.sh # [ask first] Playwright + registry installs; prints "SMOKE OK: <path>/genclass-runtime-0.1.0-alpha.1.tgz" -# without the smoke test [agent]: -npm run build && npm pack # -> genclass-runtime-0.1.0-alpha.1.tgz in packages/runtime (gitignored *.tgz) -shasum -a 1 genclass-runtime-0.1.0-alpha.1.tgz # keep it; compare with dist.shasum after the publish +cd packages/runtime-model +npm pack # genclass-runtime-model-0.1.0.tgz (gitignored) +shasum -a 1 genclass-runtime-model-0.1.0.tgz +npm publish genclass-runtime-model-0.1.0.tgz --access public ``` -`smoke.sh` runs `npm run build` and `npm pack` itself, so the tarball it leaves behind is the one to publish. It needs Chromium for Playwright 1.63.0 (revision 1243) in the Playwright cache; this machine has `chromium-1243` and `chromium_headless_shell-1243` in `~/Library/Caches/ms-playwright`. It leaves a temp Vite app behind (`mktemp -d`). It asserts no page or console errors, a mounted `genclass-devtools` element, and `rt.history().length >= 3`. None of these depend on the mode (not re-run on `mvp-v2`). - -Optional **[agent, tell the user first: it is an `npm publish` invocation, but it uploads nothing]**: - -```sh -npm publish genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha --dry-run -``` +- `--access public` is required for a scoped package. No `--tag` is needed: `0.1.0` becomes `latest`. +- Whether `karanvir1729` (developer role in the `genclass` org) may create a new package in the scope is unverified. If npm refuses, `meharpro` (owner) publishes. +- **Irreversible.** Every runtime on the default URL starts loading this model, including the published `0.1.0-alpha.1` and `0.1.0-alpha.0` (both pin `@genclass/runtime-model@0.1.0/files/`; checked at tags `v0.1.0-alpha.1` and `v0.1.0-alpha.0`). + - alpha.1 defaults to observe, so it only reports. + - alpha.0 defaults to **guard**, holds store writes, and renders `situation-v1` text, which this model was not trained on. In apps still on alpha.0 it can act on that text. + - Consider `npm deprecate @genclass/runtime@0.1.0-alpha.0 "<message>"` **[user only]** before this publish. -### A6. Publish **[user only]** +### B5. GitHub release `runtime-model-v0.1.0` **[ask first; user's call]** -On a machine logged in to npm as `karanvir1729` or `meharpro` (`npm whoami`), from `packages/runtime` in the release worktree: +`fetch-model` resolves each card file as `new URL(file, from)`, so the assets must be the same six files, flat, with the card's names: ```sh -npm whoami -npm publish genclass-runtime-0.1.0-alpha.1.tgz --access public --tag alpha +git tag -a runtime-model-v0.1.0 -m "@genclass/runtime-model 0.1.0 (npm)" +git push origin runtime-model-v0.1.0 +gh release create runtime-model-v0.1.0 packages/runtime-model/files/* \ + -R daybot-solutions-inc/GenClass-lib --verify-tag --latest=false \ + --title "@genclass/runtime-model 0.1.0" --notes-file packages/runtime-model/MODEL_CARD.md ``` -npm asks for the 2FA code, or opens the browser; `--otp <code>` also works. Publishing the tarball file publishes exactly what was smoke-tested. Running `npm publish` without a file would pack again from whatever `dist/` holds. A version can never be republished, even after an unpublish. - -### A7. Optional: move `latest` **[user only, decision A0.2]** +### B6. Verify the CDN and the release ```sh -npm dist-tag add @genclass/runtime@0.1.0-alpha.1 latest +npm view @genclass/runtime-model dist-tags version dist.shasum dist.fileCount # [agent] shasum = B4's +curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ + | grep -i -E "^HTTP|access-control-allow-origin|content-type" # [agent] 200, CORS allowed +curl -fsS https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ + | diff - packages/runtime-model/files/model.json && echo "CDN card identical" # [agent] +# [ask first: model downloads] into a scratch directory +node packages/runtime/bin/genclass-runtime.mjs fetch-model <scratch>/gc-cdn --from https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/ +node packages/runtime/bin/genclass-runtime.mjs info <scratch>/gc-cdn +node packages/runtime/bin/genclass-runtime.mjs fetch-model <scratch>/gc-gh # default --from = DEFAULT_FROM +node packages/runtime/bin/genclass-runtime.mjs info <scratch>/gc-gh ``` -### A8. Verify **[agent]** - -```sh -npm view @genclass/runtime dist-tags # alpha: 0.1.0-alpha.1 (latest: alpha.0 or alpha.1 per A7) -npm view @genclass/runtime@0.1.0-alpha.1 version dist.shasum dist.fileCount # shasum = A5's; fileCount 26 -T=$(mktemp -d) && cd "$T" && npm init -y >/dev/null \ - && npm i --no-audit --no-fund @genclass/runtime@0.1.0-alpha.1 \ - && node -e "import('@genclass/runtime').then(m => console.log(Object.keys(m).length, m.DEFAULT_MODEL_BASE_URL))" \ - && npx genclass-runtime --help | head -3 -``` +### B7. Demos eval: Off / Observe / Guard **[ask first; Mehar's VM; two code changes first]** -The import check works in Node: it was checked against the workspace build, which exports 30 names. The registry may take a minute to show the new version. +Does the shipped default (`observe` with the model) or `guard` make the six demos worse than the baseline, and what does guard fix? Never tune the demos for a result (`HANDOFF.md`). -### A9. Tag, push, GitHub release **[ask first for every push; `gh release` is the user's call]** +Prerequisites (code changes, not done on this branch): -These follow the `0.1.0-alpha.0` precedent: an annotated tag "@genclass/runtime 0.1.0-alpha.0 (npm)", and a GitHub pre-release with the `.tgz` as an asset. +1. **`demos/src/server/data/cities.ts` is missing from git** (the root `.gitignore` rule `data/` ignores it). Recreate it with `searchCities(q)` and `TYPED_TARGETS` (see [docs/agents/demos.md](docs/agents/demos.md)), and add it with `git add -f` or narrow the rule. +2. **An `observe` demo mode.** `GcMode` in `demos/src/shared/types.ts` is `"off" | "guard" | "heal"`, and demo **Off** = `GenClass.init({ mode: "observe", model: false })` (`demos/src/shared/genclass.ts` -> `startGenClass`). Add `"observe"` to `GcMode` and `MODES`, `demos/e2e/eval.ts` -> `ALL_MODES`, and the `MODE_LABEL` / `MODE_HINT` records in `demos/src/site/demo-page.ts` and `demos/src/site/trials-panel.ts`. ```sh -cd ../GenClass-lib-release # repo root of the worktree -git tag -a v0.1.0-alpha.1 -m "@genclass/runtime 0.1.0-alpha.1 (npm)" -git push origin release/runtime-0.1.0-alpha.1 # or the branch agreed in A0.3 -git push origin v0.1.0-alpha.1 -gh release create v0.1.0-alpha.1 packages/runtime/genclass-runtime-0.1.0-alpha.1.tgz \ - -R daybot-solutions-inc/GenClass-lib --verify-tag --prerelease \ - --title "@genclass/runtime 0.1.0-alpha.1" --notes-file <notes.md> +scripts/vm.sh run demos 'GENCLASS_MODEL_URL=cdn setsid nohup bash demos/scripts/vm-eval.sh --modes off,observe,guard --tag runtime-model-0.1.0 > ~/gcl/logs/demos-eval.log 2>&1 < /dev/null &' ``` -Release notes, compared with `0.1.0-alpha.0`: - -- NaN in app state no longer recurses forever (`test/nan.test.ts`); -- the default mode is `observe` (was `guard`; `guard` is opt-in and `heal` is experimental); -- decisions happen at the network boundary (`delivery` trigger), and store writes are not held by default (`policy.holdWrites`); -- EventSource is observed; -- synthetic DOM events are ignored unless `observe: { untrustedEvents: true }` is set; -- the situation format is v2; -- no model is published yet, so the runtime only observes; -- known issues: list the open review findings from [Drift](#drift-and-open-issues). - -Then bring the release commit back to `mvp-v2`: `git -C /Users/karanvirkhanna/GenClass-lib merge --ff-only release/runtime-0.1.0-alpha.1`. If other agents' uncommitted edits touch the same files, the merge refuses: commit or stash them first, with the user's say. Then remove the worktree: `git worktree remove ../GenClass-lib-release`. +`GENCLASS_MODEL_URL=cdn` loads the published package. Results go to `demos/results-runtime-model-0.1.0.{json,md}`; record them in `docs/runtime/RESULTS.md` §5. **Gate for Part C:** on clean runs, Observe and Guard introduce no bugs that Off does not have; report every fix count with its false interventions. -### A10. Bookkeeping **[agent]** +## Part C: `@genclass/runtime@0.1.0-beta.0` (or `0.1.0-alpha.2` without the model) -Update every place that still lists `0.1.0-alpha.0` as latest or alpha.1 as pending: +Replace `0.1.0-beta.0` with `0.1.0-alpha.2` throughout if it goes out before Part B. -- `OPEN_TASKS.md`: move "Needs the user: Patch release `0.1.0-alpha.1`" to "Done"; -- `HANDOFF.md`: the "Current state" npm row; -- `AGENTS.md`: the npm line; -- `docs/agents/runtime/build-test-release.md`: "Publish history"; -- `docs/agents/status-and-known-issues.md`. +### C0. Decisions for the user (and Mehar) -Find them with `git grep -n "0.1.0-alpha" -- '*.md'`. +1. **Version:** `0.1.0-beta.0` (with the model) or `0.1.0-alpha.2` (before it). +2. **Format drift** (TL;DR): accept f107013 and 5bc40c9 against a model trained on `situation-v2`, or tag and regenerate. +3. **Which blockers to fix** (table above). At least the high-severity `init --mode` mapping and the version bump. Every fix to `bin/lib/*` needs a `cli.test.ts` case. +4. **Alias:** publish `genclass-runtime` too, or remove `npx genclass-runtime` from the README. +5. **Branch:** the release commit must reach `origin`. This branch (`mvp-v2-merge`) and `mvp-v2` (806a296, tag `v0.1.0-alpha.1` local only) are not pushed. -## Part B: model package, then `@genclass/runtime@0.1.0` (after a situation-v2 model exists) +### C1. Merge and docs **[agent]** -Order from `HANDOFF.md` "How to continue": v2 data, then the teacher, then distillation (R17 default, R32), then DAgger via SIM `--on-policy`, then EVAL, then **`@genclass/runtime-model@0.1.0`**, then the demos rerun, then **`@genclass/runtime@0.1.0`**. Everything up to EVAL is TRAIN's work on Azure (Mehar). Nobody on our side touches it. - -### B0. Gates before packaging anything - -- **EVAL exists for a situation-v2 model.** It must be in `training/EVAL.md` and `docs/runtime/RESULTS.md`, with the false-intervention rate (guard and heal) next to every recall number (`HANDOFF.md` rule "Report honestly"). The default is R17 (`HANDOFF.md`, round-1 choice in `training/LOG.md`). Choosing R32 for WebGPU is a separate user decision (`OPEN_TASKS.md` item 9). -- **TRAIN's post-processing is v2-correct.** `training/final_post.sh` is hard-wired to the situation-v1 eval set `simAe`: it runs `eval_sim.sh simAe`, uses `--calibration out/cal/$M-simAe.json`, and uses `--data-rows data/simAe/dev.jsonl,...`. It also does not stop when an eval fails (`set -u` only). `training/eval_runtime.py` caches logits by checkpoint and data *name* only. Unless these are fixed (TRAIN/Mehar), the export's `calibration.json` can be fitted on v1 situations or on stale logits. Confirm which eval set and which checkpoint the calibration came from before trusting the export. -- **Version.** The card's `version` must be `0.1.0`, and the npm package version must be exactly `0.1.0`, because `DEFAULT_MODEL_BASE_URL` pins `@0.1.0`. Any other version also needs a code change in `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`, and therefore a runtime release. - -### B1. Get the export **[user only (Mehar) for the Azure side; ask first to copy it here: model download]** - -TRAIN's chain, from the scripts: - -1. On the model's rank-0 node, `bash training/final_post.sh <M> <NAME> <VER>` (header example: `final_post.sh r17-final1 genclass-runtime-r17 1.0.0-rc1`). For the v2 release, use `<NAME>` = `genclass-runtime-r17` and `<VER>` = `0.1.0`. The script: - - runs the SIM eval and fits the temperatures; - - runs `training/export_runtime.py --ckpt models/<M> --out out/export-<M> --name <NAME> --version <VER> --calibration ...`; - - touches `out/.post-done-<M>`; - - tars `out/export-<M>` without `ref/` into `~/xfer/export-<M>.tar` and serves it on port 8801. -2. On the `train` VM, `training/pull_on_train.sh <IP> <M> <ROUND> <SUB>` (or `training/deliver_final.sh <M> <NODE> <ROUND> <SUB>` from the Mac) does the following: - - unpacks the tar into `~/gcl/train-out/<ROUND>/<SUB>/`; - - checks every file's sha256 against `model.json`; - - runs `ortweb/validate.mjs <dir> q8 120`, which writes `ortweb_report_q8.json` there. - - Round 1 landed in `~/gcl/train-out/final1/{r17,r32}/`. The v2 round's directory name is not decided yet (unverified). -3. Copy it to the release machine as `<repo>/.cache-model/`. That path is gitignored, and it is the default `GENCLASS_MODEL_DIR` of the model tests. On Mehar's setup, `scripts/vm.sh get` copies from `~/gcl/<SLOT>/<REMOTE>`, so `scripts/vm.sh get train-out <ROUND>/<SUB> .cache-model` should work (unverified; it needs his hosts file and key). - -Expected contents, from `export_runtime.py`: - -- `model.json`; -- `genclass-runtime-r17-q8.onnx` and `genclass-runtime-r17-fp16.onnx`; -- `tokenizer.json`, `calibration.json`, `meta.json`; `meta.json`'s `name` is `genclass-runtime-r17-0.1.0`; -- `parity.json`, `requests.json`, `pack_fixtures.json`, `torch_fixtures.json`, `ortweb_report_q8.json`. +- Merge origin/runtime (5bc40c9 or later), resolve, `npm install --no-audit --no-fund` if the lockfile changed, and run C2. +- `packages/runtime/README.md`: + - status: the model is published, and what it measures; + - "Modes": what observe, guard and heal do *with* the model and its gates (batch 6 adds `rt.gates()`); + - the install section loses "Next release"; + - known limitations: drop what the blockers fixed. +- `packages/runtime/CHANGELOG.md`: a `## 0.1.0-beta.0` section with the install features, 054da38, f107013 and batch 6. The `0.1.0-alpha.1` section keeps only what was published (NaN fix, situation-v2 runtime, observe default, docs). +- `test/install/INSTALL-README-SNIPPET.md`: observe is the default. -### B2. Validate **[agent once the directory is here; ask first where marked]** +### C2. Clean release worktree and pre-flight **[agent]** ```sh -cd /Users/karanvirkhanna/GenClass-lib # or the release worktree -node packages/runtime/bin/genclass-runtime.mjs info .cache-model -node -e "const c=require('./.cache-model/model.json'); console.log(c.format, c.name, c.version, Object.keys(c.variants))" +git worktree add -b release/runtime-0.1.0-beta.0 ../GenClass-lib-release-beta <release-branch> +cd ../GenClass-lib-release-beta && git status --porcelain # must print nothing +npm ci --no-audit --no-fund # on Linux: ONNXRUNTIME_NODE_INSTALL=skip, as CI does +npm run typecheck -w @genclass/runtime +npm run build -w @genclass/runtime cd packages/runtime -GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run test/model -GENCLASS_MODEL_DIR=$PWD/../../.cache-model NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" +NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts +NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 +npm pack --dry-run ``` -- **`info`** must exit 0: - - every listed file reads `sha256 ok`; - - `fp16*` is marked "needs a WebGPU feature"; - - there are no `WARNING` lines (the graph check is "any fp16 tensor -> needs: shader-f16"); - - the card prints `genclass-runtime-model/1`, name `genclass-runtime-r17`, version `0.1.0`, and variants `q8` and `fp16`. -- **Model unit tests.** Because the export contains `requests.json`, `pack_fixtures.json` and `torch_fixtures.json`, `FIXTURES_FROM_MODEL` is true. The packer, engine and calibration tests then compare the TypeScript packer and ONNX engine (onnxruntime-node CPU, and onnxruntime-web WASM in Node) with the export's own PyTorch fixtures and its `parity.json`. Without a model directory these tests skip (14 skips). With one, they should run. Which ones stay skipped, and whether the py-fixture cases tied to the v0.1 tokenizer still pass, has not been checked on any v2 export (unverified). Read failures before dismissing them. -- **`ortweb_report_q8.json`.** For every backend in `results`: `argmax_agree` equals `argmax_total`, and there is no `error`. Note `est_ms_at_seq_tokens`, the latency for the model card. Round 1 got 233/233 decisions on both runtimes (`training/LOG.md`). To re-run it here **[ask first; installs onnxruntime-node/web in `training/ortweb`]**: `cd training/ortweb && npm install && node validate.mjs ../../.cache-model q8 120`. -- **Browser model specs [ask first; Playwright]:** `GENCLASS_MODEL_DIR=$PWD/../../.cache-model npm run test:browser` in `packages/runtime`. Caveat (from the code, not run): `test/browser/model-helpers.ts` always loads the **v0.1** `requests50.json`, `pack_fixtures.json` and `torch_fixtures.json` from `test/fixtures/model/`. It has no `FIXTURES_FROM_MODEL` switch, so the parity part of the first `model.spec.ts` test ("loads over WASM ... matches PyTorch ...") is expected to fail on a v2 model. The other specs (fallbacks, preload modes, WebGPU probe, latency) are model-agnostic. To make that test meaningful, teach `model-helpers.ts` to use the export's fixtures. +Mind the disk: a worktree plus `npm ci` needs several hundred MB. On 2026-10-08 this machine had under 3 GB free, and `/Users/karanvirkhanna/GenClass-lib-release` (the alpha.1 worktree) still exists. Remove it first (`git worktree remove ../GenClass-lib-release`) once nobody needs it. -### B3. Package `@genclass/runtime-model@0.1.0` **[agent]** +Measured at f107013 (version still `0.1.0-alpha.1`): -1. Fill `files/` with **only** the card's files, flat. `model.json` must sit directly in `files/`, because the runtime fetches `<baseUrl>model.json` (`packages/runtime/src/model/loader.ts`). Remove anything else, especially a leftover `files/r17/` (the situation-v1 round-1 model). - - ```sh - cd /Users/karanvirkhanna/GenClass-lib - rm -rf packages/runtime-model/files && mkdir -p packages/runtime-model/files - cp .cache-model/{model.json,tokenizer.json,calibration.json,meta.json,genclass-runtime-r17-q8.onnx,genclass-runtime-r17-fp16.onnx} packages/runtime-model/files/ - node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files - cp packages/runtime/LICENSE packages/runtime-model/LICENSE - ``` +- unit run: "Test Files 44 passed | 1 skipped (45)", "Tests 375 passed | 14 skipped (389)"; +- perf: 4 passed; +- `npm pack --dry-run`: 52 files, 1.1 MB packed, 4.2 MB unpacked. That includes `dist/genclass.global.min.js` (254.5 kB; 86 kB gzip) and `dist/cdn/{worker,ort-wasm,ort-webgpu}.js` (16 / 24 / 39 kB gzip). -2. Create `packages/runtime-model/package.json`: +With batch 6 merged, the counts change. Batch 6 alone reported 45 files and 375 tests on the VM, without our two fixes. Write down the new numbers here. - ```json - { - "name": "@genclass/runtime-model", - "version": "0.1.0", - "description": "The GenClass runtime model for @genclass/runtime (situation-v2): q8 ONNX for WASM, fp16 ONNX for WebGPU, tokenizer and calibration. Loaded from jsDelivr as the runtime's default model.", - "license": "Apache-2.0", - "repository": { - "type": "git", - "url": "git+https://github.com/daybot-solutions-inc/GenClass-lib.git", - "directory": "packages/runtime-model" - }, - "homepage": "https://github.com/daybot-solutions-inc/GenClass-lib#readme", - "files": ["files/", "MODEL_CARD.md"] - } - ``` +### C3. Version bump, then rebuild **[agent]** - `files/` stays gitignored but **is packed**. Listing it in `files` overrides the ignore rule; this was checked with npm 11.8.0 on a scratch monorepo with the same `.gitignore` line, from the package directory and with `-w`. npm always adds `package.json`, `LICENSE` and any `README*`. With no README the npm page shows none, so optionally add a short `README.md` that links to `MODEL_CARD.md`. +```sh +npm version 0.1.0-beta.0 -w @genclass/runtime -w genclass-runtime --no-git-tag-version +# then set packages/genclass-runtime/package.json dependencies["@genclass/runtime"] to "0.1.0-beta.0" (npm version leaves it) +npm install --no-audit --no-fund # resync the lockfile's alias dependency +git diff --stat # expect the two package.json files and package-lock.json only +npm run build -w @genclass/runtime # required: the global build bakes the version +grep -o '0\.1\.0-[a-z]*\.[0-9]*' packages/runtime/dist/genclass.global.min.js | sort -u # expect only the new version +``` -3. The new `package.json` makes `packages/runtime-model` a workspace (root `workspaces: ["packages/*"]`). Update and commit the lockfile, or CI's `npm ci` fails: +Unlike alpha.1, **the version is in the build**: `tsup.config.ts` -> `globalBuild` defines `__GENCLASS_VERSION__`, which `src/cdn/global.ts` -> `assetBase` uses for every CDN URL. `init` writes `^<version>` and a CDN URL pinned to `<version>`, and hashes the local `dist/genclass.global*.js` for SRI. So pack only after the rebuild. The `-w genclass-runtime` form and the lockfile step for the alias are unverified; check the diff. Commit: - ```sh - npm install --no-audit --no-fund # adds packages/runtime-model to package-lock.json - cd packages/runtime-model && npm pack --dry-run # expect LICENSE, MODEL_CARD.md, package.json + the 6 files/ entries - ``` +```sh +git add packages/runtime/package.json packages/genclass-runtime/package.json package-lock.json +git commit -m "release: @genclass/runtime 0.1.0-beta.0 -4. Rewrite `packages/runtime-model/MODEL_CARD.md` for the v2 model. It still says "final round 1 on the frozen runtime (situation-v1)" and quotes round-1 numbers. Take the numbers from the v2 `training/EVAL.md`. Keep false-intervention rates next to recall. Give the sizes and latencies from `parity.json` and `ortweb_report_q8.json`. -5. Commit `packages/runtime-model/{package.json,LICENSE,MODEL_CARD.md}` and `package-lock.json` (never `files/`). The npm package size is about 23 MB for R17 (round-1 q8 9.58 MB plus fp16 13.57 MB). Whether jsDelivr's npm size limit matters for adding R32 too is unverified. `training/LOG.md` only notes that "R32 + R17 would exceed 60 MB". +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` -### B4. Publish the model **[user only]** +### C4. Pack and smoke-test the exact tarball ```sh -cd packages/runtime-model -npm pack # genclass-runtime-model-0.1.0.tgz (gitignored) -shasum -a 1 genclass-runtime-model-0.1.0.tgz -npm publish genclass-runtime-model-0.1.0.tgz --access public +cd packages/runtime +npm run build && npm pack # [agent] genclass-runtime-0.1.0-beta.0.tgz (gitignored) +shasum -a 1 genclass-runtime-0.1.0-beta.0.tgz +bash test/smoke/smoke.sh # [ask first] Playwright; packs again, prints "SMOKE OK: <tgz>" ``` -- `--access public` is required: scoped packages default to restricted. -- No `--tag` is needed: `0.1.0` is not a prerelease, and it becomes `latest`. -- `karanvir1729` has the developer role in the `genclass` org. Whether that role may *create* a new package in the scope is unverified. If npm refuses, `meharpro` (owner) publishes. -- **This publish is irreversible:** `0.1.0` can never be reused, and every runtime that uses the default URL loads it. - -### B5. GitHub release `runtime-model-v0.1.0` **[ask first; user's call]** +- `smoke.sh` runs `npm run build` and `npm pack` itself; publish the tarball it leaves. It uses `model: false` and does not cover `init`, `/auto` or the script tag. +- **Install end-to-end [ask first; Mehar's VM]:** `bash test/install/run-all.sh` (`cdn-check.mjs` plus the real scaffolds). Its last results (`test/install/RESULTS.md`) are from `0.1.0-alpha.0`, when `/auto` meant guard. Re-run it on the beta tarball and update RESULTS.md. +- **Smoke with the model [ask first]:** a page built from the tarball, default `GenClass.init()`. Expect `GenClass.runtime.status.state === "ready"`, the card's model and version in the status, `status.variant` `q8` (WASM) or `fp16` (WebGPU), and `GenClass.runtime.gates().source.guard === "model"` (batch 6). +- Optional **[agent; tell the user first: it is an `npm publish` call that uploads nothing]**: `npm publish genclass-runtime-0.1.0-beta.0.tgz --access public --tag beta --dry-run`. -`fetch-model` resolves each card file as `new URL(file, from)`. The assets must therefore be the same six files, flat, with exactly the card's names: +### C5. Publish **[user only]** ```sh -git tag -a runtime-model-v0.1.0 -m "@genclass/runtime-model 0.1.0 (npm)" -git push origin runtime-model-v0.1.0 -gh release create runtime-model-v0.1.0 packages/runtime-model/files/* \ - -R daybot-solutions-inc/GenClass-lib --verify-tag --latest=false \ - --title "@genclass/runtime-model 0.1.0" --notes-file packages/runtime-model/MODEL_CARD.md +npm whoami +npm publish genclass-runtime-0.1.0-beta.0.tgz --access public --tag beta +npm dist-tag add @genclass/runtime@0.1.0-beta.0 latest # so npx @genclass/runtime init and the script tag get it +# alias, if C0.4 says so (from packages/genclass-runtime, after the runtime is on npm): +npm pack && npm publish genclass-runtime-0.1.0-beta.0.tgz --access public --tag beta && npm dist-tag add genclass-runtime@0.1.0-beta.0 latest ``` -### B6. Verify the CDN and the release +A version can never be republished, even after an unpublish. Publish the checked tarball, never a bare `npm publish`. + +### C6. Verify **[agent]** ```sh -npm view @genclass/runtime-model dist-tags version dist.shasum dist.fileCount # [agent] shasum = B4's -curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ - | grep -i -E "^HTTP|access-control-allow-origin|content-type" # [agent] 200, CORS allowed -curl -fsS https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ - | diff - packages/runtime-model/files/model.json && echo "CDN card identical" # [agent] -# [ask first: model downloads] end-to-end bytes + sha256 from both sources, then the card check -node packages/runtime/bin/genclass-runtime.mjs fetch-model /tmp/gc-cdn --from https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/ -node packages/runtime/bin/genclass-runtime.mjs info /tmp/gc-cdn -node packages/runtime/bin/genclass-runtime.mjs fetch-model /tmp/gc-gh # default --from = DEFAULT_FROM (the GitHub release) -node packages/runtime/bin/genclass-runtime.mjs info /tmp/gc-gh +npm view @genclass/runtime dist-tags # beta and latest: 0.1.0-beta.0 +npm view @genclass/runtime@0.1.0-beta.0 version dist.shasum dist.fileCount # shasum = C4's +curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.0/dist/genclass.global.min.js | head -1 # 200 +curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.0/dist/cdn/worker.js | head -1 # 200 ``` -`fetch-model` checks bytes and sha256 against the remote card and writes a normalised `model.json`. `info` checks again and exits 1 on any mismatch. Use a scratch directory instead of `/tmp` when the agent's rules require it. - -### B7. Demos eval: Off / Observe / Guard **[ask first; runs on Mehar's VM; needs two code changes first]** - -What it answers: does the shipped default (`observe` with the model) or `guard` make the six demos worse than the baseline, and what does guard fix? The demos are honest evaluation: never tune them for a result (`HANDOFF.md`). +Then, in a scratch directory **[agent]**: `npm init -y`, `npm i @genclass/runtime@0.1.0-beta.0`, an import check, and `npx @genclass/runtime init --dry-run --yes` on a scratch Vite project. It must print `npm install @genclass/runtime@^0.1.0-beta.0`. -Prerequisites (code changes, not done at b435acb): - -1. **`demos/src/server/data/cities.ts` is missing from git.** The root `.gitignore` rule `data/` ignores it. The search world, scenario and oracle import it, so a fresh clone cannot build the demos. Recreate it with the exports `searchCities(q)` and `TYPED_TARGETS` (see [docs/agents/demos.md](docs/agents/demos.md)), and add it with `git add -f` or narrow the ignore rule. -2. **An `observe` demo mode.** - - `GcMode` in `demos/src/shared/types.ts` is `"off" | "guard" | "heal"`. Today demo **Off** = `GenClass.init({ mode: "observe", model: false })` (`demos/src/shared/genclass.ts` -> `startGenClass`). - - Add `"observe"` to `GcMode` and `MODES`, `demos/e2e/eval.ts` -> `ALL_MODES`, and the `MODE_LABEL`/`MODE_HINT` records in `demos/src/site/demo-page.ts` and `demos/src/site/trials-panel.ts`; `tsc` flags any `Record<GcMode, ...>` you miss. - - `startGenClass` already passes any non-off mode through as `GenClass.init({ mode, model: { baseUrl, preload: "eager" } })`, so `observe` gets the model loaded. - - While there, fix the stale "guard (the default)" comment in `genclass.ts`. - -Run (from `demos/scripts/vm-eval.sh`'s header; arguments pass through to `e2e/eval.ts`): +### C7. Tag, push, GitHub release **[ask first for every push; `gh release` is the user's call]** ```sh -scripts/vm.sh run demos 'GENCLASS_MODEL_URL=cdn setsid nohup bash demos/scripts/vm-eval.sh --modes off,observe,guard --tag runtime-model-0.1.0 > ~/gcl/logs/demos-eval.log 2>&1 < /dev/null &' +git tag -a v0.1.0-beta.0 -m "@genclass/runtime 0.1.0-beta.0 (npm)" +git push origin <release-branch> && git push origin v0.1.0-beta.0 +gh release create v0.1.0-beta.0 packages/runtime/genclass-runtime-0.1.0-beta.0.tgz \ + -R daybot-solutions-inc/GenClass-lib --verify-tag --prerelease \ + --title "@genclass/runtime 0.1.0-beta.0" --notes-file <notes.md> ``` -- `GENCLASS_MODEL_URL=cdn` makes the pages load the runtime's default URL, which tests the published package itself. `GENCLASS_MODEL_FROM=https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` serves a local copy instead. -- The results go to `demos/results-runtime-model-0.1.0.{json,md}`. -- Gate for B8: on clean runs, Observe and Guard introduce no bugs that Off does not have. Report every fixed count with its false interventions. -- Record the result in `docs/runtime/RESULTS.md` §5 (it currently holds the v0.1-model baseline). +Release notes, compared with `0.1.0-alpha.1`: -### B8. `@genclass/runtime@0.1.0-beta.0` or `0.1.0` **[same steps as Part A]** +- the first situation-v2 model (`@genclass/runtime-model@0.1.0`) and its measured numbers, with FIR; +- the model's own gate thresholds (batch 6); +- one-command install (`init` / `remove`), the `/auto` entries, the script tag; +- observe mode never holds or delays a response, and its delivery decisions are recorded; +- the F2 and container redaction fixes; +- the no-baseline stall fallback; +- known issues: the remaining blockers and the open runtime findings. -Blockers to clear or explicitly accept with the user and Mehar first: +### C8. Bookkeeping **[agent]** -- the high-severity review findings: the F2 redaction bypass, the redactor regression, and the redux/zustand discard no-op; -- the observe-mode delivery holds, which affect the default. +Update every place that lists `0.1.0-alpha.1` as latest or the model as unpublished. Find them with `git grep -n "0.1.0-alpha\|runtime-model" -- '*.md'`. That includes: -All are listed in [Drift](#drift-and-open-issues). Fixes under `packages/runtime/src/situation/*` change the model's input. They mean a new frozen tag after `situation-v2` and regenerated data, so coordinate with Mehar (`HANDOFF.md` "The training format is frozen"). +- `OPEN_TASKS.md` ("Next" items for the model package and the next prerelease; "Needs the user"); +- `HANDOFF.md`; +- `AGENTS.md`; +- `docs/agents/runtime/build-test-release.md` ("Publish history"); +- `docs/agents/status-and-known-issues.md`; +- `docs/runtime/API.md` and `docs/runtime/CONTRACT.md`; +- both READMEs. -Then repeat A1–A10 with: +## Part A (done): `@genclass/runtime@0.1.0-alpha.1` -- **README status:** the model is published; the "Modes" table says what observe, guard and heal do *with* the model. -- **Version:** - - `npm version 0.1.0-beta.0 -w @genclass/runtime --no-git-tag-version`, published with `--tag beta`; optionally `npm dist-tag add @genclass/runtime@0.1.0-beta.0 latest`; - - **or** `npm version 0.1.0 -w @genclass/runtime --no-git-tag-version`, published with **no** `--tag`. It becomes `latest`, because no non-prerelease version exists yet (npm 11.8.0 leaves prereleases out of its "higher version" check). -- **Smoke with the model [ask first]:** in a page built from the tarball, `GenClass.init()` (default `observe`) should reach `GenClass.runtime.status.state === "ready"`, with `status.model`/`status.version` from the CDN card and `status.variant` `q8` (WASM) or `fp16` (WebGPU). `smoke.sh` passes `model: false`, so this check needs a variant of it, or the demos. -- **Tag:** `v0.1.0-beta.0` or `v0.1.0`. Make it a GitHub pre-release only for the beta. -- **Bookkeeping:** `OPEN_TASKS.md` item 11 (and item 9 for the model) to "Done"; `HANDOFF.md` npm/model rows; `packages/runtime/README.md`, `docs/runtime/API.md` and `docs/runtime/CONTRACT.md` where they say no model is published. +- **Published** 2026-10-08 05:33 UTC by `karanvir1729` under dist-tag `latest` (planned `alpha`). The first attempt got a 403 (no 2FA on the account); after 2FA it went through browser approval. +- **Source:** release commit 806a296 on `mvp-v2`; local annotated tag `v0.1.0-alpha.1`, not pushed; built in the worktree `/Users/karanvirkhanna/GenClass-lib-release` (branch `release/runtime-0.1.0-alpha.1`). +- **Tarball:** 26 files, 486.8 kB; shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff (`npm view` agrees: `dist.fileCount` 26, unpacked 1,967,322 bytes). +- **Contents:** the NaN fix (ad24804), the situation-v2 runtime (batch 4 fcd1e68, batch 5 6e5e86e), the `observe` default (f3636b2) and docs. No `./auto` exports, no `dist/cdn/*`, no global build, and no `init` in `bin/genclass-runtime.mjs`. +- **Still to do:** push `mvp-v2` and the tag (user). There is no GitHub release for alpha.1. ## Invariants and gotchas -- **Publish only tarballs you checked.** Run `npm publish <file>.tgz`, not a bare `npm publish`. A bare publish packs again from the current `dist/`, and `tsup`'s `clean: true` means a failed build leaves a half-empty `dist/`. -- **Build from a clean tree.** The main checkout can hold other agents' uncommitted runtime edits; use the release worktree (A2). -- **Never commit `files/` or `*.tgz`.** Both are gitignored. The model package is reproducible only from the export, so keep the export directory (and its sha256s in `model.json`) on the train VM. -- **Lockfile.** A version bump or a new workspace changes `package-lock.json`. Commit it in the same commit, or CI's `npm ci` fails. -- **Dist-tags.** A prerelease without `--tag` is refused (npm 11). A non-prerelease that is not the highest non-prerelease is also refused without `--tag` ("Cannot implicitly apply the \"latest\" tag ..."). `npm dist-tag add` moves a tag without republishing. -- **The default model URL is a contract.** `DEFAULT_MODEL_BASE_URL` (`@0.1.0/files/`) and `DEFAULT_FROM` (`runtime-model-v0.1.0`) are pinned in code. Changing either means a runtime release. +- **Publish only tarballs you checked:** `npm publish <file>.tgz`. A bare publish packs again from the current `dist/`, and `tsup`'s `clean` means a failed build leaves a half-empty `dist/`. +- **Bump, then build, then pack.** The global build and `init`'s SRI depend on the version and the built files (C3). +- **Build from a clean tree** (C2). Other checkouts hold other agents' uncommitted edits. +- **Never commit `files/` or `*.tgz`.** Both are gitignored. Keep the export directory (and its sha256s) on the train VM. +- **Lockfile.** A version bump, the alias's dependency or a new workspace changes `package-lock.json`. Commit it in the same commit. +- **Dist-tags.** A prerelease without `--tag` is refused (npm 11). `npm dist-tag add` moves a tag without republishing. The README's commands resolve `latest`. +- **The default model URL is a contract.** `DEFAULT_MODEL_BASE_URL` (`@0.1.0/files/`) and `DEFAULT_FROM` (`runtime-model-v0.1.0`) are pinned. Changing either means a runtime release, and every older runtime keeps loading `0.1.0`. - **2FA and accounts.** Agents never run `npm login`, handle tokens, or publish. Hand the user the exact command. -- **Run policy.** On machines other than Mehar's 8 GB Mac, `npm ci`, `tsc`, `tsup`, vitest and `npm pack` are fine. The `HANDOFF.md` rule "never run npm/tsc/vitest on the Mac" is about his machine. Ask first before Playwright, `smoke.sh`, model downloads, the demos eval, training, realapps, Azure, `git push`, `gh release` and `npm publish`. +- **Run policy.** On machines other than Mehar's 8 GB Mac, `npm ci`, `tsc`, `tsup`, vitest and `npm pack` are fine. Ask first before Playwright, `smoke.sh`, `test/install/run-all.sh`, model downloads, the demos eval, training, realapps, Azure, `git push`, `gh release` and `npm publish`. ## Tests | step | what proves it | |---|---| -| A3 | CI-equivalent run: 332 passed + 14 skipped (346) at b435acb, or 333 + 14 (347) with the DL-7 fix committed, then perf 4 passed; `npm pack --dry-run` lists 26 files | -| A5 | `smoke.sh` prints `SMOKE OK: <tgz>` | -| A8 | `dist-tags`, `dist.shasum` equal to the local tarball's sha1, a clean install that imports, `npx genclass-runtime --help` | -| B2 | `genclass-runtime info` exits 0; `vitest run test/model` with `GENCLASS_MODEL_DIR` (export fixtures); `ortweb_report_q8.json` with full argmax agreement | -| B6 | CDN card identical to the packed one; `fetch-model` from the CDN and from the GitHub release verifies every sha256 | -| B7 | demos eval Off / Observe / Guard, with no clean-run regressions | +| B2 | `genclass-runtime info` exits 0; `vitest run test/model` with `GENCLASS_MODEL_DIR` (export fixtures); `ortweb_report_q8.json` with full argmax agreement; `meta.json` has `gate` | +| B6 | the CDN card is identical to the packed one; `fetch-model` from the CDN and from the GitHub release verifies every sha256 | +| B7 | demos eval Off / Observe / Guard with no clean-run regressions | +| C2 | the CI-equivalent run (375 passed + 14 skipped at f107013; re-measure after the merge), perf 4 passed, `npm pack --dry-run` file list | +| C3 | the built global file contains only the new version | +| C4 | `smoke.sh` prints `SMOKE OK`; `run-all.sh` results updated; status `ready` and model gates with the published model | +| C6 | `dist-tags`, `dist.shasum` equal to the local sha1, CDN 200s, `init --dry-run` installs `^<new version>` | ## Drift and open issues -- **Stale release text elsewhere (as of b435acb):** - - `HANDOFF.md` gives the publish command without `--tag`, which fails for prereleases; - - `packages/runtime/README.md` mentions `fetch-model`, whose default source is 404; confirm the "none for this runtime yet" caveat is still present before packing; - - `MODEL_CARD.md` describes round 1. -- **Open review findings (2026-10-08) that matter for B8**, by `path` -> `symbol`: - - **high:** - - `packages/runtime/src/situation/content.ts` -> `contentFacts`: the F2 fact prints raw text of redacted fields through `stringDiff`; - - `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter`: a delivery discard is a no-op on redux/zustand stores but is recorded as a drop. - - **medium:** - - `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`: observe mode (the default) still holds deliveries up to 100 ms, and XHR listeners run outside dispatch; - - background delivery decisions are dropped as stale; - - discard marks catch later chained polls (`RuntimeImpl.dropFilter`); - - a delivery `defer` can stall a push channel for 20 s; - - held WS/SSE messages are delivered after `close()` (`packages/runtime/src/observe/messages.ts` -> `MessageGate.pump`). - - **low:** - - `packages/runtime/src/util.ts` -> `isSensitivePath`/`defaultRedact` no longer redacts numbers or arrays under secret-named containers; - - `packages/runtime/src/situation/evidence.ts` -> `NOT_PROCESSED` treats 502 as "not processed". - - **TRAIN-side (they affect the model's quality, not the packaging):** - - unlabeled rows keep `expected` diagnoses that S1 would relabel (`sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`, `training/label_teacher.py`); - - `training/label_cluster.sh` can report done without labelling anything; - - `training/final_post.sh` is tied to `simAe` (see B0); - - SIM still samples the v1 3,200-char budget (`sim/src/world/scenario.ts`); - - several `training/curriculum/rt.py` divergences from the frozen renderer. -- **Real-app claims.** The "0/396 changed" never-worse sweep (`docs/runtime/RESULTS.md` §4) compares only final visible text and server content. It covers 66 of the now 91 apps, and it never compares observe mode against no runtime. Quote it that way in release notes; see [docs/agents/realapps.md](docs/agents/realapps.md). +- **Stale text elsewhere:** + - `packages/runtime/CHANGELOG.md` lists the install features under `0.1.0-alpha.1`; + - `test/install/INSTALL-README-SNIPPET.md` and `bin/lib/init.mjs` USAGE say guard is the default; + - `test/install/RESULTS.md` was run on alpha.0; + - `packages/runtime-model/MODEL_CARD.md` describes round 1; + - `HANDOFF.md` gives the publish command without `--tag`. +- **Open runtime review findings (2026-10-08), by `path` -> `symbol`:** + - `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter`: a delivery discard is a no-op on Redux/Zustand stores but is recorded as a drop (high); + - `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter`: discard marks catch later chained polls for 10 s (medium); + - a delivery `defer` can stall a push channel (medium); + - `packages/runtime/src/observe/messages.ts` -> `MessageGate.pump`: held WS/SSE messages are delivered after `close()` (medium); + - `packages/runtime/src/situation/evidence.ts` -> `NOT_PROCESSED`: 502 is treated as "not processed" (low). +- **Fixed since the review:** observe-mode delivery holds and dropped background delivery decisions (054da38); the F2 diff of redacted text and numbers/arrays under secret containers (f107013). +- **Redaction gaps that remain** (`packages/runtime/STATUS.md`, "Fix after 0.1.0-alpha.1"): + - a container named by a secret word pair (`cardNumber`, `apiKey`) counts as broad, so `payment.cardNumber.value` is shown; + - the "is back to V" fact compares rendered text; + - the curriculum's Python renderer (`training/curriculum/rt.py`) has no redactor. +- **TRAIN-side (model quality, not packaging):** + - unlabeled rows keep `expected` diagnoses that S1 would relabel (`sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`, `training/label_teacher.py`); + - `training/label_cluster.sh` can report done without labelling; + - SIM samples the v1 3,200-char budget (`sim/src/world/scenario.ts`); + - several `training/curriculum/rt.py` divergences from the runtime's renderer. +- **Real-app claims.** The "0/396 changed" never-worse sweep (`docs/runtime/RESULTS.md` §4) compares only final visible text and server content, covers 66 apps (the tree now has 128 app manifests), and never compares observe mode with no runtime. It predates 054da38. Quote it that way. - **Unverified:** - - the v2 round's delivery directory name on the train VM; + - the version string `r17-v2a` was exported with; + - whether its tar already includes fitted gates; + - the v2 delivery directory on the train VM; - whether the `genclass` developer role can create `@genclass/runtime-model`; - - jsDelivr's size limit for a larger model package; - which model tests skip with a v2 export; - - `smoke.sh` on `mvp-v2`. + - `mvp-v2-b6` (4e95373); + - `smoke.sh` and `run-all.sh` on the merged tree. ## Related docs @@ -453,5 +476,5 @@ Then repeat A1–A10 with: - [docs/agents/training.md](docs/agents/training.md): TRAIN's eval and export chain. - [docs/agents/demos.md](docs/agents/demos.md): the demos eval, `cities.ts`, demo modes. - [docs/agents/realapps.md](docs/agents/realapps.md): the real-app corpus and the never-worse sweep. -- [docs/agents/playbooks.md](docs/agents/playbooks.md): recipes 19 and 20. +- [packages/runtime/INSTALL-NEEDS.md](packages/runtime/INSTALL-NEEDS.md): the install owner's decisions and package.json notes. - [HANDOFF.md](HANDOFF.md), [OPEN_TASKS.md](OPEN_TASKS.md), [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md), [packages/runtime/STATUS.md](packages/runtime/STATUS.md), [packages/runtime-model/MODEL_CARD.md](packages/runtime-model/MODEL_CARD.md). diff --git a/packages/runtime/README.md b/packages/runtime/README.md index cb053fcb..e71fe696 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -34,7 +34,10 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known > runtime. Do not self-host them with this version. > - **Versions.** `0.1.0-alpha.1` is the current `latest` on npm: the v2 runtime, observe by default, with the > `NaN` fix. It does **not** include the one-command install, the `@genclass/runtime/auto` entries or the script -> tag described under [Install](#install); those are in this repository and ship in the next release. +> tag described under [Install](#install). It also lacks two fixes made since: observe mode no longer holds or +> delays any response, and two redaction leaks are closed (see [Privacy](#privacy)). All of these are in this +> repository and ship in the next release: `0.1.0-beta.0` with the model, or `0.1.0-alpha.2` if a release +> without the model goes out first. > `0.1.0-alpha.0`, the first version on npm, is the older v1 runtime: guard by default, holds store writes, and > can crash when app state contains `NaN`. Do not use it. > @@ -63,11 +66,11 @@ user action (#5). Delivered the response to GET /api/search?q=rea (#4) and dropp newer data (search.results). (stale, 0.97; discard 0.97) ``` -In observe mode the response is delivered without waiting for the model, and the write it causes is judged in the -background instead: +In observe mode the response reaches the app at once, exactly as without GenClass, and the same decision is made +in the background, for the report only: ``` -[GenClass] Flagged a stale write: search.results was written once by other operations since this write's cause (#4) +[GenClass] Flagged a stale response: search.results was written once by other operations since its operation (#4) started (version 1 → 2), … Not acted on (would have done discard 0.97): observe mode never changes execution. (stale, 0.97) ``` @@ -103,7 +106,9 @@ npx @genclass/runtime remove # undo exactly what init added ``` Other flags: `--no-install`, `--no-devtools`, `--cwd <dir>`, `remove --keep-package`. `init` sets up observe mode; -to let GenClass act, change the import it added to `@genclass/runtime/auto/guard` (see the next path). +to let GenClass act, change the import it added to `@genclass/runtime/auto/guard` (see the next path). Do this by +hand for now: `init --mode guard` still writes the observe import (see +[Known limitations](#known-limitations)). Tested end to end on fresh projects from each framework's own generator: Vite 8 (React with npm and pnpm, Vue, Svelte), Next.js 16.4 (App and Pages Router, plus the paths for Next < 15.3), Create React App 5, SvelteKit, Astro, @@ -414,7 +419,7 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - **Bundle:** the main entry is about 240 KB minified / 83 KB gzip, measured with esbuild and onnxruntime-web external. ONNX Runtime Web (the only dependency) is loaded by the model worker on demand: about 2.7 MB brotli for - the WASM-only path, 4.7 MB with WebGPU. The script-tag file (next release) is 253 KB / 86 KB gzip without ONNX + the WASM-only path, 4.7 MB with WebGPU. The script-tag file (next release) is 255 KB / 86 KB gzip without ONNX Runtime; its model worker (16 KB gzip) and ONNX Runtime glue (25–39 KB gzip) load on demand. - **Model size:** the round-1 R17 export (pruned 16k vocabulary, int8) is 9.6 MB. On single-thread WASM it took about 0.18 s per decision on a 500-token situation, measured in Node. @@ -443,22 +448,30 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - **Redaction:** the default redactor (`redact` option) works by the leaf field's meaning, not by substring. - Redacted: `auth.token`, `form.password`, `users.3.password`, `payment.card.number`, `settings.apiKey`, and opaque credential-like strings under `auth` / `session` / `cookie`. + - Under a container named for a secret, strings, numbers and arrays are all redacted: `payment.cvv.value = 123`, + `login.otp.code`, `account.password.history = [...]`. A side effect: numbers under a container whose name is + a secret word in another sense are hidden too (`map.pin.lat`). - Visible: `auth.loading`, `auth.user.name`, and a kanban `card`. - Booleans and null are never redacted. - Query parameters are redacted by the same rule. + - The "would replace text the user typed" fact shows a character diff only when the redactor leaves both values + unchanged; otherwise it prints `[redacted] → [redacted]` (or your redactor's replacement). - Pass your own `redact(path, value)` for app-specific secrets or PII. The default has gaps (see below). + - The container rule for numbers and arrays and the typed-text rule are fixes made after `0.1.0-alpha.1`; they + ship in the next release. ## Known limitations **Today.** Without a published model nothing is detected or prevented (see Status). The bullets below matter once a model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. -- **Redaction gaps (all modes with a model).** These values reach the situation text, `explain()`, the console - evidence and devtools, though never the network: - - The "would replace text the user typed" fact prints a diff of the raw strings, even for a field the redactor - hides. - - The default redactor does not redact numbers or arrays under a secret-named container, for example - `payment.cvv.value = 123` or `login.otp.code`. +- **Redaction gaps (all modes with a model).** + - A container named by a two-word secret (`cardNumber`, `apiKey`, `creditCard`) counts as broad, like `auth`. + So `payment.cardNumber.value = "4111 1111 1111 1111"`, or the same number, is shown. It reaches the situation + text, `explain()`, the console evidence and devtools, though never the network. A leaf with such a name + (`settings.apiKey`) is redacted. + - The fact "X changed since #N started and is back to V" compares the rendered text, so two different redacted + values read as "back to [redacted]". Pass a custom `redact`, and avoid keeping secrets in observed stores. - **Redux/Zustand discard.** If a stale response's dispatch also changes other fields, a delivery `discard` applies @@ -473,9 +486,6 @@ model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. the app closed the socket meanwhile. EventSource `open` events are not kept in order behind held messages. - **XHR listeners of a held response** run after the original dispatch, so `e.currentTarget` is `null`. Use the `xhr` object itself. -- **Observe mode with a model.** A conflicting delivery whose body is read can still be delayed up to 100 ms. - Delivery decisions are not made in observe mode (the resulting write is judged instead), so standing questions on - `delivery` are not answered there. - **`retry` (heal) does not check idempotency.** It is offered for any replayable fetch, POST included. The model sees whether the method is idempotent and whether the failed request may have been applied. HTTP 502 is described as usually not processed, which is not always true behind proxies. @@ -489,9 +499,35 @@ model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. This is best effort; wrap important work in `rt.op(name, fn)` for exact attribution. - **Store state** is visible and protectable only through GenClass-aware stores. Other state is seen only through its effects. -- **React Router dev server (next-release install).** On the very first dev start after `init`, Vite discovers the - new imports late, re-optimizes and reloads the page, logging a few "Outdated Optimize Dep" errors once. Later - loads are clean. +- **Next-release install (`init`, `remove`, `/auto`, script tag).** Known issues, to be fixed before or in that + release. Always read the diff `init` and `remove` show before you confirm. + - **`init --mode guard` installs observe.** It prints `Mode guard`, but writes the plain `@genclass/runtime/auto` + import (or a script tag without `data-mode`), which observes. Plain `init` also prints `guard` as the + default. Change the import to `@genclass/runtime/auto/guard` yourself. + - **Running `init` again with another `--mode`** reports "Nothing to do" and leaves the existing import alone. + - **TypeScript with `"moduleResolution": "node"`** (Create React App TypeScript, older templates) cannot find the + types of `@genclass/runtime/auto`, `/devtools` or `/react` (TS2307), so the type check, and with it a CRA + build, fails after `init`. `"moduleResolution": "bundler"` works. + - **Server and library projects.** A project that lists esbuild, rollup, parcel or webpack is treated as a + browser app, so `init` can add the import to a Node server's or a library's entry file. + - **Formatters.** If a formatter rewraps a line `init` added (the dev-only devtools line, or the one-line form + in a Next.js layout), `remove` takes out only part of it and leaves code that does not compile. Fix the file + by hand. + - **What `remove` deletes.** Code you added inside a block `init` marked goes with the block; a file `init` + created is one such block and is deleted whole. If a block's end marker is missing, everything after its start + marker goes. Any other line that contains `genclass:init` goes too. It uninstalls the package unless it finds + an import in your sources, and it does not look in dot-folders (`.storybook`), `tmp`, `out` or `build`. Use + `remove --keep-package` when you import GenClass there. + - **`init --cdn <url>`** adds an SRI hash of the CLI's own copy of the file, whatever version the URL names. With + `@latest` or another version, the browser refuses the script. Pass `--no-sri`. + - **SRI covers only the script-tag file.** The model worker, ONNX Runtime glue and overlay it loads from the CDN + are not integrity-checked. + - **Page configuration is read from every `<meta name="genclass">` in the document**, including the body, + and it may set the mode and the model and ONNX Runtime URLs. On a page that renders untrusted HTML which can + include `<meta>` tags, set those keys in `window.GENCLASS_CONFIG` (it overrides meta tags), or call + `GenClass.init(options)` instead of importing `/auto`. + - **React Router dev server.** On the very first dev start after `init`, Vite discovers the new imports late, + re-optimizes and reloads the page, logging a few "Outdated Optimize Dep" errors once. Later loads are clean. - **The model can be wrong.** It is trained on simulated apps and real apps driven in a headless browser. It is not a substitute for tests. That is why the default only observes, guard acts only at ≥ 0.9, and every action is logged. From 92e6b99d0bad6f1c3ef2e1328c6cacaae8d0bc1a Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 03:17:49 -0400 Subject: [PATCH 12/25] docs: merge origin/runtime eff18cb into the agent docs; record the observe and redaction fixes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- AGENTS.md | 134 ++++-- docs/agents/glossary.md | 84 ++-- docs/agents/realapps.md | 143 ++++-- docs/agents/repo-map.md | 219 ++++++--- docs/agents/runtime/build-test-release.md | 196 +++++--- docs/agents/runtime/decide-policy-actions.md | 135 ++++-- docs/agents/runtime/learn-situation-triage.md | 123 +++-- docs/agents/runtime/model-host.md | 85 +++- docs/agents/runtime/observe-and-trace.md | 49 +- .../runtime/public-api-and-lifecycle.md | 136 ++++-- docs/agents/status-and-known-issues.md | 447 ++++++++++++------ docs/agents/training.md | 113 +++-- 12 files changed, 1276 insertions(+), 588 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index aa966f96..d92e52d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ Root entry point for AI coding agents in GenClass-lib. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (`mvp-v2` + origin/runtime eff18cb merged + two runtime fixes), 2026-10-08 ~07:00 UTC. If this doc and the code disagree, the code wins. ## 1. What this repo is @@ -13,12 +13,17 @@ Root entry point for AI coding agents in GenClass-lib. - **Situation-v2 design:** decisions happen at the network boundary. The `delivery` trigger (`packages/runtime/src/types.ts` -> `TriggerKind`) holds only the delivery of a response or push message, and only when newer data already sits in the fields it would write. Store writes are not held by default (`policy.holdWrites` is opt-in). +- **Install paths** (Mehar's f3a9dd1, merged here, **not in the published `0.1.0-alpha.1`**): `npx @genclass/runtime init` + / `remove` (`packages/runtime/bin/lib/*`), the zero-code import `@genclass/runtime/auto` (and `/auto/observe`, + `/auto/guard`, `/auto/heal`; `packages/runtime/src/auto.ts`, `packages/runtime/src/cdn/auto-*.ts`) and a CDN script + tag (`dist/genclass.global.min.js`; `packages/runtime/src/cdn/global.ts`). - `sim/` generates training data by driving the real runtime. `realapps/` runs real framework apps in headless Chromium with the real runtime for real-browser training rows and the "never worse" sweep. `training/` trains and exports the model. `demos/` holds six evaluation apps. - `jev_local/`, `extension/`, `bench/`, `results/`, `tests/` and the legacy `docs/*.md` are the older GenClass model, Chrome extension and benchmarks that the runtime builds on. -- npm workspaces: `packages/*`, `sim`, `demos` (`realapps/` has its own `package.json` but is not a workspace). +- npm workspaces: `packages/*` (now also `packages/genclass-runtime`, the unpublished unscoped CLI alias), `sim`, + `demos` (`realapps/` has its own `package.json` but is not a workspace). Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current by the colleague, Mehar) and **[docs/agents/README.md](docs/agents/README.md)** (index: which doc answers which question), then @@ -26,34 +31,59 @@ Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current b [playbooks](docs/agents/playbooks.md), [status-and-known-issues](docs/agents/status-and-known-issues.md) and [RELEASE.md](RELEASE.md) (release procedure). -## 2. Status in brief (2026-10-08) - -- **Branches.** `mvp-v2` (here) = `origin/runtime` 74f17c0 (Mehar's latest: runtime batches 4 and 5, situation-v2, `realapps/`, - v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus six local commits: 7dab2b3 (these agent docs), - f3636b2 (default mode `observe`), b435acb (CI, committed root lockfile, CLI mode 100755), b561244 and 6ac4737 (docs), - 806a296 (release commit, `packages/runtime` version `0.1.0-alpha.1`; the head). Not pushed. The local - branch `mvp` is based on situation-v1 (654d822) and is superseded. -- **Runtime:** situation-v2, frozen at tag `situation-v2` (6e5e86e). Since that tag, `packages/runtime/src` changed only in - f3636b2 (`runtime.ts`, `types.ts`, `devtools/index.ts`); `git diff situation-v2 HEAD -- packages/runtime/src/situation` is empty. -- **Model: none for v2.** Round-1 R17/R32 models were trained on situation-v1 and do not match this runtime. The v2 plan - (HANDOFF "Current state"): 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> - DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. -- **Data is being generated now on Azure by Mehar** (per `training/NEEDS.md`): SIM situation-v2 gold and unlabeled rows on - 20 nodes, REAL real-browser gold rows on 3 nodes. Nobody on our side touches Azure. +## 2. Status in brief (2026-10-08, ~07:00 UTC) + +- **Branches.** `mvp-v2-merge` (here, head f107013, not pushed) = `mvp-v2` (c16a3b0: `origin/runtime` 74f17c0 plus + 7dab2b3 agent docs, f3636b2 default mode `observe`, b435acb CI + committed root lockfile, b561244/6ac4737 docs, + 806a296 release commit `0.1.0-alpha.1`, c16a3b0 publish record) + dabbce2 (merge of Mehar's `origin/runtime` at + eff18cb: d53e836 realapps wave 3, d05abc1 npm README, 2516a6e OPEN_TASKS, 29b7f28 `situation()` purity test, + f3a9dd1 one-command install, eff18cb "v2 data done") + 10e5c3b (lockfile sync) + 054da38 and f107013 (the two runtime + fixes below). `origin/runtime` has since moved on to 5bc40c9 (ca08174 realapps wave 4, 6d6eb00 REAL v2 production + done, 416e374 first r17-v2a results, 5bc40c9 runtime batch 6 with tag `situation-v2.1`); none of these four is in + this branch. The local branch `mvp-v2-b6` (4e95373, worktree `GenClass-lib-b6`) merges 5bc40c9 on top of f107013; + this doc does not describe it. `mvp` (situation-v1) is superseded. +- **Runtime:** situation-v2 (tag `situation-v2`, 6e5e86e) plus: default `observe`; the install entries (`src/auto.ts`, + `src/cdn/*`); **054da38**: observe mode never holds or delays a delivery (released synchronously before any body + read; the delivery decision is still made in the background and recorded with `executed: false`); **f107013**: the + F2 fact no longer diffs redacted text (`packages/runtime/src/state/fields.ts` -> `redactedStringDiff`) and the + default redactor hides numbers, bigints and arrays under strong secret-named containers (`packages/runtime/src/util.ts` + -> `isSensitivePath`). f107013 changes model-visible text for redacted values only, so `git diff situation-v2 HEAD -- + packages/runtime/src/situation packages/runtime/src/state/fields.ts packages/runtime/src/util.ts` is no longer empty + (`content.ts`, `fields.ts`, `util.ts`); no new tag was cut and the v2 data predates it (`packages/runtime/STATUS.md` + "Fix after 0.1.0-alpha.1"). +- **Data and training (Azure, Mehar's jobs; they run on their own, Mehar is asleep):** SIM v2 data is done: 10,423,855 + gold and 51,272,078 unlabeled rows (`OPEN_TASKS.md` "Done"). `r17-v2a` (R17 on v2 gold, 64 ranks, launched 05:14 UTC, + ETA ≈ 06:20; `training/v2_post.sh` then evaluates `sim2e`/`sim2f`, exports and serves the tar) and `t150-v2a` (150M + teacher, 88 ranks, launched 05:20 UTC, ETA ≈ 08:30) per `training/LOG.md`. Not in this branch but on + `origin/runtime` (416e374, `docs/runtime/RESULTS.md`): r17-v2a finished, `sim2e` diagnosis 84.4%, action 77.9%, guard + FIR 0.00%, heal FIR 0.46%, recall at the fixed gates very low. REAL `v2c*` gold had not landed at eff18cb. +- **Model: none published** (`@genclass/runtime-model` 404), so `packages/runtime/src/model/host.ts` -> + `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` fail: a default `GenClass.init()` ends with model status `error` + and logs `[GenClass] Model unavailable (...); observing only.` - **npm:** `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296: NaN fix, situation-v2, - default `observe`). `0.1.0-alpha.0` predates situation-v2 and defaults to `guard`. Neither has a model. - `@genclass/runtime-model` is not published, so `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the - CLI's `DEFAULT_FROM` 404: a default `GenClass.init()` ends with model status `error` and logs - `[GenClass] Model unavailable (...); observing only.` Release plan: [RELEASE.md](RELEASE.md) (see also - [build-test-release](docs/agents/runtime/build-test-release.md) "Cut a release"). -- **Stale human docs:** `HANDOFF.md` ('Modes: observe → guard (default; ...)') and the older published `0.1.0-alpha.0` still - say guard is the default; both READMEs now say observe. Test counts in STATUS/HANDOFF are older. Drift tables: [status-and-known-issues](docs/agents/status-and-known-issues.md). -- **Open defects found by review at b435acb** (details and fixes in the subsystem docs' "Drift and open issues"): - the F2 content fact can print the raw text of redacted fields (`situation/content.ts` -> `contentFacts`); a delivery - `discard` applies a Redux/Zustand dispatch whole when it also changes other fields, yet the record names the fields - as dropped (`state/hub.ts` -> `StoreHub.applyFilter`); SIM still samples the - v1 3,200-char budget (`sim/src/world/scenario.ts`); unlabeled SIM rows hard-label `expected` diagnoses that S1 would - relabel. Several of these touch model-visible text or live data generation: coordinate with the user before fixing. + default `observe`). It does **not** contain the install paths (`./auto` exports, `dist/cdn/`, the global build, + `init`/`remove`) nor the two fixes. **The next release** (`0.1.0-alpha.2`, or a beta together with the v2 model once + validated) carries them. `packages/runtime/package.json` and `packages/genclass-runtime/package.json` still say + `0.1.0-alpha.1`: bump before any build or pack that is meant to ship (the global build bakes the version into its + CDN URLs). Release plan: [RELEASE.md](RELEASE.md). +- **Open defects in the install code (review 2026-10-08, all confirmed; none shipped yet):** high: `init` and + `init --mode guard` install observe while printing "Mode guard" (`packages/runtime/bin/lib/plan.mjs` -> `AUTO`, + `scriptTag`; `packages/runtime/bin/lib/init.mjs` -> `USAGE` still says "guard (default)"); medium: the tree's version + makes the CLI and global build point at the published alpha.1, which lacks these files, and `CHANGELOG.md` lists the + install under alpha.1; `remove` breaks the build after a formatter wraps the marked lines + (`packages/runtime/bin/lib/edit.mjs` -> `removeMarked`); `/auto` and `/devtools` do not resolve under TypeScript + `moduleResolution: node` (no `typesVersions`); any esbuild/rollup/parcel/webpack dependency is treated as a browser + app (`packages/runtime/bin/lib/detect.mjs` -> `detectProject`); local SRI is added to any `--cdn` URL + (`plan.mjs` -> `integrityFor`); low: five more. Full table: [status-and-known-issues](docs/agents/status-and-known-issues.md#install-code-review-2026-10-08). +- **Earlier review (situation-v2 work):** SIT-1, SIT-3 (redaction) and DL-3, DL-4 (observe deliveries) are fixed here; + still open among others: a delivery `discard` applies a Redux/Zustand dispatch whole when it also changes other + fields, yet the record names the fields as dropped (`state/hub.ts` -> `StoreHub.applyFilter`); SIM samples the v1 + 3,200-char budget (`sim/src/world/scenario.ts`); unlabeled SIM rows hard-label `expected` diagnoses that S1 would + relabel. Several touch model-visible text or data generation: coordinate with the user before fixing. +- **Stale human docs:** `HANDOFF.md` ('Modes: observe → guard (default; ...)'), + `packages/runtime/test/install/INSTALL-README-SNIPPET.md` and the `init` usage text still say guard is the default; + both READMEs say observe. Test counts in STATUS/HANDOFF are older. Drift tables: + [status-and-known-issues](docs/agents/status-and-known-issues.md). - `demos/src/server/data/cities.ts` is not in git (root `.gitignore` rule `data/`), so a fresh clone cannot build or typecheck the demos, and root `npm run typecheck` fails. @@ -72,8 +102,10 @@ UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule s realapps bundles it from source, and `training/curriculum/rt.py` ports it. **Any change to `packages/runtime/src/situation/*` or to other model-visible text** (facts, questions, action/diagnosis wording, `packages/runtime/src/util.ts` formatting and redaction, op/event names) **means a new tag and regenerated data** (and - an `rt.py` mirror and retraining). Data is being generated from this code right now: never make such a change without - the user's explicit go-ahead. See [model-io-contract](docs/agents/model-io-contract.md). + an `rt.py` mirror and retraining). Training runs on v2 data right now: never make such a change without the user's + explicit go-ahead. This branch already carries one such change: f107013 (a privacy fix) changes the text of + redacted values only, and no new tag was cut; the curriculum port does not mirror it (`packages/runtime/STATUS.md` "Fix after + 0.1.0-alpha.1"). See [model-io-contract](docs/agents/model-io-contract.md). 3. **Determinism.** Runtime code never calls `Math.random`, `Date.now` or `performance.now` directly and never schedules with the global `setTimeout`; it uses the injected `Clock` (`packages/runtime/src/clock.ts`). IDs come from counters. Same inputs give byte-identical situations. Known exceptions, none touching situation text: @@ -82,7 +114,9 @@ UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule s 4. **Honest-evaluation separation.** `sim/` and `realapps/` never read or model `demos/`; demos are never tuned and contain nothing beyond a normal integration. (`realapps/` does import the sim's cost weights and label rule from `sim/src`.) 5. **Default `observe`; never make a correct app worse.** Since f3636b2 the default mode is `observe` (`runtime.ts` -> - `o.mode ?? "observe"`, CONTRACT §13): it never takes an action. `guard` is opt-in (minimal guard-tier actions: + `o.mode ?? "observe"`, CONTRACT §13): it never takes an action and, since 054da38, never holds or delays a delivery + (`RuntimeImpl.deliveryHoldable` is false in observe, so `runDelivery` releases at once). `origin/runtime` still + defaults to `guard`, and the merged install CLI still assumes guard (open defect, §2). `guard` is opt-in (minimal guard-tier actions: `discard`, `defer`, `coalesce`, `delay`); `heal` is experimental. An action runs only when the summed calibrated probability of permitted non-passive actions reaches the tier threshold (`decide/policy.ts`: guard 0.9, heal 0.8) and the top diagnosis is not `expected`. Model unavailable, loading, late or erroring means the passive action; holds are @@ -99,38 +133,43 @@ UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule s ## 4. Where to run things - **Our run policy (lead, 2026-10-08).** Light local checks are fine on this machine (macOS, 16 GB, Node v25.6.0): - `npm install`/`npm ci`, `tsc`, `tsup`, vitest unit tests (runtime and sim). + `npm install`/`npm ci`, `tsc`, `tsup`, vitest unit tests (runtime and sim; `test/install/cli.test.ts` is one of them: + it runs the CLI on fixture projects in temp dirs with `--no-install`, no network). - **Ask the user first** before: Playwright (`npm run test:browser`, the UI spec), `test/smoke/smoke.sh`, the sim generator (`sim/scripts/*`, `gen.js`), training (`training/*.sh`, any Python training or eval), realapps runs (`gen.js`, - `debug.js`, `realapps/scripts/*`), the demos' eval, model downloads (`genclass-runtime fetch-model`), **anything on + `debug.js`, `realapps/scripts/*`), the install test suite (`packages/runtime/test/install/run-all.sh`, `scaffold.sh`, + `frameworks.mjs`, `cdn-check.mjs`: real framework scaffolds, package managers, Chromium; written for the VM), the + demos' eval, model downloads (`genclass-runtime fetch-model`), **anything on Azure** (`scripts/*.sh`, `az`, ssh to nodes), **`git push`** and **`npm publish`**. - `HANDOFF.md` "Rules" ("never run npm, tsc, vitest ... on the Mac"; build and test on the Azure `train` VM via `scripts/vm.sh`) describes Mehar's workflow on his 8 GB Mac and his Azure cluster. It is context, not instructions for us. -## 5. Commands (verified 2026-10-08 on mvp-v2, Node v25.6.0) +## 5. Commands (verified 2026-10-08 on `mvp-v2-merge` at f107013, Node v25.6.0, unless noted) | command | dir | result / notes | |---|---|---| -| `npm ci --no-audit --no-fund` | repo root | OK from the committed lockfile (fresh clone too). Add `ONNXRUNTIME_NODE_INSTALL=skip` on Linux, as CI does. EBADENGINE warning from vitest on Node 25 is harmless | +| `npm ci --no-audit --no-fund` | repo root | OK from the committed lockfile at b435acb (not rerun after the merge; 10e5c3b synced the lockfile for the new `packages/genclass-runtime` workspace). Add `ONNXRUNTIME_NODE_INSTALL=skip` on Linux, as CI does. EBADENGINE warning from vitest on Node 25 is harmless | | `npx tsc -p tsconfig.json --noEmit` | `packages/runtime` | clean. Checks `src/` only: test files are never type-checked | -| `npx tsup` | `packages/runtime` | OK. 6 entries (`index`, 3 adapters, `devtools/index`, `worker`) into `dist/` | -| `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` | `packages/runtime` | Files 40 passed, 1 skipped (41). Tests 332 passed, 14 skipped (346). The 14 skips are model-parity tests needing `GENCLASS_MODEL_DIR` | +| `npx tsup` | `packages/runtime` | OK. Four configs: the ESM build (10 entries: `index`, `auto`, `auto/{observe,guard,heal}`, 3 adapters, `devtools/index`, `worker`), the script-tag builds `dist/genclass.global.js` and `.global.min.js` (IIFE, the package version baked in as `__GENCLASS_VERSION__`), and the CDN worker `dist/cdn/{worker,ort-webgpu,ort-wasm}.js` | +| `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` | `packages/runtime` | Files 44 passed, 1 skipped (45). Tests 375 passed, 14 skipped (389). The 14 skips are model-parity tests needing `GENCLASS_MODEL_DIR`. New since 806a296: `test/install/cli.test.ts` (20), `test/observe-delivery.test.ts` (11), `test/redaction-v2.test.ts` (10), `test/situation-purity.test.ts` (2) | | `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | `packages/runtime` | 4 passed. Run it alone: in a full parallel run it flaked once (5.5 ms vs a 2 ms bound). CI uses `--retry=2` | -| `npm run build` then `SIM_RUNTIME=real npx vitest run` | root, then `sim/` | 19 passed (5 files). Sim `tsc` clean. Without `SIM_RUNTIME=real` the sim tests use a fake runtime | +| `npm run build` then `SIM_RUNTIME=real npx vitest run` | root, then `sim/` | 19 passed (5 files) at b435acb; not rerun after the merge. Without `SIM_RUNTIME=real` the sim tests use a fake runtime | -Total: 350 runtime unit tests (336 passed, 14 skipped without a model dir). CI (`.github/workflows/ci.yml`, Node 22) runs -`npm ci` -> runtime typecheck -> build -> the two vitest steps above; triggers: push to `main`/`runtime`/`mvp`/`mvp-v2`, -`pull_request`, `workflow_dispatch`. It has not run on GitHub yet (mvp-v2 is not pushed). Not run by us: Playwright, -`smoke.sh`, realapps, demos eval, Python tests, training. One test: `npx vitest run test/delivery.test.ts -t "<name>"`. +Total: 393 runtime unit tests in 46 files (379 passed, 14 skipped without a model dir). CI (`.github/workflows/ci.yml`, +Node 22) runs `npm ci` -> runtime typecheck -> build -> the two vitest steps above; triggers: push to +`main`/`runtime`/`mvp`/`mvp-v2`, `pull_request`, `workflow_dispatch` (not `mvp-v2-merge`). It has not run on GitHub yet +(nothing pushed). Not run by us: Playwright, `smoke.sh`, the install suite (`test/install/run-all.sh`), realapps, +demos eval, Python tests, training. One test: `npx vitest run test/delivery.test.ts -t "<name>"`. ## 6. Top-level layout | path | what it is | doc | |---|---|---| -| `packages/runtime/` | `@genclass/runtime`: `src/`, `test/`, `bin/genclass-runtime.mjs` CLI, `STATUS.md` (runtime state, example situations, deviations), `UI-NEEDS.md` | [runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle and [build-test-release](docs/agents/runtime/build-test-release.md)), [model-io-contract](docs/agents/model-io-contract.md) | +| `packages/runtime/` | `@genclass/runtime`: `src/` (incl. `auto.ts`, `cdn/`), `test/` (incl. `install/`), `bin/genclass-runtime.mjs` CLI (`init`, `remove`, `fetch-model`, `info`; `init`/`remove` in `bin/lib/`), `STATUS.md` (runtime state, example situations, deviations), `CHANGELOG.md`, `INSTALL-NEEDS.md` (INSTALL's requests), `UI-NEEDS.md` | [runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle and [build-test-release](docs/agents/runtime/build-test-release.md)), [model-io-contract](docs/agents/model-io-contract.md) | +| `packages/genclass-runtime/` | unscoped alias `genclass-runtime` 0.1.0-alpha.1 (unpublished): `cli.mjs` forwards to `@genclass/runtime`'s CLI so `npx genclass-runtime init` could work; a workspace | [repo-map](docs/agents/repo-map.md) | | `packages/runtime-model/` | only `MODEL_CARD.md` of the unpublished model package | [model-host](docs/agents/runtime/model-host.md) | | `sim/` | `@genclass/sim`: deterministic training-data simulator (S1/S2 labels, `SEPARABILITY.md`) | [sim.md](docs/agents/sim.md) | -| `realapps/` | 91 real apps (corpus + 14 open-source Conduit front-ends) in headless Chromium; REAL rows and the never-worse sweep | [realapps.md](docs/agents/realapps.md) | +| `realapps/` | 128 app directories with a `manifest.ts` (Mehar's commits say 96 after wave 3; wave-4 apps arrived inside f3a9dd1/eff18cb), incl. 14 open-source Conduit front-ends, in headless Chromium; REAL rows and the never-worse sweep | [realapps.md](docs/agents/realapps.md) | | `training/` | Python training, curriculum (`curriculum/rt.py`), eval, export, Azure launch scripts; `NEEDS.md`, `LOG.md`, `EVAL.md` | [training.md](docs/agents/training.md) | | `demos/` | `@genclass/demos`: six Vite demo apps, Service Worker chaos backend, Playwright trials | [demos.md](docs/agents/demos.md) | | `docs/runtime/` | `CONTRACT.md` (binding; changes appended to §13), `API.md`, `ARCHITECTURE.md`, [RESULTS.md](docs/runtime/RESULTS.md) (model and design comparisons, data volume, training log) | [status-and-known-issues](docs/agents/status-and-known-issues.md) | @@ -168,7 +207,8 @@ Total: 350 runtime unit tests (336 passed, 14 skipped without a model dir). CI ( - `HANDOFF.md`: live state and how to continue. `OPEN_TASKS.md`: Done / In progress / Next / Needs the user / Known risks. - `packages/runtime/STATUS.md`: test state, batch changes, example situations, "Deviations from the contract", "Open issues". - [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md): update it with every result (HANDOFF repo map). -- `NEEDS.md` files live in the requester's directory (`sim/`, `training/`, `demos/`, plus `packages/runtime/UI-NEEDS.md`); +- `NEEDS.md` files live in the requester's directory (`sim/`, `training/`, `demos/`, plus `packages/runtime/UI-NEEDS.md` + and `packages/runtime/INSTALL-NEEDS.md`, from the INSTALL workstream that owns `src/auto.ts`, `src/cdn/**`, `bin/lib/**`, `test/install/**`); only the requester closes an item. `training/NEEDS.md` also holds Azure node claims and data locations. - `docs/runtime/CONTRACT.md`: approved changes go to §13; an accepted divergence goes into STATUS "Deviations". @@ -176,7 +216,7 @@ Total: 350 runtime unit tests (336 passed, 14 skipped without a model dir). CI ( 1. If you touched `packages/runtime/src`: `tsc` clean and `tsup` builds (keep tsup entries as literal `"src/...ts"` strings and the worker URL / ORT `import()` literals). -2. Runtime unit tests pass in both CI steps (§5: 332 + 14 skipped, then review-perf 4), plus new tests in house style. +2. Runtime unit tests pass in both CI steps (§5: 375 + 14 skipped, then review-perf 4), plus new tests in house style. No `review-*.test.ts` edited. For sim, realapps, demos or training changes, name the checks you could not run and why. 3. No model-visible text changed (rule 2) unless the user approved it; if approved, update exact-text tests and STATUS example situations, and flag that a new situation tag, `rt.py` mirror, regenerated data and retraining are needed. diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md index 8305dbaa..58e4ae7f 100644 --- a/docs/agents/glossary.md +++ b/docs/agents/glossary.md @@ -2,9 +2,9 @@ > **Scope:** every term defined in the subsystem docs under `docs/agents/`, the shared runtime vocabulary (op, trigger, situation, hold, tier, delivery, ...) and project jargon (workstreams, datasets, label rules S1/S2/T1, training stages and the teacher/distillation/DAgger pipeline, hosts, model names, benchmark names, the realapps sweeps). One alphabetical list. A qualifier in parentheses separates words that mean different things in different subsystems, e.g. *chaos (demos)* vs *chaos (sim)*, *Decision (runtime)* vs *Decision (extension)*, *S1 (fact)* vs *S1 (sim label rule)*. > **Read this when:** a doc, a status file or the code uses a word you do not know, or two docs seem to use one word differently. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (`mvp-v2` + origin/runtime eff18cb merged + two runtime fixes), 2026-10-08. Entries untouched by the merge keep their b435acb wording where nothing changed. If this doc and the code disagree, the code wins. -Conventions: **Code:** `path/from/repo/root` -> `symbol` (a method is written `Class.method`). **Doc:** the subsystem doc with the full detail. "See *x*" points to another entry of this glossary. Runtime numbers (thresholds, budgets, sizes) are the defaults at b435acb. Fact ids: the runtime's own fact ids (M2, R3, F1 for "failure", S1 for "stall", ...) predate batch 5 and collide with the batch-5 evidence facts **F1–F9** (named after `sim/SEPARABILITY.md` §6) and with SIM's label rules **S1/S2**; the qualifier in each entry says which is meant. +Conventions: **Code:** `path/from/repo/root` -> `symbol` (a method is written `Class.method`). **Doc:** the subsystem doc with the full detail. "See *x*" points to another entry of this glossary. Runtime numbers (thresholds, budgets, sizes) are the defaults at f107013 (unchanged since b435acb). Fact ids: the runtime's own fact ids (M2, R3, F1 for "failure", S1 for "stall", ...) predate batch 5 and collide with the batch-5 evidence facts **F1–F9** (named after `sim/SEPARABILITY.md` §6) and with SIM's label rules **S1/S2**; the qualifier in each entry says which is meant. Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](#g) · [H](#h) · [I](#i) · [J](#j) · [K](#k) · [L](#l) · [M](#m) · [N](#n) · [O](#o) · [P](#p) · [Q](#q) · [R](#r) · [S](#s) · [T](#t) · [U](#u) · [V](#v) · [W](#w) · [X](#x) · [Z](#z) @@ -21,13 +21,16 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **apply (action)**: Passive action of the `mutation` trigger: keep the write. By default (`holdWrites` off) the write has already applied when the non-blocking `mutation` trigger is decided, so `apply` changes nothing; with `policy.holdWrites: true` it lets the held write update the state (or when the store's queue drains). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.observeWrite`, `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **ask (trigger)**: The developer-question trigger. `rt.ask(question, { about, timeoutMs })`, `rt.decide(question, options)` and `rt.situation()` build an `ask` situation about now, an op id or a store outside `trigger()`: no triage, no gate, no `Decision`, queue priority 1. `rt.ask` replaces the questions with `{ answer: q }`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.ask`, `RuntimeImpl.decide`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **ask row / ask probe (sim)**: At `scenario.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records it; `askQuestions` attaches 1–3 programmatic questions with exact labels (`q_*` qids). Code: `sim/src/ask/questions.ts` -> `askQuestions`. Doc: [sim](sim.md). +- **assetBase (script-tag build)**: Where the script-tag build loads its other files (model worker, ORT chunks, devtools): for a jsDelivr or unpkg URL of `@genclass/runtime` (any version or none) the same CDN pinned to the version baked in at build time (`@<__GENCLASS_VERSION__>/dist/`), else the script file's own directory, else jsDelivr at that version. Because the version comes from `package.json`, building this tree before the version bump points it at the published alpha.1, which has no `dist/cdn/`. Code: `packages/runtime/src/cdn/global.ts` -> `assetBase`. Doc: [status-and-known-issues](status-and-known-issues.md). - **atom (store kind)**: A store whose value GenClass owns (`StoreRec.value`), created by `rt.atom(name, initial, opts)` and by the React hook `useGenClassState`; always writable. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.atom`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **attempt (model load)**: `LoadAttempt { variant, device, error }`: a load plan that failed, listed in `status.attempts`. Code: `packages/runtime/src/model/errors.ts` -> `LoadAttempt`. Doc: [model-host](runtime/model-host.md). - **auto budget**: See *situation budget*. +- **auto entry (`@genclass/runtime/auto`)**: Zero-code setup (INSTALL, f3a9dd1; not in the published `0.1.0-alpha.1`): `import "@genclass/runtime/auto"` as the first import of the entry file calls `startAuto()`, which merges `<meta name="genclass">` and `window.GENCLASS_CONFIG` and calls `GenClass.init` (devtools if asked). With no mode it runs the runtime default, **observe** on this branch; `/auto/observe`, `/auto/guard` and `/auto/heal` pass that mode. The default export is the runtime. Outside a browser it is the inert runtime. Kept by bundlers through `sideEffects`. Code: `packages/runtime/src/auto.ts`; `packages/runtime/src/cdn/auto-start.ts` -> `startAuto`; `packages/runtime/src/cdn/auto-{observe,guard,heal}.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). ## B - **backfill (devtools)**: At mount the overlay replays `decisions(200)`, `interventions(200)` and `history(400)`, and re-derives detections with the literal 0.6 threshold; report sentences are not available for these items. Code: `packages/runtime/src/devtools/index.ts` -> `mountDevtools`. Doc: [devtools](runtime/devtools.md). +- **background delivery decision**: A delivery that cannot be held (`RuntimeImpl.deliveryHoldable` false: observe mode, paused, model not `ready`, no permitted non-passive delivery action, or the model too slow for the hold budget) is released synchronously, before its body is read, and still decided in the background (054da38): an in-memory body (XHR, WebSocket, EventSource) is analysed before the app's listeners run; a fetch body is analysed until `BODY_WAIT_MS` or until its chain's first write (`RuntimeImpl.finalizeDeliveries`). The decision is recorded and reported with `executed: false` and answers delivery standing questions; while it is pending it covers its chain's predicted writes (no second mutation decision). In guard or heal with a too-slow model, the chain's writes keep their own decisions and late revert instead (`RuntimeImpl.writesCanAct`). Fixes review findings DL-3 and DL-4. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`, `deliveryHoldable`, `finalizeDeliveries`, `covered`; test `packages/runtime/test/observe-delivery.test.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). - **BandedEncoder**: See *tree layout / BandedEncoder*. - **base run (sim)**: The scenario run with the real runtime, a recording decider, exploration (ε of 0, 0.08 or 0.2, weighted 4/3/2; ε where the sim sees a problem, ε/4 elsewhere) and ask probes. Its recorded decisions are the candidate decision points. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `generateTrajectory`. Doc: [sim](sim.md). - **baseline**: Online statistics per op signature, for fetch/XHR ops only (not synthetic, not GenClass): last 64 non-failure latencies (nearest-rank median/p95, need ≥ 5 samples), last 20 outcomes, failure streak, an EWMA error rate (computed but never read), last 128 start times (recent vs usual rate), and per request identity an EWMA gap between identical requests. Memory only; feeds facts, stats lines, the stall timer and `delay` backoff. Code: `packages/runtime/src/learn/baselines.ts` -> `Baselines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). @@ -47,20 +50,22 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## C -- **c01 / c02–c23**: Azure F80 hosts (`vm-jev-c01`…`c23` in resource group `rg-jev-train`). `c01` (10.0.0.6) is TRAIN's workbench and data hub (prune, generate, eval, export); `c02`–`c11` were the round-1 training nodes (`c02` R32 rank 0, `c09` R17 rank 0); `c12`–`c23` were added on 2026-10-08 by `training/cluster_expand.sh`. During v2 data generation SIM holds c02–c09 and c12–c23 and REAL holds c01, c10 and c11 (`training/NEEDS.md`); nobody on our side touches Azure. The host table lives in `~/.jev-local/azure_hosts` (not in the repo). See *train VM*. Doc: [training](training.md), [sim](sim.md), [realapps](realapps.md). +- **c01 / c02–c23**: Azure F80 hosts (`vm-jev-c01`…`c23` in resource group `rg-jev-train`). `c01` (10.0.0.6) is TRAIN's workbench and data hub (prune, generate, eval, export); `c02`–`c11` were the round-1 training nodes (`c02` R32 rank 0, `c09` R17 rank 0); `c12`–`c23` were added on 2026-10-08 by `training/cluster_expand.sh`. SIM's v2 generation is done (its 20 nodes were deallocated 04:55–05:10 UTC); per the `training/NEEDS.md` claim table at eff18cb, TRAIN holds c02 (v2 workbench), c03–c09 and c13 (*r17-v2a*) and c12 and c14–c23 (*t150-v2a*), and REAL runs `v2c1`..`v2c4` on c01, c10, c11 and `data`. Nobody on our side touches Azure. The host table lives in `~/.jev-local/azure_hosts` (not in the repo). See *train VM*. Doc: [training](training.md), [sim](sim.md), [realapps](realapps.md). - **cadence (F6)**: What the runtime learned about when a request signature is sent: `periodic { period, intervals, last, next }` (a schedule: requests not caused by user actions, ≥ 4 runs, ≥ 75% of intervals within ±25%, dropped after 3 missed periods) or `debounced { delay, matching, of }` (sent a fixed delay after the user's last input, from timers started by user actions). Stated by fact F6 ("GET /api/feed runs on a schedule: every 1.00s …; the next run is due in 0.95s."), always neutral; it tells the model whether a stale value will heal by itself. Code: `packages/runtime/src/learn/cadence.ts` -> `Cadence`, `CadenceInfo`; `packages/runtime/src/situation/evidence.ts` -> `cadenceFact`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **calibration / calibration.json**: Post-hoc temperature scaling of raw logits read from `calibration.json`: τ by header key, else by `(kind, K-bucket)`, else `τ(K) = a + b·ln K` clamped to `[0.5, 5.0]`, else per kind; a noul uses its header temperature, else a Platt affine, else the per-kind temperature. Trained checkpoints ship all-1.0 temperatures; the real file comes from `training/eval_runtime.py --write-calibration`. Code: `packages/runtime/src/model/calibrate.ts` -> `tauFor`, `noulAffine`, `calibrateLogits`; `jev_local/engine/encoder/calibrate.py` -> `tau_for`. Doc: [model-host](runtime/model-host.md), [genclass-model-lineage](genclass-model-lineage.md). - **candidate**: See *permitted set / candidate / mass*. - **cause / root (op)**: `OpRec.cause` is the id of the op that was ambient (or passed explicitly) when the op started; `root` is the cause's root, or the op's own id when it has no cause. User ops and WS messages are always roots; a retry or hedge op names the original op as its cause. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). +- **CDN script tag / global build**: `dist/genclass.global.min.js` (and the unminified `.global.js`), an IIFE built from `packages/runtime/src/cdn/global.ts` by `tsup.config.ts` -> `globalBuild` (INSTALL, f3a9dd1; not in the published `0.1.0-alpha.1`). Put first in `<head>`, it calls `GenClass.init()` with options from its `data-*` attributes, the meta tag and `window.GENCLASS_CONFIG`, exposes `window.GenClass`, and loads the model worker (`dist/cdn/worker.js`, from a same-origin Blob URL), onnxruntime-web (`dist/cdn/ort-*.js`) and the devtools on demand from *assetBase*. Without `data-mode` it runs the runtime default (observe here). `init` writes a pinned jsDelivr tag with *SRI* for plain-HTML projects. Doc: [status-and-known-issues](status-and-known-issues.md). - **chain**: An op and its causal descendants (ops sharing its `root`). In facts, "same chain" means one op is an ancestor-or-self of the other; "the op's chain wrote" (`RuntimeImpl.chainWrites`) means fields written by the op's root chain since the root started. Code: `packages/runtime/src/situation/facts.ts` -> `computeFacts`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.chainWrites`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **chain keys (normalised)**: Keys of `OpRec.chain`: field paths passed through `normalizeFieldPath`, which turns every segment after the store name that is id-like or contains a digit into `:id` (`chat.byId.m21` -> `chat.byId.:id`). Transition shapes, involved fields and transition `SubjectRef.paths` use them. Code: `packages/runtime/src/util.ts` -> `normalizeFieldPath`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **chain revert**: The `rollback` implementation for `transition` and `error` triggers: restore exactly the fields the op's root chain wrote (not overwritten since, with a known earlier value, in a writable store) to their values before the chain's first write; undo restores the replaced values. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.revertChain`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). - **chain write**: `ChainWrite { kind, len0, len1 }`, accumulated per normalised path in `OpRec.chain` of profiled ops (the writer plus up to 8 ancestors) by `RuntimeImpl.onApplied`; the input to transition profiles. `ChainWriteInfo` (`SitEnv.chainWrites`) is the real-path view used by facts and rollback applicability. Code: `packages/runtime/src/trace/ops.ts` -> `ChainWrite`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **CHANGELOG.md**: `packages/runtime/CHANGELOG.md` (f3a9dd1). Its `## 0.1.0-alpha.1` section lists the one-command install, `/auto` and the script tag, which the published alpha.1 (806a296) does not contain; those bullets belong to the *next release*. Doc: [status-and-known-issues](status-and-known-issues.md). - **chaos (demos)**: `RouteChaos` knobs (latency, jitter, failRate, commitFailRate, timeoutRate, hangMs, spikeRate, spikeFactor, reorder, outage, offline) plus per-route overrides, applied by the Service Worker mock server; environment only, never app logic. Clean trials use `CLEAN_CHAOS` (45 ± 15 ms, no failures). Code: `demos/src/shared/chaos.ts` -> `RouteChaos`, `resolveChaos`; `demos/src/shared/scenario-kit.ts` -> `CLEAN_CHAOS`. Doc: [demos](demos.md). - **chaos (sim)**: Per-scenario network regime `calm | normal | flaky | degraded | storm | mobile | peak | deploy` (weights 2/3/3/3/1/1/1/1; the last three, added in round 2, start from the flaky/degraded/normal base and add their own conditions) that `makeNet` turns into latency multipliers, transient and network-error rates, outages, slow periods, capacity, rate limits, replica lag and server bugs. Code: `sim/src/world/scenario.ts` -> `buildScenario`, `makeNet`. Doc: [sim](sim.md). - **chaos trial / clean trial (demos)**: A chaos trial randomises chaos and stresses the simulated user, and measures bug rate; a clean trial uses a calm network and a calm user on which the app is correct, so any executed non-passive action is a *false intervention*. Doc: [demos](demos.md). - **choice (question kind)**: A typed question answered by a softmax over 2–255 labels (`criteria`: label -> description or `null`); the answer is `{ choice, confidence, probabilities }` with probabilities in criteria order. `diagnosis` and `action` are choice questions; `rt.decide()` is a choice shortcut. Code: `packages/runtime/src/types.ts` -> `Question`, `ChoiceAnswer`; `jev_local/schema.py` -> `ChoiceQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). -- **CI**: `.github/workflows/ci.yml` (added in b435acb on `mvp-v2`), job `runtime`: on push to `main`, `runtime`, `mvp`, `mvp-v2`, on pull requests and on manual dispatch; Ubuntu, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci` from the committed root lockfile, `typecheck` and `build` of `@genclass/runtime`, then the unit tests without `test/browser/**` and `review-perf`, then `review-perf` alone with `--retry=2` (it is a wall-clock test that flakes under parallel load). Playwright, `smoke.sh`, the sim, realapps and Python tests are not in CI. Doc: [build-test-release](runtime/build-test-release.md). +- **CI**: `.github/workflows/ci.yml` (added in b435acb on `mvp-v2`), job `runtime`: on push to `main`, `runtime`, `mvp`, `mvp-v2`, on pull requests and on manual dispatch; Ubuntu, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci` from the committed root lockfile, `typecheck` and `build` of `@genclass/runtime`, then the unit tests without `test/browser/**` and `review-perf`, then `review-perf` alone with `--retry=2` (it is a wall-clock test that flakes under parallel load). The unit step also runs `packages/runtime/test/install/cli.test.ts` (init/remove on fixture projects in temp dirs, no network). Playwright, `smoke.sh`, the install suite (`test/install/run-all.sh`), the sim, realapps and Python tests are not in CI. The triggers do not include `mvp-v2-merge`. Doc: [build-test-release](runtime/build-test-release.md). - **classify (sim)**: A feature-provided closure on a sim op or sim write, evaluated at decision time, that returns a diagnosis (`stale`, `conflict`, `duplicate`, `expected`) from content bookkeeping; a returned label takes precedence in `diagnose`. Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`; `sim/src/oracle/diagnose.ts` -> `diagnose`. Doc: [sim](sim.md). - **clean run (realapps)**: One of the 8% of realapps scenarios with the first (correct) flag options, a calm network and no accidental clicks; the never-worse sweep counts how many clean runs change. Code: `realapps/src/harness/scenario.ts` -> `buildScenario`. Doc: [realapps](realapps.md). - **clear (devtools)**: Overlay-only removal of cards and rows; runtime buffers are untouched and a remount backfills them again. Doc: [devtools](runtime/devtools.md). @@ -83,10 +88,10 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **CORE (workstream)**: Owns `packages/runtime/**` except `packages/runtime/src/{model,devtools,adapters}/**`, including the situation wording and `packages/runtime/src/types.ts`; writes `packages/runtime/STATUS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). - **cost (sim)**: `runCost`, a run's cost relative to the ideal run: 1.0 × D(t) integrated over the 10 s after the decision + 4.0 × final client divergence + server damage (25 per extra/missing item, 6 per differing field or counter unit) + 0.8 × relation-violation seconds + 2.0 × relations still violated at the end + 1.5 × shown errors + 1.0 × uncaught errors + 0.08 × extra requests + 0.25 × pending seconds; "final" is decision + 15 s. Code: `sim/src/oracle/cost.ts` -> `runCost`, `W`. Doc: [sim](sim.md). - **counterfactual run / counterfactual cost (sim)**: A sim re-run with a forced map (explored choices before decision `k`, action `a` at `k`, passive after), stopped at `t_k + 15 s` and required to reproduce the base run's fingerprints up to `k`; its `runCost` against the ideal run is the counterfactual cost of `a` at `k`. Code: `sim/src/run/runner.ts` -> `runScenario`; `sim/src/gen/trajectory.ts` -> `pointCosts`. Doc: [sim](sim.md), [model-io-contract](model-io-contract.md). -- **covered write**: A store write whose causal chain (≤ 16 ancestors) passed a delivery gate whose predicted write set was known and includes every changed path, and that delivery was not salient or was decided in time. A covered write raises no `mutation` trigger (never covered with `triage: "always"`), so one response costs at most one model call. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.covered`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [learn-situation-triage](runtime/learn-situation-triage.md). +- **covered write**: A store write whose causal chain (≤ 16 ancestors) passed a delivery gate whose predicted write set was known and includes every changed path, and that delivery was not salient, was decided in time, or (since 054da38) is still being decided in the background after a release without a hold (`deliveryPending`). A covered write raises no `mutation` trigger (never covered with `triage: "always"`), so one response costs at most one model call. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.covered`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **createRuntime**: The headless entry point (tests, sim, SSR): builds a `RuntimeImpl`, creating and owning a model host only when `decider` is `undefined` and `model` is an object. It can throw on malformed options and never sets `GenClass.runtime`. Code: `packages/runtime/src/index.ts` -> `createRuntime`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **CU / GEN**: The two sets of the GenClass-vs-Jev head-to-head: CU = synthetic computer-use harness examples (the extension's domain), GEN = generic questions from task families held out of training. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **cur1 / cur2 / cur3 / cur4**: Curriculum datasets from `training/curriculum/generate.py`: `cur1` 800k train rows, all varied style (seed 1); `cur2` 400k, `--p-runtime 0.6` with the pre-freeze `rt.py` (seed 2); `cur3` 300k stage-2 replay, `--p-runtime 0.8`, pre-freeze wording (seed 4); `cur4` 300k final replay in the frozen `situation-v1` wording, `--p-runtime 0.8` (seed 5). `--p-runtime` is the share of decision rows rendered runtime-exact. All four predate situation-v2; `training/curriculum/rt.py` now renders v2 text (d73d20c), but no v2 curriculum set has been generated (and the review found several places where `rt.py` diverges from the runtime). Doc: [training](training.md). +- **cur1 / cur2 / cur3 / cur4**: Curriculum datasets from `training/curriculum/generate.py`: `cur1` 800k train rows, all varied style (seed 1); `cur2` 400k, `--p-runtime 0.6` with the pre-freeze `rt.py` (seed 2); `cur3` 300k stage-2 replay, `--p-runtime 0.8`, pre-freeze wording (seed 4); `cur4` 300k final replay in the frozen `situation-v1` wording, `--p-runtime 0.8` (seed 5). `--p-runtime` is the share of decision rows rendered runtime-exact. All four predate situation-v2. The first v2 set is `cur5` (300k rows, seed 15, 80% runtime-exact, built by `training/import_v2.sh`; see *sim2 / sim2e / sim2f / cur5*); the review found several places where `rt.py` diverges from the runtime, and `rt.py` has no redactor (so it does not follow f107013). Doc: [training](training.md). - **custom action**: An `ActionDef` added with `rt.action(def)`, a plugin's `actions` or the `plugins` option. Offered when `def.on` includes the trigger, the name is new and `applicable(draft)` is true; gated at its own tier (default `heal`); runs inside a GenClass op; `ctx.builtin(name)` may run an offered built-in (re-checked for mode, deny/allow, pause and rate limit, not thresholds); if no built-in took over, the passive action runs afterwards. Code: `packages/runtime/src/types.ts` -> `ActionDef`, `ActionContext`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runCustom`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). ## D @@ -101,12 +106,12 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **Decision Score (jevbench)**: `clip(1 − mean Brier / mean prior Brier, −1, 1)` per dataset. Code: `jev_local/bench/metrics.py` -> `decision_score`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **DecisionProvider**: The only seam between the runtime and a model: `{ status, ready(), evaluate(req), onStatus?(fn), dispose?() }`. Implemented by the model host, the test deciders, the sim's recording decider and `failedProvider`; passed as `options.decider`, which wins over `options.model` (`null` = no model). `evaluate` receives `EvaluateRequest { trigger, state, questions, priority?, subject?, timeoutMs? }`. Code: `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [model-io-contract](model-io-contract.md). - **decontamination stage 1 (benchmax)**: Name-level exclusion of training sources per track. Code: `jev_local/bench/registry.py` -> `is_excluded`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS "Next": Model package, currently item 9; release procedure in [RELEASE.md](../../RELEASE.md) Part B; no `runtime-model-v0.1.0` tag in the repo; the lead found it returns 404 on 2026-10-08), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS "Next": Model package, item 12 in the merged tree; release procedure in [RELEASE.md](../../RELEASE.md) Part B; no `runtime-model-v0.1.0` tag in the repo; the lead found it returns 404 on 2026-10-08), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). - **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published (npm 404 on 2026-10-08, and no situation-v2 model exists to publish), so a default `GenClass.init()` ends with model status `error` and only observes; since f3636b2 it is also in `observe` mode by default. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **defer (action)**: Guard-tier action of `mutation` and `delivery`, offered while the subject was deferred fewer than 2 times. Mutation: with `holdWrites: true`, wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies; with `holdWrites` off it is offered but only recorded (the write already applied). Delivery: offered only when related ops are in flight (same name outside the op's chain, or whose signatures wrote a matched store); hold the response or message, wait for them (`waitOps`), then decide again. A review finding: each delivery defer waits up to 10 s (`LONG_RUNNING_MS`), not the hold budget, so two defers can hold a response for 20 s, and on a push channel every later message waits behind it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`, `RuntimeImpl.runDelivery`, `RuntimeImpl.waitOps`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **delay (action)**: Guard-tier `request` action (fetch and XHR): wait `min(250 × 2^failStreak, 8000)` ms, where `failStreak` is the signature's current failure streak, then send. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **deliver (action)**: Passive action of the `failure` trigger (hand the original `Response` or rejection to the app) and of the `delivery` trigger (pass the response or message to the app now). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **delivery (trigger)**: The situation-v2 decision point (batch 4): a fetch or async-XHR response, or a WebSocket/EventSource message, is about to reach the app. `runDelivery` predicts the op's write set (from its transition profile, else the last completion of its signature) and raises the trigger only when that set has a newer-data conflict the body would change, a pending local change the body would put back (F1), or text the user typed since the request started that the body would replace (F2); it reads the body (a clone, JSON, ≤ 256 KB) only for such candidates, waiting ≤ 100 ms (`BODY_WAIT_MS`). Holdable, priority 2; held only when a non-passive action is permitted and the expected model latency fits the hold budget, so holding a delivery is only added latency and channel order is kept. Actions `deliver` (passive), `discard`, `defer`. Trigger sentence: `The response to <opLabel> arrived and is about to be delivered; …`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`; `packages/runtime/src/situation/env.ts` -> `DeliverySpec`; `packages/runtime/src/observe/messages.ts` -> `MessageGate`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **delivery (trigger)**: The situation-v2 decision point (batch 4): a fetch or async-XHR response, or a WebSocket/EventSource message, is about to reach the app. `runDelivery` predicts the op's write set (from its transition profile, else the last completion of its signature) and raises the trigger only when that set has a newer-data conflict the body would change, a pending local change the body would put back (F1), or text the user typed since the request started that the body would replace (F2); it reads the body (a clone, JSON, ≤ 256 KB) only for such candidates, waiting ≤ 100 ms (`BODY_WAIT_MS`). Holdable, priority 2; held only when a non-passive action is permitted and the expected model latency fits the hold budget, so holding a delivery is only added latency and channel order is kept. Since 054da38, a delivery that cannot be held (`RuntimeImpl.deliveryHoldable` false: always in observe) is released synchronously before any body read and decided in the background (see *background delivery decision*); the 100 ms body wait applies only to deliveries that can be held. Actions `deliver` (passive), `discard`, `defer`. Trigger sentence: `The response to <opLabel> arrived and is about to be delivered; …`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`; `packages/runtime/src/situation/env.ts` -> `DeliverySpec`; `packages/runtime/src/observe/messages.ts` -> `MessageGate`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **delta signature**: `deltaOf` output that is equal for "the same change applied again": `n:<diff>` (numbers), `a:+added|-removed` (array multiset diff), `o:<hash>` (pure reorder), `c:+k/~k/-k` (collections), `v:<hash>` (anything else), `x:removed`. Feeds `RecentChange.key` and the repetition facts. Code: `packages/runtime/src/state/fields.ts` -> `deltaOf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **demo mode**: `GcMode = "off" | "guard" | "heal"`. Off = `GenClass.init({ mode: "observe", model: false })`, the baseline; Guard and Heal init with that mode and `model: { baseUrl, preload: "eager" }`. The demos always pass a mode explicitly, so the runtime's default-mode change does not affect them (the file comment still calls guard "the default"). Not the same as `?genclass=off`, the runtime kill switch that installs nothing. Code: `demos/src/shared/types.ts` -> `GcMode`; `demos/src/shared/genclass.ts` -> `startGenClass`. Doc: [demos](demos.md). - **DEMOS (workstream)**: Owns `demos/`; writes `demos/NEEDS.md`, `demos/README.md` and `demos/results*.{md,json}`. Doc: [status-and-known-issues](status-and-known-issues.md), [demos](demos.md). @@ -137,7 +142,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## F -- **F1–F9 (evidence facts)**: The situation-v2 facts proposed in `sim/SEPARABILITY.md` §6 to separate clear actionable cases from benign look-alikes, implemented in batches 4–5 (not to be confused with the runtime's older per-trigger fact ids such as F1 = "this request failed"). **F1** put back an older value: the response/write has the value a newer op (or a still-pending user change) replaced, per field or per item cell joined on an id key (salient). **F2** replace typed text: the response would replace text the user typed into a field after the request started, with a diff-centred preview (salient). **F3** no change: the body equals the current value of everything it is predicted to write (neutral; for a delivery this also makes it non-salient and logs `delivery.unchanged`). **F4** has no runtime fact of that name; SEPARABILITY's F4 idea became the *read-your-writes* fact. **F5** failure scope (other endpoints of the origin failing, `navigator.onLine` false) and commit ambiguity of a failed non-GET. **F6** learned *cadence*. **F7** repeat-action evidence (`MouseEvent.detail`, request still in flight). **F8** relation quality in the invariant miner (no spurious `==`/`∈` relations; count-by-group template); it changes which invariants exist, not a fact sentence. **F9** stale marks: a field last written by a response delivered over newer data, a ≥ 5× slow response, a write after an ambiguous failure, or a push received while its channel had been down. All are neutral unless stated. Review findings: F2 can print redacted text, and F5 calls HTTP 502 "usually not processed". Code: `packages/runtime/src/situation/content.ts` -> `contentFacts`, `pendingRevertFacts`, `rywFacts`; `packages/runtime/src/situation/evidence.ts` -> `markFacts`, `cadenceFact`, `scopeFacts`, `commitAmbiguity`, `repeatEvidence`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). +- **F1–F9 (evidence facts)**: The situation-v2 facts proposed in `sim/SEPARABILITY.md` §6 to separate clear actionable cases from benign look-alikes, implemented in batches 4–5 (not to be confused with the runtime's older per-trigger fact ids such as F1 = "this request failed"). **F1** put back an older value: the response/write has the value a newer op (or a still-pending user change) replaced, per field or per item cell joined on an id key (salient). **F2** replace typed text: the response would replace text the user typed into a field after the request started, with a diff-centred preview (salient). **F3** no change: the body equals the current value of everything it is predicted to write (neutral; for a delivery this also makes it non-salient and logs `delivery.unchanged`). **F4** has no runtime fact of that name; SEPARABILITY's F4 idea became the *read-your-writes* fact. **F5** failure scope (other endpoints of the origin failing, `navigator.onLine` false) and commit ambiguity of a failed non-GET. **F6** learned *cadence*. **F7** repeat-action evidence (`MouseEvent.detail`, request still in flight). **F8** relation quality in the invariant miner (no spurious `==`/`∈` relations; count-by-group template); it changes which invariants exist, not a fact sentence. **F9** stale marks: a field last written by a response delivered over newer data, a ≥ 5× slow response, a write after an ambiguous failure, or a push received while its channel had been down. All are neutral unless stated. Review findings: F2 printed redacted text (fixed in f107013: it diffs only values the redactor leaves unchanged, `packages/runtime/src/state/fields.ts` -> `redactedStringDiff`), and F5 calls HTTP 502 "usually not processed" (open). Code: `packages/runtime/src/situation/content.ts` -> `contentFacts`, `pendingRevertFacts`, `rywFacts`; `packages/runtime/src/situation/evidence.ts` -> `markFacts`, `cadenceFact`, `scopeFacts`, `commitAmbiguity`, `repeatEvidence`; `packages/runtime/src/state/invariants.ts` -> `InvariantMiner`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **F80**: The Azure VM size of the cluster nodes (`c01`–`c23`), about $5.46/h per node (`training/LOG.md`); training runs use 8 ranks × 10 threads per node. Doc: [training](training.md). - **facade**: `GenClass` (named and default export), the browser singleton around `createRuntime`. `GenClass.init(options)` never throws (it falls back to an inert runtime), is idempotent (a second call returns the first runtime and ignores its options), applies the kill switch and loads the local model by default; `GenClass.runtime` and `GenClass.destroy()` complete it. Code: `packages/runtime/src/index.ts` -> `GenClass`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **fact**: `Fact { text, kind, neutral }`: a uniform English sentence computed per trigger by `computeFacts`; `neutral: false` makes the situation salient. Ordered non-neutral first, then by kind rank (invariant/transition/error 0, versions 1, repetition 2, inputs 3, outcome 4, baseline 5, concurrency 6, provenance 7, request 8, cache 9, delta 10, plugin 11), capped at 12 (`MAX_FACTS`). Plugin facts are always neutral. Code: `packages/runtime/src/situation/facts.ts` -> `computeFacts`, `orderFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). @@ -153,7 +158,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **feed pause (devtools)**: Overlay-only freeze of list, activity and Now rendering; intake and counters continue and "N new" is counted. Unrelated to `runtime.pause()`. Doc: [devtools](runtime/devtools.md). - **field / path / leaf**: A store value is flattened into dotted fields `store.k1.k2` (at most 4 key levels). Arrays, plain objects with more than 32 keys or none, and non-plain objects are one leaf each; a store has a soft cap of 200 fields. `Leaf { value, hash, kind, len, elems?, keys?, khash?, src? }`. Code: `packages/runtime/src/state/fields.ts` -> `flatten`, `Leaf`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **FieldState / FieldHist / LogEntry**: Per-field bookkeeping in the hub: version `v`, writer op, `t` and `seq`; the last 16 writes with before/after values (history); the last 512 writes as compact entries (log). Facts read field versions from them. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). -- **final round 1 / round 2**: TRAIN's training rounds on frozen-format data. Round 1 = R17 and R32 on situation-v1 SIM phase A plus `cur4`/`cur1`/`gen` replay (`mix_final1`), 2026-10-08 00:06–01:36 UTC, done: R17 90.5% diagnosis, 81.9% action, guard FIR 0.05%, heal FIR 0.24%, but recall on clear stale/duplicate cases only 7.7% (R32 no better, so R17 is the default on every device). Its exports live only on the train VM and the colleague's Mac and do not match the v2 runtime. "Round 2" (format v2: ~10M SIM gold + ~50M unlabeled + ~0.5M real-browser rows) is now the teacher → distillation → DAgger program of `training/PLAN-v1.md`, in progress (data generating). Doc: [training](training.md), `docs/runtime/RESULTS.md`. +- **final round 1 / round 2**: TRAIN's training rounds on frozen-format data. Round 1 = R17 and R32 on situation-v1 SIM phase A plus `cur4`/`cur1`/`gen` replay (`mix_final1`), 2026-10-08 00:06–01:36 UTC, done: R17 90.5% diagnosis, 81.9% action, guard FIR 0.05%, heal FIR 0.24%, but recall on clear stale/duplicate cases only 7.7% (R32 no better, so R17 is the default on every device). Its exports live only on the train VM and the colleague's Mac and do not match the v2 runtime. "Round 2" (format v2) is the teacher → distillation → DAgger program of `training/PLAN-v1.md`: SIM data done (10,423,855 gold, 51,272,078 unlabeled), REAL `v2c*` landing, and the first runs *r17-v2a* and *t150-v2a* launched 05:14 / 05:20 UTC (`training/LOG.md`). `origin/runtime` (416e374, not merged) reports r17-v2a: diagnosis 84.4%, action 77.9%, guard FIR 0.00% on `sim2e`, but very low recall at the fixed gates. Doc: [training](training.md), `docs/runtime/RESULTS.md`. - **FIR**: False-intervention rate in TRAIN's evaluation: gate fires on passive-best rows ÷ passive-best rows, per mode (guard, heal), with the runtime's policy gate mirrored in Python. Code: `training/eval_runtime.py` -> `decision_metrics`. Doc: [training](training.md). - **fixed / introduced (demos)**: Paired with Off on the same chaos seed: *fixed* = Off had the bug and the mode did not; *introduced* = Off was fine and the mode had the bug. Read against A/A noise. Code: `demos/src/shared/aggregate.ts` -> `summarizeMode`. Doc: [demos](demos.md). - **FIXTURES_FROM_MODEL**: Flag in the model test helpers, true when `requests.json`, `pack_fixtures.json` and `torch_fixtures.json` exist in the model directory (written by `training/export_runtime.py`); the unit parity tests then use them instead of the v0.1 fixture set (browser specs never do). Code: `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL`. Doc: [build-test-release](runtime/build-test-release.md). @@ -173,19 +178,21 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **GenClass 0.1 (v0.1 model)**: The v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers, unpruned vocabulary) exported as ONNX `genclass-model-0.1.0` for the Chrome extension and published at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. A general typed-decision classifier, not trained for runtime decisions; the demos and model tests use it and R32 is initialised from it. Doc: [genclass-model-lineage](genclass-model-lineage.md), [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). - **GenClass op**: An instant op of kind `genclass` started by `RuntimeImpl.runAsGenClass(name, fn)` (cause `null`) for undo, revert, rollback, resync and custom actions. Writes and requests inside it are never gated and are excluded from baselines and profiles. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runAsGenClass`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **genclass-<size> / meharsjev-<size>**: Model ids allowed for benchmax runs (`genclass-<size>`, legacy `meharsjev-<size>`); `jev-*` and `typesafe/*` ids are rejected (W10). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **genclass-runtime (CLI)**: The package's bin: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info <dir>` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`. Doc: [model-host](runtime/model-host.md). -- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.1` is the latest published version (`latest`, 2026-10-08, release commit 806a296): NaN fix, situation-v2, default `observe`; with no published model it takes no actions. The older `0.1.0-alpha.0` predates batches 4–5 and the observe default (its default is `guard`). `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths: `.`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) +- **genclass-runtime (CLI)**: The package's bin, also run as `npx @genclass/runtime <command>`: `init [--mode observe|guard|heal] [--yes] [--dry-run] [--no-install] [--no-devtools] [--cwd <dir>] [--from <spec>] [--cdn <url>]` and `remove [--yes] [--dry-run] [--keep-package]` (see *init / remove*; merged in f3a9dd1, not in the published `0.1.0-alpha.1`); `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info <dir>` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime/bin/lib/*`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **genclass-runtime (alias package)**: `packages/genclass-runtime/` (f3a9dd1), an unscoped package whose `cli.mjs` forwards to `@genclass/runtime`'s CLI so `npx genclass-runtime init` would work. Version and dependency `0.1.0-alpha.1`; a workspace; **not published** (no `genclass-runtime` on npm, so `npx genclass-runtime init` fails today and the name is unreserved: `packages/runtime/INSTALL-NEEDS.md` item 1). `npx @genclass/runtime init` is the documented form. Doc: [status-and-known-issues](status-and-known-issues.md). +- **genclass:init / genclass:inline (markers)**: The comments `init` puts on every line or block it adds (`// genclass:init`, `// genclass:init start` … `end` around files it creates, `genclass:inline` for JSX/Astro inline forms); `remove` deletes exactly what carries them. Review findings: a formatter that wraps a marked line breaks `remove`, a lost end marker makes it drop the rest of the file, and any line containing the text is dropped. Code: `packages/runtime/bin/lib/edit.mjs` -> `MARK`, `MARK_INLINE`, `removeMarked`. Doc: [status-and-known-issues](status-and-known-issues.md#install-code-review-2026-10-08). +- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.1` is the latest published version (`latest`, 2026-10-08, release commit 806a296): NaN fix, situation-v2, default `observe`; with no published model it takes no actions, and it has none of the install paths (`./auto*`, the script-tag build, `init`/`remove`). The older `0.1.0-alpha.0` predates batches 4–5 and the observe default (its default is `guard`). The tree still says `0.1.0-alpha.1`; the *next release* carries the install paths and the two fixes; `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths in the tree: `.`, `/auto`, `/auto/observe`, `/auto/guard`, `/auto/heal`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker` (published alpha.1: no `/auto*`). Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md), [RELEASE.md](../../RELEASE.md). - **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0 (npm 404). Only `packages/runtime-model/MODEL_CARD.md` exists. 0.1.0 must be a situation-v2 model, which does not exist yet. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **`@genclass/sim` / `@genclass/demos` / `@genclass/realapps`**: The private packages `sim/` and `demos/` (root workspaces) and `realapps/` (not a workspace). `sim` and `demos` depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first; `realapps/build.mjs` bundles the runtime from source instead (`RW_RUNTIME_SRC`, default the working tree). Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). - **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `<repo>/.cache-model`, filled with `genclass-runtime fetch-model <dir> --from <v0.1 release URL>` (ask first; the default `--from` is unpublished)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). - **GENCLASS_REPLACE**: `"@@genclass/REPLACE"`, the Redux action the enhancer uses for GenClass's whole-state writes (rollback, revert); it never reaches the app reducer. Code: `packages/runtime/src/adapters/redux.ts` -> `GENCLASS_REPLACE`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **GenClassUnavailableError**: The error `rt.ask()` / `rt.decide()` reject with when no model can answer; `reason` is `destroyed`, `off`, `timeout` or `error` (with `timeoutMs` set, a raw provider load error can escape instead). Provider errors never escape a trigger. Code: `packages/runtime/src/errors.ts` -> `GenClassUnavailableError`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). -- **gold row**: A training row with counterfactual action labels (SIM's default row mode; REAL's decision rows): the scenario is re-run once per applicable action at the decision point over 2–3 paired futures, and costs become a soft `action` label (`actionLabel`) plus a hard `diagnosis` label (with *S1*). SIM v2 targets ≥ 10M gold rows (seeds from 11e9), REAL about 495k ([HANDOFF](../../HANDOFF.md)/[RESULTS](../runtime/RESULTS.md); NEEDS target ≥ 500k). Contrast *unlabeled rows* and *on-policy rows* (see *DAgger*). Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts`. Doc: [sim](sim.md), [realapps](realapps.md). +- **gold row**: A training row with counterfactual action labels (SIM's default row mode; REAL's decision rows): the scenario is re-run once per applicable action at the decision point over 2–3 paired futures, and costs become a soft `action` label (`actionLabel`) plus a hard `diagnosis` label (with *S1*). SIM v2 produced 10,423,855 gold rows (seeds from 11e9; `OPEN_TASKS.md` "Done"); REAL's usable v2 gold comes from `v2c1`..`v2c4` (616,437 rows per `origin/runtime` 6d6eb00, not merged here). Contrast *unlabeled rows* and *on-policy rows* (see *DAgger*). Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts`. Doc: [sim](sim.md), [realapps](realapps.md). - **guard (store kind)**: A store whose value the app owns behind `get` / `set` / `subscribe` (`rt.guard(name, io, opts)`); external changes arrive through `subscribe` and are recorded, never held; always writable. Not the same as the guard mode or tier (see *mode*, *tier*). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.guard`; `packages/runtime/src/types.ts` -> `StoreIO`. Doc: [state-and-adapters](runtime/state-and-adapters.md). ## H -- **HANDOFF.md**: The colleague's repo-root "read this first" for continuing Claude sessions (d73d20c): current state (npm, git tags, runtime, model, data, training), repo map, hard rules (the 8 GB Mac must not run npm/tsc/vitest/browsers/models; Azure etiquette; the frozen format; licensing; commit identity) and how to continue. Its Mac rule is about the colleague's machine; our run policy lives in `AGENTS.md`. It still calls guard the default mode. Doc: [status-and-known-issues](status-and-known-issues.md)., [HANDOFF.md](../../HANDOFF.md), [RESULTS.md](../runtime/RESULTS.md) +- **HANDOFF.md**: The colleague's repo-root "read this first" for continuing Claude sessions (d73d20c): current state (npm, git tags, runtime, model, data, training), repo map, hard rules (the 8 GB Mac must not run npm/tsc/vitest/browsers/models; Azure etiquette; the frozen format; licensing; commit identity) and how to continue. Its Mac rule is about the colleague's machine; our run policy lives in `AGENTS.md`. It still calls guard the default mode, says 66 real apps and lists "150M teacher on v2 gold" as next although *r17-v2a* and *t150-v2a* are already training. Doc: [status-and-known-issues](status-and-known-issues.md)., [HANDOFF.md](../../HANDOFF.md), [RESULTS.md](../runtime/RESULTS.md) - **harness (extension)**: The extension's incremental voice decision loop (`extension/src/core/controller.js` with the policy, safety, stream and spans modules) and its Python original `jev_local/harness/*` (macOS voice computer use); the JS core is parity-tested against fixtures generated from the Python. Code: `extension/src/core/controller.js` -> `Controller`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **header / item**: A question's header is its `instructions` text (a default when missing); its items are the options (choice: `label` or `label: desc`), the levels (score) or the true/false criteria (noul). Question ids are never shown to the model. Code: `packages/runtime/src/model/serialize.ts` -> `questionBlock`. Doc: [model-io-contract](model-io-contract.md). - **header key**: `sha1(header)[:12]`, the key of `calibration.json` `by_header` (e.g. `041ccfa6318c` = "What is happening here?"). Code: `packages/runtime/src/model/calibrate.ts` -> `headerKey`. Doc: [model-io-contract](model-io-contract.md). @@ -205,6 +212,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **in_flight (section)**: The situation section listing in-flight ops other than user ops and the subject op, same signature first, then same root, then by start time: `<opPhrase> (#id) <secs> so far[, by #cause]`. Code: `packages/runtime/src/situation/build.ts` -> `inFlightLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **inconsistency (trigger)**: Raised at a settled point for fresh violations of learned or developer invariants (once per episode); not held, priority 1; actions `ignore`, `rollback` (to the last consistent snapshot), `resync`. Fact I1 makes it always salient. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.raiseInconsistency`. Doc: [state-and-adapters](runtime/state-and-adapters.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **inert runtime**: A `RuntimeImpl` with every observer off (`ALL_OFF`), no decider, `report: "silent"`, mode `observe`, produced by the `off` kill switch and by `GenClass.init`'s fallback after a throw. Stores, `op`, `emit` and `user` still record; nothing is held or asked. Code: `packages/runtime/src/index.ts` -> `GenClass`, `initUnsafe`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **init / remove (CLI)**: `npx @genclass/runtime init` detects the framework (Vite, CRA, webpack-likes, Angular, SvelteKit, Nuxt, Remix/React Router, Next app/pages, Astro, plain HTML), installs `@genclass/runtime@^<CLI version>` (or `--from`), adds one marked import of the *auto entry* (plus a dev-only devtools line) or a script tag, shows the diff and asks first; running it again changes nothing. `remove` undoes it and uninstalls the package when its scan finds no other use. INSTALL's code, merged in f3a9dd1, not on npm. Open review findings include: `init` and `init --mode guard` install observe while printing "Mode guard"; the install spec and script tag point at the published alpha.1 until the version is bumped. Code: `packages/runtime/bin/lib/init.mjs` -> `init`, `remove`; `bin/lib/detect.mjs` -> `detectProject`; `bin/lib/plan.mjs` -> `planInit`, `AUTO`, `scriptTag`. Tests: `packages/runtime/test/install/cli.test.ts` (local), `test/install/run-all.sh` (VM). Doc: [status-and-known-issues](status-and-known-issues.md#install-code-review-2026-10-08). +- **INSTALL (workstream)**: The colleague-side role behind the one-command install (f3a9dd1): owns `packages/runtime/src/auto.ts`, `src/cdn/**`, `bin/lib/**`, the `init`/`remove` commands and `test/install/**`; writes `packages/runtime/INSTALL-NEEDS.md` (requests to lead/CORE/MODEL/UI: the npx naming decision, the `package.json` and tsup changes, runtime behaviour it relies on) and `test/install/RESULTS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). - **instant op**: An op created already ended (`end = start`, status `ok`) and never in flight: user actions, timer ticks, WS messages and sends, GenClass actions. Code: `packages/runtime/src/trace/ops.ts` -> `OpRegistry`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **intent (sim)**: `Intent` in `Knowledge`: one user step with the slot (`key`) it targets, `mode` `replace` (a newer replace-intent on the same key supersedes older ones, making them stale) or `accumulate`, and an `accidental` flag (double click, impatient re-click) with `repeatOf`. Code: `sim/src/oracle/knowledge.ts` -> `Intent`. Doc: [sim](sim.md). - **interference (realapps)**: How much the runtime changes an app's behaviour when it takes no actions; measured by the *never-worse sweep*. @@ -232,7 +241,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **late revert**: When a write already applied (by default every write applies at once and its `mutation` trigger is decided in the background; with `holdWrites`, a held write whose hold budget expired), a gate-passing `discard` that arrives within `LATE_REVERT_MS` (2,000 ms) reverts exactly that write if `StoreHub.revertable` allows it (store writable, none of its fields changed since, no later write from the same root chain). The `ActionRecord` gets `late: true` and the report lead `Reverted`; undo re-applies the write. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`; `packages/runtime/src/state/hub.ts` -> `StoreHub.revertable`, `StoreHub.revert`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md). - **lazy preload**: When a salient trigger finds the provider in state `off`, the runtime reads `rt.ready` (calling `decider.ready()` once, which starts loading) and fails open for that trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **LazyOp (lazy timer op)**: Created for each wrapped timer callback; it becomes a real instant `timer` op only when something calls `ctx.op()`. Its parent is always a real op or `null` (`LazyOp.nearest`), so recursive timer loops never build a chain. Code: `packages/runtime/src/trace/context.ts` -> `LazyOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). -- **lead**: The coordinator workstream: owns `docs/runtime/CONTRACT.md`, `packages/runtime-model/` and (per CONTRACT §1) `training/`; approves contract additions (§13) and new dependencies, relays NEEDS items, publishes. On `mvp-v2` we act as lead for `AGENTS.md`, `CLAUDE.md`, `docs/agents/**`, `test/default-mode.test.ts` and CI. Doc: [status-and-known-issues](status-and-known-issues.md). +- **lead**: The coordinator workstream: owns `docs/runtime/CONTRACT.md`, `packages/runtime-model/` and (per CONTRACT §1) `training/`; approves contract additions (§13) and new dependencies, relays NEEDS items, publishes. On `mvp-v2` / `mvp-v2-merge` we act as lead for `AGENTS.md`, `CLAUDE.md`, `docs/agents/**`, `test/default-mode.test.ts`, `test/observe-delivery.test.ts`, `test/redaction-v2.test.ts`, CI and the `0.1.0-alpha.1` publish. Doc: [status-and-known-issues](status-and-known-issues.md). - **learned invariant**: See *invariant*. ## M @@ -244,9 +253,9 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **max_tokens_exceeded**: The packer's limit error (`MaxTokensExceededError`): state + longest question branch > `meta.max_len` (default 1536), or the whole sequence > `meta.max_total` (default 8192). The runtime reacts by multiplying its budget scale by 0.8 (floor 0.5). Code: `packages/runtime/src/model/errors.ts` -> `MaxTokensExceededError`; `packages/runtime/src/model/packer.ts` -> `Packer`. Doc: [model-host](runtime/model-host.md). - **meharsjev**: See *genclass-<size> / meharsjev-<size>*. - **MessageGate**: The batch-4 delivery gate for push channels: one per WebSocket or EventSource, intercepting `message` events, queueing them per channel in arrival order, asking `runDelivery` for each and re-dispatching released messages to the app's listeners, so a held message delays later ones instead of being overtaken. Review findings: held messages can be dispatched after the app called `close()`, a capture-phase listener can see a held message twice, and EventSource `open` is not kept in order. Code: `packages/runtime/src/observe/messages.ts` -> `MessageGate`, `MsgHost`; installed by `packages/runtime/src/observe/websocket.ts` -> `installWebSocket` and `packages/runtime/src/observe/eventsource.ts` -> `installEventSource`. Doc: [observe-and-trace](runtime/observe-and-trace.md). -- **mix_* (mixture config)**: `training/configs/mix_*.json`: bucket weights for a training round, read as `MixConfig`. Round-1 era: `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` (simA 0.85, cur4 0.12, cur1 0.02, gen 0.01). Added since: `mix_t150` (teacher: simA 0.9, cur4 0.1), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs on `simAg10` / `simAg20` / `simAh`). All name v1 buckets; no v2 or distillation mixture exists yet. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). +- **mix_* (mixture config)**: `training/configs/mix_*.json`: bucket weights for a training round, read as `MixConfig`. Round-1 era: `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1` (simA 0.85, cur4 0.12, cur1 0.02, gen 0.01). Added since: `mix_t150` (teacher: simA 0.9, cur4 0.1), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs on `simAg10` / `simAg20` / `simAh`). v2 (eff18cb): `mix_v2a` (*r17-v2a*: sim2 0.86, cur5 0.11, cur1 0.02, gen 0.01) and `mix_t150v2` (*t150-v2a*: sim2 0.9, cur5 0.1). No distillation mixture exists yet. Code: `jev_local/train/stream.py` -> `MixConfig`. Doc: [training](training.md). - **MockRuntime / loadScenario / runStoreSession**: The devtools and adapter UI test harness: `MockRuntime` is a scripted `Runtime`; `loadScenario` scripts a store story with 3 interventions and 3 detections; `runStoreSession` drives the real `createRuntime` with a virtual clock, a fake backend and the rule-based `SessionDecider`. Code: `packages/runtime/test/browser/ui/mock-runtime.ts` -> `MockRuntime`; `packages/runtime/test/browser/ui/scenario.ts` -> `loadScenario`; `packages/runtime/test/browser/ui/session.ts` -> `runStoreSession`. Doc: [devtools](runtime/devtools.md). -- **mode**: `observe | guard | heal`, which action tiers may run. **Default `observe`** since f3636b2 on `mvp-v2` (`o.mode ?? "observe"`; it was `guard` up to and including `0.1.0-alpha.0` and origin/runtime; `0.1.0-alpha.1` on npm defaults to `observe`). `observe` permits passive only: it never runs an action or holds a request or write, but while a model is consultable a conflicting delivery can still wait up to 100 ms (`BODY_WAIT_MS`) for its body read and WebSocket/EventSource messages are re-dispatched as clones (see [observe-and-trace](runtime/observe-and-trace.md) Drift); but triggers are still built and decided in the background so detections and reports work (review finding: background `delivery` decisions are dropped as stale, so delivery detections and delivery standing questions never answer in observe mode). `guard` (opt-in) adds guard-tier actions; `heal` (experimental) adds heal-tier actions. Set with `options.mode`, the kill switch or `rt.setMode`; devtools labels them "Observe (default)", "Guard (opt-in)", "Heal (experimental)". The test harness `setup()` still defaults to `guard`, and the sim and realapps pass `heal` explicitly. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `Mode`, `InitOptions.mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`; test `packages/runtime/test/default-mode.test.ts`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **mode**: `observe | guard | heal`, which action tiers may run. **Default `observe`** since f3636b2 on our line (`o.mode ?? "observe"`; it was `guard` up to and including `0.1.0-alpha.0` and is still `guard` on `origin/runtime`; `0.1.0-alpha.1` on npm defaults to `observe`). `observe` permits passive only: it never runs an action or holds a request or write and, since 054da38 on this branch, never holds or delays a delivery either (npm alpha.1 can still wait up to 100 ms, `BODY_WAIT_MS`, for a conflicting delivery's body); triggers are still built and decided in the background so detections, reports and delivery standing questions work (delivery decisions recorded with `executed: false`). `guard` (opt-in) adds guard-tier actions; `heal` (experimental) adds heal-tier actions. Set with `options.mode`, the kill switch, `rt.setMode`, the `/auto/<mode>` entries, `data-mode` on the script tag or `mode=` in `<meta name="genclass">`; devtools labels them "Observe (default)", "Guard (opt-in)", "Heal (experimental)". The install CLI still treats guard as the default (`packages/runtime/bin/lib/plan.mjs` -> `AUTO`): `init --mode guard` writes the bare `/auto` import, which runs observe (open finding). The test harness `setup()` still defaults to `guard`, and the sim and realapps pass `heal` explicitly. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor; `packages/runtime/src/types.ts` -> `Mode`, `InitOptions.mode`; `packages/runtime/src/decide/policy.ts` -> `modeAllows`; tests `packages/runtime/test/default-mode.test.ts`, `observe-delivery.test.ts`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). - **MODEL (workstream)**: Owns `packages/runtime/src/model/**` and `packages/runtime/bin/genclass-runtime.mjs`, and co-owns the "model seam" section of `packages/runtime/src/types.ts`. Doc: [status-and-known-issues](status-and-known-issues.md). - **model card**: `model.json` in format `genclass-runtime-model/1`: `name`, `version`, `variants` (`q8`, `fp16`: file, bytes, sha256, provider, needs) and `files` (`tokenizer`, `calibration`, `meta`). `parseCard` also accepts the v0.1 extension card. Code: `packages/runtime/src/model/loader.ts` -> `parseCard`, `CARD_FORMAT`. Doc: [model-host](runtime/model-host.md). - **model directory**: A folder or URL holding `model.json` plus the ONNX variants, `tokenizer.json`, `calibration.json` and `meta.json`; produced by `training/export_runtime.py`, fetched with `genclass-runtime fetch-model`, passed as `model: { baseUrl }`, read by tests from `GENCLASS_MODEL_DIR`. Downloads are cached in Cache Storage `genclass-runtime-v1`. Doc: [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md). @@ -259,12 +268,13 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## N -- **NaN fix / 0.1.0-alpha.1**: Commit ad24804 fixed infinite recursion when a store value is `NaN` (`packages/runtime/src/util.ts`, test `test/nan.test.ts`), found after `0.1.0-alpha.0` was published. It shipped in `0.1.0-alpha.1`, published 2026-10-08 under `latest` from release commit 806a296. Doc: [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) +- **NaN fix / 0.1.0-alpha.1**: Commit ad24804 fixed infinite recursion when a store value is `NaN` (`packages/runtime/src/util.ts`, test `test/nan.test.ts`), found after `0.1.0-alpha.0` was published. It shipped in `0.1.0-alpha.1`, published 2026-10-08 under `latest` from release commit 806a296. That version does not contain Mehar's one-command install (his commit f3a9dd1 is titled "0.1.0-alpha.1: one-command install", but the number went to our publish) nor the fixes 054da38 and f107013; see *next release*. Doc: [build-test-release](runtime/build-test-release.md)., [RELEASE.md](../../RELEASE.md) - **native timers (demos)**: Timers captured before `GenClass.init` wraps the globals; all test code (driver, oracle) uses them, so the runtime never sees test ops. Code: `demos/src/shared/native.ts`. Doc: [demos](demos.md). - **NATIVE_FETCH**: `globalThis.fetch` captured when `index.ts` is evaluated; an owned model host downloads with it, so GenClass never observes its own model download. Code: `packages/runtime/src/index.ts` -> `NATIVE_FETCH`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). -- **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exception `packages/runtime/UI-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). +- **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exceptions `packages/runtime/UI-NEEDS.md` and `packages/runtime/INSTALL-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). - **NetCause (sim)**: Why a simulated request ended (`NetEntry.cause`): `ok, transient, outage, overload, ratelimit, spike, slow-period, gateway-timeout, bug, replica-lag, neterr, aborted, notfound`; diagnoses read it. Code: `sim/src/net/network.ts` -> `NetCause`. Doc: [sim](sim.md). - **never-worse sweep**: The check of the product principle "never make a correct app worse": REAL's `debug.js --interference` runs each realapps scenario in `observe` mode and in `heal` mode with an all-passive decider and counts runs whose outcome differs. Situation-v2 result (STATUS.md, RESULTS.md §4): 0/396 clean runs changed (all 66 apps of the time, seeds 1–6), 3/198 under chaos (request-time holds shifting a request by ~25 ms; open item), Conduit 0/30; situation-v1 changed 4/198 and the React/Redux Conduit never rendered its feed. Caveats from review: it compares only final non-input, non-alert DOM text and server content (not requests, stores or errors), it never compares `observe` against no runtime at all, and the 25 apps added later were never swept. The runtime-side regression test is `test/no-reorder.test.ts`. Code: `realapps/src/harness/debug.ts`. Doc: [realapps](realapps.md)., [RESULTS.md](../runtime/RESULTS.md) +- **next release (`0.1.0-alpha.2`)**: The next `@genclass/runtime` prerelease (`OPEN_TASKS.md` Next 14): `0.1.0-alpha.2`, or a beta together with the v2 model once validated. It carries Mehar's install paths (*auto entry*, *CDN script tag*, *init / remove*), the fixes 054da38 and f107013, and whatever of `origin/runtime` is merged by then. Before building or packing it: bump the version, fix the install findings, move the CHANGELOG bullets; the user publishes with 2FA. Doc: [status-and-known-issues](status-and-known-issues.md). - **noul**: A typed question asking for the absolute probability that a statement is true (sigmoid head; `criteria` optional `{ true?, false? }`); the answer is `{ noul: P(true) }`, with no confidence field. Code: `packages/runtime/src/types.ts` -> `NoulAnswer`; `jev_local/schema.py` -> `NoulQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **Now view (devtools)**: Renders `runtime.situation()` (an "ask about now" situation) and `inflight()`, refreshed every second while visible. Doc: [devtools](runtime/devtools.md). - **numbered pick (extension)**: After "which element?", the top-3 candidates get page badges; "number two" within 10 s and ≤ 5 words clicks it without a model call (still through the safety gate). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). @@ -276,7 +286,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **on-policy rows**: See *DAgger / on-policy rows*. - **op / OpRec**: Anything the app does asynchronously, recorded in `OpRegistry`: kind `user | fetch | xhr | ws | task | timer | genclass`, a sequential `id` per runtime, `name` (the op signature), optional `detail`, start/end, status (`ok | error | aborted | blocked`), `code`, `cause` / `root`, `attempt`, `identity`, and since batch 4 `delivery` (the delivery gate's record) and `discardMark`. User actions, timer ticks, WS messages and sends, and GenClass actions are instant ops. Code: `packages/runtime/src/trace/ops.ts` -> `OpRec`, `OpRegistry`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.startOp`, `RuntimeImpl.endOp`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **op signature**: `OpRec.name`, the key ops are grouped by. For fetch/XHR it is `METHOD normalisedPath` (`requestSignature`: path only, host + path when cross-origin, no query or fragment, id-like segments -> `:id`, e.g. `GET /api/items/:id`); other kinds use their own names (`click button "Add to cart"`, `WS message <path>`, `timer 300ms`, a task name). It keys baselines, transition profiles (user ops as `user <name>`) and `storeWriters`. Code: `packages/runtime/src/util.ts` -> `requestSignature`, `normalizePath`, `isIdSegment`. Doc: [observe-and-trace](runtime/observe-and-trace.md), [learn-situation-triage](runtime/learn-situation-triage.md). -- **OPEN_TASKS.md**: Repo-root project status maintained by the lead: Done / In progress / Next / Needs the user / Known risks. The working-tree rewrite numbers items 1–14 (In progress: 1 v2 data, 2 Demos; Next: 3 data checks … 8 EVAL, 9 Model package, 10 demo rerun, 11 publish 0.1.0, 12 CI (done), 13 Docs, 14 Review fixes); cite items by title, since numbers change. Doc: [status-and-known-issues](status-and-known-issues.md). +- **OPEN_TASKS.md**: Repo-root project status maintained by the lead: Done / In progress / Next / Model quality / Needs the user / Known risks. In the merged tree ("as of ~05:45 UTC"): In progress 1 `r17-v2a`, 2 `t150-v2a`, 3 REAL v2 data, 4 one-command install (not in the published alpha.1), 5 Demos; Next 6 data checks … 11 EVAL, 12 Model package, 13 demo rerun, 14 next prerelease with the install, 15 publish 0.1.0, 16 CI, 17 Docs, 18 Review fixes. Cite items by title, since numbers change. Doc: [status-and-known-issues](status-and-known-issues.md). - **opLabel / opPhrase**: How ops are worded in model text: `opPhrase` gives `<signature><detail>` for requests (e.g. `GET /api/search?q=re`), the user phrase for user ops, `task <name>` and `GenClass <name>`; `opLabel` = `<opPhrase truncated to 90> (#id)`, or `an earlier operation` when the op is unknown. Also used in `ActionEffect.changed` sentences. Code: `packages/runtime/src/situation/describe.ts` -> `opPhrase`, `opLabel`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **oracle (demos)**: Per-demo scorer (`start`, `check`, `finish` -> `Score { bug, reasons, metrics }`) that samples the DOM with native timers and reads the mock server's truth and log; never passed to GenClass or the app. Code: `demos/src/shared/demo-def.ts` -> `Oracle`. Doc: [demos](demos.md). - **ORT / ORT build**: ORT = onnxruntime-web, the runtime's only dependency. The ORT build is the bundle the backend imports: `webgpu` (`onnxruntime-web/webgpu`, asyncify wasm, WebGPU and WASM execution providers) when any WebGPU plan exists, else `wasm` (`onnxruntime-web/wasm`, CPU only); reported as `status.ortBuild`. Doc: [model-host](runtime/model-host.md). @@ -304,6 +314,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **pill (devtools)**: The collapsed overlay button: mode, intervention and detection counters, a model-status dot and a load progress bar; it pulses on new items. Doc: [devtools](runtime/devtools.md). - **plan (model load)**: A `{ variant, device }` pair the backend tries in order: `webgpu+fp16` (needs `shader-f16`) -> `webgpu+q8` -> `wasm+q8` (`wasm+fp16` when there is no q8 variant); the first plan that passes its warm-up wins. Code: `packages/runtime/src/model/loader.ts` -> `planOrder`. Doc: [model-host](runtime/model-host.md). - **plugin**: `Plugin { name, setup?(api), facts?(draft), actions?, questions?, diagnoses? }`, installed with `rt.use(plugin)` or the `plugins` option. Plugin facts are always neutral (they cannot make a trigger salient), plugin actions default to the heal tier, plugin diagnosis labels are appended if new. `PluginApi` offers `runtime`, `clock`, `emit`, `recordOp` / `endOp` / `runInOp`, `user`, `reportError`, `on`, `stores`. Code: `packages/runtime/src/types.ts` -> `Plugin`, `PluginApi`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.use`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). +- **Polar Parts**: `MeharPro/Polar-Parts`, the storefront where the runtime is to be installed once the trained model is good (user OK'd; `OPEN_TASKS.md` "Needs the user", rollout plan from 2516a6e): observe mode on a branch first, verify the storefront is unchanged, then guard. Doc: [status-and-known-issues](status-and-known-issues.md). - **policy gate**: The final check between the model's answer and an action (runtime CONTRACT §8, the "summed-mass gate"): an action runs only if the runtime is not paused, the permitted set's mass ≥ the candidate tier's threshold (guard 0.9, heal 0.8), the top diagnosis is not `expected` (`requireDiagnosis`), fewer than `maxActionsPerMinute` (60) actions ran in the last minute, and, for holdable triggers only (delivery, request, fetch failure, held mutation), the subject is still held (otherwise late-revert rules apply). It only filters what the model chose; `training/eval_runtime.py` mirrors it. Code: `packages/runtime/src/decide/policy.ts` -> `gate`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md), [training](training.md). - **predicted write set (P)**: For a delivery, the field patterns the op's chain is expected to write: from its signature's transition profile (`Profile.wrote`), else what the last completion of its signature wrote (`SitEnv.lastChain`), else unknown. Stated in the delivery trigger sentence and fact D4; delivery salience, matched fields and *covered writes* are computed against it. Code: `packages/runtime/src/situation/conflicts.ts` -> `predictedWrites`, `matchFields`, `Predicted`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **prefix-mismatch**: See *fp (fingerprint, sim)*. @@ -321,18 +332,19 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## R -- **R17**: Runtime model candidate initialised from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers, fresh heads) with the pruned 16,364-token vocabulary: 8.1M + 0.7M head parameters, q8 9.58 MB, fp16 13.6 MB; WASM single-thread ≈ 177 / 323 / 589 ms at 500 / 780 / 1,170 tokens. Chosen as the default on every device after final round 1 (RESULTS.md §2); the existing R17 checkpoints are situation-v1 and must be retrained (distilled) for v2. Doc: [training](training.md), [model-host](runtime/model-host.md)., [RESULTS.md](../runtime/RESULTS.md) +- **R17**: Runtime model candidate initialised from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers, fresh heads) with the pruned 16,364-token vocabulary: 8.1M + 0.7M head parameters, q8 9.58 MB, fp16 13.6 MB; WASM single-thread ≈ 177 / 323 / 589 ms at 500 / 780 / 1,170 tokens. Chosen as the default on every device after final round 1 (RESULTS.md §2); the round-1 R17 checkpoints are situation-v1; the first v2 R17 is *r17-v2a* (trained directly on v2 gold, not distilled). Doc: [training](training.md), [model-host](runtime/model-host.md)., [RESULTS.md](../runtime/RESULTS.md) +- **r17-v2a**: The first situation-v2 model run: R17 from `r17-final1` on `mix_v2a` (sim2 0.86, cur5 0.11, cur1 0.02, gen 0.01), 4 × 500M tokens, 64 ranks on c09, c03–c08, c13, launched 05:14 UTC 2026-10-08, ETA ≈ 06:20; `training/v2_post.sh` (detached on c09) evaluates `sim2e` and `sim2f`, expected gain, exports q8/fp16 with the `sim2e` calibration and serves the tar on :8801 (`training/LOG.md`). Not distilled from a teacher. Results are only on `origin/runtime` (416e374, not merged): `sim2e` diagnosis 84.4%, action 77.9%, guard FIR 0.00%, heal FIR 0.46%; real-app eval set FIR 0.00%; recall at the fixed 0.9/0.8 gates very low, which motivated batch 6's model-provided thresholds. Not published. Doc: [training](training.md). - **r300k**: The pre-freeze SIM run used for the stage-2 pilot, imported as bucket `sim1`. Doc: [training](training.md). - **R32**: Runtime model candidate initialised from GenClass 0.1 `jev-local-fast` (ettin-32m, d 384, 10 layers, v1 heads) with the pruned 16,364-token vocabulary: 18.8M + 1.6M head parameters, q8 22.5 MB, fp16 34.8 MB. In final round 1 it matched R17 at about 3× the size and latency, so it is not the default; it remains a distillation student in PLAN-v1. - **R68**: Student benchmark candidate on `ettin-encoder-68m` (≈ 42M parameters, pruned vocabulary) in PLAN-v1, with `mix_r68.json` and `training/launch_r68.sh`; never run. Doc: [training](training.md). Doc: [training](training.md), [model-host](runtime/model-host.md). - **rate limit**: `policy.maxActionsPerMinute` (default 60): a sliding 60 s window of non-passive actions. When full, the gate refuses with `rate limit: …`, and a status line is emitted at most once a minute. Code: `packages/runtime/src/decide/policy.ts` -> `RateLimiter`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **raw logits**: Head outputs at τ = 1 (`choice_logits`, `score_logits`, `noul_logits`) before calibration; what PyTorch parity fixtures and calibration fitting use. Doc: [model-io-contract](model-io-contract.md). - **read-your-writes (fact)**: Batch-5 fact (SEPARABILITY's F4 idea): create responses (POST, or 201) are parsed in the background (`RuntimeImpl.noteResponse`, `createdIds`), and a list loaded by a request that started after the create is checked for the created item: "… created item "weekend" 0.10s ago (201), and does not contain it." / "… contains item … twice". Salient. Used for lists in delivery bodies, mutation values, inconsistency and transition fields, within `RYW_WINDOW_MS` (10 s). Review finding: every successful JSON POST counts as a "create". Code: `packages/runtime/src/situation/content.ts` -> `rywFacts`, `createdIds`, `RYW_WINDOW_MS`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **REAL (workstream)**: Owns `realapps/` and the real-browser training data (`training/NEEDS.md` items 13–16; batches `v2b1`–`v2b3` on c01, c10, c11 into `train:/data/real-out/`); a colleague-side workstream added after 654d822, and the source of batch 5's "real-app text fixes". Doc: [realapps](realapps.md). -- **realapps**: The real-browser corpus in `realapps/` (fcb8189): 91 apps at b435acb (77 written for it + 14 open-source RealWorld "Conduit" front-ends; READMEs still say 66) across 23 frameworks, run in headless Chromium with the real runtime bundled from source, on virtual time with an in-page mock backend and chaos. It labels decisions by counterfactual outcome with the sim's cost weights and label rule and writes CONTRACT-D rows (`meta.source = "realapps"`, ids `real-<app>-<seed>-…`), and hosts the *never-worse* and *determinism* sweeps. Not a workspace, not in CI, no tests; everything real needs Chromium or Azure (ask first). Doc: [realapps](realapps.md). -- **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when `isSensitivePath(path, value)` holds: since fcb8189 the rule looks at the leaf field name by meaning (words and secret pairs such as password, token, card number, api key, ...), with container rules (a strong secret container redacts strings beneath it, a broad one only opaque-looking strings), never at the store's name. Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Review findings: numbers and arrays under a secret container are no longer redacted, the F2 diff preview can print redacted text, and `docs/runtime/CONTRACT.md` still describes the old substring rule; use a custom redactor for app-specific secrets. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). +- **REAL (workstream)**: Owns `realapps/` and the real-browser training data (`training/NEEDS.md` items 13–16; batches `v2b1`–`v2b3`, then `v2c1`–`v2c4` on c01, c10, c11 and `data`, into `train:/data/real-out/`); a colleague-side workstream added after 654d822, and the source of batch 5's "real-app text fixes". Doc: [realapps](realapps.md). +- **realapps**: The real-browser corpus in `realapps/` (fcb8189): 128 app directories at f107013 (91 at b435acb; 114 written for it + 14 open-source RealWorld "Conduit" front-ends; READMEs still say 66, Mehar's wave-3 commit says 96) across 23+ frameworks, run in headless Chromium with the real runtime bundled from source, on virtual time with an in-page mock backend and chaos. It labels decisions by counterfactual outcome with the sim's cost weights and label rule and writes CONTRACT-D rows (`meta.source = "realapps"`, ids `real-<app>-<seed>-…`), and hosts the *never-worse* and *determinism* sweeps. Not a workspace, not in CI, no tests; everything real needs Chromium or Azure (ask first). Doc: [realapps](realapps.md). +- **redaction**: The `redact(path, value)` option (return something `!==` value to redact). The default `defaultRedact` returns `"[redacted]"` when `isSensitivePath(path, value)` holds: since fcb8189 the rule looks at the leaf field name by meaning (words and secret pairs such as password, token, card number, api key, ...), with container rules, never at the store's name. Since f107013 a strong secret-named container redacts numbers, bigints and arrays beneath it as well as strings (`payment.cvv.value`, `login.otp.code`), booleans and null stay visible, and a broad container (`auth`, `session`, `cookie`) still redacts only opaque-looking strings; diff previews (F2, `changeText`) are built only for values the redactor leaves unchanged (`redactedStringDiff`). Applied by the hub, the invariant miner, observers, `emit`, `user` and situation building. Known gaps (STATUS "Fix after 0.1.0-alpha.1"): a container named by a secret word pair (`cardNumber`, `apiKey`) counts as broad; `docs/runtime/CONTRACT.md` still describes the old substring rule; `training/curriculum/rt.py` has no redactor. Use a custom redactor for app-specific secrets. Code: `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath`; `packages/runtime/src/state/fields.ts` -> `redactedStringDiff`; test `packages/runtime/test/redaction-v2.test.ts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **relation (sim)**: An app-declared executable invariant (`Relation { fields, desc, check(stores) }`, e.g. count = len(items), total = Σ price × qty, badge = cart count); ground truth for the `inconsistent` diagnosis and a cost term. Code: `sim/src/app/feature.ts` -> `Relation`. Doc: [sim](sim.md). -- **RELEASE.md**: Repo-root release procedure (untracked at b435acb, committed in b561244): Part A `0.1.0-alpha.1` (planned under dist-tag `alpha`, published under `latest` on 2026-10-08); Part B `@genclass/runtime-model@0.1.0` (plus the `runtime-model-v0.1.0` GitHub release), then the runtime. Only the user publishes. Doc: [RELEASE.md](../../RELEASE.md). +- **RELEASE.md**: Repo-root release procedure (untracked at b435acb, committed in b561244): Part A `0.1.0-alpha.1` (planned under dist-tag `alpha`, published under `latest` on 2026-10-08); Part B `@genclass/runtime-model@0.1.0` (plus the `runtime-model-v0.1.0` GitHub release), then the runtime. Only the user publishes. It has no part yet for the *next release* with the install paths. Doc: [RELEASE.md](../../RELEASE.md). - **render bits (devtools)**: Dirty flags `STATUS=1, MODE=2, LISTS=4, EVENTS=8` (ALL=15) OR'ed by `mark()` and flushed once per animation frame; LISTS and EVENTS are deferred while the panel is closed or paused. Doc: [devtools](runtime/devtools.md). - **repeat folding (devtools)**: Detections with the same `repeatKey` (trigger, diagnosis, action and subject, digits normalised) within 60 s of a card's latest repeat fold into one card with a `×N` badge. Code: `packages/runtime/src/devtools/ui.ts` -> `repeatKey`. Doc: [devtools](runtime/devtools.md). - **replay (training)**: Curriculum (`cur1`–`cur4`) and GenClass 0.1 (`gen`, `cu`) buckets mixed into SIM-based rounds. Doc: [training](training.md). @@ -379,17 +391,20 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **shape / Unusual**: See *transition profile*. - **SIM (workstream)**: Owns `sim/`; writes `sim/NEEDS.md`, `sim/README.md`, `sim/SEPARABILITY.md` and the training data (`sim/out/` locally, gitignored; v2 production on Azure into `train:/data/sim-out/v2-*` via `sim/scripts/cluster/`). Doc: [status-and-known-issues](status-and-known-issues.md), [sim](sim.md). - **sim op / sim write**: The sim's app-level ground-truth records, not runtime ops: `SimOp` (a request with role, intent, key, idempotent, attempt, `retryOf`, `dupOf`, `classify()`, linked runtime op id) and `SimWrite` (a store write with role, op, intent, key, changed fields, anomaly, `classify()`, linked runtime mutation). Code: `sim/src/oracle/knowledge.ts` -> `SimOp`, `SimWrite`. Doc: [sim](sim.md). -- **simA / sim1 (buckets)**: Training buckets of SIM data: `simA` = phase A (`final-a`, frozen format; 448,420 / 14,613 / 137,643 rows), `sim1` = the pre-freeze run `r300k` (224,051 / 7,426 / 68,790). `simAe` (8k dev / 20k test) and `sim1e` (20k test) are random eval subsets; `simsample` is the 200-row `sim/samples/sample.jsonl`. Doc: [training](training.md). +- **simA / sim1 (buckets)**: Training buckets of SIM data: `simA` = phase A (`final-a`, frozen format; 448,420 / 14,613 / 137,643 rows), `sim1` = the pre-freeze run `r300k` (224,051 / 7,426 / 68,790). `simAe` (8k dev / 20k test) and `sim1e` (20k test) are random eval subsets; `simsample` is the 200-row `sim/samples/sample.jsonl`. The v2 buckets are *sim2 / sim2e / sim2f / cur5*. Doc: [training](training.md). +- **sim2 / sim2e / sim2f / cur5**: The v2 training data on the workbench c02 (`training/import_v2.sh`, `training/prep_v2.py`; `training/LOG.md` 04:50–05:22): `sim2` = 128 train shards of SIM v2 gold (`train:/data/sim-out/v2-gold`: train 7,560,367 / dev 317,732 / test 2,545,756); `sim2e` = 20k held-out test + 8k dev rows; `sim2f` = 18,690 held-out-**feature** test rows (swcache, presence, cascade, saga, prefetch, permissions); `cur5` = 300k v2 curriculum replay rows (seed 15, 80% runtime-exact). A 27 GB tar served from c02:8799 feeds the nodes (`training/v2_node_setup.sh`). Doc: [training](training.md). - **SitEnv**: The read-only view of the runtime that situation code receives (ops, hub, baselines, profiles, events, redactor, cache peek, identical requests, consistent snapshots, `storeWriters`, `chainWrites`, ...), implemented by `RuntimeImpl.makeEnv`. Code: `packages/runtime/src/situation/env.ts` -> `SitEnv`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.makeEnv`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **situation**: The model input for one trigger: a `JevState` with seven keys in fixed order, `app`, `trigger` (the subject sentence), `facts`, `in_flight`, `timeline`, `state` (store field lines), `stats` (signature baselines), shaped to the situation budget, plus the typed `questions`. The `Situation` object (`rt.situation()`, `buildSituation`) also carries `trigger, subject, actions, salient, facts, compact, budget`, which the model does not read. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). - **situation budget**: The situation's size in characters as measured by `stateChars`: `STATE_CHAR_BUDGET` 2400 (full; 3200 in situation-v1, lowered in batch 4), `COMPACT_BUDGET` 1100 (smallest section limits), floor `MIN_BUDGET` 500, linear in between (`sectionLimits`). `situation.budget: "auto"` (default) gives 2400 for WebGPU or an unknown device and 1000 / 1333 / 1667 / 2000 for WASM with 1 / 2 / 3 / 4+ threads, times the budget scale; a number is used as is. Over budget, `toJevState` drops timeline lines (oldest first), then state, facts (keeping ≥ 1), in-flight and stats lines, then shortens facts and the trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **situation-v1**: Annotated git tag on commit 1a77558 ("Frozen runtime situation format for model training"), the previous training format: SIM phase A/B, `cur4` and final round 1 (the R17/R32 checkpoints that exist) use it. Superseded by *situation-v2*; nothing trained on v1 matches the current runtime. -- **situation-v2**: Annotated git tag on commit 6e5e86e ("Frozen runtime situation format v2"), the **current** frozen training format: batches 4 and 5 (the *delivery* trigger, non-blocking mutations, conflicts, F1–F9, 2,400-char budget, leaf redaction). The v2 SIM gold/unlabeled data, REAL batches `v2b1`–`v2b3` and `training/curriculum/rt.py` ("FROZEN at git tag `situation-v2`") target it; no v2 model exists yet. On `mvp-v2`, `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts`, `types.ts` and `devtools/index.ts` (the default mode), not model input. Any change to text the model reads (situation code, `learn/`, `util.ts` formatters, `state/fields.ts` `changeText`/`stringDiff`, questions, vocabulary, budgets) needs a new tag, regenerated SIM and REAL data, a matching `rt.py` change and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference. Doc: [model-io-contract](model-io-contract.md), [learn-situation-triage](runtime/learn-situation-triage.md). Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). +- **situation-v2**: Annotated git tag on commit 6e5e86e ("Frozen runtime situation format v2"), the **current** frozen training format: batches 4 and 5 (the *delivery* trigger, non-blocking mutations, conflicts, F1–F9, 2,400-char budget, leaf redaction). The v2 SIM gold/unlabeled data, REAL batches `v2b1`–`v2b3` and `training/curriculum/rt.py` ("FROZEN at git tag `situation-v2`") target it; no v2 model exists yet. On `mvp-v2` (b435acb) the diff from the tag touched no model input; on `mvp-v2-merge`, f107013 (redaction) changes the text of redacted values (`situation/content.ts`, `state/fields.ts`, `util.ts`) without a new tag, and the v2 data and r17-v2a predate it. `origin/runtime` has since tagged *situation-v2.1*. Any change to text the model reads (situation code, `learn/`, `util.ts` formatters, `state/fields.ts` `changeText`/`stringDiff`, questions, vocabulary, budgets) needs a new tag, regenerated SIM and REAL data, a matching `rt.py` change and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference. Doc: [model-io-contract](model-io-contract.md), [learn-situation-triage](runtime/learn-situation-triage.md). Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). +- **situation-v2.1**: Tag on `origin/runtime` 5bc40c9 (runtime batch 6, not merged into `mvp-v2-merge`): situation-v2 plus one new neutral fact (requests with no latency baseline raise a stall after 10 s in flight); existing situation text unchanged; batch 6 also lets the model's `meta.json` supply gate thresholds. Doc: [status-and-known-issues](status-and-known-issues.md). - **skill (jevbench)**: `clip((m − c) / (1 − c), 0, 1)` for primary metric `m` and chance level `c`. Code: `jev_local/bench/metrics.py` -> `skill`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **slot (VM slot)**: A per-workstream directory `~/gcl/<SLOT>` on the Azure `train` VM used by `scripts/vm.sh` (names `[a-zA-Z0-9_-]+`, conventionally `core`, `model`, `sim`, `demos`). `sync` uses `rsync --delete`, so files created in a slot outside the excluded paths are removed on the next sync. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). - **smoke test**: `packages/runtime/test/smoke/smoke.sh`: build, `npm pack`, install the tarball into a temporary Vite 8 app, build it and load it in headless Chromium (Playwright) on port 4191, requiring no errors, a devtools element and ≥ 3 history events; runs with `model: false`. Doc: [build-test-release](runtime/build-test-release.md). - **Spec (benchmax)**: Registry entry `{ id, suite, adapter, harness, verification, counted_rows, description, owner }` whose `id` equals a `targets.json` `spec_id` byte for byte; 19 are registered (4 group A, 15 group B). Code: `jev_local/bench/benchmax/__init__.py` -> `Spec`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **split (sim)**: Decided per scenario: test = a held-out domain, a held-out family hash (first 17%), a held-out pattern or (since round 2) a held-out feature (`TEST_FEATURES`, disabled by `SIM_FEATURE_HOLDOUT=off`); dev = 3% of the remaining families; only 33% of test trajectories are kept (`--test-keep`). All rows of a trajectory share its split. realapps has its own held-out apps and frameworks (`TEST_APPS`, `TEST_FRAMEWORKS`). Code: `sim/src/world/scenario.ts` -> `splitOf`. Doc: [sim](sim.md). +- **SRI (script tag)**: The `integrity="sha384-…"` attribute `init` adds to the script tag for plain-HTML projects, hashed from the CLI's own local `dist/genclass.global{,.min}.js`. It covers only the loader (the worker, ORT chunks and devtools are loaded by `import()` without integrity), and it is also added to any `--cdn` URL whose filename matches, even one for another version, which the browser then blocks (`--no-sri`, undocumented, turns it off). Code: `packages/runtime/bin/lib/plan.mjs` -> `integrityFor`, `scriptTag`. Doc: [status-and-known-issues](status-and-known-issues.md#install-code-review-2026-10-08). - **stage 1 / 1c / 2 (training)**: Training rounds before the freeze: s1 = curriculum `cur1` + `gen`/`cu` replay (`mix_s1`); s1c = continuation with runtime-exact `cur2` (`mix_s1c`), the current best checkpoints (`rt1` action ≈ 98%, FIR 0%); s2 = pilot on the pre-freeze SIM run `r300k` (`mix_s2`), precise but with heal recall ≈ 1.3%. Final rounds restart from the s1c weights. Doc: [training](training.md). - **staged evaluation (extension)**: The extension first asks the `STAGE1` questions (intent, complete, is_command, destructive) and, only when the policy returns `need_args`, the argument question the intent needs (`ARG_QUESTIONS[intent]`); exact because questions are block-isolated in the attention mask. Code: `extension/src/core/policy.js` -> `evaluatePolicy`, `ARG_QUESTIONS`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **stale mark (F9)**: `StaleMark { t, op, why }` on a field's `FieldState.mark`, set by `RuntimeImpl.markWrites` / `RuntimeImpl.onChannel` when a write is known to be suspicious (its response was delivered over newer data or a pending local change without a decision to drop it, took ≥ 5× its usual time, followed an ambiguous failure, or came from a push channel that had been down) and cleared by the next write. Stated by fact F9 in later delivery, mutation, inconsistency, transition and error situations. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.markWrites`; `packages/runtime/src/situation/evidence.ts` -> `markFacts`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). @@ -398,7 +413,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **standing question**: `StandingQuestion { id, on, question, always?, onAnswer? }`, registered with `rt.question` or a plugin: asked next to `diagnosis` / `action` on its triggers; `always: true` makes the trigger *forced* (bypasses triage); `onAnswer` receives the answer after the decide/detect events, before any action. Docs also call the built-in `diagnosis` and `action` questions "standing questions". Code: `packages/runtime/src/types.ts` -> `StandingQuestion`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **state (section)**: The `state` key inside a situation, not the whole `JevState`: lines `<path> = <value> (v<version>[, by #writer] <secs> ago)` for the involved fields first, then fields of all involved stores, most recent write first; a store registered with `describe` contributes one line instead. Code: `packages/runtime/src/situation/build.ts` -> `stateLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **stats (section)**: The situation section of baseline lines for the subject op's signature and every in-flight fetch/XHR signature: `<sig>: <count> done[, median <secs>, p95 <secs>], <failed> of last <of> failed, <recent> in last 10s[ (usual <n>)]`. Code: `packages/runtime/src/situation/build.ts` -> `statsLines`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). -- **STATUS.md**: `packages/runtime/STATUS.md`, CORE's status file read by SIM, DEMOS, UI and MODEL: test state, batch changes, the headless recipe, the trigger table, example situations, "Deviations from the contract (and why)" and "Open issues". Now also the batch 4 and 5 sections and the never-worse sweep; last changed in bac4409 (it predates `default-mode.test.ts`, so its "41 files, 346 tests" excludes that file). Doc: [status-and-known-issues](status-and-known-issues.md). +- **STATUS.md**: `packages/runtime/STATUS.md`, CORE's status file read by SIM, DEMOS, UI and MODEL: test state, batch changes, the headless recipe, the trigger table, example situations, "Deviations from the contract (and why)" and "Open issues". In the merged tree it also has "Fix after 0.1.0-alpha.1: two redaction leaks" (f107013) and "Fix after batch 5: situation() purity" (29b7f28), and says 42 files / 348 tests (VM); its "Updated" line still names batch 5 and nothing describes 054da38 yet. Doc: [status-and-known-issues](status-and-known-issues.md). - **stick**: `Context.stick(op)`: makes `op` ambient until `clock.afterTask` clears it at the end of the macrotask (only if it is still that op); done when a fetch/XHR/Response body settles, a user action is recorded, a timer fires, a WS message arrives or `rt.op` settles. Code: `packages/runtime/src/trace/context.ts` -> `Context.stick`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **store / StoreHub**: Every store registered with a runtime lives in one `StoreHub`, keyed by a store name that is global per runtime. The hub holds the three store kinds (*atom*, *guard*, *adapter*), the mutation pipeline, per-field versions and logs, recent changes, late-revert primitives and snapshots. Code: `packages/runtime/src/state/hub.ts` -> `StoreHub`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **storeWriters**: `Map<signature, Map<store, count>>` learned in `RuntimeImpl.onApplied` (the writer plus up to 8 ancestors; ≤ 1000 signatures): how often each signature's chain wrote each store. Used for involved stores, timeline relevance, concurrency facts and `defer`'s related ops. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onApplied`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). @@ -414,7 +429,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# ## T - **T1 (expected-gain target)**: TRAIN's proposal from SEPARABILITY §5/§7: train on expected advantage instead of "probability of being best", either by relabelling the action as softmax(gain/τ) (`r17-t1g10` τ 1, `r17-t1g20` τ 2; buckets `simAg10`/`simAg20`) or by keeping SIM's label and adding a *gain head* (`r17-t1h`, bucket `simAh`), then gating on predicted gain per action. All three runs were on v1 data and were stopped at the v2 freeze with no results; T1 labels put ≥ 0.5 non-passive mass on 64% of rows, so they must be evaluated with `eval_gain.py`'s `gain>m` / `head>m` policies, not the summed-mass gate. Not the runtime's transition fact T1. Code: `training/t1_relabel.py`, `training/eval_gain.py`. Doc: [training](training.md). -- **T150 / teacher**: The *teacher* is a large model that is never shipped (T150 = `ettin-encoder-150m`, ≈ 111M parameters, pruned vocabulary, fresh heads; T400 only if T150 clearly beats R68). It is trained on gold rows, then its calibrated probabilities become `dist` labels on unlabeled rows (`training/label_teacher.py`, across nodes `training/label_cluster.sh`, which is untested) for *distillation*. The only teacher run so far, `t150-g1` on v1 data (`mix_t150`), was stopped at step 69 at the v2 freeze; HANDOFF's next step is a 150M teacher on v2 gold. Code: `training/launch_t150.sh`, `training/label_teacher.py` -> `main`. Doc: [training](training.md). +- **T150 / teacher**: The *teacher* is a large model that is never shipped (T150 = `ettin-encoder-150m`, ≈ 111M parameters, pruned vocabulary, fresh heads; T400 only if T150 clearly beats R68). It is trained on gold rows, then its calibrated probabilities become `dist` labels on unlabeled rows (`training/label_teacher.py`, across nodes `training/label_cluster.sh`, which is untested) for *distillation*. The v1 teacher run `t150-g1` (`mix_t150`) was stopped at step 69 at the v2 freeze; the v2 teacher is *t150-v2a*. Code: `training/launch_t150.sh`, `training/label_teacher.py` -> `main`. Doc: [training](training.md). +- **t150-v2a**: The v2 teacher run: T150 from the MIT ettin-150m base (pruned vocabulary, fresh heads) on `mix_t150v2` (sim2 0.9, cur5 0.1), 2 × 500M tokens, 88 ranks on c12, c14–c23, launched 05:20 UTC 2026-10-08, ETA ≈ 08:30 (`training/LOG.md`); SIM gold only, a continuation run adds REAL `v2c*` gold. No result is recorded yet. Its labels on the unlabeled rows feed distillation. Doc: [training](training.md). - **Tail / vid (extension)**: `Tail` is the unconsumed transcript `{ vid, text, words, cursor, isFinal, silentMs, uid, joined }`; `vid` is the virtual utterance id `"<uid>+<gen>"`, where `gen` increments on every consume. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **templates (devtools)**: `actTitle`, `diagTitle` and `phrase`: card titles used when no report sentence is known; they approximate the wording of `packages/runtime/src/decide/report.ts`. Code: `packages/runtime/src/devtools/ui.ts` -> `actTitle`, `diagTitle`, `phrase`. Doc: [devtools](runtime/devtools.md). - **tier**: The mode an action needs: `passive` (always allowed), `guard` (withhold, deduplicate or slow down: `discard`, `defer`, `coalesce`, `delay`) or `heal` (change what the app receives or restore state: `block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`; custom actions by default). The policy gate compares the mode with the tier and uses the tier's threshold (guard 0.9, heal 0.8). Code: `packages/runtime/src/types.ts` -> `Tier`; `packages/runtime/src/situation/questions.ts` -> `BUILTIN_ACTIONS`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). @@ -443,7 +459,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **UI (workstream)**: Owns `packages/runtime/src/devtools/**` and `packages/runtime/src/adapters/**` (CONTRACT §13; §1's table still says CORE); writes `packages/runtime/UI-NEEDS.md`. Doc: [status-and-known-issues](status-and-known-issues.md). - **undo**: `ActionRecord.undo()`, present only for reversible effects (discard, late revert, rollback, chain revert, custom `onUndo`): idempotent, runs inside a GenClass op named `undo`, never gated, pushes an `action` event `undid <action> (<id>)`, and fires no `act` event or report. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.onDecision`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **unholdable**: See *detached preview / unholdable*. -- **unlabeled rows**: SIM's cheap row mode (`gen.js --unlabeled`): one base run per scenario (exploration × 1.5, ask probes always on), every decision point becomes a row with the gold `diagnosis` (when correlated) but no action label; ids `u-<seed>-d<k>`, `meta.unlabeled: true`. About 150 rows/s per worker vs about 4.4 for gold. They exist to be soft-labelled by the *teacher*; SIM v2 targets ≥ 50M of them (seeds from 16e9), REAL writes `-u<k>` rows too. Review finding: their hard `expected` diagnoses ignore S1, and `label_teacher.py` keeps existing labels unless `--overwrite`. Code: `sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`. Doc: [sim](sim.md), [training](training.md). +- **unlabeled rows**: SIM's cheap row mode (`gen.js --unlabeled`): one base run per scenario (exploration × 1.5, ask probes always on), every decision point becomes a row with the gold `diagnosis` (when correlated) but no action label; ids `u-<seed>-d<k>`, `meta.unlabeled: true`. About 150 rows/s per worker vs about 4.4 for gold. They exist to be soft-labelled by the *teacher*; SIM v2 produced 51,272,078 of them (seeds from 16e9), REAL writes `-u<k>` rows too. Review finding: their hard `expected` diagnoses ignore S1, and `label_teacher.py` keeps existing labels unless `--overwrite`. Code: `sim/src/gen/trajectory.ts` -> `unlabeledTrajectory`. Doc: [sim](sim.md), [training](training.md). - **untrustedEvents**: `observe.untrustedEvents` (default `false`, batch 4): whether synthetic DOM events (`isTrusted === false`, e.g. `el.dispatchEvent(new MouseEvent("click"))`, testing-library) count as user actions. Off, they are dropped, so scripted drivers that are not real browser input (the demos' in-page synthetic driver, unit tests) record no user ops unless they opt in; realapps turns it on for its scripted user (`realapps/src/harness/trajectory.ts` -> `OBSERVE`). It is a flag in the `observe` map, not an observer. Code: `packages/runtime/src/types.ts` -> `InitOptions.observe`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.installObservers`; `packages/runtime/src/observe/dom-user.ts` -> `installDomUser`. Doc: [observe-and-trace](runtime/observe-and-trace.md). - **user model (sim)**: `UserModel`: think times (`max(120, lognormal)` ms), per-keystroke typing with typos and backspaces, accidental double clicks and impatient re-clicks guarded by `when` conditions; accidental steps carry `repeatOf`. Code: `sim/src/app/feature.ts` -> `UserModel`. Doc: [sim](sim.md). - **user-sync write**: A write whose cause is the current task's user op or shares its root (`Context.isUserSync`); it bypasses gating and is never held unless `policy.holdUserWrites` is true. Code: `packages/runtime/src/trace/context.ts` -> `Context.isUserSync`. Doc: [state-and-adapters](runtime/state-and-adapters.md). @@ -453,7 +469,9 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **v0.1 fixture set**: `packages/runtime/test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests with the Python packer output and PyTorch logits of the v0.1 GenClass model. Doc: [build-test-release](runtime/build-test-release.md). - **v0.1 model**: See *GenClass 0.1 (v0.1 model)*. - **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, the first published alpha; since 2026-10-08 `latest` is `0.1.0-alpha.1` (tag `v0.1.0-alpha.1` on 806a296, local only). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) -- **v2b1 / v2b2 / v2b3 (REAL batches)**: REAL's situation-v2 production batches on c01, c10 and c11 (30k trajectories each, about 495k gold rows in total per HANDOFF/RESULTS; NEEDS target ≥ 500k), to be copied to `train:/data/real-out/` (`training/NEEDS.md` item 16; not verifiable from the repo). Their `manifest.json` still says `situation-v1` (hardcoded in `realapps/src/harness/gen.ts`). Doc: [realapps](realapps.md). +- **v2b1 / v2b2 / v2b3 (REAL batches)**: REAL's first situation-v2 production batches on c01, c10 and c11 (planned 30k trajectories each). Per `training/NEEDS.md` item 16 (eff18cb) they stopped at ≈ 20.5k trajectories each (≈ 380k gold, 66 apps) with **pre-fix diagnosis labels**: action labels valid, diagnosis labels only with the NEEDS filter; use *v2c1–v2c4* instead. Their `manifest.json` says `situation-v1` (hardcoded in `realapps/src/harness/gen.ts`). Doc: [realapps](realapps.md). +- **v2c1–v2c4 (REAL batches)**: REAL's situation-v2 batches with fixed labels: 96 apps, 4 × 20k trajectories on c01, c10, c11 and `data`, expected ≈ 530k gold + ≈ 500k unlabeled; the real-app eval set `v2-eval` is built from them (`training/NEEDS.md` item 16, "USE THESE"). Not landed at eff18cb; `origin/runtime` 6d6eb00 (not merged) reports REAL v2 production done: 616,437 gold, eval set 16,600. Doc: [realapps](realapps.md). +- **v2_post.sh**: `training/v2_post.sh RUN NAME VERSION`, run detached on a v2 run's rank-0 node: waits until `models/RUN/meta.json` says `final`, runs `eval_sim.sh` on `sim2e` and `sim2f`, `eval_gain.py`, then `export_runtime.py` with the `sim2e` calibration, and serves the export tar on :8801. It replaces the v1-wired `final_post.sh` for v2; it publishes nothing. Running for *r17-v2a* on c09. Doc: [training](training.md). - **variant (jevbench)**: Request flavour per item: `main` (the only one counted), `shuffle` (option-order rotation), `bare` (no descriptions), `choice` (SST-2 only). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **variant (model)**: One ONNX file of a model, keyed in `card.variants`: `q8` (meant for WASM) or `fp16` (meant for WebGPU with `shader-f16`). See *q8*, *plan*. Doc: [model-host](runtime/model-host.md). - **varied style**: See *runtime-exact row / varied style (curriculum)*. @@ -468,11 +486,11 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **W1–W11**: Engine and wire requirements for benchmax runs from `docs/benchmax-research/suite-reproduction-specs.md` §1.2 (e.g. W1 choice = argmax of unrounded probabilities with ties to the first key, W2 score fields, W3 precision, W4 refusal bodies, W5 overflow refuse/truncate, W9 one global calibration file, W10 model id never `jev-*`, W11 determinism). Code: `jev_local/bench/benchmax/runner.py` -> `check_model_id`; `jev_local/api.py` -> `ServeConfig`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md), [genclass-model-lineage](genclass-model-lineage.md). - **wait (action)**: Passive action of the `stall` trigger: keep waiting for the response. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). -- **waits**: In `RuntimeImpl.trigger`: `opts.hold`, at least one non-passive action permitted by mode and policy, not paused, and (since batch 4) the expected model latency fits the hold budget (`expectedLatency() <= holdBudgetMs()`): whether the subject is actually held. A holdable trigger that does not wait runs its passive action at once and is decided in the background (detection only, `BACKGROUND_DEADLINE_MS` 5 s), which is what every trigger does in the default `observe` mode. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). +- **waits**: In `RuntimeImpl.trigger`: `opts.hold`, at least one non-passive action permitted by mode and policy, not paused, and (since batch 4) the expected model latency fits the hold budget (`expectedLatency() <= holdBudgetMs()`): whether the subject is actually held. A holdable trigger that does not wait runs its passive action at once and is decided in the background (detection only, `BACKGROUND_DEADLINE_MS` 5 s), which is what every trigger does in the default `observe` mode. For a delivery, `RuntimeImpl.runDelivery` checks the same conditions up front (`deliveryHoldable`, 054da38) and releases a delivery that will not wait before reading its body. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **warm-up**: One forward pass (two on WebGPU) over `WARMUP_STATE` / `WARMUP_QUESTIONS` before a plan is accepted; it sets `status.warmupMs` (which seeds the auto hold budget) and seeds `status.latency`. Code: `packages/runtime/src/model/backend.ts` -> `ModelBackend`, `WARMUP_STATE`. Doc: [model-host](runtime/model-host.md). - **wire request**: `{ state, questions }`, the only part of `EvaluateRequest` the model host uses; `trigger`, `subject`, `priority` and `timeoutMs` are scheduling and test metadata that never reach the packer. Code: `packages/runtime/src/model/protocol.ts` -> `ToWorker`. Doc: [model-io-contract](model-io-contract.md). - **worker URL pattern**: The literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `defaultWorkerFactory` (and the literal `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` calls beside it) that app bundlers recognise; the browser-test build asserts they survive bundling. Code: `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory`. Doc: [build-test-release](runtime/build-test-release.md). -- **workstream**: A team role that owns paths (runtime CONTRACT §1 and §13): lead, CORE, MODEL, UI, SIM, REAL (added with `realapps/`), DEMOS, TRAIN, REVIEW. The colleague's Claude sessions play all of them; they communicate through `packages/runtime/STATUS.md`, `HANDOFF.md` and per-requester NEEDS files (REAL's requests live in `training/NEEDS.md`); each has its own entry here. Doc: [status-and-known-issues](status-and-known-issues.md). +- **workstream**: A team role that owns paths (runtime CONTRACT §1 and §13): lead, CORE, MODEL, UI, SIM, REAL (added with `realapps/`), DEMOS, TRAIN, REVIEW, INSTALL (added with f3a9dd1). The colleague's Claude sessions play all of them; they communicate through `packages/runtime/STATUS.md`, `HANDOFF.md` and per-requester NEEDS files (REAL's requests live in `training/NEEDS.md`); each has its own entry here. Doc: [status-and-known-issues](status-and-known-issues.md). - **world (demos)**: One mock-server session in the demos' Service Worker, keyed by `live-<demo>-<rand>` or `trial-<demo>-<run>`; it owns state, chaos, request and event logs, SSE streams and timers. The page controls it only via `postMessage`, so GenClass never observes test traffic. Code: `demos/src/server/core.ts` -> `World`. Doc: [demos](demos.md). ## X diff --git a/docs/agents/realapps.md b/docs/agents/realapps.md index f7db4b8b..e8b57c5d 100644 --- a/docs/agents/realapps.md +++ b/docs/agents/realapps.md @@ -8,7 +8,7 @@ > **Read this when:** you need to know what a REAL (`meta.source = "realapps"`) training row is and how it was > labelled; you add or change an app, a harness rule, a cost term or a diagnosis rule; you rerun the determinism or > interference ("never worse") sweeps after a runtime change; or you plan a real-browser generation batch. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR @@ -18,21 +18,29 @@ the **sim's own cost weights and label rule** (it imports them from `sim/src`), and writes **CONTRACT-D rows** in the same shape as SIM rows. It closes the sim-to-real gap (React's MessageChannel scheduler, Vue/Svelte microtask flushes, TanStack Query/SWR dedupe, XHR libraries, Redux middleware, the apps' own bugs). -- **Corpus at b435acb: 91 apps** (77 written for the corpus + 14 open-source RealWorld "Conduit" front-ends), - 23 distinct `framework` values. `realapps/README.md` and `HANDOFF.md` still say 66 apps and - `docs/runtime/RESULTS.md` §6 says "66 → ~96"; 25 apps were added after fcb8189 (24 in d73d20c, `preact-mappins` in - 74f17c0; see Drift). +- **Corpus on `mvp-v2-merge`: 128 app manifests** (114 written for the corpus + 14 open-source RealWorld "Conduit" + front-ends), still 23 distinct `framework` values; the 37 apps added since 74f17c0 put more apps on the smaller + stacks (Knockout, Backbone, Mithril, petite-vue, Hyperapp, Alpine, Lit) and libraries (RxJS, effector, nanostores, + XState, Valtio, Jotai). Growth: 66 at fcb8189, 91 at + 74f17c0, **96 after "realapps wave 3"** (d53e836, the count its commit message, `OPEN_TASKS.md` and + [RESULTS.md](../runtime/RESULTS.md) use), then 18 more in f3a9dd1 and 14 more in eff18cb that neither commit's + message mentions. `realapps/README.md` and `HANDOFF.md` still say 66 (see Drift). - It is also the runtime's **"never make a correct app worse" harness**: `debug.js --interference` compares observe mode with heal mode under an all-passive decider. Situation-v2 result (STATUS.md): **0/396 clean runs changed** - over all 66 apps then in the corpus, seeds 1–6; 3/198 changed under chaos (an open item per RESULTS.md §4). Under - situation-v1 the gothinkster React/Redux Conduit never rendered its feed. + over all 66 apps then in the corpus, seeds 1–6; 3/198 changed under chaos (an open item per RESULTS.md §4). The + wave-3 commit (d53e836) claims each new app passes determinism (120/120), drop-free trajectories and zero + interference on situation-v2; no recorded sweep covers all 128 apps or the merged runtime. Under situation-v1 the + gothinkster React/Redux Conduit never rendered its feed. - **Nothing here is in CI or the root workspaces, there are no tests and no tsconfig.** Every real step needs Chromium, and generation runs on Azure F80 nodes. Under our run policy: **ask the user before running anything in `realapps/`** that launches Chromium (`debug.js`, `gen.js`, `chromium_probe.mjs`), clones the OSS corpus (`corpus/prepare_oss.sh`), or touches a VM (`scripts/vm.sh`, `realapps/scripts/cluster.sh`, `node_setup.sh`). -- Data status (from `training/NEEDS.md` 16, not verifiable from here): v2 production batches `v2b1`/`v2b2`/`v2b3` on - c01/c10/c11 (30k trajectories each, target ≥ 500k gold; [HANDOFF.md](../../HANDOFF.md)/[RESULTS.md](../runtime/RESULTS.md): about 495k), to be copied to `train:/data/real-out/`. No training - code in the repo reads realapps output by name yet; it is consumed as generic CONTRACT-D batches (see +- Data status (from `training/NEEDS.md` 16, not verifiable from here): **use `v2c1`..`v2c4`** (fixed labels: runtime + diagnosis vocabulary, `delivery` diagnosed by its first write, S1; 96 apps; 4 × 20k trajectories on c01, c10, c11, + `data`; seeds 11M/12M/13M/14M+; expected ≈ 530k gold + ≈ 500k unlabeled), to land on `train:/data/real-out/`. The + earlier `v2b1`..`v2b3` (66 apps, ≈ 380k gold, stopped at ≈ 20.5k trajectories each) have **pre-fix diagnosis + labels**; their action labels are valid. Audit pilot: `v2-pilot4` (400 trajectories, 92 apps, 2,631 gold). No + training code in the repo reads realapps output by name yet; it is consumed as generic CONTRACT-D batches (see [training.md](training.md)). ## Files @@ -43,11 +51,11 @@ | `realapps/EXAMPLES.md` | 13 audited rows from the v1 pilot `pilot4` (situation, labels, per-action and per-future costs, cost parts, verdict). Not re-audited on v2 (unverified). | | `realapps/package.json` | `@genclass/realapps` 0.0.0, private. Scripts `build` (`node build.mjs`), `gen` (`node dist/harness/gen.js`), `build:runtime`. devDependencies: `playwright`/`@playwright/test` 1.63.0, esbuild, esbuild-svelte, and every framework/library the apps use (React 19, Redux/RTK, Zustand, Vue 3, Pinia, Solid, Preact, Lit, jQuery, MobX, TanStack Query, SWR, axios, Alpine, Jotai, Valtio, XState, effector, nanostores, redux-saga, ky, ofetch, wretch, superagent, React Router 7, vue-router, Mithril, Hyperapp, petite-vue, htm, RxJS, Backbone, Knockout...). | | `realapps/.gitignore` | `node_modules/`, `dist/`, `src/harness/apps.gen.ts` (generated by `build.mjs`). | -| `realapps/build.mjs` | esbuild build of the world IIFE (`dist/world.js`), the harness entries (`dist/harness/{gen,worker,debug}.js`; it would also pick up `audit`/`evalset` entries, which do not exist), the manifest registry (`dist/manifests.mjs`) and every app whose manifest has no `build.vite`/`build.prebuilt` (`dist/apps/<name>/{index.html,bundle.js}`): the 77 written apps plus the 3 OSS apps of build kind `esbuild` (`oss-react-redux-conduit`, `oss-rtk-conduit`, `oss-mobx-conduit`, bundled from their `$RW_OSS_DIR` checkout). Writes `dist/runtime-tag.txt`. | +| `realapps/build.mjs` | esbuild build of the world IIFE (`dist/world.js`), the harness entries (`dist/harness/{gen,worker,debug}.js`; it would also pick up `audit`/`evalset` entries, which do not exist), the manifest registry (`dist/manifests.mjs`) and every app whose manifest has no `build.vite`/`build.prebuilt` (`dist/apps/<name>/{index.html,bundle.js}`): the 114 written apps plus the 3 OSS apps of build kind `esbuild` (`oss-react-redux-conduit`, `oss-rtk-conduit`, `oss-mobx-conduit`, bundled from their `$RW_OSS_DIR` checkout). Writes `dist/runtime-tag.txt`. | | `realapps/apps/<name>/manifest.ts` + source | One app: an `AppManifest` default export (Node side) plus the app source (entry = `manifest.entry`). OSS apps have only a manifest; their source is cloned by `corpus/prepare_oss.sh`. | | `realapps/apps/README.md` | Authoring guide for app-writing agents: hard rules, mock backend API, affordance options, cost meaning, determinism do/don't, test loop. Written for the colleague's setup (absolute Mac path, branch `runtime`, "never run node on the Mac"). | | `realapps/apps/_shared/genclass.ts` | The app's one-line integration: `rt = GenClass.init(window.__GENCLASS_INIT__ ?? {})` and `flag(name, default)` reading `window.__RW_VARIANT`. | -| `realapps/apps/_shared/{vue,svelte,solid,preact,lit}-atom.ts`, `lit-toast.ts`, `hyperapp-guard.ts`, `react-genclass-reducer.ts`, `w3-http.ts` | Bridges from framework state to runtime atoms/guards, and small shared helpers. | +| `realapps/apps/_shared/{vue,svelte,solid,preact,lit}-atom.ts`, `lit-toast.ts`, `hyperapp-guard.ts`, `react-genclass-reducer.ts`, `w3-http.ts`, `w4-effector.ts` | Bridges from framework state to runtime atoms/guards, and small shared helpers (`w4-effector.ts` -> `guardStore`: an effector store behind `rt.guard`, async results written through the guarded handle). | | `realapps/apps/_shared/conduit-manifest.ts` | `conduitManifest(...)` and `conduitAffordances`: the shared manifest builder for the 14 OSS Conduit apps (title, domain, server `{ base: "/api", ext: ["conduit"] }`, affordances, external events, `errorSelector`, `sessionMs`, `startMs`). It does **not** set `domWeight`; each observe-only OSS manifest sets `domWeight: 2` itself. | | `realapps/apps/_shared/onnx-stub.ts` | Stub aliased for `onnxruntime-web*`: the harness never loads a model. | | `realapps/corpus/oss.json` | The 14 open-source apps: name, repo, pinned commit, build kind, deps, licence. | @@ -55,20 +63,20 @@ | `realapps/corpus/prepare_oss.sh` | On a VM: clone each OSS app at its commit into `$RW_OSS_DIR` (default `~/gcl/real-cache/oss`), install deps and toolchain, apply `patch_oss.py`, build into `dist/apps/<name>/`. Build kinds: `esbuild` (left to `build.mjs`), `vite-*` (`vite.oss.config.mjs`), `angular`/`elm`/`ember`/`purescript` (own compiler then `rebundle.mjs`), `webcomponents`, `angularjs` (`build_angularjs.mjs`). Clones from GitHub. | | `realapps/corpus/patch_oss.py` | The GenClass integration a developer would add to each OSS app (Redux apps: `genclassEnhancer`; others: one init import, observe-only). | | `realapps/corpus/{rebundle.mjs,build_angularjs.mjs,vite.oss.config.mjs}` | OSS build helpers. | -| `realapps/src/world/index.ts` | The in-page world entry (an IIFE injected as an init script before any page script): installs the loop, network, server, user and probe; clears storage/cookies and applies the manifest's preloads; sets `window.__GENCLASS_INIT__` and `window.__RW_VARIANT`; prevents link/submit navigation; exposes `window.__RW.start()`, which schedules external events, WebSocket drops and the ask probes (`runtime.situation("ask")`, base run only) and runs the session. | -| `realapps/src/world/loop.ts` | Virtual time: timers, rAF, idle callbacks, MessageChannel, `scheduler.postTask`, `AbortSignal.timeout`, `Date`, `performance.now`, seeded randomness; real-macrotask yielding until native async work settles. | +| `realapps/src/world/index.ts` | The in-page world entry (an IIFE injected as an init script before any page script): installs the loop, network, server, user and probe; clears storage/cookies and applies the manifest's preloads; sets `window.__GENCLASS_INIT__` and `window.__RW_VARIANT`; prevents link/submit navigation; exposes `window.__RW.start()`, which schedules external events, WebSocket drops and the ask probes (`runtime.situation("ask")`; scheduled in every non-ideal run, kept only in the recording base run) and runs the session; returns a per-step `stepLog` for debugging. | +| `realapps/src/world/loop.ts` | Virtual time: timers, rAF, idle callbacks, MessageChannel, `scheduler.postTask`, `AbortSignal.timeout`, `Date`, `performance.now`, seeded randomness; real-macrotask yielding until native async work settles. Also disables scrolling (focus never scrolls, `scrollIntoView`/`scrollTo`/`scroll`/`scrollBy` are no-ops, scroll events are stopped), because the browser fires scroll events on real time. | | `realapps/src/world/net.ts`, `netapi.ts` | In-page `fetch` (a `Response` subclass from `makeResponseClass`), `XMLHttpRequest`, `WebSocket` on virtual time, with chaos draws. `netapi.ts` sets `window.EventSource = undefined`, so the runtime's v2 `eventsource` observer never installs. | | `realapps/src/world/server.ts`, `ext/conduit.ts` | The mock backend (collections, CRUD, versions/409, `Idempotency-Key` replay, relative actions, bulk, docs, counters, auth with rotating refresh tokens, cart echoes, replica lag, live WebSocket topics) and the RealWorld API extension. | | `realapps/src/world/user.ts` | The scripted user (user-event style untrusted events), intent pinning to the ideal run. | -| `realapps/src/world/probe.ts` | `Probe`: the recording `DecisionProvider` (forced actions by decision index, ε-exploration, simulated model latency, answers with confidence 1), runtime hooks, the store-snapshot plugin, DOM text snapshots, error episodes/writes, and the in-page diagnosis call. | -| `realapps/src/world/diagnose.ts` | In-page diagnosis rules from harness knowledge (scripted intents, server failure records, user writes, retries); handles situation-v2's `delivery` trigger. | -| `realapps/src/harness/scenario.ts` | `buildScenario(seed, apps, opts)`: app + flags, scripted session, chaos profile, external events, wording vocabulary, budget, exploration, split. Holds `TEST_FRAMEWORKS`, `TEST_APPS`, `TEST_PATTERNS`, `splitOf`. | +| `realapps/src/world/probe.ts` | `Probe`: the recording `DecisionProvider` (forced actions by decision index, ε-exploration, simulated model latency, answers with confidence 1), runtime hooks, the store-snapshot plugin, DOM text snapshots, error episodes/writes, and the in-page diagnosis call. Marks S1 inputs on each decision (`repeat`: the subject repeats an accidental user step; `twin`, on `request` decisions only: an identical request in flight or answered within 10 s) and, when a `delivery` decision's own verdict is `rel-check` or missing, diagnoses it by the first write its response or message makes (`pendingDelivery`, mutation rules). | +| `realapps/src/world/diagnose.ts` | In-page diagnosis rules from harness knowledge (scripted intents, server failure records, user writes, retries); handles situation-v2's `delivery` trigger. Includes the generic `stale` rule `newer-op-wrote <path>`: a write from an older async operation over elements already written by a newer one. | +| `realapps/src/harness/scenario.ts` | `buildScenario(seed, apps, opts)`: app + flags, scripted session, chaos profile, external events, wording vocabulary, budget, exploration, split. Holds `TEST_FRAMEWORKS`, `TEST_APPS`, `TEST_PATTERNS`, `splitOf`, and `DEFAULT_DIAGNOSES` (now the bundled runtime's own map, via `@rt/questions`). | | `realapps/src/harness/trajectory.ts` | `generateTrajectory`: ideal run, base run, counterfactuals, prefix check, cost, labels, the four row kinds. Holds `PASSIVE` (from the bundled runtime), `RUNTIME_TAG`, `TRIGGER_W`, `OBSERVE`, `runConfig`. | | `realapps/src/harness/cost.ts` | `runCost`, `states`, `serverDist`, `relationBroken`; `BLOCKED = 1.0`. Mirrors `sim/src/oracle/cost.ts`. | -| `realapps/src/harness/labels.ts` | `finishDiagnosis` (Node-side diagnosis finishing with the manifest's relations), `duplicateKeys`. | +| `realapps/src/harness/labels.ts` | `finishDiagnosis` (Node-side diagnosis finishing with the manifest's relations), `duplicateKeys`, and the S1 rule as in SIM: `S1_GAP` (1.0), `divergedAt`, `diagnosisFromOutcome` (rules a–e). | | `realapps/src/harness/browser.ts` | `Runner`: one headless Chromium per worker, a fresh page per run, contexts recycled every 60 runs, apps served from memory at `ORIGIN = "https://app.example.com"`. | | `realapps/src/harness/gen.ts`, `worker.ts` | The resumable generator (worker pool, per-split JSONL append, `done.txt`, `stats.json`, `manifest.json`) and its worker process. | -| `realapps/src/harness/debug.ts` | Inspection CLI: one scenario, `--twice`, `--traj`, `--force k:action`, `--det` (determinism sweep), `--interference` (never-worse sweep). | +| `realapps/src/harness/debug.ts` | Inspection CLI: one scenario, `--twice`, `--traj`, `--force k:action`, `--det` (determinism sweep; on a mismatch it prints the first differing step and request with their neighbours), `--interference` (never-worse sweep), `--ask-check` (the base run with and without ask probes must decide identically). | | `realapps/src/shared/{manifest,types,routes}.ts` | `AppManifest`/`Affordance`/`Relation` types; `RunConfig`, `RunResult`, `ServerSpec`, `Step`...; `endpointsOf`. | | `realapps/scripts/analyze.py` | Batch stats plus comparison with `sim/samples/stats-final-a.json` (the v1 sim final-A stats; `--sim`, `--json`). | | `realapps/scripts/evalset.py` | Builds `<out>/real_eval.jsonl` plus a `manifest.json`, the unambiguous real-app eval set. | @@ -94,8 +102,10 @@ `sameNth`, `followOnly`, `resets`, `requires`, `requiresText`. - **Integration kinds.** `stores`: the app puts state in runtime stores (`rt.atom`, `useGenClassState`, `genclassEnhancer` for Redux/RTK, `genclass()` for Zustand, `rt.guard` for Pinia/MobX, atom bridges for - Vue/Svelte/Solid/Preact/Lit). `observe`: no stores (17 manifests at b435acb: the jQuery apps, `superagent-fleet` - and the non-Redux OSS Conduits); they still produce request, failure, stall and error rows, and their divergence is + Vue/Svelte/Solid/Preact/Lit, `guardStore` for effector). `observe`: no stores (27 manifests on `mvp-v2-merge`: the + 4 jQuery apps with `integration: "observe"`, `superagent-fleet`, 10 apps added since 74f17c0 (`alpine-bikeshare`, + `backbone-logtail`, `hyperapp-webhooks`, `knockout-shifts`, `lit-draft`, `mithril-elections`, `nano-departures`, + `petite-transcode`, `preact-beds`, `rx-jobs`) and the 12 non-Redux OSS Conduits); they still produce request, failure, stall and error rows, and their divergence is measured on visible DOM text. "Observe-only" here is an integration style; the harness still runs these apps with `mode: "heal"`. - **Scenario** (`realapps/src/harness/scenario.ts` -> `Scenario`): one seed determines app, flags (`variant`, @@ -127,8 +137,9 @@ `apps/*/manifest.ts` whose directory does not start with `_`). 2. It bundles `src/world/index.ts` into `dist/world.js` (IIFE) and the harness into `dist/harness/*.js` (ESM, Node 22, `playwright` external). Alias `@rt/questions` -> `<RT>/situation/questions.ts`, so both the in-page probe - and `trajectory.ts` read the **runtime's own `PASSIVE` map** (the only symbol imported through it). -3. Every app without `build.vite`/`build.prebuilt` (the 77 written apps and the 3 `esbuild`-kind OSS apps, the + and `trajectory.ts` read the **runtime's own `PASSIVE` map**, and `scenario.ts` reads its `DEFAULT_DIAGNOSES` (the + only two symbols imported through it). +3. Every app without `build.vite`/`build.prebuilt` (the 114 written apps and the 3 `esbuild`-kind OSS apps, the latter from their `$RW_OSS_DIR` checkout) is bundled by esbuild with aliases `@genclass/runtime[/react|/redux|/zustand]` -> `<RT>/index.ts` / `<RT>/adapters/*.ts`, `@realapps/genclass` -> `apps/_shared/genclass.ts`, `onnxruntime-web*` -> the stub, plus framework settings (JSX mode, Svelte plugin, Vue @@ -139,9 +150,11 @@ (`cluster.sh sync` with `TAG=...` does this into `~/gcl/real-cache/runtime/<tag>/src` and writes `~/gcl/real-cache/runtime/current`; `node_setup.sh` exports both variables from it). The tag goes to `dist/runtime-tag.txt` and from there (`trajectory.ts` -> `RUNTIME_TAG`, `"unknown"` when the file is missing) - into every row's `meta.runtime`. At b435acb, `packages/runtime/src` differs from `situation-v2` only by our - default-mode commit f3636b2, which realapps overrides with explicit modes; a working-tree build still stamps - `working-tree`, not `situation-v2`. + into every row's `meta.runtime`. On `mvp-v2-merge`, `packages/runtime/src` differs from `situation-v2` (6e5e86e) + by f3636b2 (default mode observe; realapps sets modes explicitly), 29b7f28 (errors pruned on record), f3a9dd1 + (`/auto` entry, CDN build; not used by realapps), 054da38 (observe mode never holds deliveries; background + delivery decisions recorded) and f107013 (redaction of F2 diffs and numeric/array secrets). A working-tree build + therefore is **not** situation-v2 and stamps `working-tree`; data batches are built from the frozen tag. ### One run (`realapps/src/harness/browser.ts` -> `Runner.run`) @@ -173,7 +186,8 @@ `skipped = "test-subsample"`). 2. **Ideal run**; its states define the target and its `pins` define the user's intents. 3. **Base run** with exploration (ε on decisions whose in-page diagnosis is not `expected`, ε/4 elsewhere) and ask - probes (`runtime.situation("ask")`). + probes (`runtime.situation("ask")`). Counterfactuals schedule the same probes (unless `ask: false`), so a probe + can never make a counterfactual prefix differ; only the base run keeps their output. 4. **Decision points:** `pickPoints` samples up to `maxPoints` (6) decisions with ≥ 2 actions, weighted by `TRIGGER_W` (mutation 1, request 1, failure 1.6, stall 2.2, inconsistency 3, transition 3, error 2.2; anything else, including `delivery`, 1) × 1.5 for a non-`expected` diagnosis. @@ -193,11 +207,19 @@ realapps-only **blocked intents** term (`BLOCKED = 1.0` per user step whose element never appeared beyond the ideal run's). Client state = registered stores (manifest weights) plus visible DOM text lines × `domWeight`. 8. **Action label:** sim's `actionLabel(costs, passive)` (tier premiums, tie pinning, `p ∝ exp(−gap/τ)`, - `τ = 0.1 + SE`), then sim's `transformQuestions` (option shuffles/drops, paraphrases). -9. **Diagnosis:** in-page rules (`diagnose.ts`) finished in Node by `finishDiagnosis` (relations, duplicate - entities, `delivery` handled like `mutation` for `rel-check`). The label is written only when the diagnosis is in - the row's (possibly reduced) vocabulary; otherwise counted in `notes` (`diagnosis-not-in-vocab`, - `diagnosis-uncorrelated`). `meta.diag_why`/`diag_trace` say which rule fired. + `τ = 0.1 + SE`), then sim's `transformQuestions` (action option shuffles and drops only; wording paraphrases come from the scenario's `vocab` through the runtime). +9. **Diagnosis:** in-page rules (`diagnose.ts`; a `delivery` decision without its own verdict, or with only `rel-check`, takes the verdict of its first write) finished + in Node by `finishDiagnosis` (relations, duplicate entities, `delivery` handled like `mutation` for `rel-check`). + Then **S1** (as SIM): when the result is `expected` or missing but a non-passive action wins with adjusted passive + cost ≥ `S1_GAP` (1.0), `diagnosisFromOutcome` names what the action repairs (a: verdict of the latest + non-`expected` mutation/delivery that wrote the diverged fields; b: `duplicate` for a repeated accidental step; + c: `duplicate` for a coalesce/block of a twin request; d: `inconsistent` or `stale` for diverged fields; e: + `unusual`). The S1 label goes into `meta.diagnosis` and the row's diagnosis label; `meta.diagnosis_s1` records which rule fired + (`a-write`, `b-repeat`, `c-twin`, `d-diverged`, `e-other`) and `meta.diagnosis_subject` the pre-S1 verdict (`null` + when there was none). The + vocabulary always holds every runtime label (only wording is paraphrased), so the label is normally written; + otherwise `notes` counts `diagnosis-not-in-vocab:<label>` or `diagnosis-uncorrelated`. `meta.diag_why`/ + `diag_trace` say which rule fired. 10. **Ask rows** from the base run's probes, using sim's `askQuestions` generators with exact answers. 11. **Unlabeled rows:** up to `unlabeled` (40) other base decisions with ≥ 2 actions; gold diagnosis only, `meta.unlabeled: true`, `base_choice`; action left to the teacher. @@ -210,14 +232,17 @@ appends to `done.txt`. `stats.json` and `manifest.json` refresh every 30 s and at the end. Rerunning the same command resumes. - `stats.json`: per trigger (n, passive-best count, best actions, diagnoses, mean harm of non-passive actions on - passive-best points), per app, drops, notes, skipped, run counts and times, first 50 errors. + passive-best points), per app (trajectories, rows, decisions, `stepsRan`, `stepsSkipped`, `dead` = trajectories + whose base run ran no step), drops, notes, skipped, run counts and times, first 50 errors (including + `prefix-mismatch <app> seed <seed> k=<k> a=<action> j=<future> first-diff=<k>` lines). - `manifest.json` (for TRAIN, `training/NEEDS.md` 11): seeds, counts, file descriptions, `on_policy: false`, held-out frameworks/apps/patterns, app list with OSS repo/commit/licence, options. Its `runtime` field is a hard-coded string (see Drift). ### Splits (`realapps/src/harness/scenario.ts` -> `splitOf`) -- **test:** framework in `TEST_FRAMEWORKS` (`lit`), app in `TEST_APPS` (`swr-status`, `alpine-tasks`, +- **test:** framework in `TEST_FRAMEWORKS` (`lit`: 6 apps now, including `lit-draft`, `lit-expenses`, + `lit-shipping` added since 74f17c0), app in `TEST_APPS` (`swr-status`, `alpine-tasks`, `xhr-autocomplete`), manifest `heldOut` (only `oss-rtk-conduit`), or a pattern in `TEST_PATTERNS` (`react-search/guard:reqid`, `vue-editor/save:serialize`, `zustand-board/push:version-check`). - **dev:** `hashAll("realapps-dev-v1", app, ...patterns) % 100 < 4`. @@ -235,8 +260,9 @@ `program_family`, `family`, `patterns`, `chaos`, `clean`, `budget`, `runtime`, `browser = "chromium-headless"`, `oss`; decision rows add `trigger`, `decision`, `t`, `explored_before`, `best`, `passive_best`, `passive`, `costs`, `cost_futures`, `futures`, `adjusted`, `se`, `non_passive_mass`, `cost_parts`, `tiers`, `diagnosis`, - `diag_why`, `diag_trace`, `subject`, `transform`; ask rows add `kinds`; unlabeled rows add `unlabeled`, - `base_choice`; diagnosis-only rows add `diagnosis_only`. + `diag_why`, `diag_trace`, `diagnosis_s1`/`diagnosis_subject` (when S1 fired), `subject`, `transform`; ask rows add + `kinds`; unlabeled rows add `unlabeled`, `base_choice`, `repeat` (when set); diagnosis-only rows add + `diagnosis_only`. - **Eval set** (`realapps/scripts/evalset.py <dirs> --out <dir> [--splits test,dev]`; default splits `test,dev,train`): cases `stale-overwrite`, `duplicate-submit`, `clean-benign`, `benign-salient`, `genuine-break`, each with `meta.eval_case` and `meta.eval_expect`, capped per case (`--per-case`, default 2000), original split @@ -254,7 +280,9 @@ "never make a correct app worse" check cited in `docs/runtime/RESULTS.md` §4 and `packages/runtime/STATUS.md`. - Single-scenario modes (`--app`, `--seed`, `--clean`): default (ideal + base summary, triggers, diagnoses, network correlation), `--twice`, `--traj` (runs `generateTrajectory` with `testKeep: 1`), `--show N`, `--steps`, - `--dom-at t1,t2`, `--force K:action` (DOM over time: ideal vs base vs forced), `--mode <mode>` for the base run. + `--dom-at t1,t2`, `--force K:action` (DOM over time: ideal vs base vs forced, plus whether the forced run's + decision `k` kept the base `fp`), `--mode <mode>` for the base run, `--ask-check` (base run without vs with ask + probes; first differing decision). `--traj` also prints base/ideal step counts and flags a `DEAD SESSION`. ## Configuration and constants @@ -298,11 +326,19 @@ Throughput (README, measured on `train`, 64 vCPU): 28 workers ≈ 3.3 trajectori - **Passive actions come from the bundled runtime's `PASSIVE`;** a trigger missing there (or mapped to `""`, as `ask` is) falls back to the first offered action. `realapps/scripts/analyze.py` and `evalset.py` keep their own copies of the map (both include `delivery`); update them if the runtime's map changes. -- **Secret-word redaction:** `apps/README.md` says not to name a store `auth` (use `session`). At b435acb the - runtime (`packages/runtime/src/util.ts` -> `isSensitivePath`) judges object fields by their leaf name, so - `auth.loading` or `auth.user.name` survive and only secret leaves (`auth.token`, `form.password`) or opaque - credential-like strings under `auth`/`session`/`cookie` are redacted; a string or number atom named `auth` is - still redacted whole. Keep following the guide's advice. +- **Secret-word redaction:** `apps/README.md` says not to name a store `auth` (use `session`). The runtime + (`packages/runtime/src/util.ts` -> `isSensitivePath`) judges object fields by their leaf name, so `auth.loading` or + `auth.user.name` survive and only secret leaves (`auth.token`, `form.password`) or opaque credential-like strings + under `auth`/`session`/`cookie` are redacted; a string or number atom named `auth` is still redacted whole. On + `mvp-v2-merge` (f107013, not in `situation-v2`) numbers, bigints and arrays under a strong secret-named container + (`payment.cvv.value`, `login.otp.code`) are redacted too, so a working-tree build can show different situation + text from the tagged data. Keep following the guide's advice. +- **No scrolling in the world** (`loop.ts`): scroll events would fire on real time, so focus never scrolls and + programmatic scrolling is a no-op. Apps must not depend on scroll position or scroll handlers (infinite lists need + an explicit "load more" path). +- **The diagnosis vocabulary is the bundled runtime's `DEFAULT_DIAGNOSES`** (`scenario.ts` imports it through + `@rt/questions`); `DIAG_PARA` only paraphrases. `diagVocab` still draws the old label-drop coin so every other + scenario choice keeps its RNG stream; do not remove that draw without accepting that all scenarios change. - **The ideal run's `ALL_OFF` (`src/world/index.ts`) and the other runs' `OBSERVE` (`trajectory.ts`) predate the v2 `eventsource` observer** (neither lists it, so the runtime's default "on" applies). It never installs because `netapi.ts` sets `window.EventSource = undefined`; @@ -311,8 +347,8 @@ Throughput (README, measured on `train`, 64 vCPU): 28 workers ≈ 3.3 trajectori - **The DOM term is coarse** (line multisets): an empty page and a page with different data can look alike. Store weights and blocked intents carry most of the signal for store apps. - **Observe-only OSS apps weigh the DOM ×2 via their own manifests** (each of the 12 sets `domWeight: 2`; - `conduitManifest` does not, so the two store-integrated OSS Conduits use 1); the jQuery and `superagent-fleet` - observe-only apps do not set it and use 1, although the README says 2 for all observe-only apps. + `conduitManifest` does not, so the two store-integrated OSS Conduits use 1); the jQuery, `superagent-fleet` and the 10 + observe-only apps added since 74f17c0 do not set it and use 1, although the README says 2 for all observe-only apps. - **Ideal runs are blind but installed:** observe mode, every observer off, no decider. Do not turn observers on there; the ideal must not depend on the runtime. - **`debug.js --interference` compares explicit modes**, so it is unaffected by the library's default mode. Its @@ -360,14 +396,23 @@ Throughput (README, measured on `train`, 64 vCPU): 28 workers ≈ 3.3 trajectori - v2 runtime batch 5 (STATUS.md): all 66 apps, seeds 1–6, clean: 0/396 changed; chaos seeds 1–3: 3/198 changed (preact-likes ×2, vanilla-spreadsheet), from request-time holds shifting a request about 25 ms; Conduit 0/30; determinism 198/198. + - Wave 3 (d53e836 commit message): each new app passes determinism (120/120), drop-free trajectories and zero + interference on situation-v2. `v2-pilot4` (NEEDS 16): 400 trajectories, 92 apps, 2,631 gold. ## Drift and open issues -- **App count.** 91 app manifests at b435acb against 66 at fcb8189: 24 added in d73d20c (e.g. `alpine-podcast`, - `react-ci`, `rtk-payroll`, `svelte-auction`, `vue-wiki`, `zustand-sequences`, `lit-dispatch`) and `preact-mappins` - in 74f17c0. The framework count stayed at 23. `realapps/README.md`, - [HANDOFF.md](../../HANDOFF.md) and the STATUS.md sweep say 66; [RESULTS.md](../runtime/RESULTS.md) §6 says "66 → ~96". The v2 sweeps above were over 66 - apps; whether v2b1–v2b3 include the new 25 depends on what was synced to the nodes (unverified). +- **App count.** 128 app manifests on `mvp-v2-merge`: 66 at fcb8189, +24 in d73d20c and `preact-mappins` in 74f17c0 + (91), +5 in the wave-3 commit d53e836 (96, the "96 total" of its message; its "30 more" counts from 66), +18 in f3a9dd1 (e.g. `effector-kds`, + `knockout-cfp`, `xstate-loan`) and +14 in eff18cb (e.g. `rx-jobs`, `valtio-vetclinic`, `vue-dataimport`), whose + messages do not mention apps (origin/runtime ca08174, a later commit not merged into `mvp-v2-merge`, calls these 32 + "realapps wave 4 (128 total)"). The framework count stayed at 23. `realapps/README.md` (also its "52 written"), + [HANDOFF.md](../../HANDOFF.md) and the STATUS.md sweep say 66; [RESULTS.md](../runtime/RESULTS.md) and + `OPEN_TASKS.md` say 96. The v2 sweeps were over 66 apps; `v2b1`..`v2b3` used 66 and `v2c1`..`v2c4` 96 (NEEDS 16), + so the last 32 apps are in no recorded batch or sweep (unverified beyond NEEDS). +- **The merged runtime changes the never-worse observe leg.** 054da38 (ours) makes observe mode deliver responses + immediately and decide deliveries in the background. `--interference` on a working-tree build of `mvp-v2-merge` + therefore compares against a different observe baseline than the recorded 0/396; rerun it (with the user's OK) + before citing never-worse numbers for the merged runtime. Tagged data (`situation-v2`) is unaffected. - **`gen.ts` -> `manifest` hard-codes `runtime: "situation-v1 (packages/runtime/src bundled from source)"`.** v2 batch `manifest.json` files therefore say situation-v1. The per-row `meta.runtime` is correct (read from `dist/runtime-tag.txt`). Trust `meta.runtime`. diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index 2e821bd6..b4e604d9 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -1,8 +1,8 @@ # Repository map (GenClass-lib) -> **Scope:** every tracked path (`git ls-files`: 1,082 files at b435acb, up from 749 at 654d822), plus the generated and ignored paths that show up in a working copy. +> **Scope:** every tracked path (`git ls-files`: 1,202 files at f107013, 1,082 at b435acb, 749 at 654d822), plus the generated and ignored paths that show up in a working copy. > **Read this when:** you need to find where a file, symbol, constant, CLI command, env var or config key lives; decide whether a directory matters for `@genclass/runtime`; or want to know which paths are generated, ignored or too large to read in full. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (`mvp-v2` + origin/runtime eff18cb merged + two runtime fixes), 2026-10-08. Sections not touched by the merge keep their b435acb wording where nothing changed. If this doc and the code disagree, the code wins. Conventions: code pointers are `path/from/repo/root` -> `symbol`. Relevance to the runtime library: @@ -14,37 +14,45 @@ Workstream names (lead, CORE, MODEL, UI, SIM, REAL, DEMOS, TRAIN, REVIEW) and th **What changed since 654d822** (the commit the first version of this map described): `git log --oneline 654d822..b435acb` lists the NaN fix (ad24804), runtime batch 4 (fcd1e68: decisions at the network boundary), the `realapps/` corpus (fcb8189), runtime batch 5 and the `situation-v2` freeze (6e5e86e), `HANDOFF.md` and the v2 curriculum port (d73d20c), `docs/runtime/RESULTS.md` (74f17c0), then our three commits on `mvp-v2`: agent docs (7dab2b3), default mode `observe` (f3636b2) and CI plus the committed root lockfile (b435acb). Use `git diff --stat 654d822 b435acb -- <path>` to see what changed in a path. +**What changed since b435acb** (`git log --oneline b435acb..f107013`): our docs and release commits (b561244, 6ac4737, +806a296 = published `0.1.0-alpha.1`, c16a3b0), the merge dabbce2 of Mehar's `origin/runtime` at eff18cb (realapps wave 3 +and more apps, the npm README rewrite, the `situation()` purity test, **the one-command install**: `packages/runtime/bin/lib/`, +`packages/runtime/src/auto.ts`, `packages/runtime/src/cdn/`, `packages/runtime/test/install/`, `packages/genclass-runtime/`, +and the v2 import/eval scripts under `training/`), 10e5c3b (lockfile), 054da38 (observe never holds deliveries) and +f107013 (redaction). `origin/runtime` has four newer commits (up to 5bc40c9, runtime batch 6) that are not in this tree. + ## 1. Top-level directories | dir | tracked files | what | owner / workstream | doc | relevance | |---|---|---|---|---|---| -| `packages/runtime/` | 154 | `@genclass/runtime` 0.1.0-alpha.1 (since release commit 806a296), the npm library: `src/` (61), `test/` (84), `bin/genclass-runtime.mjs` CLI (mode 100755 since b435acb), package and build configs, STATUS/UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Lead (us, on `mvp-v2`): `test/default-mode.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/runtime/` | 183 | `@genclass/runtime`, version `0.1.0-alpha.1` in the tree (= the published `latest`, which lacks the install code: bump before the next build), the npm library: `src/` (72), `test/` (95), `bin/` (6: `genclass-runtime.mjs` CLI, mode 100755, plus `bin/lib/` with `init`/`remove`), package and build configs, STATUS, CHANGELOG, INSTALL-NEEDS, UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/genclass-runtime.mjs` (`fetch-model`, `info`). INSTALL owns `src/auto.ts`, `src/cdn/**`, `bin/lib/**`, `test/install/**`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Us (lead): `test/default-mode.test.ts`, `test/observe-delivery.test.ts`, `test/redaction-v2.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/genclass-runtime/` | 4 | (new, f3a9dd1) unscoped alias package `genclass-runtime` 0.1.0-alpha.1: `cli.mjs` imports `@genclass/runtime`'s `bin/genclass-runtime.mjs`; `package.json` (dependency `@genclass/runtime` `0.1.0-alpha.1`), `README.md`, `LICENSE`. A workspace (`packages/*`), **not published** | INSTALL | `packages/runtime/INSTALL-NEEDS.md` item 1 | core (planned) | | `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished (npm 404). No situation-v2 model exists yet | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | | `sim/` | 106 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows. Now 46 feature combinators, 115 domains, S1/S2 labels, gold / unlabeled / on-policy row modes, Azure cluster scripts, separability analysis | SIM | [sim.md](sim.md) | supporting | -| `realapps/` | 230 | `@genclass/realapps` (private, **not** a root workspace): 91 real web apps (77 written + 14 open-source Conduit front-ends) run in headless Chromium with the real runtime; counterfactual labels like the sim; the "never worse" interference and determinism sweeps | REAL | [realapps.md](realapps.md) | supporting | -| `training/` | 61 | Python curriculum generator, runtime-text port (`curriculum/rt.py`, frozen at `situation-v2`), eval, ONNX export, Azure launch scripts for R17/R32/R68 students and the T150 teacher, teacher labelling, T1 expected-gain scripts | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | +| `realapps/` | 307 | `@genclass/realapps` (private, **not** a root workspace): 128 app directories with a `manifest.ts` (114 written + 14 open-source Conduit front-ends; Mehar's commit messages say 96 after wave 3, the wave-4 apps arrived inside f3a9dd1 and eff18cb) run in headless Chromium with the real runtime; counterfactual labels like the sim; the "never worse" interference and determinism sweeps | REAL | [realapps.md](realapps.md) | supporting | +| `training/` | 69 | Python curriculum generator, runtime-text port (`curriculum/rt.py`, frozen at `situation-v2`), eval, ONNX export, Azure launch scripts for R17/R32/R68 students and the T150 teacher, teacher labelling, T1 expected-gain scripts | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | | `demos/` | 133 | `@genclass/demos`: Vite site with six demo apps, a Service Worker chaos backend, Playwright trial eval and shipped results (still the v0.1 model) | DEMOS | [demos.md](demos.md) | supporting | -| `scripts/` | 26 | Ops scripts (unchanged since 654d822). `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | +| `scripts/` | 26 | Ops scripts (since 654d822 only `vm.sh` changed, in eff18cb: its sync keeps the `sim/out` symlink). `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | | `.github/` | 1 | `workflows/ci.yml`: the only CI (added in b435acb) | lead (us) | [runtime/build-test-release.md](runtime/build-test-release.md) | core | | `jev_local/` | 136 | Python package `jev-local` 0.1.0: Jev-wire API, encoder engine, trainer, voice harness, benchmark harnesses | none of the runtime workstreams (pre-runtime GenClass) | [genclass-model-lineage.md](genclass-model-lineage.md) | legacy. `serialize.py`, `confidence.py`, `engine/encoder/{tokenize_pack,calibrate,heads}.py` are the parity references for `packages/runtime/src/model`; `train/` is used by `training/` (the gain head the T1 scripts need exists only in the parent repo on the nodes, not here) | | `extension/` | 104 | GenClass 0.1.0 MV3 voice-control Chrome extension. Its own npm package, not a workspace | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy. `src/core/{engine,packer,tokenizer,serialize,pyutil}.js` are the ancestors of the runtime's `src/model/*.ts` | | `bench/` | 5 | jevbench and benchmax pre-registrations, `public/` target and exclusion JSON | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | | `tests/` | 74 | pytest suites for `jev_local` (71 `test_*.py`, `conftest.py`, 2 fixtures) | none of the runtime workstreams | [genclass-model-lineage.md](genclass-model-lineage.md) ("Tests") | legacy | | `results/` | 3 | Benchmark write-ups (CU head-to-head, jevbench M0, Z-68m notes) | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy | -| `docs/` | 36 | `docs/runtime/` (4: CONTRACT, API, ARCHITECTURE, RESULTS: the runtime's human docs), `docs/agents/` (20 tracked: these docs; `realapps.md` is new, not yet committed), `docs/benchmax-research/` (5), 7 legacy jev-local docs | `docs/runtime/CONTRACT.md`: lead. `docs/agents/**`: lead (us). Rest: not recorded / legacy | [status-and-known-issues.md](status-and-known-issues.md) (doc drift tables) | `docs/runtime/`, `docs/agents/`: core. Rest: legacy | +| `docs/` | 37 | `docs/runtime/` (4: CONTRACT, API, ARCHITECTURE, RESULTS: the runtime's human docs), `docs/agents/` (21: these docs), `docs/benchmax-research/` (5), 7 legacy jev-local docs | `docs/runtime/CONTRACT.md`: lead. `docs/agents/**`: lead (us). Rest: not recorded / legacy | [status-and-known-issues.md](status-and-known-issues.md) (doc drift tables) | `docs/runtime/`, `docs/agents/`: core. Rest: legacy | Root files (13): | file | what | relevance | |---|---|---| -| `package.json` | private `genclass-lib`, `"type": "module"`, workspaces `packages/*`, `sim`, `demos` (not `realapps`, not `extension`, not `training/ortweb`); scripts `build` and `test` (runtime only), `typecheck` (all workspaces); devDep `typescript ~5.9.3`; `engines.node >=20` | core | -| `package-lock.json` | root lockfile, **committed in b435acb** (3,203 lines); CI runs `npm ci` from it. Update it only with a deliberate `npm install` | core | +| `package.json` | private `genclass-lib`, `"type": "module"`, workspaces `packages/*` (runtime and, since the merge, the `genclass-runtime` alias), `sim`, `demos` (not `realapps`, not `extension`, not `training/ortweb`); scripts `build` and `test` (runtime only), `typecheck` (all workspaces); devDep `typescript ~5.9.3`; `engines.node >=20` | core | +| `package-lock.json` | root lockfile, **committed in b435acb** (3,220 lines at f107013; 10e5c3b added the alias workspace); CI runs `npm ci` from it. Update it only with a deliberate `npm install` | core | | `tsconfig.base.json` | shared TypeScript compiler options | core | | `.gitignore` | ignore rules (see [section 4](#4-generated-and-ignored-paths)) | core | | `README.md` | repo landing page: status banner, install, repo map. Says `observe` is the default (Status box and Modes table) | core | | [`HANDOFF.md`](../../HANDOFF.md) | the colleague's "read this first" for continuing sessions (d73d20c): current state table, repo map, hard rules for the 8 GB Mac and Azure, how to continue. Still says "guard (default)" | core | -| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | project-level status: done, in progress, next, needs the user, known risks (owner inferred: lead). Describes the situation-v2 pipeline under In progress/Next, items 1-14, CI listed as done | core | -| [`RELEASE.md`](../../RELEASE.md) | release procedure for `@genclass/runtime` and `@genclass/runtime-model` (new, not yet committed) | core | +| [`OPEN_TASKS.md`](../../OPEN_TASKS.md) | project-level status: done, in progress, next, needs the user, known risks (owner inferred: lead). In the merged tree: r17-v2a and t150-v2a in progress, the one-command install "not in the published `0.1.0-alpha.1`", Next 14 = the next prerelease with it, Polar Parts rollout under Needs the user | core | +| [`RELEASE.md`](../../RELEASE.md) | release procedure for `@genclass/runtime` and `@genclass/runtime-model` (b561244; publish recorded in c16a3b0). Part A (alpha.1) is done; no part yet for the next prerelease with the install | core | | `LICENSE` | Apache-2.0 | core | | `pyproject.toml` | Python package `jev-local` 0.1.0 (Python >=3.12,<3.14), console script `jev-local`, pytest config | legacy | | `BENCHMARKS.md` | public summary of GenClass 0.1 benchmark results | legacy | @@ -67,41 +75,75 @@ docs/runtime/RESULTS.md (new) model stages compared, R17 vs R32, why round 1 comparison, demo baseline, data volume, training log summary ``` -### `packages/runtime/` package root (9 files) +### `packages/runtime/` package root (10 files, plus `bin/` with 6) Doc: [runtime/build-test-release.md](runtime/build-test-release.md), [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). ```text packages/runtime/ - package.json @genclass/runtime 0.1.0-alpha.1 (806a296); exports . ./react ./redux ./zustand ./devtools ./worker; bin genclass-runtime; - dep onnxruntime-web ^1.30.0; optional peers react/redux/zustand; scripts build typecheck test test:browser + package.json @genclass/runtime, version 0.1.0-alpha.1 (= published latest; bump before the next build); exports . ./auto + ./auto/observe ./auto/guard ./auto/heal ./react ./redux ./zustand ./devtools ./worker (no typesVersions); + sideEffects [dist/auto.js, dist/auto/*.js, dist/genclass.global{,.min}.js, dist/cdn/*.js, src/model/worker.ts]; + unpkg/jsdelivr -> dist/genclass.global.min.js; bin genclass-runtime; dep onnxruntime-web ^1.30.0; + optional peers react/redux/zustand; scripts build typecheck test test:browser tsconfig.json typecheck project (include src only: tests are never type-checked) - tsup.config.ts 6 ESM entries (index, adapters/react|redux|zustand, devtools/index, worker) -> dist/; .d.ts for all but worker + tsup.config.ts four configs: ESM (10 entries: index, auto, auto/{observe,guard,heal}, adapters/react|redux|zustand, + devtools/index, worker; .d.ts for all but worker); globalBuild(false|true) -> dist/genclass.global{,.min}.js + (IIFE, onnxruntime-web external, __GENCLASS_VERSION__ = package version); CDN worker -> dist/cdn/{worker, + ort-webgpu,ort-wasm}.js (onnxruntime-web bundled, plugin cdnOrt) vitest.config.ts unit tests: test/**/*.test.ts, excludes test/browser/**, env node, testTimeout 20000 - README.md npm package README (observe default; notes no model is published yet) - STATUS.md CORE status: test state (41 files / 346 tests before default-mode.test.ts), never-worse sweep, - batch 4/5 notes, headless recipe, trigger table, example situations, deviations, open issues + README.md npm package README (rewritten by Mehar, d05abc1): one-command install, observe default, no model yet; + says init, /auto and the script tag are "not in 0.1.0-alpha.1" + CHANGELOG.md (new, f3a9dd1) "## 0.1.0-alpha.1" wrongly lists the install paths (they are not in the published alpha.1) + INSTALL-NEEDS.md (new, f3a9dd1) INSTALL -> lead/CORE/MODEL/UI: npx naming decision, package.json and tsup changes, + runtime behaviour INSTALL relies on + STATUS.md CORE status: test state (42 files / 348 tests on the VM), "Fix after 0.1.0-alpha.1: two redaction leaks", + "Fix after batch 5: situation() purity", never-worse sweep, batch 4/5 notes, headless recipe, trigger table, + example situations, deviations, open issues UI-NEEDS.md UI -> CORE request log (partly stale) LICENSE Apache-2.0 - bin/genclass-runtime.mjs CLI (Node >= 20, no deps): fetch-model <dir> [--from] [--variant q8|fp16|all] [--force] [--quiet], info <dir> + bin/genclass-runtime.mjs CLI (Node >= 20, no deps; also `npx @genclass/runtime <cmd>`): init, remove (in bin/lib/), + fetch-model <dir> [--from] [--variant q8|fp16|all] [--force] [--quiet], info <dir> + bin/lib/init.mjs (new) USAGE, init (detect -> plan -> diff -> confirm -> write -> install), remove (strip markers, delete + created files, uninstall if unused); installSpec (@genclass/runtime@^<own version> or --from); flags incl. + undocumented --no-sri, --strategy + bin/lib/detect.mjs (new) detectProject (framework, entry, package manager, TS), walkSources (SKIP_DIRS, dot-dirs skipped, + depth 10, 20,000 files), detectState, htmlModuleEntry + bin/lib/plan.mjs (new) AUTO (mode -> import path; treats guard as the default), planInit and one plan per framework (Vite, + CRA, webpack-likes, Angular, SvelteKit, Nuxt, Remix/React Router, Next app/pages, Astro, HTML), + scriptTag, integrityFor (SRI from the local dist file) + bin/lib/edit.mjs (new) MARK "genclass:init", MARK_INLINE "genclass:inline", insertTop, appendEnd, removeMarked, codeStyle + bin/lib/ui.mjs (new) colours, symbols, line diff, yes/no prompt ``` -### `packages/runtime/src/` (61 files) +### `packages/runtime/src/` (72 files) ```text packages/runtime/src/ index.ts public facade: GenClass (init/runtime/destroy), createRuntime, re-exports; killSwitch, makeHost, NATIVE_FETCH, ALL_OFF runtime.ts RuntimeImpl: wires every layer; default mode (o.mode ?? "observe"); installObservers, trigger (triage), - runDelivery (delivery gate), observeWrite / gateMutation, covered, dropFilter / writtenOver (discard - marks), noteResponse, onChannel, markWrites (F9), onDecision, settled points, rollback/revertChain/resync, - explain, undo, destroy + runDelivery (delivery gate), deliveryHoldable / writesCanAct / finalizeDeliveries (054da38: deliveries + that cannot be held are released at once and decided in the background), observeWrite / gateMutation, + covered, dropFilter / writtenOver (discard marks), noteResponse, onChannel, markWrites (F9), onDecision, + settled points, rollback/revertChain/resync, explain, undo, destroy + auto.ts (new, INSTALL) @genclass/runtime/auto: startAuto() with no defaults (observe), default export = the runtime types.ts every public and shared type: options (PolicyOptions.holdWrites, observe.untrustedEvents), Runtime, RuntimeEvents, plugins, and the "model seam" (JevState, Question, Answer, EvaluateRequest, DecisionProvider) mirrored by sim/src/types.ts errors.ts GenClassUnavailableError clock.ts browserClock (timers captured at module load, afterTask) util.ts hashing (fnv1a, stableStringify, hashValue), URL signatures (normalizePath, isIdSegment, - requestSignature), formatting (secs, rel, fmtNum, truncate), redaction (defaultRedact, isSensitivePath: leaf-based) + requestSignature), formatting (secs, rel, fmtNum, truncate), redaction (defaultRedact, isSensitivePath: + leaf-based; since f107013 numbers, bigints and arrays under strong secret containers are redacted too) + cdn/auto-start.ts (new, INSTALL) startAuto(defaults): meta tag + window.GENCLASS_CONFIG -> GenClass.init, optional devtools + cdn/auto-observe.ts, cdn/auto-guard.ts, cdn/auto-heal.ts (new) the /auto/<mode> entries: startAuto({ mode }) + cdn/config.ts (new) page config: parsePairs, fromPairs, fromDataset, readMetaConfig (every meta[name="genclass"]), + readWindowConfig, mergeConfig, splitConfig, devtoolsOptions, isLocalHost, isKilled, whenBody + cdn/global.ts (new) script-tag build entry: install (window.GenClass, data attributes, data-manual), assetBase + (pins jsDelivr/unpkg URLs to the baked __GENCLASS_VERSION__), blobModuleWorker (Blob-URL module worker) + cdn/worker.ts (new) CDN worker entry: imports ../model/worker.js, captures ortWasmPaths (cdnState) + cdn/ort-env.ts (new) cdnState, prepareOrt (points ORT's threaded .mjs glue at the wasm directory) + cdn/ort-webgpu.ts, cdn/ort-wasm.ts (new) onnxruntime-web wrappers bundled into dist/cdn/ adapters/react.ts @genclass/runtime/react: GenClassProvider, useGenClass, useGenClassState, useAtom, useGenClassDecisions/Interventions/Status adapters/redux.ts @genclass/runtime/redux: genclassEnhancer, GENCLASS_REPLACE adapters/zustand.ts @genclass/runtime/zustand: genclass middleware @@ -158,19 +200,20 @@ packages/runtime/src/ situation/env.ts SitEnv (read-only runtime view for situation code), SubjectSpec (incl. DeliverySpec), ReqMeta, FailureInfo, Violation state/hub.ts StoreHub: atom/guard/adapter stores, mutation pipeline (holdWrites opt-in), propose -> applyFilter (delivery drop filter), flushQueue, field versions, stale marks and logs, late revert, snapshots - state/fields.ts flatten, diffLeaves, deltaOf, changeText, stringDiff (diff-centred previews), patchValue, cloneValue; - MAX_DEPTH, MAX_FIELDS_PER_STORE + state/fields.ts flatten, diffLeaves, deltaOf, changeText, stringDiff (diff-centred previews), redactedStringDiff (f107013: + diff only when the redactor leaves both values unchanged; used by changeText and contentFacts), + patchValue, cloneValue; MAX_DEPTH, MAX_FIELDS_PER_STORE state/invariants.ts InvariantMiner (9 templates + count-by-group; relation-quality rules (F8); LEARN_AFTER, LEARN_AFTER_NONNULL), expect() trace/ops.ts OpRegistry, OpRec (+ delivery, discardMark) trace/context.ts Context (ambient op: run, stick, isUserSync), LazyOp trace/events.ts EventLog ring buffer ``` -Docs by folder: `index.ts`, `runtime.ts`, `types.ts`, `errors.ts`, `clock.ts`, `util.ts` -> [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md); `observe/`, `trace/` -> [runtime/observe-and-trace.md](runtime/observe-and-trace.md); `state/`, `adapters/` -> [runtime/state-and-adapters.md](runtime/state-and-adapters.md); `learn/`, `situation/` and the delivery gate -> [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md); `decide/` and the delivery actions -> [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md); `model/` -> [runtime/model-host.md](runtime/model-host.md); `devtools/` -> [runtime/devtools.md](runtime/devtools.md). Everything the model reads is frozen at tag `situation-v2` (6e5e86e): [model-io-contract.md](model-io-contract.md). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts`, `types.ts` and `devtools/index.ts` (the default-mode change). +Docs by folder: `index.ts`, `runtime.ts`, `types.ts`, `errors.ts`, `clock.ts`, `util.ts` -> [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md); `observe/`, `trace/` -> [runtime/observe-and-trace.md](runtime/observe-and-trace.md); `state/`, `adapters/` -> [runtime/state-and-adapters.md](runtime/state-and-adapters.md); `learn/`, `situation/` and the delivery gate -> [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md); `decide/` and the delivery actions -> [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md); `model/` -> [runtime/model-host.md](runtime/model-host.md); `devtools/` -> [runtime/devtools.md](runtime/devtools.md). `auto.ts`, `cdn/` (INSTALL) have no subsystem doc yet; see [status-and-known-issues.md](status-and-known-issues.md) ("What the merged install paths do", "Install code review"). Everything the model reads is frozen at tag `situation-v2` (6e5e86e): [model-io-contract.md](model-io-contract.md). At f107013, `git diff --stat situation-v2 HEAD -- packages/runtime/src` lists `auto.ts`, `cdn/*`, `devtools/index.ts`, `observe/messages.ts`, `observe/xhr.ts`, `runtime.ts`, `trace/ops.ts`, `types.ts` and three model-visible files changed by the redaction fix f107013: `situation/content.ts`, `state/fields.ts`, `util.ts`. -### `packages/runtime/test/` (84 files) +### `packages/runtime/test/` (95 files) -Doc: [runtime/build-test-release.md](runtime/build-test-release.md) ("Tests" has one row per file with test counts). 36 top-level `*.test.ts` + 6 `model/*.test.ts` = 42 unit test files; the local run on b435acb excluding `review-perf` gave 40 passed + 1 skipped files, 332 passed + 14 skipped tests; `review-perf` alone 4 passed. +Doc: [runtime/build-test-release.md](runtime/build-test-release.md) ("Tests" has one row per file with test counts). 39 top-level `*.test.ts` + 6 `model/*.test.ts` + 1 `install/cli.test.ts` = 46 unit test files; the local run on f107013 excluding `review-perf` gave 44 passed + 1 skipped files, 375 passed + 14 skipped tests; `review-perf` alone 4 passed (393 in total). ```text packages/runtime/test/ @@ -195,6 +238,8 @@ packages/runtime/test/ invariants.test.ts InvariantMiner learning, inconsistency once per episode, rollback learn.test.ts Baselines and Profiles; transition trigger nan.test.ts (new) no infinite recursion when a store value is NaN (ad24804; the 0.1.0-alpha.1 patch) + observe-delivery.test.ts (new, ours, 054da38) observe never holds/delays fetch, XHR, WebSocket, EventSource deliveries; + background delivery decisions recorded; guard unchanged (11 tests) no-reorder.test.ts (new) realworld promise middleware through genclassEnhancer with an always-passive model: guard/heal give the same dispatches, order and final state as observe plugins.test.ts plugin facts/diagnoses/actions, ctx.builtin, standing questions, vocabulary @@ -210,6 +255,9 @@ packages/runtime/test/ review-redaction.test.ts REVIEW: custom redact applies to invariant facts review-timers.test.ts REVIEW: recursive timer loops; gc check needs NODE_OPTIONS=--expose-gc review-xhr.test.ts REVIEW: sync XHR never held, abort while held + redaction-v2.test.ts (new, ours, f107013) F2 never diffs redacted text; numbers/bigints/arrays under strong secret + containers redacted (10 tests) + situation-purity.test.ts (new, 29b7f28) building situations changes no counter, id, decision or hold (2 tests) situation.test.ts one situation per trigger: key order and section limits; prints situations smoke.test.ts atoms, context through real awaits, stale delivery discarded in guard mode (explicit mode "guard") xhr.test.ts XHR op + cause, block, detection-only failures, destroy restores open/send @@ -243,6 +291,15 @@ packages/runtime/test/ browser/ui/page.ts fake "Acme" store page for the UI spec (window.__gc) browser/ui/screenshots/ 18 PNGs: {activity,detections,evidence-answers,evidence,interventions,loading,now,overlay,pill}-{dark,light}.png smoke/smoke.sh npm pack -> fresh Vite 8 app -> headless Chromium check (run from packages/runtime; ask first) + install/cli.test.ts (new, INSTALL) init/remove on fixture projects in temp dirs with --no-install (20 tests; runs in CI); + covers --mode observe only, no case for guard or the default mode + install/run-all.sh (new) VM: build + pack -> cli tests -> cdn-check -> scaffold -> frameworks (ask first) + install/scaffold.sh (new) VM: scaffold real projects with each framework's generator (network, package managers) + install/frameworks.mjs (new) VM: per scaffold init -> build -> Chromium (prod + dev) -> remove -> byte comparison + install/cdn-check.mjs (new) VM: script-tag build and /auto in headless Chromium, cross-origin "CDN" + install/server.mjs (new) static/CORS server for those checks + install/RESULTS.md (new) VM results, recorded against a 0.1.0-alpha.0-versioned tarball of Mehar's tree (guard default) + install/INSTALL-README-SNIPPET.md (new) README snippet; still says guard is the default ``` The 18 PNGs are written by `ui-devtools.spec.ts`; no README embeds them. @@ -330,9 +387,9 @@ sim/ test/latent.test.ts (new) S2 latent re-draws ``` -Check run on b435acb when these docs were written: `SIM_RUNTIME=real npx vitest run` in `sim/` gives 19 passed (5 files); `tsc` clean. +Check run on b435acb when these docs were written: `SIM_RUNTIME=real npx vitest run` in `sim/` gives 19 passed (5 files); `tsc` clean. `sim/` is unchanged since b435acb (not rerun at f107013; the sim pins `mode: "heal"`, so 054da38's observe change does not reach it, but a heal-mode delivery that cannot be held is now released before its body read). -### `realapps/` (230 files) +### `realapps/` (307 files) Doc: [realapps.md](realapps.md). Not a root workspace, no tsconfig, no tests, not in CI; everything real needs Chromium (ask first). @@ -345,14 +402,15 @@ realapps/ every esbuild-built app; RW_RUNTIME_SRC / RW_RUNTIME_TAG pin the runtime (default: working tree, tag "working-tree"); writes dist/runtime-tag.txt README.md design document (corpus, integration, determinism, labels, row kinds, splits, run commands, v1 pilot numbers); - still says 66 apps + still says 66 apps (128 app directories now) EXAMPLES.md 13 audited rows from the v1 pilot apps/README.md authoring guide for app-writing agents (written for the colleague's Mac and branch runtime) apps/_shared/ 12 files: genclass.ts (one-line integration: GenClass.init(window.__GENCLASS_INIT__ ?? {}), flag()), {vue,svelte,solid,preact,lit}-atom.ts, lit-toast.ts, hyperapp-guard.ts, react-genclass-reducer.ts, w3-http.ts, conduit-manifest.ts (conduitManifest for the 14 OSS apps), onnx-stub.ts (aliased for onnxruntime-web) - apps/<name>/ 91 apps: manifest.ts (AppManifest) + source (88 .ts/.tsx/.svelte files across the 77 written apps; - the 14 oss-*-conduit apps have a manifest only). Names: actions-comments, alpine-*, backbone-*, effector-iot, + apps/<name>/ 128 apps at f107013 (91 at b435acb; the merge added waves 3 and 4): manifest.ts (AppManifest) + source + (the 14 oss-*-conduit apps have a manifest only). The name list below is from b435acb; newer apps add + more of the same stacks (backbone-*, knockout-*, valtio-*, xstate-*, vue-*, svelte-*, vanilla-*, ...). Names: actions-comments, alpine-*, backbone-*, effector-iot, htm-iot-dashboard, hyperapp-*, jotai-planner, jquery-*, knockout-*, ky-banking, lit-*, mithril-*, mobx-*, nano-notifications, ofetch-clinic, oss-{angular,angularjs,elm,ember,halogen,mobx,react-redux,rescript,rtk, solid,svelte,vue2,vue3,wc}-conduit, petite-*, pinia-*, preact-*, react-*, reducer-inbox, router-crm, rtk-*, @@ -392,7 +450,7 @@ realapps/ scripts/cluster.sh Mac-side ssh/rsync helper: sync, setup, run (detached gen.js into ~/gcl/real-out/<name>), status, stop ``` -### `training/` (61 files) +### `training/` (69 files) Doc: [training.md](training.md). Every script here runs on Azure VMs; ask before running any of them. @@ -400,9 +458,10 @@ Doc: [training.md](training.md). Every script here runs on Azure VMs; ask before training/ README.md overview and reproduce commands (partly stale) PLAN-v1.md (new) the scaled program: targets, data, models R17/R32/R68/T150/T400, phases P0-P5, costs, eval, risks - LOG.md dated run log (what ran where, throughput, costs, decisions) up to the v2 freeze + LOG.md dated run log (what ran where, throughput, costs, decisions) up to the r17-v2a / t150-v2a launches (05:22 UTC) EVAL.md metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot, final round 1) - NEEDS.md TRAIN requests to SIM / CORE / MODEL / REAL; node claims; v2 data locations + NEEDS.md TRAIN requests to SIM / CORE / MODEL / REAL; node claims (TRAIN: c02 workbench, r17-v2a, t150-v2a); v2 data + locations; item 16: use REAL v2c1..v2c4, not v2b* prune_vocab.py prune/analyze: keep the first N BPE merges (16,000 -> 16,364 tokens) of a checkpoint or HF base eval_runtime.py accuracy, NLL/Brier/ECE, temperature fit (calibration.json), CONTRACT §8 gate metrics, SIM cost regret eval_gain.py (new) T1 expected-gain evaluation of gate policies from cached logits @@ -421,6 +480,16 @@ training/ configs/mix_t150.json (new) teacher (v1 buckets simA .9, cur4 .1) configs/mix_r68.json (new) R68 student benchmark (never run) configs/mix_t1a.json, mix_t1b.json, mix_t1h.json (new) T1 runs (simAg10 / simAg20 / simAh) + configs/mix_v2a.json (new, eff18cb) r17-v2a: sim2 .86, cur5 .11, cur1 .02, gen .01; 500M tokens per pass + configs/mix_t150v2.json (new, eff18cb) t150-v2a teacher: sim2 .9, cur5 .1 + import_v2.sh (new, eff18cb) v2 import from the Mac: serve a collected SIM batch, then on the workbench (c02) download gz + shards, prep_v2.py, the cur5 curriculum replay (300k, 80% runtime-exact), tar served on WB:8799 (Azure) + prep_v2.py (new) collected SIM gz shards -> train shards + eval sets (sim2, sim2e, sim2f held-out features) + v2_node_setup.sh (new) prepare one node for v2 training (sync code, pull the v2 data tar from the workbench) + v2_post.sh (new) detached on a v2 run's rank-0 node: wait for final, eval_sim on sim2e and sim2f, eval_gain, export + with the sim2e calibration, serve the tar on :8801 (runs for r17-v2a on c09) + import_real.sh (new) REAL v2 batches -> data/s3/real2 shards, real2e eval sets, realev (REAL's unambiguous eval set) + eval_real.py (new) REAL eval set under the runtime gate (rows with meta.eval_case / eval_expect) curriculum/__init__.py package docstring curriculum/generate.py seeded parallel curriculum generator (CONTRACT-D jsonl + stats.json); --p-runtime -> GC_P_RUNTIME curriculum/rt.py Python port of packages/runtime/src/situation/* (runtime-exact rows); "FROZEN at git tag situation-v2" @@ -611,7 +680,7 @@ scripts/ demo_proof.sh offline mid-sentence proof (Mac only) ``` -### `docs/` (36 tracked files) +### `docs/` (37 tracked files) ```text docs/ @@ -620,8 +689,7 @@ docs/ runtime/ARCHITECTURE.md architecture overview [runtime/RESULTS.md](../runtime/RESULTS.md) (new) results, comparisons and training-log summary; "update it with every result" (HANDOFF) agents/ these docs: README, overview, repo-map, glossary, playbooks, status-and-known-issues, model-io-contract, - genclass-model-lineage, extension-and-benchmarks, demos, sim, training, runtime/ (8 docs); - realapps.md (new, not yet committed) + genclass-model-lineage, extension-and-benchmarks, demos, sim, training, realapps, runtime/ (8 docs) benchmax-research/ 5 planning notes (read-only background) SPEC.md, CONTRACT.md, CONTRACT-v2.md, DEMO.md, GENCLASS.md, COMPARISON.md, PLAN-excel.md legacy jev-local docs ``` @@ -663,7 +731,7 @@ demos/screenshots/ 31 <demo>.png, <demo>-dark.png, <demo> ## 3. Where is X? -Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/runtime/src/runtime.ts` unless stated. +Verified with `grep` at b435acb; rows touched by the merge and the two fixes re-checked at f107013. Methods are `RuntimeImpl.<name>` in `packages/runtime/src/runtime.ts` unless stated. ### Runtime public API, options and lifecycle @@ -702,11 +770,27 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | In-flight age that blocks settled points (10 s) | constant | `packages/runtime/src/runtime.ts` -> `LONG_RUNNING_MS` | [state-and-adapters](runtime/state-and-adapters.md) | | Console line `[GenClass] Model unavailable (...); observing only.` | string | `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor (status subscription) | [status](status-and-known-issues.md) | +### Install paths (INSTALL, f3a9dd1; not in the published `0.1.0-alpha.1`) + +| X | kind | where | doc | +|---|---|---|---| +| `import "@genclass/runtime/auto"` (observe on this branch) | entry | `packages/runtime/src/auto.ts`; `packages/runtime/src/cdn/auto-start.ts` -> `startAuto` | [status](status-and-known-issues.md) | +| `/auto/observe`, `/auto/guard`, `/auto/heal` | entry | `packages/runtime/src/cdn/auto-observe.ts`, `auto-guard.ts`, `auto-heal.ts` | [status](status-and-known-issues.md) | +| Page config (`<meta name="genclass">`, `window.GENCLASS_CONFIG`, `data-*`) | function | `packages/runtime/src/cdn/config.ts` -> `readMetaConfig`, `readWindowConfig`, `fromDataset`, `fromPairs`, `mergeConfig` | [status](status-and-known-issues.md) | +| Script-tag build (`window.GenClass`) and its asset base | function | `packages/runtime/src/cdn/global.ts` -> `install`, `assetBase`, `blobModuleWorker`; build `packages/runtime/tsup.config.ts` -> `globalBuild` | [status](status-and-known-issues.md) | +| CDN model worker and ORT glue | file, function | `packages/runtime/src/cdn/worker.ts`; `packages/runtime/src/cdn/ort-env.ts` -> `prepareOrt`, `cdnState` | [model-host](runtime/model-host.md) | +| `npx @genclass/runtime init` / `remove` | CLI | `packages/runtime/bin/lib/init.mjs` -> `init`, `remove`, `USAGE` | [status](status-and-known-issues.md) | +| Mode -> import path (guard treated as default: install finding 1) | function | `packages/runtime/bin/lib/plan.mjs` -> `AUTO`, `scriptTag`, `integrityFor` | [status](status-and-known-issues.md#install-code-review-2026-10-08) | +| Framework / entry detection | function | `packages/runtime/bin/lib/detect.mjs` -> `detectProject`, `walkSources` | [status](status-and-known-issues.md#install-code-review-2026-10-08) | +| Edit markers `genclass:init` / `genclass:inline` and their removal | constant, function | `packages/runtime/bin/lib/edit.mjs` -> `MARK`, `MARK_INLINE`, `removeMarked` | [status](status-and-known-issues.md#install-code-review-2026-10-08) | +| Unscoped alias `npx genclass-runtime` (unpublished) | file | `packages/genclass-runtime/cli.mjs` | [status](status-and-known-issues.md) | + ### Delivery decisions (situation-v2, batches 4 and 5) | X | kind | where | doc | |---|---|---|---| -| **The delivery trigger / gate** (pre-filter, body read, hold, actions) | method | `RuntimeImpl.runDelivery` (public member) | [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy](runtime/decide-policy-actions.md) | +| **The delivery trigger / gate** (pre-filter, body read, hold, actions) | method | `RuntimeImpl.runDelivery` (public member) | +| Can this delivery be held? (false in observe, while paused, model not ready, nothing permitted, model too slow) | method | `RuntimeImpl.deliveryHoldable`; `RuntimeImpl.writesCanAct`; `RuntimeImpl.finalizeDeliveries` (decide a released fetch delivery at its chain's first write) (054da38) | [decide-policy](runtime/decide-policy-actions.md) | [learn-situation-triage](runtime/learn-situation-triage.md), [decide-policy](runtime/decide-policy-actions.md) | | Body wait for salience (100 ms) | constant | `packages/runtime/src/runtime.ts` -> `BODY_WAIT_MS` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Discard mark lifetime (10 s) and the drop filter | constant, method | `packages/runtime/src/runtime.ts` -> `DISCARD_MARK_MS`; `RuntimeImpl.dropFilter`, `RuntimeImpl.writtenOver`, `RuntimeImpl.onDropped`; `packages/runtime/src/state/hub.ts` -> `StoreHub.propose` (calls the private `applyFilter`) | [decide-policy](runtime/decide-policy-actions.md), [state-and-adapters](runtime/state-and-adapters.md) | | Discard mark on the op (`discardMark`) and the delivery record (`delivery`) | type | `packages/runtime/src/trace/ops.ts` -> `OpRec` | [observe-and-trace](runtime/observe-and-trace.md) | @@ -727,7 +811,7 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | Delivery facts and the trigger sentence's prediction text | function | `packages/runtime/src/situation/facts.ts` -> `computeFacts` (internal `deliveryFacts`), `predictedText` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Delivery actions `deliver` / `discard` / `defer` | constant | `packages/runtime/src/situation/questions.ts` -> `TRIGGER_ACTIONS.delivery`, `PASSIVE.delivery` | [decide-policy](runtime/decide-policy-actions.md) | | Relation quality (F8) and count-by-group invariants | class | `packages/runtime/src/state/invariants.ts` -> `InvariantMiner` | [state-and-adapters](runtime/state-and-adapters.md) | -| Diff-centred string previews (F2, timeline, deltas) | function | `packages/runtime/src/state/fields.ts` -> `stringDiff`, `changeText` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Diff-centred string previews (F2, timeline, deltas); only for values the redactor leaves unchanged (f107013) | function | `packages/runtime/src/state/fields.ts` -> `stringDiff`, `redactedStringDiff`, `changeText` | [learn-situation-triage](runtime/learn-situation-triage.md) | ### Observers and trace @@ -749,7 +833,7 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | Event ring buffer | class | `packages/runtime/src/trace/events.ts` -> `EventLog` | [observe-and-trace](runtime/observe-and-trace.md) | | Op signature normalisation (`GET /api/items/:id`) | function | `packages/runtime/src/util.ts` -> `normalizePath`, `isIdSegment`, `requestSignature` | [observe-and-trace](runtime/observe-and-trace.md) | | Hashing | function | `packages/runtime/src/util.ts` -> `fnv1a`, `stableStringify` | [public-api](runtime/public-api-and-lifecycle.md) | -| Default redaction (leaf-name based) | function | `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath` | [learn-situation-triage](runtime/learn-situation-triage.md) | +| Default redaction (leaf-name based; numbers/bigints/arrays under strong secret containers since f107013) | function | `packages/runtime/src/util.ts` -> `defaultRedact`, `isSensitivePath` | [learn-situation-triage](runtime/learn-situation-triage.md) | ### State and adapters @@ -782,7 +866,7 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | Read-only runtime view for situation code; trigger subjects | type | `packages/runtime/src/situation/env.ts` -> `SitEnv`, `SubjectSpec` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Op phrasing in situations and `changed` sentences | function | `packages/runtime/src/situation/describe.ts` -> `opPhrase` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Python port of the situation text | function | `training/curriculum/rt.py` -> `render` | [training](training.md) | -| Freeze marker | git tag | `situation-v2` (6e5e86e; current); `situation-v1` (1a77558; old format). Check with `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/learn packages/runtime/src/util.ts packages/runtime/src/state/fields.ts` (empty at b435acb) | [model-io-contract](model-io-contract.md) | +| Freeze marker | git tag | `situation-v2` (6e5e86e; the v2 data's format); `situation-v2.1` (5bc40c9, on `origin/runtime` only); `situation-v1` (1a77558; old format). Check with `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/learn packages/runtime/src/util.ts packages/runtime/src/state/fields.ts` (empty at b435acb; at f107013 it shows the redaction fix in `content.ts`, `fields.ts`, `util.ts`) | [model-io-contract](model-io-contract.md) | ### Decide, policy and reports @@ -840,8 +924,8 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | Workspaces (`packages/*`, `sim`, `demos`) and root scripts `build`, `test`, `typecheck` | config | `package.json` -> `workspaces`, `scripts` | [build-test-release](runtime/build-test-release.md) | | Root lockfile (committed) | file | `package-lock.json` | [build-test-release](runtime/build-test-release.md) | | **CI** (typecheck, build, unit tests, perf budgets) | workflow | `.github/workflows/ci.yml` -> job `runtime` | [build-test-release](runtime/build-test-release.md) | -| Subpath exports and `bin` | config | `packages/runtime/package.json` -> `exports`, `bin` | [build-test-release](runtime/build-test-release.md) | -| Build entries and externals | config | `packages/runtime/tsup.config.ts` -> `entry`, `dts`, `external` | [build-test-release](runtime/build-test-release.md) | +| Subpath exports (incl. `./auto*`), `sideEffects`, `bin`, `version` | config | `packages/runtime/package.json` -> `exports`, `sideEffects`, `bin`, `version` | [build-test-release](runtime/build-test-release.md) | +| Build entries and externals (ESM, two global builds, CDN worker) | config | `packages/runtime/tsup.config.ts` -> `entry`, `dts`, `external`, `globalBuild`, plugins `cdnOrt`, `ortExternal` | [build-test-release](runtime/build-test-release.md) | | Unit-test include/exclude | config | `packages/runtime/vitest.config.ts` | [build-test-release](runtime/build-test-release.md) | | Typecheck: `npx tsc -p tsconfig.json --noEmit` (in `packages/runtime`), or `npm run typecheck -w @genclass/runtime` | command | `packages/runtime/package.json` -> `scripts.typecheck` | [build-test-release](runtime/build-test-release.md) | | Unit tests: `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then `npx vitest run test/review-perf.test.ts --retry=2` (in `packages/runtime`) | command | `packages/runtime/vitest.config.ts`; `.github/workflows/ci.yml`; gc check in `packages/runtime/test/review-timers.test.ts` | [build-test-release](runtime/build-test-release.md) | @@ -854,12 +938,14 @@ Verified with `grep` at b435acb. Methods are `RuntimeImpl.<name>` in `packages/r | Playwright global setup (rebuilds `dist/`) | function | `packages/runtime/test/browser/build.mjs` -> `buildLibrary` | [build-test-release](runtime/build-test-release.md) | | Model fixtures from an export instead of v0.1 | flag | `packages/runtime/test/model/helpers.ts` -> `FIXTURES_FROM_MODEL` | [build-test-release](runtime/build-test-release.md) | | VM helper `scripts/vm.sh sync\|run\|exec\|get SLOT ...` (Azure; ask first) | command | `scripts/vm.sh` | [build-test-release](runtime/build-test-release.md) | -| Release and freeze tags `v0.1.0-alpha.0` (654d822), `situation-v1` (1a77558), `situation-v2` (6e5e86e) | git tag | `git tag -n1` | [build-test-release](runtime/build-test-release.md) | +| Release and freeze tags `v0.1.0-alpha.0` (654d822), `v0.1.0-alpha.1` (806a296, local), `situation-v1` (1a77558), `situation-v2` (6e5e86e), `situation-v2.1` (5bc40c9, not merged) | git tag | `git tag -n1` | +| Changelog and install requests | file | `packages/runtime/CHANGELOG.md`; `packages/runtime/INSTALL-NEEDS.md` | [build-test-release](runtime/build-test-release.md) | ### Environment variables | X | used by | where | doc | |---|---|---|---| +| `INSTALL_OUT`, `INSTALL_TMP`, `SCAFFOLDS`, `WORK`, `TGZ`, `SKIP_DEV` | install suite on the VM (ask first) | `packages/runtime/test/install/run-all.sh`, `scaffold.sh`, `frameworks.mjs` | [status](status-and-known-issues.md) | | `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) | model unit tests and browser specs | `packages/runtime/test/model/helpers.ts` -> `MODEL_DIR`; `packages/runtime/test/browser/model-helpers.ts` -> `MODEL_DIR` | [build-test-release](runtime/build-test-release.md) | | `GENCLASS_WEBGPU_VARIANTS` | WebGPU spec variants | `packages/runtime/test/browser/model-webgpu.spec.ts` | [build-test-release](runtime/build-test-release.md) | | `GENCLASS_BENCH_MODELS`, `GENCLASS_OFFLINE` | browser model specs | `packages/runtime/test/browser/model.spec.ts` | [build-test-release](runtime/build-test-release.md) | @@ -985,7 +1071,7 @@ Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitign | `node_modules/` (root) | root | `npm ci` / `npm install` at the repo root (workspaces hoisted) | `extension/`, `realapps/` and `training/ortweb/` are not workspaces and need their own `npm install` | | `package-lock.json` (root) | **tracked** since b435acb | `npm install` at the root rewrites it | CI uses `npm ci`, which fails if `package.json` and the lockfile disagree; commit lockfile changes only when you changed dependencies on purpose | | `packages/runtime/bin/genclass-runtime.mjs` mode | — | committed as 100755 since b435acb | the old spurious "mode changed" diff after `npm install` is gone | -| `packages/runtime/dist/` | root `dist/` | `npx tsup` / `npm run build` (in `packages/runtime`); also `sim`'s `build:runtime-core` script and `packages/runtime/test/browser/build.mjs` (Playwright global setup) rewrite it | `sim` and `demos` import the runtime through this `dist/`; a working copy may hold a stale one | +| `packages/runtime/dist/` | root `dist/` | `npx tsup` / `npm run build` (in `packages/runtime`); also `sim`'s `build:runtime-core` script and `packages/runtime/test/browser/build.mjs` (Playwright global setup) rewrite it | `sim` and `demos` import the runtime through this `dist/`; a working copy may hold a stale one. Since the merge it also holds `auto.js`, `auto/*.js`, `genclass.global{,.min}.js` (version baked in) and `cdn/` (the CDN worker with onnxruntime-web bundled); the CLI hashes the global build for SRI | | `sim/dist/` | root `dist/` | `npm run build` in `sim` (tsup: `gen`, `worker`, `index`, `smoke`; plus `build:model-host` -> `sim/dist/model-host/`) | — | | `realapps/dist/`, `realapps/node_modules/` | root and `realapps/.gitignore` | `node build.mjs` in `realapps/` (world, harness, apps, `runtime-tag.txt`); `npm install` there | builds launch nothing, but the outputs are only useful with Chromium (ask first to run) | | `realapps/src/harness/apps.gen.ts` | `realapps/.gitignore` | `realapps/build.mjs` (one import per `apps/*/manifest.ts`) | regenerate after adding an app | @@ -1009,11 +1095,11 @@ Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitign | `extension/release-assets/*.onnx` | `extension/.gitignore` | `extension/tools/genclass_export.py` | absent | | `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/` | root | Python venv, pytest, `pip install -e .` of `jev-local` | — | | `.DS_Store` | root, `extension/.gitignore` | macOS Finder | — | -| `docs/agents/realapps.md` | not ignored | new, not yet committed | untracked at b435acb; commit it with the other doc refreshes | +| `/data/install/*` (VM) | outside the repo | `packages/runtime/test/install/run-all.sh` (`INSTALL_OUT`, scaffolds, work dirs, tarball) | VM paths | ## 5. Large files: do not read in full -Sizes from `git ls-tree -l b435acb` / `wc -l`. "0 lines" means one line with no trailing newline: inspect it with `python3 -c` or `jq` (keys, lengths, one record) instead of opening it. +Sizes from `git ls-tree -l b435acb` / `wc -l` (rows marked f107013 re-measured there). "0 lines" means one line with no trailing newline: inspect it with `python3 -c` or `jq` (keys, lengths, one record) instead of opening it. | path | bytes | lines | what it is / how to read it | |---|---|---|---| @@ -1033,12 +1119,12 @@ Sizes from `git ls-tree -l b435acb` / `wc -l`. "0 lines" means one line with no | `extension/test/fixtures/questions_py.json` | 222,955 | 16,984 | Python-harness question fixtures | | `docs/benchmax-research/jev-published.md` | 217,513 | 2,206 | census of published Jev numbers | | `packages/runtime/test/fixtures/model/py_fixtures.json` | 167,629 | 0 | Python reference cases for serialize/tokenize/calibrate/confidence | -| `package-lock.json` | 105,864 | 3,203 | root lockfile; never edit by hand | +| `package-lock.json` | 106,273 | 3,220 | root lockfile (f107013); never edit by hand | | `jev_local/bench/registry.py` | 90,896 | 1,888 | jevbench dataset registry and exclusion rules (source; grep it) | -| `packages/runtime/src/runtime.ts` | 87,440 | 2,003 | `RuntimeImpl`; jump to methods by name (`trigger`, `runDelivery`, `onDecision`, `settled`) | +| `packages/runtime/src/runtime.ts` | 95,517 | 2,143 | `RuntimeImpl` (f107013); jump to methods by name (`trigger`, `runDelivery`, `deliveryHoldable`, `onDecision`, `settled`) | | `docs/SPEC.md` | 84,347 | 1,131 | legacy jev-local rebuild spec | | `docs/benchmax-research/{PLAN,feasibility-targets,suite-reproduction-specs,train-data-and-supervised-ceilings}.md` | 72,630-93,641 each | 768-971 each | benchmax planning notes | -| `packages/runtime/STATUS.md` | 75,336 | 1,045 | CORE status; read "State", then the batch section you need | +| `packages/runtime/STATUS.md` | 80,206 | 1,097 | CORE status (f107013); read "State", then the fix or batch section you need | | `sim/samples/EXAMPLES.md` | 68,211 | 1,484 | pretty-printed sim rows | | `training/curriculum/rt.py` | 66,963 | 1,349 | Python port of the situation renderer; grep by function (`render`, `event_lines`, `content_facts`) | | `extension/test/fixtures/spans_py.json` | 59,806 | 5,458 | Python-harness span fixtures | @@ -1057,9 +1143,22 @@ Other source files over 25 KB that are better read by symbol than end to end: `p Doc-vs-code drift you will meet while navigating; the subsystem docs have the details. -- **Default mode**: code, `docs/runtime/API.md`, CONTRACT §13 and the devtools say `observe`; `README.md` and `packages/runtime/README.md` agree; only `HANDOFF.md` (and the older published alpha.0) still say guard is the default. -- **`OPEN_TASKS.md`** now describes the v2 pipeline (items 1-14); see also [HANDOFF.md](../../HANDOFF.md) and [training.md](training.md). -- **App counts**: `realapps/README.md` and `HANDOFF.md` say 66 apps; the tree has 91 (25 added after the sweeps were run). The never-worse result 0/396 covers the 66 ([realapps.md](realapps.md)). -- **Sim budget**: `sim/src/world/scenario.ts` still samples situation budgets 3,200 / 2,000 / 1,000 (40/30/30), while the v2 runtime's full budget is 2,400 ([sim.md](sim.md)). -- **Test counts**: `packages/runtime/STATUS.md` says 41 files / 346 tests (before `default-mode.test.ts`); see [runtime/build-test-release.md](runtime/build-test-release.md) for the b435acb numbers. -- **realapps output**: batch `manifest.json` files hardcode `situation-v1` and `TRIGGER_W` has no `delivery` weight (`realapps/src/harness/gen.ts`, `realapps/src/harness/trajectory.ts`); see [realapps.md](realapps.md). +- **Default mode**: code, `docs/runtime/API.md`, CONTRACT §13, the devtools and both READMEs say `observe`; `HANDOFF.md`, + `origin/runtime` (code), the older published alpha.0, the `init` usage text (`packages/runtime/bin/lib/init.mjs` -> + `USAGE`), its mode mapping (`packages/runtime/bin/lib/plan.mjs` -> `AUTO`) and + `packages/runtime/test/install/INSTALL-README-SNIPPET.md` still assume guard + ([status-and-known-issues.md](status-and-known-issues.md#install-code-review-2026-10-08)). +- **Version**: `packages/runtime/package.json` and `packages/genclass-runtime/package.json` say `0.1.0-alpha.1`, already + published without the install paths; `packages/runtime/CHANGELOG.md` lists the install paths under alpha.1. +- **Subsystem docs**: `docs/agents/runtime/build-test-release.md` and `public-api-and-lifecycle.md` (as committed at + f107013) still describe six tsup entries and `"sideEffects": false`; no subsystem doc covers `src/auto.ts`, + `src/cdn/` or `bin/lib/` yet. +- **App counts**: `realapps/README.md` and `HANDOFF.md` say 66 apps; the tree has 128 app directories. The never-worse + result 0/396 covers the 66 ([realapps.md](realapps.md)). +- **Sim budget**: `sim/src/world/scenario.ts` still samples situation budgets 3,200 / 2,000 / 1,000 (40/30/30), while the + v2 runtime's full budget is 2,400 ([sim.md](sim.md)); the finished v2 SIM data carries it. +- **Test counts**: `packages/runtime/STATUS.md` says 42 files / 348 tests; this branch has 46 files / 393 tests. +- **realapps output**: batch `manifest.json` files hardcode `situation-v1` and `TRIGGER_W` has no `delivery` weight + (`realapps/src/harness/gen.ts`, `realapps/src/harness/trajectory.ts`); see [realapps.md](realapps.md). +- **Newer upstream**: `origin/runtime` 5bc40c9 (batch 6, `situation-v2.1`, 150 app directories) is not merged here; the + local branch `mvp-v2-b6` merges it. diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index 5458012e..dcd07643 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -1,25 +1,26 @@ # Build, test and release (@genclass/runtime and the monorepo) -> **Scope:** `package.json` and `package-lock.json` (root), `tsconfig.base.json`, `.gitignore`, `.github/workflows/ci.yml`, `packages/runtime/{package.json,tsconfig.json,tsup.config.ts,vitest.config.ts}`, `packages/runtime/bin/genclass-runtime.mjs` (packaging only), `packages/runtime/test/**` (unit, model, browser, smoke, fixtures), `packages/runtime/STATUS.md` ("State" and "How to drive it headless"), `scripts/vm.sh`, `OPEN_TASKS.md` and `HANDOFF.md` (packaging, release), `sim/package.json`, `demos/package.json`, `realapps/package.json`, `packages/runtime-model/`. -> **Read this when:** you need to build, typecheck or test the runtime; add or fix a test; understand or change CI; regenerate fixtures; run the Playwright model/UI specs or the npm-pack smoke test; publish a version; or understand how `sim/`, `demos/` and `realapps/` consume the runtime package. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Scope:** `package.json` and `package-lock.json` (root), `tsconfig.base.json`, `.gitignore`, `.github/workflows/ci.yml`, `packages/runtime/{package.json,tsconfig.json,tsup.config.ts,vitest.config.ts}`, `packages/runtime/bin/genclass-runtime.mjs` and `bin/lib/*.mjs` (packaging only), `packages/genclass-runtime/` (the unscoped CLI alias), `packages/runtime/test/**` (unit, model, install, browser, smoke, fixtures), `packages/runtime/STATUS.md` ("State" and "How to drive it headless"), `scripts/vm.sh`, `OPEN_TASKS.md` and `HANDOFF.md` (packaging, release), `sim/package.json`, `demos/package.json`, `realapps/package.json`, `packages/runtime-model/`. +> **Read this when:** you need to build, typecheck or test the runtime; add or fix a test; understand or change CI; regenerate fixtures; run the Playwright model/UI specs, the npm-pack smoke test or the install tests (`test/install/`); publish a version; or understand how `sim/`, `demos/` and `realapps/` consume the runtime package. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. `origin/runtime` has since moved on to 5bc40c9 (Mehar: realapps wave 4, `r17-v2a` results in `docs/runtime/RESULTS.md`, runtime batch 6 with model-provided gate thresholds, tag `situation-v2.1`); none of that is merged here. If this doc and the code disagree, the code wins. ## TL;DR -- npm workspaces monorepo: `packages/*`, `sim`, `demos` (`realapps/` has its own `package.json` but is **not** a workspace). Root `npm run build` / `npm test` touch only `@genclass/runtime`; root `npm run typecheck` runs every workspace's `typecheck` (`--if-present`: runtime, `sim`, `demos`), and the demos part fails in this checkout (see gotchas). +- npm workspaces monorepo: `packages/*`, `sim`, `demos` (`realapps/` has its own `package.json` but is **not** a workspace). Since f3a9dd1, `packages/*` also matches `packages/genclass-runtime` (the unscoped alias package `genclass-runtime`, no scripts). Root `npm run build` / `npm test` touch only `@genclass/runtime`; root `npm run typecheck` runs every workspace's `typecheck` (`--if-present`: runtime, `sim`, `demos`), and the demos part fails in this checkout (see gotchas). - **A root `package-lock.json` is committed now** (b435acb, lockfileVersion 3), so `npm ci` works on a fresh clone and CI uses it. -- **CI exists**: `.github/workflows/ci.yml` (b435acb), one job on `ubuntu-latest`, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`: `npm ci` -> typecheck -> build -> unit tests (browser specs and `review-perf.test.ts` excluded) -> `review-perf.test.ts` alone with `--retry=2`. Triggers: push to `main`, `runtime`, `mvp`, `mvp-v2`; every `pull_request`; `workflow_dispatch`. It has not run on GitHub yet: `mvp-v2` is not pushed (`origin/runtime` = 74f17c0 has no `.github/`). -- **Run policy.** Mehar's team rule ("the Mac only edits files"; everything runs on the Azure `train` VM through `scripts/vm.sh`) exists because *his* Mac has 8 GB RAM (`HANDOFF.md` "Rules", `scripts/vm.sh` header, `docs/runtime/CONTRACT.md` §0 rule 5). For agents on other machines (lead policy, 2026-10-08): npm install/ci, tsc, tsup and the vitest unit tests are light and run locally; **ask the user first** before Playwright (including `test/smoke/smoke.sh`), the sim generator, training, realapps runs, the demos' eval, model downloads, anything on Azure, `git push` and `npm publish`. See [Where to run things](#where-to-run-things). -- Build = `tsup` (`packages/runtime/tsup.config.ts`, unchanged since situation-v1): ESM only, 6 entries (`index`, 3 adapters, `devtools/index`, `worker`), `.d.ts` for all but the worker, `clean: true`, `splitting: true`. Output goes to `packages/runtime/dist/`, which `package.json` `exports` points at. +- **CI exists**: `.github/workflows/ci.yml` (b435acb), one job on `ubuntu-latest`, Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`: `npm ci` -> typecheck -> build -> unit tests (browser specs and `review-perf.test.ts` excluded) -> `review-perf.test.ts` alone with `--retry=2`. Triggers: push to `main`, `runtime`, `mvp`, `mvp-v2`; every `pull_request`; `workflow_dispatch` (`mvp-v2-merge` is not a trigger branch; a push of it runs CI only through a pull request). The unit-test step now also runs `test/install/cli.test.ts` (it is under `test/**`). It has not run on GitHub yet: neither `mvp-v2` nor `mvp-v2-merge` is pushed (`origin/runtime`, eff18cb at the merge and 5bc40c9 now, has no `.github/`). +- **Run policy.** Mehar's team rule ("the Mac only edits files"; everything runs on the Azure `train` VM through `scripts/vm.sh`) exists because *his* Mac has 8 GB RAM (`HANDOFF.md` "Rules", `scripts/vm.sh` header, `docs/runtime/CONTRACT.md` §0 rule 5). For agents on other machines (lead policy, 2026-10-08): npm install/ci, tsc, tsup and the vitest unit tests are light and run locally; **ask the user first** before Playwright (including `test/smoke/smoke.sh`), the sim generator, training, realapps runs, the install tests other than `cli.test.ts` (`test/install/run-all.sh`, `cdn-check.mjs`, `scaffold.sh`, `frameworks.mjs`), the demos' eval, model downloads, anything on Azure, `git push` and `npm publish`. See [Where to run things](#where-to-run-things). +- Build = `tsup` (`packages/runtime/tsup.config.ts`, rewritten in f3a9dd1): **an array of 4 configs** that tsup runs in parallel. (1) The main ESM build: 10 entries (`index`, `auto`, `auto/observe`, `auto/guard`, `auto/heal`, 3 adapters, `devtools/index`, `worker`), `.d.ts` for all but the worker, `splitting: true`, `clean: ["!cdn/**", "!genclass.global*"]`. (2, 3) The script-tag build `src/cdn/global.ts` as IIFE (`window.GenClass`), unminified `dist/genclass.global.js` and minified `dist/genclass.global.min.js` (+ map), onnxruntime-web kept out. (4) The CDN module worker + onnxruntime-web into `dist/cdn/` (`worker.js`, `ort-webgpu.js`, `ort-wasm.js`, chunks; minified, onnxruntime-web bundled). Output goes to `packages/runtime/dist/`, which `package.json` `exports` (and the new `unpkg` / `jsdelivr` fields) point at. - Typecheck = `tsc -p tsconfig.json --noEmit` over `src/` only. **Test files are never type-checked.** -- Unit tests = vitest, **42 tracked files** (36 under `test/`, 6 under `test/model/`), **350 tests**. Default environment `node`; 5 files opt into `happy-dom` per file. Verified 2026-10-08 without a model directory: 336 passed + 14 skipped, split the way CI runs them (346 in the main run, 4 in `review-perf.test.ts`; see [Verified locally](#verified-locally-2026-10-08)). +- Unit tests = vitest, **46 tracked files** (39 under `test/`, 6 under `test/model/`, 1 under `test/install/`), **393 tests**. Default environment `node`; 5 files opt into `happy-dom` per file. Verified 2026-10-08 on `mvp-v2-merge` without a model directory: 379 passed + 14 skipped, split the way CI runs them (389 in the main run: 375 passed + 14 skipped; 4 in `review-perf.test.ts`; see [Verified locally](#verified-locally-2026-10-08)). New since b435acb: `install/cli.test.ts` (20), `situation-purity` (2), `observe-delivery` (11), `redaction-v2` (10). - **Default mode is `observe`** in the product (f3636b2: `src/runtime.ts` -> `o.mode ?? "observe"`), but the test harness `test/helpers.ts` -> `setup()` passes `mode: "guard"` by default, and `smoke.test.ts`, `review-fetch.test.ts` -> `headless()` and `test/browser/ui/session.ts` -> `runStoreSession` pass `mode: "guard"` explicitly. Pass `mode: undefined` to `setup()` to get the product default (`test/default-mode.test.ts` does). - **Store writes are not held by default** (situation-v2, `policy.holdWrites` off). Tests that exercise held store writes pass `policy: { holdWrites: true }` (`atoms.test.ts` wraps `setup()` to add it); default behaviour (delivery decisions at the network boundary, late reverts) is tested in `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts`. - Runtime unit tests run on a virtual clock (`test/helpers.ts` -> `FakeClock`), a virtual HTTP server (`FakeServer`) and a scripted model (`ScriptedDecider` / `ManualDecider`): no real time, no network, no model. Exceptions (wall-time perf checks, `loader.test.ts`'s real `browserClock`, model-file tests) are listed under gotchas. -- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. **No situation-v2 model exists yet**; the only fixtures and models are the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). +- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`); without it 14 model tests skip. **No situation-v2 model is published or in this branch** (Mehar's first one, `r17-v2a`, is evaluated only in origin/runtime 416e374's `docs/runtime/RESULTS.md`, not merged); the only fixtures and models here are the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). - Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. Not run in CI. - `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. Not run in CI. -- Released: `@genclass/runtime@0.1.0-alpha.1` on npm, dist-tag `latest`, 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. Before it: `@genclass/runtime@0.1.0-alpha.0` (was `latest`; checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish <tgz> --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). Pending: `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. +- Install tests (`test/install/`, f3a9dd1): `cli.test.ts` is an ordinary vitest file (runs `bin/genclass-runtime.mjs init --yes --no-install` and `remove --yes` on fixture projects in the OS temp dir, no network) and runs locally and in CI. The rest is a VM harness (`run-all.sh` -> build + pack -> `cli.test.ts` -> `cdn-check.mjs` -> `scaffold.sh` -> `frameworks.mjs`; Playwright, framework generators, npm registry; outputs under `/data/install`). Mehar's last run is in `test/install/RESULTS.md` (15/15 projects, CLI 20/20, CDN 26/26, against a locally packed `0.1.0-alpha.0`-versioned tarball). Not run in CI. +- Released: `@genclass/runtime@0.1.0-alpha.1` on npm, 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. Before it: `@genclass/runtime@0.1.0-alpha.0` (was `latest`; checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish <tgz> --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). **The published `0.1.0-alpha.1` does not contain Mehar's one-command install** (`init`/`remove`, `/auto`, the CDN script tag, the `genclass-runtime` alias, f3a9dd1): those came in with the merge of origin/runtime eff18cb, after the publish. npm versions are immutable, so they ship in the **next** version (`0.1.0-alpha.2`, or a beta together with the model); `packages/runtime/package.json` still says `0.1.0-alpha.1` on `mvp-v2-merge` and must be bumped before packing. Pending: that next runtime version, `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. - `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. `realapps` bundles `packages/runtime/src` directly with esbuild (see [../realapps.md](../realapps.md)). ## Files @@ -29,15 +30,20 @@ | `package.json` | root, private `genclass-lib`, `"type": "module"` | workspaces `packages/*`, `sim`, `demos`; scripts `build`, `test`, `typecheck`; devDep `typescript ~5.9.3`; `engines.node >=20`; license Apache-2.0 | | `tsconfig.base.json` | shared compiler options | see Configuration | | `.gitignore` | ignores build and model artefacts | "GenClass runtime" block: `node_modules/`, `dist/`, `.vite/`, `test-results/`, `playwright-report/`, `sim/out/`, `packages/runtime-model/files/`, `.cache-model/`, `.publish/`, `*.tgz` (the last two added in 59c213f). Older Python block: `.venv/`, `__pycache__/`, `*.pyc`, `.pytest_cache/`, `*.egg-info/`, `data/`, `models/`, `runs/`, `dist/`, `node_modules/`, `.DS_Store`. `data/`, `models/`, `runs/` are unanchored (match at any depth). `package-lock.json` is **not** ignored | -| `package-lock.json` (root) | committed lockfile (b435acb) | `lockfileVersion: 3`, 213 `packages` entries; records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }`. Resolved versions include `vitest 5.0.3`, `tsup 8.5.1`, `typescript 5.9.3`, `esbuild 0.27.7`, `happy-dom 20.14.5`, `onnxruntime-web`/`onnxruntime-node 1.30.0`, `@playwright/test 1.63.0`, `vite 8.3.3`. `npm ci` installs exactly this | +| `package-lock.json` (root) | committed lockfile (b435acb) | `lockfileVersion: 3`, 215 `packages` entries (213 at b435acb; the merge added the `genclass-runtime` alias workspace, re-synced in 10e5c3b); records `node_modules/@genclass/runtime` as `{ "resolved": "packages/runtime", "link": true }` and `node_modules/genclass-runtime` -> `packages/genclass-runtime` the same way. Resolved versions include `vitest 5.0.3`, `tsup 8.5.1`, `typescript 5.9.3`, `esbuild 0.27.7`, `happy-dom 20.14.5`, `onnxruntime-web`/`onnxruntime-node 1.30.0`, `@playwright/test 1.63.0`, `vite 8.3.3`. `npm ci` installs exactly this | | `.github/workflows/ci.yml` | the only CI workflow (b435acb) | job `runtime`; see [CI](#ci-githubworkflowsciyml) | -| `packages/runtime/package.json` | the published package | name `@genclass/runtime`, version `0.1.0-alpha.1` (bumped in release commit 806a296, the head of `mvp-v2`; it was `0.1.0-alpha.0` from 59c213f to b435acb), `exports`, `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | +| `packages/runtime/package.json` | the published package | name `@genclass/runtime`, version `0.1.0-alpha.1` (bumped in release commit 806a296; it was `0.1.0-alpha.0` from 59c213f to b435acb; on `mvp-v2-merge` the tree has moved on, so the next release must bump it), `exports` (since f3a9dd1 also `./auto`, `./auto/observe`, `./auto/guard`, `./auto/heal`), `unpkg` / `jsdelivr` = `./dist/genclass.global.min.js` (what a bare `cdn.jsdelivr.net/npm/@genclass/runtime` URL serves), `sideEffects` (a list since f3a9dd1, was `false`), `bin`, `files`, scripts `build`/`typecheck`/`test`/`test:browser` | | `packages/runtime/tsconfig.json` | typecheck project | extends base; `rootDir: src`, `outDir: dist`, `jsx: react-jsx`, `types: []`, `include: ["src"]` | -| `packages/runtime/tsup.config.ts` | build | entries, dts entries, externals | -| `packages/runtime/vitest.config.ts` | unit-test runner config | include `test/**/*.test.ts`, exclude `test/browser/**`, env `node`, `testTimeout 20000` | -| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (not built); committed as mode 100755 since b435acb (it was 100644, and every root `npm install` showed a mode change) | `fetch-model <dir> [--from] [--variant q8\|fp16\|all] [--force] [--quiet]`, `info <dir>`; `DEFAULT_FROM` | +| `packages/runtime/tsup.config.ts` | build | `defineConfig([...])` with 4 configs: main ESM (entries, dts entries, externals), `globalBuild(false)` / `globalBuild(true)` (IIFE script tag, plugin `genclass-ort-external`, `define: { __GENCLASS_VERSION__ }` from `package.json` `version`), CDN worker (`outDir: "dist/cdn"`, `noExternal: [/^onnxruntime-web/]`, plugin `genclass-cdn-ort` that maps the worker's `import("onnxruntime-web/webgpu" \| "/wasm")` to `src/cdn/ort-*.ts`). A top-level `readdirSync("dist")` loop deletes old `genclass.global*` files before any build starts | +| `packages/runtime/vitest.config.ts` | unit-test runner config | include `test/**/*.test.ts`, exclude `test/browser/**`, env `node`, `testTimeout 20000` (unchanged; it now also collects `test/install/cli.test.ts`) | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI shipped in the tarball (not built); committed as mode 100755 since b435acb (it was 100644, and every root `npm install` showed a mode change) | `init [--mode observe\|guard\|heal] [--yes] [--dry-run] [--no-install] [--no-devtools]`, `remove [--yes] [--dry-run] [--keep-package]` (both f3a9dd1; both also take `--cwd <dir>`, per `bin/lib/init.mjs`), `fetch-model <dir> [--from] [--variant q8\|fp16\|all] [--force] [--quiet]`, `info <dir>`; `DEFAULT_FROM` | +| `packages/runtime/bin/lib/{detect,edit,init,plan,ui}.mjs` | `init` / `remove` implementation (f3a9dd1), shipped via `files: ["bin"]` | framework detection, text edits with markers (`edit.mjs` -> `appendEnd`, `bodyTagEnd`, `codeStyle`, `insertTop`, `removeMarked`, `topOffset`, imported by `cli.test.ts`), plan and prompts | +| `packages/runtime/src/auto.ts`, `src/cdn/*.ts` | sources of the `/auto` entries and the script-tag / CDN builds (f3a9dd1) | `auto-{observe,guard,heal}.ts`, `auto-start.ts`, `config.ts` (data-attribute / meta / query config: `fromDataset`, `readMetaConfig`, `mergeConfig`, ...), `global.ts` (`assetBase`), `worker.ts`, `ort-env.ts`, `ort-{wasm,webgpu}.ts`. Behaviour: [public-api-and-lifecycle.md](public-api-and-lifecycle.md) | +| `packages/genclass-runtime/{package.json,cli.mjs,README.md,LICENSE}` | unscoped alias package `genclass-runtime` `0.1.0-alpha.1` (f3a9dd1), so `npx genclass-runtime init` works | `cli.mjs` resolves `@genclass/runtime/package.json` and imports its `bin/genclass-runtime.mjs`; `dependencies: { "@genclass/runtime": "0.1.0-alpha.1" }` (exact). A workspace (no scripts), so it is in the root lockfile. Not on npm (`npm view genclass-runtime` returned 404 on 2026-10-08) | +| `packages/runtime/test/install/` | install tests (f3a9dd1) | `cli.test.ts` (vitest, 20 tests); VM-only `run-all.sh`, `cdn-check.mjs`, `scaffold.sh`, `frameworks.mjs`, `server.mjs`; `RESULTS.md` (last VM run), `INSTALL-README-SNIPPET.md` | +| `packages/runtime/CHANGELOG.md`, `INSTALL-NEEDS.md` | release notes and the install workstream's needs (f3a9dd1) | CHANGELOG lists the install features under `0.1.0-alpha.1` (see Drift) | | `packages/runtime/test/helpers.ts` | core test kit | `drain`, `FakeClock`, `choice`, `ScriptedDecider`, `defaultScript`, `FakeServer`, `makeGlobal`, `setup` (defaults `mode: "guard"` since f3636b2), `ManualDecider` | -| `packages/runtime/test/*.test.ts` | 36 tracked unit test files (CORE, UI, REVIEW, lead) | see Tests. New since 654d822: `content`, `delivery`, `no-reorder`, `nan`, `default-mode` | +| `packages/runtime/test/*.test.ts` | 39 tracked unit test files (CORE, UI, REVIEW, lead) | see Tests. New since 654d822: `content`, `delivery`, `no-reorder`, `nan`, `default-mode`; since b435acb: `situation-purity` (29b7f28), `observe-delivery` (054da38), `redaction-v2` (f107013) | | `packages/runtime/test/model/helpers.ts` | model test kit | `PKG`, `FIX`, `MODEL_DIR`, `readJson`, `modelFile`, `hasModelFile`, `FIXTURES_FROM_MODEL`, `requests`, `packs`, `torch`, `exportParity`, `pyFixturesPath`, `pythonOnlyFloatRequests`, `questionsInPythonOrder`, `pruneTokenizer` (mirrors `prune_tokenizer()` in `make_py_fixtures.py`), `vocabDigest`, `isV01Tokenizer`; types `PackFixture`, `TorchFixture`, `RequestFixture` | | `packages/runtime/test/model/*.test.ts` | 6 model test files (MODEL) | see Tests | | `packages/runtime/test/fixtures/model/` | parity fixtures + their generators | see Fixtures | @@ -50,12 +56,12 @@ | `packages/runtime/test/browser/model-webgpu.spec.ts` | model host on SwiftShader WebGPU | adapter without `shader-f16` | | `packages/runtime/test/browser/ui-devtools.spec.ts` | devtools overlay in a real browser + screenshots | writes `ui/screenshots/*.png` | | `packages/runtime/test/browser/ui/playwright.config.ts` | UI specs config | `testMatch /ui-.*\.spec\.ts$/`, viewport 1280x800, DPR 2 | -| `packages/runtime/test/browser/ui/{mock-runtime,scenario,session,page}.ts` | UI fixtures, **also imported by unit tests** | `mock-runtime.ts`: `MockRuntime` (scripted `Runtime`, not the runtime; `situationBudget()` returns `2400` since batch 4; a public `holdWrites = false` field that the `adapters-*` tests set to `true` to exercise hold paths), `MockClock`, `choice(probs)`, `makeDecision`, `makeAction`; `scenario.ts`: `loadScenario(rt, opts)`, `ScenarioOptions`; `session.ts`: `runStoreSession(opts)` (real `createRuntime` under virtual time, `mode: "guard"` explicitly), `Session`, `SessionOptions`, `VirtualClock`, `realTurn`, `READY` (a `ModelStatus`), `SessionDecider` (rule-based test decider; its `judge()` has a `delivery` case since batch 4); `page.ts`: `window.__gc` | +| `packages/runtime/test/browser/ui/{mock-runtime,scenario,session,page}.ts` | UI fixtures, **also imported by unit tests** | `mock-runtime.ts`: `MockRuntime` (scripted `Runtime`, not the runtime; `situationBudget()` returns `2400` since batch 4; a public `holdWrites = false` field that the `adapters-*` tests set to `true` to exercise hold paths), `MockClock`, `choice(probs)`, `makeDecision`, `makeAction`; `scenario.ts`: `loadScenario(rt, opts)`, `ScenarioOptions`; `session.ts`: `runStoreSession(opts)` (real `createRuntime` under virtual time, `mode: "guard"` explicitly), `Session`, `SessionOptions` (`onRuntime?(rt)` since 29b7f28, called right after `createRuntime`; `situation-purity.test.ts` uses it to poll like the overlay), `VirtualClock`, `realTurn`, `READY` (a `ModelStatus`), `SessionDecider` (rule-based test decider; its `judge()` has a `delivery` case since batch 4); `page.ts`: `window.__gc` | | `packages/runtime/test/browser/ui/screenshots/` | 18 committed PNGs | `{pill,overlay,interventions,evidence,evidence-answers,detections,activity,now,loading}-{light,dark}.png` | | `packages/runtime/test/browser/.gitignore` | ignores `.build/` | build output of `build.mjs` | | `packages/runtime/test/smoke/smoke.sh` | npm-pack smoke test | run from `packages/runtime` | -| `packages/runtime/STATUS.md` | CORE status + headless recipe + example situations | last measured (VM, with a model dir): 41 files / 346 tests passing; written before `default-mode.test.ts` (+1 file, +4 tests) | -| `packages/runtime-model/MODEL_CARD.md` | only file of the planned `@genclass/runtime-model` package | no `package.json` yet, so not a workspace. Status line now describes round 1 (situation-v1) R17; a v2 model is not trained yet | +| `packages/runtime/STATUS.md` | CORE status + headless recipe + example situations | "State" (VM, with a model dir): 42 files / 348 tests passing; it predates `default-mode`, `situation-purity`, `observe-delivery`, `redaction-v2` and `install/cli` (now 46 files / 393 tests) | +| `packages/runtime-model/MODEL_CARD.md` | only file of the planned `@genclass/runtime-model` package | no `package.json` yet, so not a workspace. Status line describes round 1 (situation-v1) R17 and says the next rounds retrain on v2 data; it does not mention `r17-v2a` (trained on origin/runtime's side, not merged here) | | `scripts/vm.sh` | VM helper (Mehar's machine; needs his hosts file and key) | `sync`, `run`, `exec`, `get` | | `sim/package.json`, `demos/package.json` | consumers of the runtime | `"@genclass/runtime": "*"`; scripts listed under "How `sim`, `demos` and `realapps` consume the runtime" | | `realapps/package.json` | `@genclass/realapps` (private, not a workspace) | scripts `build:runtime` (`cd ../packages/runtime && npx tsup`), `build` (`node build.mjs`), `gen`; pins `@playwright/test`/`playwright` `1.63.0`. See [../realapps.md](../realapps.md) | @@ -75,8 +81,13 @@ | package build vs model-entries build | `build.mjs` -> `buildLibrary`: uses the real `npx tsup` output (`mode: "package"`) when every tsup entry file exists and `dist/index.js` mentions `createModelHost`; otherwise builds only `src/model/index.ts` + `src/model/worker.ts` into `.build/dist` (`mode: "model-entries"`) | | worker URL pattern | the literal `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` in `src/model/host.ts` -> `defaultWorkerFactory` that app bundlers key on (its sibling `defaultOrtLoader` holds the two literal calls `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`); `build.mjs` -> `WORKER_URL_RE` asserts it survives both builds | | `situation-v1` | annotated git tag on 1a77558 ("Frozen runtime situation format for model training"); round-1 SIM data and the R17/R32 round-1 models come from it. Superseded | -| `situation-v2` | annotated git tag on 6e5e86e ("Frozen runtime situation format v2", runtime batch 5). **The current frozen training format** (`HANDOFF.md`): SIM and REAL are generating v2 data from it; any change under `src/situation/*` means a new tag and regenerated data | +| `situation-v2` | annotated git tag on 6e5e86e ("Frozen runtime situation format v2", runtime batch 5). **The current frozen training format** (`HANDOFF.md`): SIM and REAL are generating v2 data from it; any change under `src/situation/*` means a new tag and regenerated data. origin/runtime has since added tag `situation-v2.1` on 5bc40c9 ("situation-v2 + no-baseline stall fact (additive)"), not merged into `mvp-v2-merge` | | `v0.1.0-alpha.0` | annotated git tag on 654d822 ("@genclass/runtime 0.1.0-alpha.0 (npm)"); a GitHub pre-release per `HANDOFF.md` | +| `v0.1.0-alpha.1` | local annotated tag on 806a296 (not pushed): the commit published as `@genclass/runtime@0.1.0-alpha.1`. Everything merged after it (install features, the observe/redaction fixes) is unreleased | +| one-command install | f3a9dd1 (Mehar): `npx @genclass/runtime init` / `remove` (CLI in `bin/lib/`), `import "@genclass/runtime/auto"` (+ `/auto/observe`, `/auto/guard`, `/auto/heal`), the script tag (`dist/genclass.global.min.js`, `window.GenClass`, config from data attributes) and the CDN worker (`dist/cdn/*`, started from a Blob URL so it works cross-origin). Not in any published version yet | +| main / global / CDN build | the 4 tsup configs: main ESM `dist/**` (what `exports` serves to bundlers), global IIFE `dist/genclass.global{,.min}.js` (script tag; never contains onnxruntime-web), CDN `dist/cdn/*` (module worker + onnxruntime-web, loaded on demand by the global build) | +| situation purity | `runtime.situation()` must have no side effects (CONTRACT §13): no op ids consumed, no events, decisions, writes, timers or provider calls. Asserted for every `TriggerKind` by `test/situation-purity.test.ts` (29b7f28), because the devtools "Now" view and the sim / realapps probes call it | +| background delivery decision | in `observe` mode (and whenever a delivery cannot be held) the delivery reaches the app synchronously and untouched; the body analysis and the `delivery` decision still run in the background, never act, and are recorded and reported (054da38, `test/observe-delivery.test.ts`) | | `delivery` trigger | situation-v2 (batch 4): the runtime decides at the network boundary (a response, WebSocket/EventSource message or XHR completion) instead of holding store writes; a `discard` drops only the response's stale field writes (`ActionRecord.dropped`). Tests: `delivery.test.ts`, `content.test.ts`, `smoke.test.ts`, `situation.test.ts` | | `policy.holdWrites` | `PolicyOptions.holdWrites?` in `src/types.ts`, default off: store writes apply at once and a background `discard` becomes a late revert. `true` restores pre-v2 held writes; tests about held writes must opt in | | default mode vs harness mode | product default `observe` (`src/runtime.ts` -> `o.mode ?? "observe"`, f3636b2); `test/helpers.ts` -> `setup()` defaults to `"guard"` so CORE tests keep exercising interventions | @@ -117,6 +128,10 @@ Per-file fakes outside `test/helpers.ts` (copy these when testing the same area) | `FakeWS` / `FakeES` (`EventTarget` subclasses) + `board(s)`; `makeXHR(ref, handler)` | `test/delivery.test.ts` | WebSocket and EventSource channels for message delivery decisions; an `XMLHttpRequest` for XHR delivery holds | | `PassiveDecider` (always the passive action with an alarming diagnosis, after `latency` virtual ms) | `test/no-reorder.test.ts` | a model that never acts, for "never worse" checks | | `counterStore()` (minimal redux-like store) | `test/default-mode.test.ts` | an adapter store for `rt.adapter(...).propose` | +| `counters(s)` (op ids, ops, in-flight, last event seq, decisions, ...) + its own `FakeWS`; `runStoreSession({ onRuntime })` | `test/situation-purity.test.ts` | snapshots compared before and after `rt.situation(...)` for every trigger kind | +| `streamingFetch(ref, route)` (a fetch on the `FakeClock` whose body can arrive after the headers: `latency`, `bodyDelay`) | `test/observe-delivery.test.ts` | the fake server's fetch, for bodies slower than the headers | +| `f2Facts({ store, field, redact? })` (an autosave that echoes text while the user types) | `test/redaction-v2.test.ts` | an app producing the F2 "would replace text the user typed" fact | +| `project(files)` / `snapshot(dir)` / `cli(dir, ...args)` / `roundTrip(dir, ...)` (fixture projects under `os.tmpdir()`, removed in `afterAll`; the CLI run with `process.execPath`, `--cwd`, `NO_COLOR=1`) | `test/install/cli.test.ts` | a real project and the npm install (`--no-install`) | Fixture record types (`test/model/helpers.ts`): @@ -131,24 +146,30 @@ interface TorchFixture { id: string; logits: Record<string, number[]>; probs: Re ### Build (`npm run build` -> `tsup`) -1. tsup reads `packages/runtime/tsup.config.ts`; `clean: true` empties `dist/` first. -2. Bundles the 6 entries as ESM (`target es2022`, `platform browser`, `splitting`, `treeshake`, `sourcemap`), leaving `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand` external. `onnxruntime-web/wasm` is not listed, but tsup also externalises every `dependencies`/`peerDependencies` entry and its subpaths (`^dep($|/)`), so it stays external too; `build.mjs` asserts `import("onnxruntime-web/wasm")` and `import("onnxruntime-web/webgpu")` stay dynamic imports in `dist/worker.js` or its `chunk-*.js`. -3. Emits `.d.ts` for the 5 dts entries (not the worker). +1. tsup loads `packages/runtime/tsup.config.ts`. At load time a top-level loop deletes every `dist/genclass.global*` file (the global builds use `clean: false`), and `package.json` `version` is read for `__GENCLASS_VERSION__`. +2. tsup runs the 4 configs in parallel, all writing under `dist/`: + - **Main** (ESM): `clean: ["!cdn/**", "!genclass.global*"]` (empties `dist/` except the other configs' outputs), bundles the 10 entries below (`target es2022`, `platform browser`, `splitting`, `treeshake`, `sourcemap`), leaving `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand` external. `onnxruntime-web/wasm` is not listed, but tsup also externalises every `dependencies`/`peerDependencies` entry and its subpaths (`^dep($|/)`), so it stays external too; `build.mjs` asserts `import("onnxruntime-web/wasm")` and `import("onnxruntime-web/webgpu")` stay dynamic imports in `dist/worker.js` or its `chunk-*.js`. Emits `.d.ts` for the 9 dts entries (not the worker), plus a shared `types-<hash>.d.ts`. + - **Global** x2 (IIFE): entry `{ genclass: "src/cdn/global.ts" }`, `target es2020`, `outExtension` `.global.js` (unminified, no map) and `.global.min.js` (minified, with map), `define: { __GENCLASS_VERSION__ }`. Plugin `genclass-ort-external` marks every `onnxruntime-web(/...)` import external, because tsup ignores `external` for IIFE; the global build passes its own `ortLoader`, so that import is never reached. + - **CDN** (ESM, `outDir: "dist/cdn"`, `clean: true`, minified, no maps, no dts): entries `worker` (`src/cdn/worker.ts`), `ort-webgpu`, `ort-wasm` (`src/cdn/ort-*.ts`), `noExternal: [/^onnxruntime-web/]`. Plugin `genclass-cdn-ort` redirects the model worker's `import("onnxruntime-web/webgpu" | "/wasm")` to `src/cdn/ort-*.ts` (which import the real package and prepare it for a cross-origin script) unless the importer is itself under `src/cdn/`. | tsup entry key | source | output | types | `exports` subpath | |---|---|---|---|---| | `index` | `src/index.ts` | `dist/index.js` | `dist/index.d.ts` | `.` (also `main`, `module`, `types`) | +| `auto` | `src/auto.ts` | `dist/auto.js` | `.d.ts` | `./auto` | +| `auto/observe`, `auto/guard`, `auto/heal` | `src/cdn/auto-{observe,guard,heal}.ts` | `dist/auto/{observe,guard,heal}.js` | `.d.ts` | `./auto/observe`, `./auto/guard`, `./auto/heal` | | `adapters/react` | `src/adapters/react.ts` | `dist/adapters/react.js` | `dist/adapters/react.d.ts` | `./react` | | `adapters/redux` | `src/adapters/redux.ts` | `dist/adapters/redux.js` | `.d.ts` | `./redux` | | `adapters/zustand` | `src/adapters/zustand.ts` | `dist/adapters/zustand.js` | `.d.ts` | `./zustand` | | `devtools/index` | `src/devtools/index.ts` | `dist/devtools/index.js` | `.d.ts` | `./devtools` | | `worker` | `src/model/worker.ts` | `dist/worker.js` | none | `./worker` (`import` only) | +| `genclass` (global, x2) | `src/cdn/global.ts` | `dist/genclass.global.js`, `dist/genclass.global.min.js` (+ `.map`) | none | none; `unpkg` / `jsdelivr` fields point at the `.min.js` | +| `worker`, `ort-webgpu`, `ort-wasm` (CDN) | `src/cdn/worker.ts`, `src/cdn/ort-{webgpu,wasm}.ts` | `dist/cdn/{worker,ort-webgpu,ort-wasm}.js` + `chunk-*.js` | none | none (loaded by URL from the global build) | -Plus shared `chunk-*.js` files (code splitting) and `.map` files. `exports` also exposes `./package.json`. Only `import` conditions exist: the package is ESM-only (no `require`). The tarball contains `files: ["dist", "bin", "README.md", "LICENSE"]` (+ `package.json`). `bin.genclass-runtime` = `./bin/genclass-runtime.mjs` (plain Node >= 20 ESM, no dependencies, not built). +Plus shared `chunk-*.js` files (code splitting) and `.map` files. `exports` also exposes `./package.json`. Only `import` conditions exist: the package is ESM-only (no `require`); the script tag uses the IIFE file directly. The tarball contains `files: ["dist", "bin", "README.md", "LICENSE"]` (+ `package.json`): 52 files, 1.1 MB packed / 4.2 MB unpacked on `mvp-v2-merge` (`npm pack --dry-run`, 2026-10-08), against 26 files / 486.8 kB for the published `0.1.0-alpha.1`. The largest additions are `genclass.global.min.js` (254.5 kB), `genclass.global.js` (454.9 kB), `genclass.global.min.js.map` (1.2 MB) and `dist/cdn/*` (~232 kB). `bin.genclass-runtime` = `./bin/genclass-runtime.mjs` (plain Node >= 20 ESM with its `bin/lib/*.mjs` helpers, no dependencies, not built). ### Unit tests (`npm test` -> `vitest run`) -1. vitest collects `test/**/*.test.ts` minus `test/browser/**` (42 tracked files; plus any untracked `*.test.ts` in your working copy). It transpiles TS without type-checking. +1. vitest collects `test/**/*.test.ts` minus `test/browser/**` (46 tracked files, including `test/install/cli.test.ts`; plus any untracked `*.test.ts` in your working copy). It transpiles TS without type-checking. 2. Each file runs in `node` unless its first line is `// @vitest-environment happy-dom` (`adapters-react`, `devtools`, `devtools-runtime`, `dom`, `review-dom`). 3. A typical test calls `setup()`: builds `FakeClock` + `FakeServer` + `makeGlobal(server)` + `ScriptedDecider`, then `createRuntime({ clock, global: g, decider, mode: "guard", report: "silent", observe: { fetch: true, xhr/user/errors/nav/storage/perf/websocket/timers: false }, ...rest })` (`eventsource` unlisted, so default on) and casts to `RuntimeImpl` (so tests can reach `rt.hub`, `rt.ops`, `rt.ctx`, `rt.cache`, `rt.miner`, `rt.internals`). 4. The test drives the app through `rt.user(...)`, `rt.op(...)`, atoms and `fetch`, then advances virtual time: `await clock.advance(ms)` runs due timers in order, each followed by `flush()`; `flush()` drains microtasks with 4 real `setImmediate` turns (`drain`), runs `afterTask` hooks, and repeats up to 50 times. @@ -194,12 +215,19 @@ Facts STATUS records for this mode: `global.fetch` (and WebSocket, EventSource, 4. `check.mjs` serves `dist/` on port `4191` (plain `node:http`), opens it in Chromium (`chromium.launch()` from the app's `@playwright/test`), waits for `window.__smoke.ok`, `p.fill("#q", "rea")`, waits for `#out` to read `rea-1`, prints one JSON line `{ info: { status, events, devtools }, errs }`, and exits 1 unless there are no page errors / console errors, `genclass-devtools` exists, and `rt.history().length >= 3` (`status` is printed, not asserted). Then prints `SMOKE OK: <tgz>`. 5. The script is unchanged since 59c213f. `GenClass.init({ model: false, report: "console" })` now starts in `observe` (default since f3636b2); nothing it asserts depends on the mode (unverified: not re-run on mvp-v2). 6. Leftovers: the `.tgz` stays in `packages/runtime/` and the `mktemp -d` app is not deleted. The script never runs `playwright install`: Chromium for Playwright `1.63.0` must already be in the Playwright browser cache on the machine (how the VM got it is not recorded in the repo). +7. It imports only `@genclass/runtime` and `/devtools`, so it does not exercise `/auto`, the script tag or `init`; `test/install/` covers those. + +### Install tests (`test/install/`, f3a9dd1) + +1. **`cli.test.ts`** (vitest, node, 20 tests; runs in `npm test` and in CI): `describe("init / remove on fixture projects")` builds fixture projects in `os.tmpdir()` (`gc-init-*`, removed in `afterAll`) and runs `node bin/genclass-runtime.mjs init --yes --no-install ... --cwd <dir>`, then `init` again (no change), then `remove --yes` (byte-for-byte back); `describe("edit helpers")` tests `bin/lib/edit.mjs`; `describe("page config")` tests `src/cdn/config.ts` and `src/cdn/global.ts` -> `assetBase`. No network, no package manager, no browser. +2. **VM harness** (ask first; Mehar ran it on the `train` VM): `bash test/install/run-all.sh [framework ...]` from `packages/runtime` = `npm run build` -> `npm pack` into `$INSTALL_OUT` (default `/data/install`) -> `npx vitest run test/install` -> `node test/install/cdn-check.mjs` (script tag and `/auto` in headless Chromium, page and "CDN" on different origins, `GENCLASS_MODEL_DIR` default `~/gcl/model/.cache-model`) -> `bash test/install/scaffold.sh` (fresh projects from each framework's generator under `$SCAFFOLDS`, default `/data/install/scaffolds`; installs pnpm 10 there) -> `TGZ=... node test/install/frameworks.mjs` (init, re-init, prod build + Chromium, dev server + Chromium, remove, sha256 compare). `server.mjs` is their static server (prefix mounts, optional CORS and COOP/COEP, request log); the checks use it to serve the jsDelivr defaults (model files, onnxruntime-web wasm) from local copies, since `@genclass/runtime-model` is not published. +3. Results: `test/install/RESULTS.md` (2026-10-08, VM, Node 22.22): 15/15 projects (Vite React/Vue/Svelte, pnpm, Next.js App/Pages incl. `--strategy layout|pages`, CRA, SvelteKit, Astro, Nuxt, React Router, Angular, plain HTML), CLI 20/20, CDN 26/26. The tarball was packed from that tree while `version` was still `0.1.0-alpha.0`; the harness has not run on `mvp-v2-merge`. ### VM workflow (`scripts/vm.sh`) 1. Reads the `train` host IP from `~/.jev-local/azure_hosts` (line `train <ip>`), key `~/.ssh/jev_azure`, user `azureuser`, ssh options `StrictHostKeyChecking=accept-new`, `ConnectTimeout=20`, `ServerAliveInterval=30`, `ServerAliveCountMax=6`. Exits 2 if the host line is missing, the slot name has characters outside `[a-zA-Z0-9_-]`, or the subcommand is unknown. Every step is wrapped in GNU `timeout` (see Configuration). The sibling `scripts/azvm.sh HOST ...` uses the same hosts file and key for the other jev VMs (out of scope here). -2. `sync SLOT`: `ssh mkdir -p gcl/SLOT`, then `rsync -az --delete` the repo to `~/gcl/SLOT/`, excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out/`, `.cache-model/`. Excluded paths on the VM are kept (rsync does not delete excluded files without `--delete-excluded`), so `node_modules`, `dist` and model caches survive syncs. -3. `run SLOT 'cmd'` = sync + remote (the script is unchanged since 654d822; it only works from a machine holding Mehar's hosts file and key); `exec SLOT 'cmd'` = remote only; remote runs `export PATH=$HOME/node/bin:$PATH; cd ~/gcl/SLOT && cmd` (Node 22 per the header and CONTRACT §0 rule 6). +2. `sync SLOT`: `ssh mkdir -p gcl/SLOT`, then `rsync -az --delete` the repo to `~/gcl/SLOT/`, excluding `node_modules`, `.git`, `dist/`, `.vite`, `/data/`, `test-results/`, `playwright-report/`, `__pycache__`, `.DS_Store`, `/models/`, `/runs/`, `/extension/`, `/sim/out` (without the trailing slash since eff18cb, so a `sim/out` symlink on the VM is kept too), `.cache-model/`. Excluded paths on the VM are kept (rsync does not delete excluded files without `--delete-excluded`), so `node_modules`, `dist` and model caches survive syncs. +3. `run SLOT 'cmd'` = sync + remote (the script changed since 654d822 only in that `/sim/out` exclude; it only works from a machine holding Mehar's hosts file and key); `exec SLOT 'cmd'` = remote only; remote runs `export PATH=$HOME/node/bin:$PATH; cd ~/gcl/SLOT && cmd` (Node 22 per the header and CONTRACT §0 rule 6). 4. `get SLOT REMOTE LOCAL`: `scp -r` from `~/gcl/SLOT/REMOTE`. ### How `sim`, `demos` and `realapps` consume the runtime @@ -247,8 +275,9 @@ cd packages/runtime NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts # CI "Unit tests" NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # CI "Perf budgets" npx vitest run test/atoms.test.ts -t "late discard" # one file / one test +npx vitest run test/install/cli.test.ts # init/remove CLI on fixture projects (OS temp dir, no network) npx vitest run test/situation.test.ts test/delivery.test.ts test/content.test.ts test/budget.test.ts # prints the STATUS example situations (console.log) -npm pack --dry-run # list tarball contents (files: dist, bin, README.md, LICENSE) +npm pack --dry-run # list tarball contents (files: dist, bin, README.md, LICENSE); 52 files on mvp-v2-merge cd ../../sim && npx tsc -p tsconfig.json --noEmit && SIM_RUNTIME=real npx vitest run # sim tests on the real runtime (needs the runtime build); not the generator ``` @@ -261,12 +290,14 @@ scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/ scripts/vm.sh exec model 'cd packages/runtime && GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/browser/playwright.config.ts model.spec.ts -g "inline fallback"' # one spec / one test scripts/vm.sh exec core 'cd packages/runtime && npx playwright test --config test/browser/ui/playwright.config.ts' scripts/vm.sh exec core 'cd packages/runtime && bash test/smoke/smoke.sh' +scripts/vm.sh exec core 'cd packages/runtime && bash test/install/run-all.sh' # install harness (Playwright, generators, npm registry; outputs in /data/install); add framework names to limit it +scripts/vm.sh exec core 'cd packages/runtime && npx tsup && node test/install/cdn-check.mjs' # script tag + /auto only # one-time per machine (not in any repo script; unverified that the VM needed it): npx playwright install chromium # fetch the v0.1 model for the model tests (command from packages/runtime/src/model/README.md; default --variant all) scripts/vm.sh exec model 'node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/' ``` -The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runtime/STATUS.md` and `packages/runtime/src/model/README.md`; which of them exists on the VM is unverified. Both hold the v0.1 GenClass model (the parity fixtures' model), not a runtime model: no situation-v2 runtime model exists yet. +The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runtime/STATUS.md` and `packages/runtime/src/model/README.md`; which of them exists on the VM is unverified. Both hold the v0.1 GenClass model (the parity fixtures' model), not a runtime model: no situation-v2 runtime model is published or in this branch. ### Where to run things @@ -274,9 +305,10 @@ The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runti - **Lead policy for agents (2026-10-08):** on any other machine, run these locally; they are light and were verified (next section): - `npm install` / `npm ci` at the repo root; - typecheck (`tsc`) and build (`tsup`) of `packages/runtime`; - - the runtime unit tests (vitest, browser specs excluded), and the sim's unit tests with `SIM_RUNTIME=real`. + - the runtime unit tests (vitest, browser specs excluded; this includes `test/install/cli.test.ts`), and the sim's unit tests with `SIM_RUNTIME=real`. - **Ask the user first** before running any of: - Playwright (`npm run test:browser`, the UI spec, `test/smoke/smoke.sh`, which also installs from the npm registry); + - the install harness (`test/install/run-all.sh`, `cdn-check.mjs`, `scaffold.sh`, `frameworks.mjs`: Playwright, framework generators, npm registry; `test/install/cli.test.ts` alone is light and runs with the unit tests); - the sim generator (`sim` `gen`, `sim/scripts/*`); - training (`training/*.sh`, Python training or tests); - realapps runs (`realapps` `build`/`gen`, its harness scripts); @@ -287,24 +319,25 @@ The two `GENCLASS_MODEL_DIR` paths above are the ones written in `packages/runti ### Verified locally (2026-10-08) -Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the lead (the per-file vitest counts in [Tests](#tests) were re-collected for this doc): +Run on `mvp-v2-merge` at f107013 (worktree, existing `node_modules`) on a macOS machine (16 GB RAM, Node v25.6.0), by the lead; the per-file counts in [Tests](#tests) were collected in the same pass with vitest's JSON reporter: | step | command (directory) | result | |---|---|---| -| install | `npm ci` (fresh clone, repo root) | OK from the committed lockfile; EBADENGINE warning from vitest on Node 25 (below) | -| typecheck | `npx tsc -p tsconfig.json --noEmit` (`packages/runtime`) | clean | -| build | `npx tsup` (`packages/runtime`) | OK, 6 entries, `.d.ts` for all but `worker` | -| unit tests | `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` (`packages/runtime`) | Test Files 40 passed \| 1 skipped (41); Tests 332 passed \| 14 skipped (346) | -| perf budgets | `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts` | 4 passed. In a full parallel run it once failed at 5.5 ms against its 2 ms bound (contention), hence CI's separate step with `--retry=2` | -| sim | `npx tsc --noEmit`; `SIM_RUNTIME=real npx vitest run` (`sim`) | clean; 19 passed (5 files) | -| CI steps | the five steps of `ci.yml`, in a fresh clone | pass | - -- **The 14 skipped tests** are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`), which did not exist on that machine: `test/model/packer.test.ts` all 10 (the one fully skipped file), `test/model/engine.test.ts` 3 of 4, `test/model/calibrate.test.ts` 1 of 8. With a model directory all 350 should pass (STATUS: 346 on the VM, before `default-mode.test.ts`). Getting one means a model download: ask the user first. -- **On `origin/runtime` (74f17c0) itself**, where the default mode is still `guard`: 331 passed + 1 flaky perf failure + 14 skipped = 346. +| typecheck | `npm run typecheck -w @genclass/runtime` (repo root) | clean | +| build | `npm run build -w @genclass/runtime` (repo root) | OK: 2 ESM + 2 IIFE "Build success" lines, then DTS; `dist/` holds `index`, `auto`, `auto/{observe,guard,heal}`, adapters, devtools, `worker`, `genclass.global{,.min}.js`, `cdn/{worker,ort-webgpu,ort-wasm}.js` | +| unit tests | `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` (`packages/runtime`) | Test Files 44 passed \| 1 skipped (45); Tests 375 passed \| 14 skipped (389) | +| perf budgets | `NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2` | 4 passed. In a full parallel run on b435acb it once failed at 5.5 ms against its 2 ms bound (contention), hence CI's separate step with `--retry=2` | +| pack | `npm pack --dry-run` (`packages/runtime`) | 52 files, 1.1 MB packed, 4.2 MB unpacked | + +Earlier pass (b435acb, fresh clone): `npm ci` OK from the committed lockfile (EBADENGINE warning, below); all five `ci.yml` steps passed; `sim` `npx tsc --noEmit` clean and `SIM_RUNTIME=real npx vitest run` 19 passed (5 files). Those were not re-run on `mvp-v2-merge` (the lockfile was re-synced in 10e5c3b; `npm ci` from it was not re-checked in a fresh clone). + +- **The 14 skipped tests** are model-parity tests that need model files in `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`), which did not exist on that machine: `test/model/packer.test.ts` all 10 (the one fully skipped file), `test/model/engine.test.ts` 3 of 4, `test/model/calibrate.test.ts` 1 of 8. With a model directory all 393 should pass (STATUS: 348 on the VM, before the newer files). Getting one means a model download: ask the user first. +- **Earlier counts**: `mvp-v2` at b435acb 336 passed + 14 skipped = 350 (42 files); `origin/runtime` 74f17c0 (default `guard`) 331 passed + 1 flaky perf failure + 14 skipped = 346. - **EBADENGINE warning.** `vitest@5.0.3` declares `engines.node` `^22.12.0 || ^24.0.0 || >=26.0.0`. Node 25 is outside that range, so npm warns, but the tests run. Node 22.x from 22.12, 24.x and 26+ are inside it; 23.x and 25.x are not. CI uses `node-version: 22` (latest 22.x). - **Install side effects are gone**: the lockfile is committed and the CLI is committed as 100755, so a root `npm install` / `npm ci` leaves `git status` clean (unless dependencies changed). - **Untracked test files.** Working copies used by parallel agents may contain untracked `test/zz-*.test.ts` files (`zz-review-*`, `zz-verify-*`; one appeared mid-run during this doc's check and lifted the count to 351); vitest collects them (`include` is `test/**/*.test.ts`) and some may fail. They are not part of the branch: check `git status` before trusting a red run, and count only tracked files. -- **Not run:** Playwright (main and UI configs), `test/smoke/smoke.sh`, realapps, the demos' eval, Python tests, training, model downloads, anything on Azure. +- **`test/install/cli.test.ts` writes to the OS temp dir** (`gc-init-*` directories) and deletes them in `afterAll`; nothing is left in the repo. +- **Not run:** Playwright (main and UI configs), `test/smoke/smoke.sh`, the install harness (`run-all.sh`, `cdn-check.mjs`, `scaffold.sh`, `frameworks.mjs`), realapps, the demos' eval, Python tests, training, model downloads, anything on Azure. ## Configuration and constants @@ -318,9 +351,11 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the | `types` | tsc | `[]` | `packages/runtime/tsconfig.json` | no `@types/node` in `src/`: src must not use Node APIs | | `include` | tsc | `["src"]` | `packages/runtime/tsconfig.json` | tests are not type-checked | | `jsx` | tsc | `react-jsx` | `packages/runtime/tsconfig.json` | | -| tsup `format` / `target` / `platform` | build | `["esm"]` / `es2022` / `browser` | `tsup.config.ts` | | -| tsup `splitting` / `treeshake` / `sourcemap` / `clean` | build | `true` | `tsup.config.ts` | `clean` wipes `dist/` at build start | -| tsup `external` | build | `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand` | `tsup.config.ts` | | +| tsup `format` / `target` / `platform` | build | main: `["esm"]` / `es2022` / `browser`; global: `["iife"]` / `es2020` / `browser`; CDN: `["esm"]` / `es2022` / `browser` | `tsup.config.ts` | | +| tsup `splitting` / `treeshake` / `sourcemap` / `clean` | build | main: `true` / `true` / `true` / `["!cdn/**", "!genclass.global*"]`; global: no splitting, `treeshake`, map only for `.min.js`, `clean: false`; CDN: `splitting`, `minify`, no map, `clean: true` (of `dist/cdn`) | `tsup.config.ts` | the main `clean` wipes `dist/` except the other configs' outputs; the global files are deleted by the config's top-level loop | +| tsup `external` | build | main: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`; global: plugin `genclass-ort-external` (all `onnxruntime-web(/...)`); CDN: `noExternal: [/^onnxruntime-web/]` | `tsup.config.ts` | only the CDN build contains onnxruntime-web | +| `__GENCLASS_VERSION__` | build define | `JSON.stringify(pkg.version)` | `tsup.config.ts` -> `globalBuild` | version baked into the script-tag build (today `0.1.0-alpha.1`, so bump `version` before building a release) | +| `unpkg` / `jsdelivr` | pkg | `./dist/genclass.global.min.js` | `packages/runtime/package.json` | what `https://cdn.jsdelivr.net/npm/@genclass/runtime` serves | | vitest `include` / `exclude` | test | `test/**/*.test.ts` / `test/browser/**` | `vitest.config.ts` | | | vitest `environment` / `testTimeout` | test | `node` / `20000` ms | `vitest.config.ts` | per-file override for happy-dom; model tests set `600_000` / `900_000` | | Playwright `timeout` / `expect.timeout` | test | `600_000` / `30_000` ms | `test/browser/playwright.config.ts` | | @@ -341,7 +376,7 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the | other devDeps | devDep | `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `tsup ^8.5.1`, `vitest ^5.0.3`, `typescript ~5.9.3`, `react`/`react-dom ^19.3.0`, `@types/react`/`@types/react-dom ^19.0.0`, `redux ^5.0.1`, `zustand ^5.0.15` | `packages/runtime/package.json` | | | `dependencies` | dep | `onnxruntime-web ^1.30.0` (only runtime dependency; CONTRACT §0 rule 6 forbids others without the lead) | `packages/runtime/package.json` | | | `peerDependencies` | peer | `react >=18`, `redux >=4`, `zustand >=4`, all optional | `packages/runtime/package.json` | | -| `sideEffects` | pkg | `false` | `packages/runtime/package.json` | bundlers may drop unused imports | +| `sideEffects` | pkg | `./dist/auto.js`, `./dist/auto/*.js`, `./dist/genclass.global.js`, `./dist/genclass.global.min.js`, `./dist/cdn/*.js`, `./src/model/worker.ts` (was `false` until f3a9dd1) | `packages/runtime/package.json` | bundlers keep `import "@genclass/runtime/auto"` (a side-effect-only import); every other module may still be dropped when unused | | `engines.node` | pkg | `>=20` (root and runtime) | `package.json`s | VM and CI run Node 22 | | CI triggers | ci | push to `main`, `runtime`, `mvp`, `mvp-v2`; `pull_request` (any branch); `workflow_dispatch` | `.github/workflows/ci.yml` -> `on` | | | CI `permissions` / `concurrency` | ci | `contents: read`; group `ci-${{ github.ref }}`, `cancel-in-progress: true` | `.github/workflows/ci.yml` | a new push cancels the running job of the same ref | @@ -372,7 +407,9 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the - **`dist/` must exist before anything consumes the package.** `sim`, `demos` and demo typechecking resolve `@genclass/runtime` through `exports` -> `dist/`. Root `npm run typecheck` therefore needs `npm run build` first (demos' `typecheck` reads `dist/*.d.ts`; `typecheck:shim` avoids it). The demos typecheck (and `typecheck:shim`) also needs the missing `demos/src/server/data/cities.ts` (see [../demos.md](../demos.md#drift-and-open-issues) Drift 1). It is not in git because the root `.gitignore`'s unanchored `data/` matches `demos/src/server/data/` (`git check-ignore -v` names that line). `src/server/worlds/search.ts`, `src/demos/search/scenario.ts` and `src/demos/search/oracle.ts` import it, so `tsc -p demos/tsconfig.json` and `tsconfig.shim.json` fail with TS2307 "Cannot find module ... cities.ts" (checked 2026-10-08 with `packages/runtime/dist/` built), and so does the root `npm run typecheck`. - **`clean: true` + a failed build = a half-empty `dist/`.** `demos/scripts/vm-eval.sh` refuses to measure after a failed runtime build for this reason (`ALLOW_BROKEN_RUNTIME=1` overrides). - **`npm run test:browser` rebuilds `packages/runtime/dist/`** (its global setup runs `npx tsup`). Do not run it in a slot where another job is reading `dist/`. -- **Keep tsup entries as literal `"src/...ts"` strings.** `build.mjs` -> `fullBuildPossible` finds them with a regex over the config text. +- **Keep tsup entries as literal `"src/...ts"` strings.** `build.mjs` -> `fullBuildPossible` finds them with a regex over the config text (`/"(src\/[^"]+\.tsx?)"/g`; it now also matches the `auto`, `cdn/*` and global entries, and skips the template literal in the `genclass-cdn-ort` plugin). +- **`tsup` is now 4 parallel builds writing into one `dist/`.** Each config must leave the others' outputs alone: the main build's `clean` excludes `cdn/**` and `genclass.global*`, the CDN build cleans only `dist/cdn`, and the global builds rely on the config file's top-level delete loop. When you add an output directory or file name, update those exclusions too, or a parallel `clean` deletes it mid-build. The global and CDN builds must keep onnxruntime-web out of / inside them respectively (`genclass-ort-external`, `noExternal`); a change there changes the script-tag download size. +- **The bundle carries the version.** `__GENCLASS_VERSION__` is read from `packages/runtime/package.json` when tsup starts, so bump `version` before the release build, never after. - **Keep the worker URL pattern and the two `import("onnxruntime-web/webgpu" | "onnxruntime-web/wasm")` literals.** Bundlers (Vite, webpack) recognise them; `build.mjs` fails if either disappears from the output. - **Tests are not type-checked** (`tsconfig.json` `include: ["src"]`; vitest strips types). A test can drift from the public types and still pass; `MockRuntime` (`implements Runtime`) in particular can fall behind the `Runtime` interface without any error (the situation-v1 STATUS said so explicitly; the current STATUS no longer mentions it). - **Unit tests import from `test/browser/ui/`** (`mock-runtime.ts`, `scenario.ts`, `session.ts`). The vitest exclude only stops test discovery there; moving or renaming those files breaks `adapters-*.test.ts`, `devtools*.test.ts`. @@ -380,7 +417,10 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the - **Wall-clock thresholds in `review-perf.test.ts`** (user write < 1 ms, async write < 2 ms, redux dispatch < 1 / < 2 ms, settled point < 16 ms on 5,000-item stores) can fail on a loaded machine: the lead saw one 5.5 ms failure against the 2 ms bound in a full parallel run on 2026-10-08, and it passed alone. CI therefore runs it in its own step with `--retry=2`; run it alone locally too before calling it a regression. STATUS (batch 5, shared VM): keystroke write 0.22 ms, async write 0.14 ms, redux dispatch 0.71 ms (user) / 0.70 ms (async), settled point 0.3 ms (+2.3 ms with an unchanged 5,000-item adapter store). - **The gc test passes silently without `--expose-gc`.** `review-timers.test.ts` "a polling loop does not retain..." logs `[review] skipped: run with NODE_OPTIONS=--expose-gc` and returns. - **Review tests are a contract.** Never edit `test/review-*.test.ts` to make them pass; fix `src/`. -- **Situation wording is frozen at `situation-v2`** (tag on 6e5e86e; `situation-v1` is superseded). `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `content.test.ts` and `delivery.test.ts` assert exact fact sentences (regexes / `toContain`), and `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts` assert fact fragments; `report.test.ts`, `atoms.test.ts`, `fetch.test.ts`, `learn.test.ts`, `devtools-runtime.test.ts` assert report / reason / `changed` / title wording. (`smoke.test.ts` prints a delivery situation but asserts only the decision, `dropped` and `subject.kind`, not wording.) SIM's ≥ 10M-row v2 data set and REAL's real-browser rows are being generated from that tag right now, and `training/curriculum/rt.py` mirrors the renderer (its header names `src/situation/{facts,conflicts,content,evidence,describe,build,serialize,questions}.ts` and `src/state/fields.ts` -> `changeText` / `stringDiff`). The example situations in `packages/runtime/STATUS.md` are copied from the `console.log` output of `budget.test.ts` (compact budgets) and `situation.test.ts`, `delivery.test.ts`, `content.test.ts` (full budget). Any change under `src/situation/*` (or to `changeText` / `stringDiff`) means a new tag and regenerated data: coordinate with Mehar (SIM, REAL, TRAIN) first (`HANDOFF.md` "Rules"). +- **Situation wording is frozen at `situation-v2`** (tag on 6e5e86e; `situation-v1` is superseded; origin/runtime's additive `situation-v2.1` on 5bc40c9 is not merged into this branch). `situation.test.ts`, `budget.test.ts`, `batch3.test.ts`, `content.test.ts` and `delivery.test.ts` assert exact fact sentences (regexes / `toContain`), and `invariants.test.ts`, `review-fetch.test.ts`, `review-hub.test.ts` assert fact fragments; `report.test.ts`, `atoms.test.ts`, `fetch.test.ts`, `learn.test.ts`, `devtools-runtime.test.ts` assert report / reason / `changed` / title wording. (`smoke.test.ts` prints a delivery situation but asserts only the decision, `dropped` and `subject.kind`, not wording.) SIM's ≥ 10M-row v2 data set and REAL's real-browser rows are being generated from that tag right now, and `training/curriculum/rt.py` mirrors the renderer (its header names `src/situation/{facts,conflicts,content,evidence,describe,build,serialize,questions}.ts` and `src/state/fields.ts` -> `changeText` / `stringDiff`). The example situations in `packages/runtime/STATUS.md` are copied from the `console.log` output of `budget.test.ts` (compact budgets) and `situation.test.ts`, `delivery.test.ts`, `content.test.ts` (full budget). Any change under `src/situation/*` (or to `changeText` / `stringDiff`) means a new tag and regenerated data: coordinate with Mehar (SIM, REAL, TRAIN) first (`HANDOFF.md` "Rules"). +- **f107013 changed model-visible text for secret fields.** `src/state/fields.ts` -> `redactedStringDiff` now backs both `changeText` and the F2 fact in `src/situation/content.ts` -> `contentFacts`, and `src/util.ts` -> `isSensitivePath` (behind `defaultRedact`) now also marks numbers, bigints and arrays as secret under a strong secret-named container (`cvv`, `otp`, `pin`, `password`). Text for fields the redactor leaves alone is unchanged (`redaction-v2.test.ts` "keeps the diff-centred preview"), so the `situation-v2` tag was not moved, but rows generated before it may show raw digits or a raw diff where the runtime now prints `[redacted]`, and `training/curriculum/rt.py` (which mirrors `stringDiff`) does not have the redaction rule. Tell Mehar (TRAIN, SIM) before the next data run. +- **Situation building must stay pure.** `test/situation-purity.test.ts` fails if `rt.situation(...)` consumes an op id, records an event or decision, writes, schedules a timer or calls the provider, for any `TriggerKind`. Keep new situation code read-only. +- **Observe mode now records delivery decisions.** Since 054da38 a response, XHR completion or push message in `observe` is delivered synchronously and decided in the background, so `rt.decisions()` in observe also contains `delivery` entries (`policy.test.ts` "observe mode never holds" and `default-mode.test.ts` expect `["delivery", "mutation", "request"]`). A test that counts observe-mode decisions must include them. - **Browser parity fixtures are v0.1-only.** `test/browser/model-helpers.ts` always reads `test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`, so `model.spec.ts` parity assertions only hold when `GENCLASS_MODEL_DIR` is the v0.1 GenClass model. The unit tests switch to an export's own fixtures (`FIXTURES_FROM_MODEL`); the browser specs do not. - **The default Playwright config also runs `ui-devtools.spec.ts`.** Its `chromium` project matches every `*.spec.ts` except `*webgpu.spec.ts`, so `npm run test:browser` also re-runs the UI spec. That run uses Playwright's default viewport and device scale factor (the main config sets neither) and overwrites the committed screenshots. Use the UI config to regenerate screenshots. - **The UI spec needs the demos workspace installed** (fonts come from `@fontsource-variable/*`, dependencies of `demos`, hoisted to `<repo>/node_modules`). Run a root `npm install`, not one scoped to the runtime. @@ -388,6 +428,8 @@ Run on `mvp-v2` at b435acb on a macOS machine (16 GB RAM, Node v25.6.0), by the - **Global singletons in tests.** `report.test.ts`, `batch3.test.ts` and `default-mode.test.ts` use `GenClass.init`; always `GenClass.destroy()` (and delete `globalThis.location` if you set it). happy-dom tests patch `window` globals: `rt.destroy()` in `afterEach`. `review-hub.test.ts` swaps `process` `unhandledRejection` listeners and restores them in `finally`. - **Network-dependent steps:** `smoke.sh` (npm registry), `model.spec.ts` "default ORT wasm path" (jsDelivr; `GENCLASS_OFFLINE=1` skips it), `fetch-model` (GitHub). - **Fixture JSON files are single-line.** `wc -l` prints `0` for `pack_fixtures.json` (955,379 bytes), `py_fixtures.json` (167,629), `requests50.json` (285,309) and `torch_fixtures.json` (255,945): no trailing newline, not empty. Use `wc -c` or a JSON parser. +- **Two workspaces declare the `genclass-runtime` bin** (`packages/runtime` and the alias `packages/genclass-runtime`). In this checkout `node_modules/.bin/genclass-runtime` links to `@genclass/runtime`'s `bin/genclass-runtime.mjs`; both end up running the same file, so the collision is harmless, but run the CLI by path (`node packages/runtime/bin/genclass-runtime.mjs ...`) in scripts. +- **The alias pins the runtime exactly.** `packages/genclass-runtime/package.json` depends on `"@genclass/runtime": "0.1.0-alpha.1"`, and the published `0.1.0-alpha.1` has no `init` / `remove`. Publishing the alias as is would make `npx genclass-runtime init` fail with the alpha.1 CLI's `unknown command init` usage error. Bump both versions together and publish the runtime first. - **No `prepublishOnly` and no `publishConfig`.** `npm publish` packs whatever `dist/` holds; build right before publishing. Scoped packages publish as restricted unless `--access public` is passed (npm behaviour). - **The root lockfile is committed; keep it in sync.** Since b435acb `package-lock.json` is tracked and CI runs `npm ci`, which fails when any workspace `package.json` (root, `packages/*`, `sim`, `demos`) no longer matches the lockfile. After changing a dependency, run `npm install` at the repo root and commit the updated lockfile in the same commit. `realapps/` is not a workspace and has no lockfile of its own. - **Test harness mode is not the product mode.** `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so a test that does not pass `mode` exercises guard, while a real app (and `GenClass.init`, the smoke script, any package built from this branch, including the published `0.1.0-alpha.1`; only the older `0.1.0-alpha.0` defaults to guard) starts in `observe`. To test default behaviour pass `mode: undefined`. New headless harnesses that build their own runtime (like `review-fetch.test.ts` -> `headless()`) must pass `mode` explicitly or they observe only. @@ -440,8 +482,8 @@ Run it locally: `cd packages/runtime && npx vitest run test/<file>.test.ts` ([Wh ### Add a public entry point (new subpath export) -1. Add the entry to `tsup.config.ts` `entry` **and** `dts.entry` (keep the `"src/...ts"` literal form). -2. Add `"./<name>": { "types": "./dist/<name>.d.ts", "import": "./dist/<name>.js" }` to `packages/runtime/package.json` `exports`. +1. Add the entry to the **main** config in `tsup.config.ts`, `entry` **and** `dts.entry` (keep the `"src/...ts"` literal form). The global and CDN configs are for the script tag only; do not add package entries there. +2. Add `"./<name>": { "types": "./dist/<name>.d.ts", "import": "./dist/<name>.js" }` to `packages/runtime/package.json` `exports`. If the entry is imported only for its side effects (like `/auto`), also list its `dist/` file in `sideEffects`, or bundlers drop the import. 3. If demos import it, add a shim to `demos/src/dev/runtime-shim/`, an alias in `demos/vite.config.ts` and a path in `demos/tsconfig.shim.json`. 4. Build locally (`npx tsup`). Then, with the user's OK (ask first), run `bash test/smoke/smoke.sh`, extending `src/main.js` in the script to import the new subpath. @@ -475,10 +517,13 @@ The format is frozen at `situation-v2` and v2 training data is being generated f | 2026-10-08 00:14 / 00:18 UTC | (npm) | `@genclass/runtime@0.0.0-stage` (about one minute before 654d822's commit time) then `0.1.0-alpha.0` (about three minutes after it) published (`npm view @genclass/runtime time`); dist-tag `latest` = `0.1.0-alpha.0`. OPEN_TASKS: "2026-10-08, `genclass` org, owner meharpro", smoke-tested first | | 2026-10-07 21:16 -0400 (01:16 UTC 10-08) | ad24804, ce27efd | fix infinite recursion on `NaN` in state (`test/nan.test.ts`); OPEN_TASKS asks the user to publish `0.1.0-alpha.1` (needs 2FA); published later, see below | | 2026-10-07 22:31 / 23:26 -0400 | fcd1e68, 6e5e86e (tag `situation-v2`) | runtime batch 4 (delivery trigger, no store holds by default) and batch 5 (separability facts); situation format v2 frozen | -| 2026-10-08 00:15 -0400 | f3636b2, b435acb (`mvp-v2`, ours, not pushed) | default mode `observe`; CI workflow, committed root lockfile, CLI mode 100755 | -| 2026-10-08 ~05:33 UTC | 806a296, local tag `v0.1.0-alpha.1` (not pushed) | `@genclass/runtime@0.1.0-alpha.1` published by karanvir1729 under `latest` (26 files, 486.8 kB, shasum 9e3e82bc...); first attempt 403 (no 2FA on the account), then browser-based 2FA approval | +| 2026-10-07 23:30 / 2026-10-08 00:15 -0400 | f3636b2, b435acb (`mvp-v2`, ours, not pushed) | default mode `observe`; CI workflow, committed root lockfile, CLI mode 100755 | +| 2026-10-08 00:50 / 01:12 -0400 | 29b7f28, f3a9dd1 (origin/runtime, Mehar) | situation purity test; one-command install, `/auto`, script tag + CDN builds, `genclass-runtime` alias. f3a9dd1's subject says "0.1.0-alpha.1" and `CHANGELOG.md` lists these under `0.1.0-alpha.1`, but they were never in the published tarball (built from 806a296 on `mvp-v2`) | +| 2026-10-08 ~05:33 UTC (01:33 -0400) | 806a296, local tag `v0.1.0-alpha.1` (not pushed) | `@genclass/runtime@0.1.0-alpha.1` published by karanvir1729 under `latest` (26 files, 486.8 kB, shasum 9e3e82bc...); first attempt 403 (no 2FA on the account), then browser-based 2FA approval | +| 2026-10-08 02:08 / 02:09 -0400 | dabbce2, 10e5c3b (`mvp-v2-merge`) | merge of origin/runtime eff18cb into `mvp-v2`; lockfile re-synced (adds the alias workspace) | +| 2026-10-08 02:47 -0400 | 054da38, f107013 (`mvp-v2-merge`) | observe mode never holds or delays deliveries (`observe-delivery.test.ts`); redaction of F2 diffs and numeric/array secrets (`redaction-v2.test.ts`). Unreleased | -`package.json` `version` is `0.1.0-alpha.1` on `mvp-v2`: release commit 806a296 is now the head of `mvp-v2` (fast-forwarded). What `.publish/` was used for is not recorded (unverified). +`package.json` `version` is still `0.1.0-alpha.1` on `mvp-v2-merge`, although the tree now contains everything after 806a296 (install features, observe/redaction fixes). The next release bumps it (`0.1.0-alpha.2`, or a beta with the model). What `.publish/` was used for is not recorded (unverified). ### Cut a release of `@genclass/runtime` @@ -486,19 +531,21 @@ Full procedure: [RELEASE.md](../../../RELEASE.md) Part A. There is no publish script, no `prepublishOnly` and no `publishConfig`. The recorded procedure (`HANDOFF.md` "Current state": "Each publish needs the user's 2FA, so give them the exact `npm publish <tgz> --access public` command") is: the agent prepares and checks a tarball, the **user** publishes it. -1. Locally: `npm ci`, `npm run typecheck -w @genclass/runtime`, `npm run build -w @genclass/runtime`, the unit tests and perf budgets as in CI (or a green CI run on the pushed branch). With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs and `bash test/smoke/smoke.sh`. -2. Bump `version` in `packages/runtime/package.json` (e.g. `0.1.0-alpha.1`), plus the version strings in READMEs, `OPEN_TASKS.md` and `HANDOFF.md`. Run `npm install` at the root so the lockfile's `packages/runtime` entry picks up the version, and commit both. -3. From `packages/runtime`: `npm run build && npm pack` -> `genclass-runtime-<version>.tgz`; check `npm pack --dry-run` lists only `dist/`, `bin/`, `README.md`, `LICENSE`, `package.json`. +1. Locally: `npm ci`, `npm run typecheck -w @genclass/runtime`, `npm run build -w @genclass/runtime`, the unit tests and perf budgets as in CI (or a green CI run on the pushed branch). With the user's OK (ask first): vitest with `GENCLASS_MODEL_DIR`, the browser specs, `bash test/smoke/smoke.sh` and, for a release that ships the install features, `bash test/install/run-all.sh` (its `RESULTS.md` run used an `0.1.0-alpha.0`-versioned tarball, not the release tree). +2. Bump `version` in `packages/runtime/package.json` (next: `0.1.0-alpha.2`, or `0.1.0-beta.0` with the model), plus `packages/genclass-runtime/package.json` `version` **and** its exact `@genclass/runtime` dependency, the `CHANGELOG.md` heading (move the install entries out of `0.1.0-alpha.1`), and the version strings in READMEs, `OPEN_TASKS.md` and `HANDOFF.md`. Run `npm install` at the root so the lockfile's workspace entries pick up the versions, and commit them together. Bump before building: the script-tag build bakes `version` in as `__GENCLASS_VERSION__`. +3. From `packages/runtime`: `npm run build && npm pack` -> `genclass-runtime-<version>.tgz`; check `npm pack --dry-run` lists only `dist/` (incl. `dist/auto/`, `dist/cdn/`, `genclass.global*`), `bin/` (incl. `bin/lib/`), `README.md`, `LICENSE`, `package.json` (52 files on `mvp-v2-merge`). If the alias is released too, pack `packages/genclass-runtime` the same way and have the user publish it **after** the runtime (unscoped, so no `--access public` needed; a prerelease still needs `--tag`). 4. Give the user the command to run (on a machine logged in to npm with publish rights on the `genclass` org, with their 2FA): `npm publish genclass-runtime-<version>.tgz --access public --tag <tag>`. **A prerelease needs `--tag`** on npm 11: `lib/commands/publish.js` in npm 11.8.0 throws "You must specify a tag using --tag when publishing a prerelease version." unless `--tag` (or `publishConfig.tag`, or `--force`) is given, so `HANDOFF.md`'s bare `npm publish <tgz> --access public` fails for `0.1.0-alpha.1`. Use `--tag alpha` (or `next`) to leave `latest` where it is, or `--tag latest` to move it (today `latest` = `0.1.0-alpha.1`). A non-prerelease such as `0.1.0` needs no tag and becomes `latest`. Never run `npm publish` yourself without an explicit user go-ahead in chat. 5. After the publish: `git tag -a v<version> -m "@genclass/runtime <version> (npm)"` (push only with the user's OK); move the item to "Done" in `OPEN_TASKS.md`; check `npm view @genclass/runtime dist-tags`. What `0.1.0-alpha.1` (built from `mvp-v2`) changed for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model the runtime still only observes either way. -### Publish the model package (planned; OPEN_TASKS.md item 9; HANDOFF.md "How to continue") +What the next version (from `mvp-v2-merge` or its successor) adds over `0.1.0-alpha.1`: `init` / `remove`, `/auto` entries, the script tag and CDN worker, the `genclass-runtime` alias (all f3a9dd1); observe mode never holds or delays deliveries (054da38); redaction of F2 diffs and numeric/array secrets (f107013); `situation()` purity (29b7f28). The tarball roughly doubles (26 -> 52 files, 486.8 kB -> 1.1 MB packed), mostly the script-tag build and its source map. + +### Publish the model package (planned; OPEN_TASKS.md item 12; HANDOFF.md "How to continue") Full procedure: [RELEASE.md](../../../RELEASE.md) Part B. -Blocked on training: no situation-v2 model exists (next per HANDOFF: 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL). The round-1 R17 (`files/r17/` per MODEL_CARD, situation-v1) does not match the v2 runtime and must not be published as the default. `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` both 404 today. +Blocked on training: no situation-v2 model is ready to publish. The first one, `r17-v2a`, has held-out results in origin/runtime 416e374 (`docs/runtime/RESULTS.md`, not merged here): its fixed 0.9/0.8 gates block nearly every action, and runtime batch 6 (5bc40c9, not merged) reads gate thresholds from the model's `meta.json` instead. Still to come (per HANDOFF: 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL). The round-1 R17 (`files/r17/` per MODEL_CARD, situation-v1) does not match the v2 runtime and must not be published as the default. `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` both 404 today. 1. Put a model directory (card `genclass-runtime-model/1`: `model.json`, `<name>-q8.onnx`, `<name>-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`) under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `DEFAULT_MODEL_BASE_URL`. Check it with `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files`. 2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`), so run a root `npm install` and commit the lockfile change, or CI's `npm ci` fails. @@ -516,16 +563,16 @@ One workflow, `CI`, one job `runtime` ("@genclass/runtime: typecheck, build, uni | Install | `npm ci --no-audit --no-fund` | job env `ONNXRUNTIME_NODE_INSTALL: skip` | | Typecheck | `npm run typecheck -w @genclass/runtime` | runtime only; the root `npm run typecheck` would also typecheck `sim` and `demos` (which needs `dist/` and the missing `demos/src/server/data/cities.ts`) | | Build | `npm run build -w @genclass/runtime` | | -| Unit tests | `npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in `packages/runtime`, `NODE_OPTIONS: --expose-gc` | model parity tests skip (no `GENCLASS_MODEL_DIR`) | +| Unit tests | `npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in `packages/runtime`, `NODE_OPTIONS: --expose-gc` | model parity tests skip (no `GENCLASS_MODEL_DIR`); includes `test/install/cli.test.ts` (spawns `node bin/genclass-runtime.mjs` on fixture projects in the runner's temp dir). Expected on `mvp-v2-merge`: 375 passed + 14 skipped | | Perf budgets | `npx vitest run test/review-perf.test.ts --retry=2`, same env | | -Not in CI: Playwright (model and UI specs), `smoke.sh`, model-dir tests, `sim`/`demos`/`realapps`, Python tests. It has not run on GitHub yet (the branch is unpushed; `origin/runtime` has no `.github/`). +The Build step now runs all 4 tsup configs (main, 2 global, CDN). Not in CI: Playwright (model and UI specs), `smoke.sh`, the install harness (`run-all.sh`, `cdn-check.mjs`, `frameworks.mjs`), model-dir tests, `sim`/`demos`/`realapps`, Python tests. It has not run on GitHub yet (neither `mvp-v2` nor `mvp-v2-merge` is pushed; `origin/runtime` (eff18cb) has no `.github/`). `mvp-v2-merge` is not in the `push` branch list; if it becomes the branch that is pushed, add it or push it as `mvp-v2`. To change it: keep the runtime steps green locally first (same commands, [Exact commands](#exact-commands)). Adding the sim tests would need `npm run build -w @genclass/runtime` first and `SIM_RUNTIME=real`; adding browser specs needs `npx playwright install --with-deps chromium` and, for model specs, a model directory (a download: ask the user). Changing the trigger branches or adding jobs that publish is a user decision. ## Tests -Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder.test.ts` loop counts 4), collected with vitest's JSON reporter on b435acb. **Total 350 in 42 tracked files**: CORE 188, UI 53, MODEL 62, REVIEW 43, lead 4 (`default-mode.test.ts`). STATUS's "41 files, 346 tests" predates `default-mode.test.ts`. Without a model directory 14 MODEL tests skip (see [Verified locally](#verified-locally-2026-10-08)). Since 654d822: +5 files (`content` 14, `delivery` 16, `no-reorder` 6, `nan` 1, `default-mode` 4), and `atoms` +2, `batch3` +1, `dom` +4, `report` +1, `situation` +1. Tests that rely on held store writes now pass `policy: { holdWrites: true }` (`adapter-seam`, `adapters-*` real-runtime blocks, `plugins`, `report` (2 cases), `batch3` "ctx.builtin returns false ...", `review-hub` "in-place updater while held", `budget` hold-budget case, `no-reorder` last case; `atoms.test.ts` wraps `setup()` to always add it); the `adapters-*` `MockRuntime` blocks set `rt.holdWrites = true` on the mock instead. +Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder.test.ts` loop counts 4), collected with vitest's JSON reporter on `mvp-v2-merge` (f107013). **Total 393 in 46 tracked files**: CORE 190, UI 53, MODEL 62, REVIEW 43, lead 25 (`default-mode` 4, `observe-delivery` 11, `redaction-v2` 10), INSTALL 20 (`install/cli`). STATUS's "42 files, 348 tests" predates the newer files. Without a model directory 14 MODEL tests skip (see [Verified locally](#verified-locally-2026-10-08)). Since b435acb (350 in 42 files): +4 files (`install/cli` 20, `situation-purity` 2, `observe-delivery` 11, `redaction-v2` 10); `default-mode` and `policy` "observe mode never holds" now expect a background `delivery` decision (same counts). Since 654d822: +5 files (`content` 14, `delivery` 16, `no-reorder` 6, `nan` 1, `default-mode` 4), and `atoms` +2, `batch3` +1, `dom` +4, `report` +1, `situation` +1. Tests that rely on held store writes now pass `policy: { holdWrites: true }` (`adapter-seam`, `adapters-*` real-runtime blocks, `plugins`, `report` (2 cases), `batch3` "ctx.builtin returns false ...", `review-hub` "in-place updater while held", `budget` hold-budget case, `no-reorder` last case; `atoms.test.ts` wraps `setup()` to always add it); the `adapters-*` `MockRuntime` blocks set `rt.holdWrites = true` on the mock instead. | test file | owner | env | tests | what it asserts | |---|---|---|---|---| @@ -539,8 +586,9 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder. | `test/budget.test.ts` | CORE | node | 12 | `sectionLimits` at 500 (= 1,100)/1,100/1,750/2,400 (3,200 = 2,400); budgets 1,000/1,100/2,000 shape every section of a `delivery` situation; compact questions at <= 1,400; vocabulary overrides <= 24 chars kept; determinism; auto budget (webgpu 2,400; wasm 1,000/1,333/2,000; unknown 2,400; fixed 1,500); `max_tokens_exceeded` shrinks auto budget to 1,920; `holdBudget` auto = clamp(1.5 x median, 150, 800) else 300; held write `timeoutMs` = budget + 2,000; fetch `timeoutMs` = remaining budget. Prints example situations | | `test/content.test.ts` | CORE | node | 14 | batch 5 situation-v2 facts from `sim/SEPARABILITY.md` §6, one per fact: F3 a response that changes nothing is not salient; F1 put back a value a newer operation replaced (field, item cells); F2 overwrites text the user typed (diff-centred preview); F9 provenance of known-stale values (incl. a live channel that was down); F6 learned cadence (polling, debounced save); F5 failure scope and commit ambiguity; F7 repeated user action evidence; F8 relation quality; read-your-writes. Prints STATUS example situations | | `test/context.test.ts` | CORE | node | 7 | causal context: fetch -> json -> set cause/root, concurrent chains, `rt.op` ambient in body and continuation, nested op causes, ambient cleared by `afterTask`, timers observer carries cause (`timer 300ms`), idle timers create no ops | -| `test/default-mode.test.ts` | lead (f3636b2) | node | 4 | `createRuntime` without `mode` is `observe`; `GenClass.init` without `mode` is `observe`, `mode: "guard"` or `?genclass=guard` opt in; in observe nothing is held, delayed or changed even at p = 0.99 (decisions recorded, `executed` false, detections reported); with a never-answering model nothing waits (atom, adapter commit, fetch success and failure all immediate) | +| `test/default-mode.test.ts` | lead (f3636b2) | node | 4 | `createRuntime` without `mode` is `observe`; `GenClass.init` without `mode` is `observe`, `mode: "guard"` or `?genclass=guard` opt in; in observe nothing is held, delayed or changed even at p = 0.99 (decisions recorded for `delivery`, `mutation` and `request` since 054da38, `executed` false, detections reported); with a never-answering model nothing waits (atom, adapter commit, fetch success and failure all immediate) | | `test/delivery.test.ts` | CORE | node | 16 | situation-v2 network-boundary decisions: clean typeahead (in-order, loading flags, debounce) makes zero model calls; a stale out-of-order response gets a `delivery` decision and `discard` drops only its stale field writes; holding a response is only latency; no hold when the model cannot answer within the hold budget; store writes never held by default (read-after-write, late revert, slow model released at the budget, superseded queued decisions dropped); WebSocket messages (held only when they would put back a value a pending local change replaced, order kept), EventSource (custom event types as ops), XHR (held before any completion listener, abort during the hold); forced actions with probability 1 | +| `test/install/cli.test.ts` | INSTALL (f3a9dd1) | node | 20 | `init` / `remove` round trips on fixture projects (`--yes --no-install`; init twice changes nothing; remove restores every byte) for Vite + React, Next.js 16 / 15.1 App Router / 14 Pages Router, SvelteKit, Nuxt 3 and 4, Astro, Angular, CRA, Remix, React Router, webpack and plain HTML; `--mode observe`, `--no-devtools`, `--dry-run`, no write without a terminal unless `--yes`; hand-written setups left alone; an unrecognised project explained; `bin/lib/edit.mjs` helpers (`appendEnd`, `bodyTagEnd`, `codeStyle`, `insertTop`, `removeMarked`, `topOffset`); page config parsing in `src/cdn/config.ts` (`parsePairs`, `fromPairs`, `fromDataset`, `readMetaConfig`, `mergeConfig`, `isKilled`, `isLocalHost`, `devtoolsOptions`) and `src/cdn/global.ts` -> `assetBase` | | `test/devtools-runtime.test.ts` | UI | happy-dom | 7 | overlay on the real runtime (`runStoreSession`, guard): interventions newest first ("Prevented a stale response", "Reverted a duplicate write", "Prevented a duplicate request", "Slowed down a failing request"), folded detections, evidence = `explain()` (trigger "The response to GET /api/search?q=rea"), activity timeline, Now view, undo, live report sentence | | `test/devtools.test.ts` | UI | happy-dom | 20 | overlay vs `MockRuntime` + `loadScenario`: mount/unmount (shadow root, `data-genclass-ignore`, no global CSS, listeners and plugin removed), no-op handle, theme/position, feeds, activity rows, typing bursts, evidence, undo and undo errors, live pill, folding, 200-card cap, policy reasons, pause/clear, Now view, mode switch, keyboard (Alt+Shift+G), empty states | | `test/dom.test.ts` | CORE | happy-dom | 12 | `describeElement` (incl. batch 5: a control nested in its `<label>`, open shadow roots, `aria-labelledby`, slotted text); DOM user observer (clicks, typing bursts, passwords never recorded, submit/change/Enter, `[data-genclass-ignore]` incl. shadow roots, shadow-DOM targets described as the real element, synthetic `isTrusted: false` events only with `observe.untrustedEvents`, destroy); destroy restores fetch/XHR/history/Storage/WebSocket/timers; uncaught errors -> error trigger | @@ -548,9 +596,11 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder. | `test/invariants.test.ts` | CORE | node | 6 | `InvariantMiner` learns len/sum/equality/unique relations, ignores unchanged fields and id-like keys; inconsistency once per episode + rollback + undo; unsettled transients ignored; `expect()` predicates | | `test/learn.test.ts` | CORE | node | 8 | `Baselines` (latency after 5 samples, EWMA 0.9 error rate, streaks, outcomes, rate vs usual, identity gaps); `Profiles` (write set < 1% of >= 20, value kind, status class); transition trigger + rollback | | `test/nan.test.ts` | CORE (ad24804) | node | 1 | a store holding `NaN` builds situations without infinite recursion (the alpha.0 crash; fixed in the published `0.1.0-alpha.1`) | +| `test/observe-delivery.test.ts` | lead (054da38) | node | 11 | observe mode: a fetch response resolves at the network time even with a slow body, the background `delivery` decision is recorded and reported and its writes are not decided again; the decision sees the state the response was delivered into; an app write before the body read decides the delivery at that write; F1 is not lost; standing questions on deliveries; XHR listeners run inside the original dispatch; WebSocket and EventSource messages delivered synchronously and in order, still decided; guard mode unchanged (stale response held, discard drops the stale write; a delivery that cannot be held is released and its write late-reverted; slow model + standing question decides without acting) | | `test/no-reorder.test.ts` | CORE | node | 6 | "never worse": realworld's Redux promise-middleware pattern through `genclassEnhancer` with an always-passive model (`PassiveDecider`, 10 ms): observe baseline renders; guard and heal x triage salient and always give identical dispatches, order, pages and final state with 0 interventions; `holdWrites: true` never reorders a store's dispatches | | `test/plugins.test.ts` | CORE | node | 7 | plugin facts/diagnoses/custom actions, `ctx.builtin` (with `holdWrites: true`), plugin actions default to heal tier, `applicable()`, standing questions + `onAnswer`, `setup()`/cleanup API, vocabulary overrides | | `test/policy.test.ts` | CORE | node | 14 | `gate()` summed mass, mode tiers, thresholds 0.9 guard / 0.8 heal, passive top, `requireDiagnosis`, deny/allow, pause, rate limit with 60 s sliding window, observe never holds, `setMode`, `pause()/resume()`, loading fails open without a record, detection threshold | +| `test/redaction-v2.test.ts` | lead (f107013) | node | 10 | F2 "would replace text the user typed": default and custom redactors show `[redacted]` / the replacement, never a raw diff; non-secret fields keep the diff-centred preview; `redactedStringDiff`; under strong secret containers numbers, bigints and arrays are redacted (booleans, null, undefined kept; broad containers like `auth` unchanged); `changeText` and `describe()` hide them | | `test/report.test.ts` | CORE | node | 8 | report line format, `explain(id)`, without `holdWrites` a discarded write is applied at once, late-reverted and reported "Reverted a stale write ... (decided 0.00s after it applied)" with `late: true`, "Not acted on (would have done ...)", console group + "(×2 more in the last minute)", `on()` listeners, `GenClass.init` idempotent, `?genclass=off`, `?genclass=heal` | | `test/review-actions.test.ts` | REVIEW | node | 1 | error-trigger rollback only when the failing chain wrote state; user input survives | | `test/review-dom.test.ts` | REVIEW | happy-dom | 2 | unlabeled password never recorded; programmatic `click()` inside an op is not a user action | @@ -562,6 +612,7 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder. | `test/review-redaction.test.ts` | REVIEW | node | 1 | custom `redact` also applies to invariant facts | | `test/review-timers.test.ts` | REVIEW | node | 2 | 200,000-step recursive `setTimeout` loop does not throw; polling loop does not retain ops (registry prunes beyond 2,000; gc check needs `--expose-gc`) | | `test/review-xhr.test.ts` | REVIEW | node | 4 | sync XHR never held, abort while held means never sent, listeners added once per object, reuse after a blocked answer | +| `test/situation-purity.test.ts` | CORE (29b7f28) | node | 2 | building situations for every `TriggerKind` in every context changes no counter (`ops.peekNextId`, ops, in-flight, events, decisions, ...) and no later op id; polling `situation()` every microtask turn like the devtools overlay (`runStoreSession({ onRuntime })`) changes no decision, hold or id | | `test/situation.test.ts` | CORE | node | 11 | one situation per trigger: `delivery` (a stale response about to overwrite newer results; in-order responses never ask), `mutation` (an older task's write over a newer task's, applied then late-reverted), request, failure, stall, inconsistency, transition, error, `ask` (side-effect free): keys `app, trigger, facts, in_flight, timeline, state, stats`, section limits, `stateChars <= STATE_CHAR_BUDGET`; serializer drop order; determinism. Prints situations | | `test/smoke.test.ts` | CORE | node | 3 | atoms apply synchronously when nothing is salient; context through real awaits; in guard mode a stale out-of-order response gets one `delivery` decision, `discard` drops only `search.results` (`interventions()[0].dropped`), the app still sees the response (own local `setup()` with `mode: "guard"`) | | `test/xhr.test.ts` | CORE | node | 5 | XHR op + cause, block replays 503, failures detection-only, request gate fails open at 300 ms, destroy restores `open`/`send` | @@ -575,6 +626,8 @@ Counts are `it(...)` cases (the `budget.test.ts` loop counts 3; the `no-reorder. | `test/browser/model-webgpu.spec.ts` | MODEL | Chromium + SwiftShader | 2 + per variant + per export | model on WebGPU without `shader-f16` (runs or falls back to WASM on f16 tensors); `GENCLASS_WEBGPU_VARIANTS` variants (`f32emb` must run on WebGPU); `GENCLASS_BENCH_MODELS` exports; `auto` skips software adapters | | `test/browser/ui-devtools.spec.ts` | UI | Chromium | 5 | style isolation, keyboard, undo, screenshots light + dark | | `test/smoke/smoke.sh` | packaging (owner not recorded) | bash + Chromium | 1 script | npm tarball works in a fresh Vite 8 app (see How it works) | +| `test/install/cdn-check.mjs` | INSTALL | node + Chromium (VM) | 26 checks (RESULTS.md) | script tag and `/auto` across origins: Blob-URL model worker, model ready, config from data attributes | +| `test/install/frameworks.mjs` (+ `scaffold.sh`, `server.mjs`, `run-all.sh`) | INSTALL | bash/node + Chromium (VM) | 15 projects (RESULTS.md) | real framework projects: init, re-init, prod + dev in Chromium, remove byte-identical | ### Fixtures @@ -594,8 +647,12 @@ Doc-vs-code mismatches (code wins): - **`HANDOFF.md` "What this is"** says "Modes: observe -> guard (default; ...) -> heal". Since f3636b2 (on `mvp-v2` only) the default is `observe`; guard is opt-in and heal experimental. `HANDOFF.md` and `STATUS.md` were not updated by that commit. - **`HANDOFF.md` "Current state"** gives the publish command as `npm publish <tgz> --access public`. With npm 11 that fails for any prerelease (`0.1.0-alpha.1`) unless `--tag` is added ([Cut a release](#cut-a-release-of-genclassruntime) step 4). - **`.gitignore` `data/` hides `demos/src/server/data/cities.ts`**, which the demos import; see gotchas and [../demos.md](../demos.md). -- **Test counts.** `STATUS.md` "State" says "41 files, 346 tests" and `HANDOFF.md` "346 tests pass"; on `mvp-v2` it is 42 files, 350 tests (`default-mode.test.ts` added). -- **Branch header.** `OPEN_TASKS.md` says "Branch `runtime`"; `origin/main` is still 654d822, so "Merging `runtime` into `main`" ("Needs the user") is still open. +- **Test counts.** `STATUS.md` "State" says "42 files, 348 tests" and `HANDOFF.md` "346 tests pass"; on `mvp-v2-merge` it is 46 files, 393 tests. +- **Install features labelled as alpha.1.** f3a9dd1's subject ("0.1.0-alpha.1: one-command install ...") and `packages/runtime/CHANGELOG.md` "## 0.1.0-alpha.1" list `init`, `/auto` and the script tag, but the published `0.1.0-alpha.1` (806a296) has none of them. The CHANGELOG entry and any README text that tells users `npx @genclass/runtime init` works today are wrong until the next version is out. +- **`packages/genclass-runtime` pins `@genclass/runtime` `0.1.0-alpha.1`**, the version without `init` (see gotchas). +- **`test/install/RESULTS.md`** was measured against a tarball versioned `0.1.0-alpha.0` from Mehar's tree, before the merge and before 054da38 / f107013. `cli.test.ts` passes on `mvp-v2-merge`; the browser and framework parts are unverified there. +- `test/install/cli.test.ts`'s header names `test/install/frameworks.sh`; the file is `frameworks.mjs`. +- **Branch header.** `OPEN_TASKS.md` names `runtime` "at eff18cb"; `origin/runtime` is now 5bc40c9. `origin/main` is still 654d822, so "Merging into `main`" (`runtime` and/or `mvp-v2`, "Needs the user") is still open. - `packages/runtime/STATUS.md` "Open issues" says `react-dom` is not a devDependency of `@genclass/runtime`, and `packages/runtime/UI-NEEDS.md` item 2 (still under "Open") asks for `react-dom` and `@types/react-dom`. Both are devDependencies: `react-dom ^19.3.0`, `@types/react-dom ^19.0.0`. UI-NEEDS item 1 (ignore `[data-genclass-ignore]`) is also listed as open but is implemented and tested (`dom.test.ts`). - `packages/runtime/src/model/README.md` ("Bundling") says `dist/worker.js` imports `onnxruntime-web/webgpu`. The worker imports either `onnxruntime-web/webgpu` or `onnxruntime-web/wasm` on demand (`src/model/worker.ts`; the same README's file table says so), and `build.mjs` checks both. - `test/browser/model-helpers.ts` -> `saveResults` doc comment says it writes `test-results/browser/<name>.json`. The code writes `test-results/model-bench/<name>.json` (the model README is correct). @@ -606,16 +663,17 @@ Doc-vs-code mismatches (code wins): - Documented `GENCLASS_MODEL_DIR` locations differ: `~/gcl/model/.cache-model` (STATUS), `~/gcl-cache/model-v0.1` (model README), `~/gcl/models/genclass-v0.1` (demos `vm-eval.sh` default model dir). Unverified which exist on the VM. - `scripts/genclass_export.py` usage text passes `--requests extension/genclass/test/fixtures/requests50.json`; that path does not exist in this repo (the file is `extension/test/fixtures/requests50.json`; the script's own instructions say to run "from ~/jev on the VM"). - Ownership: `docs/runtime/CONTRACT.md` §1 (layout) still lists `src/adapters/` and `src/devtools/` as owner CORE, but §13 (Additions) reassigns them to UI, which matches `STATUS.md` counting their tests as UI's. §1 is stale; the Tests table follows §13 / STATUS. -- `test/browser/model-helpers.ts` and `model.spec.ts` parity still target the v0.1 GenClass model; nothing in the browser specs exercises a situation-v2 runtime model (none exists). +- `test/browser/model-helpers.ts` and `model.spec.ts` parity still target the v0.1 GenClass model; nothing in the browser specs exercises a situation-v2 runtime model (none is published or in this branch). Resolved since 654d822 (moved out): no CI and no committed lockfile (b435acb); the CLI's 100644 mode flip on install (b435acb); the npm dist-tag question (`latest` was `0.1.0-alpha.0` per `npm view`; since 2026-10-08 it is `0.1.0-alpha.1`); `STATUS.md`'s stale "For UI" note about `MockRuntime.holdBudgetMs()/situationBudget()` and its redundant `--exclude "test/browser/**"` command (both gone from STATUS). Open items in scope (from `OPEN_TASKS.md`, `HANDOFF.md`, `training/NEEDS.md`, STATUS): -- **`0.1.0-alpha.1`**: published 2026-10-08 from `mvp-v2` (806a296) under `latest`. 806a296 is now the head of `mvp-v2`. Still open: push `mvp-v2` and tag `v0.1.0-alpha.1` to origin (needs an account with write access). -- **Push and first CI run**: `mvp-v2` (with `.github/workflows/ci.yml`) is local only; pushing needs the user's OK. Until then CI has never run on GitHub (the `review-perf` retry and the `ONNXRUNTIME_NODE_INSTALL=skip` setting are verified only locally). -- **Model package**: blocked on v2 training (SIM v2 data on c02–c09 and c12–c23, REAL on c01, c10, c11, per `training/NEEDS.md`; then teacher, distillation, DAgger, EVAL). Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. -- Docs (item 13): dev-only lazy import of the devtools (52 KB min / 17 KB gz). +- **`0.1.0-alpha.1`**: published 2026-10-08 from `mvp-v2` (806a296) under `latest`. Still open: push the branch and tag `v0.1.0-alpha.1` to origin (needs an account with write access and the user's OK). +- **Next runtime version** (`0.1.0-alpha.2`, or a beta with the model): carries the install features and the observe/redaction fixes from `mvp-v2-merge`. Before packing: bump the runtime and alias versions together, fix the CHANGELOG heading, run the install harness on the release tree (ask first). The user publishes (2FA, `--tag` for a prerelease). +- **Push and first CI run**: `mvp-v2` / `mvp-v2-merge` (with `.github/workflows/ci.yml`) are local only; pushing needs the user's OK, and Mehar (asleep at the time of writing) should see the merge before it lands on `runtime`. Until then CI has never run on GitHub (the `review-perf` retry, `ONNXRUNTIME_NODE_INSTALL=skip` and `cli.test.ts` on Linux are verified only locally on macOS). +- **Model package**: blocked on v2 training. v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled rows); on 2026-10-08 Mehar's Azure jobs `r17-v2a` (R17 on v2 gold, auto eval + export via `training/v2_post.sh`) and `t150-v2a` (150M teacher) ran unattended. `r17-v2a` has since finished: origin/runtime 416e374 records its eval (guard FIR 0.00%, but the fixed gates block nearly every action), and 5bc40c9 (batch 6) makes the gates come from the model's `meta.json`; neither is merged here. The teacher's status is not recorded in the repo. Then teacher labels, distillation, DAgger, EVAL. Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. +- Docs (OPEN_TASKS item 17): whether a dev-only lazy import of the devtools is still needed is open; the README's "52 KB minified / 17 KB gzip" is unverified (see [devtools.md](devtools.md)). - The VM path (`scripts/vm.sh`) depends on Mehar's hosts file and SSH key. Without them the light checks run locally under the run policy in AGENTS.md; anything heavier needs the user's go-ahead. - Any situation-wording change must be coordinated with SIM, REAL and TRAIN (frozen at `situation-v2`). - Working copies may hold untracked `test/zz-*.test.ts` files from parallel review agents; vitest collects them. They are not part of `mvp-v2`. diff --git a/docs/agents/runtime/decide-policy-actions.md b/docs/agents/runtime/decide-policy-actions.md index fc0d6eb7..a9244fee 100644 --- a/docs/agents/runtime/decide-policy-actions.md +++ b/docs/agents/runtime/decide-policy-actions.md @@ -12,13 +12,15 @@ > latency, stale-item dropping, fail-open), the delivery gate, the policy gate or its defaults, any built-in action's > mechanics or `changed` text, custom actions / standing questions, the console report wording, > `Decision` / `ActionRecord` / `Explanation` shapes, `explain()` or undo. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes 054da38, f107013), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - **Default mode is `observe`** (`packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`, commit f3636b2): it permits no non-passive action, so nothing is ever held, delayed or changed; decisions still - run in the background and detections are still reported. `guard` is opt-in; `heal` is experimental. + run in the background and detections are still reported, for mutations, requests **and deliveries** (commit + 054da38: a response/message is released synchronously, before any body read, and its delivery decision is made in + the background; `test/observe-delivery.test.ts`). `guard` is opt-in; `heal` is experimental. - **situation-v2 decides at the network boundary** (commit fcd1e68, frozen at tag `situation-v2` = 6e5e86e). A new trigger `delivery` fires when a fetch/XHR response or a WebSocket/EventSource message is about to reach the app and the fields its operation is predicted to write hold newer data that the body would change (any newer-data conflict @@ -33,7 +35,11 @@ single-flight priority queue (`DeciderQueue`). The subject is **held** only if the trigger is holdable (`opts.hold`), at least one non-passive action is permitted by mode + policy, the runtime is not paused, **and** the expected model latency fits the hold budget (`expectedLatency() <= holdBudgetMs()`). Otherwise the passive - action runs at once and the decision is still made in the background. + action runs at once and the decision is still made in the background. Deliveries check this up front + (`runtime.ts` -> `deliveryHoldable`): one that cannot be held is released before its body is read; it is then + decided in the background when its chain's writes could not act on their own (observe, or a policy restricting + `discard`), and otherwise (guard/heal with a model too slow to hold for) only when forced (an `always` standing question on `delivery`, or + `triage: "always"`). - **Fail-open everywhere:** no provider, provider not `ready`, provider error (any `code`), queue overflow, expired deadline, superseded subject (`Controller.stale`), runtime-side timeout, hold budget expiry, a throwing action -> the passive action runs. A missing model never blocks the app and never produces a `Decision`. @@ -45,7 +51,8 @@ Candidate = argmax of probability over A. It runs only if: not paused; Σ p(A) ≥ the candidate's tier threshold (guard 0.9, heal 0.8); the model's top diagnosis ≠ `expected` (unless `requireDiagnosis: false`); fewer than `maxActionsPerMinute` (60) actions in the last 60 s; and the subject has not already proceeded - (`Controller.proceeded`), except for a late-revert `discard` and for custom actions. + (`Controller.proceeded`), except for a late-revert `discard` and for custom actions (not on a delivery that was + already released). - **Built-in actions** are generic capabilities defined in `situation/questions.ts` -> `BUILTIN_ACTIONS` and implemented by per-subject `Controller`s (`decide/exec.ts`): mutation (`runtime.ts` -> `mutationController`), delivery (`runtime.ts` -> `runDelivery`), request/failure/stall (`observe/fetch.ts`, `observe/xhr.ts`), @@ -67,14 +74,14 @@ | `packages/runtime/src/decide/exec.ts` | Types only: the seam between the decision flow and the subject of a trigger | `ActionEffect`, `Controller`, `TriggerOpts`, `EndOpts`, `NetHost` (incl. `deliver`, `noteResponse`) | | `packages/runtime/src/decide/policy.ts` | Policy config, mode/tier permission, the §8 gate, rate limiter, hold budget | `policyConfig`, `PolicyConfig`, `modeAllows`, `restriction`, `permittedActions`, `gate`, `GateInput`, `GateOutcome`, `RateLimiter`, `holdBudget`, `HOLD_MIN_MS`, `HOLD_MAX_MS`, `HOLD_FALLBACK_MS` | | `packages/runtime/src/decide/report.ts` | Report sentences and console sink with dedupe | `interventionLine`, `detectionLine`, `decisionLine`, `Reporter` | -| `packages/runtime/src/runtime.ts` | Wiring: `trigger`, `onDecision`, `runCustom`, `mutationController`, `gateMutation` (holdWrites), `observeWrite` (default), `covered`, `expectedLatency`, `runDelivery` (delivery gate), `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `noteResponse`, `onChannel`, `markWrites`, `waitRelated`, `raiseInconsistency`, `raiseTransition`, `reportError`, `watchStall`, `rollback`, `revertChain`, `resync`, `runAsGenClass`, `explain`, `decisions`, `interventions`, `holdBudgetMs`, `action`, `question`, `use`, `setMode`, `pause`, `resume`, `destroy`, `setReport`, `isPaused` | `RuntimeImpl` (exported publicly from `src/index.ts`; `runDelivery` is a public member) | +| `packages/runtime/src/runtime.ts` | Wiring: `trigger`, `onDecision`, `runCustom`, `mutationController`, `gateMutation` (holdWrites), `observeWrite` (default), `covered`, `expectedLatency`, `runDelivery` (delivery gate), `deliveryHoldable`, `writesCanAct`, `finalizeDeliveries` (background deliveries), `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `noteResponse`, `onChannel`, `markWrites`, `waitRelated`, `raiseInconsistency`, `raiseTransition`, `reportError`, `watchStall`, `rollback`, `revertChain`, `resync`, `runAsGenClass`, `explain`, `decisions`, `interventions`, `holdBudgetMs`, `action`, `question`, `use`, `setMode`, `pause`, `resume`, `destroy`, `setReport`, `isPaused` | `RuntimeImpl` (exported publicly from `src/index.ts`; `runDelivery` is a public member) | | `packages/runtime/src/situation/questions.ts` | Action catalogue and diagnosis vocabulary (model-facing wording, frozen at tag `situation-v2`) | `BuiltinAction`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions`, `COMPACT_QUESTIONS_BUDGET` | | `packages/runtime/src/situation/build.ts` | Which actions are offered for a subject (applicability); delivery subject text and `SubjectRef` | `buildSituation`, `subjectOf`, `relatedInFlight`, `subjectRef`, `ActionOption`, `BuiltSituation` (internal `builtinApplicable`, `revertableChain`) | | `packages/runtime/src/situation/conflicts.ts` | Delivery prediction and conflicts (salience inputs; see [learn-situation-triage.md](learn-situation-triage.md)) | `predictedWrites`, `matchFields`, `conflictsOn` | | `packages/runtime/src/situation/content.ts` | Response-body analysis at delivery (does the body change / put back a value) | `analyzeBody`, `createdIds`, `vhash`, `parseJsonBody` | | `packages/runtime/src/observe/fetch.ts` | fetch controllers: request gate (`send`/`coalesce`/`delay`/`block`/`serve_cached`), failure gate (`deliver`/`retry`/`serve_cached`), stall (`wait`/`hedge`/`serve_cached`); calls `host.deliver` for successful responses | `installFetch` (internal `runRequest`, `failureGate`, `stallController`, `reqCtl`, `jsonOfBuffered`) | -| `packages/runtime/src/observe/xhr.ts` | XHR request gate (`send`/`delay`/`block`/`serve_cached`); delivery gate for successful async responses (wraps the app's completion listeners); failures/stalls passive-only | `installXHR` (internal `arrive`, `gateCall`, `wrapHandlers`, `fake`, `passiveOnly`) | -| `packages/runtime/src/observe/messages.ts` | Delivery gate for push channels: per-channel ordered queue, re-dispatch of released messages | `MessageGate`, `MsgHost`, `messageSummary` | +| `packages/runtime/src/observe/xhr.ts` | XHR request gate (`send`/`delay`/`block`/`serve_cached`); delivery gate for successful async responses (wraps the app's completion listeners; the body is also exposed synchronously as `body.now`, read by `NetHost.deliver` as `bodyNow`); failures/stalls passive-only | `installXHR` (internal `arrive`, `gateCall`, `wrapHandlers`, `fake`, `passiveOnly`) | +| `packages/runtime/src/observe/messages.ts` | Delivery gate for push channels: per-channel ordered queue, re-dispatch (a cloned event) of messages released after a hold or queued behind one; a message the gate releases synchronously with nothing queued ahead is not re-dispatched (the original event continues to the app's listeners); passes `bodyNow` (the parsed message) | `MessageGate`, `MsgHost`, `messageSummary` | | `packages/runtime/src/observe/websocket.ts`, `packages/runtime/src/observe/eventsource.ts` | Install a `MessageGate` per socket / event source; report channel down/up | `installWebSocket`, `installEventSource` | | `packages/runtime/src/observe/cache.ts` | Response buffers used by `coalesce` / `serve_cached` | `ResponseCache`, `makeResponse`, `blockedResponse`, `MAX_BODY`, `MAX_ENTRIES`, `COALESCE_WINDOW_MS`, `BUFFER_WAIT_MS` | | `packages/runtime/src/state/hub.ts` | Applies a mutation verdict (`apply`/`discard`/`defer`) when `holdWrites`; calls `observeWrite` otherwise; applies the delivery drop filter; late-revert checks and patches | `StoreHub.holdWrites`, `.revertable`, `.revert`, `.reapply`, `.restoreFields`, `.commit`, `.flushQueue`, `.pendingView`, `Verdict` (internal `applyFilter`) | @@ -108,8 +115,16 @@ app now (`release()`), after the model, or after related ops (defer). Sets `op.delivery = { patterns, known, salient, decided, overNewer? }` on the subject op (`trace/ops.ts` -> `OpRec.delivery`). - **covered write**: `runtime.ts` -> `covered(m)`: the write's causal chain (≤ 16 ancestors) passed a delivery gate - whose prediction was known and includes every changed path, and that delivery was not salient or was decided - before it proceeded. Covered writes raise no `mutation` trigger (never with `triage: "always"`). + whose prediction was known and includes every changed path, and that delivery was not salient, was decided + before it proceeded, or is a background delivery decision (released without a hold, `trigger` -> `background`) + still pending (`deliveryPending`) or done (`decided`). Covered writes raise no `mutation` trigger (never with + `triage: "always"`). +- **background delivery**: a delivery `runDelivery` releases at once because `deliveryHoldable` is false (observe, + no permitted non-passive delivery action, model not `ready`, or `expectedLatency()` over the hold + budget). Its content analysis and decision run afterwards, on the state it was released into; the decision can + only record (`executed` false for a non-passive top, gate reason e.g. `observe mode never changes execution`). + When `writesCanAct()` (guard/heal, `discard` not restricted) it is decided only when forced; with the provider not + `ready` it is not decided at all (`trigger` fails open). - **discard mark / drop filter**: a delivery `discard` sets `op.discardMark = { protect, until, dropped, onDrop? }`; for `DISCARD_MARK_MS` (10 s) `StoreHub.propose` asks `runtime.ts` -> `dropFilter(m)` which changes of each write in that op's chain to drop (`hub.ts` -> `applyFilter`). @@ -269,7 +284,7 @@ Call sites and their `TriggerOpts`: |---|---|---|---| | `runtime.ts` -> `observeWrite` (hub hook, default: `holdWrites` false) | `mutation` | false | 1 | | `runtime.ts` -> `gateMutation` (hub `gate` hook, only with `holdWrites: true`) | `mutation` | true | 2 | -| `runtime.ts` -> `runDelivery` (from fetch, XHR, WebSocket, EventSource) | `delivery` | true | 2 | +| `runtime.ts` -> `runDelivery` (from fetch, XHR, WebSocket, EventSource) | `delivery` | true; false for a background delivery (already released, `deliveryHoldable` false) | 2 | | `observe/fetch.ts` -> `runRequest` request gate | `request` | true (`keepalive` requests raise no trigger: sent at once) | 2 | | `observe/fetch.ts` -> `failureGate` | `failure` | true | 2 | | `observe/xhr.ts` -> `wSend` (async XHR only) | `request` | true | 2 | @@ -299,12 +314,20 @@ Steps: 5. If the provider is not `"ready"` (i.e. `"off"`): read `this.ready` (starts the lazy load) and run passive. 6. `permitted = permittedActions(policy, mode, built.actions)`; `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`. If `!waits`, run passive **now** and keep deciding in the background. + Deliveries that do not wait: if `writesCanAct()` (not paused and `discard` not restricted by mode/policy, i.e. + guard/heal) and the trigger is neither forced nor `triage: "always"` -> passive, no record (the chain's writes keep + their own decisions and late revert). Otherwise (observe, `discard` restricted) the delivery op is added to + `deliveryPending` **before** passive runs (passive may run the app's listeners and their writes synchronously), + so `covered()` skips mutation triggers for its chain's predicted writes while the decision is pending. 7. `budget = holdBudgetMs()`. If `waits`, start a budget timer: on fire set `expired = true` and run passive. 8. Deadline: `waits` -> `t0 + budget + (ctl.revert ? LATE_REVERT_MS : 0)` (only a held mutation has `revert` and waits); not waiting -> `t0 + BACKGROUND_DEADLINE_MS` (5,000), which includes default-mode background mutations. 9. `queue.submit({ trigger, state, questions, priority: waits ? opts.priority : min(opts.priority, 1), subject }, - deadline, ctl.stale)`. -10. On result: clear the budget timer; destroyed or `null` -> passive; else `onDecision(...)`. Any throw -> passive. + deadline, stale)`, where `stale = ctl.stale` except for a delivery that does not wait (no `stale`: it is already + released and is still decided for detection, reports and standing questions). +10. On result: clear the budget timer; destroyed or `null` -> passive; else `onDecision(...)` (with `covers` = a + background delivery). Any throw -> passive. Either way a background delivery leaves `deliveryPending` (a dropped + one leaves its later writes to their own `mutation` decisions). The `passive` closure in `trigger` is guarded by `passiveRan`, so the controller's `passive()` runs at most once through that path. `t0` is read after the situation is built, so `Decision.latencyMs` excludes build time. @@ -368,11 +391,14 @@ runtime timeout). They bypass triage, the gate and `Decision` records (see 6. Else `run = candidate`. Reasons 1–3 are reported only when the model's own top choice was non-passive; 4–5 are always set. 3. `proceeded = ctl.proceeded ? ctl.proceeded() : hold && (expired || passiveRan())`. For a `delivery` that has not - proceeded, set `op.delivery.decided = true` (this is what makes its chain's writes `covered`). + proceeded, or a background delivery (`covers`), set `op.delivery.decided = true` (this is what makes its chain's + writes `covered`; a held delivery released at its budget is not marked). 4. If `run` is a built-in and `proceeded`: `discard` with `ctl.revert`/`ctl.revertable` -> late-revert path (flow 5); otherwise `run = null` with reason `"the decision arrived after the hold budget expired"` when the subject had waited, else `"the subject was not held (decided in the background)"`. Custom actions are exempt (they run even - after the subject proceeded). These overrides never call `rate.take`. + after the subject proceeded), except on a `delivery`: a released delivery can only take the passive action. These + overrides never call `rate.take`. (In observe mode the gate already returns no `run`, so the reason is the gate's, + e.g. `observe mode never changes execution` when the model's top was non-passive.) 5. A `rate limit` reason emits a status report at most once per 60,000 ms: `[GenClass] Rate limit reached (<N> actions/minute): running passive actions until it clears.` 6. Build `Decision` (`action = run ?? top`), push to `decisionsBuf` (keeps 200) and `explainMap` (if the map holds @@ -446,8 +472,8 @@ Entry points: fetch -> `NetHost.deliver` for a non-failure response (any status of the primary request while `gated` and not yet answered (body = parsed JSON of the buffered clone, when the request has an identity and a `Response` constructor exists); XHR -> `arrive()` on the first completion event of a successful async response (`readyState 4`, status not 0/5xx/429/408; -body = `xhrJson`); WebSocket/EventSource -> `MessageGate.decide` for each incoming message (body = -`parseJsonBody(data)`). `release()` delivers: fetch resolves the app's promise, XHR runs the queued app completion +body = `xhrJson`, also synchronously as `bodyNow`); WebSocket/EventSource -> `MessageGate.decide` for each incoming +message (body = `parseJsonBody(data)`, also as `bodyNow`). Fetch has no `bodyNow` (its clone is still being read). `release()` delivers: fetch resolves the app's promise, XHR runs the queued app completion listeners in order with the op ambient, `MessageGate` re-dispatches a cloned event (later messages and close/error events wait behind a held one). @@ -457,18 +483,36 @@ events wait behind a held one). 0, decided: false }`. 3. No conflicts, no typed-into text field and not forced (`triage: "always"` or an `always` standing question on `delivery`) -> release synchronously (no model call, no record). -4. With a body: wait at most `BODY_WAIT_MS` (100) for it, then `analyzeBody` decides salience: newer-data conflicts - whose incoming value differs, pending changes the body would put back (`vhash` of the value the user replaced), - typed text the body would replace. If every conflicting field is unchanged, an event `delivery.unchanged` is - pushed. No body / timeout / analysis error -> salient iff newer-data conflicts exist. (Salience details: - [learn-situation-triage.md](learn-situation-triage.md).) -5. Not salient and not forced -> release. Else `trigger(spec, ctl, { hold: true, priority: 2 })`. +4. `deliveryHoldable(op, matched, defers)` false (observe mode, paused, provider not `"ready"`, no non-passive + delivery action permitted by mode + policy (`defer` counts only with related ops in flight and `defers < 2`; a + permitted custom delivery action counts), or `expectedLatency() > holdBudgetMs()`) -> **background**: release + synchronously now, before any body read, so the app gets the delivery exactly as without GenClass. +5. With a body: `analyzeBody` decides salience: newer-data conflicts whose incoming value differs, pending changes + the body would put back (`vhash` of the value the user replaced), typed text the body would replace. If every + conflicting field is unchanged, an event `delivery.unchanged` is pushed. No body / timeout / analysis error -> + salient iff newer-data conflicts exist. (Salience details: [learn-situation-triage.md](learn-situation-triage.md).) + - Held path: wait at most `BODY_WAIT_MS` (100) for the body. + - Background with `bodyNow` (XHR, WebSocket, EventSource): analyze at once, before the app's listeners run + (errors are logged, never break the delivery). + - Background without `bodyNow` (fetch): wait at most `BODY_WAIT_MS`, but no longer than the first write of the + delivery's chain: the hub's `proposed` hook calls `finalizeDeliveries(m.cause)` (≤ 16 ancestors), which cuts the + analysis short (`deliveryAnalysis`) so the situation shows the state the response was delivered into. At that + cut, with newer-data conflicts or forced -> decide without the body; otherwise (only a pending change / typed + text, which only the body can show) the delivery stays undecided with `salient = true`, so `covered()` does not + cover its writes and they get their own `mutation` decisions (F1/F2 are not lost). +6. Held path: not salient and not forced -> release; else `trigger(spec, ctl, { hold: true, priority: 2 })`. + Background: `markOverNewer()`, then, when salient or forced, `trigger(spec, ctl, { hold: false, priority: 2 })` + (flow 1 step 6 decides whether it is recorded and whether it covers the chain's writes). Delivery controller: `passive()` releases and, when the delivery was salient over conflicts, sets `op.delivery.overNewer` (later writes of that chain get a field mark "delivered over newer data", `markWrites`); `discard` and `defer` are below. In observe mode nothing is permitted, so a salient delivery is released at once and -decided in the background; its writes are then not `covered` (not decided in time), so they raise background -`mutation` decisions too. +decided in the background: one `Decision` with `trigger: "delivery"` (detection, `decide`/`detect` events, reports, +standing questions), never acting. While that decision is pending or after it is made, its chain's predicted writes +are `covered` (no second `mutation` decision about the same writes); writes outside the prediction are still decided +on their own. In guard/heal mode a delivery that cannot be held (model too slow) is released the same way but is not +decided unless forced (an `always` standing question or `triage: "always"`); its writes keep their own decisions and late revert (`test/observe-delivery.test.ts` "guard +mode is unchanged"). ### 7. Custom actions and standing questions (`runtime.ts` -> `action`, `question`, `use`, `runCustom`) @@ -551,7 +595,7 @@ Status lines emitted by `runtime.ts`: `[GenClass] Model ready (<model, device, v | `pause()` | `paused = true`, `hub.gating = false`, `NetHost.gated` false (no request/failure/stall/delivery triggers); `consultable()` false; decisions already queued still produce a `Decision` but never run (`"GenClass is paused"`) | | `resume()` | undoes `pause()` (no-op after `destroy`) | | `isPaused` | getter on `RuntimeImpl` only (not on `Runtime`) | -| `destroy()` | `destroyed = true`, `hub.gating = false`, `queue.dispose()` (pending decisions resolve `null` -> passive, which releases held deliveries), `reporter.dispose()`, observers uninstalled, plugins unregistered, an owned provider disposed | +| `destroy()` | `destroyed = true`, `hub.gating = false`, `queue.dispose()` (pending decisions resolve `null` -> passive, which releases held deliveries), pending background delivery analyses cleared, `reporter.dispose()`, observers uninstalled, plugins unregistered, an owned provider disposed | | `setReport(sink)` | `RuntimeImpl` only: swaps the report sink live (`Reporter.setSink`) | ### Events @@ -636,12 +680,12 @@ Notes: | `LATENCY_SAMPLES` | number | 20 | `decider.ts` | provider latencies kept for the hold budget and expected latency | | `PROVIDER_TIMEOUT_MS` | ms | 10,000 | `decider.ts` (exported) | runtime-side timeout when a request has no deadline | | `LATE_REVERT_MS` | ms | 2,000 | `runtime.ts` | late-revert window; also extends held-mutation deadlines | -| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `runtime.ts` | deadline of non-held decisions (incl. default-mode mutations) | +| `BACKGROUND_DEADLINE_MS` | ms | 5,000 | `runtime.ts` | deadline of non-held decisions (incl. default-mode mutations and background deliveries) | | `DISCARD_MARK_MS` | ms | 10,000 | `runtime.ts` | how long a delivery `discard` keeps dropping its chain's writes | -| `BODY_WAIT_MS` | ms | 100 | `runtime.ts` | max wait for a delivery's body before deciding salience without it | +| `BODY_WAIT_MS` | ms | 100 | `runtime.ts` | max wait for a delivery's body before deciding salience without it (background fetch deliveries: also cut at their chain's first write) | | `DECISIONS_KEPT` | number | 200 (explainMap 400) | `runtime.ts` | `decisions()`, `interventions()`, explain retention | | `LONG_RUNNING_MS` | ms | 10,000 | `runtime.ts` | cap on mutation `defer` (`waitRelated`) and delivery `defer` (`waitOps`) waits | -| ancestor search depth | number | 16 | `runtime.ts` -> `covered`, `dropFilter`, `onDropped` (literals) | how far up a write's chain a delivery / discard mark is looked for | +| ancestor search depth | number | 16 | `runtime.ts` -> `covered`, `dropFilter`, `onDropped`, `finalizeDeliveries` (literals) | how far up a write's chain a delivery / discard mark is looked for | | `WINDOW_MS` | ms | 60,000 | `report.ts` | console dedupe window | | rate-limit warning interval | ms | 60,000 | `runtime.ts` -> `onDecision` (literal) | at most one rate-limit status line per minute | | `COALESCE_MAX_WAIT_MS` | ms | 8,000 | `observe/fetch.ts` | coalesce wait for the shared response | @@ -670,9 +714,14 @@ Notes: order, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS`, `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `PASSIVE` are model input and are mirrored in `training/curriculum/rt.py` (header "FROZEN at git tag `situation-v2`") and the sim. `ActionRecord.changed` and the `dropped` event text are also model input (timelines). No file under - `situation/` or `decide/` changed between `situation-v2` and b435acb. + `situation/` or `decide/` changed between `situation-v2` and b435acb; since then only `situation/content.ts` + (f107013: F2 typed-text diffs go through `state/fields.ts` -> `redactedStringDiff`), which changes redacted + rendering, not model wording. - **Default mode cannot act.** In observe mode `permittedActions` is empty, so `waits` is always false and no gate - `run` exists; only detections are reported. Tests that exercise actions get guard from `test/helpers.ts` -> + `run` exists; only detections are reported. Deliveries are never held or delayed there (released synchronously, + before any body read; XHR listeners and push messages run inside the original dispatch), but a salient or + forced delivery is still decided in the background (one `Decision`, when the provider is `ready` and `trigger`'s + triage keeps it). Tests that exercise actions get guard from `test/helpers.ts` -> `setup()`; `test/default-mode.test.ts` asserts the product default. - **No hold when the model is late.** `expectedLatency()` > budget (e.g. `warmupMs` 2,000 with an 800 ms max budget, or a stuck provider) means nothing waits, even in guard mode (`test/delivery.test.ts` "does not hold when @@ -687,9 +736,16 @@ Notes: - **Holds can outlast the budget after a decision:** `coalesce`, `delay` (≤ 8 s), `retry` (≤ 5 s), delivery `defer` (≤ 10 s, then a second decision) and custom actions (unbounded) keep the subject waiting. - **Custom actions run late.** Unlike built-ins they are not nulled when the subject already proceeded (a custom - action may act after a write applied); only `ctx.builtin` refuses then. -- **Covered writes skip the mutation trigger** only when the delivery was decided before release; a delivery - released by budget expiry or in observe mode leaves its writes to background `mutation` decisions. + action may act after a write applied); only `ctx.builtin` refuses then. Exception: a delivery already released + only ever takes the passive action. +- **Covered writes skip the mutation trigger** when the delivery was decided before release or is a background + delivery decision (pending or done: observe, `discard` restricted). A held delivery released by budget expiry, a + guard/heal delivery released because the model is too slow, a dropped background decision (deadline, queue + overflow), and a fetch delivery cut at its first write with only pending/typed conflicts all leave their writes to + their own `mutation` decisions. +- **Background delivery analysis must read the pre-delivery state.** The decision is built on the state the delivery + was released into: `bodyNow` analysis runs before the listeners; fetch analysis is cut at the chain's first + `proposed` write (`finalizeDeliveries`). Keep `deliveryPending.add` before the passive action in `trigger`. - **Runtime timeout does not cancel the provider.** A late answer from an abandoned call is still cached and its latency still sampled; it also clears `stuck`. - **Determinism:** only the injected `Clock` is used (timers, `now`, body wait, discard mark); ids are counters. Do @@ -707,7 +763,7 @@ Notes: Light local checks are allowed on this machine (see [build-test-release.md](build-test-release.md)): `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts` in -`packages/runtime` (lead's run at b435acb: 332 passed, 14 skipped), then `test/review-perf.test.ts` alone (flaky under +`packages/runtime` (run on `mvp-v2-merge` at f107013, 2026-10-08: 44 files passed, 1 skipped; 375 tests passed, 14 skipped), then `test/review-perf.test.ts` alone (flaky under parallel load). CI (`.github/workflows/ci.yml`) runs the same split. Do not run Playwright, the sim, realapps or demos eval without asking. @@ -723,7 +779,9 @@ eval without asking. 4. **Change the delivery gate:** `runtime.ts` -> `runDelivery`, `dropFilter`, `writtenOver`, `onDropped`; channel plumbing in `observe/fetch.ts`, `observe/xhr.ts`, `observe/messages.ts`; salience in `situation/conflicts.ts` / `content.ts`. Salience changes alter which situations exist (sim/training data): coordinate with SIM/TRAIN. - Tests `test/delivery.test.ts`, `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts`. + Background (non-holdable) deliveries: `deliveryHoldable`, `writesCanAct`, `finalizeDeliveries`, `covered`, + `trigger` (`background`, `deliveryPending`). Tests `test/delivery.test.ts`, `test/observe-delivery.test.ts`, + `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts`. 5. **Change an action's mechanics:** edit its controller. Keep: throw when it cannot run; return an exact `changed` sentence; provide `undo` only if truly reversible; end synthetic ops with `synthetic: true`. Coordinate `changed` wording with SIM (timeline input). Tests: `test/fetch.test.ts`, `test/xhr.test.ts`, `test/atoms.test.ts`, @@ -753,9 +811,10 @@ eval without asking. | Test file | What it asserts (scope-relevant) | |---|---| | `packages/runtime/test/delivery.test.ts` | typeahead makes zero model calls; stale out-of-order response -> delivery `discard` drops only the stale field; hold is only latency; no hold when the model cannot answer in time; default: read-after-write, background late revert, slow model (released at budget, writes late-reverted), superseded queued decision dropped; WebSocket order + discard; EventSource custom types; XHR held before completion listeners, abort during hold; forced actions | -| `packages/runtime/test/default-mode.test.ts` | `createRuntime` / `GenClass.init` default to observe (`?genclass=guard` opts in); observe never holds or delays even with a sure model or a model that never answers; findings still reported | +| `packages/runtime/test/default-mode.test.ts` | `createRuntime` / `GenClass.init` default to observe (`?genclass=guard` opts in); observe never holds or delays even with a sure model or a model that never answers; findings still reported (mutation, request and delivery decisions) | +| `packages/runtime/test/observe-delivery.test.ts` | observe mode: a conflicting fetch response with a slow body resolves at network time, its background decision is recorded/reported and its writes are not decided again; the decision sees the pre-delivery state; an app write before the body is read decides the delivery at that write; F1 (pending change put back) is not lost; standing questions on delivery answered; XHR listeners run inside the original dispatch after body analysis; WebSocket/EventSource messages delivered synchronously and in order, still decided; guard mode unchanged (stale response held, slow model -> writes late-reverted, forced question decides without acting) | | `packages/runtime/test/no-reorder.test.ts` | an always-passive model changes nothing in any mode/triage (same dispatches, order, state); `holdWrites` never reorders a store's dispatches | -| `packages/runtime/test/policy.test.ts` | gate: mass split, mode tiers, thresholds with exact reasons, `requireDiagnosis`, deny/allow, pause, rate limit, observe never holds, `setMode`, `pause/resume`, loading fails open | +| `packages/runtime/test/policy.test.ts` | gate: mass split, mode tiers, thresholds with exact reasons, `requireDiagnosis`, deny/allow, pause, rate limit, observe never holds (writes, requests and responses; delivery decided in the background), `setMode`, `pause/resume`, loading fails open | | `packages/runtime/test/report.test.ts` | line formats (held discard with `holdWrites`; default -> `Reverted a stale write …` late revert), `explain()`, console groups, ×N summary, listeners | | `packages/runtime/test/atoms.test.ts` | (all with `holdWrites: true`) holds, fail-open at budget, late revert text and undo, refusals incl. `too late to revert` recorded as a reason, user write never overtakes a held write, read-your-writes, provider error codes fail open, discard + undo, defer max 2 | | `packages/runtime/test/budget.test.ts` | `holdBudget` values; adaptive budget; `timeoutMs` = budget + 2,000 for held writes and = budget for requests; expired items never computed; situation budget 2,400 (webgpu) | @@ -813,7 +872,7 @@ Open items (from `HANDOFF.md`, `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `d proposals are in `sim/NEEDS.md` ("Situation-v2 fact proposals from the separability analysis"). Whether a trained v2 model separates `discard` from `deliver` is unmeasured. - Slow single-thread WASM: with `expectedLatency` over the budget nothing is held; writes rely on late revert - (≤ 2 s) and deliveries are decided too late to act. + (≤ 2 s) and, in guard/heal, deliveries are released undecided (decided only when forced: an `always` standing question or `triage: "always"`). - Code-reading follow-ups (unverified at runtime): late answers after a runtime timeout still feed the cache and latency samples; custom actions can hold a subject indefinitely and can run after it proceeded. diff --git a/docs/agents/runtime/learn-situation-triage.md b/docs/agents/runtime/learn-situation-triage.md index f57155a1..32cc5747 100644 --- a/docs/agents/runtime/learn-situation-triage.md +++ b/docs/agents/runtime/learn-situation-triage.md @@ -15,14 +15,24 @@ > descriptions, diagnosis labels), the triage rule (what is salient), the delivery gate, the situation budget or > section limits, redaction, the latency/error/rate/cadence baselines, or transition profiles; or when you need to know > why a trigger did or did not reach the model. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR - **Every byte here is model input, and the format is frozen.** The current training format is git tag - `situation-v2` (commit 6e5e86e, "Runtime batch 5 … freeze situation-v2"). `git diff situation-v2 b435acb -- - packages/runtime/src` touches only `runtime.ts` (default mode), `types.ts` and `devtools/index.ts`; nothing in - `src/situation/`, `src/learn/`, `util.ts` or `state/fields.ts` changed after the freeze. Producers of training rows + `situation-v2` (commit 6e5e86e, "Runtime batch 5 … freeze situation-v2"). `git diff situation-v2 HEAD -- + packages/runtime/src` touches `runtime.ts` (default mode f3636b2; background deliveries 054da38, §4-§5; the + purity fix to `recentErrors` 29b7f28), `types.ts` and `devtools/index.ts` (default-mode comments and labels), + `trace/ops.ts` (`OpRegistry.peekNextId`, for tests), `observe/messages.ts` (`bodyNow`) and `observe/xhr.ts` + (`body.now`), the install entries (`auto.ts`, `cdn/*`) and the redaction fix (commit f107013, §12): + `situation/content.ts` (F2), `state/fields.ts` (`redactedStringDiff`) and `util.ts` (`isSensitivePath`). The + redaction fix is the only change to what a given state renders to, and only for values the redactor hides; + everything else renders byte-for-byte as at the freeze. 054da38 changes when a delivery that cannot be held + (observe mode, no permitted action, model not ready or too slow) is released, analysed and decided, not the text; + the sim and realapps' recorded (non-`ideal`) runs default to `mode: "heal"` with `holdBudgetMs: 1e9` and a ready + decider, so their deliveries stay holdable (`sim/src/run/rt.ts` -> `createOptions`, + `realapps/src/world/index.ts` -> `__GENCLASS_INIT__`). Nothing in `src/learn/` + changed. Producers of training rows run this exact code: the sim (`sim/src/run/rt.ts` -> `realRuntimeFactory`), the real-browser corpus ([realapps](../realapps.md)) and the hand-written Python port `training/curriculum/rt.py` (its docstring says "FROZEN at git tag `situation-v2`"). No situation-v2 model exists yet ([HANDOFF.md](../../../HANDOFF.md), `training/NEEDS.md`); the old @@ -58,7 +68,9 @@ `MIN_BUDGET = 500`. "auto": WebGPU or unknown device 2400; WASM 1000/1333/1667/2000 for 1..4+ threads; x0.8 per `max_tokens_exceeded`, floor 0.5 (2400 -> 1920 -> 1536 -> 1229 -> 1200). - **Deterministic and almost side-effect free**: only the injected clock is read; the only write inside fact code is - `X.reads.set(path, vStart)` (the gate itself sets `op.delivery`, marks and buffers; see Invariants). + `X.reads.set(path, vStart)` (the gate itself sets `op.delivery`, marks and buffers; see Invariants). Building a + situation consumes no op ids, events, decisions or timers (`test/situation-purity.test.ts`); `SitEnv.recentErrors` + only filters, pruning happens when an error is recorded. ## Files @@ -76,9 +88,9 @@ | `packages/runtime/src/situation/build.ts` | subject sentence, sections, applicable actions, questions, salience | `buildSituation`, `subjectOf`, `subjectRef`, `relatedInFlight` (new), `isTrigger` (unused), `BuildOptions`, `BuiltSituation`, `ActionOption`; internal `subjectOp`, `involvedStores`, `involvedFields`, `builtinApplicable`, `revertableChain`, section builders | | `packages/runtime/src/situation/questions.ts` | action catalogue, per-trigger actions and descriptions, diagnosis vocabulary | `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `ACTION_INSTRUCTIONS`, `TRIGGER_DESCRIPTIONS` (new), `DIAGNOSIS_INSTRUCTIONS`, `DEFAULT_DIAGNOSES`, `COMPACT_QUESTIONS_BUDGET`, `diagnosisVocabulary`, `actionDescription`, `buildQuestions` | | `packages/runtime/src/situation/serialize.ts` | budget-shaped Jev state | `toJevState`, `sectionLimits`, `stateChars`, `stateText`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `MIN_BUDGET`, `LIMITS` | -| `packages/runtime/src/runtime.ts` (parts) | owns `Baselines`/`Profiles`/`Cadence`, feeds them, implements `SitEnv`, runs the delivery gate and triage, sets stale marks | `RuntimeImpl.trigger`, `runDelivery`, `observeWrite`, `gateMutation`, `mutationController`, `covered`, `expectedLatency`, `noteResponse`, `onChannel`, `markWrites`, `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `settled`, `situationBudget`, `buildOpts`, `makeEnv`, `startOp`/`endOp`/`onApplied`/`watchStall` | +| `packages/runtime/src/runtime.ts` (parts) | owns `Baselines`/`Profiles`/`Cadence`, feeds them, implements `SitEnv`, runs the delivery gate and triage, sets stale marks | `RuntimeImpl.trigger`, `runDelivery`, `deliveryHoldable`, `writesCanAct`, `finalizeDeliveries`, `observeWrite`, `gateMutation`, `mutationController`, `covered`, `expectedLatency`, `noteResponse`, `onChannel`, `markWrites`, `dropFilter`, `writtenOver`, `onDropped`, `waitOps`, `settled`, `situationBudget`, `buildOpts`, `makeEnv`, `startOp`/`endOp`/`onApplied`/`watchStall` | | `packages/runtime/src/util.ts` (parts) | formatters and redaction | `secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `defaultRedact`, `isSensitivePath` (new), `isSensitiveName`, `words`, `REDACTED`, `Redactor`, `kindOf`, `normalizeFieldPath`, `requestSignature`, `normalizePath`, `isIdSegment`, `parseUrl` | -| `packages/runtime/src/state/fields.ts` (parts) | change sentences ([state-and-adapters](state-and-adapters.md) owns it) | `changeText`, `stringDiff` (new), `elementDiff`, `addedElements`, `normalizeLeafKind` | +| `packages/runtime/src/state/fields.ts` (parts) | change sentences ([state-and-adapters](state-and-adapters.md) owns it) | `changeText`, `stringDiff` (new), `redactedStringDiff` (redaction fix), `elementDiff`, `addedElements`, `normalizeLeafKind` | | `packages/runtime/src/state/hub.ts` (parts) | stale marks on fields | `FieldState.mark`, `StaleMark`, `StoreHub.markField` (cleared by the next write) | | `packages/runtime/src/index.ts` | public re-exports from this area | `stateText`, `stateChars`, `sectionLimits`, `STATE_CHAR_BUDGET`, `COMPACT_BUDGET`, `BUILTIN_ACTIONS`, `TRIGGER_ACTIONS`, `PASSIVE`, `DEFAULT_DIAGNOSES` | @@ -107,7 +119,7 @@ Public types in `packages/runtime/src/types.ts`: `TriggerKind` (now with `delive | pending local change | `Conflict { kind: "pending" }` from `pendingConflict(env, X, path, now)`: in the last 10 s (`PENDING_WINDOW_MS`) a chain rooted at a user op (not X's root) wrote the field, and a non-user op of that root with a name different from X's is in flight (`x` null: any name). | | delivery spec | `DeliverySpec { op, channel, req?, status?, message?, predicted, matched, conflicts, defers, queuedAhead, body?, content? }` (`env.ts`). | | `op.delivery` | set by `runDelivery` on the op: `{ patterns, known, salient, decided, overNewer? }`; read by `covered` (skip `mutation` triggers for covered writes) and `markWrites` (F9 "delivered over newer data"). | -| covered write | `RuntimeImpl.covered(m)`: walking up to 16 causes from `m.cause`, the first op with `op.delivery`: covered iff P was known, every changed path is in P (raw or normalised), and the delivery was not salient or was decided in time. Never covered with `triage: "always"`. | +| covered write | `RuntimeImpl.covered(m)`: walking up to 16 causes from `m.cause`, the first op with `op.delivery`: covered iff P was known, every changed path is in P (raw or normalised), and the delivery was not salient, was decided in time, or has a background decision pending (`deliveryPending`, observe or no permitted action; since 054da38). Never covered with `triage: "always"`. | | content comparison | `Cmp` (`content.ts` -> `compareField`): incoming vs current value by value hash, the value when X started (if the 16-entry history covers it), other chains' writes since X, `revertOf` (newest such write whose replaced value equals the incoming one), typed-text writes (`user`), and `items` (`ItemCmp`, list joined on `id`/`_id`/`uuid`/`slug`/`key`). | | stale mark | `StaleMark { t, op, why }` on `FieldState.mark`, set by `RuntimeImpl.markWrites` / `onChannel`, cleared on the next write; stated by F9 (`markFacts`). | | cadence | `CadenceInfo`: `periodic { period, intervals, last, next }` or `debounced { delay, matching, of }` (`Cadence.get`). | @@ -247,21 +259,26 @@ The profile is now model input twice: transition facts (T1) and the delivery pre any) x (1 + decisions waiting) + the one computing (at least its elapsed time); `Infinity` while `queue.stuck`. If not waiting, passive runs now and the decision is made in the background (deadline 5 s). In the default `observe` mode (commit f3636b2, `o.mode ?? "observe"`) no action is permitted, so nothing is ever held; salient - situations are still built and decided in the background for detection, except `delivery`: its candidates still - wait up to `BODY_WAIT_MS` (100 ms) for the body (`runDelivery` ignores the mode), then `passive()` sets - `released`, and `DeciderQueue` drops the background decision as stale (`ctl.stale = () => released`), so in - observe mode delivery situations never reach the model and produce no detections (same in guard whenever a - delivery does not wait). + situations are still built and decided in the background for detection. A `delivery` that does not wait (commit + 054da38): if its chain's writes can still act on their own (`writesCanAct`: discard permitted, not paused, i.e. + guard/heal with a model too slow to hold for), it is passive and not decided unless forced or `triage: "always"`; + otherwise (observe, no permitted action) its op goes into `deliveryPending` before `passive()` and the + background decision covers its chain's predicted writes (`covered`) until it returns. 7. Submit to the decider queue with `ctl.stale` (queued decisions whose subject was superseded are dropped before - the model sees them). Gate/apply: [decide-policy-actions](decide-policy-actions.md). + the model sees them), except for a `delivery` that does not wait: its controller is stale as soon as it is + released, so it gets no stale check and is still decided (detection, reports, standing questions); `onDecision` + only records it (a released delivery can only take the passive action). Gate/apply: + [decide-policy-actions](decide-policy-actions.md). `ask` bypasses `trigger()`. `rt.situation(trigger?)` returns `lastBuilt[trigger]` or an "ask about now" situation relabelled with the trigger. ### 5. The delivery gate (`RuntimeImpl.runDelivery`) -Called with `{ op, channel, req?, status?, message?, queuedAhead?, body? }` and a `release` callback (lets the -response/message through). Holding is only latency; the response object is unchanged. +Called with `{ op, channel, req?, status?, message?, queuedAhead?, body?, bodyNow? }` and a `release` callback +(lets the response/message through). Holding is only latency; the response object is unchanged. `bodyNow` is the +body read synchronously when it is already in memory (WebSocket/EventSource `MessageGate`, XHR `body.now`; fetch +has none). 1. Not consultable, paused, destroyed or a GenClass op -> release. 2. `predicted = predictedWrites(env, op)`, `matched = matchFields(env, predicted.patterns)`, `conflicts = conflictsOn(env, op, matched, now)` (per field: newer conflict, else pending conflict; newer first). @@ -269,6 +286,14 @@ response/message through). Holding is only latency; the response object is uncha 4. `typed` = matched string fields that a user write (outside the op's chain) changed since the op started. `always` = `triage: "always"` or an `always` standing question on `delivery`. 5. No conflict, nothing typed, not `always` -> release (no body read, no latency). +5b. Background delivery (commit 054da38): when `deliveryHoldable(op, matched, defers)` is false (observe mode, + paused, decider not `ready`, no permitted non-passive delivery action or permitted custom action, or + `expectedLatency() > holdBudgetMs()`), the delivery is released now, before any body read. Steps 6-8 still + run, but settling marks `overNewer` and, if salient or `always`, calls `trigger(spec, ctl, { hold: false, + priority: 2 })` (decided for detection only). A `bodyNow` body is analysed synchronously; otherwise the body + wait is cut short when the delivery's chain is about to write (`finalizeDeliveries` from the hub's `proposed` + hook): with a newer conflict or `always` it is decided without the body, else it is marked salient and left + undecided, so its writes get their own `mutation` decisions. 6. No body reader -> salient iff a newer conflict exists. 7. Else read the body (`o.body()`: fetch's buffered clone or XHR text/response; messages' data), wait at most `BODY_WAIT_MS = 100` (clock time; on timeout decide as in 6). With a body: `spec.content = analyzeBody(env, op, @@ -278,8 +303,8 @@ response/message through). Holding is only latency; the response object is uncha - a typed field the body would change (F2). All conflicts equal to the body -> custom event `delivery.unchanged` (shows in the timeline as `event delivery.unchanged`). Analysis throw -> logged, decide as in 6. -8. Not salient and not `always` -> release. Else `trigger(spec, ctl, { hold: true, priority: 2 })` (which runs the - cheap pass again on `computeFacts`). +8. Holdable delivery: not salient and not `always` -> release. Else `trigger(spec, ctl, { hold: true, priority: 2 })` + (which runs the cheap pass again on `computeFacts`). Controller: `passive` releases; if released over salient conflicts it records `op.delivery.overNewer` (used by F9). `discard`: releases now and sets `op.discardMark = { protect: conflicting paths, until: now + 10 s }`; while the mark @@ -336,7 +361,8 @@ events `event ws.message <summary> (#id)` / `event sse.message …`, `event deli `action` lines from delivery `discard`/`defer` and drops. `changeText(c, redact)` (`state/fields.ts`) gained one branch before the generic `<describe 36> → <describe 36>`: -two strings whose redaction leaves them unchanged and at least one longer than 30 chars use `stringDiff`: both sides +two strings whose redaction leaves them unchanged (`redactedStringDiff`, shared with F2 since commit f107013) and +at least one longer than 30 chars use `stringDiff`: both sides previewed from 14 chars before the first difference, 30 chars wide, plus `(removes "…")`, `(inserts "…")` or `(replaces "…" with "…")` (each <= 28 chars). Example asserted in `test/content.test.ts`: `"…e sword shield market lib" → "…e sword shield" (removes " market lib")`. This changes timeline write summaries, M15 deltas and I2 too. @@ -435,7 +461,7 @@ equal. | F1 item cell | versions | yes | `<S> would put back <key> = <v> for item <id> of <path>[ and N more cells]: the store has <cur>, changed since #X started; delivering (applying) it would undo that change.` | | item newer-same | versions | no | `The newer writes to <path> changed only N item(s) (<ids>); this response's copy of it/them equals the store.` | | item join delta | delta | no | `Joined by <idKey> with <path>, <s> would change N cell(s) in M item(s), add …, remove ….` | -| F2 | versions | yes | `<S> would replace text the user typed into <path> after #X started (N user write(s), the last <secs> ago): <stringDiff text or a → b>.` | +| F2 | versions | yes | `<S> would replace text the user typed into <path> after #X started (N user write(s), the last <secs> ago): <stringDiff text or a → b>.` The diff comes from `redactedStringDiff` (only when both values pass the redactor unchanged), else both sides go through `describe()` (`[redacted] → [redacted]`, or a custom redactor's replacement); before commit f107013 it diffed the raw strings and leaked characters of a redacted field. | | F1 field | versions | yes | `<S> has <path> = <v>, the value that <writer> replaced with <v'> <secs> ago[ (it started after/before #X)]; delivering (applying) it would put the older value back.` | | third value | versions | no | `<S> has <path> = <v>: neither the current value <cur>[, nor the value when #X started].` | | F3 | delta | no | `<S> matches the current values of everything it is predicted to write (<list>): delivering it changes nothing.` or `<S> has the current value of <list>.` | @@ -560,22 +586,35 @@ line limits are computed from the formula. A budget above 2400 keeps full sectio ### 12. Redaction -`defaultRedact` now uses `isSensitivePath(path, value)` (`util.ts`), batch 5: +`defaultRedact` now uses `isSensitivePath(path, value)` (`util.ts`), batch 5, plus the post-0.1.0-alpha.1 fix +(commit f107013, `packages/runtime/STATUS.md` "Fix after 0.1.0-alpha.1: two redaction leaks"): - Never secret: `null`, `undefined`, booleans; plain objects (judged key by key, never redacted whole). - Not a dotted path (free text such as `input "Card number"`, header lines) -> `isSensitiveName` on its words. - Array-index segments are skipped (`users.3.password`). The **leaf** segment decides (`isSensitiveName`), or a secret pair across the last two segments (`payment.card.number`). -- A non-leaf container that names a secret: strings under it are secret if the container is not "broad"; under a - broad container (`auth`, `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: +- A non-leaf container that names a secret: strings, numbers, bigints and arrays under it are secret if the + container is not "broad" (`payment.cvv.value = 123`, `login.otp.code`, `lock.pin.value`, + `account.password.history = [...]`; before the fix only strings); under a broad container (`auth`, + `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: >= 20 chars of letters, digits and `_-.+/=:`, containing both a letter and a digit) are secret. - A store holding a primitive is judged by its name (its name is the leaf). The container rule above also covers the store segment: a broad store name never redacts its fields (`auth.loading`, `auth.user.name` visible), but a - store or container named by a non-broad secret word (`token`, `secret`, `password`, ...) redacts every string leaf - under it (`credentials.password.value`). Numbers are only redacted by the leaf or pair rule. The code comment + store or container named by a non-broad secret word (`token`, `secret`, `password`, ...) redacts every string, + number, bigint and array leaf under it (`credentials.password.value`). Side effect: numbers under a container + that is a secret word in another sense are hidden too (`map.pin.lat`, `boarding.pass.seat`). The code comment ("never by the store's or a container's name alone") describes the broad case only. +- Known gaps (unchanged, they would change other model-visible text): a container named by a secret pair + (`cardNumber`, `apiKey`, `creditCard`) counts as broad, so `payment.cardNumber.value` is shown; the "is back to V" + fact (`situation/facts.ts`) compares rendered text, so two different redacted values read as "back to + [redacted]". `isSensitiveName` (word lists `SECRET_WORDS`, `SECRET_PAIRS`) is unchanged but now memoised (`nameCache`, cleared above 4096 entries). `describe` and `redactSearch` compare with `Object.is`. A custom `redact` option replaces the -default everywhere; `opts.describe` output bypasses it. +default everywhere; `opts.describe` output bypasses it. Every diff-centred string preview (`changeText`, F2) goes +through `state/fields.ts` -> `redactedStringDiff`, so a redacted value is never diffed. +Training parity: sim and realapps rows are rendered by the runtime and follow automatically; the Python port +`training/curriculum/rt.py` has no redactor at all and was not changed (secret-looking curriculum names such as +`iban`, `pin`, `pass` print in the curriculum but render as `[redacted]` in the runtime; a curriculum follow-up, +see `packages/runtime/STATUS.md`). ### 13. Device-sized situations (`RuntimeImpl.situationBudget`) @@ -742,9 +781,9 @@ stall, inconsistency, transition and error. runtime's buffered clone). - **No store holds by default.** `mutation` is non-blocking (priority 1, background, 5 s deadline); discard is a late revert (<= 2 s, fields unchanged since). Writes covered by a delivery decision raise no `mutation` at all, except - with `triage: "always"`. M13 and `defer` only mean something with `holdWrites: true`. Caveat: delivery candidates - still wait up to 100 ms for the body, and in observe mode their background decision is dropped as stale before - reaching the model (see §4 step 6). + with `triage: "always"`. M13 and `defer` only mean something with `holdWrites: true`. Since commit 054da38 a + delivery that cannot be held (observe mode included) is released synchronously before any body read, and its + background decision reaches the model and is recorded (§4 steps 6-7, §5 step 5b; `test/observe-delivery.test.ts`). - **Newer same-signature request in flight neutralises newer-data conflicts** (`newerSameSignature`, fetch/XHR only): in-order typeahead and autosave make zero model calls; the in-flight request is still stated (M6, neutral). - **A plain user write is not a conflict.** Only a user-rooted write whose request of another signature is in flight @@ -756,7 +795,10 @@ stall, inconsistency, transition and error. content facts uninformative but not false. Ambiguous bodies produce no content facts. - **Side effects of the gate (outside fact code).** `runDelivery` sets `op.delivery` and, through the controller, `op.discardMark`; `markWrites` and `onChannel` set field marks; `noteResponse` parses create bodies in the - background. Fact code itself still writes only `X.reads`. `rt.situation()` stays side-effect free (tested). + background. Fact code itself still writes only `X.reads`. `rt.situation()` stays side-effect free (`test/situation-purity.test.ts`: probes for every trigger kind + from handlers, timers, fetch continuations, message dispatch and tasks, and devtools-style polling, change no op + id, event, decision, timer or provider call). Keep `SitEnv` callbacks read-only (`recentErrors` used to prune + `errorsRecent` while building; since 29b7f28 that happens in `RuntimeImpl.reportError`). - **Determinism.** Read time only from `env.now()`; body reads and create parsing are promise-based but timed by the injected clock (`BODY_WAIT_MS` uses `clock.setTimeout`). Tests assert byte-identical situations (`situation.test.ts`, `budget.test.ts`). @@ -780,7 +822,9 @@ stall, inconsistency, transition and error. `SitEnv.writtenByChain`, `isTrigger`, `SigCadence.userStarts`. - **Past bugs fixed (keep fixed):** batch 3 items (direction of "started after/before", real failure counts, 512-entry version log, "is back to", no `= undefined`, empty/non-empty array kinds, digit keys -> `:id`, word-level - redaction); NaN store values no longer recurse forever (commit ad24804, `test/nan.test.ts`). + redaction); NaN store values no longer recurse forever (commit ad24804, `test/nan.test.ts`); F2 never diffs a + redacted value and strong secret containers hide numbers/bigints/arrays (commit f107013, + `test/redaction-v2.test.ts`); situation building prunes nothing (commit 29b7f28, `test/situation-purity.test.ts`). ## How to change it safely @@ -831,7 +875,9 @@ packages/runtime/src/situation`. also drive delivery prediction (`predictedWrites`). **Change redaction**: `isSensitivePath`/`isSensitiveName`/`SECRET_WORDS`/`SECRET_PAIRS`/`WEAK_CONTAINER`/`OPAQUE` in -`util.ts`; update `test/batch3.test.ts` (auth store), `test/review-redaction.test.ts`, API.md "Privacy". +`util.ts`, `redactedStringDiff` in `state/fields.ts`; update `test/batch3.test.ts` (auth store), +`test/review-redaction.test.ts`, `test/redaction-v2.test.ts`, API.md "Privacy". Any new diff or preview of a field +value must go through the redactor first (use `redactedStringDiff`). **Change timeline or action-effect wording**: `eventLine` (`describe.ts`), `changeText`/`stringDiff` (`state/fields.ts`), effect strings in `runtime.ts` (`runDelivery` discard/defer, `onDropped`) and observers, @@ -851,11 +897,14 @@ also drive delivery prediction (`predictedWrites`). | `packages/runtime/test/atoms.test.ts` | runs with `holdWrites: true`: held writes never reordered, read-your-writes | | `packages/runtime/test/learn.test.ts` | baselines and profiles (unchanged) | | `packages/runtime/test/review-precision.test.ts`, `review-redaction.test.ts`, `review-hub.test.ts`, `review-fetch.test.ts`, `review-actions.test.ts`, `invariants.test.ts`, `plugins.test.ts`, `ask.test.ts`, `dom.test.ts`, `devtools-runtime.test.ts`, `nan.test.ts` | as before (precision, custom redactor, version counts past 16 entries, direction texts, error facts, plugin facts, ask sentences, error fact text, devtools Now view); `dom.test.ts` adds `untrustedEvents` and shadow-DOM descriptions; `nan.test.ts` the NaN fix | - -Full unit run on mvp-v2 at b435acb (lead, 2026-10-08): 40 files passed + 1 skipped, 332 passed + 14 skipped, plus -`review-perf` alone 4 passed (see [build-test-release](build-test-release.md)). An uncommitted working-tree change -(`state/hub.ts` ignores a held-write verdict after the write is `done`, plus one test in `atoms.test.ts`) would make -it 333 + 14 once committed (see [state-and-adapters](state-and-adapters.md)). +| `packages/runtime/test/redaction-v2.test.ts` (10, new, commit f107013) | F2 on a secret field renders `[redacted] → [redacted]` with the default redactor and the replacement with a custom one, never characters of the raw text; an unredacted field keeps the diff-centred preview; `redactedStringDiff` returns null unless both sides pass the redactor; strong secret containers hide numbers, bigints and arrays (booleans/null/undefined visible, plain objects judged key by key); broad containers and unrelated paths unchanged; `changeText` and `describe()` hide those values | +| `packages/runtime/test/situation-purity.test.ts` (2, new, commit 29b7f28) | a mixed app raising every trigger kind (`triage: "always"`), probed with `situation()`, `situation(kind)` and from-scratch rebuilds inside handlers, timers, fetch continuations, message dispatch and tasks: next op id (`OpRegistry.peekNextId`), op count, event seq, decisions, interventions, in-flight count, hub seq, timers and provider calls unchanged, and the whole run identical with and without probes; devtools-style polling (`situation`, `inflight`, `explain`, `interventions`, `history` on every `setImmediate` turn of `test/browser/ui/session.ts` -> `runStoreSession`) changes no decision, intervention, op or event | +| `packages/runtime/test/observe-delivery.test.ts` (11, new, commit 054da38) | observe: a conflicting fetch response with a slow body resolves at network time and is decided once in the background on the state it was delivered into; an app write before the body is read decides it at that write; F1 is not lost; standing questions on `delivery` answered; XHR body analysed before the listeners run; WebSocket/EventSource messages delivered synchronously and in order, still decided; guard: stale response held and discarded, a too-slow model releases at once and the write is late-reverted on its own | + +Full unit run on `mvp-v2-merge` (f107013, 2026-10-08, `npx vitest run` in `packages/runtime`, no model +directory): 45 files passed + 1 skipped, 379 passed + 14 skipped (393), `review-perf` included (see +[build-test-release](build-test-release.md)). The earlier mvp-v2 run at b435acb was 40 + 1 files, 332 + 14 tests; +the uncommitted `state/hub.ts` held-write-verdict change mentioned there is not in this branch. ## Drift and open issues diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md index 708d8bd2..1c771fe3 100644 --- a/docs/agents/runtime/model-host.md +++ b/docs/agents/runtime/model-host.md @@ -1,16 +1,16 @@ # @genclass/runtime: model host (worker, loader, backends, engine, packer, calibration, CLI) -> **Scope:** `packages/runtime/src/model/*.ts` (backend, calibrate, engine, errors, hash, host, index, loader, packer, protocol, pyutil, serialize, tokenizer, worker), `packages/runtime/src/model/README.md` (internal notes), `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/MODEL_CARD.md`, the `worker` entry of `packages/runtime/tsup.config.ts`, and the model sections (§2 `model` options, §8 `DecisionProvider`, §10, §13) of `docs/runtime/CONTRACT.md`. -> **Read this when:** you change how the model is downloaded, cached, verified or run; touch the worker or its message protocol; change WebGPU/WASM selection or onnxruntime-web settings; change the tokenizer, packer, Python-parity serializer or calibration; add or change a model error; work on the `genclass-runtime` CLI; debug "model unavailable", "observing only", stuck loads or slow decisions. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/model/*.ts` (backend, calibrate, engine, errors, hash, host, index, loader, packer, protocol, pyutil, serialize, tokenizer, worker), `packages/runtime/src/model/README.md` (internal notes), `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime-model/MODEL_CARD.md`, the model-loading side of the CDN builds (`packages/runtime/src/cdn/ort-env.ts`, `ort-wasm.ts`, `ort-webgpu.ts`, `worker.ts`, and in `src/cdn/global.ts` the `withCdnModel` / `blobModuleWorker` / `assetBase` parts; the rest of `src/cdn/*`, `src/auto.ts` and `bin/lib/*` belong to INSTALL and are covered in [public-api-and-lifecycle.md](./public-api-and-lifecycle.md) and [build-test-release.md](./build-test-release.md)), the `worker` entry and the CDN entries of `packages/runtime/tsup.config.ts`, and the model sections (§2 `model` options, §8 `DecisionProvider`, §10, §13) of `docs/runtime/CONTRACT.md`. +> **Read this when:** you change how the model is downloaded, cached, verified or run; touch the worker or its message protocol; change WebGPU/WASM selection or onnxruntime-web settings; change the tokenizer, packer, Python-parity serializer or calibration; add or change a model error; change how the script-tag (CDN) build starts the model worker or loads onnxruntime-web; work on the `genclass-runtime` CLI (`fetch-model` / `info`); debug "model unavailable", "observing only", stuck loads or slow decisions. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. If this doc and the code disagree, the code wins. > -> **What changed since the previous verification (654d822 = v0.1.0-alpha.0, situation-v1 format; tag situation-v1 = 1a77558), in one line:** nothing under `packages/runtime/src/model/` changed. The changes that matter here are on the runtime side (`runtime.ts`, `decide/decider.ts`, `situation/*`): the default mode is `observe`, decisions moved to the network boundary (`delivery` trigger), store writes are no longer held by default, the automatic situation budget is 2,400 chars, and no trained model matches the v2 situation format yet. One new consumer of the host appeared outside the runtime: the sim's `--on-policy` (DAgger) mode loads it in Node (`sim/src/run/onpolicy.ts` -> `loadModelDecider`, 04a264f). +> **What changed since the previous verification (`mvp-v2` at b435acb), in one line:** still nothing under `packages/runtime/src/model/` changed. New around it: the CDN builds from origin/runtime (f3a9dd1, owner INSTALL): the script tag `dist/genclass.global(.min).js` hands the host its own `workerFactory` (a same-origin Blob-URL module worker that imports `dist/cdn/worker.js` from the CDN) and `ortLoader` (`dist/cdn/ort-webgpu.js` / `ort-wasm.js`, which bundle onnxruntime-web and prepare it for a cross-origin script); see [CDN script-tag build](#2b-cdn-script-tag-build-srccdn-tsupconfigts). The `/auto` entries use the ordinary npm host; the CLI gained `init` / `remove` (`bin/lib/*`, INSTALL). Runtime side (054da38): in `observe` a delivery is released at once and its decision now reaches the host in the background instead of being dropped as stale. None of this is on npm: the published `0.1.0-alpha.1` (806a296) predates the merge, so the CDN builds ship in the next version. ## TL;DR - `createModelHost(opts)` (`packages/runtime/src/model/host.ts`) returns a `ModelHost`, which implements the runtime's `DecisionProvider` seam (`packages/runtime/src/types.ts`). `GenClass.init()` creates one by default in a browser. The runtime only calls `status`, `ready()`, `evaluate()`, `onStatus()` and `dispose()`. - **Fail open, never wait.** `evaluate()` rejects at once with `ModelNotReadyError` (code `not_ready`) unless `status.state === "ready"`. Every provider error makes the runtime run the passive action. While the host is `"loading"` or `"error"`, the runtime does not even build situations. -- **Transport:** inference runs in a module Worker (`dist/worker.js`, built from `src/model/worker.ts`). If the Worker cannot be created, errors before its `hello`, or sends no `hello` within 15 s, the same `ModelBackend` runs inline on the main thread. `worker: false` forces inline. +- **Transport:** inference runs in a module Worker (`dist/worker.js`, built from `src/model/worker.ts`). If the Worker cannot be created, errors before its `hello`, or sends no `hello` within 15 s, the same `ModelBackend` runs inline on the main thread. `worker: false` forces inline. The script-tag (CDN) build swaps in its own worker factory and ORT loader (both on the host's existing injection points `workerFactory` / `ortLoader`): a Blob-URL module worker importing `dist/cdn/worker.js`, and `dist/cdn/ort-*.js` with onnxruntime-web bundled in. The backend and the load sequence are unchanged. - **Load sequence** (`packages/runtime/src/model/backend.ts` -> `ModelBackend.doLoad`): 1. The `model.json` card, fetched in parallel with a WebGPU probe. 2. The plans are computed. @@ -23,8 +23,8 @@ - **Python parity is the contract.** `serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts` and `calibrate.ts` are ports of `jev_local` Python. The model was trained on the Python rendering, so any change here is a model-format change. The situation format (the text CORE builds in `packages/runtime/src/situation/*`, which this module then tokenizes) is frozen at tag `situation-v2` (6e5e86e); `situation-v1` is the old format. The model module itself is identical in v1 and v2. - **No model exists for the current runtime, and none is published.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm (as of 2026-10-08). The only trained runtime model, R17-final1, was trained on `situation-v1` and lives only on the train VM / Mehar's Mac; it does **not** match the v2 runtime. The v2 model comes from the scaled program ([HANDOFF](../../../HANDOFF.md): 150M teacher -> distil R17/R32 -> DAgger -> EVAL -> `@genclass/runtime-model@0.1.0`). The card fetch therefore fails (HTTP 404), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). - **Status:** `off` -> `loading` (phases `card` / `download` / `runtime` / `session` / `warmup`) -> `ready` or `error`; `dispose()` -> `off`. See [Status lifecycle](#status-lifecycle-modelhoststatusstate). The runtime core reads only `state`, `device`, `threads`, `warmupMs`, `model`, `variant`, `loadMs` and `error` (the devtools overlay also shows `progress`); `status.latency` (p50/p90 of the last 20 evaluations) and `host.stats` are for tooling. -- **Default mode `observe` (since f3636b2) still loads and consults the model.** `observe` permits no non-passive action, so nothing is ever held: every salient trigger except `delivery` is decided in the background (priority capped at 1, deadline 5 s), for detection and reports. `delivery` decisions never reach the host: `trigger()` runs `passive()` first, which marks them stale, so `DeciderQueue` drops them; `runDelivery` (no mode check) may still delay a candidate by up to `BODY_WAIT_MS` (100 ms) for the body read. Only `mode: "guard"`/`"heal"` can make the runtime wait for the host. -- **CLI** `genclass-runtime fetch-model <dir>` / `info <dir>` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is a 404 too, so pass `--from`. The file is now committed executable (mode 100755, b435acb). +- **Default mode `observe` (since f3636b2) still loads and consults the model.** `observe` permits no non-passive action, so nothing is ever held: every salient trigger, `delivery` included (since 054da38), is decided in the background (priority capped at 1, deadline 5 s), for detection and reports. A salient delivery is released to the app at once (`runDelivery` -> `deliveryHoldable` is false in `observe`), before any body read, and its background decision is no longer dropped as stale. Only `mode: "guard"`/`"heal"` can make the runtime wait for the host. +- **CLI** `genclass-runtime fetch-model <dir>` / `info <dir>` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is a 404 too, so pass `--from`. The file is committed executable (mode 100755, b435acb). The same binary now also has `init` / `remove` (project setup; `bin/lib/*`, owner INSTALL, not covered here) and runs as `npx @genclass/runtime <command>`. A short-alias package `genclass-runtime` (`packages/genclass-runtime/cli.mjs`, which only imports this file; not on npm yet) is meant to make `npx genclass-runtime <command>` work without a local install. ## Files @@ -46,9 +46,14 @@ | `packages/runtime/src/model/index.ts` | Barrel for the model module (internal; not a package entry point). Nothing in `src/` imports it: the runtime imports `model/host.js` and `model/errors.js` directly. Its only user is the fallback "model-entries" build in `packages/runtime/test/browser/build.mjs`, which uses it as the `index` entry | re-exports everything above **except** `withTimeout`, `StepTimeoutError`, `TimerEnv`, `errorMessage`, `sha256HexSync`, `sha1`, `sha256`, `pyFloatRepr`, `HeadOutput`, `Marker`, `OrtEnvLike`, and the protocol types `ToWorker` / `FromWorker` (`EvaluateOk` is re-exported via `host.ts`) | | `packages/runtime/src/model/README.md` | MODEL's internal notes: card format, load steps, parity results, measured latency and transfer sizes | — | | `packages/runtime/src/index.ts` | Public facade. Re-exports `createModelHost`, `DEFAULT_MODEL_BASE_URL`, the host types and all error classes. Builds the host in `makeHost` | `createRuntime`, `GenClass.init`, `makeHost`, `failedProvider`, `NATIVE_FETCH` | -| `packages/runtime/tsup.config.ts` | Build. Entry `worker: "src/model/worker.ts"` -> `dist/worker.js` (not in `dts.entry`, so no `.d.ts`); `external: ["onnxruntime-web", "onnxruntime-web/webgpu", "react", "redux", "zustand"]`; ESM, `target: "es2022"`, `platform: "browser"`, `splitting: true` (the build output's `worker.js` imports `ModelBackend` from a chunk shared with `index.js`), sourcemaps | — | -| `packages/runtime/package.json` | `exports["./worker"]` -> `./dist/worker.js`; `bin.genclass-runtime` -> `./bin/genclass-runtime.mjs`; dependency `onnxruntime-web ^1.30.0` | — | -| `packages/runtime/bin/genclass-runtime.mjs` | CLI (Node >= 20, no deps): `fetch-model`, `info` | `main`, `fetchModel`, `info`, `parseCard` (JS copy), `scanOnnx` | +| `packages/runtime/src/cdn/global.ts` | Script-tag build (`dist/genclass.global.js` / `.global.min.js`, iife, `window.GenClass`; owner INSTALL). Model side: `withCdnModel` adds `workerFactory: () => blobModuleWorker(<base>cdn/worker.js)` and `ortLoader: build => import(<base>cdn/ort-webgpu.js \| ort-wasm.js)` to `model` (user keys spread after them; skipped when a `decider` is given or `model === false`); `assetBase` picks `<base>` | `assetBase`, `GenClassGlobal` (internal: `blobModuleWorker`, `withCdnModel`, `findScript`, `install`) | +| `packages/runtime/src/cdn/worker.ts` | CDN module-worker entry (-> `dist/cdn/worker.js`). Imports `../model/worker.js` unchanged, plus a `message` listener that copies `load.options.ortWasmPaths` into `cdnState` | (side-effect module) | +| `packages/runtime/src/cdn/ort-env.ts` | Shared by the CDN worker and the ORT wrappers (lands in a shared chunk of `dist/cdn/`). `prepareOrt` points ORT's threaded glue `.mjs` at the onnxruntime-web directory (only in a `crossOriginIsolated` worker with `env.wasm.wasmPaths` unset, the case where a cross-origin ORT would need it) | `cdnState`, `prepareOrt` | +| `packages/runtime/src/cdn/ort-wasm.ts`, `ort-webgpu.ts` | `import * as ort from "onnxruntime-web/wasm" \| "/webgpu"`, `prepareOrt(ort.env, "ort-wasm-simd-threaded.mjs" \| "ort-wasm-simd-threaded.asyncify.mjs")`, re-export everything (-> `dist/cdn/ort-wasm.js` / `ort-webgpu.js`) | (re-exports of onnxruntime-web) | +| `packages/runtime/src/cdn/config.ts` | Page configuration for the script tag and `/auto` (owner INSTALL). Model keys of `<meta name="genclass">` / `data-*`: `model` (a directory URL, or `off` -> `model: false`), `modelurl`/`baseurl`, `device`, `preload`, `ort`/`ortwasmpaths` -> `ortWasmPaths`, `worker` | `fromPairs`, `parsePairs`, `mergeConfig`, `readMetaConfig`, `readWindowConfig`, `fromDataset` | +| `packages/runtime/tsup.config.ts` | Four builds. (1) The ESM library: entry `worker: "src/model/worker.ts"` -> `dist/worker.js` (not in `dts.entry`, so no `.d.ts`); `external: ["onnxruntime-web", "onnxruntime-web/webgpu", "react", "redux", "zustand"]`; `target: "es2022"`, `platform: "browser"`, `splitting: true` (the build output's `worker.js` imports `ModelBackend` from a chunk shared with `index.js`), sourcemaps; `clean` spares `cdn/**` and `genclass.global*`. (2, 3) `globalBuild(false \| true)`: iife, `es2020`, plugin `genclass-ort-external` keeps every `onnxruntime-web(/...)` import external (the host's default inline loader stays as a bare `import("onnxruntime-web/...")` that the script tag never calls), defines `__GENCLASS_VERSION__` from `package.json`. (4) The CDN worker build: entries `worker` (`src/cdn/worker.ts`), `ort-webgpu`, `ort-wasm` -> `dist/cdn/`, ESM, minified, `splitting: true`, `noExternal: [/^onnxruntime-web/]`, plugin `genclass-cdn-ort` maps the model worker's `import("onnxruntime-web/webgpu" \| "/wasm")` (any importer outside `src/cdn/`) to `src/cdn/ort-*.ts`, so the built `dist/cdn/worker.js` does `import('./ort-webgpu.js')` / `import('./ort-wasm.js')` | default export (the four configs); module-local `cdnOrt`, `ortExternal`, `globalBuild` | +| `packages/runtime/package.json` | `exports["./worker"]` -> `./dist/worker.js`; `unpkg` / `jsdelivr` -> `./dist/genclass.global.min.js` (what a bare `cdn.jsdelivr.net/npm/@genclass/runtime` URL serves); `sideEffects` lists `./dist/cdn/*.js`, the global builds, the `/auto` files and `./src/model/worker.ts`; `bin.genclass-runtime` -> `./bin/genclass-runtime.mjs`; dependency `onnxruntime-web ^1.30.0` (1.30.0 in the lockfile, which is what the CDN build bundles) | — | +| `packages/runtime/bin/genclass-runtime.mjs` | CLI (Node >= 20, no deps): `fetch-model`, `info`; `init` / `remove` are dispatched to `bin/lib/init.mjs` -> `run` (INSTALL) before argument parsing | `main`, `fetchModel`, `info`, `parseCard` (JS copy), `scanOnnx` | | `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. Its status line (fcd1e68) reports final round 1 on `situation-v1` and says the next rounds retrain on v2. **The npm package itself does not exist yet** (no `package.json`, no `files/` in git, although the card says "`files/r17/` here") | — | ## Concepts and data structures @@ -192,13 +197,15 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty - `fetch` is `NATIVE_FETCH`, or, when `createRuntime` got a `global`, that global's `fetch` bound before the observers install. It is used only by the inline transport; - `clock` is passed only when `createRuntime` got one (otherwise the host uses `browserClock`). + The script-tag build gets here through `GenClass.init(withCdnModel(init))` (`src/cdn/global.ts`), so its `model` object also carries `workerFactory` and `ortLoader`; they are not typed on `ModelOptions` and pass through the spread like any other `ModelHostOptions` key. The `/auto` entries (`src/auto.ts`, `src/cdn/auto-*.ts`) call plain `GenClass.init` (through `src/cdn/auto-start.ts` -> `startAuto`), so they use the default factory and loader (bundler output). + If construction throws, it uses `failedProvider`, a provider with `status: {state:"error"}` and no `onStatus` (so no console line and no `"status"` event). The runtime then owns the host (`ownsDecider`) and calls `dispose()` on `destroy()`. 4. `RuntimeImpl` (`packages/runtime/src/runtime.ts`) consumes the provider as follows: - `onStatus`: re-fires as the runtime `"status"` event. On `ready` the reporter prints `[GenClass] Model ready (<model>, <device>, <variant>, <loadMs>). Mode: <mode>.` (`<mode>` is `observe` unless the app chose otherwise: `o.mode ?? "observe"` in the `RuntimeImpl` constructor). On `error` it prints `[GenClass] Model unavailable (<error>); observing only.` Both go through `console.info` under `report: "console"`. - `consultable()`: triggers are built only when `status.state` is `"ready"` or `"off"`. With `"loading"` or `"error"`, every trigger (including the delivery gate, `runDelivery`) runs its passive action at once and nothing is held. Store writes are held only under `policy.holdWrites: true` (opt-in): `hub.hooks.mayHold` = `hub.holdWrites && consultable() && mode !== "observe"`. By default a salient write goes to `observeWrite` and is decided in the background. - `trigger()`: if a situation is salient but `status.state !== "ready"`, it calls `void this.ready`, which starts a load (the effective "lazy" start), and runs the passive action. The public `rt.ready` getter calls `decider.ready()` once and caches the promise, so any read of `rt.ready` by the app, and any `rt.ask()`/`rt.decide()`, also starts the load regardless of `preload`. - `priority` per request (the `trigger(...)` call sites in `runtime.ts`, `observe/fetch.ts`, `observe/xhr.ts`; `ask` submits directly): 2 for `delivery` (fetch/XHR responses, WebSocket and EventSource messages, via `runDelivery`), `request` (fetch and XHR), fetch `failure` and a held `mutation` (`gateMutation`, only with `holdWrites`); 1 for a background `mutation` (`observeWrite`, the default), `inconsistency`, `stall`, XHR `failure` and `ask`; 0 for `transition` and `error`. In `trigger`, a request that will not hold is capped at 1 (`waits ? priority : min(priority, 1)`). - - Holding: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`. In `observe` mode `permittedActions` is always empty, so nothing waits and every request except `delivery` reaches the host at priority <= 1 with the 5 s background deadline. `delivery` requests are dropped as stale by `DeciderQueue` before reaching the host (`passive()` runs first and sets `released`; the controller's `stale` is `() => released`), the same as any non-waiting delivery in guard; `runDelivery` may still delay a candidate by up to 100 ms (`BODY_WAIT_MS`) for the body read. `expectedLatency()` is `Infinity` while `DeciderQueue.stuck` (the provider's last evaluation timed out and none has answered since), and otherwise `base × (1 + waiting)` plus, while an evaluation is in flight, `max(base, the time it has taken so far)`, where `base` is the (lower) median of the queue's recent latencies, or `status.warmupMs` before any. A slow or wedged host therefore stops causing holds instead of delaying the app. + - Holding: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`. In `observe` mode `permittedActions` is always empty, so nothing waits and every request, `delivery` included, reaches the host at priority <= 1 with the 5 s background deadline. Since 054da38 a non-waiting delivery gets no `stale` check (`stale` is passed only when `waits || spec.trigger !== "delivery"`), so its background decision is no longer dropped; in `observe` `runDelivery` releases it before reading the body (`deliveryHoldable` is false), and the body analysis is cut short at the first write of its chain (`finalizeDeliveries`). In guard/heal a delivery that cannot wait while `discard` is permitted (`writesCanAct`) runs `passive()` only and is not sent, unless a question forces it or `triage: "always"`; a holdable delivery may still wait up to 100 ms (`BODY_WAIT_MS`) for its body. `expectedLatency()` is `Infinity` while `DeciderQueue.stuck` (the provider's last evaluation timed out and none has answered since), and otherwise `base × (1 + waiting)` plus, while an evaluation is in flight, `max(base, the time it has taken so far)`, where `base` is the (lower) median of the queue's recent latencies, or `status.warmupMs` before any. A slow or wedged host therefore stops causing holds instead of delaying the app. - `situationBudget()`: reads `status.device` and `status.threads`: webgpu (and unknown devices) `STATE_CHAR_BUDGET` = 2,400 chars (about 1,000 tokens); wasm `1000 + round((threads - 1) × 1000 / 3)` (1,000 at 1 thread to 2,000 at 4); then `× budgetScale`. - `holdBudgetMs()`: seeds from `status.warmupMs` until the decider queue has its own latency samples. - `Decision.model`: comes from `status.model ?? status.variant ?? "custom"`. @@ -216,7 +223,7 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty - `"eager"`: `start()` now. - `"idle"`: `scheduleIdle`. If `document.readyState !== "complete"`, it waits for `load` (or `LOAD_EVENT_WAIT_MS` = 5 s), then calls `requestIdleCallback(run, {timeout: 2000})`. Without `requestIdleCallback` it uses a `clock.setTimeout` of 1 s. - `"lazy"`: nothing until the first `ready()`, `load()`, `evaluate()` or `measure()`. -3. `start()` (once): unless `opts.worker === false`, it calls `workerFactory ?? defaultWorkerFactory`. The default factory is `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`, or `null` when `Worker` is undefined. If the factory throws (CSP, `file://`, ...), the result counts as `null`. A `null` worker means `useInline()`. +3. `start()` (once): unless `opts.worker === false`, it calls `workerFactory ?? defaultWorkerFactory`. The default factory is `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`, or `null` when `Worker` is undefined. If the factory throws (CSP, `file://`, ...), the result counts as `null`. A `null` worker means `useInline()`. The script tag's factory is `blobModuleWorker` (see [2b](#2b-cdn-script-tag-build-srccdn-tsupconfigts)); the same factory is used again for the WASM retry. 4. `useWorker(w)`: - registers `message`, `error` and `messageerror` listeners. Every `error` event is `preventDefault()`ed so it never reaches the page's error handlers or GenClass's own error observer; - arms `helloTimer` (`helloTimeoutMs ?? 15_000`); @@ -233,6 +240,19 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty - Otherwise it builds `ModelBackend({ ort: dynamic import by build, fetch: self.fetch, caches (try/catch), clock: browserClock, emit: post status, inWorker: true })`, routes messages to it, and posts `hello`. 8. Every `status` message re-arms the **stall watch** (`loadStallMs ?? 180_000`; worker transport only, only while `loading`). Silence for that long calls `onStall`. If `status.device` is `"webgpu"` it first adds an attempt `{device:"webgpu", error:"stalled"}`. It then calls `retryOnWasm`; if that returns false it calls `onWorkerCrash("the model worker stopped responding while loading (<phase> on <device>)")` (`<phase>` is `start-up` when no phase was reported yet). +### 2b. CDN script-tag build (`src/cdn/*`, `tsup.config.ts`) + +The model code is the same; only how the worker script and onnxruntime-web get onto the page differs. Owner of `src/cdn/*`: INSTALL. + +1. **Where files come from.** `install()` in `global.ts` computes `base`, the package's `dist/` URL: `data-base` on the tag (resolved against the page, trailing `/` added), else `assetBase(script.src)`. On jsDelivr (`cdn`, `fastly`, `gcore`, `testingcf`) and unpkg URLs of `@genclass/runtime`, `assetBase` pins the version to `__GENCLASS_VERSION__` (the `package.json` version at build time), so an unversioned or `@latest` tag never mixes files of two releases. Anywhere else it is the script's own directory. Without a script URL it falls back to `https://cdn.jsdelivr.net/npm/@genclass/runtime@<version>/dist/`. `GenClass.base` exposes it. +2. **Host options.** `withCdnModel` (skipped when the options have a `decider` or `model === false`) sets `model = { workerFactory, ortLoader, ...user }`. `model.baseUrl`, `ortWasmPaths`, `device`, `preload` and `worker` come from the merged page configuration (`<meta name="genclass">`, the tag's `data-*`, `window.GENCLASS_CONFIG`, then the `GenClass.init(options)` argument; `src/cdn/config.ts` -> `fromPairs`: `data-model` / `data-ort` / `data-device` / `data-preload` / `data-worker`). With no `model`/`baseUrl` the host uses `DEFAULT_MODEL_BASE_URL`, so today the script tag observes only, exactly like the npm path (see the 404 flow below). +3. **Worker.** `workerFactory: () => blobModuleWorker(base + "cdn/worker.js")`. Browsers refuse `new Worker(<cross-origin URL>)`, so `blobModuleWorker` creates a same-origin Blob URL whose only line is `import "<base>cdn/worker.js";` and starts `new Worker(blobUrl, { type: "module", name: "genclass-model" })`. It returns `null` when `Worker`, `Blob` or `URL.createObjectURL` is missing (host goes inline); if the constructor throws it revokes the URL and rethrows (the host counts that as `null` too). The Blob URL is revoked on the worker's first `message` (its `hello`) or `error`. A module worker may import cross-origin modules over CORS, and jsDelivr/unpkg send `Access-Control-Allow-Origin: *`; a self-hosted `dist/` on another origin must send CORS headers too. If the import fails (404, CORS, CSP), the worker fires `error` before `hello`, and the host falls back inline as in step 5 of section 2. The 15 s hello timeout covers fetching `cdn/worker.js` (40 KB raw, 16 KB gzip per `test/install/RESULTS.md`) and its shared chunk (`ort-env.ts`, under 1 KB in a local build); ORT still comes later. +4. **`dist/cdn/worker.js`** (`src/cdn/worker.ts`) is `src/model/worker.ts` unchanged (same `hello`, same em-pthread guard, same protocol) plus a second `message` listener that copies `load.options.ortWasmPaths` into `cdnState` (`ort-env.ts`). The model worker's `loadOrt` dynamic imports are rewritten at build time by the `genclass-cdn-ort` plugin, so in the built file they are `import('./ort-webgpu.js')` / `import('./ort-wasm.js')`, resolved next to `worker.js` on the CDN. No bare `onnxruntime-web` specifier is left, so no import map or bundler is needed. Only the bundle the plans need is fetched (`status.ortBuild`), as on npm. +5. **`dist/cdn/ort-webgpu.js` / `ort-wasm.js`** (`src/cdn/ort-webgpu.ts` / `ort-wasm.ts`) bundle `onnxruntime-web/webgpu` / `/wasm` (`noExternal`; minified 118 KB / 73 KB raw per RESULTS.md), call `prepareOrt(ort.env, glue)` once at module evaluation, and re-export the module. `prepareOrt` does something only when the realm is `crossOriginIsolated`, has no `document` (a worker) and `env.wasm.wasmPaths` is unset. Then it sets `env.wasm.wasmPaths = { mjs: <dir>/<glue> }` with `<dir>` = `cdnState.ortWasmPaths` or `https://cdn.jsdelivr.net/npm/onnxruntime-web@<env.versions.web>/dist/`, and `<glue>` = `ort-wasm-simd-threaded.asyncify.mjs` (webgpu bundle) or `ort-wasm-simd-threaded.mjs` (wasm bundle). Reason: with WASM threads, ORT refuses its embedded glue in a cross-origin script and would look for the `.mjs` next to itself, which this package does not ship; given an explicit URL it preloads the glue as a same-origin Blob and can start its pthread workers. Single-threaded (no COOP/COEP), nothing changes: ORT uses its embedded glue because the backend hands it the wasm bytes. +6. **ORT `.wasm` and model files.** Unchanged backend behaviour (section 3, step 7): `prefetchWasm` fetches `ORT_WASM_FILES[build]` from `ortWasmPaths || ortCdnBase(ort.env.versions.web)` through Cache Storage and sets `env.wasm.wasmBinary`. `env.versions.web` is the version bundled into `dist/cdn/ort-*.js` (1.30.0 from the lockfile), so the default wasm and glue always match the bundled JS. The model card and files come from `baseUrl` as on npm. The `.wasm` is not in `@genclass/runtime`; it always comes from the onnxruntime-web package (jsDelivr) or `data-ort`. +7. **Inline fallback** (no `Worker`, CSP `worker-src` blocking the Blob URL, failed import, hello timeout, `data-worker="false"`): `ortLoader(build)` does `import(base + "cdn/ort-webgpu.js" | "cdn/ort-wasm.js")` on the main thread (`/* webpackIgnore */`, `/* @vite-ignore */`). `prepareOrt` is a no-op there (`document` exists), the backend uses 1 thread and `wasmBinary` as usual. Checked in `cdn-check.mjs` ("CSP `worker-src 'none'`: inline fallback loads ORT from the CDN"). +8. **What the iife never contains:** onnxruntime-web. `globalBuild` marks every `onnxruntime-web(/...)` import external, so the host's `defaultOrtLoader` survives as a bare `import("onnxruntime-web/webgpu")` in `genclass.global.js`; it is never called because `ortLoader` is always set, unless the page passes its own `model.ortLoader`. The default `new Worker(new URL("./worker.js", import.meta.url))` factory is likewise replaced. `genclass.global.min.js` is 253 KB raw / 86 KB gzip (RESULTS.md). + ### 3. Backend load (`backend.ts` -> `ModelBackend.load` / `doLoad`) 1. `load(opts)` joins an in-flight load and resolves at once when an engine exists. On failure `loading` resets, so a later `load` starts over. @@ -261,7 +281,7 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty It then starts `prefetchWasm`: - fetches `ORT_WASM_FILES[build]` from `ortWasmPaths || ortCdnBase(ort.env.versions.web || "1.30.0")` through the same cache (tag `onnxruntime-web@<version>`, no sha256); - sets `env.wasm.wasmBinary` so ORT never fetches the wasm itself; - - if that fails, sets `env.wasm.wasmPaths = <base>` instead. + - if that fails, sets `env.wasm.wasmPaths = <base>` instead. In the CDN worker on a `crossOriginIsolated` page this replaces the `{ mjs }` object `prepareOrt` set, so ORT then resolves both the glue and the wasm under `<base>` on its own (not tested). 8. For each plan: - `download` (await the variant; extra variants are fetched on demand and memoised per load); - `runtime` (await the wasm prefetch); @@ -403,11 +423,11 @@ Lookup order: ### When the default model URL 404s (the alpha today) -No runtime model is published, and none exists yet for `situation-v2`. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/` and is a 404 on the registry (checked by the lead, 2026-10-08); OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` is still open, behind the v2 data, teacher, distillation and EVAL steps in HANDOFF. The published `@genclass/runtime@0.1.0-alpha.0` defaults to `guard`; this branch defaults to `observe`, which changes nothing below because nothing can act without a model. The release procedure is in [RELEASE.md](../../../RELEASE.md). Traced through the code, a default `GenClass.init()` in a browser does the following. +No runtime model is published, and none exists yet for `situation-v2`. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/` and is a 404 on the registry (checked by the lead, 2026-10-08); OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` is still open, behind the v2 data, teacher, distillation and EVAL steps in HANDOFF. The published `@genclass/runtime@0.1.0-alpha.0` defaults to `guard`; `0.1.0-alpha.1` (`latest`) and this branch default to `observe`, which changes nothing below because nothing can act without a model. The script-tag build (not on npm yet) behaves the same, with `cdn/worker.js` from the asset base as the worker. The release procedure is in [RELEASE.md](../../../RELEASE.md). Traced through the code, a default `GenClass.init()` in a browser does the following. 1. The host is created with `preload: "idle"`, so the status is `off`. Until the idle start, triggers compute facts. A salient one calls `void this.ready`, which starts the load early, and runs the passive action. 2. The worker starts and posts `hello`. `doLoad` sets phase `card`, starts the WebGPU probe, and fetches `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json` (`cache:"no-cache"`). The probe is not cancelled when the card fails: on a WebGPU-capable browser it still requests an adapter and creates and destroys a device; its result is discarded. -3. The fetch returns a 404, so `fetchCard` throws `ModelLoadError("model card download failed: HTTP 404 for <url>")`. The Cache Storage has no copy, so the error is rethrown. **No ORT bundle, ORT wasm, tokenizer or ONNX file is downloaded**, because those steps come after the card. The only network traffic is the worker chunk(s) and `model.json`. If the request fails without a response instead (offline, CSP `connect-src` blocking jsDelivr, CORS), the message is `model card download failed for <url>: <fetch error message>` and the rest is identical. With `worker: false` or the inline fallback, the same happens on the main thread with `worker: false` in the status. +3. The fetch returns a 404, so `fetchCard` throws `ModelLoadError("model card download failed: HTTP 404 for <url>")`. The Cache Storage has no copy, so the error is rethrown. **No ORT bundle, ORT wasm, tokenizer or ONNX file is downloaded**, because those steps come after the card. The only network traffic is the worker chunk(s) and `model.json` (script tag: `cdn/worker.js` and its chunk from the asset base, no `cdn/ort-*.js`). If the request fails without a response instead (offline, CSP `connect-src` blocking jsDelivr, CORS), the message is `model card download failed for <url>: <fetch error message>` and the rest is identical. With `worker: false` or the inline fallback, the same happens on the main thread with `worker: false` in the status. 4. The backend emits `{state:"error", error:"model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json", worker:true}`, with no `attempts` and no `gpu`. 5. Host: `retryOnWasm` returns false (no WebGPU attempt), so `setStatus(error)` runs and `ready()` waiters reject with `ModelLoadError`. The worker is **not** terminated; it stays idle until `dispose()`. 6. Runtime: the console shows `[GenClass] Model unavailable (model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json); observing only.` (via `console.info`, only with `report: "console"`), and a `"status"` event fires. The devtools overlay shows "Model unavailable" with `observing only · <error>` (`packages/runtime/src/devtools/index.ts` -> `renderStatus`). @@ -455,7 +475,10 @@ genclass-runtime info <dir> | `ModelHostOptions.warmup` | boolean | `true` | `backend.ts` | `false` skips the warm-up (tests). Then `warmupMs` and `latency` are absent, so the runtime's automatic hold budget is 300 ms (`HOLD_FALLBACK_MS`) until it has its own samples | | `ModelHostOptions.helloTimeoutMs` | number | `HELLO_TIMEOUT_MS` = 15_000 | `host.ts` | worker start-up budget before the inline fallback | | `ModelHostOptions.loadStallMs` | number | `LOAD_STALL_MS` = 180_000 | `host.ts` | silence while loading = stuck worker | -| `ModelHostOptions.fetch` / `clock` / `workerFactory` / `ortLoader` / `probeGpu` | — | native fetch / `browserClock` / real Worker / dynamic import / `probeWebGPU` | `host.ts` | injection points (runtime passes `fetch`, `clock`; tests pass the rest) | +| `ModelHostOptions.fetch` / `clock` / `workerFactory` / `ortLoader` / `probeGpu` | — | native fetch / `browserClock` / real Worker / dynamic import / `probeWebGPU` | `host.ts` | injection points (runtime passes `fetch`, `clock`; the script-tag build passes `workerFactory` = `blobModuleWorker(<base>cdn/worker.js)` and `ortLoader` = `import(<base>cdn/ort-*.js)`; tests pass the rest) | +| Script-tag model keys | string attributes / meta pairs | `data-model` / `model=` (URL, or `off`), `data-ort` / `ort=` -> `ortWasmPaths`, `data-device`, `data-preload`, `data-worker`; `data-base` = asset base | `src/cdn/config.ts` -> `fromPairs`, `fromDataset`; `src/cdn/global.ts` -> `install` | page-level `model` options for the CDN build (any `ModelOptions` also via `window.GENCLASS_CONFIG`) | +| CDN asset base | URL | `assetBase(script.src)`: jsDelivr/unpkg -> `<cdn>/@genclass/runtime@<__GENCLASS_VERSION__>/dist/`; elsewhere the script's directory; fallback `https://cdn.jsdelivr.net/npm/@genclass/runtime@<version>/dist/` | `src/cdn/global.ts` | where `cdn/worker.js`, `cdn/ort-*.js` and `devtools/index.js` load from | +| CDN threaded glue | file | `ort-wasm-simd-threaded.asyncify.mjs` (webgpu) / `ort-wasm-simd-threaded.mjs` (wasm), under `ortWasmPaths` or `https://cdn.jsdelivr.net/npm/onnxruntime-web@<version>/dist/` | `src/cdn/ort-env.ts` -> `prepareOrt` | only in a `crossOriginIsolated` worker, when `wasmPaths` is unset | | `BackendLoadOptions.sessionTimeoutMs` | `{webgpu?, wasm?}` | webgpu 60_000, wasm 180_000 | `backend.ts` -> `createEngine` | session-creation timeout; **not settable through the host** | | `IDLE_TIMEOUT_MS` | ms | 2_000 (`requestIdleCallback` timeout); fallback timer `IDLE_TIMEOUT_MS / 2` = 1_000 | `host.ts` | idle preload | | `LOAD_EVENT_WAIT_MS` | ms | 5_000 | `host.ts` | idle preload waits at most this long for `load` | @@ -490,7 +513,7 @@ Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` ar - BPE behaviour; - the packer layout (position restarts, groups, marker choice). - **Per-header calibration is keyed on the exact instruction text** (`sha1(header)[:12]`). Rewording a standing question in `packages/runtime/src/situation/questions.ts` silently falls back to bucket or kind temperatures. v2 added a new header, `ACTION_INSTRUCTIONS.delivery` ("What should the runtime do with this response or message?"), and per-trigger action descriptions (`TRIGGER_DESCRIPTIONS.delivery`): a v1 calibration file has no `by_header` entry for it. -- **The default mode does not reduce model traffic.** In `observe` (the default since f3636b2) every salient situation except `delivery` is still evaluated, in the background; it only never waits. `delivery` decisions are dropped as stale before reaching the host, and `runDelivery` may still delay a candidate by up to 100 ms for the body read. Turning the model off needs `model: false` or the kill switch. +- **The default mode does not reduce model traffic.** In `observe` (the default since f3636b2) every salient situation is still evaluated, in the background; it only never waits. Since 054da38 that includes `delivery` (released to the app at once, decided afterwards; the decision cannot act, so it records `executed: false` unless the model's top choice was the passive action itself, `runtime.ts` -> `onDecision`), so `observe` sends the host more requests than before, not fewer. Turning the model off needs `model: false` (script tag: `data-model="off"`) or the kill switch. - **JS cannot emit Python float literals** like `25.0` (`pyNumber(25)` = `"25"`). That is why training/NEEDS.md item 8 asks the curriculum to write integral floats as ints. - **The public `stateText`** (`packages/runtime/src/situation/serialize.ts`, used by `explain()`) is a human rendering (indented list items). It is *not* the token text: the packer uses `model/serialize.ts` -> `segmentText` with `[SEP]` between segments. `model/serialize.ts` also has a `stateText`, which is internal. - **Nothing about the vocabulary is hardcoded.** Marker, CLS and SEP ids come from `meta.json` (checked) or `tokenizer.json`, so pruned vocabularies (16,364 tokens, markers 16359-16363) work unchanged. Keep it that way (CONTRACT §13). @@ -504,7 +527,10 @@ Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` ar - Inline does not structured-clone, so `questions` containing functions work inline but fail in the worker with `ModelInputError`. - Inline WebGPU timeouts do not stop the remaining plans. - **The worker and the onnxruntime threads:** `worker.ts` must stay inert when `self.name` starts with `em-pthread` or equals `ort-wasm-proxy-worker`. Removing that guard spawns nested backends. -- **`hello` is posted before ORT is imported** (ORT is a dynamic import on `load`). The 15 s hello timeout therefore only covers fetching and evaluating the worker chunk. +- **`hello` is posted before ORT is imported** (ORT is a dynamic import on `load`). The 15 s hello timeout therefore only covers fetching and evaluating the worker chunk (for the script tag: the cross-origin `cdn/worker.js` and its chunk, imported from the Blob URL). +- **CDN worker ordering:** `src/cdn/worker.ts` registers its `message` listener after `src/model/worker.ts`'s; both run synchronously on the `load` message, and ORT is imported only after the card and the GPU probe, so `cdnState.ortWasmPaths` is set before `prepareOrt` runs. Importing ORT earlier (at module top, or before the first `await` in `doLoad`) would make `prepareOrt` miss a page's `data-ort`, and `prepareOrt` runs once per realm (at module evaluation), so a later `ortWasmPaths` is never picked up for the glue. +- **CDN self-hosting (`data-base`, `data-ort`):** the `dist/` directory must serve `genclass.global*.js`, `cdn/worker.js`, `cdn/ort-*.js`, the `cdn/chunk-*.js` they import (and `devtools/index.js` for the overlay), with CORS headers when on another origin than the page. A `data-ort` directory must hold both `.wasm` files and, for `crossOriginIsolated` pages, both threaded `.mjs` glue files (`ort-wasm-simd-threaded.mjs`, `ort-wasm-simd-threaded.asyncify.mjs`). The CDN `worker.js` is not a drop-in for `dist/worker.js` (and vice versa): one bundles ORT, the other imports bare `onnxruntime-web` specifiers. +- **The asset version must exist on the CDN.** `assetBase` pins jsDelivr/unpkg URLs, and the no-script-URL fallback, to `__GENCLASS_VERSION__` (the `package.json` version at build time). This branch's `package.json` still says `0.1.0-alpha.1`, which is on npm from 806a296 without `dist/cdn/` or the global builds. So a local build whose base resolves to jsDelivr (the fallback, e.g. when `findScript` finds no tag) loads `.../@genclass/runtime@0.1.0-alpha.1/dist/cdn/worker.js`, which 404s: the worker errors before `hello`, the inline `ortLoader` 404s too, and the load ends in `error` (observe only). Bump the version before testing against or publishing to the CDN; npm refuses a republish of `0.1.0-alpha.1` anyway. - **Stall vs session timeout:** `LOAD_STALL_MS` (180 s) equals the WASM session timeout (180 s), and no status is posted during session creation. On a very slow WASM session the host's stall watchdog and the backend's step timeout fire at about the same time. - **The WASM retry happens once per host lifetime** (`wasmRetried` is never reset). - **A worker crash after `ready` is usually permanent for the runtime.** A worker `error`/`messageerror` event after `hello` moves `ready` -> `error` (`onWorkerCrash`), rejects the running job with `ModelLoadError` and queued jobs with `ModelNotReadyError`. The runtime never calls `host.load()`, and triggers stop consulting in `error`. The one exception: `RuntimeImpl`'s `ready` getter calls `decider.ready()` only on its first read and caches the promise. If nothing had read `rt.ready` before the crash (no salient trigger while `off`, no `rt.ask()` while not ready, no app read), the first `rt.ask()`/`rt.decide()` or app read of `rt.ready` afterwards calls `host.ready()`, which starts a fresh worker because `started` was reset. Otherwise the runtime observes only until the page reloads. @@ -523,18 +549,18 @@ Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` ar - The ORT wasm is prefetched and handed over as `wasmBinary` so ORT never fetches it (offline second loads). - Worker `error` events are `preventDefault`ed so they never reach the app's error handlers. - **Thread count:** WASM threads need a `crossOriginIsolated` page (COOP/COEP) *and* the worker transport: `min(maxThreads ?? 4, hardwareConcurrency)`. The runtime's automatic situation budget grows with `status.threads`. -- **Self-hosting needs three things served:** the model directory (`baseUrl`), the worker chunk next to the host chunk (bundler output), and the ORT wasm (`ortWasmPaths`, default jsDelivr). Which wasm is fetched depends on the plans: `ort-wasm-simd-threaded.wasm` when no WebGPU plan exists (e.g. `device: "wasm"`, no `navigator.gpu`, software adapter under `"auto"`), else `ort-wasm-simd-threaded.asyncify.wasm`. Serve both. The model files and the wasm are `fetch`ed, so a Content-Security-Policy whose `connect-src` blocks their origin makes the load fail and the runtime observe only; a blocked worker script only triggers the inline fallback (which policy governs the worker's own fetches depends on how the worker script is served; no test covers CSP). +- **Self-hosting needs three things served:** the model directory (`baseUrl`), the worker chunk next to the host chunk (bundler output; for the script tag, `dist/cdn/*` under the asset base, see the CDN bullets above), and the ORT wasm (`ortWasmPaths`, default jsDelivr). Which wasm is fetched depends on the plans: `ort-wasm-simd-threaded.wasm` when no WebGPU plan exists (e.g. `device: "wasm"`, no `navigator.gpu`, software adapter under `"auto"`), else `ort-wasm-simd-threaded.asyncify.wasm`. Serve both. The model files and the wasm are `fetch`ed, so a Content-Security-Policy whose `connect-src` blocks their origin makes the load fail and the runtime observe only; a blocked worker script only triggers the inline fallback (which policy governs the worker's own fetches depends on how the worker script is served; no test covers CSP). - **`host.stats` is the live counters object**, typed `Readonly` but mutated in place; copy it if you need a snapshot. - **The v0.1 q8 needs `shader-f16` on WebGPU** (its embedding table is fp16; ORT's WebGPU Gather fails with "Program Gather requires f16"), but its card does not say so. The loader then wastes a `webgpu+q8` session and warm-up before WASM. TRAIN's exports use an int8 embedding table and declare `needs: "shader-f16"` only on fp16. Check with `genclass-runtime info`. - **Bundling:** - tsup keeps `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` verbatim; Vite and webpack 5 bundle that pattern. - - Both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")` must stay **static string specifiers** so bundlers split them into separate chunks and a page downloads only one. + - Both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")` must stay **static string specifiers** so bundlers split them into separate chunks and a page downloads only one. The CDN build depends on this too: the `genclass-cdn-ort` plugin's `onResolve` filter (`/^onnxruntime-web\/(webgpu|wasm)$/`) only rewrites those exact specifiers; any other ORT import in `src/model/` would be bundled into `dist/cdn/worker.js` directly (or, in the iife, left as an unresolvable bare import). - `onnxruntime-web/wasm` is missing from `tsup.config.ts` `external`. It stays external only because `onnxruntime-web` is a `dependency` (tsup externalises dependencies including subpaths). The local `packages/runtime/dist/` from the 2026-10-08 tsup build on this branch (untracked build output) keeps both `import('onnxruntime-web/webgpu')` and `import('onnxruntime-web/wasm')` as dynamic imports in `dist/worker.js` and in the chunk that `dist/index.js` re-exports `createModelHost` from (which also holds the `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` pattern). - **Determinism:** the host uses the injected `Clock` for timers. `scheduleIdle` uses the global `requestIdleCallback` and `load` event. The sim's default modes plug in their own `decider` and never touch the host, but the `--on-policy` (DAgger) mode runs the real host inline in Node (`sim/src/run/onpolicy.ts`; it passes no `clock`, so the host's timers use `browserClock`, and `preload: "eager"` bypasses `scheduleIdle`). A change to `host.ts`, `backend.ts`, the loader, packer or calibration therefore also changes on-policy data generation; rebuild `sim/dist/model-host` (`npm run build:model-host` in `sim/`) after one. ## How to change it safely -Run policy: HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac. On other machines agents may run light local checks (`npm ci`, `tsc`, `tsup`, vitest unit tests, including `test/model/*`). Ask the user before model downloads (`fetch-model`), Playwright specs, `smoke.sh`, or anything on Azure ([build-test-release.md](build-test-release.md#where-to-run-things)). Model-file tests read `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) and **skip** when it is absent: these are the 14 skipped tests of the unit run (332 passed + 14 skipped, plus 4 in `review-perf.test.ts` run alone, pinned to b435acb; re-check after the uncommitted `state/hub.ts` held-write fix and its `atoms.test.ts` test land, expected 333 + 14). Unit tests with fakes always run, and CI (`.github/workflows/ci.yml`, b435acb) runs them on every push to `main`/`runtime`/`mvp`/`mvp-v2` and on pull requests, without a model directory and without Playwright, so CI never exercises a real ONNX model. +Run policy: HANDOFF.md's "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac. On other machines agents may run light local checks (`npm ci`, `tsc`, `tsup`, vitest unit tests, including `test/model/*`). Ask the user before model downloads (`fetch-model`), Playwright specs, `smoke.sh`, or anything on Azure ([build-test-release.md](build-test-release.md#where-to-run-things)). Model-file tests read `GENCLASS_MODEL_DIR` (default `<repo>/.cache-model`) and **skip** when it is absent: these are the 14 skipped tests of the unit run (`npx vitest run` in `packages/runtime` on `mvp-v2-merge`, 2026-10-08: 379 passed + 14 skipped in 46 files, `test/install/cli.test.ts` included; one of three full parallel runs had a single failure that did not reproduce, consistent with timing-sensitive tests: CI runs `review-perf.test.ts` alone with `--retry=2`). Unit tests with fakes always run, and CI (`.github/workflows/ci.yml`, b435acb) runs them on every push to `main`/`runtime`/`mvp`/`mvp-v2` and on pull requests, without a model directory and without Playwright, so CI never exercises a real ONNX model. ```sh node packages/runtime/bin/genclass-runtime.mjs fetch-model ~/gcl-cache/model-v0.1 --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/ @@ -584,13 +610,20 @@ GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/brow - Update `package.json` (`^1.30.0`) and `ORT_FALLBACK_VERSION`. - Check `ORT_WASM_FILES` names exist in the new `dist/` (`node_modules/onnxruntime-web/package.json` exports `./wasm`, `./webgpu` and the `.wasm` files) and that `tsup.config.ts` externals still apply. - Update the browser test regex expecting `onnxruntime-web@1.30.x`, and `onnxruntime-node` in devDependencies (pinned `1.30.0`) for parity tests. + - CDN build: `dist/cdn/ort-*.js` bundle whatever version the lockfile installs, and the default wasm and threaded glue follow `env.versions.web`, so they stay matched. Check that the glue names in `src/cdn/ort-webgpu.ts` / `ort-wasm.ts` (`prepareOrt` argument) still exist in the new `dist/`, that ORT still accepts `env.wasm.wasmPaths = { mjs }`, and rerun `test/install/cdn-check.mjs` (crossOriginIsolated case) on the VM. - Re-measure latency and transfer (Playwright writes `test-results/model-bench/{latency,transfer}.json`). -10. **Change the CLI.** Keep its `parseCard` in sync with `loader.ts` `parseCard` (same file-name safety rules and defaults). There are no automated CLI tests: verify on the VM with `fetch-model` and `info` against a real directory. +10. **Change the CLI.** Keep its `parseCard` in sync with `loader.ts` `parseCard` (same file-name safety rules and defaults). `test/install/cli.test.ts` covers only `init` / `remove` and the page config; there are no automated tests of `fetch-model` / `info`: verify on the VM against a real directory. Keep the `init` / `remove` dispatch in `main` ahead of `parseArgs`. 11. **Self-host everything (app integration; derived from the code).** - `npx genclass-runtime fetch-model public/genclass-model --from <a directory URL that serves model.json>`. - Copy **both** `node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` to e.g. `public/ort/` (the plain one is used when no WebGPU plan exists, the asyncify one otherwise). - `GenClass.init({ model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`. For WASM threads, serve the page with COOP/COEP so it is `crossOriginIsolated`. - Check: `status.ortBuild`, `status.threads`, `status.fromCache`, and that the network panel shows no jsDelivr requests. + - Script tag instead of a bundler: serve the package's `dist/` (at least `genclass.global.min.js`, `cdn/`), then `<script src="/genclass/genclass.global.min.js" data-model="/genclass-model/" data-ort="/ort/"></script>` first in `<head>` (a non-CDN `src` makes the script's directory the asset base; `data-base` overrides it). For WASM threads also copy `ort-wasm-simd-threaded.mjs` and `ort-wasm-simd-threaded.asyncify.mjs` into `/ort/`. + +12. **Change how the CDN build loads the worker or ORT** (`src/cdn/global.ts` -> `withCdnModel` / `blobModuleWorker` / `assetBase`, `src/cdn/worker.ts`, `src/cdn/ort-*.ts`, `tsup.config.ts` CDN entries; coordinate with INSTALL). + - Keep `src/model/*` free of CDN knowledge: the CDN side only uses `workerFactory`, `ortLoader` and the `load` message's `ortWasmPaths`. A new load option the CDN worker needs must still go through `BackendLoadOptions`. + - After `npx tsup` in `packages/runtime`, check that `dist/cdn/worker.js` contains `import('./ort-webgpu.js')` and `import('./ort-wasm.js')` and no bare `onnxruntime-web` import, and that `dist/genclass.global.js` contains no onnxruntime-web code (only the external bare `import("onnxruntime-web/...")` of the unused default loader). + - Tests: `test/install/cli.test.ts` "page config" (`assetBase`, `fromPairs`) runs with vitest; the browser check is `node test/install/cdn-check.mjs` (headless Chromium via Playwright, needs a model directory; VM only, ask first). ## Tests @@ -606,6 +639,8 @@ GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/brow | `packages/runtime/test/browser/model-webgpu.spec.ts` | On SwiftShader WebGPU: `webgpu+q8` without `shader-f16` runs or falls back; embedding variants (`GENCLASS_WEBGPU_VARIANTS`); exported models; `auto` skips a software adapter. | | `packages/runtime/test/model/helpers.ts`, `test/browser/model-helpers.ts`, `test/fixtures/model/*` | `MODEL_DIR` resolution (both helpers: `GENCLASS_MODEL_DIR`, default `<repo>/.cache-model`). Fixture selection in the Node helpers (`test/model/helpers.ts`): from the model directory when the export ships `requests.json`/`pack_fixtures.json`/`torch_fixtures.json` (plus `parity.json` for `exportParity`), else the v0.1 set in `test/fixtures/model`. The browser helpers always read the v0.1 set (`requests50.json`, `pack_fixtures.json`, `torch_fixtures.json`). Generators: `make_py_fixtures.py`, `make_webgpu_variants.py`. | | `packages/runtime/test/browser/build.mjs`, `server.mjs`, `playwright.config.ts`, `page/*` | Test infrastructure, no assertions of its own. `build.mjs` (Playwright global setup) builds the library with `npx tsup` (falls back to building `src/model/index.ts` + `worker.ts` alone into `.build/dist` when a tsup entry file is missing, the package build fails, or `dist/index.js` does not mention `createModelHost`), bundles a test app with esbuild, and throws unless a built file contains the `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })` pattern, `worker.js` exists, and the worker code holds both `import("onnxruntime-web/webgpu")` and `import("onnxruntime-web/wasm")`. `server.mjs` serves the app, `/model/` (`GENCLASS_MODEL_DIR`), `/ort/` (onnxruntime-web's `dist/`, so both wasm files), extra models at `/m/<name>/`, and the same under `/coi/` with COOP/COEP headers for WASM-thread tests. | +| `packages/runtime/test/install/cli.test.ts` (vitest, runs in CI) | Mostly INSTALL (`init` / `remove` on fixture projects, edit helpers). Model-relevant: "page config" (`fromPairs` / `parsePairs` of meta content and data attributes, including model keys) and `assetBase` (jsDelivr/unpkg URLs pinned to the build's version, `@latest` and unversioned included; other hosts use the script's directory; `null` -> jsDelivr fallback). | +| `packages/runtime/test/install/cdn-check.mjs` (+ `server.mjs`; not vitest, not CI) | Headless Chromium (Playwright) after `npx tsup`, with `GENCLASS_MODEL_DIR` (default `~/gcl/model/.cache-model`). Page on `http://localhost:A`, "CDN" on `http://127.0.0.1:B` with CORS. Checks: the model gets ready in the Blob-URL module worker and `decide()` answers through it; a crossOriginIsolated page gets ready with WASM threads in the worker (the check asserts `threads > 1`; RESULTS.md reports 4 threads and the glue preloaded from the ORT directory); CSP `worker-src 'none'` -> inline fallback loads ORT from the CDN; an unversioned jsDelivr URL pins the worker to the build's version; default URLs; kill switch; `data-manual`; meta + `GENCLASS_CONFIG`; the tag twice; `/auto` bundled by esbuild; SSR. Last recorded result 26/26 (`test/install/RESULTS.md`, Mehar's VM run; not rerun here). | | `packages/runtime/test/smoke/smoke.sh` | npm tarball in a fresh Vite app. Uses `model: false`, so it does **not** exercise the model host. | | `packages/runtime/test/atoms.test.ts` (runtime side) | "provider errors (not ready, too many tokens, timeout, busy) fail open at once": a decider throwing an error with `code` `not_ready` / `max_tokens_exceeded` / `timeout` / `busy` lets the write apply immediately, with no decision and no hold. | | `packages/runtime/test/default-mode.test.ts` (runtime side, f3636b2) | `createRuntime()` and `GenClass.init()` without a mode start in `observe`; `guard` is opt-in (option or `?genclass=guard`); observe never holds writes or requests even when the model is sure, and with a decider that never answers nothing is delayed. `test/helpers.ts` -> `setup()` defaults to `mode: "guard"`, so the other runtime tests keep testing guard behaviour. | @@ -613,7 +648,7 @@ GENCLASS_MODEL_DIR=~/gcl-cache/model-v0.1 npx playwright test --config test/brow Environment variables of the model tests: `GENCLASS_MODEL_DIR` (model directory; default `<repo>/.cache-model`; model-file tests skip without it), `GENCLASS_WEBGPU_VARIANTS` (embedding variants for `model-webgpu.spec.ts`), `GENCLASS_BENCH_MODELS` (`name=dir,...`: extra model directories for the per-size latency bench and WebGPU tests), `GENCLASS_OFFLINE` (skips the test that loads the default ORT wasm from jsDelivr). -No test covers the default-URL 404 end-to-end, the CLI, the runtime's reaction to a host that goes `ready` -> `error` (the host side is covered in `host.test.ts`), or `ModelAbortedError`. The browser tests always serve both ORT wasm files, so a self-hosted `ortWasmPaths` missing one of them is not caught. +No test covers the default-URL 404 end-to-end, the CLI's `fetch-model` / `info`, the CDN build's `prefetchWasm` failure path (where `wasmPaths` replaces the `{ mjs }` glue override), the runtime's reaction to a host that goes `ready` -> `error` (the host side is covered in `host.test.ts`), or `ModelAbortedError`. The browser tests always serve both ORT wasm files, so a self-hosted `ortWasmPaths` missing one of them is not caught. ## Drift and open issues @@ -629,6 +664,9 @@ Mismatches between docs and code (code wins): - CONTRACT §10 says "the worker imports `onnxruntime-web/webgpu`". The code imports `onnxruntime-web/wasm` when no WebGPU plan exists, and `/webgpu` otherwise (worker and inline). The same staleness is in `src/model/README.md` "Bundling" ("`dist/worker.js` imports `onnxruntime-web/webgpu`"; "the inline fallback's `import("onnxruntime-web/webgpu")`"). - CONTRACT §2 and `docs/runtime/API.md` list only `baseUrl`, `device`, `worker` and `preload` for `model`. `ModelOptions` in `types.ts` also has `ortWasmPaths` and `cacheName`. Host-only options (`timeoutMs`, `maxQueue`, `maxThreads`, `helloTimeoutMs`, `loadStallMs`, `warmup`) are untyped through `init`. - CONTRACT §8 `DecisionProvider.evaluate(req)` lists `{trigger, state, questions}`. `EvaluateRequest` also has `priority`, `subject` (§13) and `timeoutMs`, which the host honours. +- `host.ts` -> `ModelHostOptions.workerFactory` is commented "Tests: create the worker", and `ortLoader` "Inline path". `workerFactory` is now a production injection point of the script-tag build (`src/cdn/global.ts` -> `withCdnModel`), as is `ortLoader` (correctly inline-only: the worker has its own `loadOrt`, which the CDN build rewrites at bundle time). Neither is typed on `ModelOptions`. +- `src/model/README.md` and CONTRACT §10 describe only the npm/bundler path (`dist/worker.js` + bare `onnxruntime-web` imports). The CDN path (Blob-URL worker, `dist/cdn/*`, bundled ORT, `prepareOrt`) is documented only in `src/cdn/*` comments, `packages/runtime/README.md`'s install section (one sentence: the tag loads the worker, ONNX Runtime Web and the overlay on demand from the same CDN version) and `test/install/RESULTS.md`. +- `src/cdn/global.ts` header comment says the onnxruntime-web wasm comes "from the jsDelivr onnxruntime-web package or `data-ort`"; with `window.GENCLASS_CONFIG.model.ortWasmPaths` or the `GenClass.init` argument it can come from elsewhere too (same option). - `protocol.ts` comment: `hello` is "posted once when the worker module (and onnxruntime-web) finished loading". In fact ORT is imported later, on `load`. - `host.ts` comment on `recordLatency`: "for status.latency (adaptive hold budgets and situation sizes)". No runtime code reads `status.latency`. The hold budget uses `DeciderQueue.latencies()` and `status.warmupMs`, and the situation budget uses `status.device`/`threads`. - `MODEL_CARD.md`: @@ -670,6 +708,7 @@ Open items and TODOs relevant to this scope: - [../../../RELEASE.md](../../../RELEASE.md): release procedure for `@genclass/runtime` and `@genclass/runtime-model`. - [../../../HANDOFF.md](../../../HANDOFF.md): project state and "How to continue". - [../../runtime/RESULTS.md](../../runtime/RESULTS.md): measured results (latency, model choice). +- [../../../packages/runtime/test/install/RESULTS.md](../../../packages/runtime/test/install/RESULTS.md): install, script-tag and CDN-worker checks (`cdn-check.mjs`) and CDN file sizes. - [public-api-and-lifecycle.md](./public-api-and-lifecycle.md): `GenClass.init`, `createRuntime`, `InitOptions.model`, `ready`/`status`, kill switch. - [decide-policy-actions.md](./decide-policy-actions.md): `DeciderQueue`, hold budget, policy gate, late revert, fail-open handling of provider errors. diff --git a/docs/agents/runtime/observe-and-trace.md b/docs/agents/runtime/observe-and-trace.md index 531df314..eced5840 100644 --- a/docs/agents/runtime/observe-and-trace.md +++ b/docs/agents/runtime/observe-and-trace.md @@ -2,7 +2,7 @@ > **Scope:** `packages/runtime/src/observe/*.ts` (fetch, xhr, dom-user, errors, nav, storage, perf, websocket, eventsource, messages, timers, cache), `packages/runtime/src/trace/*.ts` (events, ops, context), and the parts of `packages/runtime/src/runtime.ts` that install/uninstall observers and route their events (`installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runDelivery` (only the observer-facing side), `noteResponse`, `onChannel`, `destroy`). Also the helpers they depend on in `packages/runtime/src/util.ts`, `packages/runtime/src/clock.ts` and `packages/runtime/src/decide/exec.ts`. > **Read this when:** you change or debug how GenClass patches `fetch` / `XMLHttpRequest` / `WebSocket` / `EventSource` / timers / DOM events / history / Storage / errors / long tasks; how requests are held, faked, coalesced or served from cache; how a response or a pushed message is held at the delivery gate before the app sees it; how ops, op signatures, request identities and cause/root links are produced; how the ambient op is propagated across `await`; or what lands in the event ring buffer. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. If this doc and the code disagree, the code wins. ## TL;DR @@ -12,7 +12,7 @@ - The **ambient op** (`packages/runtime/src/trace/context.ts` -> `Context`) is the op whose work is running. `startOp` uses it as the `cause` and state writes use it as their writer. GenClass sets it in three ways. `run` sets it synchronously. `stick` sets it until `clock.afterTask` clears it at the end of the macrotask; `stick` happens when a wrapped fetch/Response body settles (or a held response is released), an XHR completes (or its held completion listeners run), a user action is recorded, a timer fires, a WebSocket/EventSource message is dispatched to the app, or `rt.op` settles. GenClass does **not** propagate context through arbitrary promises. - Timer callbacks get a **`LazyOp`**. It becomes a real `timer` op only when something calls `ctx.op()`. A `LazyOp`'s parent is always a real op or `null`, never another `LazyOp`, so recursive `setTimeout` loops never build a chain. - **Four network gates** (situation-v2). fetch: request gate (send / coalesce / delay / block / serve_cached), failure gate (deliver / retry / serve_cached), stall watch (wait / hedge / serve_cached), and the **delivery gate** (deliver / discard / defer) for successful responses. XHR: request gate (send / delay / block / serve_cached), delivery gate, and detection-only failures and stalls. WebSocket and EventSource: the delivery gate for every incoming message (`packages/runtime/src/observe/messages.ts` -> `MessageGate`), keeping per-channel order. The app's promise or event always arrives; holding is only latency; a failed action falls back to the passive one. -- **Holds need a non-passive action permitted by the mode** (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`). The default mode is now `observe` (commit f3636b2), which permits no non-passive action, so by default nothing is held at the request/failure/delivery gates; decisions are made in the background. One exception from code reading: the delivery gate reads the body (≤ 100 ms) *before* asking, so while the runtime is consultable (provider state `ready` or `off`; the default model host starts `off` until its idle preload runs) a response or message with a conflict can arrive a little later even in observe mode (see Drift). +- **Holds need a non-passive action permitted by the mode** (`RuntimeImpl.trigger`: `waits = opts.hold && permitted.length > 0 && !paused && expectedLatency() <= holdBudgetMs()`). The default mode is now `observe` (commit f3636b2), which permits no non-passive action, so by default nothing is held at the request/failure/delivery gates; decisions are made in the background. The delivery gate checks this up front (`RuntimeImpl.deliveryHoldable`, commit 054da38): when no hold is possible (observe, paused, model not `ready`, no permitted non-passive delivery action, or the model too slow for the hold budget) it releases the response/message synchronously, before any body read, and analyses it in the background. In observe a salient (or `always`) delivery then gets a background `delivery` decision in `decisions()` (if the model is `ready`); when the model picks a non-passive action that decision has `executed: false` and reason "observe mode never changes execution" (`packages/runtime/src/decide/policy.ts`). In guard/heal with a model too slow to hold for, the delivery is decided only when triage is `always` or a standing question forces it; its chain's writes get their own decisions (see §4). - Synchronous XHRs and `keepalive` fetches never raise a request trigger at all. - **Request identity** = FNV-1a of method + absolute URL + non-volatile headers + body content key. Bodies that cannot be read cheaply get a unique `uniq:N` key and so never match. - The response cache (`packages/runtime/src/observe/cache.ts` -> `ResponseCache`) has two parts: @@ -42,7 +42,7 @@ | `packages/runtime/src/trace/events.ts` | Event ring buffer | `EventLog` | | `packages/runtime/src/trace/ops.ts` | Op registry (plus the delivery fields `OpRec.delivery` and `OpRec.discardMark`) | `OpRegistry`, `OpRec`, `StartOpts`, `ChainWrite` | | `packages/runtime/src/trace/context.ts` | Ambient-op propagation | `Context`, `LazyOp`, `Ambient` | -| `packages/runtime/src/runtime.ts` | Wiring: installs observers, builds hosts, creates and ends ops, routes events and triggers, runs the delivery gate | `RuntimeImpl.installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runDelivery`, `noteResponse`, `onChannel`, `runAsGenClass`, `destroy` | +| `packages/runtime/src/runtime.ts` | Wiring: installs observers, builds hosts, creates and ends ops, routes events and triggers, runs the delivery gate | `RuntimeImpl.installObservers`, `netHost`, `timerHost`, `wsHost`, `onStorage`, `startOp`, `endOp`, `registerIdentity`, `user`, `reportError`, `op`, `emit`, `watchStall`, `runDelivery`, `deliveryHoldable`, `finalizeDeliveries`, `noteResponse`, `onChannel`, `runAsGenClass`, `destroy` | | `packages/runtime/src/decide/exec.ts` | Seam between observers and decisions | `NetHost` (incl. `deliver`, `noteResponse`), `Controller` (incl. `proceeded`, `stale`), `ActionEffect` (incl. `onRecord`), `EndOpts`, `TriggerOpts` | | `packages/runtime/src/util.ts` | URL parsing, signature normalisation, hashing, redaction | `parseUrl`, `normalizePath`, `isIdSegment`, `requestSignature`, `redactSearch`, `fnv1a`, `stableStringify`, `IDEMPOTENT_METHODS`, `isSensitiveName`, `isSensitivePath`, `defaultRedact` | | `packages/runtime/src/situation/content.ts` | JSON body parsing used by fetch, XHR and the message gate (out of scope; see [learn-situation-triage.md](learn-situation-triage.md)) | `parseJsonBody` | @@ -69,7 +69,7 @@ Terms specific to this doc (see also [../glossary.md](../glossary.md)): | controller | A `Controller` from `packages/runtime/src/decide/exec.ts`. `passive()` lets the subject proceed. `run(action)` performs a built-in action and returns `ActionEffect.changed`, or throws, in which case passive runs instead. | | gated | `NetHost.gated(op)`: `!paused && !destroyed && !op.genclass`. fetch and XHR raise request/failure/stall triggers only for gated ops (the `error` trigger from `reportError` does not use `gated`). | | synthetic end | `endOp(..., { synthetic: true })`: the op was answered by GenClass (block, cache or coalesce). It is kept out of latency baselines and transition profiles. | -| delivery gate | `RuntimeImpl.runDelivery`: a successful fetch/XHR response or a WebSocket/EventSource message is about to reach the app. Observers hand it a `release` callback; the gate calls it at most once, synchronously when nothing is salient. Trigger `delivery`, actions `deliver` (passive) / `discard` / `defer` (see [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md) for salience). | +| delivery gate | `RuntimeImpl.runDelivery`: a successful fetch/XHR response or a WebSocket/EventSource message is about to reach the app. Observers hand it a `release` callback; the gate calls it at most once, synchronously when nothing is salient or when no hold is possible (`deliveryHoldable` false: then any analysis and decision happen after the release, in the background). Trigger `delivery`, actions `deliver` (passive) / `discard` / `defer` (see [decide-policy-actions.md](decide-policy-actions.md) and [learn-situation-triage.md](learn-situation-triage.md) for salience). | | message gate | `MessageGate` (`packages/runtime/src/observe/messages.ts`): one per socket/stream. Its `message` (and custom-type) listener is the first one on the target for that type (GenClass's own `open`/`error`/`close` bookkeeping listeners are registered just before its `close`/`error` ones); it creates the message op, asks the delivery gate, and if held stops the event and re-dispatches a clone later, queueing later messages and `close`/`error` events behind it. | | channel down / up | `MsgHost.channel("down" \| "up", channel, path, code?)` -> `RuntimeImpl.onChannel`: a socket/stream that errored or closed (WebSocket: code ≠ 1000) and later re-opened on the same path marks the fields its messages wrote as possibly stale (F9). | @@ -180,9 +180,9 @@ Host interfaces (what each installer receives; all built in `packages/runtime/sr | Interface | Defined in | Members | |---|---|---| -| `NetHost` (fetch, XHR) | `packages/runtime/src/decide/exec.ts` | `clock`, `ctx`, `global`, `cache`, `redact()`, `baseHref()`, `startOp(kind, name, o)`, `endOp(op, status, o?)`, `gated(op)`, `trigger(spec, ctl, opts)`, `watchStall(op, req, ctl)`, `failureStreak(sig)`, `emit(name, data?, op?)`, `deliver({ op, req, status, body? }, release)` (-> `runDelivery` with channel `response`), `noteResponse?({ op, req, status, body })` (read-your-writes: remembers ids returned by POST/201 responses), `uniqueId()`, `setIdentity(op, req, identity)` | +| `NetHost` (fetch, XHR) | `packages/runtime/src/decide/exec.ts` | `clock`, `ctx`, `global`, `cache`, `redact()`, `baseHref()`, `startOp(kind, name, o)`, `endOp(op, status, o?)`, `gated(op)`, `trigger(spec, ctl, opts)`, `watchStall(op, req, ctl)`, `failureStreak(sig)`, `emit(name, data?, op?)`, `deliver({ op, req, status, body? }, release)` (-> `runDelivery` with channel `response`; a `body` function carrying a synchronous `body.now`, as XHR's does, is passed on as `bodyNow`), `noteResponse?({ op, req, status, body })` (read-your-writes: remembers ids returned by POST/201 responses), `uniqueId()`, `setIdentity(op, req, identity)` | | `TimerHost` | `packages/runtime/src/observe/timers.ts` | `global`, `ctx`, `lazyTimer(parent, label)` | -| `MsgHost` (= `WsHost`; WebSocket and EventSource) | `packages/runtime/src/observe/messages.ts` | `global`, `ctx`, `redact()`, `baseHref()`, `startOp(name, o)` (kind fixed to `ws`), `endOp(op, status, o?)`, `event(name, data, op?)` (a `custom` event), `deliverMessage({ op, channel, message: { path, summary }, queuedAhead, body? }, release)` (-> `runDelivery`), `channel?(state, channel, path, code?)` (-> `onChannel`) | +| `MsgHost` (= `WsHost`; WebSocket and EventSource) | `packages/runtime/src/observe/messages.ts` | `global`, `ctx`, `redact()`, `baseHref()`, `startOp(name, o)` (kind fixed to `ws`), `endOp(op, status, o?)`, `event(name, data, op?)` (a `custom` event), `deliverMessage({ op, channel, message: { path, summary }, queuedAhead, body?, bodyNow? }, release)` (-> `runDelivery`; `bodyNow` = the parsed message, read synchronously), `channel?(state, channel, path, code?)` (-> `onChannel`) | | `UserSink` (module-private) | `packages/runtime/src/observe/dom-user.ts` | `untrusted?` (= `observe.untrustedEvents`), `user(action, handler?)`, `ambientKind?()`, `runningKind?()` | | `ErrorSink` (module-private) | `packages/runtime/src/observe/errors.ts` | `reportError(error, info?)` (the `RuntimeImpl` itself is passed) | | nav / storage / perf | their files | plain callbacks: `onNav(route)`, `cb(area, op, key)`, `cb(name, duration)` | @@ -198,7 +198,7 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi 3. Hosts: - `netHost()` (`NetHost`) serves fetch and XHR. It provides `gated`, `trigger` (`RuntimeImpl.trigger`), `watchStall`, `failureStreak(sig)` (= `base.stats(sig)?.failStreak ?? 0`), `uniqueId()` (= `uniq:${++n}`), `setIdentity` (updates `op.identity` and `req.identity`, then re-registers), `emit` (a `custom` event) and `baseHref()` (= `global.location.href`). - `timerHost()` provides `lazyTimer(parent, label)` = `new LazyOp(parent, cause => startOp("timer", label, { cause, instant: true }))`. - - `netHost().deliver` calls `runDelivery({ ..., channel: "response" }, release)`; `noteResponse` remembers the ids a POST or 201 response returned (`createsBuf`, ≤ 16 entries, 30 s) for read-your-writes facts. + - `netHost().deliver` calls `runDelivery({ ..., channel: "response", bodyNow? }, release)` (`bodyNow` = `body.now` when the observer provides it: XHR); `noteResponse` remembers the ids a POST or 201 response returned (`createsBuf`, ≤ 16 entries, 30 s) for read-your-writes facts. - `wsHost()` (a `MsgHost`, shared by WebSocket and EventSource) maps `startOp` to kind `ws`, `event` to a `custom` event, `deliverMessage` to `runDelivery`, and `channel` to `onChannel`. Its `baseHref()` returns `global.location?.href` without the string check `netHost` does. 4. Routing: - DOM user actions go to `RuntimeImpl.user`, with `ambientKind` and `runningKind` callbacks (a `LazyOp` reports as `"timer"`). @@ -206,7 +206,7 @@ Decision seam types (`packages/runtime/src/decide/exec.ts`): `Controller { passi - Nav, perf and storage become events only. They never raise triggers. 5. `destroy()` sets `destroyed` and runs every uninstall in reverse order, then unregisters plugins and calls `ctx.clear()`. It does **not** clear `ResponseCache`. Full order (`RuntimeImpl.destroy`, idempotent): 1. `destroyed = true`, `hub.gating = false`; - 2. `queue.dispose()` (`packages/runtime/src/decide/decider.ts` -> `DeciderQueue`): every *queued* decision resolves `null`, so `RuntimeImpl.trigger` runs the controller's `passive()` (it checks `destroyed` first). The one decision already being evaluated ends when the provider answers or its deadline timer fires, and the hold-budget timer is not cleared by `destroy()`, so it also runs `passive()`. Either way a held fetch or XHR is **sent** (not dropped), a held failure is delivered, and a held response or WebSocket/EventSource message is released to the app; + 2. `queue.dispose()` (`packages/runtime/src/decide/decider.ts` -> `DeciderQueue`), then `deliveryAnalysis.clear()` (drops the "decide at the chain's first write" hooks of no-hold fetch deliveries still waiting for their body; a body or `BODY_WAIT_MS` timer that fires later finds the runtime destroyed, so `trigger` only runs passive on an already released delivery): every *queued* decision resolves `null`, so `RuntimeImpl.trigger` runs the controller's `passive()` (it checks `destroyed` first). The one decision already being evaluated ends when the provider answers or its deadline timer fires, and the hold-budget timer is not cleared by `destroy()`, so it also runs `passive()`. Either way a held fetch or XHR is **sent** (not dropped), a held failure is delivered, and a held response or WebSocket/EventSource message is released to the app; 3. `reporter.dispose()`, clear the settle and persist timers; 4. run `uninstall` in reverse (observers, decider status listener); 5. `unuse` every plugin, `unsubscribeIO` every store, `ctx.clear()`, dispose the decider if the runtime owns it. @@ -337,8 +337,9 @@ Stall (`RuntimeImpl.watchStall`, armed by `send` for gated primary sends): Delivery gate (fetch side; the gate itself is `RuntimeImpl.runDelivery`, see [decide-policy-actions.md](decide-policy-actions.md)): - Raised only for a primary send's non-failed response (status not ≥ 500/429/408), gated, not yet answered. 4xx responses pass through it too. Hedge answers, `block`/`serve_cached`/`coalesce` answers and failures do not. -- `release` = `answer(res)`: the app's `await fetch()` resolves (with the op stuck) only after the release. `runDelivery` releases synchronously when nothing is salient (no conflict on the op's predicted write fields, no text typed into those fields since the op started, triage not `always`), when the runtime is not consultable/paused/destroyed, or for `genclass` ops. -- With a conflict (or typed text, or triage `always`) and a `body` function, it first waits for the body (≤ `BODY_WAIT_MS` = 100 ms, `runtime.ts`), analyses it, and only then decides salience and raises the `delivery` trigger (`hold: true, priority: 2`). So the release is asynchronous for such responses whatever the mode. Without a `body` (an untracked fetch) it decides at once from newer-data conflicts only. When the body shows every conflicting field would be unchanged, it pushes a `custom` `delivery.unchanged` event and (unless triage is `always`) releases without asking. +- `release` = `answer(res)`: the app's `await fetch()` resolves (with the op stuck) only after the release. `runDelivery` releases synchronously when nothing is salient (no conflict on the op's predicted write fields, no text typed into those fields since the op started, triage not `always` and no standing question with `always` on `delivery`), when the runtime is not consultable/paused/destroyed, or for `genclass` ops. +- **No-hold path** (commit 054da38). With a conflict (or typed text, or `always`) it next asks `RuntimeImpl.deliveryHoldable(op, matched, defers)`. That is false in `observe` mode, while paused, when the model's state is not `ready` (also `off`, which `consultable()` accepts), when mode and policy permit no non-passive delivery action (`defer` counts only with related work in flight and fewer than 2 defers; a permitted custom delivery action counts), or when `expectedLatency() > holdBudgetMs()`. Then the response is released **synchronously, before any body read**: the app gets it in the same task as without GenClass. The analysis follows in the background on the state the response was delivered into: fetch has no `bodyNow`, so the body is read from the buffered clone (≤ `BODY_WAIT_MS`) but not waited for past the first write of the delivery's chain (`finalizeDeliveries`, called from the hub's `proposed` hook: with newer data or `always` it decides without the body; otherwise it marks the delivery salient and undecided, so its writes get their own `mutation` decisions and F1/F2 is not lost); an untracked fetch (no `body`) is settled at once from newer-data conflicts only. The decision is raised with `hold: false` only when salient or `always`; `markOverNewer` runs first (F9). In observe the delivery is added to `deliveryPending` while its decision is pending, so `covered()` treats its chain's predicted writes as covered (no second decision on the same writes); in guard/heal (the model only too slow) the chain's writes keep their own decisions and late revert instead, and the delivery itself is decided only when a question forces it or triage is `always` (`RuntimeImpl.trigger` -> `writesAct`). A background delivery decision is never dropped as stale and can only take the passive action (`onDecision`: `proceeded`). +- **Hold path** (a hold is possible: guard/heal with a `ready`, fast enough model). With a `body` function it first waits for the body (≤ `BODY_WAIT_MS` = 100 ms, `runtime.ts`), analyses it, and only then decides salience and raises the `delivery` trigger (`hold: true, priority: 2`). Without a `body` (an untracked fetch) it decides at once from newer-data conflicts only. When the body shows every conflicting field would be unchanged, it pushes a `custom` `delivery.unchanged` event and (unless `always`) releases without asking. - Actions: `deliver` (passive) releases (and marks `op.delivery.overNewer` when delivered over newer data); `discard` releases and sets `op.discardMark` so this chain's writes to the conflicting paths are dropped for 10 s (`ActionRecord.dropped` lists them; `undo` restores); `defer` waits for related in-flight ops, then runs `runDelivery` again (at most 2 defers). - Request-gate controllers now also expose `proceeded()` (`sent || answered`) and `stale()` (not sent and the app's signal aborted), so a queued decision about a request the app already aborted is dropped before it reaches the model. The failure controller exposes `proceeded()` (`handled || answered`). @@ -378,7 +379,7 @@ The app's promise always settles. Every action that throws or rejects makes `Run 6. `arrive(xhr, st)` (the first completion event of a response, from the app's wrapper or GenClass's own `readystatechange` listener, whichever runs first; runs once per request): - Returns without gating when there is no op/req, the op already ended, `failed` is set, status is 0, or status is a failure (≥ 500, 429, 408): failures are handled at `loadend` (step 7). - Otherwise it **ends the op `ok` with the status now** (at readyState 4, before `loadend`) and sticks it. If not gated, done. - - If gated: for a non-GET/HEAD response with status < 300, `host.noteResponse(...)`; then `dlv = "held"` and `host.deliver({ op, req, status, body }, release)`. `body` is `xhrJson(xhr)`: `response` for `responseType` `json`, `parseJsonBody(responseText)` for `""`/`"text"`, else `undefined`. + - If gated: for a non-GET/HEAD response with status < 300, `host.noteResponse(...)`; then `dlv = "held"` and `host.deliver({ op, req, status, body }, release)`. `body` is `xhrJson(xhr)`: `response` for `responseType` `json`, `parseJsonBody(responseText)` for `""`/`"text"`, else `undefined`. The `body` function also carries `body.now` (the same read, synchronous), so on the no-hold path (observe mode, see §4) the gate releases at once and analyses the in-memory body before the app's completion listeners run, for detection only. - `release` sets `dlv = "open"`; if it came asynchronously, it sticks the op and runs the queued app calls in order (a throw is passed to `global.reportError`, else `console.error`). A release after an `abort()` is ignored. 7. `onEnd` (on `loadend`): - Returns at once if the op already ended (the `arrive` path ended it). @@ -508,7 +509,7 @@ The app's promise always settles. Every action that throws or rejects makes `Run 2. `intercept(e)` for a fresh event: - creates the message op **synchronously inside the dispatch**: instant, `cause: null` (a root), detail = summary, name per channel (§10/§10a). `hooks.opCreated` therefore fires before any app listener. It pushes the `ws.message`/`sse.message` `custom` event. A throw here leaves the event alone (tracing never breaks a channel); - if messages are already queued, it stops the event (`stopImmediatePropagation`) and queues it behind them (order kept); - - else it asks the delivery gate (`deliverMessage`, `queuedAhead: 0`, `body` = `parseJsonBody(data)`). Released synchronously: it sticks the op and lets the event continue to the app's listeners. Not released yet: it stops the event and queues it. + - else it asks the delivery gate (`deliverMessage`, `queuedAhead: 0`, `body` = `parseJsonBody(data)`, `bodyNow` = the same parse, synchronous). Released synchronously: it sticks the op and lets the event continue to the app's listeners. Not released yet: it stops the event and queues it. When no hold is possible (observe mode, see §4) the release is always synchronous, so the app gets the original event (no clone) inside the original dispatch, and, when the message conflicts (or `always`), its content is analysed through `bodyNow` before its listeners run; the decision follows in the background. (A message that arrives while older ones are still queued, e.g. held before a switch to observe, still waits behind them.) 3. `orderOnly(e)` (close/error): if anything is queued, stops the event and queues it (ready) so it keeps its place; otherwise does nothing. 4. `pump()` (on each asynchronous release) dispatches ready items in order. Each is a **clone** (`cloneEvent`: a new `MessageEvent` with `data`, `origin`, `lastEventId`, `ports`; a new `CloseEvent` with `code`, `reason`, `wasClean`; else a plain `Event`), built with the module's `globalThis` constructors. The clone is remembered (`mine`), so `intercept` only sticks its op and lets it through. When the next queued message reaches the head it gets its own decision. `queuedAhead` is computed as `first ? 0 : queue.indexOf(item)`, but a decision is only ever asked for a fresh message on an empty queue or for the queue's head, so in practice it is always 0. 5. Consequences for apps: a held message reaches the app as a different event object with `isTrusted === false` and no `source`; listeners on the socket see it in the original order relative to other messages and to `close`/`error`. Because the gate registers `message`/`close`/`error` in the constructor (and an EventSource custom type just before the app's first listener for it), every app listener and `on*` handler of the instance runs after it. GenClass's own `close`/`error` bookkeeping listeners run before the gate, so a close queued behind a held message is still recorded (and reported to `onChannel`) at once; only the app's view of it waits. @@ -630,8 +631,9 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store - Parsing errors fall back to `nativeFetch`. - Tracing code inside wrapped methods (nav `pushState`/`replaceState`, storage methods, the message gate's op creation, WebSocket `send`, `channel` reports, the WebSocket/EventSource connect `startOp`) is wrapped in try/catch. A listener that throws during a gate re-dispatch (`MessageGate.pump`) is swallowed there (the platform reports it); a queued XHR completion call that throws goes to `global.reportError`. The DOM-user, XHR-state and error listeners are **not**; they are separate listeners, so a throw there is reported as an uncaught error rather than stopping the app's own handlers. - Installers that throw are skipped (`tryAdd`). - - The app's fetch promise always settles: every controller path ends in `answer`, `sendNow` or the original rejection. Every delivery-gate path ends in exactly one `release` (passive, `discard`, a `defer` that re-runs the gate, the hold budget, or `destroy()`). + - The app's fetch promise always settles: every controller path ends in `answer`, `sendNow` or the original rejection. Every delivery-gate path ends in exactly one `release` (the synchronous no-hold release, passive, `discard`, a `defer` that re-runs the gate, the hold budget, or `destroy()`). The background analysis of a no-hold delivery (`bodyNow`, `finish`, `finalizeDeliveries`) is wrapped in try/catch and never breaks the delivery. - **Holding is only latency.** The delivery gate never alters a response or message; it only decides when the app sees it, and keeps a channel's order (messages, then `close`/`error`). Never reorder or drop a message in the gate. + - **Observe mode adds no latency at the delivery gate** (`test/observe-delivery.test.ts`). When `deliveryHoldable` is false, `runDelivery` must call `release` before reading any body or calling `trigger`; any analysis that needs the body runs after the release (or synchronously through `bodyNow`, before the app's listeners). Do not move a body read or a decision in front of that release. - Keep these properties when you edit. **Pass-through after destroy.** @@ -699,7 +701,7 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store - Every request with a non-empty identity has a clone of its response buffered: up to 256 KB and up to 1 s of streaming. - Each keystroke creates a user op, even though typing bursts share one event. - In-flight ops (a connecting WebSocket or EventSource, a long poll) delay settled points for up to 10 s each. -- The delivery gate is cheap when nothing conflicts (synchronous release, no body read). With a conflict it parses the response/message JSON (fetch: from the buffered clone; XHR: `responseText`/`response`; messages: `data`). +- The delivery gate is cheap when nothing conflicts (synchronous release, no body read). With a conflict it parses the response/message JSON (fetch: from the buffered clone; XHR: `responseText`/`response`; messages: `data`). On the no-hold path (observe) the XHR and message parse runs synchronously inside the delivery, before the app's listeners, adding that parse cost (not a wait) to the task. - Every XHR completion listener and `on*` handler runs through a wrapper; every WebSocket/EventSource message gets an op and costs one ring-buffer event (the `custom` one; instant `ws` ops push no `op.start`). A chatty socket can therefore push older events out of the 500-event buffer. **XHR.** @@ -790,7 +792,8 @@ Transition profiles use a different normaliser, `normalizeFieldPath`, for store 6a. **Touch a delivery-gate hookup** (fetch `host.deliver`, XHR `arrive`/`gateCall`, `MessageGate`). - Keep: `release` runs at most once; synchronous release means the app sees the response/message in the same task as without GenClass; asynchronous release sticks the op before the app's code runs; order per channel/XHR is kept; abort during a hold drops the response (XHR) or the request (`stale()`). - Failures, faked answers and hedges must not reach the delivery gate (they have their own gates). - - Run `test/delivery.test.ts`, `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts` and `test/default-mode.test.ts`. + - Keep the no-hold path: when `deliveryHoldable` is false, release first, then analyse; pass a synchronous `bodyNow` when the body is already in memory. + - Run `test/delivery.test.ts`, `test/observe-delivery.test.ts`, `test/content.test.ts`, `test/no-reorder.test.ts`, `test/smoke.test.ts`, `test/default-mode.test.ts` and `test/policy.test.ts`. 7. **Change DOM recording.** - Edit the handler table in `installDomUser`. Keep the `stopped || ignoredEvent(e) || programmatic(e)` guard, the `untrustedEvents` opt-in, `originOf` (composed path) for the target, and the rule that sensitive fields record `""`. - Run `test/dom.test.ts` and `test/review-dom.test.ts` (happy-dom). happy-dom events have `isTrusted === undefined` and count as trusted, so these tests need `untrustedEvents` only to test the filter itself (set `isTrusted: false` with `Object.defineProperty`, as `dom.test.ts` does). Real-browser drivers that dispatch events need `observe: { user: true, untrustedEvents: true }`. @@ -814,7 +817,9 @@ All paths are under `packages/runtime/test/`. | `delivery.test.ts` (16 `it` blocks; STATUS.md says 14) | The delivery gate end to end: clean typeahead makes zero model calls; a stale out-of-order fetch response gets a `delivery` decision and `discard` drops only the stale field; holding is only latency; no hold when the model cannot answer within the budget; store writes are not held by default; superseded queued decisions are dropped; WebSocket messages held in order with `discard`; messages touching nothing pending deliver at once; EventSource custom event types; XHR completion listeners (before/after `open`, `on*`) held in order, op ambient, `removeEventListener` of a wrapped listener, `abort()` during the hold. Uses fake `WebSocket`/`EventSource` classes passed through `extraGlobal` | | `content.test.ts` | Body-content salience (F1/F2/F3), F9 provenance (incl. "a live channel that was down: the fields its messages wrote may have missed updates", which exercises `channel` down/up), F5–F8, read-your-writes (`noteResponse`) | | `no-reorder.test.ts` | An always-passive model in guard/heal gives the same dispatches, order and final state as observe mode | -| `default-mode.test.ts` | No `mode` means `observe`; observe never holds writes or requests and never waits for a model that never answers (fetch success and 500 both delivered at once). It does not cover the delivery gate with a conflict | +| `observe-delivery.test.ts` (11 `it` blocks, commit 054da38) | The no-hold delivery path. Observe, fetch: a conflicting response with a slow body resolves at the network time and its background decision is recorded and reported (its writes are not decided again); the decision sees the state the response was delivered into; an app write before the body is read decides the delivery at that write; F1 (puts back what a pending local change replaced) is not lost when the write comes first; standing questions on delivery are answered. Observe, XHR: listeners run inside the original dispatch, after the body was analysed. Observe, push channels: a WebSocket message is delivered synchronously inside the dispatch and decided in the background with its content; EventSource messages with triage `always` stay in order and are each decided. Guard is unchanged: a stale response is held until its decision (`discard`); with a model too slow to hold for, the response is released at once and its stale write is decided and late-reverted on its own; a standing `always` delivery question decides without acting | +| `default-mode.test.ts` | No `mode` means `observe`; observe never holds writes, requests or responses and never waits for a model that never answers (fetch success and 500 both delivered at once); with triage `always` the response's `delivery` decision is recorded too (`executed: false`) and reported as a detection | +| `policy.test.ts` (this scope) | "observe mode never holds: writes, requests and responses proceed while decisions are still reported": `mutation`, `request` and `delivery` decisions, all `executed: false` with a reason matching `/observe mode/` (the gate's reason is "observe mode never changes execution"; the script picks non-passive actions) | | `fetch.test.ts` | Neutral traffic makes no model call. The app reads its own body while GenClass reads a clone. `coalesce` reuses an in-flight POST (`x-genclass: coalesced`). `block` returns 503 `blocked` in heal mode, and guard never runs heal actions. `serve_cached` works. `delay` = 250 ms at streak 0. `retry` backs off 200 ms and the app gets attempt 2. `retry` is not offered for stream bodies. A network error is delivered as the original `TypeError`. Failure and request gates fail open at 300 ms. `hedge` wins a stall. Abort before send records `aborted`. `TimeoutError` gives `code: "timeout"`. The GET cache keeps ≤ 64 entries and skips > 256 KB. `destroy()` restores fetch | | `review-fetch.test.ts` (its `headless()` now passes `mode: "guard"`) | `Request` bodies are part of the identity. `Range` splits the identity. Coalescing with opaque or streaming responses settles. Buffer memory ≤ 64 × 256 KB. No abort-listener leak. No work after destroy even when wrapped on top. Failures are not held in guard mode (app sees the 503 at +50 ms). `keepalive` is sent synchronously. Identical-request "after/before" direction and error-rate facts | | `xhr.test.ts` | Op name, detail and cause. The op is ambient in `onload` (the write is attributed to it). `block` fakes a 503 `blocked` without sending. A failure is observed with no action question. The request gate holds and fails open at 300 ms. `destroy()` restores `open`/`send` | @@ -829,9 +834,9 @@ All paths are under `packages/runtime/test/`. | `situation.test.ts` | Determinism: the same scripted inputs on a fake clock give identical situations (depends on sequential op ids and identities) | | `review-perf.test.ts` | Cost with 5,000-item stores: a user-sync keystroke write through `rt.user` (< 1 ms/write), an async gated write (< 2 ms), a redux-style dispatch (user < 1 ms, async < 2 ms), and a settled point. Run alone (CI: separate step with `--retry=2`); its bounds flake under parallel load | -Coverage gaps: there are no unit tests for WebSocket connect ops, causality of `WS send`, or close codes other than through `content.test.ts`'s channel case; the perf observer; `sessionStorage` area detection; XHR `serve_cached`/`delay`; XHR `responseType` faking; nav redaction; stall `serve_cached`; interval-tick causality; what existing WebSockets/EventSources/timers do after `destroy()`; two runtimes on one page; the delivery gate in `observe` mode with a conflict; the XHR `on*` getter returning the wrapper; cloned-event fidelity in `MessageGate`; and `EventLog`/`OpRegistry` in isolation (they are exercised only through the runtime). The Playwright specs under `test/browser/` cover the model host and the devtools UI, not the observers; the realapps harness exercises the observers in real browsers but is a data generator, not a test suite (see [../realapps.md](../realapps.md)). +Coverage gaps: there are no unit tests for WebSocket connect ops, causality of `WS send`, or close codes other than through `content.test.ts`'s channel case; the perf observer; `sessionStorage` area detection; XHR `serve_cached`/`delay`; XHR `responseType` faking; nav redaction; stall `serve_cached`; interval-tick causality; what existing WebSockets/EventSources/timers do after `destroy()`; two runtimes on one page; the XHR `on*` getter returning the wrapper; cloned-event fidelity in `MessageGate`; and `EventLog`/`OpRegistry` in isolation (they are exercised only through the runtime). The Playwright specs under `test/browser/` cover the model host and the devtools UI, not the observers; the realapps harness exercises the observers in real browsers but is a data generator, not a test suite (see [../realapps.md](../realapps.md)). -Last local run by the lead (2026-10-08, mvp-v2 at b435acb): 40 files passed + 1 skipped, 332 tests passed + 14 skipped, plus `review-perf` alone 4 passed. Not run: Playwright, smoke.sh, realapps. +Last local run (2026-10-08, `mvp-v2-merge` at f107013, `packages/runtime`): `vitest run` without `review-perf`: 44 files passed + 1 skipped, 375 tests passed + 14 skipped; `review-perf` alone 4 passed. Not run: Playwright, smoke.sh, realapps. ## Drift and open issues @@ -839,7 +844,6 @@ Doc-vs-code mismatches (the code is right): | What | Doc says | Code does | |---|---|---| -| Observe mode and the delivery gate | `types.ts` `InitOptions.mode` JSDoc (f3636b2) and `test/default-mode.test.ts` header: observe "never holds, delays or changes anything" | `runDelivery` does not check the mode. While the runtime is consultable (provider state `ready` or `off`), for a response or message with a conflict (or `triage: "always"`) it reads the body (≤ `BODY_WAIT_MS` = 100 ms) before calling `trigger`, which then runs passive at once. So in observe mode the app's `fetch` promise resolves, and XHR completion listeners run, asynchronously; a WebSocket/EventSource message is stopped and **re-dispatched as a clone** (`isTrusted` false, no `source`) after a microtask or more. From code reading; no test covers observe mode with a conflict (`test/default-mode.test.ts` runs with triage `always`, so its fetches do take the body-read path, but it only checks the status after advancing the clock 5 ms, not same-task delivery) | | Untrusted DOM events | `packages/runtime/STATUS.md` ("Precision" list): untrusted events are not user actions only "while a non-user op is ambient" | Since batch 4 they are dropped unless `observe.untrustedEvents: true` (`dom-user.ts` -> `programmatic`). STATUS's batch-4 section, its `observe` defaults bullet (under "How to drive it headless") and API.md are correct | | Trusted-event filtering | `docs/runtime/ARCHITECTURE.md`: "DOM user events (capture phase, trusted events only)" | Correct by default now; it omits the `untrustedEvents` opt-in, EventSource and timers | | `observe` default | `types.ts`: two JSDoc blocks precede `InitOptions.observe`; the first still says "Default: all true (where the global supports them)" | The second block is right: all on, `timers` only with a document, `untrustedEvents` false | @@ -861,11 +865,10 @@ Doc-vs-code mismatches (the code is right): | Which timer callbacks get context | CONTRACT §3 and API.md: "timer callbacks scheduled while an op was ambient" / "inside timers scheduled during an operation" | Every wrapped timer callback gets a `LazyOp`; with no ambient op at schedule time it materialises as a root `timer` op (`timers.ts`) | | Abort-listener removal | STATUS "Memory": "the abort listener is removed when the request settles" | Removed when the request is **sent** (`send`, primary) or answered (`answer`), whichever comes first (`fetch.ts` -> `runRequest` -> `unlisten`) | -Resolved since 654d822 (the situation-v1 version of this doc): WebSocket disconnects after `open` being invisible (they now reach `onChannel`, though still with no op or event); "an app `onreadystatechange` assigned before `open()` misses the ambient op" (now true only for failed responses, see Invariants). +Resolved since 654d822 (the situation-v1 version of this doc): WebSocket disconnects after `open` being invisible (they now reach `onChannel`, though still with no op or event); "an app `onreadystatechange` assigned before `open()` misses the ambient op" (now true only for failed responses, see Invariants); observe mode not being zero-delay at the delivery gate (the gate read the body, ≤ 100 ms, before asking, and re-dispatched held WebSocket/EventSource messages as clones even in observe): fixed in 054da38 by the no-hold path (§4), so the `observe` promise in the `types.ts` `InitOptions.mode` JSDoc and the `test/default-mode.test.ts` header now holds for deliveries too (`test/observe-delivery.test.ts`). Open issues (from code reading; none has a test unless stated): -- Observe mode is not strictly zero-delay at the delivery gate (first row of the table). Either `runDelivery` should release before reading the body when the mode permits no delivery action, or the observe-mode promise should be reworded. Needs an owner decision; changing it does not touch situation text. -- `MessageGate` re-dispatches held messages as clones: `e.isTrusted` is false, `source` is lost, and the clone is built with the module's `globalThis` constructors rather than `host.global`'s. Apps that check event identity or `isTrusted` behave differently for held messages. +- `MessageGate` re-dispatches held messages (guard/heal only; observe never holds) as clones: `e.isTrusted` is false, `source` is lost, and the clone is built with the module's `globalThis` constructors rather than `host.global`'s. Apps that check event identity or `isTrusted` behave differently for held messages. - The unit tests cannot catch a regression that drops genuinely untrusted events in the wrong place: happy-dom leaves `isTrusted` undefined (treated as trusted), so only `dom.test.ts`'s forced-`isTrusted: false` test exercises the untrusted branch. Real-browser behaviour is covered only by the realapps harness (a data generator, not a test). - Nav routes, including query strings and fragments, are not redacted. They go into `nav` events and are always "relevant" in situation timelines (`situation/build.ts` -> `timelineLines`). - `ResponseCache` is not cleared on `destroy()`. @@ -882,7 +885,7 @@ Open issues (from code reading; none has a test unless stated): From STATUS.md / HANDOFF.md / OPEN_TASKS.md / training/NEEDS.md (relevant here): - The `situation-v2` freeze (tag 6e5e86e): HANDOFF.md says any change to `packages/runtime/src/situation/*` changes the training format. Op names, details and event names, element descriptions and the `ws`/`sse` event names reach situation text, so they fall under the same rule. As of 2026-10-08 SIM is generating situation-v2 data on 20 Azure nodes and REAL on 3 (training/NEEDS.md), so a wording change now invalidates data being produced. -- No situation-v2 model exists yet (HANDOFF: teacher on v2 gold → distillation → DAgger → EVAL → `@genclass/runtime-model@0.1.0`). Until then the delivery gate and every other gate run passive in practice (the provider is not ready, so `trigger` runs passive). The delivery gate's body read still happens while the default model host is in state `off` (before its idle preload starts, or with `preload: "lazy"`), because `consultable()` accepts `off`; once the load fails (state `error`) everything releases synchronously. +- No situation-v2 model exists yet (HANDOFF: teacher on v2 gold → distillation → DAgger → EVAL → `@genclass/runtime-model@0.1.0`). Until then the delivery gate and every other gate run passive in practice (the provider is not ready, so `trigger` runs passive). While the default model host is in state `off` (before its idle preload starts, or with `preload: "lazy"`) `consultable()` accepts it, but `deliveryHoldable` requires `ready`, so a conflicting delivery is released synchronously and only analysed in the background (its `trigger` then starts the lazy load and runs passive: no decision is recorded); once the load fails (state `error`) everything releases synchronously with no analysis. - OPEN_TASKS.md: batch 4 (the delivery gate, EventSource, `untrustedEvents`) was the redesign answering "hold-induced harm" from the v0.1 demo eval (search clean-run latency 14 ms → 125 ms because salient *writes* were held; typeahead salient about 6 times per trial). Item 10 (demo rerun) lists triage sensitivity for re-investigation once a v2 model exists; the delivery tests claim zero model calls for clean typeahead. - Known risk: on slow devices, hold budgets expire more often (more fail-open decisions); batch 4's "hold only when it can help" rule (`expectedLatency() <= holdBudgetMs()`) reduces holds that would only expire. diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md index fbcecf68..f74a4619 100644 --- a/docs/agents/runtime/public-api-and-lifecycle.md +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -1,16 +1,17 @@ # @genclass/runtime: public API, options and lifecycle -> **Scope:** `packages/runtime/src/index.ts`, `packages/runtime/src/runtime.ts` (wiring, construction, init/destroy, modes, kill switch, option resolution, events, plugins, introspection, settled points, the delivery gate and background write observation as seen from the facade), `packages/runtime/src/types.ts`, `packages/runtime/src/errors.ts`, `packages/runtime/src/clock.ts`, `packages/runtime/src/util.ts`, `packages/runtime/package.json`. -> **Read this when:** you add or change an init option, a `Runtime` method, an event, a plugin hook or a subpath export; you touch `GenClass.init` / `createRuntime` / the kill switch / `destroy()`; you need the exact default of any option (the default mode is now `observe`); you add timing or scheduling code; you wire a new subsystem into `RuntimeImpl`. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Scope:** `packages/runtime/src/index.ts`, `packages/runtime/src/runtime.ts` (wiring, construction, init/destroy, modes, kill switch, option resolution, events, plugins, introspection, settled points, the delivery gate and background write observation as seen from the facade), `packages/runtime/src/types.ts`, `packages/runtime/src/errors.ts`, `packages/runtime/src/clock.ts`, `packages/runtime/src/util.ts`, `packages/runtime/package.json`; the consumer-facing side of the zero-code entries (`packages/runtime/src/auto.ts`, `packages/runtime/src/cdn/*`, `packages/runtime/bin/genclass-runtime.mjs` `init`/`remove`); their internals (framework detection, edit planning, the CDN worker and onnxruntime bundling) belong to INSTALL and are only summarised here. +> **Read this when:** you add or change an init option, a `Runtime` method, an event, a plugin hook or a subpath export; you touch `GenClass.init` / `createRuntime` / the kill switch / `destroy()`; you touch `@genclass/runtime/auto*`, the script-tag global (`window.GenClass`) or `genclass-runtime init|remove`; you need the exact default of any option (the default mode is `observe`); you add timing or scheduling code; you wire a new subsystem into `RuntimeImpl`. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes 054da38, f107013), 2026-10-08. origin/runtime has since moved past eff18cb (ca08174..5bc40c9: realapps wave 4, runtime batch 6 with model-provided gate thresholds, tag `situation-v2.1`); none of that is merged here or described in this doc. If this doc and the code disagree, the code wins. ## TL;DR - Two entry points: `GenClass.init(options)` (browser facade: singleton, never throws, kill switch, loads the local model by default) and `createRuntime(options)` (headless: tests, sim, SSR; no model unless `decider` or `model: {...}` is passed). Both return a `RuntimeImpl` typed as `Runtime`. `createRuntime` can throw on malformed options; `GenClass.init` never throws (it falls back to an inert runtime). - `GenClass.init` is idempotent: a second call returns the first runtime and **ignores its new options**. Only `GenClass.destroy()` clears the singleton; `rt.destroy()` alone does not. -- Three modes: `observe` (**default** on `mvp-v2` since f3636b2: `o.mode ?? "observe"` in `RuntimeImpl`'s constructor; never changes execution, nothing held, decisions still made in the background and reported), `guard` (opt-in; guard-tier actions only), `heal` (experimental; guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. The published `0.1.0-alpha.0` on npm still defaults to `guard`. +- Zero-code entries (merged from origin/runtime f3a9dd1; **not** in the published `0.1.0-alpha.1`, they ship in the next version): `import "@genclass/runtime/auto"` (and `/auto/observe`, `/auto/guard`, `/auto/heal`), the script tag `dist/genclass.global(.min).js` (exposes `window.GenClass`), and the CLI `npx @genclass/runtime init|remove`. All of them end in `GenClass.init`, so the singleton, the kill switch and the defaults below apply unchanged. See [Zero-code entries](#zero-code-entries-auto-script-tag-cli). +- Three modes: `observe` (**default** on `mvp-v2` since f3636b2: `o.mode ?? "observe"` in `RuntimeImpl`'s constructor; never changes execution, nothing held or delayed (since 054da38 also no response/message delivery), decisions still made in the background and reported), `guard` (opt-in; guard-tier actions only), `heal` (experimental; guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. The npm `0.1.0-alpha.0` and origin/runtime (through eff18cb, and still at 5bc40c9) default to `guard`; npm `0.1.0-alpha.1` defaults to `observe`. The `init` CLI still assumes `guard` is the default (see Drift). - The unit-test harness (`test/helpers.ts` -> `setup`) passes `mode: "guard"` explicitly, because most CORE tests exercise interventions; pass `setup({ mode: undefined })` to get the product default. -- Situation-v2 (batch 4/5): decisions about responses and push messages are taken at the **network boundary** (the `delivery` trigger, `RuntimeImpl.runDelivery`). Store writes are **never held by default**: a salient write not covered by a delivery decision is triaged when proposed and decided in the background (`observeWrite`); `policy.holdWrites: true` restores the old hold-the-write path (opt-in, never reorders a store's writes). +- Situation-v2 (batch 4/5): decisions about responses and push messages are taken at the **network boundary** (the `delivery` trigger, `RuntimeImpl.runDelivery`). Store writes are **never held by default**: a salient write not covered by a delivery decision is triaged when proposed and decided in the background (`observeWrite`); `policy.holdWrites: true` restores the old hold-the-write path (opt-in, never reorders a store's writes). A delivery that cannot be held (observe mode, paused, model not ready, no permitted delivery action, or the model too slow) is released synchronously, before any body read, and (in observe, or whenever `discard` is not permitted) decided in the background on the state it was delivered into; in guard/heal its chain's writes get their own `mutation` decisions instead, and the delivery is asked only when a standing question or `triage: "always"` forces it (054da38; `RuntimeImpl.deliveryHoldable`, `writesCanAct`). - Kill switch: `?genclass=off` (URL wins) or `localStorage.genclass = "off"` gives an inert runtime; the values `observe|guard|heal` override `options.mode`. - The decider (`DecisionProvider`) is the only seam to the model. `createRuntime` builds a model host (`createModelHost`) only when `options.decider === undefined` and `options.model` is an object; the runtime then **owns** it and disposes it on `destroy()`. A caller-supplied decider is never disposed. - The runtime consults the decider only while its `status.state` is `"ready"` or `"off"` (lazy). `"loading"` and `"error"` mean every trigger fails open at once (passive action, nothing held, no decision recorded). @@ -18,7 +19,7 @@ - Construction order matters: core subsystems, then queue/reporter/env, hub hooks, event and status subscriptions, persisted profiles, observers (each wrapped in try/catch), then plugins. `destroy()` is idempotent and tears down in roughly reverse order. - A **settled point** is reached `settleMs` (default 60 ms) after the last op end / applied write / discarded write, when nothing younger than 10 s is in flight and no write is pending. Invariants and transition profiles are learned there and `inconsistency` / `transition` triggers are raised there. - Events: `detect`, `decide`, `act`, `event`, `status`, `report` via `rt.on(type, fn)`; listener exceptions are swallowed (logged with `debug: true`). -- `util.ts` helpers (`secs`, `fmtNum`, `describe`, `normalizePath`, `isSensitiveName`, `isSensitivePath`, ...) shape the situation text. Changing them changes the frozen `situation-v2` format (tag `situation-v2` = 6e5e86e) and breaks train/runtime parity. `situation-v1` (tag at 1a77558; `packages/runtime/src` is identical at 654d822 = the npm `0.1.0-alpha.0`) is superseded; the R17-final1 model trained on it does not match this runtime. +- `util.ts` helpers (`secs`, `fmtNum`, `describe`, `normalizePath`, `isSensitiveName`, `isSensitivePath`, ...) shape the situation text. Changing them changes the frozen `situation-v2` format (tag `situation-v2` = 6e5e86e) and breaks train/runtime parity. f107013 deliberately changed redaction (numbers, bigints and arrays under a secret-named container; redacted F2 diffs), which changes situation text only where a secret used to leak (see Invariants). `situation-v1` (tag at 1a77558; `packages/runtime/src` is identical at 654d822 = the npm `0.1.0-alpha.0`) is superseded; the R17-final1 model trained on it does not match this runtime. ## Files @@ -31,7 +32,14 @@ | `packages/runtime/src/clock.ts` | Real clock; captures timers at module load | `browserClock` | | `packages/runtime/src/util.ts` | Deterministic helpers: hashing, stable stringify, number/time formatting, redaction, value descriptions, URL signatures | see [util.ts helpers](#utilts-helpers) | | `packages/runtime/package.json` | Package manifest: exports map, bin, deps, peer deps | `exports`, `bin.genclass-runtime` | -| `packages/runtime/tsup.config.ts` | Build entries (one per subpath export, including `worker`) | `entry`, `dts.entry`, `external` | +| `packages/runtime/tsup.config.ts` | Four build configs: the ESM build (one entry per subpath export, including `auto*` and `worker`), the script-tag IIFE build twice (unminified / minified), and the CDN worker + onnxruntime-web build into `dist/cdn/` | `defineConfig([...])`, `globalBuild`, plugins `cdnOrt`, `ortExternal` | +| `packages/runtime/src/auto.ts` | `@genclass/runtime/auto`: `GenClass.init()` at import time from page config | default export `Runtime`, named `GenClass` | +| `packages/runtime/src/cdn/auto-observe.ts`, `auto-guard.ts`, `auto-heal.ts` | `@genclass/runtime/auto/<mode>`: same as `/auto` with that mode as the lowest-precedence default | default export `Runtime`, named `GenClass` | +| `packages/runtime/src/cdn/auto-start.ts` | Shared zero-code start | `startAuto(defaults)` | +| `packages/runtime/src/cdn/config.ts` | Page configuration: `<meta name="genclass">`, script data attributes, `window.GENCLASS_CONFIG`; devtools setting; kill-switch check | `PageConfig`, `DevtoolsSetting`, `parsePairs`, `fromPairs`, `mergeConfig`, `readMetaConfig`, `readWindowConfig`, `fromDataset`, `isLocalHost`, `isKilled`, `devtoolsOptions`, `splitConfig`, `whenBody` | +| `packages/runtime/src/cdn/global.ts` | Script-tag build (`dist/genclass.global.js`, `.min.js`): installs `window.GenClass` and auto-inits | `GenClassGlobal`, `assetBase`; private `install`, `findScript`, `blobModuleWorker` | +| `packages/runtime/src/cdn/worker.ts`, `ort-webgpu.ts`, `ort-wasm.ts`, `ort-env.ts` | CDN model worker with onnxruntime-web bundled (`dist/cdn/*`), loaded on demand by the script tag | `cdnState`, `prepareOrt` | +| `packages/runtime/bin/genclass-runtime.mjs`, `bin/lib/*.mjs` | CLI: `init`, `remove` (`bin/lib/init.mjs` -> `run`; `detect.mjs`, `plan.mjs`, `edit.mjs`, `ui.mjs`), `fetch-model`, `info` | `bin/lib/plan.mjs` -> `AUTO`, `scriptTag`, `planInit`; `bin/lib/edit.mjs` -> `MARK` | Read-only neighbours this doc leans on: `src/decide/policy.ts` (`policyConfig`, `holdBudget`, `gate`), `src/decide/decider.ts` (`DeciderQueue`, now with `waiting`, `computing`, `computingSince`, `stuck` and a per-item `stale` check), `src/decide/exec.ts` (`Controller` with new optional `proceeded()` / `stale()`, `ActionEffect.onRecord`, `NetHost.deliver` / `noteResponse`), `src/decide/report.ts` (`Reporter`), `src/model/host.ts` (`createModelHost`, `DEFAULT_MODEL_BASE_URL`), `src/situation/serialize.ts` (`STATE_CHAR_BUDGET`, `COMPACT_BUDGET`), `src/trace/events.ts` (`EventLog`), `src/state/hub.ts` (`StoreHub`, `holdWrites`, hooks `observeWrite` / `filter` / `dropped`). New in batch 4/5 and wired by `RuntimeImpl`: `src/situation/conflicts.ts` (`predictedWrites`, `matchFields`, `conflictsOn`), `src/situation/content.ts` (`analyzeBody`, `createdIds`, `vhash`), `src/situation/evidence.ts` (`commitAmbiguity`, `failureOf`, `hostOfSig`), `src/learn/cadence.ts` (`Cadence`), `src/observe/eventsource.ts` (`installEventSource`), `src/observe/messages.ts` (shared WebSocket/EventSource message ops). Their internals are in [observe-and-trace.md](observe-and-trace.md), [learn-situation-triage.md](learn-situation-triage.md) and [decide-policy-actions.md](decide-policy-actions.md). @@ -47,8 +55,9 @@ Terms introduced in this doc: | consultable | `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists, and its `status.state` is `"ready"` or `"off"`. Triggers and holds happen only when consultable. | | lazy preload | When a salient trigger finds the decider not ready, the runtime reads `this.ready` (which calls `decider.ready()` once) and fails open for that trigger. | | budget scale | `RuntimeImpl.budgetScale`, starts at 1; multiplied by 0.8 (floor 0.5) each time the decider errors with `code === "max_tokens_exceeded"`; applied to the automatic situation budget only. | -| delivery gate | `RuntimeImpl.runDelivery`: a fetch/XHR response or a WebSocket/EventSource message is about to reach the app; it is salient when a field its signature writes has newer applied data (or, judged from its body, it would put back a value the user's pending change replaced, or replace text the user typed). Salient deliveries wait for the model (trigger `delivery`, held, priority 2); otherwise they are released at once. | -| covered write | `RuntimeImpl.covered(m)`: the write's causal chain (the cause op and up to 15 ancestors, 16 ops in all; the first op carrying `op.delivery` decides) went through the delivery gate, the gate knew which fields it would write, every changed path is among them, and (if salient) the decision was taken. Covered writes raise no `mutation` trigger. Never covered with `triage: "always"`. | +| delivery gate | `RuntimeImpl.runDelivery`: a fetch/XHR response or a WebSocket/EventSource message is about to reach the app; it is salient when a field its signature writes has newer applied data (or, judged from its body, it would put back a value the user's pending change replaced, or replace text the user typed). Salient deliveries wait for the model (trigger `delivery`, held, priority 2) when a hold is possible (`deliveryHoldable`); otherwise they are released at once and, if salient, decided in the background (054da38). | +| background delivery | 054da38: a delivery released without a hold (`deliveryHoldable` false: observe mode, paused, decider not `ready`, no permitted non-passive delivery action, or `expectedLatency() > holdBudgetMs()`). It is released before the body is read; content analysis uses `bodyNow` when the body is in memory (XHR, WebSocket, EventSource) before the app's listeners run, else (fetch) the async body, cut short at the chain's first write (`finalizeDeliveries`). Its decision cannot act (only the passive action); in observe it covers its chain's writes while pending (`deliveryPending`); in guard/heal (`writesCanAct`) the chain's writes keep their own `mutation` decisions and the delivery is asked only when a question forces it. | +| covered write | `RuntimeImpl.covered(m)`: the write's causal chain (the cause op and up to 15 ancestors, 16 ops in all; the first op carrying `op.delivery` decides) went through the delivery gate, the gate knew which fields it would write, every changed path is among them, and (if salient) the decision was taken or is pending in the background (`deliveryPending`). Covered writes raise no `mutation` trigger. Never covered with `triage: "always"`. | | background write observation | Default store-write path (`policy.holdWrites` false): `StoreHub.propose` calls `hooks.observeWrite(m)` -> `RuntimeImpl.observeWrite`, which triggers `mutation` with `hold: false, priority: 1`; the hub then commits the write at once. Not called for writes the hub never gates (no changes, user-sync writes without `holdUserWrites`, GenClass ops, `hold: false` stores, `hub.gating` false i.e. paused/destroyed). A later `discard` can only late-revert it (`LATE_REVERT_MS`). | | `holdWrites` | `PolicyOptions.holdWrites` (default false), copied to `hub.holdWrites`. When true, salient writes are queued and gated (`gateMutation`), never reordering a store's writes, and `atom().get()` inside the writing chain sees its own pending value (`hub.pendingView`). | | expected latency | `RuntimeImpl.expectedLatency()`: base × (1 + queued items) + (while one is computing) `max(base, its elapsed time)`, where base = the lower median of the queue's last 20 provider latencies, else `status.warmupMs`, else 0; `Infinity` while `queue.stuck` (last evaluation timed out). A holdable trigger waits only if this is `<=` the hold budget. | @@ -57,11 +66,13 @@ Terms introduced in this doc: ### Package exports (`packages/runtime/package.json`) -ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, `engines.node >= 20`, version `0.1.0-alpha.1` on `mvp-v2` (bumped in release commit 806a296, now the head of `mvp-v2`, and published as `latest` on 2026-10-08; it was `0.1.0-alpha.0` from 654d822 through b435acb, and the published alpha.0 predates situation-v2, the NaN fix and the observe default), license Apache-2.0. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). +ESM only (`"type": "module"`, only `import` conditions; the script-tag build is an IIFE file, not an export condition), `engines.node >= 20`, license Apache-2.0. `sideEffects` is no longer `false` (f3a9dd1): it lists `./dist/auto.js`, `./dist/auto/*.js`, `./dist/genclass.global.js`, `./dist/genclass.global.min.js`, `./dist/cdn/*.js` and `./src/model/worker.ts`, so bundlers keep the bare `import "@genclass/runtime/auto"`; the root and adapter modules are still tree-shakeable. New top-level `unpkg` and `jsdelivr` fields = `./dist/genclass.global.min.js` (what `https://cdn.jsdelivr.net/npm/@genclass/runtime` serves). Version: `0.1.0-alpha.1` in `package.json` on this branch, but that number is **taken on npm** by our release 806a296 (published as `latest` on 2026-10-08: situation-v2, the NaN fix, the observe default, docs), which does **not** contain the `/auto` entries, the script tag or `init`/`remove`; those ship in the next version (`0.1.0-alpha.2`, or a beta with the model), which needs a version bump first ([RELEASE.md](../../../RELEASE.md)). The published alpha.0 predates situation-v2, the NaN fix and the observe default. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). | subpath | types | import | source entry (tsup) | documented in | |---|---|---|---|---| | `@genclass/runtime` | `./dist/index.d.ts` | `./dist/index.js` | `src/index.ts` | this doc | +| `@genclass/runtime/auto` | `./dist/auto.d.ts` | `./dist/auto.js` | `src/auto.ts` | [Zero-code entries](#zero-code-entries-auto-script-tag-cli) | +| `@genclass/runtime/auto/observe`, `/auto/guard`, `/auto/heal` | `./dist/auto/<mode>.d.ts` | `./dist/auto/<mode>.js` | `src/cdn/auto-<mode>.ts` | [Zero-code entries](#zero-code-entries-auto-script-tag-cli) | | `@genclass/runtime/react` | `./dist/adapters/react.d.ts` | `./dist/adapters/react.js` | `src/adapters/react.ts` | [state-and-adapters.md](state-and-adapters.md) | | `@genclass/runtime/redux` | `./dist/adapters/redux.d.ts` | `./dist/adapters/redux.js` | `src/adapters/redux.ts` | [state-and-adapters.md](state-and-adapters.md) | | `@genclass/runtime/zustand` | `./dist/adapters/zustand.d.ts` | `./dist/adapters/zustand.js` | `src/adapters/zustand.ts` | [state-and-adapters.md](state-and-adapters.md) | @@ -70,13 +81,14 @@ ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, | `@genclass/runtime/package.json` | | `./package.json` | | | - Legacy top-level fields: `main` and `module` = `./dist/index.js`, `types` = `./dist/index.d.ts` (same targets as the `.` export). `repository.directory` = `packages/runtime`. -- `bin`: `genclass-runtime` -> `./bin/genclass-runtime.mjs`: `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` and `info <dir>` (details in [model-host.md](model-host.md)). +- Not in `exports` but shipped in `dist/` (fetched by URL): `dist/genclass.global.js`, `dist/genclass.global.min.js` (+ map), `dist/cdn/{worker,ort-webgpu,ort-wasm}.js` and chunks. Because `exports` has no entry for them, a bundler cannot `import` them; they are for `<script src>` and the script tag's own dynamic imports. +- `bin`: `genclass-runtime` -> `./bin/genclass-runtime.mjs` (the package's only bin, so `npx @genclass/runtime <command>` runs it): `init [--mode observe|guard|heal] [--yes|-y] [--dry-run] [--no-install] [--no-devtools] [--cwd <dir>] [--from <spec>] [--cdn <url>]` (also accepted but not in `USAGE`: `--no-sri`, `--strategy instrumentation|layout|pages` for Next.js), `remove [--yes] [--dry-run] [--keep-package] [--cwd <dir>]` (both dispatched to `bin/lib/init.mjs` -> `run`), `fetch-model <dir> [--from <baseUrl>] [--variant q8|fp16|all] [--force] [--quiet]` and `info <dir>` (details in [model-host.md](model-host.md)). A separate unscoped alias package, `packages/genclass-runtime` (`genclass-runtime`, bin `cli.mjs`, which imports `@genclass/runtime`'s `bin/genclass-runtime.mjs`), exists so that `npx genclass-runtime init` works; it is not on npm (404, 2026-10-08) and see Drift for its pinned dependency. - `dependencies`: `onnxruntime-web ^1.30.0` (the only runtime dependency; CONTRACT §0 forbids adding others without the lead). - `peerDependencies` (all optional via `peerDependenciesMeta`): `react >=18`, `redux >=4`, `zustand >=4`. - `devDependencies`: `@playwright/test 1.63.0`, `@types/react ^19.0.0`, `@types/react-dom ^19.0.0`, `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `react ^19.3.0`, `react-dom ^19.3.0`, `redux ^5.0.1`, `tsup ^8.5.1`, `typescript ~5.9.3`, `vitest ^5.0.3`, `zustand ^5.0.15`. - `files`: `dist`, `bin`, `README.md`, `LICENSE`. Scripts: `build` (tsup), `typecheck` (`tsc -p tsconfig.json --noEmit`), `test` (`vitest run`), `test:browser` (`playwright test --config test/browser/playwright.config.ts`). -- `tsup.config.ts`: ESM only, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`. `worker` has no `.d.ts` (not in `dts.entry`). -- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the current freeze), `v0.1.0-alpha.0` (= 654d822, the first published alpha; same `src` as `situation-v1`) and `v0.1.0-alpha.1` (= 806a296, the current npm `latest`; local only, not pushed). +- `tsup.config.ts` (four configs): (1) the ESM build, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`, entries `index`, `auto`, `auto/{observe,guard,heal}`, the adapters, `devtools/index`, `worker`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`; `worker` has no `.d.ts` (not in `dts.entry`); its `clean` spares `cdn/**` and `genclass.global*`. (2, 3) `globalBuild(false|true)`: IIFE of `src/cdn/global.ts`, `target: "es2020"`, `define: { __GENCLASS_VERSION__ }` from `package.json`, onnxruntime-web forced external (plugin `ortExternal`), map only for `.min.js`. (4) `dist/cdn/`: `src/cdn/worker.ts`, `ort-webgpu.ts`, `ort-wasm.ts`, minified, onnxruntime-web bundled in (`noExternal`), the worker's `import("onnxruntime-web/webgpu"|"/wasm")` mapped to `src/cdn/ort-*.ts` (plugin `cdnOrt`). The config deletes old `dist/genclass.global*` files before building. +- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the freeze this branch follows), `v0.1.0-alpha.0` (= 654d822, the first published alpha; same `src` as `situation-v1`) and `v0.1.0-alpha.1` (= 806a296, the current npm `latest`; local only, not pushed). origin also has `situation-v2.1` (= 5bc40c9 on origin/runtime, "situation-v2 + no-baseline stall fact (additive)"), which is not an ancestor of this branch. Nothing that 806a296 lacks (the zero-code entries f3a9dd1, 29b7f28, 054da38, f107013) is published. ### Root module exports @@ -94,7 +106,42 @@ ESM only (`"type": "module"`, only `import` conditions), `"sideEffects": false`, | `describeElement` | DOM element -> `'button "Place order"'` | `src/observe/dom-user.ts` | | `RuntimeImpl` | class (advanced; exposes internals) | `src/runtime.ts` | -Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/`holdBudget`/`gate`, `COMPACT_QUESTIONS_BUDGET` (1400), `TRIGGER_DESCRIPTIONS` and `ACTION_INSTRUCTIONS` (`situation/questions.ts`). The root export list itself did not change in batch 4/5 (the only `index.ts` change is `eventsource` in `ALL_OFF`). +Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/`holdBudget`/`gate`, `COMPACT_QUESTIONS_BUDGET` (1400), `TRIGGER_DESCRIPTIONS` and `ACTION_INSTRUCTIONS` (`situation/questions.ts`). The root export list itself did not change in batch 4/5 (the only `index.ts` change is `eventsource` in `ALL_OFF`), nor with the zero-code entries (`index.ts` and `types.ts` are unchanged since b435acb). + +### Zero-code entries (`/auto`, script tag, CLI) + +Owner: INSTALL (f3a9dd1, merged from origin/runtime). Not in npm `0.1.0-alpha.1`. Every path ends in `GenClass.init`, so it inherits the singleton (a later `GenClass.init(...)` in app code returns the runtime the entry started and **ignores its options**), the kill switch and the `observe` default mode. + +**Page configuration** (`src/cdn/config.ts`), lowest precedence first; `mergeConfig` is a shallow merge where later wins, two `model` objects are merged and `model: false` replaces: + +| source | read by | form | +|---|---|---| +| entry defaults | `/auto/<mode>` only (`startAuto({ mode })`); bare `/auto` and the script tag have none | `InitOptions` | +| `<meta name="genclass" content="mode=guard, devtools=local">` (every such tag, in document order) | `/auto*` and the script tag (`readMetaConfig`) | key/value pairs (`parsePairs`: separators `,` `;` or whitespace; keys case-, `-`, `_`-insensitive) | +| `data-*` attributes of the script tag (`data-mode="guard" data-devtools`) | script tag only (`fromDataset`; `data-manual` and `data-base` are not options) | same keys | +| `window.GENCLASS_CONFIG = { ... }` (set before the entry runs) | `/auto*` and the script tag (`readWindowConfig`) | any `InitOptions` plus `devtools` (a shallow copy) | +| `options` of `window.GenClass.init(options)` (highest; the auto-init passes none) | script tag global | `PageConfig` | + +Note the order: for `/auto/<mode>` the mode in the import path is the **lowest** precedence, so a `<meta>` or `GENCLASS_CONFIG` mode overrides it; for the script tag the meta tag is below the data attributes. The URL / localStorage kill switch (`?genclass=off|observe|guard|heal`) still beats everything inside `GenClass.init`. + +Pair keys (`fromPairs`; unknown keys and invalid values are ignored): `mode` (`observe|guard|heal`), `model` (`off`/`false`/`0`/`no`/`none` -> `model: false`; bare/`true` -> defaults; anything else -> `model.baseUrl`), `modelurl` / `baseurl`, `device` (`auto|webgpu|wasm`), `preload` (`eager|idle|lazy`), `ort` / `ortwasmpaths` (-> `model.ortWasmPaths`), `worker` (false only for an "off" word), `report` (`console|silent`), `debug`, `triage` (`salient|always`), `devtools`. `devtools` (`DevtoolsSetting`): bare/`true` -> always; `local`/`dev`/`localhost` -> only when `isLocalHost(location)` (loopback, `*.localhost`, `*.local`, `*.test`, `file:`); a corner (`bottom-right`, `bottom-left`, `top-right`, `top-left`) -> `{ position }`; an "off" word -> not mounted. `devtools` is split off (`splitConfig`) and never reaches `GenClass.init`. + +**`@genclass/runtime/auto`, `/auto/<mode>`** (`src/auto.ts`, `src/cdn/auto-*.ts` -> `startAuto(defaults)`): +1. Not a browser (`window` or `document` not an object): return `GenClass.init(defaults)` (the non-browser branch: no observers, no model; meta and window config are not read). +2. Else `GenClass.init(mergeConfig(defaults, meta, window.GENCLASS_CONFIG))` minus `devtools`; if a devtools setting applies and `isKilled` is false, `import("../devtools/index.js")` once `document.body` exists (`whenBody`) and `mountDevtools(rt, options)`; a load failure is a `console.warn`. +3. Default export: that `Runtime` (`import rt from "@genclass/runtime/auto"`); named export `GenClass`. Runs at module evaluation, so it must be the first import of the entry for stores created at import time to see `GenClass.runtime`. The bare `/auto` has no mode default: it runs in `observe`. + +**Script tag** (`src/cdn/global.ts`, built to `dist/genclass.global.js` / `.min.js`; `install()` runs at evaluation when `window` and `document` exist): +- Installs `window.GenClass: GenClassGlobal` = `{ version, base, init(options?), runtime (getter), destroy(), devtools(options?), createRuntime, GenClassUnavailableError }`. This is **not** the module `GenClass` object: `init` merges the page configuration under `options`, adds the CDN model wiring and mounts devtools; `destroy` also unmounts the overlay; `devtools()` mounts it (initialising first if needed). A second copy of the tag keeps the first global (`__genclassGlobal` flag). +- Auto-init: `api.init()` at once unless `data-manual` is present (and not `"false"`); a throw is caught and warned. +- `base` (where everything else loads from): `data-base` (resolved, trailing `/` added), else `assetBase(script.src)`: on jsDelivr/unpkg the URL is re-pinned to `@<this file's version>/dist/` (so `@latest` never mixes releases), else the script's directory; fallback `https://cdn.jsdelivr.net/npm/@genclass/runtime@<version>/dist/`. The script element is `document.currentScript`, else the last `script[src]` whose URL looks like this file. +- Model wiring (`withCdnModel`, skipped when `decider` is set or `model === false`): host options `workerFactory` (a module Worker from a same-origin Blob URL that imports `<base>cdn/worker.js`, since browsers refuse cross-origin worker URLs) and `ortLoader` (`<base>cdn/ort-webgpu.js` / `ort-wasm.js`), with the caller's `model` fields spread over them. These are `ModelHostOptions` fields (`model/host.ts`), passed through `ModelOptions` by a cast; they are not in the public `ModelOptions` type. Model weights still come from `DEFAULT_MODEL_BASE_URL` unless `model`/`data-model` says otherwise. +- The IIFE does not contain onnxruntime-web; `dist/cdn/*` bundles it and, only in a worker of a `crossOriginIsolated` page (WASM threads), points the thread glue at `ortWasmPaths` or else the jsDelivr onnxruntime-web directory (`ort-env.ts` -> `prepareOrt`). + +**CLI `init` / `remove`** (`bin/lib/init.mjs` -> `run`; consumer view only): +- `init` detects the package manager and framework (`detect.mjs`), installs `@genclass/runtime` (unless `--no-install`; `--from <spec>` picks the spec), and adds, as the first statement of the entry file, `import "<AUTO(mode)>"` (with devtools: `import genclass from "<AUTO(mode)>"` plus a dev-only `if (<dev condition>) import("@genclass/runtime/devtools").then((d) => d.mountDevtools(genclass))` at the end). Plain HTML gets a script tag (`plan.mjs` -> `scriptTag`: jsDelivr URL pinned to the CLI's own version unless `--cdn`; an `integrity` sha384 of the package's local `dist/genclass.global(.min).js` when that file exists, unless `--no-sri`; `data-mode` when a mode other than `guard` is given; `data-devtools="local"` unless `--no-devtools`). It shows the diff and asks unless `--yes`; `--dry-run` writes nothing; running it twice changes nothing. +- Every added line or created file carries the marker `genclass:init` (`edit.mjs` -> `MARK`), except the inline forms used when the insertion point shares its line with other code (a one-line `<head>` or `<body>`), marked `genclass:inline` (`MARK_INLINE`); `remove` deletes exactly the marked lines/blocks/inline forms and uninstalls the package unless `--keep-package` or `--no-install` (or something else still uses it). +- Mode mapping (`plan.mjs` -> `AUTO`): `observe` -> `/auto/observe`, `heal` -> `/auto/heal`, `guard` **or no `--mode`** -> plain `/auto`. On this branch plain `/auto` runs in `observe`, so `init --mode guard` currently produces an observe-mode install, and the CLI's help/summary still call `guard` the default. See Drift. ### Modes and tiers @@ -102,11 +149,11 @@ Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/ | mode | permitted tiers | holds | notes | |---|---|---|---| -| `observe` (**default**, `o.mode ?? "observe"`) | passive only | never (`trigger()` never waits because `permittedActions` is empty; `hub.hooks.mayHold` also returns false) | Decisions are still made in the background (deadline 5,000 ms) and recorded, so `decide`/`detect`/report lines work; `interventions()` stays empty. Pinned by `test/default-mode.test.ts`. | +| `observe` (**default**, `o.mode ?? "observe"`) | passive only | never (`trigger()` never waits because `permittedActions` is empty; `hub.hooks.mayHold` also returns false; `deliveryHoldable` is false, so responses and messages are released synchronously, before any body read) | Decisions are still made in the background (deadline 5,000 ms) and recorded (`executed: false`, reason mentioning observe mode), so `decide`/`detect`/report lines work, for deliveries too since 054da38; `interventions()` stays empty. Pinned by `test/default-mode.test.ts`, `test/observe-delivery.test.ts`, `policy.test.ts`. | | `guard` (opt-in) | passive, guard (`discard`, `defer`, `coalesce`, `delay`, guard-tier custom actions) | when a guard action is permitted for the trigger and `expectedLatency() <= holdBudgetMs()` | Store writes are held only with `policy.holdWrites: true`; otherwise writes apply at once and `discard` can only late-revert them. | | `heal` (experimental) | passive, guard, heal (`block`, `serve_cached`, `retry`, `hedge`, `rollback`, `resync`, custom actions (`rt.action` or plugins), which default to heal) | when any non-passive action is permitted (same latency and `holdWrites` conditions) | The sim runs in `heal`. | -Ways to choose the mode: `GenClass.init({ mode })`, `createRuntime({ mode })`, `?genclass=guard` / `localStorage.genclass = "guard"` (facade only), `rt.setMode(...)`, or the devtools mode switch (`src/devtools/index.ts` -> `MODES`: buttons "Observe" / "Guard" / "Heal" whose tooltips start "Observe (default)", "Guard (opt-in)", "Heal (experimental)"). +Ways to choose the mode: `GenClass.init({ mode })`, `createRuntime({ mode })`, `?genclass=guard` / `localStorage.genclass = "guard"` (facade only, so also every zero-code entry), `import "@genclass/runtime/auto/guard"` (or `/observe`, `/heal`), `<meta name="genclass" content="mode=guard">`, the script tag's `data-mode="guard"`, `window.GENCLASS_CONFIG = { mode: "guard" }`, `genclass-runtime init --mode <m>` (but see Drift for `guard`), `rt.setMode(...)`, or the devtools mode switch (`src/devtools/index.ts` -> `MODES`: buttons "Observe" / "Guard" / "Heal" whose tooltips start "Observe (default)", "Guard (opt-in)", "Heal (experimental)"). Threshold defaults (`policyConfig`): `report` 0.6, `guard` 0.9, `heal` 0.8. The full gate is in [decide-policy-actions.md](decide-policy-actions.md). @@ -235,9 +282,9 @@ Summary only; semantics in [decide-policy-actions.md](decide-policy-actions.md). Order inside one decision (`RuntimeImpl.onDecision`): `event` (an `RtEvent` of kind `"decision"`) -> `decide` -> `detect` (if detected) -> standing-question `onAnswer` callbacks -> either (no action runs: `ctl.passive()`, then a `report` detect line if detected) or (action runs: `rate.take`, the action, and once its effect resolves or fails: `event` (kind `"action"`) -> `act` -> `report` intervene line). A failed action (throw or rejection) runs the passive action first and records `ok: false`. -Trigger priorities (`EvaluateRequest.priority`, higher is served first by `DeciderQueue`): `delivery` (`runDelivery`), held `mutation` (`gateMutation`, only with `holdWrites`), `request` and fetch `failure` = 2; background `mutation` (`observeWrite`, the default write path), `stall`, `inconsistency`, XHR `failure`, `ask` = 1; `transition`, `error` = 0. A holdable trigger that does not actually wait is capped at 1 (`Math.min(priority, 1)` in `trigger`), which in the default `observe` mode is every trigger. +Trigger priorities (`EvaluateRequest.priority`, higher is served first by `DeciderQueue`): held `delivery` (`runDelivery`; a background delivery is submitted with `hold: false, priority: 2`, capped to 1), held `mutation` (`gateMutation`, only with `holdWrites`), `request` and fetch `failure` = 2; background `mutation` (`observeWrite`, the default write path), `stall`, `inconsistency`, XHR `failure`, `ask` = 1; `transition`, `error` = 0. A holdable trigger that does not actually wait is capped at 1 (`Math.min(priority, 1)` in `trigger`), which in the default `observe` mode is every trigger. -Queued requests can be dropped before dispatch: `trigger` passes `ctl.stale` to `DeciderQueue.submit` as a third argument, and the queue resolves `null` (fail open) for an item whose subject was already delivered, overwritten or superseded. +Queued requests can be dropped before dispatch: `trigger` passes `ctl.stale` to `DeciderQueue.submit` as a third argument, and the queue resolves `null` (fail open) for an item whose subject was already delivered, overwritten or superseded. Exception (054da38): for a `delivery` that did not wait, `stale` is not passed (a released delivery is always "stale"), so its background decision is still made and recorded. Status reports emitted by the runtime itself: `"[GenClass] Model ready (<model>, <device>, <variant>, <secs>). Mode: <mode>."`, `"[GenClass] Model unavailable (<error>); observing only."`, `"[GenClass] Mode set to <mode>."`, `"[GenClass] Rate limit reached (<n> actions/minute): running passive actions until it clears."` (at most once per 60,000 ms). @@ -344,8 +391,10 @@ Key literal unions: `TriggerKind = "mutation" | "request" | "delivery" | "failur | `createsBuf` | create responses (POST or 201) with the ids they returned (read-your-writes, `env.creates`), filled by `noteResponse` | 16 entries, 30 s | | `outcomesBuf` | completed non-aborted fetch/XHR outcomes across signatures (failure scope, F5, `env.outcomes`) | 128 entries, 30 s | | `channelsDown` | `"<channel> <path>"` -> when and why a WebSocket/EventSource went down (F9 marks on reconnect) | one per channel | +| `deliveryPending` | `WeakSet<OpRec>`: background deliveries whose decision is pending; `covered` treats their chain's writes as covered (054da38) | removed when the decision settles or fails | +| `deliveryAnalysis` | `Map<OpRec, cut>`: background deliveries whose body is still being read; `hooks.proposed` -> `finalizeDeliveries(m.cause)` runs `cut` at the chain's first write (054da38) | cleared in `destroy()` | | `identicalMap` | request identity -> recent ops | 12 per identity, 512 identities, 10 s | -| `errorsRecent` | recent error keys | 64, 10 s window | +| `errorsRecent` | recent error keys | 64, 10 s window (pruned when an error is recorded; `env.recentErrors()` only filters, so situation building changes no state, 29b7f28) | | `toProfile` | ops waiting for the next settled point | 2,000 | | `snaps` | consistent snapshots `{ t, seq, values }` (newest last) | 8 | | `episode`, `muted` | violations raised in the current episode; violations whose rollback was undone | | @@ -371,6 +420,8 @@ Key literal unions: `TriggerKind = "mutation" | "request" | "delivery" | "failur `GenClass.runtime` is a getter for `current`. `GenClass.destroy()` sets `current = null` first, then calls `destroy()` on the old runtime. +The zero-code entries call `GenClass.init` with merged page configuration (`startAuto`, or `window.GenClass.init` -> `withCdnModel`); they add no branch to `initUnsafe`. See [Zero-code entries](#zero-code-entries-auto-script-tag-cli). + ### 2. `createRuntime(options)` `index.ts` -> `createRuntime`: @@ -409,20 +460,20 @@ Constructing a `RuntimeImpl` immediately patches the instrumented globals (fetch ### 5. Trigger path (facade view) -Observers and the hub call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. In order: not consultable -> passive; `computeFacts`; with `triage: "salient"`, all facts neutral and no `always` standing question -> passive; `buildSituation`; not ready -> start lazy load, passive; hold only if `hold`, some non-passive action is permitted in this mode/policy, not paused, **and `expectedLatency() <= holdBudgetMs()`** (batch 4: never hold when the model is not expected to answer in time, or while the queue is `stuck`); the hold budget timer runs passive on expiry; submit to `DeciderQueue` with deadline `t0 + holdBudget (+ 2,000 ms late-revert window when the controller can revert)` for held subjects, else `t0 + 5,000 ms` and priority `min(priority, 1)`, plus `ctl.stale` so a superseded subject is dropped before dispatch; `onDecision` gates and acts. +Observers and the hub call `RuntimeImpl.trigger(spec, ctl, { hold, priority })`. In order: not consultable -> passive; `computeFacts`; with `triage: "salient"`, all facts neutral and no `always` standing question -> passive; `buildSituation`; not ready -> start lazy load, passive; hold only if `hold`, some non-passive action is permitted in this mode/policy, not paused, **and `expectedLatency() <= holdBudgetMs()`** (batch 4: never hold when the model is not expected to answer in time, or while the queue is `stuck`); a `delivery` that does not wait while `writesCanAct()` (not paused and `discard` permitted, i.e. guard/heal) returns passive at once unless a standing question forces it or `triage: "always"` (its writes are decided on their own); any other non-waiting `delivery` is registered in `deliveryPending` before the passive action runs (054da38); the hold budget timer runs passive on expiry; submit to `DeciderQueue` with deadline `t0 + holdBudget (+ 2,000 ms late-revert window when the controller can revert)` for held subjects, else `t0 + 5,000 ms` and priority `min(priority, 1)`, plus `ctl.stale` so a superseded subject is dropped before dispatch; `onDecision` gates and acts. -In `onDecision`, "too late" is now asked of the controller: `proceeded = ctl.proceeded ? ctl.proceeded() : hold && (expired || passiveRan)`. A built-in action on a subject that already proceeded is cancelled with reason "the decision arrived after the hold budget expired" (held) or "the subject was not held (decided in the background)", except a `discard` whose controller can late-revert (`revertable()` returns null). Custom actions skip that check, but `ctx.builtin(name)` (`RuntimeImpl.runCustom`) returns false when `ctl.proceeded()` is true (and when paused, restricted by mode/policy, or rate-limited). For `delivery` triggers that have not proceeded, `op.delivery.decided` is set (so the chain's writes are covered). Full detail: [decide-policy-actions.md](decide-policy-actions.md). +In `onDecision`, "too late" is now asked of the controller: `proceeded = ctl.proceeded ? ctl.proceeded() : hold && (expired || passiveRan)`. A built-in action on a subject that already proceeded is cancelled with reason "the decision arrived after the hold budget expired" (held) or "the subject was not held (decided in the background)", except a `discard` whose controller can late-revert (`revertable()` returns null). Custom actions skip that check, but `ctx.builtin(name)` (`RuntimeImpl.runCustom`) returns false when `ctl.proceeded()` is true (and when paused, restricted by mode/policy, or rate-limited). For `delivery` triggers that have not proceeded, or that were decided in the background while covering their chain (`st.covers`), `op.delivery.decided` is set (so the chain's writes are covered). A delivery that already proceeded can only take its passive action, custom actions included (054da38). Full detail: [decide-policy-actions.md](decide-policy-actions.md). ### 5a. Delivery gate and write observation (situation-v2, batch 4/5) 1. **Response/message about to reach the app.** `observe/fetch.ts` / `observe/xhr.ts` call `netHost().deliver(...)`; `observe/messages.ts` (WebSocket, EventSource) calls `wsHost().deliverMessage(...)`. Both land in `RuntimeImpl.runDelivery(o, release)`. Not consultable, paused, destroyed or a GenClass-internal op: `release()` at once. 2. Predicted writes (`predictedWrites` from the signature's last chain, `lastChainMap`), the store fields they match (`matchFields`) and conflicts (`conflictsOn`: `newer` applied data, `pending` local changes) are computed; `op.delivery = { patterns, known, salient, decided: false }` is recorded on the op. -3. No conflict, no typed-text field and not `always`: release at once. Without a body reader: salient iff a `newer` conflict exists. With one: wait up to `BODY_WAIT_MS` (100 ms) for the parsed body (a clone); `analyzeBody` then keeps a `newer` conflict only if the body would change the value (F3), a `pending` one only if the body puts back the value the user's change replaced (F1), and typed text only if the body would replace it (F2). Unchanged conflicts push a `custom` event `delivery.unchanged`. +3. No conflict, no typed-text field and not `always`: release at once. **No hold possible** (`deliveryHoldable` false; always the case in `observe`; 054da38): release at once, before any body read, then analyze and decide in the background: with `bodyNow` (XHR `body.now`, WebSocket/EventSource parsed message) the analysis runs synchronously, before the app's listeners; otherwise (fetch) the body is awaited up to `BODY_WAIT_MS`, but the chain's first write (`hooks.proposed` -> `finalizeDeliveries`) decides it without the body (with only `pending`/typed-text conflicts it is then left undecided and marked salient, so its writes get their own `mutation` decisions and F1 is not lost). A salient (or `always`) background delivery triggers `delivery` with `hold: false`; in observe (or whenever `discard` is not permitted) the decision is recorded but cannot act, while in guard/heal `trigger` returns the passive action without asking unless a standing question or `triage: "always"` forces it (see [Trigger path](#5-trigger-path-facade-view)). Otherwise (holdable): without a body reader: salient iff a `newer` conflict exists. With one: wait up to `BODY_WAIT_MS` (100 ms) for the parsed body (a clone); `analyzeBody` then keeps a `newer` conflict only if the body would change the value (F3), a `pending` one only if the body puts back the value the user's change replaced (F1), and typed text only if the body would replace it (F2). Unchanged conflicts push a `custom` event `delivery.unchanged`. 4. Salient (or `always`): `trigger({ trigger: "delivery", ... }, ctl, { hold: true, priority: 2 })`. Controller: `passive` releases (and records `overNewer` for F9 marks when delivered over a conflict); `discard` releases and sets a `discardMark` for 10 s; `defer` waits for related in-flight ops (`relatedInFlight`, at most `LONG_RUNNING_MS`) then calls `runDelivery` again with `defers + 1`. 5. **Writes.** The hub calls `hooks.filter` (`dropFilter`: drop paths under an active discard mark), then, with `holdWrites` false, `hooks.observeWrite` (`observeWrite`: skip when not consultable, GenClass-internal or `covered(m)`; else a background `mutation` trigger with a controller whose `run` throws "the write was not held" except via late revert) and commits immediately. With `holdWrites` true, `gate` (`gateMutation`) holds as before, but also skips covered writes. 6. **Marks.** After each applied write, `onApplied` updates `lastChainMap` and calls `markWrites` (try/catch); `noteResponse` records created ids; `onChannel` marks fields of a live channel that was down when it comes back. -Behavioural tests: `delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts`; design and fact text: [learn-situation-triage.md](learn-situation-triage.md), [decide-policy-actions.md](decide-policy-actions.md), `docs/runtime/RESULTS.md`. +Behavioural tests: `delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts`, `observe-delivery.test.ts` (background deliveries in observe, and guard unchanged); design and fact text: [learn-situation-triage.md](learn-situation-triage.md), [decide-policy-actions.md](decide-policy-actions.md), `docs/runtime/RESULTS.md`. ### 6. `ask` and `decide` @@ -458,7 +509,7 @@ Details: [state-and-adapters.md](state-and-adapters.md) (invariants, snapshots) `runtime.ts` -> `RuntimeImpl.destroy`, in order: 1. Return if already destroyed; set `destroyed = true`. 2. `hub.gating = false` (later writes apply immediately). -3. `queue.dispose()` (queued requests resolve `null`, so pending triggers fail open and pending `ask`s reject). The one evaluation already dispatched is not cancelled: it settles normally (or after its deadline / `PROVIDER_TIMEOUT_MS`), a trigger waiting on it runs passive because `destroyed` is set, but an `ask` waiting on it can still resolve with an answer after `destroy()`. +3. `queue.dispose()` (queued requests resolve `null`, so pending triggers fail open and pending `ask`s reject), then `deliveryAnalysis.clear()`. The one evaluation already dispatched is not cancelled: it settles normally (or after its deadline / `PROVIDER_TIMEOUT_MS`), a trigger waiting on it runs passive because `destroyed` is set, but an `ask` waiting on it can still resolve with an answer after `destroy()`. 4. `reporter.dispose()` (open de-dup windows are dropped: pending `(×N more in the last minute)` lines are never printed). 5. Clear `settleTimer` and `persistTimer` (a pending `learn.persist` save is dropped). 6. Run `uninstall` in reverse order (observers last-installed-first, then the decider status subscription); errors ignored. Each observer's uninstall sets its `disabled` flag (its wrapper becomes a pass-through) and, for fetch for example, restores the original only if the global still holds GenClass's wrapper (`observe/fetch.ts` -> `installFetch`), so a library that wrapped on top of GenClass keeps working. @@ -481,7 +532,7 @@ After destroy: listeners registered with `on()` stay attached and can still fire | `LATE_REVERT_MS` | number | `2000` | `runtime.ts` | Late-revert window after a write applied (`mutationController` -> `revertable`): applies both to a held write whose budget expired and to a background (`observeWrite`) write, so a background `discard` decided more than 2 s after the write is refused ("too late to revert"). Only for held subjects whose controller can revert does it also extend the decision deadline. | | `BACKGROUND_DEADLINE_MS` | number | `5000` | `runtime.ts` | Deadline for non-held decisions (all decisions in `observe`, and background `mutation`s). | | `DISCARD_MARK_MS` | number | `10000` | `runtime.ts` | How long a delivery `discard` keeps dropping its chain's writes over newer data. | -| `BODY_WAIT_MS` | number | `100` | `runtime.ts` | Max wait for a salient delivery's body (a buffered clone) before deciding without it. | +| `BODY_WAIT_MS` | number | `100` | `runtime.ts` | Max wait for a salient delivery's body (a buffered clone) before deciding without it. A holdable delivery waits up to that long for its body before it is decided (and then possibly held for the model); a background delivery (observe) is already released and only its analysis waits (fetch only: XHR and push messages are analyzed synchronously via `bodyNow`). | | delivery / write-chain walk | number | `16` ops (the write's cause and up to 15 ancestors) | `runtime.ts` -> `covered`, `dropFilter`, `onDropped` | How far up the cause chain a write looks for a delivery decision or discard mark. | | `markWrites` chain | number | writer + 8 ancestors | `runtime.ts` -> `markWrites` | Ops inspected for F9 marks; slow-response mark when duration `>= 5 ×` median and `>= median + 300 ms`. | | `STALL_MIN_MS` | number | `500` | `runtime.ts` | Stall timer at `max(4 × median, 2 × p95, 500)` ms of the signature's latency. | @@ -520,7 +571,7 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants | `plural(n, one, many?)`, `ordinal(n)` | `"3 items"`; `"1st"`, `"12th"`, `"23rd"`. | | `words(s)` | Split camelCase / snake_case / kebab-case / spaces, lowercased. | | `isSensitiveName(name)` | Results memoised in a module-level `Map` (cleared when it exceeds 4,096 names). True if any word is in `SECRET_WORDS` (password, passwd, passcode, passphrase, pass, pwd, secret, token, cvv, cvc, csc, ssn, iban, otp, totp, pin, cookie, authorization, auth, apikey, creditcard, cardnumber) or a pair in `SECRET_PAIRS` (card number/num/no/cvc/cvv/code/security, credit card, cc number/num/no/exp/csc, api key/secret, private key, access key, secret key, session id/token/key, security code, one time, social security). `"author"`, `"cards"`, `"passengers"`, a kanban `"card"` are not secrets. | -| `isSensitivePath(path, value?)` | New in batch 4/5. Decides by the **leaf** field, never by a store or container name alone: `null`/`undefined`/booleans never; non-path free text (e.g. `'input "Card number"'`) -> `isSensitiveName` of the whole text; numeric segments skipped (`users.3.password`); plain objects never redacted whole; leaf `isSensitiveName`, or a secret pair across the last two segments (`payment.card.number`); otherwise, for string/number values, under a container that names a secret, strings are secrets (`credentials.password.value`), and under a broad container (`auth`, `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: >= 20 chars, letters and digits, no spaces). `auth.loading`, `auth.user.name` are not secrets. | +| `isSensitivePath(path, value?)` | New in batch 4/5. Decides by the **leaf** field, never by a store or container name alone: `null`/`undefined`/booleans never; non-path free text (e.g. `'input "Card number"'`) -> `isSensitiveName` of the whole text; numeric segments skipped (`users.3.password`); plain objects never redacted whole; leaf `isSensitiveName`, or a secret pair across the last two segments (`payment.card.number`); otherwise, for string, number, bigint or array values, under a container that names a secret, the value is a secret (`credentials.password.value`, `payment.cvv.value = 123`, `account.password.history = [...]`; numbers, bigints and arrays since f107013, strings before), and under a broad container (`auth`, `authorization`, `cookie`, `session`) only opaque credential-looking strings (`OPAQUE`: >= 20 chars, letters and digits, no spaces). `auth.loading`, `auth.user.name` are not secrets. | | `defaultRedact(path, value)` | `"[redacted]"` if `isSensitivePath(path, value)`, else `value` (was: any segment `isSensitiveName`). | | `describe(v, path, redact, max = 80)` | Compares the redactor's result with `Object.is` (ad24804: `!==` recursed forever on `NaN`). One-line value summary used in situations (strings 48 chars top-level, 24 nested; arrays show at most 3 items, e.g. `"5 items [a, b, c, …]"` (the `, …` only when items were left out); objects list id-like keys first: `id`, `_id`, `key`, `uuid`, `slug`, `name`, `title`, `label`). | | `isIdSegment(seg)` | Digits, UUID, long hex (>= 8 with a digit), long token (>= 16 with letters and digits), conservative slug ids (`tasks-1cam`, `x7k2p`, `PPBqWA9`; not `sha256`, `oauth2`, `v1beta1`). | @@ -553,10 +604,12 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants - **`inflight()` returns live `OpRec`s**; `situation()` returns the cached object for that trigger. Treat both as read-only. - **`atom(name)` reuse vs replacement.** Same name and kind `atom` reuses the store and ignores `initial`; `guard`/`adapter` (or `atom` over a non-atom store) replace the store and lose its field history. - **Determinism (CONTRACT §0 rule 3).** Inside `packages/runtime/src` no `Math.random`, `Date.now`, `performance.now` or global `setTimeout`/`setInterval`: use `this.clock` (or `api.clock` in plugins). Ids come from counters (`d<n>`, `a<n>`, `uniq:<n>`, op ids, event `seq`). The only `performance.now` uses are `clock.ts` and a default in `model/engine.ts` that `model/backend.ts` overrides with the injected clock (`now: () => this.env.clock.now()`). Exception outside the decision path: the devtools overlay (`src/devtools/index.ts`, owned by UI) captures the raw global `setTimeout` and `requestAnimationFrame` at module load for its own rendering. The model host's idle preload (`src/model/host.ts` -> `scheduleIdle`) also calls the global `requestIdleCallback`/`cancelIdleCallback` directly. None of these reaches situation text. `budget.test.ts` and `situation.test.ts` assert byte-identical situations for identical inputs. -- **Every timer the runtime arms must be cleared in `destroy()` or be harmless when it fires afterwards.** `destroy()` clears `settleTimer`, `persistTimer` and the reporter's de-dup windows. Hold-budget, stall and queue-dispatch timers are left to fire: `passive()` is idempotent, `watchStall` checks `destroyed`, and `trigger()`'s answer handler runs passive when `destroyed`. The batch-4 delivery timers are also left to fire: the `BODY_WAIT_MS` timer in `runDelivery` (it then decides without the body; `trigger` fails open because not consultable, and the body callback checks `destroyed`) and the `LONG_RUNNING_MS` cap in `waitOps` (a `defer` re-runs `runDelivery`, which releases at once when destroyed). Every delivery path is designed to end in `release()` (guarded by a per-call `released` flag), so a response or message is never swallowed; keep that property when you add a delivery action. A `defer` re-enters `runDelivery` with the same `release`, under a fresh flag (whether a failing `defer` effect can release twice is unverified; the fetch/XHR `release` callbacks would need to tolerate it). +- **Every timer the runtime arms must be cleared in `destroy()` or be harmless when it fires afterwards.** `destroy()` clears `settleTimer`, `persistTimer` and the reporter's de-dup windows. Hold-budget, stall and queue-dispatch timers are left to fire: `passive()` is idempotent, `watchStall` checks `destroyed`, and `trigger()`'s answer handler runs passive when `destroyed`. The batch-4 delivery timers are also left to fire: the `BODY_WAIT_MS` timer in `runDelivery` (it then decides without the body; `trigger` fails open because not consultable, and the body callback checks `destroyed`) and the `LONG_RUNNING_MS` cap in `waitOps` (a `defer` re-runs `runDelivery`, which releases at once when destroyed). Every delivery path is designed to end in `release()` (guarded by a per-call `released` flag), so a response or message is never swallowed; keep that property when you add a delivery action. A background delivery's analysis (`bodyNow`, `finish`, the `deliveryAnalysis` cut) runs inside try/catch after `release()`, so an analysis error can never break or delay the delivery; keep it that way. A `defer` re-enters `runDelivery` with the same `release`, under a fresh flag (whether a failing `defer` effect can release twice is unverified; the fetch/XHR `release` callbacks would need to tolerate it). - **Captured natives.** `browserClock` captures timers and `index.ts` captures `fetch` at module evaluation. If another library patched `fetch` earlier, the model host downloads through that patch. Keep these captures at module top level; moving them into functions would make the runtime observe itself (its own timers through the timers observer, its model download through the fetch observer). -- **Parity and the `situation-v2` freeze.** `util.ts` formatting (`secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `normalizePath`, `isIdSegment`, `isSensitiveName`, `isSensitivePath`, `defaultRedact`), `STATE_CHAR_BUDGET` and the default `vocabulary` feed the text the model reads. The tag `situation-v2` (6e5e86e) froze it; `git diff situation-v2 b435acb -- packages/runtime/src` touches only `devtools/index.ts` (labels), `runtime.ts` (the `o.mode` default) and `types.ts` (JSDoc), none of which reaches situation text (mode is not part of the situation). SIM is generating situation-v2 data on the Azure cluster now (training/NEEDS.md); changing any of these invalidates that data. Coordinate with SIM/TRAIN first ([model-io-contract.md](../model-io-contract.md)). `situation-v1` (tag at 1a77558, same `src` as 654d822) is superseded. +- **Parity and the `situation-v2` freeze.** `util.ts` formatting (`secs`, `rel`, `fmtNum`, `ratio`, `plural`, `ordinal`, `truncate`, `describe`, `normalizePath`, `isIdSegment`, `isSensitiveName`, `isSensitivePath`, `defaultRedact`), `STATE_CHAR_BUDGET` and the default `vocabulary` feed the text the model reads. The tag `situation-v2` (6e5e86e) froze it. `git diff situation-v2 HEAD -- packages/runtime/src` on `mvp-v2-merge` touches: `devtools/index.ts` (labels), `types.ts` (JSDoc), `trace/ops.ts` (`peekNextId`, tests only), the new `auto.ts` and `cdn/*` (no situation code), `runtime.ts` (the `o.mode` default; `errorsRecent` pruning moved to record time; background deliveries, 054da38), `observe/xhr.ts` / `observe/messages.ts` (`bodyNow`), and the redaction fix f107013 (`util.ts` -> `isSensitivePath`, `state/fields.ts` -> `redactedStringDiff`, `situation/content.ts` F2 diff). The last group **does** change situation text, but only for values that are now redacted (numbers/arrays under secret containers, F2 previews of redacted fields); 054da38 changes which situations are built (the state a background delivery was released into) and makes observe-mode delivery decisions exist, not the format. The v2 data (10.4M gold, 51.3M unlabeled, eff18cb) was generated before f107013, so it may contain such unredacted values; that is a curriculum/data follow-up for SIM/TRAIN (STATUS.md), not a format break. Any further change to the helpers above invalidates that data. Coordinate with SIM/TRAIN first ([model-io-contract.md](../model-io-contract.md)). `situation-v1` (tag at 1a77558, same `src` as 654d822) is superseded. - **Default mode is `observe`, but the test harness is `guard`.** `test/helpers.ts` -> `setup` defaults `mode: "guard"`; `smoke.test.ts`, `test/browser/ui/session.ts` and `review-fetch.test.ts` -> `headless()` pass `mode: "guard"` explicitly. A new test that expects interventions from `createRuntime` (not `setup`) must pass `mode: "guard"`; a test of the product default uses `setup({ mode: undefined })` as `default-mode.test.ts` does. +- **Observe never delays anything, deliveries included (054da38).** Before it, a conflicting response in observe still waited up to `BODY_WAIT_MS` (100 ms) for its body before release, and its decision was then dropped as stale. Now `deliveryHoldable` returns false in observe, the delivery is released synchronously (XHR listeners and WebSocket/EventSource handlers run inside the original dispatch), and the decision is still recorded. Do not add a code path that reads a body or waits before `release()` unless the delivery is holdable. +- **Zero-code entries run at import time and call `GenClass.init` once.** App code that later calls `GenClass.init(options)` gets the runtime the entry started; its options are ignored (use `window.GENCLASS_CONFIG`, the meta tag or the `/auto/<mode>` path instead). `/auto*` and the script tag never install anything outside a browser, and do not mount devtools when the kill switch is `off`. - **Writes are not held by default (even in guard).** With `policy.holdWrites` false, `mayHold` is false and `atom().set` / adapter `propose` apply in the caller's stack; a model `discard` of a `mutation` can only late-revert under the strict rules (within `LATE_REVERT_MS`, nothing overwrote it). Tests that rely on held writes set `policy: { holdWrites: true }` (`atoms.test.ts`, adapter tests; `MockRuntime` has its own `holdWrites` flag). - **The sim's observer map omits `eventsource`.** `sim/src/run/rt.ts` -> `createOptions` passes an explicit `observe` map without `eventsource`, so the EventSource observer defaults on in sim runs. `installEventSource` returns `null` when `global.EventSource` is not a function, and nothing under `sim/src` mentions `EventSource`, so today it is a no-op there; if the sim ever adds an `EventSource` to its fake global, decide explicitly whether to observe it. The unit-test harness (`test/helpers.ts` -> `setup`, `review-fetch.test.ts` -> `ONLY_FETCH`) has the same gap. - **The model seam is shared.** The first section of `types.ts` is co-owned by MODEL, and `sim/src/types.ts` mirrors it structurally. Change all three together. @@ -594,7 +647,7 @@ Policy defaults are in [PolicyOptions](#policyoptions); queue and host constants 4. Add a "destroy restores the global" assertion next to `dom.test.ts` -> "browser globals are restored by destroy()". See [observe-and-trace.md](observe-and-trace.md). **Change a default (mode, thresholds, settleMs, historySize, budgets, holdWrites)** -1. Change it where it is defined (table above), then update the JSDoc in `types.ts`, `docs/runtime/API.md`, `docs/runtime/CONTRACT.md` (§2 and a dated §13 entry for a product decision), `packages/runtime/README.md`, and devtools labels if they name the default. +1. Change it where it is defined (table above), then update the JSDoc in `types.ts`, `docs/runtime/API.md`, `docs/runtime/CONTRACT.md` (§2 and a dated §13 entry for a product decision), `packages/runtime/README.md`, and devtools labels if they name the default. For the mode default also the CLI (`bin/lib/plan.mjs` -> `AUTO`, `scriptTag`; `bin/lib/init.mjs` -> `USAGE` and the "Mode" summary row) and its fixtures in `test/install/cli.test.ts`: they encode which mode plain `/auto` means. 2. Tests pinning values: `budget.test.ts` (budgets, hold budget), `policy.test.ts`, `report.test.ts` (report line regexes include thresholds), `batch3.test.ts`, `default-mode.test.ts` (mode), `atoms.test.ts` / `no-reorder.test.ts` / adapter tests (`holdWrites`). 3. Worked example, the mode default (f3636b2): `runtime.ts` constructor `o.mode ?? "observe"`; `types.ts` JSDoc; devtools `MODES` tooltips and mode fallback; `test/helpers.ts` -> `setup` now passes `mode: "guard"` explicitly; explicit `mode: "guard"` in `smoke.test.ts`, `test/browser/ui/session.ts` and `review-fetch.test.ts` -> `headless()` (no assertion changed); new `default-mode.test.ts`; API/ARCHITECTURE/CONTRACT §13. 4. Thresholds and budgets affect training/eval comparability: tell TRAIN/SIM. @@ -606,19 +659,23 @@ Edit `index.ts` -> `killSwitch` / `initUnsafe`; keep everything in try/catch; up Keep it idempotent; clear every new timer; keep reverse uninstall order; dispose only owned deciders. Tests: `fetch.test.ts`, `xhr.test.ts`, `dom.test.ts` (restoration), `review-fetch.test.ts` (no work after destroy), `review-misc.test.ts` / `batch3.test.ts` (`ask` after destroy). **Add a subpath export** -Add the entry to `package.json` `exports`, `tsup.config.ts` `entry` and `dts.entry`, and externalise any new peer library. See [build-test-release.md](build-test-release.md). +Add the entry to `package.json` `exports`, `tsup.config.ts` `entry` and `dts.entry` (of the first, ESM config), and externalise any new peer library. If importing it for its effect is the point (like `/auto`), also add its `dist` file to `sideEffects`. See [build-test-release.md](build-test-release.md). **Add time-dependent behaviour** Use `this.clock.now()` / `this.clock.setTimeout` / `this.clock.afterTask`; store the handle and clear it in `destroy()`; test it with `FakeClock.advance`. ## Tests -All in `packages/runtime/test/` (vitest, `environment: "node"`, `testTimeout: 20000`, `test/browser/**` excluded; `dom.test.ts` uses `// @vitest-environment happy-dom`). Most use `setup()` from `helpers.ts`: `createRuntime` with `FakeClock`, `FakeServer`, `ScriptedDecider`, **`mode: "guard"`**, `report: "silent"` and only the fetch observer on (its explicit `observe` map omits `eventsource`, which therefore defaults on but installs nothing: the fake global from `makeGlobal` has no `EventSource`). Lead's run on `mvp-v2` at b435acb (2026-10-08, Node v25.6.0): unit tests without `test/browser/**` and `review-perf` -> 40 files passed, 1 skipped; 332 tests passed, 14 skipped (model parity); `review-perf.test.ts` alone 4 passed (it can flake under a full parallel run: 5.5 ms vs its 2 ms bound). With the uncommitted `hub.ts` held-write fix and its new `atoms.test.ts` test, the main run becomes 333 passed + 14 skipped (347). +All in `packages/runtime/test/` (vitest, `environment: "node"`, `testTimeout: 20000`, `test/browser/**` excluded; `dom.test.ts` uses `// @vitest-environment happy-dom`). Most use `setup()` from `helpers.ts`: `createRuntime` with `FakeClock`, `FakeServer`, `ScriptedDecider`, **`mode: "guard"`**, `report: "silent"` and only the fetch observer on (its explicit `observe` map omits `eventsource`, which therefore defaults on but installs nothing: the fake global from `makeGlobal` has no `EventSource`). Run on `mvp-v2-merge` at f107013 (2026-10-08, Node v25.6.0): unit tests without `test/browser/**` and `review-perf` -> 44 files passed, 1 skipped; 375 tests passed, 14 skipped (model parity), 389 in all (`vitest.config.ts` includes `test/**/*.test.ts`, so `test/install/cli.test.ts` runs too). `review-perf.test.ts` is run alone (4 tests at b435acb; it can flake under a full parallel run: 5.5 ms vs its 2 ms bound). | test file | what it asserts (scope of this doc) | |---|---| -| `default-mode.test.ts` (f3636b2) | `createRuntime` and `GenClass.init` without a mode start in `observe`; `mode: "guard"` and `?genclass=guard` opt in; in observe, a sure model (p 0.99) records `mutation`/`request` decisions and detections but nothing is held, `executed` is false and `interventions()` is empty; a model that never answers delays nothing (atom write, adapter propose, fetch, failed fetch) while it is still asked in the background. | +| `default-mode.test.ts` (f3636b2, 054da38) | `createRuntime` and `GenClass.init` without a mode start in `observe`; `mode: "guard"` and `?genclass=guard` opt in; in observe, a sure model (p 0.99) records `delivery`/`mutation`/`request` decisions and detections but nothing is held, `executed` is false and `interventions()` is empty; a model that never answers delays nothing (atom write, adapter propose, fetch, failed fetch) while it is still asked in the background. | | `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts` (batch 4/5) | The delivery gate (salience, `discard` drop marks and undo, `defer`), body analysis (F1/F2/F3, read-your-writes), and that held writes never reorder a store's writes. Owned by [decide-policy-actions.md](decide-policy-actions.md) / [learn-situation-triage.md](learn-situation-triage.md). | +| `observe-delivery.test.ts` (054da38) | Observe: a conflicting fetch response with a slow body resolves at network time and is decided once in the background on the state it was delivered into; an app write before the body is read decides it at that write; F1 is not lost; standing questions on `delivery` are answered; XHR listeners run inside the original dispatch with the body analyzed first; WebSocket/EventSource messages delivered synchronously and in order, still decided. Guard unchanged: stale response held and discarded; a too-slow model releases at once and the write is late-reverted on its own. | +| `redaction-v2.test.ts` (f107013) | Numbers, bigints and arrays under strong secret containers are redacted; booleans/null and broad containers unchanged; F2 previews of redacted fields do not leak characters. | +| `situation-purity.test.ts` (29b7f28) | Building situations for every trigger kind changes no counter and no later id (`OpRegistry.peekNextId`); polling the runtime like the devtools overlay changes no decision, hold or id. | +| `test/install/cli.test.ts` (f3a9dd1) | `init`/`remove` round trips on fixture projects (`--no-install`) for Vite, Next.js 14-16, SvelteKit, Nuxt, Astro, Angular/CRA/Remix/React Router/webpack and plain HTML: marked import first, dev overlay line, `/auto/observe` for `--mode observe`, script tag with `data-mode`, no write without a terminal unless `--yes`, `remove` keeps user edits outside the markers; `edit.mjs` helpers; `config.ts` parsers (`parsePairs`, `fromDataset`, `mergeConfig`, `readMetaConfig`, `isKilled`, `isLocalHost`, `devtoolsOptions`) and `global.ts` -> `assetBase`. The real-framework and CDN checks (`test/install/frameworks.mjs`, `cdn-check.mjs`, `run-all.sh`) are VM-only. | | `nan.test.ts` (ad24804) | A store holding `NaN` builds a situation without recursing (`describe` uses `Object.is`). | | `report.test.ts` | `GenClass.init` idempotent, `GenClass.runtime`, `destroy` clears it; `?genclass=off` leaves `fetch` untouched, mode `observe`, exactly one `console.info`; `?genclass=heal` overrides `mode: "guard"`; `on("decide" \| "detect" \| "act" \| "event")` order and unsubscribe; report lines and console grouping/de-dup. | | `batch3.test.ts` | Lifecycle: `ask` after destroy rejects `"destroyed"`; `createRuntime` survives read-only `fetch`; `GenClass.init` with a throwing plugin `setup` does not throw; a provider that never answers does not block later decisions; rate-limit warning once per minute. | @@ -638,13 +695,18 @@ Which `initUnsafe` branch the unit tests hit: vitest runs in `environment: "node CI (`.github/workflows/ci.yml`, b435acb) runs typecheck, build, the unit tests without `test/browser/**` and `review-perf`, then `review-perf` alone with `--retry=2`, on pushes to `main`/`runtime`/`mvp`/`mvp-v2`, pull requests and manual dispatch. It does not run Playwright, `smoke.sh`, the sim or realapps. -Untested in this scope: the `localStorage.genclass` path of the kill switch, the browser branch of `initUnsafe` with a default model, the outer `catch` fallback of `GenClass.init` (the throwing-plugin test is caught inside `use`, not by the fallback), `learn.persist`, `settleMs`, `historySize`, `setReport`, `isPaused`, `createRuntime({ model: {...} })` fetch selection and `failedProvider`, and the `ask` + `timeoutMs` + load-failure path. +Untested in this scope (by unit tests): `startAuto` and the script tag's `install()` in a DOM (only their pure helpers are unit-tested; the browser behaviour is in the VM-only install checks), that `/auto/guard` really starts in guard, the `localStorage.genclass` path of the kill switch, the browser branch of `initUnsafe` with a default model, the outer `catch` fallback of `GenClass.init` (the throwing-plugin test is caught inside `use`, not by the fallback), `learn.persist`, `settleMs`, `historySize`, `setReport`, `isPaused`, `createRuntime({ model: {...} })` fetch selection and `failedProvider`, and the `ask` + `timeoutMs` + load-failure path. ## Drift and open issues | what | docs say | code does | evidence | |---|---|---|---| -| Default mode | HANDOFF.md "Modes: observe → guard (default; ...)"; npm `0.1.0-alpha.0` | `o.mode ?? "observe"` on `mvp-v2` (f3636b2). API.md, ARCHITECTURE.md, CONTRACT §2/§13, `types.ts` JSDoc, devtools labels and both READMEs (README.md, packages/runtime/README.md) now say observe. origin/runtime 74f17c0 itself still defaults to guard. | `runtime.ts` -> `RuntimeImpl` constructor; `default-mode.test.ts` | +| Default mode | HANDOFF.md "Modes: observe → guard (default; ...)"; npm `0.1.0-alpha.0` | `o.mode ?? "observe"` on `mvp-v2` (f3636b2) and `mvp-v2-merge`. API.md, ARCHITECTURE.md, CONTRACT §2/§13, `types.ts` JSDoc, devtools labels and both READMEs (README.md, packages/runtime/README.md, which says plain `/auto` and the tag without `data-mode` observe) say observe. origin/runtime (through eff18cb) still defaults to guard. | `runtime.ts` -> `RuntimeImpl` constructor; `default-mode.test.ts` | +| `init` CLI mode | `bin/lib/init.mjs` -> `USAGE` ("guard (default)") and the summary row (`o.mode ?? "guard"`, "(default; --mode observe never changes anything)"), written against origin/runtime's guard default | `plan.mjs` -> `AUTO` maps `guard` and no `--mode` to plain `@genclass/runtime/auto`, and `scriptTag` omits `data-mode` for `guard`; on this branch both run in **observe**. So `init --mode guard` silently installs observe, and the printed "Mode guard" is wrong. Fix (INSTALL): map `guard` to `/auto/guard` and `data-mode="guard"`, make the default `observe`, update `cli.test.ts` fixtures. | `bin/lib/plan.mjs` -> `AUTO`, `scriptTag`; `bin/lib/init.mjs`; `src/auto.ts` | +| Zero-code entries vs npm | packages/runtime/README.md documents `npx @genclass/runtime init`, `/auto` and the script tag (with a note that alpha.1 lacks them); `package.json` says `0.1.0-alpha.1` | npm `0.1.0-alpha.1` (806a296) has none of them, `dist/genclass.global.min.js` is not on jsDelivr, and the CLI's `scriptTag` pins jsDelivr to the package's own version (`0.1.0-alpha.1`), whose file does not exist. The alias package `packages/genclass-runtime` (not on npm) is also at `0.1.0-alpha.1` and pins `"@genclass/runtime": "0.1.0-alpha.1"` exactly, whose bin has no `init`/`remove`; its naming question is open in `packages/runtime/INSTALL-NEEDS.md` (OPEN_TASKS.md item 14). Needs a version bump of both packages and a publish (`0.1.0-alpha.2` or a beta) before any of it works for consumers. | `npm view @genclass/runtime`, `npm view genclass-runtime` (404) (2026-10-08); `bin/lib/plan.mjs` -> `scriptTag`; `packages/genclass-runtime/package.json` | +| Script-tag model wiring | `ModelOptions` (`types.ts`) lists `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths`, `cacheName` | `global.ts` -> `withCdnModel` also passes `workerFactory` and `ortLoader` (host-only `ModelHostOptions`) through `model` by a cast; `createRuntime` spreads `model` into `createModelHost`, so they work, but the public type does not admit them | `src/cdn/global.ts`; `index.ts` -> `makeHost`; `model/host.ts` | +| `/auto/<mode>` precedence | The import path reads as "this mode" | The path's mode is the lowest-precedence default: a `<meta name="genclass" content="mode=...">` or `GENCLASS_CONFIG.mode` overrides it (as does the kill switch) | `cdn/auto-start.ts` -> `startAuto` | +| Observe deliveries | `RuntimeImpl.runDelivery` behaviour up to 054da38 | Fixed in 054da38: observe used to hold a conflicting response for up to `BODY_WAIT_MS` (body read) before release, and its decision was dropped as stale. API.md / ARCHITECTURE.md do not yet describe background delivery decisions. | `runtime.ts` -> `runDelivery`, `deliveryHoldable`; `observe-delivery.test.ts` | | Auto situation budget (WebGPU / unknown device) | `docs/runtime/ARCHITECTURE.md` ("3,200 characters on WebGPU"), STATUS.md's older line ("webgpu 3,200", followed by "(Batch 4: webgpu and unknown device 2,400.)") | `STATE_CHAR_BUDGET` = 2400 since batch 4; WASM 1000/1333/1667/2000 unchanged. `types.ts` JSDoc (fixed in batch 4), API.md, packages/runtime/README.md and `MockRuntime.situationBudget` (2400) match the code. | `situation/serialize.ts`; `runtime.ts` -> `situationBudget`; `budget.test.ts` | | Default redaction | `docs/runtime/CONTRACT.md` §2 (`/pass\|token\|secret\|card\|cvv\|ssn\|auth/i`) | Leaf-field rule (`isSensitivePath`): `auth.loading` and `auth.user.name` visible, `auth.token` redacted; opaque strings under `auth`/`session`/`cookie` redacted. `types.ts` JSDoc, API.md and packages/runtime/README.md were updated in batch 4/5 and match. | `util.ts` -> `isSensitivePath`, `defaultRedact` | | `observe` option JSDoc | `types.ts`: a leftover `/** Default: all true (where the global supports them). */` sits directly above the new JSDoc on `InitOptions.observe` (two doc comments; editors show the last one) | `timers` only with a document; `eventsource` included; `untrustedEvents` default false | `types.ts` -> `InitOptions.observe`; `runtime.ts` -> `installObservers` | @@ -666,14 +728,14 @@ Untested in this scope: the `localStorage.genclass` path of the kill switch, the | API.md shapes | `Situation` listed as `{ trigger, subject, state, questions, actions, salient, facts }`; `Op` without `meta` | `Situation` also has `compact` and `budget`; `Op` also has `meta` | `types.ts` -> `Situation`, `Op` | | API.md observers | "The DOM, fetch, XHR, WebSocket and timers are observed automatically" (packages/runtime/README.md now lists them all) | Also `eventsource` (batch 4), `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | | Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | -| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and the CLI's `DEFAULT_FROM` at the GitHub release `runtime-model-v0.1.0`; both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 9 | -| npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from this branch (806a296), is `latest` since 2026-10-08; procedure in [RELEASE.md](../../../RELEASE.md). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | +| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and the CLI's `DEFAULT_FROM` at the GitHub release `runtime-model-v0.1.0`; both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 12 | +| npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from `mvp-v2` (806a296), is `latest` since 2026-10-08; procedure in [RELEASE.md](../../../RELEASE.md). alpha.1 in turn lacks everything after 806a296 (zero-code entries, 054da38, f107013). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | | Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | | `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a<n>` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | | Init with malformed `plugins` | `GenClass.init` "never throws" | It does not throw, but a non-iterable `plugins` / `plugin.actions` / `plugin.questions` throws inside `RuntimeImpl`'s constructor after the observers were installed; the fallback inert runtime is returned while the first instance's wrappers stay on the globals | `runtime.ts` -> constructor, `use`; `index.ts` -> `GenClass.init` | | `decisions(0)` / `interventions(0)` | | Return the whole buffer (`slice(-0)`), while `history(0)` returns `[]` | `runtime.ts` | -Open items relevant here (OPEN_TASKS.md, HANDOFF.md, training/NEEDS.md): the model path is 150M teacher on situation-v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) -> rerun the demos -> publish `@genclass/runtime@0.1.0` without the alpha tag. SIM is currently generating situation-v2 data on the Azure cluster, plus real-browser gold rows from `realapps/` ([../realapps.md](../realapps.md)). OPEN_TASKS.md item 12 (CI) is done on `mvp-v2` (b435acb); the `npm pack` smoke test in a fresh Vite app is not in CI. Why writes are no longer held (commit fcd1e68): store-write holds reordered in-app writes (held echoes overwrote newer user writes, read-after-write broke) and broke the unmodified RealWorld React/Redux app even with an always-passive model; the related "hold-induced harm" in the v0.1 demos is recorded in RESULTS.md §5 and OPEN_TASKS item 10 (demo rerun). Demo numbers with a v2 model are not measured yet. Until a v2 model ships, `GenClass.init()` observes and records but never acts (and with the observe default it would not act even with a model unless `mode: "guard"` is set). +Open items relevant here (OPEN_TASKS.md, HANDOFF.md, training/NEEDS.md): the model path is 150M teacher on situation-v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) -> rerun the demos -> publish `@genclass/runtime@0.1.0` without the alpha tag. The situation-v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled; plus real-browser gold rows from `realapps/` over 96 apps (`v2c1`..`v2c4`; the corpus on this branch has 128 app manifests), [../realapps.md](../realapps.md)); on 2026-10-08 the Azure jobs `r17-v2a` (R17 on v2 gold, 8 nodes, ETA ~06:20 UTC, auto eval and export via `training/v2_post.sh`; origin/runtime 416e374, not merged here, already records first `r17-v2a` results in RESULTS.md) and `t150-v2a` (150M teacher, 11 nodes, ETA ~08:30 UTC) were launched (OPEN_TASKS.md "In progress" items 1 and 2), and no situation-v2 model is published (`@genclass/runtime-model` 404 on npm, checked 2026-10-08). The next runtime release (`0.1.0-alpha.2` or a beta with the model) carries the zero-code entries, 054da38 and f107013; fix the `init` CLI mode mapping (Drift) before it. OPEN_TASKS.md item 16 (CI) is done on `mvp-v2` (b435acb); the `npm pack` smoke test in a fresh Vite app is not in CI. Why writes are no longer held (commit fcd1e68): store-write holds reordered in-app writes (held echoes overwrote newer user writes, read-after-write broke) and broke the unmodified RealWorld React/Redux app even with an always-passive model; the related "hold-induced harm" in the v0.1 demos is recorded in RESULTS.md §5 and OPEN_TASKS item 13 (demo rerun). Demo numbers with a v2 model are not measured yet. Until a v2 model ships, `GenClass.init()` (and every zero-code entry) observes and records but never acts (and with the observe default it would not act even with a model unless `mode: "guard"` is set, e.g. via `/auto/guard`). ## Related docs diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index 93a3c698..ff3dd09f 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -3,14 +3,16 @@ > **Scope:** `HANDOFF.md`, `OPEN_TASKS.md`, `docs/runtime/RESULTS.md`, `packages/runtime/STATUS.md`, `demos/NEEDS.md`, > `sim/NEEDS.md`, `training/NEEDS.md`, `training/PLAN-v1.md`, `training/LOG.md`, `packages/runtime/UI-NEEDS.md`, > `docs/runtime/{CONTRACT,API,ARCHITECTURE}.md`, `README.md`, `packages/runtime/README.md`, `realapps/README.md`, -> `.github/workflows/ci.yml`, git history and tags, code TODO markers, and the 2026-10-08 review of the situation-v2 -> work. Cross-checked against `packages/runtime/src/**`, `packages/runtime/bin/genclass-runtime.mjs`, -> `packages/runtime/package.json`, `sim/src/**`, `realapps/**` and `training/**`. +> `.github/workflows/ci.yml`, `packages/runtime/{CHANGELOG,INSTALL-NEEDS}.md`, `packages/runtime/test/install/*.md`, +> git history and tags, code TODO markers, the 2026-10-08 review of the situation-v2 work and the 2026-10-08 review of +> the merged install code. Cross-checked against `packages/runtime/src/**`, `packages/runtime/bin/**`, +> `packages/runtime/package.json`, `packages/runtime/tsup.config.ts`, `sim/src/**`, `realapps/**`, `training/**`, +> the npm registry (`npm view`) and the newer `origin/runtime` commits (read with `git show`, not merged). > **Read this when:** you land in the repo cold and need to know what is shipped, what runs on Azure right now, what > comes next and who owns it; before any change that could break a binding rule (situation text, determinism, > dependencies, where to run things); before trusting a human doc over the code; when you pick up one of the review > findings; when you finish work and must update STATUS/NEEDS/OPEN_TASKS/HANDOFF. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` at f107013 (`mvp-v2` + origin/runtime eff18cb merged + two runtime fixes), 2026-10-08 ~07:00 UTC. If this doc and the code disagree, the code wins. ## TL;DR @@ -18,67 +20,90 @@ Path convention in this doc: `src/…`, `test/…` and `bin/…` are relative to paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.ts`, `decide/policy.ts`, `model/host.ts`, …) are relative to `packages/runtime/src/`. Every other path is from the repo root. -- **Branches.** `mvp-v2` (this doc) = `origin/runtime` 74f17c0 (the colleague Mehar's latest: runtime batches 4 and - 5, situation-v2, `realapps/`, v2 curriculum port, `HANDOFF.md`, `docs/runtime/RESULTS.md`) plus six local - commits: 7dab2b3 (AGENTS.md, CLAUDE.md, `docs/agents/**`), f3636b2 (default mode `observe`), b435acb (CI workflow, - committed root `package-lock.json`, `bin/genclass-runtime.mjs` as 100755), then b561244 and 6ac4737 (docs) and - 806a296 (release commit for `0.1.0-alpha.1`, the head). `mvp-v2` is **not pushed** - (`git rev-list --count origin/runtime..mvp-v2` = 6). The local branch `mvp` (b15415b, based on 654d822 = - situation-v1) is superseded. `main` and `origin/main` are still 654d822. -- **Shipped on npm:** `@genclass/runtime@0.1.0-alpha.1` (`latest`, 2026-10-08, release commit 806a296, local tag - `v0.1.0-alpha.1` not pushed): NaN fix, situation-v2, default `observe`, no model. Before it, - `@genclass/runtime@0.1.0-alpha.0` (git tag `v0.1.0-alpha.0` = 654d822). That one predates - situation-v2, defaults to `guard`, has no model, and predates the NaN fix (ad24804: `util.ts` -> `describe` - recursed forever on a `NaN` store value). `@genclass/runtime-model` is **not published** (404). -- **Runtime on `mvp-v2`:** situation-v2, decisions at the network boundary (`delivery` trigger, - `RuntimeImpl.runDelivery`), no store-write holds by default (`policy.holdWrites` false), default mode `observe` - (`runtime.ts` -> `o.mode ?? "observe"`). Verified when these docs were written, on 2026-10-08 (macOS, Node v25.6.0): `tsc` clean, - `tsup` OK, unit tests 40 files passed + 1 skipped (41), 332 tests passed + 14 skipped, plus `review-perf` alone - 4 passed: **350 tests, 14 model-parity skips**. CI (`.github/workflows/ci.yml`) exists but has never run on - GitHub (branch not pushed). -- **Frozen:** the model's input format is frozen at tag **`situation-v2`** (annotated tag → commit 6e5e86e, - "Frozen runtime situation format v2"). `git diff situation-v2 b435acb -- packages/runtime/src` touches only - `runtime.ts`, `types.ts` and `devtools/index.ts` (f3636b2's default-mode change); `situation/` is identical. - `situation-v1` (1a77558) is superseded: R17-final1 and every other checkpoint trained so far do **not** match this - runtime. -- **Running on Azure now** (lead's read-only portal look, 04:14 UTC 2026-10-08, resource group `rg-jev-train`): - `vm-jev-c01`…`c23` (F80) and `vm-jev-train` running, `vm-jev-data` deallocated. Per `training/NEEDS.md`, SIM is - generating situation-v2 data on 20 nodes (c02–c09, c12–c23: ≥ 10M gold + ≥ 50M unlabeled into - `train:/data/sim-out/v2-*`) and REAL real-browser gold rows on c01, c10, c11 (≥ 500k target; batches - `v2b1`/`v2b2`/`v2b3`). Mehar operates the cluster. **Nobody on our side touches Azure.** -- **No situation-v2 model exists.** Next (HANDOFF "Current state"): 150M teacher (T150) on v2 gold → teacher labels - on unlabeled rows → distil R17 (default) and R32 → DAgger via SIM `--on-policy` → EVAL → - `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0` (owner's 2FA). -- **Default install today:** `GenClass.init()` starts in `observe`, tries the unpublished model URL, ends in model - status `error` and logs `[GenClass] Model unavailable (<error>); observing only.` From then on it traces and learns - but never builds a situation or decides. No test covers this path. +- **Branches.** `mvp-v2-merge` (this doc, head f107013, **not pushed**) = `mvp-v2` (c16a3b0) + dabbce2, the merge of + Mehar's `origin/runtime` at eff18cb + 10e5c3b (lockfile sync) + 054da38 and f107013 (runtime fixes, below). + `mvp-v2` = `origin/runtime` 74f17c0 plus 7dab2b3 (agent docs), f3636b2 (default `observe`), b435acb (CI, root + lockfile, CLI 100755), b561244 and 6ac4737 (docs), 806a296 (release commit `0.1.0-alpha.1`) and c16a3b0 (publish + record). Mehar's six merged commits: d53e836 (realapps wave 3), d05abc1 (npm README rewrite), 2516a6e (OPEN_TASKS: + alpha.1 contents, Polar Parts rollout plan), 29b7f28 (`situation()` purity regression test), f3a9dd1 (one-command + install, `/auto`, CDN script tag, `genclass-runtime` alias), eff18cb (v2 data done). **`origin/runtime` has moved on + to 5bc40c9** (ca08174 realapps wave 4, 6d6eb00 REAL v2 production done, 416e374 first r17-v2a results, 5bc40c9 + runtime batch 6 = model-provided gate thresholds, tag `situation-v2.1`); none of them is merged here. A trial + `git merge-tree HEAD origin/runtime` conflicts only in `packages/runtime/STATUS.md`. Local branch `mvp-v2-b6` + (4e95373, worktree `GenClass-lib-b6`) already merges 5bc40c9 on top of f107013; this doc does not cover it. +- **Shipped on npm:** `@genclass/runtime@0.1.0-alpha.1` (`latest`, 2026-10-08 ≈ 05:33 UTC, from release commit 806a296, + local tag `v0.1.0-alpha.1` not pushed): NaN fix, situation-v2, default `observe`, no model. It has **none of Mehar's + install paths** (`npm view @genclass/runtime@0.1.0-alpha.1 exports` has no `./auto*`; `sideEffects: false`) and + neither fix below. Before it, `0.1.0-alpha.0` (tag `v0.1.0-alpha.0` = 654d822): situation-v1, `guard` default, NaN + crash. `@genclass/runtime-model` is **not published** (404). +- **Next release** (`0.1.0-alpha.2`, or a beta together with the v2 model once it is validated; `OPEN_TASKS.md` Next + 14): the install paths, the two fixes, and whatever of `origin/runtime` is merged by then. Before any build or pack + meant to ship, bump `packages/runtime/package.json` (still `0.1.0-alpha.1`; the global build bakes the version into + its jsDelivr URLs) and fix the install findings below. Publishing needs the user's 2FA ([RELEASE.md](../../RELEASE.md)). +- **Runtime on `mvp-v2-merge`:** situation-v2, decisions at the network boundary (`delivery` trigger, + `RuntimeImpl.runDelivery`), no store-write holds by default, default mode `observe` (`runtime.ts` -> + `o.mode ?? "observe"`). New: the `@genclass/runtime/auto` entries and the CDN/script-tag build (`src/auto.ts`, + `src/cdn/*`); **054da38** observe mode never holds or delays a delivery and still records its decision (fixes DL-3, + DL-4); **f107013** redaction fixes (SIT-1, SIT-3). Verified 2026-10-08 (macOS, Node v25.6.0): `tsc` clean, `tsup` OK, + unit tests 44 files passed + 1 skipped (45), 375 passed + 14 skipped, `review-perf` alone 4 passed: **393 tests in + 46 files, 14 model-parity skips**. CI exists but has never run on GitHub (nothing pushed; `mvp-v2-merge` is not a + CI trigger branch). +- **Frozen format:** tag **`situation-v2`** (annotated → 6e5e86e). f107013 changed model-visible text for redacted + values only: `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/state/fields.ts + packages/runtime/src/util.ts` now shows `content.ts`, `fields.ts`, `util.ts`. No new tag was cut, the v2 SIM data + and r17-v2a predate it, and `training/curriculum/rt.py` has no redactor at all (STATUS "Fix after + 0.1.0-alpha.1"). On `origin/runtime`, batch 6 adds one neutral stall fact and tags `situation-v2.1` (5bc40c9). +- **Azure (Mehar's jobs; they run on their own while Mehar sleeps; nobody on our side touches Azure).** SIM v2 data is + **done**: gold 10,423,855 rows, unlabeled 51,272,078 (`OPEN_TASKS.md` "Done"); SIM's 20 nodes were deallocated + 04:55–05:10 UTC. TRAIN (per `training/LOG.md` 04:50–05:22 and the `training/NEEDS.md` claim table): workbench c02; + **`r17-v2a`** (R17 from `r17-final1`, `mix_v2a`, 64 ranks on c09, c03–c08, c13, launched 05:14 UTC, ETA ≈ 06:20; + `training/v2_post.sh` detached on c09 then evaluates `sim2e` + `sim2f` + expected gain, exports q8/fp16 with the + `sim2e` calibration and serves the tar on :8801); **`t150-v2a`** (150M teacher from the MIT ettin-150m base, + `mix_t150v2`, 88 ranks on c12, c14–c23, launched 05:20 UTC, ETA ≈ 08:30). REAL `v2c1`..`v2c4` had not landed at + eff18cb; `v2b1`..`v2b3` stopped at ≈ 20.5k trajectories each with pre-fix diagnosis labels (`training/NEEDS.md` 16). + Spend ≈ $440, burn ≈ $110/h with 20 nodes (LOG 05:22). +- **First v2 model: trained, not published, not in this branch.** `origin/runtime` 416e374 (`docs/runtime/RESULTS.md`) + reports r17-v2a: `sim2e` diagnosis 84.4%, action 77.9%, guard FIR 0.00%, heal FIR 0.46%; real-app eval set guard and + heal FIR 0.00%; recall at the fixed 0.9/0.8 gates very low (duplicate 0.6%, stale 1.0% on real apps), hence batch 6's + model-provided thresholds. Still to come: teacher, distillation, DAgger, EVAL, then `@genclass/runtime-model@0.1.0` + and `@genclass/runtime@0.1.0` (owner's 2FA). No t150-v2a result is recorded anywhere yet. +- **Default install today** (npm alpha.1 and this branch): `GenClass.init()` starts in `observe`, tries the + unpublished model URL, ends in model status `error` and logs `[GenClass] Model unavailable (<error>); observing + only.` From then on it traces and learns but never builds a situation or decides. No test covers this path. +- **Install code review (2026-10-08): 11 confirmed findings, nothing shipped yet.** Worst: `init` and + `init --mode guard` install observe while printing "Mode guard" (`bin/lib/plan.mjs` -> `AUTO`, `scriptTag`), and the + tree's version makes the CLI and global build point at the published alpha.1, which lacks those files. Full table: + [Install code review](#install-code-review-2026-10-08). - **Binding rules** (CONTRACT §0, §0.5, §13): no hardcoded bug rules; one situation implementation (frozen at situation-v2); determinism through the injected `Clock`; sim/realapps never read demos; one runtime dependency; precision first, default `observe`. Our run policy replaces CONTRACT §0 rule 5 for this machine (light checks local; ask before anything heavier, Azure, `git push`, `npm publish`). - **Coordination files:** `HANDOFF.md` (start here for Mehar's sessions), `OPEN_TASKS.md`, `docs/runtime/RESULTS.md` - (results and comparisons; "update it with every result"), `packages/runtime/STATUS.md` (CORE), per-workstream - `NEEDS.md` (`training/NEEDS.md` also holds Azure node claims and data locations). -- **Review of the situation-v2 work (2026-10-08): 52 confirmed findings, none left uncertain.** The worst: the F2 - fact prints raw text of redacted fields (`situation/content.ts` -> `contentFacts`); a delivery `discard` is a - silent no-op on redux/zustand stores (`state/hub.ts` -> `StoreHub.applyFilter`); unlabeled SIM rows hard-label - `expected` diagnoses that S1 would relabel; SIM still samples the v1 3,200-char budget for 40% of trajectories - while v2 data is generated. Several touch model-visible text or the live data run: coordinate with the user (and - through them Mehar) before fixing. Full list: [Review of the situation-v2 work](#review-of-the-situation-v2-work-2026-10-08). -- **Docs drift.** `HANDOFF.md` still says `guard` is the default (both READMEs and `OPEN_TASKS.md` are fixed in the - working tree, pending commit); `CONTRACT.md` has no `delivery` trigger - and its §13 default-mode entry still says situation-v1 data "stays valid"; `docs/runtime/ARCHITECTURE.md` - still says 3,200 chars. Tables in [Doc drift](#doc-drift-project-and-coordination-files). No TODO/FIXME/XXX/HACK - markers in code. + (results and comparisons; "update it with every result"), `packages/runtime/STATUS.md` (CORE), + `packages/runtime/INSTALL-NEEDS.md` (INSTALL), per-workstream `NEEDS.md` (`training/NEEDS.md` also holds Azure node + claims and data locations). +- **Review of the situation-v2 work (2026-10-08): 52 confirmed findings; 4 fixed on this branch** (SIT-1, SIT-3 in + f107013; DL-3, DL-4 in 054da38; DL-10 only for observe mode). Still open, the worst: a delivery `discard` is a silent + no-op on redux/zustand stores (`state/hub.ts` -> `StoreHub.applyFilter`); unlabeled SIM rows hard-label `expected` + diagnoses that S1 would relabel; SIM sampled the v1 3,200-char budget for 40% of trajectories in the finished v2 + data. Coordinate with the user (and through them Mehar) before fixing. Full list: + [Review of the situation-v2 work](#review-of-the-situation-v2-work-2026-10-08). +- **Docs drift.** `HANDOFF.md`, `packages/runtime/test/install/INSTALL-README-SNIPPET.md` and the `init` usage text + still say `guard` is the default; `packages/runtime/CHANGELOG.md` lists the install paths under `0.1.0-alpha.1`; + `CONTRACT.md` has no `delivery` trigger; `docs/runtime/ARCHITECTURE.md` still says 3,200 chars. Tables in + [Doc drift](#doc-drift-project-and-coordination-files). No TODO/FIXME/XXX/HACK markers in code. ## Files | path | role | key content | |---|---|---| | `HANDOFF.md` | Mehar's hand-off for continuing Claude sessions (updated 2026-10-08) | current state table (npm, git, runtime, model, data, training), repo map, hard-won rules (8 GB Mac, Azure, zsh, freeze, licensing, commits), "How to continue" | -| `OPEN_TASKS.md` | Project status (owner inferred: lead) | Done / In progress / Next (stale, see Drift) / Model quality / Needs the user / Known risks | +| `OPEN_TASKS.md` | Project status (owner inferred: lead), "as of ~05:45 UTC" in the merged tree | Done (alpha.1 publish, v2 SIM data) / In progress (r17-v2a, t150-v2a, REAL `v2c*`, one-command install, demos) / Next 6–18 (14: next prerelease with the install) / Model quality / Needs the user (2FA publishes, push, Polar Parts rollout) / Known risks | | `docs/runtime/RESULTS.md` | Results, comparisons and training log (Mehar, 2026-10-08) | §1 model stages, §2 R17 vs R32, §3 v1 vs v2 separability, §4 never-worse sweep, §5 demos (v0.1 baseline), §6 data volume, §7 training log; FIR next to every recall number | -| `packages/runtime/STATUS.md` | CORE's status (batch 5, 2026-10-08) | State (VM test counts, perf, never-worse sweep), batch 5 and batch 4 changes with "Contract deltas", batch 3, headless recipe, trigger table, example situations, **Deviations**, **Open issues** | +| `packages/runtime/STATUS.md` | CORE's status ("Updated" line still says batch 5) | State (VM test counts: 42 files / 348 tests after 29b7f28), "Fix after 0.1.0-alpha.1: two redaction leaks" (f107013), "Fix after batch 5: situation() purity" (29b7f28), batch 5 and batch 4 with "Contract deltas", batch 3, headless recipe, trigger table, example situations, **Deviations**, **Open issues**. No entry yet for 054da38 (observe deliveries) | +| `packages/runtime/INSTALL-NEEDS.md` | INSTALL → lead / CORE / MODEL / UI (f3a9dd1) | the `npx genclass-runtime` naming decision, the `package.json` changes (`./auto*` exports, `sideEffects` list, `unpkg`/`jsdelivr`), the tsup configs, runtime behaviour INSTALL relies on | +| `packages/runtime/CHANGELOG.md` | npm changelog (f3a9dd1) | `## 0.1.0-alpha.1` lists the one-command install, `/auto` and the script tag, which the published alpha.1 does not contain (see Drift) | +| `packages/runtime/test/install/RESULTS.md`, `INSTALL-README-SNIPPET.md` | INSTALL's VM test record; README snippet | run against a packed `0.1.0-alpha.0`-versioned tarball of Mehar's tree, which defaulted to `guard`; the snippet still says `guard` is the default | | `docs/runtime/CONTRACT.md` | Binding build contract (lead) | §0 ground rules, §0.5 product principles, §1 layout, §2–§12 spec, §13 approved additions (now incl. default `observe`) | | `docs/runtime/API.md` | Public API reference | updated for v2 (delivery, `holdWrites`, `untrustedEvents`, 2,400 budget) and for the observe default | | `docs/runtime/ARCHITECTURE.md` | Design overview | principles (now observe default), data flow, training summary | @@ -90,18 +115,19 @@ paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.t | `demos/NEEDS.md` | DEMOS → CORE/MODEL/UI/lead | §1–§8, written against batch 3 (stale for v2, see Drift) | | `packages/runtime/UI-NEEDS.md` | UI → CORE requests | Open 1–2 and Nice-to-have 3 (stale, see Drift) | | `realapps/README.md`, `realapps/EXAMPLES.md` | REAL's corpus, harness and audit | see [realapps.md](realapps.md) | -| `README.md`, `packages/runtime/README.md` | Repo landing page; npm README | say `observe` is the default (working tree, pending commit) | +| `README.md`, `packages/runtime/README.md` | Repo landing page; npm README (rewritten by Mehar in d05abc1, merged) | both say `observe` is the default and `0.1.0-alpha.1` is `latest`; the npm README says the `init`, `/auto` and script-tag paths are "not in `0.1.0-alpha.1`" | | `packages/runtime-model/MODEL_CARD.md` | Model card for the unpublished `@genclass/runtime-model` | status "final round 1 on the frozen runtime (situation-v1)"; the only tracked file in `packages/runtime-model/` | | `.github/workflows/ci.yml` | CI (b435acb) | Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci`, typecheck and build of `@genclass/runtime`, unit tests without `test/browser/**` and `review-perf`, then `review-perf` with `--retry=2` | | `package-lock.json` (root) | committed in b435acb | CI runs `npm ci` from it; keep it in sync | -| `AGENTS.md`, `CLAUDE.md`, `docs/agents/**` | Agent docs (7dab2b3, refreshed for v2) | run policy, commands, ground rules, subsystem docs | +| `AGENTS.md`, `CLAUDE.md`, `docs/agents/**` | Agent docs (7dab2b3, refreshed for v2 in b561244; this doc, AGENTS.md, repo-map and glossary re-verified at f107013) | run policy, commands, ground rules, subsystem docs | | `scripts/vm.sh` | Mehar's way to build/test on the `train` VM (`sync`, `run`, `exec`, `get` per SLOT) | needs `~/.jev-local/azure_hosts` and `~/.ssh/jev_azure` (not in repo); we do not use it without asking | | `packages/runtime/test/review-*.test.ts` | REVIEW's regression tests (10 files) | must pass unchanged | | `packages/runtime/test/smoke/smoke.sh` | npm tarball smoke test (Vite app, headless Chromium) | runs with `model: false`; ask before running | | `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/SPEC.md`, … | **Legacy jev-local docs**, not the runtime contract | CONTRACT §1: "stays as is. Do not edit it." | -[RELEASE.md](../../RELEASE.md) at the repo root (untracked in the working tree, not in b435acb) is the release -procedure: Part A for `0.1.0-alpha.1`, Part B for the model and `0.1.0`. `extension/RELEASE.md` is the legacy +[RELEASE.md](../../RELEASE.md) at the repo root (committed in b561244, publish recorded in c16a3b0) is the release +procedure: Part A for `0.1.0-alpha.1` (done), Part B for the model and `0.1.0`. It has no part for the next +prerelease with the install paths (`0.1.0-alpha.2`). `extension/RELEASE.md` is the legacy Chrome-extension release note. ## Concepts and data structures @@ -110,7 +136,8 @@ Chrome-extension release note. Every commit up to 74f17c0 is by Mehar Khanna (messages prefixed "Mehar commit: …"); he ran the original multi-agent team (lead, CORE, MODEL, UI, SIM, REAL, DEMOS, TRAIN, REVIEW) and operates the Azure cluster and the npm -org (`genclass`, owner meharpro). 7dab2b3, f3636b2 and b435acb are by Karan (this repo's user). The roles below belong +org (`genclass`, owner meharpro). 7dab2b3, f3636b2, b435acb and every later `mvp-v2`/`mvp-v2-merge` commit not +prefixed "Mehar commit" are by Karan (this repo's user; `0.1.0-alpha.1` was published as `karanvir1729`). The roles below belong to the original team: where a doc says "ask the lead", **ask the user**. | workstream | owns (edit rights) | writes | reads / serves | @@ -124,6 +151,7 @@ to the original team: where a doc says "ask the lead", **ask the user**. | **DEMOS** | `demos/` | `demos/NEEDS.md`, `demos/README.md`, `demos/results*` | STATUS | | **TRAIN** | `training/` | `training/NEEDS.md`, `LOG.md`, `EVAL.md`, `PLAN-v1.md` | SIM/REAL output | | **REVIEW** | `packages/runtime/test/review-*.test.ts` | regression tests | runtime code | +| **INSTALL** (new in f3a9dd1) | `src/auto.ts`, `src/cdn/**`, `bin/lib/**`, the `init`/`remove` commands, `test/install/**` (`packages/runtime/INSTALL-NEEDS.md` header) | `packages/runtime/INSTALL-NEEDS.md`, `test/install/RESULTS.md` | runtime `GenClass.init`, model host options | Separation rule (CONTRACT §0 rule 4): SIM and DEMOS do not read each other's code. REAL also never reads demos (it imports from `sim/src`, which is allowed). @@ -170,47 +198,77 @@ imports from `sim/src`, which is allowed). | d73d20c | Mehar, 10-08 00:07 | HANDOFF.md; v2 curriculum port; realapps (+24 apps) and training updates | | 74f17c0 | Mehar, 00:09 | `docs/runtime/RESULTS.md` (= `origin/runtime`) | | b435acb | Karan, 00:15 | CI workflow, root lockfile, CLI mode 100755 | +| d53e836 | Mehar, 00:17 | realapps wave 3: "30 more apps (96 total)" | +| d05abc1, 2516a6e | Mehar, 00:19 | npm README rewrite (one-command install); OPEN_TASKS: alpha.1 contents, Polar Parts rollout plan | +| 29b7f28 | Mehar, 00:50 | `test/situation-purity.test.ts`; error pruning moved out of situation building | +| f3a9dd1 | Mehar, 01:12 | **One-command install**: `bin/lib/*` (`init`/`remove`), `src/auto.ts`, `src/cdn/*`, global + CDN builds in `tsup.config.ts`, `test/install/*`, `packages/genclass-runtime`, `CHANGELOG.md`, `INSTALL-NEEDS.md` (its message says "0.1.0-alpha.1", but that number went to our publish) | +| b561244, 6ac4737 | Karan, 01:25–01:26 | agent-doc refresh, honest READMEs, OPEN_TASKS, RELEASE.md | +| 806a296 | Karan, 01:27 | **release commit `0.1.0-alpha.1`** (published ≈ 05:33 UTC as `latest`; tag `v0.1.0-alpha.1`) | +| c16a3b0 | Karan, 01:36 | docs: record the publish (= `mvp-v2` head) | +| eff18cb | Mehar, 01:43 | "v2 data done (10.4M gold, 51.3M unlabeled)"; `vm.sh` keeps the `sim/out` symlink; v2 import/eval scripts (`import_v2.sh`, `prep_v2.py`, `v2_post.sh`, `eval_real.py`, mixes `mix_v2a`, `mix_t150v2`) | +| dabbce2 | Karan, 02:08 | merge `origin/runtime` (eff18cb) into `mvp-v2-merge` | +| 10e5c3b | Karan, 02:09 | lockfile sync after the merge | +| 054da38 | Karan, 02:47 | runtime: observe mode never holds or delays deliveries; background delivery decisions recorded (`test/observe-delivery.test.ts`) | +| f107013 | Karan, 02:47 | runtime: redact F2 diffs and numeric/array secrets under secret containers (`test/redaction-v2.test.ts`) (head) | + +Not merged (on `origin/runtime` only): ca08174 (Mehar, 02:02, realapps wave 4), 6d6eb00 (02:31, REAL v2 production +done: 616k gold, 16.6k eval), 416e374 (02:35, RESULTS: first r17-v2a numbers), 5bc40c9 (02:44, runtime batch 6: +model-provided gate thresholds, no-baseline stall fallback; tag `situation-v2.1`). `git diff --stat 654d822 b435acb`: 451 files, +90,715 / −20,699. Earlier history (13 commits from 7a7ff6d to 654d822, all Mehar's) is legacy GenClass content, the runtime build-up and batch 3 / `situation-v1`. ### Version markers -| marker | value (2026-10-08, `mvp-v2` at 806a296) | meaning | +| marker | value (2026-10-08 ~07:00 UTC) | meaning | |---|---|---| -| `mvp-v2` | 806a296 (release commit for `0.1.0-alpha.1`, fast-forwarded), not pushed | this branch | -| `origin/runtime`, local `runtime` | 74f17c0 | Mehar's line; HANDOFF says "push to `origin runtime` as you go" | -| `main`, `origin/main` | 654d822 | not updated since the alpha | +| `mvp-v2-merge` | f107013, not pushed | this branch | +| `mvp-v2` | c16a3b0, not pushed | our line before the merge (release commit 806a296 + publish record) | +| `origin/runtime` | 5bc40c9 (this branch merged it at eff18cb) | Mehar's line; HANDOFF says "push to `origin runtime` as you go"; still defaults to `guard` | +| local `runtime` | 74f17c0 | stale local copy | +| `mvp-v2-b6` | 4e95373 = f107013 + merge of 5bc40c9 | separate worktree `GenClass-lib-b6`; not described here | +| `release/runtime-0.1.0-alpha.1` | 806a296 | worktree `GenClass-lib-release` | +| `main`, `origin/main` | 654d822 | not updated since the first alpha | | `mvp` (local) | b15415b on 654d822 | superseded | | tag `situation-v1` | → 1a77558 | v1 format; superseded | -| tag `situation-v2` | annotated tag object 75df720 → commit 6e5e86e | **current frozen training format** | +| tag `situation-v2` | annotated tag object 75df720 → commit 6e5e86e | **frozen training format of the v2 data and r17-v2a** | +| tag `situation-v2.1` | → 5bc40c9 (not merged here) | batch 6: v2 plus one neutral stall fact | | tag `v0.1.0-alpha.0` | → 654d822 | the first published alpha | -| tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1; local only, not pushed | -| `packages/runtime/package.json` `version` | `0.1.0-alpha.1` on `mvp-v2` | bumped in release commit 806a296 (now the head of `mvp-v2`) | +| tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1 (`latest`); local only, not pushed | +| `packages/runtime/package.json` `version` | `0.1.0-alpha.1` | **already published**: bump before building or packing the next release | +| `packages/genclass-runtime/package.json` | `0.1.0-alpha.1`, dependency `@genclass/runtime` `0.1.0-alpha.1` | unpublished alias (no `genclass-runtime` on npm) | | `@genclass/runtime-model@0.1.0` | not published (404); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | | GitHub release `runtime-model-v0.1.0` | no such tag in the repo; the CLI's default `--from` 404s (per the lead) | | | v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** a runtime model; used by demos and model tests | | R17-final1 / R32-final1 | situation-v1; on the `train` VM (`~/gcl/train-out/final1/`) and Mehar's Mac (`packages/runtime-model/files/r17/`, gitignored) | baseline only; does not match the v2 runtime | +| `r17-v2a`, `t150-v2a` | training runs on Azure (see TL;DR); r17-v2a's export is served from c09 by `v2_post.sh`, not published | first v2 student / teacher | -### Status at b435acb +### Status at f107013 | item | state | owner | evidence | |---|---|---|---| | Runtime batches 4 and 5 (situation-v2) | done, frozen | CORE | fcd1e68, 6e5e86e; STATUS; `test/delivery.test.ts`, `no-reorder.test.ts`, `content.test.ts` | -| Default mode `observe` | done on `mvp-v2` and in npm `0.1.0-alpha.1` (not on `origin/runtime`, not in `0.1.0-alpha.0`) | us (f3636b2) | `runtime.ts` -> `RuntimeImpl` constructor; `test/default-mode.test.ts`; CONTRACT §13 | +| Default mode `observe` | done on `mvp-v2`, this branch and npm `0.1.0-alpha.1` (not on `origin/runtime`, not in `0.1.0-alpha.0`) | us (f3636b2) | `runtime.ts` -> `RuntimeImpl` constructor; `test/default-mode.test.ts`; CONTRACT §13 | +| Observe never holds or delays a delivery; background delivery decisions recorded | done here (054da38); not on npm | us | `runtime.ts` -> `RuntimeImpl.runDelivery`, `deliveryHoldable`, `finalizeDeliveries`; `test/observe-delivery.test.ts` | +| Redaction fixes (F2 diff, numbers/arrays under secret containers) | done here (f107013); not on npm; not mirrored in `rt.py` | us | `state/fields.ts` -> `redactedStringDiff`; `util.ts` -> `isSensitivePath`; `test/redaction-v2.test.ts` | +| `situation()` purity test | done (29b7f28) | CORE | `test/situation-purity.test.ts` | +| One-command install, `/auto`, script tag | merged here (f3a9dd1); not on npm; 11 open review findings | INSTALL | `bin/lib/*`, `src/auto.ts`, `src/cdn/*`, `test/install/*` | | CI | workflow committed; never run on GitHub | us (b435acb) | `.github/workflows/ci.yml` | | NaN fix | in code since ad24804; on npm since `0.1.0-alpha.1` | CORE | `util.ts` -> `describe`; `test/nan.test.ts`; `sim/NEEDS.md` g still says OPEN | | npm `0.1.0-alpha.0` | published (guard default, no model, v1) | lead | tag `v0.1.0-alpha.0` | -| npm `0.1.0-alpha.1` (NaN fix, situation-v2, observe default) | published 2026-10-08, `latest` | karanvir1729 | OPEN_TASKS "Done" | +| npm `0.1.0-alpha.1` (NaN fix, situation-v2, observe default) | published 2026-10-08, `latest` | karanvir1729 | OPEN_TASKS "Done"; `npm view` | | SIM v1 phase A / B | done (600,676 / 1,415,344 rows); superseded | SIM | training/NEEDS "SIM → TRAIN: scaled data" | | Final round 1 (situation-v1) | done: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE 0.009; guard recall on clear stale/duplicate 7.7% | TRAIN | `training/EVAL.md`, RESULTS §1 | | T1 runs and v1 teacher `t150-g1` | stopped at the v2 freeze, no results | TRAIN | `training/LOG.md` 01:13–03:35 | -| SIM v2 gold + unlabeled | **generating** on 20 nodes (≥ 10M + ≥ 50M) | SIM | HANDOFF; training/NEEDS claim table | -| REAL v2 production | **generating** on c01, c10, c11 (`v2b1`–`v2b3`, 30k trajectories each, ≥ 500k gold target); v2 pilot done (2,519 gold incl. 135 `delivery`) | REAL | training/NEEDS 16 | -| v2 teacher, students, DAgger, EVAL | not started | TRAIN | PLAN-v1 P1–P5 | +| SIM v2 gold + unlabeled | **done**: 10,423,855 gold, 51,272,078 unlabeled; imported as `sim2`, `sim2e`, `sim2f`, `cur5` | SIM / TRAIN | OPEN_TASKS "Done"; `training/LOG.md` 04:50–05:22 | +| REAL v2 production | `v2b1`–`v2b3` stopped (≈ 380k gold, pre-fix diagnosis labels); `v2c1`–`v2c4` not landed at eff18cb (done per `origin/runtime` 6d6eb00: 616,437 gold, eval set 16,600) | REAL | `training/NEEDS.md` 16 | +| `r17-v2a` | running at eff18cb (ETA ≈ 06:20 UTC); finished per `origin/runtime` 416e374 (numbers in TL;DR) | TRAIN | `training/LOG.md`; RESULTS on `origin/runtime` | +| `t150-v2a` (teacher) | running (ETA ≈ 08:30 UTC); no result recorded | TRAIN | `training/LOG.md` | +| Teacher labels, distillation, DAgger, EVAL | not started | TRAIN | PLAN-v1 P3–P5 | +| Next prerelease with the install (`0.1.0-alpha.2` or a beta with the model) | not started: version bump and install fixes first | user (2FA) | OPEN_TASKS Next 14 | | `@genclass/runtime-model@0.1.0`, then `@genclass/runtime@0.1.0` | not started | lead / user | HANDOFF "How to continue" step 3 | | Demos with a trained model | not started (numbers are v0.1 only) | DEMOS | RESULTS §5 | -| Public demo hosting; merge into `main` | waiting on the user | user | OPEN_TASKS "Needs the user" | +| Public demo hosting; merge into `main`; Polar Parts rollout | waiting on the user (Polar Parts once the trained model is good: observe first, then guard) | user | OPEN_TASKS "Needs the user" | ## How it works @@ -220,7 +278,7 @@ imports from `sim/src`, which is allowed). `localStorage.genclass`; `off` installs nothing; `observe|guard|heal` override the mode). Otherwise it sets `model: {}` and calls `createRuntime`. 2. `RuntimeImpl`'s constructor sets `this._mode = o.mode ?? "observe"`: **observe** unless the app asks for guard. - (The npm alpha.0 still defaults to guard.) + (The npm alpha.0 and `origin/runtime` still default to guard.) 3. `createModelHost` gets `baseUrl = DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`) and `preload: "idle"`; status starts `off`. 4. Observers install. Tracing, field versions, baselines, invariants, transition profiles and cadence learning run @@ -232,14 +290,35 @@ imports from `sim/src`, which is allowed). response and message at once, `trigger()` runs the passive action without building a situation, writes are never observed for decisions. No `Decision`, `Detection` or `ActionRecord` is recorded. `rt.ready` rejects (memoised); `ask`/`decide` reject. Nothing retries the load. -7. Before step 5 (status `off`), a salient trigger builds a situation, fails open and starts the load. A salient - delivery can wait up to `BODY_WAIT_MS` (100 ms) for its body even then (review finding DL-3). +7. Before step 5 (status `off`), a salient trigger builds a situation, fails open and starts the load. Since 054da38 a + delivery is never held then: `RuntimeImpl.deliveryHoldable` is false in observe mode, while paused, while the model + is not `ready`, when no non-passive delivery action is permitted, or when the model is too slow for the hold + budget, so `runDelivery` releases it synchronously before any body read and decides in the background (DL-3, DL-4 + fixed; in npm alpha.1 a salient delivery could still wait up to `BODY_WAIT_MS`, 100 ms). Even with a model, `observe` takes no action: decisions are made in the background and reported -(`test/default-mode.test.ts`). The only way to see decisions today is to self-host a model: no model matches +(`test/default-mode.test.ts`), including delivery decisions (`executed: false`; `test/observe-delivery.test.ts`). The only way to see decisions today is to self-host a model: no model matches situation-v2, the v0.1 model only exercises the pipeline (`npx genclass-runtime fetch-model <dir> --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`; a model download, so ask the user first). +### 1b. What the merged install paths do (not on npm yet) + +- `import "@genclass/runtime/auto"` (`src/auto.ts`) calls `src/cdn/auto-start.ts` -> `startAuto()` with no defaults: + it merges `<meta name="genclass">` (`src/cdn/config.ts` -> `readMetaConfig`) and `window.GENCLASS_CONFIG` + (`readWindowConfig`), calls `GenClass.init`, and mounts the devtools when the page config asks. So `/auto` runs + **observe** on this branch (the runtime default); `/auto/guard` and `/auto/heal` pass `{ mode }` + (`src/cdn/auto-guard.ts`, `auto-heal.ts`). Outside a browser it returns `GenClass.init()`'s inert runtime. +- The script tag `dist/genclass.global.min.js` (`src/cdn/global.ts` -> `install`) initialises from its data + attributes, the meta tag and `window.GENCLASS_CONFIG`, exposes `window.GenClass`, and loads the model worker + (`dist/cdn/worker.js`, from a Blob URL), onnxruntime-web (`dist/cdn/ort-*.js`) and the devtools on demand from + `assetBase()`, which pins jsDelivr/unpkg URLs to the version baked in at build time. +- `npx @genclass/runtime init` (`bin/lib/init.mjs` -> `init`, `bin/lib/detect.mjs` -> `detectProject`, + `bin/lib/plan.mjs` -> `planInit`) detects the framework, installs `@genclass/runtime@^<own version>` (or `--from`), + adds one import marked `// genclass:init` (plus a dev-only devtools line) or a script tag for plain HTML, shows the + diff and asks first. `remove` (`bin/lib/init.mjs` -> `remove`, `bin/lib/edit.mjs` -> `removeMarked`) deletes the + marked lines and files and uninstalls the package when its scan finds no other use. The CLI's mode mapping still + assumes the old guard default: see [Install code review](#install-code-review-2026-10-08). + ### 2. How a request moves between workstreams 1. The requester writes a NEEDS item with evidence and a status (OPEN or ASK), addressed to an owner. @@ -273,19 +352,27 @@ https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`; a model downloa - **Cluster** (HANDOFF "Rules"): `rg-jev-train`, eastus, quota 2,048 vCPU; nodes c01–c23 (F80 variants; c12–c23 added 2026-10-08 by `training/cluster_expand.sh`) plus `train` (1 TB `/data` disk, bundle server) and `data`. **The nightly auto-shutdown schedules are disabled** for the training push and must be re-enabled when it ends. -- **Claims** (training/NEEDS "Cluster expansion and claims"): SIM c02–c09 + c12–c23 for the v2 runs, each node - deallocated when its share is collected; REAL c01, c10, c11 until its batches finish; TRAIN holds no node; TRAIN - plans the teacher on c12–c23, students on c02–c11 and the workbench on c01 once v2 data lands. -- **Data locations:** SIM `train:/data/sim-out/v2-*` (check run: `v2chk-{gold,unl}`); REAL `c01:~/gcl/real-out/v2b1/`, - `c10:…/v2b2/`, `c11:…/v2b3/` (copied to `train:/data/real-out/` when done), v2 pilot `train:/data/real-out/v2-pilot/`. - All from training/NEEDS; not checkable from here. -- **Spend:** about $400 to date (RESULTS §7); PLAN-v1 estimates $3–4k for P0–P5. +- **Claims** (training/NEEDS "Cluster expansion and claims", at eff18cb): SIM's 20 v2 nodes are done and were + deallocated; TRAIN holds c02 (v2 workbench, from 05:05 UTC), c03–c09 + c13 (`r17-v2a`, ≈ 1.5 h) and c12 + c14–c23 + (`t150-v2a`, ≈ 5 h); REAL runs `v2c1`..`v2c4` on c01, c10, c11 and `data`. +- **Data locations:** SIM `train:/data/sim-out/v2-gold/` (10,423,855 rows: train 7,560,367 / dev 317,732 / test + 2,545,756) and `train:/data/sim-out/v2-unl/` (51,272,078 rows); on c02 (`training/import_v2.sh`, + `training/prep_v2.py`): 128 train shards `data/s3/sim2`, eval sets `sim2e` (20k held-out test + 8k dev) and `sim2f` + (18,690 held-out-feature rows), curriculum replay `cur5` (300k rows), a 27 GB tar served from c02:8799. REAL + `v2c*` into `train:/data/real-out/` when they land (the eval set `v2-eval` is built from them). All from + `training/NEEDS.md`, `training/LOG.md` and `OPEN_TASKS.md`; not checkable from here. +- **What runs unattended:** `training/v2_post.sh` on c09 waits for `models/r17-v2a/meta.json` to say `final`, then runs + `eval_sim.sh` on `sim2e` and `sim2f`, `eval_gain.py`, `export_runtime.py` with the `sim2e` calibration, and serves + the export tar on :8801 (arguments: run, export name, version; the script's own example is + `r17-v2a genclass-runtime-r17 2.0.0-rc1`). Nothing publishes it. +- **Spend:** ≈ $440 to date, ≈ $110/h while 20 TRAIN nodes run (`training/LOG.md` 05:22); PLAN-v1 estimates $3–4k + for P0–P5. The auto-shutdown schedules are still disabled (OPEN_TASKS "Needs the user"). ## Configuration and constants Status-relevant values only; the subsystem docs list the rest. -| name | value at b435acb | defined in | effect | +| name | value at f107013 | defined in | effect | |---|---|---|---| | default mode | `"observe"` | `runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | no actions unless `mode: "guard"`/`"heal"`, `?genclass=guard`, or `setMode` | | test-harness mode | `"guard"` | `test/helpers.ts` -> `setup` | CORE tests exercise interventions; `setup({ mode: undefined })` gives the product default | @@ -298,7 +385,7 @@ Status-relevant values only; the subsystem docs list the rest. | `policy.holdWrites` | `false` | `decide/policy.ts` -> `policyConfig`; `state/hub.ts` -> `StoreHub.holdWrites` | store writes apply at once; opt-in holds never reorder a store's writes | | `policy.thresholds` | report 0.6, guard 0.9, heal 0.8 | `decide/policy.ts` -> `policyConfig` | summed-mass gate + `requireDiagnosis` | | hold budget | "auto" = clamp(1.5 × median latency, `HOLD_MIN_MS` 150, `HOLD_MAX_MS` 800), `HOLD_FALLBACK_MS` 300 | `decide/policy.ts` | a trigger holds only if `expectedLatency() <= holdBudgetMs()` | -| `BODY_WAIT_MS` | 100 | `runtime.ts` | a salient delivery waits this long for its body clone | +| `BODY_WAIT_MS` | 100 | `runtime.ts` | a salient delivery that can be held waits this long for its body clone. One that cannot (`RuntimeImpl.deliveryHoldable` false: always in observe) is released first; an in-memory body (XHR, WebSocket, EventSource) is analysed at once, a fetch body at most until this wait ends or the chain's first write (`RuntimeImpl.finalizeDeliveries`) | | `DISCARD_MARK_MS` | 10,000 | `runtime.ts` | a delivery `discard` keeps dropping the chain's writes over newer data this long | | `LONG_RUNNING_MS` | 10,000 | `runtime.ts` (`waitOps`) | a delivery `defer` waits at most this per defer (≤ 2 defers) | | `BACKGROUND_DEADLINE_MS` | 5,000 | `runtime.ts` | non-held decisions | @@ -309,6 +396,11 @@ Status-relevant values only; the subsystem docs list the rest. | runtime `dependencies` | `onnxruntime-web` only; optional peers react, redux, zustand | `packages/runtime/package.json` | CONTRACT §0 rule 6 | | CI Node | 22 (`engines.node` `>=20`) | `.github/workflows/ci.yml`, `package.json` | | | kill switch | `genclass=off\|observe\|guard\|heal` (URL wins over `localStorage`) | `index.ts` -> `killSwitch` | rule GenClass out while debugging | +| package `version` | `0.1.0-alpha.1` (already on npm) | `packages/runtime/package.json` | baked into the global build (`tsup.config.ts` -> `globalBuild`, `__GENCLASS_VERSION__`), `src/cdn/global.ts` -> `assetBase`, and the CLI's install spec and default script tag (`bin/lib/init.mjs` -> `installSpec`, `bin/lib/plan.mjs` -> `scriptTag`) | +| subpath exports | `.`, `./auto`, `./auto/observe`, `./auto/guard`, `./auto/heal`, `./react`, `./redux`, `./zustand`, `./devtools`, `./worker` (only through `exports`; no `typesVersions`) | `packages/runtime/package.json` | `./auto*` are new since alpha.1 | +| `sideEffects` | `./dist/auto.js`, `./dist/auto/*.js`, `./dist/genclass.global.js`, `./dist/genclass.global.min.js`, `./dist/cdn/*.js`, `./src/model/worker.ts` (alpha.1 on npm: `false`) | `packages/runtime/package.json` | keeps `import "@genclass/runtime/auto"`; the src entry keeps the model loop in `dist/cdn/worker.js`; `./dist/worker.js` is missing (install finding) | +| `init` mode mapping | no mode and `guard` both write `@genclass/runtime/auto`; `observe`/`heal` write `/auto/<mode>`; the script tag gets `data-mode` only for non-guard modes | `bin/lib/plan.mjs` -> `AUTO`, `scriptTag` | wrong after the merge: `/auto` runs observe (install finding 1) | +| CLI markers | `genclass:init` (line, or `start`/`end` block), `genclass:inline` | `bin/lib/edit.mjs` -> `MARK`, `MARK_INLINE`, `removeMarked` | what `remove` deletes | ## Invariants and gotchas @@ -325,11 +417,13 @@ CONTRACT: "If something here is wrong, tell the lead; do not silently diverge." `packages/runtime/src/situation/*`. SIM drives it, REAL bundles it, `training/curriculum/rt.py` ports it. **Any change to model-visible text** (situation code, fact/question/action/diagnosis wording, `util.ts` formatting and redaction, op/event names) needs a new tag, regenerated SIM and REAL data, an `rt.py` mirror and retraining. - Data is being generated from this code right now: never make such a change without the user's go-ahead. + Training runs on v2 data right now: never make such a change without the user's go-ahead. On this branch f107013 + already changed the text of redacted values (no new tag; `rt.py` not mirrored; see Gotchas). Behaviour-only runtime fixes (most delivery findings) do not change wording but do change SIM/REAL dynamics and therefore labels: coordinate them too. 3. **Determinism (§0 rule 3).** No `Math.random`, `Date.now`, `performance.now` or global `setTimeout` in runtime - code; the injected `Clock`; ids from counters. Re-checked at b435acb: the only hits are `model/engine.ts` + code; the injected `Clock`; ids from counters. Re-checked at b435acb and again at f107013 (the new `src/cdn/*` and + `src/auto.ts` add none): the only hits are `model/engine.ts` (default `now = performance.now()`, timing only), `model/host.ts` (`requestIdleCallback` for preload) and `clock.ts` itself (`browserClock`). The devtools capture `requestAnimationFrame`/`setTimeout` at module load. 4. **Honest evaluation (§0 rule 4).** `demos/` is never read or modelled by `sim/` or `realapps/`; demos are never @@ -358,17 +452,29 @@ model only for salient situations, in a worker. (3) Observability: one console l - **Code wins over every doc.** CONTRACT.md does not describe batch 4/5 (no `delivery` trigger); the deltas live in STATUS "Contract deltas". HANDOFF still says guard is the default. -- **Two defaults in the wild.** `mvp-v2` and npm alpha.1 (`latest`) default to `observe`; `origin/runtime` and npm alpha.0 default to `guard`. - The tests' `setup()` defaults to `guard` on purpose. -- **"Observe never changes execution" is not quite true yet**: a salient delivery can wait up to 100 ms for its body - and XHR completion listeners run outside the original dispatch (finding DL-3). -- **The runtime is frozen.** See ground rule 2. `git diff situation-v2 HEAD -- packages/runtime/src/situation` must stay - empty unless the user approved a new format. +- **Two defaults in the wild.** This branch, `mvp-v2` and npm alpha.1 (`latest`) default to `observe`; + `origin/runtime` (still `o.mode ?? "guard"` at 5bc40c9) and npm alpha.0 default to `guard`. The tests' `setup()` + defaults to `guard` on purpose. Mehar's install CLI was written against the guard default, so on this branch it + maps `--mode guard` to the observe entry (install finding 1): never trust `init`'s "Mode" line here. +- **Observe and execution.** Since 054da38 observe never holds or delays a delivery and XHR listeners run inside the + original dispatch (`test/observe-delivery.test.ts`); npm alpha.1 still has DL-3 (up to 100 ms body wait). In guard + or heal mode, a delivery that cannot be held is now also released before its body is read. +- **The freeze has one deliberate exception.** f107013 changed model-visible text for redacted values, so + `git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/state/fields.ts + packages/runtime/src/util.ts` is not empty. Any further change needs the user's go-ahead (ground rule 2). +- **The package version is already taken.** `packages/runtime/package.json` says `0.1.0-alpha.1`, which is on npm + without the install paths. Building or packing this tree before a bump makes the global build, the CLI's install + spec and its default script tag point at the published alpha.1 (no `./auto`, no `dist/cdn/`, no global build). +- **The install evidence predates the merge.** `test/install/RESULTS.md` (real frameworks, VM) was recorded against a + tarball versioned `0.1.0-alpha.0` built from Mehar's tree, which defaulted to guard; locally only + `test/install/cli.test.ts` runs (fixture projects, `--no-install`), and it has no case for `--mode guard` or the + default mode. - **R17-final1 is a v1 model.** Do not load it into this runtime, ship it, or compare v2 numbers against it as if the formats matched. - **Tests are not type-checked.** `packages/runtime/tsconfig.json` includes only `src`. -- **Test counts differ by branch.** STATUS and HANDOFF say 41 files / 346 tests (origin/runtime, on the VM with a - model dir). On `mvp-v2`: 42 files, 350 tests (f3636b2 added `test/default-mode.test.ts`); without a model dir 14 +- **Test counts differ by branch.** HANDOFF says 346 tests, STATUS 42 files / 348 tests (origin/runtime at 29b7f28, on + the VM with a model dir). On `mvp-v2`: 42 files, 350 tests. On this branch: 46 files, 393 tests (adds + `default-mode`, `situation-purity`, `install/cli`, `observe-delivery`, `redaction-v2`); without a model dir 14 model-parity tests skip. `review-perf` can flake in a parallel run (5.5 ms vs its 2 ms bound once); run it alone. - **The shipped default path is untested.** No test references `DEFAULT_MODEL_BASE_URL` or "observing only"; the smoke test uses `model: false`. @@ -396,15 +502,15 @@ model only for salient situations, in a worker. (3) Observability: one console l and therefore labels change); (c) curriculum port only (`rt.py`/`scenarios.py`: SIT-4…SIT-7, SIT-9, SIT-12, SIT-13; no v2 curriculum set exists yet, per [training.md](training.md)); (d) data/infra scripts (SIT-2, ST-*, RA-*), which affect the live Azure runs; (e) docs (PD-*, SIT-14). -2. For (a)–(c), get the user's go-ahead and agree with Mehar whether it lands before or after the current v2 - generation. For (d), edit freely (docs owned by the right workstream). +2. For (a)–(c), get the user's go-ahead and agree with Mehar whether it lands before or after the next + training round (the v2 data is finished; r17-v2a and t150-v2a trained on it). For (d), edit freely (docs owned by the right workstream). 3. Add the regression test the finding suggests, in a new or existing non-review test file. **Change anything the model reads (after `situation-v2`)** -1. Get the user's go-ahead (it invalidates the v2 data being generated). +1. Get the user's go-ahead (it makes the finished v2 data and the models trained on it mismatch the runtime). 2. Change only `src/situation/*` plus `util.ts` helpers if needed; update STATUS example situations. 3. Tell SIM, REAL (regenerate) and TRAIN (`rt.py` mirror; per-header calibration keyed on exact instruction text, - training/NEEDS 5). Expect a new tag (`situation-v3`). + training/NEEDS 5). Expect a new tag (`origin/runtime` already has `situation-v2.1`). 4. Run the light checks locally (commands in [runtime/build-test-release.md](runtime/build-test-release.md)). **Fix doc drift** @@ -412,6 +518,14 @@ model only for salient situations, in a worker. (3) Observability: one console l 2. Edit the doc owned by the right workstream (CONTRACT: lead; STATUS/API: CORE; NEEDS: requester). 3. JSDoc in `types.ts` is safe; `BUILTIN_ACTIONS` descriptions and `DEFAULT_DIAGNOSES` are model input (frozen). +**Prepare the next release (with the install paths)** +1. Fix install findings 1, 2 and 4 at least (and decide on 3, 5, 6); add the missing `cli.test.ts` cases. +2. Bump `packages/runtime/package.json` (and `packages/genclass-runtime/package.json` if the alias ships) to + `0.1.0-alpha.2` or the planned beta; move the CHANGELOG bullets; run `npm install` so the root lockfile follows. +3. Merge or rebase onto the newer `origin/runtime` if it should ship (batch 6, `situation-v2.1`). +4. Run the light checks, then (ask first) `test/smoke/smoke.sh` and `npm pack`; the user publishes with 2FA + ([RELEASE.md](../../RELEASE.md) has no part for this version yet). + **Run checks** (local, per our run policy) - `npm ci` at the root; in `packages/runtime`: `npx tsc -p tsconfig.json --noEmit`, `npx tsup`, `NODE_OPTIONS=--expose-gc npx vitest run --exclude "test/browser/**" --exclude test/review-perf.test.ts`, then @@ -429,6 +543,10 @@ model only for salient situations, in a worker. (3) Observability: one console l | `test/content.test.ts` | F1, F2 (diff preview), F3, F5, F6, F7, F8, F9, read-your-writes | | `test/atoms.test.ts` | runs with `holdWrites: true`: a user write never overtakes an earlier held write; read-your-writes | | `test/nan.test.ts` | a `NaN` store value no longer recurses forever | +| `test/observe-delivery.test.ts` (11, 054da38) | observe: a conflicting fetch with a slow body resolves at network time and its background decision is recorded (`executed: false`) and reported, its writes not decided again; decided on the state it was delivered into; decided at the chain's first write if the body is late; F1 not lost; delivery standing questions answered; XHR listeners inside the original dispatch (`currentTarget` set); WebSocket/EventSource delivered synchronously and still decided; guard unchanged (held stale response discarded; a too-slow model releases at once and the write is late-reverted on its own) | +| `test/redaction-v2.test.ts` (10, f107013) | F2 on a secret field shows `[redacted]` on both sides (default and custom redactor); an unredacted field keeps its diff preview; `redactedStringDiff`; numbers, bigints and arrays under strong secret containers redacted; booleans/null visible; broad containers unchanged | +| `test/situation-purity.test.ts` (2, 29b7f28) | building situations for every trigger, in every context, changes no counter or later id; polling like the devtools overlay changes no decision, hold or id | +| `test/install/cli.test.ts` (20, f3a9dd1) | `init`/`remove` on fixture projects (Vite, Next 14/15/16, SvelteKit, Nuxt 3/4, Astro, Angular, CRA, Remix, React Router, webpack, plain HTML) with `--no-install`: edits, idempotence, byte-identical `remove`; edit helpers; page-config parsing; `assetBase`. Only `--mode observe` is covered: no case for `--mode guard` or the default | | `test/review-*.test.ts` (10) | REVIEW's batch-3 findings; must pass unchanged. `review-perf` times 5,000-item stores (run alone; CI retries it twice) | | `test/batch3.test.ts`, `budget.test.ts`, `situation.test.ts`, `policy.test.ts`, `smoke.test.ts` | redaction by meaning, section limits and auto budgets (2,400 on WebGPU), one situation per trigger, the §8 gate, smoke paths (explicit `mode: "guard"`) | | `test/model/*.test.ts` | 14 model-parity tests skip without `GENCLASS_MODEL_DIR` | @@ -436,7 +554,8 @@ model only for salient situations, in a worker. (3) Observability: one console l | `sim` (`SIM_RUNTIME=real npx vitest run`) | 19 tests, 5 files, against the built runtime | | `training/tests/test_curriculum.py` | the v2 curriculum test (passes per the situation reviewer; not run by the lead) | -Not run by us: Playwright specs, `smoke.sh`, realapps sweeps, demos eval, Python tests, training. `realapps/` has no +Not run by us: Playwright specs, `smoke.sh`, the install suite (`test/install/run-all.sh`: scaffolds, frameworks, +`cdn-check.mjs`), realapps sweeps, demos eval, Python tests, training. `realapps/` has no tests at all. ## Drift and open issues @@ -445,14 +564,19 @@ tests at all. | owner | item | state | |---|---|---| -| SIM (Mehar) | v2 gold ≥ 10M and unlabeled ≥ 50M on 20 nodes | running; budget skew (SIT-2) and unlabeled `expected` labels (ST-1) affect it | -| REAL (Mehar) | v2 production `v2b1`–`v2b3` (≥ 500k gold), copy to `train:/data/real-out/` with the eval set | running; see RA-* before using the data | -| TRAIN | import v2 SIM/REAL data (`import_final.sh` cannot read the v2 gz-shard layout, ST-8), T150 teacher on gold (PLAN P1), teacher eval as the separation gate (P2), soft-label unlabeled rows (P3), distil R17/R32 (P4), DAgger ×3 (P5), EVAL per trigger/budget/held-out set, calibration, export, parity | not started; several scripts untested (ST-2 to ST-7) | +| SIM (Mehar) | v2 gold and unlabeled | **done** (10,423,855 / 51,272,078); budget skew (SIT-2) and unlabeled `expected` labels (ST-1) are in it | +| REAL (Mehar) | `v2c1`–`v2c4` (fixed labels) into `train:/data/real-out/`, eval set `v2-eval` | not landed at eff18cb; done per `origin/runtime` 6d6eb00 (not merged) | +| TRAIN (Mehar) | `r17-v2a` (R17 on v2 gold) → `v2_post.sh` eval/export; `t150-v2a` teacher, then a continuation with REAL `v2c*` gold | running at eff18cb (r17-v2a done per `origin/runtime` 416e374; t150-v2a ETA ≈ 08:30 UTC) | +| TRAIN | teacher eval as the separation gate (P2), soft-label unlabeled rows (P3; `label_cluster.sh` cannot read gz shards, ST-2/ST-3), distil R17/R32 (P4), DAgger ×3 (P5), EVAL per trigger/budget/held-out set, data-derived gate thresholds (batch 6 on `origin/runtime`), export, parity | not started. v2 import uses `import_v2.sh` / `prep_v2.py` (ST-8 concerned `import_final.sh`); `v2_post.sh` evaluates on `sim2e`/`sim2f` instead of the v1-wired `final_post.sh` (ST-4) | | lead / user | `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`; rerun demos; `@genclass/runtime@0.1.0` without the alpha tag | after EVAL | | user | publish `0.1.0-alpha.1` (cut from `mvp-v2`, 806a296) | done 2026-10-08 (`latest`) | -| user | push `mvp-v2` (first CI run), merge into `runtime`/`main`; public demo hosting | waiting | +| INSTALL / us | fix the install findings (at least 1, 2 and 4 of [Install code review](#install-code-review-2026-10-08)), bump to `0.1.0-alpha.2` (or the planned beta), move the CHANGELOG bullets, resolve the `npx genclass-runtime` naming question (`INSTALL-NEEDS.md`), `npm pack` smoke test | open; before the next release | +| user | publish the next prerelease (2FA) | after the above | +| us | merge `origin/runtime` 5bc40c9 (batch 6, `situation-v2.1`, r17-v2a results, REAL v2 done; conflict only in `STATUS.md`), or adopt `mvp-v2-b6` | open | +| CORE | a STATUS entry for 054da38 (observe deliveries); `rt.py` follow-up for f107013 (no redactor in the curriculum) | open | +| user | push `mvp-v2` / `mvp-v2-merge` (first CI run; add the branch to the CI triggers or open a PR), merge into `runtime`/`main`; public demo hosting | waiting | | Mehar / user | re-enable the Azure auto-shutdown schedules when the push ends; deallocate idle nodes | open | -| CORE | review findings DL-1…DL-12 (behaviour) and SIT-1, SIT-3, SIT-8, SIT-10, SIT-11 (model-visible text) | open; see [How to change it safely](#how-to-change-it-safely) | +| CORE | review findings DL-1, DL-2, DL-5…DL-9, DL-11, DL-12, DL-10 outside observe (behaviour) and SIT-8, SIT-10, SIT-11 (model-visible text) | open (SIT-1, SIT-3, DL-3, DL-4 fixed here); see [How to change it safely](#how-to-change-it-safely) | | SIM / REAL | SIT-2 (budget weights), ST-1, ST-6, ST-9…ST-11, RA-1…RA-12 | open | | TRAIN | `rt.py` parity SIT-4…SIT-7, SIT-9, SIT-12, SIT-13; scripts ST-2…ST-5, ST-7, ST-8 | open | | CORE | `retry` still offered for non-idempotent POSTs (heal tier; `builtinApplicable` checks only `replayable && attempt < 4 && fetch`) | open (demos/NEEDS §5); SIT-11 makes it worse for 502 | @@ -461,32 +585,41 @@ tests at all. | MODEL | device-based model selection in the host card | not started | | UI | overlay ignores `Explanation.message` (`devtools/index.ts` has no `.message` use) | open | | DEMOS | rerun with the trained v2 model (Off/Observe/Guard/Heal, clean-run FIR); commit `cities.ts`; pass `untrustedEvents` for the synthetic driver (DL-11) | open | -| docs | HANDOFF default mode, CONTRACT v2 deltas and redaction rule, ARCHITECTURE budget, stale NEEDS items (SIT-14, table below) | open | +| docs | HANDOFF default mode, CONTRACT v2 deltas and redaction rule, ARCHITECTURE budget, stale NEEDS items (SIT-14), CHANGELOG alpha.1 section, INSTALL-README-SNIPPET default, a RELEASE.md part for alpha.2 (table below) | open | ### Decisions waiting on the user / repo owner 1. ~~`0.1.0-alpha.1`: publish (2FA) and from which tree.~~ Done 2026-10-08 from `mvp-v2` (806a296), dist-tag `latest`. -2. Push `mvp-v2`, merge into `runtime` and `main` (`main` is still 654d822; the old "looks merged" note no longer holds). +2. Push `mvp-v2` / `mvp-v2-merge`, merge into `runtime` and `main` (`main` is still 654d822; the old "looks merged" + note no longer holds). The default mode differs between `origin/runtime` (guard) and our line (observe): pick one + before `0.1.0` (OPEN_TASKS "Needs the user"). 3. Public demo hosting (GitHub Pages). -4. Which review fixes land before vs after the running v2 generation (SIT-2, ST-1 and DL-2 affect data being produced - now), and whether text-changing fixes justify `situation-v3`. +4. Which review fixes land before the next training round (the v2 SIM data is finished: SIT-2 and ST-1 are in it; + DL-2 shapes counterfactual costs), and whether text-changing fixes (f107013 already, SIT-8, SIT-10, SIT-11) justify + a new tag after `situation-v2.1`. +6. The next prerelease: `0.1.0-alpha.2` with the install paths now, or a beta together with the validated v2 model + (`OPEN_TASKS.md` Next 14); and whether to publish the unscoped `genclass-runtime` alias (`INSTALL-NEEDS.md`). +7. Polar Parts rollout (`MeharPro/Polar-Parts`; user OK'd once the trained model is good): observe on a branch first, + then guard. Note that `init --mode guard` currently installs observe (install finding 1). 5. Shipping models: R17 default on every device (RESULTS §2 decision for v1); R32 for WebGPU only if clearly better. ### Known risks -- **The v2 data run carries known defects.** SIM samples budget 3,200 for ~40% of trajectories (SIT-2); unlabeled rows - keep `expected` labels that S1 would flip (ST-1, fixable by a relabel pass); delivery-discard semantics under review - (DL-1, DL-2) shape the counterfactual costs. Filtering or relabelling is cheaper than regenerating; decide before - training starts. +- **The finished v2 data carries known defects.** SIM sampled budget 3,200 for ~40% of trajectories (SIT-2); + unlabeled rows keep `expected` labels that S1 would flip (ST-1, fixable by a relabel pass before teacher labelling); + delivery-discard semantics under review (DL-1, DL-2) shaped the counterfactual costs. r17-v2a and t150-v2a train on + it as is. The data also predates f107013 (redacted values) and 054da38 (observe deliveries; SIM pins heal). - **The teacher may not separate the cases.** PLAN-v1: if T150 is also near 40% argmax on clear rows, the bottleneck is the situation information, not model size. v1 → v2 separability improved but is far from solved (RESULTS §3: linear recall at 1% FIR 6% → 11% on failure, 11% → 15% on request). -- **Targets not met by any model yet:** diagnosis ≥ 95% (v1: 90.5%) and clear-case recall ≥ 80% (v1: 7.7% guard on - clear stale/duplicate). Guard FIR ≤ 0.1% and ECE ≤ 0.02 were met in v1. +- **Targets not met by any model yet:** diagnosis ≥ 95% (v1: 90.5%; r17-v2a 84.4% on `sim2e`, per `origin/runtime`) + and clear-case recall ≥ 80% (v1: 7.7% guard on clear stale/duplicate; r17-v2a heal 6.8% at the shipping gates). + Guard FIR ≤ 0.1% and ECE ≤ 0.02 were met in v1; r17-v2a guard FIR 0.00%. - **Curriculum ≠ runtime.** `rt.py` is called runtime-exact but diverges on several common cases (SIT-4…SIT-7, SIT-9, SIT-12, SIT-13). - **Never-worse evidence is narrower than claimed.** The 0/396 sweep compares final visible text and server content - only, covers 66 of 91 apps, and never compares observe against no runtime (RA-1, RA-6, RA-10). Under chaos, 3/198 + only, covers 66 of the 128 app directories now in the tree, and never compares observe against no runtime (RA-1, + RA-6, RA-10; `docs/runtime/RESULTS.md` on `origin/runtime` reports a newer interference run, 0/256, not merged). Under chaos, 3/198 runs changed from request-time holds (RESULTS §4). - **Single-thread WASM speed**: R17 ≈ 177 / 323 / 589 ms at 500 / 780 / 1,170 tokens (RESULTS §2); hold budgets cap at 800 ms, so slow devices fail open more. @@ -494,13 +627,20 @@ tests at all. re-clicks (ST-6). - **Cost and operations**: auto-shutdown disabled; label/eval scripts can mark work done after failures (ST-2, ST-4); a crashed Chromium drains a REAL worker's queue (RA-2). -- **Stale npm alpha**: users who install today get guard default, v1 situations and the NaN crash. -- **Privacy**: the F2 fact leaks redacted text (SIT-1) and the leaf redactor regressed on numbers/arrays under - secret containers (SIT-3 in the table, "low"). +- **npm alphas**: `latest` (alpha.1) is fine for observing, but still has the F2 leak and the numeric-secret + regression (fixed only here, f107013), DL-3's body wait, and no install paths. Anyone who pins `0.1.0-alpha.0` gets + the guard default, v1 situations and the NaN crash. +- **Install defects ship with the next release unless fixed first**: a silent guard→observe downgrade, stale version + pins, `remove` breaking formatted code, TypeScript `node` resolution failures (see the install table). +- **Privacy**: fixed on this branch (SIT-1, SIT-3); remaining known gaps: a container named by a secret word pair + (`cardNumber`, `apiKey`) counts as broad, so values under it are still shown, and "is back to [redacted]" compares + rendered text (STATUS "Fix after 0.1.0-alpha.1"). The script-tag build reads page config from any + `<meta name="genclass">` in the document (install finding 10). ### Review of the situation-v2 work (2026-10-08) -Five reviewers checked `git diff 654d822 b435acb` by area (delivery, situation, sim-train, realapps, project docs), +Status on `mvp-v2-merge`: SIT-1 and SIT-3 fixed in f107013, DL-3 and DL-4 fixed in 054da38, DL-10 fixed for observe +mode only; everything else below is still open. Five reviewers checked `git diff 654d822 b435acb` by area (delivery, situation, sim-train, realapps, project docs), with adversarial verification; findings marked "test" in their summaries were reproduced with temporary vitest files (deleted) or pure-Python probes. No source file was edited by the review. **52 confirmed findings; the uncertain list is empty** (one confirmed finding, DL-12, was not verified in a real browser). Area verdicts in one line each: @@ -513,7 +653,7 @@ is empty** (one confirmed finding, DL-12, was not verified in a real browser). A not affect it; labelling/eval scripts can report success after failures. - **Realapps:** virtual time, keyed draws and labels mirror the sim; headline sweep claims say more than the code measures; eval-set and manifest problems. -- **Project docs:** HANDOFF says guard is the default. +- **Project docs:** HANDOFF says guard is the default (still true). #### Delivery (runtime network-boundary path) @@ -521,14 +661,14 @@ is empty** (one confirmed finding, DL-12, was not verified in a real browser). A |---|---|---|---|---| | DL-1 | high | `packages/runtime/src/state/hub.ts` -> `StoreHub.applyFilter` | Delivery `discard` is a silent no-op on redux/zustand stores, but the `ActionRecord` claims the writes were dropped. Guard, redux `{items, loading}`: a newer op writes `items=['pushed-newer']`, the stale response dispatches `LOADED {items:['v2']}`; final state `['v2']`, record says "dropped the state changes it makes over newer data (list.items)" with `dropped: []`, and no mutation decision follows. The atom variant ends correctly with `['pushed-newer']`. | Apply the kept changes as a patched whole value through the store's `io.set` (redux `GENCLASS_REPLACE`, zustand `outer(v, true)`); else report honestly (ok:false or a reason, `op.delivery.overNewer`, leave `decided` false so the mutation trigger can decide or late-revert). Build `changed` from `mark.dropped` after the fact. Add redux and zustand variants of the discard test. | | DL-2 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter` / `RuntimeImpl.writtenOver` | A discard mark drops the fresh writes of later ops chained from the discarded op (polling chains, sagas) for 10 s. Guard: stale poll p2 is discarded, its handler schedules the next poll; p4 (cause chain p4 → timer → p2) returns fresh `v=103` and is dropped ("dropped the write of doc.v by GET /api/doc?slow=0&p=4 (#10) over newer data"); `loading`/`status` fields can stick. | Scope the mark to the discarded response's own writes: stop the cause walk at the first op with its own `delivery` record (`if (x.delivery && !x.discardMark) return null`), or compute `writtenOver` against the nearest network op. Regression test with a `setTimeout`-chained poll. Decide with Mehar whether it lands before or after the current v2 generation. | -| DL-3 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` | Observe mode (the new default) still holds deliveries: up to 100 ms waiting for the body, and XHR/WS listeners run outside the original dispatch. Measured: network answered at +500 ms, the app's fetch resolved at +600 ms, same as guard; an observe-mode XHR `readystatechange` ran with `inDispatch=false` and `load` saw `currentTarget=null`. | At the top of `runDelivery`, check whether a hold is possible (`permittedActions(this.policy, this._mode, TRIGGER_ACTIONS.delivery).length > 0 && this.expectedLatency() <= this.holdBudgetMs()`); if not, `rel()` synchronously first and do body analysis and the background trigger (F9 marks, detection) without holding. Default-mode tests for fetch and XHR with a conflicting delivery and a slow body. | -| DL-4 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` / `runDelivery` `ctl.stale` | Background (non-held) delivery decisions are always dropped as stale: delivery standing questions are never answered in observe mode, and every salient delivery's situation is built for nothing. `rt.question({ on: ["delivery"], always: true })` + one fetch: 0 answers in observe, 1 in guard; with triage `always`, observe decisions are `request`/`mutation`, never `delivery`. | Pass `stale` only for held submissions (`waits ? stale : undefined`), or skip building the situation when it will not be held and no standing question forces it. If background delivery decisions are kept, mark the writes covered when the decision lands. Correct "every trigger is decided" wording in docs/agents. | +| DL-3 | medium, **fixed in 054da38** | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` | Observe mode (the new default) still holds deliveries: up to 100 ms waiting for the body, and XHR/WS listeners run outside the original dispatch. Measured: network answered at +500 ms, the app's fetch resolved at +600 ms, same as guard; an observe-mode XHR `readystatechange` ran with `inDispatch=false` and `load` saw `currentTarget=null`. | At the top of `runDelivery`, check whether a hold is possible (`permittedActions(this.policy, this._mode, TRIGGER_ACTIONS.delivery).length > 0 && this.expectedLatency() <= this.holdBudgetMs()`); if not, `rel()` synchronously first and do body analysis and the background trigger (F9 marks, detection) without holding. Default-mode tests for fetch and XHR with a conflicting delivery and a slow body. | +| DL-4 | medium, **fixed in 054da38** | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.trigger` / `runDelivery` `ctl.stale` | Background (non-held) delivery decisions are always dropped as stale: delivery standing questions are never answered in observe mode, and every salient delivery's situation is built for nothing. `rt.question({ on: ["delivery"], always: true })` + one fetch: 0 answers in observe, 1 in guard; with triage `always`, observe decisions are `request`/`mutation`, never `delivery`. | Pass `stale` only for held submissions (`waits ? stale : undefined`), or skip building the situation when it will not be held and no standing question forces it. If background delivery decisions are kept, mark the writes covered when the decision lands. Correct "every trigger is decided" wording in docs/agents. | | DL-5 | medium | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery` `ctl.run('defer')` / `waitOps` | `defer` can hold a response, or a whole WS/SSE channel, for 20 s regardless of the hold budget (`waitOps` waits up to `LONG_RUNNING_MS` = 10 s per defer, at most 2 defers). Guard, WS `/live`, a long-poll `GET /api/feed` in flight, model answers `defer`: message delivered at +20,000 ms; every later message on the socket waits too. | Bound a delivery defer by the hold budget (`waitOps(related, Math.min(LONG_RUNNING_MS, k * this.holdBudgetMs()))`); offer defer only when related ops are expected to finish soon; for push channels do not offer it while messages are queued behind (`queuedAhead`), or cap it more tightly. | | DL-6 | medium | `packages/runtime/src/observe/messages.ts` -> `MessageGate.pump` | Held WebSocket/EventSource messages are dispatched after the app called `close()`. Guard, triage `always`: held message, app calls `ws.close()` (readyState 2), decision releases it: the listener receives `{"n":1}` with readyState 2. | Before dispatching a queued `MessageEvent`, check `readyState`: drop when a WebSocket is not OPEN (1) or an EventSource is CLOSED (2); end/emit the op as dropped; still dispatch queued close/error events. Or wrap `close()` to flush or drop the queue. | | DL-7 | medium | `packages/runtime/src/state/hub.ts` -> `StoreHub.gateAndQueue` / `StoreHub.flushQueue` | `holdWrites` (opt-in): a held write applied early by `flushQueue` flips back to state `resolved`; a late discard is then recorded as a drop while the write stays applied. Policy `{holdWrites:true, holdBudgetMs:100}`: record reads "Dropped the write to a.v from task bg (#1); a stays at version 2." with nothing reverted. | In `gateAndQueue`'s `held.then` and its `catch`, return early when `m.state === "done"`; make `proceeded` robust with `m.outcome !== undefined`. | | DL-8 | low | `packages/runtime/src/runtime.ts` -> `RuntimeImpl.dropFilter` (via `StoreHub.propose` -> `applyFilter`) | Discard marks keep dropping app writes after `rt.pause()` and `setMode("observe")`. Guard: stale response discarded, its handler applies data 500 ms later; pause (or observe) in between: the write is still dropped. | Return null from `dropFilter` when `this.paused \|\| this.destroyed \|\| this._mode === "observe"` (or call `applyFilter` only when gating); clear active `discardMark`s in `pause()`, `destroy()` and `setMode("observe")`. | | DL-9 | low | `packages/runtime/src/observe/eventsource.ts` -> `installEventSource` / `MessageGate.ensure` | EventSource `open` is not order-kept behind held messages, and the re-dispatched error clone reports a spurious channel "down". Triage `always`: open, message (held), error (queued), open: the app saw `open, open, message, error`. | Queue `open` with the orderOnly handler (like close/error); in the raw open/error/close listeners ignore the gate's own re-dispatched copies (expose `gate.isMine(e)`). | -| DL-10 | low | `packages/runtime/src/observe/xhr.ts` -> `installXHR` -> `gateCall` / `arrive` | XHR completion listeners run after the event's dispatch ended (`e.currentTarget === null`): `(e) => JSON.parse(e.currentTarget.responseText)` throws a TypeError for a held XHR (guard) or in observe mode with a conflict. | Invoke queued listeners with an event whose `currentTarget` is the xhr (Proxy, or `Object.defineProperty(ev, "currentTarget", { value: xhr, configurable: true })` plus `eventPhase` 2), or re-dispatch fresh events as `MessageGate` does. | +| DL-10 | low; **fixed for observe mode in 054da38** (released synchronously), open for held XHRs in guard/heal | `packages/runtime/src/observe/xhr.ts` -> `installXHR` -> `gateCall` / `arrive` | XHR completion listeners run after the event's dispatch ended (`e.currentTarget === null`): `(e) => JSON.parse(e.currentTarget.responseText)` throws a TypeError for a held XHR (guard) or in observe mode with a conflict. | Invoke queued listeners with an event whose `currentTarget` is the xhr (Proxy, or `Object.defineProperty(ev, "currentTarget", { value: xhr, configurable: true })` plus `eventPhase` 2), or re-dispatch fresh events as `MessageGate` does. | | DL-11 | low | `packages/runtime/src/observe/dom-user.ts` -> `installDomUser` -> `programmatic` | `untrustedEvents` defaults to false, so the demos site's in-page synthetic driver now records no user actions; decisions diverge from the Playwright driver for the same script (regresses demos/NEEDS §7). | Pass `observe: { untrustedEvents: true }` from the demos' `startGenClass` when the synthetic driver is used (or always on the demo site); update the `programmatic` comment. | | DL-12 | low | `packages/runtime/src/observe/messages.ts` -> `MessageGate.intercept` | (Not verified in a browser.) A capture-phase WS/SSE message listener (`addEventListener('message', h, { capture: true })`) sees a held message twice: at arrival and at release. | Register the interceptor with `{ capture: true }` (it still runs first), or wrap `addEventListener` for message types as `xhr.ts` does. | @@ -536,9 +676,9 @@ is empty** (one confirmed finding, DL-12, was not verified in a real browser). A | id | sev | where (file -> symbol) | finding and scenario | suggested fix | |---|---|---|---|---| -| SIT-1 | high | `packages/runtime/src/situation/content.ts` -> `contentFacts` | The F2 fact prints the raw text of redacted fields (bypass via `stringDiff`). Store `settings = {apiKey: "sk_live_AAAA…"}`, an autosave PUT in flight, the user types into the key field: every other section shows `settings.apiKey = [redacted]`, but the first fact quotes `"…AAAAAAAAAAAAAA SECRET99" → "…AAAAAAAAAAAAAA" (removes " SECRET99")`. Same with a custom redactor hiding a PII free-text field. | Use `stringDiff` only when both values pass the redactor unchanged (`Object.is(env.redact(c.path, c.current), c.current) && Object.is(env.redact(c.path, c.incoming), c.incoming)`), or route through `changeText({path, before, after}, env.redact)`. Tests with a sensitive key and a custom redactor. Changes model-visible text only for redacted fields. | +| SIT-1 | high, **fixed in f107013** (`state/fields.ts` -> `redactedStringDiff`) | `packages/runtime/src/situation/content.ts` -> `contentFacts` | The F2 fact prints the raw text of redacted fields (bypass via `stringDiff`). Store `settings = {apiKey: "sk_live_AAAA…"}`, an autosave PUT in flight, the user types into the key field: every other section shows `settings.apiKey = [redacted]`, but the first fact quotes `"…AAAAAAAAAAAAAA SECRET99" → "…AAAAAAAAAAAAAA" (removes " SECRET99")`. Same with a custom redactor hiding a PII free-text field. | Use `stringDiff` only when both values pass the redactor unchanged (`Object.is(env.redact(c.path, c.current), c.current) && Object.is(env.redact(c.path, c.incoming), c.incoming)`), or route through `changeText({path, before, after}, env.redact)`. Tests with a sensitive key and a custom redactor. Changes model-visible text only for redacted fields. | | SIT-2 | medium | `sim/src/world/scenario.ts` -> `budget` | SIM still samples the v1 3,200-char budget for 40% of trajectories while v2 data is generated on Azure (`[[3200, 40], [2000, 30], [1000, 30]]`). Measured: `toJevState(p, 3200)` 3,010 chars vs `toJevState(p, 2400)` 2,198 for identical parts; ~35% more tokens in teacher labelling and distillation, and R17/R32 train on longer sections than production shows. | Use the v2 device budgets, e.g. `[[2400, 35], [2000, 20], [1667, 5], [1333, 5], [1000, 35]]` (= `rt.py` `BUDGETS`), fix the JSDoc, tell Mehar before more v2 shards are produced; existing shards can be filtered by `meta.budget == 3200`. Optionally clamp `toJevState` to `STATE_CHAR_BUDGET × budgetScale`. | -| SIT-3 | low | `packages/runtime/src/util.ts` -> `isSensitivePath` / `defaultRedact` | The new leaf-based default redactor no longer redacts numbers or arrays under secret-named containers (regression vs 654d822): `defaultRedact("payment.cvv.value", 123)` → 123, `("login.otp.code", 123456)` → 123456, `("lock.pin.value", 1234)` → 1234; `account.password.history` arrays likewise. They then appear in state lines, deltas, timeline and facts. | Under a strong (non-broad) secret container, redact every non-boolean, non-null value (strings, numbers, bigint, arrays) before the early return that should only short-circuit the broad-container opaque test. Add the cases to `test/review-redaction.test.ts`. Model-visible. | +| SIT-3 | low, **fixed in f107013** (tests in `test/redaction-v2.test.ts`, not `review-redaction`) | `packages/runtime/src/util.ts` -> `isSensitivePath` / `defaultRedact` | The new leaf-based default redactor no longer redacts numbers or arrays under secret-named containers (regression vs 654d822): `defaultRedact("payment.cvv.value", 123)` → 123, `("login.otp.code", 123456)` → 123456, `("lock.pin.value", 1234)` → 1234; `account.password.history` arrays likewise. They then appear in state lines, deltas, timeline and facts. | Under a strong (non-broad) secret container, redact every non-boolean, non-null value (strings, numbers, bigint, arrays) before the early return that should only short-circuit the broad-container opaque test. Add the cases to `test/review-redaction.test.ts`. Model-visible. | | SIT-4 | medium | `training/curriculum/rt.py` -> `request_common` | `rt.py` adds a "Recent … outcomes" fact to every failure situation; the runtime never emits it for failures. Probe over 3,000 seeds: 479 of 479 runtime-style failure rows, e.g. "Recent GET /api/v2/listings outcomes: 500, 503, 503, 503, 503." | `elif outs and trigger == "stall":`; add a parity assertion to `test_runtime_rows_situation_v2` that failure rows have no such fact. | | SIT-5 | medium | `training/curriculum/rt.py` -> `compare_field` / `change_text` / `_json_str` | Long-text summaries skip the runtime's F2 and diff-centred paths, so autosave rows get F1 "put back" wording instead (68 of ~6,000 delivery and 25 of ~3,000 mutation rows); timeline lines show `A → B` instead of the diff preview. The model trains on the wrong wording for the main F2 case. | Let long-text scenarios carry the real strings so summaries are JSON string literals and `string_diff` runs (mirror `describe(…, 48/40)` truncation); at minimum treat summaries starting with `"` as strings in `compare_field`. | | SIT-6 | medium | `training/curriculum/rt.py` -> `event_lines` / `to_state` / `in_flight_lines` | `rt.py` keeps the last N timeline events; the runtime keeps relevant events first (and orders mutation in-flight lines by the cause). Probe: in 549 of 2,949 runtime-style rows (~19%) a relevant event (often the causing user action) was dropped while an irrelevant noise request was kept. | Return `(line, relevant)` pairs with the runtime's relevance rule (user, error, subject chain, same sig, same root, signatures that wrote the involved stores), select relevant-first with a seq re-sort, pass `spec['cause']` as the in-flight subject for mutations. | @@ -588,29 +728,58 @@ is empty** (one confirmed finding, DL-12, was not verified in a real browser). A | id | sev | where (file -> symbol) | finding and scenario | suggested fix | |---|---|---|---|---| -| PD-1 | resolved in the working tree (pending commit) | `README.md` -> Modes / "How it works" 5; `packages/runtime/README.md` -> Modes | Both READMEs still say guard is the default; a user reading the npm README after the next publish expects guard protection from `GenClass.init()` and gets observe, which takes no action. | Mark observe as the default and guard as opt-in (heal experimental) in both, change the example to `GenClass.init({ mode: "guard" })`, add a note on the change. | -| PD-2 | resolved in the working tree (pending commit) | `OPEN_TASKS.md` -> In progress / Next | The body is stale and contradicts HANDOFF: "Final data, phase A" and "Final training round 1 on phase A" read as current work (following them spends Azure compute on v1 training), batch 4 sits under Next though done, and items 3 and 4 appear twice. | Move batches 4 and 5 to Done; replace phase A / round 1 with the v2 pipeline from HANDOFF; renumber. | -| PD-3 | resolved in the working tree (pending commit): the Loading bullet now says there is no model for this runtime yet | `packages/runtime/README.md` -> Status note | Tells users to self-host with `npx genclass-runtime fetch-model`; there is no v2 model, so they get a 404, or load a v1 model into the v2 runtime and get wrong decisions. | Remove the suggestion until `@genclass/runtime-model@0.1.0` is published, or say no compatible model exists yet. | +| PD-1 | resolved in b561244 | `README.md` -> Modes / "How it works" 5; `packages/runtime/README.md` -> Modes | Both READMEs still say guard is the default; a user reading the npm README after the next publish expects guard protection from `GenClass.init()` and gets observe, which takes no action. | Mark observe as the default and guard as opt-in (heal experimental) in both, change the example to `GenClass.init({ mode: "guard" })`, add a note on the change. | +| PD-2 | resolved in b561244 | `OPEN_TASKS.md` -> In progress / Next | The body is stale and contradicts HANDOFF: "Final data, phase A" and "Final training round 1 on phase A" read as current work (following them spends Azure compute on v1 training), batch 4 sits under Next though done, and items 3 and 4 appear twice. | Move batches 4 and 5 to Done; replace phase A / round 1 with the v2 pipeline from HANDOFF; renumber. | +| PD-3 | resolved in b561244: the Loading bullet now says there is no model for this runtime yet | `packages/runtime/README.md` -> Status note | Tells users to self-host with `npx genclass-runtime fetch-model`; there is no v2 model, so they get a 404, or load a v1 model into the v2 runtime and get wrong decisions. | Remove the suggestion until `@genclass/runtime-model@0.1.0` is published, or say no compatible model exists yet. | **Uncertain findings:** none (the reviewers' uncertain list is empty). +### Install code review (2026-10-08) + +Review of Mehar's one-command install (f3a9dd1) as merged here (HEAD 10e5c3b at review time; the later fix commits do +not touch `bin/` or `src/cdn/`). Every finding was reproduced (scratch projects, `node -e` imports, tsc, esbuild, +Prettier) and verified adversarially; severities are the verifiers'. None has shipped: the published `0.1.0-alpha.1` +has no install code. All must be weighed before the next release. + +| # | sev | where (file -> symbol) | finding and scenario | suggested fix | +|---|---|---|---|---| +| 1 | high | `packages/runtime/bin/lib/plan.mjs` -> `AUTO`, `scriptTag`; `bin/lib/init.mjs` -> `USAGE`, the "Mode" row | `init` and `init --mode guard` both write `import ... from "@genclass/runtime/auto"` (and the script tag omits `data-mode` for guard), because the CLI assumed guard was the runtime default (true at eff18cb: `o.mode ?? "guard"`). After the merge `/auto` runs observe, so a user who asked for guard gets observe while the CLI prints "Mode guard"; `USAGE` says "guard (default)". Fails safe (observe changes nothing) but silently. `test/install/INSTALL-README-SNIPPET.md` repeats the guard default; `test/install/cli.test.ts` covers only `--mode observe` | `` AUTO = (mode) => mode ? `@genclass/runtime/auto/${mode}` : "@genclass/runtime/auto" ``; emit `data-mode` whenever a mode is set; usage and Mode row say observe is the default; fix the snippet; tests for `--mode guard` (`/auto/guard`, `data-mode="guard"`) and for no flag (bare `/auto`). Fix before adding the "re-run with another mode" check of finding 11 | +| 2 | medium | `packages/runtime/package.json` (`version`); `tsup.config.ts` -> `globalBuild`; `src/cdn/global.ts` -> `assetBase`; `bin/lib/init.mjs` -> `installSpec`; `bin/lib/plan.mjs` -> `scriptTag`; `packages/runtime/CHANGELOG.md` | The tree is still `0.1.0-alpha.1`, which npm already has without these files. Built or packed before a bump: the global build's `dist/cdn/worker.js` URL and the default script tag 404 on jsDelivr; `init` installs `@genclass/runtime@^0.1.0-alpha.1`, which resolves to the published alpha.1 with no `./auto` export, so the user's build fails. (The devtools would load, from the older release.) `CHANGELOG.md`'s `## 0.1.0-alpha.1` lists the install, `/auto` and the script tag. npm refuses to republish a version, so this only bites local builds, packs and tarball tests until the bump | Bump to `0.1.0-alpha.2` (or the planned beta) before any build or pack; rebuild so the baked version and SRI hashes match; move the install bullets to a new `## 0.1.0-alpha.2` section. Optionally refuse a CDN URL or install spec for a version whose registry entry lacks `dist/genclass.global.min.js` | +| 3 | medium | `packages/runtime/bin/lib/edit.mjs` -> `removeMarked`; `bin/lib/plan.mjs` -> `snippets`, `editEntry`; `bin/lib/init.mjs` -> `remove` | `init` appends a 97+ character dev-only line ending in `// genclass:init`; Prettier (format-on-save) wraps it so only the inner line carries the marker; `remove` deletes that line and leaves a dangling `if (import.meta.env.DEV)` (syntax error). Same with the Next layout's inline `<GenClassInit />{/* genclass:inline */}`: the inline regex stops matching, `remove` deletes the import and `genclass-init.tsx` but leaves `<GenClassInit />` (build error). Astro form plausible, not reproduced | Insert only short single statements or start/end marked blocks; markers that survive reflow for the JSX/Astro forms; have `remove` sanity-check its result (dangling `if`, leftover `GenClassInit` or `genclass:inline`) and refuse with a manual-edit message | +| 4 | medium | `packages/runtime/package.json` (`exports`, no `typesVersions`) | `/auto`, `/devtools` (and `/react` etc.) do not resolve under TypeScript `moduleResolution: node`: TS2307 "There are types at .../dist/auto.d.ts, but this result could not be resolved". A Create React App TypeScript project fails `npm start`/`npm run build` right after `init` (ForkTsChecker). `bundler` resolution is fine; a bare side-effect import of `/auto/<mode>` is not type-checked by TS 5.9 | Add `typesVersions` mapping `auto`, `auto/*`, `react`, `redux`, `zustand`, `devtools` to their `.d.ts` (verified with tsc under `node`: all resolve, root import unchanged); add a node10-resolution check and a CRA TS scaffold to `frameworks.mjs` | +| 5 | medium | `packages/runtime/bin/lib/detect.mjs` -> `detectProject`; `bin/lib/plan.mjs` -> `planWebpack` | Any `webpack`, `@rspack/core`, `@rsbuild/core`, `parcel`, `esbuild` or `rollup` dependency makes the project a browser app (`framework: "webpack"`). A Node CLI/server with `esbuild` as a devDependency gets `import "@genclass/runtime/auto"` after its shebang in `src/index.ts` and a runtime dependency on the package; a rollup-built library would start GenClass in every consumer's app | Require browser evidence (an HTML entry, an html plugin config, a DOM entry); refuse for `bin`/`main`/`exports` packages without HTML or entries importing `node:*`/server frameworks; otherwise fall back to the manual help | +| 6 | medium | `packages/runtime/bin/lib/plan.mjs` -> `integrityFor`, `scriptTag` | `--cdn <url>` gets an `integrity` hash of the CLI's own local `dist/genclass.global*.js` whenever the URL's filename matches, regardless of version or host: `@latest`, another version or a self-hosted copy of another build is blocked by the browser, GenClass never starts, and `@latest` breaks again on every release. `--no-sri` exists but is not in the usage text | Add SRI only for the default URL or a jsDelivr/unpkg URL pinned to exactly `@${VERSION}/`; otherwise omit it with a note (or require `--sri`); document `--no-sri` | +| 7 | low | `packages/runtime/bin/lib/edit.mjs` -> `removeMarked`; `bin/lib/init.mjs` -> `remove` | `remove` (a) deletes user code added inside a block init created (and the whole file when nothing else is left), (b) drops the rest of a file whose `// genclass:init end` line was lost, (c) drops any line that merely contains `genclass:init`. The diff is shown and confirmed unless `--yes` | Hash each created block and refuse to strip a changed one; treat a start without an end as an error; match markers only as the exact trailing comment forms | +| 8 | low | `packages/runtime/bin/lib/detect.mjs` -> `walkSources`; `bin/lib/init.mjs` -> `remove` | `remove` uninstalls the package while it is still imported from dot-directories (`.storybook/`), `tmp/`, `out/`, `build/` or beyond the 20,000-file / depth-10 scan, and also when the user installed it before `init` | Uninstall only what `init` installed (record it); scan dot-dirs except `.git` and caches | +| 9 | low | `packages/runtime/package.json` (`sideEffects`) | The published worker entry `./dist/worker.js` (the `./worker` export: top-level message loop, no exports) is not listed, so a bare `import "@genclass/runtime/worker"` bundles to nothing (esbuild warns). The default path (`new Worker(new URL("./worker.js", import.meta.url))`) is an entry and works. Alpha.1's `sideEffects: false` had the same gap. `./src/model/worker.ts` must stay: `src/cdn/worker.ts` imports it for the CDN worker build | Add `./dist/worker.js` and keep `./src/model/worker.ts` (the original suggestion to replace it would empty `dist/cdn/worker.js`); correct the `sideEffects` rows in `docs/agents/runtime/{public-api-and-lifecycle,build-test-release}.md` | +| 10 | low | `packages/runtime/src/cdn/config.ts` -> `readMetaConfig`, `fromPairs`; `src/cdn/global.ts` -> `blobModuleWorker`, `install` (its `load`); `src/cdn/ort-env.ts` -> `prepareOrt` | Page config comes from every `<meta name="genclass">` in the document (later ones win) and accepts arbitrary `ort`/`model` URLs: injected markup that lets a `<meta>` through can point the ORT wasm (and, when cross-origin isolated, its `.mjs` glue, in a page-origin Blob worker) or the model at another host, or switch the mode. SRI covers only the loader; the worker, ORT chunks and devtools load by `import()` without integrity. Needs a sanitizer that allows `<meta>`; on the CDN path a non-default loading setup | Read only `head > meta` (or the first one); do not accept remote `ort`/`model` URLs from meta (or require same-origin); document that SRI covers only the loader, or embed build-time hashes for `dist/cdn/*.js` and `devtools/index.js` | +| 11 | low | `packages/runtime/bin/lib/init.mjs` -> `init`; `src/index.ts` -> `GenClass.init` | Re-running `init --mode heal` after an observe install prints "Nothing to do" and keeps observe; a later `GenClass.init(options)` after `/auto` silently returns the first runtime (documented in the npm README) | Compare the existing marked import with the requested mode (after fixing finding 1) and offer to switch; a one-time `console.warn` when `GenClass.init` is called again with different options | + ### Doc drift: project and coordination files -| file | stale statement | reality at b435acb | +| file | stale statement | reality at f107013 | |---|---|---| -| `HANDOFF.md` ("Modes: observe → guard (default; …)") | guard is the default | `observe` (`runtime.ts`) | -| `HANDOFF.md` "Current state" | "346 tests pass"; "66 real apps"; "Push to `origin runtime` as you go" | 350 tests on `mvp-v2`; 91 apps in `realapps/` ([realapps.md](realapps.md)); our policy: ask before pushing | +| `HANDOFF.md` ("Modes: observe → guard (default; …)") | guard is the default | `observe` on our line (`runtime.ts`); `origin/runtime` still guard | +| `HANDOFF.md` "Current state" | "346 tests pass"; "66 real apps"; "Push to `origin runtime` as you go"; training "Next: 150M teacher on v2 gold" | 393 tests here; 128 app directories in `realapps/` ([realapps.md](realapps.md)); our policy: ask before pushing; r17-v2a and t150-v2a are already training | +| `packages/runtime/CHANGELOG.md` `## 0.1.0-alpha.1` | one-command install, `/auto` (`/auto/observe`, `/auto/heal`) and the script tag are in alpha.1 | the published alpha.1 (806a296) has none of them (`npm view ... exports`); they belong in the next version. The npm README already says "not in `0.1.0-alpha.1`" | +| `packages/runtime/bin/lib/init.mjs` -> `USAGE`; the "Mode" row | "guard (default)"; prints `guard` when no mode is given | the merged runtime and `/auto` default to observe (install finding 1) | +| `packages/runtime/test/install/INSTALL-README-SNIPPET.md` | "For a mode other than guard, import /auto/observe"; `data-mode` table "guard (default)" | observe is the default; guard needs `/auto/guard` or `data-mode="guard"` | +| `packages/runtime/test/install/RESULTS.md` | results for "this tree" | packed as `0.1.0-alpha.0` from Mehar's tree (guard default), before the merge | +| `packages/runtime/INSTALL-NEEDS.md` | `./src/model/worker.ts` in `sideEffects` "only for our own build" | correct, but `./dist/worker.js` is missing (install finding 9) | +| `docs/agents/runtime/public-api-and-lifecycle.md`, `docs/agents/runtime/build-test-release.md` (as committed at f107013) | `"sideEffects": false`; six tsup entries | the merged `package.json` lists side-effect files; tsup has four configs (10 ESM entries, two global builds, the CDN worker) | +| `RELEASE.md` | Part A is alpha.1 (done), Part B the model and `0.1.0` | no procedure yet for the next prerelease with the install paths (version bump, CHANGELOG, `npm pack` of the global build) | +| `packages/genclass-runtime/package.json` | version and dependency `0.1.0-alpha.1` | the alias would need the next version and is unpublished (`INSTALL-NEEDS.md` item 1) | | `docs/runtime/CONTRACT.md` | no `delivery` trigger (§6); §4 mutations "held until a decision arrives"; §6 budget "≤ 1,000 tokens"; §8 `holdBudgetMs` "default 300"; §2 redaction regex and observer list without `eventsource`/`untrustedEvents`; §13 default-mode entry: "`situation-v1` training data stays valid" | batch 4/5 deltas exist only in STATUS; no store-write holds by default; 2,400-char budget; "auto" hold budget; leaf-field redaction (SIT-14); the entry should say situation-v2 (mode does not change situation text: `src/situation/*` has no mode dependency) | | `docs/runtime/ARCHITECTURE.md` | "3,200 characters on WebGPU, 2,000 with WASM threads"; redaction regex | 2,400 on WebGPU and unknown devices, 2,000 only at 4 threads (`STATE_CHAR_BUDGET`); leaf-field rule | -| `docs/runtime/API.md` | mostly current for v2; still advises `fetch-model` without `--from`; "observe … nothing is held" | the default model 404s; observe can still wait up to 100 ms on a salient delivery (DL-3). Full API drift: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#drift-and-open-issues) | -| `packages/runtime/STATUS.md` | Open issues: "`react-dom` is not a devDependency"; "Content comparison facts … not implemented yet"; never-worse "same requests, bodies, server state and DOM"; 41 files / 346 tests | `react-dom ^19.3.0` is a devDependency; F1/F2/F3 shipped in batch 5 (`situation/content.ts`); the sweep compares less (RA-1); 42 files / 350 tests on `mvp-v2` | -| `docs/runtime/RESULTS.md` §4, §6 | "0/396" never-worse; "66 → ~96 apps" | covers 66 of 91 apps and final text/server content only (RA-1, RA-6) | +| `docs/runtime/API.md` | mostly current for v2; still advises `fetch-model` without `--from`; "observe … nothing is held"; no `/auto` or script tag | the default model 404s; "nothing is held" is now true here (054da38), not in npm alpha.1 (DL-3); the install entries are undocumented in API.md. Full API drift: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#drift-and-open-issues) | +| `packages/runtime/STATUS.md` | "Updated: … (batch 5 …)"; Open issues: "`react-dom` is not a devDependency"; never-worse "same requests, bodies, server state and DOM"; 42 files / 348 tests; nothing on 054da38 | `react-dom ^19.3.0` is a devDependency; the sweep compares less (RA-1); 46 files / 393 tests here; observe deliveries changed in 054da38 | +| `docs/runtime/RESULTS.md` §4, §6 (merged version) | "0/396" never-worse; real-browser v2 gold "~495k target, generating" (96 apps) | covers 66 apps and final text/server content only (RA-1, RA-6); the newer RESULTS on `origin/runtime` reports 616,437 REAL gold and r17-v2a | | `packages/runtime-model/MODEL_CARD.md` | "`files/r17/` here"; clear-case recall "≈ 5%" | `files/` is gitignored (only `MODEL_CARD.md` is tracked); EVAL.md gives guard 4.2% on all clear rows, 7.7% on clear stale/duplicate, heal 6.1% | | `sim/NEEDS.md` g | NaN crash OPEN | fixed in ad24804 (`util.ts` -> `describe` uses `Object.is`; `test/nan.test.ts`) | | `demos/NEEDS.md` | "Runtime: frozen batch 3"; §1 holds reorder writes, §2 hold latency, §6 EventSource not observed, §7 synthetic events recorded | batch 4: no store-write holds by default and opt-in holds never reorder; holds only when the model can answer in time, superseded decisions dropped; `observe/eventsource.ts`; synthetic events now need `untrustedEvents` (DL-11). §5 (`retry` on POST) is still open | | `packages/runtime/UI-NEEDS.md` | Open 1 (ignore the overlay), Open 2 (`react-dom`), Nice-to-have 3 (`Explanation.message`) | 1 done (`observe/dom-user.ts` -> `ignoredEvent`); 2 done (devDependency); 3 done on the CORE side, the overlay still ignores it | | `training/NEEDS.md` 10 | quota "1,024 vCPU … exactly the whole cluster" | HANDOFF / RESULTS: raised to 2,048 vCPU, c12–c23 added | -| `realapps/README.md` | 66 apps; "Run it" env-var pinning; `situation-v1` example tag | 91 apps; RA-12 | +| `realapps/README.md` | 66 apps; "Run it" env-var pinning; `situation-v1` example tag | 128 app directories with a manifest; RA-12 | ### Recorded contract deviations (STATUS "Deviations from the contract (and why)") @@ -631,7 +800,8 @@ Accepted by CORE and listed in STATUS; CONTRACT.md was not updated. ### Code TODOs None. `git grep -E "TODO|FIXME|XXX|HACK"` over `packages/runtime/src`, `sim/src`, `realapps/src`, `demos/src` and -the `training` scripts at b435acb finds nothing. Open work lives in HANDOFF, OPEN_TASKS, STATUS and the NEEDS files. +the `training` scripts at b435acb finds nothing; `packages/runtime/src` and `packages/runtime/bin` are still clean at +f107013. Open work lives in HANDOFF, OPEN_TASKS, STATUS and the NEEDS files. ### Subsystem drift tracked elsewhere @@ -665,4 +835,7 @@ Each refreshed subsystem doc has its own Drift section with more detail: [sim/SEPARABILITY.md](../../sim/SEPARABILITY.md), [demos/NEEDS.md](../../demos/NEEDS.md), [packages/runtime/UI-NEEDS.md](../../packages/runtime/UI-NEEDS.md), [realapps/README.md](../../realapps/README.md), [packages/runtime-model/MODEL_CARD.md](../../packages/runtime-model/MODEL_CARD.md), + [packages/runtime/INSTALL-NEEDS.md](../../packages/runtime/INSTALL-NEEDS.md), + [packages/runtime/CHANGELOG.md](../../packages/runtime/CHANGELOG.md), + [packages/runtime/test/install/RESULTS.md](../../packages/runtime/test/install/RESULTS.md), [.github/workflows/ci.yml](../../.github/workflows/ci.yml) diff --git a/docs/agents/training.md b/docs/agents/training.md index e89a8ddb..d5af938b 100644 --- a/docs/agents/training.md +++ b/docs/agents/training.md @@ -1,8 +1,8 @@ # training/: the GenClass runtime model (curriculum, training, export, eval) -> **Scope:** `training/` (README.md, PLAN-v1.md, LOG.md, EVAL.md, NEEDS.md, `prune_vocab.py`, `eval_runtime.py`, `eval_gain.py`, `export_runtime.py`, `report.py`, `label_teacher.py`, `t1_relabel.py`, `collect_gain.py`, every `*.sh`, `curriculum/**`, `configs/*.json`, `ortweb/**`, `tests/**`, `samples/**`), plus the parts of `jev_local/train/{train,stream,eval}.py`, `jev_local/engine/encoder/{engine,calibrate,heads,tokenize_pack}.py`, `scripts/genclass_export.py` and `scripts/launch_run.sh` that `training/` calls. -> **Read this when:** you regenerate or change the curriculum; mirror a runtime situation/question wording change into `curriculum/rt.py` (now frozen at `situation-v2`); change mixtures or launch a training round on Azure (students, the T150 teacher, distillation, DAgger); soft-label rows with a teacher; run the T1 expected-gain experiments; evaluate a checkpoint, fit calibration or read EVAL.md numbers; export a model directory (q8/fp16 ONNX, `model.json`, `meta.json`, `calibration.json`) or validate it with onnxruntime-web; change the vocabulary; pick between R17 and R32; add cluster nodes. -> **Source of truth:** the code. Verified against branch `mvp-v2` at b435acb (origin/runtime 74f17c0 = situation-v2, plus default mode observe and CI), 2026-10-08. If this doc and the code disagree, the code wins. +> **Scope:** `training/` (README.md, PLAN-v1.md, LOG.md, EVAL.md, NEEDS.md, `prune_vocab.py`, `eval_runtime.py`, `eval_gain.py`, `eval_real.py`, `export_runtime.py`, `report.py`, `label_teacher.py`, `t1_relabel.py`, `collect_gain.py`, `prep_v2.py`, every `*.sh`, `curriculum/**`, `configs/*.json`, `ortweb/**`, `tests/**`, `samples/**`), plus the parts of `jev_local/train/{train,stream,eval}.py`, `jev_local/engine/encoder/{engine,calibrate,heads,tokenize_pack}.py`, `scripts/genclass_export.py` and `scripts/launch_run.sh` that `training/` calls. +> **Read this when:** you import situation-v2 SIM/REAL data (`import_v2.sh`, `prep_v2.py`, `import_real.sh`) or check on the v2 runs `r17-v2a` / `t150-v2a`; you regenerate or change the curriculum; mirror a runtime situation/question wording change into `curriculum/rt.py` (now frozen at `situation-v2`); change mixtures or launch a training round on Azure (students, the T150 teacher, distillation, DAgger); soft-label rows with a teacher; run the T1 expected-gain experiments; evaluate a checkpoint, fit calibration or read EVAL.md numbers; export a model directory (q8/fp16 ONNX, `model.json`, `meta.json`, `calibration.json`) or validate it with onnxruntime-web; change the vocabulary; pick between R17 and R32; add cluster nodes. +> **Source of truth:** the code. Verified against branch `mvp-v2-merge` (mvp-v2 + origin/runtime eff18cb + observe/redaction fixes), 2026-10-08. If this doc and the code disagree, the code wins. Not covered: the local `origin/runtime` ref has since moved to 5bc40c9 (ca08174 realapps wave 4, 6d6eb00 REAL v2 production done, 416e374 first `r17-v2a` results, 5bc40c9 runtime batch 6 with a new tag `situation-v2.1`; they also change `training/eval_real.py`, `v2_post.sh`, NEEDS and add mixtures and `fit_gates.py`). None of that is on this branch, so the v2 status below stops at eff18cb. ## TL;DR @@ -10,13 +10,13 @@ - Two **model candidates**, both with a pruned 16,364-token vocabulary: **R17** (`jhu-clsp/ettin-encoder-17m`, d 256, 7 layers, fresh heads) and **R32** (GenClass 0.1 `jev-local-fast` = ettin-32m, d 384, 10 layers, v1 heads). Final-round-1 decision: R17 on every device (R32 matched it at 3× the latency and size; EVAL.md, RESULTS.md §2). PLAN-v1 adds R68 (student benchmark) and the never-shipped T150 teacher, same vocabulary. - Pipeline: `prune_vocab.py` (keep first 16,000 BPE merges) → **stage 1** on a synthetic curriculum (`curriculum/`, exact labels, ~55% passive-best decision rows) → **stage 2 / final round** on SIM rows from `sim/` (counterfactual-cost labels) plus curriculum replay → `eval_runtime.py` (product metrics + temperature fit) → `export_runtime.py` (fp16-free int8 **q8** ONNX for WASM, fp16 ONNX for WebGPU) → `ortweb/validate.mjs`. - `curriculum/rt.py` is a Python port of `packages/runtime/src/situation/*` (+ `state/fields.ts` `changeText`/`stringDiff`) so a share of curriculum rows are **runtime-exact** (byte-identical format to what the runtime sends). It now mirrors the frozen tag **`situation-v2`** (6e5e86e): the new `delivery` trigger (response / WebSocket message about to be delivered), conflict-driven version facts, content facts F1–F3, evidence facts F5–F7/F9, diff-centred string changes, the **2,400-char** full budget and the v2 "auto" device budgets. Any wording change in the runtime situation code must be mirrored there and needs a new freeze tag. -- **Everything trained so far is situation-v1.** All `cur*`/`rt1` sets, SIM phase A (`simA`) and every checkpoint (stage 1c, final round 1, the stopped T150 and T1 runs) predate v2. No v2 curriculum set, no imported v2 SIM/REAL data and **no v2 model exist in the repo or LOG** at this commit; v2 data is being generated on Azure by SIM/REAL (NEEDS). +- **v2 data is done and the first v2 runs are training** (LOG 04:50–05:22, NEEDS). SIM v2 gold `train:/data/sim-out/v2-gold` = **10,423,855 rows** (train 7,560,367 / dev 317,732 / test 2,545,756) and unlabeled `v2-unl` = **51,272,078 rows**. `import_v2.sh` + `prep_v2.py` turned the gold into the stream bucket `sim2` (128 train shards), the eval sets `sim2e` (held-out test sample) and `sim2f` (held-out-**feature** test rows), and the v2 curriculum replay `cur5` (300k rows, seed 15, `--p-runtime 0.8`); `v2_node_setup.sh` put the 27 GB tar on every node. Running: **`r17-v2a`** (R17 from `r17-final1`, `mix_v2a`, 8 nodes, ETA ≈ 06:20 UTC, then `v2_post.sh` evaluates on `sim2e`/`sim2f`, runs `eval_gain.py`, exports and serves the tar) and **`t150-v2a`** (teacher, `mix_t150v2`, 11 nodes, ETA ≈ 08:30 UTC). The unlabeled rows and REAL v2 (`v2c1`–`v2c4`, not landed; `import_real.sh` ready) are not imported yet. Everything finished before these runs (all `cur1`–`cur4`/`rt1` sets, `simA`, final round 1, the stopped T150/T1 runs) is situation-v1, and **no situation-v2 model has been evaluated or published yet** (`@genclass/runtime-model` is 404 on npm). - The scaled program (`training/PLAN-v1.md`): **T150 teacher** (ettin-150m) on v2 gold → `label_teacher.py` / `label_cluster.sh` soft-label a prioritised subset of the ≥ 50M unlabeled rows (PLAN P3: 5–10M rows near the gate plus a uniform sample) → distil students R17 (default) / R32 (/ R68 benchmark) with `launch_student.sh` → **DAgger** rounds on SIM `--on-policy` rows → EVAL → `@genclass/runtime-model@0.1.0`. A **T1** side track (`t1_relabel.py`, `eval_gain.py`, gain head) trains on expected-advantage targets from SIM `meta.cost_futures` (sim/SEPARABILITY.md §7). -- Training itself is `jev_local/train/train.py` in stream mode (DDP over torchrun/gloo on CPU) launched with `scripts/launch_run.sh`; all heavy work runs on Azure VMs (`c01` workbench, `c02`–`c23` F80 nodes (c12–c23 added by `cluster_expand.sh` on 2026-10-08), `train` VM, `data` VM), never on the Mac. Per the lead's portal look at 2026-10-08 04:14 UTC and training/NEEDS, SIM holds c02–c09 + c12–c23 and REAL holds c01, c10, c11 for v2 generation (NEEDS); TRAIN holds no node. +- Training itself is `jev_local/train/train.py` in stream mode (DDP over torchrun/gloo on CPU) launched with `scripts/launch_run.sh`; all heavy work runs on Azure VMs (`c01` v1 workbench, `c02`–`c23` F80 nodes (c12–c23 added by `cluster_expand.sh` on 2026-10-08), `train` VM, `data` VM), never on the Mac. Claims per training/NEEDS (05:05 UTC on): SIM finished v2 generation and deallocated its 20 nodes; TRAIN holds **c02** (v2 workbench), **c03–c09, c13** (`r17-v2a`) and **c12, c14–c23** (`t150-v2a`); REAL holds c01, c10, c11 (and `data`) for the `v2c*` batches. The jobs run unattended on the nodes; nothing on our side touches Azure. - Data mixes (`configs/mix_*.json` → `jev_local/train/stream.py` → `MixConfig`) weight **buckets** = the parent directory names of train shards found under the `--stream` roots; weights are renormalised over the buckets present, so a missing bucket is silently dropped. - The eval **gate** mirrors CONTRACT §8: candidate = argmax over permitted non-passive actions *A*; fire iff Σ_{a∈A} p(a) ≥ tier threshold (guard 0.9, heal 0.8) and top diagnosis ≠ `expected`. Headline metric: **FIR** (false-intervention rate on passive-best rows). - Trained checkpoints ship with all-1.0 temperatures; the real `calibration.json` comes from `eval_runtime.py --write-calibration` and must be passed to `export_runtime.py --calibration`. -- Status at this commit: **final round 1** (situation-v1, SIM phase A) is done and is the baseline: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE ≈ 0.01, but guard recall on clear stale/duplicate cases only 7.7% (EVAL.md); R32 is no better, so **R17 is the default on every device**. The v1 teacher `t150-g1` (stopped at step 69) and the T1 runs (`r17-t1g10`, `r17-t1g20`, `r17-t1h`, stopped at ≈ 1,000–1,350 of 2,168 steps) were halted when situation-v2 was frozen; none has results. The final1 exports exist only on the train VM / Mehar's Mac (`packages/runtime-model/files/` is gitignored); they do not match the v2 runtime. Spend to 01:56 UTC ≈ $390 (LOG). +- Status at this commit: **final round 1** (situation-v1, SIM phase A) is done and is the baseline: R17 81.9% action / 90.5% diagnosis, guard FIR 0.05%, heal FIR 0.24%, ECE ≈ 0.01, but guard recall on clear stale/duplicate cases only 7.7% (EVAL.md); R32 is no better, so **R17 is the default on every device**. The v1 teacher `t150-g1` (stopped at step 69) and the T1 runs (`r17-t1g10`, `r17-t1g20`, `r17-t1h`, stopped at ≈ 1,000–1,350 of 2,168 steps) were halted when situation-v2 was frozen; none has results. The final1 exports exist only on the train VM / Mehar's Mac (`packages/runtime-model/files/` is gitignored); they do not match the v2 runtime. The v2 runs `r17-v2a` and `t150-v2a` (above) have no results in the repo yet. Spend ≈ $440 total to 05:22 UTC, burn ≈ $110/h with 20 nodes (LOG). - Shell scripts assume a nested checkout: `JEV="$HERE/../.."` must contain `jev_local/`, `scripts/` and `pyproject.toml` (the original `/Users/meharkhanna/jev/<checkout>/training` layout). In this monorepo those live at the repo root, one level up (see Gotchas). ## Files @@ -25,9 +25,9 @@ |---|---|---| | `training/README.md` | Overview and reproduce commands (unchanged since situation-v1; partly stale, see Drift) | — | | `training/PLAN-v1.md` | The scaled program: targets, data inventory, models R17/R32/R68/T150/T400, phases P0–P5 with cost estimates, eval protocol, infra work, node claims, risks | — | -| `training/LOG.md` | Dated run log 2026-10-07/08 up to 03:35 UTC: what ran where, throughput, costs, decisions (final1, cluster expansion, T150, T1, v2 freeze) | — | +| `training/LOG.md` | Dated run log 2026-10-07/08 up to 05:22 UTC: what ran where, throughput, costs, decisions (final1, cluster expansion, T150, T1, v2 freeze, v2 import, `r17-v2a` / `t150-v2a` launch) | — | | `training/EVAL.md` | Metric definitions and results (baseline, stage 1c, sizes/latency, stage-2 pilot, **final round 1 = v1 baseline**) | — | -| `training/NEEDS.md` | Requests to SIM / CORE / MODEL / REAL (OPEN/ASK/DONE), node-claim table, SIM and REAL data locations (items 10–16) | — | +| `training/NEEDS.md` | Requests to SIM / CORE / MODEL / REAL (OPEN/ASK/DONE), node-claim table (incl. TRAIN's v2 claims c02 / c03–c09, c13 / c12, c14–c23), SIM and REAL data locations (items 10–16; v2 gold/unlabeled, REAL `v2c*` vs pre-fix `v2b*`) | — | | `training/prune_vocab.py` | First-N-merges BPE pruning of a checkpoint or HF base; inflation analysis | `prune_tokenizer_json`, `vocab_layout`, `prune_checkpoint`, `prune_hf_dir`, `slice_weights`, `remap_model_config` (+ `CONFIG_ID_KEYS`), `remap_tokenizer_config`, `iter_texts`, `analyze`, `main` (`prune` / `analyze` subcommands) | | `training/curriculum/__init__.py` | Package docstring only | — | | `training/curriculum/generate.py` | Parallel, seeded generator of CONTRACT-D jsonl (train/dev/test) + `stats.json` | `make_row`, `work`, `_validate`, `main`; `TRIGGERS`, `KINDS`, `TRAIN_DOMAINS`, `HELD_DOMAINS`, `P_RUNTIME` | @@ -50,12 +50,18 @@ | `training/label_teacher.py` | Teacher soft-labelling of CONTRACT-D rows (calibrated probabilities as `dist` labels, `meta.teacher`), resumable | `main` (`--ckpt`, `--in`, `--out`, `--calibration`, `--qids`, `--batch 32`, `--threads 16`, `--max-len 2048`, `--overwrite`, `--limit`); `PASSIVE` | | `training/export_runtime.py` | ONNX export, q8/fp16 graph surgery, parity, model directory | `main`, `make_q8`, `make_fp16`, `quantize_embedding`, `gemm_to_matmul`, `requests_from_rows`; `CARD_FORMAT`, `OUTPUTS` | | `training/ortweb/validate.mjs`, `package.json` | onnxruntime-node + onnxruntime-web 1.30.0 (WASM in Node) parity and latency check | CLI `node validate.mjs <dir> [variant=q8] [maxRequests=60]` | -| `training/configs/mix_*.json` | Mixture configs (`jev_local/train/stream.py` → `MixConfig`) | `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1`, `mix_t150` (teacher), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs) | +| `training/configs/mix_*.json` | Mixture configs (`jev_local/train/stream.py` → `MixConfig`) | `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_final1`, `mix_t150` (v1 teacher), `mix_r68` (R68 benchmark), `mix_t1a` / `mix_t1b` / `mix_t1h` (T1 runs); situation-v2: `mix_v2a` (`r17-v2a`), `mix_t150v2` (`t150-v2a`) | | `training/node.sh` | ssh/rsync wrapper for Azure hosts | `node.sh HOST sync\|'cmd'\|get R L\|put L R` | | `training/cluster_expand.sh` | Create extra F80 nodes in `rg-jev-train` (same VNet/subnet/NSG/PPG/image/key; retries without PPG), append to `~/.jev-local/azure_hosts`, add a **Disabled** DevTestLab 03:00 shutdown schedule | `cluster_expand.sh NAME:SIZE ...` (e.g. `c12:Standard_F80ads_v7`) | | `training/node_init.sh` | Run on a fresh node: pull the node kit tar (cloned venv, ettin bases, pruned bases, TRAIN data), install ONNX tooling, check torch, touch `~/.node_init_ok` | `bash node_init.sh http://<ip>:8801/kit.tar` | | `training/import_sim.sh` | Pull a SIM run to c01, shard train (stage 2) | `import_sim.sh SIM_OUT_DIR NAME` | | `training/import_final.sh` | Pull a frozen SIM run, shard, build eval subsets, bundle for nodes; env `WB` (workbench, default c01), `FILES` (default `train dev test`), `PORT` (train-VM port, default 8802) | `[WB=.. FILES=.. PORT=..] import_final.sh SIM_OUT_DIR NAME` | +| `training/import_v2.sh` | situation-v2 SIM import (from the Mac): serve a collected SIM batch from the train VM on `10.0.0.4:$PORT`, then a detached job on the workbench downloads the gz shards (12 parallel `curl`), runs `prep_v2.py`, generates `cur5` if `data/s3/cur5` is missing, tars everything for the nodes and serves `~/xfer` on `<WB IP>:8799`; env `WB` (default **c02**), `PORT` (default 8803) | `import_v2.sh SRC_DIR NAME` (e.g. `/data/sim-out/v2-gold sim2`) → `~/xfer/v2_<NAME>.tar`, log `logs/import-<NAME>.log`, done flag `~/xfer/.done-<NAME>` | +| `training/prep_v2.py` | Collected SIM batch (gz shards + `manifest.json`) → train shards (heavy meta dropped) + `crc32(id)`-sampled eval sets incl. held-out features | `main` (`--src`, `--name`, `--root data`, `--shards-per-file 8`, `--workers 32`, `--test-rows 20000`, `--dev-rows 8000`), `do_train`, `do_eval`, `write_set`, `h`; `DROP_TRAIN`, `TEST_FEATURES` | +| `training/v2_node_setup.sh` | Prepare one node for v2 training: wait for ssh (30 × 10 s), `node.sh N sync`, `azvm.sh N --sync` (jev code), pull the v2 tar from `<WB IP>:8799` unless `data/.have-<TAR>` exists | `v2_node_setup.sh NODE`; env `TAR` (default `v2_sim2.tar`), `WB` (c02) | +| `training/v2_post.sh` | On a v2 model's rank-0 node, detached: wait for `final`, `eval_sim.sh sim2e` and `sim2f`, `eval_gain.py` on `sim2e`, export with the `sim2e` calibration, serve the tar on :8801 | `bash training/v2_post.sh RUN NAME VERSION` (e.g. `r17-v2a genclass-runtime-r17 2.0.0-rc1`) → markers `out/.eval-done-RUN`, `out/.post-done-RUN` | +| `training/import_real.sh` | REAL v2 batches → bucket `real2` (32 shards), eval sets `real2e` (8k dev / 20k test) and `realev` (REAL's `real_eval.jsonl`), unlabeled bucket `realunl`, tar `~/xfer/v2_real2.tar`; train VM serves `/data/real-out` on :8804; not run yet (`v2c*` not landed) | `import_real.sh "v2c1 v2c2 v2c3 v2c4" [EVALDIR]` (positional, default `v2-eval`); env `WB` (c02); done flag `~/xfer/.done-real2` | +| `training/eval_real.py` | REAL eval set (`meta.eval_case` / `meta.eval_expect`) under the §8 gate from cached records: per case and mode, argmax accuracy, fired share (FIR on passive cases) and recall at 0.9/0.7/0.5 (guard) or 0.8/0.7/0.5 (heal) | `main` (`--rows`, repeatable `--model name=records.jsonl:cal.json`, `--out`), `evaluate`, `softmax`; `PERMIT`, `TH` | | `training/launch_student.sh` | Generic DDP launcher for r17 / r32 / r68 / t150 (per-arch base, lr, grad-accum defaults) over `data/s3 data/s1` | `launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra trainer args]`; env `RANKS`, `THREADS`, `GA_OVERRIDE`, `LR_OVERRIDE`, `HLR_OVERRIDE` | | `training/launch_t150.sh` | Teacher T150 launcher (`mix_t150.json`, stream `data/s3` only) | `launch_t150.sh RUN PASSES "nodes" MASTER_IP [extra args]`; env `RANKS` (8), `THREADS` (10) | | `training/launch_r68.sh` | R68 student benchmark launcher (`mix_r68.json`) | `launch_r68.sh RUN PASSES "nodes" MASTER_IP [extra args]` | @@ -96,7 +102,7 @@ Terms beyond the shared [glossary](glossary.md) (op, situation, questions, diagn | Stage 1 / 1c / 2 / final round | s1: curriculum `cur1` + v1 `gen`/`cu` replay (`mix_s1`); s1c: continuation with runtime-exact `cur2` (`mix_s1c`); s2: pilot on pre-freeze SIM `r300k` (`mix_s2`); final1: frozen situation-v1 SIM phase A + replay (`mix_final1`), done, the v1 baseline. PLAN-v1 phases P0 (final1) … P5 (DAgger) replace "round 2". | | FIR | False-intervention rate = gate fires on passive-best rows ÷ passive-best rows (per mode). | | Replay | Curriculum/v1 buckets mixed into SIM training (`cur*`, `gen`, `cu`). | -| Hosts | `train` VM (10.0.0.4; SIM runs, delivery, MODEL's node_modules; SIM outputs on its 1 TB `/data` disk since 02:01 UTC), `data` VM (SIM generation; deallocated per the lead's portal look at 2026-10-08 04:14 UTC and training/NEEDS), `c01` (10.0.0.6; TRAIN workbench: prune, generate, eval, export, data hub), `c02`–`c11` (F80 nodes; c02 = 10.0.0.7 was R32 rank 0, c09 = 10.0.0.14 R17 rank 0), `c12`–`c23` (added 00:40–01:13 UTC 2026-10-08: c12–c15 F80ams_v7 with 629 GB RAM, c16–c19 F80amds_v7, c20–c23 F80ads_v7; shutdown schedule Disabled). Quota 2,048 vCPU (raised from 1,024). F80 ≈ $5.46/h (LOG). Claims live in NEEDS.md. | +| Hosts | `train` VM (10.0.0.4; SIM runs, delivery, MODEL's node_modules; SIM outputs on its 1 TB `/data` disk since 02:01 UTC), `data` VM (SIM v1 generation; per NEEDS 16 it runs one of REAL's four `v2c*` batches (by the listed order `v2c4`; unverified), and its pulling job deallocates it after a verified copy), `c01` (10.0.0.6; TRAIN workbench for v1: prune, generate, eval, export, data hub; REAL since 03:35), `c02`–`c11` (F80 nodes; c02 = 10.0.0.7 was R32 rank 0 and is the **v2 workbench** from 05:05 UTC (`import_v2.sh`/`import_real.sh`/`v2_node_setup.sh` default `WB=c02`), c09 = 10.0.0.14 R17 rank 0 for final1 and `r17-v2a`), `c12`–`c23` (added 00:40–01:13 UTC 2026-10-08: c12–c15 F80ams_v7 with 629 GB RAM, c16–c19 F80amds_v7, c20–c23 F80ads_v7; shutdown schedule Disabled). Quota 2,048 vCPU (raised from 1,024). F80 ≈ $5.46/h (LOG). Claims live in NEEDS.md. | | situation-v2 | The frozen runtime format (tag `situation-v2` = 6e5e86e). Decisions happen at the network boundary: a new `delivery` trigger (a fetch response or WebSocket message about to reach the app; actions deliver / discard / defer), store writes are not held by default. Facts added: newer-data / pending-local-change conflicts (only these make a version fact non-neutral), F1–F3 content (put-back of a replaced value, overwriting user typing, "changes nothing"), F5 failure scope / commit ambiguity, F6 cadence, F7 repeat-action evidence, F9 stale marks. Full budget 2,400 chars. | | Delivery row (curriculum) | A mutation scenario whose cause is a completed OK fetch or a WS op, rendered as `delivery` with probability `P_DELIVERY` = 0.5 (`rt.render`). Actions map `apply → deliver`, `discard → discard`, `defer → defer`; `defer` is dropped when no related op is in flight or `defers ≥ 2`; if the gold action is no longer offered the row stays a mutation. `meta.trigger = "delivery"`, family `cur/delivery/<case>`, `meta.action_names` = that map, `meta.action_canonical` keeps the scenario name. | | Clear case | A decision row whose gold puts ≥ 0.9 on one permitted non-passive action (`eval_runtime.py` → `decision_metrics`: `recall_clear`, and `recall_clear_stale_dup` when the gold diagnosis is `stale` or `duplicate`). `eval_gain.py` uses SIM's different definition (`classify`: mean gain over futures ≥ 2, every future's gap > 0, same best action in every future); `benign` = no future gains, `mild` = the rest. | @@ -168,9 +174,11 @@ Remote layout (scripts and LOG; `G=/home/azureuser/gcl-train`): | every node | `$G/cache/<round>/` | stream index cache (`--stream-cache`) | | c01 / rank-0 nodes | `$G/out/{eval,cal,records,export-<M>}/`, `$G/logs/` | eval reports, calibration files, cached logits, exports, job logs | | c01 / nodes | `~/xfer/` | tars served by `python3 -m http.server` (ports below) | -| train VM | `/data/sim-out/<run>/` (old path `~/gcl/sim/sim/out` is now a symlink to it) | SIM outputs: `final-a` (v1 phase A), `final-b/parts/` (v1 phase B, 1,415,344 rows), `sep/`, `probe-150k/` (analysis only), `v2chk-{gold,unl}` (v2 pipeline check), `v2b5-100k` (first v2 + batch-5 + S1/S2 check, 64,754 decision rows; sim/SEPARABILITY.md §8), `v2-*` (v2 production, in progress) | -| train VM | `/data/real-out/<batch>/` | REAL (realapps) batches: `pilot4`, `pilot-all` (v1 audit), `v2-pilot`; v2 production `v2b1`–`v2b3` is still on c01/c10/c11 `~/gcl/real-out/` until copied (NEEDS 14–16; see [realapps.md](realapps.md)) | +| train VM | `/data/sim-out/<run>/` (old path `~/gcl/sim/sim/out` is now a symlink to it) | SIM outputs: `final-a` (v1 phase A), `final-b/parts/` (v1 phase B, 1,415,344 rows), `sep/`, `probe-150k/` (analysis only), `v2chk-{gold,unl}` (v2 pipeline check), `v2b5-100k` (first v2 + batch-5 + S1/S2 check, 64,754 decision rows; sim/SEPARABILITY.md §8), **`v2-gold/`** (10,423,855 rows, 23 gz shards + `manifest.json`, 44 GB; `meta.cost_futures`, `meta.diagnosis_s1`) and **`v2-unl/`** (51,272,078 rows: train 37,243,384 / dev 1,533,254 / test 12,495,440; 104 gz shards + `manifest.json`) (NEEDS) | +| train VM | `/data/real-out/<batch>/` | REAL (realapps) batches: `pilot4`, `pilot-all` (v1 audit), `v2-pilot`, `v2-pilot4` (v2 audit, 2,631 gold); v2 production: **`v2c1`–`v2c4`** (fixed labels, 96 apps, ≈ 530k gold + ≈ 500k unlabeled expected; not landed at 05:22 UTC) and the stopped `v2b1`–`v2b3` (≈ 380k gold, **pre-fix diagnosis labels**: use their action labels only; NEEDS 16); eval set `v2-eval/real_eval.jsonl` built from `v2c*` when they land (see [realapps.md](realapps.md)) | | data VM | `~/simdata/<run>/` | SIM distributed batches (gz shards + `manifest.json`), e.g. `gold-r1x` (v1, 832,279 rows) | +| v2 workbench (c02) | `$G/data/<NAME>raw/`, `~/xfer/v2_<NAME>.tar`, `~/xfer/.done-<NAME>`, `logs/import-<NAME>.log`, `/tmp/import-<NAME>.sh` | `import_v2.sh`: downloaded SIM gz shards + manifest (kept after prep), the node tar (`v2_sim2.tar` ≈ 27 GB, served on `<WB IP>:8799`), done flag, log, the detached job script (REAL: `data/realraw/`, `~/xfer/v2_real2.tar`, `.done-real2`, `logs/import-real.log`) | +| v2 nodes | `$G/data/.have-<TAR>` | `v2_node_setup.sh` marker: the tar was pulled and unpacked | | workbench (`WB`) | `~/xfer/label/` | `label_cluster.sh` teacher tar (`teacher-<TEACHER>.tar`) and the `src-<OUT_BUCKET>` symlink to `SRC_DIR`, served on `<WB private IP>:8805` | | labelling nodes | `$G/data/label-src-<OUT_BUCKET>/`, `$G/data/s3/<OUT_BUCKET>/`, `/tmp/label-<OUT_BUCKET>.sh`, `$G/.label-<OUT_BUCKET>-done` | downloaded source shards, labelled output shards, the detached job script, the completion marker | | train VM | `~/gcl/train-out/<round>/<sub>/`, `~/gcl/train-out/ortweb/` | delivered exports; validation dir (`node_modules` → `~/gcl/model/node_modules`, Node at `$HOME/node/bin`) | @@ -182,7 +190,7 @@ Stream-root contents (which bucket lives under which root). Only `data/s2/<NAME> | `data/s1` | `cur1`, `gen`, `cu` (stage 1); also streamed in s2 and final1 | | `data/s1b` | `cur2` (streamed from s1c on) | | `data/s2` | `sim1` (`import_sim.sh`), `cur3` (README) | -| `data/s3` | `simA` (`import_final.sh`); `cur4` must also sit under `data/s3` or `data/s1` for `mix_final1.json` to find it (no script puts it there; see Gotchas); `simAg10` / `simAg20` / `simAh` (`t1_relabel.py --out data/s3/<bucket>`); teacher-labelled buckets from `label_cluster.sh` (`data/s3/<OUT_BUCKET>`) | +| `data/s3` | v2: `sim2` (`prep_v2.py`, 128 shards), `cur5` (`import_v2.sh`, 32 shards), `real2` / `realunl` (`import_real.sh`, not run yet); v1: `simA` (`import_final.sh`); `cur4` must also sit under `data/s3` or `data/s1` for `mix_final1.json` to find it (no script puts it there; see Gotchas); `simAg10` / `simAg20` / `simAh` (`t1_relabel.py --out data/s3/<bucket>`); teacher-labelled buckets from `label_cluster.sh` (`data/s3/<OUT_BUCKET>`) | Datasets referenced by configs and scripts (sizes from LOG/EVAL; generator flags marked unverified where not in a script): @@ -199,7 +207,12 @@ Datasets referenced by configs and scripts (sizes from LOG/EVAL; generator flags | `simsample` | 200 (123 decision rows) | `sim/samples/sample.jsonl` | zero-shot check in `run_evals.sh` | | `simAg10`, `simAg20` | phase-A train shards, 291k of 448k rows relabelled | `t1_relabel.py --in data/s3/simA --tau 1.0 / 2.0` | T1 softmax(gain/τ) action labels + `meta.egain` (`mix_t1a`, `mix_t1b`) | | `simAh` | same rows | `t1_relabel.py --keep-dist` (τ required but unused) | SIM labels kept, `labels.action.gain` + `meta.egain` added (`mix_t1h`) | -| v2 SIM / REAL | target ≥ 10M gold + ≥ 50M unlabeled (SIM), ≥ 500k gold (REAL) | `train:/data/sim-out/v2-*`, REAL `v2b1`–`v2b3` | **not imported yet**; no v2 bucket, mixture or curriculum set exists in `training/` | +| `sim2` | 7,560,367 train rows in 128 shards (`data/s3/sim2`; LOG gives 128; at the default `--shards-per-file` 8 that implies 16 train gz) | SIM `v2-gold` via `import_v2.sh` + `prep_v2.py` (≈ 1 min on c02) | situation-v2 gold; `prep_v2.DROP_TRAIN` meta keys (`cost_parts`, `patterns`, `adjusted`, `se`, `program_family`) removed from train rows; `cost_futures` kept | +| `sim2e` | ≈ 8k dev / ≈ 20k test (+ `sim2e_t0..3`, `sim2e_d0,1`) | `prep_v2.py`, `crc32(id) % 100000` below a rate from `manifest.json` row counts | SIM's held-out test split (test domains/features/patterns); dev is used for temperature fitting | +| `sim2f` | 18,690 test rows (LOG), same dev rows as `sim2e` | `prep_v2.py` | test rows whose family names a `TEST_FEATURES` feature (swcache, presence, cascade, saga, prefetch, permissions), sampled at 6× the `sim2e` rate, shuffled (seed 7) and cut to `--test-rows`; rows can also be in `sim2e` | +| `cur5`, `cur5e` | 300k train (32 shards in `data/s3/cur5`) / dev + test in `data/cur5e` | `python -m curriculum.generate --n 300000 --seed 15 --p-runtime 0.8 --workers 64` (inside `import_v2.sh`) | v2 curriculum replay (`rt.py` at `situation-v2`, `delivery` rows); dev/test = generator defaults (6,000 / 12,000) | +| v2 unlabeled | 51,272,078 rows | `train:/data/sim-out/v2-unl` | **not imported**; for teacher labelling (PLAN P3) | +| `real2`, `real2e`, `realev`, `realunl` | — | REAL `v2c1`–`v2c4` via `import_real.sh` | **not built yet** (batches not landed); `realev` = REAL's unambiguous-case eval set for `eval_real.py`, test-only | Row `meta` written by the curriculum (`rows.py` → `decision_row`): `kind="decision"`, `trigger`, `case`, `domain`, `passive_best`, `action_gold` (shown name), `action_canonical`, `passive` (shown passive name), `diag_gold`, `action_names` (canonical → shown), `prims`, `heldout_templates_possible`, `soft_action`, `style`. Ask rows (`ask_row`): `kind="ask"`, `trigger="ask"`, `source_trigger`, `case`, `domain`, `prims`. Standalone: `kind="prim"`, `family`, `domain` (+ `code`, `err` for HTTP). Families: `cur/<trigger>/<case suffix>` (builder name dropped, see below; `<trigger>` is the rendered one, so `delivery` for mutation scenarios rendered as deliveries), `cur/ask/<trigger>`, `cur/prim/{json_invariants,http,js_errors,decide}`. Curriculum rows carry **no `meta.budget`**. @@ -291,6 +304,8 @@ Runs as executed (LOG; `G=/home/azureuser/gcl-train`). The s1c, s2 and final1 co | `t150-g1` (teacher, `launch_t150.sh` presumably; exact command unrecorded) | c12–c23 (12 × 8 ranks × 10 threads) | `mix_t150` (simA .9, cur4 .1); `data/s3` | ettin-150m pruned, fresh heads | 2e-4 / 1e-3 | 2 | 2048 | 2 passes (≈ 940M tokens) at ≈ 106k tok/s; **stopped at step 69** (after the lead's 01:30 situation-v2 note; c10–c23 deallocated 01:35); checkpoint kept on c12's disk | | `r17-t1g10` / `r17-t1g20` (T1, command unrecorded) | c09 c10 c11 c08 / c02–c05 | `mix_t1a` / `mix_t1b` | `r17-s1c` | as r17-final1 (LOG) | | | 3 passes planned; **stopped** at ≈ step 1,350 / 2,168 (03:32), resumable, no result | | `r17-t1h` (gain head, `--gain-loss 1.0`) | c01 c06 c07 c12 | `mix_t1h` | `r17-s1c` | as r17-final1 | | | 3 passes planned; **stopped** at ≈ 1,000; gain loss 0.98 → 0.85 vs trivial predictors 0.97–1.01 | +| **`r17-v2a`** (situation-v2; launched 05:14 UTC, exact command unrecorded, `launch_student.sh` presumably) | c09 c03–c08 c13 (64 ranks) | `mix_v2a` (sim2 .86, cur5 .11, cur1 .02, gen .01) | `r17-final1` | (`launch_student.sh` r17 defaults 2e-4 / 1e-3, unverified) | 2 (unverified) | 2048 | 4 × 500M tokens at ≈ 577k tok/s, **ETA ≈ 06:20 UTC**; `v2_post.sh r17-v2a …` detached on c09 | +| **`t150-v2a`** (teacher; launched 05:20 UTC, exact command unrecorded) | c12 c14–c23 (88 ranks) | `mix_t150v2` (sim2 .9, cur5 .1) | ettin-150m MIT base, pruned, fresh heads | (2e-4 / 1e-3 in both launchers, unverified) | 2 (unverified) | 2048 | 2 × 500M tokens, **ETA ≈ 08:30 UTC**; no post script recorded. A continuation run is to add REAL `v2c*` once landed (LOG) | Measured throughput (LOG): `r32-s1` ≈ 215k tok/s (5 s/step), falling to 134k with the 4 × 20 layout; `r17-s1` 165–210k; 1-node R17 pilot 68–70k (4 × 20) vs 93–95k (8 × 10); `r32-s2` ≈ 168k, `r17-s2` ≈ 449k; `r32-final1` ≈ 253k, `r17-final1` ≈ 322–333k tok/s; per-node probes R68 ≈ 19k, T150 ≈ 9.4k tok/s. Stage-1 loss 0.28 / 0.27 at steps 60 / 140; first stage-2 step 0.76 (R32) / 0.80 (R17). Stage 1c logged no dropped questions and no bad labels. @@ -336,9 +351,9 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th 3. Per backend: `missing_inputs` (`meta.json` `inputs` absent from the session), `max_abs_logit`, `argmax_agree/argmax_total` (questions with > 1 logit), `ms_p50/p90`, `tokens_p50`, `runtime_sized` (requests ≥ 400 tokens), and `est_ms_at_seq_tokens` at 500 / 780 / 1170 tokens (≈ 330 / 600 / 1,000-token states plus the standing questions) from a least-squares fit `ms ≈ a + bL + cL²`. Writes `<dir>/ortweb_report_<variant>.json` (`{dir, variant, file, bytes, results[]}`). 4. It has no pass/fail: a backend error is caught and recorded as `{backend, error}` (the process still exits 0; only unreadable `model.json`/fixtures crash it). There are no thresholds; read `max_abs_logit`, `argmax_agree` and `error` yourself (the delivery scripts print them). -### 9. Teacher, soft-labelling and distillation (PLAN-v1 P1–P4; prepared, not yet run on v2) +### 9. Teacher, soft-labelling and distillation (PLAN-v1 P1–P4; v2 teacher `t150-v2a` training, labelling and distillation not run yet) -1. **Teacher training:** `training/launch_t150.sh RUN PASSES "nodes" MASTER_IP` (or `launch_student.sh RUN t150 ...`). Every listed node first prunes `ettin-encoder-150m` to `models/base/ettin-150m-v16k` if missing; then `scripts/launch_run.sh` with `--stream $G/data/s3` only, `mix_t150.json`, `--max-len 2048 --batch-tokens 8192 --grad-accum 2 --ckpt-every 25 --seed 4 --lr 2e-4 --head-lr 1e-3 --resume`. `mix_t150.json` names v1 buckets (`simA`, `cur4`); a v2 teacher needs a new mixture over the imported v2 gold buckets. +1. **Teacher training:** `training/launch_t150.sh RUN PASSES "nodes" MASTER_IP` (or `launch_student.sh RUN t150 ...`). Every listed node first prunes `ettin-encoder-150m` to `models/base/ettin-150m-v16k` if missing; then `scripts/launch_run.sh` with `--stream $G/data/s3` only, `mix_t150.json`, `--max-len 2048 --batch-tokens 8192 --grad-accum 2 --ckpt-every 25 --seed 4 --lr 2e-4 --head-lr 1e-3 --resume`. `launch_t150.sh` hardcodes `mix_t150.json` (v1 buckets `simA`, `cur4`); the v2 teacher `t150-v2a` uses `mix_t150v2.json` (sim2 .9, cur5 .1), so it was launched either with `launch_student.sh t150-v2a t150 2 mix_t150v2.json …` (which also streams `data/s1`, harmless because the mixture lists `buckets`) or with an extra `--mixture` argument to `launch_t150.sh` (the trainer's argparse takes the last value); the LOG does not record which. 2. **Generic launcher:** `training/launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT] [-- extra]`. `ARCH` picks base / lr / head-lr / grad-accum (table in Concepts; all 8 ranks × 10 threads); rank 0 and master = the first node (private IP from `azure_hosts`); before launching it makes sure every node has the pruned 68m and 150m bases (for every arch); fixed flags `--stream $G/data/s3 $G/data/s1 --stream-cache $G/cache/$RUN --max-len 2048 --batch-tokens 8192 --balance --amp --no-grad-ckpt --device cpu --log-every 10 --ckpt-every 25 --seed 7 --resume`, plus `--init-from INIT` when given (must exist on the first node). `MIX` is a file name under `training/configs/` (the header's example `mix_v2_distill.json` does not exist yet). 3. **Soft-labelling one shard:** `$PY training/label_teacher.py --ckpt models/T --in shard.jsonl --out labelled.jsonl [--calibration cal.json] [--qids action,diagnosis]`. `load_checkpoint(..., encoder="banded")`, packs with `Packer(tok, max_len, buckets=train_buckets(max_len))` and `encode_example` (same packing as training), runs the heads, applies `calibrate_logits(kind, header_key(header), z, calib)` (the checkpoint's `calibration.json` unless `--calibration`), and writes per question: choice → `{"type":"choice","dist":{label:p}}`, score → `{"type":"score","dist":[...]}`, noul → `{"type":"noul","p":p}`. Existing (gold) labels are kept unless `--overwrite`; SIM/REAL unlabeled rows carry a gold `labels.diagnosis` (NEEDS), so with the default `QIDS=action,diagnosis` only `action` gets a teacher label there (the teacher's diagnosis probabilities still go into `meta.teacher`). `meta.teacher` = `{ckpt, <qid>: {top, margin[, non_passive_mass]} | {p}}` (`non_passive_mass` for `action`, over labels not in `PASSIVE` = apply/send/deliver/wait/ignore). Resumable: an existing `--out` is continued after its last complete line (a torn last line is dropped). Prints `{rows, resumed_after, seconds, tokens_per_s}`. Tested by LOG: R17 labelled 64 SIM rows at 11.5k tok/s on 16 threads. 4. **Across nodes:** `training/label_cluster.sh WB TEACHER CAL SRC_DIR OUT_BUCKET "nodes" [PROCS=8] [QIDS]` tars `models/TEACHER` + `CAL` on the workbench, symlinks `SRC_DIR` into `~/xfer/label/src-OUT_BUCKET`, serves `~/xfer/label` on `<WB IP>:8805`, assigns shards round-robin (`NR % nodes`), and on each node writes and detaches `/tmp/label-OUT.sh`: download the teacher and its shards, `xargs -P PROCS` one `label_teacher.py --batch 32 --threads 80/PROCS` per shard into `data/s3/OUT_BUCKET/`, then touch `~/gcl-train/.label-OUT_BUCKET-done`. Logs `logs/label-OUT-<shard>.log`. Re-running skips downloaded shards and resumes each output. Untested (LOG); it does **not** gather the outputs back to the workbench (the header says "then are gathered on WB"): copy them yourself. @@ -359,6 +374,17 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th 2. Serve a node kit tar from an existing node (how it is built is not scripted; LOG: served by c10; the port 8801 comes from the script's example URL `http://10.0.0.15:8801/kit.tar`) and run `bash node_init.sh http://<ip>:8801/kit.tar` on the new node: apt `rsync zstd pigz`, untar into `~`, create `~/gcl-train/{logs,out,runs}` and `~/jev/runs`, pip-install `onnx==1.23.1 onnxruntime==1.30.0 onnxscript==0.7.2 onnxconverter_common==1.16.0`, print torch/transformers versions, touch `~/.node_init_ok`. Then `node.sh NAME sync`. 3. Policy (HANDOFF): never delete VMs; deallocate idle nodes; claim nodes in NEEDS.md; run `az` calls one at a time, each in `timeout`; the nightly DevTestLab shutdown schedules are Disabled for the training push and must be re-enabled when it ends (`az resource update ... --set properties.status=Enabled`, command in HANDOFF). Our side does not touch Azure at all without the user's go-ahead. +### 12. situation-v2 import and first round (`import_v2.sh`, `prep_v2.py`, `v2_node_setup.sh`, `v2_post.sh`) + +What ran 04:50–05:22 UTC (LOG, NEEDS); all of it runs on Azure, driven from Mehar's Mac. + +1. **Import** (from the Mac): `training/import_v2.sh /data/sim-out/v2-gold sim2` (`WB=c02`, `PORT=8803`). The train VM serves the SIM dir on `10.0.0.4:8803` (started only if the port is not already listening); the file list is `*.jsonl.gz manifest.json` there. On the workbench a detached `/tmp/import-sim2.sh` (`set -eu`) downloads into `data/sim2raw/`, deletes any previous `data/s3/sim2`, `data/sim2e*`, `data/sim2f*`, runs `prep_v2.py --src data/sim2raw --name sim2 --workers 40`, generates `cur5` only if `data/s3/cur5` does not exist (in `/tmp/cur5`, then `split -n l/32` into `data/s3/cur5/` and dev/test into `data/cur5e/`), tars `data/s3/sim2 data/s3/cur5 data/sim2e* data/sim2f* data/cur5e` into `~/xfer/v2_sim2.tar` and serves `~/xfer` on `<c02 IP>:8799`. LOG: ≈ 1 min for prep on c02, 27 GB tar. +2. **`prep_v2.py`** → `main`: reads `manifest.json` `rows`; one pool job per `train-*.jsonl.gz` (`do_train`: drop `DROP_TRAIN` meta keys, round-robin over `--shards-per-file` output shards `shardNNN.jsonl`) and per `test-*`/`dev-*` gz (`do_eval`). Sampling is `h(id) = crc32(id) % 100000` against rates `round(100000 · test_rows / rows.test)` and `round(100000 · dev_rows / rows.dev)`, so it is deterministic and independent of shard order; the held-out-feature rate is 6× the test rate (capped at 100,000) and keeps test rows whose `family` (or `meta.family`), split on `+`, contains a `TEST_FEATURES` entry, then shuffles (`Random(7)`) and cuts to `--test-rows`. `write_set` writes `data/<name>{e,f}/{dev,test}.jsonl` plus `_t0..3` (test, every 4th row) and `_d0,1` (dev, every 2nd) for `eval_sim.sh`; `sim2f` reuses the `sim2e` dev rows. Prints `{train_rows, train_shards, eval_test, eval_dev, heldout_feature_test}`. +3. **Nodes** (from the Mac, per node): `training/v2_node_setup.sh cNN` (SIM had deallocated the nodes; TRAIN restarted them with `az vm start --no-wait`, one call at a time, LOG). The tar adds `data/s3/{sim2,cur5}` and the eval dirs; `cur1` and `gen` (named by `mix_v2a`) must already sit under `data/s1` from the node kit. +4. **Launch**: `r17-v2a` and `t150-v2a` (table in §4). Both mixtures list `buckets` and cap `sim2` at `max_repeat` 1.0 per pass. +5. **Post** (`v2_post.sh r17-v2a genclass-runtime-r17 2.0.0-rc1`, detached on c09; `set -u`, no `-e`): polls `models/<M>/meta.json` for `final` every 30 s, `EVAL_THREADS=10 eval_sim.sh sim2e <M>` and `… sim2f <M>` (each fits its own temperatures on the shared dev rows: `out/cal/<M>-sim2e.json`, `out/cal/<M>-sim2f.json`), `eval_gain.py --rows data/sim2e/test.jsonl --model <M>=out/records/<M>__sim2e__test.jsonl:out/cal/<M>-sim2e.json --out out/eval/gain-<M>-sim2e.json`, touches `out/.eval-done-<M>`, then `export_runtime.py --calibration out/cal/<M>-sim2e.json --data-rows data/sim2e/dev.jsonl,data/cur5e/dev.jsonl --n-per-file 60 --threads 24` → `out/export-<M>/`, tars it without `ref/` to `~/xfer/export-<M>.tar`, serves `~/xfer` on `<node IP>:8801`, touches `out/.post-done-<M>`. Logs: `logs/v2-eval-<M>-{e,f}.log`, `logs/v2-gain-<M>.log`, `logs/v2-export-<M>.log`. Unlike `final_post.sh` it creates `logs/` first. Delivery to the train VM / MODEL is a separate step (`pull_on_train.sh` pattern); the card version `2.0.0-rc1` is the export's own `model.json` version, not an npm version. +6. **REAL v2** (prepared, not run): `training/import_real.sh "v2c1 v2c2 v2c3 v2c4" v2-eval` (train VM serves `/data/real-out` on :8804; per batch `train`, `dev`, `test`, `unlabeled-train` jsonl; train rows shuffled (`yes 3`) into 32 shards `data/s3/real2/`; `real2e` = 20k test (`yes 4`) / 8k dev (`yes 5`) with `_t`/`_d` shards; `realev` from `real_eval.jsonl` if present; unlabeled into `data/s3/realunl/`). Evaluate a model on `realev` by filling `out/records/<M>__realev__test.jsonl` (e.g. `eval_sim.sh realev <M>`: its per-shard runs and the test merge work, but there are no `realev_d*` shards or `realev/dev.jsonl`, so the unmatched `data/realev_d*` job and the final dev-fitted `eval_runtime.py` step fail; unverified) and then `eval_real.py --rows data/realev/test.jsonl --model <M>=<records>:out/cal/<M>-sim2e.json`. `eval_real.py` applies the calibration's single `choice` τ to both action and diagnosis logits; a missing `meta.tiers` entry counts as heal. The LOG plans a continuation of `t150-v2a` that adds the REAL bucket. + ## Configuration and constants | Name | Type | Value / default | Defined in | Effect | @@ -399,6 +425,13 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th | `mix_t150.json` | mixture | simA .9, cur4 .1; `buckets` = those 2; 470M; `*` 2.0, simA 1.2 | `configs/` | teacher `t150-g1` (v1) | | `mix_r68.json` | mixture | simA .8, cur4 .12, cur1 .07, gen .01; 520M; simA 1.3 | `configs/` | R68 benchmark (never run) | | `mix_t1a.json` / `mix_t1b.json` / `mix_t1h.json` | mixture | as `mix_final1` with `simA` replaced by `simAg10` / `simAg20` / `simAh` | `configs/` | T1 runs | +| `mix_v2a.json` | mixture | sim2 .86, cur5 .11, cur1 .02, gen .01; `buckets` = those 4; 500M; `*` 2.0, sim2 1.0 | `configs/` | `r17-v2a` (situation-v2 student) | +| `mix_t150v2.json` | mixture | sim2 .9, cur5 .1; `buckets` = those 2; 500M; `*` 2.0, sim2 1.0 | `configs/` | `t150-v2a` (situation-v2 teacher) | +| `DROP_TRAIN` | tuple | `cost_parts`, `patterns`, `adjusted`, `se`, `program_family` | `prep_v2.py` | meta keys removed from train rows only (eval rows keep full meta) | +| `TEST_FEATURES` | set | swcache, presence, cascade, saga, prefetch, permissions | `prep_v2.py` (copy of `sim/src/world/scenario.ts`) | held-out-feature eval set `<name>f`; must follow SIM if its list changes | +| `prep_v2.py` defaults | args | `--shards-per-file` 8, `--workers` 32 (`import_v2.sh` passes 40), `--test-rows` 20,000, `--dev-rows` 8,000, `--root data`; feature oversampling 6× | `prep_v2.py` → `main` | v2 shard count and eval-set sizes | +| `cur5` generator | args | `--n 300000 --seed 15 --p-runtime 0.8 --workers 64`, `split -n l/32` | `import_v2.sh` | v2 replay set (skipped when `data/s3/cur5` exists) | +| `TH` / `PERMIT` | dict | guard (0.9, 0.7, 0.5), heal (0.8, 0.7, 0.5) / guard → guard tier, heal → guard + heal | `eval_real.py` | REAL eval thresholds and permitted tiers | | `--max-len` | int | trainer default 1536; 1536 in stage 1c (s1 command unrecorded); 2048 stage 2/final (SIM packed p95 1,523, max 1,761) | `jev_local/train/train.py`, README, launch scripts | written to servable/exported `meta.json` `max_len` | | `--batch-tokens` | int | 8192 | launch scripts | micro-batch token budget | | `--ckpt-every` | int | trainer default 500; launch scripts pass 50 | `jev_local/train/train.py` | checkpoint cadence (a SIGKILL loses at most this many steps) | @@ -425,7 +458,7 @@ CLI defaults: `--name genclass-runtime`, `--version 0.1.0` (always pass both; th | `meta.json` `max_len` / `max_total` | int | ckpt meta `max_len` or 1536 / 8192 | `export_runtime.py` | runtime packer limits | | ortweb versions | str | onnxruntime-node 1.30.0, onnxruntime-web 1.30.0 | `ortweb/package.json` | validation runtime | | validate defaults | args | variant q8, 60 requests (delivery scripts pass 120) | `validate.mjs` | — | -| ports | int | 8798 (train VM → c01 one-off v1 tar), 8799 (workbench data bundles, 10.0.0.6 for c01), 8801 (node → c01/train VM tars; node kit), 8802 (train VM SIM dir, 10.0.0.4; `import_final.sh` `PORT`), 8805 (workbench → nodes, `label_cluster.sh`), 8810 (train VM SIM bundle server, NEEDS) | scripts, LOG, NEEDS | `python3 -m http.server` transfers on the private network | +| ports | int | 8798 (train VM → c01 one-off v1 tar), 8799 (workbench data bundles: 10.0.0.6 for c01, c02 for the v2 tars), 8801 (node → c01/train VM tars; node kit), 8802 (train VM SIM dir, 10.0.0.4; `import_final.sh` `PORT`), 8803 (train VM v2 SIM dir, `import_v2.sh` `PORT`), 8804 (train VM `/data/real-out`, `import_real.sh`), 8805 (workbench → nodes, `label_cluster.sh`), 8810 (train VM SIM bundle server, NEEDS) | scripts, LOG, NEEDS | `python3 -m http.server` transfers on the private network | | `TIMEOUT` | env s | 900 | `node.sh` | per-call ssh/scp timeout for `'cmd'`/`get`/`put` (`sync` uses fixed 120 s / 600 s timeouts; `scripts/azvm.sh` and therefore `scripts/launch_run.sh` ignore it) | Model directory files (`export_runtime.py`): @@ -442,7 +475,7 @@ Model directory files (`export_runtime.py`): ## Invariants and gotchas -- **Runtime parity of `rt.py` is load-bearing.** Constants and wording (`DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR`, `TRIGGER_ACTIONS`, `RANK`, `LIMITS`, budgets, `secs`/`rel`/`ratio`/`fmt_num`, `signature`/`is_id`) must equal `packages/runtime/src/situation/{questions,serialize,facts,conflicts,content,evidence,describe,build}.ts`, `src/state/fields.ts` (`changeText`/`stringDiff`) and `src/util.ts`. `rt.py` was ported against tag `situation-v2` (6e5e86e); `git diff 6e5e86e b435acb -- packages/runtime/src/situation packages/runtime/src/state/fields.ts` is empty (the only later runtime change, the default mode `observe` in `runtime.ts`, does not touch the situation). Spot-checked at b435acb: `STATE_CHAR_BUDGET` 2400, `COMPACT_BUDGET` 1100, `MIN_BUDGET` 500, `COMPACT_QUESTIONS_BUDGET` 1400, `RANK`, `sectionLimits`, `situationBudget`, `TRIGGER_DESCRIPTIONS`, delivery instruction and `DEFAULT_DIAGNOSES` match; a full byte-parity check against runtime output was not run (unverified). Per-header calibration keys are `sha1(instructions)[:12]`, so any instruction text change silently orphans `by_header` temperatures. +- **Runtime parity of `rt.py` is load-bearing.** Constants and wording (`DIAG_INSTR`, `DIAGNOSES`, `ACTIONS`, `ACTION_INSTR`, `TRIGGER_ACTIONS`, `RANK`, `LIMITS`, budgets, `secs`/`rel`/`ratio`/`fmt_num`, `signature`/`is_id`) must equal `packages/runtime/src/situation/{questions,serialize,facts,conflicts,content,evidence,describe,build}.ts`, `src/state/fields.ts` (`changeText`/`stringDiff`) and `src/util.ts`. `rt.py` was ported against tag `situation-v2` (6e5e86e), and all v2 SIM/REAL data was generated against it. On `mvp-v2-merge` the situation code differs from the tag only by the redaction fix (f107013): `situation/content.ts` → `contentFacts` F2 ("would replace text the user typed") now uses `state/fields.ts` → `redactedStringDiff`, and `util.ts` → `isSensitivePath` also redacts numbers, bigints and arrays under a secret-named container. Both only change text for secret-looking paths; `rt.py` has no redactor at all (its F2 always uses `string_diff`), which is harmless as long as curriculum paths never look secret (unverified). Per HANDOFF a change to `situation/*` normally means a new freeze tag; this one has none. Spot-checked earlier at b435acb: `STATE_CHAR_BUDGET` 2400, `COMPACT_BUDGET` 1100, `MIN_BUDGET` 500, `COMPACT_QUESTIONS_BUDGET` 1400, `RANK`, `sectionLimits`, `situationBudget`, `TRIGGER_DESCRIPTIONS`, delivery instruction and `DEFAULT_DIAGNOSES` match; a full byte-parity check against runtime output was not run (unverified). Per-header calibration keys are `sha1(instructions)[:12]`, so any instruction text change silently orphans `by_header` temperatures. - **Known small parity gaps** in `rt.py`: `to_state`'s last-resort shortening truncates facts to max(40, …) and never shortens the trigger, while `toJevState` uses max(60, …) and then shortens the trigger; Python `round()` (banker's) vs JS `Math.round` in `secs` (≥ 1000 s) and `ratio` (≥ 10×); Python format specs (`f"{x:.2f}"`, half-even on exact binary ties) vs JS `toFixed` (ties up) in `secs`/`rel`/`fmt_num`, e.g. `secs(125)` is `0.12s` in Python and `0.13s` in JS; `truncate` counts code points (Python `len`) vs UTF-16 code units (JS `length`), so text with astral characters such as emoji is cut at different points. Rare, but they produce text the runtime never sends. - **Numbers as JS prints them.** `fmt.js_numbers` turns integral floats into ints in `state` and `questions` (not in `labels`/`meta`); without it the model trains on `25.0`, which the JS runtime never emits (NEEDS item 8). Keep it when adding new emit paths. - **Determinism** is per code version: `random.Random(f"{seed}:{split}:{chunk}")`, sorted iteration where sets are involved. Changing any generator code, `--chunk`, or `--p-runtime` from 0 to > 0 (it adds an RNG draw) changes the rows; `cur1`/`cur2`/`cur3`/`cur4` cannot be regenerated byte-identically from the current code (the generator gained `transient`, `coincidental`, budgets and compact questions, and v2 adds a `P_DELIVERY` draw per runtime-rendered mutation row and different facts/budgets). @@ -456,13 +489,18 @@ Model directory files (`export_runtime.py`): - **Mixture buckets are directory names.** Put shards in `<stream root>/<bucket>/`. Without a `buckets` list, any extra bucket dir under a stream root silently gets weight 0.04 (`OTHER_BUCKET_WEIGHT`); `mix_final1.json` and the newer `mix_t150`, `mix_r68`, `mix_t1a/b/h` list `buckets`; `mix_s1*`/`mix_s2` do not. - **Marker ids moved.** With the pruned vocab, `[Q] [O] [L] [T] [F]` are 16359–16363; runtime, sim tooling and tests must read them from `tokenizer.json` / `meta.json` (CONTRACT §10). With 16k merges, keys like `trigger`, `facts`, `apply`, `defer` split into several tokens (harmless; trained on the pruned tokenizer). - **Token budget vs characters:** the v1 runtime's 3200-char budget assumed ≈ 3.2 chars/token, measured ≈ 2.4 (NEEDS 6a), so situations are ≈ 1.3–1.4× the intended 1,000 tokens; 3.9% of SIM `r300k` packed rows exceed 1,536 tokens, hence `max_len` 2048 for stage 2 (LOG). The smaller 1,000/2,000-char WASM budgets were adopted for latency (LOG 19:00 coordinator/MODEL note); situation-v2 lowered the full budget to 2,400 (≈ 1,000 tokens, per the `situationBudget` comment). -- **Script path layout:** `node.sh`, `import_*.sh`, `deliver_final.sh`, `launch_*.sh` (incl. `launch_student.sh`, `launch_t150.sh`, `launch_r68.sh`) and `label_cluster.sh` (via `node.sh`) resolve `JEV="$HERE/../.."` (or `cd "$(dirname "$0")/../.."`) and expect `jev_local/`, `scripts/launch_run.sh`, `scripts/azvm.sh`, `pyproject.toml` there. In this monorepo they are at the repo root (`$HERE/..`), so run them from a checkout nested inside a jev tree or adjust the path (unverified). `~/.jev-local/azure_hosts` columns: name, public IP ($2, used for ssh), private IP ($3); key `~/.ssh/jev_azure`, user `azureuser`. Mac-side scripts use GNU `timeout`. `label_cluster.sh` only calls `node.sh HOST 'cmd'`, whose command mode does not use `JEV` (only `node.sh sync` rsyncs `$JEV/{jev_local,scripts,pyproject.toml}`); `cluster_expand.sh` and `node_init.sh` have no path assumption. File modes: `run_evals.sh`, `eval_sim.sh`, `t1_post.sh`, `t1h_post.sh` and all `.py` files are 100644 (invoke them via `bash` / `$PY`); every other `.sh` is 100755, including the VM-side `final_post.sh` and `pull_on_train.sh`. +- **Script path layout:** `node.sh`, `import_*.sh` (incl. `import_v2.sh`, `import_real.sh`), `v2_node_setup.sh`, `deliver_final.sh`, `launch_*.sh` (incl. `launch_student.sh`, `launch_t150.sh`, `launch_r68.sh`) and `label_cluster.sh` (via `node.sh`) resolve `JEV="$HERE/../.."` (or `cd "$(dirname "$0")/../.."`) and expect `jev_local/`, `scripts/launch_run.sh`, `scripts/azvm.sh`, `pyproject.toml` there. In this monorepo they are at the repo root (`$HERE/..`), so run them from a checkout nested inside a jev tree or adjust the path (unverified). `~/.jev-local/azure_hosts` columns: name, public IP ($2, used for ssh), private IP ($3); key `~/.ssh/jev_azure`, user `azureuser`. Mac-side scripts use GNU `timeout`. `label_cluster.sh` only calls `node.sh HOST 'cmd'`, whose command mode does not use `JEV` (only `node.sh sync` rsyncs `$JEV/{jev_local,scripts,pyproject.toml}`); `cluster_expand.sh` and `node_init.sh` have no path assumption. File modes: `run_evals.sh`, `eval_sim.sh`, `t1_post.sh`, `t1h_post.sh` and all `.py` files (incl. `prep_v2.py`, `eval_real.py`) are 100644 (invoke them via `bash` / `$PY`); every other `.sh` is 100755, including the VM-side `final_post.sh`, `pull_on_train.sh` and `v2_post.sh`. `launch_student.sh` now expands an empty `INIT_ARGS` as `${INIT_ARGS[@]+"${INIT_ARGS[@]}"}`, which macOS bash 3.2 needs under `set -u` (LOG 05:22 fix). - **Python import paths:** `export_runtime.py`, `eval_runtime.py`, `generate.py`, `prune_vocab.py analyze` and the tests insert `~/jev` (and `~/jev/scripts`) into `sys.path`; elsewhere set `PYTHONPATH=<repo>:<repo>/scripts:<repo>/training`. - **`azvm.sh` ignores `TIMEOUT`** (only `node.sh` honours it), so `TIMEOUT=... scripts/azvm.sh` lines in `import_sim.sh`/`deliver_final.sh` and `TIMEOUT=300 scripts/launch_run.sh` in `launch_*.sh` have no timeout. `import_final.sh` deliberately has no `pkill` (a self-killing `pkill` was a past bug: the remote shell's command line matched the pattern); stop the train VM's :8802 server with `pkill -f "http.server 880[2]"` in a command that does not itself contain `http.server 8802` (the script's closing comment prints that pattern even when `PORT` is not 8802; bracket the last digit of the port you used). `import_sim.sh`'s first remote command still has the old pattern (its `pkill` runs only when :8802 is already listening, and the same command line later contains `http.server 8802 --bind`, so it can kill its own shell); stop any running server first or reuse `import_final.sh`'s logic. - **`pull_on_train.sh` expects `validate.mjs` already in `~/gcl/train-out/ortweb`** (it does not copy it; `deliver_final.sh` does). - **Bug (curriculum):** `standalone.json_invariants` writes the `count` invariant check as `j_count` and then overwrites `questions["j_count"]`/`labels["j_count"]` with the "price above threshold" score question, so the count==len check never reaches the data. Rows stay valid. - **Tests do not exercise `rt.py` by default.** `generate.make_row` reads the module global `P_RUNTIME` (from `GC_P_RUNTIME`, default 0), and `test_curriculum.py` calls `make_row` directly, so the five older tests only exercise runtime-exact rendering with `GC_P_RUNTIME=1` in the environment. The new `test_runtime_rows_situation_v2` calls `decision_row(..., 1.0)` directly and covers v2 always. Run the suite both ways after touching `rt.py`. Setting `GC_P_RUNTIME` has no effect on a `generate.py` CLI run; there, `--p-runtime` wins. An exported-but-empty `GC_P_RUNTIME=` makes `import generate` raise `ValueError` (seen on this machine). -- **Every existing data set predates situation-v2.** `rt1` and `cur2` were rendered by the first `rt.py` port (3,200-char budget, pre-`situation-v1` wording); `cur3`/`cur4`, SIM `final-a`/`final-b`/`gold-r1x` and the REAL pilots use situation-v1. None has `delivery` rows, the v2 facts or the 2,400 budget. Every mixture in `configs/` names only v1 buckets, and every checkpoint (incl. `r17-final1`) reads v1 text. A v2 replay set (`generate.py --p-runtime 0.8` with the current code) and v2 SIM/REAL imports are prerequisites for any v2 round; the only v2 data at this commit is on Azure (`train:/data/sim-out/v2-*`, REAL `v2-pilot`, `v2b1`–`v2b3`). +- **v1 and v2 data sets coexist; do not mix them.** `rt1` and `cur2` were rendered by the first `rt.py` port (3,200-char budget, pre-`situation-v1` wording); `cur3`/`cur4`, `simA`, SIM `final-a`/`final-b`/`gold-r1x` and the REAL v1 pilots use situation-v1. Only `sim2`/`sim2e`/`sim2f`, `cur5`/`cur5e` and the REAL `v2*` batches are situation-v2, and only `mix_v2a` / `mix_t150v2` use them (with small `cur1`/`gen` v1 replay in `mix_v2a`). Every checkpoint up to `r17-final1` reads v1 text; `r17-v2a` starts from `r17-final1` weights. +- **REAL `v2b1`–`v2b3` diagnosis labels are pre-fix** (no S1, no delivery-by-write, subset vocabularies; NEEDS 16): use `v2c1`–`v2c4`. From `v2b*` the action labels are valid; diagnosis labels only where `meta.trigger` is not `delivery` and `meta.diag_why` != `rel-check`, or not at all. +- **`mix_v2a` needs `data/s1/{cur1,gen}` on every node.** `v2_node_setup.sh`'s tar carries only `data/s3/{sim2,cur5}` and the eval dirs; a node without the v1 `data/s1` buckets (e.g. one that never got the node kit) trains on a silently renormalised mix. +- **`import_v2.sh` keeps an existing `cur5`.** It regenerates `cur5` only when `data/s3/cur5` is missing, so a re-import after an `rt.py` change reuses the old replay set; delete `data/s3/cur5 data/cur5e` first. It also always deletes and rebuilds `data/s3/<NAME>` and the eval dirs on the workbench (never re-run it while a run streams from the workbench's copy), and leaves `data/<NAME>raw/` (≈ 44 GB for `v2-gold`) on disk. +- **`sim2f` overlaps `sim2e`.** The feature rate is a superset of the test rate on the same `crc32(id)`, so held-out-feature rows that fall under the `sim2e` rate are in both sets; they share dev rows too. Report them as different views, not disjoint sets. +- **`v2_post.sh` touches its markers even on failure** (no `set -e`, like `final_post.sh`): check `logs/v2-eval-<M>-{e,f}.log`, `logs/v2-gain-<M>.log`, `logs/v2-export-<M>.log` before trusting `out/.post-done-<M>` or the served tar. - **Runtime budgets between the drawn ones.** The runtime's auto budget is `1000 + round((threads - 1) * 1000 / 3)` on WASM (1,000 / 1,333 / 1,667 / 2,000 for 1–4 threads), else 2,400 (v2), and either is multiplied by `budgetScale` (starts at 1; × 0.8 per `max_tokens_exceeded` model error, floor 0.5); a numeric `budget` option overrides all of it (`packages/runtime/src/runtime.ts` → `situationBudget`). v2 `rt.BUDGETS` now draws all five device budgets (1,333 and 1,667 at 5% each), but scaled budgets (× 0.8, …) and app-configured budgets still rely on `section_limits` interpolation generalising. - **Missing mixture buckets are silent.** `stream.py` renormalises weights over the buckets it finds, so a typo in a bucket dir or a forgotten `cur4` shard dir trains on a different mix without an error. Check the plan before or at launch: `python -m jev_local.train.stream <roots...> --mixture <mix.json>` prints it, and the trainer writes `$G/runs/<run>/mixture_plan.json` (corpus summary + pass-0 plan; LOG's "cur1 93.1%, cu 6.2%, gen 0.7%" for `mix_s1` is this kind of realised share). - **`merges_kept: null` in exported `meta.json`** for every trainer-written checkpoint (see Export). Nothing reads it today; `vocab_size` and `markers` are always set. @@ -475,7 +513,7 @@ Model directory files (`export_runtime.py`): - **`eval_runtime.PASSIVE` has no `delivery` key.** Passive detection still works through `meta.passive` and `TIER["deliver"] == "passive"`, but `decision_metrics`' `by_trigger` breakdown will show `delivery` as its own trigger; keep `TIER`/`PASSIVE` in sync with the runtime when adding triggers. - **T1 labels and the §8 gate do not mix.** softmax(gain/τ) labels put ≥ 0.5 summed non-passive mass on 64% of phase-A rows (LOG), so evaluate T1 models with `eval_gain.py`'s `gain>m` / `head>m` policies, not only `eval_runtime.py`'s summed-mass gate. - **Past bugs recorded in LOG:** typeahead requests could start out of keystroke order (fixed with a per-app debounce in `mut_typeahead`); noul head Gemm left fp32 (fixed by `gemm_to_matmul`); Python float literals in rows (fixed by `js_numbers`). -- **Licensing hygiene:** no TRAIN script reads `jev-local-fast-v2`, `meharsjev-68m-z`, `z-cal-*`, `z-mid*` or any benchmark/third-party dataset (re-verified by grep at b435acb, incl. the new scripts). Keep it that way; the model card claims Apache-2.0 synthetic-only data. +- **Licensing hygiene:** no TRAIN script reads `jev-local-fast-v2`, `meharsjev-68m-z`, `z-cal-*`, `z-mid*` or any benchmark/third-party dataset (re-verified by grep on `mvp-v2-merge`, incl. `import_v2.sh`, `prep_v2.py`, `v2_node_setup.sh`, `v2_post.sh`, `import_real.sh`, `eval_real.py`; the only hits are mentions in `training/README.md` and `PLAN-v1.md`). `t150-v2a` starts from the MIT ettin-150m base. Keep it that way; the model card claims Apache-2.0 synthetic-only data. ## How to change it safely @@ -490,9 +528,9 @@ Model directory files (`export_runtime.py`): **Regenerate a curriculum set** (on c01, after `node.sh c01 sync`): ``` -$PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --seed 6 --workers 72 --p-runtime 0.8 +$PY training/curriculum/generate.py --out ~/gcl-train/data/cur6 --n 300000 --seed 16 --workers 72 --p-runtime 0.8 ``` -Then shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl <root>/<bucket>/shard`) under a stream root, add the bucket to a mixture, and check `stats.json` (`bad`, `errors` = 0; `passive_best_fraction` sane). Use a new seed and bucket name; never overwrite a set a run is training on. +Then shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl <root>/<bucket>/shard`) under a stream root, add the bucket to a mixture, and check `stats.json` (`bad`, `errors` = 0; `passive_best_fraction` sane). Use a new seed and bucket name (`cur5` = seed 15 is taken by the v2 replay that `r17-v2a`/`t150-v2a` stream); never overwrite a set a run is training on. **Mirror a runtime situation/question wording change** (CORE changed `packages/runtime/src/situation/*`): 1. Diff the runtime files since the last port (`git diff situation-v2 HEAD -- packages/runtime/src/situation packages/runtime/src/state/fields.ts packages/runtime/src/util.ts`) and update the matching `rt.py` function (`*_facts`, `version_facts`/`content_facts`/evidence builders, `delivery_spec`, `subject_sentence`, `event_lines`, `state_lines`, `stats_lines`, `to_state`/`section_limits`, `BUDGETS`, constants). @@ -506,13 +544,12 @@ Then shard train (`split -n l/64 -d -a 2 --additional-suffix=.jsonl train.jsonl **Change a mixture / launch a new round:** copy a `configs/mix_*.json` (keys must be `MixConfig` fields; list `buckets` explicitly), prefer `launch_student.sh RUN ARCH PASSES MIX "nodes" [INIT]` (new run name ⇒ new `--stream-cache`/`--out`; it resumes when `runs/RUN/ckpt` exists), or copy `launch_final1.sh`; keep rank 0 = the node holding `--init-from`. Use 8 ranks × 10 threads per F80 node. Make sure every bucket named in the mixture has train shards under one of the `--stream` roots (check `mixture_plan.json`). Watch `~/jev/runs/<run>/rank0.out` and `$G/runs/<run>/log.jsonl` on the rank-0 node; deallocate idle nodes. -**Prepare the first situation-v2 round** (Azure; ask the user before anything runs there; PLAN-v1 P1): -1. Generate a v2 replay set on the workbench: `$PY training/curriculum/generate.py --out ~/gcl-train/data/cur5 --n 300000 --seed 6 --workers 72 --p-runtime 0.8`, check `stats.json`, shard into `data/s3/cur5/`. -2. Import v2 SIM gold per batch with `import_final.sh` (`PORT` per source dir, `WB` = the workbench; batches are gz shards + `manifest.json` under `train:/data/sim-out/v2-*` or `data:~/simdata/<run>/`, so they may need unpacking/merging into `{train,dev,test}.jsonl` first; unverified). Import REAL v2 batches the same way (see [realapps.md](realapps.md)); keep `real_eval.jsonl` test-only. -3. Write new mixtures (e.g. `mix_v2_t150.json`, `mix_v2_distill.json`) listing `buckets` explicitly; check `mixture_plan.json` at launch. -4. Teacher: `launch_t150.sh` (or `launch_student.sh RUN t150 ...`) on v2 gold; evaluate with `eval_sim.sh` + `report.py` and check clear-case recall first (PLAN P2 gate: if the teacher is also near 40% argmax on clear rows, the bottleneck is the situation information, not model size). -5. Label: fit the teacher's calibration on v2 dev, then `label_cluster.sh WB t150-v2 out/cal/<cal>.json data/unlab/<set> <bucket> "nodes"`; gather the outputs. -6. Distil: `launch_student.sh r17-v2 r17 <passes> mix_v2_distill.json "nodes" $G/runs/r17-s1c/ckpt` (and r32); evaluate, export, validate as below. Then DAgger with SIM `--on-policy` rows from the exported students. +**Continue the situation-v2 round** (Azure; ask the user before anything runs there; PLAN-v1 P1–P5). Steps 1–3 of the original plan are done (§12: `cur5`, `sim2` import, `mix_v2a` / `mix_t150v2`, `r17-v2a` and `t150-v2a` launched); what remains: +1. Read `r17-v2a`'s results on c09 once `out/.post-done-r17-v2a` exists (check the logs first, see Gotchas): `report.py r17-v2a=out/eval/r17-v2a-sim2e.json --mode=kind` (and `-sim2f`), `out/eval/gain-r17-v2a-sim2e.json`, then deliver `~/xfer/export-r17-v2a.tar` (`:8801`) to the train VM with `pull_on_train.sh <c09 ip> r17-v2a v2a r17` and validate. Record the numbers in EVAL.md / LOG. The export is also what SIM needs for `--on-policy` (NEEDS). +2. Teacher: when `t150-v2a` is final, evaluate it the same way (`eval_sim.sh sim2e t150-v2a`, `sim2f`) and check clear-case recall first (PLAN P2 gate: if the teacher is also near 40% argmax on clear rows, the bottleneck is the situation information, not model size). No post script was started for it (LOG). +3. REAL: when `v2c1`–`v2c4` land, `import_real.sh "v2c1 v2c2 v2c3 v2c4" v2-eval`, distribute `v2_real2.tar` (`TAR=v2_real2.tar v2_node_setup.sh cNN`), add `real2` to the mixtures (LOG: a continuation run adds them), and run `eval_real.py` on `realev`. Keep `real_eval.jsonl` test-only. +4. Label: the 51.3M unlabeled SIM rows (`train:/data/sim-out/v2-unl`, gz shards) are not imported; `prep_v2.py` only shards `train-*.jsonl.gz`, so pointing `import_v2.sh` at `v2-unl` would also build throwaway eval sets and regenerate nothing else (unverified). Pick the PLAN P3 subset (5–10M rows near the gate plus a uniform sample), fit the teacher's calibration on `sim2e` dev, then `label_cluster.sh WB t150-v2a out/cal/t150-v2a-sim2e.json <src dir> <bucket> "nodes"`; gather the outputs. +5. Distil: write `mix_v2_distill.json` (gold `sim2` (+ `real2`) + teacher-labelled bucket + 5–10% `cur5` replay, `buckets` listed), `launch_student.sh r17-v2d r17 <passes> mix_v2_distill.json "nodes" <init>` (and r32); evaluate, export, validate as below. Then DAgger with SIM `--on-policy` rows from the exported students. **Run a T1 experiment:** `t1_relabel.py --in data/s3/<gold> --out data/s3/<gold>g10 --tau 1.0` (or `--keep-dist` for the gain head, which needs the parent-repo `jev_local`), add a mixture with the new bucket, launch from `r17-s1c` (or the v2 equivalent), then `bash training/t1_post.sh <run> <tau>` detached on rank 0; compare `out/eval/gain-<run>.json` with the baseline via `eval_gain.py --model` (one flag per model). @@ -549,7 +586,7 @@ Tests were written for a VM (`cd ~/gcl-train && PYTHONPATH=~/jev[:~/gcl-train/tr | `training/tests/test_prune_vocab.py` (6 tests; need `GC_V1_CKPT`, `GC_BASE_32M`) | ettin layout (243 base ids 2–244, merges from 245); pruned tokenizer at 4k/8k/16k encodes random unicode/control text, ids in range, decodes to the same text, never fewer tokens, ids < 245+N unchanged, specials/markers kept and special, markers in user text not matched; logits identical (< 1e-4) to the unpruned v1 model when tokenisation is unchanged (`vocab_new` = 245+N+119); HF-base prune → `init_model` appends markers at V..V+4 and runs a forward pass | | `training/tests/test_export_runtime.py` (3 tests; e2e needs `GC_R17_INIT`, default `~/gcl-train/models/r17-v16k-init`) | int8 embedding error ≤ scale/2 and zero rows survive; Gemm→MatMul+Add preserves outputs; end-to-end export: card format, bytes/sha256 of every file, `meta.markers`/`cls_id`/`sep_id` match `tokenizer.json`, parity fp32 < 1e-3, q8/fp16 < 0.5 (random heads), R17 q8 < 12 MB | -Last recorded runs (LOG): `test_prune_vocab.py` 6/6, `test_curriculum.py` 5/5 on c01 (before the v2 test existed). No run of `test_export_runtime.py` is recorded. Run for this doc in the mvp-v2 checkout on macOS (Python 3.14.7, no pytest, no `jev_local` deps; each test function called directly from `training/tests` with `training/curriculum` and the repo root on `sys.path`), with `GC_P_RUNTIME` unset and with `GC_P_RUNTIME=1`: 5 of 6 pass both ways, incl. `test_runtime_rows_situation_v2`; `test_all_rows_valid_and_deterministic` needs `jev_local`'s deps (`pydantic`) and was not run. +Last recorded runs (LOG): `test_prune_vocab.py` 6/6, `test_curriculum.py` 5/5 on c01 (before the v2 test existed); in the 04:50–05:22 UTC entry "full curriculum tests on c02: 7 passed" with the v2 `rt.py` (prune tests skip there: no v1 checkpoint on the node). No run of `test_export_runtime.py` is recorded. `prep_v2.py`, `eval_real.py` and the v2 shell scripts have no tests. Run for this doc in the mvp-v2 checkout on macOS (Python 3.14.7, no pytest, no `jev_local` deps; each test function called directly from `training/tests` with `training/curriculum` and the repo root on `sys.path`), with `GC_P_RUNTIME` unset and with `GC_P_RUNTIME=1`: 5 of 6 pass both ways, incl. `test_runtime_rows_situation_v2`; `test_all_rows_valid_and_deterministic` needs `jev_local`'s deps (`pydantic`) and was not run. Test inputs and skips: `test_curriculum.py` needs `~/jev` on `sys.path` (it imports `jev_local` for `_validate`) and covers only the varied style unless `GC_P_RUNTIME` is set (see Gotchas). `test_prune_vocab.py`: `GC_V1_CKPT` (default `~/jev/models/jev-local-fast`; 5 tests skip without `backbone/tokenizer.json`) and `GC_BASE_32M` (default `~/jev/models/base/ettin-encoder-32m`; the HF-base test prunes it to 8,000 merges and skips without it). `test_export_runtime.py`: the two graph-surgery tests are self-contained (tiny ONNX graphs); the end-to-end test skips unless `GC_R17_INIT/backbone` exists and runs `export_runtime.py` as a subprocess on 6 hand-written requests. @@ -606,7 +643,7 @@ Doc-vs-code drift: - New with the v2 / scaled-program commits: - `training/README.md` was not updated for situation-v2 (still "Final rounds (frozen runtime `situation-v1`)", no `delivery`, no teacher/T1 scripts); this doc and PLAN-v1/LOG are current. - - `training/NEEDS.md` "SIM → TRAIN: scaled data" still says "Runtime tag `situation-v1`" and item 10 says "the quota (1,024 vCPU) is exactly the whole cluster"; LOG (00:40) and HANDOFF say the quota is 2,048 and the v2 production batches are situation-v2. The node-claim table mixes past and current rows; HANDOFF/the lead's Azure look (2026-10-08 04:14 UTC): c01–c23 and `train` running, `data` deallocated, SIM on c02–c09 + c12–c23, REAL on c01, c10, c11. + - `training/NEEDS.md` "SIM → TRAIN: scaled data" still says "Runtime tag `situation-v1`" and item 10 says "the quota (1,024 vCPU) is exactly the whole cluster"; LOG (00:40) and HANDOFF say the quota is 2,048 and the v2 production batches are situation-v2. The node-claim table mixes past and current rows; the current ones (05:05 UTC on): SIM's 20 nodes done and deallocated, then TRAIN on c02 (workbench), c03–c09 + c13 (`r17-v2a`), c12 + c14–c23 (`t150-v2a`); REAL on c01, c10, c11 and `data` (NEEDS 16). The new "Situation-v2 big runs" entry in the same file does say `situation-v2`. - `training/NEEDS.md` numbers two different items "7." and two "10." (MODEL INFO latency and the PLAN-v1 node claims). - `launch_t150.sh` header "6 ranks × 13 threads per node" vs code default 8 × 10 (see Gotchas). PLAN-v1 §3 also says "use 6 ranks or grad-ckpt" on the 160 GB nodes. - `launch_student.sh` header example `mix_v2_distill.json` does not exist; header says "checkpoints every 25 steps" (true). @@ -617,12 +654,18 @@ Doc-vs-code drift: - `docs/runtime/RESULTS.md` §1 reports final1 "recall" as 7.7% (the guard clear stale/duplicate figure); EVAL.md's plain recall is 1.8% guard / 4.5% heal, MODEL_CARD says "≈ 5%". Same data, different definitions. RESULTS' R32 row puts 5.9% in the same "clear stale/duplicate" column, but 5.9% is R32's heal clear-case recall; its guard clear stale/duplicate figure is 6.8% (EVAL.md). - `training/PLAN-v1.md` still has situation-v1 details: §1/§5 report ECE "per budget 1,000 / 2,000 / 3,200" (v2 budgets top out at 2,400); §6.1 says `meta.teacher` holds "margin, entropy" (`label_teacher.py` writes `top`, `margin` and, for `action`, `non_passive_mass`; no entropy); §7 says the quota is 1,024 vCPU and proposes c02–c09 for TRAIN (quota is 2,048; NEEDS' later claim table supersedes it). - `collect_gain.py` docstring says "Resumable by line count"; `main` opens `--out` with `"w"` and starts over. +- New with the v2 data / first v2 round (eff18cb): + - `launch_t150.sh` hardcodes `mix_t150.json` (v1); the v2 teacher's command is not in the repo or LOG. + - `prep_v2.py` docstring says the held-out-features set has "≈ 20k test rows"; the v2 gold yielded 18,690 at 6× oversampling (LOG). + - `training/NEEDS.md` claim table says the v2 runs start "from ≈ 05:30 UTC"; LOG has 05:14 / 05:20. Item 10 still proposes c01 as workbench and c02–c09 for training; the v2 claims (c02 workbench) supersede it. + - `training/README.md` still describes situation-v1 and has no v2 import/post steps; this section and LOG are current. + - `eval_sim.sh` header says "Run on c01"; it now runs on c02 and on rank-0 nodes (`v2_post.sh`). Open items relevant to this scope (HANDOFF, OPEN_TASKS, PLAN-v1, NEEDS): -- **No situation-v2 model exists.** Next per HANDOFF: import v2 gold (SIM ≥ 10M, REAL ≈ 495k (NEEDS target ≥ 500k)) → T150 teacher on v2 gold (P1) → teacher eval incl. clear-case separation (P2) → teacher labels on the unlabeled rows (P3: a prioritised 5–10M-row subset of the ≥ 50M) → distil R17 (default) and R32 (P4) → DAgger via SIM `--on-policy` (P5) → EVAL → `@genclass/runtime-model@0.1.0` (release steps: [RELEASE.md](../../RELEASE.md); the runtime's `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` 404 until then; `@genclass/runtime-model` is 404 on npm) → demos rerun → `@genclass/runtime@0.1.0`. A v2 curriculum replay set, v2 mixtures and a distillation mixture still have to be written. +- **No situation-v2 model has results yet.** Done: SIM v2 data (10.4M gold, 51.3M unlabeled), the `sim2`/`cur5` import, `r17-v2a` (ETA ≈ 06:20 UTC, auto eval + export via `v2_post.sh`) and `t150-v2a` (ETA ≈ 08:30 UTC) launched. Next per HANDOFF / LOG: read and record `r17-v2a`'s eval, deliver its export (also SIM's on-policy input) → import REAL `v2c*` (≈ 530k gold expected; target ≥ 500k) and continue with `real2` → T150 teacher on v2 gold (P1) → teacher eval incl. clear-case separation (P2) → teacher labels on the unlabeled rows (P3: a prioritised 5–10M-row subset of the ≥ 50M) → distil R17 (default) and R32 (P4) → DAgger via SIM `--on-policy` (P5) → EVAL → `@genclass/runtime-model@0.1.0` (release steps: [RELEASE.md](../../RELEASE.md); the runtime's `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` 404 until then; `@genclass/runtime-model` is 404 on npm) → demos rerun → `@genclass/runtime@0.1.0`. The v2 replay set (`cur5`) and the v2 mixtures exist; a distillation mixture and the unlabeled import still have to be written. A trained v2 model would ship as `@genclass/runtime-model`; `@genclass/runtime@0.1.0-alpha.1` is already on npm (published from 806a296, without the one-command install, which goes into the next runtime version). - R17-final1 (situation-v1) exists only on the train VM / Mehar's Mac and does not match the v2 runtime: do not package it as the v2 default. - T1 on v2 data (rerun `r17-t1g10`/`t1g20`/`t1h` on v2 gold; the gain head must be ported into this repo's `jev_local` first). The v1 T1 runs are resumable but superseded. -- Cost: PLAN-v1 estimates ≈ $3–4k in total (P0–P5 plus per-round eval); ≈ $390 spent to 01:56 UTC (LOG), ≈ $400 (RESULTS.md). Every Azure action needs the user's OK on our side. +- Cost: PLAN-v1 estimates ≈ $3–4k in total (P0–P5 plus per-round eval); ≈ $440 spent to 05:22 UTC with ≈ $110/h burn while the 20 v2 nodes run (LOG); RESULTS.md says ≈ $400 (older). Every Azure action needs the user's OK on our side. - NEEDS 4 (ASK): clean-run rows (`meta.clean`, now produced by SIM/REAL) for a direct FIR on clean traffic. NEEDS 5 (ASK): keep instructions/descriptions stable (by_header calibration keys are `sha1(header)`). NEEDS 6a (ASK): budget with the real tokenizer (≈ 2.4 chars/token; the v2 2,400 budget targets ≈ 1,000 tokens). - Re-check q8 parity on every trained model and consider MatMulNBits block 16 (+1.8 MB for R32) if gate agreement drops (LOG). - Known risks (OPEN_TASKS, PLAN-v1 §8): label noise from few sampled futures (benign request rows softest); thin `conflict` and `transition` classes; teacher too slow on CPU (fallback: R68 as teacher); over-intervention on real apps (ship guard only when guard FIR ≤ 0.1% on all held-out sets). @@ -633,7 +676,7 @@ Open items relevant to this scope (HANDOFF, OPEN_TASKS, PLAN-v1, NEEDS): - [glossary.md](glossary.md): shared term list (stage 1 / 1c / 2, final round 1, phase A / B, bucket, `situation-v1` / `situation-v2`, `COMPACT_BUDGET` vs `COMPACT_QUESTIONS_BUDGET`). - [model-io-contract.md](model-io-contract.md): situation text → packed request → heads → calibrated answers (shared by runtime, sim and training). - [sim.md](sim.md): the SIM generator that produces the rows for the stage-2 pilot (`r300k`), the v1 final rounds (phase A/B) and the v2 gold / unlabeled / on-policy (DAgger) batches: `meta.costs`, `meta.cost_futures`, `meta.budget`, splits, held-out features. -- [realapps.md](realapps.md): the REAL corpus (91 real apps at b435acb (READMEs/HANDOFF still say 66) in headless Chromium) that produces real-browser gold rows and the test-only `real_eval.jsonl` set. +- [realapps.md](realapps.md): the REAL corpus (128 real apps on this branch: 96 after wave 3 (d53e836), then 18 more in f3a9dd1 and 14 in eff18cb that the commit messages do not mention; headless Chromium; the `v2c*` batches use 96 apps per NEEDS 16) that produces real-browser gold rows and the test-only `real_eval.jsonl` set. - [RELEASE.md](../../RELEASE.md): release procedure for `@genclass/runtime` (alpha.1) and `@genclass/runtime-model@0.1.0` (never publish round-1 R17 as 0.1.0; npm 11 needs `--tag` for prereleases). - `sim/SEPARABILITY.md`: why final1 recall is low (benign twins, label fixes S1/S2, T1 proposal in §7). - [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md): the runtime situation code that `curriculum/rt.py` mirrors. From 38ff62b65349f405b1f8a886e8887be655ac6e19 Mon Sep 17 00:00:00 2001 From: Karan <prokaranvir@gmail.com> Date: Thu, 8 Oct 2026 03:48:49 -0400 Subject: [PATCH 13/25] install CLI: observe default, safe remove, browser-app detection, SRI only for pinned files, typesVersions - init: observe is the documented default (USAGE, Mode row); no --mode writes the plain /auto import and no data-mode; --mode guard/heal/observe write /auto/<mode> and data-mode="<mode>" on the script tag. - init again with another --mode switches the marked import / data-mode in place (it used to say "Nothing to do"); a later GenClass.init({ mode }) that cannot apply now logs one warning instead of being ignored silently. - remove deletes only what init wrote: a marked statement is matched with the lines a formatter wrapped it onto (Prettier, ESLint curly), blocks only when start/end pair up and hold init's code only, inline forms only when unedited (an Astro inline <script> is checked); anything else is reported and nothing is changed. Inline forms a formatter moved onto their own lines leave no blank line. User code after a created file's block is kept. - remove keeps the package installed while dot-folders or other skipped folders (.storybook, tmp, out, build) still import it (scanned read-only) and lists them. - detection: a bundler dependency alone is not a browser app. A webpack/rspack/parcel/esbuild/rollup project needs an index.html, a UI framework or an HTML plugin / dev server; packages that look like libraries or CLIs (UI framework as a peer, exports/module/types/bin) and entries importing Node-only modules (express, node:*, react-dom/server) are refused with a clear message. - SRI only when the script URL is exactly this version's jsDelivr/unpkg file whose bytes the CLI hashed; other --cdn URLs get no integrity attribute and a note says so. Version strings come from package.json. - package.json: typesVersions for every typed subpath (moduleResolution "node", e.g. CRA TS); sideEffects adds ./dist/worker.js and keeps ./src/model/worker.ts (the CDN worker build imports it bare; without it esbuild drops the model worker from dist/cdn/worker.js). - src/cdn/config.ts documents the <meta name="genclass"> trust model and what SRI does not cover (pin versions or self-host). - tests: cli.test.ts covers each behavioural fix plus package.json typesVersions/sideEffects checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/runtime/bin/lib/detect.mjs | 101 ++++- packages/runtime/bin/lib/edit.mjs | 290 +++++++++++++-- packages/runtime/bin/lib/init.mjs | 108 +++++- packages/runtime/bin/lib/plan.mjs | 52 ++- packages/runtime/package.json | 13 + packages/runtime/src/cdn/config.ts | 13 + packages/runtime/src/index.ts | 18 +- .../test/install/INSTALL-README-SNIPPET.md | 32 +- packages/runtime/test/install/cli.test.ts | 349 +++++++++++++++++- 9 files changed, 906 insertions(+), 70 deletions(-) diff --git a/packages/runtime/bin/lib/detect.mjs b/packages/runtime/bin/lib/detect.mjs index 3c242299..5e5ad940 100644 --- a/packages/runtime/bin/lib/detect.mjs +++ b/packages/runtime/bin/lib/detect.mjs @@ -84,6 +84,46 @@ export function walkSources(dir, max = 20000) { return outFiles.sort(); } +// Generated or third-party directories even the full scan below skips: dependencies, version control and the +// frameworks' own caches (they are rebuilt from the sources). +const NEVER_SCAN = new Set([ + "node_modules", ".git", ".hg", ".svn", ".next", ".nuxt", ".output", ".svelte-kit", ".astro", ".vercel", ".netlify", + ".turbo", ".cache", ".parcel-cache", ".angular", ".vite", ".react-router", ".remix", "coverage", +]); + +/** + * Source files walkSources leaves out (dot-directories such as .storybook, tmp, out, build, dist, deeper than 10 + * levels), read-only: `remove` checks them for imports before it uninstalls the package. + */ +export function walkSkipped(dir, max = 20000) { + const seen = new Set(walkSources(dir)); + const outFiles = []; + const stack = [[dir, 0]]; + while (stack.length && outFiles.length < max) { + const [d, depth] = stack.pop(); + let entries; + try { + entries = readdirSync(d, { withFileTypes: true }); + } catch { + continue; + } + for (const e of entries) { + if (e.isDirectory()) { + if (!NEVER_SCAN.has(e.name) && depth < 30) stack.push([join(d, e.name), depth + 1]); + } else if (e.isFile() && SRC_EXT.test(e.name)) { + const p = join(d, e.name); + if (seen.has(p)) continue; + try { + if (statSync(p).size <= 1_000_000) outFiles.push(p); + } catch { + /* ignore */ + } + } + } + } + return outFiles.sort(); +} + // -------------------------------------------------------------------------------------- package manager /** npm | pnpm | yarn | bun, from lockfiles (this directory and its parents), packageManager, or the user agent. */ @@ -151,7 +191,8 @@ export function htmlModuleEntry(html) { * { * dir, pkg, deps, pm, ts, name, * framework: "next" | "nuxt" | "sveltekit" | "astro" | "angular" | "remix" | "react-router" | "cra" | "vite" | "webpack" | "html" | null, - * label, details: {...} + * label, details: {...}, + * refused?: why init will not edit this project (a bundler but no sign of a browser app) * } */ export function detectProject(cwd) { @@ -194,11 +235,67 @@ export function detectProject(cwd) { return { ...p, framework: "vite", label: `Vite + ${flavor}`, details: { flavor } }; } const bundler = ["webpack", "@rspack/core", "@rsbuild/core", "parcel", "esbuild", "rollup"].find((n) => has(n)); - if (bundler) return { ...p, framework: "webpack", label: `${bundler} project`, details: { bundler } }; + if (bundler) { + // a bundler alone does not make a browser app: Node servers, CLIs and libraries use them too + const lib = libraryEvidence(pkg); + if (lib) { + return { + ...p, + refused: + `${bundler} is a dependency, but this looks like a library or a CLI (${lib}), not an app: GenClass would start in ` + + `every app that imports it. init only edits apps; run it in the app that uses this package`, + }; + } + const evidence = browserEvidence(dir, pkg); + if (evidence) return { ...p, framework: "webpack", label: `${bundler} project`, details: { bundler, evidence } }; + return { + ...p, + refused: + `${bundler} is a dependency, but nothing shows this is a browser app (no index.html in the project, src/ or public/, ` + + `no UI framework such as react-dom or vue in dependencies, no HTML plugin or dev server). GenClass Runtime runs in the ` + + `browser, so init does not edit a Node server's or a library's entry file`, + }; + } if (htmlFiles(dir).length) return { ...p, framework: "html", label: "Plain HTML (no bundler)" }; return p; } +// UI libraries and browser-app tooling. Counted only from dependencies/devDependencies, not peerDependencies (a +// component library lists its framework as a peer). +const BROWSER_DEPS = [ + "react-dom", "vue", "svelte", "preact", "solid-js", "lit", "@angular/core", "jquery", "alpinejs", "@hotwired/turbo", + "@hotwired/stimulus", "html-webpack-plugin", "webpack-dev-server", "@rsbuild/core", "@rspack/dev-server", + "@web/dev-server", "esbuild-plugin-html", "@rollup/plugin-html", "rollup-plugin-serve", "rollup-plugin-livereload", +]; + +// UI frameworks a component library lists as peer dependencies. +const UI_PEERS = ["react", "react-dom", "vue", "svelte", "preact", "solid-js", "lit", "@angular/core"]; + +/** + * Why a bundler project's package.json looks like a published library or a CLI, or null: a UI framework as a peer + * dependency, or the fields packages publish ("exports", "module", "types", "bin"). Apps have none of them ("main" + * alone is npm init's default, so it does not count). + */ +export function libraryEvidence(pkg) { + const peer = UI_PEERS.find((n) => Object.prototype.hasOwnProperty.call(pkg?.peerDependencies ?? {}, n)); + if (peer) return `${peer} is a peer dependency`; + const field = ["exports", "module", "types", "typings", "bin"].find((f) => pkg?.[f] !== undefined); + return field ? `package.json has a "${field}" field` : null; +} + +/** Why a bundler project looks like a browser app ("index.html", "react-dom", ...), or null. */ +export function browserEvidence(dir, pkg) { + for (const f of ["index.html", "src/index.html", "public/index.html"]) if (isFile(join(dir, f))) return f; + const own = { ...(pkg?.devDependencies ?? {}), ...(pkg?.dependencies ?? {}) }; + const dep = BROWSER_DEPS.find((n) => Object.prototype.hasOwnProperty.call(own, n)); + if (dep) return dep; + // Parcel apps name their HTML entry: "source": "src/index.html" + const sources = [pkg?.source].flat().filter((x) => typeof x === "string"); + if (sources.some((x) => /\.html?$/i.test(x))) return "package.json source (HTML)"; + if (htmlFiles(dir).length) return "an .html page"; + return null; +} + /** Top-level .html files with a <head> (plain sites). */ export function htmlFiles(dir) { let names = []; diff --git a/packages/runtime/bin/lib/edit.mjs b/packages/runtime/bin/lib/edit.mjs index 55bae9e4..e61bb2bb 100644 --- a/packages/runtime/bin/lib/edit.mjs +++ b/packages/runtime/bin/lib/edit.mjs @@ -4,16 +4,12 @@ // - three inline forms, used only when the place to insert shares its line with other code (a one-line <head> or // <body>): `<GenClassInit />{/* genclass:inline */}`, `<script>... // genclass:inline</script>` (Astro) and // `<script ...></script><!-- genclass:inline -->` (HTML) -// `removeMarked` deletes exactly those (a marker line together with its line break), so a file init only added to -// comes back byte for byte. +// `planRemoval` deletes exactly those (a marked statement together with its line break), so a file init only added +// to comes back byte for byte, and refuses (reports a problem, deletes nothing there) when a marked line or block is +// not what init wrote. `switchMode` re-points the same marked code at another mode. export const MARK = "genclass:init"; export const MARK_INLINE = "genclass:inline"; -const INLINE_RES = [ - /<GenClassInit \/>\{\/\* genclass:inline \*\/\}/g, - /<script>(?:(?!<\/script>)[\s\S])*? \/\/ genclass:inline<\/script>/g, - /<script\b[^>]*><\/script><!-- genclass:inline -->/g, -]; export const eolOf = (text) => (text.includes("\r\n") ? "\r\n" : "\n"); @@ -109,33 +105,271 @@ export function indentUnit(text) { export const lineIndexAt = (text, offset) => text.slice(0, offset).split("\n").length - 1; export const linesOf = (text) => partsOf(text).map((p) => p.replace(/\r?\n$/, "")); -/** Removes every marker line, marker block and the inline JSX form. Returns the text without them. */ -export function removeMarked(text) { - let t = text; - for (const re of INLINE_RES) t = t.replace(re, ""); - const parts = partsOf(t); +// ------------------------------------------------------------------------------------------- removal +// +// `remove` deletes only what init wrote. A marked line is taken out only when, alone or together with the lines a +// formatter wrapped it onto (Prettier: `if (import.meta.env.DEV)\n import(...)...; // genclass:init`), it is one +// of the statements init writes (compared without whitespace, quote style, semicolons or trailing commas). A block +// is taken out only when its start and end markers pair up and everything between them is what init writes into +// the files it creates. Anything else (an edited line, code added inside a block, a lone start or end marker) is a +// problem: remove then changes nothing and says where. + +/** The import specifier for a mode: no mode -> "/auto" (observe, the runtime's default); else "/auto/<mode>". */ +export const AUTO = (mode) => (mode ? `@genclass/runtime/auto/${mode}` : "@genclass/runtime/auto"); + +const AUTO_SPEC = String.raw`"@genclass/runtime/auto(?:/(?:observe|guard|heal))?"`; +const DEVTOOLS_CALL = String.raw`import\("@genclass/runtime/devtools"\)\.then\(d=>d\.mountDevtools\(genclass\)\)`; +const COND = String.raw`[^;{}]+?`; +const IMPORT_AUTO = String.raw`import(?:genclassfrom)?${AUTO_SPEC};?`; +const DEV_LINE = String.raw`if\(${COND}\)${DEVTOOLS_CALL};?`; +// the same with braces (ESLint's `curly` fix) +const DEV_BLOCK = String.raw`if\(${COND}\)\{${DEVTOOLS_CALL};?\}`; +/** Statements init writes on one marked line (normalised, see norm()). */ +const LINE_RE = new RegExp( + "^(?:" + + [ + IMPORT_AUTO, + DEV_LINE, + DEV_BLOCK, + String.raw`import\{isDevModeasgenclassDevMode\}from"@angular/core";?`, + String.raw`import\{GenClassInit\}from"[^"]*genclass-init";?`, + String.raw`<GenClassInit/>`, + String.raw`<script[^<>]*></script>`, + String.raw`<script>${IMPORT_AUTO}(?:${DEV_LINE})?</script>`, + ].join("|") + + ")$", +); +/** What the files init creates hold between their start and end markers (normalised, comment lines dropped). */ +const BLOCK_RE = new RegExp( + "^(?:" + + [ + String.raw`"useclient";?`, + IMPORT_AUTO, + DEV_LINE, + DEV_BLOCK, + String.raw`importtype\{AppProps\}from"next/app";?`, + String.raw`exportfunctionGenClassInit\(\)\{returnnull;?\}`, + String.raw`exportdefaultdefineNuxtPlugin\(\(\)=>\{(?:${DEV_LINE}|${DEV_BLOCK})?\}\);?`, + String.raw`exportdefaultfunctionApp\(\{Component,pageProps\}(?::AppProps)?\)\{return\(?<Component\{\.\.\.pageProps\}/>\)?;?\}`, + ].join("|") + + ")*$", +); +// Inline forms (init puts them on a line shared with other code); whitespace a formatter adds between the element and +// its marker is taken out with them. `ok` checks the element is still what init wrote (an Astro <script> holds code). +const INLINE_SCRIPT_RE = new RegExp(String.raw`^<script>(?:${IMPORT_AUTO})(?:${DEV_LINE})?</script>$`); +const INLINE = [ + { re: /<GenClassInit\s*\/>\s*\{\s*\/\*\s*genclass:inline\s*\*\/\s*\}/g }, + { re: /<script>(?:(?!<\/script>)[\s\S])*?\/\/\s*genclass:inline\s*<\/script>/g, ok: (m) => INLINE_SCRIPT_RE.test(norm(m)) }, + { re: /<script\b[^>]*><\/script>\s*<!--\s*genclass:inline\s*-->/g }, +]; +const INLINE_RES = INLINE.map((x) => x.re); +// The only comment line init writes inside a block (planNext, the layout strategy's genclass-init component). +const BLOCK_COMMENT = /^\s*\/\/ Starts GenClass Runtime when this module loads in the browser \(on the server it is inert\)\.\s*$/; +const MAX_UP = 8; +const MAX_DOWN = 4; + +/** A statement compared without its marker, whitespace, quote style, trailing commas or arrow-parameter parens. */ +function norm(s) { + return s + .replace(/\{\s*\/\*\s*genclass:(?:init|inline)\s*\*\/\s*\}/g, "") + .replace(/<!--\s*genclass:(?:init|inline)\s*-->/g, "") + .replace(/\/\/\s*genclass:(?:init|inline)\b/g, "") + .replace(/\s+/g, "") + .replace(/'/g, '"') + .replace(/,(?=[)}\]])/g, "") + .replace(/\((\w+)\)=>/g, "$1=>"); +} + +const isStart = (l) => l.includes(`${MARK} start`); +const isEnd = (l) => l.includes(`${MARK} end`); + +/** + * The line ranges init wrote, in a text whose inline forms are already handled: { ranges: [[first, last]] (line + * indices, inclusive), problems: [{ line (1-based), reason }] }. + */ +function markedRanges(parts) { + const lines = parts.map((p) => p.replace(/\r?\n$/, "")); + const ranges = []; + const problems = []; + const taken = new Set(); + for (let i = 0; i < lines.length; i++) { + if (taken.has(i) || !lines[i].includes(MARK)) continue; + if (isEnd(lines[i]) && !isStart(lines[i])) { + problems.push({ line: i + 1, reason: `"${MARK} end" without a matching "${MARK} start" above it` }); + continue; + } + if (isStart(lines[i])) { + let e = i + 1; + while (e < lines.length && !lines[e].includes(MARK)) e++; + if (isEnd(lines[i]) || e >= lines.length || !isEnd(lines[e]) || isStart(lines[e])) { + problems.push({ line: i + 1, reason: `"${MARK} start" without its "${MARK} end" (or another marker inside the block)` }); + if (e < lines.length) taken.add(e); + continue; + } + const inner = lines.slice(i + 1, e).filter((l) => !BLOCK_COMMENT.test(l)); + if (!BLOCK_RE.test(norm(inner.join("\n")))) { + problems.push({ line: i + 1, reason: `the block init created (lines ${i + 1}-${e + 1}) was edited; code in it is not what init wrote` }); + } else ranges.push([i, e]); + for (let x = i; x <= e; x++) taken.add(x); + i = e; + continue; + } + let found = null; + for (let size = 1; size <= MAX_UP + MAX_DOWN + 1 && !found; size++) { + for (let up = Math.min(size - 1, MAX_UP); up >= 0 && !found; up--) { + const down = size - 1 - up; + if (down > MAX_DOWN) break; + const a = i - up; + const b = i + down; + if (a < 0 || b >= lines.length) continue; + let free = true; + for (let x = a; x <= b; x++) if (taken.has(x) || (x !== i && (isStart(lines[x]) || isEnd(lines[x])))) free = false; + if (free && LINE_RE.test(norm(lines.slice(a, b + 1).join("\n")))) found = [a, b]; + } + } + if (!found) { + problems.push({ line: i + 1, reason: `this line has the "${MARK}" marker but is not a statement init writes (edited?)` }); + continue; + } + ranges.push(found); + for (let x = found[0]; x <= found[1]; x++) taken.add(x); + } + return { ranges, problems }; +} + +/** + * What remove does to a file: { text, problems }. `text` is the file without init's lines, blocks and inline forms + * (marked lines it does not recognise stay); `problems` lists what it could not take out safely. + */ +export function planRemoval(text) { + const { lines: segs, problems } = stripInline(text); + const parts = segs.map((s) => s.text); + const marked = markedRanges(parts); + for (const p of marked.problems) problems.push({ line: segs[p.line - 1].line, reason: p.reason }); + const flagged = new Set(problems.map((p) => p.line)); + segs.forEach((s) => { + if (s.text.includes(MARK_INLINE) && !flagged.has(s.line)) problems.push({ line: s.line, reason: `the "${MARK_INLINE}" marker is not next to the element init added (edited?)` }); + }); + const drop = new Set(segs.flatMap((s, i) => (s.drop ? [i] : []))); + for (const [a, b] of marked.ranges) for (let x = a; x <= b; x++) drop.add(x); const kept = []; - let inBlock = false; for (let i = 0; i < parts.length; i++) { - const p = parts[i]; - const isStart = p.includes(`${MARK} start`); - const isEnd = p.includes(`${MARK} end`); - let drop = false; - if (inBlock) { - drop = true; - if (isEnd) inBlock = false; - } else if (isStart) { - drop = true; - inBlock = !isEnd; - } else if (p.includes(MARK)) drop = true; - if (!drop) { - kept.push(p); + if (!drop.has(i)) { + kept.push(parts[i]); continue; } // the last line had no line break: take the break before it instead - if (i === parts.length - 1 && !p.endsWith("\n") && kept.length) kept[kept.length - 1] = kept[kept.length - 1].replace(/\r?\n$/, ""); + if (i === parts.length - 1 && !parts[i].endsWith("\n") && kept.length) kept[kept.length - 1] = kept[kept.length - 1].replace(/\r?\n$/, ""); + } + problems.sort((x, y) => x.line - y.line); + return { text: kept.join(""), problems }; +} + +/** + * The text's lines with init's inline forms cut out: [{ text, line (1-based, in `text`), drop }]. A line holding only + * an inline form once it is cut (a formatter moved the element onto lines of its own) is dropped whole. An inline + * form that is no longer what init wrote stays, as a problem. + */ +function stripInline(text) { + const problems = []; + const cuts = []; + for (const { re, ok } of INLINE) { + for (const m of text.matchAll(re)) { + if (ok && !ok(m[0])) problems.push({ line: lineIndexAt(text, m.index) + 1, reason: `the element init added inline was edited; it is not what init wrote` }); + else cuts.push([m.index, m.index + m[0].length]); + } + } + cuts.sort((x, y) => x[0] - y[0]); + const parts = partsOf(text); + const starts = []; + let off = 0; + for (const p of parts) { + starts.push(off); + off += p.length; + } + const lineOf = (o) => { + let i = 0; + while (i + 1 < starts.length && starts[i + 1] <= o) i++; + return i; + }; + const lines = []; + let c = 0; + for (let i = 0; i < parts.length; ) { + let end = starts[i] + parts[i].length; + if (c >= cuts.length || cuts[c][0] >= end) { + lines.push({ text: parts[i], line: i + 1, drop: false }); + i++; + continue; + } + let j = i; + let pos = starts[i]; + let s = ""; + while (c < cuts.length && cuts[c][0] < end) { + s += text.slice(pos, cuts[c][0]); + pos = cuts[c][1]; + j = Math.max(j, lineOf(pos - 1)); + end = starts[j] + parts[j].length; + c++; + } + s += text.slice(pos, end); + lines.push({ text: s, line: i + 1, drop: s.trim() === "" }); + i = j + 1; + } + return { lines, problems }; +} + +/** The text without what init added (see planRemoval; unrecognised marked lines are kept). */ +export const removeMarked = (text) => planRemoval(text).text; + +// ------------------------------------------------------------------------------------------ mode switch + +const SPEC_RE = /@genclass\/runtime\/auto(?:\/(observe|guard|heal))?(?=["'])/g; +const SCRIPT_SRC_RE = /<script\b[^>]*\bsrc\s*=[^>]*>/gi; +const DATA_MODE_RE = /\s+data-mode\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i; + +/** Modes the init-written code in a segment starts with (no mode written = observe, the runtime's default). */ +function modesIn(seg) { + const modes = []; + for (const m of seg.matchAll(SPEC_RE)) modes.push(m[1] ?? "observe"); + for (const m of seg.matchAll(SCRIPT_SRC_RE)) { + const dm = DATA_MODE_RE.exec(m[0]); + modes.push((dm ? dm[1] ?? dm[2] ?? dm[3] : "observe").toLowerCase()); + } + return modes; +} + +function rewriteMode(seg, mode) { + return seg.replace(SPEC_RE, AUTO(mode)).replace(SCRIPT_SRC_RE, (tag) => { + const attr = `data-mode="${mode}"`; + if (DATA_MODE_RE.test(tag)) return tag.replace(DATA_MODE_RE, (m) => m.replace(/data-mode[\s\S]*$/i, attr)); + const dev = /\s+data-devtools\b/i.exec(tag); + if (dev) return `${tag.slice(0, dev.index)} ${attr}${tag.slice(dev.index)}`; + const close = /\s*\/?>$/.exec(tag); + return `${tag.slice(0, close.index)} ${attr}${tag.slice(close.index)}`; + }); +} + +/** + * Re-points what init added (the /auto import or the script tag's data-mode) at `mode`, in place. Returns the new + * text, or the same text when everything init added already runs in that mode. Code outside init's markers is + * never touched. + */ +export function switchMode(text, mode) { + const segs = []; + let t = text; + for (const re of INLINE_RES) t = t.replace(re, (m) => (segs.push(m), m)); + const parts = partsOf(t); + const { ranges } = markedRanges(parts); + for (const [a, b] of ranges) segs.push(parts.slice(a, b + 1).join("")); + const modes = segs.flatMap(modesIn); + if (!modes.length || modes.every((m) => m === mode)) return text; + for (const re of INLINE_RES) t = t.replace(re, (m) => rewriteMode(m, mode)); + const out = partsOf(t); + for (const [a, b] of ranges) { + out[a] = rewriteMode(out.slice(a, b + 1).join(""), mode); + for (let x = a + 1; x <= b; x++) out[x] = ""; } - return kept.join(""); + return out.join(""); } export const hasMarker = (text) => text.includes(MARK) || text.includes(MARK_INLINE); diff --git a/packages/runtime/bin/lib/init.mjs b/packages/runtime/bin/lib/init.mjs index 8eb4fb23..10c86fe4 100644 --- a/packages/runtime/bin/lib/init.mjs +++ b/packages/runtime/bin/lib/init.mjs @@ -2,15 +2,16 @@ // // init: detects the project, installs @genclass/runtime, adds the auto import as the first statement of the entry // file (plus a dev-only devtools line), shows the diff and asks before writing. Every added line or created file -// carries the marker `genclass:init`, so `remove` can take out exactly that and nothing else. Running init twice -// changes nothing. +// carries the marker `genclass:init`, so `remove` can take out exactly that and nothing else (and refuses when a +// marked line or block was edited). Running init twice changes nothing; running it again with another --mode +// switches the marked import (or the script tag's data-mode) to that mode in place. import { spawnSync } from "node:child_process"; import { mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; -import { detectProject, detectState, htmlFiles, isDir, isFile, readText, walkSources } from "./detect.mjs"; -import { MARK, hasMarker, removeMarked } from "./edit.mjs"; +import { detectProject, detectState, htmlFiles, isDir, isFile, readText, walkSkipped, walkSources } from "./detect.mjs"; +import { MARK, hasMarker, planRemoval, removeMarked, switchMode } from "./edit.mjs"; import { AUTO, planInit, scriptTag } from "./plan.mjs"; import { banner, c, confirm, err, out, printChange, row, sym } from "./ui.mjs"; @@ -31,11 +32,12 @@ export const USAGE = `Usage: genclass-runtime remove [--yes] [--dry-run] [--keep-package] [--cwd <dir>] init finds your framework, installs ${PKG}, adds one import to your entry file (and a dev-only devtools - line), shows the diff and asks before writing. Running it again changes nothing. -remove takes out exactly what init added (every line marked "${MARK}") and uninstalls the package if - nothing else uses it. + line), shows the diff and asks before writing. Running it again changes nothing; with another + --mode it switches the import init added to that mode. +remove takes out exactly what init added (the lines and blocks marked "${MARK}"; it changes nothing if + one of them was edited) and uninstalls the package if nothing else imports it. - --mode <m> observe (never changes anything), guard (default) or heal + --mode <m> observe (default: reports, never changes anything), guard or heal --yes, -y apply without asking --dry-run show what would change; write nothing --no-install do not run the package manager @@ -43,7 +45,9 @@ remove takes out exactly what init added (every line marked "${MARK}") and uni --keep-package remove: leave ${PKG} installed --cwd <dir> the project directory (default: the current directory) --from <spec> install ${PKG} from this spec (a version, tag or tarball path) - --cdn <url> plain HTML: the script URL (default: jsDelivr, this version)`; + --cdn <url> plain HTML: the script URL (default: jsDelivr, this version, with an SRI hash; other + URLs get no hash) + --no-sri plain HTML: no integrity attribute`; class UsageError extends Error {} @@ -234,10 +238,55 @@ function printRecommendations(recs) { // ------------------------------------------------------------------------------------------------ init +/** init --mode <m> on a project init already set up in another mode: rewrite the marked code in place. */ +async function switchModes(o, project, changes, install, spec, cwd) { + row("Mode", `${o.mode} ${c.gray("(switching what init added)")}`); + out(); + out(` ${c.bold("Changes")}`); + out(); + for (const ch of changes) printChange({ ...ch, file: ch.rel }); + if (install) out(` ${c.bold("Install")} ${c.cyan(installArgs(project.pm, spec).flat().join(" "))}`); + out(); + if (o.dryRun) { + out(` ${c.gray("Dry run: nothing was written.")}`); + out(); + return 0; + } + if (!o.yes) { + const ok = await confirm(`Switch to ${o.mode} mode?`); + if (ok === null) { + out(` Not a terminal, so nothing was written. Re-run with ${c.bold("--yes")} to apply.`); + out(); + return 1; + } + if (!ok) { + out(` Nothing changed.`); + out(); + return 0; + } + out(); + } + if (install && !spawn(...installArgs(project.pm, spec), cwd)) { + err(` ${c.red(sym.cross)} Installing ${PKG} failed, so no files were changed.`); + return 1; + } + for (const ch of changes) writeChange(ch); + out(` ${c.green(sym.ok)} ${c.bold(`GenClass Runtime now starts in ${o.mode} mode.`)} ${c.gray(`(${changes.map((ch) => ch.rel).join(", ")})`)}`); + out(); + return 0; +} + async function init(o) { const cwd = projectDir(o); banner("init"); const project = detectProject(cwd); + if (project.refused) { + out(` ${c.yellow(sym.warn)} Not adding GenClass to ${c.bold(cwd)}: ${project.refused}.`); + out(` If this is a browser app, add the import as the first line of its browser entry file yourself:`); + out(` ${c.cyan(`import "${AUTO()}";`)}`); + out(); + return 1; + } if (!project.framework) { out(` ${c.yellow(sym.warn)} Could not recognise the project in ${c.bold(cwd)}.`); if (project.pkg?.workspaces) out(` It looks like a monorepo root: run init inside your app's directory (or pass --cwd apps/web).`); @@ -257,6 +306,17 @@ async function init(o) { if (marked.length || manualRefs(files).length) { const where = (marked.length ? marked : manualRefs(files)).map((f) => posix(relative(cwd, f))); row("Setup", marked.length ? `already added by init in ${where.join(", ")}` : `GenClass is already imported in ${where.join(", ")}; init leaves your code alone`); + // `init --mode <m>` again: switch what init added to that mode, in place (GenClass.init() keeps the first + // runtime's options, so a later GenClass.init({ mode }) in app code would not change it) + const switches = o.mode + ? marked + .map((f) => { + const before = readText(f) ?? ""; + return { file: f, rel: posix(relative(cwd, f)), kind: "modify", before, after: switchMode(before, o.mode) }; + }) + .filter((ch) => ch.after !== ch.before) + : []; + if (switches.length) return switchModes(o, project, switches, install, spec, cwd); if (!install) { out(); out(` ${c.green("Nothing to do.")}${marked.length ? ` To take it out: ${c.cyan(`${CMD} remove`)}` : ""}`); @@ -286,7 +346,7 @@ async function init(o) { return 1; } row("Entry", posix(relative(cwd, plan.entry))); - row("Mode", `${o.mode ?? "guard"}${o.mode ? "" : c.gray(" (default; --mode observe never changes anything)")}`); + row("Mode", `${o.mode ?? "observe"}${o.mode ? "" : c.gray(" (default: reports only, never changes anything; --mode guard lets it act)")}`); out(); out(` ${c.bold("Changes")}`); out(); @@ -351,21 +411,41 @@ async function remove(o) { const files = walkSources(cwd); const changes = []; const after = new Map(); + const problems = []; for (const f of files) { const before = readText(f); if (before === null || !hasMarker(before)) continue; - const next = removeMarked(before); + const { text: next, problems: p } = planRemoval(before); + for (const x of p) problems.push(`${posix(relative(cwd, f))}:${x.line}: ${x.reason}`); if (next === before) continue; const rel = posix(relative(cwd, f)); const created = before.includes(`${MARK} start`) && next.trim() === ""; changes.push(created ? { file: f, rel, kind: "delete", before, after: "" } : { file: f, rel, kind: "modify", before, after: next }); after.set(f, created ? "" : next); } - const stillUsed = files.some((f) => REF_RE.test(after.has(f) ? after.get(f) : readText(f) ?? "")); - const uninstall = !!project.pkg && project.has(PKG) && !o.keepPackage && !stillUsed && !o.noInstall; + if (problems.length) { + out(` ${c.yellow(sym.warn)} Not removing anything: these places carry init's marker but are not what init wrote, so`); + out(` taking them out could delete your code or leave half a statement behind.`); + for (const p of problems) out(` ${sym.dot} ${p}`); + out(); + out(` Restore them to what init wrote, or delete GenClass's lines there by hand (and their "${MARK}" markers), then`); + out(` run ${c.cyan(`${CMD} remove`)} again.`); + out(); + return 1; + } + const users = files.filter((f) => REF_RE.test(after.has(f) ? after.get(f) : readText(f) ?? "")); + // also the places walkSources skips (.storybook, tmp, out, build, ...): read only, never edited + const hasPkg = !!project.pkg && project.has(PKG); + if (hasPkg && !users.length && !o.keepPackage) for (const f of walkSkipped(cwd)) if (REF_RE.test(readText(f) ?? "")) users.push(f); + const stillUsed = users.length > 0; + const uninstall = hasPkg && !o.keepPackage && !stillUsed && !o.noInstall; + + const keptBecause = () => + out(` ${c.gray(`${PKG} stays installed${stillUsed ? `: still imported in ${users.slice(0, 10).map((f) => posix(relative(cwd, f))).join(", ")}${users.length > 10 ? ` and ${users.length - 10} more` : ""}` : ""}.`)}`); if (!changes.length && !uninstall) { out(` Nothing to remove: no lines marked ${c.bold(MARK)} in ${c.bold(cwd)}.`); + if (hasPkg && stillUsed) keptBecause(); out(); return 0; } @@ -375,7 +455,7 @@ async function remove(o) { for (const ch of changes) printChange({ ...ch, file: ch.rel }); } if (uninstall) out(` ${c.bold("Uninstall")} ${c.cyan(uninstallArgs(project.pm).flat().join(" "))}`); - else if (project.pkg && project.has(PKG)) out(` ${c.gray(`${PKG} stays installed${stillUsed ? " (your code still uses it)" : ""}.`)}`); + else if (hasPkg) keptBecause(); out(); if (o.dryRun) { out(` ${c.gray("Dry run: nothing was written.")}`); diff --git a/packages/runtime/bin/lib/plan.mjs b/packages/runtime/bin/lib/plan.mjs index 8f0895ea..ba84faca 100644 --- a/packages/runtime/bin/lib/plan.mjs +++ b/packages/runtime/bin/lib/plan.mjs @@ -5,9 +5,9 @@ import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { dirname, join, relative, sep } from "node:path"; import { firstFile, htmlFiles, htmlModuleEntry, isDir, isFile, readText, walkSources, withExts } from "./detect.mjs"; -import { MARK, MARK_INLINE, appendEnd, bodyTagEnd, codeStyle, indentOf, indentUnit, insertLineAt, insertTop, lineIndexAt, linesOf } from "./edit.mjs"; +import { AUTO, MARK, MARK_INLINE, appendEnd, bodyTagEnd, codeStyle, indentOf, indentUnit, insertLineAt, insertTop, lineIndexAt, linesOf } from "./edit.mjs"; -export const AUTO = (mode) => (mode && mode !== "guard" ? `@genclass/runtime/auto/${mode}` : "@genclass/runtime/auto"); +export { AUTO }; const HEADER = `${MARK} start: GenClass Runtime, added by \`npx @genclass/runtime init\` (\`npx @genclass/runtime remove\` takes it out)`; const mark = (line) => `${line} // ${MARK}`; const posix = (p) => p.split(sep).join("/"); @@ -78,9 +78,22 @@ function planCra(p, o) { return { entry, changes: [editEntry(entry, { ...o, devCond: DEV.node })] }; } +// Modules only Node code imports: a server framework, Node's built-ins, server-side rendering. +const NODE_IMPORT_RE = + /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)(['"])(node:[\w/]+|express|fastify|koa|@hapi\/hapi|@nestjs\/core|restify|polka|http|https|http2|net|tls|dgram|fs|fs\/promises|child_process|cluster|worker_threads|react-dom\/server|vue\/server-renderer)\1/m; + +/** The Node-only module a file imports (it is a server or tool entry, not a browser entry), or null. */ +export function nodeOnlyImport(text) { + const m = NODE_IMPORT_RE.exec(text ?? ""); + return m ? m[2] : null; +} + function planWebpack(p, o) { const entry = firstFile(p.dir, [...withExts("src/main"), ...withExts("src/index"), ...withExts("src/app"), ...withExts("index")]); if (!entry) return { changes: [], manual: "no entry file found (src/main.*, src/index.*, index.*)" }; + // a bundler project with a page can still be a server (express serving public/index.html): never edit its entry + const nodeOnly = nodeOnlyImport(readText(entry)); + if (nodeOnly) return { changes: [], manual: `${posix(relative(p.dir, entry))} imports "${nodeOnly}", so it is Node code (a server?), not the browser entry` }; // webpack, rspack/rsbuild and parcel replace process.env.NODE_ENV; other bundlers may not define `process` const knowsNodeEnv = ["webpack", "@rspack/core", "@rsbuild/core", "parcel"].includes(p.details.bundler); const devtools = o.devtools && knowsNodeEnv; @@ -225,12 +238,20 @@ function planAstro(p, o) { return { entry: targets[0], changes }; } -/** SRI for our own copy of the script, when the URL serves that file. */ -function integrityFor(url, pkgDir) { - const name = /genclass\.global(\.min)?\.js(?:[?#].*)?$/.exec(url); - if (!name) return null; +export const cdnUrl = (version, min = true) => `https://cdn.jsdelivr.net/npm/@genclass/runtime@${version}/dist/genclass.global${min ? ".min" : ""}.js`; +const unpkgUrl = (version, min) => `https://unpkg.com/@genclass/runtime@${version}/dist/genclass.global${min ? ".min" : ""}.js`; + +/** + * SRI for the script URL, only when the URL is exactly this version's file on jsDelivr or unpkg, whose bytes are the + * CLI's own copy. Any other URL (another version, @latest, no version, a mirror, a self-hosted copy) may serve + * different bytes, and a wrong hash makes the browser refuse the script: no integrity attribute then. + */ +export function integrityFor(url, pkgDir, version) { + if (!/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(String(version))) return null; + const min = [true, false].find((m) => url === cdnUrl(version, m) || url === unpkgUrl(version, m)); + if (min === undefined) return null; try { - const buf = readFileSync(join(pkgDir, "dist", `genclass.global${name[1] ?? ""}.js`)); + const buf = readFileSync(join(pkgDir, "dist", `genclass.global${min ? ".min" : ""}.js`)); return `sha384-${createHash("sha384").update(buf).digest("base64")}`; } catch { return null; @@ -238,11 +259,12 @@ function integrityFor(url, pkgDir) { } export function scriptTag(o, pkgDir, version) { - const url = o.cdn || `https://cdn.jsdelivr.net/npm/@genclass/runtime@${version}/dist/genclass.global.min.js`; - const sri = o.sri === false ? null : integrityFor(url, pkgDir); + const url = o.cdn || cdnUrl(version); + const sri = o.sri === false ? null : integrityFor(url, pkgDir, version); const attrs = [`src="${url}"`]; if (sri) attrs.push(`integrity="${sri}"`, 'crossorigin="anonymous"'); - if (o.mode && o.mode !== "guard") attrs.push(`data-mode="${o.mode}"`); + // no data-mode: observe, the runtime's default + if (o.mode) attrs.push(`data-mode="${o.mode}"`); if (o.devtools) attrs.push('data-devtools="local"'); return `<script ${attrs.join(" ")}></script>`; } @@ -270,7 +292,15 @@ function planHtml(p, o, ctx) { } changes.push({ file: f, kind: "modify", before, after }); } - return { entry: files[0], changes, notes: [] }; + const notes = []; + if (o.sri !== false && !/ integrity="/.test(tag)) { + notes.push( + o.cdn + ? `No integrity (SRI) attribute: --cdn is not ${cdnUrl(ctx.version)}, so the CLI cannot know the bytes it serves. Pin a version and add the hash yourself if you want one.` + : `No integrity (SRI) attribute: this copy of the CLI has no built dist/genclass.global.min.js to hash.`, + ); + } + return { entry: files[0], changes, notes }; } const PLANNERS = { diff --git a/packages/runtime/package.json b/packages/runtime/package.json index e3a4731e..c8d9c655 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -28,11 +28,24 @@ "./dist/genclass.global.js", "./dist/genclass.global.min.js", "./dist/cdn/*.js", + "./dist/worker.js", "./src/model/worker.ts" ], "main": "./dist/index.js", "module": "./dist/index.js", "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "auto": ["./dist/auto.d.ts"], + "auto/observe": ["./dist/auto/observe.d.ts"], + "auto/guard": ["./dist/auto/guard.d.ts"], + "auto/heal": ["./dist/auto/heal.d.ts"], + "react": ["./dist/adapters/react.d.ts"], + "redux": ["./dist/adapters/redux.d.ts"], + "zustand": ["./dist/adapters/zustand.d.ts"], + "devtools": ["./dist/devtools/index.d.ts"] + } + }, "unpkg": "./dist/genclass.global.min.js", "jsdelivr": "./dist/genclass.global.min.js", "exports": { diff --git a/packages/runtime/src/cdn/config.ts b/packages/runtime/src/cdn/config.ts index 6c352f6e..2d4a766a 100644 --- a/packages/runtime/src/cdn/config.ts +++ b/packages/runtime/src/cdn/config.ts @@ -10,6 +10,19 @@ // Keys of the meta tag and data attributes: mode, model (a model directory URL, or "off"), device, preload, ort // (onnxruntime-web wasm directory), worker, report, debug, triage, devtools (bare / true, "local" = only on // localhost, false, or a corner such as "bottom-left"). +// +// Trust: every `<meta name="genclass">` in the document is read (head or body, first to last), and its keys can set +// the mode and the model and onnxruntime-web URLs. That is deliberate (no build step needed), but on a page that +// renders untrusted HTML able to contain <meta> tags, set those keys in window.GENCLASS_CONFIG (it wins over meta +// tags) or call GenClass.init(options) instead of using /auto or the script tag's automatic start. +// +// Remote code: an `integrity` attribute on the script tag covers that one file only. What it loads later at runtime +// (dist/cdn/worker.js, dist/cdn/ort-*.js, dist/devtools/index.js, onnxruntime-web's wasm and the model files) is +// fetched by URL without SRI (dynamic import() and module workers take no integrity option). On +// jsDelivr/unpkg those URLs are pinned to the tag's own version (immutable there), so pin the tag's version +// (`@genclass/runtime@x.y.z`, as `init` writes it), never @latest, in production. For full control, self-host: +// `data-base` (this package's dist/), `data-ort` (onnxruntime-web's dist/) and `data-model` (a model directory), plus +// a CSP `script-src` / `worker-src` / `connect-src` limited to those origins. import type { DevtoolsOptions, DevtoolsPosition } from "../devtools/index.js"; import type { InitOptions, Mode, ModelOptions } from "../types.js"; diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 52954511..572f779d 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -91,11 +91,25 @@ function killSwitch(g: Record<string, unknown>): string | null { } let current: Runtime | null = null; +let warnedIgnored: Runtime | null = null; export const GenClass = { - /** Install GenClass (idempotent: a second call returns the same runtime). Never throws. */ + /** + * Install GenClass (idempotent: a second call returns the same runtime and ignores its options; asking for another + * mode then logs one warning). Never throws. + */ init(options: InitOptions = {}): Runtime { - if (current) return current; + if (current) { + if (options.mode && options.mode !== current.mode && warnedIgnored !== current) { + warnedIgnored = current; + const g = globalThis as unknown as Record<string, unknown>; + (g.console as Console | undefined)?.warn?.( + `[GenClass] Already running in ${current.mode} mode (started by @genclass/runtime/auto, the script tag or an earlier GenClass.init()), so this call's options are ignored. ` + + `To change the mode: GenClass.runtime.setMode("${options.mode}"), or re-run \`npx @genclass/runtime init --mode ${options.mode}\`.`, + ); + } + return current; + } try { return initUnsafe(options); } catch (e) { diff --git a/packages/runtime/test/install/INSTALL-README-SNIPPET.md b/packages/runtime/test/install/INSTALL-README-SNIPPET.md index 3154c002..a0c2f3c1 100644 --- a/packages/runtime/test/install/INSTALL-README-SNIPPET.md +++ b/packages/runtime/test/install/INSTALL-README-SNIPPET.md @@ -10,16 +10,26 @@ npx @genclass/runtime init It finds your framework and package manager, installs `@genclass/runtime`, and adds one import as the first line of your entry file, plus a line that loads the devtools overlay in development only. It shows the diff and asks before -writing anything. Running it again changes nothing. +writing anything. Running it again changes nothing; running it with another `--mode` switches the import it added to +that mode. It sets up observe mode (reports only, never changes anything) unless you pass `--mode guard` or `--mode heal`. ```bash npx @genclass/runtime init --yes # no questions -npx @genclass/runtime init --mode observe # report only, never change anything +npx @genclass/runtime init --mode guard # let GenClass act (also: --mode heal); again later to switch npx @genclass/runtime init --dry-run # show the diff, write nothing -npx @genclass/runtime remove # undo exactly what init added +npx @genclass/runtime remove # undo exactly what init added (refuses if you edited those lines) ``` -Other flags: `--no-install` (don't run the package manager), `--no-devtools`, `--cwd <dir>`. +Other flags: `--no-install` (don't run the package manager), `--no-devtools`, `--cwd <dir>`, `--cdn <url>` and +`--no-sri` (plain HTML), `remove --keep-package`. + +`init` only edits browser apps: a project whose only build tool is esbuild, rollup, parcel or webpack needs an +`index.html`, a UI framework such as `react-dom` or `vue`, or an HTML plugin / dev server, else `init` stops and says +why (Node servers and libraries are left alone). It also stops for a package that looks like a library (a UI +framework as a peer dependency, or an `exports`, `module`, `types` or `bin` field) and for an entry file that imports +Node-only modules (`express`, `node:*`, `react-dom/server`, ...). `remove` takes out a line a formatter rewrapped as a whole; if a +line or block `init` marked was edited, it changes nothing and lists where. It keeps the package installed while +anything still imports it, including in dot-folders such as `.storybook`, `tmp`, `out` or `build`. What it adds, by framework: @@ -32,7 +42,7 @@ What it adds, by framework: | SvelteKit | `src/hooks.client.ts` | | Nuxt 3 and 4 | a new `plugins/genclass.client.ts` | | Astro | a `<script>` line in each layout's `<head>` | -| Plain HTML | a `<script>` tag first in each page's `<head>` (jsDelivr, pinned version, with SRI) | +| Plain HTML | a `<script>` tag first in each page's `<head>` (jsDelivr, pinned version, with SRI; a `--cdn` URL gets no SRI hash) | In a Vite app the result is: @@ -54,8 +64,9 @@ import "@genclass/runtime/auto"; // first line of your entry file `/auto` starts GenClass while your entry's imports load, so stores created at import time already see `GenClass.runtime`. It is a no-op on the server (SSR). `import rt from "@genclass/runtime/auto"` also gives you the -runtime. For a mode other than guard, import `@genclass/runtime/auto/observe` (or `/auto/heal`). Configure it from the -page if you like: +runtime. It observes (the default); to let GenClass act, import `@genclass/runtime/auto/guard` (or `/auto/heal`). The +subpaths have types under every TypeScript `moduleResolution`, `"node"` included. Configure it from the page if you +like: ```html <meta name="genclass" content="mode=observe, devtools=local"> @@ -74,7 +85,7 @@ demand from the same CDN, at the same version as the tag, also when the URL has | attribute | | |---|---| -| `data-mode` | `observe`, `guard` (default) or `heal` | +| `data-mode` | `observe` (default), `guard` or `heal` | | `data-devtools` | show the overlay; `="local"`: only on localhost, `*.localhost`, `*.local`, `*.test` | | `data-model` | your model directory (`npx @genclass/runtime fetch-model public/genclass-model`), or `off` | | `data-ort` | onnxruntime-web's `dist/` directory, if you self-host its wasm | @@ -83,3 +94,8 @@ demand from the same CDN, at the same version as the tag, also when the URL has The same keys work in `<meta name="genclass" content="...">`, and `window.GENCLASS_CONFIG` takes any `init` option. In every form, `?genclass=off` in the URL turns GenClass off. + +Every `<meta name="genclass">` in the document is read; on a page that renders untrusted HTML, set the options in +`window.GENCLASS_CONFIG` (it wins) or call `GenClass.init(options)` instead. The tag's SRI hash covers that file only: +the worker, ONNX Runtime and overlay it loads later come from the same CDN version without one, so pin a version (as +`init` does) or self-host with `data-base`, `data-ort` and `data-model`. diff --git a/packages/runtime/test/install/cli.test.ts b/packages/runtime/test/install/cli.test.ts index 1c7e4b93..63555a6e 100644 --- a/packages/runtime/test/install/cli.test.ts +++ b/packages/runtime/test/install/cli.test.ts @@ -6,14 +6,26 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, wr import { tmpdir } from "node:os"; import { dirname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { afterAll, describe, expect, it } from "vitest"; +import { afterAll, describe, expect, it, vi } from "vitest"; // @ts-expect-error plain ESM module without types -import { appendEnd, bodyTagEnd, codeStyle, insertTop, removeMarked, topOffset } from "../../bin/lib/edit.mjs"; +import { appendEnd, bodyTagEnd, codeStyle, insertTop, planRemoval, removeMarked, switchMode, topOffset } from "../../bin/lib/edit.mjs"; +// @ts-expect-error plain ESM module without types +import { integrityFor, nodeOnlyImport, scriptTag } from "../../bin/lib/plan.mjs"; +// @ts-expect-error plain ESM module without types +import { libraryEvidence } from "../../bin/lib/detect.mjs"; import { assetBase } from "../../src/cdn/global.js"; +import { GenClass } from "../../src/index.js"; import { devtoolsOptions, fromDataset, fromPairs, isKilled, isLocalHost, mergeConfig, parsePairs, readMetaConfig } from "../../src/cdn/config.js"; const HERE = dirname(fileURLToPath(import.meta.url)); const BIN = resolve(HERE, "..", "..", "bin", "genclass-runtime.mjs"); +const PKG_JSON = JSON.parse(readFileSync(resolve(HERE, "..", "..", "package.json"), "utf8")) as { + version: string; + exports: Record<string, string | { types?: string; import?: string }>; + typesVersions?: Record<string, Record<string, string[]>>; + sideEffects: string[]; + files: string[]; +}; const roots: string[] = []; afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); @@ -189,7 +201,7 @@ describe("init / remove on fixture projects", () => { const rr = roundTrip(project({ "package.json": pkg({ "@react-router/dev": "^7" }), "app/entry.client.tsx": `import { HydratedRouter } from "react-router/dom";\n`, "app/root.tsx": "x\n" })); expect(rr["app/entry.client.tsx"].split("\n")[0]).toContain("@genclass/runtime/auto"); expect(rr["app/root.tsx"]).toBe("x\n"); - const wp = roundTrip(project({ "package.json": pkg({ webpack: "^5" }), "src/index.ts": `"use strict";\nconsole.log(1);\n` })); + const wp = roundTrip(project({ "package.json": pkg({ webpack: "^5", "html-webpack-plugin": "^5" }), "src/index.ts": `"use strict";\nconsole.log(1);\n` })); expect(wp["src/index.ts"].split("\n")[1]).toContain("@genclass/runtime/auto"); }); @@ -237,13 +249,15 @@ describe("edit helpers", () => { expect(insertTop(`'use client'\nexport {}\n`, ["a // genclass:init"])).toBe(`'use client'\na // genclass:init\nexport {}\n`); }); it("appendEnd / removeMarked restore files with and without a final newline, and CRLF", () => { + const top = `import genclass from "@genclass/runtime/auto"; // genclass:init`; + const dev = `if (import.meta.env.DEV) import("@genclass/runtime/devtools").then((d) => d.mountDevtools(genclass)); // genclass:init`; for (const t of ["a\nb\n", "a\nb", "a\r\nb\r\n", "a\r\nb", ""]) { - const added = appendEnd(insertTop(t, ["x // genclass:init"]), ["y // genclass:init"]); + const added = appendEnd(insertTop(t, [top]), [dev]); expect(removeMarked(added)).toBe(t); } }); it("removeMarked drops blocks and inline forms", () => { - expect(removeMarked(`// genclass:init start\na\nb\n// genclass:init end\nkeep\n`)).toBe(`keep\n`); + expect(removeMarked(`// genclass:init start: x\nimport genclass from "@genclass/runtime/auto";\n\nexport default defineNuxtPlugin(() => {});\n// genclass:init end\nkeep\n`)).toBe(`keep\n`); expect(removeMarked(`<body><GenClassInit />{/* genclass:inline */}{children}</body>\n`)).toBe(`<body>{children}</body>\n`); }); it("codeStyle and bodyTagEnd", () => { @@ -289,3 +303,328 @@ describe("page config", () => { expect(assetBase(null)).toBe(`https://cdn.jsdelivr.net/npm/@genclass/runtime@${v}/dist/`); }); }); + +const VITE_MAIN = `import { createApp } from "vue";\nimport App from "./App.vue";\n\ncreateApp(App).mount("#app");\n`; +const viteVue = () => project({ "package.json": pkg({ vue: "^3", vite: "^7" }), "index.html": VITE_HTML.replace("main.tsx", "main.js"), "src/main.js": VITE_MAIN }); +const PAGE = `<!doctype html>\n<html>\n<head>\n <title>x\n\n\n\n`; + +describe("modes: observe is the default; --mode guard / heal install those modes", () => { + it("init without --mode writes the plain /auto import (observe) and says so", () => { + const dir = viteVue(); + const r = cli(dir, "init", "--yes", "--no-install", "--no-devtools"); + expect(r.code, r.out).toBe(0); + expect(r.out).toMatch(/Mode\s+observe \(default/); + expect(readFileSync(join(dir, "src/main.js"), "utf8").split("\n")[0]).toBe(`import "@genclass/runtime/auto"; // genclass:init`); + }); + + it("--mode guard / heal write /auto/guard, /auto/heal and data-mode on the script tag", () => { + for (const mode of ["guard", "heal"]) { + const after = roundTrip(viteVue(), "--mode", mode); + expect(after["src/main.js"].split("\n")[0]).toBe(`import genclass from "@genclass/runtime/auto/${mode}"; // genclass:init`); + const html = roundTrip(project({ "index.html": PAGE }), "--mode", mode, "--no-sri"); + expect(html["index.html"]).toContain(` data-mode="${mode}" data-devtools="local"> `); + } + const plain = roundTrip(project({ "index.html": PAGE }), "--no-sri"); + expect(plain["index.html"]).not.toContain("data-mode"); + }); + + it("the default script URL is pinned to package.json's version", () => { + const r = cli(project({ "index.html": PAGE }), "init", "--dry-run"); + expect(r.out).toContain(`https://cdn.jsdelivr.net/npm/@genclass/runtime@${PKG_JSON.version}/dist/genclass.global.min.js`); + }); + + it("USAGE documents observe as the default", () => { + const r = cli(project({}), "init", "--help"); + expect(r.out).toContain("observe (default"); + expect(r.out).not.toContain("guard (default)"); + }); + + it("init again with another --mode switches the marked import in place; the same mode changes nothing", () => { + const dir = viteVue(); + const before = snapshot(dir); + expect(cli(dir, "init", "--yes", "--no-install").code).toBe(0); + const main = () => readFileSync(join(dir, "src/main.js"), "utf8"); + const plainObserve = main(); + expect(cli(dir, "init", "--yes", "--no-install", "--mode", "observe").out).toContain("Nothing to do"); + expect(main()).toBe(plainObserve); + const g = cli(dir, "init", "--yes", "--no-install", "--mode", "guard"); + expect(g.code, g.out).toBe(0); + expect(g.out).not.toContain("Nothing to do"); + expect(main().split("\n")[0]).toBe(`import genclass from "@genclass/runtime/auto/guard"; // genclass:init`); + expect(main().replace("/auto/guard", "/auto")).toBe(plainObserve); + expect(cli(dir, "init", "--yes", "--no-install", "--mode", "guard").out).toContain("Nothing to do"); + // a dry run shows the switch and writes nothing + expect(cli(dir, "init", "--dry-run", "--no-install", "--mode", "heal").out).toContain("auto/heal"); + expect(main()).toContain("/auto/guard"); + expect(cli(dir, "init", "--yes", "--no-install", "--mode", "heal").code).toBe(0); + expect(main()).toContain(`"@genclass/runtime/auto/heal"`); + expect(cli(dir, "remove", "--yes").code).toBe(0); + expect(snapshot(dir)).toEqual(before); + + const site = project({ "index.html": PAGE }); + expect(cli(site, "init", "--yes", "--no-sri").code).toBe(0); + expect(cli(site, "init", "--yes", "--mode", "heal").code).toBe(0); + expect(readFileSync(join(site, "index.html"), "utf8")).toContain(`data-mode="heal" data-devtools="local"> `); + expect(cli(site, "remove", "--yes").code).toBe(0); + expect(readFileSync(join(site, "index.html"), "utf8")).toBe(PAGE); + }); + + it("a later GenClass.init({ mode }) that cannot apply says so once (it used to be ignored silently)", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + const rt = GenClass.init({ model: false, report: "silent" }); + expect(rt.mode).toBe("observe"); + expect(GenClass.init({ mode: "guard" })).toBe(rt); + expect(GenClass.init({ mode: "guard" })).toBe(rt); + expect(GenClass.init({ mode: "observe" })).toBe(rt); + expect(GenClass.init()).toBe(rt); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toMatch(/Already running in observe mode.*setMode\("guard"\).*init --mode guard/); + } finally { + GenClass.destroy(); + warn.mockRestore(); + } + }); + + it("switchMode only touches code inside init's markers", () => { + const t = `import "@genclass/runtime/auto"; // genclass:init\nimport rt from "@genclass/runtime/auto/heal";\n`; + expect(switchMode(t, "guard")).toBe(`import "@genclass/runtime/auto/guard"; // genclass:init\nimport rt from "@genclass/runtime/auto/heal";\n`); + expect(switchMode(t, "observe")).toBe(t); + expect(switchMode(``, "heal")).toBe(``); + }); +}); + +describe("remove after a formatter rewrapped init's lines", () => { + it("takes out a Prettier-wrapped devtools statement whole (byte for byte)", () => { + const dir = viteVue(); + const before = snapshot(dir); + expect(cli(dir, "init", "--yes", "--no-install").code).toBe(0); + const f = join(dir, "src/main.js"); + const added = readFileSync(f, "utf8"); + const wrapped = added.replace( + `if (import.meta.env.DEV) import("@genclass/runtime/devtools").then((d) => d.mountDevtools(genclass)); // genclass:init`, + `if (import.meta.env.DEV)\n import("@genclass/runtime/devtools").then((d) =>\n d.mountDevtools(genclass),\n ); // genclass:init`, + ); + expect(wrapped).not.toBe(added); + writeFileSync(f, wrapped); + const r = cli(dir, "remove", "--yes"); + expect(r.code, r.out).toBe(0); + expect(snapshot(dir)).toEqual(before); + }); + + it("handles wrapped imports, single quotes, no semicolons and arrowParens: avoid", () => { + const t = `import genclass from '@genclass/runtime/auto' // genclass:init\nimport {\n isDevMode as genclassDevMode,\n} from '@angular/core' // genclass:init\nbootstrap()\nif (genclassDevMode())\n import('@genclass/runtime/devtools').then(d => d.mountDevtools(genclass)) // genclass:init\n`; + expect(planRemoval(t)).toEqual({ text: `bootstrap()\n`, problems: [] }); + }); + + it("an ESLint curly fix (braces), alone or then wrapped by Prettier", () => { + const one = `x();\nif (import.meta.env.DEV) { import("@genclass/runtime/devtools").then((d) => d.mountDevtools(genclass)); } // genclass:init\n`; + expect(planRemoval(one)).toEqual({ text: `x();\n`, problems: [] }); + const wrapped = `x();\nif (import.meta.env.DEV) {\n import("@genclass/runtime/devtools").then((d) => d.mountDevtools(genclass));\n} // genclass:init\ny();\n`; + expect(planRemoval(wrapped)).toEqual({ text: `x();\ny();\n`, problems: [] }); + }); + + it("an inline form a formatter split onto lines of its own leaves no blank line behind", () => { + const jsx = ` \n \n {/* genclass:inline */}\n {children}\n \n`; + expect(planRemoval(jsx)).toEqual({ text: ` \n {children}\n \n`, problems: [] }); + const html = `\n \n \n \n One\n \n\n`; + expect(planRemoval(html)).toEqual({ text: `\n \n One\n \n\n`, problems: [] }); + // still on a line with other code: only the element goes + expect(planRemoval(`a`).text).toBe(`a`); + }); + + it("a multi-line script tag whose marker comment moved to its own line", () => { + const t = `\n \n \n x\n\n`; + expect(planRemoval(t)).toEqual({ text: `\n x\n\n`, problems: [] }); + }); +}); + +describe("remove never deletes code init did not write", () => { + it("refuses (and changes nothing) when code was added inside a file init created", () => { + const dir = project({ "package.json": pkg({ "@sveltejs/kit": "^2" }), "src/routes/+page.svelte": "x\n" }); + expect(cli(dir, "init", "--yes", "--no-install").code).toBe(0); + const f = join(dir, "src/hooks.client.js"); + const edited = readFileSync(f, "utf8").replace(`import genclass from "@genclass/runtime/auto";\n`, `import genclass from "@genclass/runtime/auto";\nexport const handleError = () => {};\n`); + writeFileSync(f, edited); + const snap = snapshot(dir); + const r = cli(dir, "remove", "--yes"); + expect(r.code).toBe(1); + expect(r.out).toContain("Not removing anything"); + expect(r.out).toContain("src/hooks.client.js:1"); + expect(snapshot(dir)).toEqual(snap); + }); + + it("refuses when a block's end marker is gone, or a marked line is not init's", () => { + const lost = project({ "package.json": pkg({ "@sveltejs/kit": "^2" }), "src/routes/+page.svelte": "x\n" }); + expect(cli(lost, "init", "--yes", "--no-install").code).toBe(0); + const f = join(lost, "src/hooks.client.js"); + writeFileSync(f, readFileSync(f, "utf8").replace(/\/\/ genclass:init end\n/, "") + `export const handleError = () => {};\n`); + const snap = snapshot(lost); + const r = cli(lost, "remove", "--yes"); + expect(r.code).toBe(1); + expect(r.out).toContain("without its"); + expect(snapshot(lost)).toEqual(snap); + + const mention = project({ "package.json": pkg({ vite: "^7" }), "index.html": VITE_HTML.replace("main.tsx", "main.js"), "src/main.js": `start(); // genclass:init is documented in the README\n` }); + const r2 = cli(mention, "remove", "--yes"); + expect(r2.code).toBe(1); + expect(readFileSync(join(mention, "src/main.js"), "utf8")).toBe(`start(); // genclass:init is documented in the README\n`); + expect(planRemoval(`// genclass:init end\nx();\n`).problems).toHaveLength(1); + }); + + it("keeps code added after the block of a file init created (the file stays, holding only that code)", () => { + const dir = project({ "package.json": pkg({ "@sveltejs/kit": "^2" }), "src/routes/+page.svelte": "x\n" }); + expect(cli(dir, "init", "--yes", "--no-install").code).toBe(0); + const f = join(dir, "src/hooks.client.js"); + writeFileSync(f, readFileSync(f, "utf8") + `export const handleError = () => {};\n`); + const r = cli(dir, "remove", "--yes"); + expect(r.code, r.out).toBe(0); + expect(readFileSync(f, "utf8")).toBe(`export const handleError = () => {};\n`); + }); + + it("an edited inline \n`; + const a = planRemoval(astro); + expect(a.text).toBe(astro); + expect(a.problems).toEqual([{ line: 1, reason: expect.stringContaining("edited") }]); + const ok = `x\n`; + expect(planRemoval(ok)).toEqual({ text: `x\n`, problems: [] }); + const block = `// genclass:init start: x\n// GenClass: our team's note\nimport genclass from "@genclass/runtime/auto";\n// genclass:init end\n`; + expect(planRemoval(block).text).toBe(block); + expect(planRemoval(block).problems).toHaveLength(1); + for (const line of [`foo(); import "@genclass/runtime/auto"; // genclass:init\n`, `const x = foo(\n import("@genclass/runtime/auto"), // genclass:init\n);\n`]) { + expect(planRemoval(line).text).toBe(line); + expect(planRemoval(line).problems).toHaveLength(1); + } + }); +}); + +describe("remove keeps the package while anything still imports it", () => { + it("looks in dot-folders and other skipped folders (read-only) before uninstalling", () => { + const files = { + "package.json": pkg({ vue: "^3", vite: "^7", "@genclass/runtime": "^0.1.0" }), + "index.html": VITE_HTML.replace("main.tsx", "main.js"), + "src/main.js": VITE_MAIN, + }; + const clean = project(files); + expect(cli(clean, "init", "--yes", "--no-install").code).toBe(0); + const r1 = cli(clean, "remove", "--dry-run"); + expect(r1.out).toContain("Uninstall"); + for (const extra of [".storybook/preview.ts", "tmp/demo.ts", "build/check.mjs"]) { + const dir = project({ ...files, [extra]: `import { GenClass } from "@genclass/runtime";\nGenClass.init();\n` }); + expect(cli(dir, "init", "--yes", "--no-install").code).toBe(0); + const r = cli(dir, "remove", "--dry-run"); + expect(r.code, r.out).toBe(0); + expect(r.out).not.toContain("Uninstall"); + expect(r.out).toContain(`stays installed: still imported in ${extra}`); + expect(readFileSync(join(dir, extra), "utf8")).toContain("@genclass/runtime"); + } + }); +}); + +describe("init only edits browser apps", () => { + it("refuses a Node server or a library that merely lists a bundler", () => { + const server = project({ "package.json": pkg({ express: "^5" }, { devDependencies: { esbuild: "^0.25" } }), "src/index.ts": `import express from "express";\nexpress().listen(3000);\n` }); + const snap = snapshot(server); + const r = cli(server, "init", "--yes", "--no-install"); + expect(r.code).toBe(1); + expect(r.out).toContain("nothing shows this is a browser app"); + expect(snapshot(server)).toEqual(snap); + const lib = project({ "package.json": pkg({}, { peerDependencies: { react: ">=18" }, devDependencies: { rollup: "^4", react: "^19" } }), "src/index.ts": `export const Button = () => null;\n` }); + expect(cli(lib, "init", "--yes", "--no-install").code).toBe(1); + expect(readFileSync(join(lib, "src/index.ts"), "utf8")).toBe(`export const Button = () => null;\n`); + }); + + it("refuses a server that serves an index.html (its entry imports express) and a library with react-dom in devDependencies", () => { + const ssr = project({ + "package.json": pkg({ express: "^5", react: "^19", "react-dom": "^19" }, { devDependencies: { webpack: "^5" } }), + "public/index.html": PAGE, + "src/index.ts": `import express from "express";\nimport { renderToString } from "react-dom/server";\nexpress().use(express.static("public")).listen(3000);\n`, + }); + const snap = snapshot(ssr); + const r = cli(ssr, "init", "--yes", "--no-install"); + expect(r.code).toBe(1); + expect(r.out).toContain(`src/index.ts imports "express", so it is Node code`); + expect(snapshot(ssr)).toEqual(snap); + const lib = project({ + "package.json": pkg({}, { exports: { ".": "./dist/index.js" }, peerDependencies: { react: ">=18", "react-dom": ">=18" }, devDependencies: { rollup: "^4", react: "^19", "react-dom": "^19" } }), + "src/index.ts": `export { Button } from "./Button";\n`, + }); + const r2 = cli(lib, "init", "--yes", "--no-install"); + expect(r2.code).toBe(1); + expect(r2.out).toContain("looks like a library or a CLI (react is a peer dependency)"); + expect(readFileSync(join(lib, "src/index.ts"), "utf8")).toBe(`export { Button } from "./Button";\n`); + expect(libraryEvidence({ module: "dist/x.js", devDependencies: { "react-dom": "^19" } })).toBe(`package.json has a "module" field`); + expect(libraryEvidence({ main: "index.js", private: true })).toBeNull(); + expect(nodeOnlyImport(`import { readFile } from "node:fs/promises";`)).toBe("node:fs/promises"); + expect(nodeOnlyImport(`const http = require('http');`)).toBe("http"); + expect(nodeOnlyImport(`import { createRoot } from "react-dom/client";\nhistory.listen(() => {});`)).toBeNull(); + }); + + it("accepts a bundler project with an index.html or a UI framework", () => { + const withHtml = project({ "package.json": pkg({ esbuild: "^0.25" }), "public/index.html": PAGE, "src/index.ts": `console.log(1);\n` }); + expect(roundTrip(withHtml)["src/index.ts"].split("\n")[0]).toContain("@genclass/runtime/auto"); + const withReact = project({ "package.json": pkg({ rollup: "^4", "react-dom": "^19" }), "src/main.tsx": `console.log(1);\n` }); + expect(roundTrip(withReact)["src/main.tsx"].split("\n")[0]).toContain("@genclass/runtime/auto"); + }); +}); + +describe("SRI on the script tag", () => { + const pkgDir = () => project({ "dist/genclass.global.min.js": "min\n", "dist/genclass.global.js": "full\n" }); + it("only for exactly this version's file on jsDelivr / unpkg", () => { + const d = pkgDir(); + const v = "1.2.3-beta.0"; + expect(integrityFor(`https://cdn.jsdelivr.net/npm/@genclass/runtime@${v}/dist/genclass.global.min.js`, d, v)).toMatch(/^sha384-/); + expect(integrityFor(`https://unpkg.com/@genclass/runtime@${v}/dist/genclass.global.js`, d, v)).toMatch(/^sha384-/); + for (const url of [ + `https://cdn.jsdelivr.net/npm/@genclass/runtime@latest/dist/genclass.global.min.js`, + `https://cdn.jsdelivr.net/npm/@genclass/runtime@1.2.2/dist/genclass.global.min.js`, + `https://cdn.jsdelivr.net/npm/@genclass/runtime/dist/genclass.global.min.js`, + `https://static.example.test/genclass.global.min.js`, + `https://cdn.jsdelivr.net/npm/@genclass/runtime@${v}/dist/genclass.global.min.js?x=1`, + ]) { + expect(integrityFor(url, d, v), url).toBeNull(); + expect(scriptTag({ cdn: url }, d, v)).not.toContain("integrity"); + } + expect(scriptTag({}, d, v)).toContain(`integrity="sha384-`); + expect(scriptTag({}, d, "latest")).not.toContain("integrity"); + }); + it("init --cdn with another URL writes no integrity attribute and says so", () => { + const dir = project({ "index.html": PAGE }); + const r = cli(dir, "init", "--yes", "--cdn", "https://cdn.jsdelivr.net/npm/@genclass/runtime@latest/dist/genclass.global.min.js"); + expect(r.code, r.out).toBe(0); + expect(r.out).toContain("No integrity (SRI) attribute"); + expect(readFileSync(join(dir, "index.html"), "utf8")).not.toContain("integrity="); + }); +}); + +describe("package.json", () => { + it("typesVersions maps every subpath export with types (TypeScript moduleResolution node)", () => { + const map = PKG_JSON.typesVersions?.["*"] ?? {}; + for (const [key, v] of Object.entries(PKG_JSON.exports)) { + if (key === "." || typeof v !== "object" || !v.types) continue; + expect(map[key.slice(2)], key).toEqual([v.types]); + } + expect(Object.keys(map).length).toBeGreaterThanOrEqual(8); + for (const v of Object.values(PKG_JSON.exports)) if (typeof v === "object") for (const k of Object.keys(v)) expect(["types", "import"]).toContain(k); + }); + it("sideEffects names the published model worker, and every source file the build imports for its side effects", () => { + expect(PKG_JSON.sideEffects).toContain("./dist/worker.js"); + expect((PKG_JSON.exports["./worker"] as { import: string }).import).toBe("./dist/worker.js"); + for (const f of PKG_JSON.sideEffects) expect(/^\.\/(dist|src)\//.test(f), f).toBe(true); + // esbuild applies this package.json while tsup builds it: a bare `import "../model/worker.js"` (src/cdn/worker.ts) + // of a file missing here is dropped, and dist/cdn/worker.js would ship without the model worker + const SRC = resolve(HERE, "..", "..", "src"); + const bare: string[] = []; + const walk = (d: string) => { + for (const e of readdirSync(d)) { + const p = join(d, e); + if (statSync(p).isDirectory()) walk(p); + else if (p.endsWith(".ts")) for (const m of readFileSync(p, "utf8").matchAll(/^import\s+["'](\.[^"']+)["'];?\s*$/gm)) bare.push(`./${relative(resolve(SRC, ".."), resolve(dirname(p), m[1])).split("\\").join("/").replace(/\.js$/, ".ts")}`); + } + }; + walk(SRC); + expect(bare).toContain("./src/model/worker.ts"); + for (const f of bare) expect(PKG_JSON.sideEffects, f).toContain(f); + }); +}); From f4c4e5252b1c0fda9dc778a1f49fb0125bc8e2da Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 03:57:01 -0400 Subject: [PATCH 14/25] CLI: fetch-model defaults to @genclass/runtime-model@0.1.0 on jsDelivr (= DEFAULT_MODEL_BASE_URL) The GitHub release runtime-model-v0.1.0 that DEFAULT_FROM pointed at cannot be created (no write access to the repo's releases). The default --from is now https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/, the same files as the runtime's default model. Help text updated; cli.test.ts checks DEFAULT_FROM == DEFAULT_MODEL_BASE_URL and the help output. RELEASE.md: the GitHub release (B5) is optional; B6 verifies fetch-model with the default. Agent docs updated where they stated the old default. Co-Authored-By: Claude Opus 5.5 --- RELEASE.md | 17 ++++++++++------- docs/agents/extension-and-benchmarks.md | 2 +- docs/agents/glossary.md | 2 +- docs/agents/playbooks.md | 2 +- docs/agents/repo-map.md | 2 +- docs/agents/runtime/build-test-release.md | 4 ++-- docs/agents/runtime/model-host.md | 15 +++++++-------- docs/agents/runtime/public-api-and-lifecycle.md | 2 +- docs/agents/status-and-known-issues.md | 4 ++-- packages/runtime/bin/genclass-runtime.mjs | 13 +++++++++---- packages/runtime/test/install/cli.test.ts | 11 +++++++++++ 11 files changed, 46 insertions(+), 28 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index 24fd3fca..69a1c890 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -12,7 +12,7 @@ - The tree still says `0.1.0-alpha.1` (`packages/runtime/package.json`, `packages/genclass-runtime/package.json`). Bump before any build or pack (step C3). - **Order.** 1. Validate the `r17-v2a` export, with gate thresholds fitted (B0–B2). - 2. Publish `@genclass/runtime-model@0.1.0` and the GitHub release `runtime-model-v0.1.0` (B3–B6). + 2. Publish `@genclass/runtime-model@0.1.0` (B3, B4, B6). The GitHub release `runtime-model-v0.1.0` (B5) is optional: the CLI no longer defaults to it. 3. Run the demos eval: Off / Observe / Guard (B7). 4. Publish `@genclass/runtime@0.1.0-beta.0` and move `latest` to it (Part C). - **The model needs batch 6, which is not on this branch.** @@ -37,7 +37,7 @@ - `genclass-runtime` (unscoped alias): **404**, so the name is unregistered. - **The default model URL is pinned.** - `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. - - `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. + - `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` = the same jsDelivr directory (`fetch-model`'s default `--from`; `test/install/cli.test.ts` keeps the two equal). It used to be the GitHub release `runtime-model-v0.1.0`, which we cannot create (no write access to the repo's releases); the published `0.1.0-alpha.1` CLI still defaults to that release, so with alpha.1 pass `--from` explicitly. - npm versions are immutable, so **whatever is published as `@genclass/runtime-model@0.1.0` is what every default `GenClass.init()` loads, permanently.** That includes alpha.1, which is `latest` today: it starts loading the model the moment the package exists (in observe mode, so it only reports). - **Never publish a round-1 (`situation-v1`) model as `0.1.0`.** `packages/runtime/src/model/loader.ts` checks only the card format `genclass-runtime-model/1`, never a situation version. A v1 model would load into the v2 runtime without any error. - **npm 11 refuses to publish a prerelease without `--tag`.** npm 11.8.0 `lib/commands/publish.js` throws "You must specify a tag using --tag when publishing a prerelease version." A non-prerelease (`0.1.0`) needs no tag and becomes `latest`. @@ -224,7 +224,9 @@ npm publish genclass-runtime-model-0.1.0.tgz --access public - alpha.0 defaults to **guard**, holds store writes, and renders `situation-v1` text, which this model was not trained on. In apps still on alpha.0 it can act on that text. - Consider `npm deprecate @genclass/runtime@0.1.0-alpha.0 ""` **[user only]** before this publish. -### B5. GitHub release `runtime-model-v0.1.0` **[ask first; user's call]** +### B5. GitHub release `runtime-model-v0.1.0` **[optional; ask first; user's call]** + +Not needed by the CLI any more (`DEFAULT_FROM` is the jsDelivr directory). Only the published `0.1.0-alpha.1` CLI defaults to this release; it needs write access to the repo's releases. `fetch-model` resolves each card file as `new URL(file, from)`, so the assets must be the same six files, flat, with the card's names: @@ -245,9 +247,10 @@ curl -fsSI https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/mode curl -fsS https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json \ | diff - packages/runtime-model/files/model.json && echo "CDN card identical" # [agent] # [ask first: model downloads] into a scratch directory -node packages/runtime/bin/genclass-runtime.mjs fetch-model /gc-cdn --from https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/ +node packages/runtime/bin/genclass-runtime.mjs fetch-model /gc-cdn # default --from = DEFAULT_FROM = the jsDelivr directory node packages/runtime/bin/genclass-runtime.mjs info /gc-cdn -node packages/runtime/bin/genclass-runtime.mjs fetch-model /gc-gh # default --from = DEFAULT_FROM +# only if B5 was done: +node packages/runtime/bin/genclass-runtime.mjs fetch-model /gc-gh --from https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/ node packages/runtime/bin/genclass-runtime.mjs info /gc-gh ``` @@ -418,7 +421,7 @@ Update every place that lists `0.1.0-alpha.1` as latest or the model as unpublis - **Never commit `files/` or `*.tgz`.** Both are gitignored. Keep the export directory (and its sha256s) on the train VM. - **Lockfile.** A version bump, the alias's dependency or a new workspace changes `package-lock.json`. Commit it in the same commit. - **Dist-tags.** A prerelease without `--tag` is refused (npm 11). `npm dist-tag add` moves a tag without republishing. The README's commands resolve `latest`. -- **The default model URL is a contract.** `DEFAULT_MODEL_BASE_URL` (`@0.1.0/files/`) and `DEFAULT_FROM` (`runtime-model-v0.1.0`) are pinned. Changing either means a runtime release, and every older runtime keeps loading `0.1.0`. +- **The default model URL is a contract.** `DEFAULT_MODEL_BASE_URL` and `DEFAULT_FROM` (both `@genclass/runtime-model@0.1.0/files/` on jsDelivr) are pinned. Changing either means a runtime release, and every older runtime keeps loading `0.1.0`. - **2FA and accounts.** Agents never run `npm login`, handle tokens, or publish. Hand the user the exact command. - **Run policy.** On machines other than Mehar's 8 GB Mac, `npm ci`, `tsc`, `tsup`, vitest and `npm pack` are fine. Ask first before Playwright, `smoke.sh`, `test/install/run-all.sh`, model downloads, the demos eval, training, realapps, Azure, `git push`, `gh release` and `npm publish`. @@ -427,7 +430,7 @@ Update every place that lists `0.1.0-alpha.1` as latest or the model as unpublis | step | what proves it | |---|---| | B2 | `genclass-runtime info` exits 0; `vitest run test/model` with `GENCLASS_MODEL_DIR` (export fixtures); `ortweb_report_q8.json` with full argmax agreement; `meta.json` has `gate` | -| B6 | the CDN card is identical to the packed one; `fetch-model` from the CDN and from the GitHub release verifies every sha256 | +| B6 | the CDN card is identical to the packed one; `fetch-model` with the default `--from` (the CDN), and from the GitHub release if B5 was done, verifies every sha256 | | B7 | demos eval Off / Observe / Guard with no clean-run regressions | | C2 | the CI-equivalent run (375 passed + 14 skipped at f107013; re-measure after the merge), perf 4 passed, `npm pack --dry-run` file list | | C3 | the built global file contains only the new version | diff --git a/docs/agents/extension-and-benchmarks.md b/docs/agents/extension-and-benchmarks.md index 400ce695..c8c81fa2 100644 --- a/docs/agents/extension-and-benchmarks.md +++ b/docs/agents/extension-and-benchmarks.md @@ -9,7 +9,7 @@ ## TL;DR - **This whole area is adjacent/legacy relative to `@genclass/runtime`.** It is the pre-runtime GenClass project (the "jev-local" era): a voice-controlled MV3 Chrome extension (GenClass 0.1.0), the Python benchmark harnesses that compared the model with TypeSafe's hosted Jev, and the Azure/Mac ops scripts. `docs/runtime/CONTRACT.md` says "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." -- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it, and `realapps/README.md` runs the realapps build, debug runs and pilot generator through it with slot `real`, see [realapps.md](realapps.md); our CI and the lead's local checks on a 16 GB machine do not use it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh`, and (new since 654d822) `training/launch_student.sh`, `training/launch_t150.sh` and `training/launch_r68.sh`, plus the `training/README.md` recipes, to start multi-node torchrun jobs), `scripts/cluster_up.sh` (whose VNet/subnet/NSG/PPG/image/key settings `training/cluster_expand.sh` copies when it adds nodes) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the `runtime-model-v0.1.0` release of GenClass-lib (both 404 as of 2026-10-08: no situation-v2 model exists yet, and the situation-v1 R17-final1 does not match the v2 runtime; see [status-and-known-issues.md](status-and-known-issues.md)). The v0.1 extension model reads the extension's own `state` serialisation, not runtime situation text (v1 or v2), so it is useful only for engine/packer/loader mechanics, never for decision quality; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/realapps/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. +- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it, and `realapps/README.md` runs the realapps build, debug runs and pilot generator through it with slot `real`, see [realapps.md](realapps.md); our CI and the lead's local checks on a 16 GB machine do not use it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh`, and (new since 654d822) `training/launch_student.sh`, `training/launch_t150.sh` and `training/launch_r68.sh`, plus the `training/README.md` recipes, to start multi-node torchrun jobs), `scripts/cluster_up.sh` (whose VNet/subnet/NSG/PPG/image/key settings `training/cluster_expand.sh` copies when it adds nodes) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the same directory (until 2026-10-08 the `runtime-model-v0.1.0` release of GenClass-lib) (both 404 as of 2026-10-08: no situation-v2 model exists yet, and the situation-v1 R17-final1 does not match the v2 runtime; see [status-and-known-issues.md](status-and-known-issues.md)). The v0.1 extension model reads the extension's own `state` serialisation, not runtime situation text (v1 or v2), so it is useful only for engine/packer/loader mechanics, never for decision quality; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/realapps/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. - **Extension architecture:** service worker (`src/background/sw.js`: tabs, navigation, feature plumbing) + offscreen document "brain" (`src/offscreen/offscreen.js`: model, speech, decision loop) + content script (`src/content/content.js`: page observation, in-page actions, ad hiding) + side panel (`src/sidepanel/panel.js`: view + settings). Pure-JS decision logic lives in `src/core/`: `types`, `catalog`, `questions`, `state`, `spans`, `stream`, `policy`, `safety` and `controller` port the Python macOS harness `jev_local/harness/*`; `tokenizer`, `packer` and `engine` port `jev_local/engine/encoder/{tokenize_pack,engine,calibrate}.py` plus `jev_local/confidence.py`; `serialize` ports `jev_local/serialize.py`; `features`, `sites` and the numbered-pick/rescue code are GenClass-only additions. - **The model is asked typed questions** (choice / noul / score) about a `state` object (screen, focused element, recent actions, pending, transcript). Questions are block-isolated in the attention mask, so the extension asks in two exact stages (intent/complete/is_command/destructive first, then only the argument question the intent needs). - **Mid-sentence acting is safe** because of a consumed-prefix transcript cursor (`core/stream.js` -> `Stream`), stability gates (`core/policy.js` -> `evaluatePolicy`), deterministic safety rules plus spoken confirmation (`core/safety.js` -> `gate`), and a 3 actions/s rate limit. diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md index 58e4ae7f..70537cb2 100644 --- a/docs/agents/glossary.md +++ b/docs/agents/glossary.md @@ -106,7 +106,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **Decision Score (jevbench)**: `clip(1 − mean Brier / mean prior Brier, −1, 1)` per dataset. Code: `jev_local/bench/metrics.py` -> `decision_score`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **DecisionProvider**: The only seam between the runtime and a model: `{ status, ready(), evaluate(req), onStatus?(fn), dispose?() }`. Implemented by the model host, the test deciders, the sim's recording decider and `failedProvider`; passed as `options.decider`, which wins over `options.model` (`null` = no model). `evaluate` receives `EvaluateRequest { trigger, state, questions, priority?, subject?, timeoutMs? }`. Code: `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [model-io-contract](model-io-contract.md). - **decontamination stage 1 (benchmax)**: Name-level exclusion of training sources per track. Code: `jev_local/bench/registry.py` -> `is_excluded`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`, a planned release (OPEN_TASKS "Next": Model package, item 12 in the merged tree; release procedure in [RELEASE.md](../../RELEASE.md) Part B; no `runtime-model-v0.1.0` tag in the repo; the lead found it returns 404 on 2026-10-08), so pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, the same directory as `DEFAULT_MODEL_BASE_URL` (`test/install/cli.test.ts` keeps them equal). Until 2026-10-08 it was the GitHub release `runtime-model-v0.1.0`, which we cannot create (no write access to releases); the published `0.1.0-alpha.1` CLI still defaults to that release. It 404s until `@genclass/runtime-model@0.1.0` is on npm ([RELEASE.md](../../RELEASE.md) Part B), so until then pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). - **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published (npm 404 on 2026-10-08, and no situation-v2 model exists to publish), so a default `GenClass.init()` ends with model status `error` and only observes; since f3636b2 it is also in `observe` mode by default. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **defer (action)**: Guard-tier action of `mutation` and `delivery`, offered while the subject was deferred fewer than 2 times. Mutation: with `holdWrites: true`, wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies; with `holdWrites` off it is offered but only recorded (the write already applied). Delivery: offered only when related ops are in flight (same name outside the op's chain, or whose signatures wrote a matched store); hold the response or message, wait for them (`waitOps`), then decide again. A review finding: each delivery defer waits up to 10 s (`LONG_RUNNING_MS`), not the hold budget, so two defers can hold a response for 20 s, and on a push channel every later message waits behind it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`, `RuntimeImpl.runDelivery`, `RuntimeImpl.waitOps`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **delay (action)**: Guard-tier `request` action (fetch and XHR): wait `min(250 × 2^failStreak, 8000)` ms, where `failStreak` is the signature's current failure streak, then send. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). diff --git a/docs/agents/playbooks.md b/docs/agents/playbooks.md index ea008ee0..66631e8a 100644 --- a/docs/agents/playbooks.md +++ b/docs/agents/playbooks.md @@ -618,7 +618,7 @@ Sim typecheck and `SIM_RUNTIME=real npx vitest run` are light local checks (buil 1. Choose the model with the user (R17 default on every device per final round 1; R32 only if clearly better) and get its validated export directory (recipes 18, 30). 2. Put the directory under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@/files/` (`DEFAULT_MODEL_BASE_URL`). Check it: `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files` (card rules, hashes, `needs: shader-f16` on fp16). Never publish the round-1 `files/r17/` (situation-v1). 3. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, version, `files` including `files/`). It becomes a workspace automatically (`packages/*`), so run `npm install` at the root and commit the lockfile, or CI's `npm ci` fails. Confirm with `npm pack --dry-run` in that directory that `files/` is included. -4. The user publishes it (`npm publish --access public`) and attaches the same files to a GitHub release tagged `runtime-model-v` (the CLI's `DEFAULT_FROM`). +4. The user publishes it (`npm publish --access public`) and, optionally, attaches the same files to a GitHub release tagged `runtime-model-v` (the CLI's `DEFAULT_FROM` is the jsDelivr directory, so this is not required). 5. If the version is not 0.1.0, update `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`, then release the runtime (recipe 19). 6. Update `packages/runtime-model/MODEL_CARD.md` (it describes round 1), `docs/runtime/CONTRACT.md` §2/§10, `docs/runtime/API.md`, both READMEs' "Status", `docs/runtime/RESULTS.md`, `OPEN_TASKS.md`, `HANDOFF.md`. diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index b4e604d9..1749a180 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -905,7 +905,7 @@ Verified with `grep` at b435acb; rows touched by the merge and the two fixes re- | sha256 integrity / sha1 header keys | function | `packages/runtime/src/model/hash.ts` -> `sha256Hex`, `sha1Hex` | [model-host](runtime/model-host.md) | | Host <-> worker messages | type | `packages/runtime/src/model/protocol.ts` -> `ToWorker`, `FromWorker` | [model-host](runtime/model-host.md) | | `genclass-runtime fetch-model ` / `info ` | CLI | `packages/runtime/bin/genclass-runtime.mjs` -> `fetchModel`, `info` | [model-host](runtime/model-host.md) | -| CLI default source (release `runtime-model-v0.1.0`, 404) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | +| CLI default source (jsDelivr `@genclass/runtime-model@0.1.0/files/` = `DEFAULT_MODEL_BASE_URL`, 404 until published) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | ### Devtools overlay diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index dcd07643..db1bee18 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -389,7 +389,7 @@ Earlier pass (b435acb, fresh clone): `npm ci` OK from the committed lockfile (EB | `policy.holdWrites` | option | `false` (unset) | `src/types.ts` -> `PolicyOptions.holdWrites` | tests about held store writes pass `true` | | `MockRuntime.situationBudget()` | test | `2400` (was `3200`) | `test/browser/ui/mock-runtime.ts` | matches the v2 full budget | | `DEFAULT_MODEL_BASE_URL` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default model location = the unpublished package | -| CLI `DEFAULT_FROM` | const | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | default `fetch-model --from` (planned release) | +| CLI `DEFAULT_FROM` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (= `DEFAULT_MODEL_BASE_URL`) | `bin/genclass-runtime.mjs` | default `fetch-model --from` (404 until the model package is published) | | test env vars | env | `GENCLASS_MODEL_DIR`, `NODE_OPTIONS=--expose-gc`, `GENCLASS_BENCH_MODELS="name=dir,..."`, `GENCLASS_WEBGPU_VARIANTS=`, `GENCLASS_OFFLINE=1` | test files | see Tests | | `HAVE_MODEL` | test | `existsSync(/model.json)` | `test/browser/model-helpers.ts` | every model spec calls `test.skip(!HAVE_MODEL, ...)` | | `DEFAULT_CACHE_NAME` | const | `"genclass-runtime-v1"` | `src/model/loader.ts` | Cache Storage bucket; default of `window.GC.cacheKeys()` | @@ -549,7 +549,7 @@ Blocked on training: no situation-v2 model is ready to publish. The first one, ` 1. Put a model directory (card `genclass-runtime-model/1`: `model.json`, `-q8.onnx`, `-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`) under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `DEFAULT_MODEL_BASE_URL`. Check it with `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files`. 2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`), so run a root `npm install` and commit the lockfile change, or CI's `npm ci` fails. -3. Attach the same files to a GitHub release tagged `runtime-model-v0.1.0` (the CLI's `DEFAULT_FROM`). +3. Optionally attach the same files to a GitHub release tagged `runtime-model-v0.1.0` (only the published `0.1.0-alpha.1` CLI defaults to it; the CLI's `DEFAULT_FROM` is now the jsDelivr directory). 4. Rerun the demos with the trained model, then publish `@genclass/runtime@0.1.0` without a prerelease tag (user, 2FA). ### CI (`.github/workflows/ci.yml`) diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md index 1c771fe3..6d5ec5b6 100644 --- a/docs/agents/runtime/model-host.md +++ b/docs/agents/runtime/model-host.md @@ -24,7 +24,7 @@ - **No model exists for the current runtime, and none is published.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm (as of 2026-10-08). The only trained runtime model, R17-final1, was trained on `situation-v1` and lives only on the train VM / Mehar's Mac; it does **not** match the v2 runtime. The v2 model comes from the scaled program ([HANDOFF](../../../HANDOFF.md): 150M teacher -> distil R17/R32 -> DAgger -> EVAL -> `@genclass/runtime-model@0.1.0`). The card fetch therefore fails (HTTP 404), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). - **Status:** `off` -> `loading` (phases `card` / `download` / `runtime` / `session` / `warmup`) -> `ready` or `error`; `dispose()` -> `off`. See [Status lifecycle](#status-lifecycle-modelhoststatusstate). The runtime core reads only `state`, `device`, `threads`, `warmupMs`, `model`, `variant`, `loadMs` and `error` (the devtools overlay also shows `progress`); `status.latency` (p50/p90 of the last 20 evaluations) and `host.stats` are for tooling. - **Default mode `observe` (since f3636b2) still loads and consults the model.** `observe` permits no non-passive action, so nothing is ever held: every salient trigger, `delivery` included (since 054da38), is decided in the background (priority capped at 1, deadline 5 s), for detection and reports. A salient delivery is released to the app at once (`runDelivery` -> `deliveryHoldable` is false in `observe`), before any body read, and its background decision is no longer dropped as stale. Only `mode: "guard"`/`"heal"` can make the runtime wait for the host. -- **CLI** `genclass-runtime fetch-model ` / `info ` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is a 404 too, so pass `--from`. The file is committed executable (mode 100755, b435acb). The same binary now also has `init` / `remove` (project setup; `bin/lib/*`, owner INSTALL, not covered here) and runs as `npx @genclass/runtime `. A short-alias package `genclass-runtime` (`packages/genclass-runtime/cli.mjs`, which only imports this file; not on npm yet) is meant to make `npx genclass-runtime ` work without a local install. +- **CLI** `genclass-runtime fetch-model ` / `info ` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is the same jsDelivr directory as `DEFAULT_MODEL_BASE_URL`, a 404 too until the model package is published, so pass `--from` until then. The file is committed executable (mode 100755, b435acb). The same binary now also has `init` / `remove` (project setup; `bin/lib/*`, owner INSTALL, not covered here) and runs as `npx @genclass/runtime `. A short-alias package `genclass-runtime` (`packages/genclass-runtime/cli.mjs`, which only imports this file; not on npm yet) is meant to make `npx genclass-runtime ` work without a local install. ## Files @@ -433,7 +433,7 @@ No runtime model is published, and none exists yet for `situation-v2`. The npm p 6. Runtime: the console shows `[GenClass] Model unavailable (model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json); observing only.` (via `console.info`, only with `report: "console"`), and a `"status"` event fires. The devtools overlay shows "Model unavailable" with `observing only · ` (`packages/runtime/src/devtools/index.ts` -> `renderStatus`). 7. From then on `consultable()` is false. Every trigger and every delivery takes the passive action immediately; no situations, decisions or detections are produced, and nothing is held. Observers, tracing and baselines keep running. 8. `rt.ask()` / `rt.decide()` reject with `GenClassUnavailableError("error", "the model failed to load: ...")`. Exception: with `opts.timeoutMs` set, `ask` awaits `Promise.race([wait, to])` without wrapping, so the raw `ModelLoadError` propagates instead. The runtime caches its `ready` promise and has no public reload. Only a direct `createModelHost` user can call `host.load()` to retry. The next page load tries the card again. -9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` release is a 404 too, so pass `--from` explicitly. Only the v0.1 development model (`https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, whether it serves a CLI-readable `model.json` is unverified) and the situation-v1 R17-final1 export (train VM only) exist; neither is trained on `situation-v2`, so their decisions are not meaningful for this runtime. Use them to exercise the loading machinery, not to evaluate behaviour. +9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` (the same jsDelivr directory) is a 404 too, so pass `--from` explicitly. Only the v0.1 development model (`https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, whether it serves a CLI-readable `model.json` is unverified) and the situation-v1 R17-final1 export (train VM only) exist; neither is trained on `situation-v2`, so their decisions are not meaningful for this runtime. Use them to exercise the loading machinery, not to evaluate behaviour. ### CLI (`packages/runtime/bin/genclass-runtime.mjs`) @@ -444,7 +444,7 @@ genclass-runtime info - Flags: `--key value` or `--key=value`. `--force` and `--quiet` are booleans. `-h`/`--help` or no command prints usage. Unknown `--flags` are accepted silently (and consume the next argument as their value). Exit code 2 for a `UsageError` (unknown command, missing dir, flag without a value, variant not in the card), 1 for other errors (including a `--from` that is not an absolute URL, and any card error from the CLI's `parseCard`, which throws plain `Error`s) and for `info` finding missing or invalid files. - No environment variables are read. Files are processed sequentially. - **`fetch-model`** steps: - 1. `--from` defaults to `DEFAULT_FROM` = `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/`. A trailing slash is ensured. + 1. `--from` defaults to `DEFAULT_FROM` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (= `DEFAULT_MODEL_BASE_URL`; before 2026-10-08 the GitHub release `runtime-model-v0.1.0`, still the default of the published `0.1.0-alpha.1` CLI). A trailing slash is ensured. 2. `--variant` defaults to `all` and accepts a comma-separated list of card variant names. 3. Fetches `model.json` (Node `fetch`, `redirect:"follow"`, user-agent `genclass-runtime-cli`) and parses it with a JS copy of `parseCard`. 4. For the 3 role files and the chosen variants: a valid local copy is kept unless `--force` is given. A local copy is valid when it matches the card's sha256, or its size when the card has no hash. A card with neither always re-downloads. @@ -501,7 +501,7 @@ genclass-runtime info | `MAX_ARRAY_SEGMENTS` | number | 64 | `serialize.ts` | array state items before `[64:]` overflow | | `DEFAULT_NOUL_INSTR` / `DEFAULT_CHOICE_INSTR` / `DEFAULT_SCORE_INSTR` | string | `"Is the statement true of the state?"` / `"Which option best fits the state?"` / `"Which level best describes the state?"` | `serialize.ts` | header when instructions are empty | | `K_BUCKETS` / `BUCKET_CLAMP` | — | `[2,2],[3,5],[6,10],[11,30],[31,100],[101,255]` / `[0.5, 5.0]` | `calibrate.ts` | v2 calibration | -| CLI `DEFAULT_FROM` | string | `"https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/"` | `bin/genclass-runtime.mjs` | `fetch-model` source | +| CLI `DEFAULT_FROM` | string | `"https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/"` | `bin/genclass-runtime.mjs` | `fetch-model` source (= `DEFAULT_MODEL_BASE_URL`) | | Runtime-side (context only) | — | default mode `"observe"` (`runtime.ts`, `o.mode ?? "observe"`); `DeciderQueue` `PROVIDER_TIMEOUT_MS` 10_000, `MAX_QUEUE` 32, answer cache 64 entries / 30 s (`CACHE_MAX`, `CACHE_TTL`); `BACKGROUND_DEADLINE_MS` 5000; `LATE_REVERT_MS` 2000; hold budget `HOLD_MIN_MS`..`HOLD_MAX_MS` = 150..800 ms (fallback `HOLD_FALLBACK_MS` 300); `STATE_CHAR_BUDGET` 2400, `COMPACT_BUDGET` 1100, `MIN_BUDGET` 500 (`situation/serialize.ts`) | `decide/decider.ts`, `runtime.ts`, `decide/policy.ts`, `situation/serialize.ts` | see [decide-policy-actions.md](./decide-policy-actions.md), [learn-situation-triage.md](./learn-situation-triage.md) | Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` are typed on `InitOptions.model` (`ModelOptions` in `types.ts`). `makeHost` spreads the object into `createModelHost`, so other `ModelHostOptions` keys pass through at runtime but are not typed for `GenClass.init`. @@ -655,12 +655,11 @@ No test covers the default-URL 404 end-to-end, the CLI's `fetch-model` / `info`, Mismatches between docs and code (code wins): - **The default model is not published, and no model matches the runtime.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, but `packages/runtime-model/` has no `package.json` or `files/`, the npm package is a 404, and OPEN_TASKS "Next" (Model package `@genclass/runtime-model@0.1.0`) lists publishing as future work; see [RELEASE.md](../../../RELEASE.md). Result: observe-only (see the 404 flow above). The only trained export (R17-final1) is `situation-v1`; publishing it as-is would ship a model out of distribution for the v2 runtime. -- **Three different default model sources:** - - host: jsDelivr npm (`DEFAULT_MODEL_BASE_URL`); - - CLI: `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` (`DEFAULT_FROM`); +- **Two different default model sources:** + - host and CLI: jsDelivr npm (`DEFAULT_MODEL_BASE_URL`, and `DEFAULT_FROM` since 2026-10-08; before that the CLI defaulted to the GitHub release `runtime-model-v0.1.0`, which the published `0.1.0-alpha.1` CLI still does); - CONTRACT §10 and `src/model/README.md`: the dev v0.1 model at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. - `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. The `runtime-model-v0.1.0` release URL is a 404 (lead, 2026-10-08); OPEN_TASKS "Next" (Model package) lists the GitHub release as future work. + `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. That default is the jsDelivr directory, a 404 until `@genclass/runtime-model@0.1.0` is published; the `runtime-model-v0.1.0` release URL (alpha.1's default) is a 404 too and optional (RELEASE.md B5). - CONTRACT §10 says "the worker imports `onnxruntime-web/webgpu`". The code imports `onnxruntime-web/wasm` when no WebGPU plan exists, and `/webgpu` otherwise (worker and inline). The same staleness is in `src/model/README.md` "Bundling" ("`dist/worker.js` imports `onnxruntime-web/webgpu`"; "the inline fallback's `import("onnxruntime-web/webgpu")`"). - CONTRACT §2 and `docs/runtime/API.md` list only `baseUrl`, `device`, `worker` and `preload` for `model`. `ModelOptions` in `types.ts` also has `ortWasmPaths` and `cacheName`. Host-only options (`timeoutMs`, `maxQueue`, `maxThreads`, `helloTimeoutMs`, `loadStallMs`, `warmup`) are untyped through `init`. - CONTRACT §8 `DecisionProvider.evaluate(req)` lists `{trigger, state, questions}`. `EvaluateRequest` also has `priority`, `subject` (§13) and `timeoutMs`, which the host honours. diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md index f74a4619..94d2418b 100644 --- a/docs/agents/runtime/public-api-and-lifecycle.md +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -728,7 +728,7 @@ Untested in this scope (by unit tests): `startAuto` and the script tag's `instal | API.md shapes | `Situation` listed as `{ trigger, subject, state, questions, actions, salient, facts }`; `Op` without `meta` | `Situation` also has `compact` and `budget`; `Op` also has `meta` | `types.ts` -> `Situation`, `Op` | | API.md observers | "The DOM, fetch, XHR, WebSocket and timers are observed automatically" (packages/runtime/README.md now lists them all) | Also `eventsource` (batch 4), `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | | Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | -| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and the CLI's `DEFAULT_FROM` at the GitHub release `runtime-model-v0.1.0`; both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 12 | +| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and so does the CLI's `DEFAULT_FROM` (until 2026-10-08 the GitHub release `runtime-model-v0.1.0`); both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 12 | | npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from `mvp-v2` (806a296), is `latest` since 2026-10-08; procedure in [RELEASE.md](../../../RELEASE.md). alpha.1 in turn lacks everything after 806a296 (zero-code entries, 054da38, f107013). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | | Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | | `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index ff3dd09f..afd6f79b 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -238,7 +238,7 @@ model-provided gate thresholds, no-baseline stall fallback; tag `situation-v2.1` | `packages/runtime/package.json` `version` | `0.1.0-alpha.1` | **already published**: bump before building or packing the next release | | `packages/genclass-runtime/package.json` | `0.1.0-alpha.1`, dependency `@genclass/runtime` `0.1.0-alpha.1` | unpublished alias (no `genclass-runtime` on npm) | | `@genclass/runtime-model@0.1.0` | not published (404); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | -| GitHub release `runtime-model-v0.1.0` | no such tag in the repo; the CLI's default `--from` 404s (per the lead) | | +| GitHub release `runtime-model-v0.1.0` | no such tag in the repo (we have no write access to releases); no longer the CLI's default `--from` (now the jsDelivr directory, = `DEFAULT_MODEL_BASE_URL`), but still the published `0.1.0-alpha.1` CLI's | optional (RELEASE.md B5) | | v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** a runtime model; used by demos and model tests | | R17-final1 / R32-final1 | situation-v1; on the `train` VM (`~/gcl/train-out/final1/`) and Mehar's Mac (`packages/runtime-model/files/r17/`, gitignored) | baseline only; does not match the v2 runtime | | `r17-v2a`, `t150-v2a` | training runs on Azure (see TL;DR); r17-v2a's export is served from c09 by `v2_post.sh`, not published | first v2 student / teacher | @@ -377,7 +377,7 @@ Status-relevant values only; the subsystem docs list the rest. | default mode | `"observe"` | `runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | no actions unless `mode: "guard"`/`"heal"`, `?genclass=guard`, or `setMode` | | test-harness mode | `"guard"` | `test/helpers.ts` -> `setup` | CORE tests exercise interventions; `setup({ mode: undefined })` gives the product default | | `DEFAULT_MODEL_BASE_URL` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | unpublished → status `error`, observe only | -| `DEFAULT_FROM` | `https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/` | `bin/genclass-runtime.mjs` | `fetch-model` default source; 404 | +| `DEFAULT_FROM` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `bin/genclass-runtime.mjs` | `fetch-model` default source (= `DEFAULT_MODEL_BASE_URL`); 404 until the model package is published | | `STATE_CHAR_BUDGET` | 2400 (was 3200 in v1) | `situation/serialize.ts` | full situation budget (≈ 1,000 tokens at the measured 2.4 chars/token) | | `COMPACT_BUDGET` / `COMPACT_QUESTIONS_BUDGET` | 1100 / 1400 | `situation/serialize.ts` / `situation/questions.ts` | section-limit floor / bare-label questions | | auto situation budget | webgpu and unknown device 2,400; wasm `1000 + round((threads − 1) × 1000 / 3)`, threads clamped 1–4; × `budgetScale` (× 0.8 per `max_tokens_exceeded`, floor 0.5) | `RuntimeImpl.situationBudget` | device sizing; a numeric `situation.budget` wins | diff --git a/packages/runtime/bin/genclass-runtime.mjs b/packages/runtime/bin/genclass-runtime.mjs index 8c76fa12..f4fc04c4 100755 --- a/packages/runtime/bin/genclass-runtime.mjs +++ b/packages/runtime/bin/genclass-runtime.mjs @@ -9,7 +9,8 @@ // Download a GenClass model directory (model.json + model files) so an app can self-host it: // GenClass.init({ model: { baseUrl: "/genclass-model/" } }). Follows redirects (GitHub release URLs work), // verifies sizes and sha256, skips files that are already present and valid, and writes a model.json that -// lists exactly the downloaded files with their sizes and hashes. +// lists exactly the downloaded files with their sizes and hashes. Default --from: @genclass/runtime-model@0.1.0 +// on jsDelivr (https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/), the runtime's default model. // genclass-runtime info // Show the model card of a directory, verify every file it lists, and check each variant's ONNX graph against // the card rule "any fp16 tensor -> needs: shader-f16" (WebGPU without shader-f16 cannot run fp16 tensors). @@ -21,7 +22,9 @@ import { dirname, join, resolve, sep } from "node:path"; import { Readable, Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; -const DEFAULT_FROM = "https://github.com/daybot-solutions-inc/GenClass-lib/releases/download/runtime-model-v0.1.0/"; +// The npm package @genclass/runtime-model@0.1.0 served by jsDelivr: the same files as the runtime's default model +// (src/model/host.ts -> DEFAULT_MODEL_BASE_URL; test/install/cli.test.ts checks they stay equal). +const DEFAULT_FROM = "https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/"; const CARD_FORMAT = "genclass-runtime-model/1"; const ROLES = ["tokenizer", "calibration", "meta"]; @@ -33,8 +36,10 @@ const USAGE = `Usage: init sets GenClass up in the current project (shows the diff and asks first); remove undoes it (\`genclass-runtime init --help\` for details). -fetch-model downloads a GenClass model directory for self-hosting (default --from ${DEFAULT_FROM}, -default --variant all). Serve and point the runtime at it: GenClass.init({ model: { baseUrl: "/genclass-model/" } }).`; +fetch-model downloads a GenClass model directory for self-hosting (default --variant all). The default --from is +@genclass/runtime-model@0.1.0 on npm via jsDelivr, the runtime's own default model: + ${DEFAULT_FROM} +Serve and point the runtime at it: GenClass.init({ model: { baseUrl: "/genclass-model/" } }).`; class UsageError extends Error {} diff --git a/packages/runtime/test/install/cli.test.ts b/packages/runtime/test/install/cli.test.ts index 63555a6e..e26135c2 100644 --- a/packages/runtime/test/install/cli.test.ts +++ b/packages/runtime/test/install/cli.test.ts @@ -15,6 +15,7 @@ import { integrityFor, nodeOnlyImport, scriptTag } from "../../bin/lib/plan.mjs" import { libraryEvidence } from "../../bin/lib/detect.mjs"; import { assetBase } from "../../src/cdn/global.js"; import { GenClass } from "../../src/index.js"; +import { DEFAULT_MODEL_BASE_URL } from "../../src/model/host.js"; import { devtoolsOptions, fromDataset, fromPairs, isKilled, isLocalHost, mergeConfig, parsePairs, readMetaConfig } from "../../src/cdn/config.js"; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -333,6 +334,16 @@ describe("modes: observe is the default; --mode guard / heal install those modes expect(r.out).toContain(`https://cdn.jsdelivr.net/npm/@genclass/runtime@${PKG_JSON.version}/dist/genclass.global.min.js`); }); + it("fetch-model's default --from is the runtime's default model directory (npm via jsDelivr), not a GitHub release", () => { + const src = readFileSync(BIN, "utf8"); + expect(src.match(/^const DEFAULT_FROM = "([^"]+)";$/m)?.[1]).toBe(DEFAULT_MODEL_BASE_URL); + expect(DEFAULT_MODEL_BASE_URL).toBe("https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/"); + const r = cli(project({}), "--help"); + expect(r.code).toBe(0); + expect(r.out).toContain(DEFAULT_MODEL_BASE_URL); + expect(r.out).not.toContain("releases/download"); + }); + it("USAGE documents observe as the default", () => { const r = cli(project({}), "init", "--help"); expect(r.out).toContain("observe (default"); From ba11126f1cf8cc1cda212f90588a0861f54256b2 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 03:57:25 -0400 Subject: [PATCH 15/25] runtime-model: package @genclass/runtime-model packages/runtime-model/package.json (0.1.0, files/ + MODEL_CARD.md, public) and the root lockfile entry for the new workspace (npm install --package-lock-only). Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 9 ++++++++ packages/runtime-model/package.json | 33 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 packages/runtime-model/package.json diff --git a/package-lock.json b/package-lock.json index 287d8976..233b4a71 100644 --- a/package-lock.json +++ b/package-lock.json @@ -508,6 +508,10 @@ "resolved": "packages/runtime", "link": true }, + "node_modules/@genclass/runtime-model": { + "resolved": "packages/runtime-model", + "link": true + }, "node_modules/@genclass/sim": { "resolved": "sim", "link": true @@ -3200,6 +3204,11 @@ } } }, + "packages/runtime-model": { + "name": "@genclass/runtime-model", + "version": "0.1.0", + "license": "Apache-2.0" + }, "sim": { "name": "@genclass/sim", "version": "0.0.0", diff --git a/packages/runtime-model/package.json b/packages/runtime-model/package.json new file mode 100644 index 00000000..0e0c0e57 --- /dev/null +++ b/packages/runtime-model/package.json @@ -0,0 +1,33 @@ +{ + "name": "@genclass/runtime-model", + "version": "0.1.0", + "description": "R17 situation-v2 runtime model for @genclass/runtime: ONNX q8 (WASM) + fp16 (WebGPU) exports, tokenizer, calibration and gates. A data package, served from jsDelivr.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/daybot-solutions-inc/GenClass-lib.git", + "directory": "packages/runtime-model" + }, + "homepage": "https://github.com/daybot-solutions-inc/GenClass-lib/tree/main/packages/runtime-model#readme", + "bugs": { + "url": "https://github.com/daybot-solutions-inc/GenClass-lib/issues" + }, + "keywords": [ + "genclass", + "onnx", + "onnxruntime-web", + "wasm", + "webgpu", + "model", + "encoder", + "runtime", + "self-healing" + ], + "files": [ + "files/", + "MODEL_CARD.md" + ], + "publishConfig": { + "access": "public" + } +} From bcbee89afb1a8221d068374b42beb7864227f9cf Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 09:15:34 -0400 Subject: [PATCH 16/25] runtime-model: model card for r17-v2b (genclass-runtime-r17 2.0.0-rc2); add LICENSE What it is, training data (SIM v2 gold + 1B tokens with real-app gold), the trainer's results, our q8 re-verification of the guard/heal gates, the dev-fitted report threshold 0.85 with its held-out test numbers (SIM 1.41%, REAL 3.78% false findings; one app dominates REAL), gates per tier/trigger, parity, latency from ortweb_report_q8.json, file hashes, intended use and limits. LICENSE (Apache-2.0, copy of packages/runtime/LICENSE) so the tarball carries the license text. Co-Authored-By: Claude Opus 5.5 --- packages/runtime-model/LICENSE | 202 +++++++++++++++ packages/runtime-model/MODEL_CARD.md | 352 +++++++++++++++++++++++---- 2 files changed, 501 insertions(+), 53 deletions(-) create mode 100644 packages/runtime-model/LICENSE diff --git a/packages/runtime-model/LICENSE b/packages/runtime-model/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/packages/runtime-model/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/runtime-model/MODEL_CARD.md b/packages/runtime-model/MODEL_CARD.md index a4ee1022..e0967259 100644 --- a/packages/runtime-model/MODEL_CARD.md +++ b/packages/runtime-model/MODEL_CARD.md @@ -1,60 +1,306 @@ -# GenClass runtime model — model card +# @genclass/runtime-model: model card -Status: **final round 1 on the frozen runtime (situation-v1)** delivered (`files/r17/` here; R17 and R32 in -`~/gcl/train-out/final1/` on the train VM): on SIM's held-out test R17 reaches 81.9% action / 90.5% diagnosis accuracy -with a 0.05% guard-mode and 0.24% heal-mode false-intervention rate and ECE ≈ 0.01, but it intervenes rarely (recall on -clear actionable cases ≈ 5%). The runtime is moving to situation-v2; the next rounds retrain on v2 data. -Numbers below are filled from `training/EVAL.md`; see it for definitions and the full tables. +`genclass-runtime-r17` version **2.0.0-rc2** (checkpoint `r17-v2b`), package `@genclass/runtime-model@0.1.0`. It is +the default model of [`@genclass/runtime`](https://www.npmjs.com/package/@genclass/runtime) `0.1.0-beta.0`, which +loads it from `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. This is a data package with no +JavaScript entry point. To self-host, copy `files/` (or run `npx @genclass/runtime fetch-model `) and point the +runtime's `model.baseUrl` at it. `npx @genclass/runtime info ` checks a copy against the hashes in `model.json`. + +**Status: first model for the `situation-v2` runtime format, release candidate.** In short: + +- It diagnoses about 84% of held-out decisions correctly, on simulated and on real apps. +- When it acts (`guard` / `heal`), it is precise: false interventions are 0.02% (guard) and 0.23% (heal) on held-out + simulated apps, and none were seen on held-out real apps. +- It acts on few of the cases where acting would help: 1–6% of clear cases on simulated apps, 8.5% of actionable + real-app cases in heal mode. +- In `observe` mode (the default) it flags a problem on 1.4% (simulated) to 3.8% (real) of held-out decisions where + nothing was wrong. On real apps those false flags were concentrated in one app. + +Read [Measured quality](#measured-quality) before relying on it. ## What it is -A Jev-style typed-decision encoder for `@genclass/runtime`: one forward pass over a *situation* (the runtime's -`app / trigger / facts / in_flight / timeline / state / stats` text) and typed questions (choice / noul / score), -answers calibrated per question, options attention-isolated (option order cannot change answers). The runtime asks -two standing questions per salient trigger: `action` (the applicable actions, with descriptions) and `diagnosis` -(expected / stale / conflict / duplicate / inconsistent / failing / slow / overload / unusual), and acts only when -`p(action) ≥ 0.9` (guard tier) / `0.8` (heal tier) **and** the top diagnosis is not `expected`. - -| variant | backbone | params | vocab | q8 (WASM) | fp16 (WebGPU) | -|---|---|---|---|---|---| -| `genclass-runtime-r17` | ettin-encoder-17m (d 256, 7 layers) | 8.1M + 0.7M heads | 16,364 | 9.6 MB | 13.6 MB | -| `genclass-runtime-r32` | ettin-encoder-32m (d 384, 10 layers), from GenClass 0.1 | 18.8M + 1.6M heads | 16,364 | 22.5 MB | 34.8 MB | - -Latency (onnxruntime-web 1.30 WASM, 1 thread, q8; fitted over 184 requests): R17 ≈ 190 / 340 / 610 ms and R32 -≈ 500 / 880 / 1,540 ms at 500 / 780 / 1,170 sequence tokens (≈ the runtime's 1,000 / 2,000 / 3,200-char state -budgets). WebGPU and 4-thread WASM (crossOriginIsolated pages) are much faster (MODEL's measurements). - -Stage-1c accuracy on the held-out runtime-format curriculum test: action 98.0% (R17) / 98.2% (R32), diagnosis -98.3% / 98.4%, 0 false interventions in 3,355 passive-best rows in both guard and heal mode. Zero-shot on SIM traffic -it is not yet good enough (≈ 50% action accuracy, 18–34% heal-mode false interventions on SIM's sample): the -shipping model is the stage-2 model trained on the frozen SIM data (see `training/EVAL.md`). - -Files per model directory (`model.json` format `genclass-runtime-model/1`): `-q8.onnx` (MatMulNBits 8-bit -block 32 + int8 row-wise token embeddings; for onnxruntime-web WASM), `-fp16.onnx` (fp16 weights + int8 -embeddings; WebGPU with `shader-f16`), `tokenizer.json` (byte-level BPE, first 16,000 merges of the ettin tokenizer; -markers `[Q] [O] [L] [T] [F]` = ids 16359–16363), `calibration.json` (per-kind temperatures), `meta.json`. -Graph inputs/outputs are identical to GenClass 0.1 (`input_ids, position_ids, q_group, i_group, choice_q, -choice_items, score_q, score_items, noul_q, noul_t, noul_f` → `choice_logits, score_logits, noul_logits`). - -## Training data and licence - -Apache-2.0. Initialisations: `jhu-clsp/ettin-encoder-17m` (MIT) for R17; GenClass 0.1 `jev-local-fast` (ettin-32m, -MIT, fine-tuned by us only on our own synthetic computer-use and generic data) for R32. Training data: only -programmatic synthetic data written for this project — the stage-1 curriculum (`training/curriculum/`, ≈ 1.2M rows: -runtime situations with exact labels, timeline/causality/version/identity/streak/baseline/invariant/transition/ -HTTP/JS-error primitives, described-option decisions), plus replay of GenClass 0.1's synthetic `data/gen` (all) and a -slice of `data/cu`. No benchmark, scraped or third-party dataset; no weights from other GenClass experiments. +A typed-decision encoder. One forward pass reads a *situation* (the runtime's `app / trigger / facts / in_flight / +timeline / state / stats` text) plus typed questions (choice / noul / score), and returns calibrated answers. Options +are attention-isolated, so option order cannot change an answer. + +| | | +|---|---| +| Backbone | `jhu-clsp/ettin-encoder-17m` (MIT): hidden 256, 7 layers, alternating full / sliding-window (64) attention | +| Parameters | about 8.8M (8.1M encoder + 0.7M decision heads) | +| Vocabulary | 16,364 tokens: byte-level BPE pruned to the first 16,000 ettin merges, plus markers `[Q] [O] [L] [T] [F]` (ids 16359–16363) | +| Max length | 2,048 tokens per segment, 8,192 total | +| Exports | q8 for onnxruntime-web WASM (MatMulNBits 8-bit, block 32, symmetric; int8 row-wise token embeddings; no fp16 tensors); fp16 for WebGPU with `shader-f16` (fp16 weights, int8 embeddings) | +| Graph | inputs `input_ids, position_ids, q_group, i_group, choice_q, choice_items, score_q, score_items, noul_q, noul_t, noul_f`; outputs `choice_logits, score_logits, noul_logits` | + +### Training + +| Stage | Data | +|---|---| +| Round 1, `r17-final1` | ettin-encoder-17m, trained on the runtime-format curriculum and on SIM gold in the previous format (`situation-v1`) | +| `r17-v2a` | from `r17-final1`, 2B tokens: SIM v2 gold 86% (7.56M training rows from simulated apps), v2 curriculum replay 13%, general 1% | +| **`r17-v2b` (this model)** | from `r17-v2a`, 1B more tokens (learning rate 1e-4): SIM v2 gold 70%, **real-app gold 18%**, curriculum 11%, general 1% | + +- **SIM gold:** rows from simulated apps that run on the real runtime in a deterministic virtual world. Each label is + the expected cost of each action, given what the runtime can observe. +- **Real-app gold:** about 453k training rows from REAL batches `v2c1`–`v2c4`. They were recorded from 96 small apps: + apps written for the corpus, plus unmodified open-source RealWorld front-ends. Scripted users drove the apps in + headless Chromium with the real runtime, and the rows were labelled the same way as SIM. + - The 16,600 rows of the real-app eval set were removed from training. + - Rows from held-out apps are test-only: every Lit and SWR app, `alpine-tasks`, `xhr-autocomplete` and + `oss-rtk-conduit`. So are rows that use three held-out app variants, in `react-search`, `vue-editor` and + `zustand-board`. +- **No other data:** no benchmark, scraped or third-party dataset was used. The only external weights are the + MIT-licensed ettin-encoder-17m initialisation. + +**Format.** The training data was rendered by the runtime at tag `situation-v2`. The `0.1.0-beta.0` runtime renders +`situation-v2.3` and also changes how redacted values print: + +| Change | What the model sees | Accounted for here? | +|---|---|---| +| v2.1 | one new fact for a stall with no latency baseline | not measured | +| v2.2 | `retry` offered only when repeating is safe | yes: the gate numbers below use v2.2 retry rules | +| v2.3 | fewer, more precise learned relations, so far fewer `inconsistency` decisions | not measured | +| redaction | the text of redacted values | not measured | + +## How the runtime uses it + +For each salient trigger (a request, a response about to be delivered, a mutation, a failure, a stall, an +inconsistency, a transition, an error), the runtime asks two standing questions: + +- `action`: which of the applicable actions to take. Each action comes with a description; examples are deliver / + discard / defer, send / coalesce / delay / block / serve_cached, deliver / retry, wait / hedge, and ignore / + rollback / resync. +- `diagnosis`: expected / stale / conflict / duplicate / inconsistent / failing / slow / overload / unusual / + transient. + +What happens next depends on the mode: + +- **Report (every mode).** A decision is reported as a detection (a console line, a `detect` event, the devtools + Detections view) when the top calibrated diagnosis is not `expected` and its probability is at least `report`. In + `observe` mode, the runtime's default, this is all that happens: nothing is held or changed. +- **Act (guard / heal).** The candidate is the most probable action the mode permits. Guard mode permits guard-tier + actions; heal mode permits guard and heal. The candidate runs only when both of these hold: + - the summed probability of all permitted non-passive actions reaches the threshold of the candidate's tier for + that trigger; + - the top diagnosis is not `expected`. + +Where the thresholds come from, in order: the app's `policy.thresholds`, then this model's `meta.json` `gate`, then +the runtime defaults (report 0.6, guard 0.9, heal 0.8). `runtime.gates(trigger)` shows the values in force and the +source of each. With this model and no app override, the source is `"model"` for all three. + +The model never sees app code. It sees only what the runtime observed (with secrets redacted). + +## Gate thresholds + +`meta.json` → `gate`: + +| Trigger | Guard | Heal | +|---|---|---| +| default | 0.80 | 0.85 | +| `delivery` | 0.75 | (default) | +| `mutation` | 0.95 | (default) | +| `request` | 0.75 | 1.0 (heal-tier actions effectively never run on requests; guard-tier ones still can, at 0.75) | +| `failure` | (default) | 0.90 | +| `inconsistency` | (default) | 0.80 | +| `transition` | (default) | 0.55 | +| `stall`, `error` | (default) | (default) | +| **report** (all triggers) | | **0.85** | + +Built-in guard-tier actions exist only on `delivery`, `request` and `mutation`. The guard default therefore applies +only to custom guard-tier actions on other triggers. + +### Guard and heal thresholds + +These were fitted by the model's trainer with `training/fit_gates.py`. The data was dev data the model never trained +on: + +- `sim2g`: a 104k-row SIM dev sample; +- the real-app eval set outside its test split; +- REAL dev rows. + +Rule: per tier and trigger, take the lowest summed-probability threshold that meets the limits below at the one-sided +95% Wilson upper bound, at that threshold and at every grid value above it. A trigger with too little dev data uses +the tier default. + +| Limit | Guard | Heal | +|---|---|---| +| FIR: SIM passive-best rows, and real-app clean-benign plus benign-salient rows | ≤ 0.1% | ≤ 0.5% | +| Harm: the fired action costs at least 1 more than doing nothing | ≤ 0.2% | ≤ 1% | + +We re-verified these gates independently with the shipped **q8 ONNX** logits, using a port of the runtime's gate code +(`parseGate`, `effectiveGates`, `gate`, calibration). The runtime applies the v2.2 retry rule: it renormalises +probabilities where it does not offer `retry`. A re-run of those rows without `retry` gave the same probabilities +(max difference 0.0). All pooled test limits are met, so the gates are unchanged. + +### Report threshold + +The runtime's default report threshold, 0.6, is too noisy for this model. At 0.6 on held-out test, the model flags +4.3% of gold-`expected` decisions on simulated apps and 6.2% on real apps. + +We fitted `report` on dev data only, with q8 logits: + +- **Rule:** the lowest grid value (0.50–0.95 in steps of 0.05, then 0.97 and 0.99) at which false findings are at most + 1.0% on SIM dev and, separately, on REAL dev, at that value and every higher one. A false finding is a detection on + a gold-`expected` decision. +- **Dev data:** SIM is `sim2g`, 79,839 rows with 32,392 gold-`expected`. REAL is the eval set outside its test split + plus REAL dev, with 9,841 gold-`expected` rows. +- **Result: 0.85.** The one-sided 95% upper-bound version of the rule also gives 0.85. On dev at 0.85, false findings + are SIM 0.80% (260/32,392) and REAL 0.30% (30/9,841). + +The trainer's first export carried 0.70, a dev fit against a looser limit (2% on SIM) that failed on test. The +trainer then chose 0.85 after looking at test results. Our dev-only fit reaches the same value without using test. +**Held-out test does not meet the 1% dev limit** (next section). It was not refitted on test. + +## Measured quality + +All numbers are on held-out data. FIR (false-intervention rate) is the share of rows where doing nothing was best but +the gate fired anyway. Recall is the share of rows that should be acted on (or flagged) where it did so. Brackets are +95% Wilson intervals. + +Test sets (never trained on, never used for fitting): + +| Set | Rows | Contents | +|---|---|---| +| `sim2e` | 20k | random rows of SIM's held-out test split | +| `sim2f` | 18,690 | simulated apps whose family contains an app feature held out from training (service-worker cache, presence, cascade, saga, prefetch, permissions) | +| `real2e` test | 20k | real-app test rows from 10 apps: 7 held out of training entirely, and 3 seen in training whose test rows use a held-out variant | +| Real-app eval set, test split | 1,546 | the test-split subset (held-out apps and variants) of 16,600 unambiguous recorded real-app cases (clean-benign, benign-salient, duplicate, genuine break, stale) | + +### Accuracy + +The trainer measured these with PyTorch on SIM test and REAL test rows: + +| | Diagnosis | Action | +|---|---|---| +| Simulated apps | 84.2% | 77.8% | +| Real apps | 83.6% | 80.0% | + +Our argmax cross-check with the shipped q8 export (argmax of logits against argmax of the gold target): + +| Set | Diagnosis | Action | +|---|---|---| +| `sim2e` | 85.0% (12,946/15,224) | 77.6% (9,977/12,858) | +| `sim2f` | 82.4% (11,853/14,388) | 76.9% (9,156/11,909) | +| `real2e` test | 85.6% (11,892/13,894) | 80.4% (10,269/12,765) | + +Row selection differs slightly from the trainer's evaluation. + +### Guard and heal on test + +Each mode below is measured with the shipped gates. + +| Mode | FIR, SIM | FIR, real held-out | Harm | Recall | +|---|---|---|---|---| +| guard | 0.02% (2/8,987) [0.01, 0.08] | 0.00% (0/66) [0, 5.5] | SIM 0.01% (1/12,111) | 1.2% (7/602) of clear SIM cases | +| heal | 0.23% (38/16,290) [0.17, 0.32] | 0.00% (0/1,124) [0, 0.34] | SIM 0.07% (15/22,322); `real2e` 0.08% (10/12,214) | 5.7% (88/1,545) of clear SIM cases; 8.5% (36/422) of actionable real-app cases | + +In heal mode, real-app recall on requests is 20.9% (36/172) and 0 on the other triggers. The trainer reports 6.0% +heal clear-case recall, and real-app duplicate recall of 8.2% (14% on held-out apps). + +Per trigger, pooled `sim2e` + `sim2f` test (SIM passive-best FIR; real held-out FIR where there are benign rows): + +| Trigger | Guard FIR | Heal FIR | Heal recall, clear SIM cases | Notes | +|---|---|---|---|---| +| `delivery` | 0.07% (1/1,416) | 0.07% | 2.1% (2/96) | real 0/26 | +| `request` | 0.02% (1/5,860) | 0.10% (6/5,882) | 3.8% (16/423) | real 0/40 | +| `mutation` | 0.00% (0/1,711) | 0.00% | 0% (0/84) | | +| `failure` | – | **0.66% (24/3,618) [0.45, 0.99]** | 10.2% (60/590) | **over the 0.5% heal limit on test** (dev 0.28%); `real2e` harm 0.39% (8/2,043) | +| `inconsistency` | – | 0.11% (2/1,796) | 3.8% (8/213) | real 0/1,008 | +| `transition` | – | 0.38% (5/1,311) | 1.3% (1/79) | real 0/49 | +| `stall` | – | 0.00% (0/451) | 1.7% (1/59) | | +| `error` | – | 0.00% (0/105) | – | | + +We also refitted the gates on q8 dev logits with `fit_gates.py`. Two values came out differently: guard `delivery` 0.80 +instead of 0.75 (one q8 dev false intervention in 3,615 rows), and heal `transition` 0.50 instead of 0.55. The +shipped values were kept, and both pass on test. + +### Observe mode: detections at report 0.85 + +| Set | False findings (of gold-`expected` decisions) | Flagged (of gold problem decisions) | Right diagnosis (of flags) | +|---|---|---|---| +| `sim2e` | 1.11% (61/5,474) [0.87, 1.43] | 66.4% | 94.8% | +| `sim2f` | 1.72% (88/5,108) [1.40, 2.12] | 63.6% | 93.4% | +| **SIM test, pooled** | **1.41% (149/10,582)** [1.20, 1.65] | 65.0% | 94.1% | +| Real eval set, test split | 0.18% (2/1,118) [0.05, 0.65] | 46.7% | 98.0% | +| `real2e` test | 4.35% (303/6,961) [3.90, 4.86] | 61.5% | 89.1% | +| **REAL test, pooled** | **3.78% (305/8,079)** [3.38, 4.21] | 60.7% | 89.5% | +| (runtime default 0.6, for comparison) | SIM 4.31%, REAL 6.18% | SIM 82.9%, REAL 82.7% | SIM 88.0%, REAL 84.4% | + +- **One app dominates the real false findings.** `real2e` test has gold-`expected` rows from only 9 apps. 240 of + its 303 false findings come from one of them, the held-out `oss-rtk-conduit`: 240 of that app's 955 + gold-`expected` rows, flagged as `stale` on its `article.inProgress` field. That is why REAL `mutation` decisions + show 21.8% false findings (265/1,215). Without that app, `real2e` test is 1.05% (63/6,006). The other eight apps + range from 0.50% to 2.33% each. +- **Benign real-app cases** (clean-benign and benign-salient, eval-set test split): 0.27% (3/1,124) were flagged. +- **Flag rate by trigger:** failures, stalls and errors are flagged most often (63% or more of their problem + decisions). Deliveries are flagged least (28–31%), and transitions on real apps only 20%. + +### Calibration + +`calibration.json` holds per-kind softmax temperatures fitted on the `sim2e` dev split: noul 1.0551, choice 0.9212, +score 0.8716. The runtime divides logits by them before the softmax. The `action` and `diagnosis` questions use the +choice temperature, and every threshold above assumes these calibrated probabilities. The trainer has not reported +calibration error for this checkpoint; it was 0.011 on `sim2e` for `r17-v2a`. + +### Not yet met + +- Diagnosis ≥ 95%. +- Clear-case recall ≥ 80%. +- Heal FIR ≤ 0.5% on the `failure` trigger on held-out data. +- Detection false findings ≤ 1% on held-out data. + +## Parity and latency + +The q8 export agrees with the PyTorch checkpoint on the top answer of 223 of 223 questions, in onnxruntime and in +onnxruntime-web 1.30 (WASM), with max |Δlogit| 0.848. It agrees on 191 of 191 gate outcomes at 0.8 and at 0.9. The fp16 export also agrees on 223 of 223 (max +|Δlogit| 0.474). Our own q8 collector reproduced the 223 of 223 agreement, with max |Δlogit| 0.848 against the +PyTorch fixtures. + +Latency of the q8 export, measured by the trainer in Node on the training VM over the 120 parity requests (median +598 tokens): + +| Backend | 500 tokens | 780 tokens | 1,170 tokens | Runtime-sized requests (89, median 772 tokens) | +|---|---|---|---|---| +| onnxruntime-web 1.30, WASM, 1 thread | 176 ms | 320 ms | 583 ms | p50 315 ms, p90 621 ms | +| onnxruntime-node, CPU, 1 thread | 35 ms | 62 ms | 115 ms | p50 62 ms | + +500 / 780 / 1,170 tokens is roughly the runtime's 1,000 / 2,000 / 3,200-character situation budgets. On single-thread +WASM the runtime uses a 1,000-character budget. Multi-threaded WASM (cross-origin-isolated pages) and WebGPU are faster +in browsers; neither was measured for this checkpoint. + +## Files + +`files/model.json` (format `genclass-runtime-model/1`) lists every file with its size and sha256. The runtime and +`genclass-runtime info` verify them. + +| File | Size | sha256 | Purpose | +|---|---|---|---| +| `genclass-runtime-r17-q8.onnx` | 9,582,526 B (9.6 MB) | `65d94e4cd4f1180abab0db6c7a6639f1e749c4cc93fda2bb5963b4652b01c4c0` | WASM (default); also runs on WebGPU without `shader-f16` | +| `genclass-runtime-r17-fp16.onnx` | 13,569,879 B (13.6 MB) | `2958f4baf3e1e6a92c603f51559da05c97a7b6a3125879a1395f521a4549b628` | WebGPU with `shader-f16` | +| `tokenizer.json` | 1,138,910 B (1.1 MB) | `11a0f913475cabb7568acc69f8fb884bbbde04edb513b9280c174b911f9e939a` | pruned byte-level BPE | +| `calibration.json` | 501 B | `843c1131bfbf947b2172392d96dcdceae1e0e0ee770febc2cb3dd0a49ab767d4` | per-kind temperatures | +| `meta.json` | 6,079 B | `0308b212152f93725fd48cdd5d81638e903bded575439232f499ca75ba2550de` | ids, graph signature, quantisation, `gate`, and the fitting records (`gate_fit`, `report_fit`, `gate_q8_check`) | +| `model.json` | 999 B | `fb682536d89da304c32a16b747eb1b1ad2c57b169ea1ee1b64caaa70ae490bbc` | manifest: variants and hashes of the files above | + +Every file is under jsDelivr's 20 MB per-file limit. ## Intended use and limits -- Decides generic runtime actions (apply/discard/defer, send/coalesce/delay/block/serve_cached, deliver/retry/ - serve_cached, wait/hedge/serve_cached, ignore/rollback/resync) and diagnoses from the runtime's facts. It never sees - app code; it only sees what the runtime observed. -- Stage-1 labels come from an explicit rule-based oracle over a synthetic world (clear-cut cases; soft labels leaning - passive where cases are genuinely ambiguous), not from counterfactual outcomes of real apps. The held-out test uses - unseen app domains and unseen phrasings, but it is still synthetic: expect a gap on real apps until stage 2 (SIM). -- Precision first: about 55% of decision training rows have the passive action as the best answer, including - salient-looking benign cases (older writers in between, deliberate repeats, polling, typing bursts, long-poll - timeouts, explained relation changes, third-party errors). Report false interventions from your app. -- Developer `ask`/`decide` questions work for short factual questions about the situation; it is a 17M/32M encoder, - not a general reasoner. +- **What it is for.** It decides generic runtime actions and diagnoses from the runtime's observed facts, inside + `@genclass/runtime`. It is not a general classifier or reasoner. Developer `ask` / `decide` questions work for short + factual questions about the situation. +- **Not tested on your app.** It was evaluated on simulated apps and on small real apps driven in headless Chromium. + Run it in `observe` mode (the default) first and read what it flags before you turn on `guard` or `heal`. +- **Observe mode will show some false flags.** Expect roughly 1–4 in 100 decisions where nothing was wrong. In some + apps, one recurring pattern can produce many of them (one held-out app: 25% of its clean decisions). Raise + `policy.thresholds.report` to see fewer, at the cost of recall (at 0.9: SIM 0.89%, REAL 3.44%, flagged 58% / 52%). +- **Precision over recall.** It acts on few of the cases where acting would help (see the recall numbers above). + Expect it to miss most problems. False interventions are rare but possible, and `heal` on failures (retry, + serve_cached) is the least precise. Please report them. +- **It cannot see everything.** It does not see app code, request headers it was not shown, or server state. +- **Not a safety net.** It is not a substitute for tests, correct concurrency control or server-side validation. + +## License + +Apache-2.0. Base weights: `jhu-clsp/ettin-encoder-17m`, MIT. From 9695830e159339e2662b957d925339a3a3fb587a Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 09:22:30 -0400 Subject: [PATCH 17/25] release: @genclass/runtime 0.1.0-beta.0 (ships with @genclass/runtime-model@0.1.0, r17-v2b) - packages/runtime 0.1.0-alpha.1 -> 0.1.0-beta.0; the genclass-runtime alias's exact dependency follows (the alias itself is not published); package-lock.json synced. - CHANGELOG: 0.1.0-beta.0 section (default model, model-provided gates, observe never delays, batches 6-8, one-command install / auto / script tag, install and redaction fixes); the install bullets move out of 0.1.0-alpha.1, which never contained them. - READMEs: beta status with the model's held-out numbers (diagnosis 84% / real 83.6%, observe false flags 1.41% sim / 3.78% real at report 0.85, guard/heal FIR 0.02% / 0.23%, recall 1-9%), the shipped gates, real model output for the example, install without the 'next release' caveats and fixed issues, model size and latency, known limitations for a model-backed beta. Co-Authored-By: Claude Opus 5.5 --- README.md | 52 +++-- package-lock.json | 4 +- packages/genclass-runtime/package.json | 2 +- packages/runtime/CHANGELOG.md | 68 +++++- packages/runtime/README.md | 311 ++++++++++++++----------- packages/runtime/package.json | 2 +- 6 files changed, 272 insertions(+), 167 deletions(-) diff --git a/README.md b/README.md index 0b250ea8..a25dc214 100644 --- a/README.md +++ b/README.md @@ -23,20 +23,22 @@ generic facts about each write, request and response, and asks a small GenClass The model runs in the browser (WebGPU or WASM, in a Web Worker). It answers two questions: what is happening, and which available action is best. There is no list of known bugs in the code. -> **Status: alpha. The runtime is built; its model is still in training.** +> **Status: beta. `@genclass/runtime@0.1.0-beta.0` ships with its first trained model, +> `@genclass/runtime-model@0.1.0`.** > -> - **Runtime:** works and is unit-tested (situation format `situation-v2`, tag `situation-v2`). -> - **Default mode** is `observe`. `guard` is opt-in; `heal` is experimental. -> - **No model is published for this format yet.** `@genclass/runtime-model` is not on npm, so a default -> `GenClass.init()` prints `[GenClass] Model unavailable (...); observing only.` and finds nothing. -> - **Round 1 models** (format `situation-v1`) exist but do not match this runtime. -> - **On npm:** `@genclass/runtime@0.1.0-alpha.1` (`latest`) is this runtime. `0.1.0-alpha.0` is the older v1 -> runtime: it defaults to guard, holds store writes, and has a `NaN` crash that alpha.1 fixes. -> - **In this repository, not yet on npm:** the one-command install (`npx @genclass/runtime init`), the -> `@genclass/runtime/auto` entries and the script tag; observe mode never holding or delaying a response; and -> two redaction fixes. They ship in the next release: `0.1.0-beta.0` with the model, or `0.1.0-alpha.2` if a -> release without the model goes out first ([RELEASE.md](RELEASE.md)). The install path still has known issues, -> listed under the runtime README's known limitations. +> - **Runtime:** works and is unit-tested (situation format tag `situation-v2.3`). Install with +> `npx @genclass/runtime init`, one import (`@genclass/runtime/auto`) or one script tag. +> - **Default mode** is `observe`: the model diagnoses salient situations and the runtime reports likely problems, +> without changing what the app does. `guard` is opt-in; `heal` is experimental. +> - **Model:** `genclass-runtime-r17` 2.0.0-rc2 (9.6 MB, WASM or WebGPU), loaded from jsDelivr by default. +> - On held-out data it diagnoses about 84% of decisions correctly (83.6% on real apps). +> - In observe mode it flags 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong. +> - When it acts, it is rarely wrong (0.02% guard, 0.23% heal on simulated apps; none seen on held-out real apps), +> but it acts on only 1–9% of the cases where acting would help. +> +> See the [model card](packages/runtime-model/MODEL_CARD.md). +> - **Older versions on npm:** `0.1.0-alpha.1` (the v2 runtime without the install commands or model gates) and +> `0.1.0-alpha.0` (the v1 runtime: guard by default, holds store writes, `NaN` crash). Use `0.1.0-beta.0`. > > What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: > start at [AGENTS.md](AGENTS.md). @@ -63,8 +65,11 @@ which available action is best. There is no list of known bugs in the code. | mode | behaviour | |---|---| | `observe` (default) | reports only | - | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability is ≥ 0.9 | - | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions (≥ 0.8) | + | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability reaches the model's fitted guard threshold for that trigger (0.75–0.95) | + | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions, at the heal threshold for that trigger (0.55–0.90; 1.0 on requests) | + + Detections are reported when the top diagnosis is not `expected` with probability ≥ 0.85 (the model's report + threshold). 6. **Explain.** - Every detection and intervention is logged in plain English, with the exact situation text the model read. @@ -83,17 +88,19 @@ All numbers are on held-out data, with each recall reported next to its false-in |---|---| | Round 1 model, R17 (9.6 MB int8; **previous format** `situation-v1`), simulated apps | diagnosis 90.5%, action 81.9%, guard FIR 0.05%, heal FIR 0.24%, calibration error 0.009. Recall on clear stale/duplicate cases is only 7.7% (precise but timid). | | Why round 1 was timid ([sim/SEPARABILITY.md](sim/SEPARABILITY.md)) | Many clear cases had benign twins with identical visible facts; 24% of clear rows were mislabelled `expected`; labels assumed knowledge a runtime cannot have. v2 adds measured facts and fixes the labels. | -| Round 2 (`situation-v2`, this runtime) | **in progress**: ~10M simulated gold rows, ~50M unlabeled rows for teacher labelling, ~0.5M rows from real apps in headless Chromium | +| **r17-v2b** (`situation-v2`; shipped as `@genclass/runtime-model@0.1.0`) | Simulated apps: diagnosis 84.2%, action 77.8%. Real apps: diagnosis 83.6%, action 80.0%. Guard FIR 0.02% simulated, 0.00% on held-out real apps; heal FIR 0.23% / 0.00%. Recall: heal acts on 5.7% of clear simulated cases and 8.5% of actionable real-app cases; guard on 1.2%. | +| Observe mode with r17-v2b (report threshold 0.85, fitted on dev data) | Held-out test: 1.41% of decisions where nothing was wrong flagged on simulated apps, 3.78% on real apps (1.05% without one app); 61–65% of problem decisions flagged, 89–94% of flags with the right diagnosis | +| Training continues | teacher model, distillation, DAgger rounds; ~10M simulated gold rows, ~50M unlabeled rows, ~0.6M real-app rows | | Never make a correct app worse (always-passive model, heal vs observe, 66 real apps × 6 seeds) | 0/396 clean runs changed: final page text (inputs and alerts excluded) and server state. Request timing and store contents are not compared, nor is observe mode against no runtime. With chaos: 3/198 changed. | | Same check on the v1 runtime (store-write holds) | 4/198 clean runs changed; the React/Redux RealWorld app never rendered its home feed | -| Demos | Baseline only, with the untrained GenClass 0.1 model: guard took 0 actions. Rerun when the v2 model exists. | +| Demos | Baseline only, with the untrained GenClass 0.1 model: guard took 0 actions. Not yet re-run with r17-v2b. | ## What's in this repo | path | what | |---|---| | [`packages/runtime`](packages/runtime) | `@genclass/runtime`, the library. Observers, causality, stores and adapters, learned baselines/relations/profiles, facts, triage, policy gate, actions, model host (Web Worker, ONNX Runtime Web on WebGPU/WASM), devtools overlay. [README](packages/runtime/README.md) · [STATUS](packages/runtime/STATUS.md) | -| [`packages/runtime-model`](packages/runtime-model) | Model card for the not-yet-published `@genclass/runtime-model` | +| [`packages/runtime-model`](packages/runtime-model) | `@genclass/runtime-model`, the default model package (data only; `files/` is gitignored and filled at release time) and its [model card](packages/runtime-model/MODEL_CARD.md) | | [`sim`](sim) | Training-data simulator: random apps run on the real runtime in a deterministic virtual world, labelled by counterfactual outcomes | | [`realapps`](realapps) | 128 real apps (written for the corpus, plus open-source ones) run with the real runtime in headless Chromium, labelled the same way; the never-worse sweep covered the first 66. [README](realapps/README.md) | | [`training`](training) | Vocabulary pruning, curriculum (`curriculum/rt.py` mirrors the runtime's renderer), multi-node CPU training on Azure, int8 ONNX export, evaluation | @@ -118,8 +125,8 @@ NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # t The same steps run in CI ([.github/workflows/ci.yml](.github/workflows/ci.yml), Node 22) on pushes to `main`, `runtime`, `mvp` and `mvp-v2`, on pull requests, and on manual dispatch. -Last full local run (2026-10-08, branch `mvp-v2-merge` at f107013): 375 tests passed and 14 skipped, plus the 4 -perf tests run alone. The skips are model-parity tests, which need `GENCLASS_MODEL_DIR`. The perf tests time a +Last full local run (2026-10-08, branch `mvp-v2-b6`, version `0.1.0-beta.0`): 419 tests passed and 14 skipped, plus +the 4 perf tests run alone. The skips are model-parity tests, which need `GENCLASS_MODEL_DIR`. The perf tests time a 5,000-item store and can fail under parallel load. Releasing: [RELEASE.md](RELEASE.md). @@ -132,8 +139,9 @@ Not covered by CI: These are heavier or need Azure; see [AGENTS.md](AGENTS.md) before running them. -**The training format is frozen** at tag `situation-v2`. Any change to `packages/runtime/src/situation/*` (or other -text the model reads) changes the model's input and means a new tag and regenerated data. See +**The training format is tagged.** The current tag is `situation-v2.3`; the shipped model was trained on data from +`situation-v2`. Any change to `packages/runtime/src/situation/*` (or other text the model reads) changes the model's +input and means a new tag and regenerated data. See [docs/agents/model-io-contract.md](docs/agents/model-io-contract.md). ## License diff --git a/package-lock.json b/package-lock.json index 233b4a71..81760e0b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3150,7 +3150,7 @@ "version": "0.1.0-alpha.1", "license": "Apache-2.0", "dependencies": { - "@genclass/runtime": "0.1.0-alpha.1" + "@genclass/runtime": "0.1.0-beta.0" }, "bin": { "genclass-runtime": "cli.mjs" @@ -3161,7 +3161,7 @@ }, "packages/runtime": { "name": "@genclass/runtime", - "version": "0.1.0-alpha.1", + "version": "0.1.0-beta.0", "license": "Apache-2.0", "dependencies": { "onnxruntime-web": "^1.30.0" diff --git a/packages/genclass-runtime/package.json b/packages/genclass-runtime/package.json index 4939d1b9..e471c134 100644 --- a/packages/genclass-runtime/package.json +++ b/packages/genclass-runtime/package.json @@ -8,6 +8,6 @@ "homepage": "https://www.npmjs.com/package/@genclass/runtime", "bin": { "genclass-runtime": "./cli.mjs" }, "files": ["cli.mjs", "README.md", "LICENSE"], - "dependencies": { "@genclass/runtime": "0.1.0-alpha.1" }, + "dependencies": { "@genclass/runtime": "0.1.0-beta.0" }, "engines": { "node": ">=20" } } diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md index b0d70944..f3ab78fe 100644 --- a/packages/runtime/CHANGELOG.md +++ b/packages/runtime/CHANGELOG.md @@ -1,17 +1,71 @@ # Changelog +## 0.1.0-beta.0 + +- **Ships with a model.** A default `GenClass.init()` now loads `@genclass/runtime-model@0.1.0` + (`genclass-runtime-r17` 2.0.0-rc2, checkpoint `r17-v2b`) from jsDelivr. The model is 9.6 MB (q8, WASM) and is + cached after the first load. On held-out data: + - Diagnosis: 84.2% on simulated apps and 83.6% on real apps. + - False interventions: 0.02% (guard) and 0.23% (heal) on simulated apps; none were seen on held-out real apps. + - Recall is low: guard acts on 1.2% of clear simulated cases; heal on 5.7% of them and on 8.5% of actionable + real-app cases. + - In observe mode, 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong get flagged. + + Numbers, gates and limits are in the model card (`@genclass/runtime-model`, `MODEL_CARD.md`). +- **The model sets the gate thresholds** (runtime batch 6). The model's `meta.json` `gate` provides the report, + guard and heal thresholds per trigger kind; `policy.thresholds` still overrides them. The shipped model uses: + - report 0.85; + - guard 0.75–0.95; + - heal 0.55–1.0. + + `rt.gates(trigger)` shows the values in force and where each came from. Decisions record the threshold and its + source, and the devtools overlay shows the gates. Also in batch 6: a request with no latency baseline counts as a + stall after 10 s. +- **Observe stays the default**, and in this version it never holds or delays a response. The delivery decision is + made in the background and recorded with `executed: false`. A later `GenClass.init({ mode })` that cannot apply + (the runtime is already running) now logs one warning instead of being ignored silently. +- **`retry` only when repeating is safe** (runtime batch 7). It is offered for idempotent methods, and for POST / + PATCH only with an idempotency-key header (`policy.idempotencyHeaders`). `Situation.notOffered` says why an action + was left out. +- **Fewer false `inconsistency` triggers** (runtime batch 8, relation learner precision): + - sentinel "nothing selected" values are understood; + - uniqueness is learned only for id columns; + - pagination and envelope fields are ignored; + - nothing is checked during typing bursts; + - busy counters are excluded; + - equality, count and sum relations need compatible field names. + + On 444 clean runs of 148 real apps, inconsistency decisions fell from 745 to 45. The situation format tag is now + `situation-v2.3`. +- **One-command install** (new in this version; not in 0.1.0-alpha.1): `npx @genclass/runtime init` detects your + framework and installs GenClass, and `remove` undoes it. In end-to-end runs on fresh Vite (React, Vue, Svelte), + Next.js App and Pages Router, Create React App, SvelteKit, Astro, Nuxt, React Router, Angular and plain-HTML + projects, `remove` restored every file byte for byte. Those runs predate the install fixes below. +- **One import:** `import "@genclass/runtime/auto"` (also `/auto/observe`, `/auto/guard` and `/auto/heal`). +- **One script tag:** ``, which loads the model + worker cross-origin. +- **Install fixes:** + - `init` without `--mode` writes the observe import. `--mode guard|heal|observe` writes `/auto/` (or + `data-mode` on the script tag), and running `init` again with another `--mode` switches it in place. + - `remove` deletes only what `init` wrote, including lines a formatter rewrapped (Prettier, ESLint `curly`). If you + edited inside a marked block, it reports where and changes nothing. It keeps the package installed while + dot-folders or `tmp` / `out` / `build` still import it. + - Node servers and libraries that merely list a bundler are refused instead of edited. + - An SRI hash is added only for this version's own jsDelivr / unpkg file. + - `typesVersions` makes the subpath types resolve under TypeScript `"moduleResolution": "node"`. + - `fetch-model` downloads from `@genclass/runtime-model@0.1.0` on jsDelivr by default, the runtime's own default + model. +- **Redaction fixes:** + - The "would replace text the user typed" fact no longer prints characters of a redacted field. + - Numbers and arrays under a secret-named container (`payment.cvv.value`, `login.otp.code`) are redacted. + ## 0.1.0-alpha.1 -- **One-command install:** `npx @genclass/runtime init` detects your framework and installs GenClass. Tested in - fresh Vite (React, Vue, Svelte), Next.js App and Pages Router, Create React App, SvelteKit, Astro, Nuxt, - React Router, Angular and plain-HTML projects. `remove` restores every file byte for byte. -- **One import:** `import "@genclass/runtime/auto"` (also `/auto/observe` and `/auto/heal`). -- **One script tag:** ``, with the model - worker loaded cross-origin. - **Never reorders your app's writes.** Decisions now happen at the network boundary (the new `delivery` trigger for fetch, XHR, WebSocket and EventSource), which looks like latency to the app. Store holds are opt-in (`policy.holdWrites`). With a model that never intervenes, GenClass changed 0 of 396 clean runs across 66 real apps. +- **Observe is the default mode**; `guard` is opt-in and `heal` is experimental. - **New facts:** "would put back a value a newer write replaced", "would replace text the user typed", "response changes nothing", stale-value provenance, refresh/save cadence, failure scope, commit ambiguity, repeat-click evidence, and count-by-group relations. @@ -22,6 +76,8 @@ - redaction is now by field name, so a store named `auth` is no longer hidden wholesale; - 34 review findings, each with a regression test. +No model for this runtime was published with this version. + ## 0.1.0-alpha.0 First alpha. diff --git a/packages/runtime/README.md b/packages/runtime/README.md index e71fe696..413bfc70 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -22,24 +22,26 @@ import { GenClass } from "@genclass/runtime"; GenClass.init(); // observe mode: reports only, never takes an action (see Known limitations) ``` -> **Status: alpha. No trained model is published yet, so today the runtime finds nothing.** +> **Status: beta (`0.1.0-beta.0`), the first version with a trained model.** > -> - The runtime, model host, devtools overlay and React/Redux/Zustand adapters are built and unit-tested. -> - The model for this runtime's situation format (`situation-v2`) is still in training. -> `@genclass/runtime-model` is not on npm, so the default model URL returns 404. A default `GenClass.init()` -> prints `[GenClass] Model unavailable (...); observing only.`, consults no model, records no detections and takes -> no actions. It still traces, learns baselines and answers `rt.situation()`; `rt.ask()` / `rt.decide()` reject -> with `GenClassUnavailableError`. -> - The only trained models so far (round 1) read the previous format (`situation-v1`) and do not match this -> runtime. Do not self-host them with this version. -> - **Versions.** `0.1.0-alpha.1` is the current `latest` on npm: the v2 runtime, observe by default, with the -> `NaN` fix. It does **not** include the one-command install, the `@genclass/runtime/auto` entries or the script -> tag described under [Install](#install). It also lacks two fixes made since: observe mode no longer holds or -> delays any response, and two redaction leaks are closed (see [Privacy](#privacy)). All of these are in this -> repository and ship in the next release: `0.1.0-beta.0` with the model, or `0.1.0-alpha.2` if a release -> without the model goes out first. -> `0.1.0-alpha.0`, the first version on npm, is the older v1 runtime: guard by default, holds store writes, and -> can crash when app state contains `NaN`. Do not use it. +> - **The model loads by default.** A default `GenClass.init()` loads `@genclass/runtime-model@0.1.0` (9.6 MB, +> `genclass-runtime-r17` 2.0.0-rc2) from jsDelivr at idle, in a Web Worker, and caches it. Self-hosting and +> `model: false` are under [Performance](#performance). +> - **Observe is the default.** The model diagnoses salient situations and the runtime reports likely problems; it +> never changes what your app does. `guard` is opt-in and `heal` is experimental. +> - **The model is precise when it acts, but timid, and observe mode shows some false flags.** +> - Diagnosis is right on about 84% of held-out decisions (83.6% on real apps). +> - It flags 1.4% (simulated apps) to 3.8% (real apps) of held-out decisions where nothing was wrong. On real apps, +> most of those came from one app. +> - In `guard` / `heal` it intervened wrongly on 0.02% / 0.23% of held-out simulated cases, and never on held-out +> real apps, but it acts on only 1–9% of the cases where acting would help. +> +> Details: [Model quality](#model-quality) and the +> [model card](https://www.npmjs.com/package/@genclass/runtime-model). +> - **Older versions.** `0.1.0-alpha.1` is the v2 runtime without the install commands, without the model's gate +> support, and with a delivery delay in observe mode. `0.1.0-alpha.0` is the older v1 runtime: guard by default, +> it holds store writes, and it can crash when app state contains `NaN`. Do not use it. Both load this model too, +> from the same default URL, but were not tested with it. > > Progress: [OPEN_TASKS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/OPEN_TASKS.md) · > measured results: [RESULTS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/RESULTS.md). @@ -55,70 +57,66 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known ## What it looks like Run your app as usual. When the model flags something, the console gets one plain-English line per detection or -intervention, followed by a collapsed group with the evidence. This is real output of the runtime in guard mode for -an out-of-order search response. A scripted stand-in decider supplied the answer (`stale`, `discard`, 0.97), since no -trained model exists yet: +intervention, followed by a collapsed group with the evidence. Here a typeahead's slow response for "rea" lands +after the response for "reac". This is real output of `0.1.0-beta.0` with its default model (q8 on WASM, in Node), +in the default observe mode. The response reaches the app at once, exactly as without GenClass, and the decision is +made in the background, for the report only: ``` -[GenClass] Prevented a stale response: search.results was written once by other operations since its operation (#4) -started (version 1 → 2), last 0.40s ago by GET /api/search?q=react (#6), which started 1.30s after #4, from a later -user action (#5). Delivered the response to GET /api/search?q=rea (#4) and dropped the state changes it makes over -newer data (search.results). (stale, 0.97; discard 0.97) +[GenClass] Model ready (genclass-runtime-r17, wasm, q8, 0.43s). Mode: observe. +[GenClass] Flagged a stale response: search.results was written twice by other operations since its operation (#6) +started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later +user action (#7). (stale, 0.96) ``` -In observe mode the response reaches the app at once, exactly as without GenClass, and the same decision is made -in the background, for the report only: +The same run in guard mode. The model's `discard` (0.98) passed the model's delivery gate (0.75), so the results +for "reac" stayed: ``` -[GenClass] Flagged a stale response: search.results was written once by other operations since its operation (#4) -started (version 1 → 2), … Not acted on (would have done discard 0.97): observe mode never changes execution. (stale, 0.97) +[GenClass] Prevented a stale response: search.results was written twice by other operations since its operation (#6) +started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which started 0.09s after #6, from a later +user action (#7). Delivered the response to GET /api/search?q=rea (#6) and dropped the state changes it makes over +newer data (search.results). (stale, 0.97; discard 0.98) ``` ## Install -### Today: `0.1.0-alpha.1` (npm `latest`) - -```bash -npm install @genclass/runtime -``` - -```ts -// first thing in your entry file -import { GenClass } from "@genclass/runtime"; - -const rt = GenClass.init(); // observe; GenClass.init({ mode: "guard" }) to let it act once a model exists -``` - -### Next release: one command, one import or one script tag - -These three paths are built and tested in this repository but are **not in `0.1.0-alpha.1`**; they ship in the next -release. All three start the same runtime, in observe mode unless you choose otherwise. +Pick one. All of them start the same runtime, in observe mode unless you choose otherwise. **1. One command.** `init` finds your framework and package manager, installs the package, adds one import as the first line of your entry file (plus a line that loads the devtools overlay in development only), and shows you the -diff before writing anything. Running it again changes nothing. +diff before writing anything. Running it again changes nothing; running it with another `--mode` switches the +import it added. ```bash -npx @genclass/runtime init # shows the diff, asks, then writes -npx @genclass/runtime init --yes # no questions -npx @genclass/runtime init --dry-run # show the diff, write nothing -npx @genclass/runtime remove # undo exactly what init added +npx @genclass/runtime init # observe; shows the diff, asks, then writes +npx @genclass/runtime init --mode guard # let GenClass act (also: --mode heal); run again later to switch +npx @genclass/runtime init --yes # no questions +npx @genclass/runtime init --dry-run # show the diff, write nothing +npx @genclass/runtime remove # undo exactly what init added ``` -Other flags: `--no-install`, `--no-devtools`, `--cwd `, `remove --keep-package`. `init` sets up observe mode; -to let GenClass act, change the import it added to `@genclass/runtime/auto/guard` (see the next path). Do this by -hand for now: `init --mode guard` still writes the observe import (see -[Known limitations](#known-limitations)). +Other flags: `--no-install`, `--no-devtools`, `--cwd `, `--cdn ` and `--no-sri` (plain HTML), +`remove --keep-package`. + +- **What `init` edits.** It only edits browser apps. It stops and says why for a Node server, a library (a UI + framework as a peer dependency, or an `exports`, `module`, `types` or `bin` field), or an entry file that imports + Node-only modules. +- **What `remove` deletes.** Only what `init` wrote, including lines a formatter rewrapped. If you edited a marked + line or block, it changes nothing and lists where. Tested end to end on fresh projects from each framework's own generator: Vite 8 (React with npm and pnpm, Vue, Svelte), Next.js 16.4 (App and Pages Router, plus the paths for Next < 15.3), Create React App 5, SvelteKit, Astro, -Nuxt 4.6, React Router 8 (framework mode), Angular 20 and plain HTML. In all 15 projects the app built and ran in -Chromium after `init` (production build where the project has one; model loaded in a worker, overlay only in -development, no console errors on a warm load), and `remove` left every file byte-identical to the scaffold -(node_modules, lockfiles and build output excluded). +Nuxt 4.6, React Router 8 (framework mode), Angular 20 and plain HTML. In all 15 projects: + +- the app built and ran in Chromium after `init` (production build where the project has one); +- the model loaded in a worker, the overlay appeared only in development, and a warm load had no console errors; +- `remove` left every file byte-identical to the scaffold (node_modules, lockfiles and build output excluded). + Remix, Solid, Preact and Next.js before 15.3 are detected but were not scaffolded with their own generators. Details: [test/install/RESULTS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/packages/runtime/test/install/RESULTS.md). -Those runs predate the switch to observe as the default; the files `init` writes are the same. +Those runs predate observe becoming the default and the `init` / `remove` fixes in this version (`--mode`, formatter +handling, server and library detection). The fixes are covered by unit tests; the scaffolds have not been re-run. **2. One import** (any bundler), first in your entry file so stores created at import time see the runtime: @@ -143,11 +141,24 @@ SSR or in Node, `/auto` installs nothing and returns an inert runtime. It exposes `window.GenClass` and loads the model worker, ONNX Runtime Web and the overlay on demand from the same version on the CDN. `data-mode` takes `observe` (the default), `guard` or `heal`; `data-devtools="local"` shows the -overlay only on localhost; `data-manual` skips the automatic `GenClass.init()`. Pin a version in production (the -plain-HTML path of `init` writes a pinned jsDelivr URL with SRI). Until the next release, the unversioned URL serves -`0.1.0-alpha.1`, which has no script-tag build. +overlay only on localhost; `data-manual` skips the automatic `GenClass.init()`. Pin a version in production +(`https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.0`); the plain-HTML path of `init` writes a pinned +jsDelivr URL with SRI. + +**4. By hand:** + +```bash +npm install @genclass/runtime +``` + +```ts +// first thing in your entry file +import { GenClass } from "@genclass/runtime"; -`npx genclass-runtime init` will be a short alias for the same CLI (the `genclass-runtime` package, not on npm yet). +const rt = GenClass.init(); // observe; GenClass.init({ mode: "guard" }) to let it act +``` + +The unscoped name `genclass-runtime` is not published; use `npx @genclass/runtime`. ## Why it's an easy yes (measured) @@ -171,25 +182,31 @@ These hold for the runtime; whether the model's decisions are good is a separate it changed carry an `x-genclass` header. - **Off in one step.** `?genclass=off` in the URL installs nothing, and observe (the default) never changes execution. -- **Small.** The main entry is about 83 KB gzip (minified, without the optional devtools). The only round-1 model - export so far is 9.6 MB; the size of the coming `situation-v2` model is not known yet. +- **Small.** The main entry is about 83 KB gzip (minified, without the optional devtools). The default model is + 9.6 MB on WASM (13.6 MB fp16 on WebGPU with `shader-f16`), downloaded once at idle and cached. ## Modes -| mode | what it does | non-passive actions | gate | +| mode | what it does | non-passive actions | gate (default model) | |---|---|---|---| | `observe` (**default**) | Reports what it sees and what it would have done. Never holds a request, never runs an action. | none | n/a | -| `guard` (opt-in) | Also prevents failures with guard-tier actions: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down. | guard tier | summed probability of the permitted actions ≥ 0.9, and the top diagnosis is not `expected` | -| `heal` (**experimental**) | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions. | guard + heal tier | guard actions ≥ 0.9, heal actions ≥ 0.8, diagnosis not `expected` | +| `guard` (opt-in) | Also prevents failures with guard-tier actions: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down. | guard tier | summed probability of the permitted actions ≥ the trigger's guard threshold (delivery 0.75, request 0.75, mutation 0.95), and the top diagnosis is not `expected` | +| `heal` (**experimental**) | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions. | guard + heal tier | heal actions ≥ the trigger's heal threshold (transition 0.55, inconsistency 0.80, default 0.85, failure 0.90; 1.0 on requests, so effectively never there), guard actions as in guard mode, diagnosis not `expected` | ```ts GenClass.init({ mode: "guard" }); ``` -In every mode, a decision is reported as a detection when its diagnosis is not `expected` at confidence ≥ 0.6. Actions -are also limited to 60 per minute (`policy.maxActionsPerMinute`). A held decision that misses the hold budget runs -the passive action; a background write decision can still revert the write late. Thresholds and the `allow` / `deny` -lists are in `policy`. Switch at runtime with `rt.setMode(mode)`, or stop consulting the model with `rt.pause()` / `rt.resume()`. +- **Where the thresholds come from.** They were fitted on held-out data and ship in the model's `meta.json` + ([model card](https://www.npmjs.com/package/@genclass/runtime-model)). A model without a `gate` gets the + runtime's defaults: report 0.6, guard 0.9, heal 0.8. `policy.thresholds: { report, guard, heal }` overrides both. + `rt.gates(trigger)` shows the values in force and where each came from (`"policy"`, `"model"` or `"default"`). +- **Detections.** In every mode, a decision is reported as a detection when its top diagnosis is not `expected` and + its probability is at least the report threshold: 0.85 with the default model. +- **Limits.** Actions are limited to 60 per minute (`policy.maxActionsPerMinute`). A held decision that misses the + hold budget runs the passive action; a background write decision can still revert the write late. +- **Control.** The `allow` / `deny` lists are in `policy`. Switch at runtime with `rt.setMode(mode)`, or stop + consulting the model with `rt.pause()` / `rt.resume()`. **The default changed.** `0.1.0-alpha.0` defaulted to `guard`. Now `GenClass.init()` with no `mode` (and `@genclass/runtime/auto`, and the script tag without `data-mode`) observes only; pass `mode: "guard"` to let it act. @@ -204,7 +221,7 @@ browser (SSR, Node) it returns a runtime with no observers and no model. For tes ## What it looks for -At a glance (actions other than flagging need `guard` or `heal`, and a published model): +At a glance (actions other than flagging need `guard` or `heal`): | situation | example | what GenClass can do | |---|---|---| @@ -327,8 +344,9 @@ const when = await rt.decide("Which upload strategy fits what is happening now?" // "now" | "later" ``` -Without a model (today, or with `model: false`) both reject with `GenClassUnavailableError` (`reason`: `off`, -`error`, `timeout` or `destroyed`). `{ timeoutMs }` bounds the wait. +Without a model (`model: false`, or when it cannot load) both reject with `GenClassUnavailableError` (`reason`: +`off`, `error`, `timeout` or `destroyed`). `{ timeoutMs }` bounds the wait. With the default model, short factual +questions about the current situation work best; it is not a general-purpose reasoner. Standing questions ride along with built-in decisions: `rt.question({ id, on: ["failure"], question, onAnswer })`. @@ -379,28 +397,57 @@ measured. ## Model quality -There are no numbers yet for a model that matches this runtime. - -**Round 1 (previous format, `situation-v1`)**, R17 on held-out simulated apps: +The default model is `genclass-runtime-r17` 2.0.0-rc2 (`@genclass/runtime-model@0.1.0`): an 8.8M-parameter encoder +trained on simulated apps and on real apps driven in headless Chromium. Every number below is on held-out data: -| metric | value | -|---|---| -| diagnosis accuracy | 90.5% | -| action accuracy | 81.9% | -| guard false-intervention rate | 0.05% | -| heal false-intervention rate | 0.24% | -| calibration error | 0.009 | -| recall on clear stale/duplicate cases | 7.7% | +- simulated test rows, including apps built from features held out of training; +- real-app test rows from 10 apps, 7 of which never appeared in training. -R17 was precise but timid. The analysis found the limit was in the situation text and the labels, not the model -size: many clear cases had benign twins with identical visible facts, and some labels were wrong. +Full tables, per-trigger gates and how each threshold was fitted: the +[model card](https://www.npmjs.com/package/@genclass/runtime-model). -**Round 2 (`situation-v2`, this runtime)** adds measured facts aimed at those twins, plus relabelled data. The data is -generated from simulated apps (10.4M labelled rows and 51.3M unlabeled rows for teacher labelling), rows from real -apps driven in headless Chromium are being added, and the models are training now. Results will be published with the model package. +| | Simulated apps | Real apps | +|---|---|---| +| Diagnosis accuracy | 84.2% | 83.6% | +| Action accuracy | 77.8% | 80.0% | +| **Observe:** decisions flagged where nothing was wrong (report 0.85) | 1.41% (149 / 10,582) | 3.78% (305 / 8,079); 1.05% without one app | +| Observe: problem decisions flagged | 65% | 61% | +| Observe: flags with the right diagnosis | 94% | 89% | +| **Guard:** false interventions | 0.02% (2 / 8,987) | 0.00% (0 / 66) | +| Guard: clear cases acted on | 1.2% | – | +| **Heal:** false interventions | 0.23% (38 / 16,290) | 0.00% (0 / 1,124) | +| Heal: cases acted on | 5.7% of clear cases | 8.5% of actionable cases | + +What this means in practice: + +- **Observe (default).** Expect roughly 1 to 4 false flags per 100 decisions where nothing was wrong. + - In one held-out real app, `oss-rtk-conduit`, the model flagged 25% of clean decisions as `stale`, all on its + `article.inProgress` field. A single recurring pattern in your app can do the same. + - Each flag names its evidence, and identical lines within a minute are summarised. + - Raise `policy.thresholds.report` to see fewer flags. At 0.9: 0.9% (simulated) and 3.4% (real) false, with 58% and + 52% of problems flagged. +- **Guard (opt-in).** When it acts, it is almost always right, but it rarely acts. Expect it to miss most problems. +- **Heal (experimental).** On held-out simulated apps, heal actions on failures (`retry`, `serve_cached`) were wrong + on 0.66% of the failures where doing nothing was best. That is over the 0.5% target the thresholds were fitted to. +- **Not yet met:** diagnosis ≥ 95%, clear-case recall ≥ 80%, and false flags ≤ 1% on held-out data. Training + continues (a larger teacher model, distillation, more real-app data). +- **Format.** The model was trained on situations rendered by the runtime at `situation-v2`. This version renders + `situation-v2.3`: + - an extra stall fact; + - `retry` offered only when safe; + - fewer learned relations; + - redacted values printed differently. + + The retry change is accounted for in the numbers above; the others were not measured. + +**Round 1** (previous format `situation-v1`, not compatible with this runtime): R17 reached 90.5% diagnosis and 81.9% +action accuracy on held-out simulated apps, with 0.05% / 0.24% guard / heal false interventions, but acted on only +7.7% of clear cases. The analysis found the limit was in the situation text and the labels, not the model size. The +v2 format adds measured facts for those cases, with relabelled data. The "never make a correct app worse" check uses an always-passive model in heal mode, compared against observe mode, -on 66 real apps (6 seeds each). **0 of 396 clean runs** changed, measured on final page text (inputs and alerts +on 66 real apps (6 seeds each), with the v2 runtime as of `0.1.0-alpha.1` (not re-run on this version). +**0 of 396 clean runs** changed, measured on final page text (inputs and alerts excluded) and server state. The check does not compare request timing or store contents, and it does not compare observe mode against running without GenClass. With network chaos, 3 of 198 runs differed: a request held about 25 ms changed the simulated network's draws. Details: @@ -419,10 +466,12 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - **Bundle:** the main entry is about 240 KB minified / 83 KB gzip, measured with esbuild and onnxruntime-web external. ONNX Runtime Web (the only dependency) is loaded by the model worker on demand: about 2.7 MB brotli for - the WASM-only path, 4.7 MB with WebGPU. The script-tag file (next release) is 255 KB / 86 KB gzip without ONNX + the WASM-only path, 4.7 MB with WebGPU. The script-tag file is about 255 KB / 86 KB gzip without ONNX Runtime; its model worker (16 KB gzip) and ONNX Runtime glue (25–39 KB gzip) load on demand. -- **Model size:** the round-1 R17 export (pruned 16k vocabulary, int8) is 9.6 MB. On single-thread WASM it took about - 0.18 s per decision on a 500-token situation, measured in Node. +- **Model:** the default model is 9.6 MB (q8, pruned 16k vocabulary) on WASM and 13.6 MB (fp16) on WebGPU with + `shader-f16`. With onnxruntime-web 1.30 on single-thread WASM, measured in Node on the training VM, a forward pass + took about 176 / 320 / 583 ms at 500 / 780 / 1,170 tokens (p50 315 ms on runtime-sized requests). Single-thread + WASM uses the smallest situation budget (1,000 characters, about 500 tokens with the questions). - **Holds are bounded.** A held response or request waits at most the hold budget, then proceeds unchanged. The default `"auto"` budget is 1.5 × the median of the last 20 model latencies, clamped to 150–800 ms; it is 300 ms before any latency is known. @@ -433,10 +482,12 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs Override with `situation: { budget }`. - **Threads:** serving the page with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` enables WASM threads (about 3× faster with 4 threads in Chromium, - measured with a round-1 model). -- **Loading:** the model loads at idle after page load (`model.preload: "idle"`). It is cached in Cache Storage and - checked with sha256. `model: { baseUrl }` points at a self-hosted model directory - (`npx @genclass/runtime fetch-model ` downloads one); there is none for this runtime yet. + measured with the round-1 model of the same size). +- **Loading:** the model loads at idle after page load (`model.preload: "idle"`) from + `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. It is cached in Cache Storage and checked + with sha256. To self-host, `npx @genclass/runtime fetch-model public/genclass-model` downloads it, and + `model: { baseUrl: "/genclass-model/" }` points the runtime at it. `model: false` loads no model (nothing is + detected or prevented then). ## Privacy @@ -457,14 +508,18 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - The "would replace text the user typed" fact shows a character diff only when the redactor leaves both values unchanged; otherwise it prints `[redacted] → [redacted]` (or your redactor's replacement). - Pass your own `redact(path, value)` for app-specific secrets or PII. The default has gaps (see below). - - The container rule for numbers and arrays and the typed-text rule are fixes made after `0.1.0-alpha.1`; they - ship in the next release. + - The container rule for numbers and arrays and the typed-text rule are new in `0.1.0-beta.0`. ## Known limitations -**Today.** Without a published model nothing is detected or prevented (see Status). The bullets below matter once a -model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. +- **The model is new and imperfect.** The numbers are under [Model quality](#model-quality). + - In observe mode, expect some false flags: 1–4 per 100 decisions where nothing was wrong, more in some apps. + - It misses most problems. + - It was not evaluated on your app. + - Heal-mode actions on failures (`retry`, `serve_cached`) exceeded their false-intervention target on held-out + data. + Watch observe mode before turning on `guard` or `heal`. - **Redaction gaps (all modes with a model).** - A container named by a two-word secret (`cardNumber`, `apiKey`, `creditCard`) counts as broad, like `auth`. So `payment.cardNumber.value = "4111 1111 1111 1111"`, or the same number, is shown. It reaches the situation @@ -486,9 +541,10 @@ model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. the app closed the socket meanwhile. EventSource `open` events are not kept in order behind held messages. - **XHR listeners of a held response** run after the original dispatch, so `e.currentTarget` is `null`. Use the `xhr` object itself. -- **`retry` (heal) does not check idempotency.** It is offered for any replayable fetch, POST included. The model - sees whether the method is idempotent and whether the failed request may have been applied. HTTP 502 is - described as usually not processed, which is not always true behind proxies. +- **`retry` (heal) trusts HTTP semantics.** It is offered for idempotent methods, and for POST / PATCH only when + the request carries an idempotency key (`policy.idempotencyHeaders`, default `Idempotency-Key`, + `X-Idempotency-Key`). An endpoint that is not idempotent despite its method (a `PUT` that appends) can still be + retried. HTTP 502 is described as usually not processed, which is not always true behind proxies. - **Transport coverage.** `coalesce`, `retry`, `hedge` and failure/stall `serve_cached` are fetch-only. XHR failures and stalls are detection-only. - **Synthetic events.** DOM events with `isTrusted === false` (`el.click()`, `dispatchEvent`, in-page test @@ -499,39 +555,24 @@ model ships and you opt into `guard` or `heal`, unless a bullet says otherwise. This is best effort; wrap important work in `rt.op(name, fn)` for exact attribution. - **Store state** is visible and protectable only through GenClass-aware stores. Other state is seen only through its effects. -- **Next-release install (`init`, `remove`, `/auto`, script tag).** Known issues, to be fixed before or in that - release. Always read the diff `init` and `remove` show before you confirm. - - **`init --mode guard` installs observe.** It prints `Mode guard`, but writes the plain `@genclass/runtime/auto` - import (or a script tag without `data-mode`), which observes. Plain `init` also prints `guard` as the - default. Change the import to `@genclass/runtime/auto/guard` yourself. - - **Running `init` again with another `--mode`** reports "Nothing to do" and leaves the existing import alone. - - **TypeScript with `"moduleResolution": "node"`** (Create React App TypeScript, older templates) cannot find the - types of `@genclass/runtime/auto`, `/devtools` or `/react` (TS2307), so the type check, and with it a CRA - build, fails after `init`. `"moduleResolution": "bundler"` works. - - **Server and library projects.** A project that lists esbuild, rollup, parcel or webpack is treated as a - browser app, so `init` can add the import to a Node server's or a library's entry file. - - **Formatters.** If a formatter rewraps a line `init` added (the dev-only devtools line, or the one-line form - in a Next.js layout), `remove` takes out only part of it and leaves code that does not compile. Fix the file - by hand. - - **What `remove` deletes.** Code you added inside a block `init` marked goes with the block; a file `init` - created is one such block and is deleted whole. If a block's end marker is missing, everything after its start - marker goes. Any other line that contains `genclass:init` goes too. It uninstalls the package unless it finds - an import in your sources, and it does not look in dot-folders (`.storybook`), `tmp`, `out` or `build`. Use - `remove --keep-package` when you import GenClass there. - - **`init --cdn `** adds an SRI hash of the CLI's own copy of the file, whatever version the URL names. With - `@latest` or another version, the browser refuses the script. Pass `--no-sri`. - - **SRI covers only the script-tag file.** The model worker, ONNX Runtime glue and overlay it loads from the CDN - are not integrity-checked. - - **Page configuration is read from every `` in the document**, including the body, - and it may set the mode and the model and ONNX Runtime URLs. On a page that renders untrusted HTML which can - include `` tags, set those keys in `window.GENCLASS_CONFIG` (it overrides meta tags), or call +- **Install and CDN.** + - **Read the diff.** Always read the diff `init` and `remove` show before you confirm. + - **SRI covers only the script-tag file.** The model worker, ONNX Runtime glue and overlay it loads from the CDN, + and the model files, are not integrity-checked by the browser. The runtime checks the model files against the + sha256 values in `model.json`. Pin a version, or self-host. + - **Page configuration is read from every `` in the document**, including the body, and it + may set the mode and the model and ONNX Runtime URLs. On a page that renders untrusted HTML which can include + `` tags, set those keys in `window.GENCLASS_CONFIG` (it overrides meta tags), or call `GenClass.init(options)` instead of importing `/auto`. - **React Router dev server.** On the very first dev start after `init`, Vite discovers the new imports late, re-optimizes and reloads the page, logging a few "Outdated Optimize Dep" errors once. Later loads are clean. + - **Not re-run end to end.** The end-to-end scaffold runs predate this version's `init` / `remove` changes, which + are covered by unit tests only. - **The model can be wrong.** It is trained on simulated apps and real apps driven in a headless browser. It is not - a substitute for tests. That is why the default only observes, guard acts only at ≥ 0.9, and every action is - logged. + a substitute for tests. That is why the default only observes, guard acts only above thresholds fitted to keep + false interventions at or below 0.1% on data the model never trained on, and every action is logged. ## License -Apache-2.0. The model package, once published, comes with its own model card. +Apache-2.0. The model package, `@genclass/runtime-model` (Apache-2.0), comes with its own +[model card](https://www.npmjs.com/package/@genclass/runtime-model). diff --git a/packages/runtime/package.json b/packages/runtime/package.json index c8d9c655..04e10c98 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@genclass/runtime", - "version": "0.1.0-alpha.1", + "version": "0.1.0-beta.0", "description": "A client-side AI runtime for web apps: a local GenClass model watches user actions, async work, network, state and errors, and prevents stale writes, races, duplicates, inconsistent state and failure storms in real time.", "type": "module", "license": "Apache-2.0", From 1f0f6170b1aa247f4ee95a04c57a752de9bc7222 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 09:33:18 -0400 Subject: [PATCH 18/25] runtime-model: final 0.1.0 gates (on-policy refit) and model card The model card, runtime README, root README and runtime CHANGELOG now describe the shipped meta.json (c3358947...0eb50, 2,602 B; model.json 9e2a42bd...afff20): guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85, refit on on-policy dev (training/EVAL.md, 9bd0aed). Trainer's test numbers side by side with our independent q8 re-verification: pooled guard FIR 0.01%, heal FIR 0.07%, heal failure 0.19% (now under the 0.5% limit). Co-Authored-By: Claude Opus 5.5 --- README.md | 12 +- packages/runtime-model/MODEL_CARD.md | 165 +++++++++++++++++---------- packages/runtime/CHANGELOG.md | 13 ++- packages/runtime/README.md | 28 ++--- 4 files changed, 133 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index a25dc214..44c8f524 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,8 @@ which available action is best. There is no list of known bugs in the code. > - **Model:** `genclass-runtime-r17` 2.0.0-rc2 (9.6 MB, WASM or WebGPU), loaded from jsDelivr by default. > - On held-out data it diagnoses about 84% of decisions correctly (83.6% on real apps). > - In observe mode it flags 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong. -> - When it acts, it is rarely wrong (0.02% guard, 0.23% heal on simulated apps; none seen on held-out real apps), -> but it acts on only 1–9% of the cases where acting would help. +> - When it acts, it is rarely wrong (0.01% guard, 0.07% heal on simulated apps; none seen on held-out real apps), +> but it acts on under 6% of the cases where acting would help. > > See the [model card](packages/runtime-model/MODEL_CARD.md). > - **Older versions on npm:** `0.1.0-alpha.1` (the v2 runtime without the install commands or model gates) and @@ -65,8 +65,8 @@ which available action is best. There is no list of known bugs in the code. | mode | behaviour | |---|---| | `observe` (default) | reports only | - | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability reaches the model's fitted guard threshold for that trigger (0.75–0.95) | - | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions, at the heal threshold for that trigger (0.55–0.90; 1.0 on requests) | + | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability reaches the model's fitted guard threshold for that trigger (0.80; 0.95 on mutations) | + | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions, at the heal threshold for that trigger (0.85; 0.95 on failures) | Detections are reported when the top diagnosis is not `expected` with probability ≥ 0.85 (the model's report threshold). @@ -88,8 +88,8 @@ All numbers are on held-out data, with each recall reported next to its false-in |---|---| | Round 1 model, R17 (9.6 MB int8; **previous format** `situation-v1`), simulated apps | diagnosis 90.5%, action 81.9%, guard FIR 0.05%, heal FIR 0.24%, calibration error 0.009. Recall on clear stale/duplicate cases is only 7.7% (precise but timid). | | Why round 1 was timid ([sim/SEPARABILITY.md](sim/SEPARABILITY.md)) | Many clear cases had benign twins with identical visible facts; 24% of clear rows were mislabelled `expected`; labels assumed knowledge a runtime cannot have. v2 adds measured facts and fixes the labels. | -| **r17-v2b** (`situation-v2`; shipped as `@genclass/runtime-model@0.1.0`) | Simulated apps: diagnosis 84.2%, action 77.8%. Real apps: diagnosis 83.6%, action 80.0%. Guard FIR 0.02% simulated, 0.00% on held-out real apps; heal FIR 0.23% / 0.00%. Recall: heal acts on 5.7% of clear simulated cases and 8.5% of actionable real-app cases; guard on 1.2%. | -| Observe mode with r17-v2b (report threshold 0.85, fitted on dev data) | Held-out test: 1.41% of decisions where nothing was wrong flagged on simulated apps, 3.78% on real apps (1.05% without one app); 61–65% of problem decisions flagged, 89–94% of flags with the right diagnosis | +| **r17-v2b** (`situation-v2`; shipped as `@genclass/runtime-model@0.1.0`) | Simulated apps: diagnosis 84.2%, action 77.8%. Real apps: diagnosis 83.6%, action 80.0%. Gates refit on the model's own on-policy traffic. Guard FIR 0.01% simulated, 0.00% on held-out real apps; heal FIR 0.07% / 0.00%. Recall: heal acts on 2.9% of clear simulated cases and 5.7% of actionable real-app cases; guard on 0.7%. | +| Observe mode with r17-v2b (report threshold 0.85, fitted on dev data) | Held-out test: 1.41% of decisions where nothing was wrong flagged on simulated apps (3.1% on the model's own on-policy traffic), 3.78% on real apps (1.05% without one app); 61–65% of problem decisions flagged, 89–94% of flags with the right diagnosis | | Training continues | teacher model, distillation, DAgger rounds; ~10M simulated gold rows, ~50M unlabeled rows, ~0.6M real-app rows | | Never make a correct app worse (always-passive model, heal vs observe, 66 real apps × 6 seeds) | 0/396 clean runs changed: final page text (inputs and alerts excluded) and server state. Request timing and store contents are not compared, nor is observe mode against no runtime. With chaos: 3/198 changed. | | Same check on the v1 runtime (store-write holds) | 4/198 clean runs changed; the React/Redux RealWorld app never rendered its home feed | diff --git a/packages/runtime-model/MODEL_CARD.md b/packages/runtime-model/MODEL_CARD.md index e0967259..68467054 100644 --- a/packages/runtime-model/MODEL_CARD.md +++ b/packages/runtime-model/MODEL_CARD.md @@ -9,12 +9,14 @@ runtime's `model.baseUrl` at it. `npx @genclass/runtime info ` checks a cop **Status: first model for the `situation-v2` runtime format, release candidate.** In short: - It diagnoses about 84% of held-out decisions correctly, on simulated and on real apps. -- When it acts (`guard` / `heal`), it is precise: false interventions are 0.02% (guard) and 0.23% (heal) on held-out - simulated apps, and none were seen on held-out real apps. -- It acts on few of the cases where acting would help: 1–6% of clear cases on simulated apps, 8.5% of actionable - real-app cases in heal mode. +- When it acts (`guard` / `heal`), it is precise: false interventions are 0.01% (guard) and 0.07% (heal) on held-out + simulated apps, and none were seen on held-out real apps. Its gates were refit on the model's own on-policy traffic + before release. +- It acts on few of the cases where acting would help: under 3% of clear cases on simulated apps (guard 0.7%, heal + 2.9%), 5.7% of actionable real-app cases in heal mode. - In `observe` mode (the default) it flags a problem on 1.4% (simulated) to 3.8% (real) of held-out decisions where - nothing was wrong. On real apps those false flags were concentrated in one app. + nothing was wrong, and on 3.1% of the model's own on-policy simulated traffic. On real apps those false flags were + concentrated in one app. Read [Measured quality](#measured-quality) before relying on it. @@ -98,59 +100,77 @@ The model never sees app code. It sees only what the runtime observed (with secr | Trigger | Guard | Heal | |---|---|---| | default | 0.80 | 0.85 | -| `delivery` | 0.75 | (default) | | `mutation` | 0.95 | (default) | -| `request` | 0.75 | 1.0 (heal-tier actions effectively never run on requests; guard-tier ones still can, at 0.75) | -| `failure` | (default) | 0.90 | -| `inconsistency` | (default) | 0.80 | -| `transition` | (default) | 0.55 | -| `stall`, `error` | (default) | (default) | +| `failure` | (default) | **0.95** | +| `inconsistency` | (default) | 0.85 (the default, set explicitly) | +| `delivery`, `request`, `stall`, `transition`, `error` | (default) | (default) | | **report** (all triggers) | | **0.85** | -Built-in guard-tier actions exist only on `delivery`, `request` and `mutation`. The guard default therefore applies -only to custom guard-tier actions on other triggers. +Built-in guard-tier actions exist only on `delivery`, `request` and `mutation`, so guard acts at 0.80 on deliveries and +requests and at 0.95 on mutations. The guard default applies to custom guard-tier actions on other triggers. -### Guard and heal thresholds +### Where they come from -These were fitted by the model's trainer with `training/fit_gates.py`. The data was dev data the model never trained -on: +The model's trainer fitted these with `training/fit_gates.py` and refit them on 2026-10-08 (10:30 UTC) on the +shipped model's own distribution (`training/EVAL.md`, "r17-v2b gates refit on the shipped model's own distribution"). + +**Why a refit.** SIM's on-policy round b ran this model with its first gates on the `situation-v2.3` runtime. On that +traffic the first gates were too loose: 41% of heal `transition` actions (gate 0.55) were false, as were 18% of guard +`delivery` actions and 19% of guard `request` actions (gate 0.75 each; mostly `coalesce` on intended repeats). + +**Dev data** (never trained on): - `sim2g`: a 104k-row SIM dev sample; +- on-policy round b dev (33.7k rows) and round a dev (37.8k rows); - the real-app eval set outside its test split; -- REAL dev rows. +- REAL dev (`real2e`). -Rule: per tier and trigger, take the lowest summed-probability threshold that meets the limits below at the one-sided -95% Wilson upper bound, at that threshold and at every grid value above it. A trigger with too little dev data uses -the tier default. +**Rule.** Per tier and trigger, take the lowest summed-probability threshold whose 95% Wilson upper bounds meet +0.8 × each limit below on dev, with `diagnosis != expected` applied as in the runtime. A trigger gets its own threshold +only where its dev evidence (SIM and REAL) certifies every limit. Otherwise it gets max(tier default, SIM-certified +value), never less than the default. `retry` is removed where the v2.2 runtime does not offer it (unkeyed POST/PATCH). | Limit | Guard | Heal | |---|---|---| | FIR: SIM passive-best rows, and real-app clean-benign plus benign-salient rows | ≤ 0.1% | ≤ 0.5% | | Harm: the fired action costs at least 1 more than doing nothing | ≤ 0.2% | ≤ 1% | -We re-verified these gates independently with the shipped **q8 ONNX** logits, using a port of the runtime's gate code -(`parseGate`, `effectiveGates`, `gate`, calibration). The runtime applies the v2.2 retry rule: it renormalises -probabilities where it does not offer `retry`. A re-run of those rows without `retry` gave the same probabilities -(max difference 0.0). All pooled test limits are met, so the gates are unchanged. +**One test-informed value: heal `failure` 0.95.** The dev rule gave 0.90. Its held-out test FIR was 0.74% +[0.51, 0.98], over the 0.5% limit. The trainer chose 0.95 after that check: failure FIR 0.21% [0.11, 0.34], with the +gain captured on failures falling from 8.4% to 2.5%. `meta.json` records this in `gate_fit.test_informed`. Every +other value, including `report`, is the dev fit. + +**History.** The first export of this checkpoint (`meta.json` 6,079 B, sha256 `0308b212…50de`) had guard `delivery` +and `request` 0.75, heal `transition` 0.55, `failure` 0.90, `inconsistency` 0.80 and `request` 1.0. The refit replaced +it before release. + +### Our q8 re-verification + +We re-verified the shipped gates independently with the shipped **q8 ONNX** logits, using a port of the runtime's +gate code (`parseGate`, `effectiveGates`, `gate`, calibration) and the shipped `meta.json` (sha256 `c3358947…0eb50`). +The runtime applies the v2.2 retry rule: it renormalises probabilities where it does not offer `retry`. A re-run of +those rows without `retry` gave the same probabilities (max difference 0.0). + +- **Every pooled limit holds on test:** guard FIR 0.01% (≤ 0.1%), heal FIR 0.07% (≤ 0.5%), on SIM and on real apps. +- **Heal `failure` is now under its limit:** 0.19% (7/3,618) [0.09, 0.40], down from 0.66% at the first gates. +- Our test sets do not include on-policy round b test (we have no q8 records for it); the trainer's do. ### Report threshold The runtime's default report threshold, 0.6, is too noisy for this model. At 0.6 on held-out test, the model flags 4.3% of gold-`expected` decisions on simulated apps and 6.2% on real apps. -We fitted `report` on dev data only, with q8 logits: - -- **Rule:** the lowest grid value (0.50–0.95 in steps of 0.05, then 0.97 and 0.99) at which false findings are at most - 1.0% on SIM dev and, separately, on REAL dev, at that value and every higher one. A false finding is a detection on - a gold-`expected` decision. -- **Dev data:** SIM is `sim2g`, 79,839 rows with 32,392 gold-`expected`. REAL is the eval set outside its test split - plus REAL dev, with 9,841 gold-`expected` rows. -- **Result: 0.85.** The one-sided 95% upper-bound version of the rule also gives 0.85. On dev at 0.85, false findings - are SIM 0.80% (260/32,392) and REAL 0.30% (30/9,841). +- **Trainer's rule** (`gate_fit.report_rule`): the lowest top-diagnosis probability with false detections ≤ 1% on + real-app clean plus benign-salient rows and ≤ 2% on SIM gold-`expected` dev rows (including on-policy a and b dev), + at the 95% upper bound against 0.8 × each limit. **Result: 0.85.** +- **Our independent dev-only fit** with q8 logits: the lowest grid value (0.50–0.95 in steps of 0.05, then 0.97 and + 0.99) at which false findings (detections on gold-`expected` decisions) are at most 1.0% on SIM dev (`sim2g`, + 32,392 gold-`expected`) and, separately, on REAL dev (eval set outside its test split plus REAL dev, 9,841 + gold-`expected`), at that value and every higher one. **Result: 0.85** (the one-sided 95% upper-bound version also + gives 0.85). On dev at 0.85: SIM 0.80% (260/32,392), REAL 0.30% (30/9,841). -The trainer's first export carried 0.70, a dev fit against a looser limit (2% on SIM) that failed on test. The -trainer then chose 0.85 after looking at test results. Our dev-only fit reaches the same value without using test. -**Held-out test does not meet the 1% dev limit** (next section). It was not refitted on test. +**Held-out test does not meet the 1% limit**, and on on-policy round b test it exceeds the trainer's 2% SIM limit +(next section). It was not refitted on test. ## Measured quality @@ -188,35 +208,48 @@ Row selection differs slightly from the trainer's evaluation. ### Guard and heal on test -Each mode below is measured with the shipped gates. - -| Mode | FIR, SIM | FIR, real held-out | Harm | Recall | -|---|---|---|---|---| -| guard | 0.02% (2/8,987) [0.01, 0.08] | 0.00% (0/66) [0, 5.5] | SIM 0.01% (1/12,111) | 1.2% (7/602) of clear SIM cases | -| heal | 0.23% (38/16,290) [0.17, 0.32] | 0.00% (0/1,124) [0, 0.34] | SIM 0.07% (15/22,322); `real2e` 0.08% (10/12,214) | 5.7% (88/1,545) of clear SIM cases; 8.5% (36/422) of actionable real-app cases | +Each mode below is measured with the shipped gates. The trainer's test is on-policy round b test (20k rows) + +`sim2e` + `sim2f`, plus the REAL test-split eval rows. Ours is `sim2e` + `sim2f` with q8 logits, plus the real-app +eval set's test split (FIR and action recall) and `real2e` test (harm). -In heal mode, real-app recall on requests is 20.9% (36/172) and 0 on the other triggers. The trainer reports 6.0% -heal clear-case recall, and real-app duplicate recall of 8.2% (14% on held-out apps). - -Per trigger, pooled `sim2e` + `sim2f` test (SIM passive-best FIR; real held-out FIR where there are benign rows): +| | Trainer | Ours (q8) | +|---|---|---| +| Guard FIR, SIM | 0.01% [0.00, 0.02] | 0.01% (1/8,987) [0.00, 0.06] | +| Guard FIR, real held-out | 0.00% | 0.00% (0/66) [0, 5.5] | +| Guard harm, SIM / real | 0.00% / 0.00% | 0.01% (1/12,111) / 0.00% (0/6,620) | +| Guard recall, clear SIM cases | 0.6% | 0.7% (4/602) [0.3, 1.7] | +| Guard recall, actionable real-app cases | 0.0% | 0.0% (0/281) | +| Heal FIR, SIM | 0.07% (0.17% [0.12, 0.22] with failure at 0.90) | 0.07% (11/16,290) [0.04, 0.12] | +| Heal FIR, real held-out | 0.00% | 0.00% (0/1,124) [0, 0.34] | +| Heal FIR, `failure`, SIM | 0.21% [0.11, 0.34] (0.74% at 0.90) | 0.19% (7/3,618) [0.09, 0.40] | +| Heal harm, SIM / real | 0.04% / 0.07% (failure at 0.90) | 0.04% (9/22,322) / 0.04% (5/12,214) | +| Heal recall, clear SIM cases | 5.9% (failure at 0.90) | 2.9% (45/1,545) [2.2, 3.9] | +| Heal recall, actionable real-app cases | 5.7% (requests 14%) | 5.7% (24/422) [3.9, 8.3]; requests 14.0% (24/172) | +| Heal gain captured | 3.8% | not computed | + +Where the trainer's number is marked "failure at 0.90", it was reported only at the dev-rule value, before +`failure` was raised to 0.95. Raising `failure` lowers heal recall on clear SIM cases. In heal mode, every real-app +action was on a request: real-app recall on the other triggers is 0. + +Per trigger, ours (q8), pooled `sim2e` + `sim2f` test (SIM passive-best FIR; real held-out FIR where there are benign +rows): | Trigger | Guard FIR | Heal FIR | Heal recall, clear SIM cases | Notes | |---|---|---|---|---| -| `delivery` | 0.07% (1/1,416) | 0.07% | 2.1% (2/96) | real 0/26 | -| `request` | 0.02% (1/5,860) | 0.10% (6/5,882) | 3.8% (16/423) | real 0/40 | -| `mutation` | 0.00% (0/1,711) | 0.00% | 0% (0/84) | | -| `failure` | – | **0.66% (24/3,618) [0.45, 0.99]** | 10.2% (60/590) | **over the 0.5% heal limit on test** (dev 0.28%); `real2e` harm 0.39% (8/2,043) | -| `inconsistency` | – | 0.11% (2/1,796) | 3.8% (8/213) | real 0/1,008 | -| `transition` | – | 0.38% (5/1,311) | 1.3% (1/79) | real 0/49 | +| `delivery` | 0.07% (1/1,416) | 0.07% (1/1,416) | 1.0% (1/96) | real 0/26 | +| `request` | 0.00% (0/5,860) | 0.05% (3/5,882) | 4.7% (20/423) | real 0/40 | +| `mutation` | 0.00% (0/1,711) | 0.00% (0/1,711) | 0% (0/84) | | +| `failure` | – | 0.19% (7/3,618) [0.09, 0.40] | 3.6% (21/590) | `real2e` harm 0.20% (4/2,043) | +| `inconsistency` | – | 0.00% (0/1,796) | 0.9% (2/213) | real 0/1,008 | +| `transition` | – | 0.00% (0/1,311); no fires | 0% (0/79) | real 0/49; the trainer also saw 0 fires on test | | `stall` | – | 0.00% (0/451) | 1.7% (1/59) | | | `error` | – | 0.00% (0/105) | – | | -We also refitted the gates on q8 dev logits with `fit_gates.py`. Two values came out differently: guard `delivery` 0.80 -instead of 0.75 (one q8 dev false intervention in 3,615 rows), and heal `transition` 0.50 instead of 0.55. The -shipped values were kept, and both pass on test. - ### Observe mode: detections at report 0.85 +The report threshold and calibration did not change in the refit, so our q8 observe numbers are those of the +first export. + | Set | False findings (of gold-`expected` decisions) | Flagged (of gold problem decisions) | Right diagnosis (of flags) | |---|---|---|---| | `sim2e` | 1.11% (61/5,474) [0.87, 1.43] | 66.4% | 94.8% | @@ -227,6 +260,17 @@ shipped values were kept, and both pass on test. | **REAL test, pooled** | **3.78% (305/8,079)** [3.38, 4.21] | 60.7% | 89.5% | | (runtime default 0.6, for comparison) | SIM 4.31%, REAL 6.18% | SIM 82.9%, REAL 82.7% | SIM 88.0%, REAL 84.4% | +The trainer's held-out numbers at 0.85: + +- SIM gold-`expected`: 1.1% (`sim2e`) and 1.7% (`sim2f`), the same as ours. +- **On-policy round b test: 3.1%**, over the trainer's 2% limit, on the model's own distribution. This set is not in + our q8 sets. +- Real-app clean plus benign-salient rows: 0.36% (ours: 0.27%, 3/1,124, on the eval set's test split; row selection + differs). +- Detection with the right diagnosis on held-out real apps: duplicate submit 76%, stale overwrite 28%. + +Notes on our numbers: + - **One app dominates the real false findings.** `real2e` test has gold-`expected` rows from only 9 apps. 240 of its 303 false findings come from one of them, the held-out `oss-rtk-conduit`: 240 of that app's 955 gold-`expected` rows, flagged as `stale` on its `article.inProgress` field. That is why REAL `mutation` decisions @@ -247,8 +291,9 @@ calibration error for this checkpoint; it was 0.011 on `sim2e` for `r17-v2a`. - Diagnosis ≥ 95%. - Clear-case recall ≥ 80%. -- Heal FIR ≤ 0.5% on the `failure` trigger on held-out data. -- Detection false findings ≤ 1% on held-out data. +- Detection false findings ≤ 1% on held-out data (and ≤ 2% on the model's own on-policy traffic: 3.1%). + +Met by the gate refit: heal FIR ≤ 0.5% on the `failure` trigger on held-out data (now 0.19–0.21%, was 0.66–0.74%). ## Parity and latency @@ -280,8 +325,8 @@ in browsers; neither was measured for this checkpoint. | `genclass-runtime-r17-fp16.onnx` | 13,569,879 B (13.6 MB) | `2958f4baf3e1e6a92c603f51559da05c97a7b6a3125879a1395f521a4549b628` | WebGPU with `shader-f16` | | `tokenizer.json` | 1,138,910 B (1.1 MB) | `11a0f913475cabb7568acc69f8fb884bbbde04edb513b9280c174b911f9e939a` | pruned byte-level BPE | | `calibration.json` | 501 B | `843c1131bfbf947b2172392d96dcdceae1e0e0ee770febc2cb3dd0a49ab767d4` | per-kind temperatures | -| `meta.json` | 6,079 B | `0308b212152f93725fd48cdd5d81638e903bded575439232f499ca75ba2550de` | ids, graph signature, quantisation, `gate`, and the fitting records (`gate_fit`, `report_fit`, `gate_q8_check`) | -| `model.json` | 999 B | `fb682536d89da304c32a16b747eb1b1ad2c57b169ea1ee1b64caaa70ae490bbc` | manifest: variants and hashes of the files above | +| `meta.json` | 2,602 B | `c335894748d9e1ba09885968c902adc10bbd4e816b4f2e852a5f4fe92be0eb50` | ids, graph signature, quantisation, `gate`, and the fitting record `gate_fit` (data, limits, rules, refit date, the test-informed `failure` value) | +| `model.json` | 999 B | `9e2a42bd7948014d5320104fd56f541b1d7216055d4eb858f1bbe50783afff20` | manifest: variants and hashes of the files above | Every file is under jsDelivr's 20 MB per-file limit. diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md index f3ab78fe..fc0b4ce2 100644 --- a/packages/runtime/CHANGELOG.md +++ b/packages/runtime/CHANGELOG.md @@ -6,17 +6,20 @@ (`genclass-runtime-r17` 2.0.0-rc2, checkpoint `r17-v2b`) from jsDelivr. The model is 9.6 MB (q8, WASM) and is cached after the first load. On held-out data: - Diagnosis: 84.2% on simulated apps and 83.6% on real apps. - - False interventions: 0.02% (guard) and 0.23% (heal) on simulated apps; none were seen on held-out real apps. - - Recall is low: guard acts on 1.2% of clear simulated cases; heal on 5.7% of them and on 8.5% of actionable + - False interventions: 0.01% (guard) and 0.07% (heal) on simulated apps; none were seen on held-out real apps. + - Recall is low: guard acts on 0.7% of clear simulated cases; heal on 2.9% of them and on 5.7% of actionable real-app cases. - - In observe mode, 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong get flagged. + - In observe mode, 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong get flagged (3.1% on the + model's own on-policy simulated traffic). Numbers, gates and limits are in the model card (`@genclass/runtime-model`, `MODEL_CARD.md`). - **The model sets the gate thresholds** (runtime batch 6). The model's `meta.json` `gate` provides the report, guard and heal thresholds per trigger kind; `policy.thresholds` still overrides them. The shipped model uses: - report 0.85; - - guard 0.75–0.95; - - heal 0.55–1.0. + - guard 0.80 (mutation 0.95); + - heal 0.85 (failure 0.95). + + These were refit on the model's own on-policy traffic before release. `rt.gates(trigger)` shows the values in force and where each came from. Decisions record the threshold and its source, and the devtools overlay shows the gates. Also in batch 6: a request with no latency baseline counts as a diff --git a/packages/runtime/README.md b/packages/runtime/README.md index 413bfc70..22a3dcba 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -33,8 +33,8 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known > - Diagnosis is right on about 84% of held-out decisions (83.6% on real apps). > - It flags 1.4% (simulated apps) to 3.8% (real apps) of held-out decisions where nothing was wrong. On real apps, > most of those came from one app. -> - In `guard` / `heal` it intervened wrongly on 0.02% / 0.23% of held-out simulated cases, and never on held-out -> real apps, but it acts on only 1–9% of the cases where acting would help. +> - In `guard` / `heal` it intervened wrongly on 0.01% / 0.07% of held-out simulated cases, and never on held-out +> real apps, but it acts on under 6% of the cases where acting would help. > > Details: [Model quality](#model-quality) and the > [model card](https://www.npmjs.com/package/@genclass/runtime-model). @@ -69,7 +69,7 @@ started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which user action (#7). (stale, 0.96) ``` -The same run in guard mode. The model's `discard` (0.98) passed the model's delivery gate (0.75), so the results +The same run in guard mode. The model's `discard` (0.98) passed the model's delivery gate (0.80), so the results for "reac" stayed: ``` @@ -190,14 +190,15 @@ These hold for the runtime; whether the model's decisions are good is a separate | mode | what it does | non-passive actions | gate (default model) | |---|---|---|---| | `observe` (**default**) | Reports what it sees and what it would have done. Never holds a request, never runs an action. | none | n/a | -| `guard` (opt-in) | Also prevents failures with guard-tier actions: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down. | guard tier | summed probability of the permitted actions ≥ the trigger's guard threshold (delivery 0.75, request 0.75, mutation 0.95), and the top diagnosis is not `expected` | -| `heal` (**experimental**) | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions. | guard + heal tier | heal actions ≥ the trigger's heal threshold (transition 0.55, inconsistency 0.80, default 0.85, failure 0.90; 1.0 on requests, so effectively never there), guard actions as in guard mode, diagnosis not `expected` | +| `guard` (opt-in) | Also prevents failures with guard-tier actions: `discard`, `defer`, `coalesce`, `delay`. These withhold, deduplicate or slow something down. | guard tier | summed probability of the permitted actions ≥ the trigger's guard threshold (delivery 0.80, request 0.80, mutation 0.95), and the top diagnosis is not `expected` | +| `heal` (**experimental**) | Also recovers: `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync`, plus your own actions. | guard + heal tier | heal actions ≥ the trigger's heal threshold (0.85 on every trigger except failure, 0.95), guard actions as in guard mode, diagnosis not `expected` | ```ts GenClass.init({ mode: "guard" }); ``` -- **Where the thresholds come from.** They were fitted on held-out data and ship in the model's `meta.json` +- **Where the thresholds come from.** They were fitted on held-out dev data, including the model's own on-policy + traffic, and ship in the model's `meta.json` ([model card](https://www.npmjs.com/package/@genclass/runtime-model)). A model without a `gate` gets the runtime's defaults: report 0.6, guard 0.9, heal 0.8. `policy.thresholds: { report, guard, heal }` overrides both. `rt.gates(trigger)` shows the values in force and where each came from (`"policy"`, `"model"` or `"default"`). @@ -413,10 +414,10 @@ Full tables, per-trigger gates and how each threshold was fitted: the | **Observe:** decisions flagged where nothing was wrong (report 0.85) | 1.41% (149 / 10,582) | 3.78% (305 / 8,079); 1.05% without one app | | Observe: problem decisions flagged | 65% | 61% | | Observe: flags with the right diagnosis | 94% | 89% | -| **Guard:** false interventions | 0.02% (2 / 8,987) | 0.00% (0 / 66) | -| Guard: clear cases acted on | 1.2% | – | -| **Heal:** false interventions | 0.23% (38 / 16,290) | 0.00% (0 / 1,124) | -| Heal: cases acted on | 5.7% of clear cases | 8.5% of actionable cases | +| **Guard:** false interventions | 0.01% (1 / 8,987) | 0.00% (0 / 66) | +| Guard: cases acted on | 0.7% of clear cases | 0.0% of actionable cases | +| **Heal:** false interventions | 0.07% (11 / 16,290) | 0.00% (0 / 1,124) | +| Heal: cases acted on | 2.9% of clear cases | 5.7% of actionable cases | What this means in practice: @@ -427,8 +428,8 @@ What this means in practice: - Raise `policy.thresholds.report` to see fewer flags. At 0.9: 0.9% (simulated) and 3.4% (real) false, with 58% and 52% of problems flagged. - **Guard (opt-in).** When it acts, it is almost always right, but it rarely acts. Expect it to miss most problems. -- **Heal (experimental).** On held-out simulated apps, heal actions on failures (`retry`, `serve_cached`) were wrong - on 0.66% of the failures where doing nothing was best. That is over the 0.5% target the thresholds were fitted to. +- **Heal (experimental).** Heal actions on failures (`retry`, `serve_cached`) are the least precise: wrong on 0.19% + of held-out simulated failures where doing nothing was best (target 0.5%), at a failure threshold of 0.95. - **Not yet met:** diagnosis ≥ 95%, clear-case recall ≥ 80%, and false flags ≤ 1% on held-out data. Training continues (a larger teacher model, distillation, more real-app data). - **Format.** The model was trained on situations rendered by the runtime at `situation-v2`. This version renders @@ -516,8 +517,7 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - In observe mode, expect some false flags: 1–4 per 100 decisions where nothing was wrong, more in some apps. - It misses most problems. - It was not evaluated on your app. - - Heal-mode actions on failures (`retry`, `serve_cached`) exceeded their false-intervention target on held-out - data. + - Heal-mode actions on failures (`retry`, `serve_cached`) are its least precise actions. Watch observe mode before turning on `guard` or `heal`. - **Redaction gaps (all modes with a model).** From da97588ab8d47979575b8c0d41bb238213412d13 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 09:45:46 -0400 Subject: [PATCH 19/25] docs: record @genclass/runtime 0.1.0-beta.0 and @genclass/runtime-model 0.1.0 on npm Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 ++++----- OPEN_TASKS.md | 13 +++++++++---- RELEASE.md | 8 +++++--- docs/agents/runtime/build-test-release.md | 13 +++++++------ docs/agents/status-and-known-issues.md | 8 ++++---- packages/runtime/CHANGELOG.md | 2 +- 6 files changed, 30 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d92e52d0..9fbaee53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,10 +57,9 @@ Read next: **[HANDOFF.md](HANDOFF.md)** (the team's live handoff, kept current b teacher, 88 ranks, launched 05:20 UTC, ETA ≈ 08:30) per `training/LOG.md`. Not in this branch but on `origin/runtime` (416e374, `docs/runtime/RESULTS.md`): r17-v2a finished, `sim2e` diagnosis 84.4%, action 77.9%, guard FIR 0.00%, heal FIR 0.46%, recall at the fixed gates very low. REAL `v2c*` gold had not landed at eff18cb. -- **Model: none published** (`@genclass/runtime-model` 404), so `packages/runtime/src/model/host.ts` -> - `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` fail: a default `GenClass.init()` ends with model status `error` - and logs `[GenClass] Model unavailable (...); observing only.` -- **npm:** `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296: NaN fix, situation-v2, +- **Model: published** (2026-10-08 ~13:40 UTC): `@genclass/runtime-model@0.1.0` (`r17-v2b`, `latest`). `packages/runtime/src/model/host.ts` -> + `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` (both the jsDelivr `files/` directory) now resolve. +- **npm (updated 2026-10-08 ~13:40 UTC):** `@genclass/runtime@0.1.0-beta.0` is `latest` (from 1f0f617; install paths, fixes, batch 6+, ships with the model); `0.1.0-alpha.0` is deprecated. Older note: `@genclass/runtime@0.1.0-alpha.1` was `latest` (published 2026-10-08 from 806a296: NaN fix, situation-v2, default `observe`). It does **not** contain the install paths (`./auto` exports, `dist/cdn/`, the global build, `init`/`remove`) nor the two fixes. **The next release** (`0.1.0-alpha.2`, or a beta together with the v2 model once validated) carries them. `packages/runtime/package.json` and `packages/genclass-runtime/package.json` still say @@ -167,7 +166,7 @@ demos eval, Python tests, training. One test: `npx vitest run test/delivery.test |---|---|---| | `packages/runtime/` | `@genclass/runtime`: `src/` (incl. `auto.ts`, `cdn/`), `test/` (incl. `install/`), `bin/genclass-runtime.mjs` CLI (`init`, `remove`, `fetch-model`, `info`; `init`/`remove` in `bin/lib/`), `STATUS.md` (runtime state, example situations, deviations), `CHANGELOG.md`, `INSTALL-NEEDS.md` (INSTALL's requests), `UI-NEEDS.md` | [runtime/](docs/agents/runtime/public-api-and-lifecycle.md) (8 docs; start with public-api-and-lifecycle and [build-test-release](docs/agents/runtime/build-test-release.md)), [model-io-contract](docs/agents/model-io-contract.md) | | `packages/genclass-runtime/` | unscoped alias `genclass-runtime` 0.1.0-alpha.1 (unpublished): `cli.mjs` forwards to `@genclass/runtime`'s CLI so `npx genclass-runtime init` could work; a workspace | [repo-map](docs/agents/repo-map.md) | -| `packages/runtime-model/` | only `MODEL_CARD.md` of the unpublished model package | [model-host](docs/agents/runtime/model-host.md) | +| `packages/runtime-model/` | only `MODEL_CARD.md` of the model package (published as `@genclass/runtime-model@0.1.0`; files come from the export) | [model-host](docs/agents/runtime/model-host.md) | | `sim/` | `@genclass/sim`: deterministic training-data simulator (S1/S2 labels, `SEPARABILITY.md`) | [sim.md](docs/agents/sim.md) | | `realapps/` | 128 app directories with a `manifest.ts` (Mehar's commits say 96 after wave 3; wave-4 apps arrived inside f3a9dd1/eff18cb), incl. 14 open-source Conduit front-ends, in headless Chromium; REAL rows and the never-worse sweep | [realapps.md](docs/agents/realapps.md) | | `training/` | Python training, curriculum (`curriculum/rt.py`), eval, export, Azure launch scripts; `NEEDS.md`, `LOG.md`, `EVAL.md` | [training.md](docs/agents/training.md) | diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 024f65f4..4ab5e85e 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -6,11 +6,12 @@ release commit 806a296); `mvp-v2-merge` merges the two. Spec: [docs/runtime/CONTRACT.md](docs/runtime/CONTRACT.md). Results and numbers: [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md). The runtime decides through a trained local model; nothing here is hardcoded per bug pattern. -The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). No situation-v2 model is published yet (`@genclass/runtime-model` returns 404); the first -v2 runs are training (In progress). +The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). Since 2026-10-08 (~13:40 UTC) `@genclass/runtime-model@0.1.0` (`r17-v2b`) and +`@genclass/runtime@0.1.0-beta.0` are on npm (`latest`), so the default model URL resolves (Done). ## Done +- **Published `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88)** and **`@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`)**. jsDelivr serves `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`model.json` 200; all 5 files' sha256 match `model.json`). Browser check: a plain HTML page with the jsDelivr script tag (`genclass.global.min.js` @0.1.0-beta.0) in Chromium: mode `observe`, model ready in a Web Worker on WebGPU (fp16), `loadMs` 4750, every gate's source `model`, `decide()` 72 ms. `@genclass/runtime@0.1.0-alpha.0` deprecated: "Old situation-v1 build that defaults to guard; use 0.1.0-beta.0 or later". Nothing was pushed and no GitHub release was created (the user's GitHub account is read-only on daybot-solutions-inc/GenClass-lib). - **Published `@genclass/runtime@0.1.0-alpha.1` to npm** (published 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff). It ships the NaN fix (ad24804), the situation-v2 runtime (decisions at the network boundary via the `delivery` trigger; store writes not held by default), EventSource observed, synthetic DOM events ignored unless `observe: { untrustedEvents: true }`, default mode `observe` @@ -105,6 +106,10 @@ Mehar operates the Azure cluster; nobody else touches Azure. The jobs below run The usual order (HANDOFF.md): v2 data collected → teacher → labels → distillation → DAgger → EVAL → model package → demos rerun → runtime release. +- **Push `mvp-v2-b6` and the tags** (`v0.1.0-beta.0`, `runtime-model-v0.1.0`, `v0.1.0-alpha.1`) through an account with + write access to daybot-solutions-inc/GenClass-lib. GitHub releases for them are optional. +- **Model `0.2.0` (`r17-v2c`)**: the next model package. + 6. **Check the v2 data before training on it** (from the review findings): SIM samples budget 3,200 for ~40% of trajectories (`sim/src/world/scenario.ts` → `budget`), above the v2 device budgets; unlabeled rows hard-label `expected` diagnoses that S1 would relabel (`sim/src/gen/trajectory.ts` → `unlabeledTrajectory`; a relabel pass @@ -177,8 +182,8 @@ package → demos rerun → runtime release. ## Needs the user -- **2FA publishes:** the next prerelease with the one-command install (`0.1.0-alpha.2` or a beta with the model; - Next item 14), `@genclass/runtime-model@0.1.0` and `@genclass/runtime@0.1.0` (`0.1.0-alpha.1` is done). Agents +- **2FA publishes:** `@genclass/runtime@0.1.0` and the next model (`0.1.0-alpha.1`, `0.1.0-beta.0` and + `@genclass/runtime-model@0.1.0` are done). Agents prepare the tarball and the exact command per [RELEASE.md](RELEASE.md). - **Push** `mvp-v2` (head = release commit 806a296) and tag `v0.1.0-alpha.1` to origin (needs an account with write access). - **Install on Polar Parts** (`MeharPro/Polar-Parts`) once the trained model is good (user OK'd). Start in diff --git a/RELEASE.md b/RELEASE.md index 69a1c890..58b4276d 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -4,6 +4,8 @@ > **Read this when:** you are asked to cut a release, prepare a tarball for the user to publish, or package a trained model. > **Source of truth:** the code. Verified 2026-10-08 (~07:00 UTC) against branch `mvp-v2-merge` at f107013. That branch is `mvp-v2` (release commit 806a296), merged with origin/runtime eff18cb (dabbce2), plus the two runtime fixes 054da38 and f107013. Newer commits on origin/runtime (up to 5bc40c9) were read with `git show` and are not merged on this branch. If this doc and the code disagree, the code wins. +> **Done 2026-10-08 (~13:40 UTC): Part B and Part C.** Published `@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`) and `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88). `@genclass/runtime@0.1.0-alpha.0` deprecated: "Old situation-v1 build that defaults to guard; use 0.1.0-beta.0 or later". jsDelivr serves `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`model.json` 200; all 5 files' sha256 match `model.json`). Browser check: a plain HTML page with the jsDelivr script tag (`genclass.global.min.js` @0.1.0-beta.0) in Chromium: mode `observe`, model ready in a Web Worker on WebGPU (fp16), `loadMs` 4750, every gate's source `model`, `decide()` 72 ms. Nothing was pushed and no GitHub release was created (the user's GitHub account is read-only on daybot-solutions-inc/GenClass-lib); the CLI's `fetch-model` default is the jsDelivr model directory. Still open: push `mvp-v2-b6` and the tags (needs an account with write access); the GitHub releases (B5, C7) are optional. The rest of this doc is the procedure as planned. + ## TL;DR - **Versions.** @@ -33,7 +35,7 @@ - Agents ask first before Playwright, `smoke.sh`, the install end-to-end runs, model downloads, the demos eval, and anything that touches training or Azure. Mehar runs Azure (`HANDOFF.md`). - **Registry** (`npm view`, 2026-10-08 ~07:00 UTC): - `@genclass/runtime`: versions `0.0.0-stage`, `0.1.0-alpha.0`, `0.1.0-alpha.1`; `latest` = `0.1.0-alpha.1`, no other dist-tags. - - `@genclass/runtime-model`: **404**. + - `@genclass/runtime-model`: **404**. (Since 2026-10-08 ~13:40 UTC: `0.1.0` is `latest`; `@genclass/runtime` `latest` = `0.1.0-beta.0`, `0.1.0-alpha.0` deprecated. See the note at the top.) - `genclass-runtime` (unscoped alias): **404**, so the name is unregistered. - **The default model URL is pinned.** - `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. @@ -134,7 +136,7 @@ Runtime review findings still open (2026-10-08 review; see [Drift and open issue Step markers: **[agent]** is light and allowed locally. **[ask first]** needs the user's OK in chat. **[user only]** is run by the user with their npm 2FA, or by Mehar on his Azure setup. -## Part B: `@genclass/runtime-model@0.1.0` (first, once `r17-v2a` is validated) +## Part B: `@genclass/runtime-model@0.1.0` (done 2026-10-08 with `r17-v2b`; see the note at the top) ### B0. Gates before packaging anything @@ -269,7 +271,7 @@ scripts/vm.sh run demos 'GENCLASS_MODEL_URL=cdn setsid nohup bash demos/scripts/ `GENCLASS_MODEL_URL=cdn` loads the published package. Results go to `demos/results-runtime-model-0.1.0.{json,md}`; record them in `docs/runtime/RESULTS.md` §5. **Gate for Part C:** on clean runs, Observe and Guard introduce no bugs that Off does not have; report every fix count with its false interventions. -## Part C: `@genclass/runtime@0.1.0-beta.0` (or `0.1.0-alpha.2` without the model) +## Part C: `@genclass/runtime@0.1.0-beta.0` (done 2026-10-08; see the note at the top) Replace `0.1.0-beta.0` with `0.1.0-alpha.2` throughout if it goes out before Part B. diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index db1bee18..37d2cda1 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -20,7 +20,7 @@ - Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. Not run in CI. - `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. Not run in CI. - Install tests (`test/install/`, f3a9dd1): `cli.test.ts` is an ordinary vitest file (runs `bin/genclass-runtime.mjs init --yes --no-install` and `remove --yes` on fixture projects in the OS temp dir, no network) and runs locally and in CI. The rest is a VM harness (`run-all.sh` -> build + pack -> `cli.test.ts` -> `cdn-check.mjs` -> `scaffold.sh` -> `frameworks.mjs`; Playwright, framework generators, npm registry; outputs under `/data/install`). Mehar's last run is in `test/install/RESULTS.md` (15/15 projects, CLI 20/20, CDN 26/26, against a locally packed `0.1.0-alpha.0`-versioned tarball). Not run in CI. -- Released: `@genclass/runtime@0.1.0-alpha.1` on npm, 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. Before it: `@genclass/runtime@0.1.0-alpha.0` (was `latest`; checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). **The published `0.1.0-alpha.1` does not contain Mehar's one-command install** (`init`/`remove`, `/auto`, the CDN script tag, the `genclass-runtime` alias, f3a9dd1): those came in with the merge of origin/runtime eff18cb, after the publish. npm versions are immutable, so they ship in the **next** version (`0.1.0-alpha.2`, or a beta together with the model); `packages/runtime/package.json` still says `0.1.0-alpha.1` on `mvp-v2-merge` and must be bumped before packing. Pending: that next runtime version, `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. +- Released (latest): `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88), and `@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`); `0.1.0-alpha.0` deprecated. See [Publish history](#publish-history-from-git-and-the-registry). Earlier: `@genclass/runtime@0.1.0-alpha.1` on npm, 2026-10-08 (~05:33 UTC) by `karanvir1729` under dist-tag `latest`, from release commit 806a296 (local annotated tag `v0.1.0-alpha.1`, not pushed); 26 files, 486.8 kB, shasum 9e3e82bcf752d6eb34db0620d072e6a913508dff. Before it: `@genclass/runtime@0.1.0-alpha.0` (was `latest`; checked with `npm view` 2026-10-08; the registry also lists a `0.0.0-stage` version published four minutes earlier), git tag `v0.1.0-alpha.0` on 654d822. That tarball predates situation-v2 and still defaults to `guard`. Release recipe from `HANDOFF.md`: the user runs `npm publish --access public` with 2FA; for a prerelease such as `0.1.0-alpha.1`, npm 11 (11.8.0 on the lead's machine) refuses that command without `--tag` (see [Cut a release](#cut-a-release-of-genclassruntime)). **The published `0.1.0-alpha.1` does not contain Mehar's one-command install** (`init`/`remove`, `/auto`, the CDN script tag, the `genclass-runtime` alias, f3a9dd1): those came in with the merge of origin/runtime eff18cb, after the publish. npm versions are immutable, so they ship in the **next** version (`0.1.0-alpha.2`, or a beta together with the model); `packages/runtime/package.json` still says `0.1.0-alpha.1` on `mvp-v2-merge` and must be bumped before packing. Pending: that next runtime version, `@genclass/runtime-model@0.1.0` (404 today) and `@genclass/runtime@0.1.0`. - `sim` and `demos` depend on `"@genclass/runtime": "*"` (workspace symlink), which resolves to `packages/runtime/dist/`: **build the runtime first**. `realapps` bundles `packages/runtime/src` directly with esbuild (see [../realapps.md](../realapps.md)). ## Files @@ -388,8 +388,8 @@ Earlier pass (b435acb, fresh clone): `npm ci` OK from the committed lockfile (EB | `setup()` `mode` | test | `"guard"` | `test/helpers.ts` -> `setup` | override with `mode: undefined` for the product default | | `policy.holdWrites` | option | `false` (unset) | `src/types.ts` -> `PolicyOptions.holdWrites` | tests about held store writes pass `true` | | `MockRuntime.situationBudget()` | test | `2400` (was `3200`) | `test/browser/ui/mock-runtime.ts` | matches the v2 full budget | -| `DEFAULT_MODEL_BASE_URL` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default model location = the unpublished package | -| CLI `DEFAULT_FROM` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (= `DEFAULT_MODEL_BASE_URL`) | `bin/genclass-runtime.mjs` | default `fetch-model --from` (404 until the model package is published) | +| `DEFAULT_MODEL_BASE_URL` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `src/model/host.ts` | default model location = `@genclass/runtime-model@0.1.0` (published 2026-10-08) | +| CLI `DEFAULT_FROM` | const | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (= `DEFAULT_MODEL_BASE_URL`) | `bin/genclass-runtime.mjs` | default `fetch-model --from` (resolves since 2026-10-08) | | test env vars | env | `GENCLASS_MODEL_DIR`, `NODE_OPTIONS=--expose-gc`, `GENCLASS_BENCH_MODELS="name=dir,..."`, `GENCLASS_WEBGPU_VARIANTS=`, `GENCLASS_OFFLINE=1` | test files | see Tests | | `HAVE_MODEL` | test | `existsSync(/model.json)` | `test/browser/model-helpers.ts` | every model spec calls `test.skip(!HAVE_MODEL, ...)` | | `DEFAULT_CACHE_NAME` | const | `"genclass-runtime-v1"` | `src/model/loader.ts` | Cache Storage bucket; default of `window.GC.cacheKeys()` | @@ -521,9 +521,10 @@ The format is frozen at `situation-v2` and v2 training data is being generated f | 2026-10-08 00:50 / 01:12 -0400 | 29b7f28, f3a9dd1 (origin/runtime, Mehar) | situation purity test; one-command install, `/auto`, script tag + CDN builds, `genclass-runtime` alias. f3a9dd1's subject says "0.1.0-alpha.1" and `CHANGELOG.md` lists these under `0.1.0-alpha.1`, but they were never in the published tarball (built from 806a296 on `mvp-v2`) | | 2026-10-08 ~05:33 UTC (01:33 -0400) | 806a296, local tag `v0.1.0-alpha.1` (not pushed) | `@genclass/runtime@0.1.0-alpha.1` published by karanvir1729 under `latest` (26 files, 486.8 kB, shasum 9e3e82bc...); first attempt 403 (no 2FA on the account), then browser-based 2FA approval | | 2026-10-08 02:08 / 02:09 -0400 | dabbce2, 10e5c3b (`mvp-v2-merge`) | merge of origin/runtime eff18cb into `mvp-v2`; lockfile re-synced (adds the alias workspace) | -| 2026-10-08 02:47 -0400 | 054da38, f107013 (`mvp-v2-merge`) | observe mode never holds or delays deliveries (`observe-delivery.test.ts`); redaction of F2 diffs and numeric/array secrets (`redaction-v2.test.ts`). Unreleased | +| 2026-10-08 02:47 -0400 | 054da38, f107013 (`mvp-v2-merge`) | observe mode never holds or delays deliveries (`observe-delivery.test.ts`); redaction of F2 diffs and numeric/array secrets (`redaction-v2.test.ts`). Released in 0.1.0-beta.0 | +| 2026-10-08 ~13:40 UTC | 1f0f617 (`release/runtime-0.1.0-beta.0`), local tags `v0.1.0-beta.0`, `runtime-model-v0.1.0` (not pushed) | by karanvir1729 with 2FA: `@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`); `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88); `@genclass/runtime@0.1.0-alpha.0` deprecated: "Old situation-v1 build that defaults to guard; use 0.1.0-beta.0 or later". jsDelivr serves `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`model.json` 200; all 5 files' sha256 match `model.json`). No GitHub release | -`package.json` `version` is still `0.1.0-alpha.1` on `mvp-v2-merge`, although the tree now contains everything after 806a296 (install features, observe/redaction fixes). The next release bumps it (`0.1.0-alpha.2`, or a beta with the model). What `.publish/` was used for is not recorded (unverified). +`package.json` `version` is `0.1.0-beta.0` from 1f0f617 on (published). Earlier note: it was still `0.1.0-alpha.1` on `mvp-v2-merge`, although the tree now contains everything after 806a296 (install features, observe/redaction fixes). The next release bumps it (`0.1.0-alpha.2`, or a beta with the model). What `.publish/` was used for is not recorded (unverified). ### Cut a release of `@genclass/runtime` @@ -672,7 +673,7 @@ Open items in scope (from `OPEN_TASKS.md`, `HANDOFF.md`, `training/NEEDS.md`, ST - **`0.1.0-alpha.1`**: published 2026-10-08 from `mvp-v2` (806a296) under `latest`. Still open: push the branch and tag `v0.1.0-alpha.1` to origin (needs an account with write access and the user's OK). - **Next runtime version** (`0.1.0-alpha.2`, or a beta with the model): carries the install features and the observe/redaction fixes from `mvp-v2-merge`. Before packing: bump the runtime and alias versions together, fix the CHANGELOG heading, run the install harness on the release tree (ask first). The user publishes (2FA, `--tag` for a prerelease). - **Push and first CI run**: `mvp-v2` / `mvp-v2-merge` (with `.github/workflows/ci.yml`) are local only; pushing needs the user's OK, and Mehar (asleep at the time of writing) should see the merge before it lands on `runtime`. Until then CI has never run on GitHub (the `review-perf` retry, `ONNXRUNTIME_NODE_INSTALL=skip` and `cli.test.ts` on Linux are verified only locally on macOS). -- **Model package**: blocked on v2 training. v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled rows); on 2026-10-08 Mehar's Azure jobs `r17-v2a` (R17 on v2 gold, auto eval + export via `training/v2_post.sh`) and `t150-v2a` (150M teacher) ran unattended. `r17-v2a` has since finished: origin/runtime 416e374 records its eval (guard FIR 0.00%, but the fixed gates block nearly every action), and 5bc40c9 (batch 6) makes the gates come from the model's `meta.json`; neither is merged here. The teacher's status is not recorded in the repo. Then teacher labels, distillation, DAgger, EVAL. Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. +- **Model package**: done 2026-10-08 (`@genclass/runtime-model@0.1.0` = `r17-v2b`; the default model URL resolves). Next: `0.2.0` (`r17-v2c`). Historical note: was blocked on v2 training. v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled rows); on 2026-10-08 Mehar's Azure jobs `r17-v2a` (R17 on v2 gold, auto eval + export via `training/v2_post.sh`) and `t150-v2a` (150M teacher) ran unattended. `r17-v2a` has since finished: origin/runtime 416e374 records its eval (guard FIR 0.00%, but the fixed gates block nearly every action), and 5bc40c9 (batch 6) makes the gates come from the model's `meta.json`; neither is merged here. The teacher's status is not recorded in the repo. Then teacher labels, distillation, DAgger, EVAL. Then `@genclass/runtime-model@0.1.0` + GitHub release `runtime-model-v0.1.0`, demos rerun, `@genclass/runtime@0.1.0`. Until then the default model URL 404s and the runtime only observes. - Docs (OPEN_TASKS item 17): whether a dev-only lazy import of the devtools is still needed is open; the README's "52 KB minified / 17 KB gzip" is unverified (see [devtools.md](devtools.md)). - The VM path (`scripts/vm.sh`) depends on Mehar's hosts file and SSH key. Without them the light checks run locally under the run policy in AGENTS.md; anything heavier needs the user's go-ahead. - Any situation-wording change must be coordinated with SIM, REAL and TRAIN (frozen at `situation-v2`). diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index afd6f79b..788c1ad8 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -35,7 +35,7 @@ paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.t local tag `v0.1.0-alpha.1` not pushed): NaN fix, situation-v2, default `observe`, no model. It has **none of Mehar's install paths** (`npm view @genclass/runtime@0.1.0-alpha.1 exports` has no `./auto*`; `sideEffects: false`) and neither fix below. Before it, `0.1.0-alpha.0` (tag `v0.1.0-alpha.0` = 654d822): situation-v1, `guard` default, NaN - crash. `@genclass/runtime-model` is **not published** (404). + crash. **Since 2026-10-08 ~13:40 UTC:** `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88) and `@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`); `0.1.0-alpha.0` deprecated; the default model URL resolves. - **Next release** (`0.1.0-alpha.2`, or a beta together with the v2 model once it is validated; `OPEN_TASKS.md` Next 14): the install paths, the two fixes, and whatever of `origin/runtime` is merged by then. Before any build or pack meant to ship, bump `packages/runtime/package.json` (still `0.1.0-alpha.1`; the global build bakes the version into @@ -237,7 +237,7 @@ model-provided gate thresholds, no-baseline stall fallback; tag `situation-v2.1` | tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1 (`latest`); local only, not pushed | | `packages/runtime/package.json` `version` | `0.1.0-alpha.1` | **already published**: bump before building or packing the next release | | `packages/genclass-runtime/package.json` | `0.1.0-alpha.1`, dependency `@genclass/runtime` `0.1.0-alpha.1` | unpublished alias (no `genclass-runtime` on npm) | -| `@genclass/runtime-model@0.1.0` | not published (404); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | +| `@genclass/runtime-model@0.1.0` | published 2026-10-08 (`latest`, `r17-v2b`, shasum 84f33344...); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | | GitHub release `runtime-model-v0.1.0` | no such tag in the repo (we have no write access to releases); no longer the CLI's default `--from` (now the jsDelivr directory, = `DEFAULT_MODEL_BASE_URL`), but still the published `0.1.0-alpha.1` CLI's | optional (RELEASE.md B5) | | v0.1 GenClass model | `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` | general classifier, **not** a runtime model; used by demos and model tests | | R17-final1 / R32-final1 | situation-v1; on the `train` VM (`~/gcl/train-out/final1/`) and Mehar's Mac (`packages/runtime-model/files/r17/`, gitignored) | baseline only; does not match the v2 runtime | @@ -376,8 +376,8 @@ Status-relevant values only; the subsystem docs list the rest. |---|---|---|---| | default mode | `"observe"` | `runtime.ts` -> `RuntimeImpl` constructor (`o.mode ?? "observe"`) | no actions unless `mode: "guard"`/`"heal"`, `?genclass=guard`, or `setMode` | | test-harness mode | `"guard"` | `test/helpers.ts` -> `setup` | CORE tests exercise interventions; `setup({ mode: undefined })` gives the product default | -| `DEFAULT_MODEL_BASE_URL` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | unpublished → status `error`, observe only | -| `DEFAULT_FROM` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `bin/genclass-runtime.mjs` | `fetch-model` default source (= `DEFAULT_MODEL_BASE_URL`); 404 until the model package is published | +| `DEFAULT_MODEL_BASE_URL` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | resolves since 2026-10-08 (model `0.1.0` on npm/jsDelivr) | +| `DEFAULT_FROM` | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `bin/genclass-runtime.mjs` | `fetch-model` default source (= `DEFAULT_MODEL_BASE_URL`); resolves since 2026-10-08 | | `STATE_CHAR_BUDGET` | 2400 (was 3200 in v1) | `situation/serialize.ts` | full situation budget (≈ 1,000 tokens at the measured 2.4 chars/token) | | `COMPACT_BUDGET` / `COMPACT_QUESTIONS_BUDGET` | 1100 / 1400 | `situation/serialize.ts` / `situation/questions.ts` | section-limit floor / bare-label questions | | auto situation budget | webgpu and unknown device 2,400; wasm `1000 + round((threads − 1) × 1000 / 3)`, threads clamped 1–4; × `budgetScale` (× 0.8 per `max_tokens_exceeded`, floor 0.5) | `RuntimeImpl.situationBudget` | device sizing; a numeric `situation.budget` wins | diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md index fc0b4ce2..c7ef6de7 100644 --- a/packages/runtime/CHANGELOG.md +++ b/packages/runtime/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.1.0-beta.0 +## 0.1.0-beta.0 (2026-10-08) - **Ships with a model.** A default `GenClass.init()` now loads `@genclass/runtime-model@0.1.0` (`genclass-runtime-r17` 2.0.0-rc2, checkpoint `r17-v2b`) from jsDelivr. The model is 9.6 MB (q8, WASM) and is From c465b1f4ba301e47cf9d9716b88407b520a365cc Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 09:51:17 -0400 Subject: [PATCH 20/25] docs: the model is published; update remaining agent docs Co-Authored-By: Claude Opus 5.5 --- HANDOFF.md | 11 +++-- docs/agents/README.md | 10 ++-- docs/agents/demos.md | 2 +- docs/agents/extension-and-benchmarks.md | 2 +- docs/agents/genclass-model-lineage.md | 6 +-- docs/agents/glossary.md | 20 ++++---- docs/agents/model-io-contract.md | 10 ++-- docs/agents/overview.md | 46 ++++++++++--------- docs/agents/playbooks.md | 14 +++--- docs/agents/repo-map.md | 24 +++++----- docs/agents/runtime/build-test-release.md | 6 +-- docs/agents/runtime/decide-policy-actions.md | 5 +- docs/agents/runtime/learn-situation-triage.md | 4 +- docs/agents/runtime/model-host.md | 22 ++++----- docs/agents/runtime/observe-and-trace.md | 2 +- .../runtime/public-api-and-lifecycle.md | 18 ++++---- docs/agents/runtime/state-and-adapters.md | 2 +- docs/agents/sim.md | 2 +- docs/agents/status-and-known-issues.md | 24 +++++----- docs/agents/training.md | 2 +- packages/runtime/test/install/RESULTS.md | 4 +- 21 files changed, 123 insertions(+), 113 deletions(-) diff --git a/HANDOFF.md b/HANDOFF.md index 97eb3ae8..84e570cb 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -26,10 +26,10 @@ generic action. It has no hardcoded bug rules. | piece | state | |---|---| -| npm | `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296; NaN fix, situation-v2, default `observe`); `0.1.0-alpha.0` is the older v1 build (org `genclass`, owner meharpro). The alphas take no actions: there is no published model yet. Each publish needs the user's 2FA, so give them the exact `npm publish --access public` command. | +| npm | `@genclass/runtime@0.1.0-beta.0` is `latest` (published 2026-10-08 ~13:40 UTC from 1f0f617; default `observe`, loads the model by default) and `@genclass/runtime-model@0.1.0` is `latest` (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2; the default model URL `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` resolves). `0.1.0-alpha.1` (806a296, no model) was `latest` before; `0.1.0-alpha.0` (older v1 build) is deprecated (org `genclass`, owner meharpro). Each publish needs the user's 2FA, so give them the exact `npm publish --access public` command. | | git | Branch `runtime` (also fast-forwarded into `main` once). Tags: `situation-v1` (old format), `situation-v2` (**current frozen training format**, commit 6e5e86e), `v0.1.0-alpha.0` (GitHub pre-release). | | runtime | Batch 5 done; 346 tests pass. Decisions happen at the network boundary (`delivery` trigger). Store writes are never held by default. The never-worse sweep over 66 real apps with an always-passive model changed 0/396 clean runs. | -| model | Round 1 (v1 data): R17 9.6 MB, guard false-intervention rate (FIR) 0.05%, recall on clear cases only ~8%. The cause is analysed in `sim/SEPARABILITY.md`; the fixes are in v2. **No v2 model trained yet.** | +| model | Round 1 (v1 data): R17 9.6 MB, guard false-intervention rate (FIR) 0.05%, recall on clear cases only ~8%. The cause is analysed in `sim/SEPARABILITY.md`; the fixes are in v2. Since 2026-10-08 the v2 model `r17-v2b` is published as `@genclass/runtime-model@0.1.0` (gates guard 0.80 {mutation 0.95}, heal 0.85 {failure 0.95, inconsistency 0.85}, report 0.85). | | data | SIM is generating about 10M gold + 50M unlabeled rows on v2 (20 Azure nodes) into `train:/data/sim-out/v2-*`. REAL is generating about 495k real-browser gold rows (c01, c10, c11) into `train:/data/real-out/`. Locations are in `training/NEEDS.md`. | | training | Next: 150M teacher on v2 gold, then teacher-labels the unlabeled rows, then distil R17 (default) and R32, then DAgger via SIM `--on-policy`. Plan: `training/PLAN-v1.md`; log: `training/LOG.md`; eval: `training/EVAL.md`. | @@ -79,7 +79,8 @@ generic action. It has no hardcoded bug rules. ``` Then check the job logs on the nodes, as described in each agent's README/LOG. -3. Pick up the next unfinished item in `OPEN_TASKS.md`. The usual order is: v2 data collected → teacher → - distillation → EVAL → model package `@genclass/runtime-model@0.1.0` (the default CDN URL the runtime loads) → - rerun the demos with the trained model → `@genclass/runtime@0.1.0` (2FA by the user). +3. Pick up the next unfinished item in `OPEN_TASKS.md`. The usual order was: v2 data collected → teacher → + distillation → EVAL → model package `@genclass/runtime-model@0.1.0` (the default CDN URL the runtime loads; + published 2026-10-08 together with `@genclass/runtime@0.1.0-beta.0`) → rerun the demos with the trained model → + `@genclass/runtime@0.1.0` (2FA by the user). 4. Report honestly: false-intervention rate next to every recall or bug-fix number. diff --git a/docs/agents/README.md b/docs/agents/README.md index bfd07548..b5a0e925 100644 --- a/docs/agents/README.md +++ b/docs/agents/README.md @@ -21,10 +21,10 @@ For live state and results, also use the human sources [HANDOFF.md](../../HANDOF Five facts change how you should read every other doc: -- **The situation format is frozen at tag `situation-v2`** (6e5e86e, runtime batch 5). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts` (the default mode), `types.ts` (its JSDoc) and `devtools/index.ts` (mode labels); no model-visible code changed. The old tag `situation-v1` (1a77558) is the format of all data and models trained so far, so **no trained model matches the current runtime**. Any change to text the model reads needs the user's go-ahead (coordinate with the colleague who runs SIM/REAL/TRAIN), a new tag, regenerated SIM and realapps data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). +- **The situation format is frozen at tag `situation-v2`** (6e5e86e, runtime batch 5). `git diff situation-v2 b435acb -- packages/runtime/src` touches only `runtime.ts` (the default mode), `types.ts` (its JSDoc) and `devtools/index.ts` (mode labels); no model-visible code changed. The old tag `situation-v1` (1a77558) is the format of the round-1 data and models (R17/R32-final1), which do not match the current runtime. The published `@genclass/runtime-model@0.1.0` (`r17-v2b`, 2026-10-08) is trained on `situation-v2` data (the `0.1.0-beta.0` runtime renders `situation-v2.3`; see `packages/runtime-model/MODEL_CARD.md`). Any change to text the model reads needs the user's go-ahead (coordinate with the colleague who runs SIM/REAL/TRAIN), a new tag, regenerated SIM and realapps data, a `training/curriculum/rt.py` mirror and retraining. See [model-io-contract.md](model-io-contract.md). - **Decisions happen at the network boundary.** situation-v2 adds the `delivery` trigger (a fetch/XHR response or a WebSocket/EventSource message about to reach the app; actions `deliver` / `discard` / `defer`) and no longer holds store writes by default (`policy.holdWrites: false`). Older docs and the human docs often still describe held store writes. See [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md). -- **The default mode is `observe`** on `mvp-v2` (our commit f3636b2: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`). `guard` is opt-in and `heal` experimental. The published `@genclass/runtime@0.1.0-alpha.1` (`latest`) also defaults to `observe`; the older `0.1.0-alpha.0` (situation-v1 code) defaults to `guard`, and so does `HANDOFF.md` (both READMEs now say `observe`). The unit-test harness (`packages/runtime/test/helpers.ts` -> `setup`) passes `mode: "guard"`. See [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). -- **No model is published, so every install only observes.** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0`, which is a 404 on npm, as is the CLI's `DEFAULT_FROM`. A default `GenClass.init()` ends in model status `error` and never decides. The situation-v2 model comes from the scaled program in [training.md](training.md) (teacher -> distillation -> DAgger -> EVAL -> export). See [runtime/model-host.md](runtime/model-host.md). +- **The default mode is `observe`** on `mvp-v2` (our commit f3636b2: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` constructor, `o.mode ?? "observe"`). `guard` is opt-in and `heal` experimental. The published `@genclass/runtime@0.1.0-beta.0` (`latest` since 2026-10-08 ~13:40 UTC) and the earlier `0.1.0-alpha.1` also default to `observe`; the older `0.1.0-alpha.0` (situation-v1 code, now deprecated) defaults to `guard`, and so does `HANDOFF.md` (both READMEs now say `observe`). The unit-test harness (`packages/runtime/test/helpers.ts` -> `setup`) passes `mode: "guard"`. See [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md). +- **The model is published (2026-10-08).** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2; gates guard 0.80 {mutation 0.95}, heal 0.85 {failure 0.95, inconsistency 0.85}, report 0.85), which resolves, as does the CLI's `DEFAULT_FROM`. A default `GenClass.init()` loads the model and decides, but in the default `observe` mode it takes no actions; `guard`/`heal` act. A Chromium check (2026-10-08, jsDelivr script tag) loaded it in a Web Worker on WebGPU (fp16) in 4.75 s, and `decide()` answered in 72 ms. Before 2026-10-08 the URL was a 404 and every install ended in model status `error`. The model comes from the scaled program in [training.md](training.md) (teacher -> distillation -> DAgger -> EVAL -> export). See [runtime/model-host.md](runtime/model-host.md). - **Run policy for agents** (set by the lead for this machine; `HANDOFF.md`'s "never run npm/tsc/vitest on the Mac" rule is about the colleague's 8 GB Mac): - You may run `npm install` / `npm ci`, typecheck, the tsup build and the vitest unit tests locally. All of them were run when these docs were written, on 2026-10-08 (350 tests: 336 passed, 14 model-parity skips). - Ask the user before you run Playwright (including `test/smoke/smoke.sh`), the sim generator, training, anything in `realapps/` that launches Chromium or touches a VM, the demos' eval, model downloads, anything on Azure, `git push` or `npm publish`. The colleague is operating the Azure cluster right now (SIM on c02–c09 and c12–c23, REAL on c01, c10, c11); nobody on our side touches it. @@ -186,7 +186,7 @@ Line counts were taken with `wc -l docs/agents/*.md docs/agents/runtime/*.md AGE 1. **Update the doc in the same change as the code.** If you change code under a doc's Scope, edit the affected sections in that doc (Files, constants, How it works, Tests). Remove Drift entries your change resolves, and add any mismatch it creates. 2. **Update the "Source of truth" line.** Name the branch and commit you checked the doc against, and the date. If you re-checked only part of the doc, name those sections in that line. -3. **Fix every copy of a repeated fact.** Several facts appear in more than one doc: the `situation-v2` freeze, the default mode `observe`, `holdWrites` off by default, the unpublished model and its 404 URLs, the default hold budget, the 2,400-char full budget, test counts (350 = 336 passed + 14 skipped), the realapps app count (91 at b435acb). Before you finish, search for the symbol or value you changed and fix every hit, for example `rg -n "DEFAULT_MODEL_BASE_URL|situation-v1" docs/agents`. +3. **Fix every copy of a repeated fact.** Several facts appear in more than one doc: the `situation-v2` freeze, the default mode `observe`, `holdWrites` off by default, the published model (`@genclass/runtime-model@0.1.0`) and its default URLs, the default hold budget, the 2,400-char full budget, test counts (350 = 336 passed + 14 skipped), the realapps app count (91 at b435acb). Before you finish, search for the symbol or value you changed and fix every hit, for example `rg -n "DEFAULT_MODEL_BASE_URL|situation-v1" docs/agents`. 4. **Model-visible changes cascade.** A change to situation text, delivery salience, questions, labels or budgets touches [runtime/learn-situation-triage.md](runtime/learn-situation-triage.md), [model-io-contract.md](model-io-contract.md), [sim.md](sim.md), [realapps.md](realapps.md), [training.md](training.md) and [status-and-known-issues.md](status-and-known-issues.md) (freeze tag). 5. **New docs.** A new subsystem doc keeps the same header block and ten sections. Add it to the catalogue and the routing table here, and to [repo-map.md](repo-map.md). Refresh the line counts with `wc -l docs/agents/*.md docs/agents/runtime/*.md` when a doc grows or shrinks a lot. 6. **Mark what you could not check.** Write "(unverified)" next to anything you could not confirm. Never add line numbers. @@ -199,6 +199,6 @@ The agent docs are derived from the code. They cite the human docs mainly to rec - `docs/runtime/API.md` is the public API reference for library users. If you change the public surface, update API.md and the JSDoc in `packages/runtime/src/types.ts` in the same change, then the agent doc. - `docs/runtime/ARCHITECTURE.md` is the design overview for humans. [docs/runtime/RESULTS.md](../runtime/RESULTS.md) holds the measured comparisons and the training log (HANDOFF asks for an update with every result). Their known drift is listed in [status-and-known-issues.md](status-and-known-issues.md). - [HANDOFF.md](../../HANDOFF.md) is the colleague's entry point for a new session (state, rules, how to continue). Its run rules are for his 8 GB Mac and the Azure cluster; our agents follow `AGENTS.md`. -- [RELEASE.md](../../RELEASE.md) at the repo root is the release procedure: Part A for `0.1.0-alpha.1` (done 2026-10-08), Part B for the model and `0.1.0`. +- [RELEASE.md](../../RELEASE.md) at the repo root is the release procedure: Part A for `0.1.0-alpha.1` (done 2026-10-08), Part B for the model and `0.1.0` (the model `0.1.0` and runtime `0.1.0-beta.0` were published 2026-10-08). - The workstream status files (`packages/runtime/STATUS.md`, `packages/runtime/UI-NEEDS.md`, `sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, `OPEN_TASKS.md`) are how the team coordinates. Follow the process in [status-and-known-issues.md](status-and-known-issues.md), and do not close or rewrite another workstream's items: the requester flips an item to DONE after verifying (owners may add answers under their own heading). REAL has no NEEDS file of its own; its requests and node claims live in `training/NEEDS.md`. - The legacy jev-local docs (`docs/SPEC.md`, `docs/CONTRACT.md`, `docs/CONTRACT-v2.md`, `docs/DEMO.md`, `docs/GENCLASS.md`, `docs/COMPARISON.md`, `docs/PLAN-excel.md`) and `docs/benchmax-research/` are not the runtime contract. CONTRACT §1 says this earlier GenClass content "stays as is". They are summarised in [genclass-model-lineage.md](genclass-model-lineage.md) and [extension-and-benchmarks.md](extension-and-benchmarks.md). diff --git a/docs/agents/demos.md b/docs/agents/demos.md index ae27ec0f..a703ebd7 100644 --- a/docs/agents/demos.md +++ b/docs/agents/demos.md @@ -515,7 +515,7 @@ Doc-vs-code mismatches (checked at b435acb): 9. `src/demos/status/scenario.ts` comment says incidents are the same in clean and chaos runs of a seed; the RNG label includes `kind`, so they differ. 10. `eval.ts` options `--base`, `--port`, `--trial-timeout`, `--out` are still not in the README (which now lists `--kinds` and `--trace`); the `eval.ts` header comment lists neither those nor `--trace`, `--kinds`, `--tag`, `--budget`, `trace-report.ts`. 11. The runtime shim is behind the public types, and `npm run typecheck:shim` fails (checked 2026-10-08 with `tsc -p demos/tsconfig.shim.json --noEmit`): `ShimRuntime implements Runtime` lacks `adapter()`, `holdBudgetMs()` and `situationBudget()` (`packages/runtime/src/types.ts` -> `Runtime`), and its `situation()` return lacks `Situation.compact` and `Situation.budget`; the cities.ts errors of item 1 come on top. These members already existed at 654d822, so the gap predates v2. The shim's `GenClassUnavailableError(message)` also lacks the real class's `reason` field (`packages/runtime/src/errors.ts`), and its constructor still defaults `mode` to `"guard"` (item 4). -12. README example `GENCLASS_MODEL_URL=https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/` lacks the `files/` suffix of the runtime's `DEFAULT_MODEL_BASE_URL`; `@genclass/runtime-model` is not published (npm 404), so `?model=cdn` and `--model cdn` cannot load a model. The README's re-run recipe uses a placeholder `https://…/runtime-model-v0.1.0/`. +12. README example `GENCLASS_MODEL_URL=https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/` lacks the `files/` suffix of the runtime's `DEFAULT_MODEL_BASE_URL`; `@genclass/runtime-model@0.1.0` is published since 2026-10-08 (it was a 404 before, so `?model=cdn` and `--model cdn` could not load a model); `?model=cdn` / `--model cdn` use the runtime default with `files/` and should now load it (not run in the demos). The README's re-run recipe uses a placeholder `https://…/runtime-model-v0.1.0/`. 13. README results table shows decisions latency "–"; `results.md` has 0 / 215 / 219 ms. 14. Not drift but an open risk: the world-clock offset between Off and Guard/Heal trials (see [Invariants](#invariants-and-gotchas)); none of `README.md`, `NEEDS.md` or `results.md` mention it. The current run's model load (median ~1.6 s) makes it larger than in the previous run. diff --git a/docs/agents/extension-and-benchmarks.md b/docs/agents/extension-and-benchmarks.md index c8c81fa2..2fa9993a 100644 --- a/docs/agents/extension-and-benchmarks.md +++ b/docs/agents/extension-and-benchmarks.md @@ -9,7 +9,7 @@ ## TL;DR - **This whole area is adjacent/legacy relative to `@genclass/runtime`.** It is the pre-runtime GenClass project (the "jev-local" era): a voice-controlled MV3 Chrome extension (GenClass 0.1.0), the Python benchmark harnesses that compared the model with TypeSafe's hosted Jev, and the Azure/Mac ops scripts. `docs/runtime/CONTRACT.md` says "Existing GenClass content (jev_local/, extension/, docs/, etc.) stays as is. Do not edit it." -- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it, and `realapps/README.md` runs the realapps build, debug runs and pilot generator through it with slot `real`, see [realapps.md](realapps.md); our CI and the lead's local checks on a 16 GB machine do not use it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh`, and (new since 654d822) `training/launch_student.sh`, `training/launch_t150.sh` and `training/launch_r68.sh`, plus the `training/README.md` recipes, to start multi-node torchrun jobs), `scripts/cluster_up.sh` (whose VNet/subnet/NSG/PPG/image/key settings `training/cluster_expand.sh` copies when it adds nodes) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the same directory (until 2026-10-08 the `runtime-model-v0.1.0` release of GenClass-lib) (both 404 as of 2026-10-08: no situation-v2 model exists yet, and the situation-v1 R17-final1 does not match the v2 runtime; see [status-and-known-issues.md](status-and-known-issues.md)). The v0.1 extension model reads the extension's own `state` serialisation, not runtime situation text (v1 or v2), so it is useful only for engine/packer/loader mechanics, never for decision quality; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/realapps/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. +- **What the runtime work actually depends on here:** (1) `scripts/vm.sh` (the original team's build/test path: every workstream built/tested on the `train` VM through it, and `realapps/README.md` runs the realapps build, debug runs and pilot generator through it with slot `real`, see [realapps.md](realapps.md); our CI and the lead's local checks on a 16 GB machine do not use it); (2) `scripts/azvm.sh` (training scripts `training/{deliver_final,import_sim,import_final}.sh` call it, see [training.md](training.md)), `scripts/launch_run.sh` (called by `training/launch_s2.sh`, `training/launch_final1.sh`, and (new since 654d822) `training/launch_student.sh`, `training/launch_t150.sh` and `training/launch_r68.sh`, plus the `training/README.md` recipes, to start multi-node torchrun jobs), `scripts/cluster_up.sh` (whose VNet/subnet/NSG/PPG/image/key settings `training/cluster_expand.sh` copies when it adds nodes) and `scripts/genclass_export.py`, whose `ExportModel`/`plan_inputs`/`unpack` `training/export_runtime.py` imports; (3) the **v0.1 GenClass ONNX model** that the extension shipped (GitHub release `MeharPro/GenClass` v0.1.0) is the model the runtime's model tests and parity work were developed against (`docs/runtime/CONTRACT.md` §10: "Until the runtime model exists, develop against the v0.1 GenClass ONNX"), and its card format is accepted by `packages/runtime/src/model/loader.ts` -> `parseCard`. It is **not** the runtime's default model: that is `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` (`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`), and `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` points at the same directory (until 2026-10-08 the `runtime-model-v0.1.0` release of GenClass-lib) (both were 404 until 2026-10-08 ~13:40 UTC; since then they serve `@genclass/runtime-model@0.1.0` = `r17-v2b`, the first situation-v2 model; the situation-v1 R17-final1 does not match the v2 runtime; see [status-and-known-issues.md](status-and-known-issues.md)). The v0.1 extension model reads the extension's own `state` serialisation, not runtime situation text (v1 or v2), so it is useful only for engine/packer/loader mechanics, never for decision quality; (4) the runtime's `src/model/{engine,packer,tokenizer,serialize,pyutil,calibrate}.ts` are TypeScript ports of `extension/src/core/{engine,packer,tokenizer,serialize,pyutil}.js` (calibration lives inside `engine.js` in the extension), and both are tested against the **same** Python-generated parity fixtures. No runtime/sim/demos/realapps/training code imports anything from `extension/` or `jev_local/bench/` or `bench/` (checked with grep; `packages/runtime/src/model/{engine,serialize,pyutil,loader}.ts` mention the extension only in comments). Besides this area's own tests (`tests/test_bench_*.py`, `tests/test_bm_*.py`), the only importers of `jev_local/bench` are the legacy `jev_local` data tests `tests/test_data_s.py`, `tests/test_data_s_intent_topic.py` and `tests/test_data_s_verify.py`. - **Extension architecture:** service worker (`src/background/sw.js`: tabs, navigation, feature plumbing) + offscreen document "brain" (`src/offscreen/offscreen.js`: model, speech, decision loop) + content script (`src/content/content.js`: page observation, in-page actions, ad hiding) + side panel (`src/sidepanel/panel.js`: view + settings). Pure-JS decision logic lives in `src/core/`: `types`, `catalog`, `questions`, `state`, `spans`, `stream`, `policy`, `safety` and `controller` port the Python macOS harness `jev_local/harness/*`; `tokenizer`, `packer` and `engine` port `jev_local/engine/encoder/{tokenize_pack,engine,calibrate}.py` plus `jev_local/confidence.py`; `serialize` ports `jev_local/serialize.py`; `features`, `sites` and the numbered-pick/rescue code are GenClass-only additions. - **The model is asked typed questions** (choice / noul / score) about a `state` object (screen, focused element, recent actions, pending, transcript). Questions are block-isolated in the attention mask, so the extension asks in two exact stages (intent/complete/is_command/destructive first, then only the argument question the intent needs). - **Mid-sentence acting is safe** because of a consumed-prefix transcript cursor (`core/stream.js` -> `Stream`), stability gates (`core/policy.js` -> `evaluatePolicy`), deterministic safety rules plus spoken confirmation (`core/safety.js` -> `gate`), and a 3 actions/s rate limit. diff --git a/docs/agents/genclass-model-lineage.md b/docs/agents/genclass-model-lineage.md index 35c4f6f6..db49a3dc 100644 --- a/docs/agents/genclass-model-lineage.md +++ b/docs/agents/genclass-model-lineage.md @@ -14,7 +14,7 @@ - Raw logits are turned into probabilities by **post-hoc calibration** (`calibration.json`: per kind, per header hash, per (kind, K-bucket), τ(K), noul Platt), then into Jev answers by `confidence.build_answer`. - **The runtime model is a direct descendant.** `packages/runtime/src/model` is a TypeScript port of `serialize.py`, the HF tokenizer call, `tokenize_pack.Packer` (single-pass subset), `calibrate.py` lookup and `confidence.py`. The network itself is exported to ONNX by `scripts/genclass_export.py` (graph) / `training/export_runtime.py` (q8/fp16 + card). Parity is pinned by Python-generated fixtures in `packages/runtime/test/fixtures/model/`. - **R32** (runtime candidate) is initialised from the v1 `jev-local-fast` checkpoint (ettin-32m, d 384, 10 layers) with a pruned 16,364-token vocabulary; **R17** starts from `jhu-clsp/ettin-encoder-17m` (d 256, 7 layers per `training/README.md`; fresh `DecisionHeads(enc.hidden_size)`), also pruned to 16,364 tokens. The scaled program (`training/PLAN-v1.md`, 2026-10-08) adds **R68** (ettin-68m student benchmark; never trained, per `training/LOG.md`) and **T150** (ettin-150m **teacher**, never shipped); their pruned bases `ettin-68m-v16k` / `ettin-150m-v16k` are made on each node by the launchers when missing. All are trained with `jev_local/train/train.py` (stream mode, DDP) launched from `training/` (`training/launch_student.sh` is the generic launcher). Caveat: `training/node.sh sync` copies `jev_local/` from the **parent jev repo** (`$HERE/../..`), not from this repo's root, and the two copies have now **diverged** (the parent has the gain head; see Drift). -- **No situation-v2 model exists yet.** The newest trained models (`r17-final1` = R17 default, `r32-final1`) were trained on situation-v1 SIM data and do not match the v2 runtime (`packages/runtime-model/MODEL_CARD.md`, `training/LOG.md`). Next per `HANDOFF.md`: T150 teacher on v2 gold -> teacher labels on unlabeled rows (`training/label_teacher.py`, which calls this package's `load_checkpoint` / `Packer` / `collate_tree` / `build_plan` / `calibrate_logits`) -> distil R17 and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` (release procedure: [RELEASE.md](../../RELEASE.md)). The text contract (serialize/pack/calibrate) is unchanged by v2; what changed is the *content* of the situations (e.g. the new `delivery` trigger with actions `deliver` (passive) / `discard` / `defer`; `deliver` itself already existed as the `failure` passive in v1) rendered by `packages/runtime/src/situation/*` (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`). +- **The first situation-v2 model is published (2026-10-08):** `@genclass/runtime-model@0.1.0` = `r17-v2b` (`genclass-runtime-r17` 2.0.0-rc2; card: `packages/runtime-model/MODEL_CARD.md`). The rest of this bullet is the earlier status. The round-1 models (`r17-final1` = R17 default, `r32-final1`) were trained on situation-v1 SIM data and do not match the v2 runtime (`packages/runtime-model/MODEL_CARD.md`, `training/LOG.md`). Next per `HANDOFF.md`: T150 teacher on v2 gold -> teacher labels on unlabeled rows (`training/label_teacher.py`, which calls this package's `load_checkpoint` / `Packer` / `collate_tree` / `build_plan` / `calibrate_logits`) -> distil R17 and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` (release procedure: [RELEASE.md](../../RELEASE.md)). The text contract (serialize/pack/calibrate) is unchanged by v2; what changed is the *content* of the situations (e.g. the new `delivery` trigger with actions `deliver` (passive) / `discard` / `defer`; `deliver` itself already existed as the `failure` passive in v1) rendered by `packages/runtime/src/situation/*` (`questions.ts` -> `TRIGGER_ACTIONS`, `PASSIVE`). - Python entry points: console script `jev-local` (`cli.py`), and `python -m` on `jev_local.server.app`, `jev_local.train.train`, `jev_local.train.eval`, `jev_local.train.stream`, `jev_local.engine.encoder.calibrate`, `jev_local.harness.observe`, `jev_local.demo` (table in Files). - **Changing `serialize.py`, `tokenize_pack.py`, marker ids, `heads.py`, `calibrate.py` lookup or `confidence.py` breaks train/runtime parity** unless the TS port, fixtures and model are changed together. - Legacy for the runtime library (safe to ignore unless asked): `api.py` routing and benchmax `ServeConfig`, `validate.py`, `server/app.py`, `engine/registry.py`, `engine/heuristic.py`, `engine/decoder/mlx_scorer.py`, all of `harness/**`, `demo.py`, `cli.py`, and the legacy docs listed in Scope. @@ -546,11 +546,11 @@ Code wins in every row. | 23 | `training/launch_student.sh` usage comment: MIX "e.g. `mix_v2_distill.json`" | no such file in `training/configs/` (existing: `mix_final1`, `mix_r68`, `mix_s1`, `mix_s1b`, `mix_s1c`, `mix_s2`, `mix_t150`, `mix_t1a`, `mix_t1b`, `mix_t1h`); the v2 mixtures are not written yet | | 24 | `training/NEEDS.md` item 8 is still an open ASK (curriculum rows carry Python-only float literals such as `25.0`) | `training/curriculum/fmt.py` -> `js_numbers` (already present at 654d822) turns integral floats into ints, and `training/curriculum/generate.py` applies it to `state` and `questions`; rows generated before it (e.g. the one in export-r32's `requests.json`) still carry `25.0` | | 25 | `training/NEEDS.md` item 11 (asks for the runtime tag, example `situation-v1`) and its "SIM → TRAIN: scaled data" section ("Runtime tag `situation-v1`") | the scaled SIM and REAL runs now in progress are `situation-v2` (`HANDOFF.md`; NEEDS item 16 and the c02–c09/c12–c23 claim row); `training/PLAN-v1.md` already says everything in it starts on v2 data | -| 26 | `packages/runtime-model/MODEL_CARD.md` status: R17 "delivered" in `files/r17/` | `packages/runtime-model/files/` is gitignored (not in the repo); R17-final1 is situation-v1 and does not match the v2 runtime; `@genclass/runtime-model` is unpublished (npm 404) | +| 26 | `packages/runtime-model/MODEL_CARD.md` status: R17 "delivered" in `files/r17/` | `packages/runtime-model/files/` is gitignored (not in the repo); R17-final1 is situation-v1 and does not match the v2 runtime; `@genclass/runtime-model` was unpublished (npm 404) until 2026-10-08; since then `0.1.0` = `r17-v2b` (situation-v2) and the card describes it | Open issues relevant to this scope: -- No situation-v2 model: every number in `packages/runtime-model/MODEL_CARD.md` and `training/EVAL.md` is a v1 number (round-1 results: [RESULTS.md](../runtime/RESULTS.md)). CI exercises the serialize, calibration and answer-math parity against the committed `py_fixtures.json`, but the tokenizer/packer, ONNX engine and torch-calibration parity tests need a local model directory, so CI does not exercise them today. +- Before 2026-10-08 there was no situation-v2 model and every number in `packages/runtime-model/MODEL_CARD.md` and `training/EVAL.md` was a v1 number; since bcbee89/1f0f617 the card reports `r17-v2b` (situation-v2) (round-1 results: [RESULTS.md](../runtime/RESULTS.md)). CI exercises the serialize, calibration and answer-math parity against the committed `py_fixtures.json`, but the tokenizer/packer, ONNX engine and torch-calibration parity tests need a local model directory, so CI does not exercise them today. - The two `jev_local` copies (this tree vs the parent repo synced to the cluster) have diverged (row 22). Decide which is canonical before changing either; until then, Python edits here do not reach training. - T1 (expected-gain targets / gain head) was stopped on v1 with no result and is to be rerun on v2 data; LOG reports the gain-head interim loss barely beat trivial predictors (0.85 vs 0.97–1.01). - TS port intentionally lacks multi-pass option batching and `lr`/median answer modes; the runtime must stay within `maxPositions` / `maxTotal`. diff --git a/docs/agents/glossary.md b/docs/agents/glossary.md index 70537cb2..4d026bb0 100644 --- a/docs/agents/glossary.md +++ b/docs/agents/glossary.md @@ -21,7 +21,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **apply (action)**: Passive action of the `mutation` trigger: keep the write. By default (`holdWrites` off) the write has already applied when the non-blocking `mutation` trigger is decided, so `apply` changes nothing; with `policy.holdWrites: true` it lets the held write update the state (or when the store's queue drains). Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.observeWrite`, `RuntimeImpl.gateMutation`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **ask (trigger)**: The developer-question trigger. `rt.ask(question, { about, timeoutMs })`, `rt.decide(question, options)` and `rt.situation()` build an `ask` situation about now, an op id or a store outside `trigger()`: no triage, no gate, no `Decision`, queue priority 1. `rt.ask` replaces the questions with `{ answer: q }`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.ask`, `RuntimeImpl.decide`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [learn-situation-triage](runtime/learn-situation-triage.md). - **ask row / ask probe (sim)**: At `scenario.askTimes` the base run calls `runtime.situation("ask")` (side-effect free) and records it; `askQuestions` attaches 1–3 programmatic questions with exact labels (`q_*` qids). Code: `sim/src/ask/questions.ts` -> `askQuestions`. Doc: [sim](sim.md). -- **assetBase (script-tag build)**: Where the script-tag build loads its other files (model worker, ORT chunks, devtools): for a jsDelivr or unpkg URL of `@genclass/runtime` (any version or none) the same CDN pinned to the version baked in at build time (`@<__GENCLASS_VERSION__>/dist/`), else the script file's own directory, else jsDelivr at that version. Because the version comes from `package.json`, building this tree before the version bump points it at the published alpha.1, which has no `dist/cdn/`. Code: `packages/runtime/src/cdn/global.ts` -> `assetBase`. Doc: [status-and-known-issues](status-and-known-issues.md). +- **assetBase (script-tag build)**: Where the script-tag build loads its other files (model worker, ORT chunks, devtools): for a jsDelivr or unpkg URL of `@genclass/runtime` (any version or none) the same CDN pinned to the version baked in at build time (`@<__GENCLASS_VERSION__>/dist/`), else the script file's own directory, else jsDelivr at that version. Because the version comes from `package.json`, a build made before the bump to `0.1.0-beta.0` (1f0f617) pointed it at the published alpha.1, which has no `dist/cdn/`; beta.0 has it. Code: `packages/runtime/src/cdn/global.ts` -> `assetBase`. Doc: [status-and-known-issues](status-and-known-issues.md). - **atom (store kind)**: A store whose value GenClass owns (`StoreRec.value`), created by `rt.atom(name, initial, opts)` and by the React hook `useGenClassState`; always writable. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.atom`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **attempt (model load)**: `LoadAttempt { variant, device, error }`: a load plan that failed, listed in `status.attempts`. Code: `packages/runtime/src/model/errors.ts` -> `LoadAttempt`. Doc: [model-host](runtime/model-host.md). - **auto budget**: See *situation budget*. @@ -78,7 +78,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **conflict (newer data / pending local change)**: The two situation-v2 version conflicts on a field an op X will write (`situation/conflicts.ts`). *Newer-data conflict*: the field changed since X started, written by an op that started after X, outside X's chain, not itself a user action, with no newer request of X's signature still in flight. *Pending local change*: a user action's chain wrote the field in the last 10 s (`PENDING_WINDOW_MS`) and an op of that chain with a different signature is still in flight. Only these make a version fact non-neutral, and they drive delivery salience. Code: `packages/runtime/src/situation/conflicts.ts` -> `newerConflict`, `pendingConflict`, `conflictsOn`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **consistency pair**: A `meta.pairs` entry (`neg`, `noul_choice`, `score_choice`) that the v2 training loss penalises to keep related answers coherent. Code: `jev_local/train/losses.py` -> `consistency_terms`. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **consistent snapshot**: A deep clone of all stores taken at a settled point where no violation newly broke (lingering ones allowed); `RuntimeImpl.snaps` keeps the last 8. Inconsistency `rollback` writes the last one back. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.settled`, `RuntimeImpl.rollback`. Doc: [state-and-adapters](runtime/state-and-adapters.md). -- **consultable**: `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists and its `status.state` is `"ready"` or `"off"`. When false, every trigger runs its passive action without building a situation and no write is held; a default install today reaches this state because the unpublished model ends in status `error`. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.consultable`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [status-and-known-issues](status-and-known-issues.md). +- **consultable**: `RuntimeImpl.consultable()`: not paused, not destroyed, a decider exists and its `status.state` is `"ready"` or `"off"`. When false, every trigger runs its passive action without building a situation and no write is held; a default install reached this state before 2026-10-08, when the unpublished model (404) ended in status `error`; since `@genclass/runtime-model@0.1.0` is published, it reaches it only when the model cannot be fetched. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.consultable`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [status-and-known-issues](status-and-known-issues.md). - **consumed prefix (extension)**: Transcript words already acted on; later partials must still start with them (fillers and chain words ignored) or the stream freezes (`revised_after_act`), so an action never runs twice. Code: `extension/src/core/stream.js` -> `Stream`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **CONTRACT (legacy)**: `docs/CONTRACT.md` (the jev-local v0.1 build contract per workstream A–H, whose section D defines the CONTRACT-D row format), with `docs/CONTRACT-v2.md`, `docs/SPEC.md` and the other jev-local design docs. Legacy: runtime CONTRACT §1 says not to edit them. Doc: [genclass-model-lineage](genclass-model-lineage.md). - **CONTRACT (runtime)**: `docs/runtime/CONTRACT.md`, the binding build contract owned by the lead: §0 ground rules (no hardcoded bug rules, one situation implementation shared with the sim, determinism through the injected `Clock`, sim and demos never read each other, no runtime dependency besides `onnxruntime-web`, builds on the VM), §0.5 product principles, §1 layout and owners, §2–§12 spec (§8 = the policy gate), §13 approved additions. Substantively last edited in a53dd38 (before batch 3); f3636b2 only appended the observe-default §13 entry. It has no `delivery` trigger or `holdWrites`, so it lags the code. See also [HANDOFF.md](../../HANDOFF.md), [RESULTS.md](../runtime/RESULTS.md). Doc: [status-and-known-issues](status-and-known-issues.md). @@ -106,8 +106,8 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **Decision Score (jevbench)**: `clip(1 − mean Brier / mean prior Brier, −1, 1)` per dataset. Code: `jev_local/bench/metrics.py` -> `decision_score`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **DecisionProvider**: The only seam between the runtime and a model: `{ status, ready(), evaluate(req), onStatus?(fn), dispose?() }`. Implemented by the model host, the test deciders, the sim's recording decider and `failedProvider`; passed as `options.decider`, which wins over `options.model` (`null` = no model). `evaluate` receives `EvaluateRequest { trigger, state, questions, priority?, subject?, timeoutMs? }`. Code: `packages/runtime/src/types.ts` -> `DecisionProvider`, `EvaluateRequest`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [model-io-contract](model-io-contract.md). - **decontamination stage 1 (benchmax)**: Name-level exclusion of training sources per track. Code: `jev_local/bench/registry.py` -> `is_excluded`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). -- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, the same directory as `DEFAULT_MODEL_BASE_URL` (`test/install/cli.test.ts` keeps them equal). Until 2026-10-08 it was the GitHub release `runtime-model-v0.1.0`, which we cannot create (no write access to releases); the published `0.1.0-alpha.1` CLI still defaults to that release. It 404s until `@genclass/runtime-model@0.1.0` is on npm ([RELEASE.md](../../RELEASE.md) Part B), so until then pass `--from` explicitly. Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). -- **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is not published (npm 404 on 2026-10-08, and no situation-v2 model exists to publish), so a default `GenClass.init()` ends with model status `error` and only observes; since f3636b2 it is also in `observe` mode by default. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **DEFAULT_FROM**: Default source of `genclass-runtime fetch-model`: `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, the same directory as `DEFAULT_MODEL_BASE_URL` (`test/install/cli.test.ts` keeps them equal). Until 2026-10-08 it was the GitHub release `runtime-model-v0.1.0`, which we cannot create (no write access to releases); the published `0.1.0-alpha.1` CLI still defaults to that release. Since 2026-10-08 `@genclass/runtime-model@0.1.0` is on npm ([RELEASE.md](../../RELEASE.md) Part B) and the jsDelivr directory resolves, so `--from` is optional (the published `0.1.0-beta.0` CLI uses it). Code: `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). +- **DEFAULT_MODEL_BASE_URL**: The default model directory, `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. That package is published since 2026-10-08 ~13:40 UTC (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2; before that it was a 404 and a default `GenClass.init()` ended with model status `error`), so a default `GenClass.init()` loads the model and decides; since f3636b2 it is in `observe` mode by default, so it acts only with `guard`/`heal`. Code: `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **defer (action)**: Guard-tier action of `mutation` and `delivery`, offered while the subject was deferred fewer than 2 times. Mutation: with `holdWrites: true`, wait for related in-flight ops (cap 10 s), then re-propose the write as a new trigger; after 2 defers it applies; with `holdWrites` off it is offered but only recorded (the write already applied). Delivery: offered only when related ops are in flight (same name outside the op's chain, or whose signatures wrote a matched store); hold the response or message, wait for them (`waitOps`), then decide again. A review finding: each delivery defer waits up to 10 s (`LONG_RUNNING_MS`), not the hold budget, so two defers can hold a response for 20 s, and on a push channel every later message waits behind it. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.gateMutation`, `RuntimeImpl.waitRelated`, `RuntimeImpl.runDelivery`, `RuntimeImpl.waitOps`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **delay (action)**: Guard-tier `request` action (fetch and XHR): wait `min(250 × 2^failStreak, 8000)` ms, where `failStreak` is the signature's current failure streak, then send. Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/observe/xhr.ts` -> `installXHR`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). - **deliver (action)**: Passive action of the `failure` trigger (hand the original `Response` or rejection to the app) and of the `delivery` trigger (pass the response or message to the app now). Code: `packages/runtime/src/observe/fetch.ts` -> `installFetch`; `packages/runtime/src/runtime.ts` -> `RuntimeImpl.runDelivery`. Doc: [decide-policy-actions](runtime/decide-policy-actions.md). @@ -181,10 +181,10 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **genclass-runtime (CLI)**: The package's bin, also run as `npx @genclass/runtime `: `init [--mode observe|guard|heal] [--yes] [--dry-run] [--no-install] [--no-devtools] [--cwd ] [--from ] [--cdn ]` and `remove [--yes] [--dry-run] [--keep-package]` (see *init / remove*; merged in f3a9dd1, not in the published `0.1.0-alpha.1`); `fetch-model [--from ] [--variant q8|fp16|all] [--force] [--quiet]` downloads and verifies a self-hostable model directory; `info ` describes one. No dependencies. Code: `packages/runtime/bin/genclass-runtime.mjs`, `packages/runtime/bin/lib/*`. Doc: [model-host](runtime/model-host.md), [status-and-known-issues](status-and-known-issues.md). - **genclass-runtime (alias package)**: `packages/genclass-runtime/` (f3a9dd1), an unscoped package whose `cli.mjs` forwards to `@genclass/runtime`'s CLI so `npx genclass-runtime init` would work. Version and dependency `0.1.0-alpha.1`; a workspace; **not published** (no `genclass-runtime` on npm, so `npx genclass-runtime init` fails today and the name is unreserved: `packages/runtime/INSTALL-NEEDS.md` item 1). `npx @genclass/runtime init` is the documented form. Doc: [status-and-known-issues](status-and-known-issues.md). - **genclass:init / genclass:inline (markers)**: The comments `init` puts on every line or block it adds (`// genclass:init`, `// genclass:init start` … `end` around files it creates, `genclass:inline` for JSX/Astro inline forms); `remove` deletes exactly what carries them. Review findings: a formatter that wraps a marked line breaks `remove`, a lost end marker makes it drop the rest of the file, and any line containing the text is dropped. Code: `packages/runtime/bin/lib/edit.mjs` -> `MARK`, `MARK_INLINE`, `removeMarked`. Doc: [status-and-known-issues](status-and-known-issues.md#install-code-review-2026-10-08). -- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-alpha.1` is the latest published version (`latest`, 2026-10-08, release commit 806a296): NaN fix, situation-v2, default `observe`; with no published model it takes no actions, and it has none of the install paths (`./auto*`, the script-tag build, `init`/`remove`). The older `0.1.0-alpha.0` predates batches 4–5 and the observe default (its default is `guard`). The tree still says `0.1.0-alpha.1`; the *next release* carries the install paths and the two fixes; `0.1.0` is planned after `@genclass/runtime-model@0.1.0`. Subpaths in the tree: `.`, `/auto`, `/auto/observe`, `/auto/guard`, `/auto/heal`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker` (published alpha.1: no `/auto*`). Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md), [RELEASE.md](../../RELEASE.md). -- **`@genclass/runtime-model`**: The planned npm package for the trained model files (`packages/runtime-model/files/`, gitignored); `DEFAULT_MODEL_BASE_URL` points at its unpublished 0.1.0 (npm 404). Only `packages/runtime-model/MODEL_CARD.md` exists. 0.1.0 must be a situation-v2 model, which does not exist yet. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **`@genclass/runtime`**: The npm library in `packages/runtime/` (ESM only, Apache-2.0, sole runtime dependency `onnxruntime-web`). `0.1.0-beta.0` is `latest` (published 2026-10-08 ~13:40 UTC from 1f0f617; install paths, the two fixes, batch 6+, default `observe`, loads `@genclass/runtime-model@0.1.0` by default); the tree says `0.1.0-beta.0`. Before it, `0.1.0-alpha.1` (806a296) was `latest`: NaN fix, situation-v2, default `observe`, no published model, none of the install paths (`./auto*`, the script-tag build, `init`/`remove`). The older `0.1.0-alpha.0` (deprecated) predates batches 4–5 and the observe default (its default is `guard`). `0.1.0` is planned next. Subpaths in the tree: `.`, `/auto`, `/auto/observe`, `/auto/guard`, `/auto/heal`, `/react`, `/redux`, `/zustand`, `/devtools`, `/worker` (published alpha.1: no `/auto*`). Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [build-test-release](runtime/build-test-release.md), [RELEASE.md](../../RELEASE.md). +- **`@genclass/runtime-model`**: The npm package for the trained model files (`packages/runtime-model/files/`, gitignored; tracked: `package.json`, `MODEL_CARD.md`, `LICENSE`). `0.1.0` is `latest` since 2026-10-08 ~13:40 UTC: `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2, the first situation-v2 model, gates guard 0.80 {mutation 0.95}, heal 0.85 {failure 0.95, inconsistency 0.85}, report 0.85. `DEFAULT_MODEL_BASE_URL` points at its jsDelivr `files/` directory, which resolves. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **`@genclass/sim` / `@genclass/demos` / `@genclass/realapps`**: The private packages `sim/` and `demos/` (root workspaces) and `realapps/` (not a workspace). `sim` and `demos` depend on `"@genclass/runtime": "*"`, which resolves to `packages/runtime/dist/`, so build the runtime first; `realapps/build.mjs` bundles the runtime from source instead (`RW_RUNTIME_SRC`, default the working tree). Doc: [sim](sim.md), [demos](demos.md), [build-test-release](runtime/build-test-release.md). -- **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `/.cache-model`, filled with `genclass-runtime fetch-model --from ` (ask first; the default `--from` is unpublished)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). +- **GENCLASS_MODEL_DIR**: Model directory for the model unit tests and browser specs (default `/.cache-model`, filled with `genclass-runtime fetch-model --from ` (ask first: download; the default `--from` is the published `@genclass/runtime-model@0.1.0`, which is not the v0.1 parity fixture)); without it 14 model-parity tests skip. Doc: [build-test-release](runtime/build-test-release.md). - **GENCLASS_REPLACE**: `"@@genclass/REPLACE"`, the Redux action the enhancer uses for GenClass's whole-state writes (rollback, revert); it never reaches the app reducer. Code: `packages/runtime/src/adapters/redux.ts` -> `GENCLASS_REPLACE`. Doc: [state-and-adapters](runtime/state-and-adapters.md). - **GenClassUnavailableError**: The error `rt.ask()` / `rt.decide()` reject with when no model can answer; `reason` is `destroyed`, `off`, `timeout` or `error` (with `timeoutMs` set, a raw provider load error can escape instead). Provider errors never escape a trigger. Code: `packages/runtime/src/errors.ts` -> `GenClassUnavailableError`. Doc: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md). - **gold row**: A training row with counterfactual action labels (SIM's default row mode; REAL's decision rows): the scenario is re-run once per applicable action at the decision point over 2–3 paired futures, and costs become a soft `action` label (`actionLabel`) plus a hard `diagnosis` label (with *S1*). SIM v2 produced 10,423,855 gold rows (seeds from 11e9; `OPEN_TASKS.md` "Done"); REAL's usable v2 gold comes from `v2c1`..`v2c4` (616,437 rows per `origin/runtime` 6d6eb00, not merged here). Contrast *unlabeled rows* and *on-policy rows* (see *DAgger*). Code: `sim/src/gen/trajectory.ts` -> `generateTrajectory`, `pointCosts`. Doc: [sim](sim.md), [realapps](realapps.md). @@ -274,7 +274,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **NEEDS file**: A request file kept in the requester's directory (`sim/NEEDS.md`, `training/NEEDS.md`, `demos/NEEDS.md`, and the exceptions `packages/runtime/UI-NEEDS.md` and `packages/runtime/INSTALL-NEEDS.md`); `training/NEEDS.md` also carries other workstreams' sections (e.g. "MODEL → TRAIN (from MODEL, …)"). `sim/NEEDS.md` and `training/NEEDS.md` use the status legend OPEN (needed), ASK (would help), DONE (landed, verified by the requester), plus INFO in `training/NEEDS.md`; `UI-NEEDS.md` uses sections Open / Nice to have / Done; `demos/NEEDS.md` uses numbered sections naming the addressee. Doc: [status-and-known-issues](status-and-known-issues.md). - **NetCause (sim)**: Why a simulated request ended (`NetEntry.cause`): `ok, transient, outage, overload, ratelimit, spike, slow-period, gateway-timeout, bug, replica-lag, neterr, aborted, notfound`; diagnoses read it. Code: `sim/src/net/network.ts` -> `NetCause`. Doc: [sim](sim.md). - **never-worse sweep**: The check of the product principle "never make a correct app worse": REAL's `debug.js --interference` runs each realapps scenario in `observe` mode and in `heal` mode with an all-passive decider and counts runs whose outcome differs. Situation-v2 result (STATUS.md, RESULTS.md §4): 0/396 clean runs changed (all 66 apps of the time, seeds 1–6), 3/198 under chaos (request-time holds shifting a request by ~25 ms; open item), Conduit 0/30; situation-v1 changed 4/198 and the React/Redux Conduit never rendered its feed. Caveats from review: it compares only final non-input, non-alert DOM text and server content (not requests, stores or errors), it never compares `observe` against no runtime at all, and the 25 apps added later were never swept. The runtime-side regression test is `test/no-reorder.test.ts`. Code: `realapps/src/harness/debug.ts`. Doc: [realapps](realapps.md)., [RESULTS.md](../runtime/RESULTS.md) -- **next release (`0.1.0-alpha.2`)**: The next `@genclass/runtime` prerelease (`OPEN_TASKS.md` Next 14): `0.1.0-alpha.2`, or a beta together with the v2 model once validated. It carries Mehar's install paths (*auto entry*, *CDN script tag*, *init / remove*), the fixes 054da38 and f107013, and whatever of `origin/runtime` is merged by then. Before building or packing it: bump the version, fix the install findings, move the CHANGELOG bullets; the user publishes with 2FA. Doc: [status-and-known-issues](status-and-known-issues.md). +- **next release (`0.1.0-alpha.2`)**: The next `@genclass/runtime` prerelease (`OPEN_TASKS.md` Next 14): `0.1.0-alpha.2`, or a beta together with the v2 model once validated. It carries Mehar's install paths (*auto entry*, *CDN script tag*, *init / remove*), the fixes 054da38 and f107013, and whatever of `origin/runtime` is merged by then. Before building or packing it: bump the version, fix the install findings, move the CHANGELOG bullets; the user publishes with 2FA. Shipped as `0.1.0-beta.0` together with `@genclass/runtime-model@0.1.0` on 2026-10-08. Doc: [status-and-known-issues](status-and-known-issues.md). - **noul**: A typed question asking for the absolute probability that a statement is true (sigmoid head; `criteria` optional `{ true?, false? }`); the answer is `{ noul: P(true) }`, with no confidence field. Code: `packages/runtime/src/types.ts` -> `NoulAnswer`; `jev_local/schema.py` -> `NoulQuestion`. Doc: [model-io-contract](model-io-contract.md), [genclass-model-lineage](genclass-model-lineage.md). - **Now view (devtools)**: Renders `runtime.situation()` (an "ask about now" situation) and `inflight()`, refreshed every second while visible. Doc: [devtools](runtime/devtools.md). - **numbered pick (extension)**: After "which element?", the top-3 candidates get page badges; "number two" within 10 s and ≤ 5 words clicks it without a model call (still through the safety gate). Doc: [extension-and-benchmarks](extension-and-benchmarks.md). @@ -397,7 +397,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **situation**: The model input for one trigger: a `JevState` with seven keys in fixed order, `app`, `trigger` (the subject sentence), `facts`, `in_flight`, `timeline`, `state` (store field lines), `stats` (signature baselines), shaped to the situation budget, plus the typed `questions`. The `Situation` object (`rt.situation()`, `buildSituation`) also carries `trigger, subject, actions, salient, facts, compact, budget`, which the model does not read. Code: `packages/runtime/src/situation/build.ts` -> `buildSituation`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md), [model-io-contract](model-io-contract.md). - **situation budget**: The situation's size in characters as measured by `stateChars`: `STATE_CHAR_BUDGET` 2400 (full; 3200 in situation-v1, lowered in batch 4), `COMPACT_BUDGET` 1100 (smallest section limits), floor `MIN_BUDGET` 500, linear in between (`sectionLimits`). `situation.budget: "auto"` (default) gives 2400 for WebGPU or an unknown device and 1000 / 1333 / 1667 / 2000 for WASM with 1 / 2 / 3 / 4+ threads, times the budget scale; a number is used as is. Over budget, `toJevState` drops timeline lines (oldest first), then state, facts (keeping ≥ 1), in-flight and stats lines, then shortens facts and the trigger. Code: `packages/runtime/src/runtime.ts` -> `RuntimeImpl.situationBudget`; `packages/runtime/src/situation/serialize.ts` -> `toJevState`, `sectionLimits`. Doc: [learn-situation-triage](runtime/learn-situation-triage.md). - **situation-v1**: Annotated git tag on commit 1a77558 ("Frozen runtime situation format for model training"), the previous training format: SIM phase A/B, `cur4` and final round 1 (the R17/R32 checkpoints that exist) use it. Superseded by *situation-v2*; nothing trained on v1 matches the current runtime. -- **situation-v2**: Annotated git tag on commit 6e5e86e ("Frozen runtime situation format v2"), the **current** frozen training format: batches 4 and 5 (the *delivery* trigger, non-blocking mutations, conflicts, F1–F9, 2,400-char budget, leaf redaction). The v2 SIM gold/unlabeled data, REAL batches `v2b1`–`v2b3` and `training/curriculum/rt.py` ("FROZEN at git tag `situation-v2`") target it; no v2 model exists yet. On `mvp-v2` (b435acb) the diff from the tag touched no model input; on `mvp-v2-merge`, f107013 (redaction) changes the text of redacted values (`situation/content.ts`, `state/fields.ts`, `util.ts`) without a new tag, and the v2 data and r17-v2a predate it. `origin/runtime` has since tagged *situation-v2.1*. Any change to text the model reads (situation code, `learn/`, `util.ts` formatters, `state/fields.ts` `changeText`/`stringDiff`, questions, vocabulary, budgets) needs a new tag, regenerated SIM and REAL data, a matching `rt.py` change and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference. Doc: [model-io-contract](model-io-contract.md), [learn-situation-triage](runtime/learn-situation-triage.md). Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). +- **situation-v2**: Annotated git tag on commit 6e5e86e ("Frozen runtime situation format v2"), the **current** frozen training format: batches 4 and 5 (the *delivery* trigger, non-blocking mutations, conflicts, F1–F9, 2,400-char budget, leaf redaction). The v2 SIM gold/unlabeled data, REAL batches `v2b1`–`v2b3` and `training/curriculum/rt.py` ("FROZEN at git tag `situation-v2`") target it; the first v2 model, `r17-v2b`, is published as `@genclass/runtime-model@0.1.0` (2026-10-08). On `mvp-v2` (b435acb) the diff from the tag touched no model input; on `mvp-v2-merge`, f107013 (redaction) changes the text of redacted values (`situation/content.ts`, `state/fields.ts`, `util.ts`) without a new tag, and the v2 data and r17-v2a predate it. `origin/runtime` has since tagged *situation-v2.1*. Any change to text the model reads (situation code, `learn/`, `util.ts` formatters, `state/fields.ts` `changeText`/`stringDiff`, questions, vocabulary, budgets) needs a new tag, regenerated SIM and REAL data, a matching `rt.py` change and retraining; changes to the packer, tokenizer or calibration lookup break parity with the Python reference. Doc: [model-io-contract](model-io-contract.md), [learn-situation-triage](runtime/learn-situation-triage.md). Doc: [status-and-known-issues](status-and-known-issues.md), [model-io-contract](model-io-contract.md). - **situation-v2.1**: Tag on `origin/runtime` 5bc40c9 (runtime batch 6, not merged into `mvp-v2-merge`): situation-v2 plus one new neutral fact (requests with no latency baseline raise a stall after 10 s in flight); existing situation text unchanged; batch 6 also lets the model's `meta.json` supply gate thresholds. Doc: [status-and-known-issues](status-and-known-issues.md). - **skill (jevbench)**: `clip((m − c) / (1 − c), 0, 1)` for primary metric `m` and chance level `c`. Code: `jev_local/bench/metrics.py` -> `skill`. Doc: [extension-and-benchmarks](extension-and-benchmarks.md). - **slot (VM slot)**: A per-workstream directory `~/gcl/` on the Azure `train` VM used by `scripts/vm.sh` (names `[a-zA-Z0-9_-]+`, conventionally `core`, `model`, `sim`, `demos`). `sync` uses `rsync --delete`, so files created in a slot outside the excluded paths are removed on the next sync. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md). @@ -468,7 +468,7 @@ Jump to: [A](#a) · [B](#b) · [C](#c) · [D](#d) · [E](#e) · [F](#f) · [G](# - **v0.1 fixture set**: `packages/runtime/test/fixtures/model/{requests50,pack_fixtures,torch_fixtures}.json`: 50 computer-use requests with the Python packer output and PyTorch logits of the v0.1 GenClass model. Doc: [build-test-release](runtime/build-test-release.md). - **v0.1 model**: See *GenClass 0.1 (v0.1 model)*. -- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, the first published alpha; since 2026-10-08 `latest` is `0.1.0-alpha.1` (tag `v0.1.0-alpha.1` on 806a296, local only). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) +- **v0.1.0-alpha.0**: Annotated git tag on 654d822 marking the npm alpha `@genclass/runtime@0.1.0-alpha.0`, the first published alpha; now deprecated; `latest` was `0.1.0-alpha.1` (tag `v0.1.0-alpha.1` on 806a296, local only) and since 2026-10-08 ~13:40 UTC is `0.1.0-beta.0` (local tag `v0.1.0-beta.0`). It is situation-v1 code with default mode `guard`. Doc: [build-test-release](runtime/build-test-release.md), [status-and-known-issues](status-and-known-issues.md)., [RELEASE.md](../../RELEASE.md) - **v2b1 / v2b2 / v2b3 (REAL batches)**: REAL's first situation-v2 production batches on c01, c10 and c11 (planned 30k trajectories each). Per `training/NEEDS.md` item 16 (eff18cb) they stopped at ≈ 20.5k trajectories each (≈ 380k gold, 66 apps) with **pre-fix diagnosis labels**: action labels valid, diagnosis labels only with the NEEDS filter; use *v2c1–v2c4* instead. Their `manifest.json` says `situation-v1` (hardcoded in `realapps/src/harness/gen.ts`). Doc: [realapps](realapps.md). - **v2c1–v2c4 (REAL batches)**: REAL's situation-v2 batches with fixed labels: 96 apps, 4 × 20k trajectories on c01, c10, c11 and `data`, expected ≈ 530k gold + ≈ 500k unlabeled; the real-app eval set `v2-eval` is built from them (`training/NEEDS.md` item 16, "USE THESE"). Not landed at eff18cb; `origin/runtime` 6d6eb00 (not merged) reports REAL v2 production done: 616,437 gold, eval set 16,600. Doc: [realapps](realapps.md). - **v2_post.sh**: `training/v2_post.sh RUN NAME VERSION`, run detached on a v2 run's rank-0 node: waits until `models/RUN/meta.json` says `final`, runs `eval_sim.sh` on `sim2e` and `sim2f`, `eval_gain.py`, then `export_runtime.py` with the `sim2e` calibration, and serves the export tar on :8801. It replaces the v1-wired `final_post.sh` for v2; it publishes nothing. Running for *r17-v2a* on c09. Doc: [training](training.md). diff --git a/docs/agents/model-io-contract.md b/docs/agents/model-io-contract.md index d67c3bc1..48f030c8 100644 --- a/docs/agents/model-io-contract.md +++ b/docs/agents/model-io-contract.md @@ -16,7 +16,7 @@ - **Heads → answers:** raw logits (τ = 1) → calibration (`calibration.json`: by-header, by-bucket, τ(K), per-kind temperature; Platt for noul) → `Answer`. The runtime gate reads only `probabilities` and the diagnosis `choice`. Since f3636b2 the default mode is `observe`, so by default no answer changes execution. - **SIM rows now come in three kinds** (`sim/src/gen.ts`): **gold** (counterfactual soft `action` dist + hard `diagnosis`; ids `sim-…`), **unlabeled** (`--unlabeled`: every decision point of a base run, diagnosis only; ids `u-…`), **on-policy** (`--on-policy `: a real export decides through the production gate, DAgger rows; ids `p-…`). Labels gained **S1** (never `expected` where acting clearly wins; `meta.diagnosis_s1`) and **S2** (re-seeded futures re-draw what the runtime cannot observe; `src/run/latent.ts`). - **Training-side gains (T1):** `training/t1_relabel.py` derives expected-gain labels from `meta.cost_futures` (`gain(a) = mean c(passive) − mean c(a) − premium`), `eval_gain.py` scores gate policies by captured gain, `label_teacher.py` soft-labels unlabeled rows with a teacher. -- **Model directory** (`export_runtime.py`, unchanged): `model.json` (card `genclass-runtime-model/1`, bytes + sha256), `-q8.onnx` (WASM), `-fp16.onnx` (WebGPU + `shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, and parity fixtures. **No situation-v2 model exists yet** and `@genclass/runtime-model` is not published. +- **Model directory** (`export_runtime.py`, unchanged): `model.json` (card `genclass-runtime-model/1`, bytes + sha256), `-q8.onnx` (WASM), `-fp16.onnx` (WebGPU + `shader-f16`), `tokenizer.json`, `calibration.json`, `meta.json`, and parity fixtures. `@genclass/runtime-model@0.1.0` (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2, the first situation-v2 model) is published since 2026-10-08 ~13:40 UTC; its `files/` directory is such a model directory. ## Files @@ -464,7 +464,7 @@ Run by `training/final_post.sh` after the eval: `--calibration out/cal/-simAe Candidate students (MODEL_CARD; sizes of the round-1 `final1` exports, `training/LOG.md`): R17 `genclass-runtime-r17` (ettin-17m, d 256, 7 layers) q8 9.6 MB / fp16 13.6 MB; R32 `genclass-runtime-r32` (ettin-32m, d 384, 10 layers) q8 22.5 MB / fp16 34.8 MB; both vocab 16,364. `training/PLAN-v1.md` adds R68 and a 150M teacher (T150, never shipped). -The runtime reads `model.json` (`loader.ts` -> `parseCard`; `format` defaults to `CARD_FORMAT` and is **not** checked), then `meta.json` and `calibration.json`. Load plans (`planOrder`): webgpu+fp16 → webgpu+q8 → wasm+q8. The default base URL is `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`host.ts` -> `DEFAULT_MODEL_BASE_URL`), which returns 404 today. More in [model-host.md](runtime/model-host.md). +The runtime reads `model.json` (`loader.ts` -> `parseCard`; `format` defaults to `CARD_FORMAT` and is **not** checked), then `meta.json` and `calibration.json`. Load plans (`planOrder`): webgpu+fp16 → webgpu+q8 → wasm+q8. The default base URL is `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`host.ts` -> `DEFAULT_MODEL_BASE_URL`), which resolves since 2026-10-08 (it was a 404 before). More in [model-host.md](runtime/model-host.md). ## Configuration and constants @@ -517,7 +517,7 @@ The runtime reads `model.json` (`loader.ts` -> `parseCard`; `format` defaults to | export | — | opset 17, block 32, `max_total` 8192, parity requests ≤ 1,500 tokens, `--n-per-file` 40 | `training/export_runtime.py` | model directory | | `CARD_FORMAT` | string | `genclass-runtime-model/1` | `loader.ts`, `export_runtime.py` | written, not validated on read | | `DEFAULT_CACHE_NAME` | string | `genclass-runtime-v1` | `loader.ts` | Cache Storage bucket | -| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | unpublished (404) | +| `DEFAULT_MODEL_BASE_URL` | string | `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` | `model/host.ts` | published 2026-10-08 (was a 404 before) | | `--p-runtime` / `GC_P_RUNTIME` | float | 0.0 (`cur4`: 0.8) | `training/curriculum/generate.py` | share of runtime-exact decision rows | | `GC_RT_BUDGET` | env | unset | `training/curriculum/rt.py` -> `render` | render every runtime row at one budget (analysis) | | `GENCLASS_RUNTIME` | env | `@genclass/runtime` | `sim/src/run/rt.ts` | runtime module the sim imports | @@ -560,7 +560,7 @@ The runtime reads `model.json` (`loader.ts` -> `parseCard`; `format` defaults to | tag | commit | what it froze | data / models on it | |---|---|---|---| | `situation-v1` | 1a77558 ("Runtime fix batch 3", 2026-10-07 19:19 -0400) | v1 text: no `delivery`, held mutations, 3,200 budget | SIM phase A (600,676 rows) and B (1,415,344), `gold-r1x` (832,279), REAL pilots, `cur4`; round-1 models R17/R32-final1 | -| `situation-v2` | 6e5e86e ("Runtime batch 5 …; freeze situation-v2", 2026-10-07 23:26 -0400) | v2 text: `delivery` trigger + descriptions, non-blocking mutations, newer-data/pending conflicts, F1–F3, F5–F7, F9, read-your-writes, leaf-field redaction, diff previews, 2,400 budget | SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL v2 batches (`v2-pilot`, `v2b1–3`), `rt.py` port (d73d20c); no model yet | +| `situation-v2` | 6e5e86e ("Runtime batch 5 …; freeze situation-v2", 2026-10-07 23:26 -0400) | v2 text: `delivery` trigger + descriptions, non-blocking mutations, newer-data/pending conflicts, F1–F3, F5–F7, F9, read-your-writes, leaf-field redaction, diff previews, 2,400 budget | SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL v2 batches (`v2-pilot`, `v2b1–3`), `rt.py` port (d73d20c); first model `r17-v2b` = `@genclass/runtime-model@0.1.0` (2026-10-08) | Since `situation-v2`, `packages/runtime/src/situation`, `util.ts`, `state/` and `learn/` are unchanged at b435acb; the only `src` changes are f3636b2 (default mode, devtools labels, `InitOptions.mode` JSDoc), none of them model text. The model side (`src/model`, `jev_local`, `scripts/genclass_export.py`, `export_runtime.py`, the parity fixtures) is unchanged since `situation-v1`, so a v2 export uses the same packer/tokenizer/graph contract. @@ -627,7 +627,7 @@ Since `situation-v2`, `packages/runtime/src/situation`, `util.ts`, `state/` and ## Drift and open issues -- **No situation-v2 model; npm default URL 404.** R17-final1 is `situation-v1` and exists only on the train VM / Mehar's Mac. `@genclass/runtime-model` is not published, so `DEFAULT_MODEL_BASE_URL` (and the CLI default) return 404; `@genclass/runtime@0.1.0-alpha.1` (`latest`, published 2026-10-08) ships no model, nor did the older `0.1.0-alpha.0` (which also defaults to `guard`). Plan per HANDOFF: T150 teacher on v2 gold → teacher labels on unlabeled rows → distil R17 (default) and R32 → DAgger via `--on-policy` → EVAL → `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0`. Release procedure: [RELEASE.md](../../RELEASE.md) (Part A alpha.1, done; Part B model packaging and validation). +- **The first situation-v2 model is published (2026-10-08 ~13:40 UTC).** `@genclass/runtime-model@0.1.0` (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2, the first situation-v2 model) is `latest` on npm, so `DEFAULT_MODEL_BASE_URL` (and the CLI default) resolve on jsDelivr; `@genclass/runtime@0.1.0-beta.0` (`latest`) loads it by default. Before that, `@genclass/runtime@0.1.0-alpha.1` shipped with no published model (the URL was a 404), as did the older `0.1.0-alpha.0` (default `guard`, now deprecated). R17-final1 is `situation-v1` and exists only on the train VM / Mehar's Mac. Original plan per HANDOFF: T150 teacher on v2 gold → teacher labels on unlabeled rows → distil R17 (default) and R32 → DAgger via `--on-policy` → EVAL → `@genclass/runtime-model@0.1.0` → demos rerun → `@genclass/runtime@0.1.0`. Release procedure: [RELEASE.md](../../RELEASE.md) (Part A alpha.1, done; Parts B and C, model and beta.0, done 2026-10-08). - **SIM scenario budgets still 3,200 / 2,000 / 1,000** (`scenario.ts`, comment "3,200 WebGPU"; sim/README.md says the same), while the runtime's webgpu/unknown auto budget is 2,400 and section limits saturate at 2,400. SIM v2 data never renders the production webgpu budget exactly, and its 3,200 rows are longer than anything a v2 runtime sends by default. `rt.py` `BUDGETS` uses 2,400. `training/PLAN-v1.md` ECE targets and MODEL_CARD latency still quote 3,200. - **Sim action paraphrases on delivery** (gotchas): `ACTION_PARA` is keyed by action name, so paraphrased trajectories give delivery `deliver`/`discard`/`defer` failure- or write-flavoured descriptions; there is no delivery-specific paraphrase set. - **`collect_gain.py` needs a gain head the repo does not have:** it reads `o.gain` from `heads(...)`, but `jev_local/engine/encoder/heads.py` -> `HeadOut` defines no `gain` field. The gain-head code (`r17-t1h`, `training/LOG.md` 03:00–03:12) presumably lives in the VM's `~/jev` (unverified). No T1 result exists on v1; T1 is to be rerun on v2 (`training/LOG.md` 03:32). diff --git a/docs/agents/overview.md b/docs/agents/overview.md index 75b214d4..770dfc74 100644 --- a/docs/agents/overview.md +++ b/docs/agents/overview.md @@ -1,7 +1,7 @@ # GenClass-lib system overview: the mental model > **Scope:** the whole monorepo at the level of one mental model: `@genclass/runtime` (`packages/runtime/src/**`), -> the unpublished model package (`packages/runtime-model/`), `sim/`, `realapps/`, `training/`, `demos/`, and the +> the model package (`packages/runtime-model/`, published as `@genclass/runtime-model@0.1.0`), `sim/`, `realapps/`, `training/`, `demos/`, and the > legacy GenClass content it builds on (`jev_local/`, `extension/`, `bench/`, `results/`, `scripts/`, legacy > `docs/*.md`). Detail lives in the subsystem docs linked from every section; this doc names the stages and the seams > between them. @@ -42,11 +42,13 @@ Path convention: every code pointer is `path/from/repo/root` -> `symbol`. Runtim - Fail open everywhere: no model, a loading or failed model, a timeout or any error means the passive action runs; the runtime holds only when a non-passive action is permitted **and** the model is expected to answer within the hold budget (at most 800 ms with the default `"auto"`). -- **Where it stands:** `@genclass/runtime@0.1.0-alpha.1` (situation-v2, NaN fix, default `observe`) is `latest` on npm; no model is - published (`@genclass/runtime-model` is a 404), so any install only observes. No situation-v2 model exists. The - colleague is generating v2 data on Azure (SIM ~10M gold + ~50M unlabeled rows on 20 nodes; REAL ~0.5M real-browser - gold rows on 3 nodes); next comes the 150M teacher, distillation into R17/R32, DAgger, EVAL, the model package, a - demos rerun and `@genclass/runtime@0.1.0`. +- **Where it stands (2026-10-08 ~13:45 UTC):** `@genclass/runtime@0.1.0-beta.0` (default `observe`, loads the model by + default) is `latest` on npm, and `@genclass/runtime-model@0.1.0` (`r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2, the + first situation-v2 model; gates guard 0.80 {mutation 0.95}, heal 0.85 {failure 0.95, inconsistency 0.85}, report + 0.85) is `latest`; the default model URL on jsDelivr resolves. A default install loads the model and decides, but + acts only in `guard`/`heal`. `0.1.0-alpha.0` is deprecated. Nothing is pushed to GitHub. Earlier the same day, + `0.1.0-alpha.1` was `latest` with no model published. Next: a `0.2.0` model, a demos rerun and + `@genclass/runtime@0.1.0`. ## 1. The problem and the product principles @@ -105,7 +107,7 @@ Adoption path: `observe` (default) -> `guard` -> `heal`. +-------------------------------------------------------------------------------------------------------+ ^ model directory: model.json, *-q8.onnx, *-fp16.onnx, | tokenizer.json, calibration.json, meta.json - OFFLINE | (planned: @genclass/runtime-model@0.1.0, a 404 today) + OFFLINE | (@genclass/runtime-model@0.1.0, published 2026-10-08) sim/ --drives the real createRuntime in a virtual world--> gold / unlabeled / on-policy rows realapps/ --91 real apps + the real runtime in headless Chromium--> gold / unlabeled REAL rows training/ curriculum (rt.py) + T150 teacher on gold -> teacher labels on unlabeled rows @@ -121,11 +123,11 @@ Adoption path: `observe` (default) -> `guard` -> `heal`. | State | `packages/runtime/src/state/*`, `packages/runtime/src/adapters/*` | `StoreHub` (atom/guard/adapter stores), drop filter, late revert, opt-in holds, invariant miner (10 templates), stale marks, snapshots; React/Redux/Zustand adapters | frozen at `situation-v2` | [state-and-adapters](runtime/state-and-adapters.md) | | Learn, situation, triage | `packages/runtime/src/learn/*` (incl. `cadence.ts`), `packages/runtime/src/situation/*` (incl. `conflicts.ts`, `content.ts`, `evidence.ts`) | baselines, profiles, cadence, version conflicts, content facts F1–F3, evidence facts F5–F9, triage, situation text and questions (model input) | frozen at `situation-v2` | [learn-situation-triage](runtime/learn-situation-triage.md) | | Decide | `packages/runtime/src/decide/*`, controllers in `runtime.ts` | queue (stale drop, deadlines), hold budget, policy gate, actions, reports, explain, undo | frozen at `situation-v2` | [decide-policy-actions](runtime/decide-policy-actions.md) | -| Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | unchanged since `situation-v1`; no model to load | [model-host](runtime/model-host.md) | +| Model host | `packages/runtime/src/model/*`, `packages/runtime/bin/genclass-runtime.mjs` | worker, loader (Cache Storage + sha256), WebGPU/WASM plans, Python-parity packer, calibration, CLI | default model `@genclass/runtime-model@0.1.0` published 2026-10-08 | [model-host](runtime/model-host.md) | | Devtools | `packages/runtime/src/devtools/*` | shadow-DOM overlay on the public API | mode labels "Observe (default)", "Guard (opt-in)", "Heal (experimental)" | [devtools](runtime/devtools.md) | -| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}`, root `package-lock.json`, `.github/workflows/ci.yml` | tsup ESM build (6 entries), vitest (351 tests), Playwright, smoke test, CI | alpha.1 published (`latest`; alpha.0 before it); lockfile and CI committed (CI not yet run on GitHub: `mvp-v2` is not pushed) | [build-test-release](runtime/build-test-release.md) | +| Build, test, release | `packages/runtime/{package.json,tsup.config.ts,test/**}`, root `package-lock.json`, `.github/workflows/ci.yml` | tsup ESM build (6 entries), vitest (351 tests), Playwright, smoke test, CI | `0.1.0-beta.0` published (`latest` since 2026-10-08 ~13:40 UTC; alpha.1 before it, alpha.0 deprecated); lockfile and CI committed (CI not yet run on GitHub: `mvp-v2` is not pushed) | [build-test-release](runtime/build-test-release.md) | | Model I/O contract | runtime `situation/*` + `model/*`, `sim/`, `realapps/`, `training/` | situation text -> packed request -> heads -> calibrated answers; row kinds and labels | format `situation-v2` | [model-io-contract](model-io-contract.md) | -| Model package | `packages/runtime-model/` | planned home of the published model directory | only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | +| Model package | `packages/runtime-model/` | home of the published model directory | tracks `MODEL_CARD.md` (and LICENSE); `@genclass/runtime-model@0.1.0` is `latest` on npm (2026-10-08) | [model-host](runtime/model-host.md), [build-test-release](runtime/build-test-release.md) | | Sim | `sim/` (`@genclass/sim`) | training-data generator driving the real runtime in a virtual world: 46 feature combinators × 115 domains; gold, unlabeled and on-policy rows; S1/S2 labels | v1 data on disk (phase A 600,676, phase B 1,415,344 rows); v2 runs in progress on Azure | [sim](sim.md) | | Real-app corpus | `realapps/` | 91 real apps (77 written + 14 OSS RealWorld front-ends, 23 frameworks) with the real runtime in headless Chromium on virtual time; same labels as the sim; the never-worse sweep | v2 batches `v2b1`–`v2b3` in progress on c01/c10/c11 (per `training/NEEDS.md`, unverified from here); no tests, not in CI or the workspaces | [realapps](realapps.md) | | Training | `training/` | vocabulary, curriculum (`rt.py` at situation-v2), training rounds, teacher labelling, distillation, eval, ONNX export | final round 1 (situation-v1) done and superseded; v2 program prepared, not run | [training](training.md) | @@ -257,7 +259,7 @@ Other outcomes of the same delivery: | default `mode: "observe"` | nothing is permitted, so `waits` is false and the response is released as soon as the trigger runs (after the body read, up to 100 ms: the pre-filter does not check the mode). The release marks the chain as delivered over newer data (F9). Because the subject is already released, the queued delivery decision is dropped as stale before the model sees it; the app's write is not `covered` (salient, not decided), so `observeWrite` raises a background `mutation` decision instead, which can only flag (`[GenClass] Flagged a stale write: ...`). | | gate fails (mass < 0.9, top diagnosis `expected`, rate limit) | `deliver`: the stale results show; a `Flagged a stale response` detection line prints when the diagnosis is not `expected` with p ≥ 0.6 | | model not expected within the hold budget (`expectedLatency` too high) or slower than the budget | the response is released at once or at the budget (fail open); the writes are then not `covered`, so they get a background `mutation` decision, and a gate-passing `discard` can **late-revert** the write within 2 s if nothing changed those fields since (`delivery.test.ts` -> "a slow model: the response is released at the budget, its writes are decided in the background and late-reverted") | -| model loading, failed or absent (every install today: the default model URL 404s) | `consultable()` is false: `runDelivery` releases at once, no facts are computed, nothing is recorded; the stale write applies exactly as without GenClass | +| model loading, failed or absent (every install before 2026-10-08, when the default model URL was a 404) | `consultable()` is false: `runDelivery` releases at once, no facts are computed, nothing is recorded; the stale write applies exactly as without GenClass | | model status `off` (lazy preload not started) | the pre-filter and facts run; this salient delivery starts the model load and is released at once (fail open) | | `heal` mode | as `guard` here (no heal-tier delivery action) | @@ -409,8 +411,8 @@ guard 0.9, heal 0.8. Default: `packages/runtime/src/runtime.ts` -> `RuntimeImpl` Also: `policy.allow` / `policy.deny` narrow the permitted set; `policy.holdWrites: true` re-enables held store writes (opt-in, never reorders a store's writes); `pause()` stops gating and triggers while tracing continues; `setMode` applies to the next gate. Passive actions per trigger: mutation `apply`, request `send`, delivery `deliver`, failure -`deliver`, stall `wait`, inconsistency/transition/error `ignore`. The older published alpha.0 and HANDOFF.md still say -`guard` is the default (alpha.1 says `observe`); the unit-test harness passes `mode: "guard"`. Details: +`deliver`, stall `wait`, inconsistency/transition/error `ignore`. The older published alpha.0 (deprecated) and HANDOFF.md still say +`guard` is the default (alpha.1 and beta.0 say `observe`); the unit-test harness passes `mode: "guard"`. Details: [public-api-and-lifecycle](runtime/public-api-and-lifecycle.md), [decide-policy-actions](runtime/decide-policy-actions.md). ## 7. With no model: fail open, observe only @@ -426,14 +428,16 @@ and its state is `ready` or `off`. Consequences: | `error` | same as `loading`, permanently: `ready` is memoised and nothing retries the load | | `ready` | full pipeline | -What a default `GenClass.init()` does at b435acb (code reading; no test covers the browser path): it creates a model -host for `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` -(`packages/runtime/src/model/host.ts`); the idle preload fetches `model.json` from a package that does not exist (a -404 per a check on 2026-10-08), the status becomes `error`, the console prints `[GenClass] Model unavailable +What a default `GenClass.init()` does: it creates a model host for `DEFAULT_MODEL_BASE_URL` = +`https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`packages/runtime/src/model/host.ts`); since +2026-10-08 that package is published and the idle preload loads it (a Chromium check with the jsDelivr script tag +loaded it in a Web Worker on WebGPU (fp16) in 4.75 s; `decide()` answered in 72 ms), so the status becomes `ready`. +When the model cannot be fetched (offline, blocked CDN, or before 2026-10-08 when the package was a 404; code reading +at b435acb, no test covers the browser path), the status becomes `error`, the console prints `[GenClass] Model unavailable (...); observing only.`, and from then on no situation is built and nothing is held or acted on. Tracing, field versions, baselines, cadence, invariants and profiles keep learning; `rt.situation()` still works; `rt.ask()` rejects. -The CLI's default source (`genclass-runtime fetch-model`, `DEFAULT_FROM`) is a 404 too. The only trained runtime model, -R17-final1, is situation-v1 and lives only on the train VM / the colleague's Mac; it does not match this runtime. Full +The CLI's default source (`genclass-runtime fetch-model`, `DEFAULT_FROM`) is the same jsDelivr directory and resolves +too. The round-1 model R17-final1 is situation-v1 and does not match this runtime; the published `r17-v2b` does. Full sequence: [model-host](runtime/model-host.md). ## 8. Workstreams and ownership @@ -467,8 +471,8 @@ update the relevant STATUS/NEEDS entry when you change behaviour they describe. | Runtime | batches 4 and 5 done: decisions at the network boundary, no store holds by default, EventSource observer, F1–F9 facts, leaf-based redaction, 2,400-char full budget; default mode `observe` (ours). | | Tests | lead's run on `mvp-v2` (macOS, Node v25.6.0): `tsc` clean, `tsup` OK, vitest 351 tests = 337 passed + 14 model-parity skips (333 + 14 in the main run, counting the uncommitted `atoms.test.ts` test, 4 in `review-perf.test.ts` alone; it flaked once at 5.5 ms vs its 2 ms bound under parallel load). sim: `tsc` clean, `SIM_RUNTIME=real npx vitest run` 19 passed in 5 files. Not run: Playwright, `smoke.sh`, realapps, demos eval, Python tests, training. | | CI | `.github/workflows/ci.yml` (Node 22, `npm ci`, typecheck, build, unit tests, then `review-perf` with `--retry=2`); its steps pass in a fresh clone; it has not run on GitHub yet. | -| npm | `@genclass/runtime@0.1.0-alpha.1` is `latest` (published 2026-10-08 from 806a296; NaN fix, situation-v2, default `observe`, no model). The older `0.1.0-alpha.0` is situation-v1 code with default `guard`. `@genclass/runtime-model` is a 404. Release procedure: [RELEASE.md](../../RELEASE.md). | -| Model | no situation-v2 model. R17-final1 (situation-v1) is the baseline only (section 5.3). | +| npm | Since 2026-10-08 ~13:40 UTC: `@genclass/runtime@0.1.0-beta.0` is `latest` (from 1f0f617; default `observe`, loads the model by default) and `@genclass/runtime-model@0.1.0` is `latest` (`r17-v2b`); `0.1.0-alpha.0` (situation-v1, default `guard`) is deprecated. Before that, `0.1.0-alpha.1` (806a296; NaN fix, situation-v2, default `observe`, no model) was `latest`. Release procedure: [RELEASE.md](../../RELEASE.md). | +| Model | `@genclass/runtime-model@0.1.0` = `r17-v2b` (first situation-v2 model, published 2026-10-08). R17-final1 (situation-v1) is the baseline only (section 5.3). | | Data | SIM v2 (≥ 10M gold + ≥ 50M unlabeled) on c02–c09 and c12–c23; REAL v2 (≥ 500k gold) on c01, c10, c11; the colleague is operating the cluster (a read-only portal look at 04:14 UTC showed c01–c23 and `vm-jev-train` running, `vm-jev-data` deallocated). Nobody on our side touches Azure. | | Never worse | realapps sweep, v2 runtime, all-passive model: 0/396 clean runs changed, 3/198 with chaos (request-time holds shifting chaos draws; open), determinism 198/198, conduit 0/30 (STATUS.md). These cover the 66 apps at the time, not the 25 added since, and compare final visible text and server content only ([realapps](realapps.md)). | | Next (HANDOFF.md) | v2 data collected -> 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0`. | diff --git a/docs/agents/playbooks.md b/docs/agents/playbooks.md index 66631e8a..239465fd 100644 --- a/docs/agents/playbooks.md +++ b/docs/agents/playbooks.md @@ -8,7 +8,7 @@ - The runtime is **situation-v2** (tag `situation-v2` = 6e5e86e): decisions happen at the network boundary (trigger `delivery`), store writes are not held by default, and the model-visible text is **frozen**. Any change to what the model reads needs the user's go-ahead, a new tag, regenerated SIM **and** realapps data, and a retrain (recipe 6). - On `mvp-v2` the only runtime changes since the tag are ours: f3636b2 (default mode `observe`; `guard` opt-in, `heal` experimental) and b435acb (CI, committed root lockfile, CLI 100755). Neither touches model text. -- **No situation-v2 model exists.** The plan (HANDOFF): 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0` (recipes 30, 20, 22, 19; release procedure in [`RELEASE.md`](../../RELEASE.md)). +- **The first situation-v2 model is published (2026-10-08):** `@genclass/runtime-model@0.1.0` = `r17-v2b`, loaded by default by `@genclass/runtime@0.1.0-beta.0`. The plan was (HANDOFF): 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> `@genclass/runtime-model@0.1.0` -> demos rerun -> `@genclass/runtime@0.1.0` (recipes 30, 20, 22, 19; release procedure in [`RELEASE.md`](../../RELEASE.md)). - Light local checks are fine: `npm ci`, runtime `tsc`/`tsup`/vitest, sim `tsc` and `SIM_RUNTIME=real` vitest. **Ask the user first** for Playwright, `smoke.sh`, the sim generator, realapps, training, demos eval, model downloads, anything on Azure, `git push`, `npm publish`. Azure is operated by the colleague (Mehar) right now; nobody on our side touches it. - Baseline at b435acb: runtime unit tests 332 passed + 14 skipped (40 + 1 files) without `review-perf`, which passes alone (4); sim 19 passed (5 files). CI (`.github/workflows/ci.yml`) runs the same runtime steps (recipe 21). - New recipes: never-worse sweep (28), add a realapps app (29), the v2 training pipeline (30). @@ -44,7 +44,7 @@ Conventions used below: | tag | commit | data and models built on it | |---|---|---| | `situation-v1` | 1a77558 | SIM phase A (600,676 rows) and B (1,415,344), `gold-r1x`, REAL pilots `pilot4`/`pilot-all`, curriculum `cur1`–`cur4`, round-1 R17/R32-final1. Superseded: does not match the v2 runtime. | -| `situation-v2` | 6e5e86e | **current.** SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL `v2-pilot` and `v2b1`–`v2b3`, the `rt.py` port (d73d20c). No model yet. | +| `situation-v2` | 6e5e86e | **current.** SIM v2 gold/unlabeled runs (`train:/data/sim-out/v2-*`), REAL `v2-pilot` and `v2b1`–`v2b3`, the `rt.py` port (d73d20c). First model: `r17-v2b` = `@genclass/runtime-model@0.1.0` (published 2026-10-08). | `git diff situation-v2 b435acb -- packages/runtime/src` touches only `devtools/index.ts`, `runtime.ts` (the default mode) and `types.ts` (JSDoc), all f3636b2, none of them model text. Before editing, classify your change (condensed from [model-io-contract.md](model-io-contract.md#versioning-what-invalidates-the-trained-model)): @@ -400,7 +400,7 @@ A change is done when all of these hold. Say explicitly in your final report whi **Tests.** Pattern: `packages/runtime/test/plugins.test.ts`. In an app, verify with `rt.explain(id)` and the devtools overlay. -**Parity / retrain / release.** No retrain is needed: the model reads the description at runtime. Answer quality on custom actions and questions is unmeasured, and no v2 model exists yet. +**Parity / retrain / release.** No retrain is needed: the model reads the description at runtime. Answer quality on custom actions and questions is unmeasured (also with the published v2 model, `r17-v2b`). **Gotchas.** Custom actions are gated at their own tier. At budgets ≤ 1,400 characters (`COMPACT_QUESTIONS_BUDGET`), custom descriptions are sent as `null` unless a `vocabulary.actions` override of ≤ 24 characters exists. Avoid question ids `action` and `diagnosis`. A non-iterable `plugins`, `actions` or `questions` throws inside the constructor (`GenClass.init` then returns an inert runtime). Custom actions can hold a subject indefinitely. @@ -443,7 +443,7 @@ A change is done when all of these hold. Say explicitly in your final report whi 5. **New graph input or head:** `packages/runtime/src/model/engine.ts` -> `FEEDS`, `OUTPUT_KIND`; `packages/runtime/src/model/packer.ts` -> `planInputs`, `unpackLogits`; `packages/runtime/src/model/serialize.ts` -> `BlockKind`, `questionBlock`; `packages/runtime/src/model/calibrate.ts`; the `Question` / `Answer` types in `packages/runtime/src/types.ts`. This is also a training change (recipe 13). 6. **onnxruntime-web upgrade:** `packages/runtime/package.json` (`^1.30.0`; update the lockfile), `packages/runtime/src/model/backend.ts` -> `ORT_FALLBACK_VERSION`, check `ORT_WASM_FILES` names exist in the new `dist/`, keep the externals, update the browser-test regex expecting `onnxruntime-web@1.30.x` and the pinned `onnxruntime-node` devDependency (CI skips its binary download with `ONNXRUNTIME_NODE_INSTALL=skip`). 7. **CLI:** `packages/runtime/bin/genclass-runtime.mjs` (`fetch-model`, `info`; committed as 100755); keep its `parseCard` in sync with `packages/runtime/src/model/loader.ts` -> `parseCard`. No automated CLI tests. -8. **Default model URL:** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` (recipe 20). Both 404 today. +8. **Default model URL:** `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` and the CLI's `DEFAULT_FROM` (recipe 20). Both resolve since `@genclass/runtime-model@0.1.0` was published (2026-10-08); before that both were 404. 9. **Self-hosting (app integration):** `npx genclass-runtime fetch-model public/genclass-model --from ` **[ask first]** (download); copy both `ort-wasm-simd-threaded.wasm` and `ort-wasm-simd-threaded.asyncify.wasm` from `node_modules/onnxruntime-web/dist/`; `GenClass.init({ mode: "guard", model: { baseUrl: "/genclass-model/", ortWasmPaths: "/ort/" } })`; serve COOP/COEP for WASM threads. There is no situation-v2 model to self-host yet: the round-1 R17 export reads v1 text and must not be loaded into this runtime. **Tests.** Local, no model files needed: `packages/runtime/test/model/`: `host.test.ts`, `loader.test.ts`, the `engine.test.ts` graph-contract test. **[ask first]** `npm run test:browser` (needs a model directory and Playwright Chromium; rebuilds `dist/`). @@ -592,7 +592,7 @@ Sim typecheck and `SIM_RUNTIME=real npx vitest run` are light local checks (buil **Steps.** 1. **Decide with the user which release** (RELEASE.md A0, B0): - **Part A, `0.1.0-alpha.1` (done 2026-10-08, no model):** the NaN fix plus the situation-v2 runtime and the `observe` default, published under dist-tag `latest` from release commit 806a296 (the plan was dist-tag `alpha`). Without a model it only observes, so the open review findings go into the release notes, not the blocker list. - - **Part B (after a situation-v2 model exists):** `@genclass/runtime-model@0.1.0` and its GitHub release first (recipe 20), then the demos eval (recipe 22), then `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. Part B treats the open findings as blockers. + - **Part B (after a situation-v2 model exists):** `@genclass/runtime-model@0.1.0` and its GitHub release first (recipe 20), then the demos eval (recipe 22), then `@genclass/runtime@0.1.0-beta.0` or `0.1.0`. Part B treats the open findings as blockers. Published 2026-10-08 ~13:40 UTC: `@genclass/runtime-model@0.1.0` (`r17-v2b`) and `@genclass/runtime@0.1.0-beta.0`, both `latest`; no GitHub release was created. - Which branch and commit: `mvp-v2` is unpushed; the colleague works on `origin/runtime`. The release commit must reach `origin` (the user decides how). 2. **Fix what the tarball ships** (RELEASE.md A1): `packages/runtime/README.md` is the npm page: check the README status line and version before packing, and commit any fix. 3. **Clean release worktree** (RELEASE.md A2): `git worktree add -b release/runtime- ../GenClass-lib-release `; `git status --porcelain` must print nothing. The main checkout may hold other agents' uncommitted edits, and `tsup` bundles whatever is on disk. @@ -628,7 +628,7 @@ Sim typecheck and `SIM_RUNTIME=real npx vitest run` are light local checks (buil **Gotchas.** Cache Storage (`genclass-runtime-v1`) never evicts old versions. `model.json` is revalidated on every load. The demos' `?model=cdn` falls back to `DEFAULT_MODEL_BASE_URL`. -**See.** [RELEASE.md Part B](../../RELEASE.md#part-b-model-package-then-genclassruntime010-after-a-situation-v2-model-exists), [build-test-release.md](runtime/build-test-release.md), [model-host.md](runtime/model-host.md). +**See.** [RELEASE.md Part B](../../RELEASE.md#part-b-genclassruntime-model010-done-2026-10-08-with-r17-v2b-see-the-note-at-the-top), [build-test-release.md](runtime/build-test-release.md), [model-host.md](runtime/model-host.md). ### 21. Change the CI workflow @@ -745,7 +745,7 @@ The example is a sketch: check the exact late-revert conditions in `atoms.test.t **Goal.** Find out why GenClass changed an app's behaviour when it should not have, relieve the user, and fix the right layer without adding a rule. **Steps.** -1. **Confirm the runtime could act.** Check `GenClass.runtime.status` (`state`, `model`, `variant`) and `GenClass.runtime.mode`. In the default `observe` mode (this branch) nothing non-passive can run. With `@genclass/runtime@0.1.0-alpha.0` (default `guard`) the default model URL 404s, the status ends in `error` and the console says "Model unavailable (...); observing only.". So an intervention implies an explicit `mode: "guard" | "heal"` (or `setMode`, or `?genclass=guard|heal`) **and** a self-hosted `model.baseUrl` or a custom `decider`. Guard runs only guard-tier actions: `discard`, `defer`, `coalesce`, `delay`, and custom actions declared `tier: "guard"`. +1. **Confirm the runtime could act.** Check `GenClass.runtime.status` (`state`, `model`, `variant`) and `GenClass.runtime.mode`. In the default `observe` mode (this branch) nothing non-passive can run. With the alphas (`@genclass/runtime@0.1.0-alpha.0`, default `guard`, and `0.1.0-alpha.1`) the default model URL was a 404 before 2026-10-08, the status ended in `error` and the console said "Model unavailable (...); observing only.". Since 2026-10-08 the default URL serves `@genclass/runtime-model@0.1.0`, which `0.1.0-beta.0` loads by default. So an intervention implies an explicit `mode: "guard" | "heal"` (or `setMode`, or `?genclass=guard|heal`) **and** a model with status `ready` (the default one, a self-hosted `model.baseUrl` or a custom `decider`). Guard runs only guard-tier actions: `discard`, `defer`, `coalesce`, `delay`, and custom actions declared `tier: "guard"`. 2. **Collect the evidence.** The console line `[GenClass] : (, p; p)`; `GenClass.runtime.interventions()` -> `ActionRecord` (`id` `a`, `decisionId`, `action`, `tier`, `changed`, `ok`, `error`, `late`); `GenClass.runtime.explain("a")` -> `Explanation` (`situationText`, `facts`, `timeline`, `answers`, and `decision` with `diagnosisProbabilities`, `probabilities`, `candidate`, `mass`, `tier`, `reason`). The devtools overlay shows the same evidence with a Copy button. `GenClass.runtime.history(400)` gives the event log; `debug: true` logs swallowed errors. 3. **Relieve the user.** `ActionRecord.undo?.()` exists only for `discard`, late reverts, `rollback` and custom actions with `onUndo`. At the next page load: `GenClass.init({ policy: { deny: [""] } })`, or drop the explicit mode (default observe), or `?genclass=observe` / `?genclass=off` / `localStorage.genclass = "off"`. A delivery `discard` mark keeps dropping that chain's writes for 10 s even after `pause()` or `setMode("observe")` (open finding): a reload is the reliable reset. 4. **Classify** (read the evidence against the code): diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index 1749a180..6d2b5c97 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -25,9 +25,9 @@ f107013 (redaction). `origin/runtime` has four newer commits (up to 5bc40c9, run | dir | tracked files | what | owner / workstream | doc | relevance | |---|---|---|---|---|---| -| `packages/runtime/` | 183 | `@genclass/runtime`, version `0.1.0-alpha.1` in the tree (= the published `latest`, which lacks the install code: bump before the next build), the npm library: `src/` (72), `test/` (95), `bin/` (6: `genclass-runtime.mjs` CLI, mode 100755, plus `bin/lib/` with `init`/`remove`), package and build configs, STATUS, CHANGELOG, INSTALL-NEEDS, UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/genclass-runtime.mjs` (`fetch-model`, `info`). INSTALL owns `src/auto.ts`, `src/cdn/**`, `bin/lib/**`, `test/install/**`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Us (lead): `test/default-mode.test.ts`, `test/observe-delivery.test.ts`, `test/redaction-v2.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | +| `packages/runtime/` | 183 | `@genclass/runtime`, version `0.1.0-alpha.1` in the tree at f107013 (bumped to `0.1.0-beta.0` in 9695830; `0.1.0-beta.0` is the published `latest` since 2026-10-08 ~13:40 UTC), the npm library: `src/` (72), `test/` (95), `bin/` (6: `genclass-runtime.mjs` CLI, mode 100755, plus `bin/lib/` with `init`/`remove`), package and build configs, STATUS, CHANGELOG, INSTALL-NEEDS, UI-NEEDS | CORE. MODEL owns `src/model/**` and `bin/genclass-runtime.mjs` (`fetch-model`, `info`). INSTALL owns `src/auto.ts`, `src/cdn/**`, `bin/lib/**`, `test/install/**`. UI owns `src/devtools/**` and `src/adapters/**`. REVIEW owns `test/review-*.test.ts`. Us (lead): `test/default-mode.test.ts`, `test/observe-delivery.test.ts`, `test/redaction-v2.test.ts` | the 8 docs under `runtime/`; start with [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | core | | `packages/genclass-runtime/` | 4 | (new, f3a9dd1) unscoped alias package `genclass-runtime` 0.1.0-alpha.1: `cli.mjs` imports `@genclass/runtime`'s `bin/genclass-runtime.mjs`; `package.json` (dependency `@genclass/runtime` `0.1.0-alpha.1`), `README.md`, `LICENSE`. A workspace (`packages/*`), **not published** | INSTALL | `packages/runtime/INSTALL-NEEDS.md` item 1 | core (planned) | -| `packages/runtime-model/` | 1 | `MODEL_CARD.md` only. Planned npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at. It has no `package.json` and its `files/` directory is gitignored, so it is not a workspace and is unpublished (npm 404). No situation-v2 model exists yet | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | +| `packages/runtime-model/` | 1 | `MODEL_CARD.md` only at f107013 (since ba11126/bcbee89 also `package.json` and `LICENSE`, so it is a workspace). The npm package `@genclass/runtime-model` that `DEFAULT_MODEL_BASE_URL` points at; `0.1.0` (`r17-v2b`, the first situation-v2 model) is published since 2026-10-08. Its `files/` directory is gitignored | lead | [runtime/model-host.md](runtime/model-host.md) | core (planned) | | `sim/` | 106 | `@genclass/sim` (private): training-data simulator that drives the real runtime and writes CONTRACT-D rows. Now 46 feature combinators, 115 domains, S1/S2 labels, gold / unlabeled / on-policy row modes, Azure cluster scripts, separability analysis | SIM | [sim.md](sim.md) | supporting | | `realapps/` | 307 | `@genclass/realapps` (private, **not** a root workspace): 128 app directories with a `manifest.ts` (114 written + 14 open-source Conduit front-ends; Mehar's commit messages say 96 after wave 3, the wave-4 apps arrived inside f3a9dd1 and eff18cb) run in headless Chromium with the real runtime; counterfactual labels like the sim; the "never worse" interference and determinism sweeps | REAL | [realapps.md](realapps.md) | supporting | | `training/` | 69 | Python curriculum generator, runtime-text port (`curriculum/rt.py`, frozen at `situation-v2`), eval, ONNX export, Azure launch scripts for R17/R32/R68 students and the T150 teacher, teacher labelling, T1 expected-gain scripts | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | @@ -81,7 +81,7 @@ Doc: [runtime/build-test-release.md](runtime/build-test-release.md), [runtime/pu ```text packages/runtime/ - package.json @genclass/runtime, version 0.1.0-alpha.1 (= published latest; bump before the next build); exports . ./auto + package.json @genclass/runtime, version 0.1.0-alpha.1 (0.1.0-beta.0 since 9695830 = published latest); exports . ./auto ./auto/observe ./auto/guard ./auto/heal ./react ./redux ./zustand ./devtools ./worker (no typesVersions); sideEffects [dist/auto.js, dist/auto/*.js, dist/genclass.global{,.min}.js, dist/cdn/*.js, src/model/worker.ts]; unpkg/jsdelivr -> dist/genclass.global.min.js; bin genclass-runtime; dep onnxruntime-web ^1.30.0; @@ -92,7 +92,7 @@ packages/runtime/ (IIFE, onnxruntime-web external, __GENCLASS_VERSION__ = package version); CDN worker -> dist/cdn/{worker, ort-webgpu,ort-wasm}.js (onnxruntime-web bundled, plugin cdnOrt) vitest.config.ts unit tests: test/**/*.test.ts, excludes test/browser/**, env node, testTimeout 20000 - README.md npm package README (rewritten by Mehar, d05abc1): one-command install, observe default, no model yet; + README.md npm package README (rewritten by Mehar, d05abc1): one-command install, observe default, no model yet (at f107013); says init, /auto and the script tag are "not in 0.1.0-alpha.1" CHANGELOG.md (new, f3a9dd1) "## 0.1.0-alpha.1" wrongly lists the install paths (they are not in the published alpha.1) INSTALL-NEEDS.md (new, f3a9dd1) INSTALL -> lead/CORE/MODEL/UI: npx naming decision, package.json and tsup changes, @@ -308,7 +308,7 @@ The 18 PNGs are written by `ui-devtools.spec.ts`; no README embeds them. ```text packages/runtime-model/ - MODEL_CARD.md model card for R17/R32 (sizes, final round 1 on situation-v1, limits); the package itself does not exist yet + MODEL_CARD.md model card for R17/R32 (sizes, final round 1 on situation-v1, limits); since bcbee89 the card for r17-v2b, published as @genclass/runtime-model@0.1.0 ``` ### `sim/` (106 files) @@ -887,7 +887,7 @@ Verified with `grep` at b435acb; rows touched by the merge and the two fixes re- | X | kind | where | doc | |---|---|---|---| | Model host factory | function | `packages/runtime/src/model/host.ts` -> `createModelHost` | [model-host](runtime/model-host.md) | -| Default model URL (unpublished `@genclass/runtime-model@0.1.0`, 404) | constant | `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | [model-host](runtime/model-host.md) | +| Default model URL (`@genclass/runtime-model@0.1.0` on jsDelivr, published 2026-10-08) | constant | `packages/runtime/src/model/host.ts` -> `DEFAULT_MODEL_BASE_URL` | [model-host](runtime/model-host.md) | | Host defaults (`DEFAULT_TIMEOUT_MS` 10 s, `DEFAULT_MAX_QUEUE` 32) | constant | `packages/runtime/src/model/host.ts` | [model-host](runtime/model-host.md) | | Worker URL literal `new Worker(new URL("./worker.js", import.meta.url), ...)` | code pattern | `packages/runtime/src/model/host.ts` -> `defaultWorkerFactory` | [build-test-release](runtime/build-test-release.md) | | Load and evaluate (in the worker or inline) | class | `packages/runtime/src/model/backend.ts` -> `ModelBackend` | [model-host](runtime/model-host.md) | @@ -905,7 +905,7 @@ Verified with `grep` at b435acb; rows touched by the merge and the two fixes re- | sha256 integrity / sha1 header keys | function | `packages/runtime/src/model/hash.ts` -> `sha256Hex`, `sha1Hex` | [model-host](runtime/model-host.md) | | Host <-> worker messages | type | `packages/runtime/src/model/protocol.ts` -> `ToWorker`, `FromWorker` | [model-host](runtime/model-host.md) | | `genclass-runtime fetch-model ` / `info ` | CLI | `packages/runtime/bin/genclass-runtime.mjs` -> `fetchModel`, `info` | [model-host](runtime/model-host.md) | -| CLI default source (jsDelivr `@genclass/runtime-model@0.1.0/files/` = `DEFAULT_MODEL_BASE_URL`, 404 until published) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | +| CLI default source (jsDelivr `@genclass/runtime-model@0.1.0/files/` = `DEFAULT_MODEL_BASE_URL`, resolves since 2026-10-08) | constant | `packages/runtime/bin/genclass-runtime.mjs` -> `DEFAULT_FROM` | [status](status-and-known-issues.md) | ### Devtools overlay @@ -1079,8 +1079,8 @@ Ignore rules live in `.gitignore` (root), `demos/.gitignore`, `extension/.gitign | `demos/dist/` | root and `demos/.gitignore` | `npm run build` in `demos` (`demos/scripts/build.mjs`) | — | | `extension/dist/` | root and `extension/.gitignore` | `extension/scripts/build.mjs` (`dist/genclass/`) | — | | `sim/out/` | root | `sim/src/gen.ts` (default `--out sim/out/run`), `sim/scripts/final.sh` (`sim/out/final-a/`, `sim/out/final-b/parts/`) | training data; excluded from `scripts/vm.sh` syncs. v2 production data lives on the train VM under `/data/sim-out/v2-*` and REAL's under `/data/real-out/` (per `training/NEEDS.md`; not checked) | -| `.cache-model/` | root | `node packages/runtime/bin/genclass-runtime.mjs fetch-model .cache-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` (ask first: download; without `--from` the CLI uses `DEFAULT_FROM`, which 404s) | default `GENCLASS_MODEL_DIR`; absent in a fresh clone, so 14 model tests skip. The v0.1 model is a parity fixture only; it does not match situation-v2 | -| `packages/runtime-model/files/` | root | intended for `training/export_runtime.py` output (the planned `@genclass/runtime-model` package) | does not exist at b435acb | +| `.cache-model/` | root | `node packages/runtime/bin/genclass-runtime.mjs fetch-model .cache-model --from https://github.com/MeharPro/GenClass/releases/download/v0.1.0/` (ask first: download; without `--from` the CLI uses `DEFAULT_FROM`, the published `@genclass/runtime-model@0.1.0`, which is not the parity fixture) | default `GENCLASS_MODEL_DIR`; absent in a fresh clone, so 14 model tests skip. The v0.1 model is a parity fixture only; it does not match situation-v2 | +| `packages/runtime-model/files/` | root | intended for `training/export_runtime.py` output (the `@genclass/runtime-model` package, published 2026-10-08) | does not exist at b435acb | | `demos/public/genclass-model/` | `demos/.gitignore` | `npm run fetch-model` in `demos` (`demos/scripts/fetch-model.sh`, v0.1 model) | — | | `packages/runtime/test/browser/.build/` | `packages/runtime/test/browser/.gitignore` | `packages/runtime/test/browser/build.mjs` | bundled test app and build info | | `test-results/` | root, `demos/.gitignore`, `extension/.gitignore` | Playwright (`packages/runtime/test-results/{browser,ui}`), model benchmarks (`packages/runtime/test-results/model-bench/`) | — | @@ -1148,8 +1148,10 @@ Doc-vs-code drift you will meet while navigating; the subsystem docs have the de `USAGE`), its mode mapping (`packages/runtime/bin/lib/plan.mjs` -> `AUTO`) and `packages/runtime/test/install/INSTALL-README-SNIPPET.md` still assume guard ([status-and-known-issues.md](status-and-known-issues.md#install-code-review-2026-10-08)). -- **Version**: `packages/runtime/package.json` and `packages/genclass-runtime/package.json` say `0.1.0-alpha.1`, already - published without the install paths; `packages/runtime/CHANGELOG.md` lists the install paths under alpha.1. +- **Version**: `packages/runtime/package.json` and `packages/genclass-runtime/package.json` said `0.1.0-alpha.1`, already + published without the install paths; `packages/runtime/CHANGELOG.md` listed the install paths under alpha.1. Since 9695830 + the runtime says `0.1.0-beta.0` (published `latest`, 2026-10-08) and the CHANGELOG lists the install paths under it; + the alias is still `0.1.0-alpha.1` (unpublished) with dependency `0.1.0-beta.0`. - **Subsystem docs**: `docs/agents/runtime/build-test-release.md` and `public-api-and-lifecycle.md` (as committed at f107013) still describe six tsup entries and `"sideEffects": false`; no subsystem doc covers `src/auto.ts`, `src/cdn/` or `bin/lib/` yet. diff --git a/docs/agents/runtime/build-test-release.md b/docs/agents/runtime/build-test-release.md index 37d2cda1..ff6aa419 100644 --- a/docs/agents/runtime/build-test-release.md +++ b/docs/agents/runtime/build-test-release.md @@ -16,7 +16,7 @@ - **Default mode is `observe`** in the product (f3636b2: `src/runtime.ts` -> `o.mode ?? "observe"`), but the test harness `test/helpers.ts` -> `setup()` passes `mode: "guard"` by default, and `smoke.test.ts`, `review-fetch.test.ts` -> `headless()` and `test/browser/ui/session.ts` -> `runStoreSession` pass `mode: "guard"` explicitly. Pass `mode: undefined` to `setup()` to get the product default (`test/default-mode.test.ts` does). - **Store writes are not held by default** (situation-v2, `policy.holdWrites` off). Tests that exercise held store writes pass `policy: { holdWrites: true }` (`atoms.test.ts` wraps `setup()` to add it); default behaviour (delivery decisions at the network boundary, late reverts) is tested in `delivery.test.ts`, `content.test.ts`, `no-reorder.test.ts`. - Runtime unit tests run on a virtual clock (`test/helpers.ts` -> `FakeClock`), a virtual HTTP server (`FakeServer`) and a scripted model (`ScriptedDecider` / `ManualDecider`): no real time, no network, no model. Exceptions (wall-time perf checks, `loader.test.ts`'s real `browserClock`, model-file tests) are listed under gotchas. -- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `/.cache-model`); without it 14 model tests skip. **No situation-v2 model is published or in this branch** (Mehar's first one, `r17-v2a`, is evaluated only in origin/runtime 416e374's `docs/runtime/RESULTS.md`, not merged); the only fixtures and models here are the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). +- Model tests need a model directory (`GENCLASS_MODEL_DIR`, default `/.cache-model`); without it 14 model tests skip. Since 2026-10-08 the situation-v2 model `@genclass/runtime-model@0.1.0` = `r17-v2b` is published (its files are not in git: `packages/runtime-model/files/` is gitignored); the committed parity fixtures are still the v0.1 GenClass model's. The gc test needs `NODE_OPTIONS=--expose-gc` (otherwise it logs "skipped" and passes). - Browser tests = Playwright (`npm run test:browser` in `packages/runtime`): `globalSetup` builds the library with tsup and bundles a test app with esbuild; model specs skip without a model directory. A separate config runs the devtools UI spec and writes 18 screenshots. Not run in CI. - `test/smoke/smoke.sh` packs the tarball, installs it into a fresh Vite 8 app, builds it and loads it in headless Chromium. Not run in CI. - Install tests (`test/install/`, f3a9dd1): `cli.test.ts` is an ordinary vitest file (runs `bin/genclass-runtime.mjs init --yes --no-install` and `remove --yes` on fixture projects in the OS temp dir, no network) and runs locally and in CI. The rest is a VM harness (`run-all.sh` -> build + pack -> `cli.test.ts` -> `cdn-check.mjs` -> `scaffold.sh` -> `frameworks.mjs`; Playwright, framework generators, npm registry; outputs under `/data/install`). Mehar's last run is in `test/install/RESULTS.md` (15/15 projects, CLI 20/20, CDN 26/26, against a locally packed `0.1.0-alpha.0`-versioned tarball). Not run in CI. @@ -538,7 +538,7 @@ There is no publish script, no `prepublishOnly` and no `publishConfig`. The reco 4. Give the user the command to run (on a machine logged in to npm with publish rights on the `genclass` org, with their 2FA): `npm publish genclass-runtime-.tgz --access public --tag `. **A prerelease needs `--tag`** on npm 11: `lib/commands/publish.js` in npm 11.8.0 throws "You must specify a tag using --tag when publishing a prerelease version." unless `--tag` (or `publishConfig.tag`, or `--force`) is given, so `HANDOFF.md`'s bare `npm publish --access public` fails for `0.1.0-alpha.1`. Use `--tag alpha` (or `next`) to leave `latest` where it is, or `--tag latest` to move it (today `latest` = `0.1.0-alpha.1`). A non-prerelease such as `0.1.0` needs no tag and becomes `latest`. Never run `npm publish` yourself without an explicit user go-ahead in chat. 5. After the publish: `git tag -a v -m "@genclass/runtime (npm)"` (push only with the user's OK); move the item to "Done" in `OPEN_TASKS.md`; check `npm view @genclass/runtime dist-tags`. -What `0.1.0-alpha.1` (built from `mvp-v2`) changed for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model the runtime still only observes either way. +What `0.1.0-alpha.1` (built from `mvp-v2`) changed for users of `0.1.0-alpha.0`: default mode `observe` (was `guard`), situation-v2 runtime (delivery decisions, no store holds by default), the NaN fix. Without a published model (until 2026-10-08) the runtime still only observed either way. What the next version (from `mvp-v2-merge` or its successor) adds over `0.1.0-alpha.1`: `init` / `remove`, `/auto` entries, the script tag and CDN worker, the `genclass-runtime` alias (all f3a9dd1); observe mode never holds or delays deliveries (054da38); redaction of F2 diffs and numeric/array secrets (f107013); `situation()` purity (29b7f28). The tarball roughly doubles (26 -> 52 files, 486.8 kB -> 1.1 MB packed), mostly the script-tag build and its source map. @@ -546,7 +546,7 @@ What the next version (from `mvp-v2-merge` or its successor) adds over `0.1.0-al Full procedure: [RELEASE.md](../../../RELEASE.md) Part B. -Blocked on training: no situation-v2 model is ready to publish. The first one, `r17-v2a`, has held-out results in origin/runtime 416e374 (`docs/runtime/RESULTS.md`, not merged here): its fixed 0.9/0.8 gates block nearly every action, and runtime batch 6 (5bc40c9, not merged) reads gate thresholds from the model's `meta.json` instead. Still to come (per HANDOFF: 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL). The round-1 R17 (`files/r17/` per MODEL_CARD, situation-v1) does not match the v2 runtime and must not be published as the default. `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` both 404 today. +Historical (done 2026-10-08: `@genclass/runtime-model@0.1.0` = `r17-v2b` is published and the default URLs resolve). Blocked on training: no situation-v2 model was ready to publish. The first one, `r17-v2a`, has held-out results in origin/runtime 416e374 (`docs/runtime/RESULTS.md`, not merged here): its fixed 0.9/0.8 gates block nearly every action, and runtime batch 6 (5bc40c9, not merged) reads gate thresholds from the model's `meta.json` instead. Still to come (per HANDOFF: 150M teacher on v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL). The round-1 R17 (`files/r17/` per MODEL_CARD, situation-v1) does not match the v2 runtime and must not be published as the default. `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` were both 404 then. 1. Put a model directory (card `genclass-runtime-model/1`: `model.json`, `-q8.onnx`, `-fp16.onnx`, `tokenizer.json`, `calibration.json`, `meta.json`) under `packages/runtime-model/files/` (gitignored), so jsDelivr serves it at `DEFAULT_MODEL_BASE_URL`. Check it with `node packages/runtime/bin/genclass-runtime.mjs info packages/runtime-model/files`. 2. Add `packages/runtime-model/package.json` (`@genclass/runtime-model`, `0.1.0`, `files` including `files/`). It then becomes a workspace automatically (`packages/*`), so run a root `npm install` and commit the lockfile change, or CI's `npm ci` fails. diff --git a/docs/agents/runtime/decide-policy-actions.md b/docs/agents/runtime/decide-policy-actions.md index a9244fee..02838ba1 100644 --- a/docs/agents/runtime/decide-policy-actions.md +++ b/docs/agents/runtime/decide-policy-actions.md @@ -861,8 +861,9 @@ Doc-vs-code mismatches (code is authoritative): Open items (from `HANDOFF.md`, `OPEN_TASKS.md`, `packages/runtime/STATUS.md`, `docs/runtime/RESULTS.md`): -- No situation-v2 model exists yet; until `@genclass/runtime-model@0.1.0` ships, the published alphas - (`@genclass/runtime` 0.1.0-alpha.1 = `latest`, default observe; the older 0.1.0-alpha.0, default guard; neither has a model) take no actions, and R17-final1 (situation-v1) does +- Since 2026-10-08 ~13:40 UTC the first situation-v2 model is published (`@genclass/runtime-model@0.1.0` = `r17-v2b`), and `@genclass/runtime@0.1.0-beta.0` + (`latest`, default observe) loads it by default. Before that the published alphas (0.1.0-alpha.1, default observe; the older + 0.1.0-alpha.0, default guard, now deprecated; neither had a model) took no actions. R17-final1 (situation-v1) does not match this runtime. SIM is generating v2 data on Azure (`training/NEEDS.md`). - Hold-induced harm ([RESULTS.md](../../runtime/RESULTS.md) §5; rerun is OPEN_TASKS item 10) was measured with v0.1 on held store writes; v2 holds only deliveries, and the never-worse sweep over 66 real apps changed 0/396 clean runs ([../realapps.md](../realapps.md), diff --git a/docs/agents/runtime/learn-situation-triage.md b/docs/agents/runtime/learn-situation-triage.md index 32cc5747..070c48c0 100644 --- a/docs/agents/runtime/learn-situation-triage.md +++ b/docs/agents/runtime/learn-situation-triage.md @@ -35,7 +35,7 @@ changed. Producers of training rows run this exact code: the sim (`sim/src/run/rt.ts` -> `realRuntimeFactory`), the real-browser corpus ([realapps](../realapps.md)) and the hand-written Python port `training/curriculum/rt.py` (its docstring says - "FROZEN at git tag `situation-v2`"). No situation-v2 model exists yet ([HANDOFF.md](../../../HANDOFF.md), `training/NEEDS.md`); the old + "FROZEN at git tag `situation-v2`"). The first situation-v2 model, `@genclass/runtime-model@0.1.0` = `r17-v2b`, is published since 2026-10-08 (trained on `situation-v2` data; see `packages/runtime-model/MODEL_CARD.md`); the old `situation-v1` tag (1a77558) and its R17 checkpoint do not match this code. Any wording/threshold/budget change means a new tag and regenerated data. - **Decisions moved to the network boundary (batch 4).** New trigger `delivery`: a fetch/XHR response or a @@ -940,7 +940,7 @@ Resolved since 654d822 (removed from this list): the `InitOptions.situation` doc is new since 654d822) and disables `xhr`, `user`, `errors`, `nav`, `perf`; `eventsource` is left at its default (on), but nothing in `sim/src` references `EventSource`. XHR/EventSource deliveries and DOM-derived evidence (F7 click counts) therefore come only from realapps (inferred from options and a grep, not checked against data). -- **Open (OPEN_TASKS.md, [HANDOFF.md](../../../HANDOFF.md); release order in [RELEASE.md](../../../RELEASE.md))**: no situation-v2 model yet; the demo items "hold-induced harm" and "typeahead +- **Open (OPEN_TASKS.md, [HANDOFF.md](../../../HANDOFF.md); release order in [RELEASE.md](../../../RELEASE.md))**: the first situation-v2 model is published since 2026-10-08 (`@genclass/runtime-model@0.1.0` = `r17-v2b`); the demo items "hold-induced harm" and "typeahead salient about 6 times per trial" were measured with v0.1 store holds (situation-v1) and need re-measuring with a v2 model; STATUS.md reports 0/396 clean real-app runs changed with an always-passive model. diff --git a/docs/agents/runtime/model-host.md b/docs/agents/runtime/model-host.md index 6d5ec5b6..d388db09 100644 --- a/docs/agents/runtime/model-host.md +++ b/docs/agents/runtime/model-host.md @@ -21,10 +21,10 @@ - **Downloads** (`packages/runtime/src/model/loader.ts` -> `fetchFile`) go through Cache Storage `genclass-runtime-v1`. They are checked against the card's size and sha256 (WebCrypto, with a pure-TS fallback) and streamed with progress. The card itself is always revalidated from the network. A cached card is used only when the network fails. - **Engine** (`engine.ts`): `Packer` (`packer.ts`, `Tokenizer` from `tokenizer.ts`, text from `serialize.ts`) packs everything into int64 feeds. One ORT forward pass produces `choice_logits` / `score_logits` / `noul_logits`. Temperature or Platt calibration (`calibrate.ts`) then gives typed `Answer`s. - **Python parity is the contract.** `serialize.ts`, `pyutil.ts`, `tokenizer.ts`, `packer.ts` and `calibrate.ts` are ports of `jev_local` Python. The model was trained on the Python rendering, so any change here is a model-format change. The situation format (the text CORE builds in `packages/runtime/src/situation/*`, which this module then tokenizes) is frozen at tag `situation-v2` (6e5e86e); `situation-v1` is the old format. The model module itself is identical in v1 and v2. -- **No model exists for the current runtime, and none is published.** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. `packages/runtime-model/` holds only `MODEL_CARD.md`; `@genclass/runtime-model` is a 404 on npm (as of 2026-10-08). The only trained runtime model, R17-final1, was trained on `situation-v1` and lives only on the train VM / Mehar's Mac; it does **not** match the v2 runtime. The v2 model comes from the scaled program ([HANDOFF](../../../HANDOFF.md): 150M teacher -> distil R17/R32 -> DAgger -> EVAL -> `@genclass/runtime-model@0.1.0`). The card fetch therefore fails (HTTP 404), the host goes to `state: "error"`, and the runtime prints `[GenClass] Model unavailable (...); observing only.` From then on it observes only. See [When the default model URL 404s](#when-the-default-model-url-404s-the-alpha-today). +- **The default model is published (2026-10-08 ~13:40 UTC).** `DEFAULT_MODEL_BASE_URL` = `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, which resolves and serves files matching its `model.json`: `@genclass/runtime-model@0.1.0` = `r17-v2b` (`genclass-runtime-r17` 2.0.0-rc2, the first situation-v2 model; gates guard 0.80 {mutation 0.95}, heal 0.85 {failure 0.95, inconsistency 0.85}, report 0.85; card: `packages/runtime-model/MODEL_CARD.md`). `@genclass/runtime@0.1.0-beta.0` (`latest`) loads it by default; a Chromium check with the jsDelivr script tag loaded it in a Web Worker on WebGPU (fp16) in 4.75 s, and `decide()` answered in 72 ms. The round-1 model R17-final1 was trained on `situation-v1` and does **not** match the v2 runtime. Before 2026-10-08 (the alphas) the card fetch failed (HTTP 404), the host went to `state: "error"`, and the runtime printed `[GenClass] Model unavailable (...); observing only.`; the same happens today whenever the model cannot be fetched. See [When the default model URL fails](#when-the-default-model-url-fails-a-404-until-2026-10-08). - **Status:** `off` -> `loading` (phases `card` / `download` / `runtime` / `session` / `warmup`) -> `ready` or `error`; `dispose()` -> `off`. See [Status lifecycle](#status-lifecycle-modelhoststatusstate). The runtime core reads only `state`, `device`, `threads`, `warmupMs`, `model`, `variant`, `loadMs` and `error` (the devtools overlay also shows `progress`); `status.latency` (p50/p90 of the last 20 evaluations) and `host.stats` are for tooling. - **Default mode `observe` (since f3636b2) still loads and consults the model.** `observe` permits no non-passive action, so nothing is ever held: every salient trigger, `delivery` included (since 054da38), is decided in the background (priority capped at 1, deadline 5 s), for detection and reports. A salient delivery is released to the app at once (`runDelivery` -> `deliveryHoldable` is false in `observe`), before any body read, and its background decision is no longer dropped as stale. Only `mode: "guard"`/`"heal"` can make the runtime wait for the host. -- **CLI** `genclass-runtime fetch-model ` / `info ` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is the same jsDelivr directory as `DEFAULT_MODEL_BASE_URL`, a 404 too until the model package is published, so pass `--from` until then. The file is committed executable (mode 100755, b435acb). The same binary now also has `init` / `remove` (project setup; `bin/lib/*`, owner INSTALL, not covered here) and runs as `npx @genclass/runtime `. A short-alias package `genclass-runtime` (`packages/genclass-runtime/cli.mjs`, which only imports this file; not on npm yet) is meant to make `npx genclass-runtime ` work without a local install. +- **CLI** `genclass-runtime fetch-model ` / `info ` downloads and verifies a self-hostable model directory, with no dependencies. Its own default source (`DEFAULT_FROM`) is the same jsDelivr directory as `DEFAULT_MODEL_BASE_URL`, which resolves since 2026-10-08 (a 404 before), so `--from` is optional. The file is committed executable (mode 100755, b435acb). The same binary now also has `init` / `remove` (project setup; `bin/lib/*`, owner INSTALL, not covered here) and runs as `npx @genclass/runtime `. A short-alias package `genclass-runtime` (`packages/genclass-runtime/cli.mjs`, which only imports this file; not on npm yet) is meant to make `npx genclass-runtime ` work without a local install. ## Files @@ -54,7 +54,7 @@ | `packages/runtime/tsup.config.ts` | Four builds. (1) The ESM library: entry `worker: "src/model/worker.ts"` -> `dist/worker.js` (not in `dts.entry`, so no `.d.ts`); `external: ["onnxruntime-web", "onnxruntime-web/webgpu", "react", "redux", "zustand"]`; `target: "es2022"`, `platform: "browser"`, `splitting: true` (the build output's `worker.js` imports `ModelBackend` from a chunk shared with `index.js`), sourcemaps; `clean` spares `cdn/**` and `genclass.global*`. (2, 3) `globalBuild(false \| true)`: iife, `es2020`, plugin `genclass-ort-external` keeps every `onnxruntime-web(/...)` import external (the host's default inline loader stays as a bare `import("onnxruntime-web/...")` that the script tag never calls), defines `__GENCLASS_VERSION__` from `package.json`. (4) The CDN worker build: entries `worker` (`src/cdn/worker.ts`), `ort-webgpu`, `ort-wasm` -> `dist/cdn/`, ESM, minified, `splitting: true`, `noExternal: [/^onnxruntime-web/]`, plugin `genclass-cdn-ort` maps the model worker's `import("onnxruntime-web/webgpu" \| "/wasm")` (any importer outside `src/cdn/`) to `src/cdn/ort-*.ts`, so the built `dist/cdn/worker.js` does `import('./ort-webgpu.js')` / `import('./ort-wasm.js')` | default export (the four configs); module-local `cdnOrt`, `ortExternal`, `globalBuild` | | `packages/runtime/package.json` | `exports["./worker"]` -> `./dist/worker.js`; `unpkg` / `jsdelivr` -> `./dist/genclass.global.min.js` (what a bare `cdn.jsdelivr.net/npm/@genclass/runtime` URL serves); `sideEffects` lists `./dist/cdn/*.js`, the global builds, the `/auto` files and `./src/model/worker.ts`; `bin.genclass-runtime` -> `./bin/genclass-runtime.mjs`; dependency `onnxruntime-web ^1.30.0` (1.30.0 in the lockfile, which is what the CDN build bundles) | — | | `packages/runtime/bin/genclass-runtime.mjs` | CLI (Node >= 20, no deps): `fetch-model`, `info`; `init` / `remove` are dispatched to `bin/lib/init.mjs` -> `run` (INSTALL) before argument parsing | `main`, `fetchModel`, `info`, `parseCard` (JS copy), `scanOnnx` | -| `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. Its status line (fcd1e68) reports final round 1 on `situation-v1` and says the next rounds retrain on v2. **The npm package itself does not exist yet** (no `package.json`, no `files/` in git, although the card says "`files/r17/` here") | — | +| `packages/runtime-model/MODEL_CARD.md` | Model card of the runtime model (R17/R32), training data, limits. Its status line (fcd1e68) reports final round 1 on `situation-v1` and says the next rounds retrain on v2. (At fcd1e68 the npm package did not exist yet. Since ba11126/bcbee89 the directory has `package.json` and `LICENSE` and the card describes `r17-v2b`; `@genclass/runtime-model@0.1.0` is published since 2026-10-08. `files/` stays gitignored.) | — | ## Concepts and data structures @@ -245,7 +245,7 @@ Public re-exports (`packages/runtime/src/index.ts`): all 12 classes, plus the ty The model code is the same; only how the worker script and onnxruntime-web get onto the page differs. Owner of `src/cdn/*`: INSTALL. 1. **Where files come from.** `install()` in `global.ts` computes `base`, the package's `dist/` URL: `data-base` on the tag (resolved against the page, trailing `/` added), else `assetBase(script.src)`. On jsDelivr (`cdn`, `fastly`, `gcore`, `testingcf`) and unpkg URLs of `@genclass/runtime`, `assetBase` pins the version to `__GENCLASS_VERSION__` (the `package.json` version at build time), so an unversioned or `@latest` tag never mixes files of two releases. Anywhere else it is the script's own directory. Without a script URL it falls back to `https://cdn.jsdelivr.net/npm/@genclass/runtime@/dist/`. `GenClass.base` exposes it. -2. **Host options.** `withCdnModel` (skipped when the options have a `decider` or `model === false`) sets `model = { workerFactory, ortLoader, ...user }`. `model.baseUrl`, `ortWasmPaths`, `device`, `preload` and `worker` come from the merged page configuration (``, the tag's `data-*`, `window.GENCLASS_CONFIG`, then the `GenClass.init(options)` argument; `src/cdn/config.ts` -> `fromPairs`: `data-model` / `data-ort` / `data-device` / `data-preload` / `data-worker`). With no `model`/`baseUrl` the host uses `DEFAULT_MODEL_BASE_URL`, so today the script tag observes only, exactly like the npm path (see the 404 flow below). +2. **Host options.** `withCdnModel` (skipped when the options have a `decider` or `model === false`) sets `model = { workerFactory, ortLoader, ...user }`. `model.baseUrl`, `ortWasmPaths`, `device`, `preload` and `worker` come from the merged page configuration (``, the tag's `data-*`, `window.GENCLASS_CONFIG`, then the `GenClass.init(options)` argument; `src/cdn/config.ts` -> `fromPairs`: `data-model` / `data-ort` / `data-device` / `data-preload` / `data-worker`). With no `model`/`baseUrl` the host uses `DEFAULT_MODEL_BASE_URL`, exactly like the npm path; since 2026-10-08 that loads the published model (before, the script tag observed only; see the failure flow below). 3. **Worker.** `workerFactory: () => blobModuleWorker(base + "cdn/worker.js")`. Browsers refuse `new Worker()`, so `blobModuleWorker` creates a same-origin Blob URL whose only line is `import "cdn/worker.js";` and starts `new Worker(blobUrl, { type: "module", name: "genclass-model" })`. It returns `null` when `Worker`, `Blob` or `URL.createObjectURL` is missing (host goes inline); if the constructor throws it revokes the URL and rethrows (the host counts that as `null` too). The Blob URL is revoked on the worker's first `message` (its `hello`) or `error`. A module worker may import cross-origin modules over CORS, and jsDelivr/unpkg send `Access-Control-Allow-Origin: *`; a self-hosted `dist/` on another origin must send CORS headers too. If the import fails (404, CORS, CSP), the worker fires `error` before `hello`, and the host falls back inline as in step 5 of section 2. The 15 s hello timeout covers fetching `cdn/worker.js` (40 KB raw, 16 KB gzip per `test/install/RESULTS.md`) and its shared chunk (`ort-env.ts`, under 1 KB in a local build); ORT still comes later. 4. **`dist/cdn/worker.js`** (`src/cdn/worker.ts`) is `src/model/worker.ts` unchanged (same `hello`, same em-pthread guard, same protocol) plus a second `message` listener that copies `load.options.ortWasmPaths` into `cdnState` (`ort-env.ts`). The model worker's `loadOrt` dynamic imports are rewritten at build time by the `genclass-cdn-ort` plugin, so in the built file they are `import('./ort-webgpu.js')` / `import('./ort-wasm.js')`, resolved next to `worker.js` on the CDN. No bare `onnxruntime-web` specifier is left, so no import map or bundler is needed. Only the bundle the plans need is fetched (`status.ortBuild`), as on npm. 5. **`dist/cdn/ort-webgpu.js` / `ort-wasm.js`** (`src/cdn/ort-webgpu.ts` / `ort-wasm.ts`) bundle `onnxruntime-web/webgpu` / `/wasm` (`noExternal`; minified 118 KB / 73 KB raw per RESULTS.md), call `prepareOrt(ort.env, glue)` once at module evaluation, and re-export the module. `prepareOrt` does something only when the realm is `crossOriginIsolated`, has no `document` (a worker) and `env.wasm.wasmPaths` is unset. Then it sets `env.wasm.wasmPaths = { mjs: / }` with `` = `cdnState.ortWasmPaths` or `https://cdn.jsdelivr.net/npm/onnxruntime-web@/dist/`, and `` = `ort-wasm-simd-threaded.asyncify.mjs` (webgpu bundle) or `ort-wasm-simd-threaded.mjs` (wasm bundle). Reason: with WASM threads, ORT refuses its embedded glue in a cross-origin script and would look for the `.mjs` next to itself, which this package does not ship; given an explicit URL it preloads the glue as a same-origin Blob and can start its pthread workers. Single-threaded (no COOP/COEP), nothing changes: ORT uses its embedded glue because the backend hands it the wasm bytes. @@ -421,9 +421,9 @@ Lookup order: `host.dispose()` cancels the idle scheduling and the hello and stall timers, and rejects the running job, queued jobs, `measure`s and `ready()` waiters with `ModelDisposedError`. It then closes the transport (worker: posts `dispose` then `terminate()`; inline: `backend.dispose()`), sets status `{state:"off"}`, notifies listeners once, and clears them. Every later call rejects with `ModelDisposedError`. -### When the default model URL 404s (the alpha today) +### When the default model URL fails (a 404 until 2026-10-08) -No runtime model is published, and none exists yet for `situation-v2`. The npm package `@genclass/runtime-model` has no `package.json` in `packages/runtime-model/` and is a 404 on the registry (checked by the lead, 2026-10-08); OPEN_TASKS "Next": Model package `@genclass/runtime-model@0.1.0` is still open, behind the v2 data, teacher, distillation and EVAL steps in HANDOFF. The published `@genclass/runtime@0.1.0-alpha.0` defaults to `guard`; `0.1.0-alpha.1` (`latest`) and this branch default to `observe`, which changes nothing below because nothing can act without a model. The script-tag build (not on npm yet) behaves the same, with `cdn/worker.js` from the asset base as the worker. The release procedure is in [RELEASE.md](../../../RELEASE.md). Traced through the code, a default `GenClass.init()` in a browser does the following. +**Historical for the default URL:** until 2026-10-08 ~13:40 UTC no runtime model was published and `@genclass/runtime-model` was a 404 on the registry (checked by the lead, 2026-10-08), so every alpha install (`0.1.0-alpha.0`, default `guard`, now deprecated; `0.1.0-alpha.1`, default `observe`) went through this flow. Since then `@genclass/runtime-model@0.1.0` is published, the default URL resolves, and `@genclass/runtime@0.1.0-beta.0` (`latest`) loads the model. The flow below still applies whenever the card cannot be fetched (a self-hosted `baseUrl` that 404s, offline, CSP, CORS). The script-tag build behaves the same, with `cdn/worker.js` from the asset base as the worker. The release procedure is in [RELEASE.md](../../../RELEASE.md). Traced through the code, a `GenClass.init()` in a browser whose model card returns 404 does the following. 1. The host is created with `preload: "idle"`, so the status is `off`. Until the idle start, triggers compute facts. A salient one calls `void this.ready`, which starts the load early, and runs the passive action. 2. The worker starts and posts `hello`. `doLoad` sets phase `card`, starts the WebGPU probe, and fetches `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json` (`cache:"no-cache"`). The probe is not cancelled when the card fails: on a WebGPU-capable browser it still requests an adapter and creates and destroys a device; its result is discarded. @@ -433,7 +433,7 @@ No runtime model is published, and none exists yet for `situation-v2`. The npm p 6. Runtime: the console shows `[GenClass] Model unavailable (model card download failed: HTTP 404 for https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/model.json); observing only.` (via `console.info`, only with `report: "console"`), and a `"status"` event fires. The devtools overlay shows "Model unavailable" with `observing only · ` (`packages/runtime/src/devtools/index.ts` -> `renderStatus`). 7. From then on `consultable()` is false. Every trigger and every delivery takes the passive action immediately; no situations, decisions or detections are produced, and nothing is held. Observers, tracing and baselines keep running. 8. `rt.ask()` / `rt.decide()` reject with `GenClassUnavailableError("error", "the model failed to load: ...")`. Exception: with `opts.timeoutMs` set, `ask` awaits `Promise.race([wait, to])` without wrapping, so the raw `ModelLoadError` propagates instead. The runtime caches its `ready` promise and has no public reload. Only a direct `createModelHost` user can call `host.load()` to retry. The next page load tries the card again. -9. To get decisions today, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). The CLI's default `--from` (the same jsDelivr directory) is a 404 too, so pass `--from` explicitly. Only the v0.1 development model (`https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`, whether it serves a CLI-readable `model.json` is unverified) and the situation-v1 R17-final1 export (train VM only) exist; neither is trained on `situation-v2`, so their decisions are not meaningful for this runtime. Use them to exercise the loading machinery, not to evaluate behaviour. +9. To get decisions without the CDN, self-host a model directory and pass `model: { baseUrl }` (see [CLI](#cli-packagesruntimebingenclass-runtimemjs)). Since 2026-10-08 the CLI's default `--from` (the same jsDelivr directory) serves the published `r17-v2b`; before that it was a 404 and only the v0.1 development model (`https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`) and the situation-v1 R17-final1 export (train VM only) existed, neither trained on `situation-v2` (use them to exercise the loading machinery, not to evaluate behaviour). ### CLI (`packages/runtime/bin/genclass-runtime.mjs`) @@ -530,7 +530,7 @@ Only `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths` and `cacheName` ar - **`hello` is posted before ORT is imported** (ORT is a dynamic import on `load`). The 15 s hello timeout therefore only covers fetching and evaluating the worker chunk (for the script tag: the cross-origin `cdn/worker.js` and its chunk, imported from the Blob URL). - **CDN worker ordering:** `src/cdn/worker.ts` registers its `message` listener after `src/model/worker.ts`'s; both run synchronously on the `load` message, and ORT is imported only after the card and the GPU probe, so `cdnState.ortWasmPaths` is set before `prepareOrt` runs. Importing ORT earlier (at module top, or before the first `await` in `doLoad`) would make `prepareOrt` miss a page's `data-ort`, and `prepareOrt` runs once per realm (at module evaluation), so a later `ortWasmPaths` is never picked up for the glue. - **CDN self-hosting (`data-base`, `data-ort`):** the `dist/` directory must serve `genclass.global*.js`, `cdn/worker.js`, `cdn/ort-*.js`, the `cdn/chunk-*.js` they import (and `devtools/index.js` for the overlay), with CORS headers when on another origin than the page. A `data-ort` directory must hold both `.wasm` files and, for `crossOriginIsolated` pages, both threaded `.mjs` glue files (`ort-wasm-simd-threaded.mjs`, `ort-wasm-simd-threaded.asyncify.mjs`). The CDN `worker.js` is not a drop-in for `dist/worker.js` (and vice versa): one bundles ORT, the other imports bare `onnxruntime-web` specifiers. -- **The asset version must exist on the CDN.** `assetBase` pins jsDelivr/unpkg URLs, and the no-script-URL fallback, to `__GENCLASS_VERSION__` (the `package.json` version at build time). This branch's `package.json` still says `0.1.0-alpha.1`, which is on npm from 806a296 without `dist/cdn/` or the global builds. So a local build whose base resolves to jsDelivr (the fallback, e.g. when `findScript` finds no tag) loads `.../@genclass/runtime@0.1.0-alpha.1/dist/cdn/worker.js`, which 404s: the worker errors before `hello`, the inline `ortLoader` 404s too, and the load ends in `error` (observe only). Bump the version before testing against or publishing to the CDN; npm refuses a republish of `0.1.0-alpha.1` anyway. +- **The asset version must exist on the CDN.** `assetBase` pins jsDelivr/unpkg URLs, and the no-script-URL fallback, to `__GENCLASS_VERSION__` (the `package.json` version at build time). Until 9695830 this branch's `package.json` said `0.1.0-alpha.1`, which is on npm from 806a296 without `dist/cdn/` or the global builds, so a local build whose base resolved to jsDelivr (the fallback, e.g. when `findScript` finds no tag) loaded `.../@genclass/runtime@0.1.0-alpha.1/dist/cdn/worker.js`, which 404s: the worker errors before `hello`, the inline `ortLoader` 404s too, and the load ends in `error` (observe only). It now says `0.1.0-beta.0`, which is on npm with `dist/cdn/`. Bump the version before testing unpublished CDN changes; npm refuses a republish of a version anyway. - **Stall vs session timeout:** `LOAD_STALL_MS` (180 s) equals the WASM session timeout (180 s), and no status is posted during session creation. On a very slow WASM session the host's stall watchdog and the backend's step timeout fire at about the same time. - **The WASM retry happens once per host lifetime** (`wasmRetried` is never reset). - **A worker crash after `ready` is usually permanent for the runtime.** A worker `error`/`messageerror` event after `hello` moves `ready` -> `error` (`onWorkerCrash`), rejects the running job with `ModelLoadError` and queued jobs with `ModelNotReadyError`. The runtime never calls `host.load()`, and triggers stop consulting in `error`. The one exception: `RuntimeImpl`'s `ready` getter calls `decider.ready()` only on its first read and caches the promise. If nothing had read `rt.ready` before the crash (no salient trigger while `off`, no `rt.ask()` while not ready, no app read), the first `rt.ask()`/`rt.decide()` or app read of `rt.ready` afterwards calls `host.ready()`, which starts a fresh worker because `started` was reset. Otherwise the runtime observes only until the page reloads. @@ -654,12 +654,12 @@ No test covers the default-URL 404 end-to-end, the CLI's `fetch-model` / `info`, Mismatches between docs and code (code wins): -- **The default model is not published, and no model matches the runtime.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`, but `packages/runtime-model/` has no `package.json` or `files/`, the npm package is a 404, and OPEN_TASKS "Next" (Model package `@genclass/runtime-model@0.1.0`) lists publishing as future work; see [RELEASE.md](../../../RELEASE.md). Result: observe-only (see the 404 flow above). The only trained export (R17-final1) is `situation-v1`; publishing it as-is would ship a model out of distribution for the v2 runtime. +- **Resolved 2026-10-08: the default model is published.** CONTRACT §2 says `baseUrl` defaults to "CDN of `@genclass/runtime-model@`". The code pins `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`; until 2026-10-08 that npm package was a 404 (result: observe-only, see the failure flow above). Since then `@genclass/runtime-model@0.1.0` (`r17-v2b`, situation-v2) is published and the URL resolves; see [RELEASE.md](../../../RELEASE.md). The round-1 export R17-final1 is `situation-v1` and was never published as the runtime model. - **Two different default model sources:** - host and CLI: jsDelivr npm (`DEFAULT_MODEL_BASE_URL`, and `DEFAULT_FROM` since 2026-10-08; before that the CLI defaulted to the GitHub release `runtime-model-v0.1.0`, which the published `0.1.0-alpha.1` CLI still does); - CONTRACT §10 and `src/model/README.md`: the dev v0.1 model at `https://github.com/MeharPro/GenClass/releases/download/v0.1.0/`. - `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. That default is the jsDelivr directory, a 404 until `@genclass/runtime-model@0.1.0` is published; the `runtime-model-v0.1.0` release URL (alpha.1's default) is a 404 too and optional (RELEASE.md B5). + `packages/runtime/README.md` and API.md say "self-host a model with `npx genclass-runtime fetch-model`" with no `--from`. That default is the jsDelivr directory, which resolves since `@genclass/runtime-model@0.1.0` was published (2026-10-08); the `runtime-model-v0.1.0` release URL (alpha.1's default) is a 404 too and optional (RELEASE.md B5). - CONTRACT §10 says "the worker imports `onnxruntime-web/webgpu`". The code imports `onnxruntime-web/wasm` when no WebGPU plan exists, and `/webgpu` otherwise (worker and inline). The same staleness is in `src/model/README.md` "Bundling" ("`dist/worker.js` imports `onnxruntime-web/webgpu`"; "the inline fallback's `import("onnxruntime-web/webgpu")`"). - CONTRACT §2 and `docs/runtime/API.md` list only `baseUrl`, `device`, `worker` and `preload` for `model`. `ModelOptions` in `types.ts` also has `ortWasmPaths` and `cacheName`. Host-only options (`timeoutMs`, `maxQueue`, `maxThreads`, `helloTimeoutMs`, `loadStallMs`, `warmup`) are untyped through `init`. - CONTRACT §8 `DecisionProvider.evaluate(req)` lists `{trigger, state, questions}`. `EvaluateRequest` also has `priority`, `subject` (§13) and `timeoutMs`, which the host honours. @@ -674,7 +674,7 @@ Mismatches between docs and code (code wins): - Its diagnosis list omits `transient`, and its action list omits the v2 `delivery` trigger (`deliver` / `discard` / `defer`). - Its latency paragraph maps token counts to state budgets of 1,000 / 2,000 / 3,200 chars; the v2 full budget is 2,400 (`STATE_CHAR_BUDGET`). Its figures (R17 ≈ 190 / 340 / 610 ms, R32 ≈ 500 / 880 / 1,540 ms, "fitted over 184 requests") also differ from `docs/runtime/RESULTS.md` §2 (R17 177 / 323 / 589, R32 569 / 954 / 1,580). - It describes `calibration.json` as "per-kind temperatures", while the runtime also supports `by_header`, `by_bucket`, `tau_k` and `noul_platt`. -- HANDOFF.md "What this is" still says "observe -> guard (default; ...)". Since f3636b2 on this branch the default is `observe` (CONTRACT §13, `runtime.ts`). The older published npm alpha.0 defaults to `guard`; alpha.1 (`latest`) defaults to `observe`. +- HANDOFF.md "What this is" still says "observe -> guard (default; ...)". Since f3636b2 on this branch the default is `observe` (CONTRACT §13, `runtime.ts`). The older published npm alpha.0 (deprecated) defaults to `guard`; alpha.1 and `0.1.0-beta.0` (`latest` since 2026-10-08) default to `observe`. - CONTRACT §10 refers to `/Users/meharkhanna/jev/extension/genclass/src/` (another machine). In this repo the v0.1 card is `extension/src/model/model.json`. - CONTRACT §2 comments `device` as "default auto (webgpu+fp16 if shader-f16, else wasm+q8)". `planOrder` also tries `webgpu+q8` between them, and `"auto"` skips software (fallback) adapters. - CONTRACT §2 says `preload: "lazy"` downloads "only when the first salient situation appears", and §10 says "on the first `evaluate`/`ready`". The host starts on the first `ready()`/`load()`/`evaluate()`/`measure()`; through the runtime that is the first salient trigger, `rt.ask`/`rt.decide`, or any read of `rt.ready`. diff --git a/docs/agents/runtime/observe-and-trace.md b/docs/agents/runtime/observe-and-trace.md index eced5840..bd915a29 100644 --- a/docs/agents/runtime/observe-and-trace.md +++ b/docs/agents/runtime/observe-and-trace.md @@ -885,7 +885,7 @@ Open issues (from code reading; none has a test unless stated): From STATUS.md / HANDOFF.md / OPEN_TASKS.md / training/NEEDS.md (relevant here): - The `situation-v2` freeze (tag 6e5e86e): HANDOFF.md says any change to `packages/runtime/src/situation/*` changes the training format. Op names, details and event names, element descriptions and the `ws`/`sse` event names reach situation text, so they fall under the same rule. As of 2026-10-08 SIM is generating situation-v2 data on 20 Azure nodes and REAL on 3 (training/NEEDS.md), so a wording change now invalidates data being produced. -- No situation-v2 model exists yet (HANDOFF: teacher on v2 gold → distillation → DAgger → EVAL → `@genclass/runtime-model@0.1.0`). Until then the delivery gate and every other gate run passive in practice (the provider is not ready, so `trigger` runs passive). While the default model host is in state `off` (before its idle preload starts, or with `preload: "lazy"`) `consultable()` accepts it, but `deliveryHoldable` requires `ready`, so a conflicting delivery is released synchronously and only analysed in the background (its `trigger` then starts the lazy load and runs passive: no decision is recorded); once the load fails (state `error`) everything releases synchronously with no analysis. +- Until 2026-10-08 no situation-v2 model was published, so the delivery gate and every other gate ran passive in practice (the provider was not ready, so `trigger` ran passive). Since then `@genclass/runtime-model@0.1.0` = `r17-v2b` is published and loads by default; the following still applies whenever the model is not `ready`. While the default model host is in state `off` (before its idle preload starts, or with `preload: "lazy"`) `consultable()` accepts it, but `deliveryHoldable` requires `ready`, so a conflicting delivery is released synchronously and only analysed in the background (its `trigger` then starts the lazy load and runs passive: no decision is recorded); once the load fails (state `error`) everything releases synchronously with no analysis. - OPEN_TASKS.md: batch 4 (the delivery gate, EventSource, `untrustedEvents`) was the redesign answering "hold-induced harm" from the v0.1 demo eval (search clean-run latency 14 ms → 125 ms because salient *writes* were held; typeahead salient about 6 times per trial). Item 10 (demo rerun) lists triage sensitivity for re-investigation once a v2 model exists; the delivery tests claim zero model calls for clean typeahead. - Known risk: on slow devices, hold budgets expire more often (more fail-open decisions); batch 4's "hold only when it can help" rule (`expectedLatency() <= holdBudgetMs()`) reduces holds that would only expire. diff --git a/docs/agents/runtime/public-api-and-lifecycle.md b/docs/agents/runtime/public-api-and-lifecycle.md index 94d2418b..18853a46 100644 --- a/docs/agents/runtime/public-api-and-lifecycle.md +++ b/docs/agents/runtime/public-api-and-lifecycle.md @@ -8,8 +8,8 @@ - Two entry points: `GenClass.init(options)` (browser facade: singleton, never throws, kill switch, loads the local model by default) and `createRuntime(options)` (headless: tests, sim, SSR; no model unless `decider` or `model: {...}` is passed). Both return a `RuntimeImpl` typed as `Runtime`. `createRuntime` can throw on malformed options; `GenClass.init` never throws (it falls back to an inert runtime). - `GenClass.init` is idempotent: a second call returns the first runtime and **ignores its new options**. Only `GenClass.destroy()` clears the singleton; `rt.destroy()` alone does not. -- Zero-code entries (merged from origin/runtime f3a9dd1; **not** in the published `0.1.0-alpha.1`, they ship in the next version): `import "@genclass/runtime/auto"` (and `/auto/observe`, `/auto/guard`, `/auto/heal`), the script tag `dist/genclass.global(.min).js` (exposes `window.GenClass`), and the CLI `npx @genclass/runtime init|remove`. All of them end in `GenClass.init`, so the singleton, the kill switch and the defaults below apply unchanged. See [Zero-code entries](#zero-code-entries-auto-script-tag-cli). -- Three modes: `observe` (**default** on `mvp-v2` since f3636b2: `o.mode ?? "observe"` in `RuntimeImpl`'s constructor; never changes execution, nothing held or delayed (since 054da38 also no response/message delivery), decisions still made in the background and reported), `guard` (opt-in; guard-tier actions only), `heal` (experimental; guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. The npm `0.1.0-alpha.0` and origin/runtime (through eff18cb, and still at 5bc40c9) default to `guard`; npm `0.1.0-alpha.1` defaults to `observe`. The `init` CLI still assumes `guard` is the default (see Drift). +- Zero-code entries (merged from origin/runtime f3a9dd1; **not** in the published `0.1.0-alpha.1`; they ship in `0.1.0-beta.0`, `latest` since 2026-10-08): `import "@genclass/runtime/auto"` (and `/auto/observe`, `/auto/guard`, `/auto/heal`), the script tag `dist/genclass.global(.min).js` (exposes `window.GenClass`), and the CLI `npx @genclass/runtime init|remove`. All of them end in `GenClass.init`, so the singleton, the kill switch and the defaults below apply unchanged. See [Zero-code entries](#zero-code-entries-auto-script-tag-cli). +- Three modes: `observe` (**default** on `mvp-v2` since f3636b2: `o.mode ?? "observe"` in `RuntimeImpl`'s constructor; never changes execution, nothing held or delayed (since 054da38 also no response/message delivery), decisions still made in the background and reported), `guard` (opt-in; guard-tier actions only), `heal` (experimental; guard + heal tier). A **tier** is the mode an action needs; the **policy gate** compares the mode with the action's tier. The npm `0.1.0-alpha.0` and origin/runtime (through eff18cb, and still at 5bc40c9) default to `guard`; npm `0.1.0-alpha.1` and `0.1.0-beta.0` (`latest`) default to `observe`. The `init` CLI still assumes `guard` is the default (see Drift). - The unit-test harness (`test/helpers.ts` -> `setup`) passes `mode: "guard"` explicitly, because most CORE tests exercise interventions; pass `setup({ mode: undefined })` to get the product default. - Situation-v2 (batch 4/5): decisions about responses and push messages are taken at the **network boundary** (the `delivery` trigger, `RuntimeImpl.runDelivery`). Store writes are **never held by default**: a salient write not covered by a delivery decision is triaged when proposed and decided in the background (`observeWrite`); `policy.holdWrites: true` restores the old hold-the-write path (opt-in, never reorders a store's writes). A delivery that cannot be held (observe mode, paused, model not ready, no permitted delivery action, or the model too slow) is released synchronously, before any body read, and (in observe, or whenever `discard` is not permitted) decided in the background on the state it was delivered into; in guard/heal its chain's writes get their own `mutation` decisions instead, and the delivery is asked only when a standing question or `triage: "always"` forces it (054da38; `RuntimeImpl.deliveryHoldable`, `writesCanAct`). - Kill switch: `?genclass=off` (URL wins) or `localStorage.genclass = "off"` gives an inert runtime; the values `observe|guard|heal` override `options.mode`. @@ -66,7 +66,7 @@ Terms introduced in this doc: ### Package exports (`packages/runtime/package.json`) -ESM only (`"type": "module"`, only `import` conditions; the script-tag build is an IIFE file, not an export condition), `engines.node >= 20`, license Apache-2.0. `sideEffects` is no longer `false` (f3a9dd1): it lists `./dist/auto.js`, `./dist/auto/*.js`, `./dist/genclass.global.js`, `./dist/genclass.global.min.js`, `./dist/cdn/*.js` and `./src/model/worker.ts`, so bundlers keep the bare `import "@genclass/runtime/auto"`; the root and adapter modules are still tree-shakeable. New top-level `unpkg` and `jsdelivr` fields = `./dist/genclass.global.min.js` (what `https://cdn.jsdelivr.net/npm/@genclass/runtime` serves). Version: `0.1.0-alpha.1` in `package.json` on this branch, but that number is **taken on npm** by our release 806a296 (published as `latest` on 2026-10-08: situation-v2, the NaN fix, the observe default, docs), which does **not** contain the `/auto` entries, the script tag or `init`/`remove`; those ship in the next version (`0.1.0-alpha.2`, or a beta with the model), which needs a version bump first ([RELEASE.md](../../../RELEASE.md)). The published alpha.0 predates situation-v2, the NaN fix and the observe default. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). +ESM only (`"type": "module"`, only `import` conditions; the script-tag build is an IIFE file, not an export condition), `engines.node >= 20`, license Apache-2.0. `sideEffects` is no longer `false` (f3a9dd1): it lists `./dist/auto.js`, `./dist/auto/*.js`, `./dist/genclass.global.js`, `./dist/genclass.global.min.js`, `./dist/cdn/*.js` and `./src/model/worker.ts`, so bundlers keep the bare `import "@genclass/runtime/auto"`; the root and adapter modules are still tree-shakeable. New top-level `unpkg` and `jsdelivr` fields = `./dist/genclass.global.min.js` (what `https://cdn.jsdelivr.net/npm/@genclass/runtime` serves). Version: `0.1.0-beta.0` in `package.json` since 9695830, published as `latest` on 2026-10-08 ~13:40 UTC with the `/auto` entries, the script tag, `init`/`remove` and the default model `@genclass/runtime-model@0.1.0` ([RELEASE.md](../../../RELEASE.md)). Before it, `0.1.0-alpha.1` (806a296: situation-v2, the NaN fix, the observe default, docs) was `latest` and did **not** contain the zero-code entries. The published alpha.0 predates situation-v2, the NaN fix and the observe default. `bin/genclass-runtime.mjs` is committed as mode 100755 (b435acb). CI: `.github/workflows/ci.yml` (b435acb) runs typecheck, build and the unit tests on Node 22; see [build-test-release.md](build-test-release.md). | subpath | types | import | source entry (tsup) | documented in | |---|---|---|---|---| @@ -88,7 +88,7 @@ ESM only (`"type": "module"`, only `import` conditions; the script-tag build is - `devDependencies`: `@playwright/test 1.63.0`, `@types/react ^19.0.0`, `@types/react-dom ^19.0.0`, `esbuild ^0.27.0`, `happy-dom ^20.14.5`, `onnxruntime-node 1.30.0`, `react ^19.3.0`, `react-dom ^19.3.0`, `redux ^5.0.1`, `tsup ^8.5.1`, `typescript ~5.9.3`, `vitest ^5.0.3`, `zustand ^5.0.15`. - `files`: `dist`, `bin`, `README.md`, `LICENSE`. Scripts: `build` (tsup), `typecheck` (`tsc -p tsconfig.json --noEmit`), `test` (`vitest run`), `test:browser` (`playwright test --config test/browser/playwright.config.ts`). - `tsup.config.ts` (four configs): (1) the ESM build, `target: "es2022"`, `platform: "browser"`, `splitting: true`, `sourcemap: true`, `treeshake: true`, entries `index`, `auto`, `auto/{observe,guard,heal}`, the adapters, `devtools/index`, `worker`; `external`: `onnxruntime-web`, `onnxruntime-web/webgpu`, `react`, `redux`, `zustand`; `worker` has no `.d.ts` (not in `dts.entry`); its `clean` spares `cdn/**` and `genclass.global*`. (2, 3) `globalBuild(false|true)`: IIFE of `src/cdn/global.ts`, `target: "es2020"`, `define: { __GENCLASS_VERSION__ }` from `package.json`, onnxruntime-web forced external (plugin `ortExternal`), map only for `.min.js`. (4) `dist/cdn/`: `src/cdn/worker.ts`, `ort-webgpu.ts`, `ort-wasm.ts`, minified, onnxruntime-web bundled in (`noExternal`), the worker's `import("onnxruntime-web/webgpu"|"/wasm")` mapped to `src/cdn/ort-*.ts` (plugin `cdnOrt`). The config deletes old `dist/genclass.global*` files before building. -- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the freeze this branch follows), `v0.1.0-alpha.0` (= 654d822, the first published alpha; same `src` as `situation-v1`) and `v0.1.0-alpha.1` (= 806a296, the current npm `latest`; local only, not pushed). origin also has `situation-v2.1` (= 5bc40c9 on origin/runtime, "situation-v2 + no-baseline stall fact (additive)"), which is not an ancestor of this branch. Nothing that 806a296 lacks (the zero-code entries f3a9dd1, 29b7f28, 054da38, f107013) is published. +- Git tags: `situation-v1` (= 1a77558, first situation-format freeze, superseded), `situation-v2` (= 6e5e86e, the freeze this branch follows), `v0.1.0-alpha.0` (= 654d822, the first published alpha; same `src` as `situation-v1`) and `v0.1.0-alpha.1` (= 806a296, npm `latest` until 2026-10-08 ~13:40 UTC; local only, not pushed); since then `latest` is `0.1.0-beta.0` (local tag `v0.1.0-beta.0` on 1f0f617, not pushed). origin also has `situation-v2.1` (= 5bc40c9 on origin/runtime, "situation-v2 + no-baseline stall fact (additive)"), which is not an ancestor of this branch. What 806a296 lacks (the zero-code entries f3a9dd1, 29b7f28, 054da38, f107013) was first published in `0.1.0-beta.0`. ### Root module exports @@ -110,7 +110,7 @@ Not exported from the root: `util.ts` helpers, `normalizeError`, `policyConfig`/ ### Zero-code entries (`/auto`, script tag, CLI) -Owner: INSTALL (f3a9dd1, merged from origin/runtime). Not in npm `0.1.0-alpha.1`. Every path ends in `GenClass.init`, so it inherits the singleton (a later `GenClass.init(...)` in app code returns the runtime the entry started and **ignores its options**), the kill switch and the `observe` default mode. +Owner: INSTALL (f3a9dd1, merged from origin/runtime). Not in npm `0.1.0-alpha.1`; in `0.1.0-beta.0` (`latest` since 2026-10-08). Every path ends in `GenClass.init`, so it inherits the singleton (a later `GenClass.init(...)` in app code returns the runtime the entry started and **ignores its options**), the kill switch and the `observe` default mode. **Page configuration** (`src/cdn/config.ts`), lowest precedence first; `mergeConfig` is a shallow merge where later wins, two `model` objects are merged and `model: false` replaces: @@ -703,7 +703,7 @@ Untested in this scope (by unit tests): `startAuto` and the script tag's `instal |---|---|---|---| | Default mode | HANDOFF.md "Modes: observe → guard (default; ...)"; npm `0.1.0-alpha.0` | `o.mode ?? "observe"` on `mvp-v2` (f3636b2) and `mvp-v2-merge`. API.md, ARCHITECTURE.md, CONTRACT §2/§13, `types.ts` JSDoc, devtools labels and both READMEs (README.md, packages/runtime/README.md, which says plain `/auto` and the tag without `data-mode` observe) say observe. origin/runtime (through eff18cb) still defaults to guard. | `runtime.ts` -> `RuntimeImpl` constructor; `default-mode.test.ts` | | `init` CLI mode | `bin/lib/init.mjs` -> `USAGE` ("guard (default)") and the summary row (`o.mode ?? "guard"`, "(default; --mode observe never changes anything)"), written against origin/runtime's guard default | `plan.mjs` -> `AUTO` maps `guard` and no `--mode` to plain `@genclass/runtime/auto`, and `scriptTag` omits `data-mode` for `guard`; on this branch both run in **observe**. So `init --mode guard` silently installs observe, and the printed "Mode guard" is wrong. Fix (INSTALL): map `guard` to `/auto/guard` and `data-mode="guard"`, make the default `observe`, update `cli.test.ts` fixtures. | `bin/lib/plan.mjs` -> `AUTO`, `scriptTag`; `bin/lib/init.mjs`; `src/auto.ts` | -| Zero-code entries vs npm | packages/runtime/README.md documents `npx @genclass/runtime init`, `/auto` and the script tag (with a note that alpha.1 lacks them); `package.json` says `0.1.0-alpha.1` | npm `0.1.0-alpha.1` (806a296) has none of them, `dist/genclass.global.min.js` is not on jsDelivr, and the CLI's `scriptTag` pins jsDelivr to the package's own version (`0.1.0-alpha.1`), whose file does not exist. The alias package `packages/genclass-runtime` (not on npm) is also at `0.1.0-alpha.1` and pins `"@genclass/runtime": "0.1.0-alpha.1"` exactly, whose bin has no `init`/`remove`; its naming question is open in `packages/runtime/INSTALL-NEEDS.md` (OPEN_TASKS.md item 14). Needs a version bump of both packages and a publish (`0.1.0-alpha.2` or a beta) before any of it works for consumers. | `npm view @genclass/runtime`, `npm view genclass-runtime` (404) (2026-10-08); `bin/lib/plan.mjs` -> `scriptTag`; `packages/genclass-runtime/package.json` | +| Zero-code entries vs npm | packages/runtime/README.md documents `npx @genclass/runtime init`, `/auto` and the script tag (with a note that alpha.1 lacks them); `package.json` says `0.1.0-alpha.1` | npm `0.1.0-alpha.1` (806a296) has none of them, `dist/genclass.global.min.js` is not on jsDelivr, and the CLI's `scriptTag` pins jsDelivr to the package's own version (`0.1.0-alpha.1`), whose file does not exist. The alias package `packages/genclass-runtime` (not on npm) is also at `0.1.0-alpha.1` and pins `"@genclass/runtime": "0.1.0-alpha.1"` exactly, whose bin has no `init`/`remove`; its naming question is open in `packages/runtime/INSTALL-NEEDS.md` (OPEN_TASKS.md item 14). Resolved for the scoped package on 2026-10-08: `0.1.0-beta.0` (`latest`) contains them and the alias now pins `0.1.0-beta.0`; the alias itself is still unpublished. | `npm view @genclass/runtime`, `npm view genclass-runtime` (404) (2026-10-08); `bin/lib/plan.mjs` -> `scriptTag`; `packages/genclass-runtime/package.json` | | Script-tag model wiring | `ModelOptions` (`types.ts`) lists `baseUrl`, `device`, `worker`, `preload`, `ortWasmPaths`, `cacheName` | `global.ts` -> `withCdnModel` also passes `workerFactory` and `ortLoader` (host-only `ModelHostOptions`) through `model` by a cast; `createRuntime` spreads `model` into `createModelHost`, so they work, but the public type does not admit them | `src/cdn/global.ts`; `index.ts` -> `makeHost`; `model/host.ts` | | `/auto/` precedence | The import path reads as "this mode" | The path's mode is the lowest-precedence default: a `` or `GENCLASS_CONFIG.mode` overrides it (as does the kill switch) | `cdn/auto-start.ts` -> `startAuto` | | Observe deliveries | `RuntimeImpl.runDelivery` behaviour up to 054da38 | Fixed in 054da38: observe used to hold a conflicting response for up to `BODY_WAIT_MS` (body read) before release, and its decision was dropped as stale. API.md / ARCHITECTURE.md do not yet describe background delivery decisions. | `runtime.ts` -> `runDelivery`, `deliveryHoldable`; `observe-delivery.test.ts` | @@ -728,14 +728,14 @@ Untested in this scope (by unit tests): `startAuto` and the script tag's `instal | API.md shapes | `Situation` listed as `{ trigger, subject, state, questions, actions, salient, facts }`; `Op` without `meta` | `Situation` also has `compact` and `budget`; `Op` also has `meta` | `types.ts` -> `Situation`, `Op` | | API.md observers | "The DOM, fetch, XHR, WebSocket and timers are observed automatically" (packages/runtime/README.md now lists them all) | Also `eventsource` (batch 4), `perf` (long tasks) and `timers` (timers only when `global.document` exists) | `runtime.ts` -> `installObservers` | | Report console hint | "Deny this action: `GenClass.init({ policy: { deny: [...] } })`" | A no-op once `GenClass.init` has run (idempotent init ignores the new options) | `decide/report.ts` -> `Reporter.emit`; `index.ts` -> `GenClass.init` | -| Default model URL | README: the runtime model is not published yet; alpha observes only | `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and so does the CLI's `DEFAULT_FROM` (until 2026-10-08 the GitHub release `runtime-model-v0.1.0`); both 404 as of 2026-10-08 (`@genclass/runtime-model` is not on npm), so a default browser `init()` ends in status `error` ("Model unavailable ...; observing only."). No situation-v2 model exists yet; R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 12 | -| npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from `mvp-v2` (806a296), is `latest` since 2026-10-08; procedure in [RELEASE.md](../../../RELEASE.md). alpha.1 in turn lacks everything after 806a296 (zero-code entries, 054da38, f107013). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | +| Default model URL | README (before 9695830): the runtime model is not published yet; alpha observes only | Resolved 2026-10-08 ~13:40 UTC. `DEFAULT_MODEL_BASE_URL` points at `@genclass/runtime-model@0.1.0` on jsDelivr and so does the CLI's `DEFAULT_FROM` (until 2026-10-08 the GitHub release `runtime-model-v0.1.0`); the package (`r17-v2b`, situation-v2) is published and the URL resolves, so a default browser `init()` loads the model (before that both were 404 and `init()` ended in status `error`, "Model unavailable ...; observing only."). R17-final1 (situation-v1) does not match this runtime. | `model/host.ts`; `bin/genclass-runtime.mjs` -> `DEFAULT_FROM`; HANDOFF.md; OPEN_TASKS.md item 12 | +| npm `0.1.0-alpha.0` vs this branch | npm "latest" until 2026-10-08 | The older alpha predates the NaN fix (ad24804: `describe` recursed forever on a `NaN` store value), situation-v2 (delivery gate, `holdWrites`, `eventsource`, new redaction, budget 2400) and the observe default. Resolved for new installs: `0.1.0-alpha.1`, built from `mvp-v2` (806a296), became `latest` on 2026-10-08, then `0.1.0-beta.0` (1f0f617, ~13:40 UTC; alpha.0 is deprecated); procedure in [RELEASE.md](../../../RELEASE.md). alpha.1 in turn lacks everything after 806a296 (zero-code entries, 054da38, f107013). | `npm view @genclass/runtime` (2026-10-08); `nan.test.ts` | | Dead code | | `on()` contains an empty `if (type === "report") {}` block | `runtime.ts` -> `on` | | `explainMap` bound | (no doc) the `DECISIONS_KEPT * 2` check in `onDecision` suggests a 400-entry cap | Only `onDecision` evicts (one entry, when size > 400); `finish` adds `a` entries without eviction, so the map grows by one per executed action for the life of the runtime (bounded in rate by `maxActionsPerMinute`, not in size) | `runtime.ts` -> `onDecision`, `finish` | | Init with malformed `plugins` | `GenClass.init` "never throws" | It does not throw, but a non-iterable `plugins` / `plugin.actions` / `plugin.questions` throws inside `RuntimeImpl`'s constructor after the observers were installed; the fallback inert runtime is returned while the first instance's wrappers stay on the globals | `runtime.ts` -> constructor, `use`; `index.ts` -> `GenClass.init` | | `decisions(0)` / `interventions(0)` | | Return the whole buffer (`slice(-0)`), while `history(0)` returns `[]` | `runtime.ts` | -Open items relevant here (OPEN_TASKS.md, HANDOFF.md, training/NEEDS.md): the model path is 150M teacher on situation-v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) -> rerun the demos -> publish `@genclass/runtime@0.1.0` without the alpha tag. The situation-v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled; plus real-browser gold rows from `realapps/` over 96 apps (`v2c1`..`v2c4`; the corpus on this branch has 128 app manifests), [../realapps.md](../realapps.md)); on 2026-10-08 the Azure jobs `r17-v2a` (R17 on v2 gold, 8 nodes, ETA ~06:20 UTC, auto eval and export via `training/v2_post.sh`; origin/runtime 416e374, not merged here, already records first `r17-v2a` results in RESULTS.md) and `t150-v2a` (150M teacher, 11 nodes, ETA ~08:30 UTC) were launched (OPEN_TASKS.md "In progress" items 1 and 2), and no situation-v2 model is published (`@genclass/runtime-model` 404 on npm, checked 2026-10-08). The next runtime release (`0.1.0-alpha.2` or a beta with the model) carries the zero-code entries, 054da38 and f107013; fix the `init` CLI mode mapping (Drift) before it. OPEN_TASKS.md item 16 (CI) is done on `mvp-v2` (b435acb); the `npm pack` smoke test in a fresh Vite app is not in CI. Why writes are no longer held (commit fcd1e68): store-write holds reordered in-app writes (held echoes overwrote newer user writes, read-after-write broke) and broke the unmodified RealWorld React/Redux app even with an always-passive model; the related "hold-induced harm" in the v0.1 demos is recorded in RESULTS.md §5 and OPEN_TASKS item 13 (demo rerun). Demo numbers with a v2 model are not measured yet. Until a v2 model ships, `GenClass.init()` (and every zero-code entry) observes and records but never acts (and with the observe default it would not act even with a model unless `mode: "guard"` is set, e.g. via `/auto/guard`). +Open items relevant here (OPEN_TASKS.md, HANDOFF.md, training/NEEDS.md): the model path is 150M teacher on situation-v2 gold -> teacher labels on unlabeled rows -> distil R17 (default) and R32 -> DAgger via SIM `--on-policy` -> EVAL -> publish `@genclass/runtime-model@0.1.0` (the default `baseUrl`) -> rerun the demos -> publish `@genclass/runtime@0.1.0` without the alpha tag. The situation-v2 data is done (eff18cb: 10.4M gold, 51.3M unlabeled; plus real-browser gold rows from `realapps/` over 96 apps (`v2c1`..`v2c4`; the corpus on this branch has 128 app manifests), [../realapps.md](../realapps.md)); on 2026-10-08 the Azure jobs `r17-v2a` (R17 on v2 gold, 8 nodes, ETA ~06:20 UTC, auto eval and export via `training/v2_post.sh`; origin/runtime 416e374, not merged here, already records first `r17-v2a` results in RESULTS.md) and `t150-v2a` (150M teacher, 11 nodes, ETA ~08:30 UTC) were launched (OPEN_TASKS.md "In progress" items 1 and 2). Since 2026-10-08 ~13:40 UTC the first situation-v2 model is published (`@genclass/runtime-model@0.1.0` = `r17-v2b`), together with `@genclass/runtime@0.1.0-beta.0`, which carries the zero-code entries, 054da38 and f107013. OPEN_TASKS.md item 16 (CI) is done on `mvp-v2` (b435acb); the `npm pack` smoke test in a fresh Vite app is not in CI. Why writes are no longer held (commit fcd1e68): store-write holds reordered in-app writes (held echoes overwrote newer user writes, read-after-write broke) and broke the unmodified RealWorld React/Redux app even with an always-passive model; the related "hold-induced harm" in the v0.1 demos is recorded in RESULTS.md §5 and OPEN_TASKS item 13 (demo rerun). Demo numbers with a v2 model are not measured yet. With the published model, `GenClass.init()` (and every zero-code entry) loads the model and decides, but with the observe default it does not act unless `mode: "guard"` is set, e.g. via `/auto/guard` (before 2026-10-08 no model loaded, so nothing could act). ## Related docs diff --git a/docs/agents/runtime/state-and-adapters.md b/docs/agents/runtime/state-and-adapters.md index 28113c37..170f716c 100644 --- a/docs/agents/runtime/state-and-adapters.md +++ b/docs/agents/runtime/state-and-adapters.md @@ -723,7 +723,7 @@ Open issues relevant to this scope: - **Hold latency** (`demos/NEEDS.md` §2): store writes no longer wait; responses and messages may (delivery holds, bounded by the hold budget and skipped when `expectedLatency()` exceeds it). See [decide-policy-actions.md](decide-policy-actions.md). - **`holdWrites` and library reads** (STATUS "Open issues"): `store.getState()` in Redux middleware and Zustand `get()` do not see held writes. Default off; per-store `hold: false`. - **Count-by-group cost** (STATUS "Open issues"): about +0.5 ms (STATUS) to +2.3 ms (perf note) per settled point with a large unchanged adapter store; bounded by 24 arrays × 8 columns × 8 values × 64 numbers. -- **No situation-v2 model exists yet** (HANDOFF / OPEN_TASKS): the R17 model on the train VM is situation-v1 and does not match this runtime; `@genclass/runtime-model` is not published. Store behaviour in guard mode with a real model is therefore untested end to end; the unit tests use scripted deciders. +- **Store behaviour with the real model is not covered by tests**: the round-1 R17 model is situation-v1 and does not match this runtime; since 2026-10-08 the situation-v2 model `r17-v2b` is published as `@genclass/runtime-model@0.1.0`, but the store behaviour in this doc is not tested end to end with it in guard mode; the unit tests use scripted deciders. - Unverified-by-test findings above: dotted store names, the stale snapshot of a top-level store with more than 32 keys, value writes of mutated-in-place objects (`holdWrites`), in-place value replacement in a large collection, library listeners throwing during commit, `structuredClone` prototype loss, discard marks outliving `pause()`, and the unused `StoreHub.mutations` map. - Dead or unused code paths: - `RuntimeImpl.rollback(stores, violationIds, beforeSeq?)`: no caller passes `beforeSeq`, so inconsistency rollback always uses the newest snapshot. `snapshotBefore` is used only for `SitEnv.consistentBefore` (facts). diff --git a/docs/agents/sim.md b/docs/agents/sim.md index 95a87f42..dc8c1689 100644 --- a/docs/agents/sim.md +++ b/docs/agents/sim.md @@ -641,7 +641,7 @@ exact latencies via `latencyFn`), `step`, `runBoth`, `argmin`, `find`. - **No v2 data or model is final yet.** Phase A/B and gold-r1x are situation-v1 and do not match the runtime at b435acb. The v2 runs (`train:/data/sim-out/v2-*`) are in progress on Azure (colleague-operated; [HANDOFF.md](../../HANDOFF.md), - training/NEEDS). On-policy (DAgger) rows need a v2 model export that does not exist yet. + training/NEEDS). On-policy (DAgger) rows need a v2 model export (at b435acb none existed; since 2026-10-08 `@genclass/runtime-model@0.1.0` = `r17-v2b` is published). - **`sim/NEEDS.md` is stale in several places.** Item g (NaN recursion in `describe()`) is marked OPEN but the runtime now uses `Object.is(r, v)` (`packages/runtime/src/util.ts` -> `describe`); the "Batch 4 / situation-v2" needs and the separability fact proposals (F1-F9) are marked OPEN/ASK but STATUS lists them DONE (batch 4 and batch 5); the old diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index 788c1ad8..09f5dce6 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -62,14 +62,16 @@ paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.t `mix_t150v2`, 88 ranks on c12, c14–c23, launched 05:20 UTC, ETA ≈ 08:30). REAL `v2c1`..`v2c4` had not landed at eff18cb; `v2b1`..`v2b3` stopped at ≈ 20.5k trajectories each with pre-fix diagnosis labels (`training/NEEDS.md` 16). Spend ≈ $440, burn ≈ $110/h with 20 nodes (LOG 05:22). -- **First v2 model: trained, not published, not in this branch.** `origin/runtime` 416e374 (`docs/runtime/RESULTS.md`) +- **First v2 run `r17-v2a`: trained, not itself published.** `origin/runtime` 416e374 (`docs/runtime/RESULTS.md`) reports r17-v2a: `sim2e` diagnosis 84.4%, action 77.9%, guard FIR 0.00%, heal FIR 0.46%; real-app eval set guard and heal FIR 0.00%; recall at the fixed 0.9/0.8 gates very low (duplicate 0.6%, stale 1.0% on real apps), hence batch 6's - model-provided thresholds. Still to come: teacher, distillation, DAgger, EVAL, then `@genclass/runtime-model@0.1.0` - and `@genclass/runtime@0.1.0` (owner's 2FA). No t150-v2a result is recorded anywhere yet. -- **Default install today** (npm alpha.1 and this branch): `GenClass.init()` starts in `observe`, tries the - unpublished model URL, ends in model status `error` and logs `[GenClass] Model unavailable (); observing - only.` From then on it traces and learns but never builds a situation or decides. No test covers this path. + model-provided thresholds. Since then (2026-10-08 ~13:40 UTC) `@genclass/runtime-model@0.1.0` + (`r17-v2b`, refit from `r17-v2a`) and `@genclass/runtime@0.1.0-beta.0` are published; `@genclass/runtime@0.1.0` is still to come (owner's 2FA). No t150-v2a result is recorded anywhere yet. +- **Default install** (npm `0.1.0-beta.0` and this branch, since 2026-10-08): `GenClass.init()` starts in `observe` + and loads `@genclass/runtime-model@0.1.0` from the default jsDelivr URL (Chromium check: Web Worker, WebGPU fp16, + 4.75 s load, `decide()` 72 ms); it decides and reports but acts only in `guard`/`heal`. Before 2026-10-08 (npm + alpha.1) the model URL was a 404: model status `error`, `[GenClass] Model unavailable (); observing only.`, + and no situation or decision after that. No automated test covers the default-URL path. - **Install code review (2026-10-08): 11 confirmed findings, nothing shipped yet.** Worst: `init` and `init --mode guard` install observe while printing "Mode guard" (`bin/lib/plan.mjs` -> `AUTO`, `scriptTag`), and the tree's version makes the CLI and global build point at the published alpha.1, which lacks those files. Full table: @@ -115,8 +117,8 @@ paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.t | `demos/NEEDS.md` | DEMOS → CORE/MODEL/UI/lead | §1–§8, written against batch 3 (stale for v2, see Drift) | | `packages/runtime/UI-NEEDS.md` | UI → CORE requests | Open 1–2 and Nice-to-have 3 (stale, see Drift) | | `realapps/README.md`, `realapps/EXAMPLES.md` | REAL's corpus, harness and audit | see [realapps.md](realapps.md) | -| `README.md`, `packages/runtime/README.md` | Repo landing page; npm README (rewritten by Mehar in d05abc1, merged) | both say `observe` is the default and `0.1.0-alpha.1` is `latest`; the npm README says the `init`, `/auto` and script-tag paths are "not in `0.1.0-alpha.1`" | -| `packages/runtime-model/MODEL_CARD.md` | Model card for the unpublished `@genclass/runtime-model` | status "final round 1 on the frozen runtime (situation-v1)"; the only tracked file in `packages/runtime-model/` | +| `README.md`, `packages/runtime/README.md` | Repo landing page; npm README (rewritten by Mehar in d05abc1, merged) | both say `observe` is the default; since 9695830 they describe `0.1.0-beta.0` with its model (before: `0.1.0-alpha.1` as `latest`, and the npm README said the `init`, `/auto` and script-tag paths are "not in `0.1.0-alpha.1`") | +| `packages/runtime-model/MODEL_CARD.md` | Model card for `@genclass/runtime-model` (published `0.1.0`, 2026-10-08) | since bcbee89 the card for `r17-v2b` (`genclass-runtime-r17` 2.0.0-rc2); earlier status "final round 1 on the frozen runtime (situation-v1)"; `packages/runtime-model/` also has `package.json` and `LICENSE` | | `.github/workflows/ci.yml` | CI (b435acb) | Node 22, `ONNXRUNTIME_NODE_INSTALL=skip`, `npm ci`, typecheck and build of `@genclass/runtime`, unit tests without `test/browser/**` and `review-perf`, then `review-perf` with `--retry=2` | | `package-lock.json` (root) | committed in b435acb | CI runs `npm ci` from it; keep it in sync | | `AGENTS.md`, `CLAUDE.md`, `docs/agents/**` | Agent docs (7dab2b3, refreshed for v2 in b561244; this doc, AGENTS.md, repo-map and glossary re-verified at f107013) | run policy, commands, ground rules, subsystem docs | @@ -234,7 +236,7 @@ model-provided gate thresholds, no-baseline stall fallback; tag `situation-v2.1` | tag `situation-v2` | annotated tag object 75df720 → commit 6e5e86e | **frozen training format of the v2 data and r17-v2a** | | tag `situation-v2.1` | → 5bc40c9 (not merged here) | batch 6: v2 plus one neutral stall fact | | tag `v0.1.0-alpha.0` | → 654d822 | the first published alpha | -| tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1 (`latest`); local only, not pushed | +| tag `v0.1.0-alpha.1` | → 806a296 | published alpha.1 (`latest` until 2026-10-08 ~13:40 UTC, then `0.1.0-beta.0`); local only, not pushed | | `packages/runtime/package.json` `version` | `0.1.0-alpha.1` | **already published**: bump before building or packing the next release | | `packages/genclass-runtime/package.json` | `0.1.0-alpha.1`, dependency `@genclass/runtime` `0.1.0-alpha.1` | unpublished alias (no `genclass-runtime` on npm) | | `@genclass/runtime-model@0.1.0` | published 2026-10-08 (`latest`, `r17-v2b`, shasum 84f33344...); `packages/runtime-model/` tracks only `MODEL_CARD.md` | default `model.baseUrl` | @@ -452,7 +454,7 @@ model only for salient situations, in a worker. (3) Observability: one console l - **Code wins over every doc.** CONTRACT.md does not describe batch 4/5 (no `delivery` trigger); the deltas live in STATUS "Contract deltas". HANDOFF still says guard is the default. -- **Two defaults in the wild.** This branch, `mvp-v2` and npm alpha.1 (`latest`) default to `observe`; +- **Two defaults in the wild.** This branch, `mvp-v2`, npm alpha.1 and npm beta.0 (`latest`) default to `observe`; `origin/runtime` (still `o.mode ?? "guard"` at 5bc40c9) and npm alpha.0 default to `guard`. The tests' `setup()` defaults to `guard` on purpose. Mehar's install CLI was written against the guard default, so on this branch it maps `--mode guard` to the observe entry (install finding 1): never trust `init`'s "Mode" line here. @@ -771,7 +773,7 @@ has no install code. All must be weighed before the next release. | `packages/genclass-runtime/package.json` | version and dependency `0.1.0-alpha.1` | the alias would need the next version and is unpublished (`INSTALL-NEEDS.md` item 1) | | `docs/runtime/CONTRACT.md` | no `delivery` trigger (§6); §4 mutations "held until a decision arrives"; §6 budget "≤ 1,000 tokens"; §8 `holdBudgetMs` "default 300"; §2 redaction regex and observer list without `eventsource`/`untrustedEvents`; §13 default-mode entry: "`situation-v1` training data stays valid" | batch 4/5 deltas exist only in STATUS; no store-write holds by default; 2,400-char budget; "auto" hold budget; leaf-field redaction (SIT-14); the entry should say situation-v2 (mode does not change situation text: `src/situation/*` has no mode dependency) | | `docs/runtime/ARCHITECTURE.md` | "3,200 characters on WebGPU, 2,000 with WASM threads"; redaction regex | 2,400 on WebGPU and unknown devices, 2,000 only at 4 threads (`STATE_CHAR_BUDGET`); leaf-field rule | -| `docs/runtime/API.md` | mostly current for v2; still advises `fetch-model` without `--from`; "observe … nothing is held"; no `/auto` or script tag | the default model 404s; "nothing is held" is now true here (054da38), not in npm alpha.1 (DL-3); the install entries are undocumented in API.md. Full API drift: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#drift-and-open-issues) | +| `docs/runtime/API.md` | mostly current for v2; still advises `fetch-model` without `--from`; "observe … nothing is held"; no `/auto` or script tag | the default model was a 404 until 2026-10-08 (resolves now); "nothing is held" is now true here (054da38), not in npm alpha.1 (DL-3); the install entries are undocumented in API.md. Full API drift: [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md#drift-and-open-issues) | | `packages/runtime/STATUS.md` | "Updated: … (batch 5 …)"; Open issues: "`react-dom` is not a devDependency"; never-worse "same requests, bodies, server state and DOM"; 42 files / 348 tests; nothing on 054da38 | `react-dom ^19.3.0` is a devDependency; the sweep compares less (RA-1); 46 files / 393 tests here; observe deliveries changed in 054da38 | | `docs/runtime/RESULTS.md` §4, §6 (merged version) | "0/396" never-worse; real-browser v2 gold "~495k target, generating" (96 apps) | covers 66 apps and final text/server content only (RA-1, RA-6); the newer RESULTS on `origin/runtime` reports 616,437 REAL gold and r17-v2a | | `packages/runtime-model/MODEL_CARD.md` | "`files/r17/` here"; clear-case recall "≈ 5%" | `files/` is gitignored (only `MODEL_CARD.md` is tracked); EVAL.md gives guard 4.2% on all clear rows, 7.7% on clear stale/duplicate, heal 6.1% | diff --git a/docs/agents/training.md b/docs/agents/training.md index d5af938b..3421ee10 100644 --- a/docs/agents/training.md +++ b/docs/agents/training.md @@ -662,7 +662,7 @@ Doc-vs-code drift: - `eval_sim.sh` header says "Run on c01"; it now runs on c02 and on rank-0 nodes (`v2_post.sh`). Open items relevant to this scope (HANDOFF, OPEN_TASKS, PLAN-v1, NEEDS): -- **No situation-v2 model has results yet.** Done: SIM v2 data (10.4M gold, 51.3M unlabeled), the `sim2`/`cur5` import, `r17-v2a` (ETA ≈ 06:20 UTC, auto eval + export via `v2_post.sh`) and `t150-v2a` (ETA ≈ 08:30 UTC) launched. Next per HANDOFF / LOG: read and record `r17-v2a`'s eval, deliver its export (also SIM's on-policy input) → import REAL `v2c*` (≈ 530k gold expected; target ≥ 500k) and continue with `real2` → T150 teacher on v2 gold (P1) → teacher eval incl. clear-case separation (P2) → teacher labels on the unlabeled rows (P3: a prioritised 5–10M-row subset of the ≥ 50M) → distil R17 (default) and R32 (P4) → DAgger via SIM `--on-policy` (P5) → EVAL → `@genclass/runtime-model@0.1.0` (release steps: [RELEASE.md](../../RELEASE.md); the runtime's `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` 404 until then; `@genclass/runtime-model` is 404 on npm) → demos rerun → `@genclass/runtime@0.1.0`. The v2 replay set (`cur5`) and the v2 mixtures exist; a distillation mixture and the unlabeled import still have to be written. A trained v2 model would ship as `@genclass/runtime-model`; `@genclass/runtime@0.1.0-alpha.1` is already on npm (published from 806a296, without the one-command install, which goes into the next runtime version). +- **Update 2026-10-08 ~13:40 UTC:** the first situation-v2 model, `r17-v2b` (`genclass-runtime-r17` 2.0.0-rc2, from `r17-v2a` plus real-app gold), is published as `@genclass/runtime-model@0.1.0` together with `@genclass/runtime@0.1.0-beta.0`; the default model URL resolves (see `packages/runtime-model/MODEL_CARD.md`). The rest of this item is the earlier status. **No situation-v2 model had results yet.** Done: SIM v2 data (10.4M gold, 51.3M unlabeled), the `sim2`/`cur5` import, `r17-v2a` (ETA ≈ 06:20 UTC, auto eval + export via `v2_post.sh`) and `t150-v2a` (ETA ≈ 08:30 UTC) launched. Next per HANDOFF / LOG: read and record `r17-v2a`'s eval, deliver its export (also SIM's on-policy input) → import REAL `v2c*` (≈ 530k gold expected; target ≥ 500k) and continue with `real2` → T150 teacher on v2 gold (P1) → teacher eval incl. clear-case separation (P2) → teacher labels on the unlabeled rows (P3: a prioritised 5–10M-row subset of the ≥ 50M) → distil R17 (default) and R32 (P4) → DAgger via SIM `--on-policy` (P5) → EVAL → `@genclass/runtime-model@0.1.0` (release steps: [RELEASE.md](../../RELEASE.md); the runtime's `DEFAULT_MODEL_BASE_URL` and the CLI `DEFAULT_FROM` were 404 until then) → demos rerun → `@genclass/runtime@0.1.0`. The v2 replay set (`cur5`) and the v2 mixtures exist; a distillation mixture and the unlabeled import still have to be written. A trained v2 model would ship as `@genclass/runtime-model`; `@genclass/runtime@0.1.0-alpha.1` was on npm (published from 806a296, without the one-command install, which went into `0.1.0-beta.0`). - R17-final1 (situation-v1) exists only on the train VM / Mehar's Mac and does not match the v2 runtime: do not package it as the v2 default. - T1 on v2 data (rerun `r17-t1g10`/`t1g20`/`t1h` on v2 gold; the gain head must be ported into this repo's `jev_local` first). The v1 T1 runs are resumable but superseded. - Cost: PLAN-v1 estimates ≈ $3–4k in total (P0–P5 plus per-round eval); ≈ $440 spent to 05:22 UTC with ≈ $110/h burn while the 20 v2 nodes run (LOG); RESULTS.md says ≈ $400 (older). Every Azure action needs the user's OK on our side. diff --git a/packages/runtime/test/install/RESULTS.md b/packages/runtime/test/install/RESULTS.md index 45716276..7fbb9716 100644 --- a/packages/runtime/test/install/RESULTS.md +++ b/packages/runtime/test/install/RESULTS.md @@ -8,8 +8,8 @@ again (must print "Nothing to do" and change no file) → production build → p server in Chromium → `npx file: remove --yes` → every file compared with the scaffold (sha256, excluding node_modules, lockfiles and build output). -In Chromium, the jsDelivr defaults are served from local copies, because `@genclass/runtime-model` is not published -yet: the model card and files, and onnxruntime-web's wasm. "Model ready" is the runtime's own +In Chromium, the jsDelivr defaults are served from local copies, because `@genclass/runtime-model` was not published +at the time of this run (it is since 2026-10-08): the model card and files, and onnxruntime-web's wasm. "Model ready" is the runtime's own `[GenClass] Model ready (...)` console line, so it shows the framework bundled the model worker and the model loaded in it. From 55c51a36a6f15b1e405d169d8efe36eff3d48201 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 23:13:13 -0400 Subject: [PATCH 21/25] release: @genclass/runtime 0.1.0-beta.2 (observe default + beta.1's model 0.2.0 and options) Bump @genclass/runtime and the genclass-runtime alias (and its pinned dependency) to 0.1.0-beta.2; refresh package-lock.json. CHANGELOG 0.1.0-beta.2 and 0.1.0-beta.1 sections; READMEs: beta.2 status, modes and model 0.2.0 profile numbers (balanced slightly over the FIR targets, cautious under); OPEN_TASKS Done/Next; RELEASE.md next-release note. Co-Authored-By: Claude Opus 5.5 --- OPEN_TASKS.md | 26 ++++++-- README.md | 58 ++++++++-------- RELEASE.md | 8 +++ package-lock.json | 8 +-- packages/genclass-runtime/package.json | 4 +- packages/runtime/CHANGELOG.md | 42 ++++++++++++ packages/runtime/README.md | 92 ++++++++++++++------------ packages/runtime/package.json | 2 +- 8 files changed, 159 insertions(+), 81 deletions(-) diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 51b79049..21f40068 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -6,11 +6,20 @@ release commit 806a296); `mvp-v2-merge` merges the two. Spec: [docs/runtime/CONTRACT.md](docs/runtime/CONTRACT.md). Results and numbers: [docs/runtime/RESULTS.md](docs/runtime/RESULTS.md). The runtime decides through a trained local model; nothing here is hardcoded per bug pattern. -The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). Since 2026-10-08 (~13:40 UTC) `@genclass/runtime-model@0.1.0` (`r17-v2b`) and -`@genclass/runtime@0.1.0-beta.0` are on npm (`latest`), so the default model URL resolves (Done). +The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). On npm (`latest`): `@genclass/runtime@0.1.0-beta.1` +with `@genclass/runtime-model@0.2.0` (`r17-v2dT`); `0.1.0-beta.2` (the merge of both branches, observe default) is +packed on `mvp-v2-b6` and waits to be published (Done, Next). ## Done +- **`@genclass/runtime@0.1.0-beta.2` prepared, not published** (2026-10-08, branch `mvp-v2-b6`): merges + `origin/runtime` at 696b1b4 (tag `v0.1.0-beta.1`: model 0.2.0 `r17-v2dT` with gain gate and aggressiveness + profiles, batch 11 `aggressiveness`, batch 12 options, perSubject 10/min) and restores what `0.1.0-beta.1` lacked: + default mode `observe` (guard opt-in, `aggressiveness` default `balanced` applies once you opt in), observe never + holding or delaying deliveries with background delivery decisions recorded (now also for sample / breaker / route + scope demotions and protected / cross-origin subjects), the redaction fixes, the install CLI fixes, and + `fetch-model` defaulting to `@genclass/runtime-model@0.2.0` on jsDelivr (equal to `DEFAULT_MODEL_BASE_URL`). The + `genclass-runtime` alias is bumped to `0.1.0-beta.2` and pins it. 461 unit tests + 14 skipped, plus 4 review-perf. - **npm 0.1.0-beta.1** (latest) + **model 0.2.0** (r17-v2dT, gain gate, cautious/balanced/eager profiles) + the `genclass-runtime` alias are published (2026-10-08). The registry e2e passes: guard fixes 6/6 and clean typing makes 0 model calls. - **npm:** `@genclass/runtime@0.1.0-beta.0` (latest) and `@genclass/runtime-model@0.1.0` (r17-v2b, with gates refit on on-policy data) @@ -111,9 +120,16 @@ Mehar operates the Azure cluster; nobody else touches Azure. The jobs below run The usual order (HANDOFF.md): v2 data collected → teacher → labels → distillation → DAgger → EVAL → model package → demos rerun → runtime release. -- **Push `mvp-v2-b6` and the tags** (`v0.1.0-beta.0`, `runtime-model-v0.1.0`, `v0.1.0-alpha.1`) through an account with - write access to daybot-solutions-inc/GenClass-lib. GitHub releases for them are optional. -- **Model `0.2.0` (`r17-v2c`)**: the next model package. +- **Publish `@genclass/runtime@0.1.0-beta.2`** (`--tag latest`) and the `genclass-runtime@0.1.0-beta.2` alias from + the packed tarballs (RELEASE.md, top note), then deprecate `0.1.0-beta.1` ("defaults to guard and lacks the + observe/redaction/install fixes; use 0.1.0-beta.2 or later") after checking with Mehar. +- **Push `mvp-v2-b6` and the tags** (`v0.1.0-beta.0`, `runtime-model-v0.1.0`, `v0.1.0-alpha.1`, and `v0.1.0-beta.2` + once published) through an account with write access to daybot-solutions-inc/GenClass-lib; merge it back into + `runtime` so the two branches stop diverging on the default mode. GitHub releases are optional. +- **Re-measure observe mode on model 0.2.0** (false flags per profile's report threshold 0.95 / 0.90 / 0.70); the + READMEs still quote model 0.1.0's observe numbers. +- **`balanced` is slightly over the FIR targets** (guard 0.13% vs 0.1%, heal 0.59% vs 0.5% on simulated apps): refit + with the real-app certification set (RESULTS.md §1) or make `cautious` the default for guard. 6. **Check the v2 data before training on it** (from the review findings): SIM samples budget 3,200 for ~40% of trajectories (`sim/src/world/scenario.ts` → `budget`), above the v2 device budgets; unlabeled rows hard-label diff --git a/README.md b/README.md index 3bcb8b60..aea49ff3 100644 --- a/README.md +++ b/README.md @@ -23,33 +23,37 @@ generic facts about each write, request and response, and asks a small GenClass The model runs in the browser (WebGPU or WASM, in a Web Worker). It answers two questions: what is happening, and which available action is best. There is no list of known bugs in the code. -> **Status: beta. `@genclass/runtime@0.1.0-beta.0` ships with its first trained model, -> `@genclass/runtime-model@0.1.0`.** +> **Status: beta. `@genclass/runtime@0.1.0-beta.2` with the model `@genclass/runtime-model@0.2.0`.** > > - **Runtime:** works and is unit-tested (situation format tag `situation-v2.3`). Install with > `npx @genclass/runtime init`, one import (`@genclass/runtime/auto`) or one script tag. > - **Default mode** is `observe`: the model diagnoses salient situations and the runtime reports likely problems, -> without changing what the app does. `guard` is opt-in; `heal` is experimental. -> - **Model:** `genclass-runtime-r17` 2.0.0-rc2 (9.6 MB, WASM or WebGPU), loaded from jsDelivr by default. -> - On held-out data it diagnoses about 84% of decisions correctly (83.6% on real apps). -> - In observe mode it flags 1.4% (simulated) to 3.8% (real) of decisions where nothing was wrong. -> - When it acts, it is rarely wrong (0.01% guard, 0.07% heal on simulated apps; none seen on held-out real apps), -> but it acts on under 6% of the cases where acting would help. +> without changing what the app does (it never holds or delays a response). `guard` is opt-in; `heal` is +> experimental. +> - **How eager it acts** once you opt in: `aggressiveness: "cautious" | "balanced" (default) | "eager"`. +> - **Model:** `genclass-runtime-r17` 2.0.0-rc4t (`r17-v2dT`, gain gate, 10 MB, WASM or WebGPU), loaded from jsDelivr +> at idle and cached. On held-out data ([RESULTS.md](docs/runtime/RESULTS.md) §1): > -> See the [model card](packages/runtime-model/MODEL_CARD.md). -> - **Older versions on npm:** `0.1.0-alpha.1` (the v2 runtime without the install commands or model gates) and -> `0.1.0-alpha.0` (the v1 runtime: guard by default, holds store writes, `NaN` crash). Use `0.1.0-beta.0`. +> | profile | guard FIR | guard recall (clear / real) | heal FIR | heal recall (clear / real) | report threshold | +> |---|---|---|---|---|---| +> | `cautious` | 0.005% | 2.4% / 1.4% | 0.26% | 3.7% / 3.8% | 0.95 | +> | `balanced` (default) | 0.13% | 7.8% / 7.5% | 0.59% | 7.1% / 10.4% | 0.90 | +> | `eager` | 0.54% | 14.2% / 21.0% | 1.84% | 17.1% / 24.2% | 0.70 | +> +> Our targets are guard FIR ≤ 0.1% and heal FIR ≤ 0.5%. `cautious` stays under both; `balanced` is slightly over +> both (0.13% and 0.59% on simulated apps); `eager` is well over. FIR on held-out real apps was 0.00% for every +> profile. Recall is still low: at `balanced`, guard acts on under 8% of the cases where acting would help. +> Installed from the registry into a fresh app, guard mode fixed an out-of-order typeahead in 6 of 6 trials, and +> clean typing made 0 model calls. See the [model card](packages/runtime-model/MODEL_CARD.md). +> - **Options** (activation, route scopes, protected endpoints, breaker, shadow, veto, action limits, sinks): +> [OPTIONS-SPEC.md](docs/runtime/OPTIONS-SPEC.md). +> - **Older versions on npm:** `0.1.0-beta.1` (model 0.2.0 and the options, but `guard` by default and without the +> observe-delivery, redaction and install fixes), `0.1.0-beta.0` (model 0.1.0), `0.1.0-alpha.1` and +> `0.1.0-alpha.0` (no model). Use `0.1.0-beta.2`. > > What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: > start at [AGENTS.md](AGENTS.md). -> **Status: beta.** [`@genclass/runtime@0.1.0-beta.1`](https://www.npmjs.com/package/@genclass/runtime) with the model -> [`@genclass/runtime-model@0.2.0`](https://www.npmjs.com/package/@genclass/runtime-model) (10 MB, loaded at idle and -> cached). Choose how eager it is with `aggressiveness: "cautious" | "balanced" | "eager"`. Installed from the -> registry into a fresh app, guard mode fixed an out-of-order typeahead in 6 of 6 trials, and clean typing made 0 -> model calls. Measured numbers per profile: [RESULTS.md](docs/runtime/RESULTS.md). Options: [OPTIONS-SPEC.md](docs/runtime/OPTIONS-SPEC.md). -> Remaining work: [OPEN_TASKS.md](OPEN_TASKS.md). Agents continuing the work: [HANDOFF.md](HANDOFF.md). - ## How it works 1. **Observe.** Fetch, XHR, WebSocket, EventSource, DOM events, errors, navigation, storage, long tasks and timers @@ -71,12 +75,12 @@ which available action is best. There is no list of known bugs in the code. | mode | behaviour | |---|---| - | `observe` (default) | reports only | - | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the permitted actions' summed probability reaches the model's fitted guard threshold for that trigger (0.80; 0.95 on mutations) | - | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions, at the heal threshold for that trigger (0.85; 0.95 on failures) | + | `observe` (default) | reports only; never holds, delays or changes anything | + | `guard` (opt-in) | `discard`, `defer`, `coalesce`, `delay`, only when the model's gate for that trigger says acting beats doing nothing by the margin of the chosen `aggressiveness` profile | + | `heal` (experimental) | also `retry`, `serve_cached`, `block`, `hedge`, `rollback`, `resync` and custom actions, at the heal margin of the profile | - Detections are reported when the top diagnosis is not `expected` with probability ≥ 0.85 (the model's report - threshold). + Detections are reported when the top diagnosis is not `expected` with probability at or above the profile's + report threshold (0.95 / 0.90 / 0.70 for cautious / balanced / eager). `rt.gates()` shows what is in force. 6. **Explain.** - Every detection and intervention is logged in plain English, with the exact situation text the model read. @@ -95,12 +99,12 @@ All numbers are on held-out data, with each recall reported next to its false-in |---|---| | Round 1 model, R17 (9.6 MB int8; **previous format** `situation-v1`), simulated apps | diagnosis 90.5%, action 81.9%, guard FIR 0.05%, heal FIR 0.24%, calibration error 0.009. Recall on clear stale/duplicate cases is only 7.7% (precise but timid). | | Why round 1 was timid ([sim/SEPARABILITY.md](sim/SEPARABILITY.md)) | Many clear cases had benign twins with identical visible facts; 24% of clear rows were mislabelled `expected`; labels assumed knowledge a runtime cannot have. v2 adds measured facts and fixes the labels. | -| **r17-v2b** (`situation-v2`; shipped as `@genclass/runtime-model@0.1.0`) | Simulated apps: diagnosis 84.2%, action 77.8%. Real apps: diagnosis 83.6%, action 80.0%. Gates refit on the model's own on-policy traffic. Guard FIR 0.01% simulated, 0.00% on held-out real apps; heal FIR 0.07% / 0.00%. Recall: heal acts on 2.9% of clear simulated cases and 5.7% of actionable real-app cases; guard on 0.7%. | -| Observe mode with r17-v2b (report threshold 0.85, fitted on dev data) | Held-out test: 1.41% of decisions where nothing was wrong flagged on simulated apps (3.1% on the model's own on-policy traffic), 3.78% on real apps (1.05% without one app); 61–65% of problem decisions flagged, 89–94% of flags with the right diagnosis | +| **r17-v2dT** (`situation-v2`; shipped as `@genclass/runtime-model@0.2.0`, default since `0.1.0-beta.1`) | Gain gate with three profiles (table above). `balanced`: guard FIR 0.13%, heal FIR 0.59% on simulated apps (slightly over the 0.1% / 0.5% targets); `cautious`: 0.005% / 0.26% (under). 0.00% on held-out real apps for every profile. Calibration error 0.009. | +| r17-v2b (shipped as `@genclass/runtime-model@0.1.0`) | Simulated apps: diagnosis 84.2%, action 77.8%. Real apps: diagnosis 83.6%, action 80.0%. Guard FIR 0.01%, heal FIR 0.07%; heal acts on 2.9% of clear simulated cases and 5.7% of actionable real-app cases; guard on 0.7%. | | Training continues | teacher model, distillation, DAgger rounds; ~10M simulated gold rows, ~50M unlabeled rows, ~0.6M real-app rows | | Never make a correct app worse (always-passive model, heal vs observe, 66 real apps × 6 seeds) | 0/396 clean runs changed: final page text (inputs and alerts excluded) and server state. Request timing and store contents are not compared, nor is observe mode against no runtime. With chaos: 3/198 changed. | | Same check on the v1 runtime (store-write holds) | 4/198 clean runs changed; the React/Redux RealWorld app never rendered its home feed | -| Demos | Baseline only, with the untrained GenClass 0.1 model: guard took 0 actions. Not yet re-run with r17-v2b. | +| Demos | Baseline only, with the untrained GenClass 0.1 model: guard took 0 actions. Not yet re-run with model 0.2.0. | ## What's in this repo @@ -132,7 +136,7 @@ NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # t The same steps run in CI ([.github/workflows/ci.yml](.github/workflows/ci.yml), Node 22) on pushes to `main`, `runtime`, `mvp` and `mvp-v2`, on pull requests, and on manual dispatch. -Last full local run (2026-10-08, branch `mvp-v2-b6`, version `0.1.0-beta.0`): 419 tests passed and 14 skipped, plus +Last full local run (2026-10-08, branch `mvp-v2-b6`, version `0.1.0-beta.2`): 461 tests passed and 14 skipped, plus the 4 perf tests run alone. The skips are model-parity tests, which need `GENCLASS_MODEL_DIR`. The perf tests time a 5,000-item store and can fail under parallel load. diff --git a/RELEASE.md b/RELEASE.md index 58b4276d..7ffe41a5 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -4,6 +4,14 @@ > **Read this when:** you are asked to cut a release, prepare a tarball for the user to publish, or package a trained model. > **Source of truth:** the code. Verified 2026-10-08 (~07:00 UTC) against branch `mvp-v2-merge` at f107013. That branch is `mvp-v2` (release commit 806a296), merged with origin/runtime eff18cb (dabbce2), plus the two runtime fixes 054da38 and f107013. Newer commits on origin/runtime (up to 5bc40c9) were read with `git show` and are not merged on this branch. If this doc and the code disagree, the code wins. +> **Next release: `@genclass/runtime@0.1.0-beta.2` (prepared on `mvp-v2-b6`, not published).** It merges +> `0.1.0-beta.1` (published by Mehar from `runtime` at 696b1b4 with `@genclass/runtime-model@0.2.0`, defaulting to +> `guard`) with the `0.1.0-beta.0` fixes: observe default, observe never delaying deliveries, redaction, install CLI, +> jsDelivr `fetch-model` default (model `0.2.0`). The alias `genclass-runtime@0.1.0-beta.2` pins it. Publish from +> `packages/runtime`: `npm publish genclass-runtime-0.1.0-beta.2.tgz --access public --tag latest`, then from +> `packages/genclass-runtime`: `npm publish genclass-runtime-0.1.0-beta.2.tgz --access public --tag latest`. Model +> `0.2.0` is already on npm and jsDelivr (`model.json` 200); no model publish is needed. + > **Done 2026-10-08 (~13:40 UTC): Part B and Part C.** Published `@genclass/runtime-model@0.1.0` (dist-tag `latest`, same session; `r17-v2b` = `genclass-runtime-r17` 2.0.0-rc2 with gates guard 0.80 (mutation 0.95), heal 0.85 (failure 0.95, inconsistency 0.85), report 0.85; 9 files, 21.7 MB, shasum 84f3334428f0eea4d0e1a2a636b0003d8df3175f; local tag `runtime-model-v0.1.0`) and `@genclass/runtime@0.1.0-beta.0` (dist-tag `latest`, published 2026-10-08 ~13:40 UTC by `karanvir1729` with 2FA, from the clean release worktree at 1f0f617, branch `release/runtime-0.1.0-beta.0`, local annotated tag `v0.1.0-beta.0` not pushed; 52 files, 1.1 MB, shasum a15d2fb0d054ded5df81e9cb2ae87b1fd3f67e88). `@genclass/runtime@0.1.0-alpha.0` deprecated: "Old situation-v1 build that defaults to guard; use 0.1.0-beta.0 or later". jsDelivr serves `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/` (`model.json` 200; all 5 files' sha256 match `model.json`). Browser check: a plain HTML page with the jsDelivr script tag (`genclass.global.min.js` @0.1.0-beta.0) in Chromium: mode `observe`, model ready in a Web Worker on WebGPU (fp16), `loadMs` 4750, every gate's source `model`, `decide()` 72 ms. Nothing was pushed and no GitHub release was created (the user's GitHub account is read-only on daybot-solutions-inc/GenClass-lib); the CLI's `fetch-model` default is the jsDelivr model directory. Still open: push `mvp-v2-b6` and the tags (needs an account with write access); the GitHub releases (B5, C7) are optional. The rest of this doc is the procedure as planned. ## TL;DR diff --git a/package-lock.json b/package-lock.json index 81760e0b..fd36ac3f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3147,10 +3147,10 @@ } }, "packages/genclass-runtime": { - "version": "0.1.0-alpha.1", + "version": "0.1.0-beta.2", "license": "Apache-2.0", "dependencies": { - "@genclass/runtime": "0.1.0-beta.0" + "@genclass/runtime": "0.1.0-beta.2" }, "bin": { "genclass-runtime": "cli.mjs" @@ -3161,7 +3161,7 @@ }, "packages/runtime": { "name": "@genclass/runtime", - "version": "0.1.0-beta.0", + "version": "0.1.0-beta.2", "license": "Apache-2.0", "dependencies": { "onnxruntime-web": "^1.30.0" @@ -3206,7 +3206,7 @@ }, "packages/runtime-model": { "name": "@genclass/runtime-model", - "version": "0.1.0", + "version": "0.2.0", "license": "Apache-2.0" }, "sim": { diff --git a/packages/genclass-runtime/package.json b/packages/genclass-runtime/package.json index 5b223dab..9775f2b0 100644 --- a/packages/genclass-runtime/package.json +++ b/packages/genclass-runtime/package.json @@ -1,6 +1,6 @@ { "name": "genclass-runtime", - "version": "0.1.0-beta.1", + "version": "0.1.0-beta.2", "description": "Short alias for the @genclass/runtime CLI: npx genclass-runtime init sets up GenClass Runtime in your app.", "type": "module", "license": "Apache-2.0", @@ -8,6 +8,6 @@ "homepage": "https://www.npmjs.com/package/@genclass/runtime", "bin": { "genclass-runtime": "./cli.mjs" }, "files": ["cli.mjs", "README.md", "LICENSE"], - "dependencies": { "@genclass/runtime": "0.1.0-beta.1" }, + "dependencies": { "@genclass/runtime": "0.1.0-beta.2" }, "engines": { "node": ">=20" } } diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md index c7ef6de7..ff099ebd 100644 --- a/packages/runtime/CHANGELOG.md +++ b/packages/runtime/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## 0.1.0-beta.2 (2026-10-08) + +Merges the 0.1.0-beta.1 work (model 0.2.0, aggressiveness, batch 12 options) with the fixes that shipped in +0.1.0-beta.0 but were missing from 0.1.0-beta.1, which was published from a branch without them. + +- **Default mode is `observe` again.** `GenClass.init()` with no `mode` reports what it sees and never changes + execution; `guard` is opt-in and `heal` is experimental (0.1.0-beta.1 defaulted to `guard`). `aggressiveness` + still defaults to `"balanced"`; its action gates apply once you opt into `guard` or `heal` (in observe mode it + only picks the profile's report threshold for detections: 0.95 / 0.90 / 0.70 for cautious / balanced / eager). `shadow: "guard"` in observe mode records what guard + would have done, background delivery decisions included. +- **Observe never holds or delays a delivery.** A response or push message is released synchronously, before any + body read, whenever no hold is possible (observe, sample cap, breaker downgrade, an observe / off route scope, a + protected or cross-origin subject, no permitted action, or a model too slow for the remaining hold budget). The + delivery decision is still made in the background and recorded (`executed: false`), on the state the delivery was + released into; while it is pending it covers its chain's writes, so they are not decided twice. +- **Redaction fixes:** the "would replace text the user typed" fact no longer prints characters of a redacted + field, and numbers and arrays under a secret-named container (`payment.cvv.value`, `login.otp.code`) are redacted. +- **Install CLI fixes:** `init` without `--mode` writes the observe import, and `--mode guard|heal|observe` writes + `/auto/` (or `data-mode` on the script tag) and switches it in place when run again; `remove` deletes only + what `init` wrote, including formatter-rewrapped lines, and changes nothing when you edited inside a marked block; + Node servers and libraries are refused; SRI only for this version's own jsDelivr / unpkg file; `typesVersions` + for `"moduleResolution": "node"`. +- **`fetch-model` downloads from jsDelivr by default:** `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.2.0/files/`, + the same directory as the runtime's `DEFAULT_MODEL_BASE_URL` (a test keeps them equal). +- **CI:** GitHub Actions runs typecheck, build, the unit tests and review-perf (separately, with retries) against a + committed root `package-lock.json`. + +## 0.1.0-beta.1 (2026-10-08) + +Published from the `runtime` branch; it did not include the 0.1.0-beta.0 observe default, delivery, redaction and +install fixes listed above (0.1.0-beta.2 restores them). + +- **Model 0.2.0** (`@genclass/runtime-model@0.2.0`, `genclass-runtime-r17` 2.0.0-rc4t, run `r17-v2dT`) is the + default model: a gain gate and three aggressiveness profiles in `meta.json`. Numbers in `docs/runtime/RESULTS.md`. +- **`aggressiveness`** (runtime batch 11): `"cautious" | "balanced" | "eager"` or a number 0–1, per route too; + `rt.setAggressiveness()`, `?genclass-aggr` (demote only unless `debug`), a devtools selector, `rt.gates()`. +- **Batch 12, 19 options** (`docs/runtime/OPTIONS-SPEC.md`): `enabled`, `rt.disable({ undo })`, `sample`, `routes`, + `requests.{ignore, protect, labels, correlate, crossOrigin}`, `breaker`, `shadow`, `onBeforeAction` + `vetoMode`, + `policy.actionLimits` (60/min, 10/min per subject, 200 per session), `policy.holdBudgetMs` as a hard ceiling, + `sinks`, `session`, `report: "interventions"`, `rt.summary()`, typed `rt.on()` events, and `model.{loadIf, + threads, timeoutMs, maxDecisionsPerMinute, unloadAfterIdleMs}`. + ## 0.1.0-beta.0 (2026-10-08) - **Ships with a model.** A default `GenClass.init()` now loads `@genclass/runtime-model@0.1.0` diff --git a/packages/runtime/README.md b/packages/runtime/README.md index d009f903..d6c6add4 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -22,26 +22,25 @@ import { GenClass } from "@genclass/runtime"; GenClass.init(); // observe mode: reports only, never takes an action (see Known limitations) ``` -> **Status: beta (`0.1.0-beta.0`), the first version with a trained model.** +> **Status: beta (`0.1.0-beta.2`), with model `@genclass/runtime-model@0.2.0`.** > -> - **The model loads by default.** A default `GenClass.init()` loads `@genclass/runtime-model@0.1.0` (9.6 MB, -> `genclass-runtime-r17` 2.0.0-rc2) from jsDelivr at idle, in a Web Worker, and caches it. Self-hosting and -> `model: false` are under [Performance](#performance). +> - **The model loads by default.** A default `GenClass.init()` loads `@genclass/runtime-model@0.2.0` (10.2 MB q8, +> `genclass-runtime-r17` 2.0.0-rc4t, run `r17-v2dT`, with a gain gate and three aggressiveness profiles) from +> jsDelivr at idle, in a Web Worker, and caches it. Self-hosting and `model: false` are under +> [Performance](#performance). > - **Observe is the default.** The model diagnoses salient situations and the runtime reports likely problems; it -> never changes what your app does. `guard` is opt-in and `heal` is experimental. -> - **The model is precise when it acts, but timid, and observe mode shows some false flags.** -> - Diagnosis is right on about 84% of held-out decisions (83.6% on real apps). -> - It flags 1.4% (simulated apps) to 3.8% (real apps) of held-out decisions where nothing was wrong. On real apps, -> most of those came from one app. -> - In `guard` / `heal` it intervened wrongly on 0.01% / 0.07% of held-out simulated cases, and never on held-out -> real apps, but it acts on under 6% of the cases where acting would help. -> -> Details: [Model quality](#model-quality) and the +> never changes what your app does and never holds or delays a response. `guard` is opt-in and `heal` is +> experimental. Once you opt in, `aggressiveness` (`"cautious"`, `"balanced"` (default), `"eager"`) sets how eager +> it acts. +> - **The model is precise when it acts, but misses most problems.** On held-out simulated apps, at `balanced`: +> guard intervened wrongly on 0.13% of cases and heal on 0.59%, slightly above our 0.1% / 0.5% targets; at +> `cautious`, 0.005% and 0.26%, under them. No wrong interventions were seen on held-out real apps. At `balanced`, +> guard acts on under 8% of the cases where acting would help. Details: [Model quality](#model-quality) and the > [model card](https://www.npmjs.com/package/@genclass/runtime-model). -> - **Older versions.** `0.1.0-alpha.1` is the v2 runtime without the install commands, without the model's gate -> support, and with a delivery delay in observe mode. `0.1.0-alpha.0` is the older v1 runtime: guard by default, -> it holds store writes, and it can crash when app state contains `NaN`. Do not use it. Both load this model too, -> from the same default URL, but were not tested with it. +> - **Older versions.** `0.1.0-beta.1` has model 0.2.0 and the new options but defaults to `guard`, and lacks the +> observe-delivery, redaction and install fixes of `0.1.0-beta.0` (all back in `0.1.0-beta.2`). `0.1.0-beta.0` +> ships model 0.1.0. `0.1.0-alpha.1` and `0.1.0-alpha.0` (v1 runtime: guard by default, holds store writes, `NaN` +> crash) predate the model; do not use them. > > Progress: [OPEN_TASKS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/OPEN_TASKS.md) · > measured results: [RESULTS.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/RESULTS.md). @@ -58,7 +57,7 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known Run your app as usual. When the model flags something, the console gets one plain-English line per detection or intervention, followed by a collapsed group with the evidence. Here a typeahead's slow response for "rea" lands -after the response for "reac". This is real output of `0.1.0-beta.0` with its default model (q8 on WASM, in Node), +after the response for "reac". This is real output of `0.1.0-beta.0` with model 0.1.0 (q8 on WASM, in Node), in the default observe mode. The response reaches the app at once, exactly as without GenClass, and the decision is made in the background, for the report only: @@ -69,7 +68,7 @@ started (version 1 → 3), last 0.69s ago by GET /api/search?q=reac (#8), which user action (#7). (stale, 0.96) ``` -The same run in guard mode. The model's `discard` (0.98) passed the model's delivery gate (0.80), so the results +The same run in guard mode. The model's `discard` (0.98) passed model 0.1.0's delivery gate (0.80), so the results for "reac" stayed: ``` @@ -142,7 +141,7 @@ SSR or in Node, `/auto` installs nothing and returns an inert runtime. It exposes `window.GenClass` and loads the model worker, ONNX Runtime Web and the overlay on demand from the same version on the CDN. `data-mode` takes `observe` (the default), `guard` or `heal`; `data-devtools="local"` shows the overlay only on localhost; `data-manual` skips the automatic `GenClass.init()`. Pin a version in production -(`https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.0`); the plain-HTML path of `init` writes a pinned +(`https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.2`); the plain-HTML path of `init` writes a pinned jsDelivr URL with SRI. **4. By hand:** @@ -183,7 +182,7 @@ These hold for the runtime; whether the model's decisions are good is a separate - **Off in one step.** `?genclass=off` in the URL installs nothing, and observe (the default) never changes execution. - **Small.** The main entry is about 83 KB gzip (minified, without the optional devtools). The default model is - 9.6 MB on WASM (13.6 MB fp16 on WebGPU with `shader-f16`), downloaded once at idle and cached. + 10.2 MB on WASM (13.6 MB fp16 on WebGPU with `shader-f16`), downloaded once at idle and cached. ## Modes @@ -224,13 +223,15 @@ GenClass.init({ mode: "guard" }); runtime's defaults: report 0.6, guard 0.9, heal 0.8. `policy.thresholds: { report, guard, heal }` overrides both. `rt.gates(trigger)` shows the values in force and where each came from (`"policy"`, `"model"` or `"default"`). - **Detections.** In every mode, a decision is reported as a detection when its top diagnosis is not `expected` and - its probability is at least the report threshold: 0.85 with the default model. -- **Limits.** Actions are limited to 60 per minute (`policy.maxActionsPerMinute`). A held decision that misses the + its probability is at least the report threshold of the active profile: 0.95 / 0.90 / 0.70 for cautious / + balanced / eager with the default model. +- **Limits.** Actions are limited to 60 per minute overall, 10 per minute on the same subject and 200 per session + (`policy.actionLimits`). A held decision that misses the hold budget runs the passive action; a background write decision can still revert the write late. - **Control.** The `allow` / `deny` lists are in `policy`. Switch at runtime with `rt.setMode(mode)`, or stop consulting the model with `rt.pause()` / `rt.resume()`. -**The default changed.** `0.1.0-alpha.0` defaulted to `guard`. Now `GenClass.init()` with no `mode` (and +**The default changed.** `0.1.0-alpha.0` and `0.1.0-beta.1` defaulted to `guard`. Now `GenClass.init()` with no `mode` (and `@genclass/runtime/auto`, and the script tag without `data-mode`) observes only; pass `mode: "guard"` to let it act. **Kill switch.** Append `?genclass=off` to the URL, or set `localStorage.genclass = "off"`, and nothing is installed. @@ -487,42 +488,48 @@ onIncident(() => rt.disable({ undo: true })); **Rollout recipe:** start with `mode: "observe", shadow: "guard"`, and compare the shadow records with your undo and complaint rates. Then switch to `mode: "guard", sample: 0.05`. Watch `rt.summary().undos` and `breaker` events, and widen `sample` as they stay quiet. For QA, `?genclass-sample=1` together with `debug: true` forces a session into the acting group. -## Status - ## Model quality -The default model is `genclass-runtime-r17` 2.0.0-rc2 (`@genclass/runtime-model@0.1.0`): an 8.8M-parameter encoder -trained on simulated apps and on real apps driven in headless Chromium. Every number below is on held-out data: +The default model is `genclass-runtime-r17` 2.0.0-rc4t (`@genclass/runtime-model@0.2.0`, run `r17-v2dT`): a +GenClass encoder trained on simulated apps and on real apps driven in headless Chromium. It ships a gain gate (act +only when the model's expected gain over doing nothing clears a margin) with one fitted profile per aggressiveness +level. Held-out test, from +[RESULTS.md §1](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/RESULTS.md): -- simulated test rows, including apps built from features held out of training; -- real-app test rows from 10 apps, 7 of which never appeared in training. +| profile | guard false interventions | guard recall (clear / real) | heal false interventions | heal recall (clear / real) | report threshold | +|---|---|---|---|---|---| +| `cautious` | 0.005% | 2.4% / 1.4% | 0.26% | 3.7% / 3.8% | 0.95 | +| **`balanced` (default)** | 0.13% | 7.8% / 7.5% | 0.59% | 7.1% / 10.4% | 0.90 | +| `eager` | 0.54% | 14.2% / 21.0% | 1.84% | 17.1% / 24.2% | 0.70 | -Full tables, per-trigger gates and how each threshold was fitted: the -[model card](https://www.npmjs.com/package/@genclass/runtime-model). +False interventions are on simulated apps; on held-out real apps they were 0.00% for every profile. Our targets are +0.1% (guard) and 0.5% (heal): `cautious` meets both, `balanced` is slightly over both, `eager` trades well over +them for about twice `balanced`'s recall. Pick `cautious` if a wrong intervention costs more than a missed one. + +The observe-mode numbers below were measured on the previous model, 0.1.0 (`r17-v2b`, report threshold 0.85), and +have not been re-measured for 0.2.0: -| | Simulated apps | Real apps | +| model 0.1.0 | Simulated apps | Real apps | |---|---|---| | Diagnosis accuracy | 84.2% | 83.6% | | Action accuracy | 77.8% | 80.0% | | **Observe:** decisions flagged where nothing was wrong (report 0.85) | 1.41% (149 / 10,582) | 3.78% (305 / 8,079); 1.05% without one app | | Observe: problem decisions flagged | 65% | 61% | | Observe: flags with the right diagnosis | 94% | 89% | -| **Guard:** false interventions | 0.01% (1 / 8,987) | 0.00% (0 / 66) | -| Guard: cases acted on | 0.7% of clear cases | 0.0% of actionable cases | -| **Heal:** false interventions | 0.07% (11 / 16,290) | 0.00% (0 / 1,124) | -| Heal: cases acted on | 2.9% of clear cases | 5.7% of actionable cases | What this means in practice: -- **Observe (default).** Expect roughly 1 to 4 false flags per 100 decisions where nothing was wrong. +- **Observe (default).** Expect roughly 1 to 4 false flags per 100 decisions where nothing was wrong (model 0.1.0; + `cautious` raises the report threshold to 0.95, `eager` lowers it to 0.70). - In one held-out real app, `oss-rtk-conduit`, the model flagged 25% of clean decisions as `stale`, all on its `article.inProgress` field. A single recurring pattern in your app can do the same. - Each flag names its evidence, and identical lines within a minute are summarised. - Raise `policy.thresholds.report` to see fewer flags. At 0.9: 0.9% (simulated) and 3.4% (real) false, with 58% and 52% of problems flagged. - **Guard (opt-in).** When it acts, it is almost always right, but it rarely acts. Expect it to miss most problems. -- **Heal (experimental).** Heal actions on failures (`retry`, `serve_cached`) are the least precise: wrong on 0.19% - of held-out simulated failures where doing nothing was best (target 0.5%), at a failure threshold of 0.95. + `balanced` is slightly above the 0.1% false-intervention target; `cautious` is under it. +- **Heal (experimental).** At `balanced`, 0.59% of heal interventions were wrong on simulated apps (target 0.5%); + with model 0.1.0, heal actions on failures (`retry`, `serve_cached`) were its least precise actions. - **Not yet met:** diagnosis ≥ 95%, clear-case recall ≥ 80%, and false flags ≤ 1% on held-out data. Training continues (a larger teacher model, distillation, more real-app data). - **Format.** The model was trained on situations rendered by the runtime at `situation-v2`. This version renders @@ -578,7 +585,7 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs `Cross-Origin-Embedder-Policy: require-corp` enables WASM threads (about 3× faster with 4 threads in Chromium, measured with the round-1 model of the same size). - **Loading:** the model loads at idle after page load (`model.preload: "idle"`) from - `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.1.0/files/`. It is cached in Cache Storage and checked + `https://cdn.jsdelivr.net/npm/@genclass/runtime-model@0.2.0/files/`. It is cached in Cache Storage and checked with sha256. To self-host, `npx @genclass/runtime fetch-model public/genclass-model` downloads it, and `model: { baseUrl: "/genclass-model/" }` points the runtime at it. `model: false` loads no model (nothing is detected or prevented then). @@ -602,7 +609,8 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs - The "would replace text the user typed" fact shows a character diff only when the redactor leaves both values unchanged; otherwise it prints `[redacted] → [redacted]` (or your redactor's replacement). - Pass your own `redact(path, value)` for app-specific secrets or PII. The default has gaps (see below). - - The container rule for numbers and arrays and the typed-text rule are new in `0.1.0-beta.0`. + - The container rule for numbers and arrays and the typed-text rule are new in `0.1.0-beta.0` (missing from + `0.1.0-beta.1`, back in `0.1.0-beta.2`). ## Known limitations diff --git a/packages/runtime/package.json b/packages/runtime/package.json index c97525ce..7fac34c9 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@genclass/runtime", - "version": "0.1.0-beta.1", + "version": "0.1.0-beta.2", "description": "A client-side AI runtime for web apps: a local GenClass model watches user actions, async work, network, state and errors, and prevents stale writes, races, duplicates, inconsistent state and failure storms in real time.", "type": "module", "license": "Apache-2.0", From ed82578d253572d8561633fac6589316a6b1e231 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 23:20:43 -0400 Subject: [PATCH 22/25] telemetry: Cloudflare collector worker (genclass-telemetry, R2 gzip JSONL) POST /v1/events accepts genclass-telemetry/1 batches (application/json or text/plain for sendBeacon), CORS *, 256 KB / 500 events, validates shape, drops unknown top-level fields, adds only receivedAt and coarse country, never stores IP/user-agent/cookies/headers; writes gzip JSONL to R2 at events/dt=/rt=/model=/.jsonl.gz. GET /v1/health. Deployed at https://genclass-telemetry.mehar-144.workers.dev. Co-Authored-By: Claude Opus 5.5 --- telemetry-worker/.gitignore | 2 + telemetry-worker/README.md | 43 +++++++ telemetry-worker/src/index.ts | 177 ++++++++++++++++++++++++++++ telemetry-worker/test/index.test.ts | 95 +++++++++++++++ telemetry-worker/vitest.config.ts | 2 + telemetry-worker/wrangler.toml | 16 +++ 6 files changed, 335 insertions(+) create mode 100644 telemetry-worker/.gitignore create mode 100644 telemetry-worker/README.md create mode 100644 telemetry-worker/src/index.ts create mode 100644 telemetry-worker/test/index.test.ts create mode 100644 telemetry-worker/vitest.config.ts create mode 100644 telemetry-worker/wrangler.toml diff --git a/telemetry-worker/.gitignore b/telemetry-worker/.gitignore new file mode 100644 index 00000000..41a25789 --- /dev/null +++ b/telemetry-worker/.gitignore @@ -0,0 +1,2 @@ +.wrangler/ +node_modules/ diff --git a/telemetry-worker/README.md b/telemetry-worker/README.md new file mode 100644 index 00000000..ef18c163 --- /dev/null +++ b/telemetry-worker/README.md @@ -0,0 +1,43 @@ +# genclass-telemetry (collector) + +Cloudflare Worker that receives the default-on diagnostics batches from `@genclass/runtime` (see +[`packages/runtime/TELEMETRY.md`](../packages/runtime/TELEMETRY.md)) and stores them in R2. + +- **Deployed:** `https://genclass-telemetry.mehar-144.workers.dev` (account `144bd5f5270b51dbe7faf46227a154f0`, + worker `genclass-telemetry`, workers.dev route). The runtime's `DEFAULT_TELEMETRY_ENDPOINT` is this URL + `/v1/events`. +- **Storage:** R2 bucket `genclass-telemetry`, one gzip JSON Lines object per accepted batch at + `events/dt=YYYY-MM-DD/rt=/model=/.jsonl.gz` (date = server UTC date). + Each line is `{ sid, runtime, model, sent, receivedAt, country, event }`. +- **Retention:** not set yet (owner decision, `OPEN_TASKS.md`). Add an R2 lifecycle rule once decided, e.g. + `npx --yes wrangler@4 r2 bucket lifecycle add genclass-telemetry expire-events events/ --expire-days `. + +## Routes + +| route | behaviour | +|---|---| +| `POST /v1/events` | body `{ schema: "genclass-telemetry/1", sid, sent, runtime, model, events: [{ t, ... }] }`; content-type `application/json` or `text/plain` (sendBeacon / no CORS preflight). 202 `{ ok, accepted }`; 400 bad shape/JSON; 413 over 256 KB; 415 other content type; 503 R2 failure | +| `OPTIONS /v1/events` | CORS preflight (`access-control-allow-origin: *`) | +| `GET /v1/health` | `{ ok: true, schema }` | + +Limits: 256 KB body, 500 events per batch, `sid` 8-64 chars `[A-Za-z0-9_-]`, every event an object with a string `t`. +Unknown top-level fields are dropped. Event objects are stored as sent (the client defines them). + +## Privacy invariants + +The worker never stores or logs the client IP, user agent, cookies or any other request header. The only server +additions are `receivedAt` (ISO time) and `country` (Cloudflare's two-letter `request.cf.country`; null if absent). +Workers observability/logs are disabled in `wrangler.toml`. `test/index.test.ts` asserts that headers and the city never +reach the stored object. + +## Develop / deploy + +```sh +cd telemetry-worker +../node_modules/.bin/vitest run --root . # unit tests (Node; R2 mocked) +npx --yes wrangler@4 deploy # deploy (needs wrangler login to the account above) +curl https://genclass-telemetry.mehar-144.workers.dev/v1/health +``` + +There is no `wrangler r2 object list`; list keys with the Cloudflare API +(`GET /client/v4/accounts//r2/buckets/genclass-telemetry/objects?prefix=events/`) or the dashboard, then +`npx --yes wrangler@4 r2 object get "genclass-telemetry/" --remote --file out.gz`. diff --git a/telemetry-worker/src/index.ts b/telemetry-worker/src/index.ts new file mode 100644 index 00000000..d7daa400 --- /dev/null +++ b/telemetry-worker/src/index.ts @@ -0,0 +1,177 @@ +// GenClass telemetry collector: a Cloudflare Worker that accepts batches from @genclass/runtime +// (packages/runtime/src/telemetry/*) and writes them, gzip-compressed JSON Lines, to R2. +// +// Privacy invariants (packages/runtime/TELEMETRY.md): +// - Never store the client IP, user agent, cookies or any request header. The only server-side additions are +// `receivedAt` (ISO time) and `country` (Cloudflare's coarse two-letter `request.cf.country`). +// - Only the known top-level batch fields are kept; anything else is dropped. +// - Nothing from the request is logged (wrangler.toml disables observability). +// +// Routes: POST /v1/events (application/json or text/plain, so navigator.sendBeacon needs no CORS preflight), +// OPTIONS /v1/events (CORS preflight), GET /v1/health. + +export const SCHEMA = "genclass-telemetry/1"; +export const MAX_BODY_BYTES = 256 * 1024; +export const MAX_EVENTS = 500; + +/** The subset of the R2 binding this worker uses (avoids a dependency on @cloudflare/workers-types). */ +export interface BucketLike { + put(key: string, value: ArrayBuffer | Uint8Array, options?: { httpMetadata?: Record }): Promise; +} + +export interface Env { + BUCKET: BucketLike; +} + +const CORS: Record = { + "access-control-allow-origin": "*", + "access-control-allow-methods": "POST, GET, OPTIONS", + "access-control-allow-headers": "content-type", + "access-control-max-age": "86400", +}; + +function reply(status: number, body: unknown): Response { + return new Response(body === null ? null : JSON.stringify(body), { + status, + headers: { ...CORS, "content-type": "application/json", "cache-control": "no-store" }, + }); +} + +/** Path-segment-safe version label: `[A-Za-z0-9._+-]`, at most 40 chars, else `fallback`. */ +export function pathLabel(v: unknown, fallback: string): string { + if (typeof v !== "string") return fallback; + const s = v.trim(); + return /^[A-Za-z0-9._+-]{1,40}$/.test(s) ? s : fallback; +} + +export interface Batch { + schema: string; + sid: string; + sent: number; + runtime: string; + model: string | null; + events: Record[]; +} + +/** Validate a parsed body. Returns the normalised batch (unknown top-level fields dropped) or an error string. */ +export function validate(body: unknown): Batch | string { + if (body === null || typeof body !== "object" || Array.isArray(body)) return "body must be a JSON object"; + const b = body as Record; + if (b.schema !== SCHEMA) return `schema must be "${SCHEMA}"`; + if (typeof b.sid !== "string" || !/^[A-Za-z0-9_-]{8,64}$/.test(b.sid)) return "sid must be 8-64 chars [A-Za-z0-9_-]"; + if (typeof b.sent !== "number" || !Number.isFinite(b.sent)) return "sent must be a finite number"; + if (typeof b.runtime !== "string" || b.runtime.length === 0 || b.runtime.length > 40) return "runtime must be a version string"; + if (b.model !== null && b.model !== undefined && (typeof b.model !== "string" || b.model.length > 80)) { + return "model must be a string or null"; + } + if (!Array.isArray(b.events)) return "events must be an array"; + if (b.events.length === 0) return "events must not be empty"; + if (b.events.length > MAX_EVENTS) return `at most ${MAX_EVENTS} events per batch`; + for (const e of b.events) { + if (e === null || typeof e !== "object" || Array.isArray(e)) return "each event must be an object"; + const t = (e as Record).t; + if (typeof t !== "string" || t.length === 0 || t.length > 32) return "each event needs a string type `t`"; + } + return { + schema: SCHEMA, + sid: b.sid, + sent: b.sent, + runtime: b.runtime, + model: typeof b.model === "string" ? b.model : null, + events: b.events as Record[], + }; +} + +async function gzip(text: string): Promise { + const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +/** Read the body with a hard byte cap (the Content-Length header may be absent or wrong). */ +async function readCapped(request: Request, cap: number): Promise { + const declared = Number(request.headers.get("content-length")); + if (Number.isFinite(declared) && declared > cap) return null; + if (!request.body) return new Uint8Array(0); + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > cap) { + try { await reader.cancel(); } catch { /* ignore */ } + return null; + } + chunks.push(value); + } + const out = new Uint8Array(total); + let o = 0; + for (const c of chunks) { out.set(c, o); o += c.byteLength; } + return out; +} + +export interface HandleOptions { + /** Injected for tests. */ + now?: () => Date; + uuid?: () => string; +} + +export async function handle(request: Request, env: Env, opts: HandleOptions = {}): Promise { + const url = new URL(request.url); + const path = url.pathname.replace(/\/+$/, ""); + + if (path === "/v1/health" && (request.method === "GET" || request.method === "HEAD")) { + return reply(200, { ok: true, schema: SCHEMA }); + } + if (path !== "/v1/events") return reply(404, { ok: false, error: "not found" }); + if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: CORS }); + if (request.method !== "POST") return reply(405, { ok: false, error: "method not allowed" }); + + const ct = (request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase(); + if (ct !== "application/json" && ct !== "text/plain") { + return reply(415, { ok: false, error: "content-type must be application/json or text/plain" }); + } + + const raw = await readCapped(request, MAX_BODY_BYTES); + if (raw === null) return reply(413, { ok: false, error: `body over ${MAX_BODY_BYTES} bytes` }); + + let parsed: unknown; + try { + parsed = JSON.parse(new TextDecoder().decode(raw)); + } catch { + return reply(400, { ok: false, error: "invalid JSON" }); + } + const batch = validate(parsed); + if (typeof batch === "string") return reply(400, { ok: false, error: batch }); + + const now = (opts.now ?? (() => new Date()))(); + const receivedAt = now.toISOString(); + // Coarse country only; never the IP, colo, city, ASN or any header. + const cf = (request as unknown as { cf?: { country?: unknown } }).cf; + const country = typeof cf?.country === "string" && /^[A-Z0-9]{2}$/.test(cf.country) ? cf.country : null; + + const meta = { sid: batch.sid, runtime: batch.runtime, model: batch.model, sent: batch.sent, receivedAt, country }; + const lines = batch.events.map((event) => JSON.stringify({ ...meta, event })).join("\n") + "\n"; + + const dt = receivedAt.slice(0, 10); + const rt = pathLabel(batch.runtime, "unknown"); + const model = pathLabel(batch.model, "none"); + const id = (opts.uuid ?? (() => crypto.randomUUID()))(); + const key = `events/dt=${dt}/rt=${rt}/model=${model}/${id}.jsonl.gz`; + + try { + await env.BUCKET.put(key, await gzip(lines), { + httpMetadata: { contentType: "application/gzip" }, + }); + } catch { + return reply(503, { ok: false, error: "storage unavailable" }); + } + return reply(202, { ok: true, accepted: batch.events.length }); +} + +export default { + fetch(request: Request, env: Env): Promise { + return handle(request, env).catch(() => reply(500, { ok: false, error: "internal error" })); + }, +}; diff --git a/telemetry-worker/test/index.test.ts b/telemetry-worker/test/index.test.ts new file mode 100644 index 00000000..f397a39a --- /dev/null +++ b/telemetry-worker/test/index.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { gunzipSync } from "node:zlib"; +import { handle, MAX_BODY_BYTES, MAX_EVENTS, validate } from "../src/index.js"; + +function bucket() { + const puts: { key: string; body: Uint8Array }[] = []; + return { + puts, + BUCKET: { + async put(key: string, value: ArrayBuffer | Uint8Array) { + puts.push({ key, body: value instanceof Uint8Array ? value : new Uint8Array(value) }); + }, + }, + }; +} + +const batch = (over: Record = {}) => ({ + schema: "genclass-telemetry/1", + sid: "abcdEFGH12345678", + sent: 1000, + runtime: "0.1.0-beta.3", + model: "0.1.0", + events: [{ t: "session", seq: 0 }, { t: "decision", seq: 1, situation: "x" }], + ...over, +}); + +function post(body: string, headers: Record = { "content-type": "text/plain;charset=UTF-8" }) { + const r = new Request("https://c.example/v1/events", { method: "POST", body, headers }); + Object.defineProperty(r, "cf", { value: { country: "CA", city: "Toronto", asn: 1 } }); + return r; +} + +const opts = { now: () => new Date("2026-10-08T12:00:00Z"), uuid: () => "u-1" }; + +describe("collector", () => { + it("health", async () => { + const res = await handle(new Request("https://c.example/v1/health"), bucket(), opts); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ ok: true }); + }); + + it("stores a valid batch as gzip JSONL with receivedAt and country only, dropping unknown fields", async () => { + const env = bucket(); + const req = post(JSON.stringify(batch({ extra: "drop me" })), { + "content-type": "text/plain", + "user-agent": "UA-SECRET", + cookie: "c=SECRET", + "x-forwarded-for": "1.2.3.4", + }); + const res = await handle(req, env, opts); + expect(res.status).toBe(202); + expect(res.headers.get("access-control-allow-origin")).toBe("*"); + expect(env.puts).toHaveLength(1); + expect(env.puts[0]!.key).toBe("events/dt=2026-10-08/rt=0.1.0-beta.3/model=0.1.0/u-1.jsonl.gz"); + const text = gunzipSync(env.puts[0]!.body).toString("utf8"); + expect(text).not.toMatch(/SECRET|1\.2\.3\.4|drop me|Toronto/); + const lines = text.trim().split("\n").map((l) => JSON.parse(l)); + expect(lines).toHaveLength(2); + expect(lines[0]).toEqual({ + sid: "abcdEFGH12345678", runtime: "0.1.0-beta.3", model: "0.1.0", sent: 1000, + receivedAt: "2026-10-08T12:00:00.000Z", country: "CA", event: { t: "session", seq: 0 }, + }); + }); + + it("accepts application/json and sanitises path labels", async () => { + const env = bucket(); + const res = await handle(post(JSON.stringify(batch({ runtime: "../evil", model: null })), { "content-type": "application/json" }), env, opts); + expect(res.status).toBe(202); + expect(env.puts[0]!.key).toBe("events/dt=2026-10-08/rt=unknown/model=none/u-1.jsonl.gz"); + }); + + it("rejects oversized, malformed and wrong content types", async () => { + const env = bucket(); + const big = JSON.stringify(batch({ events: [{ t: "x", pad: "a".repeat(MAX_BODY_BYTES) }] })); + expect((await handle(post(big), env, opts)).status).toBe(413); + expect((await handle(post("{not json"), env, opts)).status).toBe(400); + expect((await handle(post(JSON.stringify(batch({ schema: "v0" }))), env, opts)).status).toBe(400); + expect((await handle(post(JSON.stringify(batch({ events: [] }))), env, opts)).status).toBe(400); + expect((await handle(post(JSON.stringify(batch({ events: [{ nope: 1 }] }))), env, opts)).status).toBe(400); + expect((await handle(post("{}", { "content-type": "application/x-www-form-urlencoded" }), env, opts)).status).toBe(415); + expect(env.puts).toHaveLength(0); + }); + + it("caps events per batch", () => { + const events = Array.from({ length: MAX_EVENTS + 1 }, () => ({ t: "x" })); + expect(validate(batch({ events }))).toMatch(/at most/); + expect(typeof validate(batch({ events: events.slice(1) }))).toBe("object"); + }); + + it("answers CORS preflight", async () => { + const res = await handle(new Request("https://c.example/v1/events", { method: "OPTIONS" }), bucket(), opts); + expect(res.status).toBe(204); + expect(res.headers.get("access-control-allow-origin")).toBe("*"); + }); +}); diff --git a/telemetry-worker/vitest.config.ts b/telemetry-worker/vitest.config.ts new file mode 100644 index 00000000..8871f0ea --- /dev/null +++ b/telemetry-worker/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["test/**/*.test.ts"], environment: "node" } }); diff --git a/telemetry-worker/wrangler.toml b/telemetry-worker/wrangler.toml new file mode 100644 index 00000000..a86dadfe --- /dev/null +++ b/telemetry-worker/wrangler.toml @@ -0,0 +1,16 @@ +# GenClass telemetry collector (Cloudflare Worker + R2). +# Deploy: npx --yes wrangler@4 deploy (from this directory) +name = "genclass-telemetry" +main = "src/index.ts" +compatibility_date = "2026-09-01" +account_id = "144bd5f5270b51dbe7faf46227a154f0" +workers_dev = true +# Never log request contents: no observability/logpush of request bodies or headers. +logpush = false + +[observability] +enabled = false + +[[r2_buckets]] +binding = "BUCKET" +bucket_name = "genclass-telemetry" From 28b797642b8ece72c41d100ed3a31172afe38633 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 23:29:32 -0400 Subject: [PATCH 23/25] runtime: default-on anonymous telemetry (InitOptions.telemetry) GenClass.init() in a browser now sends anonymous diagnostics to the genclass-telemetry collector (DEFAULT_TELEMETRY_ENDPOINT): a session event (versions, mode, aggressiveness, device class, model load, host and id-normalised route), every decision (trigger, the redacted situation text the model read, calibrated answers, diagnosis, gate threshold/source, what ran, latency, held/background), action outcomes (applied, failed, undone, late revert, veto), detections, model status/errors, fail-open counts and periodic summaries. One console notice per page. Off with telemetry:false, ?genclass=no-telemetry or ?genclass=off, localStorage "genclass.telemetry"="off", Global Privacy Control, sampling, in Node/SSR and in createRuntime() unless explicitly enabled. Random per-page session id (crypto.getRandomValues, not persisted). Transport is the fetch/sendBeacon captured at module load (never observed by GenClass), text/plain + keepalive, no credentials/referrer, <=60 KB per request, bounded queue (1000), failures dropped, never throws. Read-only on the runtime: rt.on listeners plus RuntimeImpl.tap (model errors, fail-opens) and decisionInfo(); no model-visible text changes. realapps harness passes telemetry:false. New test/telemetry.test.ts. Co-Authored-By: Claude Opus 5.5 --- packages/runtime/src/cdn/config.ts | 6 +- packages/runtime/src/index.ts | 27 +- packages/runtime/src/runtime.ts | 67 ++- packages/runtime/src/telemetry/client.ts | 582 ++++++++++++++++++++ packages/runtime/src/telemetry/config.ts | 113 ++++ packages/runtime/src/telemetry/index.ts | 42 ++ packages/runtime/src/telemetry/transport.ts | 54 ++ packages/runtime/src/types.ts | 45 ++ packages/runtime/src/version.ts | 4 + packages/runtime/test/telemetry.test.ts | 346 ++++++++++++ realapps/src/world/index.ts | 4 +- 11 files changed, 1282 insertions(+), 8 deletions(-) create mode 100644 packages/runtime/src/telemetry/client.ts create mode 100644 packages/runtime/src/telemetry/config.ts create mode 100644 packages/runtime/src/telemetry/index.ts create mode 100644 packages/runtime/src/telemetry/transport.ts create mode 100644 packages/runtime/src/version.ts create mode 100644 packages/runtime/test/telemetry.test.ts diff --git a/packages/runtime/src/cdn/config.ts b/packages/runtime/src/cdn/config.ts index 2d4a766a..ee74b64d 100644 --- a/packages/runtime/src/cdn/config.ts +++ b/packages/runtime/src/cdn/config.ts @@ -9,7 +9,7 @@ // // Keys of the meta tag and data attributes: mode, model (a model directory URL, or "off"), device, preload, ort // (onnxruntime-web wasm directory), worker, report, debug, triage, devtools (bare / true, "local" = only on -// localhost, false, or a corner such as "bottom-left"). +// localhost, false, or a corner such as "bottom-left"), telemetry (off/false/no: no anonymous diagnostics). // // Trust: every `` in the document is read (head or body, first to last), and its keys can set // the mode and the model and onnxruntime-web URLs. That is deliberate (no build step needed), but on a page that @@ -106,6 +106,10 @@ export function fromPairs(pairs: Record): PageConfig { case "devtools": c.devtools = parseDevtools(lv); break; + case "telemetry": + // anonymous diagnostics (TELEMETRY.md): only an opt-out here; on is the GenClass.init default + if (isOff(lv)) c.telemetry = false; + break; } } if (modelOff) c.model = false; diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 5da785f7..c950a227 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -7,6 +7,8 @@ import type { Clock, CreateOptions, DecisionProvider, DeviceEnv, EvaluateRequest import { browserClock } from "./clock.js"; import { RuntimeImpl } from "./runtime.js"; import { createModelHost } from "./model/host.js"; +import { startTelemetry } from "./telemetry/index.js"; +import { telemetryOff } from "./telemetry/client.js"; export * from "./types.js"; export { browserClock } from "./clock.js"; @@ -32,6 +34,8 @@ export { stateText, stateChars, sectionLimits, STATE_CHAR_BUDGET, COMPACT_BUDGET export { BUILTIN_ACTIONS, TRIGGER_ACTIONS, PASSIVE, DEFAULT_DIAGNOSES } from "./situation/questions.js"; export { describeElement } from "./observe/dom-user.js"; export { RuntimeImpl } from "./runtime.js"; +export { DEFAULT_TELEMETRY_ENDPOINT, TELEMETRY_SCHEMA, TELEMETRY_NOTICE } from "./telemetry/index.js"; +export { RUNTIME_VERSION } from "./version.js"; /** fetch as it was when this module loaded: the model host downloads with it, so GenClass never observes itself. */ const NATIVE_FETCH: typeof fetch | undefined = @@ -174,7 +178,10 @@ export class IdleUnloadProvider implements DecisionProvider { } -/** Advanced/headless runtime (sim, tests, SSR). No model unless `model` options or a `decider` are given. */ +/** + * Advanced/headless runtime (sim, tests, SSR). No model unless `model` options or a `decider` are given. No + * telemetry unless `telemetry` is set (GenClass.init turns it on by default in a browser). + */ export function createRuntime(options: CreateOptions = {}): Runtime { let decider: DecisionProvider | null | undefined = options.decider; let owns = false; @@ -184,7 +191,16 @@ export function createRuntime(options: CreateOptions = {}): Runtime { const nf = options.global ? (typeof g.fetch === "function" ? g.fetch.bind(g) : undefined) : NATIVE_FETCH; decider = makeHost(options.model, nf, options.clock, (options.global ?? globalThis) as never); } - return new RuntimeImpl({ ...options, decider: decider ?? null, ownsDecider: owns }); + const rt = new RuntimeImpl({ ...options, decider: decider ?? null, ownsDecider: owns }); + if (options.enabled === false) rt.telemetry = telemetryOff("disabled"); + else + rt.telemetry = startTelemetry(rt, options.telemetry, false, { + model: owns ? "local" : decider ? "custom" : "off", + ...(options.triage ? { triage: options.triage } : {}), + ...(options.shadow ? { shadow: options.shadow } : {}), + ...(options.policy?.holdWrites ? { holdWrites: true } : {}), + }); + return rt; } const MODES: readonly Mode[] = ["observe", "guard", "heal"]; @@ -235,7 +251,7 @@ export const GenClass = { } catch (e) { const g = globalThis as unknown as Record; (g.console as Console | undefined)?.warn?.(`[GenClass] Could not start (${(e as Error)?.message ?? e}); running without it.`); - current = createRuntime({ observe: ALL_OFF, decider: null, report: "silent", mode: "observe" }); + current = createRuntime({ observe: ALL_OFF, decider: null, report: "silent", mode: "observe", telemetry: false }); return current; } }, @@ -256,7 +272,8 @@ function initUnsafe(options: InitOptions): Runtime { const ks = killSwitch(g); if (ks === "off") { (g.console as Console | undefined)?.info?.('[GenClass] Disabled by ?genclass=off or localStorage.genclass = "off": nothing is installed.'); - current = createRuntime({ observe: ALL_OFF, model: false, decider: null, report: "silent", mode: "observe" }); + current = createRuntime({ observe: ALL_OFF, model: false, decider: null, report: "silent", mode: "observe", telemetry: false }); + (current as RuntimeImpl).telemetry = telemetryOff("kill-switch"); return current; } // the kill switch may only demote (OPTIONS-SPEC §3), unless debug @@ -270,6 +287,8 @@ function initUnsafe(options: InitOptions): Runtime { } const o: CreateOptions = { ...options }; if (mode) o.mode = mode; + // anonymous diagnostics: on by default in a browser (TELEMETRY.md); opt-outs are checked in resolveTelemetry + o.telemetry = options.telemetry ?? true; if (options.decider === undefined && options.model !== false && options.enabled !== false) { o.model = options.model ?? {}; // a dynamic enabled source: never download before it says on diff --git a/packages/runtime/src/runtime.ts b/packages/runtime/src/runtime.ts index 44cf6ef5..5f4cada4 100644 --- a/packages/runtime/src/runtime.ts +++ b/packages/runtime/src/runtime.ts @@ -1,6 +1,7 @@ // Runtime: wires trace, state, learn, situation and decide together (CONTRACT §2-§9). import type { + TelemetryStatus, ActionContext, ActionDef, AdapterHandle, @@ -116,6 +117,17 @@ interface ExplainRec { answers: Record; action?: ActionRecord; gates: EffectiveGates; + /** The subject waited for this decision (false: decided in the background). */ + held: boolean; + budget: number; + compact: boolean; +} + +/** 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> }; @@ -234,6 +246,11 @@ export class RuntimeImpl implements Runtime { private learnVersion: string | undefined; private reportMode: "console" | "interventions" | "silent" | "fn" = "console"; private uninstall: (() => void)[] = []; + private teardowns: (() => void)[] = []; + /** Telemetry observation points (src/telemetry). */ + tap: RuntimeTap | null = null; + /** runtime.telemetry (set by createRuntime). */ + telemetry?: TelemetryStatus; private plugins = new Map void }>(); private customActions: ActionDef[] = []; private standing: StandingQuestion[] = []; @@ -335,6 +352,11 @@ export class RuntimeImpl implements Runtime { // 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; @@ -1114,6 +1136,7 @@ export class RuntimeImpl implements Runtime { if (provider.status.state !== "ready") { // lazy preload: the first salient situation starts loading; this one fails open void this.ready; + this.tapFailOpen("not-ready", spec.trigger); return passive(); } // gate steps 1–3: protected, cross-origin or off/observe-scoped subjects are never acted on (nor held) @@ -1183,7 +1206,10 @@ export class RuntimeImpl implements Runtime { if (waits) this.sum.held(this.clock.now() - (opts.heldSince ?? t0)); try { if (this.destroyed) return passive(); - if (!res) return passive(); + if (!res) { + this.tapFailOpen("no-answer", spec.trigger); + return passive(); + } this.sum.decision(res.latencyMs); this.onDecision(built, res.answers, this.clock.now() - t0, ctl, passive, { waits, covers: background !== null, expired, passiveRan: () => passiveRan, hold: opts.hold, budget, block, subjectOp }); } finally { @@ -1194,6 +1220,7 @@ export class RuntimeImpl implements Runtime { .catch((e) => { this.log("decision failed", e); if (background) this.deliveryPending.delete(background); + this.tapFailOpen("error", spec.trigger); passive(); }); } @@ -1359,7 +1386,17 @@ export class RuntimeImpl implements Runtime { if (reason) decision.reason = reason; this.decisionsBuf.push(decision); if (this.decisionsBuf.length > DECISIONS_KEPT) this.decisionsBuf.shift(); - const rec: ExplainRec = { decision, situationText: stateText(built.situation.state), facts: built.situation.facts, timeline: built.parts.timeline, answers, gates }; + const rec: ExplainRec = { + decision, + situationText: stateText(built.situation.state), + facts: built.situation.facts, + timeline: built.parts.timeline, + answers, + gates, + held: st.waits, + budget: built.situation.budget, + compact: built.situation.compact, + }; this.explainMap.set(decision.id, rec); if (this.explainMap.size > DECISIONS_KEPT * 2) { const first = this.explainMap.keys().next().value; @@ -2806,6 +2843,25 @@ export class RuntimeImpl implements Runtime { return built.situation; } + /** Telemetry (src/telemetry): what explain() has plus whether the subject waited. Internal. */ + decisionInfo(id: string): { situationText: string; held: boolean; budget: number; compact: boolean; gates: EffectiveGates } | null { + const r = this.explainMap.get(id); + return r ? { situationText: r.situationText, held: r.held, budget: r.budget, compact: r.compact, gates: r.gates } : null; + } + + /** Run fn first when the runtime is destroyed (telemetry's final flush). Internal. */ + addTeardown(fn: () => void): void { + this.teardowns.push(fn); + } + + private tapFailOpen(reason: string, trigger: TriggerKind): void { + try { + this.tap?.failOpen?.(reason, trigger); + } catch { + /* telemetry never breaks the runtime */ + } + } + explain(id: string): Explanation | null { const r = this.explainMap.get(id); if (!r) return null; @@ -2861,6 +2917,13 @@ export class RuntimeImpl implements Runtime { destroy(): void { if (this.destroyed) return; + for (const t of this.teardowns.splice(0)) { + try { + t(); + } catch { + /* ignore */ + } + } this.destroyed = true; this.hub.gating = false; this.queue.dispose(); diff --git a/packages/runtime/src/telemetry/client.ts b/packages/runtime/src/telemetry/client.ts new file mode 100644 index 00000000..94298f58 --- /dev/null +++ b/packages/runtime/src/telemetry/client.ts @@ -0,0 +1,582 @@ +// Telemetry client: turns runtime events into genclass-telemetry/1 batches (packages/runtime/TELEMETRY.md). +// +// Invariants: +// - Read-only on the runtime: it listens (rt.on, rt.tap) and reads decisionInfo(); nothing it does feeds a +// decision or changes model input (situation-v2 freeze). The situation text it sends is the exact text built +// from the state the model received, after the redactor. +// - Never throws into the app or the runtime; failures drop the batch. Bounded queue (MAX_QUEUE events). +// - Timers come from the runtime's Clock; times are ms since this session started (no wall clock: the collector +// stamps receivedAt). The session id is random per page load and never stored. + +import type { RuntimeImpl } from "../runtime.js"; +import type { ActionRecord, Answer, Decision, ModelStatus, TelemetryStatus } from "../types.js"; +import { normalizePath } from "../util.js"; +import { RUNTIME_VERSION } from "../version.js"; +import { TELEMETRY_SCHEMA, type TelemetryConfig } from "./config.js"; + +export const MAX_QUEUE = 1000; +/** keepalive fetch and sendBeacon refuse bodies over 64 KiB. */ +export const MAX_REQUEST_BYTES = 60_000; +export const SUMMARY_MS = 60_000; +const MAX_ERROR_EVENTS = 20; + +type Ev = Record; +type Counts = Record; + +/** What createRuntime knows about the options (never their values beyond these names). */ +export interface TelemetrySessionInfo { + model: "local" | "custom" | "off"; + triage?: string; + shadow?: string | false; + holdWrites?: boolean; + install?: string; +} + +const r4 = (n: unknown): number | undefined => (typeof n === "number" && Number.isFinite(n) ? Math.round(n * 1e4) / 1e4 : undefined); +const cut = (s: unknown, n: number): string | undefined => (typeof s === "string" ? (s.length > n ? s.slice(0, n) : s) : undefined); +const inc = (c: Counts, k: string, by = 1) => { + c[k] = (c[k] ?? 0) + by; +}; + +function probs(p: Record | undefined): Record | undefined { + if (!p) return undefined; + const o: Record = {}; + for (const [k, v] of Object.entries(p)) o[k] = r4(v) ?? 0; + return o; +} + +function answersOut(a: Record): Record { + const out: Record = {}; + for (const [id, x] of Object.entries(a ?? {})) { + if (!x || typeof x !== "object") continue; + if (x.type === "noul") out[id] = { type: "noul", p: r4(x.noul) }; + else if (x.type === "choice") out[id] = { type: "choice", choice: x.choice, confidence: r4(x.confidence), probabilities: probs(x.probabilities) }; + else if (x.type === "score") out[id] = { type: "score", score: r4(x.score), confidence: r4(x.confidence), probabilities: probs(x.probabilities) }; + } + return out; +} + +function compact(o: Ev): Ev { + for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k]; + return o; +} + +export class TelemetryClient implements TelemetryStatus { + readonly enabled = true; + private queue: Ev[] = []; + private seq = 0; + private readonly t0: number; + private timer: unknown = null; + private stopped = false; + private lastSummaryAt: number; + private dirty = false; + private modelKey = ""; + private statusKey = ""; + private errorEvents = 0; + private dropped = 0; + private sendFailures = 0; + private sentEvents = 0; + private pending = new Set>(); + private offs: (() => void)[] = []; + private readonly c = { + decisions: 0, + acted: 0, + detections: 0, + actionsOk: 0, + actionsFailed: 0, + lateReverts: 0, + undos: 0, + vetoes: 0, + breakerTrips: 0, + byTrigger: {} as Counts, + byDiagnosis: {} as Counts, + byAction: {} as Counts, + detectionsByDiagnosis: {} as Counts, + limits: {} as Counts, + modelErrors: {} as Counts, + failOpen: {} as Counts, + }; + + constructor( + private readonly rt: RuntimeImpl, + private readonly cfg: TelemetryConfig, + private readonly g: Record, + info: TelemetrySessionInfo, + ) { + this.t0 = rt.clock.now(); + this.lastSummaryAt = this.t0; + this.session(info); + this.listen(); + } + + get endpoint(): string { + return this.cfg.endpoint; + } + get sessionId(): string { + return this.cfg.sessionId; + } + + // ------------------------------------------------------------------------------------------------ events + + private at(): number { + return Math.round(this.rt.clock.now() - this.t0); + } + + private push(e: Ev): void { + if (this.stopped) return; + if (this.queue.length >= MAX_QUEUE) { + this.dropped++; + return; + } + e.seq = this.seq++; + e.at = this.at(); + this.queue.push(compact(e)); + this.arm(); + } + + private route(): string | undefined { + try { + const p = (this.g.location as { pathname?: unknown } | undefined)?.pathname; + return typeof p === "string" ? cut(normalizePath(p), 200) : undefined; + } catch { + return undefined; + } + } + + private session(info: TelemetrySessionInfo): void { + const nav = (this.g.navigator ?? {}) as { gpu?: unknown; hardwareConcurrency?: unknown; deviceMemory?: unknown; connection?: { effectiveType?: unknown; saveData?: unknown } }; + let host: string | undefined; + try { + host = cut((this.g.location as { hostname?: unknown } | undefined)?.hostname, 253); + } catch { + /* no location */ + } + const st = this.rt.status; + this.modelKey = `${st.state}|${st.version ?? ""}`; + this.statusKey = this.statusKeyOf(st); + this.push({ + t: "session", + runtime: RUNTIME_VERSION, + host, + route: this.route(), + mode: this.rt.mode, + effectiveMode: st.effectiveMode, + aggressiveness: r4(this.rt.aggressiveness), + sampled: st.sampled, + model: info.model, + modelState: st.state, + modelVersion: st.version, + triage: info.triage, + shadow: info.shadow || undefined, + holdWrites: info.holdWrites || undefined, + install: info.install, + device: compact({ + webgpu: !!nav.gpu, + cores: typeof nav.hardwareConcurrency === "number" ? nav.hardwareConcurrency : undefined, + memoryGB: typeof nav.deviceMemory === "number" ? nav.deviceMemory : undefined, + crossOriginIsolated: typeof this.g.crossOriginIsolated === "boolean" ? this.g.crossOriginIsolated : undefined, + effectiveType: cut(nav.connection?.effectiveType, 16), + saveData: typeof nav.connection?.saveData === "boolean" ? nav.connection.saveData : undefined, + }), + sample: this.cfg.sample, + situation: this.cfg.situation, + }); + } + + private statusKeyOf(s: ModelStatus): string { + return `${this.rt.mode}|${s.effectiveMode ?? ""}|${this.rt.aggressiveness}|${s.breaker?.tripped ? 1 : 0}`; + } + + private onStatus(): void { + const s = this.rt.status; + const mk = `${s.state}|${s.version ?? ""}`; + if (mk !== this.modelKey) { + this.modelKey = mk; + this.push({ + t: "model", + state: s.state, + version: s.version, + model: cut(s.model, 80), + variant: cut(s.variant, 80), + device: s.device, + threads: s.threads, + worker: s.worker, + workerError: cut(s.workerError, 200), + gpu: cut(s.gpu, 120), + ort: cut(s.ort, 40), + loadMs: typeof s.loadMs === "number" ? Math.round(s.loadMs) : undefined, + warmupMs: typeof s.warmupMs === "number" ? Math.round(s.warmupMs) : undefined, + fromCache: s.fromCache, + bytes: s.bytes, + phase: s.phase, + reason: cut(s.reason, 120), + error: cut(s.error, 200), + attempts: Array.isArray(s.attempts) ? s.attempts.slice(0, 6).map((a) => ({ variant: cut(a.variant, 80), device: cut(a.device, 16), error: cut(a.error, 160) })) : undefined, + }); + } + const sk = this.statusKeyOf(s); + if (sk !== this.statusKey) { + this.statusKey = sk; + this.push({ t: "status", mode: this.rt.mode, effectiveMode: s.effectiveMode, aggressiveness: r4(this.rt.aggressiveness), breaker: !!s.breaker?.tripped }); + } + } + + private onDecide(d: Decision): void { + this.dirty = true; + const c = this.c; + c.decisions++; + inc(c.byTrigger, d.trigger); + inc(c.byDiagnosis, d.diagnosis); + inc(c.byAction, d.ran); + const acted = d.executed && d.tier !== "passive"; + if (acted) c.acted++; + const info = this.rt.decisionInfo(d.id); + const gates = info?.gates; + this.push({ + t: "decision", + id: d.id, + trigger: d.trigger, + route: this.route(), + model: cut(d.model, 80), + latencyMs: Math.round(d.latencyMs), + held: info?.held, + situation: this.cfg.situation ? info?.situationText : undefined, + budget: info?.budget, + compact: info?.compact, + questions: Object.keys(d.answers ?? {}), + answers: answersOut(d.answers), + diagnosis: d.diagnosis, + diagnosisConfidence: r4(d.diagnosisConfidence), + action: d.action, + confidence: r4(d.confidence), + tier: d.tier, + candidate: d.candidate, + ran: d.ran, + executed: d.executed, + acted, + reason: cut(d.reason, 120), + mass: r4(d.mass), + gateKind: d.gateKind, + threshold: r4(d.threshold), + gain: r4(d.gain), + margin: r4(d.margin), + thresholdSource: d.thresholdSource, + gates: gates + ? compact({ report: r4(gates.report), guard: r4(gates.guard), heal: r4(gates.heal), aggressiveness: r4(gates.aggressiveness), level: gates.level, levelSource: gates.levelSource, source: gates.source }) + : undefined, + effectiveMode: d.effectiveMode, + shadow: d.shadow ? compact({ action: d.shadow.action, tier: d.shadow.tier, wouldPass: d.shadow.wouldPass, reason: cut(d.shadow.reason, 120) }) : undefined, + }); + if (d.reason === "vetoed" || d.reason === "would-veto") { + c.vetoes++; + this.push({ t: "veto", decision: d.id, action: d.candidate ?? d.action, enforced: d.reason === "vetoed" }); + } + } + + private onDetect(d: Decision): void { + this.dirty = true; + this.c.detections++; + inc(this.c.detectionsByDiagnosis, d.diagnosis); + this.push({ t: "detect", decision: d.id, trigger: d.trigger, diagnosis: d.diagnosis, p: r4(d.diagnosisConfidence) }); + } + + private onAct(a: ActionRecord): void { + this.dirty = true; + if (a.ok) this.c.actionsOk++; + else this.c.actionsFailed++; + if (a.late) this.c.lateReverts++; + // never the error message or the changed sentence (app text); only what happened + this.push({ + t: "action", + id: a.id, + decision: a.decisionId, + action: a.action, + tier: a.tier, + trigger: a.trigger, + outcome: a.ok ? "applied" : "failed", + late: a.late || undefined, + reversible: typeof a.undo === "function", + droppedFields: Array.isArray(a.dropped) ? a.dropped.length : undefined, + }); + } + + private listen(): void { + const rt = this.rt; + const safe = + (fn: (v: T) => void) => + (v: T) => { + try { + fn(v); + } catch { + /* telemetry never breaks the runtime */ + } + }; + this.offs.push(rt.on("decide", safe((d) => this.onDecide(d)))); + this.offs.push(rt.on("detect", safe((d) => this.onDetect(d)))); + this.offs.push(rt.on("act", safe((a) => this.onAct(a)))); + this.offs.push(rt.on("status", safe(() => this.onStatus()))); + this.offs.push( + rt.on( + "report", + safe((r) => { + if (r.kind === "undo" && r.action) { + this.dirty = true; + this.c.undos++; + this.push({ t: "action", id: r.action.id, decision: r.action.decisionId, action: r.action.action, tier: r.action.tier, trigger: r.action.trigger, outcome: "undone" }); + } + }), + ), + ); + this.offs.push( + rt.on( + "breaker", + safe((b) => { + this.dirty = true; + if (b.tripped) this.c.breakerTrips++; + this.push({ t: "breaker", tripped: b.tripped, reason: b.reason, undos: b.counts.undos, errors: b.counts.errors, decisions: b.decisionIds.slice(0, 20) }); + }), + ), + ); + this.offs.push( + rt.on( + "limit", + safe((l) => { + this.dirty = true; + inc(this.c.limits, l.kind); + }), + ), + ); + const prevTap = rt.tap; + rt.tap = { + modelError: (e) => { + try { + prevTap?.modelError?.(e); + } catch { + /* ignore */ + } + this.dirty = true; + const err = e as { code?: unknown; name?: unknown; message?: unknown } | null; + const code = cut(typeof err?.code === "string" ? err.code : typeof err?.name === "string" ? err.name : "error", 40) ?? "error"; + inc(this.c.modelErrors, code); + if (this.errorEvents++ < MAX_ERROR_EVENTS) this.push({ t: "model-error", code, message: cut(typeof err?.message === "string" ? err.message : String(e), 200) }); + }, + failOpen: (reason, trigger) => { + try { + prevTap?.failOpen?.(reason, trigger); + } catch { + /* ignore */ + } + this.dirty = true; + inc(this.c.failOpen, `${reason}:${trigger}`); + }, + }; + this.offs.push(() => { + rt.tap = prevTap; + }); + // page exit: summary + beacon + const g = this.g as { addEventListener?: (t: string, fn: () => void) => void; removeEventListener?: (t: string, fn: () => void) => void; document?: unknown }; + const doc = g.document as (EventTarget & { visibilityState?: string }) | undefined; + const onHide = () => { + try { + if (doc?.visibilityState !== "hidden") return; + this.summary("hidden"); + void this.flush(true); + } catch { + /* ignore */ + } + }; + const onPageHide = () => { + try { + this.summary("pagehide"); + void this.flush(true); + } catch { + /* ignore */ + } + }; + try { + if (typeof g.addEventListener === "function") { + g.addEventListener("pagehide", onPageHide); + this.offs.push(() => g.removeEventListener?.("pagehide", onPageHide)); + } + if (doc && typeof doc.addEventListener === "function") { + doc.addEventListener("visibilitychange", onHide); + this.offs.push(() => doc.removeEventListener("visibilitychange", onHide)); + } + } catch { + /* ignore */ + } + rt.addTeardown(() => this.stop()); + } + + // ------------------------------------------------------------------------------------------ summary, send + + /** Queue a summary event (counts since the session started). */ + summary(reason: "periodic" | "hidden" | "pagehide" | "destroy"): void { + if (this.stopped) return; + this.dirty = false; + this.lastSummaryAt = this.rt.clock.now(); + let rs: ReturnType | undefined; + try { + rs = this.rt.summary(); + } catch { + /* ignore */ + } + const c = this.c; + this.push({ + t: "summary", + reason, + counts: { + decisions: c.decisions, + acted: c.acted, + detections: c.detections, + actionsOk: c.actionsOk, + actionsFailed: c.actionsFailed, + lateReverts: c.lateReverts, + undos: c.undos, + vetoes: c.vetoes, + breakerTrips: c.breakerTrips, + byTrigger: { ...c.byTrigger }, + byDiagnosis: { ...c.byDiagnosis }, + byAction: { ...c.byAction }, + detectionsByDiagnosis: { ...c.detectionsByDiagnosis }, + limits: { ...c.limits }, + modelErrors: { ...c.modelErrors }, + failOpen: { ...c.failOpen }, + }, + runtime: rs + ? { + model: compact({ state: rs.model.state, p50Ms: r4(rs.model.p50Ms), p95Ms: r4(rs.model.p95Ms), decisions: rs.model.decisions, dropped: rs.model.dropped, hiddenSkipped: rs.model.hiddenSkipped }), + heldMs: { total: Math.round(rs.heldMs.total), max: Math.round(rs.heldMs.max) }, + denied: { ...rs.denied }, + shadow: { ...rs.shadow }, + errors: rs.errors, + } + : undefined, + telemetry: { queued: this.queue.length, dropped: this.dropped, sendFailures: this.sendFailures, sentEvents: this.sentEvents }, + }); + } + + private arm(): void { + if (this.timer !== null || this.stopped) return; + try { + this.timer = this.rt.clock.setTimeout(() => { + this.timer = null; + if (this.dirty && this.rt.clock.now() - this.lastSummaryAt >= SUMMARY_MS) this.summary("periodic"); + void this.flush(false); + }, this.cfg.flushMs); + } catch { + this.timer = null; + } + } + + /** Send everything queued, in requests of ≤ maxBatch events and ≤ MAX_REQUEST_BYTES. Never rejects. */ + flush(beacon = false): Promise { + try { + if (this.timer !== null) { + this.rt.clock.clearTimeout(this.timer); + this.timer = null; + } + const sends: Promise[] = []; + while (this.queue.length) { + const parts: string[] = []; + let n = 0; + const head = this.header(); + let bytes = head.length + 2; + while (this.queue.length && n < this.cfg.maxBatch) { + let s: string; + try { + s = JSON.stringify(this.queue[0]); + } catch { + this.queue.shift(); + this.dropped++; + continue; + } + if (head.length + s.length + 2 > MAX_REQUEST_BYTES) { + // a single event too large for one request + this.queue.shift(); + this.dropped++; + continue; + } + if (bytes + s.length + 1 > MAX_REQUEST_BYTES) break; + this.queue.shift(); + parts.push(s); + bytes += s.length + 1; + n++; + } + if (!n) continue; + sends.push(this.send(`${head}${parts.join(",")}]}`, n, beacon)); + } + return Promise.all(sends).then(() => undefined); + } catch { + return Promise.resolve(); + } + } + + /** Batch envelope up to the events array. */ + private header(): string { + let model: string | null = null; + try { + model = this.rt.status.version ?? null; + } catch { + /* ignore */ + } + return `{"schema":${JSON.stringify(TELEMETRY_SCHEMA)},"sid":${JSON.stringify(this.cfg.sessionId)},"sent":${this.at()},"runtime":${JSON.stringify(RUNTIME_VERSION)},"model":${JSON.stringify(model)},"events":[`; + } + + private send(body: string, n: number, beacon: boolean): Promise { + let p: Promise; + try { + p = Promise.resolve(this.cfg.transport.send(this.cfg.endpoint, body, { beacon })).then( + () => { + this.sentEvents += n; + }, + () => { + this.sendFailures++; + }, + ); + } catch { + this.sendFailures++; + return Promise.resolve(); + } + this.pending.add(p); + void p.finally(() => this.pending.delete(p)); + return p; + } + + /** Final summary and flush (runtime destroyed). */ + stop(): void { + if (this.stopped) return; + try { + this.summary("destroy"); + void this.flush(false); + } catch { + /* ignore */ + } + this.stopped = true; + if (this.timer !== null) { + try { + this.rt.clock.clearTimeout(this.timer); + } catch { + /* ignore */ + } + this.timer = null; + } + for (const off of this.offs.splice(0)) { + try { + off(); + } catch { + /* ignore */ + } + } + } + + /** Requests still in flight (tests, e2e). */ + settled(): Promise { + return Promise.all([...this.pending]).then(() => undefined); + } +} + +/** runtime.telemetry when nothing is sent. */ +export function telemetryOff(reason: string): TelemetryStatus { + return { enabled: false, reason, flush: () => Promise.resolve() }; +} diff --git a/packages/runtime/src/telemetry/config.ts b/packages/runtime/src/telemetry/config.ts new file mode 100644 index 00000000..1e6f3da8 --- /dev/null +++ b/packages/runtime/src/telemetry/config.ts @@ -0,0 +1,113 @@ +// Telemetry configuration: defaults, opt-outs and sampling (packages/runtime/TELEMETRY.md). +// +// On by default only through GenClass.init() in a browser; createRuntime() and Node/SSR need an explicit option. +// Off, in this order: `telemetry: false`; `?genclass=no-telemetry` or `?genclass=off`; localStorage +// "genclass.telemetry" = "off"; Global Privacy Control (navigator.globalPrivacyControl === true, an opt-out of +// sale/sharing under CCPA/CPRA that we honour for all users); not sampled; no crypto.getRandomValues; no transport. + +import type { TelemetryOptions, TelemetryTransport } from "../types.js"; +import { nativeTransport, nativeTransportAvailable } from "./transport.js"; + +/** The GenClass collector (Cloudflare Worker `genclass-telemetry`, telemetry-worker/). */ +export const DEFAULT_TELEMETRY_ENDPOINT = "https://genclass-telemetry.mehar-144.workers.dev/v1/events"; +export const TELEMETRY_SCHEMA = "genclass-telemetry/1"; +export const TELEMETRY_NOTICE = + "[GenClass] Sends anonymous diagnostics (decisions, redacted situation text) to improve the model. Opt out: GenClass.init({ telemetry: false }) or ?genclass=no-telemetry."; + +export interface TelemetryConfig { + endpoint: string; + sample: number; + flushMs: number; + maxBatch: number; + situation: boolean; + transport: TelemetryTransport; + sessionId: string; +} + +export type TelemetryResolution = { on: true; config: TelemetryConfig } | { on: false; reason: string }; + +type G = Record; + +function urlOptOut(g: G): boolean { + try { + const search = (g.location as { search?: unknown } | undefined)?.search; + if (typeof search !== "string" || !search) return false; + return new URLSearchParams(search).getAll("genclass").some((v) => { + const s = v.trim().toLowerCase(); + return s === "no-telemetry" || s === "off"; + }); + } catch { + return false; + } +} + +function storageOptOut(g: G): boolean { + try { + const ls = g.localStorage as Storage | undefined; + const v = ls?.getItem("genclass.telemetry"); + return typeof v === "string" && v.trim().toLowerCase() === "off"; + } catch { + return false; + } +} + +function gpc(g: G): boolean { + try { + return (g.navigator as { globalPrivacyControl?: unknown } | undefined)?.globalPrivacyControl === true; + } catch { + return false; + } +} + +/** n random bytes from crypto.getRandomValues, or null (telemetry never falls back to Math.random). */ +export function randomBytes(g: G, n: number): Uint8Array | null { + try { + const c = g.crypto as { getRandomValues?: (a: Uint8Array) => Uint8Array } | undefined; + if (typeof c?.getRandomValues !== "function") return null; + return c.getRandomValues(new Uint8Array(n)); + } catch { + return null; + } +} + +const num = (v: unknown, lo: number, hi: number, d: number) => (typeof v === "number" && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d); + +/** + * Decide whether this page sends telemetry. `defaultOn`: GenClass.init in a browser. `g`: where the page's + * location / localStorage / navigator / crypto live (the runtime's global). + */ +export function resolveTelemetry(opt: boolean | TelemetryOptions | undefined, g: G, defaultOn: boolean): TelemetryResolution { + if (opt === false) return { on: false, reason: "option" }; + if (opt === undefined || opt === null) { + if (!defaultOn) return { on: false, reason: "headless" }; + } else if (opt !== true && typeof opt !== "object") return { on: false, reason: "option" }; + if (urlOptOut(g)) return { on: false, reason: "url" }; + if (storageOptOut(g)) return { on: false, reason: "localStorage" }; + if (gpc(g)) return { on: false, reason: "gpc" }; + const o: TelemetryOptions = typeof opt === "object" && opt ? opt : {}; + const sample = num(o.sample, 0, 1, 1); + // 16 random bytes: 12 for the session id, 4 for the sample draw + const rnd = randomBytes(g, 16); + if (!rnd) return { on: false, reason: "no-crypto" }; + if (sample < 1) { + const draw = ((rnd[12] << 24) | (rnd[13] << 16) | (rnd[14] << 8) | rnd[15]) >>> 0; + if (draw / 0x100000000 >= sample) return { on: false, reason: "sampled-out" }; + } + const transport = o.transport && typeof o.transport.send === "function" ? o.transport : nativeTransportAvailable() ? nativeTransport : null; + if (!transport) return { on: false, reason: "no-transport" }; + let sessionId = ""; + for (let i = 0; i < 12; i++) sessionId += rnd[i].toString(16).padStart(2, "0"); + const endpoint = typeof o.endpoint === "string" && /^https?:\/\//i.test(o.endpoint) ? o.endpoint : DEFAULT_TELEMETRY_ENDPOINT; + return { + on: true, + config: { + endpoint, + sample, + flushMs: num(o.flushMs, 1000, 600_000, 10_000), + maxBatch: Math.floor(num(o.maxBatch, 1, 500, 100)), + situation: o.include?.situation !== false, + transport, + sessionId, + }, + }; +} diff --git a/packages/runtime/src/telemetry/index.ts b/packages/runtime/src/telemetry/index.ts new file mode 100644 index 00000000..745883a5 --- /dev/null +++ b/packages/runtime/src/telemetry/index.ts @@ -0,0 +1,42 @@ +// Anonymous diagnostics (InitOptions.telemetry; packages/runtime/TELEMETRY.md). startTelemetry is called by +// createRuntime (src/index.ts) after the runtime is built. + +import type { RuntimeImpl } from "../runtime.js"; +import type { TelemetryOptions, TelemetryStatus } from "../types.js"; +import { TelemetryClient, telemetryOff, type TelemetrySessionInfo } from "./client.js"; +import { TELEMETRY_NOTICE, resolveTelemetry } from "./config.js"; + +export { DEFAULT_TELEMETRY_ENDPOINT, TELEMETRY_NOTICE, TELEMETRY_SCHEMA, resolveTelemetry } from "./config.js"; +export { TelemetryClient, MAX_QUEUE, MAX_REQUEST_BYTES } from "./client.js"; +export type { TelemetrySessionInfo } from "./client.js"; + +let noticeShown = false; + +/** Tests only: show the console notice again. */ +export function resetTelemetryNotice(): void { + noticeShown = false; +} + +export function startTelemetry( + rt: RuntimeImpl, + opt: boolean | TelemetryOptions | undefined, + defaultOn: boolean, + info: TelemetrySessionInfo, +): TelemetryStatus { + try { + const res = resolveTelemetry(opt, rt.global, defaultOn); + if (!res.on) return telemetryOff(res.reason); + const client = new TelemetryClient(rt, res.config, rt.global, info); + if (!noticeShown) { + noticeShown = true; + try { + ((rt.global.console as Console | undefined) ?? (globalThis as { console?: Console }).console)?.info?.(TELEMETRY_NOTICE); + } catch { + /* ignore */ + } + } + return client; + } catch { + return telemetryOff("error"); + } +} diff --git a/packages/runtime/src/telemetry/transport.ts b/packages/runtime/src/telemetry/transport.ts new file mode 100644 index 00000000..ee685788 --- /dev/null +++ b/packages/runtime/src/telemetry/transport.ts @@ -0,0 +1,54 @@ +// Telemetry transport: the page's fetch and navigator.sendBeacon as they were when this module loaded, so GenClass +// never observes (or holds, or decides about) its own diagnostics, exactly like the model host's downloads +// (index.ts -> NATIVE_FETCH). Never throws; failures are reported to the caller as a rejected promise only. + +import type { TelemetryTransport } from "../types.js"; + +const G = globalThis as unknown as Record; + +const NATIVE_FETCH: typeof fetch | undefined = typeof G.fetch === "function" ? (G.fetch as typeof fetch).bind(globalThis) : undefined; + +const NATIVE_BEACON: ((url: string, data?: BodyInit | null) => boolean) | undefined = (() => { + try { + const nav = G.navigator as { sendBeacon?: (url: string, data?: BodyInit | null) => boolean } | undefined; + return typeof nav?.sendBeacon === "function" ? nav.sendBeacon.bind(nav) : undefined; + } catch { + return undefined; + } +})(); + +/** Whether this environment can send at all (fetch or sendBeacon captured at module load). */ +export function nativeTransportAvailable(): boolean { + return !!NATIVE_FETCH || !!NATIVE_BEACON; +} + +/** + * The default transport. Bodies go as text/plain (a CORS "simple request": no preflight; the collector accepts it), + * without credentials or referrer. On page exit, sendBeacon; if the browser refuses it, fetch with keepalive. + */ +export const nativeTransport: TelemetryTransport = { + send(url: string, body: string, o: { beacon: boolean }): Promise { + try { + if (o.beacon && NATIVE_BEACON && NATIVE_BEACON(url, body)) return Promise.resolve(); + } catch { + /* fall back to fetch */ + } + if (!NATIVE_FETCH) return Promise.reject(new Error("no fetch")); + try { + return NATIVE_FETCH(url, { + method: "POST", + body, + headers: { "content-type": "text/plain;charset=UTF-8" }, + keepalive: true, + credentials: "omit", + mode: "cors", + referrerPolicy: "no-referrer", + cache: "no-store", + }).then((r) => { + if (!r.ok) throw new Error(`HTTP ${r.status}`); + }); + } catch (e) { + return Promise.reject(e); + } + }, +}; diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts index 68f82756..d0a19413 100644 --- a/packages/runtime/src/types.ts +++ b/packages/runtime/src/types.ts @@ -639,6 +639,49 @@ export interface InitOptions { * (webgpu 2,400; wasm 1,000 at 1 thread to 2,000 at 4 threads, linear; unknown device 2,400). */ situation?: { budget?: number | "auto" }; + /** + * Anonymous diagnostics sent to the GenClass maintainers to improve the model (packages/runtime/TELEMETRY.md): + * session info, every decision (trigger, the redacted situation text the model read, its calibrated answers, the + * gate and what ran), action outcomes, detections, model errors and periodic counts. Never raw input values, cookies, + * headers or storage. **Default: on with `GenClass.init()` in a browser** (one console notice per page); off in + * Node/SSR and with `createRuntime()` unless set here. Off with `false`, `?genclass=no-telemetry` (or `off`), + * `localStorage["genclass.telemetry"] = "off"`, or when the browser sends Global Privacy Control + * (`navigator.globalPrivacyControl === true`). + */ + telemetry?: boolean | TelemetryOptions; +} + +/** InitOptions.telemetry as an object (enables telemetry). */ +export interface TelemetryOptions { + /** Collector URL (default DEFAULT_TELEMETRY_ENDPOINT). */ + endpoint?: string; + /** Fraction of page sessions that send (0..1, default 1), drawn once per page load. */ + sample?: number; + /** Batch interval in ms (default 10,000). Batches are also sent on pagehide / when the tab is hidden. */ + flushMs?: number; + /** Max events per request (default 100; requests are also kept under 60 KB for keepalive/sendBeacon). */ + maxBatch?: number; + /** situation (default true): include the redacted situation text the model read in decision events. */ + include?: { situation?: boolean }; + /** Advanced (tests, custom pipelines): replaces the network transport. Errors are swallowed. */ + transport?: TelemetryTransport; +} + +export interface TelemetryTransport { + /** `beacon`: the page is going away (pagehide / hidden); prefer navigator.sendBeacon. */ + send(url: string, body: string, o: { beacon: boolean }): void | Promise; +} + +/** runtime.telemetry: whether this page sends diagnostics, and why not. */ +export interface TelemetryStatus { + readonly enabled: boolean; + /** Off: "option", "headless", "url", "localStorage", "gpc", "sampled-out", "no-crypto", "no-transport", "kill-switch". */ + readonly reason?: string; + readonly endpoint?: string; + /** Random per page load (not persisted). */ + readonly sessionId?: string; + /** Send what is queued now (resolves when the requests settle; never rejects). */ + flush(): Promise; } export interface CreateOptions extends InitOptions { @@ -974,4 +1017,6 @@ export interface Runtime { pause(): void; resume(): void; destroy(): void; + /** Anonymous diagnostics for this page (InitOptions.telemetry). */ + readonly telemetry?: TelemetryStatus; } diff --git a/packages/runtime/src/version.ts b/packages/runtime/src/version.ts new file mode 100644 index 00000000..e7b243ca --- /dev/null +++ b/packages/runtime/src/version.ts @@ -0,0 +1,4 @@ +// The package version, for telemetry batches and diagnostics. Kept equal to package.json "version" by +// test/telemetry.test.ts ("RUNTIME_VERSION matches package.json"); bump both together (RELEASE.md). + +export const RUNTIME_VERSION = "0.1.0-beta.2"; diff --git a/packages/runtime/test/telemetry.test.ts b/packages/runtime/test/telemetry.test.ts new file mode 100644 index 00000000..a34f6a47 --- /dev/null +++ b/packages/runtime/test/telemetry.test.ts @@ -0,0 +1,346 @@ +// Anonymous diagnostics (InitOptions.telemetry, TELEMETRY.md): defaults, opt-outs, batching, page exit, event +// shapes, the redacted situation text, transport failures, and that GenClass never observes its own requests. + +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { GenClass, createRuntime, DEFAULT_TELEMETRY_ENDPOINT, RUNTIME_VERSION, TELEMETRY_NOTICE } from "../src/index.js"; +import type { RuntimeImpl } from "../src/runtime.js"; +import { stateText } from "../src/situation/serialize.js"; +import { resetTelemetryNotice, resolveTelemetry, MAX_QUEUE } from "../src/telemetry/index.js"; +import type { TelemetryTransport } from "../src/types.js"; +import { FakeClock, defaultScript, setup } from "./helpers.js"; + +interface Sent { + url: string; + body: Record & { events: Record[] }; + beacon: boolean; +} + +function recorder(fail?: "throw" | "reject"): TelemetryTransport & { sent: Sent[] } { + const sent: Sent[] = []; + return { + sent, + send(url, body, o) { + sent.push({ url, body: JSON.parse(body), beacon: o.beacon }); + if (fail === "throw") throw new Error("offline"); + if (fail === "reject") return Promise.reject(new Error("HTTP 500")); + return Promise.resolve(); + }, + }; +} + +const events = (t: { sent: Sent[] }) => t.sent.flatMap((s) => s.body.events); +const ofType = (t: { sent: Sent[] }, type: string) => events(t).filter((e) => e.t === type); + +/** A headless runtime with telemetry explicitly on and an injected transport. */ +function tsetup(opts: Parameters[0] = {}, telemetry: Record = {}, fail?: "throw" | "reject") { + const transport = recorder(fail); + const s = setup({ ...opts, telemetry: { transport, ...telemetry }, extraGlobal: { crypto: globalThis.crypto, ...(opts.extraGlobal ?? {}) } }); + return { ...s, transport }; +} + +const noRandom = { getRandomValues: undefined }; + +describe("telemetry: defaults and opt-outs (TELEMETRY.md)", () => { + const g = globalThis as unknown as Record; + afterEach(() => { + GenClass.destroy(); + delete g.location; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it("RUNTIME_VERSION matches package.json", () => { + const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }; + expect(RUNTIME_VERSION).toBe(pkg.version); + }); + + it("off in createRuntime (headless) and in GenClass.init outside a browser unless enabled", () => { + const { rt } = setup(); + expect(rt.telemetry).toMatchObject({ enabled: false, reason: "headless" }); + const r = GenClass.init({ model: false, report: "silent", observe: { fetch: false, timers: false } }); + expect(r.telemetry).toMatchObject({ enabled: false, reason: "headless" }); + }); + + it("on by default in GenClass.init in a browser, with one console notice per page, to the default endpoint", async () => { + vi.resetModules(); + const sent: { url: string; init: RequestInit }[] = []; + const fake = vi.fn((url: string, init: RequestInit) => { + sent.push({ url, init }); + return Promise.resolve(new Response(null, { status: 202 })); + }); + vi.stubGlobal("fetch", fake); + vi.stubGlobal("window", {}); + vi.stubGlobal("document", {}); + const info = vi.spyOn(console, "info").mockImplementation(() => undefined); + const m = await import("../src/index.js"); + m.GenClass.destroy(); + const rt = m.GenClass.init({ model: false, report: "silent", observe: { fetch: false, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false } }); + expect(rt.telemetry?.enabled).toBe(true); + expect(info.mock.calls.filter((c) => c[0] === TELEMETRY_NOTICE)).toHaveLength(1); + expect(TELEMETRY_NOTICE).toBe( + "[GenClass] Sends anonymous diagnostics (decisions, redacted situation text) to improve the model. Opt out: GenClass.init({ telemetry: false }) or ?genclass=no-telemetry.", + ); + // a second runtime on the same page does not repeat the notice + const rt2 = m.createRuntime({ telemetry: true, decider: null, report: "silent", observe: { fetch: false, timers: false } }); + expect(info.mock.calls.filter((c) => c[0] === TELEMETRY_NOTICE)).toHaveLength(1); + rt2.destroy(); + await rt.telemetry!.flush(); + const mine = sent.filter((s) => s.url === m.DEFAULT_TELEMETRY_ENDPOINT); + expect(mine.length).toBeGreaterThan(0); + expect(m.DEFAULT_TELEMETRY_ENDPOINT).toBe("https://genclass-telemetry.mehar-144.workers.dev/v1/events"); + const req = mine[0].init; + expect(req.method).toBe("POST"); + expect(req.keepalive).toBe(true); + expect(req.credentials).toBe("omit"); + expect((req.headers as Record)["content-type"]).toMatch(/^text\/plain/); + const body = JSON.parse(String(req.body)); + expect(body).toMatchObject({ schema: "genclass-telemetry/1", runtime: RUNTIME_VERSION, model: null }); + expect(body.sid).toMatch(/^[0-9a-f]{24}$/); + expect(body.events[0]).toMatchObject({ t: "session", seq: 0, mode: "observe", model: "off" }); + m.GenClass.destroy(); + }); + + it("every opt-out: option, ?genclass=no-telemetry / off, localStorage, GPC, sample, no crypto", () => { + const base = { crypto: globalThis.crypto }; + const ls = (v: string | null) => ({ getItem: (k: string) => (k === "genclass.telemetry" ? v : null) }); + expect(resolveTelemetry(false, base, true)).toEqual({ on: false, reason: "option" }); + expect(resolveTelemetry(undefined, base, false)).toEqual({ on: false, reason: "headless" }); + expect(resolveTelemetry(undefined, { ...base, location: { search: "?genclass=no-telemetry" } }, true)).toEqual({ on: false, reason: "url" }); + expect(resolveTelemetry(true, { ...base, location: { search: "?genclass=guard&genclass=no-telemetry" } }, true)).toEqual({ on: false, reason: "url" }); + expect(resolveTelemetry(undefined, { ...base, location: { search: "?genclass=off" } }, true)).toEqual({ on: false, reason: "url" }); + expect(resolveTelemetry(undefined, { ...base, localStorage: ls("off") }, true)).toEqual({ on: false, reason: "localStorage" }); + expect(resolveTelemetry({}, { ...base, navigator: { globalPrivacyControl: true } }, true)).toEqual({ on: false, reason: "gpc" }); + expect(resolveTelemetry({ sample: 0 }, base, true)).toEqual({ on: false, reason: "sampled-out" }); + expect(resolveTelemetry(undefined, { crypto: noRandom }, true)).toEqual({ on: false, reason: "no-crypto" }); + // still on: GPC false, localStorage other values, sample 1, an unrelated genclass value + const on = resolveTelemetry({ sample: 1 }, { ...base, navigator: { globalPrivacyControl: false }, localStorage: ls("on"), location: { search: "?genclass=guard" } }, true); + expect(on.on).toBe(true); + if (on.on) expect(on.config).toMatchObject({ endpoint: DEFAULT_TELEMETRY_ENDPOINT, flushMs: 10_000, maxBatch: 100, situation: true, sample: 1 }); + }); + + it("opt-outs apply to createRuntime and GenClass.init too (GPC, ?genclass=off kill switch)", () => { + const { rt } = tsetup({ extraGlobal: { navigator: { globalPrivacyControl: true } } }); + expect(rt.telemetry).toMatchObject({ enabled: false, reason: "gpc" }); + const { rt: rt2, transport } = tsetup({}, { sample: 0 }); + expect(rt2.telemetry).toMatchObject({ enabled: false, reason: "sampled-out" }); + void rt2.telemetry!.flush(); + expect(transport.sent).toHaveLength(0); + vi.spyOn(console, "info").mockImplementation(() => undefined); + g.location = { search: "?genclass=off", href: "http://x/?genclass=off", pathname: "/" }; + const r = GenClass.init({ telemetry: true }); + expect(r.telemetry).toMatchObject({ enabled: false, reason: "kill-switch" }); + }); +}); + +describe("telemetry: batching, flush and page exit", () => { + it("batches on the flush interval, splits by maxBatch, and keeps a bounded queue", async () => { + const { rt, clock, transport } = tsetup({ triage: "always" }, { flushMs: 5000, maxBatch: 3 }); + expect(rt.telemetry?.enabled).toBe(true); + expect(transport.sent).toHaveLength(0); + const a = rt.atom("a", 1); + for (let i = 0; i < 3; i++) { + void rt.op("w", () => a.set(i + 2)); + await clock.advance(100); + } + expect(transport.sent).toHaveLength(0); + await clock.advance(5000); + const n = events(transport).length; + expect(n).toBeGreaterThanOrEqual(4); // session + 3 decisions + expect(transport.sent.every((s) => s.body.events.length <= 3)).toBe(true); + expect(transport.sent.every((s) => s.beacon === false && s.url === DEFAULT_TELEMETRY_ENDPOINT)).toBe(true); + const seqs = events(transport).map((e) => e.seq); + expect(seqs).toEqual([...seqs].sort((x, y) => (x as number) - (y as number))); + expect(new Set(transport.sent.map((s) => s.body.sid)).size).toBe(1); + // bounded: beyond MAX_QUEUE queued events new ones are dropped and counted + const client = rt.telemetry as unknown as { push(e: Record): void; summary(r: string): void }; + for (let i = 0; i < MAX_QUEUE + 5; i++) client.push({ t: "x" }); + await rt.telemetry!.flush(); + const before = transport.sent.length; + client.summary("periodic"); + await rt.telemetry!.flush(); + const sum = transport.sent.slice(before).flatMap((s) => s.body.events).find((e) => e.t === "summary") as { telemetry: { dropped: number } }; + expect(sum.telemetry.dropped).toBe(5); + }); + + it("pagehide sends a final summary with sendBeacon; a hidden tab flushes too", async () => { + const win = new EventTarget(); + const doc = Object.assign(new EventTarget(), { visibilityState: "visible" }); + const { rt, clock, transport } = tsetup({ triage: "always", extraGlobal: { addEventListener: win.addEventListener.bind(win), removeEventListener: win.removeEventListener.bind(win), document: doc } }); + const a = rt.atom("a", 1); + void rt.op("w", () => a.set(2)); + await clock.flush(); + doc.visibilityState = "hidden"; + doc.dispatchEvent(new Event("visibilitychange")); + await clock.flush(); + expect(transport.sent.at(-1)!.beacon).toBe(true); + expect(transport.sent.at(-1)!.body.events.at(-1)).toMatchObject({ t: "summary", reason: "hidden" }); + win.dispatchEvent(new Event("pagehide")); + await clock.flush(); + const last = transport.sent.at(-1)!; + expect(last.beacon).toBe(true); + const s = last.body.events.at(-1) as Record; + expect(s).toMatchObject({ t: "summary", reason: "pagehide" }); + expect(s.counts.decisions).toBe(1); + expect(s.counts.byTrigger).toEqual({ mutation: 1 }); + rt.destroy(); + expect(transport.sent.at(-1)!.body.events.at(-1)).toMatchObject({ t: "summary", reason: "destroy" }); + }); + + it("transport errors never reach the app: failures are counted and the batch dropped", async () => { + for (const fail of ["throw", "reject"] as const) { + const { rt, clock, transport } = tsetup({ triage: "always" }, {}, fail); + const a = rt.atom("a", 1); + void rt.op("w", () => a.set(2)); + await clock.flush(); + await expect(rt.telemetry!.flush()).resolves.toBeUndefined(); + await expect(rt.telemetry!.flush()).resolves.toBeUndefined(); + expect(a.get()).toBe(2); + (rt.telemetry as unknown as { summary(r: string): void }).summary("periodic"); + await rt.telemetry!.flush(); + const s = events(transport).filter((e) => e.t === "summary").at(-1) as { telemetry: { sendFailures: number } }; + expect(s.telemetry.sendFailures).toBeGreaterThanOrEqual(1); + expect(() => rt.destroy()).not.toThrow(); + } + }); +}); + +describe("telemetry: event shapes and the situation text", () => { + it("a decision carries the exact redacted situation text the model received, its answers and the gate", async () => { + const { rt, clock, transport, decider } = tsetup({ triage: "always", policy: { holdWrites: true }, script: defaultScript({ mutation: { diagnosis: "stale", action: "discard" } }) }); + const auth = rt.atom("auth", { user: "ada", password: "hunter2-secret", token: "tok-SECRET-123" }); + void rt.op("login", () => auth.set({ user: "bob", password: "correct-horse", token: "tok-SECRET-456" })); + await clock.flush(); + await rt.telemetry!.flush(); + const [d] = ofType(transport, "decision") as Record[]; + expect(decider.calls).toHaveLength(1); + expect(d.situation).toBe(stateText(decider.calls[0].state)); + expect(d.situation).toBe(rt.explain(d.id)!.situationText); + for (const secret of ["hunter2", "correct-horse", "SECRET"]) expect(JSON.stringify(transport.sent)).not.toContain(secret); + expect(d).toMatchObject({ + t: "decision", + trigger: "mutation", + route: "/search", + model: "scripted", + held: true, + diagnosis: "stale", + action: "discard", + ran: "discard", + executed: true, + acted: true, + tier: "guard", + gateKind: "mass", + threshold: 0.9, + thresholdSource: "default", + effectiveMode: "guard", + }); + expect(d.questions).toEqual(expect.arrayContaining(["diagnosis", "action"])); + expect(d.answers.diagnosis).toMatchObject({ type: "choice", choice: "stale" }); + expect(d.answers.action.probabilities.discard).toBe(0.97); + expect(typeof d.latencyMs).toBe("number"); + expect(d.gates).toMatchObject({ guard: 0.9, heal: 0.8 }); + const [det] = ofType(transport, "detect"); + expect(det).toMatchObject({ decision: d.id, trigger: "mutation", diagnosis: "stale", p: 0.97 }); + const [act] = ofType(transport, "action") as Record[]; + expect(act).toMatchObject({ decision: d.id, action: "discard", tier: "guard", trigger: "mutation", outcome: "applied", reversible: true }); + expect(act).not.toHaveProperty("error"); + // undo + rt.interventions()[0].undo!(); + await rt.telemetry!.flush(); + expect(ofType(transport, "action").at(-1)).toMatchObject({ outcome: "undone", action: "discard" }); + }); + + it("include.situation: false leaves the text out; vetoes, failures and late reverts are recorded", async () => { + const { rt, clock, transport } = tsetup( + { triage: "always", onBeforeAction: () => false, script: defaultScript({ mutation: { diagnosis: "stale", action: "discard" } }) }, + { include: { situation: false } }, + ); + const a = rt.atom("a", 1); + void rt.op("w", () => a.set(2)); + await clock.flush(); + await rt.telemetry!.flush(); + const [d] = ofType(transport, "decision"); + expect(d).not.toHaveProperty("situation"); + expect(d).toMatchObject({ reason: "vetoed", acted: false }); + expect(ofType(transport, "veto")[0]).toMatchObject({ decision: d.id, action: "discard", enforced: true }); + expect(ofType(transport, "session")[0]).toMatchObject({ situation: false, runtime: RUNTIME_VERSION, mode: "guard", model: "custom", route: "/search" }); + }); + + it("late reverts and model errors / fail-opens are counted", async () => { + const { rt, clock, transport } = tsetup({ triage: "always", script: defaultScript({ mutation: { diagnosis: "stale", action: "discard" } }) }); + const a = rt.atom("a", 1); + void rt.op("w", () => a.set(2)); + await clock.flush(); + await rt.telemetry!.flush(); + expect(ofType(transport, "action")[0]).toMatchObject({ outcome: "applied", late: true }); + + let n = 0; + const { rt: rt2, clock: c2, transport: t2 } = tsetup({ + triage: "always", + script: () => { + n++; + throw Object.assign(new Error("inference failed"), { code: "inference_failed" }); + }, + }); + const b = rt2.atom("b", 1); + void rt2.op("w", () => b.set(2)); + await c2.flush(); + expect(n).toBe(1); + (rt2.telemetry as unknown as { summary(r: string): void }).summary("periodic"); + await rt2.telemetry!.flush(); + expect(ofType(t2, "model-error")[0]).toMatchObject({ code: "inference_failed", message: "inference failed" }); + const s = ofType(t2, "summary").at(-1) as Record; + expect(s.counts.modelErrors).toEqual({ inference_failed: 1 }); + expect(s.counts.failOpen).toEqual({ "no-answer:mutation": 1 }); + expect(b.get()).toBe(2); + }); + + it("telemetry never changes what the model sees", async () => { + const run = async (telemetry: boolean) => { + const s = telemetry ? tsetup({ triage: "always" }) : setup({ triage: "always" }); + const a = s.rt.atom("cart", { items: 1, card: "4111111111111111" }); + void s.rt.op("add", () => a.set({ items: 2, card: "4111111111111111" })); + await s.clock.flush(); + return s.decider.calls.map((c) => JSON.stringify(c.state) + JSON.stringify(c.questions)); + }; + expect(await run(true)).toEqual(await run(false)); + }); +}); + +describe("telemetry: GenClass never observes its own requests", () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.resetModules(); + }); + + it("uses the fetch captured at module load, not the instrumented one", async () => { + vi.resetModules(); + const calls: string[] = []; + const fake = vi.fn((url: string) => { + calls.push(String(url)); + return Promise.resolve(new Response("{}", { status: 202, headers: { "content-type": "application/json" } })); + }); + vi.stubGlobal("fetch", fake); + resetTelemetryNotice(); + vi.spyOn(console, "info").mockImplementation(() => undefined); + const m = await import("../src/index.js"); + const clock = new FakeClock(); + const rt = m.createRuntime({ + clock, + decider: null, + report: "silent", + telemetry: { endpoint: "https://collector.test/v1/events" }, + observe: { fetch: true, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false }, + }) as RuntimeImpl; + expect((globalThis as { fetch: unknown }).fetch).not.toBe(fake); // instrumented by the runtime + await rt.telemetry!.flush(); + expect(calls).toEqual(["https://collector.test/v1/events"]); + expect(rt.history().filter((e) => e.kind === "op.start")).toHaveLength(0); + await (globalThis as { fetch: typeof fetch }).fetch("https://app.test/api/items"); + expect(rt.history().filter((e) => e.kind === "op.start").map((e) => e.name)).toEqual([expect.stringContaining("/api/items")]); + rt.destroy(); + vi.restoreAllMocks(); + }); +}); + +void createRuntime; diff --git a/realapps/src/world/index.ts b/realapps/src/world/index.ts index 4a4df082..8208dbca 100644 --- a/realapps/src/world/index.ts +++ b/realapps/src/world/index.ts @@ -61,11 +61,13 @@ declare global { const ALL_OFF = { fetch: false, xhr: false, user: false, errors: false, nav: false, storage: false, perf: false, websocket: false, timers: false }; w.__GENCLASS_INIT__ = cfg.ideal - ? { mode: "observe", model: false, decider: null, report: "silent", observe: ALL_OFF, hooks: probe.hooks(), plugins: [probe.plugin()] } + ? { mode: "observe", model: false, decider: null, report: "silent", telemetry: false, observe: ALL_OFF, hooks: probe.hooks(), plugins: [probe.plugin()] } : { mode: cfg.mode ?? "heal", decider: probe.decider(), report: "silent", + // harness runs are synthetic: never send them to the telemetry collector + telemetry: false, triage: "salient", observe: cfg.observe, policy: { thresholds: { report: 0, guard: 0.5, heal: 0.5 }, holdBudgetMs: 1e9, maxActionsPerMinute: 1e9, requireDiagnosis: false }, From 10fc607f643d32dc1b756b943b17ab66908a59c4 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 23:32:54 -0400 Subject: [PATCH 24/25] docs: disclose default-on telemetry (TELEMETRY.md, READMEs, CHANGELOG, agent docs) New packages/runtime/TELEMETRY.md: what is collected (exact event schema), where it is stored (Cloudflare Worker + private R2 bucket), retention TBD by the owner, opt-outs, Global Privacy Control, and what apps that ship GenClass may need to disclose under GDPR/CCPA. Both READMEs replace the "no app data leaves the browser / no telemetry" claims with a Privacy and telemetry section; API.md documents the option; CHANGELOG 0.1.0-beta.3 is flagged as a privacy-relevant change. Agent docs: docs/agents/telemetry.md, AGENTS.md (rule 9: telemetry conditions), status, repo map, router; OPEN_TASKS lists the owner decisions (retention, privacy policy page, data processing terms). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 17 ++- OPEN_TASKS.md | 13 +++ README.md | 22 ++++ docs/agents/README.md | 1 + docs/agents/repo-map.md | 1 + docs/agents/status-and-known-issues.md | 6 + docs/agents/telemetry.md | 93 ++++++++++++++++ docs/runtime/API.md | 21 +++- packages/genclass-runtime/README.md | 4 + packages/runtime/CHANGELOG.md | 26 +++++ packages/runtime/README.md | 55 +++++++-- packages/runtime/STATUS.md | 10 ++ packages/runtime/TELEMETRY.md | 147 +++++++++++++++++++++++++ 13 files changed, 402 insertions(+), 14 deletions(-) create mode 100644 docs/agents/telemetry.md create mode 100644 packages/runtime/TELEMETRY.md diff --git a/AGENTS.md b/AGENTS.md index 9fbaee53..09ffab09 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,11 @@ Root entry point for AI coding agents in GenClass-lib. / `remove` (`packages/runtime/bin/lib/*`), the zero-code import `@genclass/runtime/auto` (and `/auto/observe`, `/auto/guard`, `/auto/heal`; `packages/runtime/src/auto.ts`, `packages/runtime/src/cdn/auto-*.ts`) and a CDN script tag (`dist/genclass.global.min.js`; `packages/runtime/src/cdn/global.ts`). +- **Telemetry (since `0.1.0-beta.3`, owner decision 2026-10-09):** `GenClass.init()` in a browser sends anonymous + diagnostics by default (decisions with the redacted situation text, action outcomes, detections, model status, + counts) to the Cloudflare Worker in `telemetry-worker/` (R2 bucket `genclass-telemetry`). Client: + `packages/runtime/src/telemetry/*`; disclosure: `packages/runtime/TELEMETRY.md`; agent doc: + [docs/agents/telemetry.md](docs/agents/telemetry.md). Off in `createRuntime()`, Node/SSR and the realapps harness. - `sim/` generates training data by driving the real runtime. `realapps/` runs real framework apps in headless Chromium with the real runtime for real-browser training rows and the "never worse" sweep. `training/` trains and exports the model. `demos/` holds six evaluation apps. @@ -127,7 +132,13 @@ UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule s `packages/runtime/tsconfig.json` has `types: []`, so `src/` must not use Node APIs. 8. **Leave legacy content alone** (CONTRACT §1): `jev_local/`, `extension/`, `bench/`, `results/`, `tests/`, legacy `docs/*.md`, `docs/benchmax-research/`, legacy `scripts/`. Not covered: `docs/runtime/`, `docs/agents/`, `scripts/vm.sh`. -9. **REVIEW tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make them pass. Fix `src/`. +9. **Telemetry conditions (owner-agreed, binding).** Default-on telemetry must stay disclosed (console notice, + `TELEMETRY.md`, READMEs, CHANGELOG), send only redacted data the runtime already has (never raw input values of + password/payment/secret fields), keep its opt-outs (`telemetry: false`, `?genclass=no-telemetry|off`, + `localStorage["genclass.telemetry"]="off"`, GPC) and never feed a decision or change model input. The collector + never stores IP, user agent, cookies or headers. Widening what is sent needs the owner's OK. See + [docs/agents/telemetry.md](docs/agents/telemetry.md). +10. **REVIEW tests are a contract.** Never edit `packages/runtime/test/review-*.test.ts` to make them pass. Fix `src/`. ## 4. Where to run things @@ -138,7 +149,8 @@ UI, SIM, REAL, DEMOS, TRAIN, REVIEW) belong to the original team. Where a rule s (`sim/scripts/*`, `gen.js`), training (`training/*.sh`, any Python training or eval), realapps runs (`gen.js`, `debug.js`, `realapps/scripts/*`), the install test suite (`packages/runtime/test/install/run-all.sh`, `scaffold.sh`, `frameworks.mjs`, `cdn-check.mjs`: real framework scaffolds, package managers, Chromium; written for the VM), the - demos' eval, model downloads (`genclass-runtime fetch-model`), **anything on + demos' eval, model downloads (`genclass-runtime fetch-model`), deploying `telemetry-worker/` or touching the R2 + telemetry data, **anything on Azure** (`scripts/*.sh`, `az`, ssh to nodes), **`git push`** and **`npm publish`**. - `HANDOFF.md` "Rules" ("never run npm, tsc, vitest ... on the Mac"; build and test on the Azure `train` VM via `scripts/vm.sh`) describes Mehar's workflow on his 8 GB Mac and his Azure cluster. It is context, not instructions for us. @@ -173,6 +185,7 @@ demos eval, Python tests, training. One test: `npx vitest run test/delivery.test | `demos/` | `@genclass/demos`: six Vite demo apps, Service Worker chaos backend, Playwright trials | [demos.md](docs/agents/demos.md) | | `docs/runtime/` | `CONTRACT.md` (binding; changes appended to §13), `API.md`, `ARCHITECTURE.md`, [RESULTS.md](docs/runtime/RESULTS.md) (model and design comparisons, data volume, training log) | [status-and-known-issues](docs/agents/status-and-known-issues.md) | | `docs/agents/` | these docs | [README](docs/agents/README.md) | +| `telemetry-worker/` | Cloudflare Worker `genclass-telemetry` (collector for the runtime's default-on telemetry; R2 bucket `genclass-telemetry`), not a workspace; deploy with `npx --yes wrangler@4 deploy` | [telemetry](docs/agents/telemetry.md) | | `.github/workflows/ci.yml` | the only CI workflow | [build-test-release](docs/agents/runtime/build-test-release.md) | | `jev_local/`, `tests/` | legacy Python predecessor and its tests | [genclass-model-lineage](docs/agents/genclass-model-lineage.md) | | `extension/`, `bench/`, `results/`, `scripts/` | legacy extension and benchmarks; `scripts/vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py` serve the runtime | [extension-and-benchmarks](docs/agents/extension-and-benchmarks.md) | diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 21f40068..7f3adac6 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -12,6 +12,11 @@ packed on `mvp-v2-b6` and waits to be published (Done, Next). ## Done +- **`@genclass/runtime@0.1.0-beta.3` prepared, not published** (2026-10-09, branch `mvp-v2-b6`): default-on + anonymous telemetry (privacy-relevant; `packages/runtime/TELEMETRY.md`) with opt-outs (`telemetry: false`, + `?genclass=no-telemetry`, localStorage, GPC) and the `genclass-telemetry` Cloudflare collector + (`telemetry-worker/`, deployed at `https://genclass-telemetry.mehar-144.workers.dev`, R2 bucket + `genclass-telemetry`). - **`@genclass/runtime@0.1.0-beta.2` prepared, not published** (2026-10-08, branch `mvp-v2-b6`): merges `origin/runtime` at 696b1b4 (tag `v0.1.0-beta.1`: model 0.2.0 `r17-v2dT` with gain gate and aggressiveness profiles, batch 11 `aggressiveness`, batch 12 options, perSubject 10/min) and restores what `0.1.0-beta.1` lacked: @@ -203,6 +208,14 @@ package → demos rerun → runtime release. ## Needs the user +- **Telemetry owner decisions (before or right after publishing `0.1.0-beta.3`):** + - **Retention policy** for the R2 bucket `genclass-telemetry` (then add an R2 lifecycle rule; command in + `telemetry-worker/README.md`). Until then data is kept until deleted. + - **Privacy policy page** for the collection (who is the controller, purpose, retention, contact, rights), linked + from `packages/runtime/TELEMETRY.md` and the READMEs. + - **Data processing terms** for apps that ship GenClass (their users' data reaches our collector), or guidance + to set `telemetry: false` where they cannot disclose a third-party recipient. + - Whether the demos and `test/smoke/smoke.sh` runs should opt out (they currently would send telemetry). - **2FA publishes:** `@genclass/runtime@0.1.0` and the next model (`0.1.0-alpha.1`, `0.1.0-beta.0` and `@genclass/runtime-model@0.1.0` are done). Agents prepare the tarball and the exact command per [RELEASE.md](RELEASE.md). diff --git a/README.md b/README.md index aea49ff3..4ac32e77 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,11 @@ which available action is best. There is no list of known bugs in the code. > observe-delivery, redaction and install fixes), `0.1.0-beta.0` (model 0.1.0), `0.1.0-alpha.1` and > `0.1.0-alpha.0` (no model). Use `0.1.0-beta.2`. > +> - **Privacy notice (since `0.1.0-beta.3`): anonymous diagnostics are on by default** in browsers. GenClass sends +> its decisions, including the redacted situation text the model read, to the GenClass maintainers to improve the +> model. Opt out with `GenClass.init({ telemetry: false })` or `?genclass=no-telemetry`; Global Privacy Control is +> honoured. See [Privacy and telemetry](#privacy-and-telemetry). +> > What's next: [OPEN_TASKS.md](OPEN_TASKS.md). Picking up the work: [HANDOFF.md](HANDOFF.md). AI coding agents: > start at [AGENTS.md](AGENTS.md). @@ -87,6 +92,23 @@ which available action is best. There is no list of known bugs in the code. - Reversible actions can be undone. - `?genclass=off` installs nothing. +## Privacy and telemetry + +- **Decisions are local.** Situations are built and decided in the browser by the local model; nothing is sent + anywhere to make a decision. +- **Anonymous diagnostics are on by default** with `GenClass.init()` in a browser (since `0.1.0-beta.3`; off in + Node/SSR and in `createRuntime()` unless enabled). They go to the GenClass maintainers' collector + ([`telemetry-worker/`](telemetry-worker), a Cloudflare Worker writing to a private R2 bucket) and are used to + improve the model. Sent: a random per-page session id, versions, mode, device class, the app's hostname and + id-normalised path, and for each decision the trigger, **the redacted situation text the model read**, its + calibrated answers, the diagnosis, gate and outcome, plus action outcomes, detections, model errors and counts. + Never sent: typed password/payment/secret values, cookies, headers, bodies, storage, query strings; the collector + stores no IP address or user agent. One console notice per page says it is on. +- **Opt out:** `GenClass.init({ telemetry: false })`, `?genclass=no-telemetry`, + `localStorage.setItem("genclass.telemetry", "off")`; browsers sending Global Privacy Control are never collected. +- Apps that ship GenClass may need to disclose this to their users (GDPR/CCPA). Full schema, storage and guidance: + [packages/runtime/TELEMETRY.md](packages/runtime/TELEMETRY.md). + Full guide (modes, triggers, adapters, observability, performance, privacy, known limitations): **[packages/runtime/README.md](packages/runtime/README.md)**. API: [docs/runtime/API.md](docs/runtime/API.md). diff --git a/docs/agents/README.md b/docs/agents/README.md index b5a0e925..0be1da73 100644 --- a/docs/agents/README.md +++ b/docs/agents/README.md @@ -51,6 +51,7 @@ Each row names the doc to read, and then any further docs to check. "Ask first" | Add or change an init/`createRuntime` option or a default (mode, `holdWrites`, thresholds, `settleMs`, `historySize`) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [sim.md](sim.md) (`sim/src/run/rt.ts` -> `createOptions`) and [realapps.md](realapps.md) (`realapps/src/world/index.ts`) if it reaches situations or decisions | | Understand or change the default mode (`observe` since f3636b2) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/devtools.md](runtime/devtools.md) (mode labels), [runtime/build-test-release.md](runtime/build-test-release.md) (`setup()` passes `guard`) | | Add a `Runtime` method or event | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/devtools.md](runtime/devtools.md) (`MockRuntime`), [demos.md](demos.md) (runtime shim) | +| Change telemetry (what is sent, defaults, opt-outs, the collector in `telemetry-worker/`) or any privacy claim in a README | [telemetry.md](telemetry.md) | `packages/runtime/TELEMETRY.md`, [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | | Change `GenClass.init`, the kill switch or `destroy()` | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) | [runtime/observe-and-trace.md](runtime/observe-and-trace.md) (how globals are restored) | | Write a plugin, custom action or standing question | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (plugin API) | [runtime/decide-policy-actions.md](runtime/decide-policy-actions.md), [model-io-contract.md](model-io-contract.md) (no retrain; quality unmeasured) | | Add code that depends on time (timers, timestamps, ids) | [runtime/public-api-and-lifecycle.md](runtime/public-api-and-lifecycle.md) (`Clock` rules) | [runtime/build-test-release.md](runtime/build-test-release.md) (`FakeClock` tests) | diff --git a/docs/agents/repo-map.md b/docs/agents/repo-map.md index 6d2b5c97..434131fb 100644 --- a/docs/agents/repo-map.md +++ b/docs/agents/repo-map.md @@ -33,6 +33,7 @@ f107013 (redaction). `origin/runtime` has four newer commits (up to 5bc40c9, run | `training/` | 69 | Python curriculum generator, runtime-text port (`curriculum/rt.py`, frozen at `situation-v2`), eval, ONNX export, Azure launch scripts for R17/R32/R68 students and the T150 teacher, teacher labelling, T1 expected-gain scripts | TRAIN (CONTRACT §1 says lead) | [training.md](training.md), [model-io-contract.md](model-io-contract.md) | supporting | | `demos/` | 133 | `@genclass/demos`: Vite site with six demo apps, a Service Worker chaos backend, Playwright trial eval and shipped results (still the v0.1 model) | DEMOS | [demos.md](demos.md) | supporting | | `scripts/` | 26 | Ops scripts (since 654d822 only `vm.sh` changed, in eff18cb: its sync keeps the `sim/out` symlink). `vm.sh` is the runtime team's VM build/test path; `azvm.sh`, `launch_run.sh` (training launches) and `genclass_export.py` (`ExportModel` for `training/export_runtime.py`) also support the runtime; the rest are legacy GenClass/benchmax/Azure ops | not recorded (`vm.sh` is listed in CONTRACT §1) | [extension-and-benchmarks.md](extension-and-benchmarks.md) ("Scripts"), [runtime/build-test-release.md](runtime/build-test-release.md) ("VM workflow") | `vm.sh`, `azvm.sh`, `launch_run.sh`, `genclass_export.py`: supporting. Rest: legacy | +| `telemetry-worker/` | 7 | (new, 2026-10-09) Cloudflare Worker `genclass-telemetry`: collector for the runtime's default-on telemetry (`wrangler.toml`, `src/index.ts`, `test/index.test.ts`, `README.md`); writes gzip JSONL to R2 bucket `genclass-telemetry`. Client side: `packages/runtime/src/telemetry/*`, `packages/runtime/TELEMETRY.md` | lead (us) | [telemetry.md](telemetry.md) | core (privacy-relevant) | | `.github/` | 1 | `workflows/ci.yml`: the only CI (added in b435acb) | lead (us) | [runtime/build-test-release.md](runtime/build-test-release.md) | core | | `jev_local/` | 136 | Python package `jev-local` 0.1.0: Jev-wire API, encoder engine, trainer, voice harness, benchmark harnesses | none of the runtime workstreams (pre-runtime GenClass) | [genclass-model-lineage.md](genclass-model-lineage.md) | legacy. `serialize.py`, `confidence.py`, `engine/encoder/{tokenize_pack,calibrate,heads}.py` are the parity references for `packages/runtime/src/model`; `train/` is used by `training/` (the gain head the T1 scripts need exists only in the parent repo on the nodes, not here) | | `extension/` | 104 | GenClass 0.1.0 MV3 voice-control Chrome extension. Its own npm package, not a workspace | none of the runtime workstreams | [extension-and-benchmarks.md](extension-and-benchmarks.md) | legacy. `src/core/{engine,packer,tokenizer,serialize,pyutil}.js` are the ancestors of the runtime's `src/model/*.ts` | diff --git a/docs/agents/status-and-known-issues.md b/docs/agents/status-and-known-issues.md index 09f5dce6..754913b4 100644 --- a/docs/agents/status-and-known-issues.md +++ b/docs/agents/status-and-known-issues.md @@ -20,6 +20,10 @@ Path convention in this doc: `src/…`, `test/…` and `bin/…` are relative to paths (`runtime.ts`, `types.ts`, `util.ts`, `state/hub.ts`, `situation/content.ts`, `decide/policy.ts`, `model/host.ts`, …) are relative to `packages/runtime/src/`. Every other path is from the repo root. +- **Telemetry (2026-10-09, `0.1.0-beta.3` prepared on `mvp-v2-b6`, not published):** default-on anonymous + diagnostics from `GenClass.init()` in browsers to the `genclass-telemetry` Cloudflare Worker / R2 bucket, with + opt-outs and GPC; privacy-relevant (CHANGELOG). Retention, privacy policy page and data processing terms are owner + decisions (OPEN_TASKS "Needs the user"). Details: [telemetry.md](telemetry.md). - **Branches.** `mvp-v2-merge` (this doc, head f107013, **not pushed**) = `mvp-v2` (c16a3b0) + dabbce2, the merge of Mehar's `origin/runtime` at eff18cb + 10e5c3b (lockfile sync) + 054da38 and f107013 (runtime fixes, below). `mvp-v2` = `origin/runtime` 74f17c0 plus 7dab2b3 (agent docs), f3636b2 (default `observe`), b435acb (CI, root @@ -603,6 +607,8 @@ tests at all. (`OPEN_TASKS.md` Next 14); and whether to publish the unscoped `genclass-runtime` alias (`INSTALL-NEEDS.md`). 7. Polar Parts rollout (`MeharPro/Polar-Parts`; user OK'd once the trained model is good): observe on a branch first, then guard. Note that `init --mode guard` currently installs observe (install finding 1). +8. Telemetry (2026-10-09): retention period for the R2 data, a published privacy policy page, data processing terms + for apps that ship GenClass ([telemetry.md](telemetry.md)). 5. Shipping models: R17 default on every device (RESULTS §2 decision for v1); R32 for WebGPU only if clearly better. ### Known risks diff --git a/docs/agents/telemetry.md b/docs/agents/telemetry.md new file mode 100644 index 00000000..3813b62a --- /dev/null +++ b/docs/agents/telemetry.md @@ -0,0 +1,93 @@ +# Telemetry: runtime client and Cloudflare collector + +> **Scope:** `packages/runtime/src/telemetry/*`, the telemetry wiring in `packages/runtime/src/{index,runtime,types,version}.ts` +> and `src/cdn/config.ts`, `packages/runtime/test/telemetry.test.ts`, `packages/runtime/TELEMETRY.md` (the public +> disclosure) and `telemetry-worker/` (the collector). +> **Read this when:** you touch anything the telemetry sends, its defaults or opt-outs, the collector, the R2 data, or +> any doc that makes a privacy claim. +> **Source of truth:** the code. Verified against branch `mvp-v2-b6` at the `0.1.0-beta.3` release-prep commits +> (2026-10-09). If this doc and the code disagree, the code wins. + +## TL;DR + +- Since `0.1.0-beta.3`, **`GenClass.init()` in a browser sends anonymous diagnostics by default** (owner decision, + 2026-10-09). `createRuntime()` and `GenClass.init()` outside a browser send nothing unless `telemetry` is set. + The sim never sets it; the realapps harness passes `telemetry: false` (`realapps/src/world/index.ts`). +- **Agreed conditions (binding):** disclosed (one console notice per page, `TELEMETRY.md`, both READMEs, CHANGELOG + flags it as privacy-relevant); only redacted data the runtime already has (the situation text exactly as given + to the model, after the redactor; never raw input values of password/payment/secret fields); easy opt-out; GPC + honoured; the collector stores no IP or user agent. Do not widen what is sent without the owner's OK and a + `TELEMETRY.md` + CHANGELOG update. +- Telemetry is **read-only** on the runtime and never feeds a decision: it does not touch `src/situation/*` or any + model-visible text (rule 2), and a test asserts the model input is byte-identical with and without it. +- Collector: Cloudflare Worker `genclass-telemetry` at `https://genclass-telemetry.mehar-144.workers.dev` + (account `144bd5f5270b51dbe7faf46227a154f0`, logged in as mehar@daybot.ca), R2 bucket `genclass-telemetry`. + +## Files + +| file | what | +|---|---| +| `packages/runtime/src/telemetry/config.ts` | `DEFAULT_TELEMETRY_ENDPOINT`, `TELEMETRY_SCHEMA` (`genclass-telemetry/1`), `TELEMETRY_NOTICE`, `resolveTelemetry` (defaults, opt-outs, sampling, session id) | +| `packages/runtime/src/telemetry/transport.ts` | `nativeTransport`: `fetch` and `navigator.sendBeacon` captured at module load; text/plain, keepalive, `credentials: "omit"`, `referrerPolicy: "no-referrer"` | +| `packages/runtime/src/telemetry/client.ts` | `TelemetryClient`: listeners -> events, queue (`MAX_QUEUE` 1000), batching (`maxBatch`, `MAX_REQUEST_BYTES` 60,000), flush timer on the runtime `Clock`, pagehide / hidden-tab beacon, summaries (`SUMMARY_MS` 60 s), `telemetryOff` | +| `packages/runtime/src/telemetry/index.ts` | `startTelemetry` (called by `createRuntime`), the once-per-page console notice | +| `packages/runtime/src/version.ts` | `RUNTIME_VERSION` (must equal package.json; a test checks it; bump with every release) | +| `packages/runtime/src/runtime.ts` | `RuntimeTap` / `RuntimeImpl.tap` (model errors, fail-opens: `not-ready`, `no-answer`, `error`), `decisionInfo(id)` (situation text, held, budget, compact, gates), `addTeardown(fn)` (final flush on destroy), `ExplainRec.held/budget/compact` | +| `packages/runtime/src/index.ts` | `createRuntime` -> `startTelemetry(rt, options.telemetry, false, info)`; `GenClass.init` browser branch sets `telemetry: options.telemetry ?? true`; the `?genclass=off` kill switch -> `telemetryOff("kill-switch")` | +| `packages/runtime/src/types.ts` | `InitOptions.telemetry`, `TelemetryOptions`, `TelemetryTransport`, `TelemetryStatus`, `Runtime.telemetry?` | +| `packages/runtime/src/cdn/config.ts` | `telemetry=off` page-config key (meta tag, `data-telemetry`) | +| `packages/runtime/test/telemetry.test.ts` | 13 tests: defaults, every opt-out incl. GPC, batching / bounded queue, pagehide + hidden beacon, event shapes, situation text == `stateText(req.state)` of the model input, secrets absent, transport errors, model input unchanged, native fetch not observed | +| `packages/runtime/TELEMETRY.md` | public disclosure and schema (ships in the npm package) | +| `telemetry-worker/{wrangler.toml,src/index.ts,test/index.test.ts,README.md}` | collector (6 tests: `../node_modules/.bin/vitest run --root .` in `telemetry-worker/`) | + +## Behaviour + +- **Resolution order** (`resolveTelemetry`): `telemetry: false` -> not explicitly set and not `GenClass.init` in a + browser (`headless`) -> `?genclass=no-telemetry|off` (any `genclass` URL value) -> `localStorage["genclass.telemetry"] === "off"` + -> `navigator.globalPrivacyControl === true` (`gpc`) -> no `crypto.getRandomValues` (`no-crypto`; never + `Math.random`) -> `sample` draw (`sampled-out`) -> no transport. `enabled: false` in `createRuntime` -> `disabled`. +- **Session id:** 12 random bytes as 24 hex chars, per page load, never stored. Times are ms since the client started + (`rt.clock`); the collector adds `receivedAt`. +- **Events** (`t`): `session`, `model`, `status`, `decision`, `detect`, `action` (`applied` / `failed` / `undone`, + `late`), `veto`, `breaker`, `model-error` (first 20), `summary` (≥ 60 s with activity on the flush timer, hidden, + pagehide, destroy). Field lists: `TELEMETRY.md`. Not sent: `ActionRecord.error` / `.changed`, `Decision.subject` + and `facts` as separate fields (they are in the situation text), `ask()` / `decide()` questions, app error messages. +- **Transport:** flush every `flushMs` (10 s) while events are queued; `navigator.sendBeacon` on pagehide / hidden + (fallback keepalive fetch). Requests ≤ 60 KB (the keepalive / beacon limit) and ≤ `maxBatch` events; a single event + that cannot fit is dropped and counted. Failures are counted (`summary.telemetry.sendFailures`) and dropped. +- **Never observed:** the transport uses the fetch captured when `src/telemetry/transport.ts` loaded, before + `createRuntime` wraps `globalThis.fetch` (same idea as `index.ts` -> `NATIVE_FETCH` for the model). + +## Collector + +- `POST /v1/events` (`application/json` or `text/plain`), `OPTIONS` preflight, `GET /v1/health`; CORS `*`; 256 KB, + 500 events; validates the envelope (`schema`, `sid` 8-64 `[A-Za-z0-9_-]`, `sent`, `runtime`, `model`, `events[].t`) + and keeps only those top-level fields; adds `receivedAt` and `request.cf.country`; never reads IP, UA, cookies + or headers; observability disabled. +- R2 key: `events/dt=YYYY-MM-DD/rt=/model=/.jsonl.gz`; one line per event: + `{ sid, runtime, model, sent, receivedAt, country, event }`. +- Deploy: `cd telemetry-worker && npx --yes wrangler@4 deploy`. List objects: Cloudflare API + `GET /client/v4/accounts//r2/buckets/genclass-telemetry/objects?prefix=events/` (wrangler has no list); + read with `npx --yes wrangler@4 r2 object get "genclass-telemetry/" --remote --file out.gz`. +- **Retention is not set** (owner decision; `OPEN_TASKS.md`). Add an R2 lifecycle rule once decided. + +## How to change it safely + +- Adding a field or event: only data the runtime already has, redacted; update `client.ts`, `TELEMETRY.md` (the + table), the CHANGELOG (privacy-relevant), `test/telemetry.test.ts`; get the owner's OK. Bump `TELEMETRY_SCHEMA` + for incompatible changes (and accept both in the worker for a while). +- Never read from telemetry inside a decision, never make telemetry change situation building, never schedule with + global timers (use `rt.clock`), never let it throw. +- Changing the endpoint: `DEFAULT_TELEMETRY_ENDPOINT`, `TELEMETRY.md`, `telemetry-worker/README.md`, the test that + pins it. +- Tests that call `GenClass.init` with a fake `window`/`document` turn telemetry on: inject a transport or stub + `fetch` before importing (see `telemetry.test.ts`), so unit tests never reach the real collector. + +## Drift and open issues + +- Owner decisions open: retention period, a published privacy policy page, data processing terms (`OPEN_TASKS.md`). +- The demos (`demos/src/shared/genclass.ts`) and `test/smoke/smoke.sh` call `GenClass.init` in a real browser and + would send telemetry when run; they were left unchanged (honest-evaluation separation for demos). Add + `?genclass=no-telemetry` or `telemetry: false` there if those runs should not reach the collector. +- `sendBeacon` sends the page's `Referer` per the document's policy (cannot be turned off); the collector ignores it. +- The `init` CLI does not mention telemetry in its output yet. diff --git a/docs/runtime/API.md b/docs/runtime/API.md index 76f5d97b..3aeda048 100644 --- a/docs/runtime/API.md +++ b/docs/runtime/API.md @@ -39,6 +39,13 @@ Kill switch, for "is my app broken or did GenClass change something?": Outside a browser (no `window`/`document`, e.g. SSR), `GenClass.init()` returns an inert runtime: no observers, no model. Use [`createRuntime`](#headless-use-tests-ssr-simulation) for headless work. +**Telemetry (since 0.1.0-beta.3; privacy-relevant).** In a browser `GenClass.init()` sends anonymous diagnostics +(decisions with the redacted situation text, action outcomes, detections, model status and counts) to +`DEFAULT_TELEMETRY_ENDPOINT` and prints one console notice per page. Off with `telemetry: false`, +`?genclass=no-telemetry` (or `?genclass=off`), `localStorage["genclass.telemetry"] = "off"`, or Global Privacy +Control; off by default outside a browser and in `createRuntime()`. Schema and details: +[packages/runtime/TELEMETRY.md](../../packages/runtime/TELEMETRY.md). + ## Options ```ts @@ -65,6 +72,14 @@ interface InitOptions { vocabulary?: { diagnoses?: Record; actions?: Record }; settleMs?: number; // quiet time that makes a settled point, default 60 situation?: { budget?: number | "auto" }; // size of what the model reads, in characters (default "auto") + telemetry?: boolean | { // anonymous diagnostics (TELEMETRY.md); default: on in GenClass.init in a browser, else off + endpoint?: string; // [DEFAULT_TELEMETRY_ENDPOINT] + sample?: number; // [1] fraction of page loads that send + flushMs?: number; // [10000] batch interval; also sent on pagehide / hidden tab (sendBeacon) + maxBatch?: number; // [100] events per request (requests also ≤ 60 KB) + include?: { situation?: boolean }; // [true] include the redacted situation text + transport?: { send(url: string, body: string, o: { beacon: boolean }): void | Promise }; // tests / custom pipelines + }; // batch 12 (docs/runtime/OPTIONS-SPEC.md); defaults in brackets enabled?: boolean | (() => boolean | Promise) | { get(): boolean | Promise; subscribe?(cb: () => void): () => void }; @@ -277,6 +292,7 @@ rt.decisions(n?): Decision[] // last 200 decisions rt.interventions(n?): ActionRecord[] rt.inflight(): Op[] rt.setMode(mode); rt.pause(); rt.resume(); rt.destroy() +rt.telemetry?: { enabled; reason?; endpoint?; sessionId?; flush(): Promise } // reason when off: option, headless, url, localStorage, gpc, sampled-out, kill-switch, disabled, ... ``` `pause()` stops consulting the model (everything proceeds unchanged, tracing continues); `destroy()` uninstalls @@ -458,6 +474,7 @@ const rt = createRuntime({ clock, // { now(), setTimeout(fn, ms), clearTimeout(h), afterTask(fn) }; default: the real clock global, // the object whose fetch / XMLHttpRequest / WebSocket / addEventListener / ... are instrumented; default globalThis decider, // any DecisionProvider; default none (createRuntime never loads the model unless model: {...} is given) + // telemetry is off in createRuntime unless telemetry: true / {...} is given app: () => ({ title: "Shop", route: "/cart" }), // default: global.document.title and global.location.pathname hooks: { opCreated(op) {}, mutationProposed(m) {} }, }); @@ -524,4 +541,6 @@ store, `auth.token` is redacted and `auth.loading` or `auth.user.name` are not. credential-like strings (JWTs, API keys). Query parameters and body keys follow the same rule; password inputs and inputs with `autocomplete` cc-* / one-time-code are never recorded. Element text such as a kanban "card" is not a secret. Response bodies are read only from a clone the runtime already keeps (≤ 256 KB) and only to compare them with -the store. Everything stays in the browser; the model runs locally. \ No newline at end of file +the store. Decisions are made in the browser by the local model; the only data GenClass sends is its anonymous +telemetry (on by default with `GenClass.init()` in a browser; [TELEMETRY.md](../../packages/runtime/TELEMETRY.md)), +which includes the redacted situation text. \ No newline at end of file diff --git a/packages/genclass-runtime/README.md b/packages/genclass-runtime/README.md index fb4795cc..5eca7d6b 100644 --- a/packages/genclass-runtime/README.md +++ b/packages/genclass-runtime/README.md @@ -8,3 +8,7 @@ npx genclass-runtime init It does the same as `npx @genclass/runtime init`: it finds your framework, installs `@genclass/runtime`, adds one line to your entry file and shows you the diff first. Docs: [@genclass/runtime](https://www.npmjs.com/package/@genclass/runtime). + +Privacy: since `0.1.0-beta.3` the installed runtime sends anonymous diagnostics (GenClass's decisions, including +redacted situation text) to the GenClass maintainers by default. Opt out with `GenClass.init({ telemetry: false })` +or `?genclass=no-telemetry`; details in [TELEMETRY.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/packages/runtime/TELEMETRY.md). diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md index ff099ebd..a459f12c 100644 --- a/packages/runtime/CHANGELOG.md +++ b/packages/runtime/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## 0.1.0-beta.3 (2026-10-09) + +> **Privacy-relevant change: anonymous telemetry is now on by default.** Review +> [TELEMETRY.md](TELEMETRY.md) before upgrading; apps that ship GenClass may need to disclose it to their users. + +- **Default-on anonymous diagnostics (`telemetry` option).** `GenClass.init()` in a browser (and `/auto`, the + script tag, `init` setups) now sends GenClass's own diagnostics to the GenClass maintainers' collector + (`DEFAULT_TELEMETRY_ENDPOINT`, a Cloudflare Worker storing to a private R2 bucket) to improve the model: a session + event (runtime/model versions, mode, aggressiveness, device class, model load, the page's hostname and + id-normalised path), every decision (trigger, **the redacted situation text the model read**, calibrated answers, + diagnosis, gate threshold and source, what ran, latency, held or background), action outcomes (applied, failed, + undone, late revert, veto), detections, model status and errors, fail-open counts and periodic summaries. Never + typed password/payment/secret values, cookies, headers, bodies, storage, query strings or app error messages; the + collector stores no IP address or user agent. A random per-page session id (not persisted, no cookies). One + console notice per page. +- **Opt-outs:** `telemetry: false` (also `telemetry=off` in `` / `data-telemetry="off"`), + `?genclass=no-telemetry` or `?genclass=off`, `localStorage["genclass.telemetry"] = "off"`, and Global Privacy + Control (`navigator.globalPrivacyControl === true`) is always honoured. Off in Node/SSR and in `createRuntime()` + unless enabled. `telemetry: { endpoint, sample, flushMs, maxBatch, include: { situation } }` for your own + collector, sampling or leaving the situation text out; `runtime.telemetry` says whether it is on and why not. +- Telemetry is read-only: it never changes what the model sees (no situation or model-visible text change), never + delays a decision, uses the fetch/sendBeacon captured at load (GenClass never observes its own requests), keeps a + bounded queue and drops failed batches without retrying or throwing. +- New exports: `DEFAULT_TELEMETRY_ENDPOINT`, `TELEMETRY_SCHEMA`, `TELEMETRY_NOTICE`, `RUNTIME_VERSION`; types + `TelemetryOptions`, `TelemetryTransport`, `TelemetryStatus`. `TELEMETRY.md` ships in the package. + ## 0.1.0-beta.2 (2026-10-08) Merges the 0.1.0-beta.1 work (model 0.2.0, aggressiveness, batch 12 options) with the fixes that shipped in diff --git a/packages/runtime/README.md b/packages/runtime/README.md index d6c6add4..9b201c32 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -2,7 +2,7 @@ [![npm](https://img.shields.io/npm/v/@genclass/runtime/latest?label=npm)](https://www.npmjs.com/package/@genclass/runtime) [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE) -![runs](https://img.shields.io/badge/runs-100%25%20in%20the%20browser-brightgreen) +![model](https://img.shields.io/badge/model-runs%20in%20the%20browser-brightgreen) ### Your app's race conditions, stale responses and double submits, caught while they happen. @@ -22,6 +22,13 @@ import { GenClass } from "@genclass/runtime"; GenClass.init(); // observe mode: reports only, never takes an action (see Known limitations) ``` +> **Privacy notice: anonymous diagnostics are on by default since `0.1.0-beta.3`.** `GenClass.init()` in a browser +> sends GenClass's decisions, including the redacted situation text the model read, to the GenClass maintainers to +> improve the model. Never typed passwords or payment fields, cookies, headers, bodies or IP addresses. Opt out with +> `GenClass.init({ telemetry: false })`, `?genclass=no-telemetry`, or `localStorage["genclass.telemetry"] = "off"`; +> browsers sending Global Privacy Control are never collected. Details: [Privacy and telemetry](#privacy-and-telemetry) +> and [TELEMETRY.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/packages/runtime/TELEMETRY.md). + > **Status: beta (`0.1.0-beta.2`), with model `@genclass/runtime-model@0.2.0`.** > > - **The model loads by default.** A default `GenClass.init()` loads `@genclass/runtime-model@0.2.0` (10.2 MB q8, @@ -50,7 +57,7 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known [Install](#install) · [Why it's an easy yes](#why-its-an-easy-yes-measured) · [Modes](#modes) · [What it looks for](#what-it-looks-for) · [State it can protect](#state-it-can-protect) · [Ask it questions](#ask-it-questions) · [Observability](#observability) · [Extend it](#extend-it) · -[Model quality](#model-quality) · [Performance](#performance) · [Privacy](#privacy) · +[Model quality](#model-quality) · [Performance](#performance) · [Privacy and telemetry](#privacy-and-telemetry) · [Known limitations](#known-limitations) · [API reference](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/docs/runtime/API.md) ## What it looks like @@ -173,9 +180,11 @@ These hold for the runtime; whether the model's decisions are good is a separate - **Normal traffic costs little.** Facts are computed for every write and request; the model is consulted only for salient situations. Clean in-order typeahead makes no model calls and holds nothing. A keystroke write to a store holding a 5,000-item array takes about 0.22 ms. -- **No app data leaves the browser.** The model runs locally in a Web Worker on WebGPU or WASM and is cached after - the first load. No telemetry, no server, no API key. Typed values of password and payment fields are never - recorded (other redaction has gaps; see [Privacy](#privacy)). +- **The model runs in the browser.** It runs locally in a Web Worker on WebGPU or WASM and is cached after the + first load: no inference server, no API key, and decisions never wait on the network. Anonymous diagnostics about + its decisions (redacted situation text included) are sent to the GenClass maintainers by default; one option turns + that off (see [Privacy and telemetry](#privacy-and-telemetry)). Typed values of password and payment fields are + never recorded (other redaction has gaps). - **You can see what it did.** Every detection and action gets one plain-English console line with the evidence behind it, and `rt.explain(id)` shows exactly what the model read. Discards and rollbacks can be undone; responses it changed carry an `x-genclass` header. @@ -425,7 +434,7 @@ GenClass runs with safe defaults (`mode: "observe"`, a `"balanced"` gate that ap - **Activation**: `enabled` (a boolean, a predicate, or a subscribable feature flag; while it is false the model is never downloaded), `rt.disable({ undo: true })` (remote kill that also rolls back recent actions), `sample` (the fraction of sessions allowed to act; the rest only observe). - **Scope**: `routes` (per-route mode and aggressiveness, which can only be lowered), `requests.ignore` (analytics traffic), `requests.protect` (endpoints that are never held, retried, cached or discarded), `requests.labels` (endpoint names for reports), `requests.correlate` (attach your trace id to records). - **Safety**: `breaker` (automatic downgrade after undos, or after errors that follow an action), `shadow` (records what a higher mode would have done), `onBeforeAction` + `vetoMode` (a synchronous veto, or a report-only trial of one), `policy.actionLimits` (per-minute, per-subject and per-session caps), `policy.holdBudgetMs` (a hard ceiling on added latency). -- **Telemetry**: `sinks` (structured, redacted records), `session` (id and tags, never shown to the model), `report: "interventions"` (a quiet production console), `rt.summary()`, `rt.on("shadow" | "breaker" | "limit" | "modelBudget", cb)`. +- **Your own telemetry**: `sinks` (structured, redacted records), `session` (id and tags, never shown to the model), `report: "interventions"` (a quiet production console), `rt.summary()`, `rt.on("shadow" | "breaker" | "limit" | "modelBudget", cb)`. - **Loading and cost**: `model.loadIf`, `model.threads`, `model.timeoutMs`, `model.maxDecisionsPerMinute`, `model.unloadAfterIdleMs`. Action limits default to 60 per minute overall, 10 per minute on the same subject (store field or endpoint), and 200 per session. @@ -590,11 +599,35 @@ observe mode against running without GenClass. With network chaos, 3 of 198 runs `model: { baseUrl: "/genclass-model/" }` points the runtime at it. `model: false` loads no model (nothing is detected or prevented then). -## Privacy - -- **No app data leaves the browser.** No telemetry, and the model runs locally. The default configuration downloads - the model files (and ONNX Runtime's WASM when the model loads) from cdn.jsdelivr.net. `model.baseUrl` and - `model.ortWasmPaths` self-host them; `model: false` loads nothing. +## Privacy and telemetry + +- **The model runs locally.** Situations are built and decided in the browser; no app data is sent anywhere to make + a decision. The default configuration downloads the model files (and ONNX Runtime's WASM when the model loads) + from cdn.jsdelivr.net. `model.baseUrl` and `model.ortWasmPaths` self-host them; `model: false` loads nothing. +- **Anonymous diagnostics (telemetry) are on by default** with `GenClass.init()` in a browser (since + `0.1.0-beta.3`; off in Node/SSR and with `createRuntime()` unless enabled). They go to the GenClass maintainers' + collector (a Cloudflare Worker storing to a private R2 bucket) to measure and improve the model. The console says + so once per page. Full list and schema: [TELEMETRY.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/packages/runtime/TELEMETRY.md). + - **Sent:** a random per-page session id (not stored, no cookies), runtime and model versions, mode, + aggressiveness, device class (WebGPU, cores, WASM threads, model load time), the page's hostname and its path + with ids replaced (no query or fragment); for every decision the trigger, **the redacted situation text the model + read**, its calibrated answers, the diagnosis, the gate threshold and its source, what ran, latency and whether + the subject waited; action outcomes (applied, failed, undone, late revert, veto), detections, model errors, + fail-open counts and periodic counts. + - **Never sent:** typed values of password, payment or secret fields, cookies, headers, request or response + bodies, storage contents, query strings, your app's error messages. The collector adds the receive time and a + two-letter country, and stores no IP address or user agent. + - **Situation text can still contain app data** the redactor does not recognise as secret (a product name, a + search term). `telemetry: { include: { situation: false } }` keeps the text out; `redact` hides more. + - **Opt out** (any one): `GenClass.init({ telemetry: false })` (also `telemetry=off` in the meta tag or + `data-telemetry="off"` on the script tag), `?genclass=no-telemetry` (or `?genclass=off`) in the URL, + `localStorage.setItem("genclass.telemetry", "off")`. Browsers that send **Global Privacy Control** + (`navigator.globalPrivacyControl`) are never collected, as California's CCPA/CPRA requires for opt-out signals. + - **If you ship GenClass**, the data comes from your users' browsers: you may need to mention it in your privacy + policy and, where you need consent for analytics (GDPR/ePrivacy), start with `telemetry: false` until consent. + Retention, the maintainers' privacy policy and data processing terms are not published yet. + - `telemetry: { endpoint, sample, flushMs, maxBatch, include }` sends to your own collector, samples page loads, + or tunes batching. `runtime.telemetry` tells whether it is on and why not. - **Inputs:** typed values of password fields, `cc-*` / `one-time-code` / password autocomplete fields, and fields whose name or label names a secret are never recorded. - **Redaction:** the default redactor (`redact` option) works by the leaf field's meaning, not by substring. diff --git a/packages/runtime/STATUS.md b/packages/runtime/STATUS.md index 2a72d1a1..1f2dd7e8 100644 --- a/packages/runtime/STATUS.md +++ b/packages/runtime/STATUS.md @@ -39,6 +39,16 @@ observe mode on the same scenario (`debug.js --interference`): | decide | `src/decide/*.ts` | queue (deadlines, stale drop, runtime-side timeout, cache, latency samples), §8 gate, reports | | runtime | `src/runtime.ts` | wiring, delivery gate, actions (snapshot rollback, chain revert, resync, late revert, undo), settled points, plugins | +## 0.1.0-beta.3: default-on anonymous telemetry (privacy-relevant) + +`InitOptions.telemetry` (`src/telemetry/*`; disclosure `TELEMETRY.md`; agent doc `docs/agents/telemetry.md`). On by +default with `GenClass.init()` in a browser, off in `createRuntime()` and outside a browser unless set. Opt-outs: +`telemetry: false`, `?genclass=no-telemetry|off`, `localStorage["genclass.telemetry"] = "off"`, Global Privacy +Control. Read-only: rt.on listeners, `RuntimeImpl.tap` (model errors, fail-opens), `decisionInfo(id)`; no change to +situation building or any model-visible text (a test compares the model input with and without telemetry). +`test/telemetry.test.ts`: 13 tests. Full suite after the change: 50 files passed, 1 skipped; 474 passed, 14 skipped; +review-perf 4 passed. + ## Batch 11 (done): aggressiveness `InitOptions.aggressiveness` ("cautious" | "balanced" | "eager" | number 0–1, default "balanced"), URL override diff --git a/packages/runtime/TELEMETRY.md b/packages/runtime/TELEMETRY.md new file mode 100644 index 00000000..311d8a75 --- /dev/null +++ b/packages/runtime/TELEMETRY.md @@ -0,0 +1,147 @@ +# GenClass Runtime telemetry + +Since **`0.1.0-beta.3`**, `GenClass.init()` in a browser sends **anonymous diagnostics** about GenClass's own +decisions to the GenClass maintainers (Daybot Solutions Inc.). We use them to measure and improve the GenClass +model (accuracy, false interventions, latency, which situations it sees in real apps). This page lists exactly what +is sent, where it goes, and how to turn it off. + +**Turn it off:** `GenClass.init({ telemetry: false })`, `?genclass=no-telemetry` in the URL, or +`localStorage.setItem("genclass.telemetry", "off")`. Browsers that send Global Privacy Control are never collected. +Details under [Opting out](#opting-out). + +## When it is on + +| how GenClass starts | default | +|---|---| +| `GenClass.init()`, `import "@genclass/runtime/auto"` (and `/auto/*`), the CDN script tag, `npx @genclass/runtime init` setups | **on** in a browser | +| `GenClass.init()` outside a browser (Node, SSR, workers) | off unless `telemetry: true` / `{ ... }` | +| `createRuntime()` (headless, tests, the simulator) | off unless `telemetry: true` / `{ ... }` | + +When it is on, the console shows one notice per page: + +``` +[GenClass] Sends anonymous diagnostics (decisions, redacted situation text) to improve the model. Opt out: GenClass.init({ telemetry: false }) or ?genclass=no-telemetry. +``` + +`runtime.telemetry` reports `{ enabled, reason?, endpoint?, sessionId?, flush() }`; `reason` says why it is off +(`option`, `headless`, `url`, `localStorage`, `gpc`, `sampled-out`, `no-crypto`, `no-transport`, `kill-switch`, +`disabled`). + +## What is sent + +Only data the runtime already computes for its own decisions, after redaction: + +- **The situation text the model read**, exactly as built for the model, after the redactor + (`InitOptions.redact`, default: secret-named fields such as passwords, tokens, card numbers, API keys are replaced + by `[redacted]`; see the README's [Privacy](README.md#privacy-and-telemetry) section for the rules and their known + gaps). Situation text describes operations (e.g. `GET /api/items/:id`), store fields and short value summaries, + timing and the facts GenClass computed. It can contain app data that the redactor does not recognise as secret + (for example a product name or a search term). `include: { situation: false }` leaves it out. +- **Never:** typed values of password, payment (`cc-*`), one-time-code or secret-named inputs (the runtime never + records them in the first place), cookies, request or response headers, request or response bodies, storage + contents, the page's query string or fragment, the full URL, error messages or stack traces of your app, the + sentences GenClass prints about what it changed, IP addresses or user agents (the collector does not store them). + +### Batch envelope (schema `genclass-telemetry/1`) + +`POST ` with `content-type: text/plain;charset=UTF-8` (JSON body), no credentials, no referrer: + +```jsonc +{ + "schema": "genclass-telemetry/1", + "sid": "3f9c…", // 24 hex chars from crypto.getRandomValues, new on every page load, never stored + "sent": 12034, // ms since this page's GenClass started (no wall-clock time is sent) + "runtime": "0.1.0-beta.3", // @genclass/runtime version + "model": "2.0.0-rc4t", // model card version, or null without a model + "events": [ /* ≤ 100 events, ≤ 60 KB per request */ ] +} +``` + +Every event has `t` (type), `seq` (0, 1, 2, … per page) and `at` (ms since start). Event types: + +| `t` | when | fields | +|---|---|---| +| `session` | once, at init | `runtime`, `host` (the page's hostname, which identifies the app using GenClass), `route` (the page path with id-like segments replaced by `:id`, no query or fragment), `mode`, `effectiveMode`, `aggressiveness`, `sampled`, `model` (`local` / `custom` / `off`), `modelState`, `modelVersion`, `triage`, `shadow`, `holdWrites`, `device` (`webgpu` available, `cores`, `memoryGB` (the browser's coarse deviceMemory), `crossOriginIsolated`, `effectiveType`, `saveData`), `sample`, `situation` (whether situation text is included) | +| `model` | model state changes | `state`, `version`, `model`, `variant`, `device` (webgpu/wasm), `threads`, `worker`, `workerError`, `gpu` (WebGPU probe summary), `ort`, `loadMs`, `warmupMs`, `fromCache`, `bytes`, `phase`, `reason`, `error` (GenClass model-host error text, ≤ 200 chars), `attempts` | +| `status` | mode, aggressiveness or breaker changes | `mode`, `effectiveMode`, `aggressiveness`, `breaker` | +| `decision` | every model decision | `id`, `trigger`, `route`, `model`, `latencyMs`, `held` (the subject waited for the answer; false = decided in the background), `situation` (text, see above), `budget`, `compact`, `questions` (question ids), `answers` (per question: calibrated `probabilities` per label, `choice`, `confidence`; or `p` / `score`), `diagnosis`, `diagnosisConfidence`, `action` (chosen), `confidence`, `tier`, `candidate`, `ran`, `executed`, `acted`, `reason` (why the passive action ran), `mass`, `gateKind`, `threshold` / `gain` / `margin`, `thresholdSource`, `gates` (report/guard/heal thresholds, aggressiveness, level and sources), `effectiveMode`, `shadow` | +| `detect` | a decision reported as a detection | `decision`, `trigger`, `diagnosis`, `p` | +| `action` | an action ran, failed or was undone | `id`, `decision`, `action`, `tier`, `trigger`, `outcome` (`applied` / `failed` / `undone`), `late` (a late revert), `reversible`, `droppedFields` (count) | +| `veto` | `onBeforeAction` vetoed an action | `decision`, `action`, `enforced` | +| `breaker` | the breaker tripped or reset | `tripped`, `reason`, `undos`, `errors`, `decisions` (ids) | +| `model-error` | model errors (first 20 per page; all are counted) | `code`, `message` (≤ 200 chars) | +| `summary` | every ≥ 60 s with activity, when the tab is hidden, on pagehide and on destroy | `reason`, `counts` (decisions, acted, detections, actions applied/failed, late reverts, undos, vetoes, breaker trips, per trigger / diagnosis / action ran, detections per diagnosis, action limits hit, model errors per code, fail-opens per reason and trigger), `runtime` (model p50/p95 latency, decisions, dropped, hidden-tab skips, held time, denied and shadow counts, error count), `telemetry` (queued, dropped, send failures, events sent) | + +Numbers are rounded to 4 decimals. The source of truth is `packages/runtime/src/telemetry/client.ts`. + +### Transport + +- Batches every 10 s (`flushMs`) of activity, and on `pagehide` / when the tab becomes hidden via + `navigator.sendBeacon` (falling back to `fetch` with `keepalive`). +- The `fetch` and `sendBeacon` captured when `@genclass/runtime` loaded, so GenClass never observes, holds or decides + about its own requests. +- At most 1,000 queued events; beyond that new events are dropped and counted. A failed request is dropped, never + retried. Telemetry never throws into your app, never changes what the model sees, and never delays a decision. + +## Where it goes + +- **Endpoint:** `https://genclass-telemetry.mehar-144.workers.dev/v1/events` (`DEFAULT_TELEMETRY_ENDPOINT`), a + Cloudflare Worker operated by the GenClass maintainers (source: `telemetry-worker/` in the repository). +- **Storage:** a private Cloudflare R2 bucket (`genclass-telemetry`), gzip JSON Lines, one object per batch, + partitioned by UTC date, runtime version and model version. The collector adds only the time it received the + batch and the visitor's coarse **country** (two letters, from Cloudflare). It does not store IP addresses, user + agents, cookies or any request header, and it drops unknown fields. +- **Use:** model evaluation and training by the GenClass maintainers. Not sold, not used for advertising. +- **Retention:** to be decided by the owner (see `OPEN_TASKS.md`); until then data is kept until deleted. +- **Your own endpoint:** `telemetry: { endpoint: "https://…" }` sends the same batches to a collector you run + instead (the worker in `telemetry-worker/` deploys to any Cloudflare account). + +## Options + +```ts +GenClass.init({ + telemetry: { + endpoint: "https://…", // default DEFAULT_TELEMETRY_ENDPOINT + sample: 0.25, // fraction of page loads that send (default 1) + flushMs: 10_000, // batch interval + maxBatch: 100, // events per request + include: { situation: false }, // leave the situation text out + }, +}); +``` + +`telemetry: true` is the defaults; `telemetry: false` turns it off. + +## Opting out + +Any one of these turns telemetry off for the page: + +| how | who | +|---|---| +| `GenClass.init({ telemetry: false })` (or `window.GENCLASS_CONFIG = { telemetry: false }`, ``, `data-telemetry="off"` on the script tag) | the app developer | +| `?genclass=no-telemetry` in the page URL (`?genclass=off` turns GenClass off entirely) | anyone, for one page load | +| `localStorage.setItem("genclass.telemetry", "off")` | a user or tester, persistent per origin | +| **Global Privacy Control**: `navigator.globalPrivacyControl === true` | the user's browser setting | + +**Global Privacy Control (GPC).** California law (CCPA as amended by the CPRA, and its regulations) requires +businesses to treat a GPC signal as a valid request to opt out of the sale or sharing of personal information, and +other US state laws (e.g. Colorado, Connecticut) recognise universal opt-out signals. GenClass honours GPC for every +visitor, wherever they are: when the browser sends it, nothing is collected. + +## If you ship GenClass in your app + +The data is collected from **your** users' browsers. Even though it is designed to be anonymous (random per-page +session id, no IP or user agent stored, redacted text), situation text can contain fragments of your app's data and +the session event names your hostname. Depending on your users and jurisdiction you may need to: + +- mention GenClass diagnostics in your privacy policy / cookie or tracking disclosures (GDPR transparency, + Articles 13 and 14; CCPA notice at collection); +- decide whether it needs consent where you require consent for analytics (GDPR / ePrivacy), and if so start + GenClass with `telemetry: false` until consent is given (`GenClass.init()` reads the option once; to switch it on + later, create the runtime after consent); +- turn it off (`telemetry: false`) in apps that handle regulated data (health, finance, children's services): a + custom `redact` lowers what reaches situation text but does not guarantee that nothing sensitive does. + +The GenClass maintainers' privacy policy and data processing terms for this collection are not published yet +(`OPEN_TASKS.md`). Until they are, if you cannot disclose a third-party diagnostics recipient, set +`telemetry: false`. From df6a12f3912ba58ba2cca7d42c0abb4b44e0e8a9 Mon Sep 17 00:00:00 2001 From: Karan Date: Thu, 8 Oct 2026 23:34:10 -0400 Subject: [PATCH 25/25] release: @genclass/runtime 0.1.0-beta.3 (default-on anonymous telemetry; privacy-relevant) Bump @genclass/runtime and the genclass-runtime alias (and its pinned dependency) to 0.1.0-beta.3; RUNTIME_VERSION to match; package.json files ships TELEMETRY.md; package-lock.json refreshed (versions only). READMEs: beta.3 status and pinned CDN URL; OPEN_TASKS Next; RELEASE.md next-release note with the publish commands. Co-Authored-By: Claude Opus 5.5 --- OPEN_TASKS.md | 14 ++++++++------ README.md | 6 +++--- RELEASE.md | 9 ++++++++- package-lock.json | 6 +++--- packages/genclass-runtime/package.json | 4 ++-- packages/runtime/README.md | 6 +++--- packages/runtime/package.json | 3 ++- packages/runtime/src/version.ts | 2 +- 8 files changed, 30 insertions(+), 20 deletions(-) diff --git a/OPEN_TASKS.md b/OPEN_TASKS.md index 7f3adac6..6f114ec2 100644 --- a/OPEN_TASKS.md +++ b/OPEN_TASKS.md @@ -7,8 +7,9 @@ release commit 806a296); `mvp-v2-merge` merges the two. Spec: The runtime decides through a trained local model; nothing here is hardcoded per bug pattern. The training format is frozen at tag **`situation-v2`** (commit 6e5e86e). On npm (`latest`): `@genclass/runtime@0.1.0-beta.1` -with `@genclass/runtime-model@0.2.0` (`r17-v2dT`); `0.1.0-beta.2` (the merge of both branches, observe default) is -packed on `mvp-v2-b6` and waits to be published (Done, Next). +with `@genclass/runtime-model@0.2.0` (`r17-v2dT`); `0.1.0-beta.2` (the merge of both branches, observe default) was +packed on `mvp-v2-b6` for publishing, and `0.1.0-beta.3` (beta.2 + default-on telemetry, privacy-relevant) is +packed on top of it and waits to be published (Done, Next). ## Done @@ -125,10 +126,11 @@ Mehar operates the Azure cluster; nobody else touches Azure. The jobs below run The usual order (HANDOFF.md): v2 data collected → teacher → labels → distillation → DAgger → EVAL → model package → demos rerun → runtime release. -- **Publish `@genclass/runtime@0.1.0-beta.2`** (`--tag latest`) and the `genclass-runtime@0.1.0-beta.2` alias from - the packed tarballs (RELEASE.md, top note), then deprecate `0.1.0-beta.1` ("defaults to guard and lacks the - observe/redaction/install fixes; use 0.1.0-beta.2 or later") after checking with Mehar. -- **Push `mvp-v2-b6` and the tags** (`v0.1.0-beta.0`, `runtime-model-v0.1.0`, `v0.1.0-alpha.1`, and `v0.1.0-beta.2` +- **Publish `@genclass/runtime@0.1.0-beta.3`** (`--tag latest`) and the `genclass-runtime@0.1.0-beta.3` alias from + the packed tarballs (RELEASE.md, top note; `0.1.0-beta.2` may already be published), then deprecate `0.1.0-beta.1` + ("defaults to guard and lacks the observe/redaction/install fixes; use 0.1.0-beta.2 or later") after checking + with Mehar. Decide the telemetry owner items under "Needs the user" first or right after. +- **Push `mvp-v2-b6` and the tags** (`v0.1.0-beta.0`, `runtime-model-v0.1.0`, `v0.1.0-alpha.1`, `v0.1.0-beta.2` and `v0.1.0-beta.3` once published) through an account with write access to daybot-solutions-inc/GenClass-lib; merge it back into `runtime` so the two branches stop diverging on the default mode. GitHub releases are optional. - **Re-measure observe mode on model 0.2.0** (false flags per profile's report threshold 0.95 / 0.90 / 0.70); the diff --git a/README.md b/README.md index 4ac32e77..eb112541 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ generic facts about each write, request and response, and asks a small GenClass The model runs in the browser (WebGPU or WASM, in a Web Worker). It answers two questions: what is happening, and which available action is best. There is no list of known bugs in the code. -> **Status: beta. `@genclass/runtime@0.1.0-beta.2` with the model `@genclass/runtime-model@0.2.0`.** +> **Status: beta. `@genclass/runtime@0.1.0-beta.3` with the model `@genclass/runtime-model@0.2.0`.** > > - **Runtime:** works and is unit-tested (situation format tag `situation-v2.3`). Install with > `npx @genclass/runtime init`, one import (`@genclass/runtime/auto`) or one script tag. @@ -49,7 +49,7 @@ which available action is best. There is no list of known bugs in the code. > [OPTIONS-SPEC.md](docs/runtime/OPTIONS-SPEC.md). > - **Older versions on npm:** `0.1.0-beta.1` (model 0.2.0 and the options, but `guard` by default and without the > observe-delivery, redaction and install fixes), `0.1.0-beta.0` (model 0.1.0), `0.1.0-alpha.1` and -> `0.1.0-alpha.0` (no model). Use `0.1.0-beta.2`. +> `0.1.0-alpha.0` (no model). `0.1.0-beta.2` is `0.1.0-beta.3` without telemetry. Use `0.1.0-beta.3`. > > - **Privacy notice (since `0.1.0-beta.3`): anonymous diagnostics are on by default** in browsers. GenClass sends > its decisions, including the redacted situation text the model read, to the GenClass maintainers to improve the @@ -158,7 +158,7 @@ NODE_OPTIONS=--expose-gc npx vitest run test/review-perf.test.ts --retry=2 # t The same steps run in CI ([.github/workflows/ci.yml](.github/workflows/ci.yml), Node 22) on pushes to `main`, `runtime`, `mvp` and `mvp-v2`, on pull requests, and on manual dispatch. -Last full local run (2026-10-08, branch `mvp-v2-b6`, version `0.1.0-beta.2`): 461 tests passed and 14 skipped, plus +Last full local run (2026-10-09, branch `mvp-v2-b6`, version `0.1.0-beta.3`): 474 tests passed and 14 skipped, plus the 4 perf tests run alone. The skips are model-parity tests, which need `GENCLASS_MODEL_DIR`. The perf tests time a 5,000-item store and can fail under parallel load. diff --git a/RELEASE.md b/RELEASE.md index 7ffe41a5..67296420 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -4,7 +4,14 @@ > **Read this when:** you are asked to cut a release, prepare a tarball for the user to publish, or package a trained model. > **Source of truth:** the code. Verified 2026-10-08 (~07:00 UTC) against branch `mvp-v2-merge` at f107013. That branch is `mvp-v2` (release commit 806a296), merged with origin/runtime eff18cb (dabbce2), plus the two runtime fixes 054da38 and f107013. Newer commits on origin/runtime (up to 5bc40c9) were read with `git show` and are not merged on this branch. If this doc and the code disagree, the code wins. -> **Next release: `@genclass/runtime@0.1.0-beta.2` (prepared on `mvp-v2-b6`, not published).** It merges +> **Next release: `@genclass/runtime@0.1.0-beta.3` (prepared on `mvp-v2-b6`, not published; privacy-relevant).** +> `0.1.0-beta.2` plus default-on anonymous telemetry (`packages/runtime/TELEMETRY.md`, collector `telemetry-worker/` +> deployed at `https://genclass-telemetry.mehar-144.workers.dev`). The alias `genclass-runtime@0.1.0-beta.3` pins it. +> Publish from `packages/runtime`: `npm publish genclass-runtime-0.1.0-beta.3.tgz --access public --tag latest`, then +> from `packages/genclass-runtime`: `npm publish genclass-runtime-0.1.0-beta.3.tgz --access public --tag latest`. +> `src/version.ts` -> `RUNTIME_VERSION` must equal `package.json` `version` on every bump (a unit test checks it). +> +> **Previous: `@genclass/runtime@0.1.0-beta.2` (prepared on `mvp-v2-b6`).** It merges > `0.1.0-beta.1` (published by Mehar from `runtime` at 696b1b4 with `@genclass/runtime-model@0.2.0`, defaulting to > `guard`) with the `0.1.0-beta.0` fixes: observe default, observe never delaying deliveries, redaction, install CLI, > jsDelivr `fetch-model` default (model `0.2.0`). The alias `genclass-runtime@0.1.0-beta.2` pins it. Publish from diff --git a/package-lock.json b/package-lock.json index fd36ac3f..ab787d7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3147,10 +3147,10 @@ } }, "packages/genclass-runtime": { - "version": "0.1.0-beta.2", + "version": "0.1.0-beta.3", "license": "Apache-2.0", "dependencies": { - "@genclass/runtime": "0.1.0-beta.2" + "@genclass/runtime": "0.1.0-beta.3" }, "bin": { "genclass-runtime": "cli.mjs" @@ -3161,7 +3161,7 @@ }, "packages/runtime": { "name": "@genclass/runtime", - "version": "0.1.0-beta.2", + "version": "0.1.0-beta.3", "license": "Apache-2.0", "dependencies": { "onnxruntime-web": "^1.30.0" diff --git a/packages/genclass-runtime/package.json b/packages/genclass-runtime/package.json index 9775f2b0..9e17f88c 100644 --- a/packages/genclass-runtime/package.json +++ b/packages/genclass-runtime/package.json @@ -1,6 +1,6 @@ { "name": "genclass-runtime", - "version": "0.1.0-beta.2", + "version": "0.1.0-beta.3", "description": "Short alias for the @genclass/runtime CLI: npx genclass-runtime init sets up GenClass Runtime in your app.", "type": "module", "license": "Apache-2.0", @@ -8,6 +8,6 @@ "homepage": "https://www.npmjs.com/package/@genclass/runtime", "bin": { "genclass-runtime": "./cli.mjs" }, "files": ["cli.mjs", "README.md", "LICENSE"], - "dependencies": { "@genclass/runtime": "0.1.0-beta.2" }, + "dependencies": { "@genclass/runtime": "0.1.0-beta.3" }, "engines": { "node": ">=20" } } diff --git a/packages/runtime/README.md b/packages/runtime/README.md index 9b201c32..0823fd93 100644 --- a/packages/runtime/README.md +++ b/packages/runtime/README.md @@ -29,7 +29,7 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known > browsers sending Global Privacy Control are never collected. Details: [Privacy and telemetry](#privacy-and-telemetry) > and [TELEMETRY.md](https://github.com/daybot-solutions-inc/GenClass-lib/blob/main/packages/runtime/TELEMETRY.md). -> **Status: beta (`0.1.0-beta.2`), with model `@genclass/runtime-model@0.2.0`.** +> **Status: beta (`0.1.0-beta.3`), with model `@genclass/runtime-model@0.2.0`.** > > - **The model loads by default.** A default `GenClass.init()` loads `@genclass/runtime-model@0.2.0` (10.2 MB q8, > `genclass-runtime-r17` 2.0.0-rc4t, run `r17-v2dT`, with a gain gate and three aggressiveness profiles) from @@ -44,7 +44,7 @@ GenClass.init(); // observe mode: reports only, never takes an action (see Known > `cautious`, 0.005% and 0.26%, under them. No wrong interventions were seen on held-out real apps. At `balanced`, > guard acts on under 8% of the cases where acting would help. Details: [Model quality](#model-quality) and the > [model card](https://www.npmjs.com/package/@genclass/runtime-model). -> - **Older versions.** `0.1.0-beta.1` has model 0.2.0 and the new options but defaults to `guard`, and lacks the +> - **Older versions.** `0.1.0-beta.2` is this release without telemetry. `0.1.0-beta.1` has model 0.2.0 and the new options but defaults to `guard`, and lacks the > observe-delivery, redaction and install fixes of `0.1.0-beta.0` (all back in `0.1.0-beta.2`). `0.1.0-beta.0` > ships model 0.1.0. `0.1.0-alpha.1` and `0.1.0-alpha.0` (v1 runtime: guard by default, holds store writes, `NaN` > crash) predate the model; do not use them. @@ -148,7 +148,7 @@ SSR or in Node, `/auto` installs nothing and returns an inert runtime. It exposes `window.GenClass` and loads the model worker, ONNX Runtime Web and the overlay on demand from the same version on the CDN. `data-mode` takes `observe` (the default), `guard` or `heal`; `data-devtools="local"` shows the overlay only on localhost; `data-manual` skips the automatic `GenClass.init()`. Pin a version in production -(`https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.2`); the plain-HTML path of `init` writes a pinned +(`https://cdn.jsdelivr.net/npm/@genclass/runtime@0.1.0-beta.3`); the plain-HTML path of `init` writes a pinned jsDelivr URL with SRI. **4. By hand:** diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 7fac34c9..0df3a4ee 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@genclass/runtime", - "version": "0.1.0-beta.2", + "version": "0.1.0-beta.3", "description": "A client-side AI runtime for web apps: a local GenClass model watches user actions, async work, network, state and errors, and prevents stale writes, races, duplicates, inconsistent state and failure storms in real time.", "type": "module", "license": "Apache-2.0", @@ -97,6 +97,7 @@ "dist", "bin", "README.md", + "TELEMETRY.md", "LICENSE" ], "scripts": { diff --git a/packages/runtime/src/version.ts b/packages/runtime/src/version.ts index e7b243ca..018f169c 100644 --- a/packages/runtime/src/version.ts +++ b/packages/runtime/src/version.ts @@ -1,4 +1,4 @@ // The package version, for telemetry batches and diagnostics. Kept equal to package.json "version" by // test/telemetry.test.ts ("RUNTIME_VERSION matches package.json"); bump both together (RELEASE.md). -export const RUNTIME_VERSION = "0.1.0-beta.2"; +export const RUNTIME_VERSION = "0.1.0-beta.3";