Files
wibosim/server/test/simkit.js
T
db9979andClaude Opus 5.5 4fec7fb5e5 Diagnose-Export für die Spielleitung: anonymisierte Datei und Prüfbericht mit Ampel
Admin → Protokoll & Sicherungen → Betrieb → Diagnose-Export: GET /api/admin/diagnose liefert
wibosim-diagnose-<version>-<datum>.json.gz (Admin, rate-begrenzt, Audit-Log), ?format=kurz den
Prüfbericht als Text (höchstens 15 KB). Aufbau als Register (diagnose.js, diagsections.js) mit
Abdeckungs-Test: jeder gespeicherte Zustandsbereich ist exportiert oder mit Begründung ausgenommen.
Anonymisierung in zwei Stufen (Kürzel S01 …, danach Bereinigung aller Texte und Schlüssel).

Neu: Diagnose-Protokoll g.diag (Geldströme, Handel, Ablehnungsgründe, Hebel, Kursursachen,
Nachrichtenwirkung, Feed-Statistik, Spieltakt, Antwortzeiten, Browser-Fehler, Tagesverlauf über
120 Handelstage), Invarianten live (invchecks.js, gemeinsam mit der Prüf-Simulation), Zielwerte
als einzige Quelle (diagtargets.js), scripts/diagnose.mjs (Prüfbericht, Vergleich zweier Exporte).
Doku: BETRIEB.md, API.md, ARCHITEKTUR.md (Regel für neue Datenfelder).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-06 08:59:43 +00:00

286 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Prüf-Simulation (Invarianten) für WiBoSim: unabhängiges Hauptbuch, Invarianten-Prüfungen, Neustart-Vergleich und
// eine Liste von Ereignis-Auslösern. Genutzt von src/invariants.test.js (Belastungstest Orders), src/soak.test.js
// (schneller Lauf in `npm test`) und scripts/soak.mjs (`npm run soak -- --days 60 --seed 7`).
//
// ---------------------------------------------------------------------------------------------------------------
// Geldmenge – erlaubte Quellen und Senken
// ---------------------------------------------------------------------------------------------------------------
// Die Summe aller Kontostände (Hauptdepots inkl. Rivalen, Battle-Depots, Clan-Fonds) ändert sich NUR durch Buchungen
// (game.recordFill) oder durch das Anlegen/Löschen von Konten. Jede Buchungsart hat genau eine Geldwirkung (MONEY):
// Gegenpartei außerhalb der Spielerkonten (Quelle/Senke):
// trade, auction, evening – Ausführung gegen Bots/Market Maker (Spieler-gegen-Spieler hebt sich auf)
// ipo – Zuteilung bei einem Börsengang (Geld geht an das Unternehmen)
// tender – Andienung an einen Bieter (Firma: Quelle; Pflichtangebot eines Spielers: neutral)
// delist, default – Abfindung bei Rückzug von der Börse / Restwert einer ausgefallenen Anleihe
// fundclose – Fondsauflösung: Positionen zum letzten Kurs (Gegenpartei: Markt)
// deriv, derivExpiry, derivKO, derivSeason, derivClose, derivDelist – Emittent der Hebelprodukte
// dividend, coupon – Ausschüttungen (Quelle)
// tax – Abgeltungsteuer (Senke) bzw. Erstattung (Quelle)
// cancel, borrow, fine, party, lobby – Gebühren, Leihgebühr, Bußgeld, Parteigründung, Lobby (Senken)
// admin – Nachschuss/Belastung der Spielleitung (Betrag im Feld price)
// split – Spitzenausgleich bei einer Zusammenlegung (Betrag im Feld cash, sonst 0)
// spinoffCash, mergerCash – Barausgleich für Bruchteile bei Abspaltung/Fusion (Betrag im Feld cash)
// firm – Spielerfirma (firm.js): Einlage, Eigengeschäft, Auszahlung (Betrag mit Vorzeichen im Feld cash)
// Ohne Geldwirkung: spinoff (Einbuchung der Tochter), merger (Ausbuchung des Ziels, Einbuchung des Käufers)
// Überträge zwischen Konten (neutral): fund (Fonds-Ein-/Auszahlung), fundfee (Verwaltungsgebühr an den Manager)
// Konten anlegen (Registrierung, Rivale, Battle-Depot, Fonds) ist eine Quelle in Höhe des Startguthabens; Konten
// löschen (Battle-Ende, Fondsauflösung, Spieler löschen) eine Senke in Höhe des Restguthabens. Saisonende und
// Depot-Reset setzen alle Depots neu auf (geprüft wird dann: Startkapital, keine Positionen/Orders/Hebelprodukte).
// Unbekannte Buchungsarten lassen die Prüfung scheitern – neue Arten müssen hier eingetragen werden.
//
// Stückzahlen: Für jedes Wertpapier gilt Σ Bestände aller Konten (long − short) + Netto der Bots/Market Maker im
// Orderbuch + Netto aller Gegenbuchungen außerhalb des Orderbuchs (Börsengang, Andienung, Abfindung, Abendhandel,
// Fondsauflösung, gelöschte Konten, Abspaltung, Fusion) = 0. Ein Aktiensplit skaliert alle drei Größen des Symbols
// (Konten aus den split-Buchungen: qty = neuer Bestand, before = alter Bestand; Bots und Gegenbuchungen × Verhältnis). Zusätzlich: Long-Bestände der Spieler ≤ ausgegebene Aktien (s.shares).
import assert from 'node:assert/strict';
import { MONEY, POS_KINDS, EXT_KINDS, DERIV_KINDS, FEE_KINDS, CHECKS, finiteDeep } from '../src/invchecks.js';
// Geldregeln und Invarianten liegen in src/invchecks.js (auch für den Diagnose-Export); hier weiter erreichbar
export { MONEY, POS_KINDS, EXT_KINDS, DERIV_KINDS, FEE_KINDS, CHECKS, finiteDeep };
const sgnOf = (f) => (f.side === 'buy' ? 1 : f.side === 'sell' ? -1 : 0);
/** reproduzierbarer Zufall (mulberry32) */
export function rng(seed) { let s = seed >>> 0; return () => { s = (s + 0x6D2B79F5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const isBotId = (id) => String(id).startsWith('bot:');
const BOOK_TAG = Symbol('simkit.book');
/**
* Beobachter: zählt jede Buchung mit und führt ein unabhängiges Hauptbuch. Nach einem Neustart (neues Game-Objekt)
* mit L.attach(g) neu anhängen – die Zähler bleiben erhalten.
*/
export function instrument(g, { debug = false } = {}) {
const L = {
pos: new Map(), // accId -> {sym: qty} aus den Fills
dpos: new Map(), // accId -> {productId: qty} aus den Hebelprodukt-Buchungen
fees: new Map(), // accId -> Summe Gebühren aus den Fills
tax: new Map(), // accId -> Summe der Steuerbuchungen (Einbehalt − Erstattung) seit dem letzten Neuaufsetzen
botNet: {}, // sym -> Nettobestand der Bots (aus den Trades des Orderbuchs)
sink: {}, // sym -> Gegenbuchungen außerhalb des Orderbuchs und gelöschte Konten
money: 0, // erwartete Summe aller Kontostände
flows: {}, // Geldwirkung je Buchungsart bzw. Kontoereignis (Bericht)
unknown: [], // Buchungsarten ohne Eintrag in MONEY
splitAcc: {}, // sym -> [{was, now}] Kontobestände eines laufenden Splits
fills: [], nFills: 0,
trades: [],
kinds: {},
debug,
g: null,
};
const flow = (k, v) => { L.flows[k] = (L.flows[k] ?? 0) + v; L.money += v; };
const pos = (m, id) => { if (!m.has(id)) m.set(id, {}); return m.get(id); };
L.flow = flow;
const onFill = (f) => {
L.nFills++;
L.kinds[f.kind] = (L.kinds[f.kind] ?? 0) + 1;
if (debug) L.fills.push(f); else if (L.fills.length < 400) L.fills.push(f);
const sgn = sgnOf(f);
if (POS_KINDS.has(f.kind)) {
const p = pos(L.pos, f.account);
p[f.symbol] = (p[f.symbol] ?? 0) + sgn * f.qty;
if (!p[f.symbol]) delete p[f.symbol];
if (EXT_KINDS.has(f.kind)) L.sink[f.symbol] = (L.sink[f.symbol] ?? 0) - sgn * f.qty;
}
if (f.kind === 'split') {
// Bestand neu aus der Buchung (Vorzeichen vom alten Bestand); Bots und Gegenbuchungen werden in L.splitDone skaliert
const p = pos(L.pos, f.account);
const was = p[f.symbol] ?? 0;
if (Number.isFinite(f.before)) assert.equal(was, f.before, `Split ${f.symbol}: Hauptbuch ${was} ≠ Bestand vor dem Split ${f.before} (${f.account})`);
const now = Math.sign(was) * f.qty;
(L.splitAcc[f.symbol] ??= []).push({ was, now });
p[f.symbol] = now;
if (!p[f.symbol]) delete p[f.symbol];
}
if (DERIV_KINDS.has(f.kind)) {
const p = pos(L.dpos, f.account);
p[f.symbol] = (p[f.symbol] ?? 0) + sgn * f.qty;
if (!p[f.symbol]) delete p[f.symbol];
}
if (FEE_KINDS.has(f.kind) && (f.side === 'buy' || f.side === 'sell' || f.side === 'fee')) L.fees.set(f.account, (L.fees.get(f.account) ?? 0) + f.fee);
if (f.kind === 'tax') L.tax.set(f.account, (L.tax.get(f.account) ?? 0) - f.realized);
const m = MONEY[f.kind];
if (!m) { L.unknown.push(f.kind); return; }
const v = m(f);
if (!Number.isFinite(v)) L.unknown.push(`${f.kind}(NaN)`);
else flow(f.kind, v);
};
const wrapBook = (s) => {
const book = s.book;
if (!book || book[BOOK_TAG]) return;
book[BOOK_TAG] = true;
const tally = (r) => {
for (const t of r?.trades ?? []) {
if (debug && (!isBotId(t.buyerId) || !isBotId(t.sellerId))) L.trades.push({ symbol: s.symbol, id: t.id, buyerId: t.buyerId, sellerId: t.sellerId, qty: t.qty, price: t.price, auction: t.auction, n: L.nFills });
if (isBotId(t.buyerId)) L.botNet[s.symbol] = (L.botNet[s.symbol] ?? 0) + t.qty;
if (isBotId(t.sellerId)) L.botNet[s.symbol] = (L.botNet[s.symbol] ?? 0) - t.qty;
}
return r;
};
const sub = book.submit.bind(book), unc = book.uncross.bind(book);
book.submit = (...a) => tally(sub(...a));
book.uncross = (...a) => tally(unc(...a));
};
L.wrapBooks = () => { for (const s of L.g.stocks.values()) wrapBook(s); };
/** Konto verlässt das System: Restbestände und Restgeld sind eine Senke */
const dropAcc = (acc, why) => {
for (const [sym, p] of Object.entries(acc.positions ?? {})) L.sink[sym] = (L.sink[sym] ?? 0) + p.qty;
flow(why, -acc.cash);
L.pos.delete(acc.id); L.dpos.delete(acc.id); L.fees.delete(acc.id); L.tax.delete(acc.id);
};
const addAcc = (acc, why) => {
flow(why, acc.cash);
for (const [sym, p] of Object.entries(acc.positions ?? {})) { pos(L.pos, acc.id)[sym] = p.qty; L.sink[sym] = (L.sink[sym] ?? 0) - p.qty; }
if (acc.fees) L.fees.set(acc.id, acc.fees);
if (acc.tax?.paid) L.tax.set(acc.id, acc.tax.paid);
};
/** an ein (neues) Game-Objekt anhängen */
L.attach = (gg) => {
L.g = gg;
const orig = gg.recordFill.bind(gg);
gg.recordFill = (f) => { onFill(f); return orig(f); };
const mk = gg.makeStock.bind(gg);
gg.makeStock = (...a) => { const s = mk(...a); wrapBook(s); return s; };
L.wrapBooks();
const bd = gg.battleAccounts.delete.bind(gg.battleAccounts), bs = gg.battleAccounts.set.bind(gg.battleAccounts);
gg.battleAccounts.delete = (id) => { const acc = gg.battleAccounts.get(id); if (acc) dropAcc(acc, 'kontoGeloescht'); return bd(id); };
gg.battleAccounts.set = (id, acc) => { if (!gg.battleAccounts.has(id)) addAcc(acc, 'kontoAngelegt'); return bs(id, acc); };
const pd = gg.players.delete.bind(gg.players), ps = gg.players.set.bind(gg.players);
gg.players.delete = (id) => { const p = gg.players.get(id); if (p) dropAcc(p, 'spielerGeloescht'); return pd(id); };
gg.players.set = (id, p) => { if (!gg.players.has(id)) addAcc(p, 'spielerAngelegt'); return ps(id, p); };
// Saisonende / Depot-Reset: neue Basis (die Liquidationen davor sind normale Buchungen)
const es = gg.endSeason.bind(gg);
gg.endSeason = (...a) => { const r = es(...a); L.rebase('saisonende'); L.afterSeason = gg.day; return r; };
// Aktiensplit: Bots und Gegenbuchungen des Symbols mit dem Verhältnis skalieren. Die Konten kommen aus den
// split-Buchungen; Spitzen (Zusammenlegung) gehen bar weg. Ganzzahlig: Bots gerundet, Rest außerhalb des Buchs.
const sa = gg.splits.apply.bind(gg.splits);
gg.splits.apply = (s, opts) => {
L.splitAcc[s.symbol] = [];
const r = sa(s, opts);
const f = (opts?.num ?? 1) / (opts?.den ?? 1);
const accs = L.splitAcc[s.symbol]; delete L.splitAcc[s.symbol];
const heldOld = accs.reduce((a, x) => a + x.was, 0), heldNew = accs.reduce((a, x) => a + x.now, 0);
const ledOther = [...L.pos.values()].reduce((a, p) => a + (p[s.symbol] ?? 0), 0) - heldNew; // Konten ohne Buchung (sollte 0 sein)
assert.equal(ledOther, 0, `Split ${s.symbol}: Konten mit Bestand ohne split-Buchung`);
const bot = L.botNet[s.symbol] ?? 0, sink = L.sink[s.symbol] ?? 0;
assert.equal(heldOld + bot + sink, 0, `Split ${s.symbol}: Stückzahl schon vor dem Split nicht erhalten`);
L.botNet[s.symbol] = Math.round(bot * f);
L.sink[s.symbol] = -heldNew - L.botNet[s.symbol];
return r;
};
const aa = gg.adminAction.bind(gg);
gg.adminAction = (actor, action, opts) => {
if (action !== 'reset') return aa(actor, action, opts);
const p = gg.players.get(opts?.id);
if (p) dropAcc(p, 'depotReset');
const r = aa(actor, action, opts);
if (p) addAcc(p, 'depotReset');
return r;
};
return L;
};
/** Ledger an den Ist-Stand anlegen (Saisonende): Geld- und Bestandsdifferenz als benannte Quelle/Senke */
L.rebase = (why) => {
const accs = L.g.allAccounts();
const money = accs.reduce((a, x) => a + x.cash, 0);
flow(why, money - L.money);
for (const acc of accs) {
const led = L.pos.get(acc.id) ?? {};
for (const sym of new Set([...Object.keys(led), ...Object.keys(acc.positions)])) {
const d = (acc.positions[sym]?.qty ?? 0) - (led[sym] ?? 0);
if (d) L.sink[sym] = (L.sink[sym] ?? 0) - d;
}
L.pos.set(acc.id, Object.fromEntries(Object.entries(acc.positions).map(([k, p]) => [k, p.qty])));
L.dpos.set(acc.id, Object.fromEntries(Object.entries(acc.derivs ?? {}).map(([k, p]) => [k, p.qty])));
L.fees.set(acc.id, acc.fees ?? 0);
L.tax.set(acc.id, acc.tax?.paid ?? 0);
}
};
L.attach(g);
L.money = g.allAccounts().reduce((a, x) => a + x.cash, 0);
L.flows.start = L.money;
for (const acc of g.allAccounts()) addAcc({ ...acc, cash: 0 }, 'start');
return L;
}
/** alle Invarianten prüfen; extra: weitere {name, run}-Einträge */
export function checkAll(g, L, where, extra = []) {
L.wrapBooks();
for (const c of [...CHECKS, ...extra]) c.run(g, L, where);
}
// ---------------------------------------------------------------------------------------------------------------
// Neustart: Zustand vor dem Speichern == Zustand nach dem Laden
// ---------------------------------------------------------------------------------------------------------------
const norm = (x) => JSON.parse(JSON.stringify(x ?? null));
const r6 = (x) => (Number.isFinite(x) ? Math.round(x * 1e6) / 1e6 : x);
/** Konten (Salden, Bestände, Orders) – auch nach einem Absturz ohne Meta-Speicherung identisch */
export function accountsState(g) {
const accs = {};
for (const a of g.allAccounts()) {
accs[a.id] = norm({
cash: a.cash, fees: a.fees, realized: a.realized, locked: !!a.locked, units: a.units ?? null, totalUnits: a.totalUnits ?? null,
positions: Object.fromEntries(Object.entries(a.positions).map(([k, p]) => [k, { qty: p.qty, avgCost: p.avgCost }])),
derivs: Object.fromEntries(Object.entries(a.derivs ?? {}).map(([k, p]) => [k, { qty: p.qty, avgCost: p.avgCost }])),
alerts: (a.alerts ?? []).map((x) => `${x.symbol}:${x.price}:${x.dir}`).sort(), watch: [...(a.watch ?? [])].sort(),
orders: g.ex.ordersOf(a.id).map((o) => `${o.kind}:${o.id}:${o.symbol}:${o.side}:${o.qty}:${o.filled ?? ''}:${o.price ?? o.trigger ?? ''}`).sort(),
tax: a.tax ?? null,
});
}
return accs;
}
/** relevante Teile des Spielstands (für den Neustart-Vergleich nach geordnetem Speichern) */
export function gameState(g) {
const stocks = {};
for (const s of g.stocks.values()) {
stocks[s.symbol] = {
kind: s.kind, last: r6(s.last), shares: s.shares ?? null, delisted: s.delisted ?? null, fair: r6(s.fair), control: s.control ?? null,
refAuction: r6(s.refAuction), lend: s.lend ?? null, lastAuction: s.lastAuction ?? null,
};
}
return norm({
day: g.day, season: g.season.n, phase: g.market.phase,
accounts: accountsState(g),
stocks,
indices: { seg: g.indices.st.seg, idx: g.indices.st.idx, w10: g.indices.st.w10, values: Object.fromEntries(Object.keys(g.indices.st.idx).concat('WIBO10').map((id) => [id, r6(g.indices.value(id))])) },
marks: { bySym: g.marks.bySym, locked: g.marks.locked },
// Hebelprodukte: gehaltene müssen identisch sein; beim Laden darf der Emittent fehlende Serien neu auflegen
// (derivs.init → issue, wie alle 30 Takte) – daher nur „kein Produkt verschwindet“ (derivIds, siehe sameState)
derivs: [...g.derivs.products.values()].filter((p) => g.allAccounts().some((a) => a.derivs?.[p.id])).map((p) => `${p.id}:${p.u}:${p.kind}:${p.status}:${p.strike ?? ''}`).sort(),
derivIds: [...g.derivs.products.keys()].sort(),
cond: g.ex.condOrders.map((c) => `${c.id}:${c.symbol}:${c.qty}`).sort(),
offers: g.corp.offers.map((o) => ({ ...o, tenders: o.tenders })),
ipo: g.ipo.pending.map((x) => ({ id: x.id, symbol: x.symbol, status: x.status, orders: x.orders })),
listed: g.ipo.state.listed.map((x) => x.symbol),
clubs: [...g.clubs.clubs.values()].map((c) => ({ id: c.id, members: c.members.map((m) => m.id), fundId: c.fundId ?? null })),
etfs: Object.fromEntries(g.etfs.list().map((e) => [e.symbol, Object.fromEntries(Object.entries(e.asset?.basket ?? {}).map(([k, v]) => [k, r6(v)]))])),
delisted: g.delist.history.map((h) => h.symbol),
histories: { corp: g.corp.history.length, credit: g.credit.history.length, defaults: g.credit.defaults.length },
});
}
/** erste Abweichung zweier Zustände (Pfad) – für lesbare Fehlermeldungen */
export function firstDiff(a, b, path = '') {
if (a === b) return null;
if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return `${path || '/'}: ${JSON.stringify(a)?.slice(0, 120)} ≠ ${JSON.stringify(b)?.slice(0, 120)}`;
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const k of keys) { const d = firstDiff(a[k], b[k], `${path}/${k}`); if (d) return d; }
return null;
}
/** Neustart-Vergleich: null oder die erste Abweichung (neu aufgelegte Hebelprodukte beim Laden sind erlaubt) */
export function sameState(before, after) {
const { derivIds: a = [], ...b0 } = before, { derivIds: b = [], ...a0 } = after;
const gone = a.filter((id) => !b.includes(id));
if (gone.length) return `Hebelprodukte nach dem Laden verschwunden: ${gone.slice(0, 5).join(', ')}`;
return firstDiff(b0, a0);
}