13 Commits
Author SHA1 Message Date
Claudio DrewsandClaudioDrews 251c16ffad feat: collapse v2 — attenuate Hebbian boost by query-local salience (#24)
- score_all() now multiplies amplify_gain by base salience before
  applying Hebbian cross-source corroboration boost, so globally-
  important structural facts no longer crowd out query-locally-
  relevant facts
- ICARUS_COLLAPSE_AMPLIFY_GAIN env var (default 0.15) tunes the
  tradeoff; raise to 0.20 if genuine corroboration feels undervalued
- All tests passing (_test_collapse.py, collapse_eval.py)
- Real pipeline test: 30-35% token reduction with correct ranking

Closes #23

Co-authored-by: ClaudioDrews <claudio@drews.com.br>
2026-06-07 09:48:00 -03:00
ClaudioDrews 1abce75a05 fix: strip YAML quotes in curate_entry ID comparison (fixes #20)
m.group(1) captures 'f95842e2' (with quotes) from YAML id: field.
Comparison with unquoted entry_id always failed → no entry ever found.
Added .strip('"') after .strip() to normalize before comparison.
2026-06-07 08:14:40 -03:00
ClaudioDrews 67ceb78202 refactor: extract shared parse_entry into icarus/parsing.py (fixes D01, D09)
D01 — parse_entry YAML fallback was duplicated and buggy (split ': '
breaks on URLs). Primary parser (yaml.safe_load) already handled
URLs correctly; manual fallback is now centralized in one module.

D09 — export-training.py had a duplicate parse_entry with the same
bug. Now imports from parsing.py.

Both files use try/except ImportError to support both package-mode
(icarus plugin) and standalone execution (CLI scripts).

Shared module returns both naming conventions (_body/body, _file/file)
for backward compatibility with fabric-retrieve and export-training.
2026-06-03 17:00:19 -03:00
ClaudioDrews 327b18bf47 Merge PR #13: provider-agnostic LLM extraction (brian-doherty)
Combines HERMES_AGENT_NAME + DeepSeek/custom endpoint vars in
.env.example Strongly Recommended section.
2026-06-03 16:37:38 -03:00
ClaudioDrews 3fd7cd6faf docs: Fase C — R3 (Ollama), R4 (cron jobs), R5 (agent name), R6 (Qdrant)
R3: .env.example — Embedding backend reestruturado com Option A (Ollama,
recomendado para produção) e Option B (OpenRouter). install.md passo 4
atualizado para mencionar Ollama como opção local.

R4: install.md passo 8 — adicionados 3 cron jobs stack-base na tabela
e nos exemplos CLI: holographic-memory-backup (backup semanal do
memory_store.db), wiki-raw-ingest-monitor (detecção de drift em raw/),
maas-heartbeat (healthcheck Qdrant/Redis/ARQ).

R5: .env.example + install.md passo 6 — adicionado HERMES_AGENT_NAME.
state.py write_entry agora loga warning quando AGENT_NAME não está
definido.

R6: install.md Troubleshooting — nota sobre coexistência de coleções
Qdrant (knowledge_base + outras coleções de agentes externos).
2026-06-03 15:46:31 -03:00
ClaudioDrews 170a6ba6be fix: Fase A — 3 correções de código (R7, R8, R9)
R7 (V5.03/B11): hooks.py _search_qdrant — os.environ mutation agora usa
try/finally com restore. Chave OPENROUTER_API_KEY é injetada
temporariamente só durante o import do context_enhancer.

R8 (V5.06/B06): state.py write_entry e write_memory_file — substituído
path.write_text() por tmp + rename (escrita atômica). Evita corrupção
de arquivo em caso de crash durante o write.

R9 (item 5): state.py read_pending — normalizado agent = AGENT_NAME or
'agent' para consistência com write_entry. Corrige lógica de assignment
quando HERMES_AGENT_NAME não está definido.
2026-06-03 15:05:54 -03:00
Brian Doherty 2d6281e86c feat: provider-agnostic LLM extraction
Make the Icarus extraction pipeline work with any LLM provider
instead of hardcoding OpenRouter.

New env vars (all optional, backward compatible):
  DEEPSEEK_API_KEY       — route directly to api.deepseek.com
  ICARUS_ENDPOINT        — fully custom v1/chat/completions URL
  ICARUS_API_KEY_ENV     — env var name for the custom endpoint key

Resolution priority:
  1. ICARUS_ENDPOINT + ICARUS_API_KEY_ENV (fully custom)
  2. DEEPSEEK_API_KEY → api.deepseek.com
  3. OPENROUTER_API_KEY → openrouter.ai (existing behaviour, unchanged)

Model names are automatically normalized: OpenRouter-style
deepseek/deepseek-v4-flash slugs have the provider prefix
stripped for direct API calls.

No breaking changes. If DEEPSEEK_API_KEY and ICARUS_ENDPOINT
are both unset, behaviour is identical to previous versions.
2026-06-03 11:29:15 -05:00
ClaudioDrews 144795bf74 perf: Qdrant query_batch_points + SQLite FTS5 for semantic_dedup and fabric-retrieve
V4.01: Replace O(n²) brute-force cosine similarity in semantic_dedup.py
  with Qdrant query_batch_points() — delegates nearest-neighbor search
  to the native HNSW index. Batch size auto-scales (min 200, adjusted
  for collection size). Self-match excluded server-side via
  HasIdCondition filter. Graceful fallback if qdrant-client not installed.

V4.03: Replace glob+parse in fabric-retrieve.py retrieve() with SQLite
  fabric_index + fabric_fts (FTS5). _ensure_fabric_index() rebuilds the
  index lazily when any fabric .md mtime exceeds the stored max mtime.
  Transactional rebuild (BEGIN; DELETE; DELETE; ...; COMMIT) prevents
  index corruption on partial failure. All score_entry fields preserved
  as columns — no YAML parsing after initial index build.
2026-06-03 12:14:30 -03:00
ClaudioDrews 45e2b075f7 perf: O(1) lookups for obsidian _find_entry_file + export-training _resolve_ref
V4.02: Replace glob+parse scan in _find_entry_file with in-memory dict index
  - _build_entry_index() scans fabric dirs once, builds (agent,id)→stem dict
  - Index rebuilds lazily when fabric_dir.stat().st_mtime changes
  - O(n) rebuild only on changes, O(1) per lookup thereafter

V4.07: Replace 4× O(n) linear scans in _resolve_ref with prebuilt indices
  - index_by_id, index_by_cycle: exact dict lookups (covers ~90% of calls)
  - by_agent_entries: scoped substring scans (per-agent, not full list)
  - Slow path preserved for standalone calls without indices
  - All 4 call sites in build_pairs() updated to pass indices
2026-06-03 12:04:14 -03:00
ClaudioDrews 1422a6d583 fix: resolve 5 easy Phase 4 performance/resilience issues
V4.04: Add retry_transient() to dlq_manager — re-enables reported transient
  failures for retry with --retry CLI flag, increments retry_count/last_retry

V4.05: save_report() now truncates JSONL to MAX_REPORT_HISTORY entries
  after each append (best-effort rotation)

V4.06: Wrap datetime.fromisoformat() in try/except (ValueError, TypeError)
  in get_status_summary() — skips entries with malformed timestamps

V4.08: Replace body[:50] dedup key with hashlib.sha256(body).hexdigest()
  in fabric-retrieve.py deduplicate()

V4.09: Add OrderedDict LRU cache (256 entries) to embedding.py get_embedding()
  — avoids recomputing embeddings for repeated text
2026-06-03 11:53:18 -03:00
ClaudioDrews 598eaf19d0 fix(sanitize): change system prefix replacement from silent removal to [REDACTED]
- Silent removal (empty string) left grammatically broken sentences
  and no audit trail. [REDACTED] preserves context structure.
- Control chars and zero-width Unicode keep empty string replacement
  (invisible characters, removal is correct).
- Updated 4 test assertions in _test_sanitize.py.
2026-06-02 13:45:02 -03:00
David Soff a5c1344afb security(hooks, context_enhancer): add dual-layer prompt injection sanitization (#5)
security(hooks, context_enhancer): add dual-layer prompt injection sanitization

- Layer 1 (hooks.py): aggressive sanitization at prompt boundary with
  11 regex patterns + heuristic. Detects override directives, template
  injection, URI schemes, system prefixes, HTML/XML, control chars,
  zero-width Unicode, and code fences. Applied to fabric, Qdrant,
  sessions, and facts injection points. Complements existing
  _is_system_injection() (which filters ingest, not egest).

- Layer 2 (context_enhancer.py): lightweight sanitization on all
  search result content_preview outputs (hybrid, dense, sparse,
  lexical, sqlite).

- _test_sanitize.py: manual validation script with 24 test cases.

- Replacement strategy: [REDACTED] preserves audit trail and
  grammatical context instead of silent removal.
2026-06-02 13:43:34 -03:00
ClaudioDrews 0b32ffcfc2 Initial commit: Memory OS — 6-layer memory architecture for Hermes Agent 2026-05-31 16:50:37 -03:00