SPB Git

Repository Public

next-events.test.ts 19.2 KB 188 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-events.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *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 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Events journal and time machine (SPEC §3.2, §4.4): every listed event is written by the mutation that causes it, in its transaction;45 * `page.edited` is coalesced; a refused write leaves no event; the journal is paged by a stable cursor; the state at a date is rebuilt46 * from the history only. Runs against a *_dev database.47 */48import { test, before, after } from "node:test";49import assert from "node:assert/strict";50import { randomUUID } from "node:crypto";51import { and, eq, inArray } from "drizzle-orm";52import { db, schema } from "../../src/db/index";53import { workspace, mk, doc, made, cleanup, code, kinds, eventsOf, para } from "../helpers/next";54import { createPage, updatePage, softDeletePage, restorePage, purgePage, snapshot, getPage } from "../../src/lib/pages/service";55import { setPageTags, capture, triage } from "../../src/lib/inbox/service";56import { createReference } from "../../src/lib/research/references";57import { EVENT_KINDS, listEvents, recordCoalesced, recordEvent, COALESCE_MS } from "../../src/lib/events/service";58import { withActor, currentActor } from "../../src/lib/events/context";59import { stateAt } from "../../src/lib/timemachine/service";60import { createRelation, deleteRelation } from "../../src/lib/graph/relations";61import type { PMNode } from "../../src/lib/editor/text";6263let ws: string; const PFX = "nx-evt ·";64before(async () => { ws = await workspace(); }); after(async () => { made.tags.push("nx-evt-a", "nx-evt-b"); await cleanup(ws, PFX); });65const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));6667test("the catalogue of event kinds is the one of the specification", () => {68  assert.equal(EVENT_KINDS.length, 30); assert.equal(new Set(EVENT_KINDS).size, 30); assert.equal(COALESCE_MS, 600_000);69  for (const k of ["page.created", "page.renamed", "page.edited", "page.moved", "page.archived", "page.unarchived", "page.trashed", "page.restored", "page.purged", "page.version", "tag.added", "tag.removed", "link.added", "link.removed", "relation.created", "relation.accepted", "relation.rejected", "relation.removed", "reference.added", "reference.linked", "attachment.added", "task.created", "task.completed", "task.reopened", "capture.created", "capture.filed", "ai.applied", "agent.applied", "decision.recorded", "canvas.edited"]) assert.ok((EVENT_KINDS as readonly string[]).includes(k), k);70});71test("the life of a page is journaled, each event once, by the mutation itself", async () => {72  const parent = await mk(ws, `${PFX} parent`); const p = await mk(ws, `${PFX} life`, doc("v1"));73  assert.deepEqual(await kinds(p.id), ["page.created"]); assert.equal((await eventsOf(p.id))[0].data.backfilled, undefined, "a real event is never flagged backfilled");74  let v = p.version;75  v = (await updatePage(ws, p.id, { title: `${PFX} life renamed` }, { baseVersion: v })).version;76  v = (await updatePage(ws, p.id, { content: doc("v2") }, { baseVersion: v })).version;77  v = (await updatePage(ws, p.id, { content: doc("v3") }, { baseVersion: v })).version;78  await updatePage(ws, p.id, { content: doc("v3") }); // same content again: not an edit79  await updatePage(ws, p.id, { parentId: parent.id }); await updatePage(ws, p.id, { parentId: parent.id }); // second time: nothing moved80  await updatePage(ws, p.id, { archived: true }); await updatePage(ws, p.id, { archived: false }); await updatePage(ws, p.id, { pinned: true });81  await setPageTags(ws, p.id, ["nx-evt-a", "nx-evt-b"]); await setPageTags(ws, p.id, ["nx-evt-a", "nx-evt-b"]); await setPageTags(ws, p.id, ["nx-evt-b"]);82  await softDeletePage(ws, p.id); await restorePage(ws, p.id);83  const ks = await kinds(p.id); const n = (k: string) => ks.filter((x) => x === k).length;84  assert.equal(n("page.renamed"), 1); assert.equal(n("page.edited"), 1, "three saves in a row are one coalesced page.edited"); assert.equal(n("page.moved"), 1);85  assert.equal(n("page.archived"), 1); assert.equal(n("page.unarchived"), 1); assert.equal(n("tag.added"), 2); assert.equal(n("tag.removed"), 1); assert.equal(n("page.trashed"), 1); assert.equal(n("page.restored"), 1);86  assert.ok(n("page.version") >= 1, "the first change snapshots the previous state");87  const ev = await eventsOf(p.id); const renamed = ev.find((e) => e.kind === "page.renamed")!; assert.deepEqual(renamed.data, { from: `${PFX} life`, to: `${PFX} life renamed` });88  assert.deepEqual(ev.find((e) => e.kind === "page.moved")!.data, { from: { parentId: null, section: "notes" }, to: { parentId: parent.id, section: "notes" } });89  await softDeletePage(ws, p.id); await purgePage(ws, p.id);90  assert.equal((await kinds(p.id)).filter((k) => k === "page.purged").length, 1, "the purge is journaled and the journal survives the page");91});92test("page.edited is coalesced per page over 10 minutes, and concurrent saves cannot both pass", async () => {93  const p = await mk(ws, `${PFX} coalesce`, doc("a")); const q = await mk(ws, `${PFX} coalesce other`, doc("a"));94  const base = { workspaceId: ws, kind: "page.edited" as const, pageId: p.id, summary: `${PFX} coalesce` };95  const r = await Promise.all(Array.from({ length: 8 }, () => recordCoalesced(base))); assert.equal(r.filter(Boolean).length, 1, "exactly one of 8 simultaneous writers records the event");96  assert.equal(await recordCoalesced({ ...base, pageId: q.id }), true, "another page has its own window");97  // an event older than the window no longer blocks a new one98  await db.update(schema.knowledgeEvents).set({ at: new Date(Date.now() - COALESCE_MS - 1000) }).where(and(eq(schema.knowledgeEvents.pageId, p.id), eq(schema.knowledgeEvents.kind, "page.edited")));99  assert.equal(await recordCoalesced(base), true); assert.equal(await recordCoalesced(base), false);100});101test("a refused save and a rolled-back transaction leave no event", async () => {102  const p = await mk(ws, `${PFX} refused`, doc("a")); await updatePage(ws, p.id, { title: `${PFX} refused v2` }, { baseVersion: p.version });103  const before = (await kinds(p.id)).length;104  assert.equal(await code(updatePage(ws, p.id, { title: `${PFX} refused v3` }, { baseVersion: p.version })), "conflict"); assert.equal((await kinds(p.id)).length, before);105  await assert.rejects(db.transaction(async (tx) => { await recordEvent(tx, { workspaceId: ws, kind: "page.renamed", pageId: p.id, summary: `${PFX} ghost` }); throw new Error("rollback"); }));106  assert.equal((await kinds(p.id)).length, before, "the event went away with the transaction");107});108test("links, citations, AI blocks and decisions found in a saved document become events", async () => {109  const target = await mk(ws, `${PFX} target`, doc("t")); const ref = await createReference(ws, { title: `${PFX} paper`, authors: ["Doe, J."], year: 2020 }); made.references.push(ref.id);110  const p = await mk(ws, `${PFX} doc`, doc("start"));111  const content: PMNode = doc(112    { type: "paragraph", content: [{ type: "text", text: "voir " }, { type: "mention", attrs: { id: target.id, label: "target" } }, { type: "citation", attrs: { refId: ref.id, label: "Doe 2020" } }, { type: "citation", attrs: { refId: randomUUID(), label: "Fantôme" } }] },113    { type: "aiBlock", attrs: { model: "model-x", action: "synthesis" }, content: [para("synthèse")] },114    { type: "callout", attrs: { kind: "decision" }, content: [para("On garde la version B.")] }, { type: "callout", attrs: { kind: "note" }, content: [para("note")] });115  const saved = await updatePage(ws, p.id, { content }, { baseVersion: p.version });116  let ev = await eventsOf(p.id); const of = (k: string) => ev.filter((e) => e.kind === k);117  assert.equal(of("link.added").length, 1); assert.equal(of("link.added")[0].data.toId, target.id); assert.equal(of("link.added")[0].data.toTitle, `${PFX} target`); assert.match(String(of("link.added")[0].data.sourceBlockId), /^[\w-]{10}$/);118  assert.equal(of("reference.linked").length, 1, "only the citation of a reference that exists"); assert.equal(of("reference.linked")[0].data.referenceId, ref.id); assert.equal(of("reference.linked")[0].data.via, "citation");119  assert.equal(of("ai.applied").length, 1); assert.equal(of("ai.applied")[0].data.model, "model-x"); assert.equal(of("decision.recorded").length, 1); assert.equal(of("decision.recorded")[0].summary, "On garde la version B.");120  const K = schema.knowledgeEdges; const edges = await db.select().from(K).where(eq(K.fromId, p.id));121  assert.deepEqual(edges.map((e) => `${e.kind}/${e.relType}/${e.targetKind}/${e.origin}`).sort(), ["cites/cites/reference/system", "link/related/page/system"]);122  assert.ok(edges.every((e) => e.sourceBlockId && e.rev > 0));123  // saving the same document again adds nothing; removing the link and the citation is journaled and removes the edges124  const again = await updatePage(ws, p.id, { content: (await getPage(ws, p.id)).content as PMNode, title: `${PFX} doc2` }, { baseVersion: saved.version });125  assert.equal((await eventsOf(p.id)).filter((e) => ["link.added", "reference.linked", "ai.applied", "decision.recorded"].includes(e.kind)).length, 4);126  await updatePage(ws, p.id, { content: doc("plus rien") }, { baseVersion: again.version }); ev = await eventsOf(p.id);127  assert.equal(of("link.removed").length, 1); assert.equal((await db.select().from(K).where(eq(K.fromId, p.id))).length, 0);128  assert.ok((await kinds(ref.pageId ?? p.id)).length > 0); const refEvents = await db.select().from(schema.knowledgeEvents).where(and(eq(schema.knowledgeEvents.entityId, ref.id), eq(schema.knowledgeEvents.kind, "reference.added"))); assert.equal(refEvents.length, 1);129});130test("captures, triage and the acting party are journaled", async () => {131  const c = await capture(ws, { kind: "note", text: `${PFX} capture` }); made.pages.push(c.id);132  assert.deepEqual(await kinds(c.id), ["page.created", "capture.created"]);133  await triage(ws, c.id, { action: "keep", section: "documents" }); const filed = (await eventsOf(c.id)).find((e) => e.kind === "capture.filed")!; assert.equal(filed.data.action, "keep"); assert.equal(filed.data.section, "documents");134  assert.deepEqual(currentActor(), { actor: "system", device: null }, "outside a request the actor is `system`");135  const p = await withActor({ actor: "agent", device: "worker" }, () => createPage(ws, { title: `${PFX} by agent` })); made.pages.push(p.id);136  const e = (await eventsOf(p.id))[0]; assert.equal(e.actor, "agent"); assert.equal(e.device, "worker");137  const u = await withActor({ actor: "user", device: "SP Notes · Mac" }, () => withActor({ actor: "ai" }, () => createPage(ws, { title: `${PFX} nested` }))); made.pages.push(u.id);138  const n = (await eventsOf(u.id))[0]; assert.equal(n.actor, "ai"); assert.equal(n.device, "SP Notes · Mac", "the device is inherited by a nested actor");139});140test("page.version is recorded once per history entry", async () => {141  const p = await mk(ws, `${PFX} versions`, doc("a")); await snapshot(p, "manual"); await snapshot(p, "manual again");142  const ev = (await eventsOf(p.id)).filter((e) => e.kind === "page.version"); assert.equal(ev.length, 1); assert.equal(ev[0].data.version, 1); assert.equal(ev[0].data.reason, "manual"); assert.equal(ev[0].entityKind, "page_version");143});144test("GET /api/events: newest first, stable cursor, filters by page, project, kinds and dates", async () => {145  const root = await mk(ws, `${PFX} project`, undefined, { section: "projects" }); const child = await mk(ws, `${PFX} project child`, doc("c"), { parentId: root.id }); const other = await mk(ws, `${PFX} elsewhere`);146  for (let i = 0; i < 6; i++) await recordEvent(db, { workspaceId: ws, kind: "page.renamed", pageId: child.id, summary: `${PFX} r${i}`, at: new Date(Date.now() - (10 - i) * 1000) });147  const ids = [root.id, child.id]; const all: string[] = []; let cursor: string | null = null; let pages = 0;148  do { const r: Awaited<ReturnType<typeof listEvents>> = await listEvents(ws, { pageIds: ids, limit: 3, cursor }); all.push(...r.events.map((e) => e.id)); cursor = r.nextCursor; pages++; assert.ok(r.events.length <= 3); } while (cursor && pages < 20);149  assert.equal(all.length, 8, "2 creations + 6 renames"); assert.equal(new Set(all).size, 8, "no event twice across pages"); assert.equal(pages, 3);150  const whole = await listEvents(ws, { pageIds: ids, limit: 200 }); assert.deepEqual(whole.events.map((e) => e.id), all, "same order as the paged read"); assert.equal(whole.nextCursor, null);151  for (let i = 1; i < whole.events.length; i++) assert.ok(whole.events[i - 1].at >= whole.events[i].at, "newest first");152  assert.equal(whole.events[0].pageTitle, `${PFX} project child`); assert.ok(whole.events.every((e) => e.pageId !== other.id));153  assert.equal((await listEvents(ws, { pageId: child.id, kinds: ["page.renamed"] })).events.length, 6); assert.equal((await listEvents(ws, { pageId: child.id, kinds: ["page.created"] })).events.length, 1);154  const mid = new Date(Date.now() - 7500); assert.equal((await listEvents(ws, { pageId: child.id, kinds: ["page.renamed"], to: mid })).events.length, 3); assert.equal((await listEvents(ws, { pageId: child.id, kinds: ["page.renamed"], from: mid })).events.length, 3);155  assert.equal(await code(listEvents(ws, { cursor: "not-a-cursor" })), "bad_cursor"); assert.equal((await listEvents(ws, { pageIds: [] })).events.length, 0);156  // a new event arriving while paging does not shift the pages already read157  const first = await listEvents(ws, { pageIds: ids, limit: 4 }); await recordEvent(db, { workspaceId: ws, kind: "page.renamed", pageId: child.id, summary: `${PFX} late` });158  const second = await listEvents(ws, { pageIds: ids, limit: 4, cursor: first.nextCursor }); assert.deepEqual([...first.events, ...second.events].map((e) => e.id), all);159});160test("time machine: the state of a page at a date, with where it comes from", async () => {161  const p = await mk(ws, `${PFX} tm`, doc("état 1")); const t0 = new Date(); await sleep(30);162  const a = await updatePage(ws, p.id, { content: doc("état 2"), title: `${PFX} tm v2` }, { baseVersion: p.version }); await sleep(30); const t1 = new Date(); await sleep(30);163  const b = await updatePage(ws, p.id, { content: doc("état 3") }, { baseVersion: a.version, versionReason: "checkpoint" }); await sleep(30); const t2 = new Date();164  const text = (s: any) => JSON.stringify(s.content);165  const now = (await stateAt(ws, t2, { pageId: p.id })).pages[0]; assert.equal(now.source, "current"); assert.equal(now.exact, true); assert.equal(now.version, b.version); assert.match(text(now), /état 3/); assert.equal(now.changedSince, false);166  const first = (await stateAt(ws, t0, { pageId: p.id })).pages[0]; assert.equal(first.existed, true); assert.equal(first.version, 1); assert.match(text(first), /état 1/); assert.equal(first.title, `${PFX} tm`); assert.equal(first.currentTitle, `${PFX} tm v2`); assert.equal(first.exact, false); assert.ok(["version", "version_after"].includes(first.source)); assert.ok(first.versionId);167  const mid = (await stateAt(ws, t1, { pageId: p.id })).pages[0]; assert.match(text(mid), /état [12]/); assert.equal(mid.changedSince, true);168  const early = (await stateAt(ws, new Date(p.createdAt.getTime() - 60_000), { pageId: p.id })).pages[0]; assert.equal(early.existed, false); assert.equal(early.source, "none"); assert.equal(early.content, undefined);169  assert.equal(await code(stateAt(ws, t0, { pageId: randomUUID() })), "not_found"); assert.equal(await code(stateAt(ws, t0, {})), "bad_request");170});171test("time machine: a project lists its pages, and the relations and references that existed at that date", async () => {172  const root = await mk(ws, `${PFX} tm project`, undefined, { section: "projects" }); const kid = await mk(ws, `${PFX} tm kid`, doc("k"), { parentId: root.id }); const out = await mk(ws, `${PFX} tm outside`, doc("o"));173  const { relation: old } = await createRelation(ws, { fromId: kid.id, toId: out.id, relType: "supports", validTo: new Date(Date.now() + 3600_000) });174  await db.update(schema.knowledgeEdges).set({ createdAt: new Date(Date.now() - 86_400_000), decidedAt: new Date(Date.now() - 86_400_000) }).where(eq(schema.knowledgeEdges.id, old.id));175  const ref = await createReference(ws, { title: `${PFX} tm ref`, pageId: kid.id }); made.references.push(ref.id);176  await sleep(20); const at = new Date(); await sleep(20);177  const { relation: later } = await createRelation(ws, { fromId: root.id, toId: out.id, relType: "extends" }); const late = await mk(ws, `${PFX} tm late kid`, doc("l"), { parentId: root.id });178  const { relation: expired } = await createRelation(ws, { fromId: kid.id, toId: out.id, relType: "contradicts", validTo: new Date(Date.now() - 3 * 86_400_000) });179  await db.update(schema.knowledgeEdges).set({ createdAt: new Date(Date.now() - 5 * 86_400_000), decidedAt: new Date(Date.now() - 5 * 86_400_000) }).where(eq(schema.knowledgeEdges.id, expired.id));180  const s = await stateAt(ws, at, { projectId: root.id });181  assert.deepEqual(s.scope, { projectId: root.id }); assert.deepEqual(s.pages.map((x) => [x.id, x.existed]), [[root.id, true], [kid.id, true], [late.id, false]]); assert.equal(s.pages[0].content, undefined, "no content for a project unless asked");182  assert.deepEqual(s.relations.map((r) => r.id), [old.id], "created by then, accepted by then, valid at that date — not the later one, not the expired one"); assert.equal(s.relations[0].toTitle, `${PFX} tm outside`);183  assert.deepEqual(s.references.map((r) => r.id), [ref.id]);184  assert.equal((await stateAt(ws, at, { projectId: root.id }, { content: true })).pages[1].content !== undefined, true);185  await deleteRelation(ws, old.id); const after = await stateAt(ws, at, { projectId: root.id }); assert.equal(after.relations.length, 0); assert.ok(after.removedSince.some((e) => e.kind === "relation.removed" && (e.data as any).relationId === old.id), "what was removed since is taken from the journal");186  assert.ok(after.journalSince, "the date since which the journal is complete is given"); await db.delete(schema.knowledgeEdges).where(inArray(schema.knowledgeEdges.id, [later.id, expired.id]));187});188
Files main
Menu

Theme