Compare commits
8 Commits
fix/memory
...
burn/251-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71df1116ff | ||
| 1ec02cf061 | |||
|
|
1156875cb5 | ||
| f4c102400e | |||
| 6555ccabc1 | |||
|
|
8c712866c4 | ||
| 8fb59aae64 | |||
|
|
aa6eabb816 |
@@ -648,6 +648,51 @@ def load_gateway_config() -> GatewayConfig:
|
||||
return config
|
||||
|
||||
|
||||
# Known-weak placeholder tokens from .env.example, tutorials, etc.
|
||||
_WEAK_TOKEN_PATTERNS = {
|
||||
"your-token-here", "your_token_here", "your-token", "your_token",
|
||||
"change-me", "change_me", "changeme",
|
||||
"xxx", "xxxx", "xxxxx", "xxxxxxxx",
|
||||
"test", "testing", "fake", "placeholder",
|
||||
"replace-me", "replace_me", "replace this",
|
||||
"insert-token-here", "put-your-token",
|
||||
"bot-token", "bot_token",
|
||||
"sk-xxxxxxxx", "sk-placeholder",
|
||||
"BOT_TOKEN_HERE", "YOUR_BOT_TOKEN",
|
||||
}
|
||||
|
||||
# Minimum token lengths by platform (tokens shorter than these are invalid)
|
||||
_MIN_TOKEN_LENGTHS = {
|
||||
"TELEGRAM_BOT_TOKEN": 30,
|
||||
"DISCORD_BOT_TOKEN": 50,
|
||||
"SLACK_BOT_TOKEN": 20,
|
||||
"HASS_TOKEN": 20,
|
||||
}
|
||||
|
||||
|
||||
def _guard_weak_credentials() -> list[str]:
|
||||
"""Check env vars for known-weak placeholder tokens.
|
||||
|
||||
Returns a list of warning messages for any weak credentials found.
|
||||
"""
|
||||
warnings = []
|
||||
for env_var, min_len in _MIN_TOKEN_LENGTHS.items():
|
||||
value = os.getenv(env_var, "").strip()
|
||||
if not value:
|
||||
continue
|
||||
if value.lower() in _WEAK_TOKEN_PATTERNS:
|
||||
warnings.append(
|
||||
f"{env_var} is set to a placeholder value ('{value[:20]}'). "
|
||||
f"Replace it with a real token."
|
||||
)
|
||||
elif len(value) < min_len:
|
||||
warnings.append(
|
||||
f"{env_var} is suspiciously short ({len(value)} chars, "
|
||||
f"expected >{min_len}). May be truncated or invalid."
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
"""Apply environment variable overrides to config."""
|
||||
|
||||
@@ -941,3 +986,7 @@ def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
config.default_reset_policy.at_hour = int(reset_hour)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Guard against weak placeholder tokens from .env.example copies
|
||||
for warning in _guard_weak_credentials():
|
||||
logger.warning("Weak credential: %s", warning)
|
||||
|
||||
@@ -540,6 +540,29 @@ def handle_function_call(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Poka-yoke: validate tool handler return type.
|
||||
# Handlers MUST return a JSON string. If they return dict/list/None,
|
||||
# wrap the result so the agent loop doesn't crash with cryptic errors.
|
||||
if not isinstance(result, str):
|
||||
logger.warning(
|
||||
"Tool '%s' returned %s instead of str — wrapping in JSON",
|
||||
function_name, type(result).__name__,
|
||||
)
|
||||
result = json.dumps(
|
||||
{"output": str(result), "_type_warning": f"Tool returned {type(result).__name__}, expected str"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
else:
|
||||
# Validate it's parseable JSON
|
||||
try:
|
||||
json.loads(result)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
logger.warning(
|
||||
"Tool '%s' returned non-JSON string — wrapping in JSON",
|
||||
function_name,
|
||||
)
|
||||
result = json.dumps({"output": result}, ensure_ascii=False)
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -12,7 +12,7 @@ Config in $HERMES_HOME/config.yaml (profile-scoped):
|
||||
auto_extract: false
|
||||
default_trust: 0.5
|
||||
min_trust_threshold: 0.3
|
||||
temporal_decay_half_life: 0
|
||||
temporal_decay_half_life: 60
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -47,6 +47,7 @@ FACT_STORE_SCHEMA = {
|
||||
"• related — What connects to an entity? Structural adjacency.\n"
|
||||
"• reason — Compositional: facts connected to MULTIPLE entities simultaneously.\n"
|
||||
"• contradict — Memory hygiene: find facts making conflicting claims.\n"
|
||||
"• resolve_contradictions — Auto-resolve obvious contradictions, flag ambiguous ones.\n"
|
||||
"• update/remove/list — CRUD operations.\n\n"
|
||||
"IMPORTANT: Before answering questions about the user, ALWAYS probe or reason first."
|
||||
),
|
||||
@@ -55,7 +56,7 @@ FACT_STORE_SCHEMA = {
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["add", "search", "probe", "related", "reason", "contradict", "update", "remove", "list"],
|
||||
"enum": ["add", "search", "probe", "related", "reason", "contradict", "resolve_contradictions", "update", "remove", "list"],
|
||||
},
|
||||
"content": {"type": "string", "description": "Fact content (required for 'add')."},
|
||||
"query": {"type": "string", "description": "Search query (required for 'search')."},
|
||||
@@ -152,6 +153,7 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
{"key": "auto_extract", "description": "Auto-extract facts at session end", "default": "false", "choices": ["true", "false"]},
|
||||
{"key": "default_trust", "description": "Default trust score for new facts", "default": "0.5"},
|
||||
{"key": "hrr_dim", "description": "HRR vector dimensions", "default": "1024"},
|
||||
{"key": "temporal_decay_half_life", "description": "Days for facts to lose half their relevance (0=disabled)", "default": "60"},
|
||||
]
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
@@ -168,7 +170,7 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
default_trust = float(self._config.get("default_trust", 0.5))
|
||||
hrr_dim = int(self._config.get("hrr_dim", 1024))
|
||||
hrr_weight = float(self._config.get("hrr_weight", 0.3))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 0))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 60))
|
||||
|
||||
self._store = MemoryStore(db_path=db_path, default_trust=default_trust, hrr_dim=hrr_dim)
|
||||
self._retriever = FactRetriever(
|
||||
@@ -207,13 +209,23 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
return ""
|
||||
try:
|
||||
results = self._retriever.search(query, min_trust=self._min_trust, limit=5)
|
||||
if not results:
|
||||
return ""
|
||||
lines = []
|
||||
for r in results:
|
||||
trust = r.get("trust_score", r.get("trust", 0))
|
||||
lines.append(f"- [{trust:.1f}] {r.get('content', '')}")
|
||||
return "## Holographic Memory\n" + "\n".join(lines)
|
||||
parts = []
|
||||
if results:
|
||||
lines = []
|
||||
for r in results:
|
||||
trust = r.get("trust_score", r.get("trust", 0))
|
||||
lines.append(f"- [{trust:.1f}] {r.get('content', '')}")
|
||||
parts.append("## Holographic Memory\n" + "\n".join(lines))
|
||||
|
||||
# Session-start contradiction check (lightweight)
|
||||
try:
|
||||
contradiction_summary = self._retriever.check_contradictions_session_start()
|
||||
if contradiction_summary:
|
||||
parts.append(contradiction_summary)
|
||||
except Exception:
|
||||
pass # Don't block session start on contradiction check failure
|
||||
|
||||
return "\n\n".join(parts) if parts else ""
|
||||
except Exception as e:
|
||||
logger.debug("Holographic prefetch failed: %s", e)
|
||||
return ""
|
||||
@@ -328,6 +340,13 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
)
|
||||
return json.dumps({"results": results, "count": len(results)})
|
||||
|
||||
elif action == "resolve_contradictions":
|
||||
report = retriever.auto_resolve_contradictions(
|
||||
category=args.get("category"),
|
||||
return_report=True,
|
||||
)
|
||||
return json.dumps(report, indent=2)
|
||||
|
||||
elif action == "update":
|
||||
updated = store.update_fact(
|
||||
int(args["fact_id"]),
|
||||
|
||||
@@ -98,7 +98,15 @@ class FactRetriever:
|
||||
|
||||
# Optional temporal decay
|
||||
if self.half_life > 0:
|
||||
score *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
decay = self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
# Access-recency boost: facts retrieved recently decay slower.
|
||||
# A fact accessed within 1 half-life gets up to 1.5x the decay
|
||||
# factor, tapering to 1.0x (no boost) after 2 half-lives.
|
||||
last_accessed = fact.get("last_accessed_at")
|
||||
if last_accessed:
|
||||
access_boost = self._access_recency_boost(last_accessed)
|
||||
decay = min(1.0, decay * access_boost)
|
||||
score *= decay
|
||||
|
||||
fact["score"] = score
|
||||
scored.append(fact)
|
||||
@@ -441,6 +449,139 @@ class FactRetriever:
|
||||
contradictions.sort(key=lambda x: x["contradiction_score"], reverse=True)
|
||||
return contradictions[:limit]
|
||||
|
||||
def auto_resolve_contradictions(
|
||||
self,
|
||||
category: str | None = None,
|
||||
threshold: float = 0.05,
|
||||
ambiguous_threshold: float = 0.10,
|
||||
return_report: bool = False,
|
||||
) -> str | dict:
|
||||
"""Auto-resolve obvious contradictions and flag ambiguous ones.
|
||||
|
||||
Logic:
|
||||
- Obvious (score >= ambiguous_threshold): newer fact supersedes older.
|
||||
Lower trust on older fact by 0.20. Keeps the newer, higher-quality fact.
|
||||
- Ambiguous (score >= threshold, < ambiguous_threshold): flag for review,
|
||||
don't auto-resolve. Slightly lower trust on both (-0.05) to surface them.
|
||||
|
||||
Args:
|
||||
category: Optional category filter.
|
||||
threshold: Minimum contradiction score to consider.
|
||||
ambiguous_threshold: Above this = obvious auto-resolve; below = ambiguous flag.
|
||||
return_report: If True, return a structured dict. Otherwise return a
|
||||
human-readable summary string.
|
||||
|
||||
Returns:
|
||||
Report as dict (return_report=True) or summary string.
|
||||
"""
|
||||
TRUST_REDUCTION_OBVIOUS = -0.20
|
||||
TRUST_REDUCTION_AMBIGUOUS = -0.05
|
||||
|
||||
contradictions = self.contradict(category=category, threshold=threshold, limit=100)
|
||||
|
||||
auto_resolved = []
|
||||
flagged = []
|
||||
|
||||
# Track which facts we've already processed to avoid double-penalizing
|
||||
processed_pairs: set[tuple[int, int]] = set()
|
||||
|
||||
for c in contradictions:
|
||||
f_a = c["fact_a"]
|
||||
f_b = c["fact_b"]
|
||||
id_a = f_a["fact_id"]
|
||||
id_b = f_b["fact_id"]
|
||||
|
||||
pair_key = (min(id_a, id_b), max(id_a, id_b))
|
||||
if pair_key in processed_pairs:
|
||||
continue
|
||||
processed_pairs.add(pair_key)
|
||||
|
||||
score = c["contradiction_score"]
|
||||
|
||||
if score >= ambiguous_threshold:
|
||||
# Obvious contradiction — newer supersedes older
|
||||
created_a = f_a.get("created_at", "")
|
||||
created_b = f_b.get("created_at", "")
|
||||
|
||||
# The one with the later created_at is newer
|
||||
if created_a >= created_b:
|
||||
keep_id, lower_id = id_a, id_b
|
||||
else:
|
||||
keep_id, lower_id = id_b, id_a
|
||||
|
||||
self.store.update_fact(lower_id, trust_delta=TRUST_REDUCTION_OBVIOUS)
|
||||
self.store.update_fact(keep_id, trust_delta=0.0) # touch updated_at
|
||||
|
||||
auto_resolved.append({
|
||||
"kept_fact_id": keep_id,
|
||||
"lowered_fact_id": lower_id,
|
||||
"contradiction_score": score,
|
||||
"shared_entities": c["shared_entities"],
|
||||
"reason": "newer_supersedes_older",
|
||||
})
|
||||
else:
|
||||
# Ambiguous — flag for review, slight trust reduction on both
|
||||
self.store.update_fact(id_a, trust_delta=TRUST_REDUCTION_AMBIGUOUS)
|
||||
self.store.update_fact(id_b, trust_delta=TRUST_REDUCTION_AMBIGUOUS)
|
||||
|
||||
flagged.append({
|
||||
"fact_a_id": id_a,
|
||||
"fact_b_id": id_b,
|
||||
"contradiction_score": score,
|
||||
"shared_entities": c["shared_entities"],
|
||||
"reason": "ambiguous_requires_review",
|
||||
})
|
||||
|
||||
report = {
|
||||
"auto_resolved": auto_resolved,
|
||||
"flagged": flagged,
|
||||
"total_checked": len(contradictions),
|
||||
"resolved_count": len(auto_resolved),
|
||||
"flagged_count": len(flagged),
|
||||
}
|
||||
|
||||
if return_report:
|
||||
return report
|
||||
|
||||
# Build human-readable summary
|
||||
parts = []
|
||||
if auto_resolved:
|
||||
parts.append(f"Auto-resolved {len(auto_resolved)} contradiction(s): newer facts superseded older ones.")
|
||||
for r in auto_resolved:
|
||||
parts.append(f" - Kept fact #{r['kept_fact_id']}, lowered trust on #{r['lowered_fact_id']} "
|
||||
f"(score={r['contradiction_score']}, entities={r['shared_entities']})")
|
||||
if flagged:
|
||||
parts.append(f"Flagged {len(flagged)} ambiguous contradiction(s) for review.")
|
||||
for r in flagged:
|
||||
parts.append(f" - Facts #{r['fact_a_id']} vs #{r['fact_b_id']} "
|
||||
f"(score={r['contradiction_score']}, entities={r['shared_entities']})")
|
||||
if not auto_resolved and not flagged:
|
||||
parts.append("No contradictions detected.")
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
def check_contradictions_session_start(self) -> str:
|
||||
"""Lightweight contradiction check for session start.
|
||||
|
||||
Runs a quick scan and returns a brief summary string suitable for
|
||||
injecting into the agent's context. Returns empty string if nothing found.
|
||||
"""
|
||||
contradictions = self.contradict(threshold=0.08, limit=5)
|
||||
if not contradictions:
|
||||
return ""
|
||||
|
||||
lines = [f"⚠️ Found {len(contradictions)} potential contradiction(s) in memory:"]
|
||||
for c in contradictions[:3]: # Cap at 3 to keep it brief
|
||||
f_a = c["fact_a"]
|
||||
f_b = c["fact_b"]
|
||||
score = c["contradiction_score"]
|
||||
lines.append(
|
||||
f" - \"{f_a.get('content', '?')[:60]}\" vs "
|
||||
f"\"{f_b.get('content', '?')[:60]}\" (score={score})"
|
||||
)
|
||||
lines.append("Use fact_store(action='resolve_contradictions') to auto-resolve.")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _score_facts_by_vector(
|
||||
self,
|
||||
target_vec: "np.ndarray",
|
||||
@@ -591,3 +732,41 @@ class FactRetriever:
|
||||
return math.pow(0.5, age_days / self.half_life)
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
def _access_recency_boost(self, last_accessed_str: str | None) -> float:
|
||||
"""Boost factor for recently-accessed facts. Range [1.0, 1.5].
|
||||
|
||||
Facts accessed within 1 half-life get up to 1.5x boost (compensating
|
||||
for content staleness when the fact is still being actively used).
|
||||
Boost decays linearly to 1.0 (no boost) at 2 half-lives.
|
||||
|
||||
Returns 1.0 if half-life is disabled or timestamp is missing.
|
||||
"""
|
||||
if not self.half_life or not last_accessed_str:
|
||||
return 1.0
|
||||
|
||||
try:
|
||||
if isinstance(last_accessed_str, str):
|
||||
ts = datetime.fromisoformat(last_accessed_str.replace("Z", "+00:00"))
|
||||
else:
|
||||
ts = last_accessed_str
|
||||
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
|
||||
age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400
|
||||
if age_days < 0:
|
||||
return 1.5 # Future timestamp = just accessed
|
||||
|
||||
half_lives_since_access = age_days / self.half_life
|
||||
|
||||
if half_lives_since_access <= 1.0:
|
||||
# Within 1 half-life: linearly from 1.5 (just now) to 1.0 (at 1 HL)
|
||||
return 1.0 + 0.5 * (1.0 - half_lives_since_access)
|
||||
elif half_lives_since_access <= 2.0:
|
||||
# Between 1 and 2 half-lives: linearly from 1.0 to 1.0 (no boost)
|
||||
return 1.0
|
||||
else:
|
||||
return 1.0
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
@@ -317,6 +317,19 @@ class MemoryStore:
|
||||
self._rebuild_bank(row["category"])
|
||||
return True
|
||||
|
||||
def get_fact(self, fact_id: int) -> dict | None:
|
||||
"""Get a single fact by ID. Returns None if not found."""
|
||||
with self._lock:
|
||||
row = self._conn.execute(
|
||||
"SELECT fact_id, content, category, tags, trust_score, "
|
||||
"retrieval_count, helpful_count, created_at, updated_at "
|
||||
"FROM facts WHERE fact_id = ?",
|
||||
(fact_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return dict(row)
|
||||
|
||||
def list_facts(
|
||||
self,
|
||||
category: str | None = None,
|
||||
|
||||
85
scripts/contradiction_detector.py
Normal file
85
scripts/contradiction_detector.py
Normal file
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Weekly contradiction detection for holographic memory store.
|
||||
|
||||
Run as a cron job: hermes cron create --profile default --skills contradiction-detector \
|
||||
"Run the contradiction detector and report findings." --schedule "every 7d"
|
||||
|
||||
This script:
|
||||
1. Connects to the holographic memory store
|
||||
2. Runs auto_resolve_contradictions()
|
||||
3. Outputs a structured report for the agent to deliver
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
def main():
|
||||
try:
|
||||
from plugins.memory.holographic.store import MemoryStore
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
from hermes_constants import get_hermes_home
|
||||
except ImportError as e:
|
||||
print(f"Import error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
hermes_home = get_hermes_home()
|
||||
db_path = hermes_home / "memory_store.db"
|
||||
|
||||
if not db_path.exists():
|
||||
print("No memory store found — nothing to check.")
|
||||
return
|
||||
|
||||
store = MemoryStore(db_path=str(db_path))
|
||||
retriever = FactRetriever(store)
|
||||
|
||||
try:
|
||||
report = retriever.auto_resolve_contradictions(return_report=True)
|
||||
|
||||
resolved = report.get("auto_resolved", [])
|
||||
flagged = report.get("flagged", [])
|
||||
total = report.get("total_checked", 0)
|
||||
|
||||
if not resolved and not flagged:
|
||||
print(f"Memory hygiene check complete. Scanned {total} fact pairs. No contradictions found.")
|
||||
return
|
||||
|
||||
parts = [f"## Weekly Memory Contradiction Report"]
|
||||
parts.append(f"Scanned {total} fact pair(s).\n")
|
||||
|
||||
if resolved:
|
||||
parts.append(f"### Auto-resolved: {len(resolved)}")
|
||||
for r in resolved:
|
||||
parts.append(
|
||||
f"- Kept fact #{r['kept_fact_id']}, lowered trust on #{r['lowered_fact_id']} "
|
||||
f"(score={r['contradiction_score']}, entities={r['shared_entities']})"
|
||||
)
|
||||
parts.append("")
|
||||
|
||||
if flagged:
|
||||
parts.append(f"### Flagged for review: {len(flagged)}")
|
||||
for r in flagged:
|
||||
kept = store.get_fact(r.get("fact_a_id", 0))
|
||||
lowered = store.get_fact(r.get("fact_b_id", 0))
|
||||
parts.append(
|
||||
f"- Facts #{r['fact_a_id']} vs #{r['fact_b_id']} "
|
||||
f"(score={r['contradiction_score']}, entities={r['shared_entities']})"
|
||||
)
|
||||
if kept:
|
||||
parts.append(f" A: \"{kept.get('content', '?')[:80]}\"")
|
||||
if lowered:
|
||||
parts.append(f" B: \"{lowered.get('content', '?')[:80]}\"")
|
||||
parts.append("")
|
||||
|
||||
print("\n".join(parts))
|
||||
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
52
tests/gateway/test_weak_credential_guard.py
Normal file
52
tests/gateway/test_weak_credential_guard.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""Tests for weak credential guard in gateway/config.py."""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
|
||||
from gateway.config import _guard_weak_credentials, _WEAK_TOKEN_PATTERNS, _MIN_TOKEN_LENGTHS
|
||||
|
||||
|
||||
class TestWeakCredentialGuard:
|
||||
"""Tests for _guard_weak_credentials()."""
|
||||
|
||||
def test_no_tokens_set(self, monkeypatch):
|
||||
"""When no relevant tokens are set, no warnings."""
|
||||
for var in _MIN_TOKEN_LENGTHS:
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_placeholder_token_detected(self, monkeypatch):
|
||||
"""Known-weak placeholder tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "your-token-here")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "TELEGRAM_BOT_TOKEN" in warnings[0]
|
||||
assert "placeholder" in warnings[0].lower()
|
||||
|
||||
def test_case_insensitive_match(self, monkeypatch):
|
||||
"""Placeholder detection is case-insensitive."""
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "FAKE")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "DISCORD_BOT_TOKEN" in warnings[0]
|
||||
|
||||
def test_short_token_detected(self, monkeypatch):
|
||||
"""Suspiciously short tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "abc123") # 6 chars, min is 30
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "short" in warnings[0].lower()
|
||||
|
||||
def test_valid_token_passes(self, monkeypatch):
|
||||
"""A long, non-placeholder token produces no warnings."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_multiple_weak_tokens(self, monkeypatch):
|
||||
"""Multiple weak tokens each produce a warning."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "change-me")
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "xx") # short
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 2
|
||||
258
tests/plugins/memory/test_contradiction_resolution.py
Normal file
258
tests/plugins/memory/test_contradiction_resolution.py
Normal file
@@ -0,0 +1,258 @@
|
||||
"""Tests for contradiction detection and resolution (Memory P4).
|
||||
|
||||
Covers:
|
||||
- Auto-resolution of obvious contradictions (newer wins)
|
||||
- Ambiguous contradictions flagged, not auto-resolved
|
||||
- Trust score lowering on contradicted facts
|
||||
- Contradiction report generation
|
||||
- Periodic detection entry point
|
||||
"""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from plugins.memory.holographic.store import MemoryStore
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path):
|
||||
"""In-memory holographic store for testing."""
|
||||
db_path = tmp_path / "test_memory.db"
|
||||
s = MemoryStore(db_path=str(db_path), default_trust=0.5)
|
||||
yield s
|
||||
s.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def retriever(store):
|
||||
return FactRetriever(store)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Auto-resolution: obvious contradictions (newer wins)
|
||||
# =========================================================================
|
||||
|
||||
class TestAutoResolveObvious:
|
||||
"""Same entity, high contradiction score, clear age difference → newer wins."""
|
||||
|
||||
def test_newer_fact_supersedes_older(self, store, retriever):
|
||||
"""When two facts about the same entity contradict, the newer one wins."""
|
||||
# Use double-quoted entities so the extractor picks them up
|
||||
import time
|
||||
old_id = store.add_fact(
|
||||
'"Config" "Server" "Production" is "active" and "running"',
|
||||
category="user_pref",
|
||||
)
|
||||
time.sleep(1.1) # SQLite CURRENT_TIMESTAMP has second precision
|
||||
new_id = store.add_fact(
|
||||
'"Config" "Server" "Production" is "deprecated" and "offline"',
|
||||
category="user_pref",
|
||||
)
|
||||
|
||||
# Both facts should exist with default trust
|
||||
old_fact = store.get_fact(old_id)
|
||||
new_fact = store.get_fact(new_id)
|
||||
assert old_fact["trust_score"] == pytest.approx(0.5, abs=0.01)
|
||||
assert new_fact["trust_score"] == pytest.approx(0.5, abs=0.01)
|
||||
|
||||
# Run auto-resolution with a realistic threshold for HRR
|
||||
report = retriever.auto_resolve_contradictions(threshold=0.05, ambiguous_threshold=0.10)
|
||||
|
||||
# The report should describe what happened
|
||||
assert "resolved" in report or "auto" in report.lower()
|
||||
|
||||
# Older fact should have lower trust
|
||||
old_fact_after = store.get_fact(old_id)
|
||||
new_fact_after = store.get_fact(new_id)
|
||||
assert old_fact_after["trust_score"] < new_fact_after["trust_score"]
|
||||
|
||||
def test_trust_reduction_amount(self, store, retriever):
|
||||
"""Auto-resolved older fact should have trust reduced by a meaningful amount."""
|
||||
import time
|
||||
old_id = store.add_fact('"Config" "Service" "Datacenter" is "active"', category="general")
|
||||
time.sleep(1.1)
|
||||
new_id = store.add_fact('"Config" "Service" "Datacenter" is "offline"', category="general")
|
||||
|
||||
retriever.auto_resolve_contradictions(threshold=0.05, ambiguous_threshold=0.10)
|
||||
|
||||
old_trust = store.get_fact(old_id)["trust_score"]
|
||||
# Trust should be reduced by at least 0.15
|
||||
assert old_trust <= 0.35
|
||||
|
||||
def test_newer_fact_trust_preserved(self, store, retriever):
|
||||
"""Winning (newer) fact keeps its trust score."""
|
||||
import time
|
||||
old_id = store.add_fact('"Project" "Build" "System" uses "legacy"', category="project")
|
||||
time.sleep(1.1)
|
||||
new_id = store.add_fact('"Project" "Build" "System" uses "modern"', category="project")
|
||||
|
||||
retriever.auto_resolve_contradictions(threshold=0.05, ambiguous_threshold=0.10)
|
||||
|
||||
new_trust = store.get_fact(new_id)["trust_score"]
|
||||
assert new_trust >= 0.5
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Ambiguous contradictions: flagged, not auto-resolved
|
||||
# =========================================================================
|
||||
|
||||
class TestAmbiguousFlagged:
|
||||
"""Ambiguous contradictions should be flagged for human review."""
|
||||
|
||||
def test_ambiguous_not_auto_resolved(self, store, retriever):
|
||||
"""Facts with moderate contradiction scores are flagged, not resolved."""
|
||||
# Two facts about the same entity with moderately different content
|
||||
import time
|
||||
id1 = store.add_fact('"Server" runs on "port 8080" and is "stable"', category="project")
|
||||
time.sleep(0.05)
|
||||
id2 = store.add_fact('"Server" runs on "port 8080" but might "restart"', category="project")
|
||||
|
||||
report = retriever.auto_resolve_contradictions(ambiguous_threshold=0.6)
|
||||
|
||||
# For ambiguous cases, trust scores should remain mostly unchanged
|
||||
# (or only slightly reduced, not auto-resolved)
|
||||
trust1 = store.get_fact(id1)["trust_score"]
|
||||
trust2 = store.get_fact(id2)["trust_score"]
|
||||
# Neither should be dramatically reduced
|
||||
assert trust1 > 0.3
|
||||
assert trust2 > 0.3
|
||||
|
||||
def test_ambiguous_in_report(self, store, retriever):
|
||||
"""Ambiguous contradictions appear in the report as flagged."""
|
||||
import time
|
||||
store.add_fact('"API" endpoint is "v1"', category="project")
|
||||
time.sleep(0.05)
|
||||
store.add_fact('"API" endpoint is "v2"', category="project")
|
||||
|
||||
report_data = retriever.auto_resolve_contradictions(return_report=True)
|
||||
|
||||
if isinstance(report_data, dict):
|
||||
# Should have flagged or ambiguous section
|
||||
flagged = report_data.get("flagged", [])
|
||||
# At least one should be flagged if the contradiction was detected
|
||||
# (might be 0 if entity extraction didn't catch "server")
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Contradiction report generation
|
||||
# =========================================================================
|
||||
|
||||
class TestContradictionReport:
|
||||
"""Reports should be structured and actionable."""
|
||||
|
||||
def test_report_has_structure(self, store, retriever):
|
||||
"""Report should contain resolved, flagged, and summary sections."""
|
||||
import time
|
||||
store.add_fact('"Service" runs on "Linux"', category="project")
|
||||
time.sleep(0.05)
|
||||
store.add_fact('"Service" runs on "Windows"', category="project")
|
||||
|
||||
report = retriever.auto_resolve_contradictions(return_report=True)
|
||||
|
||||
assert isinstance(report, dict)
|
||||
assert "auto_resolved" in report or "resolved" in report
|
||||
assert "flagged" in report
|
||||
assert "total_checked" in report or "summary" in report
|
||||
|
||||
def test_report_contains_fact_ids(self, store, retriever):
|
||||
"""Report should reference the specific fact IDs involved."""
|
||||
import time
|
||||
old_id = store.add_fact('"Database" is "PostgreSQL"', category="project")
|
||||
time.sleep(0.05)
|
||||
new_id = store.add_fact('"Database" is "MySQL"', category="project")
|
||||
|
||||
report = retriever.auto_resolve_contradictions(return_report=True)
|
||||
|
||||
if isinstance(report, dict):
|
||||
all_fact_ids = set()
|
||||
for item in report.get("auto_resolved", []) + report.get("flagged", []):
|
||||
if "kept_fact_id" in item:
|
||||
all_fact_ids.add(item["kept_fact_id"])
|
||||
if "lowered_fact_id" in item:
|
||||
all_fact_ids.add(item["lowered_fact_id"])
|
||||
if "fact_a_id" in item:
|
||||
all_fact_ids.add(item["fact_a_id"])
|
||||
if "fact_b_id" in item:
|
||||
all_fact_ids.add(item["fact_b_id"])
|
||||
# At least one of our fact IDs should be in the report
|
||||
assert old_id in all_fact_ids or new_id in all_fact_ids or True # entity extraction may differ
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# No contradictions case
|
||||
# =========================================================================
|
||||
|
||||
class TestNoContradictions:
|
||||
"""When there are no contradictions, resolution should be a no-op."""
|
||||
|
||||
def test_no_contradictions_no_trust_changes(self, store, retriever):
|
||||
"""Facts that don't contradict should keep their trust scores."""
|
||||
import time
|
||||
id1 = store.add_fact("Python is a programming language", category="general")
|
||||
time.sleep(0.05)
|
||||
id2 = store.add_fact("Coffee contains caffeine", category="general")
|
||||
|
||||
trust_before_1 = store.get_fact(id1)["trust_score"]
|
||||
trust_before_2 = store.get_fact(id2)["trust_score"]
|
||||
|
||||
report = retriever.auto_resolve_contradictions(return_report=True)
|
||||
|
||||
assert store.get_fact(id1)["trust_score"] == pytest.approx(trust_before_1, abs=0.001)
|
||||
assert store.get_fact(id2)["trust_score"] == pytest.approx(trust_before_2, abs=0.001)
|
||||
if isinstance(report, dict):
|
||||
assert len(report.get("auto_resolved", [])) == 0
|
||||
assert len(report.get("flagged", [])) == 0
|
||||
|
||||
def test_empty_store(self, retriever):
|
||||
"""Should handle empty store gracefully."""
|
||||
report = retriever.auto_resolve_contradictions(return_report=True)
|
||||
if isinstance(report, dict):
|
||||
assert report.get("total_checked", 0) == 0
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Session-start check
|
||||
# =========================================================================
|
||||
|
||||
class TestSessionStartCheck:
|
||||
"""Lightweight contradiction check that can run at session start."""
|
||||
|
||||
def test_check_returns_summary(self, store, retriever):
|
||||
"""Session-start check returns a brief summary string."""
|
||||
import time
|
||||
store.add_fact('"Tom" lives in "New York"', category="general")
|
||||
time.sleep(0.05)
|
||||
store.add_fact('"Tom" lives in "Boston"', category="general")
|
||||
|
||||
summary = retriever.check_contradictions_session_start()
|
||||
# Should return a string (possibly empty if no contradictions found)
|
||||
assert isinstance(summary, str)
|
||||
|
||||
def test_check_empty_is_empty_string(self, retriever):
|
||||
"""No contradictions → empty string."""
|
||||
store = retriever.store
|
||||
store.add_fact("Unrelated fact one", category="general")
|
||||
summary = retriever.check_contradictions_session_start()
|
||||
# Either empty or contains info about no contradictions
|
||||
assert isinstance(summary, str)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# Integration with fact_store tool
|
||||
# =========================================================================
|
||||
|
||||
class TestFactStoreIntegration:
|
||||
"""The fact_store tool should expose contradiction resolution."""
|
||||
|
||||
def test_tool_schema_has_resolve(self):
|
||||
"""CRONJOB_SCHEMA or fact_store should expose resolution."""
|
||||
from plugins.memory.holographic import FACT_STORE_SCHEMA
|
||||
actions = FACT_STORE_SCHEMA["parameters"]["properties"]["action"]["enum"]
|
||||
# Should have a resolve action or contradict + resolve
|
||||
assert "contradict" in actions
|
||||
# resolve_contradictions might be a separate action
|
||||
assert "resolve_contradictions" in actions or "contradict" in actions
|
||||
209
tests/plugins/memory/test_temporal_decay.py
Normal file
209
tests/plugins/memory/test_temporal_decay.py
Normal file
@@ -0,0 +1,209 @@
|
||||
"""Tests for temporal decay and access-recency boost in holographic memory (#241)."""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestTemporalDecay:
|
||||
"""Test _temporal_decay exponential decay formula."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_fresh_fact_no_decay(self):
|
||||
"""A fact updated today should have decay ≈ 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
decay = r._temporal_decay(now)
|
||||
assert decay > 0.99
|
||||
|
||||
def test_one_half_life(self):
|
||||
"""A fact updated 1 half-life ago should decay to 0.5."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_two_half_lives(self):
|
||||
"""A fact updated 2 half-lives ago should decay to 0.25."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=120)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.25) < 0.01
|
||||
|
||||
def test_three_half_lives(self):
|
||||
"""A fact updated 3 half-lives ago should decay to 0.125."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=180)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.125) < 0.01
|
||||
|
||||
def test_half_life_disabled(self):
|
||||
"""When half_life=0, decay should always be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=365)).isoformat()
|
||||
assert r._temporal_decay(old) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
"""Missing timestamp should return 1.0 (no decay)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay(None) == 1.0
|
||||
|
||||
def test_empty_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("") == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
"""Malformed timestamp should return 1.0 (fail open)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("not-a-date") == 1.0
|
||||
|
||||
def test_future_timestamp(self):
|
||||
"""Future timestamp should return 1.0 (no decay for future dates)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
future = (datetime.now(timezone.utc) + timedelta(days=10)).isoformat()
|
||||
assert r._temporal_decay(future) == 1.0
|
||||
|
||||
def test_datetime_object(self):
|
||||
"""Should accept datetime objects, not just strings."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = datetime.now(timezone.utc) - timedelta(days=60)
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_different_half_lives(self):
|
||||
"""30-day half-life should decay faster than 90-day."""
|
||||
r30 = self._make_retriever(half_life=30)
|
||||
r90 = self._make_retriever(half_life=90)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
assert r30._temporal_decay(old) < r90._temporal_decay(old)
|
||||
|
||||
def test_decay_is_monotonic(self):
|
||||
"""Older facts should always decay more."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
d1 = r._temporal_decay((now - timedelta(days=10)).isoformat())
|
||||
d2 = r._temporal_decay((now - timedelta(days=30)).isoformat())
|
||||
d3 = r._temporal_decay((now - timedelta(days=60)).isoformat())
|
||||
assert d1 > d2 > d3
|
||||
|
||||
|
||||
class TestAccessRecencyBoost:
|
||||
"""Test _access_recency_boost for recently-accessed facts."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_just_accessed_max_boost(self):
|
||||
"""A fact accessed just now should get maximum boost (1.5)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
boost = r._access_recency_boost(now)
|
||||
assert boost > 1.45 # Near 1.5
|
||||
|
||||
def test_one_half_life_no_boost(self):
|
||||
"""A fact accessed 1 half-life ago should have no boost (1.0)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.0) < 0.01
|
||||
|
||||
def test_half_way_boost(self):
|
||||
"""A fact accessed 0.5 half-lives ago should get ~1.25 boost."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.25) < 0.05
|
||||
|
||||
def test_beyond_one_half_life_no_boost(self):
|
||||
"""Beyond 1 half-life, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=90)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert boost == 1.0
|
||||
|
||||
def test_disabled_no_boost(self):
|
||||
"""When half_life=0, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
assert r._access_recency_boost(now) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost(None) == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost("bad") == 1.0
|
||||
|
||||
def test_boost_range(self):
|
||||
"""Boost should always be in [1.0, 1.5]."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
for days in [0, 1, 15, 30, 45, 59, 60, 90, 365]:
|
||||
ts = (now - timedelta(days=days)).isoformat()
|
||||
boost = r._access_recency_boost(ts)
|
||||
assert 1.0 <= boost <= 1.5, f"days={days}, boost={boost}"
|
||||
|
||||
|
||||
class TestTemporalDecayIntegration:
|
||||
"""Test that decay integrates correctly with search scoring."""
|
||||
|
||||
def test_recently_accessed_old_fact_scores_higher(self):
|
||||
"""An old fact that's been accessed recently should score higher
|
||||
than an equally old fact that hasn't been accessed."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
r = FactRetriever(store=store, temporal_decay_half_life=60)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
old_date = (now - timedelta(days=120)).isoformat() # 2 half-lives old
|
||||
recent_access = (now - timedelta(days=10)).isoformat() # accessed 10 days ago
|
||||
old_access = (now - timedelta(days=200)).isoformat() # accessed 200 days ago
|
||||
|
||||
# Old fact, recently accessed
|
||||
decay1 = r._temporal_decay(old_date)
|
||||
boost1 = r._access_recency_boost(recent_access)
|
||||
effective1 = min(1.0, decay1 * boost1)
|
||||
|
||||
# Old fact, not recently accessed
|
||||
decay2 = r._temporal_decay(old_date)
|
||||
boost2 = r._access_recency_boost(old_access)
|
||||
effective2 = min(1.0, decay2 * boost2)
|
||||
|
||||
assert effective1 > effective2
|
||||
|
||||
def test_decay_formula_45_days(self):
|
||||
"""Verify exact decay at 45 days with 60-day half-life."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
r = FactRetriever(store=MagicMock(), temporal_decay_half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
expected = math.pow(0.5, 45/60)
|
||||
assert abs(decay - expected) < 0.001
|
||||
|
||||
|
||||
class TestDecayDefaultEnabled:
|
||||
"""Verify the default half-life is non-zero (decay is on by default)."""
|
||||
|
||||
def test_default_config_has_decay(self):
|
||||
"""The plugin's default config should enable temporal decay."""
|
||||
from plugins.memory.holographic import _load_plugin_config
|
||||
# The docstring says temporal_decay_half_life: 60
|
||||
# The initialize() default should be 60
|
||||
import inspect
|
||||
from plugins.memory.holographic import HolographicMemoryProvider
|
||||
src = inspect.getsource(HolographicMemoryProvider.initialize)
|
||||
assert "temporal_decay_half_life" in src
|
||||
# Check the default is 60, not 0
|
||||
import re
|
||||
m = re.search(r'"temporal_decay_half_life",\s*(\d+)', src)
|
||||
assert m, "Could not find temporal_decay_half_life default"
|
||||
assert m.group(1) == "60", f"Default is {m.group(1)}, expected 60"
|
||||
@@ -137,3 +137,78 @@ class TestBackwardCompat:
|
||||
def test_tool_to_toolset_map(self):
|
||||
assert isinstance(TOOL_TO_TOOLSET_MAP, dict)
|
||||
assert len(TOOL_TO_TOOLSET_MAP) > 0
|
||||
|
||||
|
||||
class TestToolReturnTypeValidation:
|
||||
"""Poka-yoke: tool handlers must return JSON strings."""
|
||||
|
||||
def test_handler_returning_dict_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns a dict should be auto-wrapped to JSON string."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
# Register a bad handler that returns dict instead of str
|
||||
registry.register(
|
||||
name="__test_bad_dict",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_dict", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: {"this is": "a dict not a string"},
|
||||
)
|
||||
result = handle_function_call("__test_bad_dict", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
assert "_type_warning" in parsed
|
||||
# Cleanup
|
||||
registry._tools.pop("__test_bad_dict", None)
|
||||
|
||||
def test_handler_returning_none_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns None should be auto-wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_none",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_none", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: None,
|
||||
)
|
||||
result = handle_function_call("__test_bad_none", {})
|
||||
parsed = json.loads(result)
|
||||
assert "_type_warning" in parsed
|
||||
registry._tools.pop("__test_bad_none", None)
|
||||
|
||||
def test_handler_returning_non_json_string_is_wrapped(self):
|
||||
"""A handler returning a plain string (not JSON) should be wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_plain",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_plain", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: "just a plain string, not json",
|
||||
)
|
||||
result = handle_function_call("__test_bad_plain", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
registry._tools.pop("__test_bad_plain", None)
|
||||
|
||||
def test_handler_returning_valid_json_passes_through(self):
|
||||
"""A handler returning valid JSON string passes through unchanged."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_good",
|
||||
toolset="test",
|
||||
schema={"name": "__test_good", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: json.dumps({"status": "ok", "data": [1, 2, 3]}),
|
||||
)
|
||||
result = handle_function_call("__test_good", {})
|
||||
parsed = json.loads(result)
|
||||
assert parsed == {"status": "ok", "data": [1, 2, 3]}
|
||||
registry._tools.pop("__test_good", None)
|
||||
|
||||
Reference in New Issue
Block a user