Repository Public
1<!-- Author: Simon-Pierre Boucher — contact@spboucher.ai · File: docs/MACOS_ARCHITECTURE.md -->2# VQuant for macOS 2.0.0 — architecture34Native client (Swift 6, SwiftUI, AppKit where it earns its place) of the existing VQuant server5(`vquant.spboucher.ai`, repository `vquant.git`, Express + SQLite + Python on the MacLustr node chosen by `mld`).6No web view, no JavaScript engine, no third-party dependency: `Scripts/verify-release.sh` checks the signed bundle7for both.89## What the repository analysis found (2026-11-18, backend v5.7.0 → v5.8.0)1011The brief described VQuant as a trading and research platform with a component named Pyrus, WebSocket market12feeds and strategy/backtesting modules. The repository says otherwise, and this application follows the repository:1314| Brief | Repository | Consequence here |15|---|---|---|16| "Pyrus" computation service | **No file, route, package or process named Pyrus** (`grep -ri pyrus` matches only conversation text in the database). The server-side computation layer that exists is a Python engine (`server/services/python/*`: GARCH, VaR, Monte Carlo, options, optimiser, risk metrics, and a persistent notebook kernel) used by the agent. | The **Quant Engine** section exposes that Python engine through server jobs (`/api/quant/*`, added in v5.8.0). Nothing is named Pyrus. |17| WebSocket / streaming market data | None. Market data is a REST proxy to Financial Modeling Prep (`/api/fmp/*`). The only streams are server-sent events of analysis jobs. | Quotes are polled over HTTPS and labelled by age; nothing is called "live". `URLSessionWebSocketTask` is not used because there is nothing to connect it to. |18| Live trading, orders | None. `portfolio_positions` is a record of holdings the agent reads. | No order entry. Portfolio says so on screen. |19| Strategies, backtesting | No module. The agent can write a backtest in its notebook on request. | No section; reachable through Research. |20| Research platform | An AI research agent (`POST /api/chat`), four modes, sub-analysts, memory, watches, PDF/DOCX/slides. | Research, Agent, Jobs, Documents. |21| Electron desktop app | `desktop/` in the repository is an Electron wrapper that spawns the server locally with API keys in a config file. | Not reused. It is the opposite of what was asked. |2223## 2.0.0 "VQuant Next" in one page24252.0.0 is an upgrade of 1.0.1, not a rewrite: the 1.x core, authentication, runner and cache are unchanged, and the26app now also links the shared Swift package **VQuantKit** (`../VQuantKit`, used by the iOS app too) for everything27backend 6 adds (contract: `vquant-next/docs/next/CONTRACT.md`). The client header is `vquant-macos/2.0.0`, which is28what makes the server return the 19 Quant Lab engines and the `cancelled` job status.2930VQuant is, at its core, the autonomous research agent; the terminal, the lab, the portfolios and the studio are31surfaces around it. The sidebar says so: Research · Research Studio, then Terminal (Overview, Markets, Watchlists,32Charting, Statements, Data Explorer), Quant (Quant Lab, Jobs), Portfolio (Portfolios, Risk Analytics), Workspace33(Agent, Documents). There is still no trading: the backend has no brokerage connection.3435## Layers3637```38App (SwiftUI/AppKit, MainActor) VQuantCore (SwiftPM "Core/", Sendable, no UI) VQuantKit (shared package)39 ├ VQuantApp scenes, commands ├ Networking HTTPTransport, APIClient, SSEParser ├ VQuantKit transport seam, sync engine,40 ├ AppEnvironment dependency container ├ Auth AuthService, TokenStore, Passkey… │ models of every v6 route, Lab41 │ ├ api 1.x client (VQuantCore) ├ Services VQuantAPI (1.x routes), GenerationRunner│ form and jobs, research agent42 │ ├ vq kit clients (VQNextAPI) ├ Models Market, Research, Workspace, Quant │ state, formatting43 │ ├ sync SyncStore → VQSyncEngine ├ Cache DiskCache (AES-GCM), Freshness ├ VQuantUI design tokens (VQTokens),44 │ └ store{…} feature stores (registry) ├ Analytics Indicators, Downsampler, ChartDrawings, │ components, LabResultView,45 ├ SessionStore sign-in, lock, expiry │ PortfolioImport, CSV, DataTable │ ResearchActivityView family46 ├ App/Next KitBridge, SyncStore, ├ Markdown blocks, editing └ VQuantKitTesting fakes (tests only)47 │ StudyStore, Commands, ├ Terminal RowSelection, StatementMath, Palette48 │ WorkspaceMapping, MacLogic ├ Lab LabSupport49 ├ Features/* one folder per section └ Stores legacy local stores (migration source)50 └ Components shared views51```5253- **Two clients, one session.** `app.api` is the 1.x `VQuantAPI`; `app.vq` is the kit's entry point. The kit never54 sees a URL or a token: `MacVQTransport` (`App/Next/KitBridge.swift`) serves its `VQTransport` with the app's own55 `APIClient` (same base URL, Keychain token, `X-VQ-Client`, never an `Origin`), honours `VQRequest.contentType`56 (multipart dataset upload) and runs the app's sign-out path on a 401.57- **Dependency injection.** `AppEnvironment` is built once and passed explicitly (`let app: AppEnvironment`) to every58 view. `@Environment(Model.self)` is deliberately avoided: on macOS 27 it traps inside table cells, menus, sheets and59 toolbars. Feature stores are created on first use through `app.store { … }` and emptied at sign-out when they60 conform to `SessionScoped`.61- **Concurrency.** Core and kit are `Sendable`, Swift 6 mode, complete checking; the app target defaults to62 `MainActor`. Long work is `async`; the main thread never waits on the network.63- **Server responsibilities stay on the server**: model inference, the research sandbox, every quantitative engine,64 rendering of exports, persistence, per-person authorisation. The client computes only display aids from data it was65 sent (chart indicators, descriptive statistics, statement comparisons) and labels them as such.6667## One account, synced (CONTRACT §1)6869`SyncStore` (`App/Next/SyncStore.swift`) owns one `VQSyncEngine` per signed-in person.7071- **Replica.** `Application Support/VQuant/sync-<host>/<person>/`, every file sealed by `CacheCipher` — the kit's72 cipher hook implemented with `DiskCache.seal/open`, i.e. AES-GCM under the same Keychain key as the cache —,73 excluded from backups.74- **Lifecycle.** Started at sign-in (and unlock): load, open `/api/v2/sync/stream`, pull, replay the queue.75 Lock: the stream stops, the sealed replica stays. Sign-out, or a session ended by the server (401): replica, write76 queue and conflict records are erased, like the cache — queued offline edits are lost in that case (the 1.x rule77 "a 401 erases what this Mac keeps" was preferred to keeping a queue for a session that no longer exists).78- **Conflict policy** (shared with the web and iOS clients): lists merge element-wise (watchlist symbols, portfolio79 positions and cash, `project.items`, `chart.drawings`; local edit wins per element); other fields are80 last-writer-wins **per field** (`Configuration.granularity = .field`); `workspace` objects are whole-object81 last-writer-wins. Notices that discarded something are listed in the toolbar's sync popover and in Settings › Sync82 with "Keep the other version" / "Keep mine".83- **What is synced.** `watchlist` (Watchlists), `portfolio` (Portfolios; `main` is the agent's and is bridged by the84 server from the legacy positions), `chart` (one per symbol, id `sym-<SYMBOL>`: interval, type, indicators,85 comparisons, drawings), `workspace` (saved window layouts that map — see below), `project`, `note`, `review`86 (server-written), `preference/default`.87- **Preferences.** Up/down colour pair, default model and mode, routing, budget, memory settings and recent searches88 sync. **Light/dark is a per-device choice**: `preference.theme` is neither applied nor written. Refresh cadence,89 app lock, notifications and chart defaults are Mac-only (UserDefaults).90- **Migration of 1.x local data** (once per person and Mac, after the first complete pull): each local watchlist91 becomes object `mac-<uuid of the list>` (a re-run writes the same ids: no duplicate), the file is renamed92 `watchlists.migrated-1x.json` (nothing is deleted). Saved window layouts become `workspace` objects when every93 window has a panel type in the shared model (`WorkspaceMapping`); a layout containing Agent, Jobs or Documents94 windows has no such type and stays local, listed "This Mac only". Mac-specific data (window frames, the section)95 travels in `panel.config.mac`; web conventions (`activeSymbol`, `config.symbol`, `config.linked`, percentage96 `sizes`) are read and preserved.97- **Hints.** `hint` events of the sync stream refresh conversations, running analyses and the quant job list; slow98 polling remains as a fallback.99100## Research (CONTRACT §2, §9)101102- The composer reads the server's model registry (`/api/v2/models`), offers `Auto` (the `model_routed` event is shown103 with its reason), the five modes — Research only when `/api/v2/research/sandbox` answers —, budgets and dataset104 attachment (create workspace → multipart upload → inspection card).105- A generation's events are decoded twice from the same frames: by the 1.x `GenerationEvent` (the live run view that106 1.0.1 had) and by the kit's `VQResearchSessionStore` (the cockpit). Replay from the last event index is unchanged.107- The **cockpit** is the report plus an inspector — Activity · Code · Experiments · Figures · Files ·108 Environment — composed from the kit's `ResearchActivityView` family over a `ResearchDataSource`; the Mac adds the109 file tree, Quick Look, drag-out, Save As. A study reopened later, or started on another device, is rebuilt from110 REST (`/api/v2/research/sessions/:id`) and, while it runs, by attaching to the generation stream.111- Approvals (§9.7) appear as a banner, a sheet and — when the app is in the background — a notification whose click112 is routed to the conversation (`WindowRouter`).113- `StudyStore` reads every workspace resource network-first and keeps it in the encrypted cache for offline reading.114115## Windows116117- `WindowGroup(id: "main", for: MainSpec.self)` — any number of workstation windows. Each has its own `WindowModel`118 (section, symbol, conversation, computation, project, portfolio, watchlist, palette). The `MainSpec` value is only119 what the window was opened with; what it shows afterwards is kept in `@SceneStorage`, which macOS restores per120 window (writing navigation back into the `WindowGroup` value re-creates the window content: the 1.0.0 defect).121- `WindowGroup(id: "chart", for: ChartSpec.self)` — detached chart windows, bound to the same per-symbol chart object.122- `Settings` scene (grouped sidebar, 20 panes) and a `MenuBarExtra` (market session, a few indices, running analyses123 and jobs, a quick ask that opens Research with the question prefilled and never sends by itself).124- Menus: View lists the 14 destinations (⌘1…⌘9 for the first nine), Research and Lab menus act on the frontmost125 window through focused values (`App/Next/Commands.swift`); every shortcut comes from one table (`AppShortcuts`)126 with a unit-tested collision check. ⌘K opens the command palette (`/api/v2/search` + local commands).127- Saved layouts: synced `workspace` objects when they map, local otherwise (see sync above).128129## Charting130131`ChartCanvas` draws with Core Graphics through SwiftUI `Canvas`; `ChartInteraction` is an `NSView` that turns pointer,132scroll, pinch and keyboard input into pan and zoom, and into the drawing gestures. Swift Charts is used for result133figures (frontier, distributions, volatility forecast, allocation, drawdown).134135- **Data.** Bars come from `GET /api/v2/data/bars/:symbol` (`app.vq.data.bars`), with the provenance the data layer136 states (provider, fallback, adjustment really applied, time zone, currency, gaps, truncation) shown by the chip and137 its popover. The 1.x provider proxy is asked only when v2 answers 404 or 502, and the chip says "1.x route". A138 network failure returns the last series from the encrypted cache, marked "Cached".139- **Reduction.** When more bars are visible than fit, `Downsampler.ohlcAligned` merges neighbours for drawing only140 (first open, last close, extreme high and low, summed volume — tested), indicator lines are reduced to141 first/low/high/last per mark (`Downsampler.envelope`), both cached per zoom level in `ChartModel`; the chart states142 "1 mark = n bars", and CSV export writes the source bars.143- **Drawings** (`Core/Analytics/ChartDrawings.swift`, `ChartDrawingRender`) are anchored at `t` (epoch seconds of a144 bar) and `p` (price), never pixels: trend line, horizontal line, ray, rectangle, Fibonacci retracement, text note,145 measure. An anchor is displayed on the bar that contains its time, so drawings survive an interval change without146 being rewritten. Every edit goes through the window's `UndoManager`.147- **Persistence** (`ChartSync`). One synced `chart` object per symbol, id `sym-<SYMBOL>` derived exactly like the web148 client does (`^GSPC` → `sym-_5eGSPC`). It is created at the first change, never by viewing; saved with a 0.7 s149 debounce by editing the typed properties of the stored value, so keys, indicators and drawings written by other150 clients survive. A change made on another device is applied live.151- **Metal** was measured and not adopted: see `docs/CHART_PERFORMANCE.md`.152153## Data freshness154155`Freshness` has five states and one rule each: **Recent** (provider timestamp < 2 min), **Delayed** (older),156**Historical** (bars, statements), **Cached** (server unreachable; last value this Mac received), **Unavailable**.157The provider's timestamp is shown; the time of the request never replaces it.158159## Offline160161`DiskCache.fetch` is network-first; only a *network* failure falls back to the last stored value, marked as cached.162A server refusal is always an error. Files are AES-GCM sealed under a Keychain key, excluded from backups, bound to163their cache key, and erased at sign-out or when another person signs in. Analyses and computations are refused offline with an164explanation. Edits of synced objects (watchlists, portfolios, charts, projects, notes, preferences) are the exception165since 2.0: they are queued durably by the sync engine and sent, in order, when the connection returns.166167## Minimum system168169macOS 14: `@Observable`, `SectorMark`, `onChange(of:initial:)`, `SettingsLink`, typed `WindowGroup` restoration.170Universal binary (arm64 + x86_64).171