사건 자료 검색(case_search) — 탐정·닥터·법률 사건 채팅(dt_case_/dr_case_/lw_case_<사건ID>)에서만, 그 사건 폴더의 txt·pdf(pdftotext)·hwp·odt·docx(LibreOffice, 임시 폴더에서 변환 후 삭제)를 700자 조각으로 색인해 벡터+키워드로 찾음. 일반 기억과 분리: 벡터는 별도 컬렉션 case_docs, 키워드·색인 상태는 별도 DB case_docs.db, 일반 회상은 이 저장소를 보지 않음, 조회는 항상 workspace·app·caseId로 묶음(사건은 세션 ID로 정해 모델이 바꿀 수 없음). 바뀐 파일만 재색인, 첫 색인은 45초까지만 기다리고 뒤에서 계속(탐정 사건 59문서 743조각 192초 실측), 사건 목록에서 지우면 색인도 삭제(purgeCaseDocs). 사진·녹음·영상은 제외
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2909205d0f
commit
157e38738d
9 files changed
+342
-2
No files matched your search
@@ -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: {
|
||||
|
||||
@@ -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="<name>", 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가 막는다.
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* case-docs.ts — 탐정·닥터·법률 앱의 사건 자료 검색(2026-10-25 사용자 요청 "A부터 해줘").
|
||||
*
|
||||
* 사건 폴더(<workspace>/<app>/<사건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/<app>/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<string> {
|
||||
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<IndexResult> {
|
||||
const dir = path.join(workspace, app, caseId);
|
||||
const files = listCaseFiles(dir);
|
||||
const known = new Map<string, { mtime: number; size: number; chunks: number }>();
|
||||
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<string>();
|
||||
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<string, Promise<IndexResult>>();
|
||||
|
||||
/**
|
||||
* 색인을 시작하고 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<null>(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<CaseHit[]> {
|
||||
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<string>();
|
||||
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<number> {
|
||||
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;
|
||||
}
|
||||
@@ -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<number[]> {
|
||||
export async function embedText(text: string, taskType: 'document' | 'query', timeoutMs = 15_000): Promise<number[]> {
|
||||
const prompt = taskType === 'document'
|
||||
? `title: none | text: ${text}`
|
||||
: `task: search result | query: ${text}`;
|
||||
@@ -83,7 +83,7 @@ export async function embedQuery(text: string): Promise<number[]> {
|
||||
let clientSingleton: ChromaClient | null = null;
|
||||
const collectionCache = new Map<string, Collection>();
|
||||
|
||||
async function getCollection(name: string): Promise<Collection> {
|
||||
export async function getCollection(name: string): Promise<Collection> {
|
||||
const cached = collectionCache.get(name);
|
||||
if (cached) return cached;
|
||||
if (!clientSingleton) clientSingleton = new ChromaClient({ host: CHROMA_HOST, port: CHROMA_PORT });
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user