feat(desktop): typo auto-correct and context-aware sentence prediction
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

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).
This commit is contained in:
Yun Chan 2026-10-03 21:48:28 +09:00
parent 5ca3709b32
commit 3cac14f668
56 changed files with 4700 additions and 258 deletions

View file

@ -0,0 +1,52 @@
// packages/core — 원형(raw) 채팅 템플릿.
//
// 왜 필요한가: 인라인 제안은 "사용자 글을 그대로 이어 쓰기" 다. 모델 차례 앞에 사용자가 쓰던
// 문장을 미리 넣어 두면(prefill) 모델은 그 글자 바로 뒤부터 쓴다 — 단어 중간("회의실"+"에서")과
// 띄어쓰기까지 정확히 이어진다. Ollama 의 채팅 API 는 이어 쓸 때 응답 앞 공백을 지우고 일부
// 렌더러는 차례를 닫아 버려(실측: "검토해 보시" → "부탁드립니다.") 이 용도로 쓸 수 없다.
// 그래서 템플릿을 아는 모델 계열만 직접 그려 `raw` 로 보낸다. 모르는 계열은 null — 호출자는
// 기존(지시형) 경로를 쓴다.
export type RawChatFamily = 'gemma4' | 'gemma'
export interface RawChatInput {
system: string
user: string
/** 모델 차례 앞에 미리 넣을 텍스트 (모델이 이어 쓴다) */
assistantPrefix: string
}
/** 모델 이름(Ollama 태그)으로 원형 템플릿 계열을 판별한다. */
export function detectRawChatFamily(model: string): RawChatFamily | null {
const name = model.trim().toLowerCase().split('/').pop() ?? ''
if (/^gemma-?4/u.test(name)) return 'gemma4'
if (/^gemma-?[23]?(?:[:.-]|$)/u.test(name)) return 'gemma'
return null
}
/** 사용자 텍스트에 섞인 차례 구분 토큰을 지운다 — 문맥 텍스트가 대화 구조를 바꾸지 못하게. */
function stripTurnMarkers(text: string): string {
return text.replace(/<\|?\/?(?:turn|start_of_turn|end_of_turn|bos|eos)\|?>|<(?:turn|end_of_turn)\|>/gu, '')
}
/** 원형 프롬프트를 그린다. 템플릿을 모르는 모델이면 null. */
export function renderRawChatPrompt(model: string, input: RawChatInput): string | null {
const family = detectRawChatFamily(model)
if (!family) return null
const system = stripTurnMarkers(input.system)
const user = stripTurnMarkers(input.user)
const prefix = stripTurnMarkers(input.assistantPrefix)
if (family === 'gemma4') {
return `<|turn>system\n${system}<turn|>\n<|turn>user\n${user}<turn|>\n<|turn>model\n${prefix}`
}
// gemma 2/3 에는 system 차례가 없다 — 첫 user 차례 앞에 붙인다(공식 템플릿과 같음).
return `<start_of_turn>user\n${system}\n\n${user}<end_of_turn>\n<start_of_turn>model\n${prefix}`
}
/** 원형 요청의 정지 문자열 — 차례 종료 토큰이 텍스트로 새어 나와도 거기서 멈춘다. */
export function rawChatStopSequences(model: string): string[] {
const family = detectRawChatFamily(model)
if (family === 'gemma4') return ['<turn|>', '<|turn>']
if (family === 'gemma') return ['<end_of_turn>', '<start_of_turn>']
return []
}

View file

@ -0,0 +1,38 @@
// packages/core — KS X 1001 완성형 한글 2,350자 (상용 음절 집합).
//
// 한영 전환 오타 판정에 쓴다: 영문 자판으로 친 글자를 두벌식으로 바꿨을 때 모든 음절이
// 이 집합에 들면 "실제로 쓰이는 한글" 로 본다('dog' → '앻' 같은 우연한 조합을 걸러 낸다).
// EUC-KR 0xB0A1–0xC8FE 를 디코딩해 생성했다 — 손으로 고치지 않는다.
const COMMON_HANGUL_SYLLABLES =
'가각간갇갈갉갊감갑값갓갔강갖갗같갚갛개객갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆괌괍괏광괘괜' +
'괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄' +
'껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남' +
'납낫났낭낮낯낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨' +
'뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫달닭닮닯닳담답닷닸당닺닻닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗' +
'동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑' +
'뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례' +
'롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많맏말맑맒맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁' +
'먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍' +
'및밑바박밖밗반받발밝밞밟밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤' +
'붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘' +
'삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤샥샨샬샴샵샷샹섀섄섈섐섕서석섞섟선섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠' +
'쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘' +
'쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽' +
'얾엄업없엇었엉엊엌엎에엑엔엘엠엡엣엥여역엮연열엶엷염엽엾엿였영옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜' +
'웝웠웡웨웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응읒읓읔읕읖읗의읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊점접' +
'젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓징짖짙짚짜짝짠짢' +
'짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻찼창찾채책챈챌챔챕챗챘챙챠챤' +
'챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑' +
'캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄' +
'탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀' +
'팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗' +
'피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠' +
'훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝'
const COMMON_SET: ReadonlySet<string> = new Set(COMMON_HANGUL_SYLLABLES)
/** KS X 1001 완성형 2,350자에 드는 음절인가. */
export function isCommonHangulSyllable(char: string): boolean {
return COMMON_SET.has(char)
}

View file

@ -28,13 +28,16 @@ import {
import { NON_PROSE_GLYPH_PATTERN } from './terminal-prompt'
import type { AnchorKind, PhysicalRect } from './popup-placement'
import { countLexicalWords } from './text-segmentation'
import { extractTerms } from './personal-graph'
export {
SUGGESTION_CONTEXT_MAX_CHARS,
SUGGESTION_MAX_OUTPUT_CHARS,
buildLocalSuggestionCandidateEntries,
buildLocalSuggestionCandidates,
containsEmoji,
endsSentence,
extractContinuation,
joinSuggestion,
normalizeRequestPrefix,
normalizeSessionPrefix,
@ -43,7 +46,13 @@ export {
sanitizeSuggestionLine,
stripModelArtifacts
} from './suggestion-text'
export type { LocalSuggestionCandidate, LocalSuggestionHints, SuggestionJoint } from './suggestion-text'
export type {
ContinuationOptions,
ExtractedContinuation,
LocalSuggestionCandidate,
LocalSuggestionHints,
SuggestionJoint
} from './suggestion-text'
export { extractTerminalPromptPrefix } from './terminal-prompt'
// ============================================================
@ -193,7 +202,11 @@ export const PASTE_INSERTION_THRESHOLD_CHARS = 200
* computeTypedDelta 와 같은 공통 접두/접미 분해를 쓴다. 바뀐 구간 뒤에 남은 공통 접미가 없으면
* 끝에서 쓰거나 지운 것이다. 같으면(편집 없음) true.
*/
export function isEditAtTextEnd(prevText: string, nextText: string): boolean {
export function isEditAtTextEnd(prevRaw: string, nextRaw: string): boolean {
// RichEdit 계열(카카오톡 등)은 값 끝에 줄끝 문자(\r)를 붙여 돌려준다. 그대로 비교하면 모든 편집이
// "뒤에 기존 글이 남은 중간 편집" 이 되어 caret-unknown 으로 막혔다(실측 2026-10-03, 카톡 79회).
const prevText = prevRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
const nextText = nextRaw.replace(/[\r\n\u200b\ufeff]+$/u, '')
if (prevText === nextText) return true
let prefix = 0
const maxPrefix = Math.min(prevText.length, nextText.length)
@ -827,9 +840,24 @@ export function isLearnablePhrase(text: string): boolean {
* 텍스트가 컨트롤 이름과 같으면 빈 칸으로 취급한다.
*/
export function withoutPlaceholderText(snapshot: FocusSnapshot): FocusSnapshot {
const name = snapshot.controlName?.trim()
if (!name || snapshot.text.trim() !== name) return snapshot
return { ...snapshot, text: '', caretOffset: null }
const trimmedEnd = withoutRichEditEndMark(snapshot)
const name = trimmedEnd.controlName?.trim()
if (!name || trimmedEnd.text.trim() !== name) return trimmedEnd
return { ...trimmedEnd, text: '', caretOffset: null }
}
/**
* RichEdit 계열 입력칸(카카오톡 등)이 값 끝에 붙이는 문단 끝 표시(\r 하나)를 걷어낸다.
*
* 그대로 두면 커서 앞 글이 공백으로 끝난 것처럼 보여, 수락한 제안이 띄어쓰기 없이 들러붙었다
* (실측 2026-10-03: "오늘 저녁에 시간 되면\r" + "같이 저녁 먹을래?" → "되면같이"). 사용자가 넣은
* 줄바꿈은 그 앞에 \r 이 하나 더 있으므로("…\r\r") 하나만 지운다. 표준 줄바꿈(\r\n)은 건드리지 않는다.
*/
export function withoutRichEditEndMark(snapshot: FocusSnapshot): FocusSnapshot {
if (!snapshot.text.endsWith('\r')) return snapshot
const text = snapshot.text.slice(0, -1)
const caretOffset = snapshot.caretOffset === null ? null : Math.min(snapshot.caretOffset, text.length)
return { ...snapshot, text, caretOffset }
}
// ============================================================
@ -1092,6 +1120,22 @@ export interface PhraseHintOptions {
appName?: string | null
now?: number
halfLifeDays?: number
/**
* 지금 쓰는 글의 용어(어간화된 것). 주면 겹치는 용어가 많은 문구를 앞세우고,
* 겹치는 용어도 없고 같은 앱도 아닌 문구는 뺀다 — 문맥과 무관한 "자주 쓰는 말" 이
* 프롬프트를 흐리지 않게 한다. 생략하면 예전처럼 빈도·최근·앱만 본다.
*/
relevanceTerms?: ReadonlySet<string>
}
/** 문구가 주어진 용어 중 몇 개를 품는가 (문구 쪽도 같은 규칙으로 어간화). */
function countSharedTerms(phrase: string, terms: ReadonlySet<string>): number {
if (terms.size === 0) return 0
let shared = 0
for (const term of new Set(extractTerms(phrase, 16))) {
if (terms.has(term)) shared += 1
}
return shared
}
/**
@ -1130,6 +1174,7 @@ export function selectPhraseHints(
? (options.halfLifeDays as number)
: 30
const requestedApp = options.appName?.trim().toLowerCase() ?? null
const relevanceTerms = options.relevanceTerms ?? null
const candidates = phrases
.filter((p) => p.phrase.length <= SUGGESTION_MAX_OUTPUT_CHARS)
.filter((p) => !tail || !p.phrase.toLowerCase().endsWith(tail))
@ -1138,13 +1183,17 @@ export function selectPhraseHints(
const ageDays = Math.max(0, (now - timestamp) / (24 * 60 * 60 * 1000))
const appMatches =
requestedApp !== null && phrase.appName !== null && phrase.appName.trim().toLowerCase() === requestedApp
const relevance = relevanceTerms ? countSharedTerms(phrase.phrase, relevanceTerms) : 0
const score =
(1 + Math.log2(Math.max(1, phrase.count))) *
Math.pow(0.5, ageDays / halfLifeDays) *
(appMatches ? 1.75 : 1)
(appMatches ? 1.75 : 1) *
(1 + relevance * 1.5)
return { phrase, score, timestamp }
return { phrase, score, timestamp, relevance, appMatches }
})
// 문맥 용어가 주어지면, 지금 글과 겹치는 용어가 없고 다른 앱에서 쓴 문구는 프롬프트 잡음이다.
.filter((entry) => !relevanceTerms || relevanceTerms.size === 0 || entry.relevance > 0 || entry.appMatches)
.sort(
(a, b) =>
b.score - a.score ||
@ -1214,6 +1263,8 @@ export interface SuggestionState {
telemetryEnabled: boolean
/** 오버레이 클릭 허용 여부 (false → 완전 클릭 통과) */
overlayInteractive: boolean
/** 입력 중 오타 자동 교정 켜짐 (설정 UI 표시) */
typoAutoCorrect: boolean
/** 후보를 만든 로컬 근거의 수량만 노출한다. */
provenance: SuggestionProvenance | null
}

View file

@ -56,6 +56,11 @@ export interface GraphContext {
continuations: string[]
/** 관계로 끌어온 관련 문장 (follows 우선, 그다음 용어 공유) */
related: string[]
/**
* 직전 완결 문장(또는 그와 거의 같은 문장) 뒤에 사용자가 실제로 이어 쓴 문장 — follows 엣지.
* "다음 문장" 을 고를 때 가장 강한 근거다. 없으면 생략될 수 있다(호환).
*/
followUps?: string[]
}
/** 용어 추출에서 제외할 불용어 (한/영 최소 집합). */
@ -131,13 +136,39 @@ export function tokenizeTerms(text: string): string[] {
.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))
@ -260,4 +291,102 @@ export function rankRelated(
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
}

View file

@ -0,0 +1,94 @@
// packages/core — "이 창에서 조금 전에 쓴 글" 기억 (메모리 전용, 순수 로직).
//
// 왜 필요한가: 채팅·메신저는 보내는 순간 입력칸이 빈다. 그래서 다음 메시지를 쓸 때 커서 앞
// 텍스트에는 방금 보낸 말이 없고, 모델은 대화가 어디까지 왔는지 모른다("ㅇㅋ 그럼 나도 " 만 보고
// 엉뚱한 말을 잇는다). 입력칸이 비워지는 순간 직전 내용을 "보낸 글" 로 잠시 기억했다가 같은 창의
// 다음 제안 문맥에 넣는다.
//
// 저장하지 않는다 — 프로세스 메모리에만, 짧게(기본 30분) 둔다.
export interface RecentWriteMeta {
windowHandle: number | null
appName: string | null
windowTitle: string | null
}
export interface RecentWrite extends RecentWriteMeta {
text: string
at: number
}
export interface RecentWritesOptions {
ttlMs?: number
maxEntries?: number
maxChars?: number
}
const DEFAULT_TTL_MS = 30 * 60_000
const DEFAULT_MAX_ENTRIES = 24
const DEFAULT_MAX_CHARS = 600
function sameWindow(a: RecentWriteMeta, b: RecentWriteMeta): boolean {
if (a.windowHandle !== null && b.windowHandle !== null && a.windowHandle === b.windowHandle) return true
const appA = a.appName?.trim().toLowerCase()
const appB = b.appName?.trim().toLowerCase()
return Boolean(appA) && appA === appB && Boolean(a.windowTitle) && a.windowTitle === b.windowTitle
}
export class RecentWritesBuffer {
private _entries: RecentWrite[] = []
private _fieldKey = ''
private _fieldText = ''
private readonly _ttlMs: number
private readonly _maxEntries: number
private readonly _maxChars: number
constructor(options: RecentWritesOptions = {}) {
this._ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
this._maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES
this._maxChars = options.maxChars ?? DEFAULT_MAX_CHARS
}
/**
* 입력칸 스냅샷을 본다. 같은 칸에서 내용이 있던 칸이 비워지면(보냄) 직전 내용을 기억한다.
*
* 칸이 바뀌면 기준만 다시 잡는다 — 다른 칸으로 옮겨 간 것은 "보냄" 이 아니다.
* 일부만 지운 경우(고쳐 쓰기)도 보냄이 아니다: 남은 글이 없을 때만 기록한다.
*/
observe(fieldKey: string, text: string, meta: RecentWriteMeta, now: number): RecentWrite | null {
if (fieldKey !== this._fieldKey) {
this._fieldKey = fieldKey
this._fieldText = text
return null
}
const previous = this._fieldText.trim()
this._fieldText = text
if (text.trim().length > 0 || previous.length < 2) return null
const entry: RecentWrite = {
...meta,
text: previous.length > this._maxChars ? previous.slice(-this._maxChars) : previous,
at: now
}
this._prune(now)
this._entries.push(entry)
if (this._entries.length > this._maxEntries) this._entries.splice(0, this._entries.length - this._maxEntries)
return entry
}
/** 같은 창에서 조금 전에 쓴 글 (오래된 것부터, 최대 limit 개). */
listFor(meta: RecentWriteMeta, now: number, limit = 4): RecentWrite[] {
this._prune(now)
return this._entries.filter((entry) => sameWindow(entry, meta)).slice(-limit)
}
clear(): void {
this._entries = []
this._fieldKey = ''
this._fieldText = ''
}
private _prune(now: number): void {
this._entries = this._entries.filter((entry) => now - entry.at <= this._ttlMs)
}
}

View file

@ -115,6 +115,34 @@ export function sanitizeSuggestionLine(line: string, maxChars = SUGGESTION_MAX_O
return stripped === null ? null : normalizeSuggestionText(stripped, maxChars)
}
const WORD_BOUNDARY_AFTER = /^[\s.,!?;:。、,!?…"'”’)\]]/u
/**
* 후보 머리가 접두(지금 문장) 꼬리를 되풀이하면 그 부분을 걷어낸다.
*
* 되풀이로 보는 조건: 접두의 지금 문장 안에서 어절 경계부터 시작하는 꼬리(2자 이상)가 후보의
* 머리와 같고, 후보 쪽에서도 그 뒤가 어절 경계다. "회의실" + "실에서" 같은 우연한 글자 겹침은
* 어절 경계 조건에 걸려 그대로 둔다. 되풀이 말고 남는 것이 없으면 '' 를 돌려준다.
*/
export function stripRestatedPrefix(candidate: string, prefix: string): string {
const sentenceStart = Math.max(
...['.', '!', '?', '。', '!', '?', '…', '\n'].map((mark) => prefix.lastIndexOf(mark) + 1)
)
const sentence = prefix.slice(sentenceStart).replace(/\s+/gu, ' ').trim()
if (sentence.length < 2) return candidate
const lowerCandidate = candidate.toLowerCase()
const lowerSentence = sentence.toLowerCase()
for (let start = 0; start <= lowerSentence.length - 2; start += 1) {
if (start > 0 && lowerSentence[start - 1] !== ' ') continue
const tail = lowerSentence.slice(start)
if (!lowerCandidate.startsWith(tail)) continue
const rest = candidate.slice(tail.length)
if (rest.length > 0 && !WORD_BOUNDARY_AFTER.test(rest)) continue
return rest.trim()
}
return candidate
}
/**
* 모델 출력에서 후보 목록을 뽑아 정제한다.
*
@ -128,13 +156,16 @@ export function parseSuggestionCandidates(
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
if (!raw) return []
const prefixTail = normalizeRequestPrefix(prefix).slice(-24).toLowerCase()
const normalizedPrefix = normalizeRequestPrefix(prefix)
const out: string[] = []
for (const line of raw.split(/\r?\n/u)) {
const cleaned = sanitizeSuggestionLine(line, maxChars)
if (!cleaned) continue
if (prefixTail && cleaned.toLowerCase().startsWith(prefixTail)) continue
const sanitized = sanitizeSuggestionLine(line, maxChars)
if (!sanitized) continue
// 지금 문장의 앞부분을 다시 쓰고 이어 간 후보는 되풀이한 부분만 걷어낸다 — 그대로 넣으면
// "CI는 CI는 통과했고…" 처럼 같은 말이 두 번 들어간다(실측). 되풀이뿐이면 버린다.
const cleaned = stripRestatedPrefix(sanitized, normalizedPrefix)
if (!cleaned || cleaned.length < 2) continue
if (out.some((existing) => existing.toLowerCase() === cleaned.toLowerCase())) continue
out.push(cleaned)
if (out.length >= maxCandidates) break
@ -308,3 +339,104 @@ export function joinSuggestion(rawPrefix: string, candidate: string, joint: Sugg
if (UNSPACED_JOIN_SCRIPT.test(before) || UNSPACED_JOIN_SCRIPT.test(after)) return candidate
return ` ${candidate}`
}
// ============================================================
// 이어 쓰기(prefill) 출력 정제
// ============================================================
export interface ContinuationOptions {
/** 지금 문장 마저 쓰기인가, 다음 문장인가 */
mode: 'complete-sentence' | 'next-sentence'
/** 모델 차례 앞에 미리 넣은 사용자 글 (모델은 이 바로 뒤부터 쓴다) */
prefill: string
/** 이미 쓴 문장들 — 모델이 같은 문장을 되풀이하면 버린다 */
writtenSentences?: readonly string[]
/**
* 사용자가 친 원문이 공백으로 끝났는가(단어를 끝냈는가). prefill 은 끝 공백을 빼고 보낸다 —
* 끝 공백 하나만 남은 토큰 상태는 모델 분포를 흔들어 엉뚱한 말을 만든다(실측). 그 대신 모델이
* 끝난 단어에 글자를 붙여 쓰면(공백 없이 시작) 버린다.
*/
wordFinished?: boolean
/** 사용자가 이모지를 쓰는가 — 아니면 모델이 붙인 이모지를 지운다 */
allowEmoji?: boolean
maxChars?: number
}
export interface ExtractedContinuation {
text: string
joint: SuggestionJoint
}
const EMOJI_PATTERN = /\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}]|\u200d|\ufe0f/gu
const LEADING_LIST_MARKER = /^(?:[-*•]|\d{1,3}[.)])\s+/u
/** 텍스트에 이모지가 있는가 (사용자 습관 판별). */
export function containsEmoji(text: string): boolean {
return /\p{Extended_Pictographic}/u.test(text)
}
/** 원형 템플릿 응답에 섞일 수 있는 특수 토큰·마크다운 강조. */
const SPECIAL_TOKEN_PATTERN = /<\|?\/?(?:turn|start_of_turn|end_of_turn|eos|bos|im_start|im_end|channel|message)\|?>|<(?:turn|end_of_turn|eos)\|>/gu
const MARKDOWN_EMPHASIS_PATTERN = /\*\*|__/gu
/** 첫 문장의 끝 — 종결 부호(+닫는 따옴표/괄호) 뒤가 공백이거나 끝. "3.5", "v1.2" 의 점은 아니다. */
const FIRST_SENTENCE_END = /[.!?。!?…]+["'”’)\]]*(?=\s|$)/u
function comparable(text: string): string {
return text.replace(/[\s.!?。!?…,"'“”‘’]+/gu, '').toLowerCase()
}
/**
* prefill 한 응답(모델이 사용자 글 바로 뒤부터 쓴 텍스트)에서 삽입할 이어 쓰기를 뽑는다.
*
* 응답 원문은 사용자 글과 이음새까지 그대로 이어진다 — 첫 글자가 공백이면 새 단어이고, 아니면
* 단어 중간("회의실" + "에서")이다. 그 정보를 joint 로 보존한 뒤 첫 줄·첫 문장만 남긴다.
* 사용자 글이 이어지는 것이므로 목록 표지·따옴표는 지우지 않는다(사용자가 목록을 쓰는 중일 수 있다).
*/
export function extractContinuation(raw: string, options: ContinuationOptions): ExtractedContinuation | null {
const maxChars = options.maxChars ?? SUGGESTION_MAX_OUTPUT_CHARS
let text = raw.replace(SPECIAL_TOKEN_PATTERN, '').replace(MARKDOWN_EMPHASIS_PATTERN, '')
if (options.mode === 'complete-sentence') {
// 줄바꿈부터 시작하면 모델은 지금 문장이 이미 끝났다고 본 것이다 — 이어 쓸 것이 없다.
if (/^[ \t]*\n/u.test(text)) return null
} else {
text = text.replace(/^\s*\n/u, ' ')
}
const startsNewWord = /^\s/u.test(text)
if (!options.allowEmoji) text = text.replace(EMOJI_PATTERN, '')
// 끝난 단어 뒤에 모델이 글자를 붙였다("회의실 " + "에서") — 그대로 넣으면 띄어 쓴 조사가 된다.
if (options.wordFinished && !startsNewWord && /^[\p{L}\p{N}]/u.test(text)) return null
text = text.replace(/^\s+/u, '').split(/\r?\n/u)[0] ?? ''
// 목록 줄이 아닌데 "- " 로 시작하면 힌트 목록 형식을 베낀 것이다.
const prefillLastLine = options.prefill.split('\n').pop() ?? ''
const onListLine = LEADING_LIST_MARKER.test(prefillLastLine.trim()) || /\n$/u.test(options.prefill)
if (!onListLine) text = text.replace(LEADING_LIST_MARKER, '')
// 모델이 지금 문장을 처음부터 다시 쓴 경우 — 이미 쓴 부분을 걷어낸다.
const prefill = options.prefill.replace(/\s+/gu, ' ').trim()
if (options.mode === 'complete-sentence' && prefill.length >= 4) {
const normalized = text.replace(/\s+/gu, ' ')
if (normalized.startsWith(prefill)) text = normalized.slice(prefill.length).replace(/^\s+/u, '')
}
const end = FIRST_SENTENCE_END.exec(text)
if (end) text = text.slice(0, end.index + end[0].length)
if (INSTRUCTION_ECHO_PATTERN.test(text) || TEMPLATE_ECHO_PATTERN.test(text)) return null
const normalized = normalizeSuggestionText(text, maxChars)
// 마저 쓰기에서는 마침표 하나("뵙겠습니다" + ".")도 정당한 나머지다 — 글자 수 하한을 따로 둔다.
const result = normalized ?? (options.mode === 'complete-sentence' && text.trim().length > 0 ? text.trim() : null)
if (!result || !/[\p{L}\p{N}]/u.test(result)) return null
// 이미 쓴 문장 되풀이
const key = comparable(result)
if (key.length >= 6 && (options.writtenSentences ?? []).some((sentence) => comparable(sentence) === key)) return null
const joint: SuggestionJoint =
options.mode === 'complete-sentence' && !startsNewWord && !options.wordFinished && !/\s$/u.test(options.prefill)
? 'attach'
: 'separate'
return { text: result, joint }
}

View file

@ -564,6 +564,15 @@ export interface AppConfig {
* 바꿀 때마다 ConfigService 의 개정판을 올려 1회 마이그레이션한다.
*/
suggestionTuningRevision: number
/**
* 입력 중 오타 자동 교정 — 사용자가 멈추면 커서 앞 구간의 명백한 오타(한영 전환·늘 틀린 철자·
* 개인 어휘 근접)를 바로 고친다. 입력 수집 동의가 있어야 동작한다(제안과 같은 입력 맥락).
*/
typoAutoCorrectEnabled: boolean
/** 결정적 규칙에 더해 로컬 모델로 문장 단위 오타도 찾는다 (제안 모델 사용) */
typoAutoCorrectUseModel: boolean
/** 사용자가 교정을 되돌려 다시 고치지 않을 단어 */
typoIgnoredWords: string[]
}
export interface ConfigGetParams {

View file

@ -0,0 +1,745 @@
// packages/core — 입력 중 오타 자동 교정 정본 (순수 함수).
//
// 사용자가 멈춘 순간 커서 바로 앞 구간에서 "명백한" 오타만 찾아 고친다. 판단은 세 층이다:
// 1) 한영 전환 오타 — 한글 문맥에서 영문 자판으로 친 단어(dkssud → 안녕)와 그 반대.
// 두벌식 변환 결과가 KS X 1001 상용 음절로만 이뤄질 때만 고친다.
// 2) 늘 틀린 철자 사전 — 됬→됐, 할께→할게, teh→the 처럼 맞는 쓰임이 없는 형태.
// 3) 개인 어휘 근접 — 사용자가 자주 쓰는 영단어와 한 글자 차이인 처음 보는 단어.
// 모델(LLM)이 찾은 오타는 validateModelCorrections 가 같은 안전 기준으로 다시 거른다.
//
// 교정은 텍스트를 바꾸는 일이라 오탐 비용이 크다 — 모든 규칙은 "확실할 때만" 쪽으로 기운다.
// Electron/Node 의존 금지.
import { isCommonHangulSyllable } from './hangul-common-syllables'
// ============================================================
// 타입
// ============================================================
export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model'
/** 접두(커서 앞 텍스트) 안의 교정 하나. start/end 는 접두 문자열 오프셋(UTF-16)이다. */
export interface TypoCorrection {
start: number
end: number
from: string
to: string
source: TypoSource
}
/** 대상 앱에 보낼 교정 동작 — 커서 앞에서 deleteCount 글자를 지우고 insertText 를 넣는다. */
export interface TypoReplacementPlan {
deleteCount: number
insertText: string
/** 교체 전 구간 원문 (되돌리기 감지·로그용) */
originalText: string
corrections: TypoCorrection[]
}
export interface TypoDetectOptions {
/** 사용자가 되돌려서 다시 고치지 않을 단어 (소문자 비교) */
ignoredWords?: readonly string[]
/** 사용자가 자주 쓰는 단어 → 빈도 (개인 어휘) */
vocabulary?: ReadonlyMap<string, number>
/**
* 마지막 토큰(커서 바로 앞, 뒤에 공백이 없는 단어)도 검사할까 — 사용자가 멈췄을 때만 참.
* 거짓이면 아직 치는 중일 수 있는 마지막 단어는 건드리지 않는다.
*/
includeTrailingToken?: boolean
}
/** 교정 대상 구간 상한 — 커서에서 이보다 먼 곳은 고치지 않는다(백스페이스 수 제한). */
export const TYPO_REGION_MAX_CHARS = 120
/** 사용자가 멈춘 것으로 보고 교정을 적용할 최소 유휴 시간 (ms) */
export const TYPO_MIN_IDLE_MS = 600
/** 교정을 되돌린 것으로 판단하는 시간 창 (ms) */
export const TYPO_REVERT_WINDOW_MS = 30_000
/** 무시 단어 목록 상한 */
export const TYPO_IGNORED_WORDS_MAX = 300
// ============================================================
// 토큰
// ============================================================
export interface WordToken {
text: string
start: number
end: number
}
const WORD_PATTERN = /[\p{L}\p{N}'’]+/gu
const HANGUL_SYLLABLE = /[가-힣]/u
const HANGUL_ANY = /[가-힣ㄱ-ㆎ]/u
const LATIN_LETTER = /[A-Za-z]/u
/** 텍스트를 단어 토큰(오프셋 포함)으로 자른다. */
export function tokenizeWords(text: string): WordToken[] {
const out: WordToken[] = []
for (const match of text.matchAll(WORD_PATTERN)) {
const index = match.index ?? 0
out.push({ text: match[0], start: index, end: index + match[0].length })
}
return out
}
/**
* 교정을 검사할 구간의 시작 오프셋 — 커서에서 TYPO_REGION_MAX_CHARS 안이고, 줄바꿈을 넘지 않는다.
* 단어 중간에서 시작하지 않도록 다음 공백 뒤로 맞춘다.
*/
export function typoRegionStart(prefix: string): number {
let start = Math.max(0, prefix.length - TYPO_REGION_MAX_CHARS)
const lastBreak = Math.max(prefix.lastIndexOf('\n'), prefix.lastIndexOf('\r'))
if (lastBreak + 1 > start) return lastBreak + 1
if (start > 0 && !/\s/u.test(prefix[start - 1] ?? '')) {
const space = prefix.slice(start).search(/\s/u)
start = space < 0 ? prefix.length : start + space + 1
}
return start
}
function scriptCounts(text: string): { hangul: number; latin: number } {
let hangul = 0
let latin = 0
for (const char of text) {
if (HANGUL_ANY.test(char)) hangul += 1
else if (LATIN_LETTER.test(char)) latin += 1
}
return { hangul, latin }
}
/** URL·메일·경로·코드처럼 보이는 단어 주변 — 교정하지 않는다. */
function looksTechnical(prefix: string, token: WordToken): boolean {
const before = prefix[token.start - 1] ?? ''
const after = prefix[token.end] ?? ''
if (/[@/\\:._#$`<>{}=-]/u.test(before) || /[@/\\:_#$`<>{}=(]/u.test(after)) return true
if (after === '.' && /[A-Za-z]/u.test(prefix[token.end + 1] ?? '')) return true
if (/\d/u.test(token.text)) return true
return false
}
// ============================================================
// 두벌식 변환 (한영 전환 오타)
// ============================================================
const CHO = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']
const JUNG = ['ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ']
const JONG = ['', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']
const KEY_TO_JAMO: Readonly<Record<string, string>> = {
r: 'ㄱ', R: 'ㄲ', s: 'ㄴ', e: 'ㄷ', E: 'ㄸ', f: 'ㄹ', a: 'ㅁ', q: 'ㅂ', Q: 'ㅃ', t: 'ㅅ', T: 'ㅆ',
d: 'ㅇ', w: 'ㅈ', W: 'ㅉ', c: 'ㅊ', z: 'ㅋ', x: 'ㅌ', v: 'ㅍ', g: 'ㅎ',
k: 'ㅏ', o: 'ㅐ', O: 'ㅒ', i: 'ㅑ', j: 'ㅓ', p: 'ㅔ', P: 'ㅖ', u: 'ㅕ', h: 'ㅗ', y: 'ㅛ',
n: 'ㅜ', b: 'ㅠ', m: 'ㅡ', l: 'ㅣ'
}
const JAMO_TO_KEYS: Readonly<Record<string, string>> = (() => {
const map: Record<string, string> = {}
for (const [key, jamo] of Object.entries(KEY_TO_JAMO)) map[jamo] = key
const compounds: Record<string, string> = {
ㅘ: 'hk', ㅙ: 'ho', ㅚ: 'hl', ㅝ: 'nj', ㅞ: 'np', ㅟ: 'nl', ㅢ: 'ml',
ㄳ: 'rt', ㄵ: 'sw', ㄶ: 'sg', ㄺ: 'fr', ㄻ: 'fa', ㄼ: 'fq', ㄽ: 'ft', ㄾ: 'fx', ㄿ: 'fv', ㅀ: 'fg', ㅄ: 'qt'
}
return { ...map, ...compounds }
})()
const VOWEL_COMBINE: Readonly<Record<string, string>> = {
'ㅗㅏ': 'ㅘ', 'ㅗㅐ': 'ㅙ', 'ㅗㅣ': 'ㅚ', 'ㅜㅓ': 'ㅝ', 'ㅜㅔ': 'ㅞ', 'ㅜㅣ': 'ㅟ', 'ㅡㅣ': 'ㅢ'
}
const FINAL_COMBINE: Readonly<Record<string, string>> = {
'ㄱㅅ': 'ㄳ', 'ㄴㅈ': 'ㄵ', 'ㄴㅎ': 'ㄶ', 'ㄹㄱ': 'ㄺ', 'ㄹㅁ': 'ㄻ', 'ㄹㅂ': 'ㄼ', 'ㄹㅅ': 'ㄽ',
'ㄹㅌ': 'ㄾ', 'ㄹㅍ': 'ㄿ', 'ㄹㅎ': 'ㅀ', 'ㅂㅅ': 'ㅄ'
}
const NOT_FINAL = new Set(['ㄸ', 'ㅃ', 'ㅉ'])
function isVowelJamo(jamo: string): boolean {
return JUNG.includes(jamo)
}
function composeSyllable(cho: string, jung: string, jong: string): string {
const c = CHO.indexOf(cho)
const v = JUNG.indexOf(jung)
const f = JONG.indexOf(jong)
if (c < 0 || v < 0 || f < 0) return `${cho}${jung}${jong}`
return String.fromCharCode(0xac00 + (c * 21 + v) * 28 + f)
}
/** 두벌식 변환 결과 — complete 가 거짓이면 홀로 남은 자모가 있다(완성되지 않은 조합). */
export interface LayoutConversion {
text: string
complete: boolean
}
/** 영문 자판으로 친 글자를 두벌식 한글로 바꾼다 (자모 조합 오토마타). */
export function latinToHangul(input: string): LayoutConversion {
let out = ''
let complete = true
let cho = ''
let jung = ''
let jong: string[] = []
const flush = (): void => {
if (cho && jung) {
const finalJamo = jong.length === 2 ? FINAL_COMBINE[jong.join('')] ?? '' : jong[0] ?? ''
out += composeSyllable(cho, jung, finalJamo)
} else if (cho || jung) {
out += `${cho}${jung}`
complete = false
}
cho = ''
jung = ''
jong = []
}
for (const char of input) {
const keyed = KEY_TO_JAMO[char] ?? KEY_TO_JAMO[char.toLowerCase()]
if (!keyed) {
flush()
out += char
complete = false
continue
}
if (isVowelJamo(keyed)) {
if (jong.length > 0) {
// 받침이 다음 음절의 초성이 된다 (겹받침이면 뒤 자음만 넘어간다)
const moved = jong.pop() ?? ''
flush()
cho = moved
jung = keyed
} else if (cho && !jung) {
jung = keyed
} else if (jung && VOWEL_COMBINE[`${jung}${keyed}`]) {
jung = VOWEL_COMBINE[`${jung}${keyed}`]
} else {
flush()
jung = keyed
}
continue
}
// 자음
if (!cho && !jung) {
cho = keyed
} else if (cho && !jung) {
flush()
cho = keyed
} else if (!cho && jung) {
flush()
cho = keyed
} else if (jong.length === 0) {
if (NOT_FINAL.has(keyed)) {
flush()
cho = keyed
} else {
jong = [keyed]
}
} else if (jong.length === 1 && FINAL_COMBINE[`${jong[0]}${keyed}`]) {
jong = [jong[0], keyed]
} else {
flush()
cho = keyed
}
}
flush()
return { text: out, complete }
}
/** 한글(완성형·호환 자모)을 두벌식 자판의 영문 키로 되돌린다. 바꿀 수 없는 글자는 그대로 둔다. */
export function hangulToLatin(input: string): string {
let out = ''
for (const char of input) {
const code = char.charCodeAt(0)
if (code >= 0xac00 && code <= 0xd7a3) {
const index = code - 0xac00
const cho = CHO[Math.floor(index / 588)]
const jung = JUNG[Math.floor((index % 588) / 28)]
const jong = JONG[index % 28]
out += `${JAMO_TO_KEYS[cho] ?? ''}${JAMO_TO_KEYS[jung] ?? ''}${jong ? JAMO_TO_KEYS[jong] ?? '' : ''}`
} else if (JAMO_TO_KEYS[char]) {
out += JAMO_TO_KEYS[char]
} else {
out += char
}
}
return out
}
/** 한글 음절을 (초성, 중성, 종성) 자모 단위 배열로 푼다 — 철자 거리 계산용. */
export function decomposeHangul(input: string): string[] {
const out: string[] = []
for (const char of input) {
const code = char.charCodeAt(0)
if (code >= 0xac00 && code <= 0xd7a3) {
const index = code - 0xac00
out.push(CHO[Math.floor(index / 588)], JUNG[Math.floor((index % 588) / 28)])
const jong = JONG[index % 28]
if (jong) out.push(jong)
} else {
out.push(char.toLowerCase())
}
}
return out
}
/** 인접 전치까지 1로 세는 편집 거리 (Damerau–Levenshtein, OSA). */
export function editDistance(a: readonly string[], b: readonly string[]): number {
const rows = a.length + 1
const cols = b.length + 1
const table: number[][] = Array.from({ length: rows }, (_, i) =>
Array.from({ length: cols }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))
)
for (let i = 1; i < rows; i += 1) {
for (let j = 1; j < cols; j += 1) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1
let value = Math.min(table[i - 1][j] + 1, table[i][j - 1] + 1, table[i - 1][j - 1] + cost)
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
value = Math.min(value, table[i - 2][j - 2] + 1)
}
table[i][j] = value
}
}
return table[a.length][b.length]
}
/** 철자 거리 — 한글은 자모 단위, 그 밖은 글자 단위. */
export function spellingDistance(a: string, b: string): number {
return editDistance(decomposeHangul(a), decomposeHangul(b))
}
// ============================================================
// 영어 상용어 (한영 오타 오탐 방지 · 역방향 판정)
// ============================================================
const COMMON_ENGLISH_WORDS: ReadonlySet<string> = new Set(
(
'a about above after again against all also am an and any are as at back be because been before being ' +
'below between both but by can could day did do does doing done down during each even every few find first ' +
'for from get give go going good got great had has have having he her here hers him his how i if in into ' +
'is it its just know last let like little long look make man many me more most much must my never new next ' +
'no nor not now of off ok okay old on once one only or other our out over own people please right said same ' +
'say see she should so some still such take than thank thanks that the their them then there these they ' +
'thing think this those through time to too two under until up us use very want was way we well were what ' +
'when where which while who why will with work would year yes yet you your yours ' +
'hello hi hey bye sure fine nice cool yeah yep nope maybe today tomorrow tonight morning night week ' +
'meeting report update team project plan check send sent email mail call later soon time file data test ' +
'code app api bug fix issue review deploy build release server client user users design doc docs note ' +
'notes slack zoom google chrome react node python java sql json http https www com net org io ' +
'dog cat cup car bus run fun sun box map top tip pop hot hit kit lot dot pot ' +
'help love live life home house job jobs money free open close start stop end ask told tell talk ' +
'idea ideas easy hard fast slow high low big small best better worse worst happy sorry welcome done'
).split(/\s+/u)
)
/** 흔한 영단어인가 (소문자 비교). */
export function isCommonEnglishWord(word: string): boolean {
return COMMON_ENGLISH_WORDS.has(word.toLowerCase())
}
const ENGLISH_VOWELS = /[aeiou]/giu
/** 영단어처럼 읽히지 않는 철자인가 — 모음(aeiou) 비율이 낮다. */
function looksUnpronounceableLatin(word: string): boolean {
const vowels = word.match(ENGLISH_VOWELS)?.length ?? 0
return vowels / word.length < 0.25
}
/**
* 한글 문맥에서 영문 자판으로 친 단어인가 → 고칠 한글을 돌려준다.
*
* 조건: 단어 전체가 두벌식 키 글자, 변환이 홀로 남은 자모 없이 완성되고 모든 음절이 상용 음절,
* 2음절 이상, 흔한 영단어가 아님. 주변이 한글 위주이거나(문맥) 단어 자체가 3음절 이상이면서
* 영단어처럼 읽히지 않을 때만 고친다.
*/
export function detectLatinTypedHangul(
word: string,
context: { hangul: number; latin: number }
): string | null {
if (!/^[A-Za-z]+$/u.test(word) || word.length < 2) return null
// 전부 대문자(약어)는 건드리지 않는다.
if (/^[A-Z]+$/u.test(word)) return null
// 두벌식에서 Shift 가 의미 있는 키(R E Q T W O P) 외의 대문자는 한글 입력이 아니다 —
// 첫 글자만 대문자인 영단어(고유명사·문장 시작)도 여기서 걸러진다.
if (/[A-DF-NSUVX-Z]/u.test(word)) return null
if (isCommonEnglishWord(word)) return null
const converted = latinToHangul(word)
if (!converted.complete) return null
const syllables = Array.from(converted.text)
if (syllables.length < 2) return null
if (!syllables.every((char) => isCommonHangulSyllable(char))) return null
const contextTotal = context.hangul + context.latin
const hangulContext = context.hangul >= 2 && context.hangul / Math.max(1, contextTotal) >= 0.5
const standalone = syllables.length >= 3 && looksUnpronounceableLatin(word)
if (!hangulContext && !standalone) return null
return converted.text
}
/**
* 영어 문맥에서 한글 자판으로 친 단어인가 → 고칠 영단어를 돌려준다.
*
* 조건: 주변이 영문 위주, 되돌린 결과가 3자 이상, 그리고 (홀로 남은 자모나 비상용 음절이 있거나
* 되돌린 결과가 흔한 영단어). 정상적인 한글 단어를 영어로 바꾸지 않도록 보수적으로 본다.
*/
export function detectHangulTypedLatin(
word: string,
context: { hangul: number; latin: number }
): string | null {
if (!HANGUL_ANY.test(word) || !/^[가-힣ㄱ-ㆎ]+$/u.test(word)) return null
const contextTotal = context.hangul + context.latin
if (context.latin < 6 || context.latin / Math.max(1, contextTotal) < 0.8) return null
const latin = hangulToLatin(word)
if (!/^[A-Za-z]+$/u.test(latin) || latin.length < 3) return null
const hasLooseJamo = /[ㄱ-ㆎ]/u.test(word)
const hasRareSyllable = Array.from(word).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))
if (!isCommonEnglishWord(latin) && !(hasLooseJamo || hasRareSyllable)) return null
if (!isCommonEnglishWord(latin) && !looksPronounceableLatin(latin)) return null
return latin
}
function looksPronounceableLatin(word: string): boolean {
const vowels = word.match(ENGLISH_VOWELS)?.length ?? 0
return vowels / word.length >= 0.25 && !/[^aeiouy]{5,}/iu.test(word)
}
// ============================================================
// 늘 틀린 철자 사전
// ============================================================
interface KoreanMisspellingRule {
/** 토큰 안에서 찾을 패턴 */
pattern: RegExp
replace: string
}
/**
* 맞는 쓰임이 없는 한글 철자만 둔다. 문맥에 따라 맞을 수도 있는 것(되/돼 일반, 바램 등)은
* 모델 단계가 판단한다.
*/
const KOREAN_MISSPELLINGS: readonly KoreanMisspellingRule[] = [
{ pattern: /됬/gu, replace: '됐' },
{ pattern: /되요$/u, replace: '돼요' },
{ pattern: /되서$/u, replace: '돼서' },
{ pattern: /뵈요$/u, replace: '봬요' },
{ pattern: /^몇일/u, replace: '며칠' },
{ pattern: /^어떻해/u, replace: '어떡해' },
{ pattern: /^왠만/u, replace: '웬만' },
{ pattern: /^웬지/u, replace: '왠지' },
{ pattern: /^희안하/u, replace: '희한하' },
{ pattern: /^설겆이/u, replace: '설거지' },
{ pattern: /^역활/u, replace: '역할' },
{ pattern: /^오랫만/u, replace: '오랜만' },
{ pattern: /^일일히/u, replace: '일일이' },
{ pattern: /^어의없/u, replace: '어이없' },
{ pattern: /^궂이$/u, replace: '굳이' },
{ pattern: /^문안하/u, replace: '무난하' },
{ pattern: /^않하/u, replace: '안 하' },
{ pattern: /^않되/u, replace: '안 되' },
{ pattern: /^않돼/u, replace: '안 돼' }
]
const ENGLISH_MISSPELLINGS: Readonly<Record<string, string>> = {
teh: 'the', adn: 'and', taht: 'that', hte: 'the', thier: 'their', recieve: 'receive', recieved: 'received',
seperate: 'separate', definately: 'definitely', occured: 'occurred', untill: 'until', wich: 'which',
becuase: 'because', beacuse: 'because', tommorow: 'tomorrow', tomorow: 'tomorrow', goverment: 'government',
enviroment: 'environment', accomodate: 'accommodate', wierd: 'weird', freind: 'friend', beleive: 'believe',
acheive: 'achieve', adress: 'address', begining: 'beginning', calender: 'calendar', comming: 'coming',
concious: 'conscious', existance: 'existence', familar: 'familiar', finaly: 'finally', foward: 'forward',
happend: 'happened', immediatly: 'immediately', independant: 'independent', knowlege: 'knowledge',
neccessary: 'necessary', necesary: 'necessary', noticable: 'noticeable', occassion: 'occasion',
persue: 'pursue', posession: 'possession', publically: 'publicly', realy: 'really', recomend: 'recommend',
refered: 'referred', relevent: 'relevant', succesful: 'successful', successfull: 'successful',
suprise: 'surprise', truely: 'truly', withold: 'withhold', dont: "don't", doesnt: "doesn't", didnt: "didn't",
isnt: "isn't", wasnt: "wasn't", werent: "weren't", havent: "haven't", hasnt: "hasn't", couldnt: "couldn't",
wouldnt: "wouldn't", shouldnt: "shouldn't", arent: "aren't", thats: "that's", whats: "what's",
im: "I'm", ive: "I've", youre: "you're", theyre: "they're", thanx: 'thanks', pls: 'please', plz: 'please',
wiht: 'with', woudl: 'would', coudl: 'could', shoudl: 'should', jsut: 'just', konw: 'know', nwo: 'now',
waht: 'what', whcih: 'which', thsi: 'this', tihs: 'this', alos: 'also', aslo: 'also', abotu: 'about',
baout: 'about', becasue: 'because', yuo: 'you', yoru: 'your', soem: 'some', smoe: 'some', ahve: 'have',
hvae: 'have', wnat: 'want', gonig: 'going', goign: 'going', thnak: 'thank', thnaks: 'thanks',
meeitng: 'meeting', meetign: 'meeting', udpate: 'update', updaet: 'update', reprot: 'report'
}
/** 원문 대소문자 모양을 교정어에 옮긴다 (Teh → The, TEH → THE). */
function matchCase(original: string, replacement: string): string {
if (original === original.toUpperCase() && original.length > 1) return replacement.toUpperCase()
if (original[0] === original[0]?.toUpperCase() && original.slice(1) === original.slice(1).toLowerCase()) {
return replacement[0].toUpperCase() + replacement.slice(1)
}
return replacement
}
/** 받침 ㄹ 음절 + '께(요)' 로 끝나면 '게(요)' 로 (할께 → 할게). '선생님께' 같은 조사는 받침이 달라 걸리지 않는다. */
function fixLKke(word: string): string | null {
const match = /([가-힣])께(요?)$/u.exec(word)
if (!match) return null
const code = match[1].charCodeAt(0) - 0xac00
if (JONG[code % 28] !== 'ㄹ') return null
return `${word.slice(0, match.index)}${match[1]}게${match[2]}`
}
/** 사전 규칙으로 한 단어를 고친다. 고칠 것이 없으면 null. */
export function fixKnownMisspelling(word: string): string | null {
if (HANGUL_SYLLABLE.test(word)) {
let fixed = word
for (const rule of KOREAN_MISSPELLINGS) fixed = fixed.replace(rule.pattern, rule.replace)
fixed = fixLKke(fixed) ?? fixed
return fixed !== word ? fixed : null
}
if (/^[A-Za-z']+$/u.test(word)) {
const lower = word.toLowerCase()
// 문장 속 홀로 쓴 소문자 i 는 I 다.
if (word === 'i') return 'I'
const replacement = ENGLISH_MISSPELLINGS[lower]
if (!replacement) return null
return /^[iI]'|^I'/u.test(replacement) ? replacement : matchCase(word, replacement)
}
return null
}
// ============================================================
// 개인 어휘 근접 (영문)
// ============================================================
/** 개인 어휘로 고칠 때 요구하는 최소 빈도 */
export const TYPO_VOCABULARY_MIN_COUNT = 3
/** 사용자가 자주 쓰는 영단어와 한 글자 차이인, 처음 보는 단어를 고친다. */
export function fixByVocabulary(word: string, vocabulary: ReadonlyMap<string, number>): string | null {
if (!/^[a-z]{5,}$/u.test(word)) return null
if (vocabulary.has(word) || isCommonEnglishWord(word)) return null
let best: string | null = null
let bestCount = 0
let ties = 0
const chars = Array.from(word)
for (const [candidate, count] of vocabulary) {
if (count < TYPO_VOCABULARY_MIN_COUNT) continue
if (Math.abs(candidate.length - word.length) > 1 || !/^[a-z]+$/u.test(candidate)) continue
if (candidate[0] !== word[0]) continue
if (editDistance(chars, Array.from(candidate)) !== 1) continue
if (count > bestCount) {
best = candidate
bestCount = count
ties = 0
} else if (count === bestCount) {
ties += 1
}
}
return ties === 0 ? best : null
}
/** 텍스트들에서 개인 어휘(소문자 영단어 → 빈도)를 만든다. */
export function buildVocabulary(texts: ReadonlyArray<{ text: string; count: number }>): Map<string, number> {
const vocabulary = new Map<string, number>()
for (const { text, count } of texts) {
for (const token of text.toLowerCase().match(/[a-z]{3,}/gu) ?? []) {
vocabulary.set(token, (vocabulary.get(token) ?? 0) + Math.max(1, count))
}
}
return vocabulary
}
// ============================================================
// 탐지 (결정적 층)
// ============================================================
function isIgnored(word: string, ignored: readonly string[] | undefined): boolean {
if (!ignored || ignored.length === 0) return false
const lower = word.toLowerCase()
return ignored.some((entry) => entry.toLowerCase() === lower)
}
/**
* 커서 앞 구간에서 결정적으로 확실한 오타를 찾는다.
*
* 마지막 토큰(뒤에 공백·구두점이 없는 단어)은 includeTrailingToken 일 때만 본다 —
* 아직 치는 중인 단어를 고치면 안 된다.
*/
export function detectTypos(prefix: string, options: TypoDetectOptions = {}): TypoCorrection[] {
const regionStart = typoRegionStart(prefix)
const tokens = tokenizeWords(prefix).filter((token) => token.start >= regionStart)
if (tokens.length === 0) return []
const counts = scriptCounts(prefix.slice(Math.max(0, prefix.length - 400)))
const out: TypoCorrection[] = []
for (const token of tokens) {
const trailing = token.end === prefix.length
if (trailing && !options.includeTrailingToken) continue
if (isIgnored(token.text, options.ignoredWords)) continue
if (looksTechnical(prefix, token)) continue
// 단어 자신은 문맥 계산에서 뺀다 (dkssudgktpdy 가 "영문 문맥" 을 만들지 않게)
const own = scriptCounts(token.text)
const context = { hangul: counts.hangul - own.hangul, latin: counts.latin - own.latin }
// 홀로 쓴 소문자 i → I 는 영어 문맥에서만
if (token.text === 'i' && context.latin <= context.hangul) continue
const layout = detectLatinTypedHangul(token.text, context) ?? detectHangulTypedLatin(token.text, context)
if (layout) {
out.push({ start: token.start, end: token.end, from: token.text, to: layout, source: 'layout' })
continue
}
const known = fixKnownMisspelling(token.text)
if (known) {
out.push({ start: token.start, end: token.end, from: token.text, to: known, source: 'dictionary' })
continue
}
if (options.vocabulary && token.text === token.text.toLowerCase()) {
const near = fixByVocabulary(token.text, options.vocabulary)
if (near) out.push({ start: token.start, end: token.end, from: token.text, to: near, source: 'vocabulary' })
}
}
return out
}
// ============================================================
// 모델 교정 검증
// ============================================================
export interface ModelTypoPair {
from: string
to: string
}
/**
* 모델 출력("틀린말 => 고친말" 줄들)을 쌍으로 읽는다. "없음"/"none" 이면 빈 배열.
*/
export function parseModelTypoPairs(raw: string): ModelTypoPair[] {
const out: ModelTypoPair[] = []
for (const line of raw.split(/\r?\n/u)) {
const cleaned = line.replace(/^[\s\-*•\d.)]+/u, '').trim()
if (!cleaned) continue
const match = /^["'“”‘’`]?(.+?)["'“”‘’`]?\s*(?:=>|->|→|⇒)\s*["'“”‘’`]?(.+?)["'“”‘’`]?$/u.exec(cleaned)
if (!match) continue
const from = match[1].trim()
const to = match[2].trim()
if (!from || !to || from === to) continue
out.push({ from, to })
}
return out
}
/** 모델 교정 하나가 "오타 수정" 범위인가 — 뜻을 바꾸는 단어 교체·띄어쓰기·문체 변경은 거른다. */
export function isPlausibleTypoFix(from: string, to: string): boolean {
if (from === to) return false
if (/\s/u.test(from) || /\s/u.test(to)) return false
if (/\d/u.test(from) || /\d/u.test(to)) return false
if (from.toLowerCase() === to.toLowerCase()) return false
const fromHangul = HANGUL_SYLLABLE.test(from)
const toHangul = HANGUL_SYLLABLE.test(to)
if (fromHangul !== toHangul) return false
// 낱자 수가 크게 달라지면 오타 수정이 아니라 단어 교체다.
if (Math.abs(Array.from(from).length - Array.from(to).length) > 1) return false
const distance = spellingDistance(from, to)
if (fromHangul) {
// 1음절 어절(넘·젤·걍)과 짧은 어절이 길어지는 것은 오타가 아니라 줄임말 풀기다 (실측: gemma 가
// "넘 => 너무" 를 오타로 냈다). 긴 어절에서 빠진 음절을 채우는 것만 허용한다.
const fromSyllables = Array.from(from).length
if (fromSyllables < 2) return false
if (Array.from(to).length > fromSyllables && fromSyllables <= 3) return false
const jamoLength = decomposeHangul(from).length
return distance <= Math.min(3, Math.max(1, Math.ceil(jamoLength * 0.25)))
}
if (from.length < 3) return false
return distance <= (from.length >= 7 ? 2 : 1)
}
/**
* 모델이 고르라고 한 쌍을 접두 안의 실제 위치로 옮기고 안전 기준으로 거른다.
*
* - from 은 검사 구간 안의 온전한 단어여야 한다(가장 커서에 가까운 것).
* - isPlausibleTypoFix 를 통과해야 한다.
* - 무시 단어, 개인 어휘에서 자주 쓴 단어(사용자 고유 표현)는 고치지 않는다.
*/
export function validateModelCorrections(
prefix: string,
pairs: readonly ModelTypoPair[],
options: { ignoredWords?: readonly string[]; knownWords?: ReadonlySet<string> } = {}
): TypoCorrection[] {
const regionStart = typoRegionStart(prefix)
const tokens = tokenizeWords(prefix).filter((token) => token.start >= regionStart)
const out: TypoCorrection[] = []
const reversed = [...tokens].reverse()
for (const pair of pairs) {
// 모델은 어절 대신 어간만 돌려주기도 한다("회으에서" 를 "회으 => 회의" 로) — 그때는 어절 안의
// 그 부분만 바꾼 어절 전체로 다시 판단한다. 어절 앞부분이 맞는 것을 먼저 고른다.
const whole = reversed.find((candidate) => candidate.text === pair.from)
const partial =
whole || Array.from(pair.from).length < 2
? undefined
: reversed.find((candidate) => candidate.text.startsWith(pair.from)) ??
reversed.find((candidate) => candidate.text.includes(pair.from))
const token = whole ?? partial
if (!token) continue
const corrected = whole ? pair.to : token.text.replace(pair.from, pair.to)
if (!isPlausibleTypoFix(token.text, corrected)) continue
if (isIgnored(token.text, options.ignoredWords)) continue
if (options.knownWords?.has(token.text.toLowerCase())) continue
if (looksTechnical(prefix, token)) continue
if (out.some((existing) => existing.start === token.start)) continue
out.push({ start: token.start, end: token.end, from: token.text, to: corrected, source: 'model' })
}
return out
}
// ============================================================
// 적용 계획
// ============================================================
/** 옛한글 조합 자모(U+1100–11FF)·폭 없는 문자(U+200B–200F)·변이 선택자(U+FE00–FE0F) */
function isUnsafeCodePoint(code: number): boolean {
return (
(code >= 0x1100 && code <= 0x11ff) || (code >= 0x200b && code <= 0x200f) || (code >= 0xfe00 && code <= 0xfe0f)
)
}
/** 백스페이스 한 번이 한 글자를 지운다고 믿을 수 있는 텍스트인가 (BMP, 결합 문자·줄바꿈 없음). */
function isSafeToBackspace(text: string): boolean {
for (const char of text) {
if (char.length !== 1) return false
if (/[\p{M}\r\n]/u.test(char) || isUnsafeCodePoint(char.charCodeAt(0))) return false
}
return true
}
/**
* 교정 목록을 "커서 앞 N 글자 지우고 이 텍스트 넣기" 한 번으로 바꾼다.
*
* 가장 앞선 교정 위치부터 커서까지를 통째로 다시 쓴다 — 커서를 옮기지 않으므로 앱마다 다른
* 커서 이동 동작에 기대지 않는다. 구간이 길거나 안전하지 않으면 null.
*/
export function planTypoReplacement(prefix: string, corrections: readonly TypoCorrection[]): TypoReplacementPlan | null {
if (corrections.length === 0) return null
const sorted = [...corrections].sort((a, b) => a.start - b.start)
for (let i = 1; i < sorted.length; i += 1) {
if (sorted[i].start < sorted[i - 1].end) return null
}
const regionStart = sorted[0].start
const originalText = prefix.slice(regionStart)
if (originalText.length === 0 || originalText.length > TYPO_REGION_MAX_CHARS) return null
if (!isSafeToBackspace(originalText)) return null
for (const correction of sorted) {
if (prefix.slice(correction.start, correction.end) !== correction.from) return null
}
let insertText = ''
let cursor = regionStart
for (const correction of sorted) {
insertText += prefix.slice(cursor, correction.start) + correction.to
cursor = correction.end
}
insertText += prefix.slice(cursor)
if (!isSafeToBackspace(insertText.replace(/[\r\n]/gu, ''))) return null
return { deleteCount: originalText.length, insertText, originalText, corrections: sorted }
}
/**
* 교정 뒤 사용자가 원래 단어로 되돌렸는가.
*
* 교정한 구간 뒤로 사용자가 더 쳤을 수 있으므로, 커서 앞 근처(교정 구간 길이 + 여유)에
* 원래 단어가 온전한 단어로 다시 나타나고 교정어는 그 자리에서 사라졌는지 본다.
*/
export function detectTypoRevert(currentPrefix: string, applied: { from: string; to: string; tailLength: number }): boolean {
const window = currentPrefix.slice(-Math.max(applied.tailLength + 40, 60))
const tokens = tokenizeWords(window).map((token) => token.text)
return tokens.includes(applied.from) && !tokens.includes(applied.to)
}

View file

@ -0,0 +1,227 @@
// packages/core — 제안 문맥 분석 정본 (순수 함수).
//
// 접두(커서 앞 텍스트)를 "앞 문맥 · 직전 완결 문장 · 지금 쓰는 문장" 으로 나누고, 이어 쓰기 모드
// (문장 마저 쓰기 / 다음 문장), 언어, 말투를 판별한다. 모델 프롬프트와 개인 그래프 조회가 같은
// 분해를 쓴다 — 둘이 서로 다른 "현재 문장" 을 보면 그래프 문맥이 프롬프트와 어긋난다.
export type WritingMode = 'complete-sentence' | 'next-sentence'
export type WritingLanguage = 'ko' | 'en' | 'ja' | 'zh' | 'other'
/**
* 한국어 말투 — formal(합쇼체 -습니다), polite(해요체 -요), plain(평서·해라체 -다: 일기·문서),
* casual(반말 -어/-야/-지: 채팅).
*
* plain 과 casual 을 나누는 이유: 둘을 한 갈래로 두면 일기("피곤했다.")를 이어 쓰라는 요청에
* 모델이 "부족했어." 같은 채팅 반말을 섞는다(실측 2026-10-03).
*/
export type WritingRegister = 'formal' | 'polite' | 'plain' | 'casual'
export interface WritingContext {
/** 직전 완결 문장 이전의 앞 문맥 (최대 contextChars) */
earlierText: string
/** 커서 앞 마지막 완결 문장 (없으면 '') */
lastSentence: string
/** 아직 끝나지 않은 지금 문장 (문장이 끝났으면 '') */
currentSentence: string
mode: WritingMode
language: WritingLanguage
register: WritingRegister | null
}
const SENTENCE_END = /[.!?。!?…]["'”’)\]]*\s*$|\n\s*$/u
const SENTENCE_SPLIT = /(?<=[.!?。!?…])["'”’)\]]*\s+|\n+/u
/** 접두를 문장 단위로 나눈다 (끝에 남은 미완성 조각 포함, 공백 정규화). */
function splitKeepingTail(text: string): string[] {
return text
.split(SENTENCE_SPLIT)
.map((segment) => segment.replace(/\s+/gu, ' ').trim())
.filter((segment) => segment.length > 0)
}
/** 텍스트의 주 언어 (문자 체계 비율). */
export function detectWritingLanguage(text: string): WritingLanguage {
let hangul = 0
let latin = 0
let kana = 0
let han = 0
for (const char of text) {
if (/[가-힣ㄱ-ㆎ]/u.test(char)) hangul += 1
else if (/[A-Za-z]/u.test(char)) latin += 1
else if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(char)) kana += 1
else if (/\p{Script=Han}/u.test(char)) han += 1
}
const total = hangul + latin + kana + han
if (total === 0) return 'other'
if (hangul / total >= 0.3) return 'ko'
if (kana > 0 && (kana + han) / total >= 0.3) return 'ja'
if (han / total >= 0.3) return 'zh'
if (latin / total >= 0.5) return 'en'
return 'other'
}
/** 한 문장의 한국어 말투. 판별할 수 없으면 null. */
export function detectSentenceRegister(sentence: string): WritingRegister | null {
const trimmed = sentence.replace(/[\s.!?~…"'”’)\]^;:]+$/u, '')
if (!trimmed || !/[가-힣]$/u.test(trimmed)) return null
if (/(습니다|습니까|ㅂ니다|입니다|됩니다|합니다|십시오|시죠|드립니다|겠습니다)$/u.test(trimmed)) return 'formal'
if (/요$/u.test(trimmed)) return 'polite'
if (/다$/u.test(trimmed)) return 'plain'
if (/(어|아|야|지|냐|니|자|게|해|래|네|거든|잖아|군|구나|ㅋ|ㅎ)$/u.test(trimmed)) return 'casual'
return null
}
/** 최근 문장들의 다수결 말투 (마지막 문장에 가중). */
export function detectWritingRegister(sentences: readonly string[]): WritingRegister | null {
const votes: Record<WritingRegister, number> = { formal: 0, polite: 0, plain: 0, casual: 0 }
const recent = sentences.slice(-4)
recent.forEach((sentence, index) => {
const register = detectSentenceRegister(sentence)
if (register) votes[register] += index === recent.length - 1 ? 2 : 1
})
const best = (Object.entries(votes) as Array<[WritingRegister, number]>).sort((a, b) => b[1] - a[1])[0]
return best[1] > 0 ? best[0] : null
}
// ============================================================
// 문서 문맥 — 프롬프트 창(앞 문맥) 밖의 첫머리와 사실
// ============================================================
export interface DocumentContext {
/** 글의 첫머리(인사·제목·받는 사람) — 앞 문맥 창보다 앞에 있을 때만 */
opening: string
/** 글 전체에 나온 이름·날짜·시각·숫자·고유명사 (나중에 나온 것이 앞) */
facts: string[]
}
/**
* 사실로 볼 표현 — 이어 쓸 문장이 앞 내용과 어긋나는 가장 흔한 지점(이름·날짜·숫자).
*
* 소형 모델은 600자 앞에 나온 "11월 15일" 을 기억하지 못하고 그럴듯한 다른 날짜를 지어낸다.
* 문맥 창 밖의 사실을 목록으로 따로 보여 주면 그대로 가져다 쓴다.
*/
const FACT_PATTERNS: readonly RegExp[] = [
// 이름 + 호칭/직함 (김민수 대리, 박 팀장님, 지영 씨)
/[가-힣]{2,4} ?(?:대표님|대표|사장님|이사님|이사|부장님|부장|차장님|차장|과장님|과장|대리님|대리|팀장님|팀장|실장님|실장|매니저님|매니저|책임님|책임|선임님|선임|수석님|수석|교수님|선생님|님|씨)(?=$|[^가-힣]|[이가은는을를의에께도와과랑한로만])/gu,
// 날짜
/\d{4}[-./년] ?\d{1,2}[-./월] ?\d{1,2}일?/gu,
/\d{1,2}월 ?\d{1,2}일(?: ?\([월화수목금토일]\))?/gu,
/(?:이번|다음|지난|다다음) ?주 ?[월화수목금토일]요일/gu,
// 시각
/(?:오전|오후|저녁|아침|낮|밤) ?\d{1,2}시(?: ?\d{1,2}분| ?반)?/gu,
/\d{1,2}:\d{2}(?: ?[AaPp][Mm])?/gu,
// 금액·수량·비율
/\d[\d,.]*(?: ?(?:만|천|억|조))? ?(?:원|달러|불|%|퍼센트|개|명|건|대|장|부|시간|분|초|일|주|개월|GB|MB|TB|km|kg)(?=$|[^가-힣A-Za-z]|[이가은는을를의에도와과로만입짜쯤씩])/gu,
// 버전
/\bv?\d+\.\d+(?:\.\d+)+\b/gu,
// 영문 고유명사·약어 (문장 첫 단어 하나짜리는 고유명사인지 알 수 없어 2자 이상 대문자 약어나 낙타표기만)
/\b[A-Z]{2,}[A-Za-z0-9]*\b/gu,
/\b[A-Z][a-z]+[A-Z][A-Za-z0-9]*\b/gu,
// 사람·참석자 목록 줄 (참석: 김민수, 이지은 / 담당: 박준호) — 호칭 없는 이름은 이 자리에서만 알 수 있다
/(?:참석자?|참여자?|담당자?|수신|참조|받는 ?사람|작성자|발표자|[Cc][Cc]|[Aa]ttendees|[Tt]o)\s*[::]\s*[^\n]{2,80}/gu,
// 따옴표로 묶은 용어
/[“"「『'‘][^“”"「」『』'‘’\n]{2,24}[”"」』'’]/gu
]
/** 흔한 문장 첫 대문자 단어·약어 중 사실이 아닌 것. */
const FACT_STOPLIST: ReadonlySet<string> = new Set(['OK', 'PM', 'AM', 'I', 'ASAP'])
/**
* 글 전체에서 이름·날짜·숫자 같은 사실을 뽑는다 (중복 제거, 가장 나중에 나온 것이 앞).
*/
export function extractDocumentFacts(text: string, limit = 8): string[] {
const found: Array<{ value: string; index: number }> = []
for (const pattern of FACT_PATTERNS) {
for (const match of text.matchAll(pattern)) {
const value = match[0].replace(/\s+/gu, ' ').trim()
if (value.length < 2 || FACT_STOPLIST.has(value)) continue
found.push({ value, index: match.index ?? 0 })
}
}
found.sort((a, b) => b.index - a.index)
const out: string[] = []
for (const { value } of found) {
// 더 긴 사실에 포함된 조각("15일" ⊂ "11월 15일")은 뺀다.
if (out.some((existing) => existing.includes(value) || value.includes(existing))) {
const shorter = out.findIndex((existing) => value.includes(existing) && value !== existing)
if (shorter >= 0) out[shorter] = value
continue
}
out.push(value)
if (out.length >= limit) break
}
return out
}
/** 비교용 정규화 — 공백·괄호 차이("11월 15일(토)" vs "11월15일") 를 무시한다. */
function factKey(value: string): string {
return value.replace(/[\s()()]/gu, '').toLowerCase()
}
/**
* 후보 문장에 나온 사실(이름+호칭·날짜·시각·수량) 중 원문 어디에도 없는 것 — 모델이 지어낸 사실.
*
* 이어 쓰기에서 가장 해로운 실수다: 사용자가 그대로 수락하면 틀린 날짜·이름이 글에 박힌다.
*/
export function findUnsupportedFacts(candidate: string, sourceText: string): string[] {
const source = factKey(sourceText)
const unsupported = extractDocumentFacts(candidate, 12).filter((fact) => {
// 목록 줄 패턴은 후보 쪽에서는 사실 판정에 쓰지 않는다(이어 쓰는 줄 자체가 목록일 수 있다).
if (/[::]/u.test(fact)) return false
const key = factKey(fact.replace(/^[“"「『'‘]|[”"」』'’]$/gu, ''))
return key.length > 0 && !source.includes(key)
})
// 패턴에 안 걸리는 맨 숫자("3번", "15")와 한글 사이 외톨이 영문 식별자("회의실 B", "A동")도
// 지어내기 쉬운 사실이다 — 원문에 없으면 같은 취급을 한다.
for (const match of candidate.matchAll(/\d+(?:[.,]\d+)*|(?<![A-Za-z])[A-Z]\d{0,3}(?![A-Za-z])/gu)) {
const value = match[0]
if (!source.includes(value.toLowerCase()) && !unsupported.some((fact) => fact.includes(value))) {
unsupported.push(value)
}
}
return unsupported
}
/**
* 커서 앞 문서 전체(documentText)에서 프롬프트 창 밖의 문맥을 뽑는다.
*
* `windowChars` 는 프롬프트가 원문으로 보여 주는 꼬리 길이다. 첫머리는 그보다 앞에 있을 때만
* 돌려준다(이미 보이는 글을 두 번 넣지 않는다). 사실은 글 전체에서 뽑는다 — 보이는 창 안의
* 사실도 목록으로 강조하면 소형 모델이 숫자·이름을 바꾸지 않는다.
*/
export function analyzeDocumentContext(documentText: string, windowChars: number): DocumentContext {
const text = documentText.replace(/\r\n/gu, '\n')
const hiddenLength = text.length - windowChars
let opening = ''
if (hiddenLength > 40) {
const head = text.slice(0, Math.min(hiddenLength, 400))
const firstSentences = splitKeepingTail(head).slice(0, 2).join(' ')
opening = firstSentences.length > 160 ? `${firstSentences.slice(0, 160).replace(/\s\S*$/u, '')}…` : firstSentences
}
return { opening, facts: extractDocumentFacts(text.slice(-6000)) }
}
/**
* 접두를 문맥으로 분해한다.
*
* 마지막 조각이 종결 부호·줄바꿈으로 끝나지 않았으면 "지금 쓰는 문장" 이고 모드는 마저 쓰기다.
*/
export function analyzeWritingContext(prefix: string, contextChars = 300): WritingContext {
const normalized = prefix.replace(/\s+$/u, '')
const ended = normalized.length === 0 || SENTENCE_END.test(prefix.replace(/[ \t]+$/u, ''))
const segments = splitKeepingTail(normalized)
const currentSentence = ended ? '' : segments.pop() ?? ''
const lastSentence = segments.pop() ?? ''
const earlier = segments.join(' ')
const earlierText = earlier.length > contextChars ? earlier.slice(-contextChars).replace(/^\S*\s/u, '') : earlier
// 말투는 끝난 문장에서만 읽는다 — 쓰는 중인 문장의 끝은 아직 어미가 아니다.
const completed = [...segments, lastSentence].filter(Boolean)
return {
earlierText,
lastSentence,
currentSentence,
mode: currentSentence ? 'complete-sentence' : 'next-sentence',
language: detectWritingLanguage(normalized.slice(-400)),
register: detectWritingRegister(completed)
}
}