Spaces:
Configuration error
feat: dedup observations, fix dashboard buttons, add per-obs delete
Browse files- Add SHA-256 content fingerprint dedup to folder_observe() β identical
text from the same (folder, agent) pair returns existing obs ID without
writing a duplicate. Per-pair threading.Lock prevents TOCTOU races.
- Add dedup_folder_observations() to clean up existing duplicates across
one or all (folder, agent) pairs, rebuilding the dedup index after.
- Add POST /agentmemory/folder/dedup REST endpoint (auth-gated).
- Add memory_dedup MCP tool (schema + dispatch).
- Viewer: fix Back/Delete-folder buttons to use data-action delegation
instead of fragile inline onclick with escaped string args.
- Viewer: add per-observation Delete button on each card in folder detail.
- Viewer: add Select-all checkbox + bulk Delete-selected with single
POST /forget call; cards removed from DOM without reload.
- Viewer: add one-click Dedup button in folder detail toolbar.
- Viewer: fix Tools tab TypeError β raw fetch() replaces apiFetchRaw()
so .text() is called on the Response object, not a parsed JS object.
Files changed (8)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# Design: Deduplication & Dashboard Fixes
## 1. Root Cause Analysis
### Duplicate observations`folder_observe()` in `src/functions.py` calls `generate_id("fobs")` unconditionally and writes the result. There is no idempotency check. Agents that call `agent_observe` on every hook invocation with the same text (e.g. a status line logged on every file edit) produce hundreds of identical records.
### Broken viewer buttons- The folder detail view is rendered via `innerHTML` with inline `onclick="loadFolders()"` and `onclick="deleteFolderMemory(...)"`. These work in isolation but are brittle and inconsistent with the rest of the app's `data-action` delegation pattern.- `deleteFolderMemory` calls `apiFetchRaw('/agentmemory/forget', {...})` β the path resolution in `apiFetchRaw` prepends `REST` correctly, but the `Content-Type` header is not set in the options object passed (only in `headers` sub-key), so Flask receives an empty body and `forget` gets `{}`.- The Tools tab "Run" button calls `apiFetchRaw(...)` and then `await result.text()`. Because `apiFetchRaw` already calls `res.json()`, `result` is a plain JS object, not a `Response`, so `.text()` is not a function β `TypeError`.
---
## 2. Deduplication Design
### 2a. Fingerprint scopeA new KV scope `mem:obs_dedup:{safe_path}:{agent_id}` stores:- key = SHA-256 hex of `normalized_text` (lowercased, whitespace-collapsed, first 4000 chars)- value = `{"obsId": "<first_obs_id>", "timestamp": "<ts>"}`
This is a O(1) lookup before any write.
### 2b. ConcurrencyA `threading.Lock` per `(folder_path, agent_id)` pair is held for the duration of the dedup-check + write window. A module-level `dict[str, Lock]` keyed by `f"{folder_path}:{agent_id}"` with a global meta-lock for dict access is sufficient for the single-process Flask/Werkzeug model.
### 2c. `folder_observe` changes (functions.py)```fingerprint = sha256(safe_text[:4000].strip().lower())existing = kv.get(KV.obs_dedup(folder_path, agent_id), fingerprint)if existing: return {"observationId": existing["obsId"], "deduplicated": True}# ... proceed with normal write ...kv.set(KV.obs_dedup(folder_path, agent_id), fingerprint, {"obsId": obs_id, "timestamp": timestamp})```
### 2d. New KV scope in `KV` class```python@staticmethoddef obs_dedup(folder_path: str, agent_id: str) -> str: safe_path = folder_path.replace("\\", "/").strip("/") safe_agent = agent_id.strip() return f"mem:obs_dedup:{safe_path}:{safe_agent}"```
Mirror in `src/storage/scopes.py`.
### 2e. Cleanup endpoint `dedup_folder_observations()`New function in `functions.py`:1. Load all obs for a (folder, agent) pair.2. Build fingerprint β list of obs sorted by timestamp asc.3. Keep the first, delete the rest via the existing `forget` path (which handles BM25/vector cleanup).4. Rebuild the dedup index from scratch for that pair.5. Return counts.
New route in `src/routes/observations.py`: `POST /agentmemory/folder/dedup`.
---
## 3. Viewer Dashboard Fixes
### 3a. Observation cards β per-row delete buttonIn `loadFolderDetail`, each observation div gets:```html<button class="btn btn-danger" style="..." data-action="delete-obs" data-obs-id="<id>" data-folder-path="<fp>" data-agent-id="<aid>">Delete</button>```The global `document.addEventListener('click', ...)` handler gains a new branch:```jsif (action === 'delete-obs') { var obsId = target.getAttribute('data-obs-id'); var fp = target.getAttribute('data-folder-path'); var aid = target.getAttribute('data-agent-id'); confirmDeleteObs(obsId, fp, aid);}````confirmDeleteObs` shows a modal, then calls `apiPost('forget', {folderPath: fp, agentId: aid, observationIds: [obsId]})` and removes the card from the DOM.
### 3b. Checkbox bulk deleteThe folder detail toolbar gets a "Select all" checkbox (`id="obs-select-all"`) and a "Delete selected" button (`data-action="delete-obs-selected"`, disabled by default).
Each observation card wrapper gets `data-obs-id`, a checkbox `class="obs-checkbox"`.
`change` events on checkboxes update a `selectedObsIds` Set and toggle the button's disabled state.
### 3c. Back button β data-actionReplace inline `onclick="loadFolders()"` with:```html<button class="btn" data-action="back-to-folders">β Back</button>```Handler in the global click dispatcher:```jsif (action === 'back-to-folders') { loadFolders(); return; }```
### 3d. Delete folder button β data-action + data attributesReplace inline `onclick="deleteFolderMemory(...)"` with:```html<button class="btn btn-danger" data-action="delete-folder" data-folder-path="<fp>" data-agent-id="<aid>">Delete folder memory</button>```Handler:```jsif (action === 'delete-folder') { var fp = target.getAttribute('data-folder-path'); var aid = target.getAttribute('data-agent-id'); confirmDeleteFolder(fp, aid);}````confirmDeleteFolder` shows the modal, calls `apiPost('forget', {folderPath: fp, agentId: aid})`, then `loadFolders()`.
### 3e. Tools tab run button β fix double-parseReplace the `apiFetchRaw` call in the tool runner with a raw `fetch`:```jsvar token = getViewerToken();var headers = {'Content-Type': 'application/json'};if (token) headers['Authorization'] = 'Bearer ' + token;var rawRes = await fetch(REST + '/agentmemory/mcp/tools', { method: 'POST', headers: headers, body: JSON.stringify({ name: name, arguments: args })});var text = await rawRes.text();var ok = rawRes.ok;```
---
## 4. Files Changed
| File | Change ||------|--------|| `src/functions.py` | Add `KV.obs_dedup`, dedup lock dict, dedup check in `folder_observe`, new `dedup_folder_observations` function || `src/storage/scopes.py` | Mirror `KV.obs_dedup` || `src/routes/observations.py` | Add `POST /agentmemory/folder/dedup` route || `src/routes/mcp.py` | Add `memory_dedup` tool schema + dispatch || `src/viewer/index.html` | Fix all broken buttons, add per-obs delete, add bulk delete, fix tools tab |
---
## 5. Security Notes- The dedup fingerprint is computed over already-stripped (private-data-removed) text, so secrets are not persisted in fingerprint keys.- The cleanup endpoint is auth-gated identical to all other write endpoints.- `data-` attribute values are HTML-escaped via the existing `esc()` function before injection into innerHTML β no XSS risk.- The per-pair lock prevents TOCTOU races under concurrent agent writes.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# Requirements: Deduplication & Dashboard Fixes
## OverviewAgents are producing duplicate observations in the folder memory store, causing memory bloat and potential hallucination. The viewer dashboard has broken navigation/delete buttons and lacks per-observation delete. This spec addresses the root cause and the UI gaps.
---
## Requirements
### REQ-01: Observation Deduplication in `folder_observe`- The system MUST compute a SHA-256 content fingerprint over `(folder_path, agent_id, text_normalized)` for every incoming observation.- If an observation with the same fingerprint already exists in `KV.folder_obs(folder_path, agent_id)`, the system MUST return the existing observation ID without writing a duplicate.- The fingerprint key stored in KV MUST use the scope `mem:obs_dedup:{folder_path}:{agent_id}` with key = fingerprint hex, value = existing obs_id.- The dedup check MUST happen after normalization and private-data stripping but before writing to KV.- Duplicate detection MUST be atomic: check + write must be protected against concurrent writes by a per-(folder, agent) lock.- The response for a deduplicated observation MUST include `{"observationId": "<existing_id>", "deduplicated": true}`.
### REQ-02: One-Shot Deduplication Cleanup Endpoint- A new REST endpoint `POST /agentmemory/folder/dedup` MUST be added.- It MUST accept `{"folderPath": "...", "agentId": "..."}` in the body.- It MUST scan all observations for that pair, group by normalized text fingerprint, keep the earliest observation per group, delete all later duplicates using the existing `forget` path, and rebuild the dedup index.- If `folderPath` and `agentId` are both omitted, it MUST run across ALL folder pairs.- It MUST return `{"deduplicated": <count_removed>, "pairs_processed": <n>, "kept": <count_kept>}`.- Auth check MUST be applied.
### REQ-03: Per-Observation Delete in Folder Detail View- The folder detail view in the viewer MUST show a "Delete" button on each observation card.- Clicking delete on an observation MUST call `POST /agentmemory/forget` with `{"folderPath": "...", "agentId": "...", "observationIds": ["<id>"]}`.- After deletion the observation card MUST be removed from the DOM without a full page reload.- A confirmation modal MUST be shown before deletion (reuse the existing modal pattern).
### REQ-04: Bulk Delete with Checkbox Selection- Each observation card in the folder detail view MUST have a checkbox.- A "Select all" checkbox MUST appear in the toolbar above the list.- A "Delete selected (N)" button MUST appear in the toolbar, enabled only when β₯1 checkbox is checked.- Clicking "Delete selected" MUST call `POST /agentmemory/forget` with all selected observation IDs in a single request.- After bulk deletion all deleted cards MUST be removed from the DOM.
### REQ-05: Fix Back Button in Folder Detail- The "β Back" button MUST navigate back to the folder list without a full page reload.- It MUST use the existing `data-action` event delegation pattern rather than inline `onclick`.
### REQ-06: Fix Delete Folder Button- The "Delete folder memory" button MUST use `data-action` event delegation.- It MUST NOT use inline `onclick` with string-escaped arguments (brittle with special characters in paths).- The folder path and agent ID MUST be stored in `data-` attributes on the button element.- After successful deletion it MUST navigate back to the folder list.
### REQ-07: Fix Tools Tab `apiFetchRaw` Double-Parse Bug- The Tools tab "Run" button calls `apiFetchRaw()` then `.text()` on the result, but `apiFetchRaw` already calls `.json()` β this throws a TypeError.- The fix MUST use the raw `fetch()` response directly in the Tools tab runner so `.text()` can be called on the `Response` object, not on a parsed JS object.
### REQ-08: Add `POST /agentmemory/folder/dedup` to MCP Tools- The dedup endpoint MUST be exposed as an MCP tool named `memory_dedup`.- Schema: `{"folderPath": string (optional), "agentId": string (optional)}`.- It MUST appear in `GET /agentmemory/mcp/tools` and be dispatchable via `POST /agentmemory/mcp/tools`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Tasks: Deduplication & Dashboard Fixes
## Task 1: Add dedup KV scope and per-pair locking to functions.py- [x] Add `KV.obs_dedup(folder_path, agent_id)` static method to the `KV` class in `src/functions.py`- [x] Add module-level `_dedup_locks: Dict[str, threading.Lock] = {}` and `_dedup_locks_meta = threading.Lock()` in `src/functions.py`- [x] Add helper `_get_dedup_lock(folder_path: str, agent_id: str) -> threading.Lock` in `src/functions.py`- [x] Mirror `obs_dedup` scope in `src/storage/scopes.py`
## Task 2: Add dedup check to `folder_observe` in functions.py- [x] After `safe_text` is computed (post strip_private_data), compute fingerprint: `hashlib.sha256(safe_text[:4000].strip().lower().encode()).hexdigest()`- [x] Acquire `_get_dedup_lock(folder_path, agent_id)` before the dedup check- [x] Look up `kv.get(KV.obs_dedup(folder_path, agent_id), fingerprint)`- [x] If found, release lock and return `{"observationId": existing["obsId"], "deduplicated": True}`- [x] After the obs is written to KV (step 6 in the existing pipeline), write the dedup index entry: `kv.set(KV.obs_dedup(folder_path, agent_id), fingerprint, {"obsId": obs_id, "timestamp": timestamp})`- [x] Release the lock after the dedup index write- [x] Ensure the lock is always released (use try/finally)
## Task 3: Add `dedup_folder_observations` function to functions.py- [x] Define `def dedup_folder_observations(kv: StateKV, folder_path_raw: Optional[str], agent_id_raw: Optional[str]) -> Dict[str, Any]`- [x] If both are None, iterate all pairs from `kv.list(KV.folders)`; otherwise validate and normalize the single pair- [x] For each pair: load all obs, group by `sha256(obs["text"][:4000].strip().lower())`, keep earliest by timestamp, delete duplicates via `forget(kv, {"folderPath": fp, "agentId": aid, "observationIds": [ids_to_delete]})`- [x] After deletion, rebuild the dedup index for the pair from scratch- [x] Return `{"deduplicated": total_removed, "pairs_processed": n, "kept": total_kept}`
## Task 4: Add `POST /agentmemory/folder/dedup` REST endpoint- [x] Add route in `src/routes/observations.py`: ```python @observations_bp.route("/agentmemory/folder/dedup", methods=["POST"]) def api_folder_dedup(): ```- [x] Apply `_check_auth()`- [x] Parse `folderPath` and `agentId` from request body (both optional)- [x] Call `functions.dedup_folder_observations(_get_kv(), folder_path, agent_id)`- [x] Return result as JSON 200
## Task 5: Add `memory_dedup` MCP tool- [x] Add tool schema to `GET /agentmemory/mcp/tools` in `src/routes/mcp.py`: ```python { "name": "memory_dedup", "description": "Remove duplicate observations from a (folderPath, agentId) pair or all pairs.", "inputSchema": { "type": "object", "properties": { "folderPath": {"type": "string", "description": "Folder path to deduplicate (optional β omit for all)"}, "agentId": {"type": "string", "description": "Agent ID to deduplicate (optional β omit for all)"}, } } } ```- [x] Add dispatch branch in `POST /agentmemory/mcp/tools`: ```python elif name == "memory_dedup": res = functions.dedup_folder_observations(kv, args.get("folderPath"), args.get("agentId")) text_out = json.dumps(res, indent=2) ```
## Task 6: Fix viewer β Back button and Delete folder button (data-action pattern)- [x] In `loadFolderDetail`, replace `onclick="loadFolders()"` on the Back button with `data-action="back-to-folders"`- [x] Replace inline `onclick="deleteFolderMemory(...)"` on the Delete folder button with `data-action="delete-folder"` plus `data-folder-path` and `data-agent-id` attributes (values must go through `esc()`)- [x] Add handler for `back-to-folders` in the global `document.addEventListener('click', ...)` dispatcher- [x] Add handler for `delete-folder` in the dispatcher: reads data attributes, calls `confirmDeleteFolder(fp, aid)`- [x] Implement `confirmDeleteFolder(fp, aid)`: shows modal with confirmation message, on confirm calls `apiPost('forget', {folderPath: fp, agentId: aid})` then `loadFolders()`- [x] Remove the now-dead `deleteFolderMemory` function
## Task 7: Add per-observation delete button to folder detail view- [x] In `loadFolderDetail`, add to each observation card: - A "Delete" button: `data-action="delete-obs"`, `data-obs-id`, `data-folder-path`, `data-agent-id` (all through `esc()`)- [x] Add handler for `delete-obs` in the dispatcher: calls `confirmDeleteObs(obsId, fp, aid)`- [x] Implement `confirmDeleteObs(obsId, fp, aid)`: shows modal, on confirm calls `apiPost('forget', {folderPath: fp, agentId: aid, observationIds: [obsId]})`, then removes the card element from the DOM
## Task 8: Add bulk checkbox delete to folder detail view- [x] Add a toolbar row above the observations list in `loadFolderDetail` with: - "Select all" checkbox: `id="obs-select-all"` - "Delete selected" button: `data-action="delete-obs-selected"`, disabled initially- [x] Add a checkbox to each observation card wrapper: `class="obs-checkbox"`, `data-obs-id`- [x] Wire `change` on `#obs-select-all` to toggle all checkboxes- [x] Wire `change` on each `.obs-checkbox` to update a `selectedObsIds` Set and enable/disable the "Delete selected" button- [x] Add handler for `delete-obs-selected` in the dispatcher: reads `selectedObsIds`, calls `apiPost('forget', {folderPath, agentId, observationIds: [...selectedObsIds]})`, removes all deleted cards from DOM
## Task 9: Fix Tools tab double-parse bug- [x] In `renderToolsTab`, replace the `apiFetchRaw` call inside the "Run" button handler with a direct `fetch()` call: ```js var token = getViewerToken(); var headers = {'Content-Type': 'application/json'}; if (token) headers['Authorization'] = 'Bearer ' + token; var rawRes = await fetch(REST + '/agentmemory/mcp/tools', { method: 'POST', headers: headers, body: JSON.stringify({ name: name, arguments: args }) }); var text = await rawRes.text(); var ok = rawRes.ok; ```- [x] Update history recording to use `ok` and `text` from the above25 unmodified lines26272829303125 unmodified lines575859606162162 unmodified lines225226227228229230773 unmodified lines100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107043 unmodified lines11141115111611171118111925 unmodified lines_hybrid_search = HybridSearch(_bm25_index, _vector_index, None, None)_index_persistence = None_stream_broadcaster = None # Callable: (payload) -> None# KV scope registry β folder-based memory modelclass KV:25 unmodified linessafe_agent = agent_id.strip()return f"mem:foldermeta:{safe_path}:{safe_agent}"# ---- Global / shared scopes (kept) ----# Long-term memories β unchanged from previous implementation.162 unmodified linesreturn sanitizeddef auto_complete_old_active_sessions(kv: StateKV, current_session_id: str, project: Optional[str] = None, agent_id: Optional[str] = None) -> int:sessions = kv.list(KV.sessions)count = 0773 unmodified linessafe_text = strip_private_data(text_raw)safe_text = safe_text[:4000]# 10. Enforce MAX_OBS_PER_FOLDER cap before writing (REQ-015)max_obs = int(os.getenv("MAX_OBS_PER_FOLDER", "2000"))if max_obs > 0:existing_obs = kv.list(KV.folder_obs(folder_path, agent_id))if len(existing_obs) >= max_obs:raise ValueError(f"Folder observation limit reached ({max_obs})")# 4. Generate obs_id (REQ-010)obs_id = generate_id("fobs")# 5. Determine optional fieldsobs_type = payload.get("type")if not obs_type:# Use infer_type with no tool_name; pass "other" as hook_typeobs_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):# Try to extract file refs from the payload itselffiles = extract_files(payload)raw_importance = payload.get("importance")if raw_importance is None:importance = 5else:try:importance = max(1, min(10, int(raw_importance)))except (TypeError, ValueError):importance = 5# 5. Build FolderObservation dict (REQ-003)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,}# 6. Write observation to KV (REQ-001)obs_scope = KV.folder_obs(folder_path, agent_id)kv.set(obs_scope, obs_id, obs)# Write coordinate lookup mappingkv.set(KV.obs_lookup, obs_id, {"folderPath": folder_path,"agentId": agent_id,})# 7. Upsert folder metadata (REQ-005)meta_scope = KV.folder_meta(folder_path, agent_id)43 unmodified linesreturn {"observationId": obs_id}# =====================================================================# Folder-Based Search (folder_search)# =====================================================================25 unmodified lines262728293031323325 unmodified lines59606162636465666768697071727374162 unmodified lines237238239240241242243244245246247248249250251252253254773 unmodified lines1028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110743 unmodified lines1151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124225 unmodified lines_hybrid_search = HybridSearch(_bm25_index, _vector_index, None, None)_index_persistence = None_stream_broadcaster = None # Callable: (payload) -> None_dedup_locks: Dict[str, threading.Lock] = {} # per-(folder, agent) write locks_dedup_locks_meta = threading.Lock() # protects _dedup_locks dict itself# KV scope registry β folder-based memory modelclass KV:25 unmodified linessafe_agent = agent_id.strip()return f"mem:foldermeta:{safe_path}:{safe_agent}"@staticmethoddef obs_dedup(folder_path: str, agent_id: str) -> str:"""Deduplication index scope for (folder, agent) pairs.Key = SHA-256 fingerprint hex of normalized text.Value = {"obsId": str, "timestamp": str}"""safe_path = folder_path.replace("\\", "/").strip("/")safe_agent = agent_id.strip()return f"mem:obs_dedup:{safe_path}:{safe_agent}"# ---- Global / shared scopes (kept) ----# Long-term memories β unchanged from previous implementation.162 unmodified linesreturn sanitizeddef _get_dedup_lock(folder_path: str, agent_id: str) -> threading.Lock:"""Return a per-(folder_path, agent_id) Lock, creating it if necessary.Uses _dedup_locks_meta to protect concurrent creation of new lock entries."""key = f"{folder_path}:{agent_id}"with _dedup_locks_meta:if key not in _dedup_locks:_dedup_locks[key] = threading.Lock()return _dedup_locks[key]def auto_complete_old_active_sessions(kv: StateKV, current_session_id: str, project: Optional[str] = None, agent_id: Optional[str] = None) -> int:sessions = kv.list(KV.sessions)count = 0773 unmodified linessafe_text = strip_private_data(text_raw)safe_text = safe_text[:4000]# 3a. Deduplication check β compute fingerprint over normalized text (REQ-DEDUP)_dedup_fp = hashlib.sha256(safe_text[:4000].strip().lower().encode("utf-8")).hexdigest()_dedup_lock = _get_dedup_lock(folder_path, agent_id)_dedup_lock.acquire()try:_existing_dedup = 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}# 10. Enforce MAX_OBS_PER_FOLDER cap before writing (REQ-015)max_obs = int(os.getenv("MAX_OBS_PER_FOLDER", "2000"))if max_obs > 0:existing_obs = kv.list(KV.folder_obs(folder_path, agent_id))if len(existing_obs) >= max_obs:raise ValueError(f"Folder observation limit reached ({max_obs})")# 4. Generate obs_id (REQ-010)obs_id = generate_id("fobs")# 5. Determine optional fieldsobs_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 = 5else:try:importance = max(1, min(10, int(raw_importance)))except (TypeError, ValueError):importance = 5# 5. Build FolderObservation dict (REQ-003)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,}# 6. Write observation to KV (REQ-001)obs_scope = KV.folder_obs(folder_path, agent_id)kv.set(obs_scope, obs_id, obs)# Write coordinate lookup mappingkv.set(KV.obs_lookup, obs_id, {"folderPath": folder_path,"agentId": agent_id,})# Write dedup index entry β inside lock so check+write is atomic (REQ-DEDUP)kv.set(KV.obs_dedup(folder_path, agent_id), _dedup_fp, {"obsId": obs_id, "timestamp": timestamp})finally:_dedup_lock.release()# 7. Upsert folder metadata (REQ-005)meta_scope = KV.folder_meta(folder_path, agent_id)43 unmodified linesreturn {"observationId": obs_id}# =====================================================================# Folder Deduplication (dedup_folder_observations)# =====================================================================def dedup_folder_observations(kv: StateKV,folder_path_raw: Optional[str],agent_id_raw: Optional[str],) -> Dict[str, Any]:"""Remove duplicate observations from one or all (folder, agent) pairs.For each pair, groups observations by SHA-256 fingerprint of their normalizedtext, keeps the earliest observation per group, and deletes the rest.Also rebuilds the dedup index for each processed pair.Args:folder_path_raw: folder path to deduplicate; None = all pairs.agent_id_raw: agent ID to deduplicate; None = all pairs.Returns:{"deduplicated": <count>, "pairs_processed": <n>, "kept": <count>}"""# Determine which pairs to processif 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 kv.list(KV.folders)if e.get("folderPath") and e.get("agentId")]total_removed = 0total_kept = 0for pair in pairs:fp = pair["folderPath"]aid = pair["agentId"]all_obs = kv.list(KV.folder_obs(fp, aid))# Group by fingerprint, keeping earliest by timestampfingerprint_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] = obselse:# Keep the one with the earlier timestampexisting_ts = fingerprint_map[fp_hash].get("timestamp", "")this_ts = obs.get("timestamp", "")if this_ts < existing_ts:# This one is older β demote the previously-kept oneduplicates.append(fingerprint_map[fp_hash]["id"])fingerprint_map[fp_hash] = obselse:duplicates.append(obs["id"])if duplicates:forget(kv, {"folderPath": fp, "agentId": aid, "observationIds": duplicates})total_removed += len(duplicates)total_kept += len(fingerprint_map)# Rebuild the dedup index for this pair from scratchdedup_scope = KV.obs_dedup(fp, aid)# Clear existing dedup entries by re-writing from surviving observationsfor fp_hash, obs in fingerprint_map.items():kv.set(dedup_scope, fp_hash, {"obsId": obs["id"], "timestamp": obs.get("timestamp", "")})print(f"[dedup] Processed {len(pairs)} pair(s): removed {total_removed}, kept {total_kept}")return {"success": True,"deduplicated": total_removed,"pairs_processed": len(pairs),"kept": total_kept,}# =====================================================================# Folder-Based Search (folder_search)# =====================================================================
216 unmodified lines217218219220221222201 unmodified lines424425426427428429216 unmodified lines},},},]return jsonify({"tools": tools}), 200201 unmodified lines)text_out = json.dumps(res, indent=2)else:return jsonify({"error": f"unknown tool: {name}"}), 400216 unmodified lines217218219220221222223224225226227228229230231232233201 unmodified lines435436437438439440441442443444445446447448216 unmodified lines},},},{"name": "memory_dedup","description": "Remove duplicate observations from a (folderPath, agentId) pair or all pairs. Keeps the earliest observation per unique text fingerprint.","inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Folder path to deduplicate (optional β omit for all pairs)"},"agentId": {"type": "string", "description": "Agent ID to deduplicate (optional β omit for all pairs)"},},},},]return jsonify({"tools": tools}), 200201 unmodified lines)text_out = json.dumps(res, indent=2)elif name == "memory_dedup":res = functions.dedup_folder_observations(kv,args.get("folderPath") or None,args.get("agentId") or None,)text_out = json.dumps(res, indent=2)else:return jsonify({"error": f"unknown tool: {name}"}), 400
237 unmodified lines238239240241242243237 unmodified linesreturn jsonify({"success": True, "message": "Session model is now folder-based."}), 200# ---------------------------------------------------------------------------# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------237 unmodified lines238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271237 unmodified linesreturn jsonify({"success": True, "message": "Session model is now folder-based."}), 200# ---------------------------------------------------------------------------# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentmemory/folder/dedup", methods=["POST"])def api_folder_dedup():"""POST /agentmemory/folder/dedup β remove duplicate observations.Body (both optional):folderPath: str β deduplicate only this folder pairagentId: str β deduplicate only this agentIf both are omitted all folder pairs are processed.Returns: {"success": bool, "deduplicated": int, "pairs_processed": int, "kept": int}"""auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath") or Noneagent_id = body.get("agentId") or Noneres = functions.dedup_folder_observations(_get_kv(), folder_path, agent_id)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400# ---------------------------------------------------------------------------# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------
30 unmodified lines31323334353630 unmodified linessafe_agent = agent_id.strip()return f"mem:foldermeta:{safe_path}:{safe_agent}"# ---- Global / shared scopes (kept) ----# Long-term memories β unchanged from previous implementation.30 unmodified lines3132333435363738394041424344454630 unmodified linessafe_agent = agent_id.strip()return f"mem:foldermeta:{safe_path}:{safe_agent}"@staticmethoddef obs_dedup(folder_path: str, agent_id: str) -> str:"""Deduplication index scope for (folder, agent) pairs.Key = SHA-256 fingerprint hex of normalized text.Value = {"obsId": str, "timestamp": str}"""safe_path = folder_path.replace("\\", "/").strip("/")safe_agent = agent_id.strip()return f"mem:obs_dedup:{safe_path}:{safe_agent}"# ---- Global / shared scopes (kept) ----# Long-term memories β unchanged from previous implementation.
1731 unmodified lines173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901625 unmodified lines341634173418341934203421279 unmodified lines3701370237033704370537063707370837093710371137121731 unmodified lines});}async function loadFolderDetail(folderPath, agentId) {var el = document.getElementById('view-folders');if (!el) return;el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';try {var params = 'folderPath=' + encodeURIComponent(folderPath) + '&agentId=' + encodeURIComponent(agentId);var result = await apiFetchRaw('/agentmemory/folder/observations?' + params);var obs = (result && result.observations) || [];var html = '<div style="padding:20px 24px;">';html += '<div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">';html += '<button onclick="loadFolders()" style="background:none;border:1px solid var(--border-light);padding:6px 14px;cursor:pointer;font-family:var(--font-ui);font-size:12px;border-radius:3px;">← Back</button>';html += '<span style="font-family:var(--font-mono);font-size:13px;color:var(--ink);">' + esc(folderPath) + '</span>';html += '<span style="background:var(--bg-inset);padding:2px 8px;border-radius:3px;font-size:11px;font-weight:600;">' + esc(agentId) + '</span>';html += '<span style="margin-left:auto;font-size:12px;color:var(--ink-muted);">' + obs.length + ' observations</span>';html += '</div>';if (obs.length === 0) {html += '<div class="empty-state"><p>No observations found.</p></div>';} else {obs.forEach(function(o) {var ts = o.timestamp ? new Date(o.timestamp).toLocaleString() : '';var typeColor = {'file_edit':'var(--blue)','command_run':'var(--orange)','search':'var(--green)','error':'var(--red)','conversation':'var(--purple)'}[o.type] || 'var(--ink-muted)';html += '<div style="border:1px solid var(--border-light);border-radius:4px;padding:14px 16px;margin-bottom:10px;background:var(--bg);">';html += '<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">';html += '<span style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:' + typeColor + ';background:var(--bg-subtle);padding:2px 7px;border-radius:3px;">' + esc(o.type || 'other') + '</span>';html += '<span style="font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);">' + esc(ts) + '</span>';html += '</div>';if (o.title) html += '<div style="font-weight:600;font-size:14px;color:var(--ink);margin-bottom:4px;">' + esc(o.title) + '</div>';if (o.text) html += '<div style="font-size:13px;color:var(--ink-secondary);line-height:1.5;white-space:pre-wrap;">' + esc(o.text.length > 300 ? o.text.slice(0,300)+'\u2026' : o.text) + '</div>';html += '</div>';});}html += '<div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--border-light);">';html += '<button onclick="deleteFolderMemory(\'' + esc(folderPath).replace(/'/g,"\\'") + '\',\'' + esc(agentId).replace(/'/g,"\\'") + '\')" style="background:var(--accent);color:white;border:none;padding:8px 18px;cursor:pointer;font-family:var(--font-ui);font-size:13px;border-radius:3px;">Delete folder memory</button>';html += '</div></div>';el.innerHTML = html;} catch(err) {el.innerHTML = '<div style="padding:20px;"><button onclick="loadFolders()" style="background:none;border:1px solid var(--border-light);padding:6px 14px;cursor:pointer;">← Back</button><div style="margin-top:16px;color:var(--accent);">Error: ' + esc(String(err)) + '</div></div>';}}async function deleteFolderMemory(folderPath, agentId) {if (!confirm('Delete all observations for ' + folderPath + ' / ' + agentId + '?')) return;try {await apiFetchRaw('/agentmemory/forget', { method: 'POST', body: JSON.stringify({ folderPath: folderPath, agentId: agentId }) });loadFolders();} catch(err) {alert('Delete failed: ' + String(err));}}async function apiFetchRaw(path, opts) {opts = opts || {};var headers = Object.assign({ 'Content-Type': 'application/json' }, opts.headers || {});1625 unmodified linesif (memoryId) confirmDeleteMemory(memoryId);return;}if (action === 'save-viewer-token') {var tokenInput = document.getElementById('viewer-auth-token');var token = tokenInput ? tokenInput.value.trim() : '';279 unmodified linesbtn.textContent = 'Running...';btn.disabled = true;try {var result = await apiFetchRaw('/agentmemory/mcp/tools', {method: 'POST',body: JSON.stringify({ name: name, arguments: args })});var text = await result.text();var ok = result.ok;respEl.textContent = text;respEl.className = ok ? '' : 'error';respEl.style.display = '';1731 unmodified lines17321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241625 unmodified lines35503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605279 unmodified lines3885388638873888388938903891389238933894389538963897389838993900390139021731 unmodified lines});}// Per-folder-detail state for bulk selectionvar _folderDetailFp = '';var _folderDetailAid = '';var _selectedObsIds = new Set();async function loadFolderDetail(folderPath, agentId) {var el = document.getElementById('view-folders');if (!el) return;_folderDetailFp = folderPath;_folderDetailAid = agentId;_selectedObsIds = new Set();el.innerHTML = '<div style="padding:24px;"><div class="skeleton skeleton-card"></div><div class="skeleton skeleton-card"></div></div>';try {var qp = 'folderPath=' + encodeURIComponent(folderPath) + '&agentId=' + encodeURIComponent(agentId);var result = await apiFetchRaw('/agentmemory/folder/observations?' + qp);var obs = (result && result.observations) || [];var html = '<div id="folder-detail-root" style="padding:20px 24px;">';// ββ Header row ββββββββββββββββββββββββββββββββββββββββββββββββββhtml += '<div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;flex-wrap:wrap;">';html += '<button class="btn" data-action="back-to-folders">← Back</button>';html += '<span style="font-family:var(--font-mono);font-size:13px;color:var(--ink);">' + esc(folderPath) + '</span>';html += '<span style="background:var(--bg-inset);padding:2px 8px;border-radius:3px;font-size:11px;font-weight:600;">' + esc(agentId) + '</span>';html += '<span style="font-size:12px;color:var(--ink-muted);">' + obs.length + ' observation' + (obs.length !== 1 ? 's' : '') + '</span>';html += '<span style="flex:1;"></span>';html += '<button class="btn btn-danger" data-action="delete-folder" data-folder-path="' + esc(folderPath) + '" data-agent-id="' + esc(agentId) + '">Delete folder</button>';html += '</div>';if (obs.length === 0) {html += '<div class="empty-state"><div class="empty-icon">📋</div><p>No observations found.</p></div>';} else {// ββ Bulk-delete toolbar βββββββββββββββββββββββββββββββββββββββββhtml += '<div id="obs-bulk-toolbar" style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding:10px 14px;background:var(--bg-alt);border:1px solid var(--border-light);">';html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-family:var(--font-ui);font-size:12px;">';html += '<input type="checkbox" id="obs-select-all" style="accent-color:var(--ink);"> Select all</label>';html += '<button class="btn btn-danger" id="obs-delete-selected-btn" data-action="delete-obs-selected" disabled style="font-size:11px;padding:4px 12px;">Delete selected (0)</button>';html += '<button class="btn" data-action="run-dedup" data-folder-path="' + esc(folderPath) + '" data-agent-id="' + esc(agentId) + '" style="font-size:11px;padding:4px 12px;" title="Remove duplicate observations automatically">✨ Dedup</button>';html += '</div>';// ββ Observation cards βββββββββββββββββββββββββββββββββββββββββββhtml += '<div id="obs-list">';obs.forEach(function(o) {var ts = o.timestamp ? new Date(o.timestamp).toLocaleString() : '';var typeColor = {'file_edit':'var(--blue)','command_run':'var(--orange)','search':'var(--green)','error':'var(--red)','conversation':'var(--purple)'}[o.type] || 'var(--ink-muted)';html += '<div class="obs-detail-card" data-obs-id="' + esc(o.id) + '" style="border:1px solid var(--border-light);border-radius:4px;padding:12px 16px;margin-bottom:8px;background:var(--bg);display:flex;gap:10px;align-items:flex-start;">';// checkboxhtml += '<label style="padding-top:2px;cursor:pointer;flex-shrink:0;">';html += '<input type="checkbox" class="obs-checkbox" data-obs-id="' + esc(o.id) + '" style="accent-color:var(--ink);">';html += '</label>';// contenthtml += '<div style="flex:1;min-width:0;">';html += '<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;flex-wrap:wrap;">';html += '<span style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:' + typeColor + ';background:var(--bg-subtle);padding:2px 7px;border-radius:3px;">' + esc(o.type || 'other') + '</span>';html += '<span style="font-size:11px;color:var(--ink-muted);font-family:var(--font-mono);">' + esc(ts) + '</span>';html += '<span style="flex:1;"></span>';html += '<button class="btn btn-danger" data-action="delete-obs" data-obs-id="' + esc(o.id) + '" data-folder-path="' + esc(folderPath) + '" data-agent-id="' + esc(agentId) + '" style="font-size:9px;padding:2px 8px;">Delete</button>';html += '</div>';if (o.title) html += '<div style="font-weight:600;font-size:14px;color:var(--ink);margin-bottom:4px;">' + esc(o.title) + '</div>';if (o.text) html += '<div style="font-size:13px;color:var(--ink-secondary);line-height:1.5;white-space:pre-wrap;">' + esc(o.text.length > 300 ? o.text.slice(0, 300) + '\u2026' : o.text) + '</div>';html += '</div>';html += '</div>';});html += '</div>'; // #obs-list}html += '</div>'; // #folder-detail-rootel.innerHTML = html;// Wire up checkbox logic after innerHTML is set_wireFolderDetailCheckboxes();} catch(err) {el.innerHTML = '<div style="padding:20px;">' +'<button class="btn" data-action="back-to-folders">← Back</button>' +'<div style="margin-top:16px;color:var(--accent);">Error loading observations: ' + esc(String(err)) + '</div></div>';}}function _wireFolderDetailCheckboxes() {var selectAll = document.getElementById('obs-select-all');var deleteBtn = document.getElementById('obs-delete-selected-btn');if (!selectAll || !deleteBtn) return;function updateDeleteBtn() {deleteBtn.textContent = 'Delete selected (' + _selectedObsIds.size + ')';deleteBtn.disabled = _selectedObsIds.size === 0;}selectAll.addEventListener('change', function() {document.querySelectorAll('.obs-checkbox').forEach(function(cb) {cb.checked = selectAll.checked;var oid = cb.getAttribute('data-obs-id');if (selectAll.checked) { _selectedObsIds.add(oid); }else { _selectedObsIds.delete(oid); }});updateDeleteBtn();});document.querySelectorAll('.obs-checkbox').forEach(function(cb) {cb.addEventListener('change', function() {var oid = cb.getAttribute('data-obs-id');if (cb.checked) { _selectedObsIds.add(oid); }else { _selectedObsIds.delete(oid); }// Update select-all indeterminate statevar total = document.querySelectorAll('.obs-checkbox').length;selectAll.indeterminate = _selectedObsIds.size > 0 && _selectedObsIds.size < total;selectAll.checked = _selectedObsIds.size === total;updateDeleteBtn();});});}function confirmDeleteFolder(fp, aid) {var modal = document.getElementById('modal');var overlay = document.getElementById('modal-overlay');modal.innerHTML = '<h3>Delete Folder Memory</h3>' +'<p>Delete <strong>all observations</strong> for<br><code style="font-size:11px;">' + esc(fp) + '</code> / <code style="font-size:11px;">' + esc(aid) + '</code>?<br><br>This cannot be undone.</p>' +'<div class="modal-actions">' +'<button class="btn" data-action="close-modal">Cancel</button>' +'<button class="btn btn-danger" data-action="confirm-delete-folder" data-folder-path="' + esc(fp) + '" data-agent-id="' + esc(aid) + '">Delete all</button>' +'</div>';overlay.classList.add('open');}async function execDeleteFolder(fp, aid) {closeModal();try {await apiPost('forget', { folderPath: fp, agentId: aid });loadFolders();} catch(err) {alert('Delete failed: ' + String(err));}}function confirmDeleteObs(obsId, fp, aid) {var modal = document.getElementById('modal');var overlay = document.getElementById('modal-overlay');modal.innerHTML = '<h3>Delete Observation</h3>' +'<p>Delete this observation? This cannot be undone.</p>' +'<div class="modal-actions">' +'<button class="btn" data-action="close-modal">Cancel</button>' +'<button class="btn btn-danger" data-action="confirm-delete-obs" data-obs-id="' + esc(obsId) + '" data-folder-path="' + esc(fp) + '" data-agent-id="' + esc(aid) + '">Delete</button>' +'</div>';overlay.classList.add('open');}async function execDeleteObs(obsId, fp, aid) {closeModal();try {await apiPost('forget', { folderPath: fp, agentId: aid, observationIds: [obsId] });// Remove card from DOM without reloadvar card = document.querySelector('.obs-detail-card[data-obs-id="' + obsId + '"]');if (card) card.remove();_selectedObsIds.delete(obsId);// Update count in headervar remaining = document.querySelectorAll('.obs-detail-card').length;var countEl = document.querySelector('#folder-detail-root span[style*="ink-muted"]');if (countEl) countEl.textContent = remaining + ' observation' + (remaining !== 1 ? 's' : '');} catch(err) {alert('Delete failed: ' + String(err));}}async function execDeleteObsSelected() {var ids = Array.from(_selectedObsIds);if (!ids.length) return;closeModal();try {await apiPost('forget', { folderPath: _folderDetailFp, agentId: _folderDetailAid, observationIds: ids });ids.forEach(function(oid) {var card = document.querySelector('.obs-detail-card[data-obs-id="' + oid + '"]');if (card) card.remove();_selectedObsIds.delete(oid);});var remaining = document.querySelectorAll('.obs-detail-card').length;var countEl = document.querySelector('#folder-detail-root span[style*="ink-muted"]');if (countEl) countEl.textContent = remaining + ' observation' + (remaining !== 1 ? 's' : '');var deleteBtn = document.getElementById('obs-delete-selected-btn');if (deleteBtn) { deleteBtn.textContent = 'Delete selected (0)'; deleteBtn.disabled = true; }var selectAll = document.getElementById('obs-select-all');if (selectAll) { selectAll.checked = false; selectAll.indeterminate = false; }} catch(err) {alert('Bulk delete failed: ' + String(err));}}async function apiFetchRaw(path, opts) {opts = opts || {};var headers = Object.assign({ 'Content-Type': 'application/json' }, opts.headers || {});1625 unmodified linesif (memoryId) confirmDeleteMemory(memoryId);return;}if (action === 'back-to-folders') {loadFolders();return;}if (action === 'delete-folder') {var fp = target.getAttribute('data-folder-path');var aid = target.getAttribute('data-agent-id');if (fp && aid) confirmDeleteFolder(fp, aid);return;}if (action === 'confirm-delete-folder') {var fp = target.getAttribute('data-folder-path');var aid = target.getAttribute('data-agent-id');if (fp && aid) execDeleteFolder(fp, aid);return;}if (action === 'delete-obs') {var obsId = target.getAttribute('data-obs-id');var fp = target.getAttribute('data-folder-path');var aid = target.getAttribute('data-agent-id');if (obsId && fp && aid) confirmDeleteObs(obsId, fp, aid);return;}if (action === 'confirm-delete-obs') {var obsId = target.getAttribute('data-obs-id');var fp = target.getAttribute('data-folder-path');var aid = target.getAttribute('data-agent-id');if (obsId && fp && aid) execDeleteObs(obsId, fp, aid);return;}if (action === 'delete-obs-selected') {if (_selectedObsIds.size > 0) execDeleteObsSelected();return;}if (action === 'run-dedup') {var fp = target.getAttribute('data-folder-path');var aid = target.getAttribute('data-agent-id');if (!fp || !aid) return;target.textContent = 'β³ Runningβ¦';target.disabled = true;apiPost('folder/dedup', { folderPath: fp, agentId: aid }).then(function(res) {var removed = res && res.deduplicated != null ? res.deduplicated : '?';target.textContent = 'β Removed ' + removed + ' dupes';setTimeout(function() { loadFolderDetail(fp, aid); }, 1200);}).catch(function() {target.textContent = 'β Failed';target.disabled = false;});return;}if (action === 'save-viewer-token') {var tokenInput = document.getElementById('viewer-auth-token');var token = tokenInput ? tokenInput.value.trim() : '';279 unmodified linesbtn.textContent = 'Running...';btn.disabled = true;try {// Use raw fetch so we can call .text() on the Response β apiFetchRaw// already parses JSON and returns a plain object, not a Response.var _toolToken = getViewerToken();var _toolHeaders = { 'Content-Type': 'application/json' };if (_toolToken) _toolHeaders['Authorization'] = 'Bearer ' + _toolToken;var rawRes = await fetch(REST + '/agentmemory/mcp/tools', {method: 'POST',headers: _toolHeaders,body: JSON.stringify({ name: name, arguments: args })});var text = await rawRes.text();var ok = rawRes.ok;respEl.textContent = text;respEl.className = ok ? '' : 'error';respEl.style.display = '';