d3ro-voice/packages/core/src/text-chunking.ts
Yun Chan ba9ef9741e fix: red-team round 3 hardening across desktop, mobile, core and server
Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
2026-09-28 20:45:52 +09:00

80 lines
3.4 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/src/text-chunking.ts
// 줄바꿈이 없는 긴 텍스트를 한도 안의 조각으로 자르는 순수 정책(정본).
//
// 자막·파일 전사 히스토리(`segments.join(' ')`)와 폰 회의 전사(STT 결과 한 문단)는 줄바꿈이 없다.
// 줄 경계로만 나누면 전체가 조각 하나가 되어 LLM 입력 한도·출력 토큰 한도를 넘는다. 그래서
// 문장 경계 → 공백 → 글자 수 순으로 내려가며 자른다.
//
// 순수 함수만 둔다 — Electron/Node 의존 금지. 다른 core 모듈을 import 하지 않는다(순환 방지).
/** 문장을 끝내는 부호 (라틴·CJK·말줄임) */
const SENTENCE_END = new Set(['.', '?', '!', '…', '。', '?', '!'])
/** 뒤에 공백이 없어도 문장 경계로 보는 전각 부호 (중국어·일본어는 띄어 쓰지 않는다) */
const FULL_WIDTH_SENTENCE_END = new Set(['。', '?', '!'])
/** 문장 끝 부호 뒤에 붙을 수 있는 닫는 따옴표·괄호 */
const CLOSING_MARKS = new Set(['"', "'", '”', '’', ')', ']', '」', '』', ')'])
const WHITESPACE = /\s/u
/** 문장 경계를 이 비율보다 앞에서만 찾으면 너무 짧은 조각이 되므로 공백 경계를 대신 쓴다 */
const MIN_SENTENCE_FILL_RATIO = 0.5
function isHighSurrogate(code: number): boolean {
return code >= 0xd800 && code <= 0xdbff
}
/**
* window(= text 앞 maxChars 자) 안에서 마지막 문장 경계의 끝 위치를 찾는다(없으면 0).
* 경계: 문장 끝 부호(+닫는 부호) 뒤가 공백이거나 텍스트 끝, 또는 전각 문장 부호.
* "3.5" 처럼 부호 뒤에 바로 글자가 오면 경계가 아니다.
*/
function lastSentenceBoundary(text: string, limit: number): number {
let best = 0
for (let i = 0; i < limit; i++) {
const ch = text[i]
if (!SENTENCE_END.has(ch)) continue
let end = i + 1
while (end < limit && CLOSING_MARKS.has(text[end])) end++
const next = text[end]
if (FULL_WIDTH_SENTENCE_END.has(ch) || next === undefined || WHITESPACE.test(next)) {
best = end
}
}
return best
}
function lastWhitespace(text: string, limit: number): number {
for (let i = limit; i > 0; i--) {
if (WHITESPACE.test(text[i] ?? '')) return i
}
return 0
}
/** text(길이 > maxChars)의 첫 조각을 끊을 위치 — 문장 경계 → 공백 → 글자 수 순. */
function findCut(text: string, maxChars: number): number {
const sentence = lastSentenceBoundary(text, maxChars)
if (sentence >= Math.ceil(maxChars * MIN_SENTENCE_FILL_RATIO)) return sentence
const space = lastWhitespace(text, maxChars)
if (space > 0) return space
if (sentence > 0) return sentence
// 글자 수로 자른다 — 서로게이트 쌍(이모지 등) 가운데는 피한다
const hard = isHighSurrogate(text.charCodeAt(maxChars - 1)) ? maxChars - 1 : maxChars
return Math.max(1, hard)
}
/**
* 텍스트를 maxChars 이하 조각들로 자른다. 들어가면 [text] 그대로(앞뒤 공백만 정리).
* 자른 조각의 앞뒤 공백은 버리고, 빈 조각은 내지 않는다.
*/
export function splitTextToFit(text: string, maxChars: number): string[] {
const limit = Math.max(1, Math.floor(maxChars))
const pieces: string[] = []
let rest = text.trim()
while (rest.length > limit) {
const cut = findCut(rest, limit)
const piece = rest.slice(0, cut).trim()
if (piece) pieces.push(piece)
rest = rest.slice(cut).trim()
}
if (rest) pieces.push(rest)
return pieces
}