// 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 = { 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 = 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+)*|(? 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) } }