From 7a288129deeb063d25a681c1cf9328532049c5cf Mon Sep 17 00:00:00 2001 From: javis-bot Date: Wed, 11 Nov 2026 12:50:37 +0900 Subject: [PATCH] fix(memory): rank the whole history and keep relevant recent records - Search scored only the newest 5,000 matching records, so an old record behind enough newer chatter was never found. Both passes (word rarity counts and the score) now run in SQLite over every record in scope and only the best rows come back. - context() excluded the recent window from search and then cut that window for the budget, so a relevant recent record could vanish. Search now covers the recent window, matches keep their half of the budget, and a matched record is removed from the recent block so it appears once. - Matching used SQLite's ASCII-only lower() against Python's lowercasing. Stored text gets a folded column (NFKC + casefold) and query words are folded the same way, so case is ignored in every script. - Prompt label "Records related to this question" (matches may now be recent); eval re-run 3x on qwen2.5:7b, all pass. Spec, memory.md and roadmap updated. Co-Authored-By: Claude Opus 5.5 --- docs/v2/memory.md | 3 +- docs/v2/roadmap.md | 2 +- src/jarvis/memory/history.py | 131 ++++++++++++++++++------------ src/jarvis/memory/history.spec.md | 26 +++--- src/jarvis/reply/engine.py | 2 +- tests/test_history_store.py | 27 ++++++ 6 files changed, 125 insertions(+), 66 deletions(-) diff --git a/docs/v2/memory.md b/docs/v2/memory.md index 0c76c08..e333f29 100644 --- a/docs/v2/memory.md +++ b/docs/v2/memory.md @@ -38,4 +38,5 @@ v2에서는 다음 두 가지를 **전부** 대화 기록 저장소(SQLite)에 - 질문의 낱말이 기록에 들어 있는지로 찾습니다. 낱말 뒤쪽이 조금 달라도 찾습니다(앞부분이 60% 이상 같으면 됨, "영화를"로 "영화", "watching"으로 "watched"). 드문 낱말에 점수를 더 줍니다. 특정 언어의 낱말 목록은 쓰지 않습니다. - 뜻으로 찾는 검색(임베딩)은 아직 넣지 않았습니다. Strata는 대화 모델만 돌려서 임베딩을 만들지 못하고, 넣으려면 음성 워커에 작은 다국어 임베딩 모델을 따로 둬야 합니다. 실제 대화에서 낱말 검색이 놓치는 경우가 보이면 그때 넣습니다. - 참고 분량 상한 안에서 지난 기록은 절반까지만 씁니다. 최근 대화가 길어도 이번 질문과 관련된 기록이 밀려나지 않게 하기 위해서입니다. -- 기록 10만 개에서 한 번 찾는 데 24~61ms, 두뇌에 넘길 내용을 만드는 데 54ms가 걸렸습니다(이 서버 기준). 이 시간은 LLM 호출 없이 SQLite만 읽는 데 드는 시간입니다. +- 최근 기록만 고르지 않고 전체 기간에서 관련도가 높은 기록을 고릅니다. 대소문자는 모든 문자에서 같게 봅니다("МОСКВА"로 "москва" 찾기). 최근 대화 안에 있는 관련 기록도 지난 기록 몫으로 지켜서, 분량 상한 때문에 빠지지 않습니다. +- 기록 10만 개에서 한 번 찾는 데 48~143ms, 두뇌에 넘길 내용을 만드는 데 36ms가 걸렸습니다(이 서버 기준, 10만 개 중 가장 오래된 기록도 찾음). LLM 호출 없이 SQLite만 읽는 시간입니다. diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 6e6c31f..0a03de9 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -7,7 +7,7 @@ | M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 2026-11-10에 추가한 `desktop` 단계(agent-desktop)는 측정을 마쳤고, 자동 성능 조절용 `gamemode` 단계는 세 번 쟀고, `gamemode_stt`(LLM과 STT를 함께 켬, STT GPU·CPU)와 `gamemode_live`(실제 게임을 켬) 단계도 측정을 마쳤습니다(2026-11-10). 결과로 게임 중 최소 배치는 전문가 2GB로 정했고, 평소 배치에 STT 자리를 남기는 것과 게임 중 LLM이 답하는 동안 부분 전사 간격을 늘리는 것(게임이 없을 때는 그대로)도 정했습니다(사용자 결정, 2026-11-10). `gamemode_tune` 단계도 측정을 마쳤고(2026-11-11), 게임 중 LLM이 답하는 동안에는 부분 전사를 멈추기로 정했습니다. GPU 95% 제한은 측정에서 사용률을 낮추지 못해 기본값을 끔으로 바꿨고(사용자 결정, 2026-11-11), `video_drops` 단계(Jarvis를 돌리는 동안 유튜브 영상의 끊긴 프레임, 직접 실행)도 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 영상이 끊기지 않았고 제한이 끊김을 줄이지 못해 설정을 뺐습니다. 대신 게임 화면의 프레임을 직접 재는 `game_frames` 단계(게임을 켠 채로 Jarvis를 끈 때·쉴 때·바쁠 때와 우선순위를 낮춘 양보 상태, 직접 실행, 관리자 권한)를 넣었고 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 게임의 평균 fps와 1% low가 5% 넘게 떨어지지 않아 양보는 넣지 않기로 했습니다. 남은 M0 측정은 가상 모니터 확인(M6)입니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) | | M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과. 구현과 테스트 완료(2026-11-11): `src/voice_worker/`, 스펙은 [voice_worker.spec.md](../../src/voice_worker/voice_worker.spec.md). 이 서버의 RTX 5050에서 10명이 겹쳐 말하는 실시간 입력(48kHz 스테레오, M0 한국어 샘플 8개를 10명에게 나눠 줌, 절반은 디스코드 speaking 종료, 절반은 무음으로 끝남)을 넣어 10명 모두 최종 전사를 받았고 문자 오류율은 평균 4%, 최대 19%("일곱 시"를 "7시"로 적은 것), 말 끝 판정부터 최종 전사 전송까지 중앙값 0.64초, 최대 1.56초였습니다. TTS는 첫 문장 소리가 0.2초에 나왔고, 그 소리를 다시 넣으면 같은 문장으로 받아 적혔습니다. 샘플이 MeloTTS 합성 음성이라 실제 사람 녹음과 게임PC 수치는 아직 없습니다 | | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | -| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 기록 10만 개에서 검색 24~61ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 남은 일: 앱이 음성 워커에 전사·채팅·출입을 알리고 워커가 두뇌를 불러 답하는 연결, 채팅 채널 도구, 기존 평가 통과 확인 | +| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 남은 일: 앱이 음성 워커에 전사·채팅·출입을 알리고 워커가 두뇌를 불러 답하는 연결, 채팅 채널 도구, 기존 평가 통과 확인 | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트 | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | diff --git a/src/jarvis/memory/history.py b/src/jarvis/memory/history.py index e8c3f61..e95f702 100644 --- a/src/jarvis/memory/history.py +++ b/src/jarvis/memory/history.py @@ -9,6 +9,7 @@ import re import sqlite3 import threading import time +import unicodedata from dataclasses import dataclass, field from typing import Iterable, List, Optional @@ -24,7 +25,8 @@ CREATE TABLE IF NOT EXISTS history ( author_name TEXT NOT NULL, to_id TEXT, message_id TEXT, - text TEXT NOT NULL + text TEXT NOT NULL, + norm TEXT NOT NULL -- text folded for search (_fold) ); CREATE INDEX IF NOT EXISTS history_ts ON history(ts); CREATE INDEX IF NOT EXISTS history_author ON history(author_id); @@ -42,7 +44,6 @@ CREATE INDEX IF NOT EXISTS presence_user ON presence(user_id, channel_id); """ _WORD = re.compile(r"\w{2,}", re.UNICODE) -_SEARCH_CANDIDATES = 5000 _BYTES_PER_TOKEN = 3 @@ -77,11 +78,17 @@ class HistoryContext: matches: List[str] = field(default_factory=list) +def _fold(text: str) -> str: + """One Unicode folding for stored text and query words alike (NFKC, then case folding), + so matching does not depend on SQLite's ASCII-only lower().""" + return unicodedata.normalize("NFKC", text).casefold() + + def _word_patterns(query: str) -> List[List[str]]: """For each query word, its accepted forms, longest first (the word, then shorter prefixes).""" out: List[List[str]] = [] seen = set() - for w in _WORD.findall(query.lower()): + for w in _WORD.findall(_fold(query)): if w in seen: continue seen.add(w) @@ -90,6 +97,13 @@ def _word_patterns(query: str) -> List[List[str]]: return out +_COLUMNS = "h.id, h.ts, h.kind, h.channel_id, h.author_id, h.author_name, h.to_id, h.message_id, h.text" + + +def _record(row: sqlite3.Row) -> Record: + return Record(**{k: row[k] for k in Record.__dataclass_fields__}) + + def _tokens(line: str) -> float: return len(line.encode("utf-8")) / _BYTES_PER_TOKEN @@ -118,9 +132,9 @@ class HistoryStore: return None with self._lock: cur = self._conn.execute( - "INSERT OR REPLACE INTO history(ts, kind, channel_id, author_id, author_name, to_id, message_id, text)" - " VALUES (?,?,?,?,?,?,?,?)", - (ts, kind, channel_id, author_id, author_name, to_id, message_id, text), + "INSERT OR REPLACE INTO history(ts, kind, channel_id, author_id, author_name, to_id, message_id," + " text, norm) VALUES (?,?,?,?,?,?,?,?,?)", + (ts, kind, channel_id, author_id, author_name, to_id, message_id, text, _fold(text)), ) self._conn.commit() return int(cur.lastrowid) @@ -141,8 +155,8 @@ class HistoryStore: self.delete_chat(channel_id, message_id) return with self._lock: - self._conn.execute("UPDATE history SET text=? WHERE channel_id=? AND message_id=?", - (text, channel_id, message_id)) + self._conn.execute("UPDATE history SET text=?, norm=? WHERE channel_id=? AND message_id=?", + (text, _fold(text), channel_id, message_id)) self._conn.commit() def delete_chat(self, channel_id: str, message_id: str) -> None: @@ -178,8 +192,9 @@ class HistoryStore: def records_of(self, person: str) -> List[Record]: with self._lock: rows = self._conn.execute( - "SELECT * FROM history WHERE author_id=? OR to_id=? ORDER BY ts, id", (person, person)).fetchall() - return [Record(**dict(r)) for r in rows] + f"SELECT {_COLUMNS} FROM history h WHERE author_id=? OR to_id=? ORDER BY ts, id", + (person, person)).fetchall() + return [_record(r) for r in rows] def forget_person(self, person: str) -> None: with self._lock: @@ -221,48 +236,59 @@ class HistoryStore: where, params = self._scope_sql(asker, scope) with self._lock: rows = self._conn.execute( - f"SELECT h.* FROM history h WHERE {where} AND h.ts >= ? AND h.ts <= ?" + f"SELECT {_COLUMNS} FROM history h WHERE {where} AND h.ts >= ? AND h.ts <= ?" " ORDER BY h.ts DESC, h.id DESC LIMIT ?", (*params, now - minutes * 60, now, max_records)).fetchall() - return [Record(**dict(r)) for r in reversed(rows)] + return [_record(r) for r in reversed(rows)] def _scored_search(self, asker: str, query: str, scope: Scope, limit: int, exclude: Iterable[int]) -> List[tuple[float, Record]]: + """Score every record in scope (no recency cut before scoring) and return the best ``limit``. + + Two passes in SQLite: the first counts, per query word, how many records in scope match + it (for the rarity weight); the second scores and ranks in SQL so only ``limit`` rows + come back to Python. + """ words = _word_patterns(query) if scope.off or not words or limit <= 0: return [] where, params = self._scope_sql(asker, scope) - patterns = sorted({p for forms in words for p in forms}) - match_sql = " OR ".join("instr(lower(h.text), ?) > 0" for _ in patterns) skip = sorted(set(exclude)) skip_sql = f" AND h.id NOT IN ({','.join('?' * len(skip))})" if skip else "" + any_sql = " OR ".join("instr(h.norm, ?) > 0" for forms in words for _ in forms) + any_params = [f for forms in words for f in forms] + + def word_hit(forms: List[str]) -> tuple[str, list]: + # Fraction of the word matched: the longest accepted form found in the record. + whens = " ".join("WHEN instr(h.norm, ?) > 0 THEN ?" for _ in forms) + args: list = [] + for f in forms: + args += [f, len(f) / len(forms[0])] + return f"(CASE {whens} ELSE 0 END)", args + t0 = time.perf_counter() with self._lock: + counts_sql = ", ".join(f"SUM({word_hit(forms)[0]} > 0)" for forms in words) + counts_args = [a for forms in words for a in word_hit(forms)[1]] + row = self._conn.execute( + f"SELECT COUNT(*), {counts_sql} FROM history h WHERE {where} AND ({any_sql}){skip_sql}", + (*counts_args, *params, *any_params, *skip)).fetchone() + n = row[0] or 0 + if not n: + return [] + weights = [math.log(1 + n / max(1, row[i + 1] or 0)) for i in range(len(words))] + score_parts, score_args = [], [] + for w, forms in zip(weights, words): + expr, args = word_hit(forms) + score_parts.append(f"? * {expr}") + score_args += [w, *args] rows = self._conn.execute( - f"SELECT h.* FROM history h WHERE {where} AND ({match_sql}){skip_sql}" - " ORDER BY h.ts DESC, h.id DESC LIMIT ?", - (*params, *patterns, *skip, _SEARCH_CANDIDATES)).fetchall() - records = [Record(**dict(r)) for r in rows] - lowered = [r.text.lower() for r in records] - # Per word: matched fraction for every candidate, then inverse document frequency. - fractions = [] - for forms in words: - col = [] - for text in lowered: - hit = next((len(f) for f in forms if f in text), 0) - col.append(hit / len(forms[0])) - fractions.append(col) - n = len(records) - weights = [math.log(1 + n / max(1, sum(1 for x in col if x))) for col in fractions] - scored = [] - for i, rec in enumerate(records): - score = sum(w * col[i] for w, col in zip(weights, fractions)) - if score > 0: - scored.append((score, rec)) - scored.sort(key=lambda sr: (sr[0], sr[1].ts, sr[1].id), reverse=True) - debug_log(f"history search: {n} candidates, {len(scored)} scored, " - f"{(time.perf_counter() - t0) * 1000:.0f} ms", "memory") - return scored[:limit] + f"SELECT {_COLUMNS}, ({' + '.join(score_parts)}) AS score FROM history h" + f" WHERE {where} AND ({any_sql}){skip_sql}" + " ORDER BY score DESC, h.ts DESC, h.id DESC LIMIT ?", + (*score_args, *params, *any_params, *skip, limit)).fetchall() + debug_log(f"history search: {n} candidates, {(time.perf_counter() - t0) * 1000:.0f} ms", "memory") + return [(r["score"], _record(r)) for r in rows if r["score"] > 0] def search(self, asker: str, query: str, scope: Scope, limit: int = 5, exclude: Iterable[int] = ()) -> List[Record]: @@ -276,19 +302,20 @@ class HistoryStore: def context(self, asker: str, query: str, now: float, scope: Scope, minutes: float = 30, max_records: int = 20, limit: int = 5, budget_tokens: float = 4000) -> HistoryContext: recent = self.recent(asker, now, scope, minutes=minutes, max_records=max_records) - matches = self.search(asker, query, scope, limit=limit, exclude={r.id for r in recent}) - recent_lines = [self.format_line(r) for r in recent] - match_lines = [self.format_line(r) for r in matches] # best first - total = sum(_tokens(x) for x in recent_lines + match_lines) + # Search the whole scope, recent records included: a recent record the question is + # about must keep its place under the matches' share of the budget. + matches = self.search(asker, query, scope, limit=limit) # best first # Matches get at most half the budget so a long recent window cannot crowd out the - # one record the question is about; the recent window gets the rest. - while match_lines and sum(_tokens(x) for x in match_lines) > budget_tokens / 2: - total -= _tokens(match_lines.pop()) - while total > budget_tokens and recent_lines: - total -= _tokens(recent_lines.pop(0)) - # Oldest match first reads like a timeline. - by_line = dict(zip((self.format_line(r) for r in matches), matches)) - match_lines.sort(key=lambda line: by_line[line].ts) - debug_log(f"history context: {len(recent_lines)} recent, {len(match_lines)} matches, " + # records the question is about; the recent window gets the rest. + while matches and sum(_tokens(self.format_line(r)) for r in matches) > budget_tokens / 2: + matches.pop() + kept = {r.id for r in matches} + recent = [r for r in recent if r.id not in kept] # each record appears once + total = sum(_tokens(self.format_line(r)) for r in recent + matches) + while recent and total > budget_tokens: + total -= _tokens(self.format_line(recent.pop(0))) + matches.sort(key=lambda r: (r.ts, r.id)) # oldest first reads like a timeline + debug_log(f"history context: {len(recent)} recent, {len(matches)} matches, " f"~{total:.0f} tokens", "memory") - return HistoryContext(recent=recent_lines, matches=match_lines) + return HistoryContext(recent=[self.format_line(r) for r in recent], + matches=[self.format_line(r) for r in matches]) diff --git a/src/jarvis/memory/history.spec.md b/src/jarvis/memory/history.spec.md index f3b4e39..554ef00 100644 --- a/src/jarvis/memory/history.spec.md +++ b/src/jarvis/memory/history.spec.md @@ -50,19 +50,23 @@ Setting `since` (default none, meaning the whole history) drops records older th - `recent(asker, now, scope, minutes=30, max_records=20)`: records in scope newer than `now - minutes`, at most the newest `max_records`, oldest first. - `search(asker, query, scope, limit=5, exclude=ids)`: the records in scope that best match the - query. Query words are runs of Unicode word characters of 2 or more characters. A record matches - a word when its text contains the word, or a prefix of it that keeps at least 60% of the word and at - least 2 characters (so an inflected form or an attached particle still finds the stem: "watching" - finds "watched", "영화를" finds "영화"). The newest 5,000 matching records are scored. A word scores - its matched length divided by its own length, weighted by how rare the word is in scope (inverse - document frequency over the candidates). Ties go to the newer record. Records in `exclude` (the - recent window) are skipped so nothing is sent twice. + query, over the whole history in scope (nothing is cut by age or count before scoring). Stored + text and query are folded the same way (Unicode NFKC, then case folding) so matching ignores case + in every script ("МОСКВА" finds "москва", "STRASSE" finds "Straße"). Query words are runs of + Unicode word characters of 2 or more characters. A record matches a word when its text contains + the word, or a prefix of it that keeps at least 60% of the word and at least 2 characters (so an + inflected form or an attached particle still finds the stem: "watching" finds "watched", "영화를" + finds "영화"). A word scores its matched length divided by its own length, weighted by how rare the + word is in scope (log(1 + matching records / records matching that word)). Ties go to the newer + record. Records in `exclude` are skipped. - `context(asker, query, now, scope, ...)`: `recent` plus `search`, formatted one record per line as `[YYYY-MM-DD HH:MM] name: text` (local time of the host), and cut to the size budget - (default about 4,000 tokens, estimated as UTF-8 bytes divided by 3). Search matches may use at most - half the budget (lowest score cut first), so a long recent window cannot crowd out the record the - question is about; the recent window gets the rest (oldest cut first). Returns the two blocks separately so the - prompt can label them. + (default about 4,000 tokens, estimated as UTF-8 bytes divided by 3). The search covers the recent + window too, so a recent record the question is about is protected like any other match. Search + matches may use at most half the budget (lowest score cut first), so a long recent window cannot + crowd out the records the question is about; the recent window gets the rest (oldest cut first). + A record that is a match is not repeated in the recent block. Returns the two blocks separately + so the prompt can label them. ## Writes and maintenance diff --git a/src/jarvis/reply/engine.py b/src/jarvis/reply/engine.py index 001e54b..b32c6c2 100644 --- a/src/jarvis/reply/engine.py +++ b/src/jarvis/reply/engine.py @@ -1011,7 +1011,7 @@ def _history_block(history: Any) -> str: f"<{_HISTORY_FENCE}>", ] if matches: - parts.append("Earlier records related to this question:") + parts.append("Records related to this question:") parts.extend(clean(x) for x in matches) if recent: parts.append("Recent conversation, oldest first:") diff --git a/tests/test_history_store.py b/tests/test_history_store.py index 8746868..b0289ec 100644 --- a/tests/test_history_store.py +++ b/tests/test_history_store.py @@ -198,3 +198,30 @@ def test_search_over_a_large_history_stays_fast(store): elapsed = time.perf_counter() - t assert got and got[0].text == "희귀한 단어 오로라" assert elapsed < 1.0 + + +def test_search_covers_the_whole_history_not_just_the_newest_records(store): + store.add_voice(VC, "a", "Alice", "오늘 고양이 병원 예약은 목요일", T0) + for i in range(6000): + store.add_voice(VC, "a", "Alice", f"오늘 점심 이야기 {i}", T0 + 10 + i) + got = store.search("a", "오늘 고양이 병원 예약 언제", scope=Scope(), limit=3) + assert got and got[0].text == "오늘 고양이 병원 예약은 목요일" + + +def test_a_relevant_recent_record_survives_the_budget(store): + now = T0 + 1000 + store.add_voice(VC, "a", "Alice", "고양이 병원 예약은 목요일", now - 600) + for i in range(19): + store.add_voice(VC, "a", "Alice", f"잡담 {i} " + "가" * 400, now - 500 + i) + ctx = store.context("a", "고양이 병원 예약 언제", now=now, scope=Scope()) + lines = ctx.recent + ctx.matches + assert sum(1 for x in lines if "고양이 병원 예약은 목요일" in x) == 1 + total = sum(len(x.encode("utf-8")) for x in lines) / 3 + assert total <= 4000 + + +def test_search_folds_case_the_same_way_for_every_script(store): + store.add_voice(VC, "a", "Alice", "Поездка в МОСКВА завтра", T0) + store.add_voice(VC, "a", "Alice", "Straße frei", T0 + 1) + assert texts(store.search("a", "москва", scope=Scope())) == ["Поездка в МОСКВА завтра"] + assert texts(store.search("a", "STRASSE", scope=Scope())) == ["Straße frei"]