SPB Git

Repository Public

next-k-constellation.test.ts 8.5 KB 105 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-k-constellation.test.ts9 * Description      : Thought Constellation service on a *_dev database — pages10 *                    with chunk embeddings inserted by the test (two groups of11 *                    synthetic 1536-d vectors: fixtures, not model output) are12 *                    projected by the real code path (pgvector avg → PCA): the13 *                    two groups separate, the projection is cached by signature14 *                    and recomputed when embeddings change, links / tags /15 *                    projects are read live, and trashed pages leave the map.16 *                    No provider is called.17 * Module           : tests18 * Repository       : https://git.spboucher.ai/note-spboucher-ai19 * Project Website  : https://note.spboucher.ai20 * Created          : 2026-11-1921 * Last Modified    : 2026-11-1922 *23 * Author           : Simon-Pierre Boucher24 * Position         : Professor of Finance25 * Institution      : Université du Québec en Outaouais (UQO)26 * Organization     : SP Boucher27 * Website          : https://spboucher.ai28 * Git              : https://git.spboucher.ai29 *30 * Preferred Contact: contact@spboucher.ai31 * Development      : dev@spboucher.ai32 * Support          : support@spboucher.ai33 * Security/Admin   : admin@spboucher.ai34 *35 * Copyright (c) 202636 * Simon-Pierre Boucher37 * All rights reserved where applicable. This file is governed by the38 * applicable project license, copyright notices and relevant law.39 * Existing third-party rights and notices remain unaffected.40 *41 * License          : None specified (no license file in this repository)42 *43 * Do not embed credentials, private keys, access tokens,44 * certificates or confidential personal information.45 *46 * =============================================================================47 * END OF SP BOUCHER SOURCE HEADER48 * =============================================================================49 */5051import { test, before, after } from "node:test";52import assert from "node:assert/strict";53import { eq } from "drizzle-orm";54import { db, schema, sql } from "../../src/db/index";55import { workspace, mk, doc, made, cleanup } from "../helpers/next";56import { buildConstellation } from "../../src/lib/graph/constellation";57import { createRelation } from "../../src/lib/graph/relations";58import { setPageTags } from "../../src/lib/inbox/service";59import { softDeletePage, updatePage } from "../../src/lib/pages/service";60import { EMBEDDING_MODEL } from "../../src/lib/ai/router";6162let ws: string; const PFX = "nx-const ·"; const ids: string[] = [];63/** A unit-ish 1536-d vector: group A lives around axis 3, group B around axis 700; `j` adds a small, fixed variation. */64const vec = (group: "A" | "B", j: number) => { const v = new Array(1536).fill(0); v[group === "A" ? 3 : 700] = 1; v[(group === "A" ? 40 : 900) + j] = 0.15; v[1200] = 0.05 * (j % 3); return `[${v.join(",")}]`; };65async function embed(pageId: string, group: "A" | "B", j: number, chunks = 2) {66  for (let o = 0; o < chunks; o++) { const [c] = await db.insert(schema.chunks).values({ workspaceId: ws, sourceType: "page", sourceId: pageId, pageId, ordinal: o, content: `chunk ${o}`, contentHash: `${pageId}-${o}` }).returning({ id: schema.chunks.id }); await sql`insert into embeddings (chunk_id, model, embedding) values (${c.id}, ${EMBEDDING_MODEL}, ${vec(group, j + o)}::vector)`; }67}68before(async () => { ws = await workspace(); await db.delete(schema.settings).where(eq(schema.settings.key, `graph.constellation:${ws}`)); });69after(async () => { if (ids.length) await sql`delete from chunks where page_id = any(${ids}::uuid[])`; made.tags.push("nx-const-tag"); await db.delete(schema.settings).where(eq(schema.settings.key, `graph.constellation:${ws}`)); await cleanup(ws, PFX); });7071test("constellation: real code path over stored embeddings — separation, cache, live metadata, honest counts", async () => {72  const before0 = await buildConstellation(ws); const base = before0.stats.embedded;73  const project = await mk(ws, `${PFX} Projet`, doc("racine du projet"), { section: "projects" });74  const a = [await mk(ws, `${PFX} A1`, doc("alpha un"), { parentId: project.id, section: "projects" }), await mk(ws, `${PFX} A2`, doc("alpha deux")), await mk(ws, `${PFX} A3`, doc("alpha trois"))];75  const b = [await mk(ws, `${PFX} B1`, doc("beta un")), await mk(ws, `${PFX} B2`, doc("beta deux")), await mk(ws, `${PFX} B3`, doc("beta trois"))];76  const noVec = await mk(ws, `${PFX} sans vecteur`, doc("jamais indexée"));77  ids.push(...a.map((p) => p.id), ...b.map((p) => p.id), project.id, noVec.id);78  await sql`delete from chunks where page_id = any(${ids}::uuid[])`; // whatever a running worker may have indexed meanwhile: the test owns these vectors79  for (const [i, p] of a.entries()) await embed(p.id, "A", i); for (const [i, p] of b.entries()) await embed(p.id, "B", i);80  await createRelation(ws, { fromId: a[0].id, toId: a[1].id, relType: "supports" }); await setPageTags(ws, a[1].id, ["nx-const-tag"]);8182  const c1 = await buildConstellation(ws); assert.equal(c1.cached, false); assert.equal(c1.model, EMBEDDING_MODEL); assert.equal(c1.stats.embedded, base + 6);83  assert.ok(c1.stats.pages >= c1.stats.embedded + 2, "pages without vectors are counted, not placed"); assert.equal(c1.points.some((p) => p.id === noVec.id), false);84  const at = (id: string) => c1.points.find((p) => p.id === id)!; const pa = a.map((p) => at(p.id)), pb = b.map((p) => at(p.id));85  for (const p of [...pa, ...pb]) { assert.ok(p, "every embedded page is a point"); assert.ok(Math.abs(p.x) <= 1.05 && Math.abs(p.y) <= 1.05); }86  const d = (p: { x: number; y: number }, q: { x: number; y: number }) => Math.hypot(p.x - q.x, p.y - q.y);87  const within = Math.max(d(pa[0], pa[1]), d(pa[0], pa[2]), d(pb[0], pb[1]), d(pb[0], pb[2])); const between = Math.min(...pa.flatMap((p) => pb.map((q) => d(p, q))));88  if (base === 0) assert.ok(between > within * 3, `notes that mean the same sit together (within ${within.toFixed(3)}, between ${between.toFixed(3)})`); else assert.ok(between > within, "the two groups are apart");89  assert.equal(at(a[0].id).projectId, project.id, "project = top-most ancestor in the section projects"); assert.equal(at(a[1].id).projectId, null); assert.deepEqual(at(a[1].id).tags, ["nx-const-tag"]);90  assert.ok(c1.links.some((l) => (l.source === a[0].id && l.target === a[1].id) || (l.source === a[1].id && l.target === a[0].id)), "accepted relations are the constellation lines"); assert.equal(at(a[0].id).degree >= 1, true);91  assert.equal(c1.clusters.reduce((s, c) => s + c.size, 0), c1.points.length); assert.ok(c1.clusters.every((c) => c.label)); assert.ok(c1.projects.some((p) => p.id === project.id && p.pages === 1)); assert.ok(c1.tags.some((t) => t.name === "nx-const-tag"));92  assert.ok(c1.explained[0] > 0 && c1.explained[0] + c1.explained[1] <= 1 + 1e-6);9394  // second call: same signature → cached positions, live titles95  await updatePage(ws, a[2].id, { title: `${PFX} A3 renommée` });96  const c2 = await buildConstellation(ws); assert.equal(c2.cached, true); assert.equal(c2.computedAt, c1.computedAt); assert.equal(c2.points.find((p) => p.id === a[2].id)!.title, `${PFX} A3 renommée`);97  assert.deepEqual(c2.points.map((p) => [p.id, p.x, p.y]), c1.points.map((p) => [p.id, p.x, p.y]), "positions are stable while the embeddings do not change");98  // new embeddings → new signature → recomputed99  await embed(noVec.id, "B", 7, 1); const c3 = await buildConstellation(ws); assert.equal(c3.cached, false); assert.notEqual(c3.signature, c2.signature); assert.ok(c3.points.some((p) => p.id === noVec.id));100  const moved = c3.points.find((p) => p.id === noVec.id)!; assert.ok(Math.min(...b.map((p) => d(moved, c3.points.find((x) => x.id === p.id)!))) < Math.min(...a.map((p) => d(moved, c3.points.find((x) => x.id === p.id)!))), "the new note lands near the notes it resembles");101  // refresh=1 recomputes even when nothing changed; a trashed page leaves the map102  const c4 = await buildConstellation(ws, { refresh: true }); assert.equal(c4.cached, false); assert.deepEqual(c4.points.map((p) => [p.id, p.x, p.y]), c3.points.map((p) => [p.id, p.x, p.y]), "deterministic: recomputing gives the same map");103  await softDeletePage(ws, b[2].id); const c5 = await buildConstellation(ws); assert.equal(c5.points.some((p) => p.id === b[2].id), false);104});105
Files main
Menu

Theme