// src/main/services/PersonalGraphService.ts // // 개인 그래프 — 사용자의 문장을 노드로, 관계를 엣지로 저장하고 제안 문맥을 끌어온다. // // 왜: n-gram 문자열 조회는 "같은 꼬리 뒤" 만 찾는다. 실제 글은 관계로 이어진다 — // 어떤 문장은 늘 다른 문장 뒤에 오고(follows), 어떤 문장들은 용어를 공유한다 // (shares_terms). 그 관계를 저장하면 접두가 조금 어긋나도 관련 문맥을 쓸 수 있다. // // 전부 로컬 SQLite 다 (임베딩/네트워크 없음). 학습 동의(inputLearnTypedText)가 없으면 // 표본이 저장되지 않으므로 그래프도 비어 있다. import { SHARES_TERMS_MIN_SIMILARITY, buildQueryTerms, buildSequenceEdges, continuationsFrom, extractTerms, jaccard, rankTwoHopGraphTargets, scoreRelatedNodes, splitSentences, stemContinuationsFrom, type GraphContext, type PersonalGraphQuery, type PersonalGraphStats, type PhraseSource, type TwoHopGraphEdge } from '@d3ro/core/personal-graph' import { SUGGESTION_MEMORY_TAIL_CHARS, isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence' import { analyzeWritingContext } from '@d3ro/core/writing-context' import { and, desc, eq, gte, inArray, or, sql } from 'drizzle-orm' import { getDatabase } from '../db' import { personalPhrases, phraseEdges } from '../db/schema' import { getLogger } from './LoggerService' const logger = getLogger('PersonalGraphService') /** 계약 타입은 core 정본을 따른다 (렌더러/프리로드와 공유). */ export type { PersonalGraphQuery, PersonalGraphStats } /** 용어 공유 엣지 백필 시 한 번에 볼 노드 수. */ const MAINTENANCE_NODE_LIMIT = 300 /** 관계 조회에서 최근 노드를 훑는 수. */ const TERM_SCAN_LIMIT = 400 /** 같은 앱에서 단문 메시지를 연속으로 보낼 때 follows 엣지로 잇는 최대 세션 간격 (10분). */ const SESSION_FOLLOWS_WINDOW_MS = 10 * 60_000 /** 새 문장을 넣을 때 즉시 shares_terms 엣지를 연결할 최근 노드 수. */ const INCREMENTAL_SHARES_SCAN_LIMIT = 40 class PersonalGraphService { /** 앱별 마지막 학습 문장 — 카카오톡·슬랙 등 단문 메시지 사이의 follows 사슬을 잇는다. */ private readonly _lastIndexedByScope = new Map() /** * 텍스트를 그래프에 반영한다. * * 문장마다 노드를 upsert 하고, 연속한 문장 쌍(같은 앱의 직전 메시지 포함)을 follows 엣지로, * 용어를 충분히 공유하는 쌍을 shares_terms 엣지로 남긴다. */ indexText( text: string, meta: { source: PhraseSource; appName?: string | null; at?: number } ): void { const sentences = splitSentences(text).filter(isLearnablePhrase) if (sentences.length === 0) return const at = meta.at ?? Date.now() const scopeKey = meta.appName?.trim().toLowerCase() || null try { const db = getDatabase() const recentExisting = db .select({ phrase: personalPhrases.phrase, terms: personalPhrases.terms }) .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(INCREMENTAL_SHARES_SCAN_LIMIT) .all() for (const sentence of sentences) { const terms = extractTerms(sentence) db.insert(personalPhrases) .values({ id: crypto.randomUUID(), phrase: sentence, count: 1, source: meta.source, lastUsedAt: at, createdAt: at, terms: JSON.stringify(terms), appName: meta.appName ?? null }) .onConflictDoUpdate({ target: personalPhrases.phrase, set: { count: sql`${personalPhrases.count} + 1`, lastUsedAt: at, terms: JSON.stringify(terms), appName: meta.appName ?? null } }) .run() if (terms.length > 0) { for (const existing of recentExisting) { if (existing.phrase === sentence) continue const existingTerms = parseTerms(existing.terms) if (existingTerms.length === 0) continue if (jaccard(terms, existingTerms) >= SHARES_TERMS_MIN_SIMILARITY) { this._upsertEdge(existing.phrase, sentence, 'shares_terms') } } } } // 같은 앱에서 직전 세션(10분 이내)에 쓴 문장과 첫 문장을 follows 로 연결 if (scopeKey) { const previousInScope = this._lastIndexedByScope.get(scopeKey) if ( previousInScope && previousInScope.phrase !== sentences[0] && Math.abs(at - previousInScope.at) <= SESSION_FOLLOWS_WINDOW_MS ) { this._upsertEdge(previousInScope.phrase, sentences[0], 'follows') } this._lastIndexedByScope.set(scopeKey, { phrase: sentences[sentences.length - 1], at }) } // follows 엣지 (같은 텍스트 내 인접 문장) for (const edge of buildSequenceEdges(sentences)) { this._upsertEdge(edge.from, edge.to, 'follows') } // 같은 텍스트 안에서 용어를 많이 공유하는 쌍 for (let i = 0; i < sentences.length; i += 1) { const termsA = extractTerms(sentences[i]) for (let j = i + 1; j < sentences.length; j += 1) { const termsB = extractTerms(sentences[j]) if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue this._upsertEdge(sentences[i], sentences[j], 'shares_terms') } } } catch (error) { logger.warn(`그래프 반영 실패: ${error instanceof Error ? error.message : String(error)}`) } } private _upsertEdge(from: string, to: string, kind: 'follows' | 'shares_terms'): void { const db = getDatabase() const now = Date.now() db.insert(phraseEdges) .values({ id: crypto.randomUUID(), fromPhrase: from, toPhrase: to, kind, weight: 1, updatedAt: now }) .onConflictDoUpdate({ target: [phraseEdges.fromPhrase, phraseEdges.toPhrase, phraseEdges.kind], set: { weight: sql`${phraseEdges.weight} + 1`, updatedAt: now } }) .run() } /** * 제안 문맥을 그래프에서 끌어온다. * * 1) followUps — 직전 완결 문장(정확히 같거나 용어가 거의 같은 노드) 뒤에 실제로 이어 쓴 문장. * "다음 문장" 의 가장 강한 근거다(follows 엣지 가중치 순). * 2) continuations — 접두 꼬리를 품은 문장에서 그 꼬리 뒤에 이어 쓴 텍스트. 긴 꼬리부터 * 짧은 꼬리(어절 경계)로 물러나며 찾는다 — 14자 고정 꼬리는 새 문장에서 거의 맞지 않았다. * 3) related — 지금 문장·직전 문장·앞 문맥의 용어를 IDF 로 가중해 고른 관련 문장과, * 그 문장들 뒤에 이어 쓴 문장(follows 1단계 확장). */ retrieveContext( prefix: string, limit = 4, options: { appName?: string | null; recentWrites?: readonly string[] } = {} ): GraphContext { const empty: GraphContext = { continuations: [], related: [], followUps: [] } const normalizedPrefix = prefix.replace(/\s+/gu, ' ').trim() if (normalizedPrefix.length < 2) return empty try { const db = getDatabase() const context = analyzeWritingContext(prefix) const recentWriteSentences = options.recentWrites && options.recentWrites.length > 0 ? splitSentences(options.recentWrites[options.recentWrites.length - 1] ?? '') : [] const anchorLastSentence = context.lastSentence || (recentWriteSentences.length > 0 ? recentWriteSentences[recentWriteSentences.length - 1] : '') const inPrefix = (text: string): boolean => normalizedPrefix.includes(text) // (1) 직전 문장(또는 방금 보낸 채팅 메시지) 뒤에 이어 쓴 문장 const followUps = this._followUpsAfter(anchorLastSentence, context.currentSentence ? 2 : 3, inPrefix) // (2) 꼬리 이어쓰기 — 지금 문장 안에서만 찾는다 (앞 문장 끝과 섞이지 않게) const tailSource = context.currentSentence || context.lastSentence const continuations = this._continuationsForTail(tailSource) // (3) 관련 문장 — IDF 가중 용어 겹침 + 1-hop follows + 2-hop (shares_terms -> follows) 경로 확장 const queryTerms = buildQueryTerms([ { text: context.currentSentence, weight: 2 }, { text: anchorLastSentence, weight: 1.5 }, { text: context.earlierText.slice(-200), weight: 1 } ]) const recentNodes = db .select() .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(TERM_SCAN_LIMIT) .all() const scored = scoreRelatedNodes( { terms: queryTerms, appName: options.appName ?? null, exclude: (text) => inPrefix(text) || followUps.includes(text) }, recentNodes.map((row) => ({ text: row.phrase, terms: parseTerms(row.terms), count: row.count, lastUsedAt: row.lastUsedAt, appName: row.appName })), limit + 2 ) const related: string[] = [] const push = (text: string): void => { if (related.length >= limit || related.includes(text) || followUps.includes(text) || inPrefix(text)) return related.push(text) } // 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 확장 + 2-hop 경로 탐색 const anchors = scored.slice(0, 3).map((item) => item.text) const firstHopEdges = anchors.length ? db .select() .from(phraseEdges) .where(or(inArray(phraseEdges.fromPhrase, anchors), inArray(phraseEdges.toPhrase, anchors))) .orderBy(desc(phraseEdges.weight)) .limit(12) .all() : [] const directFollowHops = firstHopEdges.filter( (edge) => edge.kind === 'follows' && anchors.includes(edge.fromPhrase) ) const normalizedFirstHop = firstHopEdges.flatMap((edge) => { if (edge.kind === 'follows' && anchors.includes(edge.fromPhrase)) { return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows', weight: edge.weight }] } if (edge.kind === 'shares_terms') { if (anchors.includes(edge.fromPhrase)) { return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'shares_terms', weight: edge.weight }] } if (anchors.includes(edge.toPhrase)) { return [{ from: edge.toPhrase, to: edge.fromPhrase, kind: 'shares_terms', weight: edge.weight }] } } return [] }) const midNodes = [...new Set(normalizedFirstHop.map((edge) => edge.to))] const secondHopFollows = midNodes.length ? db .select() .from(phraseEdges) .where(and(inArray(phraseEdges.fromPhrase, midNodes), eq(phraseEdges.kind, 'follows'))) .orderBy(desc(phraseEdges.weight)) .limit(12) .all() .map((edge) => ({ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows' as const, weight: edge.weight })) : [] const twoHopTargets = rankTwoHopGraphTargets({ firstHopEdges: normalizedFirstHop, secondHopFollowEdges: secondHopFollows, queryTerms, exclude: (text) => inPrefix(text) || followUps.includes(text), limit: 2 }) for (const item of scored) { push(item.text) const hop = directFollowHops.find((edge) => edge.fromPhrase === item.text) if (hop) push(hop.toPhrase) } for (const target of twoHopTargets) { push(target) } return { continuations, related, followUps } } catch (error) { logger.warn( `그래프 문맥 조회 실패: ${error instanceof Error ? error.message : String(error)}` ) return empty } } /** 문장 뒤에 이어 쓴 문장 (follows). 같은 노드가 없으면 용어가 가장 많이 겹치는 노드로 대신한다. */ private _followUpsAfter(sentence: string, limit: number, exclude: (text: string) => boolean): string[] { const normalized = sentence.replace(/[.!?。!?…]+$/u, '').replace(/\s+/gu, ' ').trim() if (normalized.length < 4) return [] const db = getDatabase() let sources = [normalized] const exact = db .select({ phrase: personalPhrases.phrase }) .from(personalPhrases) .where(eq(personalPhrases.phrase, normalized)) .get() if (!exact) { const terms = buildQueryTerms([{ text: normalized, weight: 1 }]) if (terms.size < 2) return [] const near = scoreRelatedNodes( { terms }, db .select() .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(TERM_SCAN_LIMIT) .all() .map((row) => ({ text: row.phrase, terms: parseTerms(row.terms), count: row.count, lastUsedAt: row.lastUsedAt, appName: row.appName })), 2 ).filter((item) => item.sharedTerms >= Math.max(2, Math.ceil(terms.size * 0.6))) if (near.length === 0) return [] sources = near.map((item) => item.text) } const edges = db .select() .from(phraseEdges) .where(and(inArray(phraseEdges.fromPhrase, sources), eq(phraseEdges.kind, 'follows'))) .orderBy(desc(phraseEdges.weight), desc(phraseEdges.updatedAt)) .limit(limit * 2) .all() const out: string[] = [] for (const edge of edges) { if (out.includes(edge.toPhrase) || exclude(edge.toPhrase)) continue out.push(edge.toPhrase) if (out.length >= limit) break } return out } /** 최근 문장 노드 원문과 사용 횟수 — 오타 교정의 개인 어휘 근거. */ listRecentTexts(limit = TERM_SCAN_LIMIT): Array<{ text: string; count: number }> { try { return getDatabase() .select({ text: personalPhrases.phrase, count: personalPhrases.count }) .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(limit) .all() } catch (error) { logger.warn(`그래프 원문 조회 실패: ${error instanceof Error ? error.message : String(error)}`) return [] } } /** 꼬리 뒤 이어쓰기 — 긴 꼬리부터 어절 경계의 짧은 꼬리로 물러난다. */ private _continuationsForTail(text: string): string[] { const normalized = text.replace(/\s+/gu, ' ').trim() if (normalized.length < 4) return [] const db = getDatabase() const tails: string[] = [] for (const length of [SUGGESTION_MEMORY_TAIL_CHARS, 10, 7]) { let tail = prefixTail(normalized, length) // 어절 중간에서 시작하지 않게 — 첫 공백 뒤로 민다(공백이 없으면 그대로). if (tail.length < normalized.length && tail.includes(' ')) tail = tail.slice(tail.indexOf(' ') + 1) if (tail.length >= 4 && !tails.includes(tail)) tails.push(tail) } for (const tail of tails) { const pattern = `%${tail.replace(/[%_\\]/gu, '')}%` const rows = db .select({ phrase: personalPhrases.phrase }) .from(personalPhrases) .where(sql`${personalPhrases.phrase} LIKE ${pattern}`) .orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt)) .limit(20) .all() const found = continuationsFrom( rows.map((row) => row.phrase), tail, 3 ) if (found.length > 0) return found } // 정확한 문자열 꼬리가 어긋나도("회의록을 정리해서" vs "회의록 정리해서") 어간 열이 일치하면 이어쓰기를 뽑는다. const recentPhrases = db .select({ phrase: personalPhrases.phrase }) .from(personalPhrases) .orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt)) .limit(120) .all() .map((row) => row.phrase) return stemContinuationsFrom(recentPhrases, normalized, 3) } /** 용어 공유 엣지를 백필한다 (기존 노드들 사이 관계 보강). */ runMaintenance(limit = MAINTENANCE_NODE_LIMIT): number { try { const db = getDatabase() const nodes = db .select() .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(limit) .all() let created = 0 for (let i = 0; i < nodes.length; i += 1) { const termsA = parseTerms(nodes[i].terms) if (termsA.length === 0) continue for (let j = i + 1; j < nodes.length; j += 1) { const termsB = parseTerms(nodes[j].terms) if (termsB.length === 0) continue if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue this._upsertEdge(nodes[i].phrase, nodes[j].phrase, 'shares_terms') created += 1 if (created >= 200) return created } } if (created > 0) logger.info(`그래프 유지보수: shares_terms 엣지 ${created}개 생성`) return created } catch (error) { logger.warn(`그래프 유지보수 실패: ${error instanceof Error ? error.message : String(error)}`) return 0 } } getStats(days = 30): PersonalGraphStats { const empty: PersonalGraphStats = { nodes: 0, followsEdges: 0, sharesTermsEdges: 0, topEdges: [], recentNodes: [] } try { const db = getDatabase() const since = Date.now() - days * 86400000 const nodeCount = db .select({ value: sql`count(*)` }) .from(personalPhrases) .get() const follows = db .select({ value: sql`count(*)` }) .from(phraseEdges) .where(eq(phraseEdges.kind, 'follows')) .get() const shares = db .select({ value: sql`count(*)` }) .from(phraseEdges) .where(eq(phraseEdges.kind, 'shares_terms')) .get() const topEdges = db .select({ from: phraseEdges.fromPhrase, to: phraseEdges.toPhrase, kind: phraseEdges.kind, weight: phraseEdges.weight }) .from(phraseEdges) .orderBy(desc(phraseEdges.weight)) .limit(12) .all() const recentNodes = db .select() .from(personalPhrases) .where(gte(personalPhrases.createdAt, since)) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(20) .all() return { nodes: Number(nodeCount?.value ?? 0), followsEdges: Number(follows?.value ?? 0), sharesTermsEdges: Number(shares?.value ?? 0), topEdges, recentNodes: recentNodes.map((row) => ({ text: row.phrase, terms: parseTerms(row.terms), count: row.count, appName: row.appName })) } } catch (error) { logger.warn(`그래프 통계 실패: ${error instanceof Error ? error.message : String(error)}`) return empty } } /** 특정 텍스트 주변의 그래프를 조회한다 (설정/지식베이스 UI). */ query(text: string, limit = 12): PersonalGraphQuery { try { const db = getDatabase() const needle = text.trim() if (needle.length < 2) return { anchors: [], neighbors: [] } const pattern = `%${needle.replace(/[%_\\]/gu, '')}%` const anchors = db .select() .from(personalPhrases) .where(sql`${personalPhrases.phrase} LIKE ${pattern}`) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(6) .all() if (anchors.length === 0) return { anchors: [], neighbors: [] } const anchorTexts = anchors.map((row) => row.phrase) const neighbors = db .select({ text: phraseEdges.toPhrase, kind: phraseEdges.kind, weight: phraseEdges.weight }) .from(phraseEdges) .where(inArray(phraseEdges.fromPhrase, anchorTexts)) .orderBy(desc(phraseEdges.weight)) .limit(limit) .all() return { anchors: anchors.map((row) => ({ text: row.phrase, terms: parseTerms(row.terms), count: row.count })), neighbors } } catch (error) { logger.warn(`그래프 조회 실패: ${error instanceof Error ? error.message : String(error)}`) return { anchors: [], neighbors: [] } } } /** * 한 문장 노드에 닿는 엣지를 모두 지운다 (사용자가 문구를 삭제했을 때). * * 엣지는 문장 텍스트를 외래 키 없이 들고 있어, 노드만 지우면 follows 이웃으로 * 지운 문장이 계속 제안 문맥에 끌려 나온다. 호출자의 트랜잭션 안에서 부를 수 있도록 * 예외를 삼키지 않는다. */ removePhrase(phrase: string): number { const db = getDatabase() const result = db .delete(phraseEdges) .where(or(eq(phraseEdges.fromPhrase, phrase), eq(phraseEdges.toPhrase, phrase))) .run() return Number(result.changes ?? 0) } clearAll(): void { try { this._lastIndexedByScope.clear() const db = getDatabase() db.delete(phraseEdges).run() logger.info('개인 그래프 엣지 전체 삭제') } catch (error) { logger.warn(`그래프 삭제 실패: ${error instanceof Error ? error.message : String(error)}`) } } } /** DB 의 terms 컬럼(JSON)을 안전하게 파싱한다. */ function parseTerms(raw: string | null): string[] { if (!raw) return [] try { const parsed = JSON.parse(raw) as unknown if (!Array.isArray(parsed)) return [] return parsed.filter((value): value is string => typeof value === 'string') } catch { return [] } } let instance: PersonalGraphService | null = null export function getPersonalGraphService(): PersonalGraphService { if (!instance) instance = new PersonalGraphService() return instance } export function resetPersonalGraphServiceForTests(): void { instance = null }