# Next-generation implementation contract

User brief: 16 October 2026. Deliver stable P0/P1/P2 work; explicitly defer experimental social networks and optional LLM features rather than destabilising the model. No expenditure or public publication without account permission. Preserve all earlier apps and evidence.

## Runtime and ownership

Static offline/HTTPS application, classic scripts (no file:// ES-module dependency), no external libraries or network APIs. Root is `Next Generation/`. All public assets stay in this folder. Preserve original verified engine byte-for-byte as `legacy-engine.js`, exposing AmasworldEngine. New modules use UMD/CommonJS for Node tests and named window globals for browsers.

Load order: legacy-engine.js, school.js, simulation.js, analysis.js, storage.js, app.js. UI/styles are owned by UI worker, school/simulation/analysis and model tests by model worker; parent owns storage.js, browser QA, packaging, deployment, git and integration. Documentation worker owns docs/ only.

## School API — window.AmasworldSchool

`DEFAULT_CONFIG`, `validateConfig(input) -> normalized config`, `generateSchool(config) -> school`, `validateSchool(school) -> normalized/rebuilt school`.

Config fields: `{name:'Amasworld Modellschule', studentCount:300, classCount:12, seed:20261004, ageMin:12, ageMax:16, classSizes:null, motivationShift:0, organizationShift:0, performanceShift:0, stressSensitivityVariation:0}`. Preserve population50..300, classCount1..min(24,studentCount), seed0..2147483647, ages10..19, shifts -20..20, sensitivityVariation0..0.4. Explicit classSizes if supplied must be positive integer array of classCount length summing to studentCount. Default evenly allocated classes. All inputs strictly validated; names plain text max80 chars, no HTML interpretation. Metadata RNG separate from numerical initial-state RNG.

School: `{schema:'amasworld-school', schemaVersion:1, generatorVersion:'1.0', config, classes:[{id:'class-01',name:'Klasse 01',ageGroup:12,studentIds:[...] }], students:[{id:'Student-001',name:'fictional name',classId:'class-01',age:12,traits:{stressSensitivity:1,academicReadiness:60},initial:{motivation,stress,learning,focus,organization,performance}}]}`.

Default numerical initial states must equal legacy makeAgents(count,seed) exactly. Metadata and class grouping do not affect legacy numbers. Shifts and stress-sensitivity variation are explicit hypothetical model settings, neutral by default. Academic readiness means the initial performance value, not an independent validated trait. Do not invent learning-style science or model social support without actual rules.

## Simulation API — window.AmasworldSimulation

`MODEL_VERSION` = `2.0-school`, `SCENARIOS` map with labels/descriptions/equation effects, `normalizeSettings(settings,school)`, `runExperiment({school,settings}) -> experiment`.

Settings `{totalDays:10, scenarioKey:'exam', intensity:2, seed:20261004,eventStart:null,eventEnd:null,affectedClassIds:[]}`. totalDays5..30; intensity0..3 for internal tests (UI1..3); seed integer0..2147483647. Null event start/end means automatic legacy schedule, otherwise both integer 1..totalDays with start<=end. Empty affectedClassIds means all classes, otherwise validated class IDs. Population always comes from school. School seed determines initial students; experiment seed determines matched daily background fluctuations. Standard default matching school and experiment seeds must reproduce legacy reference exactly.

Scenarios: normal/exam/technical/closure/cancelled retained. Add only explicitly documented hypothetical homework/starttime/timetable scenarios. No mandatory AI calls, news, multi-events or peer graph in this release.

Experiment `{schema:'amasworld-experiment',schemaVersion:2,modelVersion, school, settings, baseline:{daily:[{day:0,event:'Startwerte',motivation,stress,learning,focus,organization,performance},...],history:[[state,...],...]},scenario:{daily:[...],history:[[state,...],...]},performance:{elapsedMs,...}}`. A state is `{id,...six numeric variables}`. Index equals actual day0..totalDays; state array order matches school.students. Independent snapshots; no aliasing. School includes identity metadata once, not on every day. Baseline/scenario histories matched initial values and background draws. Consume fixed six random draws per agent/day. Class targeting and arbitrary event dates cannot shift random streams. Individual sensitivity only modifies explicitly defined event stress response. Version new rules; never alter legacy-engine.js.

## Analysis API — window.AmasworldAnalysis

`METRICS` array of `{key,label,unit,min,max}` for six values.
`selectStates(experiment,condition,day,classId='') -> state[]`, condition baseline/scenario.
`summary(experiment,day,classId='') -> {count,baseline:{six means},scenario:{six means},delta:{six differences}}`.
`stats(values) -> {count,min,max,mean,p10,p25,median,p75,p90}`; document interpolated percentiles.
`histogram(values,min,max,bins=10) -> [{min,max,count}]`, final bucket inclusive of max.
`compareClasses(experiment,day,metric) -> [{classId,name,count,baseline,scenario,delta}]`.
`explain(experiment,metric) -> German deterministic text grounded in actual values and model rules`.

Switching day/metric/class/profile reads cached histories, never reruns. Individual lookup uses stable IDs, not display names.

## Parent-owned storage API — window.AmasworldStorage

`saveSchool(school) -> boolean`, `loadSchool() -> school|null`, `clearSaved()`, `schoolDocument(school) -> JSON object`, `importDocument(object) -> {kind:'school',school}|{kind:'experiment',experiment}`. Import regenerates school from validated config and reruns experiments, never trusts imported results. `experimentDocument(experiment)` outputs v2 school+settings+metadata; may include results but never trusts them on import. `importDocument` also migrates legacy schemaVersion1 experiments to neutral school/class config while preserving count,seed,days,scenario,intensity and exact compatible values. Unknown model/schema versions rejected. API size limits controlled at file read; localStorage failure nonfatal. UI handles download blobs/print.

## UI ownership

UI worker creates index.html, styles.css, app.js and optional icons.js only, plus UI README if useful. Professional neutral monochrome sidebar navigation: dashboard, builder, explorer, studio, analysis, methodology, settings. Every control real/functional. Public-relative links only (no ../private vault references). Accessible native dialogs, labels, tables, day slider actual states, student search/sort/class filter, profiles with paired charts and per-day values, class comparison/distribution, all six metric cards, timing/target-class options, saved config import/export, CSV mean and individual exports, printable report. Public information and help live in docs/. Preserve old app unchanged.

## Verification and delivery

Legacy22 tests remain untouched/pass. New Node tests cover deterministic school/class allocation, IDs, strict invalid inputs, complete histories, exact legacy compatibility, zero intensity, pre-event equality, unchanged untargeted agents, event schedule, bounds, stats/histograms, import migration/recomputation and measured performance. Parent runs actual Windows Edge UI/download/import/keyboard/mobile/HTTP+offline checks and screenshots. Chrome/Firefox/Safari only claimed if actually exercised. Public ZIP excludes private project notes/credentials. Local Git in Next Generation only; truthful AI commit identity, no fabricated old history. Public hosting account/permission required; never invent live URL.
