diff --git a/AGENTS.md b/AGENTS.md index d890952..30b6a71 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,18 +6,18 @@ trading bot, portfolio manager, investment adviser, or renderer decoration. ## Authority Map - Owner: Stonks owns public market data polling, normalization, provenance, - freshness, its provider-owned Eve/CultUI surface, and local snapshot logs. + freshness, request-event persistence, and its provider-owned Eve/CultUI + surface. - Inputs: public market data endpoints, configured symbols/assets, local runtime configuration, and future provider-owned market data feeds. -- Outputs: `stonks.market_snapshot.v1`, `gamecult.eve.surface_state.v1`, - `/eve/deck`, `/eve/deck/providers`, `/health`, and ignored scratch snapshots - under `scratch/stonks/`. +- Outputs: `stonks.market_snapshot.v1`, `stonks.request_event.v1`, + `gamecult.eve.surface_state.v1`, the `scratch/stonks/stonks-state.cc` + CultCache document, `/eve/deck`, `/eve/deck/providers`, and `/health`. - Derived state: Odin, Nightwing, Eve clients, dashboards, and agents consume Stonks projections; they do not own market truth or scrape markets directly. - Forbidden writers: renderers, Odin, VoidBot rumination, and repo Faces must not invent market state. They consume the Stonks provider surface. - Shared paths: HTTP status, Eve surface, and future CultMesh documents are all - derived from the same normalized market snapshot. + derived from the same normalized market snapshot and request-event state. Markets own prices. Stonks owns the adapter. Odin sees the Verse. - diff --git a/README.md b/README.md index 94531da..34b4866 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ Stonks publishes market-data pulse into the GameCult CultMesh Verse. -It polls public equity/ETF and crypto endpoints, normalizes the result, writes a -local scratch snapshot, and exposes a provider-owned Eve/CultUI surface for -Odin and renderers such as Nightwing. +It polls public equity/ETF and crypto endpoints, normalizes the result into +CultCache state, and exposes a provider-owned Eve/CultUI surface for Odin and +renderers such as Nightwing. ## Current Body @@ -13,7 +13,9 @@ Odin and renderers such as Nightwing. - Provider manifest: `http://127.0.0.1:8802/eve/deck/providers` - Health: `http://127.0.0.1:8802/health` - Snapshot: `http://127.0.0.1:8802/market/state` -- Scratch state: `scratch/stonks/` +- CultCache state: `scratch/stonks/stonks-state.cc` +- Request events: persisted as keyed `stonks.request_event.v1` CultCache + documents and projected into the surface marquee. - Default focus: gaming and tech public names such as Ubisoft, EA, Take-Two, Roblox, Nintendo, Sony, Microsoft, NVIDIA, AMD, Google, Meta, Apple, TSMC, Tesla, ASML, Corsair, Logitech, and Sea. diff --git a/docs/architecture.md b/docs/architecture.md index 8525527..3f3f6e7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,8 @@ Odin can aggregate it and renderers can lower it without owning market state. ```text Public market endpoints -> Stonks poller - -> normalized market snapshot with provenance and freshness + -> request-event, market-snapshot, and Eve-surface CultCache documents + -> normalized market snapshot with provenance, freshness, and request history -> provider-owned Eve/CultUI surface -> /eve/deck WebSocket + /eve/deck/providers manifest -> Odin interface ingestion @@ -21,6 +22,8 @@ Public market endpoints - Market sources own prices and volumes. - Stonks owns polling, normalization, provenance, and surface publication. +- Stonks owns request-event persistence; Odin may publish request events on the + marquee, but it does not create or mutate them. - Odin owns discovery and aggregation, not market truth. - Renderers lower the Stonks surface only. - Stonks does not trade, advise, custody funds, or infer portfolio intent. @@ -29,4 +32,3 @@ Public market endpoints When a typed CultMesh market feed exists, replace public polling with provider documents while preserving the same normalized snapshot and Eve surface. - diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..b7a39ec --- /dev/null +++ b/package-lock.json @@ -0,0 +1,47 @@ +{ + "name": "@gamecult/stonks", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@gamecult/stonks", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "cultcache-ts": "file:../CultLib/packages/cultcache-ts" + }, + "engines": { + "node": ">=20" + } + }, + "../CultLib/packages/cultcache-ts": { + "version": "0.13.5", + "license": "MIT", + "dependencies": { + "@msgpack/msgpack": "^3.1.3", + "zod": "^3.25.76" + }, + "devDependencies": { + "@gamecult/norn-viewer": "file:../Norn/web/norn-viewer", + "@types/node": "^24.0.0", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.2", + "concurrently": "^9.2.1", + "cross-env": "^10.1.0", + "electron": "^42.1.0", + "electron-builder": "^26.8.1", + "react": "^19.2.6", + "react-dom": "^19.2.6", + "typescript": "^5.9.0", + "vite": "^8.0.13", + "wait-on": "^9.0.10" + } + }, + "node_modules/cultcache-ts": { + "resolved": "../CultLib/packages/cultcache-ts", + "link": true + } + } +} diff --git a/package.json b/package.json index 8410e4d..12bb5ba 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,11 @@ "check": "node --check src/stonks-daemon.cjs", "start": "node src/stonks-daemon.cjs" }, + "dependencies": { + "cultcache-ts": "file:../CultLib/packages/cultcache-ts" + }, "engines": { "node": ">=20" }, "license": "MIT" } - diff --git a/src/stonks-daemon.cjs b/src/stonks-daemon.cjs index 9630084..d6a688b 100644 --- a/src/stonks-daemon.cjs +++ b/src/stonks-daemon.cjs @@ -6,6 +6,12 @@ const fs = require("fs"); const http = require("http"); const https = require("https"); const path = require("path"); +const { + CultCache, + SingleFileMessagePackBackingStore, + defineDocumentRegistry, + defineDocumentType, +} = require("cultcache-ts"); const repoRoot = path.resolve(__dirname, ".."); const args = parseArgs(process.argv.slice(2)); @@ -13,8 +19,11 @@ const port = Number(args.port || process.env.STONKS_PORT || 8802); const host = args.host || process.env.STONKS_HOST || "0.0.0.0"; const intervalMs = Number(args.intervalMs || process.env.STONKS_INTERVAL_MS || 15000); const stateDir = args.stateDir || path.join(repoRoot, "scratch", "stonks"); +const cultCachePath = args.cultCachePath || process.env.STONKS_CULTCACHE_PATH || path.join(stateDir, "stonks-state.cc"); const providerId = "stonks.market"; const clients = new Set(); +const recentRequests = []; +const pendingCultCacheWrites = new Set(); const equitySymbols = String(args.equities || process.env.STONKS_EQUITIES || "ubi.fr,ea.us,ttwo.us,rblx.us,ntdoy.us,7974.jp,sony.us,msft.us,nvda.us,amd.us,googl.us,meta.us,aapl.us,tsla.us,tsm.us,asml.us,crsr.us,logi.us,se.us") .split(",") @@ -28,9 +37,46 @@ const privateWatch = String(args.privateWatch || process.env.STONKS_PRIVATE_WATC .split(",") .map((value) => value.trim()) .filter(Boolean); +const radarSymbols = String(args.radar || process.env.STONKS_RADAR || "u.us,app.us,hood.us,coin.us,pltr.us,crm.us,orcl.us,intc.us,mu.us,adbe.us,team.us,snow.us,net.us,crwd.us,ddog.us,shop.us") + .split(",") + .map((value) => value.trim().toLowerCase()) + .filter(Boolean); fs.mkdirSync(stateDir, { recursive: true }); +const passThroughSchema = { parse: (value) => value }; +const requestEventDocument = defineDocumentType({ + type: "request-event", + schemaId: "stonks.request_event.v1", + schemaName: "stonks.request_event", + schemaVersion: "v1", + schema: passThroughSchema, + indexes: { + direction: "direction", + kind: "kind", + }, +}); +const marketSnapshotDocument = defineDocumentType({ + type: "market-snapshot", + schemaId: "stonks.market_snapshot.v1", + schemaName: "stonks.market_snapshot", + schemaVersion: "v1", + schema: passThroughSchema, + global: true, +}); +const eveSurfaceDocument = defineDocumentType({ + type: "eve-surface", + schemaId: "gamecult.eve.surface_state.v1", + schemaName: "gamecult.eve.surface_state", + schemaVersion: "v1", + schema: passThroughSchema, + global: true, +}); +const cultCache = CultCache.builder() + .withRegistry(defineDocumentRegistry(requestEventDocument, marketSnapshotDocument, eveSurfaceDocument)) + .withGenericStore(new SingleFileMessagePackBackingStore(cultCachePath)) + .build(); + let version = 0; let latestSnapshot = pendingSnapshot("Stonks starting"); let currentState = buildState(latestSnapshot); @@ -41,6 +87,8 @@ main().catch((error) => { }); async function main() { + await cultCache.pullAllBackingStores(); + loadRecentRequestsFromCultCache(); const server = http.createServer(handleHttp); server.on("upgrade", handleUpgrade); server.listen(port, host, () => { @@ -88,6 +136,13 @@ async function marketSnapshot() { equities: equities.items, crypto: crypto.items, privateWatch: privateWatch.map(privateWatchItem), + radar: radarSymbolsFor(startedAt).map((symbol) => ({ + kind: "radar", + symbol: symbol.toUpperCase(), + status: "candidate-tech-gaming-watch", + source: "stonks-radar", + })), + recentRequests: [...recentRequests], }; } @@ -149,6 +204,8 @@ function buildState(snapshot) { ...snapshot.equities.map((item) => quoteNode(item)), ...snapshot.crypto.map((item) => quoteNode(item)), ...snapshot.privateWatch.map((item) => privateWatchNode(item)), + ...snapshot.radar.map((item) => textNode(`radar-${item.symbol}`, `radar ${item.symbol} ${item.status}`)), + ...snapshot.recentRequests.slice(-12).map((item, index) => requestNode(item, index)), ]; if (snapshot.equities.length === 0 && snapshot.crypto.length === 0) { rows.push(textNode("empty", snapshot.error || "no market rows available")); @@ -168,7 +225,7 @@ function buildState(snapshot) { props: { title: "Stonks Market Pulse", providerId, - text: `Market pulse: ${snapshot.equities.length} equities, ${snapshot.crypto.length} crypto assets, ${snapshot.privateWatch.length} private watch names.`, + text: `Market pulse: ${snapshot.equities.length} equities, ${snapshot.crypto.length} crypto assets, ${snapshot.privateWatch.length} private watch names, ${snapshot.recentRequests.length} recent requests.`, }, children: rows, }, @@ -188,6 +245,12 @@ function privateWatchNode(item) { return textNode(`watch-${item.symbol}`, `${item.name} ${item.status}; ${item.movement}`); } +function requestNode(item, index) { + const detail = item.url ? `${item.method || "GET"} ${item.url}` : item.detail || item.kind; + const status = item.statusCode ? ` -> ${item.statusCode}` : item.ok === false ? " -> error" : ""; + return textNode(`request-${index}`, `${item.direction} ${detail}${status}`); +} + function textNode(id, text) { return { id, kind: "text", props: { title: id, text } }; } @@ -206,6 +269,8 @@ function pendingSnapshot(error) { equities: [], crypto: [], privateWatch: privateWatch.map(privateWatchItem), + radar: [], + recentRequests: [...recentRequests], }; } @@ -232,12 +297,15 @@ function privateWatchItem(name) { } function persistSnapshot(snapshot, state) { - fs.writeFileSync(path.join(stateDir, "latest-market-state.json"), JSON.stringify(snapshot, null, 2), "utf8"); - fs.writeFileSync(path.join(stateDir, "latest-surface.json"), JSON.stringify(state, null, 2), "utf8"); + trackCultCacheWrite("persist snapshot", async () => { + await cultCache.putGlobal(marketSnapshotDocument, snapshot); + await cultCache.putGlobal(eveSurfaceDocument, state); + }); } function handleHttp(req, res) { const url = new URL(req.url, `http://${req.headers.host || "127.0.0.1"}`); + logRequest({ direction: "inbound", kind: "http", method: req.method || "GET", url: url.pathname, remote: req.socket.remoteAddress || "" }); if (url.pathname === "/health") { sendJson(res, 200, { ok: true, @@ -246,9 +314,12 @@ function handleHttp(req, res) { clients: clients.size, intervalMs, stateDir, + cultCachePath, equities: equitySymbols, crypto: cryptoIds, privateWatch, + radar: radarSymbols, + recentRequests: [...recentRequests], sources: latestSnapshot.sources, }); return; @@ -263,8 +334,8 @@ function handleHttp(req, res) { version: String(currentState.version), endpoint: "/eve/deck", capabilities: ["market-data", "equities", "crypto", "cultui-surface"], - usesCultMesh: false, - transport: "Eve WebSocket + scratch snapshot", + usesCultMesh: true, + transport: "CultCache .cc + Eve WebSocket projection", }], }); return; @@ -279,6 +350,7 @@ function handleHttp(req, res) { } function handleUpgrade(req, socket) { + logRequest({ direction: "inbound", kind: "websocket-upgrade", method: "GET", url: req.url || "/eve/deck", remote: socket.remoteAddress || "" }); if (!req.url.startsWith("/eve/deck")) { socket.end("HTTP/1.1 404 Not Found\r\n\r\n"); return; @@ -336,12 +408,15 @@ function sendFrame(socket, opcode, payload) { } function getText(url) { + const startedAt = Date.now(); + logRequest({ direction: "outbound", kind: "fetch", method: "GET", url: redactedUrl(url), startedAt: new Date(startedAt).toISOString() }); return new Promise((resolve, reject) => { const req = https.get(url, { timeout: 8000, headers: { "user-agent": "GameCult-Stonks/0.1" } }, (res) => { let data = ""; res.setEncoding("utf8"); res.on("data", (chunk) => { data += chunk; }); res.on("end", () => { + logRequest({ direction: "outbound", kind: "fetch-complete", method: "GET", url: redactedUrl(url), statusCode: res.statusCode, durationMs: Date.now() - startedAt }); if (res.statusCode < 200 || res.statusCode >= 300) { reject(new Error(`${url} returned ${res.statusCode}`)); return; @@ -350,12 +425,74 @@ function getText(url) { }); }); req.on("timeout", () => { + logRequest({ direction: "outbound", kind: "fetch-timeout", method: "GET", url: redactedUrl(url), durationMs: Date.now() - startedAt, ok: false }); req.destroy(new Error(`${url} timed out`)); }); - req.on("error", reject); + req.on("error", (error) => { + logRequest({ direction: "outbound", kind: "fetch-error", method: "GET", url: redactedUrl(url), durationMs: Date.now() - startedAt, ok: false, error: error.message }); + reject(error); + }); }); } +function logRequest(entry) { + const observedAt = new Date().toISOString(); + const id = `request:${observedAt}:${crypto.randomUUID()}`; + const record = { + schema: "stonks.request_event.v1", + id, + observedAt, + ...entry, + }; + recentRequests.push(record); + while (recentRequests.length > 80) recentRequests.shift(); + trackCultCacheWrite("persist request event", async () => { + await cultCache.put(requestEventDocument, id, record); + }); +} + +function loadRecentRequestsFromCultCache() { + const records = cultCache.getAll(requestEventDocument) + .sort((left, right) => String(left.observedAt).localeCompare(String(right.observedAt))) + .slice(-80); + recentRequests.splice(0, recentRequests.length, ...records); +} + +function trackCultCacheWrite(label, operation) { + const write = operation().catch((error) => { + console.error(`${label} failed:`, error.message); + }).finally(() => { + pendingCultCacheWrites.delete(write); + }); + pendingCultCacheWrites.add(write); +} + +function redactedUrl(value) { + try { + const url = new URL(value); + return `${url.origin}${url.pathname}`; + } catch { + return String(value).slice(0, 180); + } +} + +function radarSymbolsFor(date) { + if (radarSymbols.length === 0) return []; + const seed = Math.floor(date.getTime() / 60000); + return [...radarSymbols] + .sort((a, b) => hashString(`${a}:${seed}`) - hashString(`${b}:${seed}`)) + .slice(0, Math.min(6, radarSymbols.length)); +} + +function hashString(value) { + let hash = 2166136261; + for (let i = 0; i < value.length; i++) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, 16777619); + } + return hash >>> 0; +} + function csvLine(line, header) { const values = line.split(","); const row = {};