Initial commit: Memory OS — 6-layer memory architecture for Hermes Agent

This commit is contained in:
ClaudioDrews
2026-05-31 16:50:37 -03:00
commit 0b32ffcfc2
52 changed files with 10838 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
# Memory OS — Scripts
Standalone Python scripts that maintain the Qdrant vector database and wiki pipeline.
## Qdrant Maintenance
| Script | What it does | Run |
|--------|-------------|-----|
| `decay_scanner.py` | Archives low-importance, aged AI content based on half-life decay | Weekly cron |
| `backfill_decay_metadata.py` | Populates missing `importance_score`, `last_accessed_at`, `confidence_score` in Qdrant points | Run once before enabling decay scanner |
| `semantic_dedup.py` | Merges near-duplicate points (cosine >0.92) | Monthly cron |
## Context Injection
| Script | What it does | Used by |
|--------|-------------|---------|
| `context_enhancer.py` | Embedding pipeline: query → embed → search Qdrant (4-level fallback). Also provides BM25 sparse embedding via FastEmbed. | Icarus `pre_llm_call` hook |
## Wiki Pipeline
| Script | What it does | Run |
|--------|-------------|-----|
| `wiki_continuous_ingest.py` | SHA-256 diff detection: finds new/modified wiki files, enqueues ARQ jobs in Redis | Hourly cron |
| `bulk_wiki_ingest.py` | One-shot bulk ingestion of all wiki files into Qdrant | After initial setup or collection rebuild |
## Quality Control
| Script | What it does | Run |
|--------|-------------|-----|
| `pre_validator.py` | Pre-flight validation of wiki documents: YAML frontmatter, required fields, link targets | Before ingestion |
| `reflection_trigger.py` | Idle detection for ARQ worker — enqueues micro-reflection when queue is empty and within hourly budget | Every 5min cron |
## Monitoring
| Script | What it does | Run |
|--------|-------------|-----|
| `dlq_manager.py` | Dead letter queue monitoring and reporting | Every 6h cron |
## Environment variables
All scripts read configuration from environment variables. See `.env.example` in the project root for the full reference.
Key variables:
- `OPENROUTER_API_KEY` — embeddings (required)
- `WIKI_PATH` — wiki root directory (default: `~/vault/wiki`)
- `COLLECTION_NAME` — Qdrant collection (default: `knowledge_base`)
- `EMBEDDING_DIMS` — vector dimensions (default: 4096)
- `REDIS_PASSWORD` — Redis auth (required for wiki ingest)
- `QDRANT_URL` — Qdrant endpoint (default: `http://localhost:6333`)
+292
View File
@@ -0,0 +1,292 @@
#!/usr/bin/env python3
"""Backfill decay metadata for Qdrant knowledge_base.
Populates missing fields (created_at, last_accessed_at, importance_score,
confidence_score, archived) so the decay_scanner can actually work.
Modes:
--dry-run Simulate everything, print stats, no writes (DEFAULT)
--commit Actually update points via REST API
--pilot N Process only N points (for validation)
Usage:
python3 backfill_decay_metadata.py --dry-run --pilot 50
python3 backfill_decay_metadata.py --dry-run
python3 backfill_decay_metadata.py --commit
Heuristics:
- created_at / last_accessed_at:
Session points: from payload.timestamp (Unix epoch → ISO 8601)
Wiki points: from file mtime if file exists, else now()
- importance_score: 0.5 flat (conservative)
- confidence_score:
wiki-* → 0.85
session → 0.70
unknown → 0.75
- archived: false (explicit)
Safety:
- Dry-run by default — no writes without --commit
- Only touches points MISSING the target fields (no overwrites)
- Batched via REST API POST /points/payload
- Uses same pattern as migrate_strength.py (2026-05-29)
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError
# ─── Config ──────────────────────────────────────────────────────────────────
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", os.environ.get("COLLECTION_NAME", "knowledge_base"))
BATCH_SIZE = 200
SCROLL_LIMIT = 200
LOG_FILE = Path(os.environ.get("HERMES_LOGS_DIR", str(Path.home() / ".hermes" / "logs"))) / "decay_scanner.log"
VAULT_ROOT = Path(os.environ.get("VAULT_PATH", "."))
# ─── Heuristics ──────────────────────────────────────────────────────────────
CONFIDENCE_BY_SOURCE = {
"wiki-concepts": 0.85,
"wiki-entities": 0.85,
"wiki-comparisons": 0.85,
"wiki-raw": 0.85,
"session": 0.70,
}
CONFIDENCE_DEFAULT = 0.75
IMPORTANCE_SCORE = 0.5
ARCHIVED = False
def log(msg: str) -> None:
"""Append timestamped message to log."""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[backfill-decay] {ts} {msg}"
print(line)
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(LOG_FILE, "a") as f:
f.write(line + "\n")
def scroll_all() -> list[dict]:
"""Scroll entire collection, returning all points with payloads."""
points = []
offset = None
while True:
body = {"limit": SCROLL_LIMIT, "with_payload": True, "with_vector": False}
if offset:
body["offset"] = offset
req = Request(
f"{QDRANT_URL}/collections/{COLLECTION}/points/scroll",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
)
try:
with urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode())
except URLError as e:
log(f"ERROR: scroll failed: {e}")
break
result = data.get("result", {})
batch = result.get("points", [])
points.extend(batch)
offset = result.get("next_page_offset")
if offset is None or len(batch) == 0:
break
return points
def resolve_timestamp(point: dict) -> str:
"""Return ISO 8601 string for created_at/last_accessed_at.
Session points: use payload.timestamp (Unix epoch float).
Wiki points: locate file via payload.filename → file mtime.
Fallback: now().
"""
pl = point.get("payload", {})
ts_raw = pl.get("timestamp")
if ts_raw is not None:
try:
ts_float = float(ts_raw)
return datetime.fromtimestamp(ts_float, tz=timezone.utc).isoformat()
except (ValueError, TypeError, OSError):
pass
# Wiki point — resolve filename to filesystem path
filename = pl.get("filename", "")
source = pl.get("source", "")
if filename and source.startswith("wiki-"):
# Map source to subfolder: wiki-concepts → concepts, wiki-entities → entities, etc.
subfolder = source.replace("wiki-", "")
candidate = VAULT_ROOT / "wiki" / subfolder / f"{filename}.md"
try:
mtime = candidate.stat().st_mtime
return datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat()
except OSError:
pass
# Absolute fallback
return datetime.now(timezone.utc).isoformat()
def compute_confidence(point: dict) -> float:
"""Heuristic confidence_score by source."""
source = point.get("payload", {}).get("source", "")
return CONFIDENCE_BY_SOURCE.get(source, CONFIDENCE_DEFAULT)
def needs_backfill(point: dict) -> list[str]:
"""Return list of fields this point is missing (that we backfill)."""
TARGETS = ["created_at", "last_accessed_at", "importance_score", "confidence_score", "archived"]
pl = point.get("payload", {})
return [f for f in TARGETS if f not in pl]
def build_payload(point: dict) -> dict:
"""Build the payload fragment to backfill for this point."""
ts = resolve_timestamp(point)
return {
"created_at": ts,
"last_accessed_at": ts,
"importance_score": IMPORTANCE_SCORE,
"confidence_score": compute_confidence(point),
"archived": ARCHIVED,
}
def upsert_batch(point_ids: list[str], payload: dict) -> bool:
"""Update payload for a batch of points via REST API. Fail-open."""
body = {"payload": payload, "points": point_ids}
req = Request(
f"{QDRANT_URL}/collections/{COLLECTION}/points/payload",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
)
try:
with urlopen(req, timeout=30) as resp:
result = json.loads(resp.read().decode())
return result.get("status") == "ok"
except URLError as e:
log(f"ERROR: upsert batch failed: {e}")
return False
def run(dry_run: bool = True, pilot: int = 0, commit: bool = False):
"""Main execution."""
mode = "DRY-RUN" if dry_run else "COMMIT"
log(f"=== BACKFILL DECAY METADATA ({mode}) ===")
log(f"Collection: {COLLECTION}")
log(f"Pilot: {pilot if pilot else 'all'}")
# ── Scroll all points ──
log("Scrolling all points...")
all_points = scroll_all()
total = len(all_points)
log(f"Total points: {total}")
# ── Identify points needing backfill ──
to_update: list[tuple[str, dict]] = [] # (point_id, payload_fragment)
skipped_already_have = 0
stats_by_source = {}
for p in all_points:
missing = needs_backfill(p)
if not missing:
skipped_already_have += 1
continue
pid = str(p["id"])
pl = build_payload(p)
to_update.append((pid, pl))
src = p.get("payload", {}).get("source", "unknown")
stats_by_source[src] = stats_by_source.get(src, 0) + 1
log(f"Points needing backfill: {len(to_update)}/{total}")
log(f"Points already complete: {skipped_already_have}")
if pilot and pilot < len(to_update):
to_update = to_update[:pilot]
log(f"Pilot mode: processing first {pilot}")
# ── Stats by source ──
log("Backfill candidates by source:")
for src, count in sorted(stats_by_source.items(), key=lambda x: -x[1]):
ts_sample = ""
for pid, pl in to_update:
if pid and len(ts_sample) < 3:
p = next((pp for pp in all_points if str(pp["id"]) == pid), None)
if p and p.get("payload", {}).get("source") == src:
ts_sample = pl.get("created_at", "")[:19]
break
log(f" {src:<25} {count:>6} pts ts_sample={ts_sample}")
if dry_run:
log("DRY-RUN complete. No changes made. Use --commit to apply.")
return
# ── Commit ──
if not commit:
log("ERROR: --commit flag required for writes. Aborting.")
return
log(f"Committing in batches of {BATCH_SIZE}...")
success = 0
failed = 0
for i in range(0, len(to_update), BATCH_SIZE):
batch = to_update[i : i + BATCH_SIZE]
# Group by identical payload (same timestamp, same confidence)
# For simplicity, each point gets its own upsert — but we batch IDs
# with identical payloads where possible
payload_groups: dict[str, tuple[list[str], dict]] = {}
for pid, pl in batch:
key = json.dumps(pl, sort_keys=True)
if key not in payload_groups:
payload_groups[key] = ([], pl)
payload_groups[key][0].append(pid)
for ids, pl in payload_groups.values():
ok = upsert_batch(ids, pl)
if ok:
success += len(ids)
else:
failed += len(ids)
log(f" FAILED batch: {len(ids)} points, first id={ids[0]}")
batch_num = i // BATCH_SIZE + 1
total_batches = (len(to_update) + BATCH_SIZE - 1) // BATCH_SIZE
log(f" Batch {batch_num}/{total_batches}: {success} ok, {failed} failed")
if i + BATCH_SIZE < len(to_update):
time.sleep(0.5) # gentle rate limit
log(f"COMMIT complete. success={success}, failed={failed}")
if failed > 0:
log("WARNING: some batches failed. Check logs.")
def main():
parser = argparse.ArgumentParser(description="Backfill decay metadata for Qdrant knowledge_base")
parser.add_argument("--dry-run", action="store_true", default=True,
help="Simulate, no writes (default)")
parser.add_argument("--commit", action="store_true",
help="Actually write to Qdrant")
parser.add_argument("--pilot", type=int, default=0,
help="Process only N points (for validation)")
args = parser.parse_args()
if args.commit:
args.dry_run = False
run(dry_run=args.dry_run, pilot=args.pilot, commit=args.commit)
if __name__ == "__main__":
main()
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env python3
"""
Bulk ingest script — populates the Qdrant knowledge_base with all wiki content.
Phase A: one-shot of existing files.
"""
import os
import re
import sys
import json
import time
import uuid
from pathlib import Path
from datetime import datetime, timezone
from collections import Counter
import aiohttp
import asyncio
# ─── Config ────────────────────────────────────────────────────────────────
OPENROUTER_KEY = os.environ.get("OPENROUTER_API_KEY")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", os.environ.get("COLLECTION_NAME", "knowledge_base"))
WIKI_ROOT = Path(os.environ.get("WIKI_ROOT", "."))
EMBEDDING_MODEL = "qwen/qwen3-embedding-8b"
EMBEDDING_DIMS = 4096
MAX_TEXT_LEN = 8000 # truncate text for embedding (model context limit)
BATCH_SIZE = 8 # parallel embedding requests
RATE_LIMIT_SLEEP = 0.5 # seconds between batches
if not OPENROUTER_KEY:
print("❌ OPENROUTER_API_KEY not found in environment")
sys.exit(1)
print(f"📁 Wiki root: {WIKI_ROOT}")
print(f"🎯 Collection: {COLLECTION}")
print(f"🔑 OpenRouter: configured")
# ─── Find all .md files ───────────────────────────────────────────────────
md_files = sorted(WIKI_ROOT.rglob("*.md"))
print(f"📄 .md files found: {len(md_files)}")
# ─── Helpers ──────────────────────────────────────────────────────────────
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Extract YAML frontmatter and return (metadata, body)."""
if text.startswith("---"):
parts = text.split("---", 2)
if len(parts) >= 3:
try:
import yaml
meta = yaml.safe_load(parts[1])
body = parts[2].strip()
return (meta if isinstance(meta, dict) else {}), body
except Exception:
pass
return {}, text
def get_source_tag(path: Path) -> str:
"""Derive source tag from path relative to wiki root."""
rel = path.relative_to(WIKI_ROOT)
parts = rel.parts
if len(parts) > 1:
return f"wiki-{parts[0]}"
return "wiki-root"
def get_tags_from_frontmatter(meta: dict) -> list[str]:
"""Extract tags from frontmatter."""
tags = meta.get("tags", [])
if isinstance(tags, str):
tags = [t.strip() for t in tags.split(",")]
return tags if isinstance(tags, list) else []
async def get_embedding(session: aiohttp.ClientSession, text: str) -> list[float] | None:
"""Generate embedding via OpenRouter."""
payload = {
"model": EMBEDDING_MODEL,
"input": text[:MAX_TEXT_LEN],
"dimensions": EMBEDDING_DIMS,
}
try:
async with session.post(
"https://openrouter.ai/api/v1/embeddings",
headers={
"Authorization": f"Bearer {OPENROUTER_KEY}",
"Content-Type": "application/json",
},
json=payload,
timeout=aiohttp.ClientTimeout(total=30),
) as resp:
if resp.status != 200:
body = await resp.text()
print(f"⚠️ Embedding HTTP {resp.status}: {body[:200]}")
return None
data = await resp.json()
return data["data"][0]["embedding"]
except Exception as e:
print(f"⚠️ Embedding error: {e}")
return None
async def upsert_to_qdrant(session: aiohttp.ClientSession, points: list[dict]) -> bool:
"""Upsert batch of points into Qdrant."""
try:
async with session.put(
f"{QDRANT_URL}/collections/{COLLECTION}/points",
headers={"Content-Type": "application/json"},
json={"points": points},
timeout=aiohttp.ClientTimeout(total=30),
) as resp:
if resp.status != 200:
body = await resp.text()
print(f"⚠️ Qdrant HTTP {resp.status}: {body[:200]}")
return False
return True
except Exception as e:
print(f"⚠️ Qdrant error: {e}")
return False
# ─── Main processing ──────────────────────────────────────────────────────
async def main():
stats = Counter({"ok": 0, "fail": 0, "skip": 0, "empty": 0})
errors = []
processed = 0
total = len(md_files)
connector = aiohttp.TCPConnector(limit=20)
async with aiohttp.ClientSession(connector=connector) as session:
# Check collection
async with session.get(f"{QDRANT_URL}/collections/{COLLECTION}") as r:
if r.status != 200:
print(f"❌ Collection {COLLECTION} does not exist!")
sys.exit(1)
print("\n🚀 Starting ingestion in batches...\n")
batch = []
for idx, path in enumerate(md_files, 1):
text = path.read_text(encoding="utf-8", errors="replace")
if not text.strip():
stats["empty"] += 1
continue
meta, body = parse_frontmatter(text)
source = get_source_tag(path)
tags = get_tags_from_frontmatter(meta)
# Additional tag from folder
folder_tag = source.replace("wiki-", "")
if folder_tag not in tags:
tags.append(folder_tag)
# Title from frontmatter or filename
title = meta.get("title", path.stem)
# Text for embedding: title + body (without frontmatter)
embed_text = f"{title}\n\n{body}"[:MAX_TEXT_LEN]
batch.append({
"idx": idx,
"path": str(path),
"title": title,
"source": source,
"tags": tags,
"embed_text": embed_text,
"meta": meta,
})
if len(batch) >= BATCH_SIZE or idx == total:
# Generate embeddings in parallel
embed_tasks = [get_embedding(session, b["embed_text"]) for b in batch]
vectors = await asyncio.gather(*embed_tasks)
# Prepare Qdrant points
points = []
for b, vec in zip(batch, vectors):
if vec is None:
stats["fail"] += 1
errors.append(f"Embedding failed: {b['path']}")
continue
# Heuristic importance_score based on path/name
importance_score = 0.5
path_str_lower = b["path"].lower()
if any(k in path_str_lower for k in ["architecture", "core", "important"]):
importance_score = 0.7
if any(t.lower() in ["important", "critical"] for t in b["tags"]):
importance_score = 0.8
if any(k in path_str_lower for k in ["draft", "temp", "old"]):
importance_score = 0.2
now_iso = datetime.now(timezone.utc).isoformat()
point = {
"id": str(uuid.uuid4()),
"vector": {"dense": vec},
"payload": {
"text": b["embed_text"],
"source": b["source"],
"tags": b["tags"],
"created_at": now_iso,
"reflection_count": 0,
"last_reflected": None,
"file_path": b["path"],
"title": b["title"],
"word_count": len(b["embed_text"].split()),
# ── Lineage fields (Phase 1)
"lineage_id": None,
"generation_model": None,
"generation_context_hash": None,
"retrieved_chunk_ids": None,
# ── Decay fields (Phase 2)
"decay_score": 1.0,
"last_accessed_at": now_iso,
"importance_score": importance_score,
"source_type": "human",
"confidence_score": 1.0,
"archived": False,
},
}
points.append(point)
# Upsert
if points:
ok = await upsert_to_qdrant(session, points)
if ok:
stats["ok"] += len(points)
else:
stats["fail"] += len(points)
for p in points:
errors.append(f"Qdrant upsert failed: {p['payload']['file_path']}")
processed += len(batch)
batch = []
# Progress
pct = (processed / total) * 100
print(f" [{processed}/{total}] {pct:.1f}% | ✅ {stats['ok']} | ⚠️ {stats['fail']} | ⏭️ {stats['skip']} | 🈳 {stats['empty']}")
# Rate limit breathing
await asyncio.sleep(RATE_LIMIT_SLEEP)
# ─── Final report ───────────────────────────────────────────────────
print("\n" + "=" * 60)
print("📊 INGESTION REPORT")
print("=" * 60)
print(f" Total files: {total}")
print(f" Ingested (ok): {stats['ok']}")
print(f" Failures: {stats['fail']}")
print(f" Empty: {stats['empty']}")
print(f" Success rate: {(stats['ok']/max(total-stats['empty'],1)*100):.1f}%")
print(f"\n ⏱️ Finished: {datetime.now(timezone.utc).isoformat()}")
if errors:
print(f"\n ⚠️ First errors ({min(10, len(errors))} of {len(errors)}):")
for e in errors[:10]:
print(f" - {e}")
# Verify final count
async with aiohttp.ClientSession() as s:
async with s.get(f"{QDRANT_URL}/collections/{COLLECTION}") as r:
data = await r.json()
final_count = data.get("result", {}).get("points_count", "?")
print(f"\n 📦 Points in collection: {final_count}")
print("\n✅ Bulk ingest complete.")
return stats
if __name__ == "__main__":
stats = asyncio.run(main())
sys.exit(0 if stats["fail"] == 0 else 1)
+715
View File
@@ -0,0 +1,715 @@
#!/usr/bin/env python3
"""
Context Enhancer — HYBRID search (semantic + BM25) on knowledge_base_hybrid
for prompt enrichment.
Runs as a synchronous function (fast, <1s) before each Hermes response.
If Qdrant is offline or embedding fails, returns "" (fail-open).
Usage:
python3 context_enhancer.py "your query here"
python3 context_enhancer.py --top-k 5 --threshold 0.50 "deploy docker"
python3 context_enhancer.py --hybrid-off "your query here" # forces dense-only
"""
import os
import sys
import json
import uuid
import hashlib
import sqlite3
import subprocess
import requests
import argparse
import re
import glob
from typing import List, Dict, Optional, Tuple
from pathlib import Path
import time
from datetime import datetime, timezone
# ─── Config ────────────────────────────────────────────────────────────────
OPENROUTER_KEY = os.environ.get("OPENROUTER_API_KEY")
if not OPENROUTER_KEY:
env_path = Path.home() / ".env"
if env_path.exists():
for line in env_path.read_text().splitlines():
if line.startswith("OPENROUTER_API_KEY="):
OPENROUTER_KEY = line.split("=", 1)[1].strip().strip('"')
break
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base")
EMBEDDING_MODEL = "qwen/qwen3-embedding-8b"
TOP_K_DEFAULT = 3
SCORE_THRESHOLD_DEFAULT = 0.55
MAX_TEXT_LEN = 8000
REQUEST_TIMEOUT = 10
# FastEmbed BM25 config
FASTEMBED_VENV = os.environ.get("FASTEMBED_VENV", "")
# Default: use current Python if venv not configured
_FASTEMBED_PYTHON = FASTEMBED_VENV if FASTEMBED_VENV else sys.executable
_FASTEMBED_SITEPKGS = os.environ.get(
"FASTEMBED_SITEPKGS",
os.path.join(os.path.dirname(sys.executable), "../lib/python3.12/site-packages")
)
BM25_MODEL = "Qdrant/bm25"
# Lineage config
LINEAGE_DB = os.environ.get(
"STATE_DB_PATH",
os.path.expanduser("~/.hermes/state.db")
)
# Telemetry config
TELEMETRY_LOG = os.environ.get(
"TELEMETRY_LOG_PATH",
os.path.expanduser("~/.hermes/logs/query-telemetry.jsonl")
)
TELEMETRY_MAX_BYTES = 10 * 1024 * 1024 # 10MB rotation
# ─── Lineage Registration ───────────────────────────────────────────────────
def register_lineage(
session_id: str,
query: str,
retrieved_chunk_ids: List[str],
generation_context_hash: str,
generation_model: str = "unknown",
) -> Optional[str]:
"""
Register generation provenance in the lineage DB.
Fail-open: if it fails, log error and return None. Never breaks the critical path.
"""
lineage_id = str(uuid.uuid4())
try:
with sqlite3.connect(LINEAGE_DB) as conn:
conn.execute(
"""
INSERT INTO lineage (lineage_id, session_id, query, retrieved_chunk_ids,
generation_model, generation_context_hash, created_at)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
""",
(lineage_id, session_id, query,
json.dumps(retrieved_chunk_ids, ensure_ascii=False),
generation_model, generation_context_hash)
)
conn.commit()
return lineage_id
except Exception as e:
print(f"[LINEAGE-WARNING] Failed to register lineage: {e}", file=sys.stderr)
return None
# ─── Telemetry ─────────────────────────────────────────────────────────────
def _rotate_telemetry_if_needed() -> None:
"""Rotate telemetry file if >10MB. Rename to .1 and restart."""
try:
if os.path.exists(TELEMETRY_LOG) and os.path.getsize(TELEMETRY_LOG) > TELEMETRY_MAX_BYTES:
rotated = TELEMETRY_LOG + ".1"
if os.path.exists(rotated):
os.remove(rotated)
os.rename(TELEMETRY_LOG, rotated)
except Exception as e:
print(f"[TELEMETRY-WARNING] Rotation failed: {e}", file=sys.stderr)
def emit_telemetry(record: dict) -> None:
"""
Append-only JSONL for query telemetry.
Fail-open: never breaks the critical path.
"""
try:
os.makedirs(os.path.dirname(TELEMETRY_LOG), exist_ok=True)
_rotate_telemetry_if_needed()
with open(TELEMETRY_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
except Exception as e:
print(f"[TELEMETRY-WARNING] Failed to write telemetry: {e}", file=sys.stderr)
def estimate_tokens(text: str) -> int:
"""Simple estimate: ~1.3 tokens per word (basic heuristic)."""
return int(len(text.split()) * 1.3)
# ─── Core ───────────────────────────────────────────────────────────────────
def embed_query(text: str) -> Optional[List[float]]:
"""Generate dense embedding via OpenRouter qwen/qwen3-embedding-8b."""
if not OPENROUTER_KEY:
return None
try:
resp = requests.post(
"https://openrouter.ai/api/v1/embeddings",
headers={
"Authorization": f"Bearer {OPENROUTER_KEY}",
"Content-Type": "application/json"
},
json={
"model": EMBEDDING_MODEL,
"input": text[:MAX_TEXT_LEN]
},
timeout=REQUEST_TIMEOUT
)
resp.raise_for_status()
return resp.json()["data"][0]["embedding"]
except Exception as e:
# Fail-open: log silently, return None
print(f"[CE-ERROR] Embedding dense failed: {e}", file=sys.stderr)
return None
def embed_query_sparse(text: str) -> Optional[Tuple[List[int], List[float]]]:
"""
Generate sparse BM25 embedding via FastEmbed (subprocess in ai-lab venv).
Fail-open: if it fails, return None. Caller falls back to dense-only.
"""
try:
# Shell-quote the text to prevent injection in Python -c
import shlex
safe_text = shlex.quote(text)
result = subprocess.run(
[_FASTEMBED_PYTHON, "-c", f"""\
import os, sys
sys.path.insert(0, os.environ["FASTEMBED_SITEPKGS"])
from fastembed.sparse import SparseTextEmbedding
import json
model = SparseTextEmbedding(model_name=\\"{BM25_MODEL}\\")
sparse = list(model.embed({safe_text}))[0]
print(json.dumps({{\\"indices\\": sparse.indices.tolist(), \\"values\\": sparse.values.tolist()}}))
"""],
capture_output=True, text=True, timeout=15
)
data = json.loads(result.stdout.strip())
return data["indices"], data["values"]
except Exception as e:
print(f"[CE-ERROR] Embedding sparse failed: {e}", file=sys.stderr)
return None
def search_knowledge_base(
dense_vector: List[float],
sparse_vector: Optional[Tuple[List[int], List[float]]] = None,
top_k: int = TOP_K_DEFAULT,
score_threshold: float = SCORE_THRESHOLD_DEFAULT
) -> List[Dict]:
"""
Hybrid search in Qdrant: dense (semantic) + sparse (BM25 keyword)
via prefetch + RRF. If sparse fails, fall back to dense-only.
"""
try:
if sparse_vector is not None:
# Hybrid: prefetch dense + prefetch sparse → RRF
resp = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/query",
headers={"Content-Type": "application/json"},
json={
"prefetch": [
{"query": dense_vector, "using": "dense", "limit": top_k * 3},
{"query": {"indices": sparse_vector[0], "values": sparse_vector[1]},
"using": "sparse", "limit": top_k * 3},
],
"query": {"fusion": "rrf"},
"limit": top_k * 2,
"with_payload": True,
},
timeout=REQUEST_TIMEOUT + 5,
)
else:
# Fallback: dense-only (collections with compatible named vectors)
resp = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/query",
headers={"Content-Type": "application/json"},
json={
"query": dense_vector,
"using": "dense",
"limit": top_k,
"with_payload": True,
},
timeout=REQUEST_TIMEOUT,
)
resp.raise_for_status()
data = resp.json()
results = []
raw_results = data.get("result", {})
# API /points/search returns direct list; API /points/query returns {"points": [...]}
points = raw_results if isinstance(raw_results, list) else raw_results.get("points", [])
for r in points:
score = r.get("score", 0)
if score < score_threshold:
continue
payload = r.get("payload", {})
results.append({
"id": r.get("id", "unknown"),
"score": score,
"title": payload.get("title", "Untitled"),
"content_preview": (payload.get("text", "") or "")[:400],
"source": payload.get("source", "unknown"),
"tags": payload.get("tags", [])
})
return results
except Exception as e:
print(f"[CE-ERROR] Qdrant search failed: {e}", file=sys.stderr)
return []
# ─── Fallback: Lexical Search in Vault ──────────────────────────────────────
def tokenize_query(text: str) -> List[str]:
"""Tokenize query into relevant terms (lowercase, alphanumeric)."""
# Remove basic Portuguese/English stopwords
stopwords = {"o", "a", "os", "as", "um", "uma", "de", "da", "do", "em", "no", "na", "para", "com", "por", "que", "se", "e", "ou", "mas", "the", "a", "an", "is", "are", "was", "were", "be", "been", "have", "has", "had", "do", "does", "did", "will", "would", "could", "should"}
tokens = re.findall(r'\b[a-zA-Z0-9]+\b', text.lower())
return [t for t in tokens if t not in stopwords and len(t) > 2]
def lexical_search_in_vault(
query_terms: List[str],
top_k: int = TOP_K_DEFAULT,
vault_root: str = os.environ.get("WIKI_PATH", os.path.expanduser("~/vault/wiki"))
) -> List[Dict]:
"""
Lexical search in .md files under vault/wiki/.
Rank by term match density / document size.
Return top-k simulated chunks (or entire file if small).
"""
if not query_terms:
return []
md_files = glob.glob(f"{vault_root}/**/*.md", recursive=True)
if not md_files:
return []
scored = []
for filepath in md_files:
try:
text = Path(filepath).read_text(encoding="utf-8", errors="replace").lower()
if not text:
continue
matches = 0
for term in query_terms:
matches += text.count(term)
if matches == 0:
continue
# Heuristic: matches / sqrt(word_count) — favors concise documents
word_count = max(1, len(text.split()))
density = matches / (word_count ** 0.5) # sqrt(word_count) to not over-penalize medium texts
scored.append({
"filepath": filepath,
"matches": matches,
"word_count": word_count,
"density": density,
"title": Path(filepath).stem,
"text": text[:2000], # truncate for return
})
except Exception:
continue
if not scored:
return []
# Sort by descending density
scored.sort(key=lambda x: x["density"], reverse=True)
results = []
for i, item in enumerate(scored[:top_k]):
# Simulate a result chunk
results.append({
"id": f"lexical-{hashlib.md5(item['filepath'].encode()).hexdigest()[:16]}",
"score": round(min(1.0, item["density"]), 2),
"title": item["title"],
"content_preview": item["text"][:400],
"source": f"vault-{item['filepath'].replace(vault_root, '').lstrip('/')[:40]}",
"tags": ["fallback", "lexical"],
"fallback_level": "lexical",
})
if results:
print(f"[CE-FALLBACK] Lexical search returned {len(results)} results from vault", file=sys.stderr)
return results
# ─── Fallback: SQLite Keyword Search ────────────────────────────────────────
def sqlite_keyword_search(
query_terms: List[str],
top_k: int = TOP_K_DEFAULT
) -> List[Dict]:
"""
Search terms in the lineage table (query field) and other state tables.
Last resort — does not replace vault.
"""
if not query_terms:
return []
try:
with sqlite3.connect(LINEAGE_DB) as conn:
conn.row_factory = sqlite3.Row
c = conn.cursor()
results = []
# Search in lineage.query
placeholders = " OR ".join(["query LIKE ?"] * len(query_terms))
params = [f"%{term}%" for term in query_terms]
c.execute(
f"""
SELECT lineage_id, session_id, query, generation_context_hash, created_at
FROM lineage
WHERE {placeholders}
ORDER BY created_at DESC
LIMIT ?
""",
params + [top_k * 2]
)
for row in c.fetchall():
results.append({
"id": f"sqlite-{row['lineage_id'][:16]}",
"score": 0.5,
"title": f"Lineage {row['lineage_id'][:8]}...",
"content_preview": (row["query"] or "")[:400],
"source": f"sqlite-history-{row['session_id']}",
"tags": ["fallback", "sqlite"],
"fallback_level": "sqlite",
})
if results:
print(f"[CE-FALLBACK] SQLite keyword search returned {len(results)} results", file=sys.stderr)
return results[:top_k]
except Exception as e:
print(f"[CE-FALLBACK] SQLite search failed: {e}", file=sys.stderr)
return []
# ─── Fallback Wrapper ──────────────────────────────────────────────────────
def search_with_fallback(
dense_vector: Optional[List[float]] = None,
sparse_vector: Optional[Tuple[List[int], List[float]]] = None,
query_text: str = "",
top_k: int = TOP_K_DEFAULT,
score_threshold: float = SCORE_THRESHOLD_DEFAULT
) -> Tuple[List[Dict], str, float, float]:
"""
4-level fallback cascade:
1. Hybrid (dense + sparse + RRF) — normal mode
2. Dense-only — if sparse fails or is None
3. Lexical-only — if Qdrant goes down (ConnectionError, Timeout)
4. SQLite keyword — if vault is inaccessible
Returns (results, fallback_level, qdrant_latency_ms, fallback_latency_ms).
"""
fallback_level = "hybrid"
qdrant_latency_ms = 0.0
t0 = time.perf_counter()
# Level 1 or 2: Qdrant (hybrid if sparse available, otherwise dense-only)
try:
t_q0 = time.perf_counter()
if sparse_vector is not None:
resp = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/query",
headers={"Content-Type": "application/json"},
json={
"prefetch": [
{"query": dense_vector, "using": "dense", "limit": top_k * 3},
{"query": {"indices": sparse_vector[0], "values": sparse_vector[1]},
"using": "sparse", "limit": top_k * 3},
],
"query": {"fusion": "rrf"},
"limit": top_k * 2,
"with_payload": True,
},
timeout=REQUEST_TIMEOUT + 5,
)
fallback_level = "hybrid"
else:
resp = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/query",
headers={"Content-Type": "application/json"},
json={
"query": dense_vector,
"using": "dense",
"limit": top_k,
"with_payload": True,
},
timeout=REQUEST_TIMEOUT,
)
fallback_level = "dense-only"
resp.raise_for_status()
qdrant_latency_ms = (time.perf_counter() - t_q0) * 1000
data = resp.json()
results = []
raw_results = data.get("result", {})
points = raw_results if isinstance(raw_results, list) else raw_results.get("points", [])
for r in points:
score = r.get("score", 0)
if score < score_threshold:
continue
payload = r.get("payload", {})
results.append({
"id": r.get("id", "unknown"),
"score": score,
"title": payload.get("title", "Untitled"),
"content_preview": (payload.get("text", "") or "")[:400],
"source": payload.get("source", "unknown"),
"tags": payload.get("tags", [])
})
if results:
fallback_latency_ms = (time.perf_counter() - t0) * 1000
return results, fallback_level, qdrant_latency_ms, fallback_latency_ms
except requests.exceptions.ConnectionError:
print("[CE-FALLBACK] Qdrant unavailable (ConnectionError), falling back to lexical search.", file=sys.stderr)
except requests.exceptions.Timeout:
print("[CE-FALLBACK] Qdrant timeout, falling back to lexical search.", file=sys.stderr)
except Exception as e:
# Unexpected Qdrant error (e.g. SparseIndexError, 5xx, etc.)
# If sparse_vector existed, it might be a sparse error — try dense-only
if sparse_vector is not None and "sparse" in str(e).lower():
print(f"[CE-FALLBACK] Sparse index failed ('{e}'), trying dense-only...", file=sys.stderr)
try:
t_q2 = time.perf_counter()
resp = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/search",
headers={"Content-Type": "application/json"},
json={
"vector": dense_vector,
"using": "dense",
"limit": top_k,
"with_payload": True,
},
timeout=REQUEST_TIMEOUT,
)
resp.raise_for_status()
qdrant_latency_ms = (time.perf_counter() - t_q2) * 1000
data = resp.json()
results = []
raw_results = data.get("result", {})
points = raw_results if isinstance(raw_results, list) else raw_results.get("points", [])
for r in points:
score = r.get("score", 0)
if score < score_threshold:
continue
payload = r.get("payload", {})
results.append({
"id": r.get("id", "unknown"),
"score": score,
"title": payload.get("title", "Untitled"),
"content_preview": (payload.get("text", "") or "")[:400],
"source": payload.get("source", "unknown"),
"tags": payload.get("tags", [])
})
if results:
fallback_latency_ms = (time.perf_counter() - t0) * 1000
print("[CE-FALLBACK] Dense-only worked after sparse error.", file=sys.stderr)
return results, "dense-only", qdrant_latency_ms, fallback_latency_ms
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
print("[CE-FALLBACK] Qdrant also unavailable for dense-only — lexical fallback.", file=sys.stderr)
except Exception as e2:
print(f"[CE-FALLBACK] Dense-only also failed: {e2}", file=sys.stderr)
else:
print(f"[CE-FALLBACK] Qdrant general error ({e}), falling back to lexical.", file=sys.stderr)
# Level 3: Lexical search in vault
terms = tokenize_query(query_text)
lexical_results = lexical_search_in_vault(terms, top_k=top_k)
if lexical_results:
fallback_latency_ms = (time.perf_counter() - t0) * 1000
return lexical_results, "lexical", qdrant_latency_ms, fallback_latency_ms
# Level 4: SQLite keyword search
sqlite_results = sqlite_keyword_search(terms, top_k=top_k)
if sqlite_results:
fallback_latency_ms = (time.perf_counter() - t0) * 1000
return sqlite_results, "sqlite", qdrant_latency_ms, fallback_latency_ms
# Nothing worked
fallback_latency_ms = (time.perf_counter() - t0) * 1000
print("[CE-FALLBACK] All fallback levels exhausted.", file=sys.stderr)
return [], "none", qdrant_latency_ms, fallback_latency_ms
def update_last_accessed_at(chunk_ids: list) -> None:
"""
Update last_accessed_at on chunks returned by search.
Reset decay for chunks that are actually being used.
Fail-open: never breaks the critical query path.
"""
if not chunk_ids:
return
try:
now = datetime.now().astimezone().isoformat()
requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/payload",
headers={"Content-Type": "application/json"},
json={
"points": chunk_ids,
"payload": {"last_accessed_at": now},
},
timeout=5,
)
except Exception as e:
print(f"[CE-WARNING] Failed to update last_accessed_at: {e}", file=sys.stderr)
def enhance_prompt(
user_message: str,
top_k: int = TOP_K_DEFAULT,
score_threshold: float = SCORE_THRESHOLD_DEFAULT,
format_mode: str = "markdown",
hybrid: bool = True,
session_id: Optional[str] = None,
generation_model: str = "unknown",
) -> str:
"""
Return a context block with relevant vault content (hybrid dense+BM25),
or an empty string if nothing relevant found / services offline.
Register lineage with chunk provenance and generated context hash.
"""
# Resolve session_id
if session_id is None:
session_id = os.environ.get("HERMES_SESSION_ID", "standalone")
# Skip very short or irrelevant queries
if len(user_message.strip()) < 5:
return ""
# Very short or social query — skip
social_keywords = {"hi", "hello", "hey", "yo", "sup", "ok", "thanks", "bye", "okay", "great"}
if user_message.strip().lower() in social_keywords:
return ""
dense_vector = embed_query(user_message)
sparse_vector = None
if hybrid:
sparse_vector = embed_query_sparse(user_message)
# Fallback cascade: hybrid → dense-only → lexical → sqlite
hits, fallback_level, qdrant_latency_ms, fallback_latency_ms = search_with_fallback(
dense_vector=dense_vector,
sparse_vector=sparse_vector,
query_text=user_message,
top_k=top_k,
score_threshold=score_threshold
)
# If empty and we had no embedding, try pure lexical
if not hits and dense_vector is None:
terms = tokenize_query(user_message)
lexical_results = lexical_search_in_vault(terms, top_k=top_k)
if lexical_results:
hits = lexical_results
fallback_level = "lexical"
if not hits:
# Emit telemetry even when empty (records that search ran and returned nothing)
emit_telemetry({
"timestamp": datetime.now(timezone.utc).isoformat(),
"session_id": session_id,
"query": user_message,
"retrieval_mode": fallback_level,
"retrieved_chunk_ids": [],
"semantic_scores": [],
"rerank_scores": [],
"final_context_tokens": 0,
"fallback_level": {"hybrid": 0, "dense-only": 1, "lexical": 2, "sqlite": 3, "none": -1}.get(fallback_level, -1),
"llm_response_quality": None,
"qdrant_latency_ms": round(qdrant_latency_ms, 2),
"fallback_latency_ms": round(fallback_latency_ms, 2),
})
return ""
# Update last_accessed_at for returned chunks (reset decay on real usage)
retrieved_chunk_ids = [h["id"] for h in hits]
update_last_accessed_at(retrieved_chunk_ids)
if format_mode == "markdown":
lines = ["\n## Relevant Context from Vault\n"]
for i, h in enumerate(hits, 1):
lines.append(f"### [{i}] {h['title']} (score: {h['score']:.2f})")
lines.append(f"- **Source:** `{h['source']}` | Tags: {', '.join(str(t) for t in h['tags'])}")
lines.append(f"- **Excerpt:** {h['content_preview']}...")
lines.append("")
context_str = "\n".join(lines)
elif format_mode == "compact":
parts = []
for h in hits:
parts.append(f"[{h['title'][:40]}] (s:{h['score']:.2f})")
context_str = "\n".join(parts)
else:
context_str = json.dumps(hits, indent=2, ensure_ascii=False)
generation_context_hash = hashlib.sha256(context_str.encode("utf-8")).hexdigest()[:32]
register_lineage(
session_id=session_id,
query=user_message,
retrieved_chunk_ids=retrieved_chunk_ids,
generation_context_hash=generation_context_hash,
generation_model=generation_model,
)
# Extract scores for telemetry
semantic_scores = [h.get("score", 0) for h in hits]
# For rerank_scores, use the same scores (internal Qdrant RRF, not exposed via simple API)
rerank_scores = semantic_scores[:]
final_context_tokens = estimate_tokens(context_str)
emit_telemetry({
"timestamp": datetime.now(timezone.utc).isoformat(),
"session_id": session_id,
"query": user_message,
"retrieval_mode": fallback_level,
"retrieved_chunk_ids": retrieved_chunk_ids,
"semantic_scores": semantic_scores,
"rerank_scores": rerank_scores,
"final_context_tokens": final_context_tokens,
"fallback_level": {"hybrid": 0, "dense-only": 1, "lexical": 2, "sqlite": 3, "none": -1}.get(fallback_level, -1),
"llm_response_quality": None,
"qdrant_latency_ms": round(qdrant_latency_ms, 2),
"fallback_latency_ms": round(fallback_latency_ms, 2),
})
return context_str
def main():
parser = argparse.ArgumentParser(description="Context Enhancer — Hybrid search in knowledge_base")
parser.add_argument("query", nargs="?", help="User message/query")
parser.add_argument("--top-k", type=int, default=TOP_K_DEFAULT, help=f"Number of results (default: {TOP_K_DEFAULT})")
parser.add_argument("--threshold", type=float, default=SCORE_THRESHOLD_DEFAULT, help=f"Minimum score (default: {SCORE_THRESHOLD_DEFAULT})")
parser.add_argument("--format", choices=["markdown", "compact", "json"], default="markdown", help="Output format")
parser.add_argument("--silent", action="store_true", help="Silent — return empty on error")
parser.add_argument("--hybrid-off", action="store_true", help="Force dense-only (ignore BM25)")
args = parser.parse_args()
if not args.query:
args.query = sys.stdin.read().strip() or "how ARQ worker works"
try:
result = enhance_prompt(
args.query,
top_k=args.top_k,
score_threshold=args.threshold,
format_mode=args.format,
hybrid=not args.hybrid_off,
generation_model=os.environ.get("HERMES_MODEL", "unknown"),
)
print(result)
except Exception as e:
if not args.silent:
print(f"[CE-ERROR] {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""
decay_scanner.py
Selective archiving script for low-importance AI-generated chunks.
Runs via weekly cron (0 3 * * 0).
Rules:
- source_type in ["human", "procedural"] → exempt (never archive)
- importance_score >= 0.7 → exempt
- archived == True → skip (already archived)
- half_life: 90d if importance_score >= 0.3, else 30d
- decay_score < 0.1:
- If confidence_score >= 0.7 → alert (report, don't archive)
- Otherwise → archive (archived = True)
- gabi_* collections are completely ignored
Usage:
python3 decay_scanner.py [--collection knowledge_base_hybrid] [--dry-run]
"""
import os
import sys
import json
import math
import argparse
import requests
from datetime import datetime, timezone
from pathlib import Path
# ─── Config ────────────────────────────────────────────────────────────────
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base")
SCROLL_LIMIT = 100 # Qdrant pagination
LOG_DIR = Path(os.environ.get("HERMES_LOGS_DIR", str(Path.home() / ".hermes" / "logs")))
LOG_FILE = LOG_DIR / "decay_scanner.log"
# ─── Helpers ──────────────────────────────────────────────────────────────
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def calculate_decay_score(last_accessed_at: str, importance_score: float) -> float:
"""
Calculate exponential decay: score = exp(-ln(2) * age_days / half_life).
More important chunks persist longer (larger half-lives).
"""
try:
last = datetime.fromisoformat(last_accessed_at.replace("Z", "+00:00"))
except (ValueError, TypeError):
# If timestamp is invalid, assume now (hasn't decayed yet)
return 1.0
now = datetime.now(timezone.utc)
age_days = max(0, (now - last).total_seconds() / 86400)
# Fix: LARGER half-life for more important chunks
if importance_score >= 0.3:
half_life = 90 # medium/high chunks → 90 days
else:
half_life = 30 # low chunks → 30 days
decay_score = math.exp(-math.log(2) * age_days / half_life)
return decay_score
def ensure_log_dir():
"""Create log directory if it doesn't exist."""
LOG_DIR.mkdir(parents=True, exist_ok=True)
def log_message(msg: str):
"""Log to stdout and append to log file."""
ts = now_iso()
line = f"[{ts}] {msg}"
print(line)
ensure_log_dir()
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
# ─── Qdrant Operations ────────────────────────────────────────────────────
def scroll_chunks(collection: str, limit: int = SCROLL_LIMIT):
"""
Generator that iterates over all points in the collection via scroll.
Avoids loading the entire collection into memory.
"""
offset = None
total_scanned = 0
while True:
payload = {
"limit": limit,
"with_payload": True,
"with_vector": False,
}
if offset is not None:
payload["offset"] = offset
try:
resp = requests.post(
f"{QDRANT_URL}/collections/{collection}/points/scroll",
headers={"Content-Type": "application/json"},
json=payload,
timeout=30,
)
resp.raise_for_status()
data = resp.json()
result = data.get("result", {})
points = result.get("points", [])
if not points:
break
for point in points:
yield point
total_scanned += 1
offset = result.get("next_page_offset")
if offset is None:
break
except Exception as e:
log_message(f"❌ Qdrant scroll error: {e}")
break
log_message(f"📊 Total chunks scanned: {total_scanned}")
def update_point_archived(point_id: str, collection: str, decay_score: float, dry_run: bool = False):
"""Update point payload: archived=True + calculated decay_score."""
if dry_run:
log_message(f" [DRY-RUN] Would archive point {point_id} (decay_score={decay_score:.4f})")
return True
try:
resp = requests.post(
f"{QDRANT_URL}/collections/{collection}/points/payload",
headers={"Content-Type": "application/json"},
json={
"points": [point_id],
"payload": {
"archived": True,
"decay_score": decay_score,
},
},
timeout=10,
)
resp.raise_for_status()
return True
except Exception as e:
log_message(f" ❌ Failed to archive point {point_id}: {e}")
return False
# ─── Main ─────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Decay Scanner — Selective chunk archiving")
parser.add_argument("--collection", default=COLLECTION, help="Qdrant collection name")
parser.add_argument("--dry-run", action="store_true", help="Simulation — does not modify anything")
parser.add_argument("--threshold", type=float, default=0.1, help="Decay threshold for archiving")
args = parser.parse_args()
collection = args.collection
# Ignore gabi_* collections
if collection.startswith("gabi_"):
log_message(f"⏭️ Collection '{collection}' is exempt (gabi_*). Exiting.")
return
log_message(f"🚀 Starting decay scanner (collection={collection}, threshold={args.threshold}, dry_run={args.dry_run})")
# Metrics
stats = {
"scanned": 0,
"archived": 0,
"alerted": 0,
"skipped_human": 0,
"skipped_procedural": 0,
"skipped_high_importance": 0,
"skipped_already_archived": 0,
"failed": 0,
}
alerts = [] # List of alerts (decay < threshold but confidence >= 0.7)
for point in scroll_chunks(collection):
stats["scanned"] += 1
point_id = point.get("id")
payload = point.get("payload", {})
source_type = payload.get("source_type", "unknown")
importance_score = payload.get("importance_score", 0.5)
archived = payload.get("archived", False)
last_accessed_at = payload.get("last_accessed_at", payload.get("created_at", now_iso()))
confidence_score = payload.get("confidence_score", 1.0)
# Skip: already archived
if archived:
stats["skipped_already_archived"] += 1
continue
# Skip: human (exempt)
if source_type == "human":
stats["skipped_human"] += 1
continue
# Skip: procedural (exempt)
if source_type == "procedural":
stats["skipped_procedural"] += 1
continue
# Skip: high importance
if importance_score >= 0.7:
stats["skipped_high_importance"] += 1
continue
# Calculate decay
decay_score = calculate_decay_score(last_accessed_at, importance_score)
# Check threshold
if decay_score < args.threshold:
# Decay-confidence rule: if confidence is high, alert instead of archiving
if confidence_score >= 0.7:
stats["alerted"] += 1
alerts.append({
"point_id": point_id,
"decay_score": round(decay_score, 4),
"confidence_score": round(confidence_score, 2),
"importance_score": round(importance_score, 2),
"age_days": round((datetime.now(timezone.utc) - datetime.fromisoformat(last_accessed_at.replace("Z", "+00:00"))).total_seconds() / 86400, 1),
"reason": "decay < threshold but confidence >= 0.7 — manual review recommended",
})
log_message(f" ⚠️ ALERT: point {point_id} (decay={decay_score:.4f}, confidence={confidence_score:.2f}) — manual review recommended")
else:
# Archive
ok = update_point_archived(point_id, collection, decay_score, args.dry_run)
if ok:
stats["archived"] += 1
log_message(f" 📦 Archived: point {point_id} (decay={decay_score:.4f}, importance={importance_score:.2f})")
else:
stats["failed"] += 1
# Structured JSON report
report = {
"timestamp": now_iso(),
"collection": collection,
"threshold": args.threshold,
"dry_run": args.dry_run,
"scanned": stats["scanned"],
"archived": stats["archived"],
"alerted": stats["alerted"],
"skipped_human": stats["skipped_human"],
"skipped_procedural": stats["skipped_procedural"],
"skipped_high_importance": stats["skipped_high_importance"],
"skipped_already_archived": stats["skipped_already_archived"],
"failed": stats["failed"],
"alerts": alerts,
}
log_message("=" * 60)
log_message("📊 DECAY SCANNER REPORT")
log_message("=" * 60)
log_message(f" Scanned: {stats['scanned']}")
log_message(f" Archived: {stats['archived']}")
log_message(f" Alerts (decay+conf.): {stats['alerted']}")
log_message(f" Skipped human: {stats['skipped_human']}")
log_message(f" Skipped procedural: {stats['skipped_procedural']}")
log_message(f" Skipped high imp.: {stats['skipped_high_importance']}")
log_message(f" Skipped archived: {stats['skipped_already_archived']}")
log_message(f" Failures: {stats['failed']}")
log_message("=" * 60)
# JSON report to stderr (parseable)
print(json.dumps(report, ensure_ascii=False, indent=2), file=sys.stderr)
log_message("✅ Decay scanner complete.")
if __name__ == "__main__":
main()
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""
DLQ Manager — Reads, classifies, reports, and marks wiki ingest failures.
Usage:
python3 dlq_manager.py --report # report unreported failures
python3 dlq_manager.py --status # DLQ status summary
python3 dlq_manager.py --json # full JSON output
"""
import os
import sys
import json
import time
from datetime import datetime, timedelta
from typing import List, Dict, Optional
from dataclasses import dataclass, asdict, field
from collections import Counter
# ─── Config ────────────────────────────────────────────────────────────────
DLQ_PATH = os.environ.get("HERMES_DLQ_PATH", os.path.expanduser("~/.hermes/wiki_ingest_failures.json"))
REPORT_LOG = os.environ.get("HERMES_DLQ_REPORT_LOG", os.path.expanduser("~/.hermes/cron/output/dlq_reports.jsonl"))
REPORT_DIR = os.environ.get("HERMES_DLQ_REPORT_DIR", os.path.expanduser("~/.hermes/cron/output/quality_report"))
MAX_REPORT_HISTORY = 100 # entries in JSONL
# ─── Data Model ─────────────────────────────────────────────────────────────
@dataclass
class DLQEntry:
file: str
error: str
timestamp: str
failure_class: str = "unknown"
reported: bool = False
retry_count: int = 0
last_retry: Optional[str] = None
error_hash: str = "" # error hash for deduplication
# ─── File I/O ─────────────────────────────────────────────────────────────
def load_dlq() -> List[DLQEntry]:
if not os.path.exists(DLQ_PATH):
return []
try:
with open(DLQ_PATH, "r") as f:
data = json.load(f)
if isinstance(data, list):
return [DLQEntry(**item) for item in data]
elif isinstance(data, dict) and "failures" in data:
return [DLQEntry(**item) for item in data["failures"]]
return []
except Exception as e:
print(f"[DLQ-ERROR] Failed to load: {e}", file=sys.stderr)
return []
def save_dlq(entries: List[DLQEntry]):
tmp = DLQ_PATH + ".tmp"
with open(tmp, "w") as f:
json.dump([asdict(e) for e in entries], f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, DLQ_PATH)
# ─── Classification ─────────────────────────────────────────────────────────
def classify_error(error_msg: str) -> str:
e = error_msg.lower()
transient = ["timeout", "connection", "temporarily", "rate limit", "503", "502", "504",
"too many requests", "unavailable", "cannot", "refused", "reset"]
permanent = ["404", "not found", "invalid format", "parse error", "file not found",
"deleted", "permission denied", "encode", "utf-8", "json", "schema"]
for p in transient:
if p in e:
return "transient"
for p in permanent:
if p in e:
return "permanent"
return "unknown"
def compute_error_hash(file: str, error: str) -> str:
"""Generate a simple hash for deduplication of similar errors."""
import hashlib
return hashlib.md5(f"{file}:{error[:80]}".encode()).hexdigest()[:8]
# ─── Reporting ─────────────────────────────────────────────────────────────
def build_report(entries: List[DLQEntry]) -> Dict:
unreported = [e for e in entries if not e.reported]
total = len(entries)
if not unreported:
return {"status": "ok", "unreported_count": 0, "total": total, "report": ""}
# Classify
for e in unreported:
if e.failure_class == "unknown":
e.failure_class = classify_error(e.error)
by_class = Counter(e.failure_class for e in unreported)
by_error_short = Counter(str(e.error)[:70] for e in unreported)
by_file = Counter(os.path.basename(e.file) for e in unreported)
lines = [
f"🚨 [DLQ-ALERT] {len(unreported)} new failure(s) in ingest",
f" Total accumulated in DLQ: {total}",
"",
"By class:",
]
emoji = {"transient": "⏳", "permanent": "💀", "unknown": "❓"}
for cls, count in by_class.most_common():
lines.append(f" {emoji.get(cls, '❓')} {cls}: {count}")
lines.append("")
lines.append("Top errors:")
for err, count in by_error_short.most_common(5):
lines.append(f" • ({count}x) {err}")
lines.append("")
lines.append("Files:")
for fname, count in by_file.most_common(10):
lines.append(f" • {fname} ({count}x)")
report_text = "\n".join(lines)
return {
"status": "alert",
"unreported_count": len(unreported),
"total": total,
"by_class": dict(by_class),
"top_errors": dict(by_error_short.most_common(5)),
"report": report_text,
}
def save_report(report: Dict):
os.makedirs(REPORT_DIR, exist_ok=True)
os.makedirs(os.path.dirname(REPORT_LOG), exist_ok=True)
timestamp = datetime.now().isoformat()
# JSONL
with open(REPORT_LOG, "a") as f:
f.write(json.dumps({"timestamp": timestamp, **report}, ensure_ascii=False) + "\n")
f.flush()
os.fsync(f.fileno())
def mark_reported(entries: List[DLQEntry]):
for e in entries:
e.reported = True
def get_status_summary(entries: List[DLQEntry]) -> Dict:
total = len(entries)
unreported = len([e for e in entries if not e.reported])
by_class = Counter(e.failure_class for e in entries)
recent = [e for e in entries if datetime.now(datetime.timezone.utc) - datetime.fromisoformat(e.timestamp.replace("Z", "+00:00")).astimezone(datetime.timezone.utc) < timedelta(hours=24)]
return {
"total": total,
"unreported": unreported,
"by_class": dict(by_class),
"last_24h": len(recent),
"oldest": entries[0].timestamp if entries else None,
}
# ─── Main ───────────────────────────────────────────────────────────────────
def main():
import argparse
p = argparse.ArgumentParser(description="DLQ Manager — Auto-report of failures")
p.add_argument("--report", action="store_true", help="Generate report of unreported failures")
p.add_argument("--status", action="store_true", help="Status summary")
p.add_argument("--json", action="store_true", help="JSON output")
p.add_argument("--silent-if-ok", action="store_true", help="Silent if DLQ is ok")
args = p.parse_args()
entries = load_dlq()
if args.status:
summary = get_status_summary(entries)
if args.json:
print(json.dumps(summary, indent=2, ensure_ascii=False))
else:
print(f"DLQ status: {summary['total']} total, {summary['unreported']} unreported")
for cls, count in summary.get("by_class", {}).items():
print(f" {cls}: {count}")
return
report = build_report(entries)
if report["status"] == "ok":
msg = "[DLQ-OK] No new failures since last check."
if not args.silent_if_ok:
print(msg)
if args.json:
print(json.dumps(report, indent=2, ensure_ascii=False))
return
# Has new failures
if args.json:
print(json.dumps(report, indent=2, ensure_ascii=False))
else:
print(report["report"])
# Save and mark as reported
save_report(report)
mark_reported(entries)
save_dlq(entries)
# Exit code 1 for cron trigger
sys.exit(1)
if __name__ == "__main__":
main()
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""
Semantic Pre-Validator — Decision linter based on the knowledge_base.
Queries the vault before I/O actions or API calls.
Usage:
python3 pre_validator.py "POST to Qdrant upsert" # should find pitfalls
python3 pre_validator.py --json "use Claude from Anthropic" # JSON output
python3 pre_validator.py --domain qdrant,api "modify docker-compose" # restrict search
Exit codes:
0 = pass/warn (action may proceed)
1 = blocked (action must be aborted)
Fail-open: if OpenRouter or Qdrant is offline, allows execution with a warning.
"""
import os
import sys
import json
import re
import requests
from typing import List, Dict, Optional
from pathlib import Path
# ─── Config ────────────────────────────────────────────────────────────────
OPENROUTER_KEY = os.environ.get("OPENROUTER_API_KEY")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base")
if not OPENROUTER_KEY:
_env_path = os.environ.get("ENV_PATH", "")
if _env_path:
_env = Path(_env_path)
else:
_env = Path.home() / ".env"
if _env.exists():
for ln in _env.read_text().splitlines():
if ln.startswith("OPENROUTER_API_KEY="):
OPENROUTER_KEY = ln.split("=", 1)[1].strip().strip('"')
break
EMBEDDING_MODEL = "qwen/qwen3-embedding-8b"
TOP_K = 5
SCORE_THRESHOLD = 0.60
WARN_THRESHOLD = 0.75 # pure wiki docs need a higher score for a warning
BLOCK_SEVERITIES = {"critical", "high"}
WARN_SEVERITIES = {"medium"}
RULE_SOURCES = {"reflection", "decision", "rule", "pitfall", "insight"}
REQUEST_TIMEOUT = 10
# ─── Restriction Patterns in wiki text ─────────────────────────────────────
RESTRICTION_KEYWORDS = [
"do not use", "must not", "cannot", "never use", "avoid",
"forbidden", "not recommended", "anti-pattern", "common mistake",
"caution", "warning", "important:", "⚠️", "🚫",
"must use", "must always", "requires", "mandatory",
"keep", "do not change", "do not modify", "freeze",
]
def contains_restriction(text: str) -> bool:
"""Check whether text contains restriction/decision patterns."""
if not text:
return False
text_lower = text.lower()
return any(kw in text_lower for kw in RESTRICTION_KEYWORDS)
# ─── Domain Tag Inference ─────────────────────────────────────────────────
DOMAIN_PATTERNS = {
"docker" : ["docker", "compose", "container", "image", "dockerfile"],
"qdrant" : ["qdrant", "collection", "points", "upsert", "vector", "vectors", "embedding"],
"redis" : ["redis", "arq", "queue", "job", "worker", "broker"],
"openrouter" : ["openrouter", "embedding", "api_key", "openai", "api_base", "model"],
"hermes" : ["hermes", "config.yaml", "skill", "cron", "gateway", "cli"],
"wiki" : ["wiki", "raw/", "ingest", "vault", "obsidian", "knowledge_base"],
"webui" : ["webui", "open-webui", "frontend", "chat", "rag"],
"infra" : ["deploy", "server", "systemd", "service", "port", "host"],
"security" : ["password", "secret", "token", "auth", "permission", "sudo"],
"maas" : ["maas", "memory", "cognitive", "agent"],
}
def infer_domain_tags(description: str) -> List[str]:
d = description.lower()
found = set()
for domain, pats in DOMAIN_PATTERNS.items():
if any(p in d for p in pats):
found.add(domain)
return sorted(found)
# ─── Core ───────────────────────────────────────────────────────────────────
def embed_text(text: str) -> Optional[List[float]]:
if not OPENROUTER_KEY:
return None
try:
r = requests.post(
"https://openrouter.ai/api/v1/embeddings",
headers={
"Authorization": f"Bearer {OPENROUTER_KEY}",
"Content-Type": "application/json"
},
json={"model": EMBEDDING_MODEL, "input": text[:8000]},
timeout=REQUEST_TIMEOUT
)
r.raise_for_status()
return r.json()["data"][0]["embedding"]
except Exception as e:
print(f"[PV-ERROR] Embedding failed: {e}", file=sys.stderr)
return None
def search_knowledge_base(vector: List[float], domain_tags: List[str]) -> List[Dict]:
try:
r = requests.post(
f"{QDRANT_URL}/collections/{COLLECTION}/points/search",
headers={"Content-Type": "application/json"},
json={"vector": vector, "limit": TOP_K * 3, "with_payload": True},
timeout=REQUEST_TIMEOUT
)
r.raise_for_status()
hits = []
for item in r.json().get("result", []):
pld = item.get("payload", {})
src = str(pld.get("source", "")).lower()
sev = str(pld.get("severity", pld.get("decision_severity", "low"))).lower()
tags = [str(t).lower() for t in pld.get("tags", [])]
score = item.get("score", 0)
# If domain filters requested, require overlap
if domain_tags:
dom_low = [d.lower() for d in domain_tags]
if not set(dom_low) & set(tags):
continue
hits.append({
"id" : str(item.get("id", "")),
"score" : score,
"title" : pld.get("title", "Untitled"),
"text" : (pld.get("text", "") or "")[:400],
"source" : src,
"severity": sev,
"tags" : tags,
})
hits.sort(key=lambda x: x["score"], reverse=True)
return hits[:TOP_K]
except Exception as e:
print(f"[PV-ERROR] Qdrant search failed: {e}", file=sys.stderr)
return []
def is_rule_hit(hit: Dict) -> bool:
"""Return True if the hit contains an explicit rule (reflection/decision/rule/insight/pitfall)."""
return any(s in hit["source"] for s in RULE_SOURCES)
def classify_hit(hit: Dict, action_desc: str) -> str:
"""
Return hit category: 'block', 'warn', 'info', or 'none'.
Considers both source=reflection/decision/rule and restriction patterns
embedded in wiki document text.
"""
sev = hit.get("severity", "low")
is_rule = is_rule_hit(hit) or contains_restriction(hit.get("text", ""))
score = hit.get("score", 0)
# If text contains restriction, give it more weight
restriction_bonus = 0.08 if contains_restriction(hit.get("text", "")) else 0
effective_score = score + restriction_bonus
# Proximity: if the action term (e.g. "POST") appears near a keyword in the text
action_terms = set(action_desc.lower().split())
text_lower = (hit.get("text", "") or "").lower()
text_words = set(text_lower.split())
proximity_match = len(action_terms & text_words) > 0
# If restriction + proximity → elevate severity
has_restriction = contains_restriction(hit.get("text", "")) and proximity_match
if is_rule or has_restriction:
if sev in BLOCK_SEVERITIES or (has_restriction and effective_score >= 0.65):
return "block"
elif sev in WARN_SEVERITIES or (has_restriction and effective_score >= SCORE_THRESHOLD):
return "warn"
# For normal wiki documents, only warn if score is very high
if effective_score >= WARN_THRESHOLD:
return "warn"
if effective_score >= SCORE_THRESHOLD:
return "info"
return "none"
def validate_action(action_description: str, domain_tags: Optional[List[str]] = None) -> Dict:
try:
dom = domain_tags or infer_domain_tags(action_description)
vec = embed_text(action_description)
if vec is None:
return {"status": "pass", "blocked": False, "message": "⚠️ Validator offline. Proceeding with caution.", "action": action_description}
hits = search_knowledge_base(vec, dom)
blockers = []
warnings = []
infos = []
for h in hits:
cat = classify_hit(h, action_description)
if cat == "block":
blockers.append(h)
elif cat == "warn":
warnings.append(h)
elif cat == "info":
infos.append(h)
if blockers:
lines = [f"🚫 ACTION BLOCKED — {len(blockers)} critical rule(s) in the vault:"]
for b in blockers:
lines.append(f" • [{b['severity'].upper()}] {b['title']} (score: {b['score']:.2f})")
lines.append(f" {b['text'][:200]}...")
lines.append("")
lines.append("Override? Type 'force' (not recommended).")
return {
"status": "blocked", "blocked": True,
"blockers": blockers, "warnings": warnings,
"message": "\n".join(lines), "action": action_description, "domain": dom,
}
if warnings:
lines = [f"⚠️ {len(warnings)} warning(s) found in the vault:"]
for w in warnings:
lines.append(f" • [{w['severity'].upper()}] {w['title']} (score: {w['score']:.2f})")
lines.append(f" {w['text'][:200]}...")
return {
"status": "warn", "blocked": False,
"warnings": warnings, "infos": infos,
"message": "\n".join(lines), "action": action_description, "domain": dom,
}
if infos:
return {
"status": "info", "blocked": False,
"infos": infos,
"message": f"ℹ️ {len(infos)} relevant document(s), none critical.",
"action": action_description, "domain": dom,
}
return {
"status": "pass", "blocked": False,
"message": "No relevant insights found. Execution authorized.",
"action": action_description, "domain": dom,
}
except Exception as e:
return {
"status": "pass", "blocked": False,
"message": f"Validator failed ({e}). Proceeding with caution.",
"action": action_description, "domain": [],
}
# ─── Main ───────────────────────────────────────────────────────────────────
def main():
import argparse
p = argparse.ArgumentParser(description="Semantic Pre-Validator")
p.add_argument("action", nargs="?", help="Action description")
p.add_argument("--domain", help="Comma-separated domain tags")
p.add_argument("--json", action="store_true", help="JSON output")
p.add_argument("--silent", action="store_true", help="Silent — exit code only")
p.add_argument("--force-block", action="store_true", help="Force block (testing)")
args = p.parse_args()
action = args.action or sys.stdin.read().strip() or "POST to Qdrant upsert endpoint"
dom = [x.strip() for x in args.domain.split(",")] if args.domain else None
res = validate_action(action, dom)
if args.force_block:
res["blocked"] = True
res["status"] = "blocked"
if args.json:
print(json.dumps(res, indent=2, ensure_ascii=False, default=str))
elif not args.silent:
print(res["message"])
if res["blocked"]:
print("\n(Use --force-block to test validator bypass)")
sys.exit(1 if res["blocked"] else 0)
if __name__ == "__main__":
main()
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""
reflection_trigger.py
Checks whether the ARQ worker is idle (no pending/running jobs)
and dispatches a micro_reflection via ARQ enqueue. Runs via cron every 5 minutes.
Rules:
- Only triggers if there are no pending or running jobs (idle)
- Respects the max_per_hour budget (reads from env or defaults to 5)
- Enqueues ARQ job "process_micro_reflection" (function registered in the worker)
- Fail-open: if Redis/ARQ is unavailable, exits silently
- Never blocks the critical query/ingestion path
Usage (cron):
*/5 * * * * $VENV_DIR/bin/python $PROJECT_DIR/scripts/reflection_trigger.py >> $HERMES_LOG_DIR/reflection_trigger.cron.log 2>&1
"""
import os
import sys
import json
import asyncio
import argparse
from datetime import datetime, timezone
from pathlib import Path
from dotenv import load_dotenv
from arq import create_pool
from arq.connections import RedisSettings
import redis.asyncio as aioredis
# ─── Config ────────────────────────────────────────────────────────────────
ENV_PATH = Path(os.environ.get("MAA_ENV_PATH", "."))
if ENV_PATH.exists():
load_dotenv(ENV_PATH)
REDIS_HOST = os.environ.get("REDIS_HOST", "127.0.0.1")
REDIS_PORT = int(os.environ.get("REDIS_PORT", "6379"))
REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD", "")
MAX_REFLECTIONS_PER_HOUR = int(os.environ.get("MICRO_REFLECTION_MAX_PER_HOUR", "5"))
redis_settings = RedisSettings(
host=REDIS_HOST,
port=REDIS_PORT,
password=REDIS_PASSWORD or None,
)
LOG_FILE = Path(
os.environ.get(
"REFLECTION_LOG_PATH",
str(Path.home() / ".hermes" / "logs" / "reflection_trigger.log")
)
)
def log_message(msg: str):
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
line = f"[{ts}] {msg}"
try:
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
print(line)
async def is_idle() -> bool:
"""Check whether there are any pending or running jobs in ARQ."""
try:
r = aioredis.Redis(
host=REDIS_HOST, port=REDIS_PORT,
password=REDIS_PASSWORD or None,
decode_responses=True,
)
# ARQ stores jobs in queues like 'arq:queue:default'
queue_names = ["arq:queue:default"]
qr_prefix = os.environ.get("ARQ_QUEUE_PREFIX", "arq:queue:")
if qr_prefix:
try:
found = await r.keys(f"{qr_prefix}*")
queue_names = list(found) if found else queue_names
except Exception:
pass
total_pending = 0
for qn in queue_names:
try:
total_pending += await r.llen(qn)
except Exception:
pass
# In-progress jobs: ARQ uses sets like 'arq:in-progress:...'
in_progress_keys = await r.keys("arq:in-progress:*")
total_in_progress = 0
for key in in_progress_keys:
try:
total_in_progress += await r.scard(key)
except Exception:
pass
await r.aclose()
return (total_pending + total_in_progress) == 0
except Exception as e:
log_message(f"Error checking idle status: {e}")
return False # fail-safe: if unable to verify, do not trigger
async def check_budget() -> tuple[bool, int, int]:
"""Return (allowed, used, max) based on the hourly counter in SQLite."""
try:
import sqlite3
db_path = Path(
os.environ.get(
"STATE_DB_PATH",
str(Path.home() / ".hermes" / "state.db")
)
)
hour_window = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H")
conn = sqlite3.connect(str(db_path))
c = conn.cursor()
c.execute("SELECT count FROM reflection_budget WHERE hour_window = ?", (hour_window,))
row = c.fetchone()
used = row[0] if row else 0
conn.close()
return (used < MAX_REFLECTIONS_PER_HOUR, used, MAX_REFLECTIONS_PER_HOUR)
except Exception as e:
log_message(f"Error checking budget: {e}")
return (True, 0, MAX_REFLECTIONS_PER_HOUR) # fail-open
def increment_budget():
"""Increment the reflection counter in SQLite."""
try:
import sqlite3
db_path = Path(
os.environ.get(
"STATE_DB_PATH",
str(Path.home() / ".hermes" / "state.db")
)
)
hour_window = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H")
conn = sqlite3.connect(str(db_path))
c = conn.cursor()
c.execute("""
INSERT INTO reflection_budget (hour_window, count, tokens_used)
VALUES (?, 1, 0)
ON CONFLICT(hour_window)
DO UPDATE SET count = count + 1
""", (hour_window,))
conn.commit()
conn.close()
except Exception as e:
log_message(f"Error incrementing budget: {e}")
async def trigger_micro_reflection(dry_run: bool = False) -> dict:
"""Pipeline: idle check → budget check → ARQ enqueue → increment budget."""
# 1. Idle check
idle = await is_idle()
if not idle:
return {"status": "busy", "triggered": False}
# 2. Budget check
budget_ok, used, max_ref = await check_budget()
if not budget_ok:
return {
"status": "budget_exceeded",
"used": used,
"max": max_ref,
"triggered": False,
}
# 3. Enqueue
if dry_run:
return {
"status": "would_trigger",
"triggered": False,
"used": used,
"max": max_ref,
}
try:
pool = await create_pool(redis_settings)
job = await pool.enqueue_job("process_micro_reflection")
await pool.aclose()
# 4. Budget accounting is owned by the worker after actual processing.
# NOT incremented here — the worker's increment_budget() call
# handles this, preventing double-counting.
# increment_budget()
return {
"status": "triggered",
"triggered": True,
"job_id": str(job.job_id) if job else None,
"used": used + 1,
"max": max_ref,
}
except Exception as e:
log_message(f"Error enqueuing micro_reflection: {e}")
return {"status": "error", "error": str(e), "triggered": False}
async def main():
parser = argparse.ArgumentParser(description="Reflection Trigger — idle detection")
parser.add_argument("--dry-run", action="store_true", help="Simulate, do not enqueue")
args = parser.parse_args()
result = await trigger_micro_reflection(dry_run=args.dry_run)
log_message(json.dumps(result, ensure_ascii=False))
if result.get("status") == "error":
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env python3
"""
semantic_dedup.py
Monthly scanner for near-duplicates in knowledge_base_hybrid via cosine similarity.
Runs on the first Sunday of each month (cron: 0 3 1 * *).
⚠️ WARNING: This performs O(n²) brute-force pairwise comparisons. For large
collections (e.g. 100K+ points), this can be extremely slow and memory-heavy.
Use --max-points to limit processing, or prefer Qdrant's built-in
nearest-neighbor search on a random sample where feasible.
Rules:
- Ignores gabi_* collections
- Does not delete automatically — only emits a JSON report of candidates
- Similarity threshold: 0.92 (configurable)
- Merge is handled via upserts in file_ingestion.py (pre-write dedup)
- This script does the retrospective scan of the entire collection
(capped by MAX_POINTS)
Usage:
python3 semantic_dedup.py [--collection knowledge_base_hybrid] [--threshold 0.92] [--dry-run] [--max-points 5000]
"""
import os
import sys
import json
import math
import argparse
import requests
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Dict, Tuple, Optional
# ─── Config ────────────────────────────────────────────────────────────────
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base")
SCROLL_LIMIT = 50 # Qdrant pagination (avoids timeout on large collections)
SIMILARITY_THRESHOLD = 0.92
TOP_NEIGHBORS = 10
LOG_DIR = Path(
os.environ.get("HERMES_LOG_DIR", str(Path.home() / ".hermes" / "logs"))
)
LOG_FILE = LOG_DIR / "semantic_dedup.log"
REPORT_FILE = LOG_DIR / "semantic_dedup_report.json"
# Safety cap — limit processed points to avoid O(n²) blowup on large collections
MAX_POINTS = int(os.environ.get("DEDUP_MAX_POINTS", "5000"))
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def log_message(msg: str):
ts = now_iso()
line = f"[{ts}] {msg}"
print(line)
try:
LOG_DIR.mkdir(parents=True, exist_ok=True)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
# ─── Qdrant Operations ────────────────────────────────────────────────────
def scroll_all_chunks(collection: str) -> List[Dict]:
"""
Load all points from the collection, paginating via scroll.
Returns a list of {id, vector, payload}.
"""
all_chunks = []
offset = None
scanned = 0
while True:
payload = {
"limit": SCROLL_LIMIT,
"with_payload": True,
"with_vector": True,
}
if offset is not None:
payload["offset"] = offset
try:
resp = requests.post(
f"{QDRANT_URL}/collections/{collection}/points/scroll",
headers={"Content-Type": "application/json"},
json=payload,
timeout=30,
)
resp.raise_for_status()
data = resp.json()
result = data.get("result", {})
points = result.get("points", [])
if not points:
break
for point in points:
# Get only the dense vector for similarity
vector = point.get("vector")
dense = None
if isinstance(vector, dict):
dense = vector.get("dense")
elif isinstance(vector, list):
dense = vector # fallback: simple vector
if dense:
all_chunks.append({
"id": point.get("id"),
"vector": dense,
"payload": point.get("payload", {}),
})
scanned += len(points)
offset = result.get("next_page_offset")
if offset is None:
break
except Exception as e:
log_message(f"❌ Error in Qdrant scroll: {e}")
break
log_message(f"📊 Total chunks loaded: {len(all_chunks)} / {scanned} scanned")
return all_chunks
def cosine_similarity(v1: List[float], v2: List[float]) -> float:
"""Calculate cosine similarity between two vectors."""
if len(v1) != len(v2):
return 0.0
dot = sum(a * b for a, b in zip(v1, v2))
norm1 = math.sqrt(sum(a * a for a in v1))
norm2 = math.sqrt(sum(b * b for b in v2))
if norm1 == 0 or norm2 == 0:
return 0.0
return dot / (norm1 * norm2)
def find_near_duplicates(chunks: List[Dict], threshold: float = SIMILARITY_THRESHOLD) -> List[Dict]:
"""
Find near-duplicate pairs via brute-force cosine similarity.
Optimization: upper-triangular matrix comparison.
Returns list of {chunk_id_a, chunk_id_b, similarity}.
"""
n = len(chunks)
if n < 2:
return []
candidates = []
ids_seen = set() # avoid duplicates (A,B) and (B,A)
for i in range(n):
for j in range(i + 1, n):
# Fast heuristic: skip if texts differ greatly in size
text_len_i = len(chunks[i]["payload"].get("text", ""))
text_len_j = len(chunks[j]["payload"].get("text", ""))
if text_len_i > 0 and text_len_j > 0:
ratio = min(text_len_i, text_len_j) / max(text_len_i, text_len_j)
if ratio < 0.5: # Very different sizes, skip
continue
sim = cosine_similarity(chunks[i]["vector"], chunks[j]["vector"])
if sim >= threshold:
pair_key = tuple(sorted([str(chunks[i]["id"]), str(chunks[j]["id"])]))
if pair_key not in ids_seen:
ids_seen.add(pair_key)
candidates.append({
"chunk_id_a": chunks[i]["id"],
"chunk_id_b": chunks[j]["id"],
"similarity": round(sim, 6),
"source_a": chunks[i]["payload"].get("source", "unknown"),
"source_b": chunks[j]["payload"].get("source", "unknown"),
"title_a": chunks[i]["payload"].get("title", "")[:60],
"title_b": chunks[j]["payload"].get("title", "")[:60],
"text_preview_a": chunks[i]["payload"].get("text", "")[:100],
"text_preview_b": chunks[j]["payload"].get("text", "")[:100],
})
# Sort by descending similarity
candidates.sort(key=lambda x: x["similarity"], reverse=True)
return candidates
def generate_report(candidates: List[Dict], collection: str, threshold: float, scanned: int) -> Dict:
"""Generate structured JSON report."""
return {
"timestamp": now_iso(),
"collection": collection,
"threshold": threshold,
"scanned_chunks": scanned,
"near_duplicate_pairs": len(candidates),
"candidates": candidates,
"recommendation": (
f"{len(candidates)} near-duplicate pairs found. "
"Review manually and apply merge via Qdrant point update if approved."
),
}
def main():
parser = argparse.ArgumentParser(description="Semantic Dedup Scanner")
parser.add_argument("--collection", default=COLLECTION, help="Qdrant collection name")
parser.add_argument("--threshold", type=float, default=SIMILARITY_THRESHOLD, help="Cosine similarity threshold")
parser.add_argument("--max-points", type=int, default=MAX_POINTS, help="Max points to process (cap O(n²))")
parser.add_argument("--dry-run", action="store_true", help="Scan only, do not save report")
args = parser.parse_args()
collection = args.collection
# Skip gabi_* collections
if collection.startswith("gabi_"):
log_message(f"⏭️ Collection '{collection}' is exempt (gabi_*). Exiting.")
return
log_message(f"🚀 Starting semantic dedup (collection={collection}, threshold={args.threshold}, dry_run={args.dry_run})")
# Load chunks (capped by --max-points to avoid O(n²) blowup)
chunks = scroll_all_chunks(collection)
if args.max_points and len(chunks) > args.max_points:
log_message(f"⚠️ Collection has {len(chunks)} points, truncating to {args.max_points} (use --max-points to change)")
chunks = chunks[:args.max_points]
if not chunks:
log_message("⚠️ No chunks found in the collection.")
return
# Find near-duplicates
log_message(f"🔍 Analyzing similarity among {len(chunks)} chunks...")
candidates = find_near_duplicates(chunks, threshold=args.threshold)
# Generate report
report = generate_report(candidates, collection, args.threshold, len(chunks))
log_message("=" * 60)
log_message("📊 SEMANTIC DEDUP REPORT")
log_message("=" * 60)
log_message(f" Chunks scanned: {report['scanned_chunks']}")
log_message(f" Near-duplicate pairs: {report['near_duplicate_pairs']}")
if candidates:
log_message(f" Top similarity: {candidates[0]['similarity']:.4f}")
log_message(f" Top pair: {candidates[0]['chunk_id_a']} ↔ {candidates[0]['chunk_id_b']}")
else:
log_message(" No near-duplicates found.")
log_message("=" * 60)
# Save JSON report
if not args.dry_run and candidates:
try:
REPORT_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(REPORT_FILE, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
log_message(f"📄 Report saved: {REPORT_FILE}")
except Exception as e:
log_message(f"❌ Error saving report: {e}")
# Output JSON to stderr (parseable)
print(json.dumps(report, ensure_ascii=False, indent=2), file=sys.stderr)
log_message("✅ Semantic dedup complete.")
if __name__ == "__main__":
main()
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""
wiki-continuous-ingest.py
Detects new/modified .md files in the vault and enqueues them to the ARQ worker.
Runs on the host, accesses local Redis (127.0.0.1:6379) and Qdrant (localhost:6333).
"""
import os
import sys
import json
import hashlib
import asyncio
from pathlib import Path
from datetime import datetime, timezone
from dotenv import load_dotenv
from arq import create_pool
from arq.connections import RedisSettings
import redis.asyncio as aioredis
# ─── Config ────────────────────────────────────────────────────────────────
ENV_PATH = os.environ.get("ENV_PATH", "")
if ENV_PATH:
env_p = Path(ENV_PATH)
if env_p.exists():
load_dotenv(env_p)
WIKI_ROOT = Path(os.environ.get("WIKI_ROOT", "."))
STATE_DIR = Path(os.environ.get("HERMES_STATE_DIR", str(Path.home() / ".hermes")))
STATE_FILE = STATE_DIR / "wiki_ingest_state.json"
FAILURES_FILE = STATE_DIR / "wiki_ingest_failures.json"
REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD", "")
redis_settings = RedisSettings(
host="127.0.0.1",
port=6379,
password=REDIS_PASSWORD or None,
)
def load_state() -> dict:
if STATE_FILE.exists():
with open(STATE_FILE) as f:
return json.load(f)
return {}
def save_state(state: dict):
"""Atomic write via tempfile + rename to avoid corruption."""
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = STATE_FILE.with_suffix(".tmp")
with open(tmp, "w") as f:
json.dump(state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, STATE_FILE)
def file_hash(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()[:16]
async def redis_ready() -> bool:
"""Check whether Redis is accessible before enqueuing."""
try:
r = aioredis.Redis(
host="127.0.0.1", port=6379,
password=REDIS_PASSWORD or None,
socket_connect_timeout=3,
socket_timeout=3,
)
ok = await r.ping()
await r.aclose()
return bool(ok)
except Exception as e:
print(f" ⚠️ Redis unavailable: {e}")
return False
async def main():
if not await redis_ready():
print("❌ Redis not ready. Docker stack may still be starting up. Aborting.")
return
state = load_state()
new_files = []
modified_files = []
skipped = 0
total = 0
# Scan all .md files
for path in sorted(WIKI_ROOT.rglob("*.md")):
total += 1
rel = str(path.relative_to(WIKI_ROOT))
mtime = path.stat().st_mtime
current_hash = file_hash(path)
if rel not in state:
new_files.append(rel)
state[rel] = {"mtime": mtime, "hash": current_hash, "queued_at": None, "ingested_at": None}
elif state[rel]["hash"] != current_hash:
modified_files.append(rel)
state[rel]["mtime"] = mtime
state[rel]["hash"] = current_hash
state[rel]["queued_at"] = None
state[rel]["ingested_at"] = None
else:
skipped += 1
files_to_ingest = new_files + modified_files
if not files_to_ingest:
print(f"⏭️ Nothing new. {total} files tracked, {skipped} unchanged.")
return
# Enqueue in ARQ
redis = await create_pool(redis_settings)
enqueued = 0
failed = 0
failures = []
for rel_path in files_to_ingest:
abs_path = str(WIKI_ROOT / rel_path)
try:
job = await redis.enqueue_job(
"process_wiki_file",
file_path=f"/wiki/{rel_path}", # path inside container
)
state[rel_path]["queued_at"] = datetime.now(timezone.utc).isoformat()
enqueued += 1
print(f" ✅ Enqueued: {rel_path} (job: {job.job_id[:8]})")
except Exception as e:
failed += 1
error_msg = str(e)
# Classify the error for the DLQ
error_lower = error_msg.lower()
transient_patterns = ["timeout", "connection", "rate limit", "503", "502", "504",
"unavailable", "too many requests", "refused", "reset"]
permanent_patterns = ["400", "404", "not found", "invalid", "parse error",
"deleted", "permission denied"]
failure_class = "unknown"
for p in transient_patterns:
if p in error_lower:
failure_class = "transient"
break
if failure_class == "unknown":
for p in permanent_patterns:
if p in error_lower:
failure_class = "permanent"
break
failures.append({
"timestamp": datetime.now(timezone.utc).isoformat(),
"file": rel_path,
"error": error_msg,
"failure_class": failure_class, # NEW: classification
"reported": False, # NEW: not yet reported
"retry_count": 0, # NEW: zero retries
})
print(f" ⚠️ Failure: {rel_path} — {e} [{failure_class}]")
await redis.aclose()
save_state(state)
# Persist failures to simple DLQ (atomic, last 500)
if failures:
FAILURES_FILE.parent.mkdir(parents=True, exist_ok=True)
existing = []
if FAILURES_FILE.exists():
with open(FAILURES_FILE) as f:
existing = json.load(f)
existing.extend(failures)
existing = existing[-500:]
tmp = FAILURES_FILE.with_suffix(".tmp")
with open(tmp, "w") as f:
json.dump(existing, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, FAILURES_FILE)
print(f"\n📊 {total} files tracked")
print(f" New: {len(new_files)} | Modified: {len(modified_files)} | Unchanged: {skipped}")
print(f" Enqueued: {enqueued} | Failures: {failed}")
if failures:
print(f" 📋 Failures persisted to: {FAILURES_FILE}")
if __name__ == "__main__":
asyncio.run(main())