JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:当记忆文件JIUWENCLAW.md大于阈值(40000字符)时,TUI首页和/status命令告警
openJiuwen-bot5bffd00635c1
diff --git a/jiuwenclaw/agents/harness/common/memory_rpc.py b/jiuwenclaw/agents/harness/common/memory_rpc.pyindex 0faf976257..6643e44fd7 100644--- a/jiuwenclaw/agents/harness/common/memory_rpc.py+++ b/jiuwenclaw/agents/harness/common/memory_rpc.py@@ -18,7 +18,9 @@ from jiuwenclaw.agents.harness.common.memory.external_memory_config import (get_external_memory_config,)from jiuwenclaw.agents.harness.common.rails.project_memory import (+ clear_project_memory_cache,discover_and_load_memory_files,+ get_large_memory_files,)from jiuwenclaw.common.config import get_config@@ -288,16 +290,26 @@ async def handle_memory_status(project_dir = params.get("project_dir")discover_workspace = project_dir or workspace+ clear_project_memory_cache(discover_workspace)project_files = discover_and_load_memory_files(workspace=discover_workspace,target_path=discover_workspace,)total_chars = sum(len(f.content) for f in project_files)+ large_files = get_large_memory_files(project_files)+ logger.info(+ "[memory_rpc] memory.status detailed: workspace=%s project_dir=%s "+ "discover_workspace=%s files=%d large_files=%d",+ workspace, project_dir, discover_workspace,+ len(project_files), len(large_files),+ )result["project_memory"] = {"files_count": len(project_files),"total_chars": total_chars,"max_chars": 60_000,+ "threshold": 40_000,}+ result["large_files"] = large_filesif project_dir:result["project_memory"]["project_dir"] = project_dirdiff --git a/jiuwenclaw/agents/harness/common/rails/project_memory/__init__.py b/jiuwenclaw/agents/harness/common/rails/project_memory/__init__.pyindex 48f5c5ccea..6fb4a6f02f 100644--- a/jiuwenclaw/agents/harness/common/rails/project_memory/__init__.py+++ b/jiuwenclaw/agents/harness/common/rails/project_memory/__init__.py@@ -7,6 +7,7 @@ from jiuwenclaw.agents.harness.common.rails.project_memory.files import (LoadedMemoryFile,MANAGED_MEMORY_FILES,MANAGED_MEMORY_GLOBS,+ MAX_MEMORY_CHARACTER_COUNT,PROJECT_MEMORY_FILES,PROJECT_MEMORY_GLOBS,PROJECT_ROOT_MARKERS,@@ -15,6 +16,7 @@ from jiuwenclaw.agents.harness.common.rails.project_memory.files import (clear_project_memory_cache,discover_and_load_memory_files,find_project_root,+ get_large_memory_files,merge_memory_content,)from jiuwenclaw.agents.harness.common.rails.project_memory.section import (@@ -27,6 +29,8 @@ __all__ = ["LoadedMemoryFile","discover_and_load_memory_files","find_project_root",+ "get_large_memory_files",+ "MAX_MEMORY_CHARACTER_COUNT","merge_memory_content","PROJECT_ROOT_MARKERS","PROJECT_MEMORY_FILES",diff --git a/jiuwenclaw/agents/harness/common/rails/project_memory/files.py b/jiuwenclaw/agents/harness/common/rails/project_memory/files.pyindex 6078bfbc3f..58afe0033d 100644--- a/jiuwenclaw/agents/harness/common/rails/project_memory/files.py+++ b/jiuwenclaw/agents/harness/common/rails/project_memory/files.py@@ -87,6 +87,7 @@ MANAGED_MEMORY_GLOBS: tuple[str, ...] = (ADDITIONAL_DIRECTORIES_ENV = "JIUWENCLAW_ADDITIONAL_DIRECTORIES"DEFAULT_MAX_CHARS = 60_000+MAX_MEMORY_CHARACTER_COUNT = 40_000# Priority: smaller = applied first (later = semantically override).PRIORITY: dict[str, int] = {@@ -366,6 +367,26 @@ def merge_memory_content(return merged+def get_large_memory_files(+ files: Iterable[LoadedMemoryFile],+ *,+ threshold: int = MAX_MEMORY_CHARACTER_COUNT,+) -> list[dict[str, Any]]:+ """Return warning dicts for memory files exceeding per-file character threshold."""+ warnings: list[dict[str, Any]] = []+ for f in files:+ char_count = len(f.content)+ if char_count > threshold:+ warnings.append({+ "path": f.path,+ "kind": f.kind,+ "char_count": char_count,+ "threshold": threshold,+ "message": f"Large {_short(f.path)} ({char_count} chars > {threshold}) will impact performance",+ })+ return warnings++# ---------------------------------------------------------------------------# Internal helpers# ---------------------------------------------------------------------------@@ -935,5 +956,7 @@ __all__ = ["clear_project_memory_cache","discover_and_load_memory_files","find_project_root",+ "get_large_memory_files",+ "MAX_MEMORY_CHARACTER_COUNT","merge_memory_content",]diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex 70a2c07678..f3264e527a 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -106,6 +106,7 @@ export interface AppSnapshot {modelInfo: { provider: string; model: string; version: string };sessionTitle: string;statusLineText: string | null;+ memoryWarnings: { path: string; kind: string; char_count: number; threshold: number; message: string }[];}export class CliPiAppState {@@ -165,6 +166,8 @@ export class CliPiAppState {model: "",version: "",};+ private memoryWarnings: { path: string; kind: string; char_count: number; threshold: number; message: string }[] = [];+ private memoryRefreshTimer: ReturnType<typeof setInterval> | null = null;/** 当 closeUi 中 cancelBeforeExit 调 cancel({showNotice:false}) 时置 true,抑制 chat.interrupt_result 的 UI 通知。 */private suppressInterruptResult = false;/** 本地中断请求标志,cancel() 调用时立即置 true,用于 long-running 命令的中断检测。 */@@ -324,14 +327,16 @@ export class CliPiAppState {this.unlistenFrames?.();this.unlistenFrames = null;this.stopStatusLinePoll();+ this.stopMemoryRefresh();this.wsClient.disconnect();}private async fetchModelInfo(): Promise<void> {try {- const [configPayload, modelsPayload] = await Promise.allSettled([+ const [configPayload, modelsPayload, memoryPayload] = await Promise.allSettled([this.request("config.get", {}),this.request("models.list", {}),+ this.request<Record<string, unknown>>("memory.status", { detailed: true }),]);const config =configPayload.status === "fulfilled" && configPayload.value && typeof configPayload.value === "object"@@ -349,12 +354,48 @@ export class CliPiAppState {model: activeModelName || String(config.model ?? ""),version: String(config.app_version ?? ""),};++ const memoryResult =+ memoryPayload.status === "fulfilled" && memoryPayload.value && typeof memoryPayload.value === "object"+ ? (memoryPayload.value as Record<string, unknown>)+ : {};+ const largeFiles = Array.isArray(memoryResult.large_files)+ ? (memoryResult.large_files as { path: string; kind: string; char_count: number; threshold: number; message: string }[])+ : [];+ this.memoryWarnings = largeFiles;++ this.startMemoryRefresh();this.emitChange();} catch {// ignore error, use defaults}}+ private startMemoryRefresh(): void {+ this.stopMemoryRefresh();+ this.memoryRefreshTimer = setInterval(async () => {+ try {+ const memoryResult = await this.request<Record<string, unknown>>(+ "memory.status", { detailed: true }, 10_000,+ );+ const largeFiles = Array.isArray(memoryResult.large_files)+ ? (memoryResult.large_files as { path: string; kind: string; char_count: number; threshold: number; message: string }[])+ : [];+ this.memoryWarnings = largeFiles;+ this.emitChange();+ } catch {+ // ignore — next interval will retry+ }+ }, 30_000);+ }++ private stopMemoryRefresh(): void {+ if (this.memoryRefreshTimer) {+ clearInterval(this.memoryRefreshTimer);+ this.memoryRefreshTimer = null;+ }+ }+onChange(listener: () => void): () => void {this.listeners.add(listener);return () => {@@ -420,6 +461,7 @@ export class CliPiAppState {modelInfo: this.modelInfo,sessionTitle: this.sessionTitle,statusLineText: this.statusLineText,+ memoryWarnings: [...this.memoryWarnings],};}diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.tsindex 9c2201cbf1..b87ea4f15a 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/status.ts@@ -3,6 +3,14 @@ import { CommandKind, type SlashCommand } from "../types.js";import type { SessionUsageSummary } from "../../../app-state.js";import type { ConfigItemSchema } from "./config.js";+export type MemoryWarning = {+ path: string;+ kind: string;+ char_count: number;+ threshold: number;+ message: string;+};+export type StatusPayload = {version: string;session_id: string;@@ -14,6 +22,7 @@ export type StatusPayload = {mcp_servers: { name: string; enabled: boolean; transport: string }[];config_path: string;settings_sources: string[];+ memory_warnings: MemoryWarning[];};function showOverview(ctx: import("../types.js").CommandContext, payload: StatusPayload): void {@@ -70,6 +79,17 @@ function showOverview(ctx: import("../types.js").CommandContext, payload: Status],}),);++ const warnings = payload.memory_warnings ?? [];+ if (warnings.length > 0) {+ ctx.addItem(+ addInfo(ctx.sessionId, "Memory warnings", "w", {+ view: "kv",+ title: "Status — Memory Warnings",+ items: warnings.map((w) => ({ label: w.kind, value: w.message })),+ }),+ );+ }}function showUsage(ctx: import("../types.js").CommandContext, summary: SessionUsageSummary): void {diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex 841306afa2..9b1eafe850 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -2374,7 +2374,7 @@ export class AppScreen implements Component, Focusable {? this.buildUsageTabItems(): this.buildConfigTabItems(configPayload);- const list = new SelectList(items, Math.min(Math.max(items.length, 1), 10), selectListTheme, {+ const list = new SelectList(items, tab === "status" ? items.length : Math.min(Math.max(items.length, 1), 10), selectListTheme, {minPrimaryColumnWidth: 20,maxPrimaryColumnWidth: 50,});@@ -2423,6 +2423,11 @@ export class AppScreen implements Component, Focusable {}items.push({ value: "__display__", label: `config_path: ${payload.config_path || "unknown"}`, description: "" });+ const warnings = payload.memory_warnings ?? [];+ for (const w of warnings) {+ items.push({ value: "__display__", label: `⚠ memory: ${w.message}`, description: "" });+ }+return items;}diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/transcript-renderer.ts b/jiuwenclaw/channels/tui/frontend/src/ui/transcript-renderer.tsindex 6171dffd52..eb46347caf 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/transcript-renderer.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/transcript-renderer.ts@@ -73,7 +73,7 @@ export function buildTranscriptLines(): string[] {const { entries: displayEntries, latestThinkingId } = selectTranscriptEntries(snapshot);- const allLines: string[] = [...buildWelcomeLines(width, snapshot.connectionStatus, snapshot.modelInfo, snapshot.mode)];+ const allLines: string[] = [...buildWelcomeLines(width, snapshot.connectionStatus, snapshot.modelInfo, snapshot.mode, snapshot.memoryWarnings)];const showPendingInput =typeof pendingInput === "string" &&pendingInput.length > 0 &&diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/welcome.ts b/jiuwenclaw/channels/tui/frontend/src/ui/welcome.tsindex 50df764c7e..629391355c 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/welcome.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/welcome.ts@@ -72,7 +72,8 @@ export function buildWelcomeLines(width: number,connectionStatus: ConnectionStatus,modelInfo: { provider: string; model: string; version: string } = { provider: "", model: "", version: "" },- mode: string = ""+ mode: string = "",+ memoryWarnings: { path: string; kind: string; char_count: number; threshold: number; message: string }[] = [],): string[] {const artWidth = Math.max(...ART_TITLE_RAW.map((line) => visibleWidth(line)));const hint = connectionHint(connectionStatus);@@ -115,6 +116,9 @@ export function buildWelcomeLines(centerLine(cmdBottom, width),...(hint ? [centerLine(chalk.hex("#FFFFFF")(hint), width)] : []),...(rgTip ? [centerLine(chalk.hex("#FFD700")(rgTip), width)] : []),+ ...(memoryWarnings.length > 0+ ? memoryWarnings.map((w) => centerLine(chalk.hex("#FFD700")(`Warning: ${w.message}`), width))+ : []),];}@@ -135,5 +139,8 @@ export function buildWelcomeLines(padToWidth(chalk.hex("#FFFFFF")("└────────────────────────────────────────────────────────────┘"), width),...(hint ? [padToWidth(chalk.hex("#FFFFFF")(hint), width)] : []),...(rgTip ? [padToWidth(chalk.hex("#FFD700")(rgTip), width)] : []),+ ...(memoryWarnings.length > 0+ ? memoryWarnings.map((w) => padToWidth(chalk.hex("#FFD700")(`Warning: ${w.message}`), width))+ : []),];}diff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.pyindex 256386aa19..ab839c5d4e 100644--- a/jiuwenclaw/server/agent_ws_server.py+++ b/jiuwenclaw/server/agent_ws_server.py@@ -2198,6 +2198,37 @@ class AgentWebSocketServer:settings_sources.append(f"env:JIUWENCLAW_CONFIG_DIR={config_dir}")settings_sources.append(config_path)+ # Memory diagnostics — use the actual workspace dir (trusted_dir or cwd),+ # same as ProjectMemoryRail, so we detect JIUWENCLAW.md where /init creates it.+ params = request.params or {}+ workspace_dir = str(params.get("cwd", "") or os.getcwd())+ trusted_dirs = params.get("trusted_dirs")+ if isinstance(trusted_dirs, list) and trusted_dirs:+ workspace_dir = str(trusted_dirs[0])+ try:+ from jiuwenclaw.agents.harness.common.rails.project_memory import (+ clear_project_memory_cache,+ discover_and_load_memory_files,+ get_large_memory_files,+ )+ clear_project_memory_cache(workspace_dir)+ project_files = discover_and_load_memory_files(+ workspace=workspace_dir, target_path=workspace_dir,+ )+ memory_warnings = get_large_memory_files(project_files)+ logger.info(+ "[AgentWebSocketServer] memory diagnostics: "+ "workspace_dir=%s, files=%d, warnings=%d",+ workspace_dir, len(project_files), len(memory_warnings),+ )+ except Exception as exc:+ logger.warning(+ "[AgentWebSocketServer] memory diagnostics failed: "+ "workspace_dir=%s, error=%s",+ workspace_dir, exc,+ )+ memory_warnings = []+resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,@@ -2213,6 +2244,7 @@ class AgentWebSocketServer:"mcp_servers": mcp_summary,"config_path": config_path,"settings_sources": settings_sources,+ "memory_warnings": memory_warnings,},)except Exception as e: # noqa: BLE001