Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test(database): 100% coverage for models/expertise (#21829)

Arvin Xuc7e726f2aa6c
diff --git a/packages/database/src/models/__tests__/expertise.guards.test.ts b/packages/database/src/models/__tests__/expertise.guards.test.ts
new file mode 100644
index 00000000000..e5da22e362f
--- /dev/null
+++ b/packages/database/src/models/__tests__/expertise.guards.test.ts
@@ -0,0 +1,403 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ expertiseBindings,
+ expertiseDomains,
+ expertiseDomainSnapshots,
+ expertiseHits,
+ expertiseInsights,
+ expertiseLessons,
+ expertiseRuns,
+ topics,
+ users,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ExpertiseModel } from '../expertise';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'expertise-guards-user';
+const otherUserId = 'expertise-guards-other';
+const domainId = 'expertise-guards-domain';
+const foreignDomainId = 'expertise-guards-foreign-domain';
+
+const model = () => new ExpertiseModel(serverDB, userId);
+
+const seedDomain = async (
+ id: string,
+ overrides: Partial<typeof expertiseDomains.$inferInsert> = {},
+) => {
+ await serverDB.insert(expertiseDomains).values({
+ anchorChosenAt: new Date(),
+ domainFilter: `${id} filter`,
+ id,
+ slug: id,
+ title: `${id} title`,
+ userId,
+ ...overrides,
+ });
+};
+
+const seedRun = async (
+ runIndex: number,
+ overrides: Partial<typeof expertiseRuns.$inferInsert> = {},
+) => {
+ const [run] = await serverDB
+ .insert(expertiseRuns)
+ .values({
+ actorId: 'agent-1',
+ actorType: 'agent',
+ domainId,
+ runIndex,
+ subjectId: `topic-${runIndex}`,
+ subjectType: 'topic',
+ userId,
+ ...overrides,
+ })
+ .returning();
+ return run;
+};
+
+const seedLesson = async (
+ code: string,
+ overrides: Partial<typeof expertiseLessons.$inferInsert> = {},
+) => {
+ const [lesson] = await serverDB
+ .insert(expertiseLessons)
+ .values({
+ code,
+ domainId,
+ polarity: 'rule',
+ sections: [{ body: code, key: 'rule' }],
+ title: code,
+ ...overrides,
+ })
+ .returning();
+ return lesson;
+};
+
+const cleanup = async () => {
+ // Domains, runs, lessons, hits, snapshots, insights and agents all cascade from the users.
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+};
+
+beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(cleanup);
+
+describe('ExpertiseModel read guards', () => {
+ it('answers an empty domain list without querying', async () => {
+ const m = model();
+
+ expect(await m.latestSnapshots([])).toEqual([]);
+ expect(await m.seriesForDomains([])).toEqual([]);
+ expect(await m.reliabilitySeries([])).toEqual([]);
+ expect(await m.listLessonsWithRecent([])).toEqual([]);
+ expect(await m.actorsByDomain([])).toEqual([]);
+ expect(await m.listInsights([])).toEqual([]);
+ });
+
+ it('lists nothing for an agent the caller cannot see', async () => {
+ await serverDB
+ .insert(agents)
+ .values({ id: 'expertise-guards-foreign-agent', userId: otherUserId });
+
+ expect(await model().listDomainsForAgent('expertise-guards-foreign-agent')).toEqual([]);
+ expect(await model().listDomainsForAgent('expertise-guards-missing-agent')).toEqual([]);
+ });
+
+ it('resolves agent, project and always-on domains', async () => {
+ await serverDB.insert(agents).values({ id: 'expertise-guards-agent', userId });
+ await seedDomain(domainId);
+ await seedDomain('expertise-guards-agent-domain');
+ await serverDB.insert(expertiseBindings).values([
+ { boundUserId: userId, domainId },
+ { agentId: 'expertise-guards-agent', domainId: 'expertise-guards-agent-domain' },
+ ]);
+
+ const forAgent = await model().listDomainsForAgent('expertise-guards-agent');
+ const forProject = await model().listDomainsForProject('expertise-guards-missing-project');
+
+ expect(forAgent.map(({ domain }) => domain.id).sort()).toEqual(
+ ['expertise-guards-agent-domain', domainId].sort(),
+ );
+ expect(forProject.map(({ domain }) => domain.id)).toEqual([domainId]);
+ });
+
+ it('reads the latest snapshot, the series and the human flags of a domain', async () => {
+ await seedDomain(domainId);
+ const first = await seedRun(1, { hadHumanInLoop: true });
+ const second = await seedRun(2);
+ await serverDB.insert(expertiseDomainSnapshots).values([
+ { activeCount: 1, domainId, learnedTotal: 1, runId: first.id, runIndex: 1 },
+ { activeCount: 3, domainId, learnedTotal: 3, runId: second.id, runIndex: 2 },
+ ]);
+
+ const m = model();
+ const [latest] = await m.latestSnapshots([domainId]);
+ const series = await m.seriesForDomains([domainId]);
+ const snapshots = await m.listSnapshots(domainId);
+ const runs = await m.listRuns(domainId, 1);
+ const flags = await m.runHumanFlags(domainId);
+
+ expect(latest).toMatchObject({ activeCount: 3, runIndex: 2 });
+ expect(series).toEqual([
+ { activeCount: 1, domainId, runIndex: 1 },
+ { activeCount: 3, domainId, runIndex: 2 },
+ ]);
+ expect(snapshots.map(({ runIndex }) => runIndex)).toEqual([1, 2]);
+ expect(runs.map(({ runIndex }) => runIndex)).toEqual([2]);
+ expect(await m.countRuns(domainId)).toBe(2);
+ expect(flags).toEqual([
+ { hadHumanInLoop: true, runIndex: 1 },
+ { hadHumanInLoop: false, runIndex: 2 },
+ ]);
+ });
+
+ it('counts runs and lessons of an empty domain as zero', async () => {
+ await seedDomain(domainId);
+
+ expect(await model().countRuns(domainId)).toBe(0);
+ expect(await model().lessonStats(domainId)).toEqual({ hits: 0, total: 0, unused: 0 });
+ });
+
+ it('falls back to zero when an aggregate returns no row', async () => {
+ await seedDomain(domainId);
+ await seedRun(1);
+ await seedLesson('P-01', { hitCount: 2 });
+ // An aggregate without GROUP BY always yields one row in Postgres; the fallbacks guard a
+ // driver that drops it, so the seam strips the rows of the aggregate queries only.
+ const db = createProxyTestDB(serverDB, (query, result) =>
+ /count\(\*\)/.test(query) ? [] : result.rows,
+ );
+ const m = new ExpertiseModel(db, userId);
+
+ expect(await m.countRuns(domainId)).toBe(0);
+ expect(await m.lessonStats(domainId)).toEqual({ hits: 0, total: 0, unused: 0 });
+ });
+
+ it('summarizes active lessons and leaves out retired ones', async () => {
+ await seedDomain(domainId);
+ await seedLesson('P-01', { hitCount: 3 });
+ await seedLesson('P-02', { hitCount: 0 });
+ await seedLesson('P-03', { hitCount: 9, status: 'retired' });
+
+ expect(await model().lessonStats(domainId)).toEqual({ hits: 3, total: 2, unused: 1 });
+ });
+
+ it('ranks lessons into tiers and filters them by layer and title', async () => {
+ await seedDomain(domainId);
+ await seedLesson('P-01', { hitCount: 10, layer: 'craft', title: 'Use tokens for colour' });
+ await seedLesson('P-02', { hitCount: 1, layer: 'craft', title: 'Name the colour scale' });
+ await seedLesson('P-03', { hitCount: 0, layer: 'taste', title: 'Prefer calm motion' });
+
+ const all = await model().listLessons(domainId);
+ const craft = await model().listLessons(domainId, { layer: 'craft' });
+ const searched = await model().listLessons(domainId, { search: 'colour' });
+
+ expect(all.map(({ code, tier }) => [code, tier])).toEqual([
+ ['P-01', 'core'],
+ ['P-02', 'niche'],
+ ['P-03', 'unused'],
+ ]);
+ expect(craft.map(({ code }) => code)).toEqual(['P-01', 'P-02']);
+ expect(searched.map(({ code }) => code)).toEqual(['P-01', 'P-02']);
+ });
+
+ it('does not list the lessons of another user domain', async () => {
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ await seedLesson('P-01', { domainId: foreignDomainId });
+
+ expect(await model().listLessons(foreignDomainId)).toEqual([]);
+ });
+
+ it('counts lessons by layer and by canon anchor, unanchored ones apart', async () => {
+ await seedDomain(domainId);
+ await seedLesson('P-01', { canonAnchor: 'contrast', layer: 'craft' });
+ await seedLesson('P-02', { canonAnchor: 'contrast', layer: 'craft' });
+ await seedLesson('P-03');
+
+ expect(await model().layerCounts(domainId)).toEqual({ craft: 2 });
+ expect(await model().canonAnchorCounts(domainId)).toEqual({
+ byKey: { contrast: 2 },
+ unanchored: 1,
+ });
+ });
+
+ it('reports no unanchored lessons when every lesson has an anchor', async () => {
+ await seedDomain(domainId);
+ await seedLesson('P-01', { canonAnchor: 'contrast' });
+
+ expect(await model().canonAnchorCounts(domainId)).toEqual({
+ byKey: { contrast: 1 },
+ unanchored: 0,
+ });
+ });
+
+ it('lists recent outcomes per lesson, newest last, with the topic they happened in', async () => {
+ await seedDomain(domainId);
+ await serverDB
+ .insert(topics)
+ .values({ id: 'expertise-guards-topic', title: 'Release checklist', userId });
+ const run1 = await seedRun(1, { subjectId: 'expertise-guards-topic' });
+ const run2 = await seedRun(2, {
+ subjectId: 'expertise-guards-standalone',
+ subjectType: 'standalone',
+ });
+ const run3 = await seedRun(3, { reflectionKey: 'material:document:doc-1' });
+ const hit = await seedLesson('P-01', { hitCount: 2 });
+ const quiet = await seedLesson('P-02', { createdByUserId: userId });
+ await serverDB.insert(expertiseHits).values([
+ { domainId, lessonId: hit.id, outcome: 'violation', runId: run1.id },
+ { domainId, lessonId: hit.id, outcome: 'pass', runId: run2.id },
+ // A material quote is not practice and stays out of the recent outcomes.
+ { domainId, lessonId: hit.id, outcome: 'pass', runId: run3.id },
+ ]);
+
+ const rows = await model().listLessonsWithRecent([domainId], 1);
+ const full = await model().listLessonsWithRecent([domainId]);
+
+ expect(rows.find(({ id }) => id === hit.id)?.recent).toEqual([
+ {
+ pass: true,
+ runIndex: 2,
+ subjectId: 'expertise-guards-standalone',
+ subjectTitle: null,
+ subjectType: 'standalone',
+ },
+ ]);
+ expect(
+ full
+ .find(({ id }) => id === hit.id)
+ ?.recent.map(({ pass, subjectTitle }) => [pass, subjectTitle]),
+ ).toEqual([
+ [false, 'Release checklist'],
+ [true, null],
+ ]);
+ expect(full.find(({ id }) => id === quiet.id)).toMatchObject({
+ recent: [],
+ taughtByUser: true,
+ });
+ expect(full.find(({ id }) => id === hit.id)?.taughtByUser).toBe(false);
+ });
+
+ it('builds the reliability series and the agents that practised a domain', async () => {
+ await seedDomain(domainId);
+ const run1 = await seedRun(1, { actorId: 'agent-a' });
+ const run2 = await seedRun(2, { actorId: userId, actorType: 'user' });
+ const lesson = await seedLesson('P-01');
+ await serverDB.insert(expertiseHits).values([
+ { domainId, lessonId: lesson.id, outcome: 'violation', runId: run1.id },
+ { domainId, lessonId: lesson.id, outcome: 'pass', runId: run1.id },
+ { domainId, lessonId: lesson.id, outcome: 'pass', runId: run2.id },
+ ]);
+
+ expect(await model().reliabilitySeries([domainId])).toEqual([
+ { domainId, pass: 1, runIndex: 1, violation: 1 },
+ { domainId, pass: 1, runIndex: 2, violation: 0 },
+ ]);
+ expect(await model().actorsByDomain([domainId])).toEqual([{ actorId: 'agent-a', domainId }]);
+ });
+
+ it('lists the evidence of a lesson, titled by its topic or else its subject', async () => {
+ await seedDomain(domainId);
+ await serverDB
+ .insert(topics)
+ .values({ id: 'expertise-guards-topic', title: 'Release checklist', userId });
+ const run1 = await seedRun(1, { subjectId: 'expertise-guards-topic' });
+ const run2 = await seedRun(2, { subjectId: 'doc-7', subjectType: 'document' });
+ const lesson = await seedLesson('P-01');
+ await serverDB.insert(expertiseHits).values([
+ {
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ domainId,
+ lessonId: lesson.id,
+ outcome: 'violation',
+ runId: run1.id,
+ },
+ {
+ createdAt: new Date('2026-01-02T00:00:00Z'),
+ domainId,
+ lessonId: lesson.id,
+ outcome: 'pass',
+ runId: run2.id,
+ },
+ ]);
+
+ const hits = await model().listLessonHits(lesson.id);
+ const limited = await model().listLessonHits(lesson.id, 1);
+ const foreign = await new ExpertiseModel(serverDB, otherUserId).listLessonHits(lesson.id);
+
+ expect(hits.map(({ runTitle }) => runTitle)).toEqual(['doc-7', 'Release checklist']);
+ expect(limited).toHaveLength(1);
+ expect(foreign).toEqual([]);
+ });
+
+ it('lists active insights in scope, including ones without a domain, and dismisses one', async () => {
+ await seedDomain(domainId);
+ const [scoped, unscoped, dismissed, foreign] = await serverDB
+ .insert(expertiseInsights)
+ .values([
+ {
+ body: 'b',
+ confidence: 0.9,
+ domainId,
+ headline: 'scoped',
+ kind: 'repeated-mistake',
+ userId,
+ },
+ { body: 'b', confidence: 0.5, headline: 'unscoped', kind: 'repeated-mistake', userId },
+ {
+ body: 'b',
+ domainId,
+ headline: 'dismissed',
+ kind: 'repeated-mistake',
+ status: 'dismissed',
+ userId,
+ },
+ { body: 'b', headline: 'foreign', kind: 'repeated-mistake', userId: otherUserId },
+ ])
+ .returning();
+
+ const listed = await model().listInsights([domainId]);
+ await model().dismissInsight(scoped.id);
+ await model().dismissInsight(foreign.id, 'not mine');
+ const after = await serverDB
+ .select({ id: expertiseInsights.id, status: expertiseInsights.status })
+ .from(expertiseInsights)
+ .where(inArray(expertiseInsights.id, [scoped.id, foreign.id]));
+
+ expect(listed.map(({ id }) => id)).toEqual([scoped.id, unscoped.id]);
+ expect(dismissed.status).toBe('dismissed');
+ expect(Object.fromEntries(after.map(({ id, status }) => [id, status]))).toEqual({
+ [foreign.id]: 'active',
+ [scoped.id]: 'dismissed',
+ });
+ });
+
+ it('keeps only the first binding of a domain mounted at several levels', async () => {
+ await serverDB.insert(agents).values({ id: 'expertise-guards-agent', userId });
+ await seedDomain(domainId);
+ await serverDB.insert(expertiseBindings).values([
+ { boundUserId: userId, domainId, sortOrder: 1 },
+ { agentId: 'expertise-guards-agent', domainId, sortOrder: 0 },
+ ]);
+
+ const rows = await model().listDomainsForAgent('expertise-guards-agent');
+ const [binding] = await serverDB
+ .select({ id: expertiseBindings.id })
+ .from(expertiseBindings)
+ .where(eq(expertiseBindings.agentId, 'expertise-guards-agent'));
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].binding.id).toBe(binding.id);
+ });
+});
diff --git a/packages/database/src/models/__tests__/expertise.lineage.guards.test.ts b/packages/database/src/models/__tests__/expertise.lineage.guards.test.ts
new file mode 100644
index 00000000000..6c34df71c34
--- /dev/null
+++ b/packages/database/src/models/__tests__/expertise.lineage.guards.test.ts
@@ -0,0 +1,252 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ expertiseBindings,
+ expertiseDomains,
+ expertiseHits,
+ expertiseLessons,
+ expertiseRuns,
+ projects,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ExpertiseModel } from '../expertise';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'expertise-lineage-user';
+const otherUserId = 'expertise-lineage-other';
+const workspaceId = 'expertise-lineage-workspace';
+const domainId = 'expertise-lineage-domain';
+const foreignDomainId = 'expertise-lineage-foreign-domain';
+
+const model = () => new ExpertiseModel(serverDB, userId);
+
+const seedDomain = async (
+ id: string,
+ overrides: Partial<typeof expertiseDomains.$inferInsert> = {},
+) => {
+ await serverDB.insert(expertiseDomains).values({
+ anchorChosenAt: new Date(),
+ domainFilter: `${id} filter`,
+ id,
+ slug: id,
+ title: `${id} title`,
+ userId,
+ ...overrides,
+ });
+};
+
+const seedLesson = async (
+ code: string,
+ overrides: Partial<typeof expertiseLessons.$inferInsert> = {},
+) => {
+ const [lesson] = await serverDB
+ .insert(expertiseLessons)
+ .values({
+ code,
+ domainId,
+ polarity: 'rule',
+ sections: [{ body: code, key: 'rule' }],
+ title: code,
+ ...overrides,
+ })
+ .returning();
+ return lesson;
+};
+
+const seedRun = async (
+ runIndex: number,
+ overrides: Partial<typeof expertiseRuns.$inferInsert> = {},
+) => {
+ const [run] = await serverDB
+ .insert(expertiseRuns)
+ .values({
+ actorId: 'agent-1',
+ actorType: 'agent',
+ domainId,
+ runIndex,
+ subjectId: `topic-${runIndex}`,
+ subjectType: 'topic',
+ userId,
+ ...overrides,
+ })
+ .returning();
+ return run;
+};
+
+const cleanup = async () => {
+ // Workspaces, projects, agents and every expertise row cascade from the users.
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+};
+
+beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(cleanup);
+
+describe('ExpertiseModel lineage', () => {
+ it('reads no sources and no runs for a rule outside the caller scope', async () => {
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const foreign = await seedLesson('P-01', { domainId: foreignDomainId });
+
+ expect(await model().listLessonSources(foreign.id)).toEqual([]);
+ expect(await model().countLineageRuns(foreign.id)).toBe(0);
+ });
+
+ it('follows merges and moves through a cycle and past a parent out of scope', async () => {
+ await seedDomain(domainId);
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const outOfScope = await seedLesson('P-01', { domainId: foreignDomainId });
+ const a = await seedLesson('P-01');
+ const b = await seedLesson('P-02', { generalizedFromIds: [a.id, outOfScope.id] });
+ const root = await seedLesson('P-03', { generalizedFromIds: [b.id], salvagedFromId: a.id });
+ // A malformed lineage that points back at the root must still terminate.
+ await serverDB
+ .update(expertiseLessons)
+ .set({ salvagedFromId: root.id })
+ .where(inArray(expertiseLessons.id, [a.id]));
+ const run1 = await seedRun(1);
+ const run2 = await seedRun(2);
+ await serverDB.insert(expertiseHits).values([
+ { domainId, lessonId: a.id, outcome: 'violation', runId: run1.id },
+ { domainId, lessonId: b.id, outcome: 'violation', runId: run1.id },
+ { domainId, lessonId: root.id, outcome: 'violation', runId: run2.id },
+ ]);
+
+ const sources = await model().listLessonSources(root.id);
+
+ expect(sources).toHaveLength(3);
+ expect(await model().countLineageRuns(root.id)).toBe(2);
+ expect(await model().countLineageRuns(b.id)).toBe(2);
+ });
+
+ it('counts lineage runs as zero when the aggregate returns no row', async () => {
+ await seedDomain(domainId);
+ const lesson = await seedLesson('P-01');
+ // A `count(distinct …)` without GROUP BY always yields a row; the seam drops it to reach the
+ // fallback a driver returning nothing would take.
+ const db = createProxyTestDB(serverDB, (query, result) =>
+ /count\(distinct/.test(query) ? [] : result.rows,
+ );
+
+ expect(await new ExpertiseModel(db, userId).countLineageRuns(lesson.id)).toBe(0);
+ });
+});
+
+describe('ExpertiseModel rule listing', () => {
+ it('lists nothing when the caller has no groups', async () => {
+ expect(await model().listRules()).toEqual([]);
+ });
+
+ it('lists an empty group with no rules and its reviewer scope', async () => {
+ await seedDomain(domainId);
+ await serverDB.insert(expertiseBindings).values({ boundUserId: userId, domainId });
+
+ expect(await model().listRules()).toEqual([
+ {
+ domain: {
+ domainFilter: `${domainId} filter`,
+ id: domainId,
+ outOfScope: null,
+ title: `${domainId} title`,
+ },
+ owner: { kind: 'mine' },
+ rules: [],
+ scopes: [{ id: userId, kind: 'user', title: null }],
+ },
+ ]);
+ });
+
+ it('names every scope a group reaches and counts a rule without hits as zero', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Workspace',
+ primaryOwnerId: userId,
+ slug: 'expertise-lineage-ws',
+ });
+ await serverDB
+ .insert(agents)
+ .values({ id: 'expertise-lineage-agent', title: 'Scout', userId, workspaceId });
+ await serverDB
+ .insert(projects)
+ .values({ id: 'expertise-lineage-project', name: 'Launch', userId, workspaceId });
+ await seedDomain(domainId, { workspaceId });
+ await serverDB.insert(expertiseBindings).values([
+ { boundWorkspaceId: workspaceId, domainId, sortOrder: 0 },
+ { domainId, projectId: 'expertise-lineage-project', sortOrder: 1 },
+ { agentId: 'expertise-lineage-agent', domainId, sortOrder: 2 },
+ ]);
+ const lesson = await seedLesson('P-01', { createdByUserId: userId });
+
+ const [group] = await new ExpertiseModel(serverDB, userId, workspaceId).listRules();
+
+ expect(group.owner).toEqual({ kind: 'mine' });
+ expect(group.scopes).toEqual([
+ { id: workspaceId, kind: 'workspace', title: null },
+ { id: 'expertise-lineage-project', kind: 'project', title: 'Launch' },
+ { id: 'expertise-lineage-agent', kind: 'agent', title: 'Scout' },
+ ]);
+ expect(group.rules).toEqual([
+ expect.objectContaining({
+ authored: true,
+ conversationHitCount: 0,
+ id: lesson.id,
+ materialHitCount: 0,
+ rejectionHitCount: 0,
+ }),
+ ]);
+ });
+
+ it("orders agents' groups by agent after the reviewer's, and drops a group only an invisible agent holds", async () => {
+ await serverDB.insert(agents).values([
+ { id: 'expertise-lineage-agent-a', title: 'A', userId },
+ { id: 'expertise-lineage-agent-b', title: 'B', userId },
+ { id: 'expertise-lineage-foreign-agent', userId: otherUserId },
+ ]);
+ for (const id of ['d-a1', 'd-b', 'd-a2', 'd-mine', 'd-hidden'])
+ await seedDomain(`expertise-lineage-${id}`);
+ await serverDB.insert(expertiseBindings).values([
+ { agentId: 'expertise-lineage-agent-a', domainId: 'expertise-lineage-d-a1', sortOrder: 0 },
+ { agentId: 'expertise-lineage-agent-b', domainId: 'expertise-lineage-d-b', sortOrder: 1 },
+ { agentId: 'expertise-lineage-agent-a', domainId: 'expertise-lineage-d-a2', sortOrder: 2 },
+ { boundUserId: userId, domainId: 'expertise-lineage-d-mine', sortOrder: 3 },
+ {
+ agentId: 'expertise-lineage-foreign-agent',
+ domainId: 'expertise-lineage-d-hidden',
+ sortOrder: 4,
+ },
+ ]);
+
+ const groups = await model().listRules();
+
+ expect(
+ groups.map(({ domain, owner }) => [
+ domain.id,
+ owner.kind === 'agent' ? owner.agent.id : 'mine',
+ ]),
+ ).toEqual([
+ ['expertise-lineage-d-mine', 'mine'],
+ ['expertise-lineage-d-a1', 'expertise-lineage-agent-a'],
+ ['expertise-lineage-d-a2', 'expertise-lineage-agent-a'],
+ ['expertise-lineage-d-b', 'expertise-lineage-agent-b'],
+ ]);
+ });
+
+ it('counts the undistilled backlog as zero when the aggregate returns no row', async () => {
+ const db = createProxyTestDB(serverDB, (query, result) =>
+ /count\(distinct/.test(query) ? [] : result.rows,
+ );
+
+ expect(await new ExpertiseModel(db, userId).countUndistilledRejectionRounds()).toBe(0);
+ expect(await model().countUndistilledRejectionRounds()).toBe(0);
+ });
+});
diff --git a/packages/database/src/models/__tests__/expertise.writes.guards.test.ts b/packages/database/src/models/__tests__/expertise.writes.guards.test.ts
new file mode 100644
index 00000000000..afd96b5c7ab
--- /dev/null
+++ b/packages/database/src/models/__tests__/expertise.writes.guards.test.ts
@@ -0,0 +1,617 @@
+// @vitest-environment node
+import { asc, eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ expertiseBindings,
+ expertiseDomains,
+ expertiseHits,
+ expertiseLessonRevisions,
+ expertiseLessons,
+ expertiseRuns,
+ projects,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ExpertiseModel } from '../expertise';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'expertise-writes-user';
+const otherUserId = 'expertise-writes-other';
+const workspaceId = 'expertise-writes-workspace';
+const domainId = 'expertise-writes-domain';
+const secondDomainId = 'expertise-writes-domain-2';
+const foreignDomainId = 'expertise-writes-foreign-domain';
+
+const model = () => new ExpertiseModel(serverDB, userId);
+
+const seedDomain = async (
+ id: string,
+ overrides: Partial<typeof expertiseDomains.$inferInsert> = {},
+) => {
+ await serverDB.insert(expertiseDomains).values({
+ anchorChosenAt: new Date(),
+ domainFilter: `${id} filter`,
+ id,
+ slug: id,
+ title: `${id} title`,
+ userId,
+ ...overrides,
+ });
+};
+
+const seedLesson = async (
+ code: string,
+ overrides: Partial<typeof expertiseLessons.$inferInsert> = {},
+) => {
+ const [lesson] = await serverDB
+ .insert(expertiseLessons)
+ .values({
+ code,
+ domainId,
+ polarity: 'rule',
+ sections: [{ body: code, key: 'rule' }],
+ title: code,
+ ...overrides,
+ })
+ .returning();
+ return lesson;
+};
+
+const readLesson = async (id: string) => {
+ const [row] = await serverDB.select().from(expertiseLessons).where(eq(expertiseLessons.id, id));
+ return row;
+};
+
+const cleanup = async () => {
+ // Workspaces, projects, agents and every expertise row cascade from the users.
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+};
+
+beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(cleanup);
+
+describe('ExpertiseModel domain writes', () => {
+ it('mounts a new domain on a project after the ones already there', async () => {
+ await serverDB
+ .insert(projects)
+ .values({ id: 'expertise-writes-project', name: 'Project', userId });
+
+ const first = await model().createDomain({
+ brief: ' Delivery bar ',
+ canonEntries: [
+ { key: 'contrast', source: 'WCAG', statement: 'Text must stand out', title: 'Contrast' },
+ ],
+ carrier: { id: 'expertise-writes-project', type: 'project' },
+ domainFilter: ' Is it a delivery? ',
+ layerCanonRef: 'canon-ref',
+ layerSource: 'canonical',
+ layers: [{ key: 'craft', title: 'Craft' }],
+ outOfScope: ' Drafts ',
+ rationale: ' Keeps the bar visible ',
+ title: ' Delivery Bar ',
+ });
+ const second = await model().createDomain({
+ brief: 'Second',
+ carrier: { id: 'expertise-writes-project', type: 'project' },
+ domainFilter: 'Second',
+ outOfScope: ' ',
+ rationale: ' ',
+ title: 'Second',
+ });
+
+ const [domain] = await serverDB
+ .select()
+ .from(expertiseDomains)
+ .where(eq(expertiseDomains.id, first));
+ const [blank] = await serverDB
+ .select()
+ .from(expertiseDomains)
+ .where(eq(expertiseDomains.id, second));
+ const bindings = await serverDB
+ .select({ domainId: expertiseBindings.domainId, sortOrder: expertiseBindings.sortOrder })
+ .from(expertiseBindings)
+ .where(eq(expertiseBindings.projectId, 'expertise-writes-project'))
+ .orderBy(asc(expertiseBindings.sortOrder));
+
+ expect(domain).toMatchObject({
+ description: 'Delivery bar',
+ domainFilter: 'Is it a delivery?',
+ layerSource: 'canonical',
+ outOfScope: 'Drafts',
+ title: 'Delivery Bar',
+ });
+ expect(domain.slug).toMatch(/^delivery-bar-/);
+ expect(domain.anchorCandidates).toEqual([
+ expect.objectContaining({
+ layerCanonRef: 'canon-ref',
+ outOfScope: 'Drafts',
+ rationale: 'Keeps the bar visible',
+ }),
+ ]);
+ expect(blank.outOfScope).toBeNull();
+ expect(blank.layerSource).toBe('invented');
+ expect(blank.anchorCandidates?.[0]).not.toHaveProperty('rationale', expect.anything());
+ expect(bindings).toEqual([
+ { domainId: first, sortOrder: 0 },
+ { domainId: second, sortOrder: 1 },
+ ]);
+ });
+
+ it('mounts an always-on domain on the workspace when one is in scope', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Workspace',
+ primaryOwnerId: userId,
+ slug: 'expertise-writes-ws',
+ });
+ const ws = new ExpertiseModel(serverDB, userId, workspaceId);
+
+ const id = await ws.createDomain({
+ brief: 'Team bar',
+ carrier: { type: 'user' },
+ domainFilter: 'Team',
+ title: 'Team bar',
+ });
+ const [binding] = await serverDB
+ .select()
+ .from(expertiseBindings)
+ .where(eq(expertiseBindings.domainId, id));
+ const listed = await ws.listDomainsForOwner();
+
+ expect(binding).toMatchObject({
+ boundUserId: null,
+ boundWorkspaceId: workspaceId,
+ sortOrder: 0,
+ });
+ expect(listed.map(({ domain }) => domain.id)).toEqual([id]);
+ expect(await model().listDomainsForOwner()).toEqual([]);
+ });
+
+ it('mounts a domain on an agent', async () => {
+ await serverDB.insert(agents).values({ id: 'expertise-writes-agent', userId });
+
+ const id = await model().createDomain({
+ brief: 'Agent bar',
+ carrier: { id: 'expertise-writes-agent', type: 'agent' },
+ domainFilter: 'Agent',
+ title: 'Agent bar',
+ });
+
+ const listed = await model().listDomainsForAgent('expertise-writes-agent');
+ expect(listed.map(({ domain }) => domain.id)).toEqual([id]);
+ });
+
+ it('deletes only a domain the caller owns', async () => {
+ await seedDomain(domainId);
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+
+ expect(await model().deleteDomain(foreignDomainId)).toBeNull();
+ expect(await model().deleteDomain(domainId)).toEqual({ id: domainId });
+ const left = await serverDB
+ .select({ id: expertiseDomains.id })
+ .from(expertiseDomains)
+ .where(inArray(expertiseDomains.id, [domainId, foreignDomainId]));
+ expect(left).toEqual([{ id: foreignDomainId }]);
+ });
+
+ it('compares reaches: the same domain, two unbound ones, and an agent against the reviewer', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'expertise-writes-agent', userId },
+ { id: 'expertise-writes-agent-2', userId },
+ ]);
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ await seedDomain('expertise-writes-agent-domain');
+ await seedDomain('expertise-writes-agent-domain-2');
+ await seedDomain('expertise-writes-mine');
+ await serverDB.insert(expertiseBindings).values([
+ { agentId: 'expertise-writes-agent', domainId: 'expertise-writes-agent-domain' },
+ { agentId: 'expertise-writes-agent-2', domainId: 'expertise-writes-agent-domain' },
+ { agentId: 'expertise-writes-agent-2', domainId: 'expertise-writes-agent-domain-2' },
+ { agentId: 'expertise-writes-agent', domainId: 'expertise-writes-agent-domain-2' },
+ { boundUserId: userId, domainId: 'expertise-writes-mine' },
+ // A disabled mount reaches nothing.
+ { boundUserId: userId, domainId: secondDomainId, enabled: false },
+ ]);
+
+ const m = model();
+ expect(await m.sameReach(domainId, domainId)).toBe(true);
+ expect(await m.sameReach(domainId, secondDomainId)).toBe(true);
+ expect(
+ await m.sameReach('expertise-writes-agent-domain', 'expertise-writes-agent-domain-2'),
+ ).toBe(true);
+ expect(await m.sameReach('expertise-writes-agent-domain', 'expertise-writes-mine')).toBe(false);
+ expect(await m.sameReach('expertise-writes-agent-domain', domainId)).toBe(false);
+ });
+
+ it('reuses a group whose name differs only in case and spacing', async () => {
+ const id = await model().createRuleGroup({ gate: 'Design?', title: 'Design System' });
+
+ const again = await model().createRuleGroup({ gate: 'Other', title: ' design system ' });
+ const other = await model().createRuleGroup({
+ gate: 'Copy?',
+ outOfScope: 'Ads',
+ title: 'Copywriting',
+ });
+
+ expect(again).toBe(id);
+ expect(other).not.toBe(id);
+ const [created] = await serverDB
+ .select({ outOfScope: expertiseDomains.outOfScope })
+ .from(expertiseDomains)
+ .where(eq(expertiseDomains.id, other));
+ expect(created.outOfScope).toBe('Ads');
+ });
+
+ it('updates a group only where the patch says so', async () => {
+ await seedDomain(domainId, { outOfScope: 'Drafts', title: 'Old' });
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const read = async () => {
+ const [row] = await serverDB
+ .select()
+ .from(expertiseDomains)
+ .where(eq(expertiseDomains.id, domainId));
+ return row;
+ };
+
+ expect(await model().updateRuleGroup(foreignDomainId, { title: 'Stolen' })).toBeNull();
+
+ expect(await model().updateRuleGroup(domainId, { gate: ' ', title: ' ' })).toEqual({
+ id: domainId,
+ });
+ expect(await read()).toMatchObject({
+ domainFilter: `${domainId} filter`,
+ outOfScope: 'Drafts',
+ title: 'Old',
+ });
+
+ await model().updateRuleGroup(domainId, {
+ gate: ' New gate ',
+ outOfScope: ' ',
+ title: ' New ',
+ });
+ expect(await read()).toMatchObject({
+ domainFilter: 'New gate',
+ outOfScope: null,
+ title: 'New',
+ });
+
+ await model().updateRuleGroup(domainId, { outOfScope: null });
+ expect((await read()).outOfScope).toBeNull();
+
+ await model().updateRuleGroup(domainId, { outOfScope: ' Ads ' });
+ expect((await read()).outOfScope).toBe('Ads');
+ });
+});
+
+describe('ExpertiseModel rule filing', () => {
+ it('refuses to file a rule into a domain the caller cannot see', async () => {
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+
+ expect(await model().createRule({ domainId: foreignDomainId, title: 'Nope' })).toBeNull();
+ });
+
+ it('files a rule with its sections and settings, numbered past non-standard codes', async () => {
+ await seedDomain(domainId);
+ await seedLesson('legacy', { sortOrder: null });
+
+ const rule = await model().createRule({
+ compilability: 'compilable',
+ direction: 'negative',
+ domainId,
+ enforcement: 'block',
+ how: ' Use the token ',
+ limits: ' ',
+ title: ' Never hard-code colours ',
+ why: ' Themes break ',
+ });
+
+ const row = await readLesson(rule!.id);
+ expect(rule!.code).toBe('P-01');
+ expect(row).toMatchObject({
+ compilability: 'compilable',
+ direction: 'negative',
+ enforcement: 'block',
+ // The only other row has no position yet, so the new one starts from the top.
+ sortOrder: 0,
+ title: 'Never hard-code colours',
+ });
+ expect(row.sections).toEqual([
+ { body: 'Never hard-code colours', key: 'rule' },
+ { body: 'Themes break', key: 'why' },
+ { body: 'Use the token', key: 'how' },
+ ]);
+ });
+
+ it('numbers a material run in the caller scope only, and keeps an empty quote as null', async () => {
+ await seedDomain(domainId);
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const lesson = await seedLesson('P-01');
+
+ expect(
+ await model().insertMaterialRun({
+ domainId: foreignDomainId,
+ reflectionKey: 'material:document:doc-x',
+ subjectId: 'doc-x',
+ subjectType: 'document',
+ }),
+ ).toBeNull();
+
+ const runId = await model().insertMaterialRun({
+ domainId,
+ reflectionKey: 'material:document:doc-1',
+ subjectId: 'doc-1',
+ subjectType: 'document',
+ });
+ const hitId = await model().insertMaterialHit({
+ domainId,
+ lessonId: lesson.id,
+ quote: '',
+ runId: runId!,
+ where: 'p. 1',
+ });
+
+ const [run] = await serverDB.select().from(expertiseRuns).where(eq(expertiseRuns.id, runId!));
+ const [hit] = await serverDB.select().from(expertiseHits).where(eq(expertiseHits.id, hitId));
+ expect(run).toMatchObject({ actorType: 'user', hadHumanInLoop: true, runIndex: 1 });
+ expect(hit).toMatchObject({ example: null, outcome: 'pass', where: 'p. 1' });
+ });
+
+ it('reorders a rule within its group, and refuses a foreign group or a stranger rule', async () => {
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const a = await seedLesson('P-01', { sortOrder: 0 });
+ const b = await seedLesson('P-02', { sortOrder: 1 });
+ const c = await seedLesson('P-03', { sortOrder: 2 });
+ const stranger = await seedLesson('P-01', { domainId: secondDomainId });
+
+ expect(await model().reorderRule(foreignDomainId, a.id, null)).toBeNull();
+ expect(await model().reorderRule(domainId, stranger.id, null)).toBeNull();
+
+ // To the end when there is nothing to go before.
+ expect(await model().reorderRule(domainId, a.id, null)).toEqual({
+ domainId,
+ order: [b.id, c.id, a.id],
+ });
+ // Also to the end when the anchor is not in the group.
+ expect(await model().reorderRule(domainId, b.id, stranger.id)).toEqual({
+ domainId,
+ order: [c.id, a.id, b.id],
+ });
+ expect(await model().reorderRule(domainId, b.id, c.id)).toEqual({
+ domainId,
+ order: [b.id, c.id, a.id],
+ });
+ expect((await readLesson(a.id)).sortOrder).toBe(2);
+ });
+});
+
+describe('ExpertiseModel rule moves', () => {
+ it('refuses a missing rule, a missing group and a rule that is not active', async () => {
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const lesson = await seedLesson('P-01');
+ const retired = await seedLesson('P-02', { status: 'retired' });
+
+ expect(await model().moveRule('00000000-0000-4000-8000-000000000000', domainId)).toBeNull();
+ expect(await model().moveRule(lesson.id, foreignDomainId)).toBeNull();
+ expect(await model().moveRule(lesson.id, domainId)).toEqual({ domainId, id: lesson.id });
+ expect(await model().moveRule(retired.id, secondDomainId)).toBeNull();
+ expect((await readLesson(retired.id)).domainId).toBe(domainId);
+ });
+
+ it('refuses to move a rule into a group with a different reach', async () => {
+ await serverDB.insert(agents).values({ id: 'expertise-writes-agent', userId });
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ await serverDB.insert(expertiseBindings).values([
+ { boundUserId: userId, domainId },
+ { agentId: 'expertise-writes-agent', domainId: secondDomainId },
+ ]);
+ const lesson = await seedLesson('P-01');
+
+ expect(await model().moveRule(lesson.id, secondDomainId)).toBeNull();
+ });
+
+ it('moves a rule without evidence in place, after the rules already in the target', async () => {
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ const lesson = await seedLesson('P-01');
+ await seedLesson('P-07', { domainId: secondDomainId, sortOrder: 4 });
+
+ expect(await model().moveRule(lesson.id, secondDomainId)).toEqual({
+ domainId: secondDomainId,
+ id: lesson.id,
+ });
+ expect(await readLesson(lesson.id)).toMatchObject({
+ code: 'P-08',
+ domainId: secondDomainId,
+ sortOrder: 5,
+ });
+ });
+
+ it('copies a rule with evidence into an empty target and hides the original', async () => {
+ await seedDomain(domainId);
+ await seedDomain(secondDomainId);
+ const lesson = await seedLesson('P-01');
+ const [run] = await serverDB
+ .insert(expertiseRuns)
+ .values({
+ actorId: 'agent-1',
+ actorType: 'agent',
+ domainId,
+ runIndex: 1,
+ subjectId: 'topic-1',
+ subjectType: 'topic',
+ })
+ .returning();
+ await serverDB
+ .insert(expertiseHits)
+ .values({ domainId, lessonId: lesson.id, outcome: 'violation', runId: run.id });
+
+ const moved = await model().moveRule(lesson.id, secondDomainId);
+
+ expect(moved!.id).not.toBe(lesson.id);
+ expect(await readLesson(moved!.id)).toMatchObject({
+ code: 'P-01',
+ domainId: secondDomainId,
+ salvagedFromId: lesson.id,
+ sortOrder: 0,
+ });
+ expect(await readLesson(lesson.id)).toMatchObject({
+ rejectedReason: `moved-to:${moved!.id}`,
+ status: 'rejected',
+ });
+ });
+});
+
+describe('ExpertiseModel lesson writes', () => {
+ it('refuses to teach, revise, restore or retire outside the caller scope', async () => {
+ await seedDomain(foreignDomainId, { userId: otherUserId });
+ const foreign = await seedLesson('P-01', { domainId: foreignDomainId });
+
+ expect(await model().teachLesson({ domainId: foreignDomainId, text: 'x' })).toBeNull();
+ expect(await model().reviseLesson(foreign.id, 'x')).toBeNull();
+ expect(await model().restoreLesson(foreign.id)).toBeNull();
+ expect(await model().retireLesson(foreign.id)).toBeNull();
+ expect(await model().lockLesson(foreign.id)).toBeUndefined();
+ expect(await model().findLesson(foreign.id)).toBeUndefined();
+ expect(await readLesson(foreign.id)).toMatchObject({ currentRevision: 1, status: 'active' });
+ });
+
+ it('teaches a long lesson under a shortened title, numbered past non-standard codes', async () => {
+ await seedDomain(domainId);
+ await seedLesson('legacy');
+ await seedLesson('P-03');
+ const text = 'a'.repeat(100);
+
+ const taught = await model().teachLesson({ domainId, text: ` ${text} ` });
+ const short = await model().teachLesson({ domainId, text: 'Short' });
+
+ expect(taught!.code).toBe('P-04');
+ expect((await readLesson(taught!.id)).title).toBe(`${'a'.repeat(79)}…`);
+ expect(await readLesson(short!.id)).toMatchObject({ code: 'P-05', title: 'Short' });
+ });
+
+ it('replaces the limits section on a revision and records it', async () => {
+ await seedDomain(domainId);
+ const lesson = await seedLesson('P-01', {
+ sections: [
+ { body: 'Rule', key: 'rule' },
+ { body: 'Old limit', key: 'limits' },
+ ],
+ });
+
+ expect(await model().reviseLesson(lesson.id, ' Not for drafts ')).toEqual({
+ id: lesson.id,
+ revision: 2,
+ });
+ expect((await readLesson(lesson.id)).sections).toEqual([
+ { body: 'Rule', key: 'rule' },
+ { body: 'Not for drafts', key: 'limits' },
+ ]);
+ const revisions = await model().listLessonRevisions(lesson.id);
+ expect(revisions).toEqual([
+ expect.objectContaining({ byViewer: true, feedback: 'Not for drafts', revision: 2 }),
+ ]);
+ });
+
+ it('stops following a salvage chain that loops back on itself', async () => {
+ await seedDomain(domainId);
+ const a = await seedLesson('P-01');
+ const b = await seedLesson('P-02', { salvagedFromId: a.id });
+ await serverDB
+ .update(expertiseLessons)
+ .set({ salvagedFromId: b.id })
+ .where(eq(expertiseLessons.id, a.id));
+ await serverDB.insert(expertiseLessonRevisions).values([
+ {
+ changedBy: 'user',
+ changedByUserId: otherUserId,
+ lessonId: a.id,
+ revision: 2,
+ sections: [],
+ },
+ { changedBy: 'agent', lessonId: b.id, revision: 2, sections: [] },
+ ]);
+
+ const revisions = await model().listLessonRevisions(b.id, 5);
+
+ expect(revisions.map(({ byViewer, changedBy }) => [changedBy, byViewer]).sort()).toEqual([
+ ['agent', false],
+ ['user', false],
+ ]);
+ });
+
+ it('restores a retired rule, but not one a merge folded in', async () => {
+ await seedDomain(domainId);
+ const retired = await seedLesson('P-01', { retiredAt: new Date(), status: 'retired' });
+ const merged = await seedLesson('P-02', {
+ rejectedReason: 'merged-into:someone',
+ status: 'rejected',
+ });
+
+ expect(await model().restoreLesson(merged.id)).toBeNull();
+ expect(await model().restoreLesson(retired.id)).toEqual({ id: retired.id });
+ expect(await readLesson(retired.id)).toMatchObject({ retiredAt: null, status: 'active' });
+ expect((await readLesson(merged.id)).status).not.toBe('active');
+ });
+
+ it('retires a rule and keeps its row', async () => {
+ await seedDomain(domainId);
+ const lesson = await seedLesson('P-01');
+
+ expect(await model().retireLesson(lesson.id)).toEqual({ id: lesson.id });
+ const row = await readLesson(lesson.id);
+ expect(row.status).toBe('retired');
+ expect(row.retiredAt).toBeInstanceOf(Date);
+ });
+
+ it('locks, revises and patches a lesson inside one transaction', async () => {
+ await seedDomain(domainId);
+ const lesson = await seedLesson('P-01');
+
+ await serverDB.transaction(async (tx) => {
+ const m = new ExpertiseModel(tx as unknown as LobeChatDatabase, userId);
+ const locked = await m.lockLesson(lesson.id);
+ await m.insertLessonRevision({
+ changedBy: 'user',
+ changedByUserId: userId,
+ lessonId: lesson.id,
+ revision: locked!.currentRevision + 1,
+ sections: locked!.sections,
+ });
+ await m.updateLessonFields(lesson.id, { currentRevision: 2, title: 'Patched' });
+ });
+
+ expect(await readLesson(lesson.id)).toMatchObject({ currentRevision: 2, title: 'Patched' });
+ expect((await model().listLessonRevisions(lesson.id)).map(({ revision }) => revision)).toEqual([
+ 2,
+ ]);
+ });
+
+ it('fills directions per kind and skips a kind nobody was judged as', async () => {
+ await seedDomain(domainId);
+ const open = await seedLesson('P-01');
+ const set = await seedLesson('P-02', { direction: 'negative' });
+
+ await model().fillLessonDirections([
+ { direction: 'positive', id: open.id },
+ { direction: 'positive', id: set.id },
+ ]);
+
+ expect((await readLesson(open.id)).direction).toBe('positive');
+ expect((await readLesson(set.id)).direction).toBe('negative');
+ });
+});
diff --git a/packages/database/src/models/expertise/lineage.ts b/packages/database/src/models/expertise/lineage.ts
index 3348bc89a03..3984784f4e4 100644
--- a/packages/database/src/models/expertise/lineage.ts
+++ b/packages/database/src/models/expertise/lineage.ts
@@ -109,7 +109,10 @@ export const listLessonSources = async (ctx: ExpertiseContext, lessonId: string,
* merge would otherwise keep the counts and lose the evidence.
*/
const resolveLineage = async (ctx: ExpertiseContext, lessonId: string): Promise<string[]> =>
- (await resolveLineages(ctx, [lessonId])).get(lessonId) ?? [];
+ (await resolveLineages(ctx, [lessonId])).get(lessonId) ??
+ /* v8 ignore start -- unreachable: the `[]` arm; resolveLineages maps every id it is given */
+ [];
+/* v8 ignore stop */
/**
* {@link resolveLineage} for many rules at once: one read per generation instead of one walk
@@ -136,9 +139,17 @@ const resolveLineages = async (ctx: ExpertiseContext, lessonIds: string[]) => {
...(row.salvagedFromId ? [row.salvagedFromId] : []),
]);
}
- frontier = [...new Set(rows.flatMap((row) => parents.get(row.id) ?? []))].filter(
- (id) => !parents.has(id),
- );
+ frontier = [
+ ...new Set(
+ rows.flatMap(
+ (row) =>
+ parents.get(row.id) ??
+ /* v8 ignore start -- unreachable: the `[]` arm; the loop above just set an entry for every row */
+ [],
+ /* v8 ignore stop */
+ ),
+ ),
+ ].filter((id) => !parents.has(id));
}
return new Map(
@@ -185,7 +196,11 @@ export const countHitsBySource = async (ctx: ExpertiseContext, lessonIds: string
return new Map(
lessonIds.map((id) => {
- const lineage = lineages.get(id) ?? [];
+ const lineage =
+ lineages.get(id) ??
+ /* v8 ignore start -- unreachable: the `[]` arm; resolveLineages maps every id in lessonIds */
+ [];
+ /* v8 ignore stop */
const sum = (key: 'conversations' | 'materials' | 'rejections') =>
lineage.reduce((total, member) => total + (byLesson.get(member)?.[key] ?? 0), 0);
return [
diff --git a/packages/database/src/models/expertise/rules.ts b/packages/database/src/models/expertise/rules.ts
index ced71ccd2ae..0fd42224a77 100644
--- a/packages/database/src/models/expertise/rules.ts
+++ b/packages/database/src/models/expertise/rules.ts
@@ -194,24 +194,32 @@ export const listRules = async (ctx: ExpertiseContext) => {
// reader uses for `taughtByUser`.
.map(({ originRunId, ...lesson }) => ({
...lesson,
+ /* v8 ignore start -- unreachable: the fallback; countHitsBySource maps every lesson id it was given, and it was given all of them */
...(bySource.get(lesson.id) ?? {
conversationHitCount: 0,
materialHitCount: 0,
rejectionHitCount: 0,
}),
+ /* v8 ignore stop */
authored: lesson.createdByUserId != null && originRunId == null,
})),
- scopes: (bindingsByDomain.get(domain.id) ?? []).map((binding) => {
- if (binding.projectId) {
- return { id: binding.projectId, kind: 'project' as const, title: binding.projectName };
- }
- if (binding.agentId) {
- return { id: binding.agentId, kind: 'agent' as const, title: binding.agentTitle };
- }
- return binding.boundWorkspaceId
- ? { id: binding.boundWorkspaceId, kind: 'workspace' as const, title: null }
- : { id: binding.boundUserId!, kind: 'user' as const, title: null };
- }),
+ scopes: (
+ bindingsByDomain.get(domain.id) ??
+ /* v8 ignore start -- unreachable: the `[]` arm; ownerOf keeps a group only when it has at least one visible binding */
+ []
+ )
+ /* v8 ignore stop */
+ .map((binding) => {
+ if (binding.projectId) {
+ return { id: binding.projectId, kind: 'project' as const, title: binding.projectName };
+ }
+ if (binding.agentId) {
+ return { id: binding.agentId, kind: 'agent' as const, title: binding.agentTitle };
+ }
+ return binding.boundWorkspaceId
+ ? { id: binding.boundWorkspaceId, kind: 'workspace' as const, title: null }
+ : { id: binding.boundUserId!, kind: 'user' as const, title: null };
+ }),
}));
};