SPB Git

Repository Public

main.swift 20.9 KB 266 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/vqkit-shots/main.swift3// Description: Renders VQuantUI to PNG files for visual review: `LabResultView` for each recorded lab fixture, in4//              light and dark, plus a sheet of the design-system components.5//6//   swift run vqkit-shots [fixtures-dir] [output-dir] [only-name…]7//   defaults: Tests/VQuantKitTests/Fixtures  /tmp/vqkit-shots8import SwiftUI9import VQuantKit10import VQuantUI1112let arguments = CommandLine.arguments.dropFirst()13let fixtures = URL(fileURLWithPath: arguments.first ?? "Tests/VQuantKitTests/Fixtures")14let output = URL(fileURLWithPath: arguments.dropFirst().first ?? "/tmp/vqkit-shots")15let only = Set(arguments.dropFirst(2).filter { !$0.hasPrefix("--") })16/// `--en` / `--fr` render one language, `--both` the two; French files keep their names, English ones end in `-en`.17let shotLanguages: [VQLanguage] = arguments.contains("--both") ? [.fr, .en] : arguments.contains("--en") ? [.en] : [.fr]18nonisolated(unsafe) var shotLanguage: VQLanguage = .fr19var shotTheme: VQTheme { VQTheme(numberLocale: shotLanguage == .fr ? .frCA : .enCA, language: shotLanguage) }2021/// What an app shows under the fields of a Quant Lab form: the sentences of `VQLabForm.validate(language:)`.22struct FormValidationSheet: View {23    let form: VQLabForm24    @Environment(\.vqTheme) private var theme25    var body: some View {26        VStack(alignment: .leading, spacing: 10) {27            Text(form.tool.title).vqFont(VQTokens.Typography.heading).foregroundStyle(VQTokens.Palette.text1)28            if case .failure(let invalid) = form.validate(language: theme.language) {29                ForEach(invalid.issues) { issue in30                    HStack(alignment: .firstTextBaseline, spacing: 8) {31                        Image(systemName: "exclamationmark.circle").foregroundStyle(VQTokens.Palette.critical)32                        Text(issue.message).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQTokens.Palette.text1).fixedSize(horizontal: false, vertical: true)33                    }34                }35            }36        }37        .frame(maxWidth: .infinity, alignment: .leading)38    }39}4041struct ComponentSheet: View {42    let overview: VQMarketOverview?43    let quotes: VQQuotes?44    @State private var period = "1M"4546    var body: some View {47        VStack(alignment: .leading, spacing: 28) {48            VQSectionHeader("Composants", overline: "VQuant Next") { VQProvenanceChip(kind: .polled, provider: "fmp", asOf: Date(timeIntervalSince1970: 1_795_211_342), now: Date(timeIntervalSince1970: 1_795_211_400), timeZone: TimeZone(identifier: "America/Toronto")!) }49            HStack(alignment: .top, spacing: 24) {50                VQMetricTile(label: "VaR 95 %", value: 0.0231, unit: .percent, kind: .calculated, delta: -0.004, note: "Historique, 1 jour")51                VQMetricTile(label: "Dernier cours", value: 342.56, unit: .currency, kind: .observed, delta: -6.65, deltaUnit: VQValueUnit.none)52                VQMetricTile(label: "Taux sans risque", value: 0.04, unit: .percent, kind: .assumption)53                VQMetricTile(label: "Volatilité à 21 j", value: 0.263, unit: .percent, kind: .forecast, large: true)54                VQMetricTile(label: "Bêta", value: nil, unit: .ratio, kind: .calculated, note: "Non disponible")55            }56            HStack(spacing: 18) {57                ForEach(VQFreshness.Kind.allCases, id: \.self) { VQProvenanceChip(kind: $0, provider: $0 == .delayed ? "eodhd" : "fmp", asOf: Date(timeIntervalSince1970: 1_795_132_800), now: Date(timeIntervalSince1970: 1_795_211_400), timeZone: TimeZone(identifier: "UTC")!) }58            }59            HStack(spacing: 18) {60                VQDelta(0.0123, unit: .percent); VQDelta(-0.0431, unit: .percent); VQDelta(0, unit: .percent); VQDelta(0.0025, unit: .bps); VQDelta(percentPoints: -1.9043); VQDelta(nil)61                ForEach(VQValueKind.allCases, id: \.self) { VQKindBadge($0) }62            }63            HStack(spacing: 18) {64                VQSegmentedControl("Période", selection: $period, options: ["1S", "1M", "3M", "1A", "5A"].map { .init($0, $0) })65                ForEach(["anthropic", "openai", "google", "openrouter", "local", "mystery"], id: \.self) { p in66                    HStack(spacing: 6) { VQProviderLogo(provider: p, size: 20); Text(p).vqFont(VQTokens.Typography.caption) }.foregroundStyle(VQTokens.Palette.text1)67                }68                VQAIActivity("Lit les états financiers", detail: "12 s")69                VQSparkline([1, 1.2, 1.1, nil, 1.4, 1.35, 1.6, 1.5, 1.8], baseline: 1.1, label: "30 séances")70            }71            if let section = overview?.section("indices"), let fresh = section.freshness {72                VQPanel("Indices", flush: true, meta: { VQProvenanceChip(fresh, now: Date(timeIntervalSince1970: 1_795_211_400), timeZone: TimeZone(identifier: "America/Toronto")!) }, content: {73                    VQDataTable("Indices", columns: [.init(id: "s", title: "Symbole"), .init(id: "n", title: "Nom"), .init(id: "p", title: "Cours", alignment: .trailing), .init(id: "c", title: "Var.", alignment: .trailing), .init(id: "pc", title: "Var.", unit: "%", alignment: .trailing)],74                                rows: section.items.prefix(7).map { i in75                                    VQTableRow(id: i.id, cells: [VQTableCell(i.symbol ?? "—"), VQTableCell(i.name), VQTableCell(VQFormat.number(i.price), numeric: true, sortValue: i.price),76                                                                 VQTableCell(VQFormat.delta(i.change), numeric: true, sortValue: i.change, direction: VQFormat.direction(i.change)),77                                                                 VQTableCell((VQFormat.direction(i.changePct) == .up ? "▲ " : VQFormat.direction(i.changePct) == .down ? "▼ " : "") + VQFormat.number(i.changePct, signed: true), numeric: true, sortValue: i.changePct, direction: VQFormat.direction(i.changePct))])78                                })79                }, footer: { Text(section.freshness?.note ?? "Cotations interrogées à la demande ; ce n'est pas un flux continu.").vqFont(VQTokens.Typography.caption).foregroundStyle(VQTokens.Palette.text3) })80            }81            HStack(alignment: .top, spacing: 24) {82                VQSurface(level: 1) { VQEmptyState(systemImage: "tray", title: "Aucune position", message: "Ajoutez une position pour suivre ce portefeuille.").frame(width: 320) }83                VQSurface(level: 2) { VStack(alignment: .leading, spacing: 12) { VQSkeletonText(lines: 3); VQSkeletonRows(rows: 3, columns: 3) }.padding(16).frame(width: 300) }84                VQSurface(level: 1) { VQSkeletonChart(height: 110).padding(16).frame(width: 240) }85            }86        }87    }88}8990import ImageIO91import UniformTypeIdentifiers9293/// Tall renders are also cut into tiles (`tiles/<name>-NN.png`) that fit an image viewer.94@MainActor func tiles(_ data: Data, _ name: String, height: Int = 1500) {95    guard name.hasSuffix(".png"), let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil), image.height > height + 300 else { return }96    let dir = output.appendingPathComponent("tiles")97    try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)98    var y = 0, n = 099    while y < image.height {100        let h = min(height, image.height - y)101        if let tile = image.cropping(to: CGRect(x: 0, y: y, width: image.width, height: h)),102           let dest = CGImageDestinationCreateWithURL(dir.appendingPathComponent(String(format: "%@-%02d.png", String(name.dropLast(4)), n)) as CFURL, UTType.png.identifier as CFString, 1, nil) {103            CGImageDestinationAddImage(dest, tile, nil)104            CGImageDestinationFinalize(dest)105        }106        y += height; n += 1107    }108}109110@MainActor func write(_ data: Data?, _ name: String) {111    guard let data else { print("FAILED \(name)"); return }112    var name = name113    if shotLanguage == .en, !name.contains("-en"), let dot = name.lastIndex(of: ".") { name.insert(contentsOf: "-en", at: dot) }114    let url = output.appendingPathComponent(name)115    do { try data.write(to: url); tiles(data, name); print("\(name)  \(data.count / 1024) KB") } catch { print("FAILED \(name): \(error)") }116}117118@MainActor func run() throws {119    try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)120    func json(_ name: String) -> VQJSON? { (try? Data(contentsOf: fixtures.appendingPathComponent(name))).flatMap { try? VQJSON.parse($0) } }121    let schemes: [(ColorScheme, String)] = [(.light, "light"), (.dark, "dark")]122123    if only.isEmpty || only.contains("components") {124        let sheet = ComponentSheet(overview: json("market_overview.json").map(VQMarketOverview.init(json:)), quotes: json("quotes.json").map(VQQuotes.init(json:)))125        for (scheme, label) in schemes {126            write(VQExport.png(sheet, width: 1100, colorScheme: scheme, theme: shotTheme), "components-\(label).png")127        }128        write(VQExport.png(sheet, width: 1100, colorScheme: .light, theme: VQTheme(upDown: .cvd, numberLocale: .enCA, language: .en)), "components-light-cvd-en.png")129    }130131    let names = only.contains("research") ? [] : (try FileManager.default.contentsOfDirectory(atPath: fixtures.path)).filter { $0.hasPrefix("job_") && $0.hasSuffix(".json") }.sorted()132    for file in names {133        let name = String(file.dropFirst(4).dropLast(5))134        guard only.isEmpty || only.contains(name), let job = json(file)?["job"].map(VQQuantJob.init(json:)), let result = job.labResult else { continue }135        var options = LabResultView.Options()136        options.expanded = false137        for (scheme, label) in schemes {138            write(VQExport.png(LabResultView(result, options: options), width: 1180, colorScheme: scheme, theme: shotTheme, scale: 1.25), "lab-\(name)-\(label).png")139        }140    }141    // 0.3 — a candles chart (no engine emits one yet: the encoding of CONTRACT §4.2 on recorded AAPL bars)142    if only.isEmpty || only.contains("extras"), let bars = json("bars_aapl_1d.json").map(VQBarSeries.init(json:)) {143        let b = Array(bars.bars.suffix(60))144        func arr(_ f: (VQBar) -> Double?) -> VQJSON { .array(b.map { VQJSON(f($0)) }) }145        let candles = VQLabResult.Chart(json: ["id": "candles", "title": "AAPL — 60 dernières séances", "type": "candles", "x": ["label": "Date", "type": "time"], "y": ["label": "Cours", "unit": "currency", "currency": "USD"],146            "series": [["name": "AAPL", "kind": "observed", "x": .array(b.map { .string(VQFormat.dateISO($0.date, timeZone: TimeZone(identifier: "UTC")!)) }), "open": arr { $0.open }, "high": arr { $0.high }, "low": arr { $0.low }, "close": arr { $0.close }, "y": arr { $0.close }]]])147        for (scheme, label) in schemes {148            write(VQExport.png(LabChartView(candles, height: 300, inspecting: VQChartX.time(b[40].date)), width: 760, colorScheme: scheme, theme: shotTheme), "chart-candles-\(label).png")149        }150        write(VQExport.png(LabChartView(candles, height: 300), width: 760, colorScheme: .light, theme: VQTheme(upDown: .cvd, numberLocale: shotTheme.numberLocale, language: shotLanguage)), "chart-candles-cvd-light.png")151    }152    // 0.4 — the validation sentences of a real tool's form (required, conditional, type and range rules)153    if only.isEmpty || only.contains("extras") || only.contains("form"), let tools = json("quant_tools.json").map(VQLabCatalog.init(json:)) {154        if let tool = tools.tools.first(where: { $0.id == "bootstrap" }) {155            var form = VQLabForm(tool: tool)156            form["symbol"] = "not a symbol"; form["statistic"] = "beta"; form["period_days"] = "abc"; form["start"] = "2026/01/01"157            write(VQExport.png(FormValidationSheet(form: form), width: 560, colorScheme: .light, theme: shotTheme), "form-validation-light.png")158        }159        if let tool = tools.tools.first(where: { $0.id == "portfolio_optimization" }) {160            var form = VQLabForm(tool: tool)161            form["symbols"] = ""; form["min_weight"] = "0.6"; form["max_weight"] = "0.2"; form["data_period"] = "5.5"162            write(VQExport.png(FormValidationSheet(form: form), width: 560, colorScheme: .light, theme: shotTheme), "form-validation-portfolio-light.png")163        }164    }165    // a narrow (phone-width) render, an inspected chart, a PDF and a failure166    if only.isEmpty || only.contains("extras"), let result = json("job_time_series.json")?["job"].map(VQQuantJob.init(json:))?.labResult {167        write(VQExport.png(LabResultView(result), width: 390, colorScheme: .light, theme: VQTheme(numberLocale: .enCA, language: .en), padding: 16), "lab-time_series-phone-en.png")168        if let fan = result.charts.first(where: { $0.type == .fan }) {169            let at = VQISODate.parse("2026-11-30").map(VQChartX.time)170            write(VQExport.png(LabChartView(fan, height: 300, inspecting: at), width: 720, colorScheme: .dark, theme: shotTheme), "chart-fan-inspected-dark.png")171            write(VQExport.pdf(chart: fan, colorScheme: .light, theme: shotTheme), "chart-fan.pdf")172        }173        let failed = VQLabResult(json: ["success": false, "schema": "lab/1", "engine": "regression", "title": "Régression", "error": "Aucune barre quotidienne pour ZZZZNOPE : vérifiez le symbole."])174        write(VQExport.png(LabResultView(failed), width: 720, colorScheme: .light, theme: shotTheme), "lab-failure-light.png")175    }176}177178/// The research activity views, from the recorded real study (Fixtures/research).179@MainActor func research() throws {180    let dir = fixtures.appendingPathComponent("research")181    func json(_ name: String) -> VQJSON? { (try? Data(contentsOf: dir.appendingPathComponent(name))).flatMap { try? VQJSON.parse($0) } }182    guard let detailJSON = json("session.json"), let events = json("stream_study.json")?.arrayValue else { print("no research fixtures in \(dir.path)"); return }183    let detail = VQResearchSessionDetail(json: detailJSON)184    let snapshot = VQResearchState(detail: detail, conversation: json("conversation.json"))185    let live = VQResearchReducer.replay(events)186    let state = live.merged(over: snapshot.filtered(generationId: live.generationId ?? ""))187    let sandbox = json("sandbox.json").map(VQSandboxStatus.init(json:))188189    var preload = ResearchPreload()190    for name in ["file_cell.json", "file_code.json", "file_common.json", "file_csv.json", "file_lock.json"] {191        if let f = json(name).map(VQResearchFilePreview.init(json:)) { preload.texts[f.path] = f.text }192    }193    // figure_NN.png are the first PNGs of artifacts/figures in file-name order (downscaled copies)194    let pngs = detail.files.map(\.path).filter { $0.hasPrefix("artifacts/figures/") && $0.hasSuffix(".png") }.sorted()195    for (i, png) in pngs.prefix(6).enumerated() {196        if let data = try? Data(contentsOf: dir.appendingPathComponent(String(format: "figure_%02d.png", i + 1))) { preload.data[png] = data }197    }198    let withImage = state.figures.filter { f in f.files?.png.map { preload.data[$0] != nil } ?? false }199    let shownFigures = withImage + state.figures.filter { f in f.lintPassed == false && !withImage.contains { $0.key == f.key } }.prefix(1)200    if let logs = json("run_detail.json").map(VQRunLogs.init(json:)) { preload.logs[logs.run.id] = logs }201202    let now = Date(timeIntervalSince1970: 1_795_213_500)203    var pending = state204    VQResearchReducer.reduce(&pending, ["type": "approval_request", "approval": ["id": "ap-demo", "action": "open_network", "reason": "Télécharger la série CPIAUCSL de FRED pour prolonger l'échantillon après 2009.",205        "detail": ["host": "fred.stlouisfed.org", "script": "code/fetch_fred.py"], "status": "pending", "createdAt": .number((now.timeIntervalSince1970 - 13 * 60 - 20) * 1000)]])206    let store = VQResearchSessionStore(state: state, detail: detail, sandbox: sandbox)207    let failedKey = state.executions.first { $0.status == .failed }?.key208    let okKey = state.executions.first { $0.status == .ok && $0.output != nil }?.key209    let runWithLogs = preload.logs.keys.first210211    func shot<V: View>(_ name: String, width: CGFloat = 1000, theme: VQTheme = shotTheme, schemes: [(ColorScheme, String)] = [(.light, "light"), (.dark, "dark")], _ view: V) {212        guard only.isEmpty || only.contains("research") || only.contains(name) else { return }213        for (scheme, label) in schemes {214            write(VQExport.png(view.researchPreload(preload), width: width, colorScheme: scheme, theme: theme, scale: 1.5), "research-\(name)-\(label).png")215        }216    }217    shot("activity", ResearchActivityView(store: store, initial: .timeline))218    shot("plan-timeline", width: 520, VStack(alignment: .leading, spacing: 20) { ResearchPlanView(state); ResearchTimelineView(state, limit: 28) })219    shot("code", ResearchExecutionList(state.executions, installs: state.installs, expanded: Set([failedKey, okKey].compactMap { $0 })))220    shot("experiments", ResearchExperimentsTable(state.experiments))221    shot("figures", ResearchFiguresGrid(shownFigures))222    shot("runs", width: 820, ResearchRunsList(state.runs, expanded: Set([runWithLogs].compactMap { $0 })))223    shot("gate", width: 760, ResearchQualityGateView(state.gateFindings))224    shot("files-code", ResearchFilesBrowser(files: detail.files, selection: .constant("code/fc_ucsv.py")))225    shot("files-csv", ResearchFilesBrowser(files: detail.files, selection: .constant("artifacts/dm_post1985.csv"), expanded: ["artifacts"]))226    shot("environment", width: 860, ResearchEnvironmentPanel(sandbox: sandbox, environment: detail.environment, library: detail.library))227    let unenforced = VQSandboxStatus(json: ["sandbox": ["enforced": false, "mechanism": .null, "note": "No isolation mechanism is available on this host."], "limits": ["memoryMb": 8192], "network": ["default": ["market data through the server"], "open": "any public host"], "uploadMaxBytes": 209715200])228    shot("environment-unenforced", width: 860, schemes: [(.light, "light")], ResearchEnvironmentPanel(sandbox: unenforced, environment: detail.environment))229    shot("approval", width: 620, VStack(spacing: 16) {230        ResearchApprovalCard(pending.pendingApprovals[0], now: now, onApprove: {}, onRefuse: {})231        ResearchApprovalCard(VQResearchApproval(json: ["id": "b", "action": "raise_budget", "reason": "La comparaison hors échantillon demande 40 minutes de plus.", "detail": ["maxCostUsd": 6, "maxMinutes": 90], "status": "pending", "createdAt": .number((now.timeIntervalSince1970 - 120) * 1000)]), now: now, onApprove: {}, onRefuse: {})232    })233    // 0.3 — the two real approval sequences (approved, denied), mid-way and at the end; a study reopened from REST234    if let streams = json("approval_stream.json") {235        for (name, label) in [("approved", "approved"), ("denied", "denied")] {236            let events = streams[name]?.list("events") ?? []237            var midway = VQResearchState()238            for e in events { VQResearchReducer.reduce(&midway, e); if e.str("type") == "approval_request" { break } }239            let end = VQResearchReducer.replay(events)240            let asked = midway.pendingApprovals.first?.createdAt ?? now241            shot("approval-\(label)", width: 640, VStack(alignment: .leading, spacing: 16) {242                if let a = midway.pendingApprovals.first { ResearchApprovalCard(a, now: asked.addingTimeInterval(1), onApprove: {}, onRefuse: {}) }243                if let a = end.approvals.first { ResearchApprovalCard(a, now: asked.addingTimeInterval(60), onApprove: {}, onRefuse: {}) }244                ResearchActivityView(store: VQResearchSessionStore(state: end, sandbox: sandbox), sections: [.timeline, .runs], initial: .timeline)245            })246        }247        if let a = VQResearchReducer.replay(streams["approved"]?.list("events").prefix(7).map { $0 } ?? []).pendingApprovals.first {248            shot("approval-expired", width: 640, schemes: [(.light, "light")], ResearchApprovalCard(a, now: (a.createdAt ?? now).addingTimeInterval(16 * 60), onApprove: {}, onRefuse: {}))249        }250    }251    if let reopenedJSON = json("session_v03_439f8b56.json") {252        let d = VQResearchSessionDetail(json: reopenedJSON)253        let st = VQResearchState(detail: d, conversation: json("conversation_v03_439f8b56.json"))254        var p2 = preload255        if let png = st.figures.first?.files?.png, let data = try? Data(contentsOf: dir.appendingPathComponent("figure_01.png")) { p2.data[png] = data }256        let saved = preload; preload = p2257        shot("reopened", width: 760, VStack(alignment: .leading, spacing: 20) { ResearchPlanView(st); ResearchTimelineView(st); ResearchFiguresGrid(st.figures) })258        preload = saved259    }260    let phoneStore = VQResearchSessionStore(state: pending, detail: detail, sandbox: sandbox)261    shot("activity-phone-en", width: 390, theme: VQTheme(numberLocale: .enCA, language: .en), schemes: [(.light, "light")], ResearchActivityView(store: phoneStore, initial: .experiments, now: now))262    shot("code-phone", width: 390, schemes: [(.dark, "dark")], ResearchExecutionList(Array(state.executions.prefix(6)), installs: state.installs, expanded: Set([failedKey].compactMap { $0 })))263}264265try MainActor.assumeIsolated { for language in shotLanguages { shotLanguage = language; try run(); try research() } }266
Files main
Menu

Theme