SPB Git

Repository Public MIT

projects.ts 34.0 KB 573 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/projects.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 * Research projects (contract §5.1). A project is an object of kind `project`; this module adds what needs the47 * server: the bundle (each item resolved against what it points to), running an analysis inside a project, and48 * exports with a methodology and provenance appendix built from what is stored with each item.49 *50 *   GET  /api/v2/projects/:id/bundle51 *   POST /api/v2/projects/:id/run      { prompt, mode, model, budget } → { generationId, sessionId }52 *   POST /api/v2/projects/:id/export   { format: "pdf"|"md"|"tex"|"zip", include?: [item ids] } → { filename, url, … }53 *54 * For POST /api/chat (server/routes.ts): `resolveProjectId`, `projectContextFor`, `linkConversationToProject`.55 * A chat body may carry `projectId`; the conversation then reasons with the project's context and is filed in it.56 */57import type { Express, Request, Response } from "express";58import type Database from "better-sqlite3";59import { randomBytes, randomUUID } from "node:crypto";60import fs from "node:fs";61import path from "node:path";62import { z } from "zod";63import { internalAccessCookie } from "../access";64import { isSqlite, pool } from "../db";65import { runningInSession } from "../routes/generations";66import { logger } from "../utils/logger";67import { audit } from "./audit";68import { markdownToLatex, zipArchive } from "./exportFormats";69import { ID_RE, getObject, listObjects, sendObjectError, writeObject, type Envelope, type Kind } from "./objects";7071interface ProjectItem {72  id: string;73  type: string;74  ref: string;75  title?: string | null;76  addedAt?: number | null;77  [key: string]: unknown;78}79interface ProjectData {80  title: string;81  question?: string | null;82  hypotheses?: Array<{ id: string; text: string; status?: string | null }> | null;83  status?: string | null;84  dataSources?: Array<{ id: string; provider?: string | null; description?: string | null }> | null;85  items: ProjectItem[];86  summary?: string | null;87  [key: string]: unknown;88}89export interface Resolved {90  title: string;91  status: string | null;92  updatedAt: number | null;93  summary: string | null;94}9596const sqlite = (): Database.Database => {97  if (!isSqlite) throw new Error("VQuant Next needs the SQLite database");98  return pool as Database.Database;99};100const ownerId = (req: Request): string => {101  const user = (req as Request & { vqUser?: { id: string } }).vqUser;102  if (!user) throw new Error("Request reached a handler without passing the access gate");103  return user.id;104};105const clip = (s: unknown, n: number): string => {106  const t = String(s ?? "").replace(/\s+/g, " ").trim();107  return t.length > n ? `${t.slice(0, n - 1).trimEnd()}…` : t;108};109/** Runs a query on a table that may not exist yet (created lazily by its own module): no table, no row. */110function tryGet<T>(sql: string, ...args: unknown[]): T | undefined {111  try {112    return sqlite().prepare(sql).get(...args) as T | undefined;113  } catch {114    return undefined;115  }116}117118function project(owner: string, id: string): Envelope<ProjectData> | null {119  return ID_RE.test(id) ? getObject<ProjectData>(owner, "project", id) : null;120}121const itemsOf = (p: Envelope<ProjectData>): ProjectItem[] => (Array.isArray(p.data.items) ? p.data.items : []);122123// ─── Resolution of items ─────────────────────────────────────────────────────124const OBJECT_ITEMS: Record<string, Kind> = { note: "note", chart: "chart", portfolio: "portfolio", watchlist: "watchlist", review: "review" };125126/** What an item points to, for the owner only. null: it does not exist (any more), or it is not theirs. */127export function resolveItem(owner: string, item: ProjectItem): Resolved | null {128  const ref = String(item.ref ?? "");129  if (!ref) return null;130  if (item.type === "conversation") {131    const s = tryGet<{ title: string; updatedAt: number; n: number | null }>(132      "SELECT title, updated_at AS updatedAt, json_array_length(messages) AS n FROM conversation_sessions WHERE session_id = ? AND owner = ?",133      ref,134      owner,135    );136    const job = runningInSession(ref);137    const running = !!job && job.owner === owner;138    // A first question still being answered has no stored conversation yet.139    if (!s) return running ? { title: clip(job!.query, 120), status: "running", updatedAt: job!.startedAt, summary: null } : null;140    // conversation_sessions stores seconds141    return { title: s.title, status: running ? "running" : "done", updatedAt: s.updatedAt * 1000, summary: typeof s.n === "number" ? `${s.n} exchange${s.n === 1 ? "" : "s"}` : null };142  }143  if (item.type === "quant_job") {144    const j = tryGet<{ tool: string; status: string; startedAt: number; finishedAt: number | null; error: string | null; title: string | null; headline: string | null }>(145      "SELECT tool, status, started_at AS startedAt, finished_at AS finishedAt, error, json_extract(result, '$.title') AS title, json_extract(result, '$.headline') AS headline FROM vq_quant_jobs WHERE id = ? AND owner = ?",146      ref,147      owner,148    );149    if (!j) return null;150    return { title: j.title || j.tool, status: j.status, updatedAt: j.finishedAt ?? j.startedAt, summary: j.headline ? clip(j.headline, 300) : j.error ? clip(j.error, 300) : null };151  }152  if (item.type === "report") {153    // A shared report (POST /api/share): readable by its share id, as it already is through GET /api/share/:id.154    const r = tryGet<{ question: string; createdAt: number }>("SELECT question, created_at AS createdAt FROM shared_reports WHERE share_id = ?", ref);155    return r ? { title: clip(r.question, 160), status: "shared", updatedAt: r.createdAt * 1000, summary: null } : null;156  }157  const kind = OBJECT_ITEMS[item.type];158  if (kind && ID_RE.test(ref)) {159    const o = getObject(owner, kind, ref);160    if (!o) return null;161    const d = o.data as Record<string, unknown>;162    const positions = Array.isArray(d.positions) ? d.positions.length : 0;163    const symbols = Array.isArray(d.symbols) ? d.symbols : [];164    switch (kind) {165      case "note":166        return { title: String(d.title ?? "Note"), status: null, updatedAt: o.updatedAt, summary: clip(d.body, 240) || null };167      case "chart":168        return { title: String(d.symbol ?? "Chart"), status: null, updatedAt: o.updatedAt, summary: [d.interval, d.chartType].filter((x) => typeof x === "string").join(" · ") || null };169      case "portfolio":170        return { title: String(d.name ?? "Portfolio"), status: null, updatedAt: o.updatedAt, summary: `${positions} position${positions === 1 ? "" : "s"}` };171      case "watchlist":172        return { title: String(d.name ?? "Watchlist"), status: null, updatedAt: o.updatedAt, summary: clip(symbols.join(", "), 240) || null };173      default:174        return { title: "Automated review", status: typeof d.status === "string" ? d.status : null, updatedAt: o.updatedAt, summary: typeof d.verdict === "string" ? clip(d.verdict, 300) : null };175    }176  }177  // notebook, dataset: no server-side store behind these item types yet.178  return null;179}180181// ─── Hooks for POST /api/chat ────────────────────────────────────────────────182/**183 * The project a chat request belongs to: the `projectId` it carries when that project is the person's, otherwise184 * the project that already lists this conversation (a follow-up question sent by a client that does not know185 * about projects stays in its project). null: an ordinary conversation.186 */187export function resolveProjectId(owner: string, projectId: string | null | undefined, sessionId?: string | null): string | null {188  try {189    if (projectId) return project(owner, projectId) ? projectId : null;190    if (!sessionId) return null;191    return listObjects<ProjectData>(owner, "project").find((p) => itemsOf(p).some((i) => i.type === "conversation" && i.ref === sessionId))?.id ?? null;192  } catch {193    return null;194  }195}196197/** System-prompt context of a conversation held inside a project; null when the project is not the person's. */198export function projectContextFor(owner: string, projectId: string | null | undefined): string | null {199  if (!projectId) return null;200  try {201    const p = project(owner, projectId);202    if (!p) return null;203    const d = p.data;204    const lines: string[] = [`RESEARCH PROJECT — this conversation is part of the person's research project "${clip(d.title, 200)}"${d.status ? ` (status: ${d.status})` : ""}.`];205    if (d.question) lines.push(`Research question: ${clip(d.question, 1500)}`);206    const hyp = (d.hypotheses ?? []).filter((h) => h && h.text);207    if (hyp.length > 0) lines.push("Hypotheses:\n" + hyp.slice(0, 30).map((h) => `- [${h.status ?? "open"}] ${clip(h.text, 400)}`).join("\n"));208    const src = (d.dataSources ?? []).filter((s) => s && (s.provider || s.description));209    if (src.length > 0) lines.push("Data sources the project relies on:\n" + src.slice(0, 30).map((s) => `- ${[s.provider, s.description].filter(Boolean).map((x) => clip(x, 300)).join(": ")}`).join("\n"));210    const items = itemsOf(p);211    // Notes filed in the project, and notes that name it as their project.212    const noteTitles = new Set<string>();213    for (const i of items) if (i.type === "note") noteTitles.add(clip(resolveItem(owner, i)?.title ?? i.title ?? "", 120));214    for (const n of listObjects<{ title?: string; projectId?: string | null }>(owner, "note")) if (n.data.projectId === projectId) noteTitles.add(clip(n.data.title, 120));215    noteTitles.delete("");216    if (noteTitles.size > 0) lines.push("Notes in the project (titles only):\n" + [...noteTitles].slice(0, 40).map((t) => `- ${t}`).join("\n"));217    const others = items.filter((i) => i.type !== "note");218    if (others.length > 0) {219      const counts = new Map<string, number>();220      for (const i of others) counts.set(i.type, (counts.get(i.type) ?? 0) + 1);221      lines.push(`Other material already in the project: ${[...counts.entries()].map(([t, n]) => `${n} ${t.replace("_", " ")}${n === 1 ? "" : "s"}`).join(", ")}.`);222    }223    if (d.summary) lines.push(`Summary so far: ${clip(d.summary, 3000)}`);224    lines.push("Work toward the project's question. When a finding bears on one of the hypotheses, say which one and whether it supports or weakens it; do not present a hypothesis as settled unless the evidence in this conversation shows it.");225    return lines.join("\n");226  } catch (e) {227    logger.warn(`[projects] context unavailable: ${(e as Error).message}`);228    return null;229  }230}231232/** Files a conversation in a project (once). Called when the run starts and again when its answer is saved. */233export function linkConversationToProject(owner: string, projectId: string | null | undefined, sessionId: string, title?: string): void {234  if (!projectId || !ID_RE.test(projectId)) return;235  try {236    writeObject<ProjectData>(owner, "project", projectId, (current) => {237      if (!current) return null;238      const items = Array.isArray(current.items) ? current.items : [];239      if (items.some((i) => i.type === "conversation" && i.ref === sessionId)) return null;240      return { ...current, items: [...items, { id: randomUUID(), type: "conversation", ref: sessionId, title: clip(title ?? "", 120) || null, addedAt: Date.now() }] };241    });242  } catch (e) {243    logger.warn(`[projects] conversation ${sessionId} not filed in project ${projectId}: ${(e as Error).message}`);244  }245}246247// ─── Export ──────────────────────────────────────────────────────────────────248interface StoredMessage {249  question?: string;250  answer?: string;251  sources?: Array<{ url?: string; title?: string } | string>;252  provenance?: { sources?: Array<{ tool?: string; provider?: string; symbols?: string[]; retrievedAt?: number | string; ok?: boolean }> } | Array<{ tool?: string; provider?: string; symbols?: string[]; retrievedAt?: number | string; ok?: boolean }>;253}254interface LabResult {255  schema?: string;256  engine?: string;257  engineVersion?: string;258  title?: string;259  headline?: string;260  summary?: Array<{ label?: string; value?: unknown; unit?: string | null; kind?: string; note?: string }>;261  tables?: Array<{ title?: string; columns?: Array<{ key: string; label?: string }>; rows?: Array<Record<string, unknown>>; note?: string }>;262  diagnostics?: Array<{ name?: string; statistic?: unknown; pvalue?: unknown; conclusion?: string }>;263  assumptions?: string[];264  warnings?: string[];265  methodology?: string;266  provenance?: { data?: Array<Record<string, unknown>>; spec?: unknown; seed?: unknown; software?: Record<string, unknown>; computedAt?: string; durationMs?: number; reproduce?: string };267}268269const mdCell = (v: unknown): string => {270  if (v === null || v === undefined) return "";271  const s = typeof v === "number" ? (Number.isInteger(v) ? String(v) : String(Number(v.toPrecision(8)))) : typeof v === "object" ? JSON.stringify(v) : String(v);272  return s.replace(/\|/g, "\\|").replace(/\s*\n\s*/g, " ");273};274const mdTable = (head: string[], rows: unknown[][]): string => [`| ${head.join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...rows.map((r) => `| ${r.map(mdCell).join(" | ")} |`)].join("\n");275/** Pushes the headings of an embedded document below the section that carries it. */276const demote = (md: string, by: number): string =>277  md278    .split("\n")279    .map((l) => l.replace(/^(#{1,6})(\s+)/, (_m, h: string, sp: string) => `${"#".repeat(Math.min(6, h.length + by))}${sp}`))280    .join("\n");281const iso = (ms: number | null | undefined) => (typeof ms === "number" && Number.isFinite(ms) ? new Date(ms).toISOString() : "unknown date");282const jsonBlock = (v: unknown, max = 4000) => {283  const s = JSON.stringify(v, null, 2) ?? "null";284  return "```json\n" + (s.length > max ? `${s.slice(0, max)}\n… (truncated; the complete value is in the ZIP export)` : s) + "\n```";285};286287export interface ProjectExport {288  title: string;289  markdown: string;290  /** raw material for the ZIP: one JSON per item that could be read */291  attachments: Array<{ name: string; data: string }>;292  itemCount: number;293}294295/** The project as one Markdown document: the project itself, each item's content, then methodology and provenance. */296export function buildProjectExport(owner: string, p: Envelope<ProjectData>, include?: string[] | null): ProjectExport {297  const d = p.data;298  const all = itemsOf(p);299  const items = include && include.length > 0 ? all.filter((i) => include.includes(i.id)) : all;300  const body: string[] = [];301  const methodology: string[] = [];302  const provenance: string[] = [];303  const attachments: ProjectExport["attachments"] = [{ name: "project.json", data: JSON.stringify(p, null, 2) }];304305  body.push(`# ${d.title}`, "");306  if (d.question) body.push(`**Research question.** ${d.question}`, "");307  if (d.status) body.push(`**Status.** ${d.status}`, "");308  const hyp = (d.hypotheses ?? []).filter((h) => h && h.text);309  if (hyp.length > 0) body.push("## Hypotheses", "", mdTable(["#", "Hypothesis", "Status"], hyp.map((h, i) => [`H${i + 1}`, h.text, h.status ?? "open"])), "");310  const src = (d.dataSources ?? []).filter((s) => s && (s.provider || s.description));311  if (src.length > 0) body.push("## Data sources", "", ...src.map((s) => `- ${[s.provider ? `**${s.provider}**` : null, s.description].filter(Boolean).join(": ")}`), "");312  if (d.summary) body.push("## Summary", "", d.summary, "");313314  let n = 0;315  for (const item of items) {316    n++;317    const label = `${n}. ${clip(item.title || resolveItem(owner, item)?.title || item.ref, 160)}`;318    if (item.type === "conversation") {319      const s = tryGet<{ title: string; messages: string; updatedAt: number }>("SELECT title, messages, updated_at AS updatedAt FROM conversation_sessions WHERE session_id = ? AND owner = ?", item.ref, owner);320      if (!s) {321        body.push(`## ${label}`, "", "_This conversation is no longer available._", "");322        continue;323      }324      let messages: StoredMessage[] = [];325      try {326        messages = JSON.parse(s.messages);327      } catch {328        /* unreadable history: exported as empty */329      }330      body.push(`## ${n}. ${s.title}`, "", `_Conversation, last updated ${iso(s.updatedAt * 1000)}._`, "");331      const prov: string[] = [];332      messages.forEach((m, k) => {333        body.push(`### Question ${k + 1}`, "", String(m.question ?? ""), "", demote(String(m.answer ?? ""), 3), "");334        const recorded = Array.isArray(m.provenance) ? m.provenance : m.provenance?.sources;335        if (Array.isArray(recorded) && recorded.length > 0) {336          prov.push(`Question ${k + 1} — data retrieved by the tools that ran:`, "", mdTable(["Tool", "Provider", "Symbols", "Retrieved at", "OK"], recorded.map((r) => [r.tool, r.provider, (r.symbols ?? []).join(", "), typeof r.retrievedAt === "number" ? iso(r.retrievedAt) : r.retrievedAt, r.ok === false ? "no" : "yes"])), "");337        } else {338          prov.push(`Question ${k + 1} — no provenance record is stored with this answer (it predates provenance recording); none is reconstructed here.`, "");339        }340        const cited = (m.sources ?? []).map((x) => (typeof x === "string" ? x : x?.url)).filter((u): u is string => typeof u === "string" && /^https?:/.test(u));341        if (cited.length > 0) prov.push(`Question ${k + 1} — web sources stored with the answer:`, "", ...cited.slice(0, 60).map((u) => `- <${u}>`), "");342      });343      provenance.push(`### ${n}. ${s.title}`, "", ...prov);344      attachments.push({ name: `items/${String(n).padStart(2, "0")}-conversation.json`, data: JSON.stringify({ sessionId: item.ref, title: s.title, updatedAt: s.updatedAt * 1000, messages: messages.map((m) => ({ question: m.question, answer: m.answer, sources: m.sources, provenance: m.provenance })) }, null, 2) });345      continue;346    }347    if (item.type === "quant_job") {348      const j = tryGet<{ tool: string; params: string; status: string; started_at: number; finished_at: number | null; result: string | null; code: string | null; error: string | null }>("SELECT tool, params, status, started_at, finished_at, result, code, error FROM vq_quant_jobs WHERE id = ? AND owner = ?", item.ref, owner);349      if (!j) {350        body.push(`## ${label}`, "", "_This computation is no longer available._", "");351        continue;352      }353      let params: unknown = {};354      let result: LabResult | null = null;355      try {356        params = JSON.parse(j.params);357        result = j.result ? (JSON.parse(j.result) as LabResult) : null;358      } catch {359        /* unreadable job: exported with what parsed */360      }361      const title = result?.title || j.tool;362      body.push(`## ${n}. ${title}`, "", `_Quant computation \`${j.tool}\`, ${j.status}, ${iso(j.finished_at ?? j.started_at)}._`, "");363      if (j.error) body.push(`**Error.** ${j.error}`, "");364      if (result?.schema === "lab/1") {365        if (result.headline) body.push(result.headline, "");366        if (result.summary?.length) body.push(mdTable(["Measure", "Value", "Unit", "Nature"], result.summary.map((x) => [x.label, x.value, x.unit ?? "", x.kind ?? ""])), "");367        for (const t of result.tables ?? []) {368          const cols = t.columns ?? [];369          if (cols.length === 0) continue;370          const rows = t.rows ?? [];371          body.push(`### ${t.title ?? "Table"}`, "", mdTable(cols.map((c) => c.label ?? c.key), rows.slice(0, 60).map((r) => cols.map((c) => r[c.key]))), "");372          if (rows.length > 60) body.push(`_${rows.length - 60} more rows are in the ZIP export._`, "");373          if (t.note) body.push(`_${t.note}_`, "");374        }375        if (result.diagnostics?.length) body.push("### Diagnostics", "", mdTable(["Test", "Statistic", "p-value", "Conclusion"], result.diagnostics.map((x) => [x.name, x.statistic, x.pvalue ?? "", x.conclusion ?? ""])), "");376        if (result.warnings?.length) body.push("### Warnings", "", ...result.warnings.map((w) => `- ${w}`), "");377        const meth: string[] = [];378        if (result.methodology) meth.push(demote(result.methodology, 3), "");379        if (result.assumptions?.length) meth.push("Assumptions:", "", ...result.assumptions.map((a) => `- ${a}`), "");380        if (meth.length > 0) methodology.push(`### ${n}. ${title}`, "", ...meth);381      } else if (result) {382        body.push("Result as stored (legacy engine, no structured schema):", "", jsonBlock(result), "");383      }384      const pv = result?.provenance;385      const lines: string[] = [`Engine \`${result?.engine ?? j.tool}\`${result?.engineVersion ? ` version ${result.engineVersion}` : ""}; parameters as recorded with the job:`, "", jsonBlock(params, 2000), ""];386      if (pv?.data?.length) {387        const keys = ["symbol", "provider", "frequency", "start", "end", "observations", "adjusted", "currency", "retrievedAt", "fallbackFrom"].filter((k) => pv.data!.some((r) => r[k] !== undefined && r[k] !== null));388        lines.push("Data used:", "", mdTable(keys, pv.data.map((r) => keys.map((k) => r[k]))), "");389      }390      if (pv) {391        const facts = [pv.computedAt ? `computed at ${pv.computedAt}` : null, typeof pv.durationMs === "number" ? `duration ${pv.durationMs} ms` : null, pv.seed !== undefined && pv.seed !== null ? `random seed ${String(pv.seed)}` : null].filter(Boolean);392        if (facts.length > 0) lines.push(`${facts.join("; ")}.`, "");393        if (pv.software && Object.keys(pv.software).length > 0) lines.push(`Software: ${Object.entries(pv.software).map(([k, v]) => `${k} ${String(v)}`).join(", ")}.`, "");394        if (pv.reproduce) lines.push("To reproduce:", "", "```python", pv.reproduce, "```", "");395      } else {396        lines.push(`No provenance record is stored with this computation${j.code ? "; the code that ran is in the ZIP export" : ""}.`, "");397      }398      provenance.push(`### ${n}. ${title}`, "", ...lines);399      attachments.push({ name: `items/${String(n).padStart(2, "0")}-quant-job.json`, data: JSON.stringify({ id: item.ref, tool: j.tool, params, status: j.status, startedAt: j.started_at, finishedAt: j.finished_at, error: j.error, result }, null, 2) });400      if (j.code) attachments.push({ name: `items/${String(n).padStart(2, "0")}-quant-job-code.py`, data: j.code });401      continue;402    }403    const kind = OBJECT_ITEMS[item.type];404    const o = kind && ID_RE.test(item.ref) ? getObject(owner, kind, item.ref) : null;405    if (!o) {406      const r = resolveItem(owner, item);407      // notebook, dataset: nothing is stored on the server for these, which is not the same as "deleted".408      const missing = kind || item.type === "report" ? `_This ${item.type.replace("_", " ")} is no longer available._` : `_${item.type} \`${item.ref}\`: not stored on the server, so not part of this export._`;409      body.push(`## ${label}`, "", r ? `_${item.type.replace("_", " ")}: ${r.title}. Its content is not part of this export._` : missing, "");410      continue;411    }412    const od = o.data as Record<string, unknown>;413    attachments.push({ name: `items/${String(n).padStart(2, "0")}-${item.type}.json`, data: JSON.stringify(o, null, 2) });414    if (kind === "note") {415      body.push(`## ${n}. ${String(od.title ?? "Note")}`, "", `_Note, last edited ${iso(o.updatedAt)}._`, "", demote(String(od.body ?? ""), 2), "");416    } else if (kind === "watchlist") {417      body.push(`## ${n}. ${String(od.name ?? "Watchlist")}`, "", `_Watchlist._ ${(Array.isArray(od.symbols) ? od.symbols : []).join(", ")}`, "");418    } else if (kind === "portfolio") {419      const positions = (Array.isArray(od.positions) ? od.positions : []) as Array<Record<string, unknown>>;420      body.push(`## ${n}. ${String(od.name ?? "Portfolio")}`, "", `_Portfolio as recorded on ${iso(o.updatedAt)} (base currency ${String(od.baseCurrency ?? "USD")}). Quantities and cost bases are the person's own entries; no market value is computed here._`, "");421      if (positions.length > 0) body.push(mdTable(["Symbol", "Quantity", "Cost basis", "Currency", "Note"], positions.map((x) => [x.symbol, x.quantity, x.costBasis ?? "", x.currency ?? "", x.note ?? ""])), "");422    } else if (kind === "chart") {423      const ind = (Array.isArray(od.indicators) ? od.indicators : []) as Array<Record<string, unknown>>;424      body.push(`## ${n}. Chart — ${String(od.symbol ?? "")}`, "", `_Saved chart configuration (interval ${String(od.interval ?? "1d")}${ind.length ? `; indicators: ${ind.map((x) => String(x.type)).join(", ")}` : ""}). The image is not part of this export._`, "");425    } else {426      const checks = (Array.isArray(od.checks) ? od.checks : []) as Array<Record<string, unknown>>;427      body.push(`## ${n}. Automated review`, "", "_Automated review — not a human peer review._", "", typeof od.verdict === "string" ? od.verdict : "", "");428      if (checks.length > 0) body.push(mdTable(["Category", "Severity", "Finding", "Evidence"], checks.map((c) => [c.category, c.severity, c.finding, c.evidence])), "");429    }430  }431432  body.push("## Appendix A — Methodology", "");433  body.push(...(methodology.length > 0 ? methodology : ["No item of this export carries a stored methodology.", ""]));434  body.push("## Appendix B — Provenance", "");435  body.push("This appendix reproduces what was recorded when each item was produced. Nothing in it was reconstructed afterwards: where no record exists, it says so.", "");436  body.push(...(provenance.length > 0 ? provenance : ["No item of this export carries a stored provenance record.", ""]));437  body.push(`_Exported from VQuant on ${new Date().toISOString()} — project \`${p.id}\`, revision ${p.rev}, ${items.length} of ${all.length} item${all.length === 1 ? "" : "s"}._`, "");438439  return { title: d.title, markdown: body.join("\n").replace(/\n{3,}/g, "\n\n"), attachments, itemCount: items.length };440}441442/** Where GET /api/download/:filename reads from (server/routes/reports.ts). */443const downloadsDir = () => path.resolve("downloads");444const EXPORT_FILE_RE = /^vquant-[a-z0-9-]+-[0-9a-f]{36}\.(md|tex|zip|pdf)$/;445const EXPORT_KEPT_MS = 7 * 86_400_000;446/** Export files are download links, not an archive: those older than a week are removed (only files this module wrote). */447export function sweepExports(now = Date.now()): number {448  let removed = 0;449  try {450    for (const name of fs.readdirSync(downloadsDir())) {451      if (!EXPORT_FILE_RE.test(name)) continue;452      const file = path.join(downloadsDir(), name);453      if (now - fs.statSync(file).mtimeMs > EXPORT_KEPT_MS) {454        fs.rmSync(file, { force: true });455        removed++;456      }457    }458  } catch {459    /* no downloads directory yet */460  }461  return removed;462}463const slug = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).toLowerCase() || "project";464465export function registerProjectRoutes(app: Express): void {466  app.get("/api/v2/projects/:id/bundle", (req: Request, res: Response) => {467    try {468      const owner = ownerId(req);469      const p = project(owner, req.params.id);470      if (!p) return res.status(404).json({ error: "Project not found" });471      res.set("Cache-Control", "private, no-store").json({ project: p, items: itemsOf(p).map((item) => ({ ...item, resolved: resolveItem(owner, item) })) });472    } catch (e) {473      sendObjectError(res, e, "project bundle");474    }475  });476477  // A thin wrapper over POST /api/chat: the same pipeline, started on the loopback interface as the scheduled478  // watches do, with `projectId` in the body. It answers as soon as the job exists; the analysis runs on.479  app.post("/api/v2/projects/:id/run", async (req: Request, res: Response) => {480    const body = z481      .object({ prompt: z.string().trim().min(1).max(10000), mode: z.enum(["fast", "standard", "deep", "ultra", "research"]).optional(), model: z.string().max(200).optional(), budget: z.object({ maxCostUsd: z.number().positive().max(1000).optional(), maxMinutes: z.number().positive().max(240).optional() }).optional() })482      .safeParse(req.body);483    if (!body.success) return res.status(400).json({ error: "Body must be { prompt, mode?, model?, budget? }" });484    const owner = ownerId(req);485    const p = project(owner, req.params.id);486    if (!p) return res.status(404).json({ error: "Project not found" });487488    const sessionId = randomUUID();489    const controller = new AbortController();490    const timeout = setTimeout(() => controller.abort(), 20_000);491    try {492      const chat = await fetch(`http://127.0.0.1:${parseInt(process.env.PORT || "5000", 10)}/api/chat`, {493        method: "POST",494        headers: { "Content-Type": "application/json", Cookie: internalAccessCookie(owner) },495        body: JSON.stringify({ query: body.data.prompt, mode: body.data.mode, model: body.data.model, budget: body.data.budget, sessionId, projectId: p.id }),496        signal: controller.signal,497      });498      if (!chat.ok || !chat.body) {499        // The chat endpoint's own refusal (too many analyses running, invalid body) is passed on as it is.500        const refused = (await chat.json().catch(() => null)) as { error?: string } | null;501        return res.status(chat.status >= 400 ? chat.status : 502).json({ error: refused?.error ?? "The analysis could not be started." });502      }503      // The first event of the stream names the job; nothing else is needed from this connection.504      const reader = chat.body.getReader();505      const decoder = new TextDecoder();506      let buffer = "";507      let generationId: string | null = null;508      while (generationId === null) {509        const { value, done } = await reader.read();510        if (done) break;511        buffer += decoder.decode(value, { stream: true });512        const m = /^data: (\{"type":"job".*\})$/m.exec(buffer);513        if (m) generationId = String((JSON.parse(m[1]) as { id?: string }).id ?? "") || null;514        else if (buffer.length > 65536) break;515      }516      // Leaving the stream does not stop the job: this connection was only its first viewer.517      controller.abort();518      if (!generationId) return res.status(502).json({ error: "The analysis could not be started." });519      linkConversationToProject(owner, p.id, sessionId, body.data.prompt);520      res.status(202).json({ generationId, sessionId });521    } catch (e) {522      logger.error(`[projects] run: ${(e as Error).message}`);523      if (!res.headersSent) res.status(502).json({ error: "The analysis could not be started." });524    } finally {525      clearTimeout(timeout);526    }527  });528529  app.post("/api/v2/projects/:id/export", async (req: Request, res: Response) => {530    const body = z.object({ format: z.enum(["pdf", "md", "tex", "zip"]), include: z.array(z.string().max(64)).max(1000).nullish() }).safeParse(req.body);531    if (!body.success) return res.status(400).json({ error: 'Body must be { format: "pdf" | "md" | "tex" | "zip", include?: [item ids] }' });532    const { format, include } = body.data;533    try {534      const owner = ownerId(req);535      const p = project(owner, req.params.id);536      if (!p) return res.status(404).json({ error: "Project not found" });537      const exp = buildProjectExport(owner, p, include);538      const date = new Date().toISOString().slice(0, 10);539540      let data: Buffer;541      if (format === "md") data = Buffer.from(exp.markdown, "utf8");542      else if (format === "tex") data = Buffer.from(markdownToLatex(exp.markdown.replace(/^# .*\n/, ""), { title: exp.title, author: "VQuant", date }), "utf8");543      else if (format === "zip") {544        data = zipArchive([545          { name: "report.md", data: exp.markdown },546          { name: "report.tex", data: markdownToLatex(exp.markdown.replace(/^# .*\n/, ""), { title: exp.title, author: "VQuant", date }) },547          ...exp.attachments,548        ]);549      } else {550        try {551          // The house research-note layout (services/pdfReport.ts), rendered by Chromium.552          const { generatePDFFromMarkdown } = await import("../services/pdfService");553          const pdf = await generatePDFFromMarkdown({ question: exp.title, answer: exp.markdown });554          data = Buffer.isBuffer(pdf) ? pdf : Buffer.from(pdf);555        } catch (e) {556          logger.error(`[projects] pdf export: ${(e as Error).message}`);557          return res.status(502).json({ error: "The PDF renderer is not available right now. The Markdown, LaTeX and ZIP exports do not depend on it." });558        }559      }560561      // The download route checks no owner: the name itself is the capability (144 random bits).562      const filename = `vquant-${slug(exp.title)}-${randomBytes(18).toString("hex")}.${format}`;563      fs.mkdirSync(downloadsDir(), { recursive: true });564      sweepExports();565      fs.writeFileSync(path.join(downloadsDir(), filename), data, { mode: 0o600 });566      audit(req, "project.export", `project/${p.id}`, { format, items: exp.itemCount, bytes: data.length });567      res.json({ filename, url: `/api/download/${filename}`, format, bytes: data.length, items: exp.itemCount, ...(format === "tex" || format === "zip" ? { compiled: false } : {}) });568    } catch (e) {569      sendObjectError(res, e, "project export");570    }571  });572}573
Files main
Menu

Theme