Spaces:
Configuration error
Configuration error
test: hardening test suite, adding auth tests, and shared conftest fixtures
Browse filesFiles changed (10)
- src/agentcache/core/observation_store.pyAdded+572
- src/agentcache/legacy.pyAdded
- src/agentcache/routes/graph.py+73-99
- src/agentcache/routes/health.py+138-166
- src/agentcache/routes/mcp.py+90-55
- src/agentcache/routes/memories.py+110-134
- tests/conftest.pyAdded+53
- tests/test_auth.py+139-49
- tests/test_observation_store.pyAdded+392
- tests/test_search_service.pyAdded+160
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572"""ObservationStore — owns folder-scoped observations lifecycle.
Handles ingestion, deduplication, deletion, timeline retrieval,and startup backfill for folder observations."""
from __future__ import annotations
import datetimeimport hashlibimport osimport threadingfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Dict, List, Optional
from ..db import StateKVfrom ..storage.paths import generate_idfrom .kv_scopes import KVfrom .search_service import SearchService
@dataclassclass ObservationEvents: on_added: List[Callable[[Dict[str, Any]], None]] = field(default_factory=list) on_deleted: List[Callable[[List[str]], None]] = field(default_factory=list) on_folder_deleted: List[Callable[[str, str], None]] = field(default_factory=list)
def normalize_folder_path(path: str) -> str: """Normalize a folder path for safe use in KV scope keys.""" if not path: raise ValueError("folder_path must not be empty")
path = path[:512]
raw_parts = path.replace("\\", "/").split("/") if any(part == ".." for part in raw_parts): raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")
normalized = os.path.normpath(path).replace("\\", "/").strip("/")
parts = normalized.split("/") if any(part == ".." for part in parts): raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")
if not normalized: raise ValueError("folder_path is empty after normalization")
return normalized
def validate_agent_id(agent_id: str) -> str: """Validate and sanitize an agent_id before use in KV scope keys.""" if not agent_id: raise ValueError("agent_id must not be empty")
agent_id = agent_id.strip()[:512]
if not agent_id: raise ValueError("agent_id must not be empty")
return agent_id
class ObservationStore: """Store for folder-scoped observations."""
def __init__( self, kv: StateKV, search_service: Optional[SearchService] = None, events: Optional[ObservationEvents] = None, ) -> None: self.kv = kv self.search_service = search_service self.events = events or ObservationEvents() self._dedup_locks: Dict[str, threading.Lock] = {} self._locks_mutex = threading.Lock()
def _get_dedup_lock(self, folder_path: str, agent_id: str) -> threading.Lock: key = f"{folder_path}:{agent_id}" with self._locks_mutex: if key not in self._dedup_locks: self._dedup_locks[key] = threading.Lock() return self._dedup_locks[key]
def ingest(self, payload: Dict[str, Any]) -> Dict[str, Any]: """Validate, deduplicate, write, index, and fire events for an observation.""" folder_path_raw = payload.get("folderPath") agent_id_raw = payload.get("agentId") text_raw = payload.get("text") timestamp = payload.get("timestamp")
if not folder_path_raw: raise ValueError("Invalid payload: folderPath is required") if not agent_id_raw: raise ValueError("Invalid payload: agentId is required") if not text_raw: raise ValueError("Invalid payload: text is required") if not timestamp: raise ValueError("Invalid payload: timestamp is required")
folder_path = normalize_folder_path(folder_path_raw) agent_id = validate_agent_id(agent_id_raw)
from ..legacy import strip_private_data, infer_type, extract_files
safe_text = strip_private_data(text_raw)[:4000]
dedup_fp = hashlib.sha256( safe_text[:4000].strip().lower().encode("utf-8") ).hexdigest()
dedup_lock = self._get_dedup_lock(folder_path, agent_id) with dedup_lock: existing_dedup = self.kv.get(KV.obs_dedup(folder_path, agent_id), dedup_fp) if existing_dedup and isinstance(existing_dedup, dict) and existing_dedup.get("obsId"): return {"observationId": existing_dedup["obsId"], "deduplicated": True}
max_obs = int(os.getenv("MAX_OBS_PER_FOLDER", "2000")) if max_obs > 0: existing_obs = self.kv.list(KV.folder_obs(folder_path, agent_id)) if len(existing_obs) >= max_obs: raise ValueError(f"Folder observation limit reached ({max_obs})")
obs_id = generate_id("fobs")
obs_type = payload.get("type") if not obs_type: obs_type = infer_type(None, "other")
title = payload.get("title") if not title: title = safe_text[:80]
concepts = payload.get("concepts") or [] if not isinstance(concepts, list): concepts = []
files = payload.get("files") if not isinstance(files, list): files = extract_files(payload)
raw_importance = payload.get("importance") if raw_importance is None: importance = 5 else: try: importance = max(1, min(10, int(raw_importance))) except (TypeError, ValueError): importance = 5
obs: Dict[str, Any] = { "id": obs_id, "folderPath": folder_path, "agentId": agent_id, "timestamp": timestamp, "text": safe_text, "type": obs_type, "title": title, "concepts": concepts, "files": files, "importance": importance, } if "forgetAfter" in payload: obs["forgetAfter"] = payload["forgetAfter"] elif ( payload.get("ttlDays") and isinstance(payload["ttlDays"], (int, float)) and payload["ttlDays"] > 0 ): try: import dateutil.parser
ts_dt = dateutil.parser.parse(timestamp) forget_time = ts_dt + datetime.timedelta(days=payload["ttlDays"]) obs["forgetAfter"] = forget_time.isoformat().replace("+00:00", "Z") except Exception: pass
self.kv.set(KV.folder_obs(folder_path, agent_id), obs_id, obs)
self.kv.set( KV.obs_lookup, obs_id, { "folderPath": folder_path, "agentId": agent_id, }, )
self.kv.set( KV.obs_dedup(folder_path, agent_id), dedup_fp, {"obsId": obs_id, "timestamp": timestamp}, )
meta_scope = KV.folder_meta(folder_path, agent_id) meta = self.kv.get(meta_scope, "meta") or { "folderPath": folder_path, "agentId": agent_id, "obsCount": 0, "lastUpdated": timestamp, "summary": None, } meta["obsCount"] = meta.get("obsCount", 0) + 1 meta["lastUpdated"] = timestamp self.kv.set(meta_scope, "meta", meta)
index_key = f"{folder_path}:{agent_id}" self.kv.set( KV.folders, index_key, { "folderPath": folder_path, "agentId": agent_id, "lastUpdated": meta["lastUpdated"], "obsCount": meta["obsCount"], }, )
if self.search_service: try: self.search_service.index(obs) self.search_service.schedule_persist() except Exception as ex: print(f"[observation_store] search_service indexing failed: {ex}")
self.kv.commit_version(f"folder_observe: {obs_id}", agent_id)
event_payload = { "type": "folder_observation", "folderPath": folder_path, "agentId": agent_id, "data": obs, } if self.events and self.events.on_added: for cb in self.events.on_added: try: cb(event_payload) except Exception as ex: print(f"[observation_store] Error in on_added callback: {ex}")
return {"observationId": obs_id}
def dedup( self, folder_path_raw: Optional[str] = None, agent_id_raw: Optional[str] = None ) -> Dict[str, Any]: """Remove duplicate observations for one or all (folder, agent) pairs.""" if folder_path_raw and agent_id_raw: try: fp = normalize_folder_path(folder_path_raw) aid = validate_agent_id(agent_id_raw) except ValueError as exc: return {"success": False, "error": str(exc)} pairs = [{"folderPath": fp, "agentId": aid}] else: pairs = [ {"folderPath": e.get("folderPath", ""), "agentId": e.get("agentId", "")} for e in self.kv.list(KV.folders) if e.get("folderPath") and e.get("agentId") ]
total_removed = 0 total_kept = 0
for pair in pairs:
fp = pair["folderPath"] aid = pair["agentId"] all_obs = self.kv.list(KV.folder_obs(fp, aid))
fingerprint_map: Dict[str, Dict[str, Any]] = {} duplicates: List[str] = []
for obs in all_obs: text = obs.get("text") or "" fp_hash = hashlib.sha256( text[:4000].strip().lower().encode("utf-8") ).hexdigest() if fp_hash not in fingerprint_map: fingerprint_map[fp_hash] = obs else: existing_ts = fingerprint_map[fp_hash].get("timestamp", "") this_ts = obs.get("timestamp", "") if this_ts < existing_ts: duplicates.append(fingerprint_map[fp_hash]["id"]) fingerprint_map[fp_hash] = obs else: duplicates.append(obs["id"])
if duplicates: self.forget({"folderPath": fp, "agentId": aid, "observationIds": duplicates}) total_removed += len(duplicates)
total_kept += len(fingerprint_map)
dedup_scope = KV.obs_dedup(fp, aid) for fp_hash, obs in fingerprint_map.items(): self.kv.set( dedup_scope, fp_hash, {"obsId": obs["id"], "timestamp": obs.get("timestamp", "")}, )
return { "success": True, "deduplicated": total_removed, "pairs_processed": len(pairs), "kept": total_kept, }
def forget(self, data: Dict[str, Any]) -> Dict[str, Any]: """Delete a folder pair, specific observations, or a global memory.""" memory_id = data.get("memoryId") session_id = data.get("sessionId") folder_path_raw = data.get("folderPath") agent_id_raw = data.get("agentId") obs_ids = data.get("observationIds") or [] deleted = 0 deleted_mem_ids: List[str] = [] deleted_obs_ids: List[str] = [] deleted_session = False
if memory_id: mem = self.kv.get(KV.memories, memory_id) self.kv.delete(KV.memories, memory_id) if mem and isinstance(mem, dict) and mem.get("imageRef"): ref = mem["imageRef"] refs = self.kv.get(KV.imageRefs, ref) or 0 if refs > 0: self.kv.set(KV.imageRefs, ref, refs - 1) if self.search_service: self.search_service.remove(memory_id) deleted_mem_ids.append(memory_id) deleted += 1
if folder_path_raw and agent_id_raw: try: fp = normalize_folder_path(folder_path_raw) aid = validate_agent_id(agent_id_raw) except ValueError as exc: return {"success": False, "error": str(exc), "deleted": 0}
obs_scope = KV.folder_obs(fp, aid) meta_scope = KV.folder_meta(fp, aid) index_key = f"{fp}:{aid}" if "observationIds" in data and data["observationIds"] is not None: partial_deleted = 0 for oid in obs_ids:
obs = self.kv.get(obs_scope, oid) existed = self.kv.delete(obs_scope, oid) if existed: self.kv.delete(KV.obs_lookup, oid) if self.search_service: self.search_service.remove(oid) if obs and isinstance(obs, dict) and obs.get("text"): fp_text = obs["text"][:4000] dedup_fp = hashlib.sha256( fp_text.strip().lower().encode("utf-8") ).hexdigest() self.kv.delete(KV.obs_dedup(fp, aid), dedup_fp) deleted_obs_ids.append(oid) partial_deleted += 1 deleted += 1
if partial_deleted > 0: meta = self.kv.get(meta_scope, "meta") if meta and isinstance(meta, dict): current_count = meta.get("obsCount", 0) meta["obsCount"] = max(0, current_count - partial_deleted) self.kv.set(meta_scope, "meta", meta) index_entry = self.kv.get(KV.folders, index_key) if index_entry and isinstance(index_entry, dict): index_entry["obsCount"] = meta["obsCount"] self.kv.set(KV.folders, index_key, index_entry)
if deleted_obs_ids and self.events and self.events.on_deleted: for cb in self.events.on_deleted: try: cb(deleted_obs_ids) except Exception as ex: print(f"[observation_store] Error in on_deleted callback: {ex}") else: all_obs = self.kv.list(obs_scope) for obs in all_obs: obs_id = obs.get("id") if obs_id: self.kv.delete(obs_scope, obs_id) self.kv.delete(KV.obs_lookup, obs_id) if self.search_service: self.search_service.remove(obs_id) deleted_obs_ids.append(obs_id) deleted += 1
self.kv.delete(meta_scope, "meta") self.kv.delete(KV.folders, index_key)
dedup_scope = KV.obs_dedup(fp, aid) for item in self.kv.list(dedup_scope): if isinstance(item, dict) and item.get("id"): self.kv.delete(dedup_scope, item["id"])
if self.events and self.events.on_folder_deleted: for cb in self.events.on_folder_deleted: try: cb(fp, aid) except Exception as ex: print(f"[observation_store] Error in on_folder_deleted callback: {ex}")
if session_id and obs_ids: for oid in obs_ids: base_oid = oid.replace(":raw", "") obs = self.kv.get(KV.observations(session_id), base_oid) raw_obs = self.kv.get(KV.observations(session_id), f"{base_oid}:raw")
self.kv.delete(KV.observations(session_id), base_oid) self.kv.delete(KV.observations(session_id), f"{base_oid}:raw") self.kv.delete(KV.obs_lookup, base_oid)
for o in (obs, raw_obs): if o and isinstance(o, dict): img = o.get("imageData") or o.get("imageRef") if img: refs = self.kv.get(KV.imageRefs, img) or 0 if refs > 0: self.kv.set(KV.imageRefs, img, refs - 1)
if self.search_service: self.search_service.remove(base_oid) self.search_service.remove(f"{base_oid}:raw") deleted_obs_ids.append(oid) deleted += 1
if session_id and not obs_ids and not memory_id and not folder_path_raw: obs_list = self.kv.list(KV.observations(session_id)) for obs in obs_list: self.kv.delete(KV.observations(session_id), obs["id"]) self.kv.delete(KV.obs_lookup, obs["id"]) if isinstance(obs, dict): img = obs.get("imageData") or obs.get("imageRef") if img: refs = self.kv.get(KV.imageRefs, img) or 0 if refs > 0: self.kv.set(KV.imageRefs, img, refs - 1) if self.search_service: self.search_service.remove(obs["id"]) deleted_obs_ids.append(obs["id"]) deleted += 1 self.kv.delete(KV.sessions, session_id) self.kv.delete(KV.summaries, session_id) deleted_session = True deleted += 2
if deleted > 0 and self.search_service: self.search_service.schedule_persist()
return {"success": True, "deleted": deleted}
def timeline( self, limit: int = 100, folder_path: Optional[str] = None, agent_id: Optional[str] = None, before: Optional[str] = None, after: Optional[str] = None, ) -> List[Dict[str, Any]]: """Return observations sorted by timestamp descending.""" index_entries = self.kv.list(KV.folders)
if folder_path is not None: index_entries = [e for e in index_entries if e.get("folderPath") == folder_path]
if agent_id is not None: index_entries = [e for e in index_entries if e.get("agentId") == agent_id]
all_obs: List[Dict[str, Any]] = []
for entry in index_entries: fp = entry.get("folderPath", "") aid = entry.get("agentId", "") if not fp or not aid: continue
obs_scope = KV.folder_obs(fp, aid) obs_list = self.kv.list(obs_scope)
if before is not None: obs_list = [o for o in obs_list if o.get("timestamp", "") < before]
if after is not None: obs_list = [o for o in obs_list if o.get("timestamp", "") > after]
all_obs.extend(obs_list)
all_obs.sort(key=lambda o: o.get("timestamp", ""), reverse=True) return all_obs[:limit]
def backfill_lookup(self) -> None: """Ensure every folder observation has an entry in KV.obs_lookup.""" folders = self.kv.list(KV.folders) if not folders: return
for entry in folders: fp = entry.get("folderPath") aid = entry.get("agentId") if not fp or not aid: continue obs_list = self.kv.list(KV.folder_obs(fp, aid)) for obs in obs_list: oid = obs.get("id") if oid and not self.kv.get(KV.obs_lookup, oid): self.kv.set(KV.obs_lookup, oid, {"folderPath": fp, "agentId": aid})
def rebuild_index(self) -> int: """Clear and rebuild the search index from all stored observations.""" if self.search_service: self.search_service.bm25.clear() if self.search_service.vector: self.search_service.vector.clear()
total_indexed = 0
# Folder-based observations folder_pairs = self.kv.list(KV.folders) for entry in folder_pairs: fp = entry.get("folderPath") aid = entry.get("agentId") if not fp or not aid: continue obs_list = self.kv.list(KV.folder_obs(fp, aid)) for obs in obs_list: oid = obs.get("id") if not oid: continue self.kv.set(KV.obs_lookup, oid, {"folderPath": fp, "agentId": aid}) if self.search_service: self.search_service.index(obs) total_indexed += 1
# Global memories memories = self.kv.list(KV.memories) for mem in memories: if mem.get("isLatest") is False: continue if not mem.get("title") or not mem.get("content"): continue converted = { "id": mem["id"], "sessionId": "memory", "timestamp": mem.get("createdAt", ""), "title": mem["title"], "text": mem["content"], "type": mem.get("type", "fact"), "agentId": mem.get("agentId", ""), } if self.search_service: self.search_service.index(converted) total_indexed += 1
if self.search_service and total_indexed > 0: self.search_service.schedule_persist()
return total_indexed
7 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101117 unmodified linesPOST /agentmemory/graph/build"""import osfrom flask import Blueprint, jsonify, requestfrom .. import functionsgraph_bp = Blueprint("graph", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kv# ---------------------------------------------------------------------------# GET /agentcache/graph# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph", methods=["GET"])@graph_bp.route("/agentmemory/graph", methods=["GET"])def api_graph():auth_err = _check_auth()if auth_err:return auth_errresult = functions.folder_graph_build(_get_kv())return jsonify(result), 200# ---------------------------------------------------------------------------# GET /agentcache/graph/stats# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/stats", methods=["GET"])@graph_bp.route("/agentmemory/graph/stats", methods=["GET"])def api_graph_stats():auth_err = _check_auth()if auth_err:return auth_errkv = _get_kv()g = functions.folder_graph_build(kv)node_count = len(g.get("nodes", []))edge_count = len(g.get("edges", []))return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 200# ---------------------------------------------------------------------------# POST /agentcache/graph/query# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/query", methods=["POST"])@graph_bp.route("/agentmemory/graph/query", methods=["POST"])def api_graph_query():auth_err = _check_auth()if auth_err:return auth_errtry:request.get_json(force=True) or {}# start_node_id = body.get("startNodeId") # reserved for future usereturn jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400# ---------------------------------------------------------------------------# POST /agentcache/graph/build# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/build", methods=["POST"])@graph_bp.route("/agentmemory/graph/build", methods=["POST"])def api_graph_build():auth_err = _check_auth()if auth_err:return auth_errtry:if functions.is_consolidation_enabled():functions.consolidate(_get_kv())return jsonify({"success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 4007 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384857 unmodified linesPOST /agentmemory/graph/build"""from flask import Blueprint, jsonify, requestfrom .. import legacy as functionsfrom .auth import require_authdef create_graph_bp(kv=None):"""Blueprint factory — receives kv at registration time."""bp = Blueprint("graph", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# GET /agentcache/graph# ------------------------------------------------------------------@bp.route("/agentcache/graph", methods=["GET"])@bp.route("/agentmemory/graph", methods=["GET"])@require_authdef api_graph():result = functions.folder_graph_build(_get_kv())return jsonify(result), 200# ------------------------------------------------------------------# GET /agentcache/graph/stats# ------------------------------------------------------------------@bp.route("/agentcache/graph/stats", methods=["GET"])@bp.route("/agentmemory/graph/stats", methods=["GET"])@require_authdef api_graph_stats():g = functions.folder_graph_build(_get_kv())node_count = len(g.get("nodes", []))edge_count = len(g.get("edges", []))return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 200# ------------------------------------------------------------------# POST /agentcache/graph/query# ------------------------------------------------------------------@bp.route("/agentcache/graph/query", methods=["POST"])@bp.route("/agentmemory/graph/query", methods=["POST"])@require_authdef api_graph_query():try:request.get_json(force=True) or {}# start_node_id = body.get("startNodeId") # reserved for future usereturn jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400# ------------------------------------------------------------------# POST /agentcache/graph/build# ------------------------------------------------------------------@bp.route("/agentcache/graph/build", methods=["POST"])@bp.route("/agentmemory/graph/build", methods=["POST"])@require_authdef api_graph_build():try:if functions.is_consolidation_enabled():functions.consolidate(_get_kv())return jsonify({"success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400return bpgraph_bp = create_graph_bp(None)
11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918011 unmodified linesfrom flask import Blueprint, Response, jsonify, requestfrom .. import functionsfrom ..functions import query_audithealth_bp = Blueprint("health", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kvdef _get_embedding_provider():from .. import app as app_modulereturn app_module.embedding_provider# ---------------------------------------------------------------------------# GET /auth.md (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/auth.md", methods=["GET"])def auth_docs():"""Serve the agent onboarding documentation in Markdown format."""base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))auth_md_path = os.path.join(base_dir, "auth.md")if os.path.exists(auth_md_path):try:with open(auth_md_path, "r", encoding="utf-8") as f:content = f.read()return Response(content,mimetype="text/markdown",headers={"Content-Type": "text/markdown; charset=utf-8"},)except Exception as e:return jsonify({"error": f"failed to read auth.md: {e}"}), 500return jsonify({"error": "auth.md not found"}), 404# ---------------------------------------------------------------------------# GET /agentcache/livez (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/agentcache/livez", methods=["GET"])@health_bp.route("/agentmemory/livez", methods=["GET"])def livez():port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))return jsonify({"status": "ok","service": "agentcache","viewerPort": port,"viewerSkipped": False,})# ---------------------------------------------------------------------------# GET /agentcache/health# ---------------------------------------------------------------------------@health_bp.route("/agentcache/health", methods=["GET"])@health_bp.route("/agentmemory/health", methods=["GET"])def health():return jsonify(functions.health_check(_get_kv()))# ---------------------------------------------------------------------------# GET /agentcache/audit# ---------------------------------------------------------------------------@health_bp.route("/agentcache/audit", methods=["GET"])@health_bp.route("/agentmemory/audit", methods=["GET"])def api_audit():auth_err = _check_auth()if auth_err:return auth_errop = request.args.get("operation")limit = int(request.args.get("limit", "50"))res = query_audit(_get_kv(), {"operation": op, "limit": limit})return jsonify({"entries": res, "success": True}), 200# ---------------------------------------------------------------------------# GET /agentcache/config/flags# ---------------------------------------------------------------------------@health_bp.route("/agentcache/config/flags", methods=["GET"])@health_bp.route("/agentmemory/config/flags", methods=["GET"])def config_flags():auth_err = _check_auth()if auth_err:return auth_errembedding_provider = _get_embedding_provider()provider_kind = "llm" if embedding_provider else "noop"embedding_prov = "gemini" if embedding_provider else "none"flags = [{"key": "GRAPH_EXTRACTION_ENABLED","label": "Knowledge graph extraction","enabled": functions.is_graph_extraction_enabled(),"default": False,"affects": ["Graph", "Dashboard"],"needsLlm": True,"description": "Extracts entities and relations from observations into a knowledge graph.","enableHow": "Set GRAPH_EXTRACTION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#knowledge-graph",},{"key": "CONSOLIDATION_ENABLED","label": "Memory consolidation","enabled": functions.is_consolidation_enabled(),"default": False,"affects": ["Dashboard", "Memories", "Crystals"],"needsLlm": True,"description": "Periodically summarizes sessions into semantic facts + procedures.","enableHow": "Set CONSOLIDATION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#consolidation",},{"key": "AGENTCACHE_AUTO_COMPRESS","label": "LLM-powered observation compression","enabled": functions.is_auto_compress_enabled(),"default": False,"affects": ["Memories", "Timeline"],"needsLlm": True,"description": "Every observation is compressed by the LLM for richer summaries. OFF uses synthetic compression.","enableHow": "Set AGENTCACHE_AUTO_COMPRESS=true.","docsHref": "https://github.com/rohitg00/agentmemory/issues/138",},]return jsonify({"version": "0.9.8","provider": provider_kind,"embeddingProvider": embedding_prov,"flags": flags,})11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115211 unmodified linesfrom flask import Blueprint, Response, jsonify, requestfrom .. import legacy as functionsfrom ..legacy import query_auditfrom .auth import require_authdef create_health_bp(kv=None, embedding_provider=None):"""Blueprint factory — receives kv and embedding_provider at registration time."""bp = Blueprint("health", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# GET /auth.md (no auth required)# ------------------------------------------------------------------@bp.route("/auth.md", methods=["GET"])def auth_docs():"""Serve the agent onboarding documentation in Markdown format."""base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))auth_md_path = os.path.join(base_dir, "auth.md")if os.path.exists(auth_md_path):try:with open(auth_md_path, "r", encoding="utf-8") as f:content = f.read()return Response(content,mimetype="text/markdown",headers={"Content-Type": "text/markdown; charset=utf-8"},)except Exception as e:return jsonify({"error": f"failed to read auth.md: {e}"}), 500return jsonify({"error": "auth.md not found"}), 404# ------------------------------------------------------------------# GET /agentcache/livez (no auth required)# ------------------------------------------------------------------@bp.route("/agentcache/livez", methods=["GET"])@bp.route("/agentmemory/livez", methods=["GET"])def livez():port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))return jsonify({"status": "ok","service": "agentcache","viewerPort": port,"viewerSkipped": False,})# ------------------------------------------------------------------# GET /agentcache/health# ------------------------------------------------------------------@bp.route("/agentcache/health", methods=["GET"])@bp.route("/agentmemory/health", methods=["GET"])def health():return jsonify(functions.health_check(_get_kv()))# ------------------------------------------------------------------# GET /agentcache/audit# ------------------------------------------------------------------@bp.route("/agentcache/audit", methods=["GET"])@bp.route("/agentmemory/audit", methods=["GET"])@require_authdef api_audit():op = request.args.get("operation")limit = int(request.args.get("limit", "50"))res = query_audit(_get_kv(), {"operation": op, "limit": limit})return jsonify({"entries": res, "success": True}), 200# ------------------------------------------------------------------# GET /agentcache/config/flags# ------------------------------------------------------------------@bp.route("/agentcache/config/flags", methods=["GET"])@bp.route("/agentmemory/config/flags", methods=["GET"])@require_authdef config_flags():provider_kind = "llm" if embedding_provider else "noop"embedding_prov = "gemini" if embedding_provider else "none"flags = [{"key": "GRAPH_EXTRACTION_ENABLED","label": "Knowledge graph extraction","enabled": functions.is_graph_extraction_enabled(),"default": False,"affects": ["Graph", "Dashboard"],"needsLlm": True,"description": "Extracts entities and relations from observations into a knowledge graph.","enableHow": "Set GRAPH_EXTRACTION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#knowledge-graph",},{"key": "CONSOLIDATION_ENABLED","label": "Memory consolidation","enabled": functions.is_consolidation_enabled(),"default": False,"affects": ["Dashboard", "Memories", "Crystals"],"needsLlm": True,"description": "Periodically summarizes sessions into semantic facts + procedures.","enableHow": "Set CONSOLIDATION_ENABLED=true and restart.","docsHref": "https://github.com/rohitg00/agentmemory#consolidation",},{"key": "AGENTCACHE_AUTO_COMPRESS","label": "LLM-powered observation compression","enabled": functions.is_auto_compress_enabled(),"default": False,"affects": ["Memories", "Timeline"],"needsLlm": True,"description": "Every observation is compressed by the LLM for richer summaries. OFF uses synthetic compression.","enableHow": "Set AGENTCACHE_AUTO_COMPRESS=true.","docsHref": "https://github.com/rohitg00/agentmemory/issues/138",},]return jsonify({"version": "0.9.8","provider": provider_kind,"embeddingProvider": embedding_prov,"flags": flags,})return bphealth_bp = create_health_bp(None)
11 unmodified lines121314151617181919 unmodified lines394041424344331 unmodified lines3763773783793803813823833843853863873883893903913921 unmodified line39439539639739839940010 unmodified lines4114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564571 unmodified line4594604614624634644654664674684 unmodified lines47347447547647747847948048148248348448516 unmodified lines50250350450550650750850951051151251351451551651751851952011 unmodified lines5325335345355365375382 unmodified lines5415425435445455465475483 unmodified lines5525535545555565575585597 unmodified lines56756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460511 unmodified linesfrom flask import Blueprint, jsonify, requestfrom .. import functionsfrom ..functions import KVmcp_bp = Blueprint("mcp", __name__)19 unmodified linesreturn app_module.kvdef _datetime_now_iso() -> str:return (datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")331 unmodified lineslimit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_save", "memory_save"):1 unmodified lineconcepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))project = args.get("project")res = functions.remember(kv,{"content": content,10 unmodified lineslimit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_diagnose", "memory_diagnose"):res = functions.health_check(kv)text_out = json.dumps(res, indent=2)elif name in ("cache_forget", "memory_forget"):obs_ids = _parse_mcp_list_arg(args.get("observationIds"))request_aid = args.get("agentId")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidres = functions.forget(kv,{"memoryId": args.get("memoryId"),"folderPath": args.get("folderPath"),"agentId": request_aid,"observationIds": obs_ids,},)text_out = json.dumps(res, indent=2)elif name in ("cache_export", "memory_export"):res = functions.export_data(kv, {})text_out = json.dumps(res, indent=2)elif name == "agent_observe":1 unmodified lineagent_id = args.get("agentId")text = args.get("text") or args.get("content") or ""# Compat shim: old plugin scripts send sessionId/project/cwd instead of# folderPath/agentId. Map them across so legacy callers keep working.if not folder_path:# Use cwd first, then project, then a sensible defaultfolder_path = (args.get("cwd")or args.get("project")4 unmodified linesif not agent_id:agent_id = (args.get("sessionId")or functions.get_agent_id()or os.getenv("AGENT_ID")or "agent")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify(16 unmodified lines"files": args.get("files"),"importance": args.get("importance"),}res = functions.folder_observe(kv, payload)text_out = json.dumps(res)elif name in ("agent_cache", "agent_remember"):agent_id = args.get("agentId") or functions.get_agent_id() or "agent"content = args.get("content")project = args.get("project")mem_type = args.get("type") or "fact"concepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify(11 unmodified lines"project": project,"agentId": agent_id,}res = functions.remember(kv, payload)text_out = json.dumps(res)elif name in ("cache_folders", "memory_folders"):2 unmodified lineskey=lambda x: x.get("lastUpdated", ""),reverse=True,)if functions.is_agent_scope_isolated():aid = functions.get_agent_id()if aid:pairs = [p for p in pairs if p.get("agentId") == aid]text_out = json.dumps(pairs, indent=2)3 unmodified linesaid = args.get("agentId", "")if not fp or not aid:return jsonify({"error": "folderPath and agentId are required"}), 400if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}7 unmodified lineselif name in ("cache_timeline", "memory_timeline"):request_aid = args.get("agentId")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidres = functions.folder_timeline(kv,limit=int(args.get("limit", 100)),folder_path=args.get("folderPath"),agent_id=request_aid,before=args.get("before"),after=args.get("after"),)text_out = json.dumps(res, indent=2)elif name in ("cache_dedup", "memory_dedup"):request_aid = args.get("agentId")if functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidres = functions.dedup_folder_observations(kv,args.get("folderPath") or None,request_aid or None,)text_out = json.dumps(res, indent=2)else:11 unmodified lines12131415161718192019 unmodified lines40414243444546474849505152535455565758331 unmodified lines3903913923933943953963973983994004014024034044054064074084094101 unmodified line41241341441541641741810 unmodified lines4294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824831 unmodified line4854864874884894904914 unmodified lines49649749849950050150250350450550650750816 unmodified lines52552652752852953053153253353453553653753853954054154254354454554654711 unmodified lines5595605615625635645652 unmodified lines5685695705715725735745753 unmodified lines5795805815825835845855867 unmodified lines59459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964011 unmodified linesfrom flask import Blueprint, jsonify, requestfrom .. import legacyfrom ..core import KVmcp_bp = Blueprint("mcp", __name__)19 unmodified linesreturn app_module.kvdef _get_search_service():from .. import app as app_modulereturn app_module.search_servicedef _get_observation_store():from .. import app as app_modulereturn app_module.observation_storedef _datetime_now_iso() -> str:return (datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")331 unmodified lineslimit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = _get_search_service()if search_svc is not None:res = search_svc.search(query=q, limit=limit, folder_path=folder_path, agent_id=agent_id, kv=kv)else:res = []text_out = json.dumps(res, indent=2)elif name in ("cache_save", "memory_save"):1 unmodified lineconcepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))project = args.get("project")res = legacy.remember(kv,{"content": content,10 unmodified lineslimit = int(args.get("limit") or 10)folder_path = args.get("folderPath")agent_id = args.get("agentId")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = _get_search_service()if search_svc is not None:res = search_svc.search(query=q, limit=limit, folder_path=folder_path, agent_id=agent_id, kv=kv)else:res = []text_out = json.dumps(res, indent=2)elif name in ("cache_diagnose", "memory_diagnose"):res = legacy.health_check(kv)text_out = json.dumps(res, indent=2)elif name in ("cache_forget", "memory_forget"):obs_ids = _parse_mcp_list_arg(args.get("observationIds"))request_aid = args.get("agentId")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:forget_payload = {"memoryId": args.get("memoryId"),"folderPath": args.get("folderPath"),"agentId": request_aid,}if obs_ids:forget_payload["observationIds"] = obs_idsres = obs_store.forget(forget_payload)else:res = {"success": False, "deleted": 0}text_out = json.dumps(res, indent=2)elif name in ("cache_export", "memory_export"):res = legacy.export_data(kv, {})text_out = json.dumps(res, indent=2)elif name == "agent_observe":1 unmodified lineagent_id = args.get("agentId")text = args.get("text") or args.get("content") or ""if not folder_path:folder_path = (args.get("cwd")or args.get("project")4 unmodified linesif not agent_id:agent_id = (args.get("sessionId")or legacy.get_agent_id()or os.getenv("AGENT_ID")or "agent")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify(16 unmodified lines"files": args.get("files"),"importance": args.get("importance"),}obs_store = _get_observation_store()if obs_store is not None:res = obs_store.ingest(payload)else:res = {"error": "ObservationStore not initialized"}text_out = json.dumps(res)elif name in ("agent_cache", "agent_remember"):agent_id = args.get("agentId") or legacy.get_agent_id() or "agent"content = args.get("content")project = args.get("project")mem_type = args.get("type") or "fact"concepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify(11 unmodified lines"project": project,"agentId": agent_id,}res = legacy.remember(kv, payload)text_out = json.dumps(res)elif name in ("cache_folders", "memory_folders"):2 unmodified lineskey=lambda x: x.get("lastUpdated", ""),reverse=True,)if legacy.is_agent_scope_isolated():aid = legacy.get_agent_id()if aid:pairs = [p for p in pairs if p.get("agentId") == aid]text_out = json.dumps(pairs, indent=2)3 unmodified linesaid = args.get("agentId", "")if not fp or not aid:return jsonify({"error": "folderPath and agentId are required"}), 400if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}7 unmodified lineselif name in ("cache_timeline", "memory_timeline"):request_aid = args.get("agentId")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:res = obs_store.timeline(limit=int(args.get("limit", 100)),folder_path=args.get("folderPath"),agent_id=request_aid,before=args.get("before"),after=args.get("after"),)else:res = []text_out = json.dumps(res, indent=2)elif name in ("cache_dedup", "memory_dedup"):request_aid = args.get("agentId")if legacy.is_agent_scope_isolated():current_aid = legacy.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:res = obs_store.dedup(args.get("folderPath") or None,request_aid or None,)else:res = {"success": False}text_out = json.dumps(res, indent=2)text_out = json.dumps(res, indent=2)else:
7 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451467 unmodified linesPOST /agentmemory/forget"""import osfrom flask import Blueprint, jsonify, requestfrom .. import functionsfrom ..functions import KVmemories_bp = Blueprint("memories", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kv# ---------------------------------------------------------------------------# POST /agentmemory/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/remember", methods=["POST"])@memories_bp.route("/agentmemory/remember", methods=["POST"])def api_remember():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.remember(_get_kv(), body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400# ---------------------------------------------------------------------------# POST /agentmemory/agent/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/agent/remember", methods=["POST"])@memories_bp.route("/agentmemory/agent/remember", methods=["POST"])def api_agent_remember():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}content = body.get("content")if not content:return jsonify({"error": "content is required"}), 400agent_id = body.get("agentId")project = body.get("project")mem_type = body.get("type") or "fact"concepts = body.get("concepts") or []if isinstance(concepts, str):concepts = [c.strip() for c in concepts.split(",") if c.strip()]files = body.get("files") or []if isinstance(files, str):files = [f.strip() for f in files.split(",") if f.strip()]payload = {"content": content,"type": mem_type,"concepts": concepts,"files": files,"project": project,}if agent_id:payload["agentId"] = agent_idres = functions.remember(_get_kv(), payload)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400# ---------------------------------------------------------------------------# GET /agentmemory/memories# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/memories", methods=["GET"])@memories_bp.route("/agentmemory/memories", methods=["GET"])def api_memories_list():auth_err = _check_auth()if auth_err:return auth_errlatest_only = request.args.get("latest", "false").lower() == "true"limit = int(request.args.get("limit", "500"))all_mems = _get_kv().list(KV.memories)if latest_only:all_mems = [m for m in all_mems if m.get("isLatest") is not False]all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200# ---------------------------------------------------------------------------# POST /agentmemory/forget# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/forget", methods=["POST"])@memories_bp.route("/agentmemory/forget", methods=["POST"])def api_forget():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}res = functions.forget(_get_kv(), body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 4007 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211227 unmodified linesPOST /agentmemory/forget"""from flask import Blueprint, jsonify, requestfrom .. import legacy as functionsfrom ..core import KVfrom .auth import require_authdef create_memories_bp(kv=None):"""Blueprint factory — receives kv at registration time."""bp = Blueprint("memories", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# POST /agentmemory/remember# ------------------------------------------------------------------@bp.route("/agentcache/remember", methods=["POST"])@bp.route("/agentmemory/remember", methods=["POST"])@require_authdef api_remember():try:body = request.get_json(force=True) or {}res = functions.remember(_get_kv(), body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400# ------------------------------------------------------------------# POST /agentmemory/agent/remember# ------------------------------------------------------------------@bp.route("/agentcache/agent/remember", methods=["POST"])@bp.route("/agentmemory/agent/remember", methods=["POST"])@require_authdef api_agent_remember():try:body = request.get_json(force=True) or {}content = body.get("content")if not content:return jsonify({"error": "content is required"}), 400agent_id = body.get("agentId")project = body.get("project")mem_type = body.get("type") or "fact"concepts = body.get("concepts") or []if isinstance(concepts, str):concepts = [c.strip() for c in concepts.split(",") if c.strip()]files = body.get("files") or []if isinstance(files, str):files = [f.strip() for f in files.split(",") if f.strip()]payload = {"content": content,"type": mem_type,"concepts": concepts,"files": files,"project": project,}if agent_id:payload["agentId"] = agent_idres = functions.remember(_get_kv(), payload)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 400# ------------------------------------------------------------------# GET /agentmemory/memories# ------------------------------------------------------------------@bp.route("/agentcache/memories", methods=["GET"])@bp.route("/agentmemory/memories", methods=["GET"])@require_authdef api_memories_list():latest_only = request.args.get("latest", "false").lower() == "true"limit = int(request.args.get("limit", "500"))all_mems = _get_kv().list(KV.memories)if latest_only:all_mems = [m for m in all_mems if m.get("isLatest") is not False]all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)return jsonify({"memories": all_mems[:limit], "total": len(all_mems)}), 200# ------------------------------------------------------------------# POST /agentmemory/forget# ------------------------------------------------------------------@bp.route("/agentcache/forget", methods=["POST"])@bp.route("/agentmemory/forget", methods=["POST"])@require_authdef api_forget():try:body = request.get_json(force=True) or {}res = functions.forget(_get_kv(), body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400return bpmemories_bp = create_memories_bp(None)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Shared pytest fixtures for agentcache test suite."""
import pytestimport agentcache.app as app_modfrom agentcache.app import create_appfrom agentcache.db import StateKV
@pytest.fixturedef tmp_db(tmp_path): """Return a fresh StateKV instance backed by a temporary SQLite file.""" db_path = str(tmp_path / "test_store.db") return StateKV(db_path=db_path)
@pytest.fixturedef app_client(tmp_path, monkeypatch): """ Reset all agentcache.app module-level globals, set AGENTCACHE_DB_PATH to a temp db, and yield a Flask test client. """ db_path = str(tmp_path / "app_client.db") monkeypatch.setenv("AGENTCACHE_DB_PATH", db_path)
app_mod.kv = None app_mod.search_service = None app_mod.observation_store = None
app = create_app() with app.test_client() as client: yield client
@pytest.fixturedef authed_client(tmp_path, monkeypatch): """ Reset all agentcache.app module-level globals, set AGENTCACHE_SECRET=test-secret and AGENTCACHE_DB_PATH to a temp db, call create_app(), and yield (client, "test-secret"). """ db_path = str(tmp_path / "authed_client.db") secret = "test-secret" monkeypatch.setenv("AGENTCACHE_DB_PATH", db_path) monkeypatch.setenv("AGENTCACHE_SECRET", secret)
app_mod.kv = None app_mod.search_service = None app_mod.observation_store = None
app = create_app() with app.test_client() as client: yield client, secret1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""tests/test_auth.pyTests for the /auth.md agent onboarding route."""import osimport pytest@pytest.fixture(scope="module")def flask_app(tmp_path_factory):tmp_dir = tmp_path_factory.mktemp("auth_test_db")db_path = str(tmp_dir / "test.db")os.environ.pop("AGENTCACHE_SECRET", None)os.environ.pop("AGENTMEMORY_SECRET", None)from agentcache.db import StateKVoriginal_init = StateKV.__init__def patched_init(self, db_path_arg=None, **kwargs):original_init(self, db_path=db_path, **kwargs)StateKV.__init__ = patched_initimport agentcache.app as app_moduleflask_application = app_module.create_app()StateKV.__init__ = original_initflask_application.config["TESTING"] = Truereturn flask_application@pytest.fixture(scope="module")def client(flask_app):return flask_app.test_client()def test_auth_md_endpoint(client):resp = client.get("/auth.md")assert resp.status_code == 200assert resp.headers["Content-Type"].startswith("text/markdown")content = resp.data.decode("utf-8")assert "# Agent Cache" in contentassert "Authorization" in contentassert "agent_observe" in contentdef test_auth_md_endpoint_with_secret(flask_app):os.environ["AGENTCACHE_SECRET"] = "super-secret-token"try:client = flask_app.test_client()resp = client.get("/auth.md")assert resp.status_code == 200content = resp.data.decode("utf-8")assert "# Agent Cache" in contentfinally:os.environ.pop("AGENTCACHE_SECRET", None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149"""Unit and integration tests for authentication and authorization."""from flask import Flask, jsonifyfrom agentcache.routes.auth import require_auth, verify_token# ------------------------------------------------------------------------------# Unit Tests — verify_token & require_auth# ------------------------------------------------------------------------------def test_verify_token():"""Verify verify_token direct behavior."""secret = "my-secret-key"assert verify_token("my-secret-key", secret) is Trueassert verify_token("wrong-secret", secret) is Falseassert verify_token("", secret) is Falsedef test_require_auth_unit(monkeypatch):"""Test require_auth decorator behavior under various header & env combinations on a toy app."""app = Flask(__name__)@app.route("/protected")@require_authdef protected():return jsonify({"status": "ok"}), 200client = app.test_client()# 1. No secret set -> request passes through with 200monkeypatch.delenv("AGENTCACHE_SECRET", raising=False)monkeypatch.delenv("AGENTMEMORY_SECRET", raising=False)res = client.get("/protected")assert res.status_code == 200# Set secret for remaining testsmonkeypatch.setenv("AGENTCACHE_SECRET", "secret-token")# 2. Missing Authorization header -> 401res = client.get("/protected")assert res.status_code == 401# 3. Basic scheme (non-Bearer) -> 401res = client.get("/protected", headers={"Authorization": "Basic secret-token"})assert res.status_code == 401# 4. Correct Bearer token -> 200res = client.get("/protected", headers={"Authorization": "Bearer secret-token"})assert res.status_code == 200# 5. Wrong Bearer token -> 401res = client.get("/protected", headers={"Authorization": "Bearer wrong-token"})assert res.status_code == 401# 6. Lowercase authorization header -> 200res = client.get("/protected", headers={"authorization": "Bearer secret-token"})assert res.status_code == 200# 7. Token with leading/trailing whitespace -> 200 (.strip() confirmed)res = client.get("/protected", headers={"Authorization": "Bearer secret-token "})assert res.status_code == 200# 8. Secret set via AGENTMEMORY_SECRET fallbackmonkeypatch.delenv("AGENTCACHE_SECRET")monkeypatch.setenv("AGENTMEMORY_SECRET", "fallback-secret")res = client.get("/protected", headers={"Authorization": "Bearer fallback-secret"})assert res.status_code == 200res = client.get("/protected", headers={"Authorization": "Bearer wrong-secret"})assert res.status_code == 401# ------------------------------------------------------------------------------# Integration Tests — protected & unprotected routes via authed_client# ------------------------------------------------------------------------------def test_protected_routes_require_auth(authed_client):"""Verify all protected HTTP routes return 401 without auth and 200/201 with auth."""client, secret = authed_clientheaders = {"Authorization": f"Bearer {secret}"}protected_endpoints = [("POST", "/agentcache/observe", {"folderPath": "src/test", "agentId": "a1", "text": "test"}),("POST", "/agentcache/remember", {"content": "test memory"}),("POST", "/agentcache/search", {"query": "test"}),("POST", "/agentcache/timeline", {}),("GET", "/agentcache/graph", None),("GET", "/agentcache/audit", None),("GET", "/agentcache/config/flags", None),("POST", "/agentcache/migrate", {}),]for method, path, payload in protected_endpoints:# Unauthenticated request -> 401if method == "POST":res_unauth = client.post(path, json=payload or {})res_auth = client.post(path, json=payload or {}, headers=headers)else:res_unauth = client.get(path)res_auth = client.get(path, headers=headers)assert res_unauth.status_code == 401, f"{method} {path} should require auth (got {res_unauth.status_code})"assert res_auth.status_code in (200, 201), f"{method} {path} failed with valid auth (got {res_auth.status_code})"def test_unprotected_routes_accessible_without_auth(authed_client):"""Verify unprotected routes return 200 even when AGENTCACHE_SECRET is set and no token is provided."""client, _ = authed_clientunprotected_paths = ["/agentcache/livez","/agentcache/health","/auth.md",]for path in unprotected_paths:res = client.get(path)assert res.status_code == 200, f"Unprotected route {path} failed (got {res.status_code})"def test_wrong_token_on_any_blueprint_returns_401(authed_client):"""Verify an invalid token returns 401 across all protected blueprints."""client, _ = authed_clientbad_headers = {"Authorization": "Bearer wrong-token-value"}protected_endpoints = [("POST", "/agentcache/observe", {"folderPath": "src/test", "agentId": "a1", "text": "test"}),("POST", "/agentcache/remember", {"content": "test memory"}),("POST", "/agentcache/search", {"query": "test"}),("POST", "/agentcache/timeline", {}),("GET", "/agentcache/graph", None),("GET", "/agentcache/audit", None),("GET", "/agentcache/config/flags", None),("POST", "/agentcache/migrate", {}),]for method, path, payload in protected_endpoints:if method == "POST":res = client.post(path, json=payload or {}, headers=bad_headers)else:res = client.get(path, headers=bad_headers)assert res.status_code == 401, f"{method} {path} accepted invalid token!"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392import pytestimport osimport jsonfrom agentcache.core import KV, ObservationStore, ObservationEvents, SearchServicefrom agentcache.db import StateKVfrom agentcache.search import SearchIndexfrom agentcache.app import create_app
def test_observation_events_dataclass(): """Verify ObservationEvents dataclass has required typed callback lists.""" events = ObservationEvents() assert isinstance(events.on_added, list) assert isinstance(events.on_deleted, list) assert isinstance(events.on_folder_deleted, list)
def test_observation_store_ingest_and_dedup(tmp_db): """Verify ObservationStore.ingest happy path, dedup on write, and events firing.""" kv = tmp_db bm25 = SearchIndex() search_svc = SearchService(bm25_index=bm25, kv=kv)
added_events = [] events = ObservationEvents(on_added=[lambda ev: added_events.append(ev)])
store = ObservationStore(kv=kv, search_service=search_svc, events=events)
payload1 = { "folderPath": "src/services", "agentId": "agent_alpha", "text": "Extracted ObservationStore module", "timestamp": "2026-07-24T12:00:00Z", }
res1 = store.ingest(payload1) assert "observationId" in res1 assert "deduplicated" not in res1 obs_id1 = res1["observationId"]
# Verify event fired assert len(added_events) == 1 assert added_events[0]["type"] == "folder_observation" assert added_events[0]["data"]["id"] == obs_id1
# Ingest distinct text -> deduplicated must NOT be set payload_distinct = { "folderPath": "src/services", "agentId": "agent_alpha", "text": "Distinct second observation text", "timestamp": "2026-07-24T12:01:00Z", } res_distinct = store.ingest(payload_distinct) assert "observationId" in res_distinct assert "deduplicated" not in res_distinct
# Ingest duplicate text on same folderPath + agentId res2 = store.ingest(payload1) assert res2.get("observationId") == obs_id1 assert res2.get("deduplicated") is True
# SearchService indexed obs1 search_results = search_svc.search("Extracted ObservationStore", limit=5) assert len(search_results) == 1 assert search_results[0]["id"] == obs_id1
def test_observation_store_max_cap(tmp_db, monkeypatch): """Verify MAX_OBS_PER_FOLDER cap is enforced during ingest.""" monkeypatch.setenv("MAX_OBS_PER_FOLDER", "2")
kv = tmp_db store = ObservationStore(kv=kv)
store.ingest({ "folderPath": "src/cap", "agentId": "agent_beta", "text": "First item", "timestamp": "2026-07-24T12:00:00Z", }) store.ingest({ "folderPath": "src/cap", "agentId": "agent_beta", "text": "Second item", "timestamp": "2026-07-24T12:01:00Z", })
with pytest.raises(ValueError, match="Folder observation limit reached"): store.ingest({ "folderPath": "src/cap", "agentId": "agent_beta", "text": "Third item", "timestamp": "2026-07-24T12:02:00Z", })
def test_observation_store_manual_dedup(tmp_db): """Verify ObservationStore.dedup removes duplicate observations across pairs.""" kv = tmp_db store = ObservationStore(kv=kv)
obs1 = { "id": "fobs_dup_1", "folderPath": "src/dedup", "agentId": "agent_gamma", "text": "Duplicated text sample", "timestamp": "2026-07-24T10:00:00Z", } obs2 = { "id": "fobs_dup_2", "folderPath": "src/dedup", "agentId": "agent_gamma", "text": "Duplicated text sample", "timestamp": "2026-07-24T11:00:00Z", }
kv.set(KV.folders, "src/dedup:agent_gamma", {"folderPath": "src/dedup", "agentId": "agent_gamma"}) kv.set(KV.folder_obs("src/dedup", "agent_gamma"), "fobs_dup_1", obs1) kv.set(KV.folder_obs("src/dedup", "agent_gamma"), "fobs_dup_2", obs2) kv.set(KV.obs_lookup, "fobs_dup_1", {"folderPath": "src/dedup", "agentId": "agent_gamma"}) kv.set(KV.obs_lookup, "fobs_dup_2", {"folderPath": "src/dedup", "agentId": "agent_gamma"})
res = store.dedup("src/dedup", "agent_gamma") assert res["success"] is True assert res["deduplicated"] == 1 assert res["kept"] == 1
remaining = kv.list(KV.folder_obs("src/dedup", "agent_gamma")) assert len(remaining) == 1 assert remaining[0]["id"] == "fobs_dup_1"
def test_observation_store_forget_full_and_partial(tmp_db): """Verify ObservationStore.forget partial and full pair deletions and events.""" kv = tmp_db bm25 = SearchIndex() search_svc = SearchService(bm25_index=bm25, kv=kv)
deleted_obs = [] deleted_folders = [] events = ObservationEvents( on_deleted=[lambda ids: deleted_obs.extend(ids)], on_folder_deleted=[lambda fp, aid: deleted_folders.append((fp, aid))], )
store = ObservationStore(kv=kv, search_service=search_svc, events=events)
obs1_id = store.ingest({ "folderPath": "src/forget", "agentId": "agent_forget", "text": "First item to forget", "timestamp": "2026-07-24T10:00:00Z", })["observationId"]
obs2_id = store.ingest({ "folderPath": "src/forget", "agentId": "agent_forget", "text": "Second item to keep initially", "timestamp": "2026-07-24T11:00:00Z", })["observationId"]
# Explicitly empty observationIds list -> graceful handling of no-op partial delete res_noop = store.forget({ "folderPath": "src/forget", "agentId": "agent_forget", "observationIds": [], }) assert res_noop["success"] is True assert res_noop["deleted"] == 0
# 1. Partial deletion res_part = store.forget({ "folderPath": "src/forget", "agentId": "agent_forget", "observationIds": [obs1_id], }) assert res_part["success"] is True assert res_part["deleted"] == 1 assert deleted_obs == [obs1_id]
meta = kv.get(KV.folder_meta("src/forget", "agent_forget"), "meta") assert meta["obsCount"] == 1
# 2. Full folder pair deletion res_full = store.forget({ "folderPath": "src/forget", "agentId": "agent_forget", }) assert res_full["success"] is True assert res_full["deleted"] == 1 assert len(deleted_folders) == 1 assert deleted_folders[0] == ("src/forget", "agent_forget")
remaining_folders = kv.list(KV.folders) assert len(remaining_folders) == 0
def test_observation_store_timeline_sorting_and_filtering(tmp_db): """Verify ObservationStore.timeline sorting descending and timestamp filters.""" kv = tmp_db store = ObservationStore(kv=kv)
store.ingest({ "folderPath": "src/t1", "agentId": "agent_t", "text": "Oldest observation", "timestamp": "2026-07-24T10:00:00Z", }) store.ingest({ "folderPath": "src/t1", "agentId": "agent_t", "text": "Middle observation", "timestamp": "2026-07-24T12:00:00Z", }) store.ingest({ "folderPath": "src/t2", "agentId": "agent_t", "text": "Newest observation", "timestamp": "2026-07-24T14:00:00Z", })
# Timeline all tl_all = store.timeline(limit=10) assert len(tl_all) == 3 assert tl_all[0]["text"] == "Newest observation" assert tl_all[1]["text"] == "Middle observation" assert tl_all[2]["text"] == "Oldest observation"
# Filter before and after tl_filtered = store.timeline( limit=10, before="2026-07-24T13:00:00Z", after="2026-07-24T11:00:00Z", ) assert len(tl_filtered) == 1 assert tl_filtered[0]["text"] == "Middle observation"
# Filter folder_path tl_folder = store.timeline(folder_path="src/t1") assert len(tl_folder) == 2
def test_observation_store_rebuild_index_and_backfill_lookup(tmp_db): """Verify ObservationStore.rebuild_index and backfill_lookup populate missing entries.""" kv = tmp_db bm25 = SearchIndex() search_svc = SearchService(bm25_index=bm25, kv=kv) store = ObservationStore(kv=kv, search_service=search_svc)
# 1. Backfill test: insert raw observation without lookup entry kv.set(KV.folders, "src/bf:agent_bf", {"folderPath": "src/bf", "agentId": "agent_bf", "obsCount": 1}) kv.set(KV.folder_obs("src/bf", "agent_bf"), "fobs_bf1", { "id": "fobs_bf1", "folderPath": "src/bf", "agentId": "agent_bf", "text": "Unindexed backfill observation", "timestamp": "2026-07-24T10:00:00Z", })
kv.delete(KV.obs_lookup, "fobs_bf1") assert kv.get(KV.obs_lookup, "fobs_bf1") is None store.backfill_lookup() lookup = kv.get(KV.obs_lookup, "fobs_bf1") assert lookup is not None assert lookup["folderPath"] == "src/bf" assert lookup["agentId"] == "agent_bf"
# 2. Rebuild index test: search_svc index is currently 0 assert search_svc.bm25_size == 0 count = store.rebuild_index() assert count == 1 assert search_svc.bm25_size == 1
search_res = search_svc.search("Unindexed backfill", limit=5) assert len(search_res) == 1 assert search_res[0]["id"] == "fobs_bf1"
def test_http_and_mcp_forget_and_timeline_end_to_end(app_client): """Verify Flask HTTP timeline & forget routes and MCP tools work end-to-end.""" client = app_client
# Ingest observation via HTTP resp1 = client.post( "/agentcache/agent/observe", json={ "folderPath": "src/mcp_test", "agentId": "agent_mcp", "text": "Testing MCP tool handlers", "timestamp": "2026-07-24T15:00:00Z", }, ) assert resp1.status_code == 201
# Timeline via HTTP POST /agentcache/timeline resp_tl = client.post( "/agentcache/timeline", json={"folderPath": "src/mcp_test", "agentId": "agent_mcp"}, ) assert resp_tl.status_code == 200 data_tl = resp_tl.get_json() assert len(data_tl["observations"]) == 1
# Timeline via MCP tool resp_mcp_tl = client.post( "/agentcache/mcp/tools", json={ "name": "cache_timeline", "arguments": {"folderPath": "src/mcp_test", "agentId": "agent_mcp"}, }, ) assert resp_mcp_tl.status_code == 200 mcp_out = resp_mcp_tl.get_json()["content"][0]["text"] assert "Testing MCP tool handlers" in mcp_out
# Forget via MCP tool resp_mcp_forget = client.post( "/agentcache/mcp/tools", json={ "name": "cache_forget", "arguments": {"folderPath": "src/mcp_test", "agentId": "agent_mcp"}, }, ) assert resp_mcp_forget.status_code == 200
# Post-forget timeline check resp_tl_post = client.post( "/agentcache/timeline", json={"folderPath": "src/mcp_test", "agentId": "agent_mcp"}, ) assert resp_tl_post.status_code == 200 assert len(resp_tl_post.get_json()["observations"]) == 0
def test_full_lifecycle_e2e_pass(app_client): """Full integration pass: observe -> search -> timeline -> forget -> rebuild (HTTP & MCP layers).""" client = app_client
# 1. OBSERVE via MCP mcp_obs = client.post( "/agentcache/mcp/tools", json={ "name": "agent_observe", "arguments": { "folderPath": "src/e2e", "agentId": "agent_e2e", "text": "Refactored observation store completely", "timestamp": "2026-07-24T16:00:00Z", }, }, ) assert mcp_obs.status_code == 200 obs_id = json.loads(mcp_obs.get_json()["content"][0]["text"])["observationId"]
# 2. SEARCH via HTTP search_resp = client.post( "/agentcache/search", json={"query": "observation store", "folderPath": "src/e2e", "agentId": "agent_e2e"}, ) assert search_resp.status_code == 200 search_data = search_resp.get_json() assert len(search_data) == 1 assert search_data[0]["id"] == obs_id
# 3. TIMELINE via MCP timeline_resp = client.post( "/agentcache/mcp/tools", json={ "name": "cache_timeline", "arguments": {"folderPath": "src/e2e", "agentId": "agent_e2e"}, }, ) assert timeline_resp.status_code == 200 assert "Refactored observation store" in timeline_resp.get_json()["content"][0]["text"]
# 4. REBUILD via ObservationStore import agentcache.app as app_mod obs_store = app_mod.observation_store count = obs_store.rebuild_index() assert count >= 1
# 5. FORGET via HTTP / MCP forget_resp = client.post( "/agentcache/mcp/tools", json={ "name": "cache_forget", "arguments": {"folderPath": "src/e2e", "agentId": "agent_e2e"}, }, ) assert forget_resp.status_code == 200
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import osimport pytestfrom agentcache.core import KV, SearchService, IndexPersistencefrom agentcache.db import StateKVfrom agentcache.search import SearchIndexfrom agentcache.app import create_app, init_services, search_service as global_search_service
def test_kv_scopes_import(): """Verify KV class is importable and defines standard scope keys.""" assert KV.folders == "mem:folders" assert KV.obs_lookup == "mem:obs_lookup" assert KV.memories == "mem:memories" assert KV.folder_obs("src/core", "agent1") == "mem:folder:src/core:agent1"
def test_search_service_index_remove_and_search(tmp_db): """Verify SearchService index, remove, and search operations work end-to-end.""" kv = tmp_db
bm25 = SearchIndex() svc = SearchService(bm25_index=bm25, kv=kv)
obs1 = { "id": "obs_1", "title": "Auth Middleware", "text": "Implemented JWT token validation in authentication middleware", "folderPath": "src/auth", "agentId": "agent_alpha", } obs2 = { "id": "obs_2", "title": "Database Connection", "text": "SQLite database pool initialization and query optimization", "folderPath": "src/db", "agentId": "agent_beta", }
# Populate KV store for hydration kv.set(KV.folders, "src/auth:agent_alpha", {"folderPath": "src/auth", "agentId": "agent_alpha"}) kv.set(KV.folder_obs("src/auth", "agent_alpha"), "obs_1", obs1) kv.set(KV.obs_lookup, "obs_1", {"folderPath": "src/auth", "agentId": "agent_alpha"})
kv.set(KV.folders, "src/db:agent_beta", {"folderPath": "src/db", "agentId": "agent_beta"}) kv.set(KV.folder_obs("src/db", "agent_beta"), "obs_2", obs2) kv.set(KV.obs_lookup, "obs_2", {"folderPath": "src/db", "agentId": "agent_beta"})
# Index observations into SearchService svc.index(obs1) svc.index(obs2)
# Search for JWT token validation results = svc.search("JWT token", limit=10) assert len(results) >= 1 assert results[0]["id"] == "obs_1" assert "score" in results[0]
# Filtered search by folder_path filtered = svc.search("token", folder_path="src/db", limit=10) assert len(filtered) == 0
filtered_auth = svc.search("token", folder_path="src/auth", limit=10) assert len(filtered_auth) == 1 assert filtered_auth[0]["id"] == "obs_1"
# Filtered search by agent_id (returns only matching agent) filtered_agent = svc.search("validation", agent_id="agent_alpha", limit=10) assert len(filtered_agent) == 1 assert filtered_agent[0]["agentId"] == "agent_alpha"
filtered_wrong_agent = svc.search("validation", agent_id="agent_other", limit=10) assert len(filtered_wrong_agent) == 0
# Remove obs1 and verify it no longer matches svc.remove("obs_1") post_remove = svc.search("JWT token", limit=10) assert len(post_remove) == 0
def test_search_service_persistence(tmp_db): """Verify IndexPersistence saves and loads index data sharded in SQLite.""" kv = tmp_db
bm25 = SearchIndex() svc = SearchService(bm25_index=bm25, kv=kv)
obs = { "id": "obs_persist_1", "title": "Cache Eviction", "text": "LRU cache eviction policy implemented for high throughput", } kv.set(KV.memories, "obs_persist_1", obs) svc.index(obs) svc.flush_persist()
# Create fresh SearchService and load persisted index new_bm25 = SearchIndex() new_svc = SearchService(bm25_index=new_bm25, kv=kv) loaded = new_svc.load_persisted()
assert loaded["bm25"] is True assert new_svc.bm25_size > 0
results = new_svc.search("LRU cache", limit=10) assert len(results) >= 1
# Search for a term never indexed returns an empty list (no error/exception) non_existent = new_svc.search("nonexistenttermxyz", limit=10) assert isinstance(non_existent, list) assert len(non_existent) == 0
def test_http_search_routes_end_to_end(app_client): """Verify Flask HTTP search endpoints work end-to-end with real SQLite DB.""" client = app_client
import agentcache.app as app_mod kv = app_mod.kv search_svc = app_mod.search_service
obs = { "id": "obs_http_1", "title": "API Authentication Strategy", "text": "Secure OAuth2 bearer token authorization for external endpoints", "folderPath": "src/api", "agentId": "agent_gamma", }
kv.set(KV.folders, "src/api:agent_gamma", {"folderPath": "src/api", "agentId": "agent_gamma"}) kv.set(KV.folder_obs("src/api", "agent_gamma"), "obs_http_1", obs) kv.set(KV.obs_lookup, "obs_http_1", {"folderPath": "src/api", "agentId": "agent_gamma"})
search_svc.index(obs)
# POST /agentcache/search res = client.post("/agentcache/search", json={"query": "OAuth2 bearer token"}) assert res.status_code == 200 data = res.get_json() assert isinstance(data, list) assert len(data) == 1 assert data[0]["id"] == "obs_http_1" assert data[0]["folderPath"] == "src/api"
# POST /agentmemory/search (alias endpoint) res_alias = client.post("/agentmemory/search", json={"query": "OAuth2 bearer token", "limit": 5}) assert res_alias.status_code == 200 data_alias = res_alias.get_json() assert len(data_alias) == 1 assert data_alias[0]["id"] == "obs_http_1"
# Validation paths: missing or empty query -> 400 res_no_query = client.post("/agentcache/search", json={}) assert res_no_query.status_code == 400
res_empty_query = client.post("/agentcache/search", json={"query": ""}) assert res_empty_query.status_code == 400
res_alias_no_query = client.post("/agentmemory/search", json={}) assert res_alias_no_query.status_code == 400
src/agentcache/core/observation_store.pyAdded+572
src/agentcache/legacy.pyAdded
src/agentcache/routes/graph.py+73-99
src/agentcache/routes/health.py+138-166
src/agentcache/routes/mcp.py+90-55
src/agentcache/routes/memories.py+110-134
tests/conftest.pyAdded+53
tests/test_auth.py+139-49
tests/test_observation_store.pyAdded+392
tests/test_search_service.pyAdded+160