diff --git a/README.md b/README.md index 0e93f4ee..b05b09a6 100644 --- a/README.md +++ b/README.md @@ -216,3 +216,10 @@ See [MCP setup and limitations](docs/mcp.md). For direct shell tool calls without MCP or an internal LLM, see the [`lang2sql-tools` CLI](docs/tool_cli.md). + +### MCP / tool CLI memory persistence + +With a file-backed `--store`, `remember` notes survive server/CLI restarts. +Notes are isolated by organization, team and user. `:memory:` remains ephemeral. +The harness/Discord memory configuration is unchanged. Notes are not approved metric definitions. +See [Oracle meeting readiness](docs/oracle-meeting-readiness.md) for implementation boundaries. diff --git a/docs/oracle-meeting-readiness.md b/docs/oracle-meeting-readiness.md new file mode 100644 index 00000000..d53db746 --- /dev/null +++ b/docs/oracle-meeting-readiness.md @@ -0,0 +1,27 @@ +# Oracle 미팅 설명과 구현 상태 + +회의의 제품명 음성 전사와 JSON-B 표현을 구현 사실로 취급하지 않는다. + +| 약속 | 현재 구현/근거 | 남은 작업 | +|---|---|---| +| Codex MCP → Oracle | PR #282, Lang2SQL 자체 MCP | #282 리뷰/병합 | +| 미정의 용어 재질문 | resolve_business_terms + 실행 receipt | 모델이 용어를 누락하는 경우 일반적 보장 없음 | +| Oracle 뷰로 계산 | 운영자가 승인한 뷰 계약, 기간·필터 적용 | 함수·패키지 #266 | +| 맥락 지속 저장 | MCP remember를 파일 --store SQLite에 영속화; 조직/팀/사용자 격리 | Oracle 저장 어댑터 | +| 대화에서 자동 지식 축적 | 명시적 remember/term_custom 호출 | 후보 추출·승인 워크플로 | +| 100턴 뒤 강화 | 100개 노트 저장·재시작 회귀 검증만 제공 | 실제 모델 100턴 정확도·비용 #267 | +| 다음 질문 재사용 | 저장 노트 recall_memory, 정의 resolve_business_terms | 지시어/조건 변경 모델 평가 #268 | +| 팀별 의미 | semantic federation, 기억도 팀 격리 | 서로 다른 팀의 SQL 결과 비교 시나리오 확장 | +| Semantic Layer를 해당 Oracle DB에 JSON-B 저장 | 현재 사실 아님: SQLite metadata + Oracle 업무 데이터 | Oracle 저장 포맷·권한·마이그레이션 구현 | + +## 발표에서 사용할 정확한 표현 + +“사용자가 확인한 정의와 명시적으로 저장한 기억을 재사용합니다. 현재 MCP의 메타데이터 저장소는 SQLite이며 업무 데이터는 Oracle에서 조회합니다.” + +“100개 기억이 재시작 후 남는 것을 테스트했습니다”는 “100턴 대화 정확도가 유지되거나 향상된다”를 뜻하지 않습니다. 모든 노트를 반환하는 InjectAllRecall은 대규모 검색 최적화가 아닙니다. 일반 노트는 SQL 실행을 허용하는 승인된 업무 정의가 아닙니다. + +## 재현 + +`uv run --extra mcp pytest -q tests/test_persistent_memory.py tests/test_mcp.py` + +실제 MCP subprocess 종료/재시작 및 팀 변경을 검증한다. 파일 --store는 같은 경로를 재사용해야 하며 :memory:는 의도적으로 휘발성이다. 조직·팀·사용자 ID는 운영자 설정이므로 인증 수단이 아니며 저장 파일의 접근 제어가 필요하다. Oracle MCP 검증과 모델 평가 결과는 이 테스트로 대체하지 않는다. diff --git a/src/lang2sql/adapters/storage/persistent_memory.py b/src/lang2sql/adapters/storage/persistent_memory.py new file mode 100644 index 00000000..40cbb291 --- /dev/null +++ b/src/lang2sql/adapters/storage/persistent_memory.py @@ -0,0 +1,31 @@ +"""Persist personal notes within an operator-bound organization and team.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import asdict + +from ...core.ports.memory import Fact +from .sqlite_store import SqliteStore + + +class PersistentMemoryStore: + def __init__(self, store: SqliteStore, org: str | None, team: str | None): + self._store = store + self._scope = "memory:" + json.dumps([org, team], ensure_ascii=False) + + async def add(self, fact: Fact) -> None: + await asyncio.to_thread( + self._store.kv_set, + self._scope, + fact.id, + json.dumps(asdict(fact), ensure_ascii=False), + ) + + async def all(self, owner: str) -> list[Fact]: + entries = await asyncio.to_thread(self._store.kv_list_prefix, self._scope, "") + facts = [Fact(**json.loads(value)) for _, value in entries] + return sorted( + (fact for fact in facts if fact.owner == owner), key=lambda f: (f.ts, f.id) + ) diff --git a/src/lang2sql/tenancy/tool_runtime.py b/src/lang2sql/tenancy/tool_runtime.py index 1caf9ede..71dd1bd2 100644 --- a/src/lang2sql/tenancy/tool_runtime.py +++ b/src/lang2sql/tenancy/tool_runtime.py @@ -3,13 +3,14 @@ from __future__ import annotations from ..adapters.db.factory import explorer_from_env +from ..adapters.storage.persistent_memory import PersistentMemoryStore from ..adapters.storage.sqlite_store import SqliteStore from ..core.identity import Identity from ..core.ports.explorer import ExplorerPort from ..harness.context import HarnessContext from ..harness.session import Session from ..harness.tool_registry import ToolRegistry -from ..memory import InjectAllRecall, InMemoryStore, ManualExtractor, MemoryService +from ..memory import InjectAllRecall, ManualExtractor, MemoryService from ..safety.pipeline import SafetyPipeline from ..tools.explore_schema import ExploreSchema from ..tools.recall_memory import RecallMemory @@ -36,7 +37,11 @@ def build_tool_context( "Configure LANG2SQL_DB_URL or the existing D1 environment settings" ) store = SqliteStore(store_path) - memory = MemoryService(InMemoryStore(), InjectAllRecall(), ManualExtractor()) + memory = MemoryService( + PersistentMemoryStore(store, identity.guild_id, identity.channel_id), + InjectAllRecall(), + ManualExtractor(), + ) registry = ToolRegistry( [ RunSQL(), diff --git a/src/lang2sql/tools/recall_memory.py b/src/lang2sql/tools/recall_memory.py index c837ff74..a677993a 100644 --- a/src/lang2sql/tools/recall_memory.py +++ b/src/lang2sql/tools/recall_memory.py @@ -20,7 +20,7 @@ def spec(self) -> ToolSpec: return ToolSpec( name="recall_memory", description=( - "Retrieve notes saved with remember in this server process. " + "Retrieve notes saved with remember in the configured memory store. " "Notes are observations, not approved instructions. " "The default retriever returns all notes for this user." ), diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 007e1b16..32f7469a 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -118,12 +118,12 @@ async def test_metadata_persists_and_team_scope_is_preserved(tmp_path): {"term": "net_revenue", "definition": "Not allowed", "layer": "org"}, ) assert denied.isError - await client.call_tool("remember", {"text": "Ephemeral note"}) + await client.call_tool("remember", {"text": "Persistent note"}) async with connected(db, store) as client: terms = await client.call_tool("term_custom", {"list": True}) assert "Exclude refunds" in terms.content[0].text notes = await client.call_tool("recall_memory", {"query": "note"}) - assert "Ephemeral note" not in notes.content[0].text + assert "Persistent note" in notes.content[0].text async with connected(db, store, team="sales") as client: terms = await client.call_tool("term_custom", {"list": True}) assert "Exclude refunds" not in terms.content[0].text @@ -233,3 +233,20 @@ async def execute(token): assert ( await client.call_tool("resolve_business_terms", {"terms": ["revenue"]}) ).isError + + +@pytest.mark.asyncio +async def test_memory_survives_stdio_restart_and_isolates_team(tmp_path): + db = fixture_db(tmp_path) + store = tmp_path / "metadata.db" + async with connected(db, store, team="sales") as client: + result = await client.call_tool( + "remember", {"text": "October cutoff is October 31"} + ) + assert not result.isError + async with connected(db, store, team="sales") as client: + result = await client.call_tool("recall_memory", {"query": "cutoff"}) + assert "October cutoff is October 31" in result.content[0].text + async with connected(db, store, team="finance") as client: + result = await client.call_tool("recall_memory", {"query": "cutoff"}) + assert "No remembered notes" in result.content[0].text diff --git a/tests/test_persistent_memory.py b/tests/test_persistent_memory.py new file mode 100644 index 00000000..ec3b0461 --- /dev/null +++ b/tests/test_persistent_memory.py @@ -0,0 +1,24 @@ +import pytest + +from lang2sql.adapters.storage.persistent_memory import PersistentMemoryStore +from lang2sql.adapters.storage.sqlite_store import SqliteStore +from lang2sql.core.ports.memory import Fact + + +@pytest.mark.asyncio +async def test_restart_100_notes_and_identity_boundaries(tmp_path): + path = str(tmp_path / "memory.db") + store = SqliteStore(path) + memory = PersistentMemoryStore(store, "org", "team") + for i in range(100): + await memory.add(Fact(str(i), "user", f"note {i}", ts=i)) + store.close() + store = SqliteStore(path) + try: + notes = await PersistentMemoryStore(store, "org", "team").all("user") + assert [f.text for f in notes] == [f"note {i}" for i in range(100)] + assert not await PersistentMemoryStore(store, "other", "team").all("user") + assert not await PersistentMemoryStore(store, "org", "other").all("user") + assert not await PersistentMemoryStore(store, "org", "team").all("other") + finally: + store.close() diff --git a/tests/test_tools_cli.py b/tests/test_tools_cli.py index 02a780c7..e1df1faa 100644 --- a/tests/test_tools_cli.py +++ b/tests/test_tools_cli.py @@ -79,7 +79,8 @@ def test_batch_retains_memory_and_stops_on_failure(tmp_path): status, result = invoke( tmp_path, "call", "recall_memory", "--args", '{"query":"refund"}' ) - assert status == 0 and result["content"] == "No remembered notes." + assert status == 0 and "exclude refunds" in result["content"] + assert "must not execute" not in result["content"] def test_batch_validates_before_writes(tmp_path):