This commit is contained in:
Timothy Jaeryang Baek
2026-06-24 14:41:34 +02:00
Unverified
parent d1abb32ae2
commit 9bbddfe971
8 changed files with 1336 additions and 30 deletions
+73 -3
View File
@@ -2,9 +2,16 @@ import { fetchJSON, jsonBody } from '$lib/apis';
export type MemoryScope = 'user' | 'workspace';
export type MemoryOperation = {
action: 'add' | 'replace' | 'remove';
action: 'add' | 'replace' | 'remove' | 'link' | 'move' | 'split' | 'merge';
content?: string;
old_text?: string;
path?: string;
new_path?: string;
source_path?: string;
target_path?: string;
heading?: string;
memory_id?: string;
link?: string;
};
export type MemorySettings = {
@@ -18,8 +25,28 @@ export type MemorySettings = {
export type MemoryState = {
settings: MemorySettings;
user: { entries: string[]; usage: string; path: string };
workspace: { entries: string[]; usage: string; path: string };
user: { entries: string[]; usage: string; path: string; root: string };
workspace: { entries: string[]; usage: string; path: string; root: string };
};
export type MemorySnippet = {
scope: MemoryScope;
path: string;
heading: string;
memory_id: string;
snippet: string;
links: string[];
reason: string;
};
export type MemoryFile = {
scope: MemoryScope;
path: string;
size: number;
modified_at: number;
headings: string[];
baseline: boolean;
trash: boolean;
};
export const getMemory = (workspace: string) =>
@@ -38,3 +65,46 @@ export const updateMemory = (
operations: MemoryOperation[]
) =>
fetchJSON('/api/memory/update', jsonBody({ scope, workspace, operations }));
export const searchMemory = (body: {
query?: string;
scope?: MemoryScope | 'both';
workspace?: string;
path?: string | null;
memory_id?: string | null;
expand_links?: boolean;
include_trash?: boolean;
limit?: number;
}) => fetchJSON<{ results: MemorySnippet[]; count: number }>('/api/memory/search', jsonBody(body));
export const listMemoryFiles = (
workspace: string,
options: {
scope?: MemoryScope | 'both';
q?: string;
limit?: number;
include_trash?: boolean;
} = {}
) => {
const params = new URLSearchParams({
workspace: workspace || '',
scope: options.scope || 'both',
q: options.q || '',
limit: String(options.limit || 100),
include_trash: String(Boolean(options.include_trash))
});
return fetchJSON<{ files: MemoryFile[]; count: number }>(`/api/memory/files?${params}`);
};
export const getMemoryFile = (workspace: string, scope: MemoryScope, path: string) => {
const params = new URLSearchParams({ workspace: workspace || '', scope, path });
return fetchJSON<{ scope: MemoryScope; path: string; content: string; sections: unknown[] }>(
`/api/memory/file?${params}`
);
};
export const reviewMemory = (workspace: string) =>
fetchJSON<{ changed: unknown[]; skipped: unknown[] }>(
'/api/memory/review',
jsonBody({ workspace })
);
@@ -59,7 +59,6 @@
toast.error('Failed to update memory');
}
}
</script>
<div class="flex flex-col h-full">
@@ -146,7 +145,6 @@
<p class="text-[11px] text-gray-400 dark:text-gray-600 -mt-1">{userUsage}</p>
</div>
{/if}
{/if}
</div>
+1 -1
View File
@@ -342,7 +342,7 @@
} else if (workspacePath && workspacePath === lastLoadedPath) {
// Same workspace — process intents immediately
processIntentParams();
} else if (!wsPath) {
} else if (!workspacePath) {
lastLoadedPath = null;
currentWorkspace.set(null);
processIntentParams();
+80
View File
@@ -9,9 +9,13 @@ from pydantic import BaseModel
from cptr.utils.config import AuthResult, check_access
from cptr.utils.memory import (
list_memory_files_state,
remember,
read_memory_file_state,
read_memory_state,
review_memory_vault,
save_memory_settings,
search_memory_state,
)
router = APIRouter(prefix="/api/memory", tags=["memory"])
@@ -48,6 +52,21 @@ class MemoryUpdateRequest(BaseModel):
workspace: str = ""
class MemorySearchRequest(BaseModel):
query: str = ""
scope: Literal["user", "workspace", "both"] = "both"
workspace: str = ""
path: str | None = None
memory_id: str | None = None
expand_links: bool = False
include_trash: bool = False
limit: int = 8
class MemoryReviewRequest(BaseModel):
workspace: str = ""
@router.get("")
async def get_memory(request: Request, workspace: str = Query("")):
user_id = _get_user(request)
@@ -69,3 +88,64 @@ async def update_memory(body: MemoryUpdateRequest, request: Request):
scope=body.scope,
operations=body.operations,
)
@router.post("/search")
async def search_memory(body: MemorySearchRequest, request: Request):
user_id = _get_user(request)
return await search_memory_state(
user_id=user_id,
workspace=body.workspace,
query=body.query,
scope=body.scope,
path=body.path,
memory_id=body.memory_id,
expand_links=body.expand_links,
include_trash=body.include_trash,
limit=body.limit,
)
@router.get("/files")
async def list_memory_files(
request: Request,
workspace: str = Query(""),
scope: Literal["user", "workspace", "both"] = Query("both"),
q: str = Query(""),
limit: int = Query(100),
include_trash: bool = Query(False),
):
user_id = _get_user(request)
return await list_memory_files_state(
user_id=user_id,
workspace=workspace,
scope=scope,
query=q,
limit=limit,
include_trash=include_trash,
)
@router.get("/file")
async def get_memory_file(
request: Request,
workspace: str = Query(""),
scope: Literal["user", "workspace"] = Query("user"),
path: str = Query(...),
):
user_id = _get_user(request)
try:
return await read_memory_file_state(
user_id=user_id,
workspace=workspace,
scope=scope,
path=path,
)
except ValueError as exc:
raise HTTPException(404, str(exc)) from exc
@router.post("/review")
async def review_memory(body: MemoryReviewRequest, request: Request):
user_id = _get_user(request)
return await review_memory_vault(user_id, body.workspace)
+54 -5
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
import json
import logging
import re
import uuid
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
@@ -102,6 +103,33 @@ def get_active_chat_ids() -> set[str]:
return {cid for mid, cid in _task_chat.items() if mid in _tasks and not _tasks[mid].done()}
def _plain_message_text(content) -> str:
if isinstance(content, list):
return " ".join(
str(block.get("text", ""))
for block in content
if isinstance(block, dict) and block.get("type") == "text"
)
return str(content or "")
def _memory_recall_inputs(
messages: list[dict],
regeneration_prompt: str | None = None,
) -> tuple[str, list[str]]:
current_message = regeneration_prompt or ""
if not current_message:
for message in reversed(messages):
if message.get("role") == "user":
current_message = _plain_message_text(message.get("content"))
break
mentioned_files = re.findall(
r"(?:^|\s)([./~]?[A-Za-z0-9_.\-/]+(?:\.[A-Za-z0-9_]+))",
current_message,
)[:12]
return current_message, mentioned_files
# ── Pending input processing ────────────────────────────────
@@ -1083,6 +1111,11 @@ async def run_chat_task(
# Load existing state so continuations don't overwrite previous output
msg = await ChatMessage.get_by_id(message_id)
summary_message_id = message_id
if msg and msg.parent_id:
parent_msg = await ChatMessage.get_by_id(msg.parent_id)
if parent_msg and parent_msg.role == "user":
summary_message_id = parent_msg.id
content = (msg.content or "") if msg else ""
output_items: list[dict] = list(msg.output or []) if msg else []
text_buffer = "" # Accumulates text between tool calls
@@ -1150,8 +1183,16 @@ async def run_chat_task(
chat_obj = await Chat.get_by_id(chat_id)
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
configured_model = (msg.model if msg else None) or model
system = await _load_system_prompt(workspace, model, user_id=user_id)
messages, loaded_summary = await _load_message_history(chat_id, message_id)
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
system = await _load_system_prompt(
workspace,
model,
user_id=user_id,
current_message=memory_message,
recent_messages=messages,
mentioned_files=memory_files,
)
if loaded_summary:
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
if regeneration_prompt:
@@ -1261,12 +1302,19 @@ async def run_chat_task(
api_type=api_type,
)
# Store on the current message — this IS the cutoff
await ChatMessage.update(message_id, chat_summary=summary)
await ChatMessage.update(summary_message_id, chat_summary=summary)
loaded_summary = summary
# Append summary to system prompt (works for all providers)
system = await _load_system_prompt(workspace, model, user_id=user_id)
memory_message, memory_files = _memory_recall_inputs(keep_zone, regeneration_prompt)
system = await _load_system_prompt(
workspace,
model,
user_id=user_id,
current_message=memory_message,
recent_messages=keep_zone,
mentioned_files=memory_files,
)
system += f"\n\n[CONVERSATION SUMMARY]\n{summary}"
# Re-inject attached skills after compaction (protect from pruning)
if attached_skill_ids:
@@ -1283,8 +1331,9 @@ async def run_chat_task(
new_messages_since = 0
logger.info(
"[task %s] compacted: dropped %d msgs, kept %d, summary=%d chars",
"[task %s] compacted: checkpoint=%s dropped %d msgs, kept %d, summary=%d chars",
message_id[:8],
summary_message_id[:8],
len(drop_zone),
len(keep_zone),
len(summary),
+1108 -15
View File
File diff suppressed because it is too large Load Diff
+15 -2
View File
@@ -248,7 +248,14 @@ def _build_template_variables(workspace: str, model: str = "", memory: str = "")
}
async def load_system_prompt(workspace: str, model: str = "", user_id: str | None = None) -> str:
async def load_system_prompt(
workspace: str,
model: str = "",
user_id: str | None = None,
current_message: str = "",
recent_messages: list[dict] | None = None,
mentioned_files: list[str] | None = None,
) -> str:
"""Load and render the system prompt for a workspace/model.
Resolution order:
@@ -289,7 +296,13 @@ async def load_system_prompt(workspace: str, model: str = "", user_id: str | Non
try:
from cptr.utils.memory import build_memory_prompt
memory = await build_memory_prompt(user_id, workspace)
memory = await build_memory_prompt(
user_id,
workspace,
current_message=current_message,
recent_messages=recent_messages or [],
mentioned_files=mentioned_files or [],
)
except Exception:
logger.debug("[memory] Failed to load managed memory", exc_info=True)
+5 -2
View File
@@ -1547,9 +1547,12 @@ async def update_memory(
Use user memory for stable preferences, communication style, and cross-workspace
facts. Use workspace memory for repo-specific conventions, verification
commands, architecture notes, and local tool quirks. Make all changes in one
operations array so removals/replacements and additions apply atomically.
operations array so removals/replacements and additions apply atomically. Simple
add/replace/remove operations update the baseline USER.md/WORKSPACE.md bullet list.
Operations with path, heading, memory_id, link, move, split, or merge edit the
Markdown memory vault.
:param scope: "user" for global per-user memory, or "workspace" for the current workspace only.
:param operations: Batch of {action, content?, old_text?}; action is add, replace, or remove.
:param operations: Batch of memory operations. Supported actions are add, replace, remove, link, move, split, and merge.
"""
from cptr.utils.memory import get_memory_settings, remember