SPB Git

Repository Public

7 entries at the root
History

Latest commit VQuantKit 0.4.1: day unit follows the language (d / j) 53b489c

NameLast commitUpdated
docs VQuantKit 0.4: localized strings (English and French String Catalog, plurals), language follows...
Scripts VQuantKit 0.3: stored research plans and figure verdicts, event ids and timestamps, applied...
Sources VQuantKit 0.4.1: day unit follows the language (d / j)
Tests VQuantKit 0.4.1: day unit follows the language (d / j)
.gitignore VQuantKit 0.1: shared sync engine, models, data, Quant Lab, research clients and VQuantUI for...
Package.swift VQuantKit 0.4: localized strings (English and French String Catalog, plurals), language follows...
README.md VQuantKit 0.4: localized strings (English and French String Catalog, plurals), language follows...
README.md View source

# VQuantKit

The shared Swift package of the VQuant native apps (macOS 14+, iOS/iPadOS 18+) for backend 6 "VQuant Next". Swift 6 language mode, strict concurrency, no third-party dependency.

Contract: vquant-next/docs/next/CONTRACT.md (§1 sync, §2 models/usage/trace, §3 data layer, §4 Quant Lab, §5 projects/review, §6 memory, §7 audit, §8 design system). Integration guide for the two apps: docs/INTEGRATION.md.

Product What it is
VQuantKit No UI, Sendable: transport seam, sync engine, models of every v6 route, Lab form and jobs, formatting
VQuantUI SwiftUI: design-system components and the generic LabResultView (Swift Charts)
VQuantKitTesting Fakes for tests: VQFakeServer (contract rev/seq rules), VQManualClock, VQScriptedTransport
vqkit-shots macOS executable: renders VQuantUI to PNG for visual review

# Layout

text
Sources/VQuantKit/
  Core/        VQJSON (lossless JSON), VQTransport + VQClient + VQError, VQSSEParser, VQClock, VQURLSessionTransport
  Sync/        VQObjectEnvelope, typed kinds (VQWatchlist, VQPortfolio, VQWorkspace + VQLayoutNode, VQChart, VQProject,
               VQNote, VQReview, VQPreference), VQObjectStoreClient, VQMerge, VQSyncStorage, VQSyncEngine,
               VQSyncedCollection / VQSyncStatusStore (@Observable)
  Models/      VQModelCatalog, VQRouteDecision, VQUsage, VQGenerationTrace, VQGenerationEvent, VQMessageExtras
  Data/        VQBarSeries, VQQuotes, VQStatements, VQMarketOverview, VQDataHealth, VQSearchResults, VQFreshness
  Lab/         VQLabResult (lab/1), VQLabCatalog / VQLabTool / VQLabParam, VQLabForm, VQQuantJob, VQLabClient,
               VQLabChartData (axis reading, downsampling, colour classes — the pure part of rendering)
  Research/    VQProjectBundle, run/export, reviews, VQMemory*, VQAuditEvent, VQResearchClient   (§5–7: projects)
  ResearchAgent/  the autonomous research agent (§9): VQResearchAgentClient (sessions, files, inspect, upload,
               ledger, runs + logs, approvals, sandbox), VQResearchEvent, VQResearchState + VQResearchReducer,
               VQResearchSessionStore (@Observable), VQAnalysisMode (`research`), VQDatasetUpload, VQResearchFileTree,
               VQDelimitedText, VQPythonSyntax
  Formatting/  VQFormat (numbers and dates identical to the web's lib/format.ts)
Sources/VQuantUI/
  Tokens/      VQTokens.swift — GENERATED, do not edit (see below)
  Components/  VQSurface, VQPanel, VQSectionHeader, VQMetricTile, VQKindBadge, VQDelta, VQProvenanceChip,
               VQSegmentedControl, VQEmptyState, VQSkeleton*, VQAIActivity, VQSparkline, VQProviderLogo,
               VQDataTable, VQMarkdownText
  Lab/         LabResultView, LabChartView, LabDiagnosticsList, LabProvenancePanel
  Research/    ResearchActivityView (container) and its pieces: ResearchPlanView, ResearchTimelineView,
               ResearchExecutionList, ResearchCodeView, ResearchExperimentsTable, ResearchFiguresGrid,
               ResearchRunsList, ResearchFilesBrowser, ResearchFilePreview, ResearchEnvironmentPanel,
               ResearchQualityGateView, ResearchApprovalCard; ResearchDataSource / ResearchPreload (environment)
  Support/     VQTheme (environment), VQSVGPath, VQExport (PNG / PDF / CSV), VQPasteboard

# Design decisions worth knowing

  • VQTransport is the only seam with the network: send (data + HTTPURLResponse, whatever the status) and stream (bytes for SSE). The package never sees a URL or a token. Each app adapts its own APIClient in a few lines; VQURLSessionTransport is a complete implementation for a token provider closure.
  • VQJSON, not JSONValue: both apps' VQuantCore already export a JSONValue.
  • Forward compatibility. The sync models are views over their JSON (VQJSONBacked): unknown keys at any depth, explicit nulls and fields of an unexpected type survive decode → typed edit → encode. Everything else is read with tolerant init(json:) initialisers that never throw; enumerations are VQOpen<Known> (unknown values are kept); unknown stream events come back as .other. Object kinds are strings (VQObjectKind), so a kind added by a later contract section is replicated by the sync engine untouched.
  • Adding §9 (or any later section) = a new folder with its models (init(json:)), a client struct over VQClient, one property on VQuantAPI. New stream events: a case in VQGenerationEvent / VQSyncStreamEvent.
  • Formatting is tested against 4 212 strings generated by the web's own format.ts.
  • Freshness never says "live": polled / delayed / close / historical / estimated.

# Sync engine in one paragraph

VQSyncEngine (an actor) keeps replica (last server state, tombstones included), an ordered durable queue of local writes, and the change-feed cursor, in a VQSyncStorage (files with atomic writes and an optional VQSyncCipher, or memory). Reads return the replica with the queue applied. flush() replays the queue in order with the rev the server gave (never an invented one); a 409 — or a replica that moved since the edit — goes through VQMerge: element-wise for watchlist symbols, portfolio positions (and cash), project.items, chart.drawings ("local edit wins per element"), last-writer-wins for the rest, with a VQConflictRecord holding both versions when content of the other side was overwritten. pull() pages the feed by since. start() opens the stream, reconnects with back-off, pulls on hello/change, exposes hint events. Nothing runs on its own unless start() is called.

Deliberate choices to review: (1) non-list fields use the contract's whole-object last-writer-wins by default; Configuration.granularity = .field keeps keys this device did not touch. (2) Portfolio cash is merged by currency like positions (the contract names positions only). (3) A local deletion wins over a concurrent remote edit and is reported with the remote content, which restoreRemoteVersion(ofConflict:) writes back.

# Tests

bash
swift build && swift test                      # 129 kit tests + 23 UI tests; live tests are skipped
xcodebuild -scheme VQuantKit-Package -destination 'generic/platform=iOS Simulator' build
swift run vqkit-shots                          # PNGs in /tmp/vqkit-shots (+ tiles/ for tall ones)

Fixtures (Tests/VQuantKitTests/Fixtures) are real responses of the frozen test backend (M2U64:5058), trimmed by Scripts/trim-fixtures.py (long arrays decimated, structure kept). Re-record: Scripts/record-fixtures.sh (never production; the token stays on the node). budget and quant_job stream events did not occur in the recorded run: those two payloads are written from the contract. Formatting vectors: TZ=America/Toronto npx tsx <kit>/Scripts/format-golden.mjs <kit>/Tests/VQuantKitTests/Fixtures/format_golden.json from the web repo root.

Live integration tests (opt-in):

bash
ssh -f -N -L 5058:localhost:5058 M2U64          # note the PID (lsof -nP -iTCP:5058 -sTCP:LISTEN), kill it afterwards
VQ_LIVE=1 VQ_BASE_URL=http://localhost:5058 VQ_TOKEN="$(ssh M2U64 cat /tmp/vq-api-token)" swift test --filter VQuantKitLiveTests

Research-agent fixtures (Fixtures/research/) come from the real study on the 5059 copy (Scripts/record-research-fixtures-remote.sh); stream_study.json is the web team's recording of that study's generation stream. No approval occurred in it: approval events in the tests are written from the contract. Live, read-only, against that copy:

bash
ssh -f -N -L 5059:localhost:5059 M2U64
VQ_LIVE=1 VQ_RESEARCH_BASE_URL=http://localhost:5059 VQ_RESEARCH_TOKEN="$(ssh M2U64 cat /tmp/vq-api-token-5059)" swift test --filter VQuantKitResearchLiveTests

# Research agent (CONTRACT §9)

One view model, two builders — the same design as the web's client/src/lib/research (the reducer is a port of it, so the three platforms show the same thing for the same events):

  • VQResearchReducer.reduce(&state, eventJSON, index:) while a generation streams. Replays at or below the last index are ignored, entities with an id are upserts, unknown events change nothing, a late duplicate never revives a finished run, failed cells are kept with their error.
  • VQResearchState(detail:conversation:) once it is over, from GET /api/v2/research/sessions/:id and the stored conversation. What the server does not keep is left empty: the linter verdict of each figure, the plan, the console output of cells that printed nothing.
  • VQResearchSessionStore holds both (live on top of the snapshot) for SwiftUI and answers approvals.

On the recorded study both builders give 56 executions (46 cells + 10 runs), 4 failed, 9 experiments (one failed, one abandoned), 14 figures, and the same quality-gate findings.

# 0.3 — additive fields of backend 6 (all source-compatible)

No public declaration was renamed, removed or re-typed, and no case was added to an existing enumeration (an app that switches exhaustively keeps compiling). New server vocabulary therefore arrives beside the frozen enumerations:

Server addition Where it is
unit years, any later unit unitName on metrics, columns and axes + VQFormat.byUnitName (VQValueUnit unchanged)
usage role utility VQUsageByModel.isUtility (decodes as .unknown("utility"))
budget_applied event VQBudgetApplied(event:) on the .other payload; VQGenerationTrace.budgetApplied
code_execution_start, new figure_lint, at, toolId handled by VQResearchReducer; VQResearchEvent keeps its cases (.other for the new type)
lab/1 renderer rules Column.currency / currencyKey / type, XAxis.unit / currency, YAxis.currency, Chart.z + cellAxis, Series.drawsCentreLine, Series.open/high/low/close/volume
conditional parameters VQLabParam.requiredWhen / visibleWhen (VQLabCondition), VQLabForm.isVisible / isRequired / visibleGroups; validate() enforces requiredWhen with the server's sentence
research REST VQResearchSessionDetail.generations / plan / figures, VQResearchAgentClient.deleteFile, researchModeAvailability()

Lab fixtures were re-recorded (Fixtures/job_*.json); the earlier recordings are kept in Fixtures/lab_v0/ and still decode and render (history holds old results). Batch bars and splits are not in CONTRACT §3 yet: not added.

# 0.4 — one language per screen (source-compatible)

  • All user-facing strings of VQuantUI and the display strings of VQuantKit live in a String Catalog (Sources/VQuantKit/Resources/Localizable.xcstrings, defaultLocalization: "en", 275 keys, English + French, plural variations). VQL10n.string(_:_:…) reads it through Bundle.module.
  • VQLanguage.preferred now follows the app's localisation (Bundle.main.preferredLocalizations) instead of the device's language list: the components no longer answer in French inside an English app.
  • Override: .vqLanguage(_:) / .vqLanguage(locale:) on any view (environment \.vqLanguage); it wins over VQTheme.language. New overloads with a language: VQLabForm.validate(language:), issue(for:language:), VQLabCondition.sentence(labels:language:), VQProviderMark.displayName(_:), VQLanguage(locale:).
  • Server-authored text is never translated. Date layouts and number formats stay formatting (VQFormat, numberLocale).
  • swift run vqkit-shots <fixtures> <out> --both renders every shot in French and in English (…-en.png).

# Design tokens

Sources/VQuantUI/Tokens/VQTokens.swift is a copy of the generated shared/design/VQTokens.swift of the web repo. Never edit it. To update: edit shared/design/tokens.json there, run node scripts/design-tokens.mjs, copy the file here again.

# Known limits

  • $…$ formulas are not typeset: the LaTeX is made readable (Greek letters, operators) and set in mono.
  • A surface chart is drawn as a filled-contour map (seven classes, boundaries in the key), not in 3-D; heat maps use the same seven classes rather than a continuous ramp.
  • candles is in the schema but no engine emits it: such a chart falls back to lines and has not been seen rendered.
  • Off-screen exports cannot scroll: wide tables are narrowed, and cut on the right below phone width.
  • Results of the six legacy tools are not lab/1: the apps keep their own renderers (job.labResult == nil).
  • Research figures are shown from their PNG; SVG and PDF are export actions (bytes handed to the app), not previews.
  • Python colouring is a tokenizer, not a parser; other languages are shown as plain mono text.
  • Studies recorded before the server kept figures have no linter verdict when reopened (shown as "not kept").
  • No engine emits candles yet: the candle marks are tested on the contract's encoding built from recorded AAPL bars.

Clone vquant-kit

Anonymous clone and fetch. Pushing requires the owner's personal access token.

Snapshot of main

Files main
Menu

Theme