8 Commits

Author SHA1 Message Date
Mavis a69cd14817 fix: null-safe kRPC handshake error reporting
CI / Lint, typecheck, test, build (pull_request) Failing after 11s
The bridge was falling back to mock mode with a confusing
'Cannot read properties of null (reading code)' error. The actual
underlying error (ECONNREFUSED, timeout, protocol mismatch) was
being swallowed by our error handler that did `(e as Error).message`
on a value that was sometimes null.

Wrap the kRPC client connect() in per-step try/catch with a
formatErr() helper that handles:
- null / undefined
- strings
- Error with .code (NodeJS.ErrnoException)
- arbitrary objects (JSON.stringify fallback)

Now when the bridge can't reach kRPC you get a real error like
'kRPC RPC TCP connect to 127.0.0.1:50000 failed: code=ECONNREFUSED:
connect ECONNREFUSED 127.0.0.1:50000' instead of the cryptic
null-code message.

Also fixed the bridge's main() error handler to be null-safe.

Discovered while debugging the user's first end-to-end run on
Windows: kRPC was reachable (Test-NetConnection succeeded) but
the bridge couldn't complete the handshake. With this fix we'll
see the real failure mode on the next attempt.
2026-06-02 23:10:19 +00:00
Mavis aebee77843 phase 1c-extract: typed kRPC service client + SpaceCenter extract
Built the missing piece that connects the ksp-bridge to a real KSP
instance via kRPC. This adds a typed service client on top of the
existing KRPCClient, plus the SpaceCenter-specific extraction logic
that pulls the universe state from a running KSP save.

@kerbal-rt/krpc-client
- types.ts — runtime representation of kRPC Type descriptors
  (TypeCode enum, KrpcType interface, decodeKrpcType, typeName)
- decoder.ts — kRPC value codec: primitive decode/encode, class refs,
  enums, collections (LIST/SET/TUPLE/DICTIONARY), system messages
  (STATUS/SERVICES/STREAM/EVENT/PROCEDURE_CALL). 34 unit tests.
- services.ts — ServiceCache built from KRPC.GetServices() response.
  Lookup by (service, procedure), enum value/name resolution. 12 tests.
- service-client.ts — KrpcServices: high-level invoke-by-name client.
  loadServices() helper to connect + load catalog. 9 integration tests
  with a mock kRPC server.
- schema.ts — added Set/Dictionary/Event/Expression types so the
  decoder can handle system messages without external .proto files.
  Also fixed a bug where 'STREAM' was being encoded as 0 due to
  protobufjs's nested-enum string lookup.

ksp-bridge
- extract.ts — the actual SpaceCenter calls. ~280 procedure calls
  per poll for a typical KSP save (UT, bodies, vessels, then per-body
  and per-vessel class methods in parallel). Build the UniverseSnapshot.
- krpc-adapter.ts — rewrote to use KrpcServices (typed) instead of
  the stub extract function. Supports an optional injected services
  for testing.
- bridge.ts — uses the new ExtractedState type and buildSnapshot.
- index.ts — connects to kRPC; falls back to mock mode if no server.
- convert.ts — backward-compat shim, re-exports from extract.ts.

The ksp-bridge can now talk to a real KSP install. We do NOT need
the kRPC mod's .proto files on disk — the server's GetServices()
response is the source of truth for type info. Documented the full
list of procedures we call, the kRPC value encoding, and the new
architecture in ksp/README.md.

Tests: 119 total, all green. Typecheck and build clean across all 11
projects.

Bonus: fixed an integer-overflow bug in the krpc-client connect()
handshake (was passing 'RPC'/'STREAM' strings to protobufjs; its
nested-enum string lookup silently encodes as 0, which made the
stream handshake send the wrong type. Switched to numeric codes.)
2026-06-02 22:02:26 +00:00
Mavis 68bc7015fd Phase 1c: real kRPC bridge (full protocol + mock mode for development)
CI / Lint, typecheck, test, build (pull_request) Failing after 9s
- packages/krpc-client: TypeScript kRPC protocol client
  - connection.ts: varint encoding/decoding, length-prefix framing,
    per-socket read queue (avoids race when multiple read promises
    in flight). Uses multiplication not '<<' for varint shift
    because JS truncates << to 32 bits.
  - schema.ts: hand-written protobufjs schema for kRPC meta-protocol
    (ConnectionRequest, Request, Response, StreamUpdate, Status, etc.)
    - enough to do connection handshake, single procedure calls, and
      stream subscription. Service-specific types (SpaceCenter.Vessel,
    Orbit, CelestialBody) need to be loaded from the kRPC mod's
    .proto files at runtime.
  - client.ts: KRPCClient with connect/invoke/addStream/removeStream/
    onStreamUpdate/close. Tested with hand-rolled mock server.
  - 10 tests (varint round-trips incl. uint64, wire format with raw
    sockets).

- apps/tools/ksp-bridge: bridge that connects KSP to our API
  - convert.ts: pure kRPC -> UniverseSnapshot conversion
    (situation enum mapping, body id normalization, etc.)
  - bridge.ts: main poll loop with retry + backoff
  - krpc-adapter.ts: KRPCAdapter class that owns the KRPCClient
  - index.ts: entrypoint with MOCK MODE for development (emits
    synthetic state when no KSP is available, so you can verify the
    HTTP pipeline end-to-end)
  - 9 tests (7 conversion + 2 end-to-end bridge)

- ksp/README.md: full setup guide
  - CKAN install, KSP server start, env vars
  - Hand-rolled KSP calls list (what SpaceCenter methods we need)
  - Roadmap for the remaining .proto-loading work
  - Protocol deep-dive (for the next dev)

- Bug fixes along the way: protobufjs default import (not namespace),
  varint 32-bit truncation, JavaScript bitwise 32-bit limit,
  handshake status enum comparison (number vs string).

End-to-end verified: API + bridge in mock mode, 2 bodies + 1 vessel
arriving at /api/v1/state, 500ms polling cadence, automatic recovery
on HTTP failures.
2026-06-02 20:42:54 +00:00
Mavis 07cc5321d1 Phase 2c: eclipse/overpass calculators + live-map camera polish
CI / Lint, typecheck, test, build (pull_request) Failing after 9s
Calculators (apps/live-map/src/calculators/):
- eclipse.ts: findEclipseWindows(bodies, opts) — coarse scan with
  threshold-crossing detection, bisection to refine start/end,
  ternary search to find peak. Handles eclipse already in progress
  at scan-start. Uses sun = parentId===null body.
- overpass.ts: findOverpasses(opts) — coarse scan for local distance
  minima, ternary refinement. Targets: vessel, body, ground station
  (lat/lon/alt → heliocentric).

UI:
- panels/CalculatorsPanel.tsx: collapsible bottom-center panel with
  two tabs. Eclipse form: observer, eclipser, from UT → 3 windows.
  Overpass form: observer vessel, target kind+id, max dist → 5 passes.
- timeFormat.ts: shared KSP-time formatters.

Live-map camera polish (apps/live-map/src/scene/):
- camera.ts: CameraController — log-scale distance (z→exp(z)*1e8 m,
  range -3..12), spherical orbit around target, smooth lerp to
  selected body/vessel. Mouse wheel zooms, drag rotates, click
  raycasts for track toggle. Pointer-move-distance gate to
  distinguish click from drag.
- glow.ts: additive shader-based atmospheric halo (rim-falloff
  fragment shader, BackSide) attached as child of body mesh.
- layout.ts: bodyPositionAt now returns true heliocentric (walks
  parent chain); previous version returned parent-relative for
  non-root children which broke the eclipse calculator.

Bug fix:
- packages/orbital-math/src/occultation.ts: sign of projection check
  was inverted. `proj <= 0` correctly returns 0 (occluder behind
  observer), `proj > 0` triggers eclipse computation.

Tests: 28 live-map tests (10 scene + 12 calculator + 6 camera),
45 total across the workspace, all passing.
2026-06-02 19:46:00 +00:00
Mavis 9e76ec9328 Phase 2: 3D live map driven by API WebSocket
CI / Lint, typecheck, test, build (pull_request) Failing after 9s
- apps/live-map/src/hooks/useLiveState.ts: WebSocket subscription
  with exponential-backoff reconnect, polling fallback, status tracking
- apps/live-map/src/scene/Scene.tsx: refactored Three.js scene with
  per-frame orbit propagation, vessel marker color-coding by owner,
  orbit-line visibility tied to focus filters, smooth camera follow
  on selected vessel/body
- apps/live-map/src/scene/layout.ts: bodyPositionAt / vesselPositionAt
  helpers (heliocentric frame, walk up the parent chain), logScale
  helpers for the system view
- apps/live-map/src/scene/color.ts: per-body and per-owner color maps
- apps/live-map/src/panels/TimeControls.tsx: play/pause/reverse/reset
  buttons, ×1/×10/×100/×1k/×10k/×100k speeds, UT scrub slider,
  live-edge indicator (LIVE / Nh behind / Nh ahead)
- apps/live-map/src/panels/VesselList.tsx: vessel sidebar with click-
  to-track; color-coded by owner (KASA=blue, SPES=orange)
- apps/live-map/src/panels/FocusPanel.tsx: planet/moon/vessel orbit
  visibility toggles
- apps/live-map/src/panels/StatusPill.tsx: WS status (LIVE/POLLING/
  OFFLINE/STALE), body + vessel + message counts
- tests/scene.test.ts: 10 tests for layout helpers (periodicity,
  vessel-centered positioning, logScale round-trips)

End-to-end verified: mock publisher → API → live-map WebSocket →
scene re-renders with the new vessel positions and orbits.
2026-06-02 19:18:22 +00:00
Mavis a457b9d96f Phase 1: data pipeline (Postgres+Redis with in-memory fallback, mock telemetry publisher, WebSocket fan-out, hub /debug page)
CI / Lint, typecheck, test, build (pull_request) Failing after 10s
- packages/db: postgres.js + ioredis wrapper, StateStore interface with
  InMemory + Postgres implementations, schema migration runner
- apps/api: refactored to use @kerbal-rt/db; live WebSocket hub subscribes
  to store changes and broadcasts to all clients
- apps/tools/mock-telemetry: Node script that generates realistic KSP
  state and POSTs to /api/v1/ingest at 1Hz (uses same keplerian math
  as the live-map renderer)
- apps/hub: new /debug page that connects to /api/v1/live and shows
  the live state
- ksp/README.md: documents Phase 1c (real kRPC bridge) and the two
  implementation options
- Tests: 17 total (5 kepler math, 5 db store, 5 API health/state,
  2 API WebSocket fan-out)

End-to-end verified: mock publisher → API → hub /debug page,
11 snapshots/5s over WebSocket, vessels advancing in mean anomaly.
2026-06-02 18:54:46 +00:00
Mavis 938ba042b3 Phase 0: fix typecheck, format, build; remove stray emit; pin port via env
CI / Lint, typecheck, test, build (push) Failing after 22s
2026-06-02 16:07:09 +00:00
Mavis 7b19c54943 Phase 0: monorepo skeleton (hub, live-map, api, packages, infra, CI) 2026-06-02 15:47:28 +00:00