refactor(suggestion): drive suggestion decisions from one core step and split SuggestionService collaborators

This commit is contained in:
Yun Chan 2026-09-28 00:53:42 +09:00
parent 9aa7302944
commit 190b6db284
13 changed files with 1994 additions and 496 deletions

View file

@ -0,0 +1,217 @@
// packages/core — 제안 텍스트 정본 (후보 정제 · 접두 정규화).
//
// 두 종류의 입력을 분리해 다룬다 (ISP):
// 1) 신뢰할 수 없는 모델 출력 — 번호/불릿/따옴표/지시문 되풀이를 걷어내야 한다
// (`stripModelArtifacts` → `normalizeSuggestionText`).
// 2) 사용자가 학습시킨 로컬 기억 문구 — 사용자 자신의 글이므로 내용을 건드리지 않고
// 공백과 길이만 정규화한다 (`normalizeSuggestionText`).
// 두 입력이 한 정제 함수를 공유하던 시절, 모델 대응 규칙이 사용자의 "3 pm …" 같은
// 문장 앞 숫자를 지웠다 — 이 분리가 그 회귀를 구조적으로 막는다.
//
// 순수 함수만 둔다 — Electron/Node 의존 금지. input-intelligence.ts 를 import 하지 않는다
// (input-intelligence 가 이 모듈을 다시 export 하므로 순환이 생긴다).
/**
* 프롬프트에 넣을 컨텍스트 길이 상한.
*
* 길이가 곧 로컬 추론 지연이므로 짧게 유지한다.
*/
export const SUGGESTION_CONTEXT_MAX_CHARS = 400
/** 후보 문자열 길이 상한. */
export const SUGGESTION_MAX_OUTPUT_CHARS = 160
/** 문장 종결 부호. */
export const SENTENCE_TERMINATORS = /[.!?。!?…]/
/** 마지막 문장 종결 여부 — 참이면 직전 문장이 끝난 것이므로 제안을 지운다. */
export function endsSentence(text: string): boolean {
const trimmed = text.replace(/\s+$/u, '')
if (!trimmed) return false
const last = trimmed[trimmed.length - 1]
return SENTENCE_TERMINATORS.test(last) || last === '\n'
}
// ============================================================
// 접두 정규화
// ============================================================
/**
* 요청 접두 정규화 — 뒤쪽 공백만 걷어낸다 (길이는 자르지 않는다).
*
* 진행 중 요청의 연속 확장 판정(decideSuggestionRefresh)은 전체 접두로 비교해야 한다 —
* 400자 창으로 자르면 한 글자만 쳐도 창이 밀려 "연속 확장" 이 깨진다.
*/
export function normalizeRequestPrefix(prefix: string): string {
return prefix.replace(/\s+$/u, '')
}
/**
* 세션 접두 정규화 — 뒤쪽 공백을 걷어내고 마지막 SUGGESTION_CONTEXT_MAX_CHARS 자만 남긴다.
*
* 세션은 이 창으로 만든 후보이므로, 표시 중인 세션의 유효성 비교는 양쪽 모두 이 함수로
* 맞춰야 한다. 한쪽만 자르면 400자를 넘는 입력창에서 텍스트가 그대로여도 매 스냅샷마다
* 세션이 stale 로 닫힌다.
*/
export function normalizeSessionPrefix(prefix: string): string {
return normalizeRequestPrefix(prefix).slice(-SUGGESTION_CONTEXT_MAX_CHARS)
}
// ============================================================
// 후보 정제
// ============================================================
/**
* 목록 표지: 불릿(-, *, •)이거나, 1~3자리 번호 뒤에 목록 구두점(. ) ])이 붙은 것.
*
* 숫자만으로는 목록 표지로 보지 않는다 — "3 pm in the lobby", "10 minutes later",
* "2026 roadmap" 의 숫자는 문장 내용이다.
*/
const LIST_MARKER_PATTERN = /^(?:[-*•]+[.)\]]?|\d{1,3}[.)\]])\s+/u
const WRAPPING_QUOTES_PATTERN = /^["'“”‘’`]+|["'“”‘’`]+$/gu
/** 모델이 지시문을 되풀이한 경우 (llm-prompts 회귀와 같은 부류) */
const INSTRUCTION_ECHO_PATTERN = /^(suggestion|completion|candidate|output|answer|다음 문장)\s*[::]/iu
const TEMPLATE_ECHO_PATTERN = /^\{\{.*\}\}$/u
/**
* 모델 출력 한 줄에서 모델 특유의 부산물을 걷어낸다.
*
* 번호/불릿/따옴표를 지우고, 지시문 되풀이·템플릿 누출은 버린다(null).
* 길이 제한은 하지 않는다 — normalizeSuggestionText 가 맡는다.
*/
export function stripModelArtifacts(line: string): string | null {
let text = line.trim()
if (!text) return null
text = text.replace(LIST_MARKER_PATTERN, '')
text = text.replace(WRAPPING_QUOTES_PATTERN, '')
text = text.replace(/\s+/gu, ' ').trim()
if (INSTRUCTION_ECHO_PATTERN.test(text)) return null
if (TEMPLATE_ECHO_PATTERN.test(text)) return null
return text
}
/**
* 후보 텍스트 정규화 — 공백을 한 칸으로 모으고 길이를 제한한다.
*
* 내용은 바꾸지 않는다 (사용자 자신의 문구에 안전). 2자 미만이면 null.
*/
export function normalizeSuggestionText(
text: string,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string | null {
let normalized = text.replace(/\s+/gu, ' ').trim()
if (normalized.length < 2) return null
if (normalized.length > maxChars) {
normalized = normalized.slice(0, maxChars)
const lastSpace = normalized.lastIndexOf(' ')
if (lastSpace > maxChars * 0.6) normalized = normalized.slice(0, lastSpace)
normalized = normalized.trim()
}
return normalized.length >= 2 ? normalized : null
}
/** 모델 출력 한 줄 정제: 번호/불릿/따옴표/지시문 제거 + 길이 제한. */
export function sanitizeSuggestionLine(line: string, maxChars = SUGGESTION_MAX_OUTPUT_CHARS): string | null {
const stripped = stripModelArtifacts(line)
return stripped === null ? null : normalizeSuggestionText(stripped, maxChars)
}
/**
* 모델 출력에서 후보 목록을 뽑아 정제한다.
*
* gemma 계열 소형 모델은 번호/따옴표/머리말을 붙이기 쉬우므로 여기서 걷어낸다.
* 접두를 그대로 되풀이하는 후보는 버린다 (ghost text 로 쓸 수 없음).
*/
export function parseSuggestionCandidates(
raw: string,
prefix: string,
maxCandidates = 3,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
if (!raw) return []
const prefixTail = normalizeRequestPrefix(prefix).slice(-24).toLowerCase()
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
if (out.some((existing) => existing.toLowerCase() === cleaned.toLowerCase())) continue
out.push(cleaned)
if (out.length >= maxCandidates) break
}
return out
}
// ============================================================
// 로컬 기억 후보
// ============================================================
export interface LocalSuggestionHints {
continuationHints: readonly string[]
relatedHints: readonly string[]
phraseHints: readonly string[]
}
function suffixPrefixOverlap(prefix: string, candidate: string): number {
const normalizedPrefix = prefix.toLowerCase()
const normalizedCandidate = candidate.toLowerCase()
const maximum = Math.min(normalizedPrefix.length, normalizedCandidate.length)
for (let length = maximum; length >= 2; length -= 1) {
if (normalizedPrefix.slice(-length) === normalizedCandidate.slice(0, length)) return length
}
return 0
}
/**
* 로컬 기억만으로 삽입 가능한 다음 문자열을 만든다.
*
* 힌트는 사용자 자신이 쓴 글이다 — 모델 출력용 정제(목록 표지·따옴표 제거)를 거치지
* 않고 공백·길이만 정규화한다. 모델 실패를 성공처럼 숨기지 않고, 호출부가
* provenance.mode 로 출처를 명시한다.
*/
export function buildLocalSuggestionCandidates(
prefix: string,
hints: LocalSuggestionHints,
limit = 3,
maxChars = SUGGESTION_MAX_OUTPUT_CHARS
): string[] {
const safeLimit = Math.max(0, Math.floor(limit))
const safeMaxChars = Math.max(0, Math.floor(maxChars))
if (safeLimit === 0 || safeMaxChars < 2) return []
const normalizedPrefix = normalizeRequestPrefix(prefix)
const normalizedPrefixLower = normalizedPrefix.toLowerCase()
const acceptsWholePhrase = endsSentence(normalizedPrefix)
const out: string[] = []
const append = (candidate: string | null): void => {
if (candidate === null || candidate.length === 0) return
if (candidate.toLowerCase() === normalizedPrefixLower) return
if (out.some((existing) => existing.toLowerCase() === candidate.toLowerCase())) return
out.push(candidate)
}
for (const raw of hints.continuationHints) {
if (out.length >= safeLimit) break
const candidate = normalizeSuggestionText(raw, safeMaxChars)
if (candidate === null) continue
if (normalizedPrefixLower && candidate.toLowerCase().startsWith(normalizedPrefixLower)) continue
append(candidate)
}
for (const source of [hints.relatedHints, hints.phraseHints]) {
for (const raw of source) {
if (out.length >= safeLimit) break
const candidate = normalizeSuggestionText(raw, safeMaxChars)
if (candidate === null) continue
const overlap = suffixPrefixOverlap(normalizedPrefix, candidate)
if (overlap >= 2) {
append(normalizeSuggestionText(candidate.slice(overlap), safeMaxChars))
} else if (acceptsWholePhrase) {
append(candidate)
}
}
}
return out
}