rea
morluto
Reverse engineer anything with agents, from app behavior down to native binaries.
PROJECT TOPICS
INSTALL REFERENCE
dsh plugin --profile web add github:bw496915-cmyk/Sports-desk-ops
该命令指向仓库当前默认分支;尚无绑定当前 commit 的完整验证结果。
PROJECT README
Production intelligence, downline risk surveillance, 10-Mode Forensic/Risk/Cross-Market/Reconciliation engine, Cloudflare R2 edge portal, Qwen3.5-4B neuron token taxonomy, and automated reporting pipeline built on the Bun runtime (v1.4.4) for SportsDesk and Fantasy402 books.
Repository: bw496915-cmyk/Sports-desk-ops
Engineering: Signal honesty ADR — errors must name cause, missing ≠ zero, cron/CLI surfaces must match reality (see also AGENTS.md).
If you are opening this repository for the first time or starting a desk shift, read the Operator Quickstart, Data Cleaning Pipeline & 10-Mode Action Runbook and open the Live 6-Tab Surveillance, ROT Bet-Ticker & 10-Mode Forensic Portal (graph.html).
Always use ./bin/dx as your primary entrypoint—it configures sandbox/host $HOME/.gitconfig, links your dotfiles checkout ($DX_DOTFILES_DIR, else ~/dotfiles; never overwriting a real file), loads Cloudflare Pages credentials, and runs its tooling through Bun (v1.4.4). Run ./bin/dx help for every command and ./bin/dx scripts for the grouped package.json scripts:
# 1. Verify environment, Git config, staged dist/ assets, and live Cloudflare R2 gateway
./bin/dx status
# 2. Run the 10-Mode Forensic, Risk, Cross-Market & Data Integrity Matrix (all 10 modes or a single mode 1..10)
./bin/dx modes
./bin/dx modes 6 # Mode 6: Activity Overlap (Confirmed Session Overlap vs Nearby Point Events)
./bin/dx modes 9 # Mode 9: Pending Exposure (Stake vs Potential Payout vs Defined Liability)
./bin/dx modes 10 # Mode 10: Reconciliation (Report Totals vs Settled Tickets vs Ledger, Gap = $0.00)
# 3. Audit all Per-Office (type="B" customerID=<Office>) & Cross-Office (customerID="0") IP-Tracker Clusters
./bin/dx iptracker
# 4. Run the 4-Week Full-Customer CFB & NBA Parlay/Combo Backtest
./bin/dx backtest
# 5. Poll configured Polymarket wallets (valid 0x addresses), stage the 6-Tab Portal and publish to R2
# Add SPORTSDESK_LIVE_INGEST=1 (Polymarket) and/or SPORTSDESK_LIVE_F402=1 (F402 probe)
SPORTSDESK_LIVE_INGEST=1 ./bin/dx deploy
Without
SPORTSDESK_LIVE_INGEST=1,stage/deploypoll in fixture mode and would publish placeholder rows. The poller now warns loudly (naming the prior mode it replaces), and./bin/dx poll --helpprints usage without polling.
Operator tools:
./bin/dx status — measured, not asserted: git, R2 S3 and Pages credentials, and a 3-second HEAD probe of the R2 portal (DX_STATUS_OFFLINE=1 skips the probe). Each line says what it checked../bin/dx setup [--replace] — reports any real file (for example ~/.zshrc) that dx declined to replace with a dotfiles symlink; --replace moves it to <path>.dx-backup-<epoch> and links../bin/dx scripts [substring] — the package.json scripts grouped by prefix; a substring lists the matching commands../bin/dx gslive <LOGIN> — GSLive Partner 118 links for one account: the 7-parameter #/reports/users deep link (bot=true, desk-day ISO window, text=player_<LOGIN>) and the #/events/bet-history sidecar (calcTime / betTime, epoch from/to, raw partnerUserId).bun run wagers:review <LOGIN> — one customer's wager review: open exposure and its single-winner scenarios, the settled record by structure (2-leg/3-leg/5-leg/free play), a reconstructed combination card (57 slots, booked vs omitted, inferred winners/losers, full-card counterfactual), and measured findings (stake escalation, reprice, free-play conversion) with the evidence gaps that remain. Joins the pending capture, ticker, graded exports, newest users report containing the login, roster and suspected-bot ledger; --deep adds ledger-tenure peers, platform context and corpus card-booking norms, --json for the agent, --root for fixtures. Exit codes: 0 reviewed, 2 usage, 3 the login is in no wager source../bin/dx docs / ./bin/dx docs gslive — deployed docs portal URLs, or the GSLive surface section../bin/dx stale -i <export> — stale-line cohort over a bet-log export (CSV/JSON/JSONL); seeds on operator stale notes or graded-then-cancelled tickets, then clusters other customers on the same market and window../bin/dx shot <url> — Bun.WebView screenshot (webkit on macOS, chrome elsewhere); --f402-login captures the manager after an opt-in login. Output goes to scratch/shots/. --profile <dir> reuses a saved WebView profile and reports signedOutMarkers (empty = no signed-out page seen)../bin/dx session [status|login] — the portal session file the replay transport reads. status (the default) is read-only; login needs F402_LIVE_LOGIN=1. A WebView profile alone gives the transport no cookies../bin/dx profile <0x|username> — Polymarket address profile: PnL, win rate, open positions, category mix, activity summary and strategy pattern from public APIs../bin/dx combo legs|price|wallet|uniqueness — CFB combo legs, product-of-legs pricing, wallet combo positions and per-game unique combo/wallet counts../bin/dx combo backtest — realized combo PnL by day/game from public activity (open combos excluded)../bin/dx bridge coverage|value|match — cross-domain join between our customer book and Polymarket wallets: attribution health, fee-aware cross-venue PnL, and leg-level mirror/opposite matching.bun run sportsdesk rank-all — 30-day batched sharp bettor rankings ($269.5M handle, 9,141 accounts, Gini stake inequality, tiering).bun run sportsdesk quarantine — sliding-window syndicate steam burst quarantine engine (autoExecute: false).bun run sportsdesk conduits — audit 21 single-bettor proxy sub-agents (concentration $\ge 80\%$).bun run dev — real-time dev server (:4022) with native WebSockets topic rooms (live-bets, syndicate-alerts, proxy-conduits, terminal-logs) and PTY terminal.schema:dump-prod, schema:sync-prod-dump, fixture allowlist, captured_at)bun:sqlite strict + safe integers)bun run schema --help (sources in cli/sportsdesk_schema_cli.ts)bun run schema:gate · lag metric: bun run schema:dump-lagbun run schema:sync-prod-dump then commit tests/fixtures/prod-schema.json (see schema-dump-operations.md)git clone https://github.com/bw496915-cmyk/Sports-desk-ops.git
cd Sports-desk-ops
# Verify Bun 1.4.4, then install the locked dependencies
bun --version
bun install --frozen-lockfile
# 1. Inspect nominal branded types & domain invariants
bun run cli -b
# 2. Inspect Qwen3.5-4B (Layers 18-28) neuron token registry with TrueColor ANSI swatches
bun run cli -N
# 3. Verify design tokens, CIEDE2000 color distance, and WCAG contrast
bun test tests/verify_tokens.test.ts
# 4. Compile tokens across TypeScript, Webview, and TMA dashboards (Zero-Drift SSOT)
bun run gen:tokens
# 5. Run every test: tests/ (what CI runs) plus the suites colocated in lib/ and scripts/ (CI does not)
bun test
# 6. Run 24h sniper surveillance
bun run cli winners -p 24h --limit 25
# 7. Generate the auditable surveillance report bundle (reports/<timestamp>/MANIFEST.md)
bun run reports -- --format table
# 8. Run 52-week bettor churn simulation
bun run sim
Repository lint uses exact-pinned Oxlint through Bun; stable Bun 1.4.4 has no
native bun lint (only the 1.4.5 canary does). Run bun run lint:check for a
read-only gate that fails on warnings or errors, or bun run lint to apply safe
fixes. CI runs lint
alongside token regeneration, the fetch/innerHTML gates, and the full tests.
Run bun run format to format the repository or bun run format:check for a
read-only check. bunfig.toml preserves the existing 80-column, two-space,
double-quote style with semicolons. Run bun run typecheck for Bun's native
strict, no-emit checker; tsconfig.json makes the previous inferred compiler
defaults explicit and includes the repository's source, tests, and declarations.
CI runs formatting and type checking before lint. Bun remains pinned to 1.4.4
in CI and declared in package.json (packageManager and engines), with
matching @types/bun; no Prettier or oxfmt package is required. These manifest
fields document the required version; CI explicitly selects it. The canonical
local checkout on this machine is ~/code/sportsdesk-ops; the dotfiles symlink
is only a convenience pointer.
Tests distinguish Fetch-spec requirements from behavior observed on Bun 1.4.4.
The pinned Request constructor retains GET/HEAD bodies and accepts spec-forbidden
methods. It also maps mixed-case Delete to GET and uppercases custom verbs.
These are compatibility differences, not application guarantees: use explicit
uppercase methods. fetch rejects nonempty GET/HEAD bodies before transmission.
String request bodies have no inferred Content-Type on this binary, and JSON
Blobs acquire charset=utf-8. Wire tests check explicit Content-Type headers
separately so application behavior does not depend on those inferences.
Subprocess fixtures await output writes and exit naturally while the parent drains stdout and stderr concurrently. They assert complete byte content rather than assuming unread pipes always deadlock or enforcing machine-speed thresholds.
Server binding in sportsdesk_webview_server.ts adheres to Bun's native port resolution cascade:
BUN_PORTPORTNODE_PORT3000SportsDesk Operational Policy: Rather than overriding Bun's cascade in code, SportsDesk relies directly on native resolution. Production deployments configure PORT=4020 inside .env, which Bun loads automatically at process initialization. When startServer(options) is called programmatically, { port, hostname, unix, development } options allow explicit test or proxy overrides; when omitted, Bun resolves port and hostname natively (defaulting hostname to 0.0.0.0).
Static HTML surfaces under static/ (customer-churn-simulation-dashboard.html and telegram-miniapp-dashboard.html) are served via native new Response(Bun.file(path)) lazy handles.
sendfile(2) on Linux, copyfile on macOS) specifically for outbound client file uploads (fetch(url, { method: "POST", body: Bun.file(...) })). This optimization activates exclusively under four strict preconditions:new Response(Bun.file(path))), Bun constructs a lazy file handle pointer in user space without eagerly reading file bytes into memory buffers. Handle allocation takes ~0.38 µs (compared to 45.9 µs for readFileSync). However, whether the subsequent socket transmission leverages sendfile(2) or writev/pread is unproven in Bun's published documentation. SportsDesk avoids conflating upload zero-copy claims with response streaming./run/sportsdesk/webview.sock) or loopback HTTP (127.0.0.1:4020). This topology eliminates TLS encryption overhead and TCP port exposure on the host.Outbound network operations across Telegram alerts, Cloudflare R2 backup, and Fantasy402 feeds are hardened against proxy hijacking, hanging connections, and transport vulnerabilities:
AbortSignal.timeout): All outbound requests enforce strict timeouts via signal: AbortSignal.timeout(timeoutMs) (e.g., 5,000 ms for Telegram dispatch, 10,000 ms for R2 verification). Unbounded fetch awaits are eliminated.NO_PROXY / proxy: false): Bun resolves HTTP_PROXY, HTTPS_PROXY, and ALL_PROXY on a per-request basis (ALL_PROXY acts as scheme-agnostic fallback). Ambient corporate or CI proxies trap loopback calls unless bypassed. SportsDesk configures NO_PROXY=127.0.0.1,localhost,::1 across .env, .env.example, and deploy_to_vps.sh. In addition, internal services pass { proxy: false } for guaranteed direct socket connections, explicit proxy objects respect NO_PROXY by default (overridable via respectNoProxy: false), and tunnel failures reject with ERR_PROXY_TUNNEL (verified by tests/fetch_proxy_isolation.test.ts).BUN_CONFIG_MAX_HTTP_REQUESTS): Set to 256 to align Bun's shared connection pool with peak alert burst throughput, preventing resource starvation.Bun.FetchSession & Pre-Warming: SportsDeskTelegramService initializes a dedicated Bun.FetchSession with tls: { rejectUnauthorized: true }, isolating session credentials and connection reuse. Outbound connections are pre-warmed at boot via fetch.preconnect("https://api.telegram.org") to eliminate initial TLS handshake latency.tests/fetch_url_credentials.test.ts, ensuring 0 plaintext http(s)://user:pass@ strings in source code and 0 occurrences of rejectUnauthorized: false.Bun automatically loads environment files at startup in strict order of increasing precedence:
.env (base configuration).env.production, .env.development, .env.test (evaluated based on NODE_ENV).env.local (Exception: strictly skipped when NODE_ENV=test to ensure deterministic test isolation).env.production.local, .env.development.local, .env.test.local (mode-specific local overrides)TypeScript declaration merging in types/env.d.ts extends both Bun.Env and NodeJS.ProcessEnv with strict typing for all SportsDesk credentials (PORT, BUN_SOCKET, NO_PROXY, BUN_CONFIG_MAX_HTTP_REQUESTS, F402_*, CLOUDFLARE_*, R2_*, TELEGRAM_*), verified via tests/env_types.test-d.ts.
To ensure seamless embedding inside Telegram Web (https://web.telegram.org), Telegram mobile apps, and desktop clients without frame hijacking vulnerabilities:
X-Frame-Options is strictly absent from all server response headers (the deprecated ALLOWALL directive is never sent).Content-Security-Policy: frame-ancestors 'self' https://web.telegram.org https://*.telegram.org telegram:;.Every Telegram variable the bot reads is in one --with telegram group, so the daemon can be launched with the five values injected from the OS keychain (com.bookdeskops.sportsdesk) without writing them to a file or the shell. See docs/runbooks/telegram_seeding.md for the full flow; the one-line summary:
# Store each secret (values on stdin, never argv; keychain service com.bookdeskops.sportsdesk):
printf %s "$BOT_TOKEN" | bun run secrets:env set TELEGRAM_BOT_TOKEN
printf %s "$WEBHOOK_SECRET" | bun run secrets:env set TELEGRAM_WEBHOOK_SECRET
printf %s "$CHAT_ID" | bun run secrets:env set TELEGRAM_CHAT_ID
printf %s "$WEBHOOK_URL" | bun run secrets:env set TELEGRAM_WEBHOOK_URL
printf %s "$MINIAPP_URL" | bun run secrets:env set TELEGRAM_MINIAPP_URL
bun run secrets:env status --with telegram # every row should read "keychain"
bun run secrets:env exec --with telegram -- bun run serve
curl -s http://127.0.0.1:4020/api/telegram/status -H "Authorization: Bearer $ADMIN" | jq '.seeding'
Mini App launches carry a signed initData payload. Server-side verification uses verifyTelegramInitData from lib/telegram_initdata.ts, which performs the documented HMAC_SHA256(key=SHA256(bot_token), data=sorted_data_check_string) check with crypto.timingSafeEqual and a 5-minute auth_date window. The helper takes no I/O and never logs the token.
Empirical measurements on Bun v1.4.4 (macOS arm64, Apple Silicon). Benchmarks reflect streaming production wager corpora (f402-bets.jsonl, 468.8 MB / 934,246 rows) alongside lazy server handles:
| Operation / Workload | Legacy / Baseline | Native Bun 1.4 Path | Benchmark / Speedup |
|---|---|---|---|
| JSONL Stream (468MB, 934k rows) | readline (1,966 ms) |
Bun.JSONL.parseChunk |
636.9 ms (676.8 MB/s, 3.1x faster) |
| Burst Arena (627k wagers, 30d) | Unbounded collections | SyndicateBurstGuardArena |
1,202 ms (bounded sliding window) |
| Response Handle (154 KB payload) | Eager file.text() |
new Response(Bun.file()) |
0.67 µs (292x faster lazy handle) |
| Socket Transfer (1 MB payload) | fetch socket transfer |
Loopback kernel sendfile | 0.489 ms/req loopback transfer |
| JSON Serialization (25 accts) | JSON.stringify + hdr |
Response.json(data) |
1.12 µs (1.09x faster) |
DNS Resolution (fantasy402.com) |
System getaddrinfo |
Bun.dns.lookup (c-ares) |
0.27 ms cached latency |
| ANSI Text Width (TUI rendering) | npm string-width |
Bun.stringWidth |
Instant C++ zero-copy lookup |
Self-healing replay for reports/ingestion-audit.jsonl (and any ASCII-field JSONL feed): Bun.JSONL.parseChunk on a streaming Uint8Array buffer, Bun.XML.parse for board prices, optional bitemporal v_t guard, and pattern flags (SPIKE_UP, DOWN, …) rendered with registry colors.
bun run replay -- --path /tmp/e.jsonl --markdown
bun cli/sportsdesk_cli.ts replay --path reports/ingestion-audit.jsonl --json
Bun.XML golden AST (Plane 1 pin / Plane 3 verify): each row with xml may carry xml_golden_ast_sha256 and bun_version (sha256 of Bun.JSON5.stringify(Bun.XML.parse(xml.trim(), { compact: false }))). Replay verifies pins unless --no-verify-xml-golden; --strict-xml-golden requires a pin on every xml row. Exit precedence: corrupt 1 → tx 2 → SLA 3 → golden drift 4. Backfill pins: bun run ingestion:enrich-xml-golden -- in.jsonl [out.jsonl].
Implementation: sportsdesk_ingestion_replay.ts, lib/bun_xml_golden_ast_replay.ts, drain mirror lib/jsonl_stream_replay.ts, runbook §8.4 in docs/runbooks/bun_server_runtime_shapes_runbook.md.
The system uses design/tokens.toml as the authoritative Single Source of Truth (SSOT) for all 13 neuron tokens, dark surfaces, ingestion channels, and algorithmic routes:
--sd-surface-primary (#070b14), --sd-surface-card (#0b1329).L18.N0204 (#1d84b5, Internet Retail Baseline, 1,500 ms SLA)L19.N0518 (#64748b, Blocked Sentinel Filter, { kind: 'sentinel_drop' } policy)L20.N1105 (#10b981, Gateway Equilibrium & Vig Gate, 1,000 ms SLA)L21.N0884 (#ef4444, Alert Twin Syndicate Mirror, 250 ms SLA)L22.N1402 (#f59e0b, Builder Steam / Line Chase, 1,000 ms SLA) — Single-owner Amber-500L23.N0412 (#28a745, Live In-Play Whale Anomaly, 500 ms SLA)L24.N2019 (#38bdf8, CSLevel2 Recreational Longshot Bias, 2,000 ms SLA)L25.N1882 (#06b6d4, Route 02 Adverse Selection Devig Expansion)L26.N3104 (#a855f7, Route 03 CLV Margin Decay Sharp Shrinkage)L27.N0912 (#d97706, Route 01 Liquidity Exhaustion Breaker) — Dedicated Amber-600L28.N2501 (#f43f5e, Route 04 Terminal Risk Mitigation Limit Clamp)All channel transport SLAs and route thresholds are modeled with strict discriminated unions rather than overloaded primitive numbers or polymorphic strings:
// Axis 1: Transport SLA Contract
export type TransportSla =
| { readonly kind: "latency"; readonly latencySlaMs: number }
| { readonly kind: "sentinel_drop" };
// Axis 2: Algorithmic Route Threshold Contract
export type RouteThreshold =
| { readonly kind: "consensus_lag"; readonly maxConsensusLagMs: number }
| { readonly kind: "bayes_shrinkage"; readonly tauStar: number; readonly minTicketCount: number }
| { readonly kind: "liquidity_depth"; readonly minTopDepthCents: Cents }
| { readonly kind: "composite_risk_gate"; readonly minToxicityScore: number; readonly maxHoldPercentage: number; readonly maxDeficitCents: Cents };
// Nominal Enum Enforcements
export enum TriggerPredicateKind { ... }
export enum MitigationActionKind { ... }
All tokens and contracts are verified continuously through lib/validation/token_validator.ts and tests/:
bun run gen:tokens:gate (CI step) resets generated outputs, regens from design/tokens.toml, and fails on drift for design/domain-branded-types.ts and the two dashboards under static/.ColorHexInt values derived from Bun.color().#070b14 / #0b1329) and $\ge 4.5:1$ for typography.The suite is grouped by what it verifies. File and assertion counts change with every edit and are
never pinned in prose; the authoritative execution surfaces are bun test tests/ (the CI gate) and
bun test (which additionally discovers colocated *.test.ts suites in lib/ and scripts/, with
scratch and generated gate paths excluded via bunfig.toml [test].pathIgnorePatterns).
tests/verify_tokens.test.ts): zero-drift regeneration from
design/tokens.toml, 24-bit colour uniqueness, CIEDE2000 perceptual separation, WCAG 2.1
contrast, dead-token/bi-directional reference consistency, discriminated-union guardrails, and
the generative property tests test_property_ciede2000_metric_axioms and
test_property_wcag_contrast_ratio_bounds.tests/sendfile_threshold.test.ts (lazy handle
construction vs end-to-end socket throughput at 16 KB / 64 KB / 1 MB),
tests/server_headers.test.ts (no X-Frame-Options; Telegram frame-ancestors present),
tests/server_error.test.ts (non-Error throws become structured 500 JSON without stack traces),
tests/fetch_proxy_isolation.test.ts (NO_PROXY, { proxy: false }, respectNoProxy),
tests/fetch_timeout.test.ts (AbortSignal.timeout), tests/bench_server.test.ts
(Response.json vs JSON.stringify equivalence, lazy Bun.file bodies),
tests/fetch_url_credentials.test.ts (no embedded URL credentials, no
rejectUnauthorized: false), tests/server_port.test.ts (BUN_PORT=4100 cascade), and
tests/env_types.test.ts / tests/env_types.test-d.ts (Bun.env typing).See ROOT_LAYOUT.md for the full map. At a glance:
├── cli/ # sportsdesk_* CLIs (bun run cli, schema, replay, …)
├── services/ # webview daemon, Telegram bot, R2, churn engine, ingestion
├── catalog/ # Fantasy402 sport navigation catalog
├── lib/ # shared modules, F402 capture, schema SSOT (+ colocated *.test.ts)
├── scripts/ # generators & capture; scripts/deploy/ for VPS/docs/reports (+ colocated *.test.ts)
├── reports/ # surveillance outputs, ingestion-audit.jsonl & docs-review
├── static/ # token-compiled daemon HTML
├── docs/ # API evidence portal; docs/runbooks/ for long-form ops guides
├── tests/ # bun test suites (CI gate target)
├── verification/ # manager-boot-oracle slices & gen-tokens zero-drift gate
├── dsh-plugin*/ # removable DeepSeek Harness plugin bundles (verify-load.mjs gated)
├── bin/dx # operator entrypoint
├── design/ # tokens.toml + domain-branded-types.ts (gen:tokens)
├── schema/ # migrations, manifest.bin, schema preload
├── infra/ # Cloudflare Pages _headers
└── types/env.d.ts
See docs/runbooks/README.md for the full index. Highlights:
Server extends Disposable, WebSocketHandler<T>, and TLSOptions.#/reports/users deep link and the #/events/bet-history sidecar, with an evidence level per surface.--live), provenance and stale-cache rules, and the F402 session plan.Post-mortem write-ups for production outages that shipped behavioral guarantees worth preserving. Read before editing the files called out in the "Guarantees to preserve" table of each incident.
CLASSIFICATION EVIDENCE
系统优先读取 GitHub Topics,再与站内分类词典和词根规则比对。当前命中: deepseek-harness。