mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 05:30:41 +01:00
/api/health has returned 503 because `public.consultations` does not exist. It
never did. Botsmann shares one self-hosted Supabase database with orangecat,
which owns `public` and its 128 tables; ours were nowhere, because all eleven
migrations were unapplied.
The schema half is fixed in the deploy pipeline (fleetcrown#398): botsmann now
declares `supabase:botsmann` and its migrations apply into a schema of its own,
exactly as printcraft's do. That has run — all 11 tags are recorded and the 12
tables exist.
This is the other half. A Supabase client that is not told the schema queries
`public`, so it would still get PGRST205. Measured against production just now:
GET /rest/v1/consultations -> 404 PGRST205
GET /rest/v1/consultations Accept-Profile: botsmann -> 200 []
`db: { schema }` is what sends that header, and it was missing from all four
client factories — anon, service-role, browser and route-handler.
The schema name is one constant in lib/constants.ts, not four literals. The
second copy is how the first goes stale, and this repo has just spent a day
proving what duplicated configuration costs.
Two things this also removes:
* `scripts/run-migration.ts` and `scripts/migrate-via-api.ts` applied SQL
through the service-role client with no schema set. They are from the era
when migrations were run by hand; now they would create our tables inside
orangecat's `public`. Schema is the pipeline's job, and a second way to do
it is a second way to do it wrong. Nothing references them.
* The bare `SupabaseClient` type hardcodes `'public'`, so annotating with it
silently asserts we query orangecat's tables — and rejects the client we
actually build. The type is now derived from the factory, which keeps the
two in step and survives supabase-js reordering its generics.
New test pins it per file, by count: every `createClient` call in a client file
must set the schema, from the shared constant, with comments stripped first so
the guard cannot be fooled by prose. Adding a fifth unscoped factory fails the
test instead of production. Mutation-checked: unscoping the browser client
fails it.
verify green: 237 tests, lint, typecheck, build.
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG
Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
110 lines
3.1 KiB
TypeScript
110 lines
3.1 KiB
TypeScript
/**
|
|
* Shared document search for RAG chat routes
|
|
* @module lib/chat/search
|
|
*
|
|
* Extracts the common "embed query → search → build context" pattern
|
|
* shared by app/api/chat and app/api/professional-chat routes.
|
|
*/
|
|
|
|
import type { AppSupabaseClient } from '@/lib/supabase';
|
|
import { logger } from '@/lib/logger';
|
|
import { truncateChunks, joinContext } from './context';
|
|
|
|
interface SearchChunk {
|
|
document_id: string;
|
|
content: string;
|
|
similarity: number;
|
|
}
|
|
|
|
export interface DocumentSource {
|
|
document_id: string;
|
|
document_name: string;
|
|
preview: string;
|
|
similarity: number;
|
|
}
|
|
|
|
export interface DocumentSearchResult {
|
|
context: string;
|
|
sources: DocumentSource[];
|
|
chunks: SearchChunk[];
|
|
}
|
|
|
|
/**
|
|
* Search user documents via match_documents RPC, build context and sources.
|
|
*
|
|
* @param supabase - Supabase service client
|
|
* @param embedding - Pre-computed query embedding vector
|
|
* @param userId - User whose documents to search
|
|
* @param options - Optional filters (documentId, allowedDocumentIds, matchCount, maxContextChars)
|
|
*/
|
|
export async function searchUserDocuments(
|
|
supabase: AppSupabaseClient,
|
|
embedding: number[],
|
|
userId: string,
|
|
options: {
|
|
documentId?: string;
|
|
allowedDocumentIds?: string[];
|
|
matchCount?: number;
|
|
maxContextChars?: number;
|
|
} = {},
|
|
): Promise<DocumentSearchResult> {
|
|
const { documentId, allowedDocumentIds, matchCount = 5 } = options;
|
|
|
|
const { data: searchResults, error: searchError } = await supabase.rpc('match_documents', {
|
|
query_embedding: `[${embedding.join(',')}]`,
|
|
match_count: matchCount,
|
|
filter_user_id: userId,
|
|
});
|
|
|
|
if (searchError) {
|
|
logger.error('[searchUserDocuments] Search error:', searchError);
|
|
return { context: '', sources: [], chunks: [] };
|
|
}
|
|
|
|
let chunks: SearchChunk[] = searchResults || [];
|
|
|
|
// Filter by specific document
|
|
if (documentId) {
|
|
chunks = chunks.filter((c) => c.document_id === documentId);
|
|
}
|
|
|
|
// Filter by allowed document IDs (e.g., professional domain access)
|
|
if (allowedDocumentIds) {
|
|
chunks = chunks.filter((c) => allowedDocumentIds.includes(c.document_id));
|
|
}
|
|
|
|
if (chunks.length === 0) {
|
|
return { context: '', sources: [], chunks: [] };
|
|
}
|
|
|
|
// Look up document names
|
|
const documentIds = Array.from(new Set(chunks.map((c) => c.document_id)));
|
|
const { data: documents } = await supabase
|
|
.from('documents')
|
|
.select('id, name')
|
|
.in('id', documentIds);
|
|
|
|
const docMap = new Map(
|
|
(documents || []).map((d: { id: string; name: string }) => [d.id, d.name]),
|
|
);
|
|
|
|
// Build context
|
|
const fitChunks = truncateChunks(chunks, options.maxContextChars);
|
|
const contextParts = fitChunks.map((chunk, i) => {
|
|
const name = docMap.get(chunk.document_id) || 'Unknown Document';
|
|
return `[Source ${i + 1}: ${name}]\n${chunk.content}`;
|
|
});
|
|
|
|
const context = joinContext(contextParts);
|
|
|
|
// Build sources
|
|
const sources: DocumentSource[] = chunks.map((chunk) => ({
|
|
document_id: chunk.document_id,
|
|
document_name: docMap.get(chunk.document_id) || 'Unknown',
|
|
preview: chunk.content.substring(0, 200) + (chunk.content.length > 200 ? '...' : ''),
|
|
similarity: chunk.similarity,
|
|
}));
|
|
|
|
return { context, sources, chunks };
|
|
}
|