SPB Git

Repository Public MIT

workspace.test.ts 30.4 KB 470 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/workspace.test.ts10 * Module           : server11 * Repository       : https://git.spboucher.ai/vquant12 * Project Website  : https://vquant.spboucher.ai13 * Created          : 2026-11-2014 * Last Modified    : 2026-11-2015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development      : dev@spboucher.ai25 * Support          : support@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier  : MIT35 * License          : MIT License36 * License File     : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Legacy portfolio bridge (contract §1.4), memory (§6), audit (§7) and /api/config, through HTTP on an in-process48 * app with a temporary database. The legacy routes are the real ones (server/routes/workspace.ts).49 */50import { afterAll, beforeAll, describe, expect, it } from "vitest";51import { bootTestApp, type TestApp } from "./testkit";5253let t: TestApp;54let ws: typeof import("../services/workspace");55let objects: typeof import("./objects");56let auditMod: typeof import("./audit");5758const DAY = 86_400_000;59const legacyRows = (owner: string) => t.db.prepare("SELECT symbol, quantity, cost_basis, note FROM portfolio_positions WHERE owner = ? ORDER BY symbol").all(owner);60const seedLegacy = (owner: string, rows: Array<[string, number, number | null, string | null]>) => {61  for (const [symbol, quantity, cost, note] of rows) t.db.prepare("INSERT INTO portfolio_positions (owner, symbol, quantity, cost_basis, note, updated_at) VALUES (?, ?, ?, ?, ?, ?)").run(owner, symbol, quantity, cost, note, 1_700_000_000_000);62};6364beforeAll(async () => {65  t = await bootTestApp();66  ws = await import("../services/workspace");67  objects = await import("./objects");68  auditMod = await import("./audit");69  // Creates the legacy tables (they are created on first use), for a person no test looks at.70  ws.listPositions("frank");71  ws.listMemories("frank");72});73afterAll(async () => {74  await t.close();75});7677describe("/api/config", () => {78  it("answers exactly { version, defaultModel, models, modes, maxRunning }", async () => {79    const r = await t.api("alice", "GET", "/api/config");80    expect(r.status).toBe(200);81    expect(Object.keys(r.body).sort()).toEqual(["defaultModel", "maxRunning", "models", "modes", "version"]);82    expect(typeof r.body.version).toBe("string");83    expect(r.body.models).toContain(r.body.defaultModel);84    expect(r.body.models.every((m: unknown) => typeof m === "string")).toBe(true);85    expect(r.body.modes).toEqual(["fast", "standard", "deep", "ultra"]);86    expect(r.body.maxRunning).toBeGreaterThan(0);87    expect((await t.api(null, "GET", "/api/config")).status).toBe(401);88  });89});9091describe("legacy portfolio bridge", () => {92  it("copies legacy positions into portfolio/main at the first access, and leaves the legacy table alone", async () => {93    seedLegacy("alice", [["MSFT", 5, 310.5, "core"], ["AAPL", 10, 150, null], ["BRK.B", 2, null, null]]);94    const before = legacyRows("alice");95    const r = await t.api("alice", "GET", "/api/workspace");96    expect(r.status).toBe(200);97    // the 1.0.x response shape, field for field98    expect(Object.keys(r.body).sort()).toEqual(["memories", "positions", "recall", "user", "watches"]);99    expect(r.body.user).toEqual({ id: "alice", name: "Alice" });100    expect(r.body.positions).toEqual([101      { symbol: "AAPL", quantity: 10, costBasis: 150, note: null, updatedAt: 1_700_000_000_000 },102      { symbol: "BRK.B", quantity: 2, costBasis: null, note: null, updatedAt: 1_700_000_000_000 },103      { symbol: "MSFT", quantity: 5, costBasis: 310.5, note: "core", updatedAt: 1_700_000_000_000 },104    ]);105    const main = await t.api("alice", "GET", "/api/v2/objects/portfolio/main");106    expect(main.status).toBe(200);107    expect(main.body.object).toMatchObject({ rev: 1, device: "server", data: { baseCurrency: "USD" } });108    expect(main.body.object.data.positions.map((p: any) => p.symbol)).toEqual(["AAPL", "BRK.B", "MSFT"]);109    expect(legacyRows("alice")).toEqual(before);110  });111112  it("copies once: later reads do not write again", async () => {113    await t.api("alice", "GET", "/api/workspace");114    ws.listPositions("alice");115    expect((await t.api("alice", "GET", "/api/v2/objects/portfolio/main")).body.object.rev).toBe(1);116  });117118  it("PUT /api/workspace/portfolio/:symbol keeps its response shape and writes the object, not the legacy table", async () => {119    const before = legacyRows("alice");120    const r = await t.api("alice", "PUT", "/api/workspace/portfolio/nvda", { quantity: 4, costBasis: 120.25, note: "  ai  " });121    expect(r.status).toBe(200);122    expect(Object.keys(r.body).sort()).toEqual(["costBasis", "note", "quantity", "symbol", "updatedAt"]);123    expect(r.body).toMatchObject({ symbol: "NVDA", quantity: 4, costBasis: 120.25, note: "ai" });124    const main = (await t.api("alice", "GET", "/api/v2/objects/portfolio/main")).body.object;125    expect(main.rev).toBe(2);126    expect(main.device).toBe("web");127    expect(main.data.positions.find((p: any) => p.symbol === "NVDA")).toMatchObject({ quantity: 4, costBasis: 120.25, note: "ai" });128    expect(legacyRows("alice")).toEqual(before);129    expect((await t.api("alice", "GET", "/api/workspace")).body.positions.map((p: any) => p.symbol)).toEqual(["AAPL", "BRK.B", "MSFT", "NVDA"]);130  });131132  it("an update keeps the cost basis and note it is not given, as before", async () => {133    const r = await t.api("alice", "PUT", "/api/workspace/portfolio/MSFT", { quantity: 7 });134    expect(r.body).toMatchObject({ symbol: "MSFT", quantity: 7, costBasis: 310.5, note: "core" });135    const cleared = await t.api("alice", "PUT", "/api/workspace/portfolio/MSFT", { quantity: 7, note: "" });136    expect(cleared.body).toMatchObject({ costBasis: 310.5, note: null });137  });138139  it("refuses what the legacy route refused, with a 400", async () => {140    for (const body of [{ quantity: 0 }, { quantity: -2 }, { quantity: "abc" }, { quantity: 1, costBasis: -5 }]) {141      const r = await t.api("alice", "PUT", "/api/workspace/portfolio/AAPL", body);142      expect(r.status).toBe(400);143      expect(typeof r.body.error).toBe("string");144    }145    expect((await t.api("alice", "PUT", "/api/workspace/portfolio/not%20a%20symbol!", { quantity: 1 })).status).toBe(400);146  });147148  it("DELETE /api/workspace/portfolio/:symbol answers { success } and removes the position from the object", async () => {149    expect((await t.api("alice", "DELETE", "/api/workspace/portfolio/nvda")).body).toEqual({ success: true });150    expect((await t.api("alice", "DELETE", "/api/workspace/portfolio/NVDA")).body).toEqual({ success: false });151    const main = (await t.api("alice", "GET", "/api/v2/objects/portfolio/main")).body.object;152    expect(main.data.positions.map((p: any) => p.symbol)).toEqual(["AAPL", "BRK.B", "MSFT"]);153  });154155  it("the new portfolio UI and the legacy route see the same portfolio, and unknown fields survive a legacy update", async () => {156    const main = (await t.api("alice", "GET", "/api/v2/objects/portfolio/main")).body.object;157    const data = { ...main.data, benchmark: "SPY", cash: [{ currency: "USD", amount: 1000 }], positions: [...main.data.positions, { symbol: "SHOP.TO", quantity: 3, costBasis: 90, currency: "CAD", openedAt: "2025-03-01", lot: "L-7" }] };158    const saved = await t.api("alice", "PUT", "/api/v2/objects/portfolio/main", { data, baseRev: main.rev });159    expect(saved.status).toBe(200);160    expect((await t.api("alice", "GET", "/api/workspace")).body.positions.find((p: any) => p.symbol === "SHOP.TO")).toEqual({ symbol: "SHOP.TO", quantity: 3, costBasis: 90, note: null, updatedAt: saved.body.object.updatedAt });161    await t.api("alice", "PUT", "/api/workspace/portfolio/SHOP.TO", { quantity: 8 });162    const after = (await t.api("alice", "GET", "/api/v2/objects/portfolio/main")).body.object.data;163    expect(after.positions.find((p: any) => p.symbol === "SHOP.TO")).toMatchObject({ quantity: 8, costBasis: 90, currency: "CAD", openedAt: "2025-03-01", lot: "L-7" });164    expect(after.benchmark).toBe("SPY");165    expect(after.cash).toEqual([{ currency: "USD", amount: 1000 }]);166  });167168  it("copies before a new client can create an empty main over positions not copied yet", async () => {169    seedLegacy("bob", [["TSLA", 1, 200, null]]);170    // Bob's very first request is the new client creating portfolio/main.171    const r = await t.api("bob", "PUT", "/api/v2/objects/portfolio/main", { data: { name: "Mine", baseCurrency: "USD", positions: [] }, baseRev: 0 });172    expect(r.status).toBe(409);173    expect(r.body.current.data.positions).toEqual([{ symbol: "TSLA", quantity: 1, costBasis: 200, note: null, updatedAt: 1_700_000_000_000 }]);174  });175176  it("includes the copied portfolio in the first sync of a new device", async () => {177    seedLegacy("carol", [["SPY", 12, 400, null]]);178    const feed = await t.api("carol", "GET", "/api/v2/sync/changes?since=0");179    expect(feed.body.changes.map((c: any) => `${c.kind}/${c.id}`)).toEqual(["portfolio/main"]);180    expect(feed.body.changes[0].data.positions[0].symbol).toBe("SPY");181  });182183  it("creates main at the first position of a person who had none, and never before", async () => {184    expect((await t.api("dave", "GET", "/api/workspace")).body.positions).toEqual([]);185    expect((await t.api("dave", "GET", "/api/v2/objects/portfolio/main")).status).toBe(404);186    expect((await t.api("dave", "DELETE", "/api/workspace/portfolio/AAPL")).body).toEqual({ success: false });187    expect((await t.api("dave", "GET", "/api/v2/objects/portfolio/main")).status).toBe(404);188    await t.api("dave", "PUT", "/api/workspace/portfolio/AAPL", { quantity: 1 });189    const main = (await t.api("dave", "GET", "/api/v2/objects/portfolio/main")).body.object;190    expect(main).toMatchObject({ rev: 1, data: { baseCurrency: "USD", positions: [{ symbol: "AAPL", quantity: 1, costBasis: null, note: null }] } });191  });192193  it("keeps a deleted portfolio deleted: the legacy rows are not copied a second time", async () => {194    const main = (await t.api("carol", "GET", "/api/v2/objects/portfolio/main")).body.object;195    expect((await t.api("carol", "DELETE", `/api/v2/objects/portfolio/main?baseRev=${main.rev}`)).status).toBe(200);196    expect((await t.api("carol", "GET", "/api/workspace")).body.positions).toEqual([]);197    expect((await t.api("carol", "GET", "/api/v2/objects/portfolio/main")).status).toBe(404);198    expect(legacyRows("carol")).toHaveLength(1);199    // a new position starts the portfolio again200    await t.api("carol", "PUT", "/api/workspace/portfolio/QQQ", { quantity: 2 });201    expect((await t.api("carol", "GET", "/api/workspace")).body.positions.map((p: any) => p.symbol)).toEqual(["QQQ"]);202  });203204  it("keeps portfolios apart between people", async () => {205    expect((await t.api("bob", "GET", "/api/workspace")).body.positions.map((p: any) => p.symbol)).toEqual(["TSLA"]);206    expect(JSON.stringify((await t.api("bob", "GET", "/api/workspace")).body)).not.toContain("SHOP.TO");207    expect((await t.api("bob", "DELETE", "/api/workspace/portfolio/AAPL")).body).toEqual({ success: false });208    expect((await t.api("alice", "GET", "/api/workspace")).body.positions.some((p: any) => p.symbol === "AAPL")).toBe(true);209  });210211  it("the agent's tools (upsertPosition / removePosition) act on main with device \"server\"", () => {212    const pos = ws.upsertPosition("alice", { symbol: "amzn", quantity: 2, costBasis: 180 });213    expect(pos).toMatchObject({ symbol: "AMZN", quantity: 2, costBasis: 180, note: null });214    expect(objects.getObject("alice", "portfolio", "main")?.device).toBe("server");215    expect(ws.removePosition("alice", "AMZN")).toBe(true);216    expect(ws.removePosition("alice", "AMZN")).toBe(false);217    expect(() => ws.upsertPosition("alice", { symbol: "AMZN", quantity: 0 })).toThrow(ws.WorkspaceError);218  });219220  it("the agent's context calls main \"their portfolio\" and lists the others briefly", async () => {221    await t.api("alice", "PUT", "/api/v2/objects/portfolio/retire", { data: { name: "Retraite", baseCurrency: "CAD", positions: [{ symbol: "XEQT.TO", quantity: 100 }, { symbol: "VFV.TO", quantity: 40 }] }, baseRev: 0 });222    const ctx = ws.buildWorkspaceContext("alice", "Alice");223    expect(ctx).toContain("YOU ARE TALKING TO: Alice");224    const mainBlock = ctx.slice(ctx.indexOf("THEIR PORTFOLIO"), ctx.indexOf("THEIR OTHER PORTFOLIOS"));225    expect(mainBlock).toContain("- AAPL: 10 @ 150");226    expect(mainBlock).toContain("- BRK.B: 2 @ cost unknown");227    expect(mainBlock).toContain("- MSFT: 7 @ 310.5");228    expect(mainBlock).not.toContain("XEQT.TO");229    const others = ctx.slice(ctx.indexOf("THEIR OTHER PORTFOLIOS"));230    expect(others).toContain('"Retraite" (CAD, 2 positions): XEQT.TO × 100, VFV.TO × 40');231    // nothing of Alice's in Bob's context232    const bob = ws.buildWorkspaceContext("bob", "Bob");233    expect(bob).toContain("- TSLA: 1 @ 200");234    expect(bob).not.toContain("AAPL");235    expect(bob).not.toContain("Retraite");236    expect(bob).not.toContain("THEIR OTHER PORTFOLIOS");237  });238});239240describe("memory", () => {241  it("the agent's memory tools work as before", () => {242    const m = ws.saveMemory("alice", "  Prefers reports in French  ", "preference");243    expect(m).toMatchObject({ content: "Prefers reports in French", category: "preference", scope: "user", source: "agent", pinned: false, expiresAt: null });244    expect(m.id).toMatch(/^[0-9a-f]{8}$/);245    expect(ws.saveMemory("alice", "prefers reports in french", "profil").id).toBe(m.id); // same fact, not saved twice246    expect(ws.saveMemory("alice", "Holds a CFA", "nonsense").category).toBe("profil");247    expect(() => ws.saveMemory("alice", "   ", "profil")).toThrow(ws.WorkspaceError);248    const updated = ws.updateMemory("alice", m.id, "Prefers reports in French, tables in English");249    expect(updated).toMatchObject({ id: m.id, content: "Prefers reports in French, tables in English" });250    expect(ws.updateMemory("alice", "nope", "x")).toBeUndefined();251    expect(ws.updateMemory("bob", m.id, "hijack")).toBeUndefined();252    expect(ws.deleteMemory("bob", m.id)).toBe(false);253    expect(ws.listMemories("alice").map((x) => x.content).sort()).toEqual(["Holds a CFA", "Prefers reports in French, tables in English"]);254    const ctx = ws.buildWorkspaceContext("alice", "Alice");255    expect(ctx).toContain(`- [${m.id}] (preference) Prefers reports in French, tables in English`);256    expect(ws.deleteMemory("alice", m.id)).toBe(true);257    expect(ws.deleteMemory("alice", m.id)).toBe(false);258  });259260  it("the legacy memory routes keep their fields (new ones are added, none removed)", async () => {261    const created = await t.api("alice", "POST", "/api/workspace/memories", { content: "Works at a pension fund", category: "profil" });262    expect(created.status).toBe(200);263    expect(created.body).toMatchObject({ content: "Works at a pension fund", category: "profil", scope: "user", source: "user" });264    for (const key of ["id", "content", "category", "createdAt"]) expect(created.body).toHaveProperty(key);265    const list = (await t.api("alice", "GET", "/api/workspace")).body.memories;266    expect(list.some((m: any) => m.id === created.body.id && m.content === "Works at a pension fund")).toBe(true);267    expect((await t.api("alice", "POST", "/api/workspace/memories", { content: "" })).status).toBe(400);268    expect((await t.api("alice", "DELETE", `/api/workspace/memories/${created.body.id}`)).body).toEqual({ success: true });269    expect((await t.api("alice", "DELETE", `/api/workspace/memories/${created.body.id}`)).body).toEqual({ success: false });270  });271272  it("PATCH /api/workspace/memories/:id edits text, kind, scope, pin and expiry", async () => {273    const m = (await t.api("alice", "POST", "/api/workspace/memories", { content: "Benchmark is the S&P/TSX", category: "preference" })).body;274    const expiresAt = Date.now() + 30 * DAY;275    const r = await t.api("alice", "PATCH", `/api/workspace/memories/${m.id}`, { content: "Benchmark is the S&P/TSX Composite", kind: "knowledge", pinned: true, expiresAt });276    expect(r.status).toBe(200);277    expect(r.body).toMatchObject({ id: m.id, content: "Benchmark is the S&P/TSX Composite", kind: "knowledge", pinned: true, expiresAt, category: "preference", scope: "user" });278    expect((await t.api("alice", "PATCH", `/api/workspace/memories/${m.id}`, { expiresAt: null })).body.expiresAt).toBeNull();279    expect((await t.api("alice", "PATCH", `/api/workspace/memories/${m.id}`, { scope: "project:p-1" })).body.scope).toBe("project:p-1");280    expect((await t.api("alice", "PATCH", `/api/workspace/memories/${m.id}`, { scope: "user" })).body.scope).toBe("user");281    for (const bad of [{}, { kind: "gossip" }, { scope: "team" }, { scope: "project:" }, { pinned: "yes" }, { expiresAt: "soon" }, { content: "  " }, { category: "x" }]) {282      expect((await t.api("alice", "PATCH", `/api/workspace/memories/${m.id}`, bad)).status).toBe(400);283    }284    expect((await t.api("alice", "PATCH", "/api/workspace/memories/unknown", { pinned: true })).status).toBe(400);285    // not someone else's286    expect((await t.api("bob", "PATCH", `/api/workspace/memories/${m.id}`, { content: "hijacked" })).status).toBe(400);287    expect(ws.listMemories("alice").find((x) => x.id === m.id)?.content).toBe("Benchmark is the S&P/TSX Composite");288  });289290  it("GET /api/v2/memory groups memories by scope, with the project's title and the settings", async () => {291    await t.api("alice", "PUT", "/api/v2/objects/project/p-1", { data: { title: "Bank capital study", items: [] }, baseRev: 0 });292    await t.api("alice", "POST", "/api/workspace/memories", { content: "Sample is Canadian D-SIBs, 2010–2025", scope: "project:p-1" });293    await t.api("alice", "POST", "/api/workspace/memories", { content: "Orphan project fact", scope: "project:gone" });294    const r = await t.api("alice", "GET", "/api/v2/memory");295    expect(r.status).toBe(200);296    expect(r.body.settings).toEqual({ enabled: true, retentionDays: null });297    expect(r.body.groups.map((g: any) => g.scope)).toEqual(["user", "project:p-1", "project:gone"]);298    expect(r.body.groups[0].project).toBeNull();299    expect(r.body.groups[1].project).toEqual({ id: "p-1", title: "Bank capital study" });300    expect(r.body.groups[1].memories[0]).toMatchObject({ content: "Sample is Canadian D-SIBs, 2010–2025", kind: "project", source: "user" });301    expect(r.body.groups[2].project).toEqual({ id: "gone", title: null });302    expect(r.body.count).toBe(r.body.groups.reduce((n: number, g: any) => n + g.memories.length, 0));303  });304305  it("injects a project's memories only in that project's conversations", () => {306    const plain = ws.buildWorkspaceContext("alice", "Alice");307    expect(plain).toContain("Benchmark is the S&P/TSX Composite");308    expect(plain).not.toContain("Canadian D-SIBs");309    expect(plain).not.toContain("Orphan project fact");310    const inProject = ws.buildWorkspaceContext("alice", "Alice", { projectId: "p-1" });311    expect(inProject).toContain("Benchmark is the S&P/TSX Composite");312    expect(inProject).toContain("WHAT YOU REMEMBER ABOUT THIS RESEARCH PROJECT");313    expect(inProject).toContain("Canadian D-SIBs");314    expect(inProject).not.toContain("Orphan project fact");315    const otherProject = ws.buildWorkspaceContext("alice", "Alice", { projectId: "p-2" });316    expect(otherProject).not.toContain("Canadian D-SIBs");317    // another person naming Alice's project gets nothing of hers318    const bob = ws.buildWorkspaceContext("bob", "Bob", { projectId: "p-1" });319    expect(bob).not.toContain("Canadian D-SIBs");320    expect(bob).not.toContain("Benchmark");321  });322323  it("never returns or injects an expired memory, and the purge deletes it", async () => {324    const soon = ws.saveMemory("dave", "Reviewing Q3 earnings this week", "suivi", { expiresAt: Date.now() + 60_000 });325    const past = ws.saveMemory("dave", "Was on holiday until last Monday", "suivi", { expiresAt: Date.now() - 1000 });326    const keep = ws.saveMemory("dave", "Risk-averse, ten-year horizon", "profil");327    expect(ws.listMemories("dave").map((m) => m.id)).toEqual([soon.id, keep.id]);328    expect(ws.listMemories("dave", { includeExpired: true }).map((m) => m.id)).toEqual([soon.id, past.id, keep.id]);329    const ctx = ws.buildWorkspaceContext("dave", "Dave");330    expect(ctx).toContain("Reviewing Q3 earnings");331    expect(ctx).toContain("Risk-averse");332    expect(ctx).not.toContain("holiday");333    const viaHttp = JSON.stringify([(await t.api("dave", "GET", "/api/workspace")).body.memories, (await t.api("dave", "GET", "/api/v2/memory")).body, (await t.api("dave", "GET", "/api/v2/memory/export")).body]);334    expect(viaHttp).toContain("Risk-averse");335    expect(viaHttp).not.toContain("holiday");336    expect(t.db.prepare("SELECT count(*) AS n FROM agent_memories WHERE id = ?").get(past.id)).toEqual({ n: 1 });337    expect(ws.purgeExpiredMemories()).toBe(1);338    expect(t.db.prepare("SELECT count(*) AS n FROM agent_memories WHERE id = ?").get(past.id)).toEqual({ n: 0 });339    // time passes: the one that was about to expire goes too340    expect(ws.purgeExpiredMemories(Date.now() + 120_000)).toBe(1);341    expect(ws.listMemories("dave", { includeExpired: true }).map((m) => m.id)).toEqual([keep.id]);342  });343344  it("PUT /api/v2/memory/settings stores the settings in preference/default without touching the rest", async () => {345    await t.api("dave", "PUT", "/api/v2/objects/preference/default", { data: { theme: "dark", memory: { futureKey: 1 } }, baseRev: 0 });346    const r = await t.api("dave", "PUT", "/api/v2/memory/settings", { retentionDays: 90 });347    expect(r.status).toBe(200);348    expect(r.body.settings).toEqual({ enabled: true, retentionDays: 90 });349    const pref = (await t.api("dave", "GET", "/api/v2/objects/preference/default")).body.object;350    expect(pref.data).toEqual({ theme: "dark", memory: { futureKey: 1, retentionDays: 90 } });351    expect(pref.rev).toBe(2);352    expect((await t.api("dave", "GET", "/api/v2/memory")).body.settings).toEqual({ enabled: true, retentionDays: 90 });353    for (const bad of [{}, { retentionDays: 0 }, { retentionDays: 1.5 }, { enabled: "no" }, { retentionDays: 90, extra: true }]) {354      expect((await t.api("dave", "PUT", "/api/v2/memory/settings", bad)).status).toBe(400);355    }356    // a person without a preference object gets one357    expect((await t.api("erin", "PUT", "/api/v2/memory/settings", { enabled: false })).body.settings).toEqual({ enabled: false, retentionDays: null });358    expect((await t.api("erin", "GET", "/api/v2/objects/preference/default")).body.object.data).toEqual({ memory: { enabled: false } });359    // and the settings of one person are not the settings of another360    expect((await t.api("alice", "GET", "/api/v2/memory")).body.settings).toEqual({ enabled: true, retentionDays: null });361  });362363  it("applies the retention period to unpinned memories only", async () => {364    const old = Date.now() - 100 * DAY;365    const insert = (id: string, content: string, pinned: number, createdAt: number) =>366      t.db.prepare("INSERT INTO agent_memories (id, owner, content, category, created_at, pinned) VALUES (?, 'dave', ?, 'profil', ?, ?)").run(id, content, createdAt, pinned);367    insert("old-loose", "Old unpinned fact", 0, old);368    insert("old-pinned", "Old pinned fact", 1, old);369    insert("fresh", "Fresh fact", 0, Date.now() - 10 * DAY);370    const visible = ws.listMemories("dave").map((m) => m.content);371    expect(visible).toContain("Old pinned fact");372    expect(visible).toContain("Fresh fact");373    expect(visible).not.toContain("Old unpinned fact");374    expect(ws.buildWorkspaceContext("dave", "Dave")).not.toContain("Old unpinned fact");375    // a longer retention brings it back as long as it was not purged376    await t.api("dave", "PUT", "/api/v2/memory/settings", { retentionDays: 365 });377    expect(ws.listMemories("dave").map((m) => m.content)).toContain("Old unpinned fact");378    // shortening the retention purges at once379    await t.api("dave", "PUT", "/api/v2/memory/settings", { retentionDays: 30 });380    expect(t.db.prepare("SELECT id FROM agent_memories WHERE owner = 'dave' AND id LIKE 'old-%' ORDER BY id").all()).toEqual([{ id: "old-pinned" }]);381    // no retention: nothing expires by age382    await t.api("dave", "PUT", "/api/v2/memory/settings", { retentionDays: null });383    expect((await t.api("dave", "GET", "/api/v2/memory")).body.settings.retentionDays).toBeNull();384    expect(ws.listMemories("dave").map((m) => m.content)).toContain("Old pinned fact");385  });386387  it("when memory is off: nothing is injected, the agent cannot save, the person still can", async () => {388    ws.saveMemory("erin", "Saved by hand", "profil", { source: "user" });389    expect(() => ws.saveMemory("erin", "Agent tries", "profil")).toThrow(/turned memory off/);390    const ctx = ws.buildWorkspaceContext("erin", "Erin");391    expect(ctx).toContain("MEMORY IS TURNED OFF");392    expect(ctx).not.toContain("Saved by hand");393    expect((await t.api("erin", "GET", "/api/v2/memory")).body.count).toBe(1);394    await t.api("erin", "PUT", "/api/v2/memory/settings", { enabled: true });395    expect(ws.buildWorkspaceContext("erin", "Erin")).toContain("Saved by hand");396    expect(ws.saveMemory("erin", "Agent may save again", "profil").source).toBe("agent");397  });398399  it("DELETE /api/v2/memory needs an explicit scope and deletes that scope only", async () => {400    expect((await t.api("alice", "DELETE", "/api/v2/memory")).status).toBe(400);401    expect((await t.api("alice", "DELETE", "/api/v2/memory?scope=")).status).toBe(400);402    expect((await t.api("alice", "DELETE", "/api/v2/memory?scope=everything")).status).toBe(400);403    const before = ws.listMemories("alice").length;404    const r = await t.api("alice", "DELETE", "/api/v2/memory?scope=project:p-1");405    expect(r.body).toEqual({ deleted: 1 });406    expect(ws.listMemories("alice")).toHaveLength(before - 1);407    expect(ws.listMemories("alice", { scope: "project:p-1" })).toEqual([]);408    const userCount = ws.listMemories("alice", { scope: "user" }).length;409    expect((await t.api("alice", "DELETE", "/api/v2/memory?scope=user")).body).toEqual({ deleted: userCount });410    expect(ws.listMemories("alice").map((m) => m.scope)).toEqual(["project:gone"]);411    expect((await t.api("alice", "DELETE", "/api/v2/memory?scope=all")).body).toEqual({ deleted: 1 });412    expect(ws.listMemories("alice", { includeExpired: true })).toEqual([]);413  });414415  it("a bulk deletion or an export of one person does not touch or show another's memories", async () => {416    ws.saveMemory("bob", "Bob's private fact", "profil");417    ws.saveMemory("carol", "Carol's private fact", "profil");418    expect((await t.api("carol", "DELETE", "/api/v2/memory?scope=all")).body).toEqual({ deleted: 1 });419    expect(ws.listMemories("bob").map((m) => m.content)).toEqual(["Bob's private fact"]);420    const carol = JSON.stringify([(await t.api("carol", "GET", "/api/v2/memory")).body, (await t.api("carol", "GET", "/api/v2/memory/export")).body, (await t.api("carol", "GET", "/api/workspace")).body]);421    expect(carol).not.toContain("Bob's private fact");422    const exported = await t.api("bob", "GET", "/api/v2/memory/export");423    expect(exported.headers.get("content-disposition")).toMatch(/^attachment; filename="vquant-memory-\d{4}-\d{2}-\d{2}\.json"$/);424    expect(exported.body.memories.map((m: any) => m.content)).toEqual(["Bob's private fact"]);425    expect(exported.body.settings).toEqual({ enabled: true, retentionDays: null });426  });427});428429describe("audit", () => {430  it("records bulk memory deletions and memory exports of the person who made them", async () => {431    const alice = (await t.api("alice", "GET", "/api/v2/audit")).body.events;432    const bulk = alice.filter((e: any) => e.action === "memory.bulk_delete");433    expect(bulk.map((e: any) => e.target)).toEqual(["all", "user", "project:p-1"]); // newest first434    expect(bulk[2].detail).toEqual({ deleted: 1 });435    expect(bulk[0]).toMatchObject({ device: "web" });436    expect(typeof bulk[0].at).toBe("number");437    const bob = (await t.api("bob", "GET", "/api/v2/audit")).body.events;438    expect(bob.map((e: any) => e.action)).toEqual(["memory.export"]);439    expect(JSON.stringify(bob)).not.toContain("project:p-1");440  });441442  it("honours limit, and attributes a native request to its device", async () => {443    await t.api("bob", "GET", "/api/v2/memory/export", undefined, { "x-test-device": "dev-bob-1" });444    const one = (await t.api("bob", "GET", "/api/v2/audit?limit=1")).body.events;445    expect(one).toHaveLength(1);446    expect(one[0]).toMatchObject({ action: "memory.export", device: "dev-bob-1" });447    expect((await t.api("bob", "GET", "/api/v2/audit")).body.events).toHaveLength(2);448    const page = (await t.api("bob", "GET", `/api/v2/audit?before=${one[0].id}`)).body.events;449    expect(page).toHaveLength(1);450    expect(page[0].device).toBe("web");451  });452453  it("audit() accepts a null request and an explicit person, and never throws", async () => {454    auditMod.audit(null, "signin.web", null, { device: "Mac · Safari" }, { owner: "frank", device: "web" });455    auditMod.audit(null, "server.note", "x", "plain text detail");456    const frank = (await t.api("frank", "GET", "/api/v2/audit")).body.events;457    expect(frank).toHaveLength(1);458    expect(frank[0]).toMatchObject({ action: "signin.web", target: null, device: "web", ip: null, detail: { device: "Mac · Safari" } });459    // an event without an owner belongs to nobody's log460    for (const who of ["alice", "bob", "frank"]) expect(JSON.stringify((await t.api(who, "GET", "/api/v2/audit")).body)).not.toContain("server.note");461    const circular: Record<string, unknown> = {};462    circular.self = circular;463    expect(() => auditMod.audit(null, "broken", null, circular, { owner: "frank" })).not.toThrow();464  });465466  it("refuses the log to a request that is not signed in", async () => {467    expect((await t.api(null, "GET", "/api/v2/audit")).status).toBe(401);468  });469});470
Files main
Menu

Theme