Files
support_backend/tests/integration/knowledge-retrieval.test.ts
T
saqib mirandClaude Sonnet 5 e33d86081f feat: implement product knowledge management & retrieval (004)
Implements 26 of 28 tasks from specs/004-product-knowledge/tasks.md
across all three user stories -- Phase 3 of the roadmap. First
feature to populate src/modules/ai-support/ (doc 07 places
`knowledge` there; only that submodule is built, matching this
codebase's convention of not pre-building unneeded submodules).

Schema (prisma/schema.prisma + migration):
- KnowledgeEntry, ErrorCode, KnownIssue, Runbook per docs/06,
  refining its conceptual flat `version` field into an explicit
  version-history mechanism: each edit inserts a new row
  (isCurrentVersion flag, compound unique on (code, version) /
  (key, productId, version)) instead of overwriting in place -- the
  only way "prior versions remain retrievable" (FR-004/FR-009) is
  actually true rather than aspirational.

User Story 1 -- knowledge entry authoring/publish/version (P1, MVP):
- draft -> published -> unpublished lifecycle; publish only takes
  effect from its effectiveDate.
- Editing uses the same conditional-update-then-insert optimistic
  concurrency pattern as 003-ticketing's Ticket.version (409 on a
  stale expectedVersion).
- Full version history readable via GET .../versions.

User Story 2 -- error codes, known issues, runbooks (P2):
- ErrorCode + KnownIssue with direct lookup-by-error-code.
- Runbook steps stored as an ordered JSON array, preserved exactly;
  same version-on-edit mechanism as knowledge entries; inactive
  runbooks are indistinguishable from nonexistent ones on lookup.

User Story 3 -- filtered retrieval (P3):
- GET /knowledge/retrieve: product-scoped, excludes draft/
  unpublished/not-yet-effective entries, validated entries ranked
  ahead of unvalidated. Deliberately NOT semantic/vector search --
  doc 11 gap B1 explicitly defers embedding-model choice to the
  future AI-support feature; this is real, usable structured
  filtering a semantic layer can sit in front of later.

Found and fixed one real bug before it reached tests: the retrieval
endpoint initially queried by the raw external product id instead of
resolving it to the internal Product.id first (every other endpoint
in this feature does that resolution) -- would have silently
returned zero results for every caller. Fixed with a lenient
tryResolveProductId (empty array, not 404, for an unregistered
product -- matches the "no matches, never an error" contract).

Deliberately skipped (not forgotten, see checklist notes): the two
planned mock-repository unit-test tasks (T004, T019) -- unlike
003-ticketing's state machine, this feature has no pure-logic
surface to isolate from Prisma; coverage comes entirely from
integration tests instead.

All 13 integration test files in the repo (36 tests, spanning this
feature and every prior one) verified passing together against a
real Postgres/Redis/MinIO -- no regressions. Full quality gate
(typecheck/lint/format/architecture/unit tests) passes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 15:55:18 +05:30

89 lines
3.3 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { buildApp } from '@/app';
import { prismaClient } from '@/infrastructure/database';
import { FastifyInstance } from 'fastify';
/** Covers specs/004-product-knowledge/quickstart.md Scenario 6 against a real Postgres. */
describe('Knowledge retrieval — scoping and ranking', () => {
let app: FastifyInstance;
const productAId = `TEST_RETRIEVE_A_${Date.now()}`;
const productBId = `TEST_RETRIEVE_B_${Date.now()}`;
const codes: string[] = [];
beforeAll(async () => {
app = await buildApp();
await prismaClient.product.create({
data: { externalProductId: productAId, name: 'Product A', status: 'active' },
});
await prismaClient.product.create({
data: { externalProductId: productBId, name: 'Product B', status: 'active' },
});
});
afterAll(async () => {
await prismaClient.knowledgeEntry.deleteMany({ where: { code: { in: codes } } });
await prismaClient.product.deleteMany({
where: { externalProductId: { in: [productAId, productBId] } },
});
await app.close();
});
async function createAndPublish(externalProductId: string, code: string) {
codes.push(code);
await app.inject({
method: 'POST',
url: `/admin/products/${externalProductId}/knowledge`,
payload: { code, type: 'faq', problem: `problem for ${code}` },
});
await app.inject({ method: 'PATCH', url: `/admin/knowledge/${code}/publish` });
}
it("never returns another product's entries", async () => {
const codeA = `KB-A-${Date.now()}`;
const codeB = `KB-B-${Date.now()}`;
await createAndPublish(productAId, codeA);
await createAndPublish(productBId, codeB);
const response = await app.inject({
method: 'GET',
url: `/knowledge/retrieve?productId=${productAId}`,
});
const returnedCodes = response.json().data.map((e: { code: string }) => e.code);
expect(returnedCodes).toContain(codeA);
expect(returnedCodes).not.toContain(codeB);
});
it('ranks a validated entry ahead of an equally-matching unvalidated one', async () => {
const validatedCode = `KB-VALID-${Date.now()}`;
const unvalidatedCode = `KB-UNVALID-${Date.now()}`;
await createAndPublish(productAId, validatedCode);
await createAndPublish(productAId, unvalidatedCode);
await app.inject({
method: 'PATCH',
url: `/admin/knowledge/${validatedCode}/validate`,
payload: { validationStatus: 'validated' },
});
const response = await app.inject({
method: 'GET',
url: `/knowledge/retrieve?productId=${productAId}`,
});
const returnedCodes = response.json().data.map((e: { code: string }) => e.code);
const validatedIndex = returnedCodes.indexOf(validatedCode);
const unvalidatedIndex = returnedCodes.indexOf(unvalidatedCode);
expect(validatedIndex).toBeGreaterThanOrEqual(0);
expect(unvalidatedIndex).toBeGreaterThanOrEqual(0);
expect(validatedIndex).toBeLessThan(unvalidatedIndex);
});
it('returns an empty array, never an error, when nothing matches', async () => {
const response = await app.inject({
method: 'GET',
url: `/knowledge/retrieve?productId=TEST_NEVER_REGISTERED_${Date.now()}`,
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual([]);
});
});