From 157e38738df2ba44e6437bc0fcf091532e6f3d27 Mon Sep 17 00:00:00 2001 From: kim Date: Sun, 25 Oct 2026 12:56:40 +0900 Subject: [PATCH] =?UTF-8?q?=EC=82=AC=EA=B1=B4=20=EC=9E=90=EB=A3=8C=20?= =?UTF-8?q?=EA=B2=80=EC=83=89(case=5Fsearch)=20=E2=80=94=20=ED=83=90?= =?UTF-8?q?=EC=A0=95=C2=B7=EB=8B=A5=ED=84=B0=C2=B7=EB=B2=95=EB=A5=A0=20?= =?UTF-8?q?=EC=82=AC=EA=B1=B4=20=EC=B1=84=ED=8C=85(dt=5Fcase=5F/dr=5Fcase?= =?UTF-8?q?=5F/lw=5Fcase=5F<=EC=82=AC=EA=B1=B4ID>)=EC=97=90=EC=84=9C?= =?UTF-8?q?=EB=A7=8C,=20=EA=B7=B8=20=EC=82=AC=EA=B1=B4=20=ED=8F=B4?= =?UTF-8?q?=EB=8D=94=EC=9D=98=20txt=C2=B7pdf(pdftotext)=C2=B7hwp=C2=B7odt?= =?UTF-8?q?=C2=B7docx(LibreOffice,=20=EC=9E=84=EC=8B=9C=20=ED=8F=B4?= =?UTF-8?q?=EB=8D=94=EC=97=90=EC=84=9C=20=EB=B3=80=ED=99=98=20=ED=9B=84=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C)=EB=A5=BC=20700=EC=9E=90=20=EC=A1=B0?= =?UTF-8?q?=EA=B0=81=EC=9C=BC=EB=A1=9C=20=EC=83=89=EC=9D=B8=ED=95=B4=20?= =?UTF-8?q?=EB=B2=A1=ED=84=B0+=ED=82=A4=EC=9B=8C=EB=93=9C=EB=A1=9C=20?= =?UTF-8?q?=EC=B0=BE=EC=9D=8C.=20=EC=9D=BC=EB=B0=98=20=EA=B8=B0=EC=96=B5?= =?UTF-8?q?=EA=B3=BC=20=EB=B6=84=EB=A6=AC:=20=EB=B2=A1=ED=84=B0=EB=8A=94?= =?UTF-8?q?=20=EB=B3=84=EB=8F=84=20=EC=BB=AC=EB=A0=89=EC=85=98=20case=5Fdo?= =?UTF-8?q?cs,=20=ED=82=A4=EC=9B=8C=EB=93=9C=C2=B7=EC=83=89=EC=9D=B8=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=EB=8A=94=20=EB=B3=84=EB=8F=84=20DB=20case=5F?= =?UTF-8?q?docs.db,=20=EC=9D=BC=EB=B0=98=20=ED=9A=8C=EC=83=81=EC=9D=80=20?= =?UTF-8?q?=EC=9D=B4=20=EC=A0=80=EC=9E=A5=EC=86=8C=EB=A5=BC=20=EB=B3=B4?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EC=9D=8C,=20=EC=A1=B0=ED=9A=8C=EB=8A=94?= =?UTF-8?q?=20=ED=95=AD=EC=83=81=20workspace=C2=B7app=C2=B7caseId=EB=A1=9C?= =?UTF-8?q?=20=EB=AC=B6=EC=9D=8C(=EC=82=AC=EA=B1=B4=EC=9D=80=20=EC=84=B8?= =?UTF-8?q?=EC=85=98=20ID=EB=A1=9C=20=EC=A0=95=ED=95=B4=20=EB=AA=A8?= =?UTF-8?q?=EB=8D=B8=EC=9D=B4=20=EB=B0=94=EA=BF=80=20=EC=88=98=20=EC=97=86?= =?UTF-8?q?=EC=9D=8C).=20=EB=B0=94=EB=80=90=20=ED=8C=8C=EC=9D=BC=EB=A7=8C?= =?UTF-8?q?=20=EC=9E=AC=EC=83=89=EC=9D=B8,=20=EC=B2=AB=20=EC=83=89?= =?UTF-8?q?=EC=9D=B8=EC=9D=80=2045=EC=B4=88=EA=B9=8C=EC=A7=80=EB=A7=8C=20?= =?UTF-8?q?=EA=B8=B0=EB=8B=A4=EB=A6=AC=EA=B3=A0=20=EB=92=A4=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EA=B3=84=EC=86=8D(=ED=83=90=EC=A0=95=20=EC=82=AC?= =?UTF-8?q?=EA=B1=B4=2059=EB=AC=B8=EC=84=9C=20743=EC=A1=B0=EA=B0=81=20192?= =?UTF-8?q?=EC=B4=88=20=EC=8B=A4=EC=B8=A1),=20=EC=82=AC=EA=B1=B4=20?= =?UTF-8?q?=EB=AA=A9=EB=A1=9D=EC=97=90=EC=84=9C=20=EC=A7=80=EC=9A=B0?= =?UTF-8?q?=EB=A9=B4=20=EC=83=89=EC=9D=B8=EB=8F=84=20=EC=82=AD=EC=A0=9C(pu?= =?UTF-8?q?rgeCaseDocs).=20=EC=82=AC=EC=A7=84=C2=B7=EB=85=B9=EC=9D=8C?= =?UTF-8?q?=C2=B7=EC=98=81=EC=83=81=EC=9D=80=20=EC=A0=9C=EC=99=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/gateway/chat/build-tools.ts | 14 ++ src/gateway/chat/execute-tool.ts | 23 ++ src/gateway/chat/tool-scope.ts | 3 + src/gateway/memory/case-docs.ts | 247 ++++++++++++++++++++++ src/gateway/memory/memory-vector.ts | 4 +- src/gateway/routes/routes-detective.ts | 3 + src/gateway/routes/routes-doctor-cases.ts | 4 + src/gateway/routes/routes-lawyer-cases.ts | 4 + tests/case-docs.test.ts | 42 ++++ 9 files changed, 342 insertions(+), 2 deletions(-) create mode 100644 src/gateway/memory/case-docs.ts create mode 100644 tests/case-docs.test.ts diff --git a/src/gateway/chat/build-tools.ts b/src/gateway/chat/build-tools.ts index 418e6a2..c42ea19 100644 --- a/src/gateway/chat/build-tools.ts +++ b/src/gateway/chat/build-tools.ts @@ -1101,6 +1101,20 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) { }, }, }, + { + type: 'function', + function: { + name: 'case_search', + description: '이 사건 폴더의 자료(카톡·문자·통화 녹취록·고소장·의견서·진료기록 등 txt·pdf·hwp·odt·docx)에서 내용을 찾는다. 사람·날짜·장소·금액·발언처럼 사건 자료에 있을 법한 사실을 묻거나 확인할 때 먼저 부를 것. 결과는 파일 이름과 해당 부분 원문 — 답에는 어느 파일에서 나온 내용인지 밝히고, 결과에 없는 내용은 자료에 없다고 말할 것. 사진·녹음·영상 내용은 검색되지 않는다.', + parameters: { + type: 'object', required: ['query'], + properties: { + query: { type: 'string', description: '찾을 내용(사람 이름·날짜·장소·키워드나 질문 문장)' }, + limit: { type: 'number', description: '결과 조각 수(기본 8, 최대 15)' }, + }, + }, + }, + }, { type: 'function', function: { diff --git a/src/gateway/chat/execute-tool.ts b/src/gateway/chat/execute-tool.ts index 5e5dff6..f78c4b8 100644 --- a/src/gateway/chat/execute-tool.ts +++ b/src/gateway/chat/execute-tool.ts @@ -1,4 +1,5 @@ import { applySearchReplaceEdits } from './search-replace-edit'; +import { caseFromSession, indexCaseWithBudget, searchCase, caseIndexStats } from '../memory/case-docs'; import path from 'path'; import fs from 'fs'; import { getConfig } from '../../config/config'; @@ -1238,6 +1239,28 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals return { name, args, result: `${mbFilename} categories:\n${mbCategories.map((c: string) => `- ${c}`).join('\n')}\n\nUse memory_write(file="${mbFile}", category="", content="...") to add a fact.`, error: false }; } + case 'case_search': { + // 사건 자료 검색(case-docs.ts) — 세션 ID로 사건을 정하므로 모델이 다른 사건을 지정할 수 없다. + const c = caseFromSession(sessionId); + if (!c) return { name, args, result: '사건 채팅에서만 쓸 수 있습니다(사건을 열고 물어보세요).', error: true }; + const query = String(args?.query || '').trim(); + if (!query) return { name, args, result: 'case_search: query is required', error: true }; + try { + const ix = await indexCaseWithBudget(workspacePath, c.app, c.caseId); + const hits = await searchCase(workspacePath, c.app, c.caseId, query, Math.min(Math.max(1, Number(args?.limit) || 8), 15)); + const st = caseIndexStats(workspacePath, c.app, c.caseId); + const idx = ix.result; + const head = ix.done && idx + ? `[사건 자료 검색] 문서 ${idx.files}개 중 색인 ${idx.files - idx.skipped.length}개(${idx.chunks}조각)${idx.indexed ? `, 이번에 새로 색인 ${idx.indexed}개` : ''}${idx.skipped.length ? ` · 글자를 못 뽑은 파일 ${idx.skipped.length}개` : ''}. 사진·녹음·영상은 검색 대상 아님.` + : `[사건 자료 검색] 처음 색인하는 중이라 지금까지 된 문서 ${st.files}개(${st.chunks}조각)에서만 찾았다 — 나머지는 뒤에서 계속 색인 중이니, 못 찾았으면 "자료를 아직 다 읽지 못했다, 잠시 뒤 다시 물어 달라"고 말할 것.`; + if (!hits.length) return { name, args, result: `${head}\n"${query}"와 관련된 내용을 사건 자료에서 찾지 못했습니다 — 자료에 없다고 답할 것.`, error: false }; + const body = hits.map((h, i) => `(${i + 1}) 파일: ${h.file}\n${h.text}`).join('\n\n'); + return { name, args, result: `${head}\n\n${body}\n\n[중요] 위 원문에 있는 것만 말하고, 어느 파일에서 나온 내용인지 밝힐 것.`, error: false }; + } catch (err: any) { + return { name, args, result: `사건 자료 검색 실패: ${err.message}`, error: true }; + } + } + case 'memory_write': { // 탐정(dt_)·닥터(dr_)·법률(lw_) 앱 대화는 장기 기억(USER.md·벡터 기억)에 올리지 않는다 — 사건·환자·의뢰인 // 정보가 메인 채팅 회상으로 새는 경로(2026-10-25 사용자 지시). 일일 로그 쪽은 server.ts logToDaily가 막는다. diff --git a/src/gateway/chat/tool-scope.ts b/src/gateway/chat/tool-scope.ts index d44815c..eee8950 100644 --- a/src/gateway/chat/tool-scope.ts +++ b/src/gateway/chat/tool-scope.ts @@ -23,6 +23,7 @@ */ import { isRecommendationWhere } from './system-prompt'; +import { caseFromSession } from '../memory/case-docs'; import { DISASTER_PATTERN } from '../guards/prompt-gates'; export interface ToolScopeInput { @@ -426,6 +427,8 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string) // 10-25 사용자: "탐정 닥터 법률은 벡터 메모리에 올리지 말기" — 그 앱들에선 기억 저장 도구를 아예 안 보인다 // (실행 단계에서도 execute-tool.ts가 거절). if (name === 'memory_write' && (isDetectiveAppSession || isDoctorAppSession || isLawyerAppSession)) return false; + // case_search — 사건 자료 검색(case-docs.ts). 그 사건 채팅(dt_case_/dr_case_/lw_case_<사건ID>)에서만. + if (name === 'case_search' && !caseFromSession(sessionId)) return false; if (name === 'run_command' && !hasRunCommandKeyword) return false; return true; }; diff --git a/src/gateway/memory/case-docs.ts b/src/gateway/memory/case-docs.ts new file mode 100644 index 0000000..23c409f --- /dev/null +++ b/src/gateway/memory/case-docs.ts @@ -0,0 +1,247 @@ +/** + * case-docs.ts — 탐정·닥터·법률 앱의 사건 자료 검색(2026-10-25 사용자 요청 "A부터 해줘"). + * + * 사건 폴더(//<사건ID>/)의 문서(txt·pdf·hwp·odt·docx …)를 조각내 색인하고, 그 사건 채팅의 + * case_search 도구만 검색한다. 같은 날 "탐정 닥터 법률은 벡터 메모리에 올리지 말기" 지시에 맞춰 일반 기억과 + * 완전히 떨어뜨린다: + * - 벡터는 별도 컬렉션 case_docs, 키워드 검색·색인 상태는 별도 DB databases/case_docs.db. + * - personality-context의 회상(user_facts·daily_extracts·workshop_facts)은 이 저장소를 보지 않는다. + * - 모든 조회는 workspace·app·caseId 세 가지로 묶는다 — 다른 사건·다른 사용자 자료가 섞이지 않게. + * - 사건 목록에서 사건을 지우면(PUT /api//cases) 그 사건 색인도 지운다(purgeCaseDocs). + * 사진·녹음·영상은 글자가 없어 건너뛴다(녹음을 글로 받아 적는 건 별도 작업). + */ +import Database from 'better-sqlite3'; +import { execFile } from 'child_process'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { getConfig } from '../../config/config.js'; +import { embedText, getCollection, dedupeFacts } from './memory-vector.js'; + +export const CASE_DOCS_COLLECTION = 'case_docs'; +export type CaseApp = 'detective' | 'doctor' | 'lawyer'; + +const PLAIN_EXT = new Set(['.txt', '.md', '.csv', '.json', '.srt', '.vtt', '.log', '.html', '.htm']); +const OFFICE_EXT = new Set(['.hwp', '.hwpx', '.odt', '.doc', '.docx', '.rtf']); +const MAX_TEXT_CHARS = 400_000; // 파일 하나에서 색인할 최대 글자(아주 큰 덤프가 색인을 독점하지 않게) +const CHUNK = 700; +const OVERLAP = 120; + +/** 세션 ID → 사건. dt_case_<사건ID> / dr_case_<사건ID> / lw_case_<사건ID>, 그 밖(dt_main 등)은 사건 없음. */ +export function caseFromSession(sessionId: string): { app: CaseApp; caseId: string } | null { + const m = /^(dt|dr|lw)_case_([A-Za-z0-9_-]+)$/.exec(String(sessionId || '')); + if (!m) return null; + return { app: ({ dt: 'detective', dr: 'doctor', lw: 'lawyer' } as const)[m[1] as 'dt' | 'dr' | 'lw'], caseId: m[2] }; +} + +let dbSingleton: Database.Database | null = null; +function db(): Database.Database { + if (dbSingleton) return dbSingleton; + const dir = path.join(getConfig().getConfigDir(), 'databases'); + fs.mkdirSync(dir, { recursive: true }); + const d = new Database(path.join(dir, 'case_docs.db')); + d.pragma('journal_mode = WAL'); + d.exec(` + CREATE TABLE IF NOT EXISTS case_files ( + workspace TEXT, app TEXT, case_id TEXT, rel_path TEXT, mtime REAL, size INTEGER, chunks INTEGER, + PRIMARY KEY (workspace, app, case_id, rel_path) + ); + CREATE VIRTUAL TABLE IF NOT EXISTS case_fts USING fts5(scope, doc_id, rel_path, text, tokenize='trigram'); + `); + dbSingleton = d; + return d; +} + +const scopeKey = (workspace: string, app: string, caseId: string) => `${workspace}#${app}#${caseId}`; +const docId = (app: string, caseId: string, rel: string, i: number) => `${app}:${caseId}:${rel}:${i}`; + +function run(cmd: string, args: string[], timeoutMs: number): Promise<{ ok: boolean; out: string }> { + return new Promise((resolve) => { + execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) => resolve({ ok: !err, out: String(stdout || '') })); + }); +} + +function decodeText(buf: Buffer): string { + const utf8 = buf.toString('utf8'); + if (!utf8.includes('�')) return utf8; + try { return new TextDecoder('euc-kr').decode(buf); } catch { return utf8; } // 옛 한글 txt(CP949) +} + +/** 파일 → 글자. 지원하지 않거나 실패하면 ''. 변환은 임시 폴더에서 하고 바로 지운다(사건 자료 사본을 남기지 않게). */ +export async function extractText(file: string): Promise { + const ext = path.extname(file).toLowerCase(); + if (PLAIN_EXT.has(ext)) return decodeText(fs.readFileSync(file)); + if (ext === '.pdf') { + const r = await run('pdftotext', ['-layout', '-enc', 'UTF-8', file, '-'], 60_000); + return r.ok ? r.out : ''; + } + if (OFFICE_EXT.has(ext)) { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'casedoc-')); + try { + // 따로 프로필을 써야 사용자가 열어 둔 LibreOffice와 부딪히지 않는다. + const r = await run('soffice', [`-env:UserInstallation=file://${tmp}/profile`, '--headless', '--convert-to', 'txt:Text', '--outdir', tmp, file], 120_000); + const out = fs.readdirSync(tmp).find(f => f.endsWith('.txt')); + return r.ok && out ? decodeText(fs.readFileSync(path.join(tmp, out))) : ''; + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + } + return ''; +} + +/** 문단 경계를 살려 CHUNK자 안팎으로 자른다(앞 조각과 OVERLAP자 겹침). */ +export function chunkText(text: string): string[] { + const clean = text.replace(/\r/g, '').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim().slice(0, MAX_TEXT_CHARS); + if (!clean) return []; + const out: string[] = []; + let start = 0; + while (start < clean.length) { + let end = Math.min(clean.length, start + CHUNK); + if (end < clean.length) { + const para = clean.lastIndexOf('\n', end); + if (para > start + CHUNK * 0.5) end = para; + } + const piece = clean.slice(start, end).trim(); + if (piece) out.push(piece); + if (end >= clean.length) break; + start = Math.max(end - OVERLAP, start + 1); + } + return out; +} + +function listCaseFiles(dir: string): string[] { + const out: string[] = []; + const walk = (d: string) => { + for (const e of fs.readdirSync(d, { withFileTypes: true })) { + if (e.name.startsWith('.')) continue; + const p = path.join(d, e.name); + if (e.isDirectory()) walk(p); + else { + const ext = path.extname(e.name).toLowerCase(); + if (PLAIN_EXT.has(ext) || OFFICE_EXT.has(ext) || ext === '.pdf') out.push(p); + } + } + }; + if (fs.existsSync(dir)) walk(dir); + return out; +} + +async function deleteFileEntries(workspace: string, app: string, caseId: string, rel: string, chunks: number) { + const ids = Array.from({ length: chunks }, (_, i) => docId(app, caseId, rel, i)); + if (ids.length) { const col = await getCollection(CASE_DOCS_COLLECTION); await col.delete({ ids }); } + db().prepare('DELETE FROM case_fts WHERE scope = ? AND rel_path = ?').run(scopeKey(workspace, app, caseId), rel); + db().prepare('DELETE FROM case_files WHERE workspace = ? AND app = ? AND case_id = ? AND rel_path = ?').run(workspace, app, caseId, rel); +} + +export interface IndexResult { files: number; indexed: number; removed: number; skipped: string[]; chunks: number } + +/** 바뀐 파일만 다시 색인하고, 사라진 파일 색인은 지운다. */ +export async function indexCase(workspace: string, app: CaseApp, caseId: string): Promise { + const dir = path.join(workspace, app, caseId); + const files = listCaseFiles(dir); + const known = new Map(); + for (const r of db().prepare('SELECT rel_path, mtime, size, chunks FROM case_files WHERE workspace = ? AND app = ? AND case_id = ?').all(workspace, app, caseId) as any[]) { + known.set(r.rel_path, { mtime: r.mtime, size: r.size, chunks: r.chunks }); + } + const res: IndexResult = { files: files.length, indexed: 0, removed: 0, skipped: [], chunks: 0 }; + const seen = new Set(); + const col = await getCollection(CASE_DOCS_COLLECTION); + for (const file of files) { + const rel = path.relative(dir, file); + seen.add(rel); + const st = fs.statSync(file); + const prev = known.get(rel); + if (prev && prev.mtime === st.mtimeMs && prev.size === st.size) { res.chunks += prev.chunks; continue; } + if (prev) await deleteFileEntries(workspace, app, caseId, rel, prev.chunks); + const text = await extractText(file).catch(() => ''); + const chunks = chunkText(text); + if (!chunks.length) res.skipped.push(rel); + for (let i = 0; i < chunks.length; i++) { + const embedding = await embedText(`[${rel}] ${chunks[i]}`, 'document', 30_000); + await col.upsert({ ids: [docId(app, caseId, rel, i)], embeddings: [embedding], documents: [chunks[i]], metadatas: [{ workspace, app, caseId, file: rel, chunk: i }] }); + db().prepare('INSERT INTO case_fts (scope, doc_id, rel_path, text) VALUES (?, ?, ?, ?)').run(scopeKey(workspace, app, caseId), docId(app, caseId, rel, i), rel, chunks[i]); + } + db().prepare('INSERT OR REPLACE INTO case_files (workspace, app, case_id, rel_path, mtime, size, chunks) VALUES (?, ?, ?, ?, ?, ?, ?)').run(workspace, app, caseId, rel, st.mtimeMs, st.size, chunks.length); + res.indexed++; + res.chunks += chunks.length; + } + for (const [rel, prev] of known) { + if (!seen.has(rel)) { await deleteFileEntries(workspace, app, caseId, rel, prev.chunks); res.removed++; } + } + return res; +} + +// 같은 사건을 동시에 두 번 색인하지 않게(채팅 도구와 다른 호출이 겹칠 때). +const running = new Map>(); + +/** + * 색인을 시작하고 budgetMs까지만 기다린다 — 첫 색인은 문서가 많으면 몇 분 걸린다(탐정 사건 59개 문서 743조각 + * 192초 실측). 시간 안에 못 끝나면 뒤에서 계속 돌리고 { done: false }로 돌려준다(그때까지 된 만큼은 검색됨). + */ +export async function indexCaseWithBudget(workspace: string, app: CaseApp, caseId: string, budgetMs = 45_000): Promise<{ done: boolean; result?: IndexResult }> { + const key = scopeKey(workspace, app, caseId); + let job = running.get(key); + if (!job) { + job = indexCase(workspace, app, caseId).finally(() => running.delete(key)); + running.set(key, job); + } + const timeout = new Promise(r => setTimeout(() => r(null), budgetMs)); + const result = await Promise.race([job, timeout]); + return result ? { done: true, result } : { done: false }; +} + +/** 지금 색인돼 있는 문서·조각 수. */ +export function caseIndexStats(workspace: string, app: CaseApp, caseId: string): { files: number; chunks: number } { + const r = db().prepare('SELECT COUNT(*) AS files, COALESCE(SUM(chunks), 0) AS chunks FROM case_files WHERE workspace = ? AND app = ? AND case_id = ?').get(workspace, app, caseId) as any; + return { files: Number(r?.files || 0), chunks: Number(r?.chunks || 0) }; +} + +export interface CaseHit { file: string; chunk: number; text: string; distance?: number } + +function ftsQuery(query: string): string | null { + const terms = query.split(/\s+/).map(t => t.replace(/["*()^:]/g, '').trim()).filter(t => t.length >= 3); + return terms.length ? terms.map(t => `"${t}"`).join(' OR ') : null; +} + +/** 벡터 + 키워드(이름·날짜·번호처럼 글자 그대로 찾아야 하는 것) 검색을 합쳐 이 사건에서만 찾는다. */ +export async function searchCase(workspace: string, app: CaseApp, caseId: string, query: string, k = 8): Promise { + const col = await getCollection(CASE_DOCS_COLLECTION); + const where = { $and: [{ workspace }, { app }, { caseId }] } as any; + const embedding = await embedText(query, 'query'); + const res = await col.query({ queryEmbeddings: [embedding], nResults: 12, where }); + const vec: CaseHit[] = (res.documents?.[0] || []).map((t, i) => { + const m: any = res.metadatas?.[0]?.[i] || {}; + return { file: String(m.file || ''), chunk: Number(m.chunk || 0), text: String(t || ''), distance: res.distances?.[0]?.[i] ?? undefined }; + }); + const q = ftsQuery(query); + const kw: CaseHit[] = q + ? (db().prepare('SELECT rel_path, doc_id, text FROM case_fts WHERE case_fts MATCH ? AND scope = ? ORDER BY rank LIMIT 12').all(q, scopeKey(workspace, app, caseId)) as any[]) + .map(r => ({ file: r.rel_path, chunk: Number(String(r.doc_id).split(':').pop()), text: r.text })) + : []; + // 키워드 적중(글자 그대로 일치)을 먼저, 그다음 가까운 벡터 순. 같은 조각은 한 번만. + const seen = new Set(); + const merged: CaseHit[] = []; + for (const h of [...kw, ...vec.filter(v => (v.distance ?? 1) < 0.75)]) { + const key = `${h.file}#${h.chunk}`; + if (seen.has(key)) continue; + seen.add(key); + merged.push(h); + } + return dedupeFacts(merged).slice(0, k); +} + +/** 사건 목록에 없는 사건의 색인을 지운다(사건 삭제 시). keepIds가 비어도 그대로 따른다 — 사건을 다 지운 경우. */ +export async function purgeCaseDocs(workspace: string, app: CaseApp, keepIds: string[]): Promise { + const keep = new Set(keepIds); + const rows = db().prepare('SELECT DISTINCT case_id FROM case_files WHERE workspace = ? AND app = ?').all(workspace, app) as any[]; + let n = 0; + for (const { case_id } of rows) { + if (keep.has(case_id)) continue; + const col = await getCollection(CASE_DOCS_COLLECTION); + await col.delete({ where: { $and: [{ workspace }, { app }, { caseId: case_id }] } as any }); + db().prepare('DELETE FROM case_fts WHERE scope = ?').run(scopeKey(workspace, app, case_id)); + db().prepare('DELETE FROM case_files WHERE workspace = ? AND app = ? AND case_id = ?').run(workspace, app, case_id); + n++; + } + return n; +} diff --git a/src/gateway/memory/memory-vector.ts b/src/gateway/memory/memory-vector.ts index 6399ddb..fca4d22 100644 --- a/src/gateway/memory/memory-vector.ts +++ b/src/gateway/memory/memory-vector.ts @@ -44,7 +44,7 @@ function getOllamaEndpoint(): string { // search_document:/search_query: — verified via Google's model card, 2026-07-24) or retrieval // quality degrades the same way nomic's did without its prefix. Documents get "title: none | // text: ", queries get "task: search result | query: ". -async function embedText(text: string, taskType: 'document' | 'query', timeoutMs = 15_000): Promise { +export async function embedText(text: string, taskType: 'document' | 'query', timeoutMs = 15_000): Promise { const prompt = taskType === 'document' ? `title: none | text: ${text}` : `task: search result | query: ${text}`; @@ -83,7 +83,7 @@ export async function embedQuery(text: string): Promise { let clientSingleton: ChromaClient | null = null; const collectionCache = new Map(); -async function getCollection(name: string): Promise { +export async function getCollection(name: string): Promise { const cached = collectionCache.get(name); if (cached) return cached; if (!clientSingleton) clientSingleton = new ChromaClient({ host: CHROMA_HOST, port: CHROMA_PORT }); diff --git a/src/gateway/routes/routes-detective.ts b/src/gateway/routes/routes-detective.ts index 938e4ef..aa6af2e 100644 --- a/src/gateway/routes/routes-detective.ts +++ b/src/gateway/routes/routes-detective.ts @@ -1,5 +1,6 @@ import express from 'express'; import fs from 'fs'; +import { purgeCaseDocs } from '../memory/case-docs'; import path from 'path'; import crypto from 'crypto'; import { execFile } from 'child_process'; @@ -232,6 +233,8 @@ export function registerDetectiveRoutes( const tmp = `${p}.tmp`; fs.writeFileSync(tmp, JSON.stringify({ cases }, null, 2), 'utf-8'); fs.renameSync(tmp, p); + // 목록에서 빠진 사건의 자료 검색 색인도 지운다(case-docs.ts, 2026-10-25). + purgeCaseDocs(getUserWorkspace(session.username), 'detective', cases.map((c: any) => String(c?.id || ''))).catch(() => {}); res.json({ success: true }); }); diff --git a/src/gateway/routes/routes-doctor-cases.ts b/src/gateway/routes/routes-doctor-cases.ts index f33772b..49ffc1d 100644 --- a/src/gateway/routes/routes-doctor-cases.ts +++ b/src/gateway/routes/routes-doctor-cases.ts @@ -12,6 +12,8 @@ */ import express from 'express'; import fs from 'fs'; +import { purgeCaseDocs } from '../memory/case-docs'; +import { getUserWorkspace } from '../../config/config'; import path from 'path'; import archiver from 'archiver'; import { execFile } from 'child_process'; @@ -46,6 +48,8 @@ export function registerDoctorCaseRoutes( const tmp = `${p}.tmp`; fs.writeFileSync(tmp, JSON.stringify({ cases }, null, 2), 'utf-8'); fs.renameSync(tmp, p); + // 목록에서 빠진 사건의 자료 검색 색인도 지운다(case-docs.ts, 2026-10-25). + purgeCaseDocs(getUserWorkspace(session.username), 'doctor', cases.map((c: any) => String(c?.id || ''))).catch(() => {}); res.json({ success: true }); }); diff --git a/src/gateway/routes/routes-lawyer-cases.ts b/src/gateway/routes/routes-lawyer-cases.ts index ef2b327..7d66577 100644 --- a/src/gateway/routes/routes-lawyer-cases.ts +++ b/src/gateway/routes/routes-lawyer-cases.ts @@ -14,6 +14,8 @@ */ import express from 'express'; import fs from 'fs'; +import { purgeCaseDocs } from '../memory/case-docs'; +import { getUserWorkspace } from '../../config/config'; import path from 'path'; import archiver from 'archiver'; import { execFile } from 'child_process'; @@ -48,6 +50,8 @@ export function registerLawyerCaseRoutes( const tmp = `${p}.tmp`; fs.writeFileSync(tmp, JSON.stringify({ cases }, null, 2), 'utf-8'); fs.renameSync(tmp, p); + // 목록에서 빠진 사건의 자료 검색 색인도 지운다(case-docs.ts, 2026-10-25). + purgeCaseDocs(getUserWorkspace(session.username), 'lawyer', cases.map((c: any) => String(c?.id || ''))).catch(() => {}); res.json({ success: true }); }); diff --git a/tests/case-docs.test.ts b/tests/case-docs.test.ts new file mode 100644 index 0000000..48ee637 --- /dev/null +++ b/tests/case-docs.test.ts @@ -0,0 +1,42 @@ +/** + * 사건 자료 검색(case-docs.ts) — 세션→사건, 조각내기, 도구 노출 범위(네트워크·DB 없음). + */ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { caseFromSession, chunkText } from '../src/gateway/memory/case-docs'; +import { buildSkillToolFilter } from '../src/gateway/chat/tool-scope'; + +describe('caseFromSession', () => { + test('사건 채팅만 사건으로 본다', () => { + assert.deepEqual(caseFromSession('dt_case_case_68hyuezs'), { app: 'detective', caseId: 'case_68hyuezs' }); + assert.deepEqual(caseFromSession('dr_case_case_292p0s0l'), { app: 'doctor', caseId: 'case_292p0s0l' }); + assert.deepEqual(caseFromSession('lw_case_case_k7a2ckao'), { app: 'lawyer', caseId: 'case_k7a2ckao' }); + assert.equal(caseFromSession('dt_iri7sweys7'), null); + assert.equal(caseFromSession('4545cbaf-x'), null); + assert.equal(caseFromSession('dt_case_../etc'), null); + }); +}); + +describe('chunkText', () => { + test('긴 글은 700자 안팎으로, 앞 조각과 겹치게', () => { + const text = Array.from({ length: 40 }, (_, i) => `문단 ${i} ` + '가'.repeat(80)).join('\n'); + const c = chunkText(text); + assert.ok(c.length >= 4); + assert.ok(c.every(x => x.length <= 700)); + assert.ok(c[1].startsWith(c[0].slice(-60).trim().slice(0, 10)) || c[0].includes(c[1].slice(0, 20))); + }); + test('빈 글은 조각 없음', () => assert.deepEqual(chunkText(' \n\n '), [])); +}); + +describe('case_search 노출', () => { + const on = (sessionId: string) => buildSkillToolFilter({ + message: '카톡에서 돈 얘기 찾아줘', recentUserText: '카톡에서 돈 얘기 찾아줘', lastAssistantMsg: '', sessionId, userWorkspace: null, isSkillEnabledForUser: () => true, + } as any)('case_search'); + test('사건 채팅에서만', () => { + assert.equal(on('dt_case_case_68hyuezs'), true); + assert.equal(on('lw_case_case_k7a2ckao'), true); + assert.equal(on('dt_iri7sweys7'), false); + assert.equal(on('ws_proj_m5j2c2bp'), false); + assert.equal(on('4545cbaf-x'), false); + }); +});