Просмотр исходного кода

feat(agent): 完善工具契约、提示词分层与多用户隔离

- 工具描述/元数据契约化,路由只引用始终注册的 base 工具
- 新增 PromptAssembler/PromptContextMiddleware,稳定提示词与动态公告分离
- 研判/通用 Agent 按用户、案件、会话隔离,修复固定 userId 与跨会话公告
- 产物扫描按用户+会话归属,Python 输出写入 exec-owner
- 删除会话自动取消在途流,补齐记忆缓存/转录清理
- 修复 ServerException.spe 改名后遗留调用
cc 2 недель назад
Родитель
Сommit
d2d206261d
36 измененных файлов с 1659 добавлено и 209 удалено
  1. 56 4
      ai-server/src/main/java/com/zsjz/ai/module/agent/artifact/AgentArtifactScanner.java
  2. 4 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/entity/AgentChatSession.java
  3. 43 14
      ai-server/src/main/java/com/zsjz/ai/module/agent/insight/agent/InsightAgentFactory.java
  4. 12 6
      ai-server/src/main/java/com/zsjz/ai/module/agent/insight/prompt/InsightPromptBuilder.java
  5. 21 8
      ai-server/src/main/java/com/zsjz/ai/module/agent/insight/service/impl/InsightServiceImpl.java
  6. 41 7
      ai-server/src/main/java/com/zsjz/ai/module/agent/middleware/CaseScopeMiddleware.java
  7. 158 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/middleware/PromptContextMiddleware.java
  8. 116 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/prompt/PromptAssembler.java
  9. 65 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/prompt/PromptSection.java
  10. 20 2
      ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonExecutor.java
  11. 10 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentInstancePool.java
  12. 109 75
      ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentService.java
  13. 158 19
      ai-server/src/main/java/com/zsjz/ai/module/agent/service/impl/AgentChatServiceImpl.java
  14. 1 1
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/CallAnalysisTool.java
  15. 2 2
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/FileAnalysisTool.java
  16. 7 7
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PersonAnalysisTool.java
  17. 9 3
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PythonAnalysisTool.java
  18. 1 1
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/RagSchemaSearchTool.java
  19. 1 1
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/SqlAnalysisTool.java
  20. 46 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/ToolDescriptor.java
  21. 186 0
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/ToolMetadataRegistry.java
  22. 4 4
      ai-server/src/main/java/com/zsjz/ai/module/agent/tools/TransAnalysisTool.java
  23. 8 8
      ai-server/src/main/java/com/zsjz/ai/module/dm/service/DmService.java
  24. 7 7
      ai-server/src/main/java/com/zsjz/ai/module/eds/service/EdsMaterialProcessService.java
  25. 15 6
      ai-server/src/main/java/com/zsjz/ai/module/plat/service/CaseDataCleanupService.java
  26. 1 1
      ai-server/src/main/java/com/zsjz/ai/module/plat/service/SysUserService.java
  27. 18 18
      ai-server/src/main/java/com/zsjz/ai/module/plat/service/SystemService.java
  28. 2 2
      ai-server/src/main/resources/prompts/insight/GRAPH_RELATION_INSIGHT.md
  29. 30 2
      ai-server/src/test/java/com/zsjz/ai/module/agent/artifact/AgentArtifactScannerTest.java
  30. 4 0
      ai-server/src/test/java/com/zsjz/ai/module/agent/insight/InsightPromptAssemblyTest.java
  31. 37 0
      ai-server/src/test/java/com/zsjz/ai/module/agent/middleware/CaseScopeMiddlewareTest.java
  32. 188 0
      ai-server/src/test/java/com/zsjz/ai/module/agent/middleware/PromptContextMiddlewareTest.java
  33. 107 0
      ai-server/src/test/java/com/zsjz/ai/module/agent/prompt/PromptAssemblyTest.java
  34. 11 3
      ai-server/src/test/java/com/zsjz/ai/module/agent/registry/ToolAnnotationScannerTest.java
  35. 10 8
      ai-server/src/test/java/com/zsjz/ai/module/agent/tools/PythonAnalysisToolTest.java
  36. 151 0
      ai-server/src/test/java/com/zsjz/ai/module/agent/tools/ToolDescriptionContractTest.java

+ 56 - 4
ai-server/src/main/java/com/zsjz/ai/module/agent/artifact/AgentArtifactScanner.java

@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.attribute.FileTime;
@@ -56,6 +57,9 @@ public class AgentArtifactScanner {
     private static final Set<String> EXCLUDED_FILES = Set.of(
             "MEMORY.md", "journal.sqlite3", ".consolidation_state");
 
+    /** Python 输出目录里的执行归属文件:第一行 userId,第二行 sessionId */
+    private static final String EXEC_OWNER_FILE = ".exec-owner";
+
     private final StorageLayout storageLayout;
     private final ArtifactService artifactService;
 
@@ -68,11 +72,13 @@ public class AgentArtifactScanner {
      * @param userId     登录用户 ID(Agent 工作区隔离维度)
      * @param caseId     案件/工作空间 ID
      * @param agentRowId 智能体行 ID
+     * @param sessionId  当前会话 ID;用于只认领本会话的 Python 输出
      * @param since      本轮开始时间;只登记修改时间不早于它的文件
      * @return 产物元数据列表(按文件修改时间升序)
      */
     public List<Map<String, Object>> scanAndRegister(Long userId, Long caseId,
-                                                     Long agentRowId, Instant since) {
+                                                     Long agentRowId, String sessionId,
+                                                     Instant since) {
         if (caseId == null || userId == null || agentRowId == null) {
             return List.of();
         }
@@ -80,9 +86,12 @@ public class AgentArtifactScanner {
         long sinceMillis = threshold.toEpochMilli() - 2000; // 容忍文件系统时间精度误差
 
         Map<String, Candidate> candidates = new LinkedHashMap<>();
-        Path agentDir = storageLayout.agentWorkspace(caseId, agentRowId);
-        collect(agentDir, 8, sinceMillis, candidates);
-        collect(storageLayout.pythonOutRoot(caseId), 4, sinceMillis, candidates);
+        // 只扫当前用户的 USER namespace:agentWorkspace 根下还有别的用户/运行态目录,
+        // 从父目录递归会把别人的文件也归集进来。
+        Path userDir = storageLayout.agentWorkspace(caseId, agentRowId)
+                .resolve(String.valueOf(userId));
+        collect(userDir, 8, sinceMillis, candidates);
+        collectOwnedPythonOutputs(caseId, userId, sessionId, sinceMillis, candidates);
 
         List<Candidate> ordered = new ArrayList<>(candidates.values());
         ordered.sort(Comparator.comparingLong(Candidate::modifiedMillis));
@@ -104,6 +113,49 @@ public class AgentArtifactScanner {
         return metas;
     }
 
+    /**
+     * 只扫描当前用户、当前会话执行产生的 Python 输出。
+     *
+     * <p>py-out 是案件级目录,不能像以前那样整根递归;否则同案件的其他用户/会话
+     * 刚生成的文件会被本轮误认领。归属由 {@code PythonExecutor} 写在每个执行目录的
+     * {@code .exec-owner} 里(userId + sessionId)。
+     */
+    private void collectOwnedPythonOutputs(Long caseId, Long userId, String sessionId,
+                                           long sinceMillis, Map<String, Candidate> out) {
+        if (sessionId == null || sessionId.isBlank()) {
+            return;
+        }
+        Path root = storageLayout.pythonOutRoot(caseId);
+        if (!Files.isDirectory(root)) {
+            return;
+        }
+        try (Stream<Path> dirs = Files.list(root)) {
+            dirs.filter(Files::isDirectory)
+                    .filter(dir -> ownedBy(dir, userId, sessionId))
+                    .forEach(dir -> collect(dir, 4, sinceMillis, out));
+        } catch (IOException e) {
+            log.info("扫描 Python 产物失败: root={}, error={}", root, e.getMessage());
+        }
+    }
+
+    /**
+     * 执行目录是否属于当前用户/会话;旧目录没有归属文件时一律不认领。
+     */
+    private static boolean ownedBy(Path execDir, Long userId, String sessionId) {
+        Path owner = execDir.resolve(EXEC_OWNER_FILE);
+        if (!Files.isRegularFile(owner)) {
+            return false;
+        }
+        try {
+            List<String> lines = Files.readAllLines(owner, StandardCharsets.UTF_8);
+            return lines.size() >= 2
+                    && String.valueOf(userId).equals(lines.get(0).trim())
+                    && sessionId.equals(lines.get(1).trim());
+        } catch (IOException e) {
+            return false;
+        }
+    }
+
     private void collect(Path root, int maxDepth, long sinceMillis, Map<String, Candidate> out) {
         if (root == null || !Files.isDirectory(root)) {
             return;

+ 4 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/entity/AgentChatSession.java

@@ -29,6 +29,10 @@ public class AgentChatSession {
     @TableField("case_id")
     private Long caseId;
 
+    /** 会话创建用户(agent_chat_session.user_id);用于删除时清理对应 Redis 记忆槽位 */
+    @TableField("user_id")
+    private Long userId;
+
     @TableField("title")
     private String title;
 

+ 43 - 14
ai-server/src/main/java/com/zsjz/ai/module/agent/insight/agent/InsightAgentFactory.java

@@ -1,8 +1,7 @@
 package com.zsjz.ai.module.agent.insight.agent;
 
-import cn.dev33.satoken.stp.StpUtil;
-import com.zsjz.ai.common.context.CaseContextHolder;
 import com.zsjz.ai.common.exception.ServerException;
+import com.zsjz.ai.common.model.plat.entity.CaseInfo;
 import com.zsjz.ai.common.storage.StorageLayout;
 import com.zsjz.ai.module.agent.entity.AgentModel;
 import com.zsjz.ai.module.agent.mapper.AgentModelMapper;
@@ -11,10 +10,12 @@ import com.zsjz.ai.module.agent.rag.RagSchemaService;
 import com.zsjz.ai.module.agent.rag.WorkspaceSchemaCatalog;
 import com.zsjz.ai.module.agent.service.AgentModelFactory;
 import com.zsjz.ai.module.agent.middleware.CaseScopeMiddleware;
+import com.zsjz.ai.module.agent.middleware.PromptContextMiddleware;
 import com.zsjz.ai.module.agent.tools.AgentToolRegistry;
 import com.zsjz.ai.module.agent.tools.PythonAnalysisTool;
 import com.zsjz.ai.module.agent.tools.RagSchemaSearchTool;
 import com.zsjz.ai.module.agent.tools.SqlAnalysisTool;
+import com.zsjz.ai.module.plat.mapper.CaseInfoMapper;
 import com.zsjz.ai.module.plat.mapper.TableFieldMapper;
 import com.zsjz.ai.module.plat.mapper.TableInfoMapper;
 import io.agentscope.core.model.Model;
@@ -82,7 +83,7 @@ public class InsightAgentFactory {
      *
      * <p>与通用池的 {@code w..-a..-m..} 形态刻意不同,便于日志里一眼区分来源。
      */
-    private static final String KEY_PREFIX = "insight-s";
+    private static final String KEY_PREFIX = "insight-";
 
     private final AgentModelFactory agentModelFactory;
     private final AgentModelMapper modelMapper;
@@ -90,6 +91,8 @@ public class InsightAgentFactory {
     private final RagSchemaService ragSchemaService;
     private final TableInfoMapper tableInfoMapper;
     private final TableFieldMapper tableFieldMapper;
+    /** 案件名称(动态公告用,只读一次) */
+    private final CaseInfoMapper caseInfoMapper;
     /** 案件 DuckDB 表目录(list_tables 的唯一事实来源,含 AI 动态表) */
     private final WorkspaceSchemaCatalog schemaCatalog;
     private final PythonExecutor pythonExecutor;
@@ -98,7 +101,7 @@ public class InsightAgentFactory {
     private final StorageLayout storageLayout;
 
     /**
-     * 独立实例池:key = insight-s{sessionId}
+     * 独立实例池:key = insight-u{userId}-c{caseId}-s{sessionId}
      */
     private final Map<String, HarnessAgent> agentPool = new ConcurrentHashMap<>();
 
@@ -115,6 +118,7 @@ public class InsightAgentFactory {
                                RagSchemaService ragSchemaService,
                                TableInfoMapper tableInfoMapper,
                                TableFieldMapper tableFieldMapper,
+                               CaseInfoMapper caseInfoMapper,
                                PythonExecutor pythonExecutor,
                                AgentToolRegistry agentToolRegistry,
                                WorkspaceSchemaCatalog schemaCatalog,
@@ -125,6 +129,7 @@ public class InsightAgentFactory {
         this.ragSchemaService = ragSchemaService;
         this.tableInfoMapper = tableInfoMapper;
         this.tableFieldMapper = tableFieldMapper;
+        this.caseInfoMapper = caseInfoMapper;
         this.pythonExecutor = pythonExecutor;
         this.agentToolRegistry = agentToolRegistry;
         this.schemaCatalog = schemaCatalog;
@@ -134,12 +139,21 @@ public class InsightAgentFactory {
     /**
      * 取或建研判 Agent 实例。
      *
-     * @param sessionId 会话ID(池 key 的组成部分,保证动态提示词不串台)
+     * @param sessionId 会话ID(池 key 的组成部分,和 userId 一起保证动态提示词不串台)
+     * @param caseId    案件ID(必须由请求线程/会话实体传入;Reactor 线程取不到 CaseContextHolder)
      * @param modelId   会话绑定的模型ID
      * @param sysPrompt 会话创建时固化下来的完整系统提示词
+     * @param userId    当前登录用户(必须由请求线程捕获后传入,Reactor 线程取不到 SaToken)
      */
-    public HarnessAgent getOrCreate(Long sessionId, Long modelId, String sysPrompt) {
-        String key = KEY_PREFIX + sessionId;
+    public HarnessAgent getOrCreate(Long sessionId, Long caseId, Long modelId, String sysPrompt, String userId) {
+        if (userId == null || userId.isBlank()) {
+            // 宁可报错,也不要用空用户键把不同用户的实例混在一起
+            throw new IllegalArgumentException("userId 不能为空:研判实例必须按用户隔离");
+        }
+        if (caseId == null) {
+            throw new IllegalArgumentException("caseId 不能为空:研判实例必须绑定案件工作区");
+        }
+        String key = poolKey(sessionId, caseId, userId);
         long now = System.currentTimeMillis();
 
         poolLock.lock();
@@ -150,7 +164,7 @@ public class InsightAgentFactory {
                 lastAccessAt.put(key, now);
                 return cached;
             }
-            HarnessAgent agent = buildAgent(modelId, sysPrompt);
+            HarnessAgent agent = buildAgent(modelId, sysPrompt, caseId);
             agentPool.put(key, agent);
             lastAccessAt.put(key, now);
             evictOverflowLocked(key);
@@ -165,9 +179,19 @@ public class InsightAgentFactory {
      * 会话删除时清理实例(记忆由状态存储侧管理,这里只丢实例)
      */
     public void evict(Long sessionId) {
-        String key = KEY_PREFIX + sessionId;
-        agentPool.remove(key);
-        lastAccessAt.remove(key);
+        // 按 sessionId 后缀清理:调用方可能不是创建实例的那个登录用户,
+        // 但同一会话的实例都不该继续留在池里。
+        String suffix = "-s" + sessionId;
+        agentPool.keySet().removeIf(key -> key.endsWith(suffix));
+        lastAccessAt.keySet().removeIf(key -> key.endsWith(suffix));
+    }
+
+    /**
+     * 池 key:用户 + 会话。研判是多人共用的,只按 sessionId 不够,
+     * 加 userId 后即使会话 ID 撞车也不会复用别人的 Agent 实例。
+     */
+    private static String poolKey(Long sessionId, Long caseId, String userId) {
+        return KEY_PREFIX + "u" + userId + "-c" + caseId + "-s" + sessionId;
     }
 
     /**
@@ -199,7 +223,7 @@ public class InsightAgentFactory {
      *   <li>默认装备 {@code graph} 组而非 {@code person} 组 —— 起点就是关系图谱数据。</li>
      * </ol>
      */
-    private HarnessAgent buildAgent(Long modelId, String sysPrompt) {
+    private HarnessAgent buildAgent(Long modelId, String sysPrompt, Long caseId) {
         AgentModel modelConfig = modelMapper.selectById(modelId);
         if (modelConfig == null) {
             throw new ServerException(404, "模型配置不存在: " + modelId);
@@ -226,11 +250,16 @@ public class InsightAgentFactory {
         b.toolkit(toolkit);
         // 允许模型自行切换工具组(必须放在 toolkit(...) 之后、build() 之前)
         b.enableMetaTool(true);
+        // 动态上下文(案件/日期)不进 system prompt:研判提示词按会话固化,
+        // 不能因为跨天就整段重建;变化时以 synthetic 公告补一条即可。
+        // caseId 由调用方从会话实体传入,不在 Reactor 线程里读 CaseContextHolder。
+        CaseInfo caseInfo = caseInfoMapper.selectById(caseId);
+        b.middleware(new PromptContextMiddleware(
+                caseInfo == null ? null : caseInfo.getName(), caseId, false));
         // 工具执行期重建案件作用域(与通用 Agent 一致,见 CaseScopeMiddleware 注释)
-        b.middleware(new CaseScopeMiddleware(CaseContextHolder.get()));
+        b.middleware(new CaseScopeMiddleware(caseId));
 
         // 工作空间:cases/{caseId}/ai/insight,记忆槽位仍按 sessionId 隔离
-        Long caseId = CaseContextHolder.get();
         Path workspace = storageLayout.insightWorkspace(caseId);
         b.workspace(workspace);
         b.stateStore(agentStateStore);

+ 12 - 6
ai-server/src/main/java/com/zsjz/ai/module/agent/insight/prompt/InsightPromptBuilder.java

@@ -2,6 +2,8 @@ package com.zsjz.ai.module.agent.insight.prompt;
 
 import com.zsjz.ai.module.agent.insight.context.InsightContext;
 import com.zsjz.ai.module.agent.insight.context.InsightContextBuilder;
+import com.zsjz.ai.module.agent.prompt.PromptAssembler;
+import com.zsjz.ai.module.agent.prompt.PromptSection;
 import com.zsjz.ai.module.agent.rag.RagSchemaService;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
@@ -11,6 +13,8 @@ import org.springframework.stereotype.Component;
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * AI 研判系统提示词装配器。
@@ -52,14 +56,16 @@ public class InsightPromptBuilder {
      * @return 完整 sysPrompt(落库到 agent_insight_session.sys_prompt)
      */
     public String build(InsightContext ctx) {
-        StringBuilder sb = new StringBuilder();
-        sb.append(loadStaticPrompt());
-        sb.append(contextBuilder.renderContextBlock(ctx));
-        sb.append(RENDER_CONTRACT);
+        // 只复用 PromptAssembler 的「有序分段 + 统一拼接」能力;内容仍是研判专属的四段,
+        // 不与通用 Agent 的工具规则/输出契约混写(两套渲染契约会互相污染,见类注释)。
+        List<PromptSection> sections = new ArrayList<>();
+        sections.add(PromptSection.system("insight-persona", loadStaticPrompt()));
+        sections.add(PromptSection.system("insight-context", contextBuilder.renderContextBlock(ctx)));
+        sections.add(PromptSection.system("insight-contract", RENDER_CONTRACT));
         if (ragSchemaService.isAvailable()) {
-            sb.append(RAG_GUIDE);
+            sections.add(PromptSection.system("insight-rag-guidance", RAG_GUIDE));
         }
-        return sb.toString();
+        return PromptAssembler.render(sections);
     }
 
     /** 首轮自动分析的固定指令(前端打开抽屉时不敲字,由服务端注入) */

+ 21 - 8
ai-server/src/main/java/com/zsjz/ai/module/agent/insight/service/impl/InsightServiceImpl.java

@@ -1,5 +1,6 @@
 package com.zsjz.ai.module.agent.insight.service.impl;
 
+import cn.dev33.satoken.stp.StpUtil;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -96,8 +97,15 @@ public class InsightServiceImpl implements InsightService {
      */
     private static final String BIZ_TYPE_GRAPH_RELATION = InsightContextBuilder.BIZ_TYPE_GRAPH_RELATION;
 
-    /** 固定运行时用户标识(项目无用户体系,仅供 AgentScope 记忆/文件隔离维度使用) */
-    private static final String RUNTIME_USER_ID = "default";
+    /**
+     * 当前登录用户:AgentScope 的记忆槽位和沙箱都按 userId 隔离。
+     *
+     * <p>不能用固定值:研判是多人共用的,固定 userId 会让所有用户的会话记忆
+     * 挤进同一个用户命名空间;虽然 sessionId 还能兜一层,但一旦 ID 复用到就是串数据。
+     */
+    private static String runtimeUserId() {
+        return StpUtil.getLoginIdAsString();
+    }
 
     /**
      * 研判会话在 {@code AgentStateStore} 里的槽位 ID。
@@ -265,7 +273,7 @@ public class InsightServiceImpl implements InsightService {
         sessionMapper.deleteById(session.getId());
         agentFactory.evict(session.getId());
         // 会话状态已落 Redis:只 evict 实例不够,记忆(对话历史)不跟着删会永久残留
-        agentFactory.deleteMemory(RUNTIME_USER_ID, stateSessionId(session.getId()));
+        agentFactory.deleteMemory(runtimeUserId(), stateSessionId(session.getId()));
         // 闸门清理只在「未被占用」时做:流式进行中删会话时,无条件 remove 会让新请求
         // computeIfAbsent 出第二个闸门,两个闸门互不互斥(应用闸门防线形同虚设)。
         // 占用中的条目极小,宁可留在 map 里也不破坏互斥(内存影响可忽略)。
@@ -346,8 +354,10 @@ public class InsightServiceImpl implements InsightService {
 
     @Override
     public Flux<ServerSentEvent<String>> stream(InsightStreamDTO dto) {
-        // 请求线程先捕获案件,避免订阅切到 Reactor 线程后取不到 CaseContextHolder
+        // 请求线程先捕获案件和用户:Flux.defer 的订阅可能切到 Reactor 线程,
+        // 那里既没有 CaseContextHolder 也不保证 SaToken 上下文,不能等到订阅后再取。
         Long openCaseId = caseAccessGuard.requireOpenCaseId();
+        String runtimeUser = StpUtil.getLoginIdAsString();
         return Flux.defer(() -> {
             AgentInsightSession session = requireSession(dto.getSessionId(), dto.getCaseId(), openCaseId);
             String key = lockKey(session.getId());
@@ -367,7 +377,7 @@ public class InsightServiceImpl implements InsightService {
                 gate.release();
                 return Flux.just(sse("error", Map.of("type", "error", "error", "该分析正在进行中,请稍候")));
             }
-            return doStream(session, dto)
+            return doStream(session, dto, runtimeUser)
                     .doFinally(signal -> {
                         // 无论正常结束、异常还是被取消,都必须复位状态位与闸门,
                         // 否则会话会永久卡在 STREAMING,后续追问全部 409
@@ -388,7 +398,8 @@ public class InsightServiceImpl implements InsightService {
      * 流末落一条完整 assistant、中止/异常落一条 {@code INTERRUPTED}。
      * 不做 token 级 UPDATE —— 那会把写放大几十倍,而收益只是"刷新能看到半句话"。
      */
-    private Flux<ServerSentEvent<String>> doStream(AgentInsightSession session, InsightStreamDTO dto) {
+    private Flux<ServerSentEvent<String>> doStream(AgentInsightSession session, InsightStreamDTO dto,
+                                                   String runtimeUser) {
         boolean firstRound = !StringUtils.hasText(dto.getMessage());
         String userText = firstRound ? promptBuilder.firstRoundInstruction() : dto.getMessage().trim();
         String messageType = firstRound ? MSG_TYPE_FIRST_ROUND : MSG_TYPE_CHAT;
@@ -400,10 +411,12 @@ public class InsightServiceImpl implements InsightService {
                     null, null, null, MSG_STATUS_DONE, firstRoundId);
         }
 
-        HarnessAgent agent = agentFactory.getOrCreate(session.getId(), session.getModelId(), session.getSysPrompt());
+        HarnessAgent agent = agentFactory.getOrCreate(
+                session.getId(), session.getCaseId(), session.getModelId(),
+                session.getSysPrompt(), runtimeUser);
 
         RuntimeContext ctx = RuntimeContext.builder()
-                .userId(RUNTIME_USER_ID)
+                .userId(runtimeUser)
                 .sessionId(stateSessionId(session.getId()))
                 .build();
 

+ 41 - 7
ai-server/src/main/java/com/zsjz/ai/module/agent/middleware/CaseScopeMiddleware.java

@@ -7,8 +7,11 @@ import io.agentscope.core.event.AgentEvent;
 import io.agentscope.core.middleware.ActingInput;
 import io.agentscope.core.middleware.MiddlewareBase;
 import lombok.extern.slf4j.Slf4j;
+import org.reactivestreams.Subscription;
+import reactor.core.publisher.BaseSubscriber;
 import reactor.core.publisher.Flux;
 
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Function;
 
 /**
@@ -53,12 +56,43 @@ public class CaseScopeMiddleware implements MiddlewareBase {
         if (caseId == null) {
             return next.apply(input);
         }
-        // 回调在订阅时执行:装配 + 订阅都在案件作用域内完成;
-        // 下游取消时内部链随之 dispose(emitter 关闭会传播取消信号)
-        return Flux.create(emitter -> CaseContextHolder.runWith(caseId, null, () ->
-                next.apply(input).subscribe(
-                        emitter::next,
-                        emitter::error,
-                        emitter::complete)));
+        // 回调在订阅时执行:装配 + 订阅都在案件作用域内完成。
+        // 下游取消(用户停止/删除会话)必须显式向内部链传播 cancel,
+        // 否则 Flux.create 只会关闭 emitter,Agent 还会继续跑工具、写文件。
+        return Flux.create(emitter -> {
+            AtomicReference<Subscription> upstream = new AtomicReference<>();
+            emitter.onCancel(() -> cancel(upstream));
+            emitter.onDispose(() -> cancel(upstream));
+            CaseContextHolder.runWith(caseId, null, () ->
+                    next.apply(input).subscribe(new BaseSubscriber<AgentEvent>() {
+                        @Override
+                        protected void hookOnSubscribe(Subscription subscription) {
+                            upstream.set(subscription);
+                            subscription.request(Long.MAX_VALUE);
+                        }
+
+                        @Override
+                        protected void hookOnNext(AgentEvent value) {
+                            emitter.next(value);
+                        }
+
+                        @Override
+                        protected void hookOnComplete() {
+                            emitter.complete();
+                        }
+
+                        @Override
+                        protected void hookOnError(Throwable throwable) {
+                            emitter.error(throwable);
+                        }
+                    }));
+        });
+    }
+
+    private static void cancel(AtomicReference<Subscription> upstream) {
+        Subscription subscription = upstream.get();
+        if (subscription != null) {
+            subscription.cancel();
+        }
     }
 }

+ 158 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/middleware/PromptContextMiddleware.java

@@ -0,0 +1,158 @@
+package com.zsjz.ai.module.agent.middleware;
+
+import io.agentscope.core.agent.Agent;
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.core.event.AgentEvent;
+import io.agentscope.core.message.Msg;
+import io.agentscope.core.message.MsgRole;
+import io.agentscope.core.message.TextBlock;
+import io.agentscope.core.middleware.MiddlewareBase;
+import io.agentscope.core.middleware.ReasoningInput;
+import io.agentscope.core.state.AgentState;
+import reactor.core.publisher.Flux;
+
+import java.time.Clock;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+
+/**
+ * 每轮推理前注入「当前案件 / 日期 / 已装备工具组」公告。
+ *
+ * <h3>为什么放在 onReasoning 而不是 system prompt</h3>
+ * 这些值每轮都可能变化(跨天、模型调用 reset_equipped_tools 切组),
+ * 写进 system prompt 会让稳定前缀每轮都变,破坏模型侧的前缀缓存;
+ * 用 synthetic USER 公告注入则只影响本轮输入,不落历史、不改 system 前缀。
+ *
+ * <h3>去重</h3>
+ * onReasoning 在多轮工具调用里会重复触发。这里保存上一次公告的完整文本,
+ * 只有值真正变化时才追加一条,避免同一段公告刷屏、白烧 token。
+ *
+ * <p>公告内容全部来自系统数据(案件名/ID/日期/工具组),不含业务指令;
+ * 案件名做了单行化和长度裁剪,避免用户可控名称破坏公告结构。
+ */
+public class PromptContextMiddleware implements MiddlewareBase {
+
+    /** 案件名最长保留字符数,超出截断 */
+    private static final int MAX_CASE_NAME = 80;
+
+    /** 最多跟踪多少个会话的快照;Agent 实例按用户/工作区复用,不能只存一份 */
+    private static final int MAX_TRACKED_SESSIONS = 1024;
+
+    private final String caseName;
+    private final Long caseId;
+    private final boolean includeEquippedGroups;
+    private final Clock clock;
+
+    /**
+     * 每个会话上一次实际注入的公告文本;相同则跳过。
+     *
+     * <p>必须按会话隔离:AgentService 的实例池按「工作区×专家×模型×用户」复用,
+     * 同一用户的多个会话共享同一个 middleware 实例;只存一份会让第二个会话
+     * 因为“别人已经公告过”而永远收不到案件/日期。
+     */
+    private final Map<String, String> lastSnapshotBySession = new ConcurrentHashMap<>();
+
+    public PromptContextMiddleware(String caseName, Long caseId, boolean includeEquippedGroups) {
+        this(caseName, caseId, includeEquippedGroups, Clock.systemDefaultZone());
+    }
+
+    public PromptContextMiddleware(String caseName, Long caseId, boolean includeEquippedGroups, Clock clock) {
+        this.caseName = caseName;
+        this.caseId = caseId;
+        this.includeEquippedGroups = includeEquippedGroups;
+        this.clock = clock == null ? Clock.systemDefaultZone() : clock;
+    }
+
+    @Override
+    public Flux<AgentEvent> onReasoning(Agent agent, RuntimeContext ctx, ReasoningInput input,
+                                        Function<ReasoningInput, Flux<AgentEvent>> next) {
+        String snapshot = snapshot(agent, ctx);
+        String previous = lastSnapshotBySession.put(sessionKey(ctx), snapshot);
+        if (snapshot.equals(previous)) {
+            return next.apply(input);
+        }
+        // 会话只增不减时做一次粗暴上限保护;清空最多让活跃会话多收一条公告,不会丢状态。
+        if (lastSnapshotBySession.size() > MAX_TRACKED_SESSIONS) {
+            lastSnapshotBySession.clear();
+        }
+
+        List<Msg> messages = new ArrayList<>(input.messages());
+        messages.add(Msg.builder()
+                .role(MsgRole.USER)
+                .name("system")
+                .content(TextBlock.builder().text(snapshot).build())
+                .metadata(Map.of(Msg.METADATA_SYNTHETIC, true, "reminderKind", "context"))
+                .build());
+        return next.apply(new ReasoningInput(messages, input.tools(), input.options()));
+    }
+
+    /**
+     * 公告正文;没有案件信息时至少给日期,保证跨天能触发一次更新。
+     */
+    private String snapshot(Agent agent, RuntimeContext ctx) {
+        StringBuilder sb = new StringBuilder("<system-reminder>\n");
+        if (caseName != null || caseId != null) {
+            sb.append("当前案件:")
+                    .append(caseName == null || caseName.isBlank() ? "未命名" : sanitize(caseName));
+            if (caseId != null) {
+                sb.append("(ID ").append(caseId).append(")");
+            }
+            sb.append('\n');
+        }
+        sb.append("当前日期:").append(LocalDate.now(clock)).append('\n');
+        if (includeEquippedGroups) {
+            List<String> groups = activatedGroups(agent, ctx);
+            if (!groups.isEmpty()) {
+                sb.append("已装备工具组:").append(String.join(", ", groups)).append('\n');
+            }
+        }
+        return sb.append("</system-reminder>").toString();
+    }
+
+    /**
+     * 从「本次调用」的 AgentState 取激活组,而不是共享 Toolkit。
+     *
+     * <p>Agent 实例会按用户/工作区复用,Toolkit 的 activeGroups 是实例级可变状态;
+     * 并发会话下直接读它可能把别的会话刚切的组播报给当前会话。AgentState 是
+     * RuntimeContext 上的 call-scoped 状态,才和当前会话一致。
+     */
+    private static List<String> activatedGroups(Agent agent, RuntimeContext ctx) {
+        AgentState state = RuntimeContext.resolveAgentState(ctx, agent);
+        if (state == null || state.getToolContext() == null) {
+            return List.of();
+        }
+        List<String> groups = state.getToolContext().getActivatedGroups();
+        return groups == null ? List.of() : groups;
+    }
+
+    /**
+     * 会话键:同一 Agent 实例会被同一用户的多个会话复用,快照必须按会话隔离。
+     */
+    private static String sessionKey(RuntimeContext ctx) {
+        if (ctx == null) {
+            return "";
+        }
+        String session = ctx.getSessionId();
+        String user = ctx.getUserId();
+        if (session == null || session.isBlank()) {
+            return user == null ? "" : user;
+        }
+        return user == null ? session : user + ":" + session;
+    }
+
+    /**
+     * 单行化 + 去结构字符 + 截断:案件名来自用户输入,不能让它插入换行、
+     * 闭合 {@code <system-reminder>} 或塞入超长内容。
+     */
+    private static String sanitize(String value) {
+        String oneLine = value.replaceAll("\\s+", " ")
+                .replace('<', '<')
+                .replace('>', '>')
+                .trim();
+        return oneLine.length() <= MAX_CASE_NAME ? oneLine : oneLine.substring(0, MAX_CASE_NAME) + "…";
+    }
+}

+ 116 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/prompt/PromptAssembler.java

@@ -0,0 +1,116 @@
+package com.zsjz.ai.module.agent.prompt;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * 系统提示词装配器:把专家人设、通用工具规则、输出契约、RAG/知识库指引
+ * 按固定顺序拼成一段 system prompt。
+ *
+ * <h3>为什么要分段</h3>
+ * 以前 {@code AgentService} 里用「字符串 + 字符串」逐段追加,顺序靠调用点保证,
+ * 新加一段很容易插错位置,也没法在测试里断言「哪段是稳定的、哪段是动态的」。
+ * 这里把每段变成 {@link PromptSection}:顺序、层次、稳定性都是显式数据。
+ *
+ * <p>本类只负责<b>稳定段</b>。案件、日期、已装备工具组等运行期信息由
+ * {@code PromptContextMiddleware} 以 synthetic USER 公告注入,不进入 system prompt。
+ *
+ * <p>注意:HarnessAgent 自带的 {@code WorkspaceContextMiddleware} 仍会通过
+ * {@code onSystemPrompt} 追加工作区/会话上下文,所以这里的“稳定”只指本装配器产出的段;
+ * 真正的 provider 前缀缓存收益取决于该中间件的输出是否稳定(当前没有强行开启 cacheControl)。
+ *
+ * <p>纪律:具体工具怎么用、返回什么、能不能画图,写在各工具的 {@code @Tool(description)} 里;
+ * 这里只放跨工具通用规则,不点名业务工具,也不写“能力受限”的放弃分支。
+ */
+public final class PromptAssembler {
+
+    private static final String TOOL_RULES = """
+            ## 工具规则
+            1. 只使用当前工具列表里实际存在的工具;不要臆造。
+            2. 优先用最匹配的专用工具;没有合适的专用工具,或参数表达不了需求时,用 query_table_data(单表)或 execute_python(JOIN/聚合/复杂计算)兜底,不要硬套。
+            3. 数据或字段不存在时明确说明缺什么,不要编造;工具报错先按提示修正,连续失败两次就换工具或缩小范围。
+            4. 正文只写结论;数据明细用 Markdown 表格或 CSV 产物。""";
+
+    private static final String OUTPUT_CONTRACT = """
+            ## 输出
+            - 代码、SQL、JSON、HTML 用 ```语言 围栏输出,前端会按语言高亮。
+            - 常规图表:调 render_chart 校验 option,再放 ```echarts 围栏。
+            - 其它可视化按对应工具 description 的返回契约输出,前端会自动渲染。""";
+
+    private static final String RAG_GUIDANCE = """
+            ## 数据表结构检索(重要)
+            你拥有 search_table_schema 工具,可按语义检索模板库中已登记的表结构(物理表名、字段、类型、中文注释;含 AI 智能清洗新建的动态表)。
+            - 在编写任何 Python 查询/分析或回答“有哪些表/字段”类问题之前,必须先调用该工具检索,禁止凭空猜测表名和字段名。
+            - 检索 query 用自然语言描述目标(如“包含手机号和身份证号的表”)。
+            - 检索结果已按相似度排序,结合字段注释理解表用途后再编写 Python/DuckDB 查询。""";
+
+    private static final String KB_GUIDANCE = """
+            ## 知识库检索(重要)
+            你拥有 search_knowledge 工具,可按语义检索本方案绑定的知识库「%s」(返回知识片段与来源文档名)。
+            - 用户问题涉及领域知识、法规条文、业务规范、背景资料时,必须先检索再回答;引用片段时标注来源文档名。
+            - 检索不到相关内容时明确告知用户,禁止凭空编造知识内容。
+            - 检索 query 用自然语言描述知识点,一次检索不理想可换角度再次检索。""";
+
+    private PromptAssembler() {
+    }
+
+    /**
+     * 构建系统提示词的稳定段。
+     *
+     * <p>顺序固定为:专家人设 → 工具规则 → 输出契约 → RAG 指引 → 知识库指引。
+     * 顺序变化会直接改变模型对规则的优先级感知,所以用测试锁住。
+     *
+     * @param expertPrompt      专家配置的 sysPrompt,可空
+     * @param ragAvailable      RAG 表结构检索是否可用
+     * @param knowledgeBaseName 绑定知识库名称,未绑定传 null
+     */
+    public static List<PromptSection> systemSections(String expertPrompt,
+                                                     boolean ragAvailable,
+                                                     String knowledgeBaseName) {
+        List<PromptSection> sections = new ArrayList<>();
+        if (expertPrompt != null && !expertPrompt.isBlank()) {
+            sections.add(PromptSection.system("expert", expertPrompt));
+        }
+        sections.add(PromptSection.system("tool-rules", TOOL_RULES));
+        sections.add(PromptSection.system("output-contract", OUTPUT_CONTRACT));
+        if (ragAvailable) {
+            sections.add(PromptSection.system("rag-guidance", RAG_GUIDANCE));
+        }
+        if (knowledgeBaseName != null && !knowledgeBaseName.isBlank()) {
+            sections.add(PromptSection.system("knowledge-guidance", KB_GUIDANCE.formatted(knowledgeBaseName)));
+        }
+        return List.copyOf(sections);
+    }
+
+    /**
+     * 只有通用规则(工具规则 + 输出契约),供单测/目录页复用。
+     */
+    public static String renderRules() {
+        return render(List.of(
+                PromptSection.system("tool-rules", TOOL_RULES),
+                PromptSection.system("output-contract", OUTPUT_CONTRACT)));
+    }
+
+    /**
+     * 按顺序拼接非空段;段间空一行。
+     *
+     * <p>只接受 {@link PromptSection.Target#SYSTEM}:USER_META 段应由中间件作为
+     * synthetic 公告注入,混进 system prompt 会破坏分层。显式报错比静默拼接好。
+     */
+    public static String render(List<PromptSection> sections) {
+        if (sections == null || sections.isEmpty()) {
+            return "";
+        }
+        for (PromptSection section : sections) {
+            if (section.target() != PromptSection.Target.SYSTEM) {
+                throw new IllegalArgumentException(
+                        "render 只拼接 SYSTEM 段,收到 " + section.target() + ": " + section.name());
+            }
+        }
+        return sections.stream()
+                .filter(section -> !section.isBlank())
+                .map(PromptSection::content)
+                .collect(Collectors.joining("\n\n"));
+    }
+}

+ 65 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/prompt/PromptSection.java

@@ -0,0 +1,65 @@
+package com.zsjz.ai.module.agent.prompt;
+
+import java.util.Objects;
+
+/**
+ * 系统提示词的一段。
+ *
+ * <p>借鉴 ZCode 的「稳定段 / 动态段」分层:稳定段按固定顺序拼成 system prompt,
+ * 动态上下文(案件、日期、已装备工具组)不进入 system prompt,而是每轮以
+ * synthetic 公告注入,避免稳定前缀被日期之类的值破坏。
+ *
+ * <p>{@code target} 目前只有 SYSTEM;USER_META 预留给后续要注入到用户消息里的公告,
+ * 让「这段内容属于哪一层」在装配阶段就显式写出来。
+ *
+ * @param name      段名(日志/测试定位用)
+ * @param target    注入层:SYSTEM=系统提示词,USER_META=每轮公告
+ * @param cacheHint 稳定性:STABLE=构建期固定,DYNAMIC=运行期变化
+ * @param content   正文(自动 trim,空内容不参与拼接)
+ */
+public record PromptSection(
+        String name,
+        Target target,
+        CacheHint cacheHint,
+        String content
+) {
+
+    public enum Target {
+        /** 拼进 HarnessAgent.sysPrompt */
+        SYSTEM,
+        /** 以 synthetic USER 消息注入,不改 system prompt */
+        USER_META
+    }
+
+    public enum CacheHint {
+        /** 构建期固定,可作为缓存前缀 */
+        STABLE,
+        /** 运行期变化,不能进稳定前缀 */
+        DYNAMIC
+    }
+
+    public PromptSection {
+        Objects.requireNonNull(name, "name");
+        Objects.requireNonNull(target, "target");
+        Objects.requireNonNull(cacheHint, "cacheHint");
+        content = content == null ? "" : content.strip();
+    }
+
+    public boolean isBlank() {
+        return content.isEmpty();
+    }
+
+    /**
+     * 稳定系统段。
+     */
+    public static PromptSection system(String name, String content) {
+        return new PromptSection(name, Target.SYSTEM, CacheHint.STABLE, content);
+    }
+
+    /**
+     * 动态公告段。
+     */
+    public static PromptSection announcement(String name, String content) {
+        return new PromptSection(name, Target.USER_META, CacheHint.DYNAMIC, content);
+    }
+}

+ 20 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonExecutor.java

@@ -12,6 +12,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.ArrayList;
@@ -94,6 +95,9 @@ public class PythonExecutor {
     /** 关系图 JSON 读取上限:超过说明模型没有先聚合,直接给可读错误 */
     private static final long MAX_RELATION_GRAPH_BYTES = 2L * 1024 * 1024;
 
+    /** Python 输出目录的执行归属文件:第一行 userId,第二行 sessionId */
+    private static final String EXEC_OWNER_FILE = ".exec-owner";
+
     /**
      * 关系图辅助模块源码。
      *
@@ -201,6 +205,13 @@ public class PythonExecutor {
      * @return 执行结果(exitCode/stdout/stderr/imageUrls/durationMs/error)
      */
     public PythonResult execute(String code) {
+        return execute(code, null, null);
+    }
+
+    /**
+     * 执行 Python,并记录执行归属(用户 + 会话),供产物扫描按归属认领。
+     */
+    public PythonResult execute(String code, String userId, String sessionId) {
         long start = System.currentTimeMillis();
         if (!isAvailable()) {
             return PythonResult.error("Python 执行环境不可用(未安装或缺少依赖:pip install pandas duckdb matplotlib)");
@@ -274,7 +285,8 @@ public class PythonExecutor {
 
             // 必须在 collectGeneratedFiles 之前读:该步骤会把 relation_graph.json 移到 py-out
             RelationGraphFile relationGraph = readRelationGraph(sandbox);
-            List<String> imageUrls = collectGeneratedFiles(workspaceId, execId, sandbox);
+            List<String> imageUrls = collectGeneratedFiles(
+                    workspaceId, execId, sandbox, userId, sessionId);
             long durationMs = System.currentTimeMillis() - start;
             log.info("Python 执行完成: workspaceId={}, execId={}, exitCode={}, images={}, relationGraph={}, costMs={}",
                     workspaceId, execId, process.exitValue(), imageUrls.size(),
@@ -448,7 +460,8 @@ public class PythonExecutor {
      * 非图片文件也一并保留,供对话结束后的产物扫描登记(否则随沙箱目录一起删除)。
      * 图片数量仍受 {@code maxImages} 限制;非图片最多保留 50 个。
      */
-    private List<String> collectGeneratedFiles(long workspaceId, String execId, Path sandbox) {
+    private List<String> collectGeneratedFiles(long workspaceId, String execId, Path sandbox,
+                                               String userId, String sessionId) {
         List<String> urls = new ArrayList<>();
         try (Stream<Path> files = Files.list(sandbox)) {
             List<Path> generated = files
@@ -461,6 +474,11 @@ public class PythonExecutor {
             }
             Path outDir = storageLayout.pythonOutDir(workspaceId, execId);
             Files.createDirectories(outDir);
+            // 归属文件不参与产物白名单,只供 AgentArtifactScanner 判断这批文件属于谁。
+            Files.writeString(outDir.resolve(EXEC_OWNER_FILE),
+                    (userId == null ? "" : userId) + "\n"
+                            + (sessionId == null ? "" : sessionId),
+                    StandardCharsets.UTF_8);
             int imageCount = 0;
             int otherCount = 0;
             int maxImages = etlProperties.getPython().getMaxImages();

+ 10 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentInstancePool.java

@@ -4,6 +4,7 @@ import lombok.extern.slf4j.Slf4j;
 
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -101,6 +102,15 @@ public class AgentInstancePool<T> {
         return pool.size();
     }
 
+    /**
+     * 当前池内实例快照(用于会话删除时清各实例的 stateCache)。
+     *
+     * <p>返回副本,调用方在锁外操作,避免持有池锁执行 HarnessAgent 的方法。
+     */
+    public synchronized List<T> values() {
+        return List.copyOf(pool.values());
+    }
+
     /**
      * 清空全部实例(技能这类全平台共享的数据变更后调用:任何专家的实例都可能引用了旧数据)
      *

+ 109 - 75
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentService.java

@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.spring.service.impl.ServiceImpl;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.zsjz.ai.common.exception.ServerException;
+import com.zsjz.ai.common.model.plat.entity.CaseInfo;
 import com.zsjz.ai.common.storage.StorageLayout;
 import com.zsjz.ai.common.utils.Json;
 import com.zsjz.ai.module.agent.artifact.ArtifactService;
@@ -21,6 +22,8 @@ import com.zsjz.ai.module.agent.mapper.AgentChatSessionMapper;
 import com.zsjz.ai.module.agent.mapper.AgentMapper;
 import com.zsjz.ai.module.agent.mapper.AgentModelMapper;
 import com.zsjz.ai.module.agent.middleware.CaseScopeMiddleware;
+import com.zsjz.ai.module.agent.middleware.PromptContextMiddleware;
+import com.zsjz.ai.module.agent.prompt.PromptAssembler;
 import com.zsjz.ai.module.agent.python.PythonExecutor;
 import com.zsjz.ai.module.agent.rag.EmbeddingProvider;
 import com.zsjz.ai.module.agent.rag.RagSchemaService;
@@ -47,10 +50,15 @@ import io.agentscope.harness.agent.filesystem.spec.LocalFilesystemSpec;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.Base64;
+import java.util.Comparator;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
+import java.util.stream.Stream;
 
 /**
  * Agent 实例管理服务(官方"无状态引擎单例"模式)。
@@ -180,12 +188,80 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
     public void deleteSessionMemory(String userId, String sessionId) {
         try {
             agentStateStore.delete(userId, sessionId);
+            // Redis 删掉后,池化 Agent 里还可能有该会话的内存缓存;不清掉会让下一次
+            // 同槽位调用继续读到旧上下文。
+            for (HarnessAgent agent : agentPool.values()) {
+                try {
+                    agent.clearStateCache(userId, sessionId);
+                } catch (Exception ignored) {
+                    // 某个实例不维护 stateCache 时忽略;持久化层已经删除
+                }
+            }
             log.info("已清理会话记忆: userId={}, sessionId={}", userId, sessionId);
         } catch (Exception e) {
             log.info("清理会话记忆失败(不影响会话删除): userId={}, sessionId={}", userId, sessionId, e);
         }
     }
 
+    /**
+     * 删除某个用户在 Agent 工作区里的会话转录目录。
+     *
+     * <p>Harness 的会话日志路径与 {@code SessionKey.storagePath()} 一致:
+     * {@code agents/{agentId}/sessions/{userId}/{sessionId}}(各段是 s_+Base64URL)。
+     * 这里只删精确匹配的会话目录,不碰同用户的其他会话。
+     */
+    public void deleteSessionTranscript(Long caseId, Long agentRowId, String userId, String sessionId) {
+        if (caseId == null || agentRowId == null || userId == null || sessionId == null) {
+            return;
+        }
+        Path agentsRoot = storageLayout.agentWorkspace(caseId, agentRowId)
+                .resolve(userId).resolve("agents");
+        if (!Files.isDirectory(agentsRoot)) {
+            return;
+        }
+        String userSegment = encodeSessionSegment(userId);
+        String sessionSegment = encodeSessionSegment(sessionId);
+        try (Stream<Path> paths = Files.walk(agentsRoot, 6)) {
+            List<Path> targets = paths
+                    .filter(Files::isDirectory)
+                    .filter(path -> sessionSegment.equals(path.getFileName().toString()))
+                    .filter(path -> path.getParent() != null
+                            && userSegment.equals(path.getParent().getFileName().toString()))
+                    .filter(path -> path.getParent().getParent() != null
+                            && "sessions".equals(path.getParent().getParent().getFileName().toString()))
+                    .toList();
+            for (Path target : targets) {
+                deleteRecursivelyQuietly(target);
+                log.info("已删除会话转录: caseId={}, userId={}, sessionId={}", caseId, userId, sessionId);
+            }
+        } catch (Exception e) {
+            log.info("删除会话转录失败(不影响会话删除): caseId={}, userId={}, sessionId={}, err={}",
+                    caseId, userId, sessionId, e.getMessage());
+        }
+    }
+
+    private static String encodeSessionSegment(String value) {
+        return "s_" + Base64.getUrlEncoder().withoutPadding()
+                .encodeToString(value.getBytes(StandardCharsets.UTF_8));
+    }
+
+    private static void deleteRecursivelyQuietly(Path root) {
+        if (root == null || !Files.exists(root)) {
+            return;
+        }
+        try (Stream<Path> paths = Files.walk(root)) {
+            paths.sorted(Comparator.reverseOrder()).forEach(path -> {
+                try {
+                    Files.deleteIfExists(path);
+                } catch (Exception ignored) {
+                    // best-effort:会话删除不能因为某个转录文件被占用而失败
+                }
+            });
+        } catch (Exception ignored) {
+            // best-effort
+        }
+    }
+
     /**
      * 取或建 agent 实例(池化,按 工作空间×agent×模型 组合去重)。
      *
@@ -237,7 +313,14 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
      * 避免页面展示的工具与实际装配的工具出现两套。
      */
     private void registerInfraTools(Toolkit toolkit) {
-        if (ragSchemaService.isAvailable()) {
+        registerInfraTools(toolkit, ragSchemaService.isAvailable());
+    }
+
+    /**
+     * 注册基础设施工具;RAG 可用性由调用方传入,保证「注册了工具」和「提示词写了指引」用同一个判断。
+     */
+    private void registerInfraTools(Toolkit toolkit, boolean ragAvailable) {
+        if (ragAvailable) {
             toolkit.registerTool(new RagSchemaSearchTool(ragSchemaService));
         }
         toolkit.registerTool(new SqlAnalysisTool(tableInfoMapper, tableFieldMapper, schemaCatalog));
@@ -273,9 +356,8 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         if (entry.getDescription() != null) {
             b.description(entry.getDescription());
         }
-        String sysPrompt = entry.getSysPrompt();
-        // sysPrompt 的最终值要等知识库工具注册后才知道(追加使用指引),
-        // 统一在 toolkit 装配完成后 b.sysPrompt(...) 一次写定
+        // 系统提示词分段装配:专家人设 → 通用工具规则 → 输出契约 → RAG/知识库指引。
+        // 知识库工具注册后才知道是否追加指引,所以统一在 toolkit 装配完成后一次写定。
         if (entry.getMaxIters() != null) {
             b.maxIters(entry.getMaxIters());
         }
@@ -286,7 +368,8 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         // 2) 业务域工具(按 call/trans/track/graph/person/file 分组,由 AgentToolRegistry 注册):
         //    默认只装备 person 组,其余组由模型调用 reset_equipped_tools 按需切换,避免每轮塞几十份 schema。
         Toolkit toolkit = new Toolkit();
-        registerInfraTools(toolkit);
+        boolean ragAvailable = ragSchemaService.isAvailable();
+        registerInfraTools(toolkit, ragAvailable);
         // 业务工具组:旧方案配置了 tools_allow_json → 只注册并装备这些组
         // (组外工具不注册 = 模型不可见、reset_equipped_tools 也切不过去,构成真实限制)
         // 工具包(tool_packs_json):包内工具与组白名单并集构成工具级白名单。
@@ -313,15 +396,14 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         // (description 只在工具实际注册时对模型可见,不会出现未注册工具名)。
         log.debug("方案业务工具装配完成: agentRowId={}, toolCount={}",
                 entry.getRowId(), toolkit.getToolNames().size());
-        sysPrompt = appendRenderPrompt(sysPrompt);
-        if (ragSchemaService.isAvailable()) {
-            sysPrompt = appendRagPrompt(sysPrompt);
-        }
-        // 知识库:绑定了知识库的方案默认注册 search_knowledge(基础设施工具,不受白名单约束),
-        // 并在 sysPrompt 追加使用指引;未绑定/嵌入模型不可用时跳过(fail-open)
-        sysPrompt = registerKnowledgeTool(toolkit, entry, sysPrompt);
+        // 知识库:绑定了知识库的方案默认注册 search_knowledge(基础设施工具,不受白名单约束);
+        // 未绑定/嵌入模型不可用时跳过(fail-open),此时不追加知识库指引。
+        KnowledgeBase knowledgeBase = registerKnowledgeTool(toolkit, entry);
         b.toolkit(toolkit);
-        b.sysPrompt(sysPrompt);
+        b.sysPrompt(PromptAssembler.render(PromptAssembler.systemSections(
+                entry.getSysPrompt(),
+                ragAvailable,
+                knowledgeBase == null ? null : knowledgeBase.getName())));
         // 注册 reset_equipped_tools 元工具(内部会调 toolkit.registerMetaTool()),
         // 模型据此在对话中自行装备/卸载业务工具组;必须放在 toolkit(...) 之后、build() 之前。
         b.enableMetaTool(true);
@@ -331,6 +413,11 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
 
         // 下一步引导建议:onAgent 钩子包裹整个推理流,对话结束后生成建议并追加 suggestions 事件
         b.middleware(new FollowupMiddleware(followupService, etlProperties.getFollowup(), modelId));
+        // 动态上下文(案件/日期/已装备工具组)不进 system prompt:每轮变化时才注入 synthetic 公告,
+        // 稳定前缀保持不变,也让模型跨天、切换工具组后能拿到最新状态。
+        CaseInfo caseInfo = workspaceId == null ? null : caseInfoMapper.selectById(workspaceId);
+        b.middleware(new PromptContextMiddleware(
+                caseInfo == null ? null : caseInfo.getName(), workspaceId, true));
         // 工具执行期(acting 阶段)重建案件作用域:业务工具查 @DS("slave") 案件库与
         // 产物 CSV 导出都依赖 CaseContextHolder,而 agentscope 执行池不在 Reactor 传播链上
         b.middleware(new CaseScopeMiddleware(workspaceId));
@@ -507,38 +594,24 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
      * <p>fail-open:库已删除 / 嵌入模型不可用时跳过注册并 log.info,不阻断对话
      * (绑定校验在保存时已做,运行期异常只降级为「没有该工具」)。
      *
-     * @return 追加知识库指引后的 sysPrompt(未注册时原样返回)
+     * @return 实际注册的知识库;未注册返回 null(调用方据此决定是否追加指引)
      */
-    private String registerKnowledgeTool(Toolkit toolkit, AgentEntity entry, String sysPrompt) {
+    private KnowledgeBase registerKnowledgeTool(Toolkit toolkit, AgentEntity entry) {
         Long kbId = entry.getKnowledgeBaseId();
         if (kbId == null) {
-            return sysPrompt;
+            return null;
         }
         KnowledgeBase kb = knowledgeBaseMapper.selectById(kbId);
         if (kb == null) {
             log.info("方案绑定的知识库不存在,跳过知识库工具注册: agentRowId={}, kbId={}", entry.getRowId(), kbId);
-            return sysPrompt;
+            return null;
         }
         if (!embeddingProvider.isAvailable()) {
             log.info("嵌入模型不可用,跳过知识库工具注册: agentRowId={}, kbId={}", entry.getRowId(), kbId);
-            return sysPrompt;
+            return null;
         }
         toolkit.registerTool(new KnowledgeSearchTool(knowledgeDocIndexer, kbId));
-        return appendKbPrompt(sysPrompt, kb.getName());
-    }
-
-    /**
-     * 在 sysPrompt 后追加知识库检索指引(Agentic RAG:Agent 自行决定何时检索)。
-     */
-    private String appendKbPrompt(String sysPrompt, String kbName) {
-        String kbPrompt = """
-
-                ## 知识库检索(重要)
-                你拥有 search_knowledge 工具,可按语义检索本方案绑定的知识库「%s」(返回知识片段与来源文档名)。
-                - 用户问题涉及领域知识、法规条文、业务规范、背景资料时,必须先检索再回答;引用片段时标注来源文档名。
-                - 检索不到相关内容时明确告知用户,禁止凭空编造知识内容。
-                - 检索 query 用自然语言描述知识点,一次检索不理想可换角度再次检索。""".formatted(kbName);
-        return sysPrompt.isBlank() ? kbPrompt.strip() : sysPrompt + kbPrompt;
+        return kb;
     }
 
     /** 内置专家不可编辑/删除;自建必须属于当前用户 */
@@ -639,53 +712,14 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         return distinct.isEmpty() ? null : Json.toStr(distinct);
     }
 
-    /**
-     * 在用户配置的 sysPrompt 后追加 RAG 检索指引(Agentic RAG:Agent 自行决定何时检索)
-     */
-    private String appendRagPrompt(String sysPrompt) {
-        String ragPrompt = """
-                ## 数据表结构检索(重要)
-                你拥有 search_table_schema 工具,可按语义检索模板库中已登记的表结构(物理表名、字段、类型、中文注释;含 AI 智能清洗新建的动态表)。
-                - 在编写任何 Python 查询/分析或回答"有哪些表/字段"类问题之前,必须先调用该工具检索,禁止凭空猜测表名和字段名。
-                - 检索 query 用自然语言描述目标(如"包含手机号和身份证号的表")。
-                - 检索结果已按相似度排序,结合字段注释理解表用途后再编写 Python/DuckDB 查询。""";
-        return sysPrompt.isBlank() ? ragPrompt.strip() : sysPrompt + ragPrompt;
-    }
-
-    /**
-     * 在用户配置的 sysPrompt 后追加通用工具使用与输出规则。
-     *
-     * <p>这里只放跨工具通用的规则,不列举具体业务工具、业务组或场景:
-     * 某个工具怎么用、返回什么、能不能画图,都写在该工具的 description 里。
-     * description 只在工具实际注册时对模型可见——提示词里不出现未注册工具名,
-     * 模型就不会照着提示词去调用一个不存在的工具。
-     */
-    private String appendRenderPrompt(String sysPrompt) {
-        String renderPrompt = buildRenderPrompt();
-        return sysPrompt == null || sysPrompt.isBlank() ? renderPrompt.strip() : sysPrompt + renderPrompt;
-    }
-
     /**
      * 通用提示词正文(包级可见,便于单测)。
      *
-     * <p>刻意保持精简:只回答「能用什么工具、没有合适工具怎么办、结果怎么输出」三个问题。
-     * 具体工具的入参、口径、可视化契约由各自的 {@code @Tool(description=...)} 负责。
-     * {@code execute_python} 是始终注册的通用兜底:专用工具不匹配时用它完成跨表、聚合、
-     * 清洗、算法等复杂计算,不写“能力受限”的放弃分支。
+     * <p>实现已迁到 {@link PromptAssembler}:这里只保留入口,避免调用方和测试来回改。
+     * 工具规则/输出契约都是稳定段,不点名具体业务工具,也不写“能力受限”的放弃分支。
      */
     static String buildRenderPrompt() {
-        return """
-
-                ## 工具规则
-                1. 只使用当前工具列表里实际存在的工具;不要臆造。
-                2. 优先用最匹配的专用工具;没有合适的专用工具,或参数表达不了需求时,用 query_table_data(单表)或 execute_python(JOIN/聚合/复杂计算)兜底,不要硬套。
-                3. 数据或字段不存在时明确说明缺什么,不要编造;工具报错先按提示修正,连续失败两次就换工具或缩小范围。
-                4. 正文只写结论;数据明细用 Markdown 表格或 CSV 产物。
-
-                ## 输出
-                - 代码、SQL、JSON、HTML 用 ```语言 围栏输出,前端会按语言高亮。
-                - 常规图表:调 render_chart 校验 option,再放 ```echarts 围栏。
-                - 其它可视化按对应工具 description 的返回契约输出,前端会自动渲染。""";
+        return PromptAssembler.renderRules();
     }
 
 }

+ 158 - 19
ai-server/src/main/java/com/zsjz/ai/module/agent/service/impl/AgentChatServiceImpl.java

@@ -40,7 +40,10 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.http.codec.ServerSentEvent;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
 import org.springframework.util.StringUtils;
+import reactor.core.Disposable;
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 import reactor.core.publisher.Sinks;
@@ -91,6 +94,12 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      */
     private final ConcurrentHashMap<Long, Semaphore> streamLocks = new ConcurrentHashMap<>();
 
+    /** 当前会话的在途流订阅:删除会话时先取消它,再等闸门释放 */
+    private final ConcurrentHashMap<Long, ActiveStream> activeStreams = new ConcurrentHashMap<>();
+
+    /** 正在删除的会话:取消/中断回调不应再把半截消息或产物写回 */
+    private final Set<Long> deletingSessions = ConcurrentHashMap.newKeySet();
+
     private final AgentChatSessionMapper chatSessionMapper;
     private final AgentMessageMapper messageMapper;
     private final AgentService agentService;
@@ -134,6 +143,8 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         AgentChatSession entity = new AgentChatSession();
         entity.setId(generateId());
         entity.setCaseId(caseId);
+        // 记录创建者:删除会话时按它清理 Redis 记忆槽位(RuntimeContext 也用它作 userId)
+        entity.setUserId(StpUtil.getLoginIdAsLong());
         entity.setAgentId(dto.getAgentId() != null ? dto.getAgentId() : AgentService.DEFAULT_AGENT_ROW_ID);
      
         entity.setTitle(dto.getTitle() != null ? dto.getTitle() : DEFAULT_TITLE);
@@ -195,20 +206,99 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         AgentChatSession session = requireSession(sessionId);
         requireSessionInOpenCase(session);
 
-        // 删除会话下的所有消息
-        messageMapper.delete(
-                new LambdaQueryWrapper<AgentMessage>()
-                        .eq(AgentMessage::getSessionId, sessionId)
-        );
+        // 删除期间持有会话闸门:先自动取消在途流,等它释放闸门后再删;
+        // 删除提交前也不允许新流进来,否则旧流会在删除后把 AgentState 写回 Redis,
+        // 或往已删会话补消息。
+        Semaphore gate = streamLocks.computeIfAbsent(sessionId, k -> new Semaphore(1));
+        deletingSessions.add(sessionId);
+        boolean gateAcquired = false;
+        boolean releasedAfterTransaction = false;
+        try {
+            ActiveStream active = activeStreams.get(sessionId);
+            if (active != null) {
+                active.cancel();
+            }
+            gateAcquired = acquireGateAfterCancel(sessionId, gate);
+            if (!gateAcquired) {
+                // 取消可能和订阅竞态,给第二次机会
+                active = activeStreams.get(sessionId);
+                if (active != null) {
+                    active.cancel();
+                }
+                gateAcquired = acquireGateAfterCancel(sessionId, gate);
+            }
+            if (!gateAcquired) {
+                throw new ServerException(409, "会话停止超时,请稍后重试");
+            }
+
+            // 删除会话下的所有消息
+            messageMapper.delete(
+                    new LambdaQueryWrapper<AgentMessage>()
+                            .eq(AgentMessage::getSessionId, sessionId)
+            );
+
+            // 删除会话
+            chatSessionMapper.deleteById(sessionId);
+            // 会话附件:数据库行 + 向量 + cases/{caseId}/ai/sessions/{sessionId} 目录
+            chatAttachmentService.deleteBySession(session.getCaseId(), sessionId);
+            // 记忆槽位 = (userId, sessionId)。会话创建者与当前操作者都要清;
+            // 只清当前用户会在"创建者 ≠ 删除者"时留下创建者的 Redis 状态。
+            Set<String> memoryUsers = new LinkedHashSet<>();
+            if (session.getUserId() != null) {
+                memoryUsers.add(String.valueOf(session.getUserId()));
+            }
+            memoryUsers.add(StpUtil.getLoginIdAsString());
+            Long agentRowId = session.getAgentId() != null
+                    ? session.getAgentId() : AgentService.DEFAULT_AGENT_ROW_ID;
+            for (String memoryUser : memoryUsers) {
+                agentService.deleteSessionMemory(memoryUser, String.valueOf(sessionId));
+                agentService.deleteSessionTranscript(session.getCaseId(), agentRowId,
+                        memoryUser, String.valueOf(sessionId));
+            }
+            releaseSessionGateAfterTransaction(sessionId, gate);
+            releasedAfterTransaction = true;
+            log.info("删除会话成功: {}", sessionId);
+        } finally {
+            if (!releasedAfterTransaction) {
+                if (gateAcquired) {
+                    gate.release();
+                }
+                deletingSessions.remove(sessionId);
+            }
+        }
+    }
+
+    /**
+     * 取消流后等它释放闸门;超时返回 false,由调用方决定是否重试。
+     */
+    private static boolean acquireGateAfterCancel(Long sessionId, Semaphore gate) {
+        try {
+            return gate.tryAcquire(5, java.util.concurrent.TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            log.info("等待会话流停止时被中断: sessionId={}", sessionId);
+            return false;
+        }
+    }
 
-        // 删除会话
-        chatSessionMapper.deleteById(sessionId);
-        // 会话附件:数据库行 + 向量 + cases/{caseId}/ai/sessions/{sessionId} 目录
-        chatAttachmentService.deleteBySession(session.getCaseId(), sessionId);
-        // 记忆槽位与对话时一致(RuntimeContext 的 userId = 登录用户 ID,sessionId = 会话主键),
-        // 会话状态已落 Redis,不跟着删就会永久残留
-        agentService.deleteSessionMemory(StpUtil.getLoginIdAsString(), String.valueOf(sessionId));
-        log.info("删除会话成功: {}", sessionId);
+    /**
+     * 事务提交后再释放删除闸门并移除条目;非事务调用(单测/内部直调)立即释放。
+     */
+    private void releaseSessionGateAfterTransaction(Long sessionId, Semaphore gate) {
+        if (TransactionSynchronizationManager.isSynchronizationActive()) {
+            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+                @Override
+                public void afterCompletion(int status) {
+                    gate.release();
+                    streamLocks.remove(sessionId, gate);
+                    deletingSessions.remove(sessionId);
+                }
+            });
+        } else {
+            gate.release();
+            streamLocks.remove(sessionId, gate);
+            deletingSessions.remove(sessionId);
+        }
     }
 
     @Override
@@ -371,7 +461,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
                     if (sessionId != null) {
                         // 出错前已生成的文件也登记为产物(帧已失败,事件只用于落库)
                         appendGeneratedArtifactEvents(process.caseId, process.userId, process.agentRowId,
-                                process.turnStart, process, new ArrayList<>(),
+                                String.valueOf(sessionId), process.turnStart, process, new ArrayList<>(),
                                 process.toolInputs, process.toolResults, process.toolNames);
                         Mono.fromRunnable(() -> persistErrorMessage(sessionId, errorMsg, process))
                                 .subscribeOn(Schedulers.boundedElastic())
@@ -401,10 +491,17 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         if (!gate.tryAcquire()) {
             return Flux.just(sse("error", Map.of("type", "error", "error", "该会话正在回复中,请等待当前回复完成后再发送")));
         }
+        ActiveStream active = new ActiveStream();
+        activeStreams.put(sessionId, active);
         try {
             return doStreamLocked(sessionId, req, process, openCaseId)
-                    .doFinally(signal -> gate.release());
+                    .doOnSubscribe(sub -> active.attach(sub::cancel))
+                    .doFinally(signal -> {
+                        activeStreams.remove(sessionId, active);
+                        gate.release();
+                    });
         } catch (RuntimeException e) {
+            activeStreams.remove(sessionId, active);
             gate.release();
             throw e;
         }
@@ -599,7 +696,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
                 }
                 // 模型/沙箱生成的文件(HTML/PNG/Word 等)登记为产物,并补发合成 tool 事件,
                 // 前端产物栏与工具卡片随本轮实时出现;同一份事件也会随消息落库,刷新后可恢复
-                appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, turnStart,
+                appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
                         process, frames, toolInputs, toolResults, toolNames);
                 String toolEventsJson = buildToolEventsJson(toolInputs, toolResults, toolNames);
                 String thinkingJson = buildThinkingMetadata(accumulatedThinking.get().toString());
@@ -612,10 +709,14 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
             }
             return Flux.fromIterable(frames);
         }).doOnCancel(() -> {
+            // 删除会话触发的取消不落半截消息/产物:随后整个会话都会被删掉
+            if (deletingSessions.contains(sessionId)) {
+                return;
+            }
             // 用户主动中止:若 AgentResultEvent 尚未到达,保存已流式输出的部分内容
             if (!resultPersisted.get()) {
                 // 中断前已生成的文件也登记为产物(帧已取消,事件只用于落库)
-                appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, turnStart,
+                appendGeneratedArtifactEvents(graphCaseId, graphUserId, agentRowId, sessionKey, turnStart,
                         process, new ArrayList<>(), toolInputs, toolResults, toolNames);
                 String partialText = accumulatedText.get().toString().trim();
                 String toolEventsJson = buildToolEventsJson(toolInputs, toolResults, toolNames);
@@ -788,6 +889,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      */
     private void persistErrorMessage(Long sessionId, String errorMsg, StreamProcess process) {
         try {
+            if (deletingSessions.contains(sessionId)
+                    || chatSessionMapper.selectById(sessionId) == null) {
+                return;
+            }
             // 完整回答已落库时(AgentResultEvent 先到、后置环节才出错)不再重复携带过程数据,
             // 避免同轮的时间线/产物在历史里出现两份
             boolean processLost = process != null && !process.resultPersisted.get();
@@ -823,6 +928,10 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      */
     private void persistPartialMessage(Long sessionId, String partialText, String toolEventsJson, String thinkingJson) {
         try {
+            if (deletingSessions.contains(sessionId)
+                    || chatSessionMapper.selectById(sessionId) == null) {
+                return;
+            }
             AgentMessage msg = new AgentMessage();
             msg.setSessionId(sessionId);
             msg.setRole("assistant");
@@ -979,7 +1088,7 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      * 扫描内部已吃掉异常,失败不影响回复落库。
      */
     private void appendGeneratedArtifactEvents(Long caseId, Long userId, Long agentRowId,
-                                               Instant since, StreamProcess process,
+                                               String sessionId, Instant since, StreamProcess process,
                                                List<ServerSentEvent<String>> frames,
                                                Map<String, StringBuilder> toolInputs,
                                                Map<String, StringBuilder> toolResults,
@@ -987,13 +1096,17 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
         if (caseId == null || userId == null || agentRowId == null) {
             return;
         }
+        Long parsedSessionId = parseSessionId(sessionId);
+        if (parsedSessionId != null && deletingSessions.contains(parsedSessionId)) {
+            return;
+        }
         if (!process.artifactsScanned.compareAndSet(false, true)) {
             return;
         }
         List<Map<String, Object>> artifacts;
         try {
             artifacts = CaseContextHolder.callWith(caseId, userId,
-                    () -> artifactScanner.scanAndRegister(userId, caseId, agentRowId, since));
+                    () -> artifactScanner.scanAndRegister(userId, caseId, agentRowId, sessionId, since));
         } catch (Exception e) {
             log.info("扫描生成文件产物失败: caseId={}, error={}", caseId, e.getMessage());
             return;
@@ -1149,6 +1262,32 @@ public class AgentChatServiceImpl extends ServiceImpl<AgentChatSessionMapper, Ag
      * 用户中止随 interrupted 消息落库,<b>中途出错也要随错误消息落库</b> ——
      * 三处共用同一份数据,任何终态都不丢过程记录。条目极少、随请求释放,不额外清理。
      */
+    /**
+     * 一条在途流的可取消句柄。
+     *
+     * <p>Flux 可能在删除请求到达时还没被订阅(attach 尚未发生),所以先记 cancelRequested;
+     * 订阅时再补一次 dispose,避免竞态下停在半路。
+     */
+    private static final class ActiveStream {
+        private final AtomicReference<Disposable> disposable = new AtomicReference<>();
+        private volatile boolean cancelRequested;
+
+        void attach(Disposable value) {
+            disposable.set(value);
+            if (cancelRequested) {
+                value.dispose();
+            }
+        }
+
+        void cancel() {
+            cancelRequested = true;
+            Disposable value = disposable.get();
+            if (value != null) {
+                value.dispose();
+            }
+        }
+    }
+
     private static final class StreamProcess {
         final Map<String, StringBuilder> toolInputs = new ConcurrentHashMap<>();
         final Map<String, StringBuilder> toolResults = new ConcurrentHashMap<>();

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/CallAnalysisTool.java

@@ -104,7 +104,7 @@ public class CallAnalysisTool {
      * 通话记录原始明细
      */
     @Tool(name = "get_call_records",
-          description = "查询通话原始明细(一行一通);按姓名/号码/主被叫/类型/基站/日期筛选,汇总用 person 组。",
+          description = "查询通话原始明细(一行一通);按姓名/号码/主被叫/类型/基站/日期筛选。只要通话次数/汇总,改用当前工具列表中的通话汇总工具,不要用本工具逐条拉全量。",
           readOnly = true)
     public ToolResultBlock getCallRecords(
             @ToolParam(name = "query", description = "通话记录筛选条件,字段全部可选(但至少要能定位到人/号码/时段)")

+ 2 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/FileAnalysisTool.java

@@ -113,7 +113,7 @@ public class FileAnalysisTool {
      * 检索非表格材料清单
      */
     @Tool(name = "list_file_profiles",
-          description = "检索非表格材料清单(txt/doc/pdf/ppt/压缩包),返回分类与摘要;看正文用 get_file_sample。",
+          description = "检索非表格材料清单(txt/doc/pdf/ppt/压缩包),返回分类与摘要;看正文用当前工具列表中的材料正文工具。",
           readOnly = true)
     public ToolResultBlock listFileProfiles(
             @ToolParam(name = "query", description = "筛选条件,全部可空(不传即查全部)")
@@ -159,7 +159,7 @@ public class FileAnalysisTool {
      * 读取某份材料的正文样本
      */
     @Tool(name = "get_file_sample",
-          description = "读取某份非表格材料的正文片段(Tika 抽取的文本样本);fileId 从 list_file_profiles 取。",
+          description = "读取某份非表格材料的正文片段(Tika 抽取的文本样本);fileId 从当前工具列表中的材料清单工具取。",
           readOnly = true)
     public ToolResultBlock getFileSample(
             @ToolParam(name = "query", description = "材料 ID 与返回长度")

+ 7 - 7
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PersonAnalysisTool.java

@@ -113,7 +113,7 @@ public class PersonAnalysisTool {
      * 通话数据画像汇总(单对象)
      */
     @Tool(name = "get_person_call_profile",
-          description = "查询某人的通话画像:号码数/运营商、通话次数、对方号码数、日期范围、主被叫占比。personName 必传;只看汇总,明细用 get_call_records。",
+          description = "查询某人的通话画像:号码数/运营商、通话次数、对方号码数、日期范围、主被叫占比。personName 必传;只看汇总,逐通明细用当前工具列表中的话单明细工具。",
           readOnly = true)
     public ToolResultBlock getPersonCallProfile(
             @ToolParam(name = "personName", description = "本方(机主)姓名,精确匹配,必传,如「张三」") String personName) {
@@ -160,7 +160,7 @@ public class PersonAnalysisTool {
      * 最常联系对象(按对方号码聚合,次数降序)
      */
     @Tool(name = "stat_person_call_top10",
-          description = "按对方号码统计某人的通话次数排行。personName 必传,日期可选;综合汇总用 stat_call_record_summary。",
+          description = "按对方号码统计某人的通话次数排行。personName 必传,日期可选;综合汇总用当前工具列表中的通话汇总工具。",
           readOnly = true)
     public ToolResultBlock statPersonCallTop10(
             @ToolParam(name = "query", description = "常联系对象统计条件,personName 必传")
@@ -188,7 +188,7 @@ public class PersonAnalysisTool {
      * 通话记录汇总(按本方号码 + 对方姓名 + 对方号码)
      */
     @Tool(name = "stat_call_record_summary",
-          description = "按「本方号码+对方姓名+号码」统计某人的通话次数。personName 必传,可选 otherName/otherPhone/日期;明细用 get_call_records。",
+          description = "按「本方号码+对方姓名+号码」统计某人的通话次数。personName 必传,可选 otherName/otherPhone/日期;逐通明细或号码排行用当前工具列表中的对应工具。",
           readOnly = true)
     public ToolResultBlock statCallRecordSummary(
             @ToolParam(name = "query", description = "通话记录汇总条件,personName 必传")
@@ -223,7 +223,7 @@ public class PersonAnalysisTool {
      * 交易数据画像汇总(单对象)
      */
     @Tool(name = "get_person_trans_profile",
-          description = "查询某人的交易画像:卡数/银行、交易总额、收支、笔数、余额合计。personName 必传;明细用 stat_trans_record_summary 或 execute_python。",
+          description = "查询某人的交易画像:卡数/银行、交易总额、收支、笔数、余额合计。personName 必传;明细用当前工具列表中的交易流水工具,或 execute_python。",
           readOnly = true)
     public ToolResultBlock getPersonTransProfile(
             @ToolParam(name = "personName", description = "本方(机主)姓名,精确匹配,必传,如「张三」") String personName) {
@@ -284,7 +284,7 @@ public class PersonAnalysisTool {
      * 交易记录汇总(按本方/对方卡号、对方姓名聚合)
      */
     @Tool(name = "stat_trans_record_summary",
-          description = "按「本方姓名+卡号、对方姓名+卡号、银行」统计交易笔数与金额。personNames 可多传(不传全案),可筛 otherName/otherCardNo/日期/现金。",
+          description = "按「本方姓名+卡号、对方姓名+卡号、银行」统计交易笔数与金额。personNames 可多传(不传全案),可筛 otherName/otherCardNo/日期/现金;逐笔明细用当前工具列表中的交易流水工具。",
           readOnly = true)
     public ToolResultBlock statTransRecordSummary(
             @ToolParam(name = "query", description = "交易记录汇总条件,字段全部可选")
@@ -354,7 +354,7 @@ public class PersonAnalysisTool {
      * 交易金额月度趋势
      */
     @Tool(name = "stat_trans_amount_trend_month",
-          description = "按月统计交易金额趋势(收入/支出)。personName 通常传,可筛对手/日期;按年用 stat_trans_amount_trend_year。",
+          description = "按月统计交易金额趋势(收入/支出)。personName 通常传,可筛对手/日期;按年用当前工具列表中的年度趋势工具。",
           readOnly = true)
     public ToolResultBlock statTransAmountTrendMonth(
             @ToolParam(name = "query", description = "交易趋势条件,字段全部可选(建议传 personName)")
@@ -373,7 +373,7 @@ public class PersonAnalysisTool {
      * 交易金额年度趋势
      */
     @Tool(name = "stat_trans_amount_trend_year",
-          description = "按年统计交易金额趋势(收入/支出)。personName 通常传,可筛对手/日期;按月用 stat_trans_amount_trend_month。",
+          description = "按年统计交易金额趋势(收入/支出)。personName 通常传,可筛对手/日期;按月用当前工具列表中的月度趋势工具。",
           readOnly = true)
     public ToolResultBlock statTransAmountTrendYear(
             @ToolParam(name = "query", description = "交易趋势条件,字段全部可选(建议传 personName)")

+ 9 - 3
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PythonAnalysisTool.java

@@ -3,6 +3,7 @@ package com.zsjz.ai.module.agent.tools;
 import com.zsjz.ai.common.utils.Json;
 import com.zsjz.ai.module.agent.python.PythonExecutor;
 import com.zsjz.ai.module.agent.render.RelationGraphPayload;
+import io.agentscope.core.agent.RuntimeContext;
 import io.agentscope.core.message.ToolResultBlock;
 import io.agentscope.core.tool.Tool;
 import io.agentscope.core.tool.ToolParam;
@@ -35,17 +36,22 @@ public class PythonAnalysisTool {
      */
     @Tool(name = "execute_python",
           description = "通用 Python 执行器(pandas/numpy/duckdb/matplotlib/openpyxl/python-docx):"
-                  + "查询、JOIN、清洗/聚合、算法、可视化、生成报告。"
+                  + "单表条件查询优先用当前工具列表中的表查询工具;JOIN/聚合/清洗/算法/可视化/生成报告用本工具。"
                   + "ETL_DB_PATH 是当前案件 DuckDB 的只读快照;print() 输出结论,"
                   + "open/pathlib 可直接读写当前目录,生成文件自动进产物栏。"
                   + "关系图用 zgraph.emit_relation_graph(nodes, edges, title):"
                   + "nodes=[{id,label,type}],edges=[{source,target,relation,weight}];"
                   + "source/target 对应 node.id,relation 是线标签。",
-          readOnly = true)
+          readOnly = false,
+          concurrencySafe = false)
     public ToolResultBlock executePython(
+            RuntimeContext ctx,
             @ToolParam(name = "code", description = "Python 3 代码,必填;单次执行默认 60 秒") String code) {
         try {
-            PythonExecutor.PythonResult result = pythonExecutor.execute(code);
+            PythonExecutor.PythonResult result = pythonExecutor.execute(
+                    code,
+                    ctx == null ? null : ctx.getUserId(),
+                    ctx == null ? null : ctx.getSessionId());
 
             Map<String, Object> data = new LinkedHashMap<>();
             data.put("exitCode", result.exitCode());

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/RagSchemaSearchTool.java

@@ -33,7 +33,7 @@ public class RagSchemaSearchTool {
      * 按语义检索可用的表结构(模板库表 + AI 智能清洗动态表 + wa_mforensics 取证数据表)
      */
     @Tool(name = "search_table_schema",
-          description = "按语义检索表结构(模板表、ai_clean_ 动态表、wa_mforensics_ 取证表),返回表名/字段/注释。",
+          description = "按语义检索表结构(模板表、ai_clean_ 动态表、wa_mforensics_ 取证表),返回表名/字段/注释;已知表名看字段用 list_tables。",
           readOnly = true)
     public ToolResultBlock searchTableSchema(
             @ToolParam(name = "query", description = "自然语言查询,必填,例如:包含手机号和身份证号的表") String query,

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/SqlAnalysisTool.java

@@ -67,7 +67,7 @@ public class SqlAnalysisTool {
      * 物理表名/物理列名见 {@link #loadMetadataTableCatalog()}。
      */
     @Tool(name = "list_tables",
-          description = "列出模板库已登记的可查表及字段(模板表 + ai_clean_ 动态表);取证表用 search_table_schema。",
+          description = "列出模板库已登记的可查表及字段(模板表 + ai_clean_ 动态表);取证表/语义检索用当前工具列表中的表结构检索工具(RAG 可用时)。",
           readOnly = true)
     public ToolResultBlock listTables() {
         try {

+ 46 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/ToolDescriptor.java

@@ -0,0 +1,46 @@
+package com.zsjz.ai.module.agent.tools;
+
+import java.util.List;
+
+/**
+ * 工具契约描述(只读元数据,不参与工具注册)。
+ *
+ * <p>借鉴 ZCode 的「工具 = 元数据 + 路由描述 + schema + 执行器」:注解负责模型可见的
+ * name/description/schema,本类把治理所需的字段集中成一份可查询的目录,供
+ * 契约测试、工具目录页、未来的权限/调度使用。
+ *
+ * <p>{@code group} 为 {@code base} 表示基础设施工具(不属于任何业务组,始终可见)。
+ * {@code siblings} 是易混淆的兄弟工具,用于契约测试检查“路由句”是否写清楚。
+ *
+ * @param name            工具名(@Tool(name))
+ * @param group           所属业务组;基础设施工具为 base
+ * @param description     模型可见的完整描述
+ * @param capability      描述的第一句(目录页/检索用的短能力说明)
+ * @param readOnly        是否只读
+ * @param destructive     是否可能造成不可逆副作用
+ * @param concurrentSafe  是否可与其他工具并行执行
+ * @param riskLevel       low / medium / high
+ * @param needsApproval   是否需要人工确认
+ * @param timeoutMs       建议执行超时
+ * @param resultBudget    进模型上下文的文本预算(字符数)
+ * @param siblings        易混淆的兄弟工具名
+ */
+public record ToolDescriptor(
+        String name,
+        String group,
+        String description,
+        String capability,
+        boolean readOnly,
+        boolean destructive,
+        boolean concurrentSafe,
+        String riskLevel,
+        boolean needsApproval,
+        int timeoutMs,
+        int resultBudget,
+        List<String> siblings
+) {
+
+    public ToolDescriptor {
+        siblings = siblings == null ? List.of() : List.copyOf(siblings);
+    }
+}

+ 186 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/ToolMetadataRegistry.java

@@ -0,0 +1,186 @@
+package com.zsjz.ai.module.agent.tools;
+
+import com.zsjz.ai.module.agent.registry.ToolAnnotationScanner;
+import com.zsjz.ai.module.agent.registry.ToolAnnotationScanner.ScannedTool;
+import io.agentscope.core.tool.Tool;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * 工具契约目录:把散落在 {@code @Tool} 注解、业务组清单和高风险配置里的元数据合并成
+ * 一份可查询的 {@link ToolDescriptor} 列表。
+ *
+ * <h3>为什么需要它</h3>
+ * AgentScope 的 {@code @Tool} 只承载模型可见的 name/description/schema/readOnly/concurrencySafe,
+ * 但调度、权限、目录页、契约测试还需要「业务组、风险级别、是否需审批、结果预算、兄弟工具」
+ * 这些信息。它们不适合塞进每个注解,也不该散落在多个 service 里,所以集中在本类。
+ *
+ * <h3>边界</h3>
+ * 本类<b>不参与工具注册</b>:AgentScope 仍从注解生成 schema;本类只读注解和静态配置,
+ * 不改变工具行为。这样 Phase A 可以低风险落地,后续权限/调度再消费这些元数据。
+ *
+ * @author cc
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class ToolMetadataRegistry {
+
+    /** 不属于任何业务组的工具归到 base */
+    private static final String BASE_GROUP = "base";
+
+    /** 默认建议超时(毫秒) */
+    private static final int DEFAULT_TIMEOUT_MS = 30_000;
+
+    /**
+     * 高风险工具策略:默认(不在表里)= 只读、低风险、无需审批、30 秒。
+     * 只维护真正需要区别对待的工具,避免给每个工具重复配置。
+     */
+    private static final Map<String, Policy> POLICIES = Map.of(
+            // execute_python 按产品要求完全放开(可读写文件/进程/网络),只记录风险,不做审批拦截。
+            "execute_python", new Policy(true, "high", false, 90_000)
+    );
+
+    /**
+     * 易混淆工具的路由关系。
+     *
+     * <p>契约测试会用这张表检查描述里是否写了“用 X 而不是本工具”,并强制
+     * 兄弟工具属于始终注册的 base 工具。工具包可以按工具名裁剪,连同组兄弟都不保证存在;
+     * 描述里只要出现具体业务工具名,就可能把模型引向一个当前不可见的工具。
+     */
+    private static final Map<String, List<String>> SIBLINGS = Map.ofEntries(
+            // 只有始终注册的 base 工具(execute_python / list_tables)才允许在描述里点名。
+            // 业务工具即使同组也可能被工具包白名单裁掉,所以组内路由一律用通用措辞,
+            // 不写具体工具名(见 ToolDescriptionContractTest)。
+            Map.entry("query_table_data", List.of("execute_python")),
+            Map.entry("search_table_schema", List.of("list_tables")),
+            Map.entry("get_case_graph", List.of("execute_python"))
+    );
+
+    private final ToolAnnotationScanner scanner;
+
+    /** 惰性构建:工具注解在启动后不会变化,构建一次即可 */
+    private volatile List<ToolDescriptor> cache;
+
+    /**
+     * 全部工具契约(按工具名排序)。
+     */
+    public List<ToolDescriptor> all() {
+        List<ToolDescriptor> local = cache;
+        if (local == null) {
+            synchronized (this) {
+                local = cache;
+                if (local == null) {
+                    local = build();
+                    cache = local;
+                }
+            }
+        }
+        return local;
+    }
+
+    /**
+     * 按工具名查契约。
+     */
+    public Optional<ToolDescriptor> find(String name) {
+        if (name == null || name.isBlank()) {
+            return Optional.empty();
+        }
+        return all().stream().filter(tool -> name.equals(tool.name())).findFirst();
+    }
+
+    private List<ToolDescriptor> build() {
+        List<ToolDescriptor> result = new ArrayList<>();
+        for (ScannedTool scanned : scanner.scan()) {
+            result.add(describe(scanned));
+        }
+        result.sort(Comparator.comparing(ToolDescriptor::name));
+        log.debug("工具契约目录构建完成: {} 个", result.size());
+        return List.copyOf(result);
+    }
+
+    private ToolDescriptor describe(ScannedTool scanned) {
+        Tool annotation = findAnnotation(scanned);
+        String description = annotation != null ? annotation.description() : scanned.description();
+        boolean readOnly = annotation != null ? annotation.readOnly() : scanned.readOnly();
+        // 注解读取失败时保守地视为不可并行:宁可串行,也不要让状态型工具并发跑。
+        boolean concurrentSafe = annotation != null && annotation.concurrencySafe();
+
+        Policy policy = POLICIES.get(scanned.name());
+        boolean destructive = policy != null && policy.destructive();
+        String riskLevel = policy != null ? policy.riskLevel() : "low";
+        boolean needsApproval = policy != null && policy.needsApproval();
+        int timeoutMs = policy != null ? policy.timeoutMs() : DEFAULT_TIMEOUT_MS;
+
+        return new ToolDescriptor(
+                scanned.name(),
+                groupOf(scanned.name()),
+                description,
+                capability(description),
+                readOnly,
+                destructive,
+                concurrentSafe,
+                riskLevel,
+                needsApproval,
+                timeoutMs,
+                ToolResultLimits.maxChars(scanned.name()),
+                SIBLINGS.getOrDefault(scanned.name(), List.of()));
+    }
+
+    /**
+     * 从扫描结果反查 @Tool 注解:{@link ToolAnnotationScanner} 只带了 name/description/readOnly,
+     * concurrencySafe 等字段仍以注解为准。
+     */
+    private static Tool findAnnotation(ScannedTool scanned) {
+        try {
+            Class<?> clazz = Class.forName(scanned.className(), false,
+                    ToolMetadataRegistry.class.getClassLoader());
+            for (Method method : clazz.getDeclaredMethods()) {
+                Tool tool = method.getAnnotation(Tool.class);
+                if (tool != null && scanned.name().equals(tool.name())) {
+                    return tool;
+                }
+            }
+        } catch (Throwable e) {
+            log.debug("读取工具注解失败: {} ({})", scanned.name(), e.getMessage());
+        }
+        return null;
+    }
+
+    /**
+     * 工具所属业务组;不在任何业务组里的(基础设施工具)归 base。
+     */
+    private static String groupOf(String name) {
+        for (String group : AgentToolRegistry.registeredGroupNames()) {
+            if (AgentToolRegistry.groupToolNames(group).contains(name)) {
+                return group;
+            }
+        }
+        return BASE_GROUP;
+    }
+
+    /**
+     * 描述的第一句作为短能力说明(目录页/检索用)。
+     */
+    private static String capability(String description) {
+        String text = description == null ? "" : description.trim();
+        int end = text.indexOf('。');
+        String first = end > 0 ? text.substring(0, end) : text;
+        if (first.length() > 80) {
+            first = first.substring(0, 77) + "…";
+        }
+        return first;
+    }
+
+    /** 高风险工具的策略覆盖 */
+    private record Policy(boolean destructive, String riskLevel, boolean needsApproval, int timeoutMs) {
+    }
+}

+ 4 - 4
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/TransAnalysisTool.java

@@ -147,7 +147,7 @@ public class TransAnalysisTool {
      * 大额交易第一层:按对手方汇总
      */
     @Tool(name = "stat_trans_big_summary",
-          description = "统计大额交易第一层:按「本方姓名 + 对方姓名 + 对方卡号」汇总大额交易的笔数与总金额,用于快速看出「谁和谁之间有大额资金往来」。",
+          description = "统计大额交易第一层:按「本方姓名+对方姓名+对方卡号」汇总笔数与金额。看日期分布用当前工具列表中的按日期统计工具,逐笔用其中的大额明细工具。",
           readOnly = true)
     public ToolResultBlock statTransBigSummary(
             @ToolParam(name = "query", description = "大额交易筛选条件,字段全部可选")
@@ -168,7 +168,7 @@ public class TransAnalysisTool {
      * 大额交易第二层:按交易日期聚合
      */
     @Tool(name = "stat_trans_big_by_date",
-          description = "统计大额交易第二层:按「交易日期」聚合某个对手方的大额交易笔数与金额,用于看「和某人的大额往来集中在哪些日子」。",
+          description = "统计大额交易第二层:按交易日期聚合某对手的大额笔数与金额。逐笔用当前工具列表中的大额明细工具。",
           readOnly = true)
     public ToolResultBlock statTransBigByDate(
             @ToolParam(name = "query", description = "大额交易筛选条件,建议传 otherName 定位对手")
@@ -189,7 +189,7 @@ public class TransAnalysisTool {
      * 大额交易第三层:按日期分组的交易明细
      */
     @Tool(name = "stat_trans_big_detail",
-          description = "统计大额交易第三层:按日期分组列出大额交易的逐笔明细(日期、金额、收付方向、交易ID)。",
+          description = "统计大额交易第三层:按日期分组列出逐笔明细(日期、金额、收付方向、交易ID)。先按对手汇总或按日期定位,再下钻本工具。",
           readOnly = true)
     public ToolResultBlock statTransBigDetail(
             @ToolParam(name = "query", description = "大额交易筛选条件,建议传 otherName 定位对手")
@@ -497,7 +497,7 @@ public class TransAnalysisTool {
      * 交易明细(原始记录)
      */
     @Tool(name = "get_trans_records",
-          description = "查询交易原始明细(一行一笔);按姓名/卡号/收付方向/金额/摘要/日期/现金筛选,汇总用 person 组。",
+          description = "查询交易原始明细(一行一笔);按姓名/卡号/收付方向/金额/摘要/日期/现金筛选。汇总用当前工具列表中的交易统计工具,大额用其中的大额交易工具,不要用本工具逐笔拉全量。",
           readOnly = true)
     public ToolResultBlock getTransRecords(
             @ToolParam(name = "query", description = "交易明细筛选条件,字段全部可选(但至少要能定位到人/卡/时段)")

+ 8 - 8
ai-server/src/main/java/com/zsjz/ai/module/dm/service/DmService.java

@@ -135,7 +135,7 @@ public class DmService {
         }
         Long caseId = CaseContextHolder.get();
         if (caseId == null) {
-            throw ServerException.spe("请先打开案件后再导入文件!");
+            throw ServerException.build("请先打开案件后再导入文件!");
         }
         Long batchId = IdUtil.getSnowflakeNextId();
         List<Path> targetFiles = resolvePreviewFiles(dto, caseId);
@@ -195,7 +195,7 @@ public class DmService {
      */
     public FileInfo preProcessUploadedFile(MultipartFile file, Long batchId, Integer reClean) {
         if (file == null || file.isEmpty()) {
-            throw ServerException.spe("上传文件为空!");
+            throw ServerException.build("上传文件为空!");
         }
         String originalName = StrUtil.blankToDefault(file.getOriginalFilename(), "未命名文件");
         String suffix = FileUtil.getSuffix(originalName);
@@ -233,7 +233,7 @@ public class DmService {
                     log.info("删除重复上传文件失败: path={}, err={}", saved, e.getMessage());
                 }
                 // 明确告知用户是 MD5 重复,而不是含糊的「未识别到可处理文件」
-                throw ServerException.spe("文件已存在(MD5 重复),已跳过");
+                throw ServerException.build("文件已存在(MD5 重复),已跳过");
             }
         }
 
@@ -474,7 +474,7 @@ public class DmService {
      */
     private Path saveUploadedFile(MultipartFile file, Long batchId, String originalName) {
         if (!StateManager.instance().isCaseOpened()) {
-            throw ServerException.spe("请先打开案件后再上传文件!");
+            throw ServerException.build("请先打开案件后再上传文件!");
         }
         Long caseId = StateManager.instance().getCaseId();
         Path dir = storageLayout.importBatchDir(caseId, batchId);
@@ -483,7 +483,7 @@ public class DmService {
             // 磁盘统一 UUID 重命名;源文件名只落 file_info.file_name 用于展示
             Path target = dir.resolve(StorageLayout.storedFileName(originalName)).normalize();
             if (!target.startsWith(dir)) {
-                throw ServerException.spe("非法文件名:" + originalName);
+                throw ServerException.build("非法文件名:" + originalName);
             }
             try (InputStream in = file.getInputStream()) {
                 Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
@@ -492,7 +492,7 @@ public class DmService {
             return target;
         } catch (IOException e) {
             log.error("保存上传文件失败: {}", originalName, e);
-            throw ServerException.spe("保存上传文件失败:" + originalName);
+            throw ServerException.build("保存上传文件失败:" + originalName);
         }
     }
 
@@ -537,7 +537,7 @@ public class DmService {
             //重新清洗文件。不校验重复文件
             if (dto.getReClean() != null && dto.getReClean() == 1) {
                 if (CollUtil.isEmpty(candidateFiles)) {
-                    throw ServerException.spe("所有文件不存在或格式错误!");
+                    throw ServerException.build("所有文件不存在或格式错误!");
                 }
                 return candidateFiles;
             }
@@ -964,7 +964,7 @@ public class DmService {
         }
         Long caseId = CaseContextHolder.get();
         if (caseId == null) {
-            throw ServerException.spe("请先打开案件后再清洗数据!");
+            throw ServerException.build("请先打开案件后再清洗数据!");
         }
         return fileInfos.stream()
                 .filter(Objects::nonNull)

+ 7 - 7
ai-server/src/main/java/com/zsjz/ai/module/eds/service/EdsMaterialProcessService.java

@@ -84,16 +84,16 @@ public class EdsMaterialProcessService {
      */
     public EdsMaterialProcess upload(MultipartFile file) {
         if (file == null || file.isEmpty()) {
-            throw ServerException.spe("上传文件为空!");
+            throw ServerException.build("上传文件为空!");
         }
         Long caseId = CaseContextHolder.currentCaseId();
         if (caseId == null) {
-            throw ServerException.spe("请先打开案件后再上传电子数据!");
+            throw ServerException.build("请先打开案件后再上传电子数据!");
         }
         String originalName = StrUtil.blankToDefault(file.getOriginalFilename(), "未命名数据包");
         String suffix = FileUtil.getSuffix(originalName);
         if (!"zip".equalsIgnoreCase(suffix)) {
-            throw ServerException.spe("仅支持上传 zip 格式的电子数据包:" + originalName);
+            throw ServerException.build("仅支持上传 zip 格式的电子数据包:" + originalName);
         }
 
         Long id = IdUtil.getSnowflakeNextId();
@@ -137,7 +137,7 @@ public class EdsMaterialProcessService {
      */
     public void clearProcesses() {
         if (CaseContextHolder.currentCaseId() == null) {
-            throw ServerException.spe("请先打开案件后再清空电子数据!");
+            throw ServerException.build("请先打开案件后再清空电子数据!");
         }
         int deleted = processMapper.clearAll();
         log.info("电子数据包进度表已清空: deleted={}", deleted);
@@ -150,7 +150,7 @@ public class EdsMaterialProcessService {
      */
     public List<EdsMaterialProcess> list() {
         if (CaseContextHolder.currentCaseId() == null) {
-            throw ServerException.spe("请先打开案件后再查看电子数据!");
+            throw ServerException.build("请先打开案件后再查看电子数据!");
         }
         return processMapper.selectList(Wrappers.<EdsMaterialProcess>lambdaQuery()
                 .orderByDesc(EdsMaterialProcess::getId));
@@ -321,7 +321,7 @@ public class EdsMaterialProcessService {
             Files.createDirectories(dir);
             Path target = dir.resolve(StorageLayout.storedFileName(originalName)).normalize();
             if (!target.startsWith(dir)) {
-                throw ServerException.spe("非法文件名:" + originalName);
+                throw ServerException.build("非法文件名:" + originalName);
             }
             try (InputStream in = file.getInputStream()) {
                 Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
@@ -331,7 +331,7 @@ public class EdsMaterialProcessService {
             throw e;
         } catch (Exception e) {
             log.error("保存电子数据包失败: name={}", originalName, e);
-            throw ServerException.spe("保存电子数据包失败:" + originalName);
+            throw ServerException.build("保存电子数据包失败:" + originalName);
         }
     }
 

+ 15 - 6
ai-server/src/main/java/com/zsjz/ai/module/plat/service/CaseDataCleanupService.java

@@ -20,7 +20,9 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Set;
 
 /**
  * 删除案件时清理主库 PG 中按 case_id 归属的 AI 数据。
@@ -65,14 +67,21 @@ public class CaseDataCleanupService {
             return;
         }
         List<Long> sessionIds = sessions.stream().map(AgentChatSession::getId).toList();
-        // Redis 会话状态按 (userId, sessionId) 存放:删案不清理会永久残留
-        if (ownerId != null) {
-            for (Long sessionId : sessionIds) {
+        // Redis 会话状态按 (userId, sessionId) 存放:创建者与案件 owner 都清,不能只清 owner。
+        for (AgentChatSession session : sessions) {
+            Set<String> memoryUsers = new LinkedHashSet<>();
+            if (session.getUserId() != null) {
+                memoryUsers.add(String.valueOf(session.getUserId()));
+            }
+            if (ownerId != null) {
+                memoryUsers.add(String.valueOf(ownerId));
+            }
+            for (String memoryUser : memoryUsers) {
                 try {
-                    agentService.deleteSessionMemory(String.valueOf(ownerId), String.valueOf(sessionId));
+                    agentService.deleteSessionMemory(memoryUser, String.valueOf(session.getId()));
                 } catch (Exception e) {
-                    log.info("清理案件会话 Redis 状态失败: caseId={}, sessionId={}, err={}",
-                            caseId, sessionId, e.getMessage());
+                    log.info("清理案件会话 Redis 状态失败: caseId={}, sessionId={}, userId={}, err={}",
+                            caseId, session.getId(), memoryUser, e.getMessage());
                 }
             }
         }

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/plat/service/SysUserService.java

@@ -407,7 +407,7 @@ public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {
     /**
      * 参数/业务校验失败一律用 400。
      *
-     * <p>不要用 {@code ServerException.spe(msg)} —— 它的默认 code 是 500(内部服务错误),
+     * <p>不要用 {@code ServerException.build(msg)} —— 它的默认 code 是 500(内部服务错误),
      * 会让「用户名或密码错误」这类客户端错误在监控里显示成服务端故障。
      */
     private static ServerException badRequest(String msg) {

+ 18 - 18
ai-server/src/main/java/com/zsjz/ai/module/plat/service/SystemService.java

@@ -149,7 +149,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
      * @param licenseFile 上传的授权文件(.xlts)
      */
     public void noNet(MultipartFile licenseFile) {
-        Assert.isTrue(licenseFile != null && !licenseFile.isEmpty(), () -> ServerException.spe("请选择授权文件!"));
+        Assert.isTrue(licenseFile != null && !licenseFile.isEmpty(), () -> ServerException.build("请选择授权文件!"));
         String fileName = String.valueOf(licenseFile.getOriginalFilename());
         if (StrUtil.isBlank(fileName) || "null".equals(fileName)) {
             throw new ServerException(LicenseErrorEnum.FILE_UPLOAD_FAIL.getMessage());
@@ -170,7 +170,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
         }
         //是否激活成功
         CheckAuthStatus checked = LicenseUtil.checkAuthStatus();
-        Assert.isTrue(checked.status(), () -> ServerException.spe(checked.message()));
+        Assert.isTrue(checked.status(), () -> ServerException.build(checked.message()));
         SystemInfo systemInfo = new SystemInfo();
         AuthInfo authInfo = authInfo();
         systemInfo.setClientNo(authInfo.getName());
@@ -217,10 +217,10 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
      * @param file 升级包(zip)
      */
     public void uploadUpgrade(MultipartFile file) {
-        Assert.isTrue(file != null && !file.isEmpty(), () -> ServerException.spe("请选择升级文件!"));
+        Assert.isTrue(file != null && !file.isEmpty(), () -> ServerException.build("请选择升级文件!"));
         String fileName = String.valueOf(file.getOriginalFilename());
         if (StrUtil.isBlank(fileName) || !fileName.toLowerCase().endsWith(".zip")) {
-            throw ServerException.spe("升级包必须是 zip 文件!");
+            throw ServerException.build("升级包必须是 zip 文件!");
         }
         Path tempZip = PathConst.ROOT_PATH.resolve("upgrade-package.zip").toAbsolutePath().normalize();
         try {
@@ -230,7 +230,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
             upgrade(tempZip.toString());
         } catch (IOException e) {
             log.error("保存升级包失败", e);
-            throw ServerException.spe("保存升级包失败!");
+            throw ServerException.build("保存升级包失败!");
         } finally {
             try {
                 Files.deleteIfExists(tempZip);
@@ -363,26 +363,26 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
      */
     public DownloadFile resolveDownloadFile(Long fid) {
         if (fid == null) {
-            throw ServerException.spe("文件ID不能为空!");
+            throw ServerException.build("文件ID不能为空!");
         }
         FileInfo fileInfo = fileInfoMapper.selectById(fid);
         if (fileInfo == null) {
-            throw ServerException.spe("文件不存在!");
+            throw ServerException.build("文件不存在!");
         }
         String filePath = resolveFilePath(fileInfo);
         if (StrUtil.isBlank(filePath)) {
-            throw ServerException.spe("该记录没有可下载的源文件!");
+            throw ServerException.build("该记录没有可下载的源文件!");
         }
         // 只允许下载当前案件工作空间内的文件:file_info 的路径可能来自历史数据/客户端导入,
         // 不能仅凭“库里有这条记录”就读取服务器任意路径。
         Path path = workspacePathGuard.requireInsideWorkspace(
                 CaseContextHolder.currentCaseId(), filePath);
         if (!Files.isRegularFile(path)) {
-            throw ServerException.spe("文件不存在或已被清理!");
+            throw ServerException.build("文件不存在或已被清理!");
         }
         String suffix = FileUtil.getSuffix(path.toFile());
         if (StrUtil.isBlank(suffix)) {
-            throw ServerException.spe("该文件类型不支持下载:" + path.getFileName());
+            throw ServerException.build("该文件类型不支持下载:" + path.getFileName());
         }
         String fileName = StrUtil.isBlank(fileInfo.getFileName()) ? path.getFileName().toString() : fileInfo.getFileName();
         return new DownloadFile(path.toAbsolutePath(), fileName);
@@ -418,7 +418,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
     public DownloadFile getFilePath(String fileId) {
         FileInfo fileInfo = fileInfoMapper.selectById(fileId);
         if (fileInfo == null) {
-            throw ServerException.spe("文件不存在!");
+            throw ServerException.build("文件不存在!");
         }
         String filePath = fileInfo.getFilePath();
         Long caseId = CaseContextHolder.currentCaseId();
@@ -437,29 +437,29 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
      */
     public void openLocalOfficeFile(String filePath) {
         if (StrUtil.isBlank(filePath)) {
-            throw ServerException.spe("文件路径不能为空!");
+            throw ServerException.build("文件路径不能为空!");
         }
         Long caseId = CaseContextHolder.currentCaseId();
         Path path = (caseId != null)
                 ? workspacePathGuard.requireInsideWorkspace(caseId, filePath)
                 : storageLayout.resolve(filePath);
         if (Files.notExists(path) || Files.isDirectory(path)) {
-            throw ServerException.spe("文件不存在!");
+            throw ServerException.build("文件不存在!");
         }
         String suffix = FileUtil.getSuffix(path.toFile());
         if (StrUtil.isBlank(suffix) || !GlobalCache.suffixList.contains(suffix.toLowerCase())) {
-            throw ServerException.spe("仅支持打开 csv、xls、xlsx 文件!");
+            throw ServerException.build("仅支持打开 csv、xls、xlsx 文件!");
         }
         try {
             int exitCode = getExitCode(path);
 
             if (exitCode != 0) {
                 log.error("打开文件失败,退出码: {}", exitCode);
-                throw ServerException.spe("打开失败,检查是否有可用的应用程序!");
+                throw ServerException.build("打开失败,检查是否有可用的应用程序!");
             }
         } catch (Exception e) {
             log.error("打开本地文件失败, filePath={}", filePath, e);
-            throw ServerException.spe("当前系统不支持打开该文件类型!");
+            throw ServerException.build("当前系统不支持打开该文件类型!");
         }
     }
 
@@ -487,7 +487,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
     public void openOfficeFile(Long fid) {
         FileInfo fileInfo = fileInfoMapper.selectById(fid);
         if (fileInfo == null) {
-            throw ServerException.spe("文件不存在!");
+            throw ServerException.build("文件不存在!");
         }
         String filePath = fileInfo.getFilePath();
         openLocalOfficeFile(filePath);
@@ -500,7 +500,7 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
      */
     public String checkAuth() {
         /*CheckAuthStatus checked = LicenseUtil.checkAuthStatus();
-        Assert.isTrue(checked.status(), () -> ServerException.spe(checked.message()));
+        Assert.isTrue(checked.status(), () -> ServerException.build(checked.message()));
         SystemInfo info = info();
         if (info == null) {
             return "试用";

+ 2 - 2
ai-server/src/main/resources/prompts/insight/GRAPH_RELATION_INSIGHT.md

@@ -36,8 +36,8 @@
 
 - 本 Agent 固定装备 `graph` 组:`get_case_graph`(整案关系图取数,返回 `nodeList` / `edgeList`,
   前端会自动把它渲染成关系图,**不要**再手写 graph 围栏块)。
-- 其他数据用基础设施工具自行查询:`search_table_schema`、`list_tables`、`render_chart`、
-  `execute_python`。
+- 其他数据用当前工具列表里的基础设施工具自行查询(表目录 `list_tables`、图表 `render_chart`、
+  `execute_python`);表结构检索指引只在 RAG 可用时由系统追加。
 - **禁止**用 `execute_python` 手写 SQL 重算已有专用工具的口径(图谱取数、资金/通话边口径已固化,
   重算必然与页面上的数字不一致)。
 

+ 30 - 2
ai-server/src/test/java/com/zsjz/ai/module/agent/artifact/AgentArtifactScannerTest.java

@@ -46,7 +46,7 @@ class AgentArtifactScannerTest {
     @DisplayName("扫描 Agent 工作区 HTML:复制进 artifacts 并返回 html 产物元数据")
     void scansHtmlAndRegistersArtifact() throws IOException {
         Path agentDir = STORAGE.agentWorkspace(CASE_ID, AGENT_ID);
-        Path html = agentDir.resolve("1").resolve("案件分析报告.html");
+        Path html = agentDir.resolve(String.valueOf(USER_ID)).resolve("案件分析报告.html");
         Files.createDirectories(html.getParent());
         Files.writeString(html, "<html><body>报告</body></html>", StandardCharsets.UTF_8);
         Files.setLastModifiedTime(html, FileTime.from(Instant.now()));
@@ -56,7 +56,7 @@ class AgentArtifactScannerTest {
         AgentArtifactScanner scanner = new AgentArtifactScanner(STORAGE, artifacts);
 
         List<Map<String, Object>> metas = CaseContextHolder.callWith(CASE_ID, USER_ID,
-                () -> scanner.scanAndRegister(USER_ID, CASE_ID, AGENT_ID, since));
+                () -> scanner.scanAndRegister(USER_ID, CASE_ID, AGENT_ID, "s1", since));
 
         assertEquals(1, metas.size(), "应只登记本轮生成的 HTML");
         Map<String, Object> meta = metas.get(0);
@@ -67,6 +67,34 @@ class AgentArtifactScannerTest {
         assertEquals(Files.size(html), ((Number) meta.get("sizeBytes")).longValue());
     }
 
+    @Test
+    @DisplayName("只认领当前用户+会话的 Python 输出,其他执行目录不登记")
+    void scansOnlyOwnedPythonOutputs() throws IOException {
+        Path owned = STORAGE.pythonOutDir(CASE_ID, "owned-exec");
+        Path other = STORAGE.pythonOutDir(CASE_ID, "other-exec");
+        Files.createDirectories(owned);
+        Files.createDirectories(other);
+
+        Path ownedHtml = owned.resolve("owned.html");
+        Files.writeString(ownedHtml, "<html>owned</html>", StandardCharsets.UTF_8);
+        Path otherHtml = other.resolve("other.html");
+        Files.writeString(otherHtml, "<html>other</html>", StandardCharsets.UTF_8);
+        Files.writeString(owned.resolve(".exec-owner"), USER_ID + "\ns1", StandardCharsets.UTF_8);
+        Files.writeString(other.resolve(".exec-owner"), (USER_ID + 1) + "\ns1", StandardCharsets.UTF_8);
+        Files.setLastModifiedTime(ownedHtml, FileTime.from(Instant.now()));
+        Files.setLastModifiedTime(otherHtml, FileTime.from(Instant.now()));
+
+        ArtifactService artifacts = new ArtifactService(new ArtifactProperties(), STORAGE);
+        AgentArtifactScanner scanner = new AgentArtifactScanner(STORAGE, artifacts);
+        Instant since = Instant.now().minusSeconds(2);
+
+        List<Map<String, Object>> metas = CaseContextHolder.callWith(CASE_ID, USER_ID,
+                () -> scanner.scanAndRegister(USER_ID, CASE_ID, AGENT_ID, "s1", since));
+
+        assertEquals(1, metas.size(), "只应登记当前用户+会话的 Python 输出");
+        assertEquals("owned.html", metas.get(0).get("fileName"));
+    }
+
     private static void deleteRecursively(Path root) throws IOException {
         if (root == null || !Files.exists(root)) {
             return;

+ 4 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/insight/InsightPromptAssemblyTest.java

@@ -169,6 +169,10 @@ class InsightPromptAssemblyTest {
         String prompt = promptBuilder(false).build(ctx);
 
         assertFalse(prompt.contains(RAG_MARK), "RAG 不可用时不该出现检索指引");
+        assertFalse(prompt.contains("search_table_schema"),
+                "RAG 不可用时静态人设也不能点名未注册的 search_table_schema");
+        assertFalse(prompt.contains("query_table_data"),
+                "研判 Agent 没有注册 query_table_data,提示词不能点名");
         assertTrue(prompt.contains(STATIC_MARK), "其余三段仍应在");
         assertTrue(prompt.contains(CONTRACT_MARK));
     }

+ 37 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/middleware/CaseScopeMiddlewareTest.java

@@ -0,0 +1,37 @@
+package com.zsjz.ai.module.agent.middleware;
+
+import io.agentscope.core.event.AgentEvent;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import reactor.core.Disposable;
+import reactor.core.publisher.Flux;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 案件作用域中间件的取消传播契约。
+ *
+ * <p>删除会话时会先 dispose 外层流;如果 {@code Flux.create} 只关闭 emitter、
+ * 不向内部 Agent 链传播 cancel,旧工具调用会继续跑,删除后还可能回写文件/状态。
+ */
+class CaseScopeMiddlewareTest {
+
+    @Test
+    @DisplayName("下游取消会传播到内部 Agent 流")
+    void cancelPropagatesToUpstream() {
+        AtomicBoolean cancelled = new AtomicBoolean(false);
+        Flux<AgentEvent> upstream = Flux.create(sink ->
+                sink.onCancel(() -> cancelled.set(true)));
+
+        CaseScopeMiddleware middleware = new CaseScopeMiddleware(1L);
+        Disposable subscription = middleware
+                .onActing(null, null, null, input -> upstream)
+                .subscribe();
+
+        subscription.dispose();
+
+        assertTrue(cancelled.get(), "外层取消必须 cancel 内部 Agent 流");
+    }
+}

+ 188 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/middleware/PromptContextMiddlewareTest.java

@@ -0,0 +1,188 @@
+package com.zsjz.ai.module.agent.middleware;
+
+import io.agentscope.core.agent.Agent;
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.core.message.Msg;
+import io.agentscope.core.middleware.ReasoningInput;
+import io.agentscope.core.state.AgentState;
+import io.agentscope.core.state.ToolContextState;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Flux;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * 每轮上下文公告的行为契约。
+ *
+ * <p>核心不是“能注入”,而是“只在变化时注入”:onReasoning 每轮工具调用都会触发,
+ * 如果每次都追加一条公告,长对话会被重复公告淹没。测试覆盖:
+ * <ul>
+ *   <li>首次注入案件/日期/工具组;</li>
+ *   <li>值不变时跳过;</li>
+ *   <li>同一 Agent 实例的不同会话各自有独立快照;</li>
+ *   <li>工具组变化时重新注入;</li>
+ *   <li>Insight 模式不注入业务工具组;</li>
+ *   <li>案件名换行/闭合标签被中和。</li>
+ * </ul>
+ *
+ * <p>工具组从调用级 {@link AgentState} 读取,而不是共享 Toolkit,测试也按这个口径构造。
+ */
+class PromptContextMiddlewareTest {
+
+    private static final Clock FIXED = Clock.fixed(
+            Instant.parse("2026-11-04T00:00:00Z"), ZoneOffset.UTC);
+
+    private static ReasoningInput run(PromptContextMiddleware middleware, List<String> groups,
+                                      List<Msg> messages) {
+        return run(middleware, groups, messages, "s1");
+    }
+
+    private static ReasoningInput run(PromptContextMiddleware middleware, List<String> groups,
+                                      List<Msg> messages, String sessionId) {
+        return run(middleware, groups, messages, sessionId, "u1");
+    }
+
+    private static ReasoningInput run(PromptContextMiddleware middleware, List<String> groups,
+                                      List<Msg> messages, String sessionId, String userId) {
+        RuntimeContext ctx = mock(RuntimeContext.class);
+        when(ctx.getSessionId()).thenReturn(sessionId);
+        when(ctx.getUserId()).thenReturn(userId);
+        ToolContextState.Builder toolContext = ToolContextState.builder();
+        groups.forEach(toolContext::addActivatedGroup);
+        when(ctx.getAgentState()).thenReturn(
+                AgentState.builder().toolContext(toolContext.build()).build());
+
+        AtomicReference<ReasoningInput> seen = new AtomicReference<>();
+        middleware.onReasoning(mock(Agent.class), ctx,
+                        new ReasoningInput(messages, List.of(), null),
+                        input -> {
+                            seen.set(input);
+                            return Flux.empty();
+                        })
+                .blockLast();
+        assertNotNull(seen.get(), "next 必须被调用");
+        return seen.get();
+    }
+
+    @Test
+    @DisplayName("首次推理注入案件、日期和工具组,并标记 synthetic")
+    void injectsContextOnFirstReasoning() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "测试案件", 7L, true, FIXED);
+
+        ReasoningInput output = run(middleware, List.of("person"), List.of());
+
+        assertEquals(1, output.messages().size());
+        Msg reminder = output.messages().get(0);
+        String text = reminder.getTextContent();
+        assertTrue(text.contains("<system-reminder>"));
+        assertTrue(text.contains("当前案件:测试案件(ID 7)"));
+        assertTrue(text.contains("当前日期:2026-11-04"));
+        assertTrue(text.contains("已装备工具组:person"));
+        assertEquals(Boolean.TRUE, reminder.getMetadata().get(Msg.METADATA_SYNTHETIC));
+    }
+
+    @Test
+    @DisplayName("值不变时不重复注入")
+    void skipsWhenSnapshotUnchanged() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "测试案件", 7L, true, FIXED);
+
+        run(middleware, List.of("person"), List.of());
+        ReasoningInput second = run(middleware, List.of("person"), List.of());
+
+        assertEquals(0, second.messages().size(), "同一快照不应再次追加公告");
+    }
+
+    @Test
+    @DisplayName("同一 Agent 实例的不同会话各自收到首次公告")
+    void sessionsHaveIndependentSnapshots() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "测试案件", 7L, true, FIXED);
+
+        run(middleware, List.of("person"), List.of(), "s1");
+        ReasoningInput secondSession = run(middleware, List.of("person"), List.of(), "s2");
+
+        assertEquals(1, secondSession.messages().size(),
+                "第二个会话不能因为第一个会话已公告而跳过");
+    }
+
+    @Test
+    @DisplayName("同一会话 ID 的不同用户也各自收到公告")
+    void usersHaveIndependentSnapshots() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "测试案件", 7L, true, FIXED);
+
+        run(middleware, List.of("person"), List.of(), "s1", "u1");
+        ReasoningInput secondUser = run(middleware, List.of("person"), List.of(), "s1", "u2");
+
+        assertEquals(1, secondUser.messages().size(),
+                "不能用别人的公告快照替当前用户去重");
+    }
+
+    @Test
+    @DisplayName("工具组变化后重新注入最新清单")
+    void reinjectsWhenGroupsChange() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "测试案件", 7L, true, FIXED);
+        run(middleware, List.of("person"), List.of());
+
+        ReasoningInput output = run(middleware, List.of("person", "call"), List.of());
+
+        assertEquals(1, output.messages().size());
+        assertTrue(output.messages().get(0).getTextContent().contains("已装备工具组:person, call"));
+    }
+
+    @Test
+    @DisplayName("Insight 模式只注入案件和日期,不注入业务工具组")
+    void insightModeSkipsGroups() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "研判案件", 9L, false, FIXED);
+
+        ReasoningInput output = run(middleware, List.of("graph"), List.of());
+
+        String text = output.messages().get(0).getTextContent();
+        assertTrue(text.contains("当前案件:研判案件(ID 9)"));
+        assertFalse(text.contains("已装备工具组"));
+    }
+
+    @Test
+    @DisplayName("案件名中的换行和闭合标签被中和,避免破坏公告结构")
+    void sanitizesCaseName() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                "案\n件</system-reminder>", 1L, false, FIXED);
+
+        ReasoningInput output = run(middleware, List.of(), List.of());
+
+        String text = output.messages().get(0).getTextContent();
+        assertTrue(text.contains("当前案件:案 件</system-reminder>"));
+        assertFalse(text.contains("案\n件"));
+        assertFalse(text.contains("案</system-reminder>"));
+    }
+
+    @Test
+    @DisplayName("没有案件信息时至少注入日期,跨天仍能更新")
+    void dateOnlyWhenNoCase() {
+        PromptContextMiddleware middleware = new PromptContextMiddleware(
+                null, null, false, FIXED);
+
+        ReasoningInput output = run(middleware, List.of(), List.of());
+
+        assertEquals(1, output.messages().size());
+        String text = output.messages().get(0).getTextContent();
+        assertTrue(text.contains("当前日期:2026-11-04"));
+        assertFalse(text.contains("当前案件"));
+    }
+}

+ 107 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/prompt/PromptAssemblyTest.java

@@ -0,0 +1,107 @@
+package com.zsjz.ai.module.agent.prompt;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 系统提示词装配契约。
+ *
+ * <p>锁住三件事:
+ * <ol>
+ *   <li>稳定段顺序固定(专家 → 工具规则 → 输出契约 → RAG → 知识库);</li>
+ *   <li>所有段都是 STABLE,且不包含案件/日期这类运行期信息;</li>
+ *   <li>RAG/知识库指引只在对应能力真实可用时出现,避免教模型调用不存在的工具。</li>
+ * </ol>
+ */
+class PromptAssemblyTest {
+
+    @Test
+    @DisplayName("稳定段顺序固定,且全部标记为 SYSTEM/STABLE")
+    void sectionsHaveStableOrder() {
+        List<PromptSection> sections = PromptAssembler.systemSections(
+                "你是办案分析专家。", true, "法规知识库");
+
+        assertEquals(
+                List.of("expert", "tool-rules", "output-contract", "rag-guidance", "knowledge-guidance"),
+                sections.stream().map(PromptSection::name).toList());
+
+        for (PromptSection section : sections) {
+            assertEquals(PromptSection.Target.SYSTEM, section.target(), section.name());
+            assertEquals(PromptSection.CacheHint.STABLE, section.cacheHint(), section.name());
+            assertFalse(section.isBlank(), section.name());
+        }
+    }
+
+    @Test
+    @DisplayName("专家人设为空时不产生空段")
+    void blankExpertPromptIsOmitted() {
+        List<PromptSection> sections = PromptAssembler.systemSections("  ", false, null);
+
+        assertEquals(List.of("tool-rules", "output-contract"),
+                sections.stream().map(PromptSection::name).toList());
+    }
+
+    @Test
+    @DisplayName("RAG/知识库指引按可用性出现,未绑定时不出现")
+    void optionalGuidanceOnlyWhenAvailable() {
+        String noRag = PromptAssembler.render(PromptAssembler.systemSections("人设", false, null));
+        assertFalse(noRag.contains("search_table_schema"), "RAG 不可用时不该出现检索指引");
+        assertFalse(noRag.contains("search_knowledge"), "未绑定知识库时不该出现检索指引");
+
+        String ragOnly = PromptAssembler.render(PromptAssembler.systemSections(null, true, null));
+        assertTrue(ragOnly.contains("search_table_schema"));
+        assertFalse(ragOnly.contains("search_knowledge"));
+
+        String kbOnly = PromptAssembler.render(PromptAssembler.systemSections(null, false, "法规库"));
+        assertTrue(kbOnly.contains("search_knowledge"));
+        assertTrue(kbOnly.contains("法规库"));
+    }
+
+    @Test
+    @DisplayName("稳定段不包含案件、日期等运行期信息")
+    void stableSectionsDoNotCarryDynamicContext() {
+        String prompt = PromptAssembler.render(PromptAssembler.systemSections("人设", true, "法规库"));
+
+        assertFalse(prompt.contains("当前案件"), "案件信息应由 PromptContextMiddleware 注入");
+        assertFalse(prompt.contains("当前日期"), "日期应由 PromptContextMiddleware 注入");
+        assertFalse(prompt.contains("已装备工具组"), "工具组应由 PromptContextMiddleware 注入");
+        assertFalse(prompt.contains("20"), "稳定段不应出现年份/日期");
+    }
+
+    @Test
+    @DisplayName("段间空一行,空段不参与拼接")
+    void renderJoinsNonBlankSections() {
+        assertEquals("a\n\nb", PromptAssembler.render(List.of(
+                PromptSection.system("a", " a "),
+                PromptSection.system("blank", "   "),
+                PromptSection.system("b", "b"))));
+        assertEquals("", PromptAssembler.render(List.of()));
+    }
+
+    @Test
+    @DisplayName("动态公告不能混进 system prompt")
+    void renderRejectsAnnouncementSections() {
+        assertThrows(IllegalArgumentException.class, () -> PromptAssembler.render(
+                List.of(PromptSection.announcement("context", "当前日期:2026-11-04"))));
+    }
+
+    @Test
+    @DisplayName("通用规则点名兜底工具,但不点名具体业务工具")
+    void rulesStayGeneric() {
+        String rules = PromptAssembler.renderRules();
+
+        assertTrue(rules.contains("query_table_data"));
+        assertTrue(rules.contains("execute_python"));
+        assertTrue(rules.contains("```echarts"));
+        assertFalse(rules.contains("get_case_graph"));
+        assertFalse(rules.contains("get_call_records"));
+        assertTrue(rules.length() < 1_200);
+    }
+}

+ 11 - 3
ai-server/src/test/java/com/zsjz/ai/module/agent/registry/ToolAnnotationScannerTest.java

@@ -63,10 +63,18 @@ class ToolAnnotationScannerTest {
     }
 
     @Test
-    @DisplayName("只读标记来自 @Tool(readOnly=true),不是全部默认为真或假")
+    @DisplayName("只读标记来自注解:查询工具只读,execute_python 非只读")
     void readOnlyFlagComesFromAnnotation() {
-        assertTrue(tools.stream().allMatch(ScannedTool::readOnly),
-                "当前工具都是只读工具,readOnly 应全为 true");
+        Map<String, ScannedTool> byName = tools.stream()
+                .collect(Collectors.toMap(ScannedTool::name, Function.identity()));
+        for (ScannedTool tool : tools) {
+            if ("execute_python".equals(tool.name())) {
+                assertFalse(tool.readOnly(), "execute_python 可写文件/起进程,readOnly 必须为 false");
+            } else {
+                assertTrue(tool.readOnly(), tool.name() + " 是查询/渲染工具,readOnly 应为 true");
+            }
+        }
+        assertTrue(byName.containsKey("execute_python"));
     }
 
     @Test

+ 10 - 8
ai-server/src/test/java/com/zsjz/ai/module/agent/tools/PythonAnalysisToolTest.java

@@ -3,6 +3,7 @@ package com.zsjz.ai.module.agent.tools;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.zsjz.ai.module.agent.python.PythonExecutor;
+import io.agentscope.core.agent.RuntimeContext;
 import io.agentscope.core.message.TextBlock;
 import io.agentscope.core.message.ToolResultBlock;
 import io.agentscope.core.message.ToolResultState;
@@ -16,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -54,7 +56,7 @@ class PythonAnalysisToolTest {
     }
 
     private void stub(PythonExecutor.PythonResult result) {
-        when(executor.execute(anyString())).thenReturn(result);
+        when(executor.execute(anyString(), any(), any())).thenReturn(result);
     }
 
     private static PythonExecutor.PythonResult result(String relationGraphJson, String relationGraphError) {
@@ -71,7 +73,7 @@ class PythonAnalysisToolTest {
                  "edges": [{"source": "p:张三", "target": "p:李四", "relation": "亲属", "weight": 2}]}
                 """, null));
 
-        String raw = text(tool.executePython("print(1)"));
+        String raw = text(tool.executePython(null, "print(1)"));
         JsonNode payload = json(raw);
 
         assertNotNull(payload.get("relationGraph"));
@@ -87,7 +89,7 @@ class PythonAnalysisToolTest {
     void reportsInvalidPayload() {
         stub(result("not-json", null));
 
-        JsonNode payload = json(text(tool.executePython("print(1)")));
+        JsonNode payload = json(text(tool.executePython(null, "print(1)")));
 
         assertEquals("ok", payload.path("stdout").asText());
         assertFalse(payload.has("relationGraph"));
@@ -99,7 +101,7 @@ class PythonAnalysisToolTest {
     void passesThroughReadError() {
         stub(result(null, "relation_graph.json 超过 2MB(3000000 字节),请在 Python 里聚合/取 TOP N 后再输出"));
 
-        JsonNode payload = json(text(tool.executePython("print(1)")));
+        JsonNode payload = json(text(tool.executePython(null, "print(1)")));
 
         assertFalse(payload.has("relationGraph"));
         assertTrue(payload.path("relationGraphError").asText().contains("超过 2MB"));
@@ -110,7 +112,7 @@ class PythonAnalysisToolTest {
     void noGraphWhenNotEmitted() {
         stub(result(null, null));
 
-        JsonNode payload = json(text(tool.executePython("print(1)")));
+        JsonNode payload = json(text(tool.executePython(null, "print(1)")));
 
         assertFalse(payload.has("relationGraph"));
         assertFalse(payload.has("relationGraphError"));
@@ -120,7 +122,7 @@ class PythonAnalysisToolTest {
     @DisplayName("工具描述保持通用:只讲 Python 能力和关系图输出契约,不点名具体业务工具")
     void descriptionStaysGeneric() throws Exception {
         Tool annotation = PythonAnalysisTool.class
-                .getDeclaredMethod("executePython", String.class)
+                .getDeclaredMethod("executePython", RuntimeContext.class, String.class)
                 .getAnnotation(Tool.class);
 
         assertNotNull(annotation);
@@ -137,7 +139,7 @@ class PythonAnalysisToolTest {
         stub(new PythonExecutor.PythonResult(-1, "", "", List.of(), 0,
                 "Python 执行环境不可用", null, null));
 
-        JsonNode payload = json(text(tool.executePython("print(1)")));
+        JsonNode payload = json(text(tool.executePython(null, "print(1)")));
 
         assertEquals("Python 执行环境不可用", payload.path("error").asText());
         assertFalse(payload.has("relationGraph"));
@@ -147,7 +149,7 @@ class PythonAnalysisToolTest {
     @DisplayName("工具结果状态为 SUCCESS(错误信息放在 JSON 里,不阻断模型继续分析)")
     void resultStateIsSuccess() {
         stub(result(null, null));
-        ToolResultBlock block = tool.executePython("print(1)");
+        ToolResultBlock block = tool.executePython(null, "print(1)");
         assertEquals(ToolResultState.SUCCESS, block.getState());
     }
 }

+ 151 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/tools/ToolDescriptionContractTest.java

@@ -0,0 +1,151 @@
+package com.zsjz.ai.module.agent.tools;
+
+import com.zsjz.ai.module.agent.registry.ToolAnnotationScanner;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 工具契约测试:锁住「模型可见描述」和「治理元数据」的一致性。
+ *
+ * <p>工具描述是模型选工具的唯一依据,改坏一个词就可能导致选错工具,所以用测试兜底:
+ * <ul>
+ *   <li>每个工具都有描述、能力摘要、业务组,长度在预算内;</li>
+ *   <li>易混淆工具的「兄弟工具路由句」必须点名真实存在的兄弟工具;</li>
+ *   <li>描述里不能出现已下线的工具名;</li>
+ *   <li>高风险工具的只读/并行/审批元数据必须显式声明。</li>
+ * </ul>
+ *
+ * <p>这里只读注解与静态配置,不实例化工具、不依赖 Spring 上下文。
+ */
+class ToolDescriptionContractTest {
+
+    /** 描述长度下限:低于这个值模型无法判断工具边界 */
+    private static final int MIN_DESCRIPTION = 30;
+
+    /** 描述长度上限:复杂工具可放宽到 400,再长会挤占上下文 */
+    private static final int MAX_DESCRIPTION = 400;
+
+    /** 全部工具描述总预算(字符),约 5.5k,留出增长余量 */
+    private static final int TOTAL_DESCRIPTION_BUDGET = 6_000;
+
+    /** 已经下线、不允许再出现在任何描述里的工具名 */
+    private static final Set<String> STALE_TOOL_NAMES = Set.of(
+            "list_person_names",
+            "execute_sql",
+            "query_rel_edge",
+            "render_graph",
+            "get_user_selected_workspace");
+
+    /** base 组里仍按运行环境条件注册的工具,不能当作“始终可见” */
+    private static final Set<String> CONDITIONAL_BASE_TOOLS = Set.of(
+            "search_table_schema", "search_knowledge");
+
+    private final List<ToolDescriptor> tools =
+            new ToolMetadataRegistry(new ToolAnnotationScanner()).all();
+
+    @Test
+    @DisplayName("每个工具都有描述、能力摘要和业务组,且长度在预算内")
+    void descriptionsArePresentAndBounded() {
+        assertFalse(tools.isEmpty(), "没有扫描到任何工具");
+
+        int total = 0;
+        for (ToolDescriptor tool : tools) {
+            String name = tool.name();
+            assertTrue(tool.description() != null && !tool.description().isBlank(),
+                    name + " 缺少 description");
+            assertTrue(tool.description().length() >= MIN_DESCRIPTION,
+                    name + " 描述过短(" + tool.description().length() + ")");
+            assertTrue(tool.description().length() <= MAX_DESCRIPTION,
+                    name + " 描述过长(" + tool.description().length() + ")");
+            assertTrue(tool.capability() != null && !tool.capability().isBlank(),
+                    name + " 缺少 capability 摘要");
+            assertTrue(tool.group() != null && !tool.group().isBlank(),
+                    name + " 缺少业务组");
+            assertTrue(tool.resultBudget() > 0, name + " 缺少结果预算");
+            total += tool.description().length();
+        }
+        assertTrue(total <= TOTAL_DESCRIPTION_BUDGET,
+                "工具描述总长度 " + total + " 超出预算 " + TOTAL_DESCRIPTION_BUDGET);
+    }
+
+    @Test
+    @DisplayName("兄弟工具路由必须真实存在、写进描述,且属于始终注册的 base")
+    void siblingRoutingReferencesRegisteredTools() {
+        Map<String, ToolDescriptor> byName = tools.stream()
+                .collect(Collectors.toMap(ToolDescriptor::name, tool -> tool));
+        for (ToolDescriptor tool : tools) {
+            for (String sibling : tool.siblings()) {
+                ToolDescriptor siblingTool = byName.get(sibling);
+                assertTrue(siblingTool != null,
+                        tool.name() + " 的路由指向未注册工具: " + sibling);
+                assertTrue(tool.description().contains(sibling),
+                        tool.name() + " 的描述缺少路由句: " + sibling);
+                assertEquals("base", siblingTool.group(),
+                        tool.name() + " 路由到业务工具 " + sibling + ":工具包可能没选它,不能写死");
+                assertFalse(CONDITIONAL_BASE_TOOLS.contains(sibling),
+                        tool.name() + " 路由到条件注册的 base 工具 " + sibling + ":当前环境可能没有");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("描述里只能点名始终注册的 base 工具")
+    void descriptionsOnlyNameBaseTools() {
+        for (ToolDescriptor tool : tools) {
+            for (ToolDescriptor other : tools) {
+                if (other.name().equals(tool.name()) || !tool.description().contains(other.name())) {
+                    continue;
+                }
+                assertEquals("base", other.group(),
+                        tool.name() + "(" + tool.group() + ")描述点名了业务工具 "
+                                + other.name() + "(" + other.group() + "):工具包/专家可能没注册它");
+                assertFalse(CONDITIONAL_BASE_TOOLS.contains(other.name()),
+                        tool.name() + " 描述点名了条件注册的 base 工具 " + other.name()
+                                + ":当前环境可能没有");
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("描述里不出现已下线的工具名")
+    void descriptionsDoNotMentionStaleTools() {
+        for (ToolDescriptor tool : tools) {
+            for (String stale : STALE_TOOL_NAMES) {
+                assertFalse(tool.description().contains(stale),
+                        tool.name() + " 的描述仍引用已下线工具: " + stale);
+            }
+        }
+    }
+
+    @Test
+    @DisplayName("execute_python 是唯一有副作用的高风险工具")
+    void pythonIsTheOnlyHighRiskTool() {
+        for (ToolDescriptor tool : tools) {
+            if ("execute_python".equals(tool.name())) {
+                assertFalse(tool.readOnly(), "execute_python 必须 readOnly=false");
+                assertFalse(tool.concurrentSafe(), "execute_python 会写文件/起进程,必须串行");
+                assertTrue(tool.destructive(), "execute_python 必须标记 destructive");
+                assertEquals("high", tool.riskLevel());
+                // 产品明确要求 Python 完全放开、不允许拦截任何操作:needsApproval 只能作为展示字段,
+                // 不能在这里置 true,否则未来的审批链路会把 execute_python 拦下来。
+                assertFalse(tool.needsApproval(), "execute_python 不允许审批拦截");
+                assertTrue(tool.timeoutMs() >= 60_000, "execute_python 超时应覆盖 60 秒执行上限");
+            } else {
+                assertTrue(tool.readOnly(), tool.name() + " 是查询/渲染工具,应 readOnly=true");
+                assertTrue(tool.concurrentSafe(), tool.name() + " 只读工具应允许并行");
+                assertEquals("low", tool.riskLevel(), tool.name() + " 不应标记高风险");
+                assertFalse(tool.destructive(), tool.name() + " 不应标记 destructive");
+                assertFalse(tool.needsApproval(), tool.name() + " 不应要求审批");
+            }
+        }
+    }
+}