Skip to content

fix: stop pass-1 narration leaking + remove PII masking + lower thres…#14

Merged
Krasimir-Hristov merged 3 commits into
mainfrom
fix/memory-retrieval-and-streaming
May 7, 2026
Merged

fix: stop pass-1 narration leaking + remove PII masking + lower thres…#14
Krasimir-Hristov merged 3 commits into
mainfrom
fix/memory-retrieval-and-streaming

Conversation

@Krasimir-Hristov

Copy link
Copy Markdown
Owner

…hold

  • Buffer supervisor pass-1 tokens and discard if memory_agent fires (prevents DeepSeek narration text leaking to user on tool calls)
  • Add CRITICAL output rule to supervisor prompt (no text before tool_call)
  • Remove PII masking from memory pipeline (Presidio was breaking embeddings)
  • Lower cosine similarity threshold from 0.6 to 0.35 for better recall
  • Add tool_use SSE event type with pulsing Database indicator in ChatWindow
  • Populate content_masked column with plaintext (masking removed)

…hold

- Buffer supervisor pass-1 tokens and discard if memory_agent fires
  (prevents DeepSeek narration text leaking to user on tool calls)
- Add CRITICAL output rule to supervisor prompt (no text before tool_call)
- Remove PII masking from memory pipeline (Presidio was breaking embeddings)
- Lower cosine similarity threshold from 0.6 to 0.35 for better recall
- Add tool_use SSE event type with pulsing Database indicator in ChatWindow
- Populate content_masked column with plaintext (masking removed)
@coderabbitai

coderabbitai Bot commented May 6, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Copilot has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 57 minutes and 32 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 56e3f4f3-4b6a-4ed0-b8ce-b483ede383cb

📥 Commits

Reviewing files that changed from the base of the PR and between d5d239c and 7210486.

📒 Files selected for processing (8)
  • backend/app/agents/subagents/memory_agent.py
  • backend/app/agents/supervisor.py
  • backend/app/features/chat/schemas.py
  • backend/app/features/chat/service.py
  • backend/app/features/memory/service.py
  • frontend/features/chat/components/ChatWindow.tsx
  • frontend/features/chat/hooks/useChat.ts
  • frontend/features/chat/types.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/memory-retrieval-and-streaming

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Krasimir-Hristov

Copy link
Copy Markdown
Owner Author

@copilot pregledaj tozi kod molq te

Copilot AI and others added 2 commits May 6, 2026 21:56
…shold default

Agent-Logs-Url: https://github.com/Krasimir-Hristov/AXON/sessions/bba8361d-8f1c-423d-8eb8-e46d11e5da93

Co-authored-by: Krasimir-Hristov <102061932+Krasimir-Hristov@users.noreply.github.com>
Agent-Logs-Url: https://github.com/Krasimir-Hristov/AXON/sessions/bba8361d-8f1c-423d-8eb8-e46d11e5da93

Co-authored-by: Krasimir-Hristov <102061932+Krasimir-Hristov@users.noreply.github.com>

Copilot AI commented May 6, 2026

Copy link
Copy Markdown
Contributor

@copilot pregledaj tozi kod molq te

Прегледах целия PR. Ето обобщение:

✅ Правилно имплементирано:

  • Pass-1 буфериране (service.py) — логиката е коректна: токените от pass-1 се буферират, изчистват се при memory_agent, и се изпращат при директен отговор. Покрива DeepSeek narration проблема.
  • CRITICAL output rule в системния промпт — добра safety мрежа срещу narration преди tool_call.
  • tool_use SSE event + Database индикатор — правилно имплементирано и на backend и на frontend.
  • SSEEvent схемата и SSEEventType типа са синхронизирани.
  • Премахването на PII masking — добре документирано с обосновка в docstring.

🐛 Бъгове, намерени и оправени (commit 799f7b1):

  • stopStreaming и resetConversation не изчистваха toolStatus → "Searching memory…" индикаторът ставаше "замръзнал" ако потребителят спре стрийма по средата на memory search. Добавих setToolStatus(null) и в двете функции.

🔧 Малки подобрения (commit 7210486):

  • search_memories имаше default threshold=0.7 докато реалното извикване е с 0.35 — несъответствие. Синхронизирах default-а и добавих docstring обясняващ защо 0.35 (multilingual embedding space контракция).

⚠️ Бележка за архитектурата:
python-backend.instructions.md изисква PII masking преди embedding. Премахването е умишлено (Presidio чупеше embeddings), но противоречи на собствената политика на проекта. Ако проектът ще се използва с чувствителни данни, помислете за алтернативно решение на по-дълъг хоризонт.

CodeQL: 0 нови alerts. ✅

@Krasimir-Hristov

Copy link
Copy Markdown
Owner Author

@copilot как точно работеше PII masking s Presidio

Copilot AI commented May 7, 2026

Copy link
Copy Markdown
Contributor

@copilot как точно работеше PII masking s Presidio

PII masking-ът работеше така (код в backend/app/core/privacy.py):

Библиотеки: Microsoft Presidio (presidio-analyzer + presidio-anonymizer) + spaCy en_core_web_sm за NLP.

Какво засичаше: PERSON, EMAIL_ADDRESS, PHONE_NUMBER, CREDIT_CARD, IBAN_CODE, IP_ADDRESS, LOCATION, US_SSN

Write path (запис на памет):

plaintext → mask_pii(text) → "<PERSON>", "<EMAIL_ADDRESS>" → embed(masked_text) → encrypt(plaintext) → insert

Embedding-ът се изчисляваше върху маскирания текст, а в DB се пазеше оригиналният шифрован текст.

Search path (търсене):

user_query → mask_pii(query) → embed(masked_query) → cosine similarity → decrypt results

Защо се счупи: spaCy-то е English-only (en_core_web_sm). Текст на български или transliterated Bulgarian ("az se kazvam Krasimir") преминаваше без маскиране, но семантичното значение на думите частично се губеше след anonymization (заместването с <PERSON> и т.н. редуцира информационното съдържание). По-важното — embedding моделът на OpenRouter embed-ваше различен текст при запис (masked) и при търсене (ако query не съдържаше PII → не беше маскиран → различно embedding пространство). Това водеше до ниска cosine similarity и невъзможност да се намерят записани спомени.

Сегашното решение: embed директно от plaintext — семантиката е запазена, multilingual работи, retrieval-ът е коректен. Оригиналният plaintext продължава да се криптира в content_encrypted преди запис в DB.

@Krasimir-Hristov

Copy link
Copy Markdown
Owner Author

@copilot koj model iypolyvam ya embedding

Copilot AI commented May 7, 2026

Copy link
Copy Markdown
Contributor

@copilot koj model iypolyvam ya embedding

Използваш openai/text-embedding-3-large с 1536 измерения (Matryoshka), рутиран през OpenRouter's OpenAI-compatible /embeddings endpoint.

Конфигурацията е в backend/app/core/config.py:

embedding_model: str = "openai/text-embedding-3-large"
embedding_dimensions: int = 1536

Именно затова threshold-ът е 0.35 — text-embedding-3-large е multilingual модел, но в многоезично embedding пространство cosine similarity-тата са по-ниски отколкото при English-only модели.

@Krasimir-Hristov
Krasimir-Hristov merged commit a6f1257 into main May 7, 2026
4 checks passed
@Krasimir-Hristov
Krasimir-Hristov deleted the fix/memory-retrieval-and-streaming branch May 7, 2026 17:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants