SPB Git

Repository Public MIT

memory.ts 7.5 KB 178 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/memory.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 * Memory management (contract §6): what the agent remembers, grouped by scope, with the person's own controls.47 *48 *   GET    /api/v2/memory            memories grouped by scope + retention settings49 *   PUT    /api/v2/memory/settings   { enabled, retentionDays } → stored in preference/default (`memory`)50 *   DELETE /api/v2/memory?scope=     bulk deletion; `scope` is mandatory: all | user | project:<id>51 *   GET    /api/v2/memory/export     everything, as a JSON download52 *   (PATCH /api/workspace/memories/:id lives with the legacy memory routes, server/routes/workspace.ts)53 *54 * The data functions are in services/workspace.ts, next to the agent's memory tools they share a table with.55 * Expired memories are purged at boot and every six hours; they are filtered out of every read in between.56 */57import type { Express, Request, Response } from "express";58import { z } from "zod";59import { logger } from "../utils/logger";60import { WorkspaceError, deleteMemories, listMemories, memorySettings, purgeExpiredMemories, type Memory } from "../services/workspace";61import { audit } from "./audit";62import { getObject, sendObjectError, writeObject } from "./objects";6364const PURGE_EVERY_MS = 6 * 3_600_000;65const SCOPE_RE = /^(all|user|project:[A-Za-z0-9_-]{1,64})$/;6667const ownerId = (req: Request): string => {68  const user = (req as Request & { vqUser?: { id: string } }).vqUser;69  if (!user) throw new Error("Request reached a handler without passing the access gate");70  return user.id;71};7273interface MemoryGroup {74  scope: string;75  /** null for the "user" scope; for a project scope its id and, when the project still exists, its title */76  project: { id: string; title: string | null } | null;77  memories: Memory[];78}7980/** Memories grouped by scope: the person's own first, then one group per project. */81export function groupedMemories(owner: string): MemoryGroup[] {82  const groups = new Map<string, Memory[]>([["user", []]]);83  for (const m of listMemories(owner)) {84    const list = groups.get(m.scope) ?? [];85    list.push(m);86    groups.set(m.scope, list);87  }88  return [...groups.entries()].map(([scope, memories]) => {89    if (scope === "user") return { scope, project: null, memories };90    const id = scope.slice("project:".length);91    const title = getObject<{ title?: string }>(owner, "project", id)?.data.title;92    return { scope, project: { id, title: typeof title === "string" ? title : null }, memories };93  });94}9596let purgeTimer: NodeJS.Timeout | null = null;97function schedulePurge(): void {98  const run = () => {99    try {100      const n = purgeExpiredMemories();101      if (n > 0) logger.info(`[memory] ${n} expired memor${n === 1 ? "y" : "ies"} purged`);102    } catch (e) {103      logger.warn(`[memory] purge failed: ${(e as Error).message}`);104    }105  };106  run();107  if (purgeTimer) clearInterval(purgeTimer);108  purgeTimer = setInterval(run, PURGE_EVERY_MS);109  purgeTimer.unref();110}111112export function registerMemoryRoutes(app: Express): void {113  schedulePurge();114115  const fail = (res: Response, e: unknown, what: string) => {116    if (e instanceof WorkspaceError) return res.status(400).json({ error: e.message });117    sendObjectError(res, e, `memory ${what}`);118  };119120  app.get("/api/v2/memory", (req: Request, res: Response) => {121    try {122      const owner = ownerId(req);123      const groups = groupedMemories(owner);124      res.set("Cache-Control", "private, no-store").json({ settings: memorySettings(owner), groups, count: groups.reduce((n, g) => n + g.memories.length, 0) });125    } catch (e) {126      fail(res, e, "list");127    }128  });129130  app.put("/api/v2/memory/settings", (req: Request, res: Response) => {131    const body = z.object({ enabled: z.boolean().optional(), retentionDays: z.number().int().min(1).max(3650).nullable().optional() }).strict().safeParse(req.body);132    if (!body.success) return res.status(400).json({ error: "Body must be { enabled?: boolean, retentionDays?: integer 1–3650 | null }" });133    if (body.data.enabled === undefined && body.data.retentionDays === undefined) return res.status(400).json({ error: "Nothing to update" });134    try {135      const owner = ownerId(req);136      writeObject(owner, "preference", "default", (current) => {137        const memory: Record<string, unknown> = { ...((current?.memory as Record<string, unknown> | null | undefined) ?? {}) };138        if (body.data.enabled !== undefined) memory.enabled = body.data.enabled;139        if (body.data.retentionDays === null) delete memory.retentionDays;140        else if (body.data.retentionDays !== undefined) memory.retentionDays = body.data.retentionDays;141        return { ...(current ?? {}), memory };142      });143      // A shorter retention takes effect now, not at the next daily purge.144      purgeExpiredMemories();145      res.json({ settings: memorySettings(owner) });146    } catch (e) {147      fail(res, e, "settings");148    }149  });150151  app.delete("/api/v2/memory", (req: Request, res: Response) => {152    const scope = typeof req.query.scope === "string" ? req.query.scope : "";153    // Nothing is deleted in bulk by default: the scope has to be spelled out.154    if (!SCOPE_RE.test(scope)) return res.status(400).json({ error: 'scope is required: "all", "user" or "project:<id>"' });155    try {156      const deleted = deleteMemories(ownerId(req), scope);157      audit(req, "memory.bulk_delete", scope, { deleted });158      res.json({ deleted });159    } catch (e) {160      fail(res, e, "bulk delete");161    }162  });163164  app.get("/api/v2/memory/export", (req: Request, res: Response) => {165    try {166      const owner = ownerId(req);167      const memories = listMemories(owner);168      audit(req, "memory.export", null, { count: memories.length });169      res170        .set("Cache-Control", "private, no-store")171        .set("Content-Disposition", `attachment; filename="vquant-memory-${new Date().toISOString().slice(0, 10)}.json"`)172        .json({ exportedAt: Date.now(), settings: memorySettings(owner), memories });173    } catch (e) {174      fail(res, e, "export");175    }176  });177}178
Files main
Menu

Theme