Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/search.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Universal search (contract §3, GET /api/v2/search): one box for symbols, the person's own material and the47 * places of the app.48 *49 * symbol FMP symbol and name search; a query shaped like an ISIN goes to the ISIN lookup50 * conversation the person's conversations, by title51 * project, note, watchlist, portfolio, chart the person's objects52 * action navigation targets and Quant Lab engines (a static list: the app's own map)53 *54 * Everything personal is read with the signed-in owner in the WHERE clause. The provider call is capped at55 * 2.5 s: when it is slow or down the local results are returned alone and `unavailable` says what is missing.56 */57import type { Express, Request, Response } from "express";58import type Database from "better-sqlite3";59import { isSqlite, pool } from "../db";60import { logger } from "../utils/logger";61import { searchByISIN, searchCompanies, searchName } from "../services/fmpService";62import { listObjects, type Kind } from "./objects";6364export const SEARCH_TYPES = ["symbol", "conversation", "project", "note", "watchlist", "portfolio", "chart", "report", "indicator", "action"] as const;65export type SearchType = (typeof SEARCH_TYPES)[number];6667export interface SearchResult {68 type: SearchType;69 id: string;70 title: string;71 subtitle: string | null;72 symbol?: string;73 exchange?: string;74 assetClass?: string;75 score: number;76}7778const SYMBOL_TIMEOUT_MS = 2500;79const ISIN_RE = /^[A-Z]{2}[A-Z0-9]{9}\d$/;8081/**82 * Navigation targets. `id` is a stable key the clients map to their own routes; `title` is the French label of83 * the web UI; `keywords` are matched as well (English names, synonyms).84 */85export const ACTIONS: ReadonlyArray<{ id: string; title: string; subtitle: string; keywords: string[] }> = [86 { id: "nav:home", title: "Accueil", subtitle: "Espace de travail", keywords: ["home", "workspace", "dashboard", "bureau"] },87 { id: "nav:chat", title: "Nouvelle analyse", subtitle: "Poser une question à l'agent", keywords: ["chat", "analyse", "analysis", "agent", "question", "new"] },88 { id: "nav:terminal", title: "Terminal", subtitle: "Marchés, cotations, graphiques", keywords: ["terminal", "market", "marché", "quotes", "cotations"] },89 { id: "nav:markets", title: "Vue des marchés", subtitle: "Indices, secteurs, taux, devises", keywords: ["markets", "overview", "indices", "sectors", "rates", "fx", "taux", "devises"] },90 { id: "nav:charts", title: "Graphiques", subtitle: "Graphiques et indicateurs", keywords: ["chart", "charts", "graph", "technical", "technique"] },91 { id: "nav:quant", title: "Quant Lab", subtitle: "Moteurs quantitatifs", keywords: ["quant", "lab", "laboratoire", "engine", "moteur", "econometrics", "économétrie"] },92 { id: "nav:portfolio", title: "Portefeuille", subtitle: "Positions, risque, allocation", keywords: ["portfolio", "positions", "holdings", "allocation"] },93 { id: "nav:watchlists", title: "Listes de suivi", subtitle: "Vos listes de titres", keywords: ["watchlist", "watchlists", "suivi", "listes"] },94 { id: "nav:research", title: "Research Studio", subtitle: "Projets de recherche", keywords: ["research", "studio", "projects", "projets", "recherche"] },95 { id: "nav:notes", title: "Notes", subtitle: "Vos notes", keywords: ["notes", "note"] },96 { id: "nav:history", title: "Historique", subtitle: "Vos conversations", keywords: ["history", "conversations", "historique", "sessions"] },97 { id: "nav:statements", title: "États financiers", subtitle: "Résultats, bilan, flux de trésorerie", keywords: ["statements", "financials", "income", "balance", "cash flow", "bilan", "états"] },98 { id: "nav:options", title: "Options", subtitle: "Chaînes, grecques, stratégies", keywords: ["options", "greeks", "grecques", "volatility surface", "chain"] },99 { id: "nav:macro", title: "Macro", subtitle: "Courbe des taux, calendrier économique", keywords: ["macro", "yield curve", "calendar", "économie", "economy"] },100 { id: "nav:agent", title: "Agent", subtitle: "Mémoire et veilles programmées", keywords: ["agent", "memory", "mémoire", "watches", "veilles", "schedule"] },101 { id: "nav:usage", title: "Usage et coûts", subtitle: "Consommation des modèles", keywords: ["usage", "cost", "coûts", "tokens", "billing"] },102 { id: "nav:settings", title: "Réglages", subtitle: "Apparence, modèles, appareils", keywords: ["settings", "preferences", "réglages", "paramètres", "theme", "devices", "appareils"] },103 { id: "nav:security", title: "Sécurité", subtitle: "Appareils, clés d'accès, journal d'audit", keywords: ["security", "sécurité", "passkeys", "audit", "devices"] },104 // Quant Lab engines (ids of contract §4.3): the palette opens the engine's form.105 { id: "engine:volatility_lab", title: "Volatility Lab", subtitle: "Quant Lab · EWMA, GARCH, HAR-RV", keywords: ["volatility", "volatilité", "garch", "egarch", "ewma", "har"] },106 { id: "engine:risk_lab", title: "Risk Lab", subtitle: "Quant Lab · VaR, expected shortfall, stress", keywords: ["risk", "risque", "var", "value at risk", "expected shortfall", "drawdown", "stress"] },107 { id: "engine:regression", title: "Regression", subtitle: "Quant Lab · OLS, WLS, GLS, erreurs robustes", keywords: ["regression", "régression", "ols", "wls", "gls", "hac"] },108 { id: "engine:factor_model", title: "Factor Model", subtitle: "Quant Lab · expositions factorielles", keywords: ["factor", "facteur", "fama", "french", "beta", "alpha"] },109 { id: "engine:panel", title: "Panel", subtitle: "Quant Lab · effets fixes et aléatoires", keywords: ["panel", "fixed effects", "random effects", "hausman"] },110 { id: "engine:time_series", title: "Time Series", subtitle: "Quant Lab · ARIMA, racine unitaire, prévisions", keywords: ["time series", "séries temporelles", "arima", "sarima", "unit root", "adf", "forecast"] },111 { id: "engine:var_model", title: "VAR / VECM", subtitle: "Quant Lab · cointégration, causalité, réponses impulsionnelles", keywords: ["var", "vecm", "cointegration", "johansen", "granger", "impulse"] },112 { id: "engine:event_study", title: "Event Study", subtitle: "Quant Lab · rendements anormaux", keywords: ["event study", "étude d'événement", "abnormal returns", "car"] },113 { id: "engine:pca", title: "PCA", subtitle: "Quant Lab · composantes principales", keywords: ["pca", "principal components", "composantes principales"] },114 { id: "engine:bootstrap", title: "Bootstrap", subtitle: "Quant Lab · rééchantillonnage", keywords: ["bootstrap", "resampling", "rééchantillonnage"] },115 { id: "engine:options_lab", title: "Options Lab", subtitle: "Quant Lab · prix, grecques, volatilité implicite", keywords: ["options", "black-scholes", "binomial", "greeks", "implied volatility", "smile"] },116 { id: "engine:backtest", title: "Backtest", subtitle: "Quant Lab · stratégies, coûts, walk-forward", keywords: ["backtest", "strategy", "stratégie", "walk-forward"] },117 { id: "engine:portfolio_lab", title: "Portfolio Lab", subtitle: "Quant Lab · allocation, frontière, attribution", keywords: ["portfolio", "portefeuille", "optimization", "optimisation", "frontier", "attribution", "rebalancing"] },118];119120/** Lower case, no accents: "Études" matches "etudes". */121const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();122123/** How well `text` answers the folded query: 1 exact, then prefix, word prefix, substring; 0 = no match. */124function matchScore(text: unknown, q: string): number {125 if (typeof text !== "string" || !text) return 0;126 const t = fold(text);127 if (t === q) return 1;128 if (t.startsWith(q)) return 0.85;129 if (new RegExp(`(^|[^a-z0-9])${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(t)) return 0.7;130 return t.includes(q) ? 0.5 : 0;131}132133const likeEscape = (s: string) => s.replace(/[\\%_]/g, (c) => `\\${c}`);134135function searchActions(q: string): SearchResult[] {136 const out: SearchResult[] = [];137 for (const a of ACTIONS) {138 // With no query the palette shows the navigation targets themselves (not the engines).139 const score = q === "" ? (a.id.startsWith("nav:") ? 0.3 : 0) : Math.max(matchScore(a.title, q), ...a.keywords.map((k) => matchScore(k, q) * 0.9));140 if (score > 0) out.push({ type: "action", id: a.id, title: a.title, subtitle: a.subtitle, score: Number((score * 0.8).toFixed(3)) });141 }142 return out;143}144145function searchConversationTitles(owner: string, raw: string, q: string, limit: number): SearchResult[] {146 if (!isSqlite) return [];147 try {148 // Titles only: message bodies hold whole reports, scanning them is not palette-fast.149 const rows = (pool as Database.Database)150 .prepare("SELECT session_id AS id, title, updated_at AS updatedAt FROM conversation_sessions WHERE owner = ? AND title LIKE ? ESCAPE '\\' ORDER BY updated_at DESC LIMIT ?")151 .all(owner, `%${likeEscape(raw)}%`, limit) as Array<{ id: string; title: string; updatedAt: number }>;152 return rows.map((r) => ({153 type: "conversation" as const,154 id: r.id,155 title: r.title,156 // conversation_sessions stores seconds157 subtitle: Number.isFinite(r.updatedAt) ? new Date(r.updatedAt * 1000).toISOString().slice(0, 10) : null,158 score: Number((Math.max(matchScore(r.title, q), 0.5) * 0.75).toFixed(3)),159 }));160 } catch {161 return []; // no conversation table yet (fresh database)162 }163}164165const OBJECT_FIELDS: Record<"project" | "note" | "watchlist" | "portfolio" | "chart", { title: string; extra: (d: Record<string, unknown>) => string[]; subtitle: (d: Record<string, unknown>) => string | null }> = {166 project: { title: "title", extra: (d) => [String(d.question ?? ""), String(d.summary ?? "")], subtitle: (d) => (typeof d.question === "string" && d.question ? d.question.slice(0, 120) : null) },167 note: { title: "title", extra: (d) => [String(d.body ?? "").slice(0, 20000)], subtitle: (d) => (typeof d.body === "string" && d.body ? d.body.replace(/\s+/g, " ").slice(0, 120) : null) },168 watchlist: { title: "name", extra: (d) => (Array.isArray(d.symbols) ? d.symbols.map(String) : []), subtitle: (d) => (Array.isArray(d.symbols) ? d.symbols.slice(0, 8).join(", ") : null) },169 portfolio: {170 title: "name",171 extra: (d) => (Array.isArray(d.positions) ? d.positions.map((p) => String((p as { symbol?: unknown })?.symbol ?? "")) : []),172 subtitle: (d) => (Array.isArray(d.positions) ? `${d.positions.length} position${d.positions.length === 1 ? "" : "s"}` : null),173 },174 chart: { title: "symbol", extra: (d) => (Array.isArray(d.compare) ? d.compare.map(String) : []), subtitle: (d) => (typeof d.interval === "string" ? d.interval : null) },175};176177function searchObjects(owner: string, kind: keyof typeof OBJECT_FIELDS, q: string): SearchResult[] {178 if (q === "") return [];179 const spec = OBJECT_FIELDS[kind];180 const out: SearchResult[] = [];181 for (const o of listObjects(owner, kind as Kind)) {182 const title = String(o.data[spec.title] ?? "");183 // A match in the title counts fully, a match inside the content half.184 const score = Math.max(matchScore(title, q), ...spec.extra(o.data).map((x) => matchScore(x, q) * 0.5));185 if (score > 0) out.push({ type: kind, id: o.id, title: title || o.id, subtitle: spec.subtitle(o.data), ...(kind === "chart" ? { symbol: title } : {}), score: Number((score * 0.9).toFixed(3)) });186 }187 return out;188}189190const ASSET_CLASS: Record<string, string> = { CRYPTO: "crypto", FOREX: "fx", COMMODITY: "commodity", INDEX: "index" };191192/** Symbols from the provider. Throws when the provider fails; the caller reports it. */193async function searchSymbols(raw: string, q: string, limit: number): Promise<SearchResult[]> {194 const upper = raw.toUpperCase();195 type Hit = { symbol: string; name: string; currency?: string; stockExchange?: string; exchangeShortName?: string; exchange?: string; exchangeFullName?: string };196 let hits: Hit[];197 if (ISIN_RE.test(upper)) {198 hits = ((await searchByISIN(upper)) as Hit[]) ?? [];199 } else {200 // Ticker search and name search answer different questions ("AAPL" vs "apple"): both, merged.201 const settled = await Promise.allSettled([searchCompanies(raw, limit), searchName(raw)]);202 if (settled.every((s) => s.status === "rejected")) throw (settled[0] as PromiseRejectedResult).reason;203 hits = settled.flatMap((s) => (s.status === "fulfilled" && Array.isArray(s.value) ? (s.value as Hit[]) : []));204 }205 const seen = new Set<string>();206 const out: SearchResult[] = [];207 for (const h of hits) {208 if (!h || typeof h.symbol !== "string" || seen.has(h.symbol)) continue;209 seen.add(h.symbol);210 const exchange = h.exchangeShortName || h.exchange || h.stockExchange || h.exchangeFullName || undefined;211 const isin = ISIN_RE.test(upper);212 // Ticker matches rank above name matches; an ISIN lookup is an exact answer.213 const score = isin ? 1 : Math.max(matchScore(h.symbol, q), matchScore(h.name, q) * 0.8, 0.3);214 out.push({215 type: "symbol",216 id: h.symbol,217 title: h.symbol,218 subtitle: [h.name, exchange, h.currency].filter(Boolean).join(" · ") || null,219 symbol: h.symbol,220 ...(exchange ? { exchange } : {}),221 // Only stated when the listing venue says it; an equity is not told apart from a fund by this endpoint.222 ...(exchange && ASSET_CLASS[exchange.toUpperCase()] ? { assetClass: ASSET_CLASS[exchange.toUpperCase()] } : {}),223 score: Number(score.toFixed(3)),224 });225 }226 return out;227}228229/** Runs the search for one person. `unavailable` lists the types whose source could not answer in time. */230export async function search(owner: string, rawQuery: string, types: SearchType[], limit: number): Promise<{ results: SearchResult[]; unavailable: SearchType[] }> {231 const raw = rawQuery.trim().slice(0, 120);232 const q = fold(raw);233 const want = (t: SearchType) => types.includes(t);234 const perType = Math.max(5, Math.ceil(limit / 2));235 const unavailable: SearchType[] = [];236 const results: SearchResult[] = [];237238 // The provider call starts first and runs while the local sources are read.239 let symbols: Promise<SearchResult[]> | null = null;240 if (want("symbol") && raw.length >= 1 && /[\p{L}\p{N}]/u.test(raw)) {241 let timer: NodeJS.Timeout | undefined;242 symbols = Promise.race([243 searchSymbols(raw, q, perType),244 new Promise<never>((_resolve, reject) => {245 timer = setTimeout(() => reject(new Error("timeout")), SYMBOL_TIMEOUT_MS);246 }),247 ])248 .catch((e: Error) => {249 logger.warn(`[search] symbols unavailable: ${e.message === "timeout" ? `no answer in ${SYMBOL_TIMEOUT_MS} ms` : "provider error"}`);250 unavailable.push("symbol");251 return [] as SearchResult[];252 })253 .finally(() => clearTimeout(timer));254 }255256 if (want("action")) results.push(...searchActions(q));257 if (q !== "") {258 if (want("conversation")) results.push(...searchConversationTitles(owner, raw, q, perType));259 for (const kind of ["project", "note", "watchlist", "portfolio", "chart"] as const) {260 if (want(kind)) results.push(...searchObjects(owner, kind, q).sort((a, b) => b.score - a.score).slice(0, perType));261 }262 }263 if (symbols) results.push(...(await symbols).sort((a, b) => b.score - a.score).slice(0, perType));264265 results.sort((a, b) => b.score - a.score || SEARCH_TYPES.indexOf(a.type) - SEARCH_TYPES.indexOf(b.type) || a.title.localeCompare(b.title));266 return { results: results.slice(0, limit), unavailable };267}268269export function registerSearchRoutes(app: Express): void {270 app.get("/api/v2/search", async (req: Request, res: Response) => {271 const user = (req as Request & { vqUser?: { id: string } }).vqUser;272 if (!user) return res.status(401).json({ error: "Accès verrouillé" });273 const q = typeof req.query.q === "string" ? req.query.q : "";274 let types: SearchType[] = [...SEARCH_TYPES];275 if (typeof req.query.types === "string" && req.query.types.trim() !== "") {276 const asked = req.query.types.split(",").map((t) => t.trim()).filter(Boolean);277 const unknown = asked.find((t) => !(SEARCH_TYPES as readonly string[]).includes(t));278 if (unknown) return res.status(400).json({ error: `Unknown type: ${unknown.slice(0, 40)}` });279 types = asked as SearchType[];280 }281 const limitRaw = Number.parseInt(String(req.query.limit ?? "20"), 10);282 const limit = Math.min(50, Math.max(1, Number.isFinite(limitRaw) ? limitRaw : 20));283 try {284 const { results, unavailable } = await search(user.id, q, types, limit);285 res.set("Cache-Control", "private, no-store").json({ results, ...(unavailable.length > 0 ? { unavailable } : {}) });286 } catch (e) {287 logger.error(`[search] ${(e as Error).message}`);288 res.status(500).json({ error: "Search error" });289 }290 });291}292