d3ro-voice/packages/core/src/personal-graph.ts
Yun Chan 3cac14f668
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled
feat(desktop): typo auto-correct and context-aware sentence prediction
Typo auto-correct (INPUT-19)
- TypoCorrectionService + core typo-correction: 2-set Korean layout
  mistypes both ways, always-wrong spellings, near-misses of the user's
  frequent words, optional model check re-validated in core; applied by
  backspace N + paste and cancelled on new keys or window change.

Prediction quality (INPUT-20/21)
- gemma models are sent raw with the user's unfinished sentence pre-filled
  into the model turn, so the model truly continues the text (mid-word
  joins and spacing exact). Other models keep the instruction prompt.
- Context: text before the caret (opening lines and a fact list of names,
  dates, amounts outside the 400-char window), messages just sent in the
  same chat window (memory only, 30 min), personal-graph follow-ups and
  IDF-ranked related sentences with Korean stemming.
- Guards: first sentence only, restated-prefix stripping (also fixes the
  instruction path), repeat drop, no invented dates/names/numbers
  (one retry), plain -다 register, no emoji unless the user uses them,
  search-box keywords. Fill loop mixes instruction prompts for variety.
- Opt-in real-model probe: tests/integration/suggestion-quality.ollama.test.ts

Suggestions now actually show up
- Terminal (Claude Code): caret trust from the input line, not the whole
  screen (status line below the box blocked every keystroke); Korean
  composition counts as typing at the end; a grey placeholder filling the
  empty box at once is not user text.
- Chrome: UIA focus flicker while typing no longer resets "edited".
- KakaoTalk/RichEdit: trailing paragraph mark ignored for edit position
  and stripped so accepted text keeps its separating space.
- While the overlay is visible the suggestion shortcuts are captured so
  Ctrl+Alt+Enter no longer also types a newline; released when hidden.
- nut-js preloaded after boot (first accept waited 4.8 s).
2026-10-03 21:48:28 +09:00

392 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// packages/core — 개인 그래프(관계형 개인화) 정본.
//
// 왜 그래프인가:
// n-gram 문자열 조회(1단계)는 "같은 꼬리 뒤에 이어 쓴 문장" 만 찾는다. 하지만 사용자의
// 글은 관계로 이어진다 — 어떤 문장은 늘 다른 문장 뒤에 오고("follows"), 어떤 문장들은
// 같은 용어를 공유한다("shares_terms"). 그 관계를 저장해 두면 접두가 조금 달라도
// 관련 문맥을 끌어올 수 있다.
//
// 전부 순수 함수로 두어 LLM/DB 없이 검증 가능하게 한다.
import type { PhraseSource } from './input-intelligence'
import { countLexicalWords, getWordSegmenter } from './text-segmentation'
// 렌더러/프리로드도 같은 계약을 쓴다 (main 모듈을 import 할 수 없다).
export type { PhraseSource }
/** 그래프 노드 = 사용자의 문장 하나. */
export interface GraphNode {
text: string
terms: string[]
source: PhraseSource
appName: string | null
count: number
lastUsedAt: number | null
}
export type GraphEdgeKind = 'follows' | 'shares_terms'
/** 그래프 엣지 = 두 문장의 관계. */
export interface GraphEdge {
from: string
to: string
kind: GraphEdgeKind
weight: number
}
/** 그래프 통계 (지식베이스 그래프 탭). */
export interface PersonalGraphStats {
nodes: number
followsEdges: number
sharesTermsEdges: number
/** 가장 강한 follows 엣지 (A → B) */
topEdges: Array<{ from: string; to: string; kind: string; weight: number }>
/** 최근 노드 */
recentNodes: Array<{ text: string; terms: string[]; count: number; appName: string | null }>
}
/** 특정 텍스트 주변 그래프 조회 결과. */
export interface PersonalGraphQuery {
anchors: Array<{ text: string; terms: string[]; count: number }>
neighbors: Array<{ text: string; kind: string; weight: number }>
}
export interface GraphContext {
/** 접두 꼬리 뒤에 실제로 이어 쓴 텍스트 (가장 강한 신호) */
continuations: string[]
/** 관계로 끌어온 관련 문장 (follows 우선, 그다음 용어 공유) */
related: string[]
/**
* 직전 완결 문장(또는 그와 거의 같은 문장) 뒤에 사용자가 실제로 이어 쓴 문장 — follows 엣지.
* "다음 문장" 을 고를 때 가장 강한 근거다. 없으면 생략될 수 있다(호환).
*/
followUps?: string[]
}
/** 용어 추출에서 제외할 불용어 (한/영 최소 집합). */
const STOPWORDS: ReadonlySet<string> = new Set([
'그리고',
'그러나',
'하지만',
'그래서',
'저는',
'제가',
'이거',
'그거',
'저거',
'있습니다',
'합니다',
'입니다',
'the',
'and',
'for',
'with',
'that',
'this',
'from',
'have',
'will',
'your',
'you',
'are',
'was',
'were',
'not',
'but'
])
/** 최소 길이 (1~2자 토큰은 노이즈가 많다). */
const MIN_TERM_CHARS = 2
/**
* 용어 경계 — 어떤 문자 체계든 문자(L)·숫자(N)·결합 부호(M)가 아닌 것.
*
* 예전에는 ASCII/한글/가나/한자만 허용해서 키릴·그리스·아랍·태국 문자는 통째로 사라지고
* 'Präsentation' 같은 악센트 라틴 단어는 'pr' + 'sentation' 조각으로 쪼개졌다.
*/
const TERM_SEPARATOR = /[^\p{L}\p{N}\p{M}]+/u
/** 띄어쓰기 없이 쓰는 문자 체계 — 경계 분리만으로는 문장 전체가 한 토큰이 된다. */
const UNSPACED_SCRIPT = /[\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u
/** 띄어쓰기 없는 문자 체계의 토큰을 사전 기반 단어로 나눈다. 분할기가 없으면 그대로 둔다. */
function segmentUnspacedToken(token: string): string[] {
if (!UNSPACED_SCRIPT.test(token)) return [token]
const segmenter = getWordSegmenter()
if (!segmenter) return [token]
const words: string[] = []
for (const part of segmenter.segment(token)) {
if (part.isWordLike) words.push(part.segment)
}
return words.length > 0 ? words : [token]
}
/**
* 텍스트를 비교용 토큰으로 자른다 (불용어/길이 필터 전 단계).
*
* NFC 정규화 → 소문자화 → 문자/숫자/결합 부호 경계로 분리 → 띄어쓰기 없는 문자 체계는 단어 분할.
* 한글 음절·ASCII·가나·한자로 된 토큰은 예전과 같은 결과를 낸다 (저장된 노드의 terms 와 호환).
*/
export function tokenizeTerms(text: string): string[] {
return text
.normalize('NFC')
.toLowerCase()
.split(TERM_SEPARATOR)
.filter((token) => token.length > 0)
.flatMap(segmentUnspacedToken)
}
/**
* 한국어 어절 끝의 조사·흔한 '하다' 활용을 떼어 낸 어간.
*
* 왜: "회의에서" 와 "회의는" 이 다른 용어로 잡히면 같은 주제의 문장끼리 겹치는 용어가 거의 없어
* 그래프가 관련 문장을 못 찾는다(한국어는 거의 모든 명사에 조사가 붙는다). 남는 어간이 2자 미만이면
* 떼지 않는다 — "회의"(의), "결과"(과) 같은 단어 끝 글자를 조사로 오인하지 않게.
*/
const KOREAN_SUFFIXES: readonly string[] = [
'했습니다', '하겠습니다', '드립니다', '합니다', '했어요', '해요', '했다', '하는', '하고', '해서', '하면', '하기',
'에서는', '에서도', '에서의', '에게서', '으로부터', '로부터', '으로는', '으로도', '이라는', '이라고', '에게는',
'한테서', '에서', '에게', '한테', '으로', '까지', '부터', '처럼', '보다', '만큼', '이나', '이랑', '과는', '와는',
'에는', '에도', '들은', '들이', '들을', '들의',
'은', '는', '이', '가', '을', '를', '에', '의', '도', '로', '만', '와', '과', '랑', '들', '한', '할'
].slice().sort((a, b) => b.length - a.length)
const HANGUL_WORD = /^[가-힣]+$/u
export function stemTerm(token: string): string {
if (!HANGUL_WORD.test(token)) return token
for (const suffix of KOREAN_SUFFIXES) {
if (token.endsWith(suffix) && token.length - suffix.length >= 2) return token.slice(0, -suffix.length)
}
return token
}
/**
* 문장에서 비교용 용어를 뽑는다.
*
* 토큰화 → 한국어 어간화 → 불용어/짧은 토큰 제거 → 빈도 순.
*/
export function extractTerms(text: string, limit = 8): string[] {
const tokens = tokenizeTerms(text)
.map(stemTerm)
.filter((token) => token.length >= MIN_TERM_CHARS)
.filter((token) => !STOPWORDS.has(token))
const frequency = new Map<string, number>()
for (const token of tokens) {
frequency.set(token, (frequency.get(token) ?? 0) + 1)
}
return [...frequency.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, limit)
.map(([token]) => token)
}
/**
* 문장 단위로 쪼갠다 (종결 부호 + 개행). 2단어 이상만 남긴다.
*
* 단어 수는 countLexicalWords 로 센다 — 공백으로만 세면 띄어쓰기 없는 중국어·일본어·태국어
* 문장이 모두 1단어가 되어 그 언어 사용자의 문장이 하나도 학습되지 않는다.
*/
export function splitSentences(text: string): string[] {
return text
.split(/[.!?。!?…\n]+/u)
.map((segment) => segment.replace(/\s+/gu, ' ').trim())
.filter((segment) => segment.length >= 4 && countLexicalWords(segment) >= 2)
}
/** 한 텍스트 안에서 인접한 문장 쌍 (follows 엣지의 근거). */
export function buildSequenceEdges(sentences: readonly string[]): Array<{ from: string; to: string }> {
const edges: Array<{ from: string; to: string }> = []
for (let index = 0; index + 1 < sentences.length; index += 1) {
const from = sentences[index]
const to = sentences[index + 1]
if (from === to) continue
edges.push({ from, to })
}
return edges
}
/** 자카드 유사도 — 두 용어 집합이 얼마나 겹치는가 (0~1). */
export function jaccard(a: readonly string[], b: readonly string[]): number {
if (a.length === 0 || b.length === 0) return 0
const setA = new Set(a)
const setB = new Set(b)
let intersection = 0
for (const term of setA) {
if (setB.has(term)) intersection += 1
}
const union = setA.size + setB.size - intersection
return union === 0 ? 0 : intersection / union
}
/** 용어 공유 엣지로 볼 최소 자카드. */
export const SHARES_TERMS_MIN_SIMILARITY = 0.34
/**
* 접두 꼬리 뒤에 실제로 이어 쓴 텍스트를 뽑는다.
*
* `texts` 는 꼬리를 포함하는 후보 문장들(최신순)이다.
*/
export function continuationsFrom(
texts: readonly string[],
tail: string,
limit = 3,
maxChars = 60
): string[] {
const needle = tail.trim()
if (needle.length < 4) return []
const out: string[] = []
for (const text of texts) {
const index = text.indexOf(needle)
if (index < 0) continue
const continuation = text
.slice(index + needle.length)
.replace(/\s+/gu, ' ')
.trim()
if (continuation.length < 3) continue
const clipped = continuation.slice(0, maxChars)
if (out.includes(clipped)) continue
out.push(clipped)
if (out.length >= limit) break
}
return out
}
export interface RelatedCandidate {
text: string
terms: readonly string[]
/** 엣지 가중치 합 (follows 가중치가 더 크게 반영된다) */
weight: number
lastUsedAt: number | null
}
/**
* 관련 문장 순위를 매긴다.
*
* 점수 = 엣지 가중치 + 용어 유사도 + 최근성 보너스.
* 이미 접두에 포함된 문장(후보 자신)은 제외한다.
*/
export function rankRelated(
anchorTerms: readonly string[],
candidates: readonly RelatedCandidate[],
limit = 4
): string[] {
const scored = candidates
.map((candidate) => {
const similarity = jaccard(anchorTerms, candidate.terms)
const recency = candidate.lastUsedAt
? Math.max(0, 1 - (Date.now() - candidate.lastUsedAt) / (7 * 86400000))
: 0
return { text: candidate.text, score: candidate.weight * 1.0 + similarity * 2.0 + recency * 0.5 }
})
.sort((a, b) => b.score - a.score)
const out: string[] = []
for (const item of scored) {
if (out.includes(item.text)) continue
out.push(item.text)
if (out.length >= limit) break
}
return out
}
// ============================================================
// 관련 문장 점수 (IDF 가중 용어 겹침)
// ============================================================
/** 관련 문장 후보 노드 — 저장소에서 읽은 그대로(용어는 어간화 전일 수 있다). */
export interface GraphNodeSample {
text: string
terms: readonly string[]
count: number
lastUsedAt: number | null
appName: string | null
}
export interface RelatedNodeQuery {
/** 질의 용어 → 가중치 (지금 문장 용어를 앞 문맥보다 무겁게) */
terms: ReadonlyMap<string, number>
appName?: string | null
now?: number
/** 이미 접두에 들어 있는 문장 등 제외할 텍스트 */
exclude?: (text: string) => boolean
}
export interface ScoredNode {
text: string
score: number
sharedTerms: number
}
/**
* 질의 용어와 노드 용어의 겹침을 IDF 로 가중해 순위를 매긴다.
*
* 자카드는 긴 문장일수록 점수가 희석되고, "합니다" 같은 흔한 어절과 "배포" 같은 주제어를 같게
* 센다. 여기서는 훑은 노드 집합에서 드문 용어일수록 무겁게, 노드 길이는 제곱근으로만 나눈다.
* 같은 앱에서 쓴 문장, 최근 문장, 자주 쓴 문장에 가산점을 준다.
*/
export function scoreRelatedNodes(
query: RelatedNodeQuery,
nodes: readonly GraphNodeSample[],
limit = 6
): ScoredNode[] {
if (query.terms.size === 0 || nodes.length === 0) return []
const now = query.now ?? Date.now()
const nodeTerms = nodes.map((node) => new Set(node.terms.map(stemTerm)))
const documentFrequency = new Map<string, number>()
for (const terms of nodeTerms) {
for (const term of terms) documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1)
}
const total = nodes.length
const idf = (term: string): number => Math.log(1 + total / (1 + (documentFrequency.get(term) ?? 0)))
const requestedApp = query.appName?.trim().toLowerCase() || null
const scored: ScoredNode[] = []
nodes.forEach((node, index) => {
if (query.exclude?.(node.text)) return
const terms = nodeTerms[index]
if (terms.size === 0) return
let overlap = 0
let shared = 0
for (const [term, weight] of query.terms) {
if (!terms.has(term)) continue
overlap += weight * idf(term)
shared += 1
}
if (shared === 0) return
const recency = node.lastUsedAt ? Math.max(0, 1 - (now - node.lastUsedAt) / (14 * 86400000)) : 0
const sameApp = requestedApp !== null && node.appName?.trim().toLowerCase() === requestedApp
const score =
(overlap / Math.sqrt(terms.size)) * (sameApp ? 1.3 : 1) +
recency * 0.3 +
Math.log2(1 + Math.max(0, node.count)) * 0.1
scored.push({ text: node.text, score, sharedTerms: shared })
})
scored.sort((a, b) => b.score - a.score || b.sharedTerms - a.sharedTerms)
const out: ScoredNode[] = []
for (const item of scored) {
if (out.some((existing) => existing.text === item.text)) continue
out.push(item)
if (out.length >= limit) break
}
return out
}
/**
* 질의 용어 가중치 — 지금 쓰는 문장 2, 직전 문장 1.5, 앞 문맥 1.
* 같은 용어가 여러 곳에 나오면 가장 큰 가중치를 쓴다.
*/
export function buildQueryTerms(parts: ReadonlyArray<{ text: string; weight: number }>): Map<string, number> {
const terms = new Map<string, number>()
for (const part of parts) {
if (!part.text) continue
for (const term of extractTerms(part.text, 12)) {
terms.set(term, Math.max(terms.get(term) ?? 0, part.weight))
}
}
return terms
}