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

feat(ai): 计划模式治理对齐上游 1.1.2(分桶/写守卫/审批闭环)

- 计划文件按会话分桶 plans/<sessionId>:sessionId 贯通装配链(指纹 |plan=on|session=、缓存键 #P<sessionId>),plan off 行为不变;会话删除回收案件会话计划目录
- 新增 PlanFileResetMiddleware:每次 plan_enter 前清空旧计划文件,保证每轮规划从空白开始
- 新增 PlanWriteGuardMiddleware:PLAN 阶段兜底拦截变更类工具(白名单计划/任务清单工具,黑名单 execute/write_file 等,未知工具按只读标记 fail-closed),堵同批 plan_enter+execute 绕过;拦截调用记入 AiRouteContext.planBlockedToolLogs 随工具审计落库
- 审批闭环:PendingConfirm 扩展 planEnabled/planPath/planContent/planRejectCount/planApproved(旧 Redis 记录缺字段容错);plan_write 全文随待确认留存,确认卡/tool_confirm/pending 接口下发防盲批;驳回计数累计、达 3 次恢复流直接 aborted 收口;计划工具禁用「记住该工具」;恢复段/信任合并沿用暂停轮冻结的 planEnabled
- 只读分类与中文标签补齐 todo_read/task_output/task_list
- 前端:PlanApprovalCard 优先展示计划正文全文与驳回进度;确认部件透传 plan 字段
- 保持本分支设计:会话级开关为主控、仅入口智能体注册、不引入专家级开关与全局熔断
- 新增单测 10 例(写守卫分类/装配签名/计划字段往返),ai-server 全量 87 测试通过;端到端真机验证分桶、写守卫、正文卡、驳回计数与 3 次上限收口
cc 1 день назад
Родитель
Сommit
edd33d4d00
19 измененных файлов с 939 добавлено и 67 удалено
  1. 6 0
      ai-electron/frontend/src/workbench/api/chat.ts
  2. 28 3
      ai-electron/frontend/src/workbench/components/chat/PlanApprovalCard.vue
  3. 15 2
      ai-electron/frontend/src/workbench/views/chat/index.vue
  4. 22 7
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentAssembler.java
  5. 6 3
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentFingerprintCalculator.java
  6. 64 21
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentRegistry.java
  7. 98 13
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiChatFacade.java
  8. 16 9
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiConfirmPendingStore.java
  9. 9 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteContext.java
  10. 69 2
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiTurnFinisher.java
  11. 86 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/PlanFileResetMiddleware.java
  12. 201 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/PlanWriteGuardMiddleware.java
  13. 4 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/ToolLabelResolver.java
  14. 15 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiChatPendingVo.java
  15. 43 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSessionServiceImpl.java
  16. 6 6
      ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/AgentRegistryCaseIsolationTest.java
  17. 93 0
      ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/AiConfirmPendingStorePlanFieldsTest.java
  18. 74 0
      ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/PlanModeAssemblySignatureTest.java
  19. 84 0
      ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/PlanWriteGuardMiddlewareTest.java

+ 6 - 0
ai-electron/frontend/src/workbench/api/chat.ts

@@ -154,6 +154,12 @@ export interface ChatPendingVO {
   expiresInSec?: number;
   expired?: boolean;
   toolCalls?: ChatPendingToolCall[];
+  /** 计划文件工作区相对路径(计划审批暂停时非空) */
+  planPath?: string;
+  /** 最近一次 plan_write 的计划正文全文(确认卡直接展示,防「盲批」) */
+  planContent?: string;
+  /** 计划驳回次数(同一编排内累计,达到上限后本轮终止) */
+  planRejectCount?: number;
 }
 
 export interface ChatConfirmBody {

+ 28 - 3
ai-electron/frontend/src/workbench/components/chat/PlanApprovalCard.vue

@@ -10,13 +10,18 @@
     </div>
 
     <div class="plan-card__body">
-      <div class="plan-card__summary">{{ summary || '(计划摘要为空,请查看完整计划文档)' }}</div>
+      <div class="plan-card__summary">{{ displayText || '(计划正文为空,请查看完整计划文档)' }}</div>
 
       <div class="plan-card__meta">
         <button class="plan-card__doc" type="button" @click="$emit('open-doc')">
           <Icon icon="i-mdi:file-document-outline" />
           查看完整计划文档
         </button>
+        <span v-if="part.planPath" class="plan-card__path" :title="part.planPath">{{ part.planPath }}</span>
+        <span
+          v-if="part.confirmState === 'pending' && part.planRejectCount > 0"
+          class="plan-card__reject"
+        >已被驳回 {{ part.planRejectCount }} 次(累计 3 次将终止本轮)</span>
         <button class="plan-card__raw-toggle" type="button" @click="showRaw = !showRaw">
           {{ showRaw ? '收起原始参数' : '原始参数' }}
         </button>
@@ -46,8 +51,11 @@
 
 <script setup lang="ts">
   /**
-   * 计划模式专用批准卡:把 plan_exit 的 summary 以可读 prose 呈现(替代通用确认卡的 raw JSON),
+   * 计划模式专用批准卡:把计划正文以可读 prose 呈现(替代通用确认卡的 raw JSON),
    * 提供「查看完整计划文档」入口与批准/拒绝动作;原始参数折叠留证。
+   *
+   * <p>正文优先取后端随待确认记录下发的 planContent(最近一次 plan_write 全文,对齐上游 1.1.2);
+   * 未下发时回退 plan_exit 入参中的 summary / plan。</p>
    */
   import { computed, ref } from 'vue';
   import { Button as AButton, Tag as ATag } from 'ant-design-vue';
@@ -78,6 +86,9 @@
     return input.summary || input.plan || '';
   });
 
+  /** 展示正文:后端下发的 plan_write 全文优先(完整方案),否则回退 plan_exit 摘要 */
+  const displayText = computed(() => props.part?.planContent || summary.value || '');
+
   const rawInput = computed(() => {
     const input = planCall.value?.input;
     if (input == null) return '';
@@ -193,7 +204,21 @@
       }
     }
 
-    &__raw-toggle {
+    &__path {
+    overflow: hidden;
+    max-width: 200px;
+    font-size: 11.5px;
+    color: var(--wb-text-muted, #94a3b8);
+    text-overflow: ellipsis;
+    white-space: nowrap;
+  }
+
+  &__reject {
+    font-size: 11.5px;
+    color: var(--wb-danger, #dc2626);
+  }
+
+  &__raw-toggle {
       margin-left: auto;
       padding: 4px 10px;
       font-size: 12px;

+ 15 - 2
ai-electron/frontend/src/workbench/views/chat/index.vue

@@ -564,9 +564,9 @@
               </div>
             </div>
             <div class="composer-actions-right">
-              <!-- 计划模式:开启后先只读设计并产出 plans/PLAN.md,确认后再执行;任务清单同时启用 -->
+              <!-- 计划模式:开启后先只读设计并产出 plans/<会话>/PLAN.md,确认后再执行;任务清单同时启用 -->
               <a-tooltip
-                title="先只读设计并产出 plans/PLAN.md,确认后再执行;任务清单同时启用"
+                title="先只读设计并产出计划文档(按会话独立存放),确认后再执行;任务清单同时启用"
                 placement="top"
                 overlay-class-name="composer-tooltip"
               >
@@ -990,6 +990,12 @@
     confirmState?: 'pending' | 'approved' | 'rejected' | 'expired';
     /** 拒绝原因(kind=confirm,用户拒绝时填写,用于卡片回显) */
     confirmReason?: string;
+    /** 计划文件工作区相对路径(kind=confirm 且为计划审批时下发) */
+    planPath?: string;
+    /** 计划正文全文(kind=confirm 且为计划审批时下发,确认卡直接展示防「盲批」) */
+    planContent?: string;
+    /** 计划驳回次数(kind=confirm 且为计划审批时下发) */
+    planRejectCount?: number;
     /** 专家标识(kind=expert,REQ-AI-30) */
     expertKey?: string;
     /** 专家智能体主键(kind=expert,用于按 agentId + attemptNo 挂回轨迹里的原始结论) */
@@ -3044,6 +3050,9 @@
         messageId: pending.messageId,
         toolCalls: pending.toolCalls ?? [],
         confirmState: pending.expired ? 'expired' : 'pending',
+        planPath: pending.planPath,
+        planContent: pending.planContent,
+        planRejectCount: pending.planRejectCount,
       });
     });
     // 后台仍在生成的会话:进入后按 2s 轮询续看进度,完成后重新加载
@@ -3575,6 +3584,10 @@
           messageId: event.messageId,
           toolCalls: event.toolCalls ?? [],
           confirmState: 'pending',
+          // 计划审批:卡片展示计划文件路径、正文全文与驳回进度(对齐上游 1.1.2,防「盲批」)
+          planPath: event.planPath,
+          planContent: event.planContent,
+          planRejectCount: event.planRejectCount,
         });
         finishStream();
         break;

+ 22 - 7
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentAssembler.java

@@ -76,9 +76,13 @@ import java.util.Map;
 public class AgentAssembler {
 
     /**
-     * 计划文件目录(相对智能体工作区,固定为 plans)
+     * 计划文件目录前缀(相对智能体工作区):计划文件按会话分桶,最终目录为 {@code plans/<sessionId>}。
+     *
+     * <p>案件会话的智能体工作区按「案件 × 智能体 × 用户」共享,不分会话会让同一案件的多个会话
+     * 互踩 {@code PLAN.md};工作台会话工作区本身已按会话隔离,分桶只是目录多一层,展示不受影响
+     * (产物扫描为递归扫描,前端按文件名匹配 PLAN.md)。</p>
      */
-    private static final String PLAN_FILE_DIRECTORY = "plans";
+    public static final String PLAN_FILE_DIR_PREFIX = "plans";
 
     /**
      * 技能内置工具名(由框架 DynamicSkillMiddleware 注册,需显式放进 ToolsConfig 白名单,
@@ -287,6 +291,7 @@ public class AgentAssembler {
      * @param workspaceCode 工作区命名空间编码(caseId 为空时的历史 / 全局 fallback)
      * @param caseId        会话所属案件(非空时工作区与长期记忆按案件隔离)
      * @param workspaceAgentId 案件工作区归属的智能体主键(入口与专家共享入口 Agent 工作区)
+     * @param planSessionId 计划生效的会话主键(计划文件按会话分桶 plans/&lt;sessionId&gt;;可空)
      * @return 装配结果(智能体实例 + 执行期快照)
      */
     AssembledAgent assemble(AiAgent definition, List<AiTool> enabledTools, List<Long> kbIds,
@@ -295,7 +300,7 @@ public class AgentAssembler {
                             AiCompactionConfigBo compactionPolicy,
                             AiMemoryConfigBo memoryPolicy,
                             McpClientAssembly mcpAssembly, boolean expertMode, boolean planEnabled,
-                            String workspaceCode, Long caseId, Long workspaceAgentId) {
+                            String workspaceCode, Long caseId, Long workspaceAgentId, Long planSessionId) {
         AiModelConfig modelConfig = modelFactory.resolveChatModel(definition.getModelId());
         // 模型级思考模式覆盖(enable_thinking 列,null 跟随模型/供应商默认;过程面板思考步的数据来源)
         Model model = modelFactory.buildChatModel(modelConfig, modelConfig.getEnableThinking());
@@ -354,7 +359,7 @@ public class AgentAssembler {
         // 上下文压缩(REQ-AI-21)按运行期策略装配;比例触发需主对话模型的上下文窗口
         applyCompaction(builder, definition, model, compactionPolicy);
         // 计划模式与任务清单(REQ-AI-22):入口智能体常驻注册,聊天输入框按会话开关动态进入 / 退出
-        applyPlanMode(builder, expertMode, planEnabled && definition.isEntry());
+        applyPlanMode(builder, expertMode, planEnabled && definition.isEntry(), planSessionId);
         // 长期记忆(REQ-AI-09)按运行期策略装配
         applyMemory(builder, definition, memoryPolicy);
         log.info("运行期策略:agent={}, compaction={}(triggerMessages={}, triggerTokens={}, keepMessages={}, "
@@ -581,19 +586,29 @@ public class AgentAssembler {
      *
      * <p>计划模式只在入口智能体常驻注册(plan_enter / plan_write / plan_exit 与只读守卫),
      * 聊天输入框按会话开关在每轮开始前调用 {@code enterPlanMode / exitPlanMode} 动态切换。
-     * 计划文件目录固定为 {@code plans}(相对智能体工作区);任务清单随计划能力默认启用。</p>
+     * 计划文件目录按会话分桶为 {@code plans/<sessionId>}(相对智能体工作区);任务清单随计划能力默认启用。</p>
+     *
+     * <p>同时注册两个治理中间件(对齐上游 1.1.2):{@link PlanFileResetMiddleware} 在每次 plan_enter
+     * 前清空旧计划文件;{@link PlanWriteGuardMiddleware} 在 PLAN 生效期兜底拦截变更类工具。</p>
      *
      * @param builder     智能体构建器
      * @param expertMode  是否专家执行装配(专家不注册计划模式能力)
      * @param planEnabled 本会话是否开启计划模式
+     * @param sessionId   会话主键(计划文件分桶用;plan on 时非空)
      */
-    private void applyPlanMode(HarnessAgent.Builder builder, boolean expertMode, boolean planEnabled) {
+    private void applyPlanMode(HarnessAgent.Builder builder, boolean expertMode, boolean planEnabled,
+                               Long sessionId) {
         if (expertMode || !planEnabled) {
             return;
         }
+        String planDirectory = PLAN_FILE_DIR_PREFIX + "/" + sessionId;
         builder.enablePlanMode(true);
-        builder.planFileDirectory(PLAN_FILE_DIRECTORY);
+        builder.planFileDirectory(planDirectory);
         builder.enableTaskList(true);
+        // 每次 plan_enter 前清空本会话遗留的计划文件(同一会话可能多次进入 PLAN,框架不会清空旧内容)
+        builder.middleware(new PlanFileResetMiddleware(planDirectory));
+        // PLAN 生效期间兜底拦截变更类工具:框架只放行只读工具,但子智能体 / 同批 plan_enter 等路径可绕过
+        builder.middleware(new PlanWriteGuardMiddleware());
     }
 
     /**

+ 6 - 3
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentFingerprintCalculator.java

@@ -40,6 +40,7 @@ public class AgentFingerprintCalculator {
      * @param mcpAssembly   外部 MCP 连接装配结果(REQ-AI-16;已按场景包收敛)
      * @param packSignature 场景包装配指纹片段(包本体 + 三类绑定;未选包时为空串)
      * @param planEnabled   是否开启计划模式(决定是否注册 plan_* / todo_write 工具与任务清单)
+     * @param planSessionId 计划生效的会话主键(计划文件目录按会话分桶;可空)
      * @return 指纹字符串
      */
     String buildFingerprint(AiAgent definition, List<AiTool> enabledTools, List<AiAgentTool> bindings,
@@ -47,7 +48,7 @@ public class AgentFingerprintCalculator {
                             AiMemoryConfigBo memoryPolicy,
                             List<String> skillNames,
                             McpClientAssembly mcpAssembly,
-                            String packSignature, boolean planEnabled) {
+                            String packSignature, boolean planEnabled, Long planSessionId) {
         StringBuilder toolPart = new StringBuilder();
         for (AiTool tool : enabledTools) {
             toolPart.append(tool.getToolCode()).append(':')
@@ -77,8 +78,10 @@ public class AgentFingerprintCalculator {
             + "|mcp=" + mcpAssembly.signature()
             // 场景包(装配单元为「智能体 × 场景包」):包本体或三类绑定变化时重建
             + "|pack=" + packSignature
-            // 计划模式变体:开启时注册 plan_* 与 todo_write、任务清单中间件,是两套装配实例
-            + "|plan=" + planEnabled;
+            // 计划模式变体:开启时注册 plan_* 与 todo_write、任务清单中间件,且计划文件目录按会话分桶
+            // (plans/<sessionId>),故 plan on 的指纹必须含会话主键;plan off 不含(缓存命中行为不变)
+            + "|plan=" + planEnabled
+            + (planEnabled ? "|session=" + planSessionId : "");
     }
 
     /**

+ 64 - 21
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentRegistry.java

@@ -301,7 +301,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent get(AiAgent definition, Long caseId) {
-        return getInternal(definition, AiSessionResourceSet.empty(), false, false, caseId).agent();
+        return getInternal(definition, AiSessionResourceSet.empty(), false, false, caseId, null).agent();
     }
 
     /**
@@ -327,7 +327,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent get(AiAgent definition, AiSessionResourceSet resources) {
-        return getInternal(definition, resources, false, false, null).agent();
+        return getInternal(definition, resources, false, false, null, null).agent();
     }
 
     /**
@@ -339,7 +339,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent get(AiAgent definition, AiSessionResourceSet resources, Long caseId) {
-        return getInternal(definition, resources, false, false, caseId).agent();
+        return getInternal(definition, resources, false, false, caseId, null).agent();
     }
 
     /**
@@ -351,7 +351,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent get(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled) {
-        return getInternal(definition, resources, false, planEnabled, null).agent();
+        return getInternal(definition, resources, false, planEnabled, null, null).agent();
     }
 
     /**
@@ -365,7 +365,22 @@ public class AgentRegistry {
      */
     public HarnessAgent get(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
                             Long caseId) {
-        return getInternal(definition, resources, false, planEnabled, caseId).agent();
+        return get(definition, resources, planEnabled, caseId, null);
+    }
+
+    /**
+     * 取用(必要时装配)指定案件下的实例(含计划模式变体;计划文件目录按会话分桶)。
+     *
+     * @param definition    智能体定义
+     * @param resources     会话级资源集(可空:表示空集)
+     * @param planEnabled   本会话是否开启计划模式
+     * @param caseId        会话所属案件(可空)
+     * @param planSessionId 计划生效的会话主键(plan on 时必须传入,用于 plans/&lt;sessionId&gt; 分桶)
+     * @return HarnessAgent 实例
+     */
+    public HarnessAgent get(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
+                            Long caseId, Long planSessionId) {
+        return getInternal(definition, resources, false, planEnabled, caseId, planSessionId).agent();
     }
 
     /**
@@ -383,7 +398,7 @@ public class AgentRegistry {
      * @return 装配结果(实例 + 指纹 + 执行期快照)
      */
     public AgentHolder holder(AiAgent definition, AiSessionResourceSet resources) {
-        return getInternal(definition, resources, false, false, null);
+        return getInternal(definition, resources, false, false, null, null);
     }
 
     /**
@@ -395,7 +410,7 @@ public class AgentRegistry {
      * @return 装配结果(实例 + 指纹 + 执行期快照)
      */
     public AgentHolder holder(AiAgent definition, AiSessionResourceSet resources, Long caseId) {
-        return getInternal(definition, resources, false, false, caseId);
+        return getInternal(definition, resources, false, false, caseId, null);
     }
 
     /**
@@ -410,7 +425,7 @@ public class AgentRegistry {
      * @return 装配结果(实例 + 指纹 + 执行期快照)
      */
     public AgentHolder holder(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled) {
-        return getInternal(definition, resources, false, planEnabled, null);
+        return getInternal(definition, resources, false, planEnabled, null, null);
     }
 
     /**
@@ -424,7 +439,22 @@ public class AgentRegistry {
      */
     public AgentHolder holder(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
                               Long caseId) {
-        return getInternal(definition, resources, false, planEnabled, caseId);
+        return holder(definition, resources, planEnabled, caseId, null);
+    }
+
+    /**
+     * 取用(必要时装配)指定案件下的实例并返回执行期快照(含计划模式变体;计划文件按会话分桶)。
+     *
+     * @param definition    智能体定义
+     * @param resources     会话级资源集(可空:表示空集)
+     * @param planEnabled   本会话是否开启计划模式
+     * @param caseId        会话所属案件(可空)
+     * @param planSessionId 计划生效的会话主键(plan on 时必须传入,用于 plans/&lt;sessionId&gt; 分桶)
+     * @return 装配结果(实例 + 指纹 + 执行期快照)
+     */
+    public AgentHolder holder(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
+                              Long caseId, Long planSessionId) {
+        return getInternal(definition, resources, false, planEnabled, caseId, planSessionId);
     }
 
     /**
@@ -445,7 +475,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent getExpert(AiAgent definition, Long caseId) {
-        return getInternal(definition, AiSessionResourceSet.empty(), true, false, caseId).agent();
+        return getInternal(definition, AiSessionResourceSet.empty(), true, false, caseId, null).agent();
     }
 
     /**
@@ -467,7 +497,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent getExpert(AiAgent definition, AiSessionResourceSet resources) {
-        return getInternal(definition, resources, true, false, null).agent();
+        return getInternal(definition, resources, true, false, null, null).agent();
     }
 
     /**
@@ -479,7 +509,7 @@ public class AgentRegistry {
      * @return HarnessAgent 实例
      */
     public HarnessAgent getExpert(AiAgent definition, AiSessionResourceSet resources, Long caseId) {
-        return getInternal(definition, resources, true, false, caseId).agent();
+        return getInternal(definition, resources, true, false, caseId, null).agent();
     }
 
     /**
@@ -490,10 +520,11 @@ public class AgentRegistry {
      * @param expertMode 是否专家执行装配(业务工具只读收敛 + 内置工具确认 + 协议工具)
      * @param planEnabled 是否开启计划模式(仅入口智能体生效;专家恒为 false)
      * @param caseId     会话所属案件(可空;非空时工作区与长期记忆按案件隔离)
+     * @param planSessionId 计划生效的会话主键(plan on 时计划文件目录按会话分桶;可空)
      * @return 装配结果(实例 + 指纹 + 执行期快照)
      */
     private AgentHolder getInternal(AiAgent definition, AiSessionResourceSet resources, boolean expertMode,
-                                    boolean planEnabled, Long caseId) {
+                                    boolean planEnabled, Long caseId, Long planSessionId) {
         if (definition == null || definition.getId() == null) {
             throw new ServiceException("智能体定义不存在");
         }
@@ -552,13 +583,14 @@ public class AgentRegistry {
         // 模型配置(地址 / 密钥 / 超时 / 重试 / 启用状态)也是装配参数:改配置后须让已装配实例失效重建
         String modelSignature = fingerprintCalculator.modelSignature(definition);
         String fingerprint = fingerprintCalculator.buildFingerprint(definition, enabledTools, bindings, modelSignature,
-            compactionPolicy, memoryPolicy, skillNames, mcpAssembly, res.packSignature(), planEnabled)
+            compactionPolicy, memoryPolicy, skillNames, mcpAssembly, res.packSignature(), planEnabled, planSessionId)
             // 专家执行装配与普通装配是两套实例:标记并入指纹,角色或模式变化即触发重建
             + "|expert=" + expertMode
             // 案件级工作区 / 记忆路径不同,必须触发独立装配
             + "|case=" + (caseId == null ? "" : caseId)
             + "|ws=" + (workspaceAgentId == null ? "" : workspaceAgentId);
-        String cacheKey = cacheKey(definition.getId(), expertMode, res.signature(), planEnabled, caseId);
+        String cacheKey = cacheKey(definition.getId(), expertMode, res.signature(), planEnabled, caseId,
+            planSessionId);
         // 会话内切换资源组合:丢弃**目标实例**(它可能此前已服务过本会话,复用会触发框架状态 CAS 读取失败)
         if (!expertMode && res.sessionId() != null) {
             String sessionKey = definition.getId() + "#" + res.sessionId();
@@ -582,7 +614,7 @@ public class AgentRegistry {
             }
             AgentAssembler.AssembledAgent assembled = assembler.assemble(definition, enabledTools, kbIds, skillNames,
                 bindings, res, compactionPolicy, memoryPolicy, mcpAssembly, expertMode, planEnabled, workspaceCode,
-                caseId, workspaceAgentId);
+                caseId, workspaceAgentId, planSessionId);
             return new AgentHolder(definition.getId(), caseId, assembled.agent(), fingerprint, assembled.snapshot());
         });
         lastAccess.put(cacheKey, System.nanoTime());
@@ -764,14 +796,19 @@ public class AgentRegistry {
      */
     public AgentSnapshot snapshotOf(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
                                     Long caseId) {
+        return snapshotOf(definition, resources, planEnabled, caseId, null);
+    }
+
+    public AgentSnapshot snapshotOf(AiAgent definition, AiSessionResourceSet resources, boolean planEnabled,
+                                    Long caseId, Long planSessionId) {
         if (definition == null || definition.getId() == null) {
             return null;
         }
         AiSessionResourceSet res = resources == null ? AiSessionResourceSet.empty() : resources;
-        String key = cacheKey(definition.getId(), false, res.signature(), planEnabled, caseId);
+        String key = cacheKey(definition.getId(), false, res.signature(), planEnabled, caseId, planSessionId);
         // 统一走 get:会话内切换资源组合时的「丢弃目标实例」判定在 get 内完成,
         // 否则这里会取到切换前的旧实例快照(工具清单与实际执行不一致)
-        get(definition, res, planEnabled, caseId);
+        get(definition, res, planEnabled, caseId, planSessionId);
         AgentHolder holder = cache.get(key);
         return holder == null ? null : holder.snapshot();
     }
@@ -828,7 +865,7 @@ public class AgentRegistry {
             return null;
         }
         AiSessionResourceSet res = resources == null ? AiSessionResourceSet.empty() : resources;
-        String key = cacheKey(definition.getId(), true, res.signature(), false, caseId);
+        String key = cacheKey(definition.getId(), true, res.signature(), false, caseId, null);
         // 先过装配:按当前指纹判定是否重建,重建后的快照才与实际执行一致
         getExpert(definition, res, caseId);
         AgentHolder holder = cache.get(key);
@@ -977,15 +1014,21 @@ public class AgentRegistry {
      * <p>{@code sig} 是会话资源集的**身份签名**(排序后的 type:key 列表 → SHA-256 前 8 字节):
      * 选中哪些场景包 / 工具 / 技能 / MCP 工具决定实例;资源内容变更由装配指纹触发重建。</p>
      *
+     * <p>计划模式开启时附加 {@code #P<sessionId>}:plan 工具与计划文件目录 {@code plans/<sessionId>}
+     * 都是按会话区分的装配产物,不同会话不得复用实例。</p>
+     *
      * @param agentId   智能体主键
      * @param expertMode 是否专家执行装配
      * @param signature 资源集签名(可空按空串处理)
+     * @param planEnabled 是否开启计划模式
+     * @param caseId 会话所属案件(可空)
+     * @param planSessionId 计划生效的会话主键(可空)
      * @return 缓存键
      */
     private String cacheKey(Long agentId, boolean expertMode, String signature, boolean planEnabled,
-                            Long caseId) {
+                            Long caseId, Long planSessionId) {
         String sig = signature == null ? "" : signature;
-        String plan = planEnabled ? "#P" : "";
+        String plan = planEnabled ? "#P" + (planSessionId == null ? "" : planSessionId) : "";
         String casePrefix = caseId == null ? "" : "case:" + caseId + "#";
         return casePrefix + (expertMode
             ? agentId + "#" + EXPERT_CACHE_SUFFIX + "#R:" + sig + plan

+ 98 - 13
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiChatFacade.java

@@ -9,6 +9,7 @@ import io.agentscope.core.permission.PermissionMode;
 import io.agentscope.core.skill.SkillFilter;
 import io.agentscope.core.state.AgentState;
 import io.agentscope.harness.agent.HarnessAgent;
+import io.agentscope.harness.agent.tool.PlanModeTools;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import com.zsjz.ai.module.ai.config.AiProperties;
@@ -122,6 +123,23 @@ public class AiChatFacade {
      */
     private static final String EVENT_ABORTED = "aborted";
 
+    /**
+     * 计划模式工具:人工批准是产品硬约束,不能被「记住该工具」沉淀为免确认(对齐上游 1.1.2)
+     */
+    private static final Set<String> PLAN_TOOLS = Set.of(
+        PlanModeTools.PLAN_ENTER, PlanModeTools.PLAN_WRITE, PlanModeTools.PLAN_EXIT);
+
+    /**
+     * 计划被拒绝的次数上限:达到后不再发起确认,直接以文字说明结束本轮
+     */
+    static final int PLAN_REJECT_LIMIT = 3;
+
+    /**
+     * 计划连续被拒绝达到上限时的结束说明
+     */
+    private static final String PLAN_REJECT_LIMIT_TEXT =
+        "\n\n计划已连续 3 次未获批准,本轮已结束,不会进入执行。你可以调整需求后重新提问。";
+
     /**
      * 用户主动停止本轮的说明文案(落链路追踪 / 编排运行的中止原因)
      */
@@ -388,7 +406,7 @@ public class AiChatFacade {
         // 原先 snapshotOf 与下方的 get 各走一遍完整装配(各含绑定 / 工具 / 知识库 / 技能 /
         // 运行期策略 / MCP 解析等查询),合并后每轮省掉一遍(口径见 docs/22 §3.1 C「前提修正」)
         AgentRegistry.AgentHolder holder = agentRegistry.holder(definition, resources, planModeActive,
-            session.getCaseId());
+            session.getCaseId(), sessionId);
         // 链路追踪(REQ-AI-28)先建:编排运行状态需要它以建立「父链路 → 专家子链路」的关系
         Long traceId = traceService.start(sessionId, definition.getId(), userId, AiTrace.SOURCE_CHAT,
             holder.snapshot());
@@ -717,8 +735,10 @@ public class AiChatFacade {
             AiSessionResourceSet resources = sessionResourceService.resolveForSession(session);
             Long userId = LoginHelper.getUserId();
             boolean planModeActive = AiSession.PLAN_ON.equals(session.getPlanMode());
-            // 必须与后续生成共用同一实例:状态按 (userId, sessionId) 存放,换实例会读回旧上下文
-            HarnessAgent agent = agentRegistry.get(definition, resources, planModeActive, session.getCaseId());
+            // 必须与后续生成共用同一实例:状态按 (userId, sessionId) 存放,换实例会读回旧上下文;
+            // 计划开启时计划文件目录按会话分桶,须带会话主键取(或装配)对应实例
+            HarnessAgent agent = agentRegistry.get(definition, resources, planModeActive, session.getCaseId(),
+                session.getId());
             if (!contextRestorer.restore(agent, userId, sessionId, userMessageId)) {
                 rejectRegenerate(emitter, regenerateFailure(AiRegenerateCheckVo.CODE_CONTEXT_RESTORE_FAILED,
                     "无法回退该轮的对话上下文,请新建会话后重试"));
@@ -827,6 +847,11 @@ public class AiChatFacade {
         if (pending.decisions() == null || pending.decisions().isEmpty()) {
             throw new ServiceException("尚未收到确认结果");
         }
+        // 计划连续被拒绝达到上限:不再恢复执行(否则会再次弹卡),直接以文字说明结束本轮(对齐上游 1.1.2)
+        if (pending.planRejectCount() != null && pending.planRejectCount() >= PLAN_REJECT_LIMIT) {
+            finishPlanRejected(sessionId, messageId, pending, emitter);
+            return;
+        }
         if (pending.expertResume() != null) {
             // 专家链路的暂停:恢复段必须驱动**专家**续跑,再由入口智能体整合(REQ-AI-30 Phase 2 HITL 贯通)
             expertResumeDriver.resumeRoute(session, messageId, pending, emitter);
@@ -835,8 +860,13 @@ public class AiChatFacade {
         AiAgent definition = agentService.getEnabledAgent(session.getAgentId());
         // 恢复段与首段使用同一份会话资源集(REQ-AI-32:每轮现读,会话内可变),保证工具 / 技能与首段一致
         AiSessionResourceSet resources = sessionResourceService.resolveForSession(session);
-        boolean planModeActive = AiSession.PLAN_ON.equals(session.getPlanMode());
-        HarnessAgent agent = agentRegistry.get(definition, resources, planModeActive, session.getCaseId());
+        // 恢复段沿用暂停轮记录的计划生效值:确认期间会话开关被改时,实例必须与暂停轮一致,
+        // 否则恢复流会命中另一套装配实例(无 plan 工具 / 状态键不同)
+        boolean planModeActive = pending.planEnabled() != null
+            ? pending.planEnabled()
+            : AiSession.PLAN_ON.equals(session.getPlanMode());
+        HarnessAgent agent = agentRegistry.get(definition, resources, planModeActive, session.getCaseId(),
+            session.getId());
         RuntimeContext.Builder resumeContext = RuntimeContext.builder()
             .userId(String.valueOf(pending.userId()))
             .sessionId(String.valueOf(sessionId))
@@ -872,7 +902,8 @@ public class AiChatFacade {
         state.traceId = traceService.findIdByMessage(sessionId, messageId);
         if (state.traceId == null) {
             state.traceId = traceService.start(sessionId, definition.getId(), pending.userId(), AiTrace.SOURCE_CHAT,
-                agentRegistry.snapshotOf(definition, resources, planModeActive, session.getCaseId()));
+                agentRegistry.snapshotOf(definition, resources, planModeActive, session.getCaseId(),
+                    session.getId()));
         } else {
             traceService.appendTransition(state.traceId, "resume", "人工确认后恢复执行");
         }
@@ -988,6 +1019,33 @@ public class AiChatFacade {
         }
     }
 
+    /**
+     * 计划连续被拒绝达到上限后的收尾:把本轮标记为已中止并结束流,不再恢复执行(对齐上游 1.1.2)。
+     *
+     * <p>不再发起确认卡片,避免「驳回 → 再弹卡」的循环;说明文案追加到暂停轮的同一条助手消息上。</p>
+     *
+     * @param sessionId 会话主键
+     * @param messageId 待确认消息主键(沿用同一条助手消息追加说明)
+     * @param pending   待确认状态(读取拒绝次数)
+     * @param emitter   SSE 发射器
+     */
+    private void finishPlanRejected(Long sessionId, Long messageId,
+                                    AiConfirmPendingStore.PendingConfirm pending, SseEmitter emitter) {
+        try {
+            sessionService.appendAssistantTurn(messageId, PLAN_REJECT_LIMIT_TEXT, AiMessage.STATUS_ABORTED,
+                0L, List.of(), null, List.of());
+        } catch (Exception e) {
+            log.warn("计划拒绝上限收尾落库失败:sessionId={}, messageId={}, err={}", sessionId, messageId, e.getMessage());
+        }
+        pendingStore.remove(sessionId, messageId);
+        Map<String, Object> payload = AiSseSupport.envelope(EVENT_ABORTED);
+        payload.put("messageId", messageId);
+        payload.put("durationMs", 0L);
+        payload.put("reason", "计划已连续 " + PLAN_REJECT_LIMIT + " 次未获批准");
+        AiSseSupport.send(emitter, payload);
+        AiSseSupport.complete(emitter);
+    }
+
     /**
      * 记录用户对待确认工具调用的处置结果(确认 / 拒绝 / 记住)。
      *
@@ -1005,17 +1063,37 @@ public class AiChatFacade {
         boolean remember = Boolean.TRUE.equals(bo.getRemember());
         // 自定义拒绝原因(可选):仅在拒绝时生效,回传模型并写入决策日志
         String rejectReason = StringUtils.trim(bo.getRejectReason());
+        // 计划工具不受「记住该工具」影响:人工批准是产品硬约束(对齐上游 1.1.2)。
+        // 若允许记住,ConfirmResult 会带回 ALLOW 规则并由框架写回会话权限上下文、跨轮生效,
+        // 之后再次 plan_exit 会静默跳过审批直接执行。前端已隐藏该按钮,此处兜底防其它调用方传 true
+        boolean effectiveRemember = remember && pending.toolCalls().stream()
+            .noneMatch(call -> PLAN_TOOLS.contains(call.toolName()));
         List<AiConfirmPendingStore.PendingDecision> decisions = new ArrayList<>();
         for (AiConfirmPendingStore.PendingToolCall call : pending.toolCalls()) {
-            decisions.add(new AiConfirmPendingStore.PendingDecision(call.toolCallId(), confirmed, remember, rejectReason));
+            decisions.add(new AiConfirmPendingStore.PendingDecision(call.toolCallId(), confirmed, effectiveRemember,
+                rejectReason));
+        }
+        // 计划审批:拒绝次数累计在同一编排的待确认记录上,达到上限后恢复段直接终止本轮
+        boolean planExitPending = pending.toolCalls().stream()
+            .anyMatch(call -> PlanModeTools.PLAN_EXIT.equals(call.toolName()));
+        int planRejectCount = pending.planRejectCount() == null ? 0 : pending.planRejectCount();
+        Boolean planApproved = pending.planApproved();
+        if (planExitPending) {
+            if (confirmed) {
+                planApproved = Boolean.TRUE;
+            } else {
+                planRejectCount++;
+                planApproved = Boolean.FALSE;
+            }
         }
         pendingStore.save(new AiConfirmPendingStore.PendingConfirm(pending.sessionId(), pending.messageId(),
             pending.agentId(), pending.userId(), pending.replyId(), pending.toolCalls(), decisions,
-            pending.createdAt(), pending.expertResume()));
-        decisionService.applyConfirm(bo.getMessageId(), confirmed, remember, rejectReason);
+            pending.createdAt(), pending.planEnabled(), pending.planPath(), pending.planContent(),
+            planRejectCount, planApproved, pending.expertResume()));
+        decisionService.applyConfirm(bo.getMessageId(), confirmed, effectiveRemember, rejectReason);
         // 框架原生 HITL:确认结果通过 ConfirmResult 在恢复流中回传,由框架决定放行或拒绝;
         // 此处处理「记住该工具」:落「智能体 × 工具 × 用户」信任决策 + 并入对应会话槽位的权限上下文
-        if (confirmed && remember) {
+        if (confirmed && effectiveRemember) {
             for (AiConfirmPendingStore.PendingToolCall call : pending.toolCalls()) {
                 agentService.rememberToolForAgent(pending.agentId(), pending.userId(), call.toolName());
             }
@@ -1026,10 +1104,13 @@ public class AiChatFacade {
             // 会话权限模式:入口 / 专家槽位重建时保持用户当前选择(完全访问不被「记住」重建降回确认)
             PermissionMode sessionMode = permissionModeStore.resolve(confirmSession);
             if (pending.expertResume() == null) {
-                // 入口智能体自身的暂停:信任并入用户会话槽位(既有口径)
-                boolean planModeActive = AiSession.PLAN_ON.equals(confirmSession.getPlanMode());
+                // 入口智能体自身的暂停:信任并入用户会话槽位(既有口径);
+                // 计划待确认期间沿用暂停时记录的生效值,不按最新会话开关重算(开关在确认期间被改时实例必须与暂停轮一致)
+                boolean planModeActive = pending.planEnabled() != null
+                    ? pending.planEnabled()
+                    : AiSession.PLAN_ON.equals(confirmSession.getPlanMode());
                 trustApplier.apply(agentRegistry.get(definition, resources, planModeActive,
-                        confirmSession.getCaseId()), definition, resources,
+                        confirmSession.getCaseId(), sessionId), definition, resources,
                     pending.userId(), sessionId, sessionMode);
             } else {
                 // 专家链路的暂停:信任必须并入**专家会话槽位**(userId, routeRunId#expertAgentId),
@@ -1065,6 +1146,10 @@ public class AiChatFacade {
             } else {
                 vo.setExpired(false);
                 vo.setReplyId(pending.replyId());
+                // 计划审批回显:确认卡直接展示计划文件路径、正文全文与当前驳回次数(防「盲批」)
+                vo.setPlanPath(pending.planPath());
+                vo.setPlanContent(pending.planContent());
+                vo.setPlanRejectCount(pending.planRejectCount());
                 List<AiChatPendingVo.ToolCall> calls = new ArrayList<>(pending.toolCalls().size());
                 for (AiConfirmPendingStore.PendingToolCall call : pending.toolCalls()) {
                     AiChatPendingVo.ToolCall item = new AiChatPendingVo.ToolCall();

+ 16 - 9
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiConfirmPendingStore.java

@@ -142,18 +142,25 @@ public class AiConfirmPendingStore {
     /**
      * 待确认状态。
      *
-     * @param sessionId    会话主键
-     * @param messageId    助手消息主键(暂停时落库)
-     * @param agentId      发起该待确认工具调用的智能体主键(**专家链路的暂停为专家主键**,否则为会话智能体)
-     * @param userId       提问用户
-     * @param replyId      AgentScope replyId
-     * @param toolCalls    待确认的工具调用
-     * @param decisions    用户处置结果(确认接口写入,恢复流读取)
-     * @param createdAt    创建时间(ISO-8601)
-     * @param expertResume 专家续跑信息;为 {@code null} 表示这是入口智能体自己的暂停(走既有入口恢复路径)
+     * @param sessionId       会话主键
+     * @param messageId       助手消息主键(暂停时落库)
+     * @param agentId         发起该待确认工具调用的智能体主键(**专家链路的暂停为专家主键**,否则为会话智能体)
+     * @param userId          提问用户
+     * @param replyId         AgentScope replyId
+     * @param toolCalls       待确认的工具调用
+     * @param decisions       用户处置结果(确认接口写入,恢复流读取)
+     * @param createdAt       创建时间(ISO-8601)
+     * @param planEnabled     计划模式在暂停轮的生效值({@code null} 表示非计划暂停;确认期间会话开关被改时,恢复段以此为准)
+     * @param planPath        计划文件工作区相对路径(计划生效时非空,{@code plans/<sessionId>/PLAN.md})
+     * @param planContent     最近一次 plan_write 的计划正文全文(随待确认留存,确认卡直接展示防「盲批」)
+     * @param planRejectCount 计划驳回次数(同一编排内「修订 → 再次确认」累计,达到上限后终止本轮)
+     * @param planApproved    计划批准结果({@code true} 批准 / {@code false} 已驳回 / {@code null} 未处置)
+     * @param expertResume    专家续跑信息;为 {@code null} 表示这是入口智能体自己的暂停(走既有入口恢复路径)
      */
     public record PendingConfirm(Long sessionId, Long messageId, Long agentId, Long userId, String replyId,
                                  List<PendingToolCall> toolCalls, List<PendingDecision> decisions, String createdAt,
+                                 Boolean planEnabled, String planPath, String planContent,
+                                 Integer planRejectCount, Boolean planApproved,
                                  ExpertResume expertResume) {
     }
 

+ 9 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteContext.java

@@ -133,6 +133,15 @@ import java.util.concurrent.atomic.AtomicLong;
      */
     final Queue<AiToolCallLog> expertToolLogs = new ConcurrentLinkedQueue<>();
 
+    /**
+     * 计划写守卫在 PLAN 阶段拦截的变更类工具调用(对齐上游 1.1.2)。
+     *
+     * <p>被拦截的调用不会产生正常工具事件,故由 {@link PlanWriteGuardMiddleware} 在拦截时记录于此
+     * (状态 DENIED),由 {@link AiTurnFinisher} 收尾时与入口轮 / 专家明细合并落库,保证计划阶段的
+     * 写操作尝试可审计。</p>
+     */
+    final Queue<AiToolCallLog> planBlockedToolLogs = new ConcurrentLinkedQueue<>();
+
     /** 决策动作(self 自答 / route 路由) */
     volatile String action;
 

+ 69 - 2
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiTurnFinisher.java

@@ -1,6 +1,7 @@
 package com.zsjz.ai.module.ai.core.agent;
 
 import io.agentscope.core.message.ToolResultState;
+import io.agentscope.harness.agent.tool.PlanModeTools;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import com.zsjz.ai.module.ai.config.AiProperties;
@@ -64,6 +65,11 @@ public class AiTurnFinisher {
      */
     private static final String EVENT_ABORTED = "aborted";
 
+    /**
+     * 计划被拒绝的次数上限:与 {@link AiChatFacade#PLAN_REJECT_LIMIT} 同源(确认卡展示用)
+     */
+    static final int PLAN_REJECT_LIMIT = AiChatFacade.PLAN_REJECT_LIMIT;
+
     /**
      * 用户主动停止本轮的说明文案(落链路追踪 / 编排运行的中止原因)
      */
@@ -588,10 +594,25 @@ public class AiTurnFinisher {
                 call.toolName(), call.toolName(), JsonUtils.toJsonString(call.input()));
         }
         // 覆盖式保存:第二次及以后的暂停同样落在该 (sessionId, messageId) 槽位上,
-        // decisions 置空以要求用户重新处置
+        // decisions 置空以要求用户重新处置;计划驳回次数与批准结果从上一份记录继承,
+        // 使同一编排内「修订 → 再次确认」仍累计在同一上限上(对齐上游 1.1.2)
+        AiConfirmPendingStore.PendingConfirm previous =
+            pendingStore.get(assistant.getSessionId(), assistant.getId()).orElse(null);
+        Integer planRejectCount = previous == null || previous.planRejectCount() == null
+            ? 0 : previous.planRejectCount();
+        Boolean planApproved = previous == null ? null : previous.planApproved();
+        // plan_exit 暂停即计划审批:留存计划路径与最近一次 plan_write 的正文全文,
+        // 确认卡直接展示防「盲批」(沙箱/文件系统时序不可依赖,故从工具入参提取)
+        boolean planExitPending = state.pendingToolCalls.stream()
+            .anyMatch(call -> PlanModeTools.PLAN_EXIT.equals(call.toolName()));
+        Boolean planEnabled = planExitPending ? Boolean.TRUE : null;
+        String planPath = planExitPending
+            ? AgentAssembler.PLAN_FILE_DIR_PREFIX + "/" + state.sessionId + "/PLAN.md" : null;
+        String planContent = planExitPending ? extractPlanContent(state) : null;
         pendingStore.save(new AiConfirmPendingStore.PendingConfirm(assistant.getSessionId(), assistant.getId(),
             pendingAgentId, state.userId, state.pendingReplyId, state.pendingToolCalls, null,
-            LocalDateTime.now().toString(), expertResume));
+            LocalDateTime.now().toString(), planEnabled, planPath, planContent,
+            planRejectCount, planApproved, expertResume));
 
         // 执行过程:确认步(waiting 非终态;恢复段按同键 upsert 为 approved/rejected)。
         // 交互按钮仍在正文流原位的 confirm 卡片,面板内只读镜像。
@@ -629,10 +650,52 @@ public class AiTurnFinisher {
         payload.put("replyId", state.pendingReplyId);
         payload.put("expiresInSec", aiProperties.getChat().getPendingConfirmTtlMinutes() * 60);
         payload.put("toolCalls", buildToolCallPayloads(state.pendingToolCalls));
+        // 计划审批:卡片展示计划文件路径、正文全文与当前驳回次数(plan_exit 的 summary 已在 toolCalls.input 中)
+        if (StringUtils.isNotBlank(planPath)) {
+            payload.put("planPath", planPath);
+            payload.put("planRejectCount", planRejectCount);
+            payload.put("planRejectLimit", PLAN_REJECT_LIMIT);
+            // 正文全文下发:用户要据此决定批准与否,仅有路径等于「盲批」
+            if (StringUtils.isNotBlank(planContent)) {
+                payload.put("planContent", planContent);
+            }
+        }
         AiSseSupport.send(emitter, payload);
         AiSseSupport.complete(emitter);
     }
 
+    /**
+     * 从本轮工具调用中提取最近一次 {@code plan_write} 的正文。
+     *
+     * <p>暂停发生在 {@code plan_exit},此时不能再可靠地读计划文件;而 {@code plan_write}
+     * 的入参里就是完整计划正文,故在此留存(对齐上游 1.1.2 同名逻辑)。</p>
+     *
+     * @param state 本轮累积状态
+     * @return 计划正文;未调用 plan_write 或解析失败时为 {@code null}
+     */
+    private String extractPlanContent(AiStreamState state) {
+        String content = null;
+        long latest = -1L;
+        for (Map.Entry<String, AiToolCallAcc> entry : state.tools.entrySet()) {
+            AiToolCallAcc acc = entry.getValue();
+            if (!PlanModeTools.PLAN_WRITE.equals(acc.toolName) || acc.input.length() == 0
+                || acc.startNanos < latest) {
+                continue;
+            }
+            try {
+                Map<String, Object> input = JsonUtils.parseMap(acc.input.toString());
+                Object value = input == null ? null : input.get("content");
+                if (value != null && StringUtils.isNotBlank(value.toString())) {
+                    content = value.toString();
+                    latest = acc.startNanos;
+                }
+            } catch (Exception e) {
+                log.debug("解析 plan_write 入参失败:{}", e.getMessage());
+            }
+        }
+        return content;
+    }
+
     /**
      * 构造 tool_confirm 事件里每个工具项的载荷。
      *
@@ -752,6 +815,10 @@ public class AiTurnFinisher {
         if (route != null && !route.expertToolLogs.isEmpty()) {
             logs.addAll(route.expertToolLogs);
         }
+        // 计划写守卫在 PLAN 阶段拦截的变更类工具调用(状态 DENIED):随本轮明细一并落库可审计
+        if (route != null && !route.planBlockedToolLogs.isEmpty()) {
+            logs.addAll(route.planBlockedToolLogs);
+        }
         for (AiToolCallLog log : logs) {
             log.setToolOutput(safetyGuard.mask(log.getToolOutput(), SafetyScene.TOOL_RESULT));
         }

+ 86 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/PlanFileResetMiddleware.java

@@ -0,0 +1,86 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import io.agentscope.core.agent.Agent;
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.core.event.AgentEvent;
+import io.agentscope.core.middleware.ActingInput;
+import io.agentscope.core.middleware.MiddlewareBase;
+import io.agentscope.harness.agent.HarnessAgent;
+import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
+import io.agentscope.harness.agent.tool.PlanModeTools;
+import io.agentscope.harness.agent.workspace.WorkspaceManager;
+import lombok.extern.slf4j.Slf4j;
+import reactor.core.publisher.Flux;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.function.Function;
+
+/**
+ * 计划文件清理中间件:在模型调用 {@code plan_enter} 进入 PLAN 前删除本会话遗留的 {@code PLAN.md}。
+ *
+ * <p>计划文件按会话分桶({@code plans/<sessionId>}),但同一会话可能多次进入 PLAN;
+ * 框架的 {@code plan_enter} 只在计划文件未指定时设置默认路径,**不会清空旧内容**,
+ * 导致上一轮的计划被本轮的 {@code plan_write} 之前的只读调研读到。中间件在 {@code plan_enter}
+ * 执行前删除该文件,保证每轮规划从空白开始(对齐上游 1.1.2)。</p>
+ *
+ * <p>只在本装配启用计划模式时注册(见 {@link AgentAssembler#applyPlanMode}),
+ * 因此不会影响未开启计划模式的智能体。</p>
+ *
+ * @author BizBuddy
+ */
+@Slf4j
+public class PlanFileResetMiddleware implements MiddlewareBase {
+
+    /**
+     * 计划文件相对工作区路径(与框架 PlanModeManager 的默认命名一致)
+     */
+    private static final String PLAN_FILE = "/PLAN.md";
+
+    private final String planDirectory;
+
+    /**
+     * @param planDirectory 计划文件目录(工作区相对路径,形如 {@code plans/<sessionId>})
+     */
+    public PlanFileResetMiddleware(String planDirectory) {
+        this.planDirectory = planDirectory;
+    }
+
+    @Override
+    public Flux<AgentEvent> onActing(Agent agent, RuntimeContext ctx, ActingInput input,
+                                     Function<ActingInput, Flux<AgentEvent>> next) {
+        if (input.toolCalls() != null
+            && input.toolCalls().stream().anyMatch(call -> PlanModeTools.PLAN_ENTER.equals(call.getName()))) {
+            reset(agent, ctx);
+        }
+        return next.apply(input);
+    }
+
+    /**
+     * 删除当前会话的计划文件;失败只告警,不阻断规划(最坏情况是模型读到旧计划)。
+     *
+     * @param agent 智能体实例
+     * @param ctx   运行期上下文
+     */
+    private void reset(Agent agent, RuntimeContext ctx) {
+        if (!(agent instanceof HarnessAgent harness)) {
+            return;
+        }
+        String relative = planDirectory + PLAN_FILE;
+        try {
+            WorkspaceManager workspace = harness.getWorkspaceManager();
+            AbstractFilesystem filesystem = workspace.getFilesystem();
+            if (filesystem != null) {
+                filesystem.delete(ctx, relative);
+                return;
+            }
+            Path path = workspace.getWorkspace().resolve(relative).normalize();
+            if (path.startsWith(workspace.getWorkspace())) {
+                Files.deleteIfExists(path);
+            }
+        } catch (Exception e) {
+            log.warn("进入 PLAN 前清理计划文件失败:path={}, err={}", relative, e.getMessage());
+        }
+    }
+
+}

+ 201 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/PlanWriteGuardMiddleware.java

@@ -0,0 +1,201 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import io.agentscope.core.ReActAgent;
+import io.agentscope.core.agent.Agent;
+import io.agentscope.core.agent.RuntimeContext;
+import io.agentscope.core.event.AgentEvent;
+import io.agentscope.core.event.ToolResultEndEvent;
+import io.agentscope.core.event.ToolResultStartEvent;
+import io.agentscope.core.event.ToolResultTextDeltaEvent;
+import io.agentscope.core.message.Msg;
+import io.agentscope.core.message.ToolResultBlock;
+import io.agentscope.core.message.ToolResultState;
+import io.agentscope.core.message.ToolUseBlock;
+import io.agentscope.core.middleware.ActingInput;
+import io.agentscope.core.middleware.MiddlewareBase;
+import io.agentscope.core.state.AgentState;
+import io.agentscope.core.tool.AgentTool;
+import io.agentscope.core.tool.ToolResultMessageBuilder;
+import io.agentscope.core.tool.Toolkit;
+import io.agentscope.harness.agent.tool.PlanModeTools;
+import com.zsjz.ai.module.ai.domain.AiToolCallLog;
+import com.zsjz.ai.common.compat.JsonUtils;
+import lombok.extern.slf4j.Slf4j;
+import reactor.core.publisher.Flux;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Function;
+
+/**
+ * 计划模式写操作守卫:PLAN 生效期间兜底拦截变更类工具(对齐上游 1.1.2)。
+ *
+ * <p>框架的 {@code PlanModeMiddleware} 在 PLAN 阶段只放行只读工具,但存在两条绕过路径:
+ * ① 同一批工具调用里「plan_enter + execute」一起下发时,plan_enter 尚未执行、计划状态未激活,
+ * 写工具会在本轮直接放行;② 子智能体不继承计划状态(本项目虽已移除子智能体,仍保留黑名单防框架回归)。
+ * 本中间件在框架过滤之后再做一层兜底:PLAN 生效时,只有计划工具、任务清单工具与
+ * {@code isReadOnly=true} 的工具能执行,其余一律返回 {@code DENIED},并给出可执行的中文指引,
+ * 避免模型把「被拒」当成工具故障反复重试。</p>
+ *
+ * <p>只在装配启用计划模式时注册(见 {@link AgentAssembler#applyPlanMode}),计划未激活时零开销放行。
+ * 被拦截的调用记入 {@link AiRouteContext#planBlockedToolLogs},随本轮工具审计一并落库。</p>
+ *
+ * @author BizBuddy
+ */
+@Slf4j
+public class PlanWriteGuardMiddleware implements MiddlewareBase {
+
+    /**
+     * 拒绝文案:告诉模型当前边界与下一步动作,避免其把「被拒」理解为工具故障后反复重试
+     */
+    private static final String DENY_MESSAGE = "已阻止:当前处于 PLAN(只读)阶段,不能执行变更类操作。"
+        + "请改用只读工具继续调研(read_file / list_files / grep_files / glob_files 等),"
+        + "把方案用 plan_write 记录到计划文件;方案完成后调用 plan_exit 请求用户批准,"
+        + "批准后才会进入执行阶段。不要重复调用被拒绝的工具。";
+
+    /**
+     * PLAN 阶段始终放行的工具:计划工具与任务清单工具(与框架口径一致)
+     */
+    private static final Set<String> ALWAYS_ALLOWED = Set.of(
+        PlanModeTools.PLAN_ENTER,
+        PlanModeTools.PLAN_WRITE,
+        PlanModeTools.PLAN_EXIT,
+        "todo_write",
+        "todo_read",
+        "task_output",
+        "task_list");
+
+    /**
+     * PLAN 阶段无条件拒绝的工具:即使被误标为只读,也不能在规划阶段执行。
+     * 覆盖命令执行、文件变更与子智能体(子智能体不继承计划状态,可绕过父级只读约束)。
+     */
+    private static final Set<String> NEVER_IN_PLAN = Set.of(
+        "execute",
+        "shell",
+        "bash",
+        "write_file",
+        "edit_file",
+        "append_file",
+        "delete_file",
+        "move_file",
+        "copy_file",
+        "create_directory",
+        "agent_spawn",
+        "agent_send");
+
+    @Override
+    public Flux<AgentEvent> onActing(Agent agent, RuntimeContext ctx, ActingInput input,
+                                     Function<ActingInput, Flux<AgentEvent>> next) {
+        if (input.toolCalls() == null || input.toolCalls().isEmpty()) {
+            return next.apply(input);
+        }
+        boolean enteringNow = input.toolCalls().stream()
+            .anyMatch(call -> PlanModeTools.PLAN_ENTER.equals(call.getName()));
+        AgentState state;
+        boolean planActive;
+        try {
+            state = RuntimeContext.resolveAgentState(ctx, agent);
+            // 计划激活标记落在 AgentState:plan_enter 写入、plan_exit 清除
+            planActive = state != null && state.getPlanModeContext() != null
+                && state.getPlanModeContext().isPlanActive();
+        } catch (Exception e) {
+            log.warn("计划写守卫读取计划状态失败,按未激活放行:err={}", e.getMessage());
+            return next.apply(input);
+        }
+        // 同一批调用里包含 plan_enter 时,其他调用必须在本次就按 PLAN 处理:
+        // 此时 plan_enter 尚未执行、状态尚未激活,否则「plan_enter + execute」同批下发即可绕过只读约束
+        if (!enteringNow && !planActive) {
+            return next.apply(input);
+        }
+        Toolkit toolkit = agent instanceof ReActAgent react ? react.getToolkit() : null;
+        List<ToolUseBlock> allowed = new ArrayList<>();
+        List<ToolUseBlock> blocked = new ArrayList<>();
+        for (ToolUseBlock call : input.toolCalls()) {
+            if (isPermitted(toolkit, call.getName())) {
+                allowed.add(call);
+            } else {
+                blocked.add(call);
+            }
+        }
+        if (blocked.isEmpty()) {
+            return next.apply(input);
+        }
+        log.info("计划写守卫拦截:tools={}", blocked.stream().map(ToolUseBlock::getName).toList());
+        recordBlocked(ctx, blocked);
+        Flux<AgentEvent> denied = Flux.defer(() -> Flux.fromIterable(deniedEvents(blocked, state)));
+        return allowed.isEmpty() ? denied : denied.concatWith(next.apply(new ActingInput(allowed)));
+    }
+
+    /**
+     * 判定单个工具在 PLAN 阶段是否可执行。
+     *
+     * <p>包级可见:单元测试直接校验分类口径(计划工具放行、变更与子智能体工具拒绝、未知工具 fail-closed)。</p>
+     *
+     * @param toolkit 工具集(只读标记来源)
+     * @param name    工具编码
+     * @return true 表示放行
+     */
+    boolean isPermitted(Toolkit toolkit, String name) {
+        if (name == null) {
+            return false;
+        }
+        if (ALWAYS_ALLOWED.contains(name)) {
+            return true;
+        }
+        if (NEVER_IN_PLAN.contains(name)) {
+            return false;
+        }
+        AgentTool tool = toolkit == null ? null : toolkit.getTool(name);
+        return tool != null && tool.isReadOnly();
+    }
+
+    /**
+     * 把被拦截的调用记入编排上下文,收尾时并入工具审计(被拦截的调用不会产生正常工具事件)。
+     *
+     * @param ctx     运行期上下文(聊天与编排链路均挂有 {@link AiRouteContext})
+     * @param blocked 被拦截的工具调用
+     */
+    private void recordBlocked(RuntimeContext ctx, List<ToolUseBlock> blocked) {
+        AiRouteContext route = ctx == null ? null : ctx.get(AiRouteContext.class);
+        if (route == null) {
+            log.warn("计划写守卫:运行期上下文缺少编排上下文,被拦截调用未记入审计:tools={}",
+                blocked.stream().map(ToolUseBlock::getName).toList());
+            return;
+        }
+        for (ToolUseBlock call : blocked) {
+            AiToolCallLog toolLog = new AiToolCallLog();
+            toolLog.setSessionId(route.sessionId);
+            toolLog.setToolCallId(call.getId());
+            toolLog.setToolName(call.getName());
+            toolLog.setToolInput(call.getInput() == null ? null : JsonUtils.toJsonString(call.getInput()));
+            toolLog.setState(ToolResultState.DENIED.name());
+            toolLog.setDurationMs(0L);
+            toolLog.setRemark("PLAN 阶段只读拦截");
+            route.planBlockedToolLogs.add(toolLog);
+        }
+    }
+
+    /**
+     * 构造拒绝事件:与框架同口径,把工具结果写回对话上下文,模型才能看到「为什么被拒」。
+     *
+     * @param blocked 被拦截的工具调用
+     * @param state   智能体状态
+     * @return 事件列表
+     */
+    private List<AgentEvent> deniedEvents(List<ToolUseBlock> blocked, AgentState state) {
+        List<AgentEvent> events = new ArrayList<>();
+        String replyId = state.getReplyId();
+        for (ToolUseBlock call : blocked) {
+            ToolResultBlock result = ToolResultBlock.text(DENY_MESSAGE)
+                .withIdAndName(call.getId(), call.getName())
+                .withState(ToolResultState.DENIED);
+            Msg message = ToolResultMessageBuilder.buildToolResultMsg(result, call, replyId);
+            state.contextMutable().add(message);
+            events.add(new ToolResultStartEvent(replyId, call.getId(), call.getName()));
+            events.add(new ToolResultTextDeltaEvent(replyId, call.getId(), call.getName(), DENY_MESSAGE));
+            events.add(new ToolResultEndEvent(replyId, call.getId(), call.getName(), ToolResultState.DENIED));
+        }
+        return events;
+    }
+}

+ 4 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/ToolLabelResolver.java

@@ -48,6 +48,9 @@ public class ToolLabelResolver {
         Map.entry("plan_write", "写入计划"),
         Map.entry("plan_exit", "请求批准计划"),
         Map.entry("todo_write", "更新任务清单"),
+        Map.entry("todo_read", "查看任务清单"),
+        Map.entry("task_output", "查看任务输出"),
+        Map.entry("task_list", "查看任务列表"),
         Map.entry("route_decision", "路由决策"),
         Map.entry("submit_expert_result", "提交专家结论"),
         // 框架内置文件 / 命令 / 联网工具(本地工作区模式)
@@ -69,6 +72,7 @@ public class ToolLabelResolver {
         Map.entry("plan_write", "把计划写入 plans/PLAN.md"),
         Map.entry("plan_exit", "请求用户批准计划后退出计划模式"),
         Map.entry("todo_write", "更新本次任务的任务清单"),
+        Map.entry("todo_read", "读取当前任务清单内容"),
         Map.entry("read_file", "读取案件工作区中的文件"),
         Map.entry("write_file", "在案件工作区中写入文件"),
         Map.entry("edit_file", "修改案件工作区中的文件"),

+ 15 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiChatPendingVo.java

@@ -43,6 +43,21 @@ public class AiChatPendingVo implements Serializable {
      */
     private List<ToolCall> toolCalls;
 
+    /**
+     * 计划文件工作区相对路径(计划审批暂停时非空,如 {@code plans/123/PLAN.md})
+     */
+    private String planPath;
+
+    /**
+     * 最近一次 plan_write 的计划正文全文(确认卡直接展示,防「盲批」)
+     */
+    private String planContent;
+
+    /**
+     * 计划驳回次数(同一编排内累计,达到上限后本轮终止)
+     */
+    private Integer planRejectCount;
+
     /**
      * 待确认的工具调用。
      */

+ 43 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSessionServiceImpl.java

@@ -9,6 +9,7 @@ import io.agentscope.core.state.AgentStateStore;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import com.zsjz.ai.module.ai.config.AiProperties;
+import com.zsjz.ai.module.ai.core.agent.AgentAssembler;
 import com.zsjz.ai.module.ai.core.agent.AiExpertDirectory;
 import com.zsjz.ai.module.ai.core.chat.AiAttachmentReclaimer;
 import com.zsjz.ai.module.ai.domain.AiAgent;
@@ -51,9 +52,14 @@ import com.zsjz.ai.common.compat.UserService;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -85,7 +91,8 @@ public class AiSessionServiceImpl implements IAiSessionService {
     private static final Set<String> BUILTIN_READ_ONLY_TOOLS = Set.of(
         "route_decision", "submit_expert_result",
         "load_skill_through_path", "read_skill",
-        "plan_enter", "plan_write", "plan_exit", "todo_write");
+        "plan_enter", "plan_write", "plan_exit", "todo_write", "todo_read",
+        "task_output", "task_list");
 
     /**
      * 默认会话标题模板
@@ -1278,6 +1285,8 @@ public class AiSessionServiceImpl implements IAiSessionService {
             list.forEach(this::clearSessionState);
             // 仅清理 workbench 会话的独立产物目录;chat 会话共享用户工作区,不能动
             list.forEach(this::deleteWorkbenchArtifacts);
+            // 计划文件按会话分桶后可精确定位:回收案件会话在共享工作区留下的 plans/<sessionId>
+            list.forEach(this::deleteCaseSessionPlanDir);
         }
         return flag;
     }
@@ -1427,6 +1436,39 @@ public class AiSessionServiceImpl implements IAiSessionService {
         }
     }
 
+    /**
+     * 清理案件会话在共享智能体工作区留下的计划文件分桶目录:{@code <用户工作区>/plans/<sessionId>}
+     * (对齐上游 1.1.2 AiPlanFileReclaimer)。
+     *
+     * <p>计划文件按会话分桶后可精确定位;只删除目录名等于本会话主键的那一层,不影响同用户其他会话。
+     * 工作台会话的 plans/ 在 {@link #deleteWorkbenchArtifacts} 整目录删除时已覆盖,此处跳过。
+     * 文件系统删除不可回滚,失败只告警不阻断会话删除。</p>
+     */
+    private void deleteCaseSessionPlanDir(AiSession session) {
+        if (AiSession.SOURCE_WORKBENCH.equals(session.getSource())
+            || session.getCaseId() == null || session.getAgentId() == null || session.getUserId() == null) {
+            return;
+        }
+        try {
+            Path plansRoot = storageLayout.caseAgentUserDir(session.getCaseId(), session.getAgentId(),
+                session.getUserId()).resolve(AgentAssembler.PLAN_FILE_DIR_PREFIX).normalize();
+            Path target = plansRoot.resolve(String.valueOf(session.getId())).normalize();
+            // 防御性校验:只删 plans/<本会话> 这一层,绝不越出 plans 根目录
+            if (!target.startsWith(plansRoot) || !Files.isDirectory(target)) {
+                return;
+            }
+            try (Stream<Path> walk = Files.walk(target)) {
+                for (Path path : walk.sorted(Comparator.reverseOrder()).toList()) {
+                    Files.deleteIfExists(path);
+                }
+            }
+            log.info("已回收案件会话计划文件目录:sessionId={}, dir={}", session.getId(), target);
+        } catch (Exception e) {
+            // 文件清理失败不阻断会话删除;残留目录可由运维后续清理
+            log.warn("清理案件会话计划目录失败,sessionId={}:{}", session.getId(), e.getMessage());
+        }
+    }
+
     /**
      * 格式化导出用时间。
      *

+ 6 - 6
ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/AgentRegistryCaseIsolationTest.java

@@ -91,9 +91,9 @@ class AgentRegistryCaseIsolationTest {
         when(mcpClientService.resolveForAssembly(any())).thenReturn(McpClientAssembly.empty());
         when(fingerprintCalculator.modelSignature(any())).thenReturn("model");
         when(fingerprintCalculator.buildFingerprint(any(), any(), any(), any(), any(), any(), any(), any(),
-            any(), anyBoolean())).thenReturn("fp");
+            any(), anyBoolean(), any())).thenReturn("fp");
         when(assembler.assemble(any(), any(), any(), any(), any(), any(), any(), any(), any(),
-            anyBoolean(), anyBoolean(), any(), any(), any()))
+            anyBoolean(), anyBoolean(), any(), any(), any(), any()))
             .thenAnswer(invocation -> {
                 HarnessAgent agent = mock(HarnessAgent.class);
                 assembledAgents.add(agent);
@@ -126,12 +126,12 @@ class AgentRegistryCaseIsolationTest {
         registry.get(definition, AiSessionResourceSet.empty(), 1L);
         registry.get(definition, AiSessionResourceSet.empty(), 2L);
         verify(assembler, times(2)).assemble(any(), any(), any(), any(), any(), any(), any(), any(),
-            any(), anyBoolean(), anyBoolean(), any(), any(), any());
+            any(), anyBoolean(), anyBoolean(), any(), any(), any(), any());
 
         // 同案件复用实例,不重复装配
         registry.get(definition, AiSessionResourceSet.empty(), 1L);
         verify(assembler, times(2)).assemble(any(), any(), any(), any(), any(), any(), any(), any(),
-            any(), anyBoolean(), anyBoolean(), any(), any(), any());
+            any(), anyBoolean(), anyBoolean(), any(), any(), any(), any());
     }
 
     @Test
@@ -149,11 +149,11 @@ class AgentRegistryCaseIsolationTest {
         // 案件二仍命中缓存
         registry.get(definition, AiSessionResourceSet.empty(), 2L);
         verify(assembler, times(2)).assemble(any(), any(), any(), any(), any(), any(), any(), any(),
-            any(), anyBoolean(), anyBoolean(), any(), any(), any());
+            any(), anyBoolean(), anyBoolean(), any(), any(), any(), any());
         // 案件一重新装配
         registry.get(definition, AiSessionResourceSet.empty(), 1L);
         verify(assembler, times(3)).assemble(any(), any(), any(), any(), any(), any(), any(), any(),
-            any(), anyBoolean(), anyBoolean(), any(), any(), any());
+            any(), anyBoolean(), anyBoolean(), any(), any(), any(), any());
     }
 
     @Test

+ 93 - 0
ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/AiConfirmPendingStorePlanFieldsTest.java

@@ -0,0 +1,93 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import cn.hutool.extra.spring.SpringUtil;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.zsjz.ai.common.compat.JsonUtils;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+
+/**
+ * 待确认记录计划字段单元测试(对齐上游 1.1.2)。
+ *
+ * <p>覆盖两点:新记录的 plan 字段经 Redis JSON 往返不丢;历史记录(无 plan 字段)反序列化后
+ * plan 字段为 {@code null},恢复段按「非计划暂停」容错处理。</p>
+ *
+ * @author BizBuddy
+ */
+@DisplayName("待确认记录计划字段")
+class AiConfirmPendingStorePlanFieldsTest {
+
+    private static MockedStatic<SpringUtil> springUtil;
+
+    @BeforeAll
+    static void init() {
+        // compat 静态工具在类初始化时经 SpringUtil 取 Bean:先挂静态 mock 再触发加载
+        springUtil = mockStatic(SpringUtil.class);
+        springUtil.when(() -> SpringUtil.getBean(ObjectMapper.class)).thenReturn(new ObjectMapper());
+        JsonUtils.getJsonMapper();
+    }
+
+    @AfterAll
+    static void close() {
+        springUtil.close();
+    }
+
+    @Test
+    @DisplayName("计划字段经 JSON 往返保持")
+    void roundTripsPlanFields() {
+        AiConfirmPendingStore.PendingConfirm pending = new AiConfirmPendingStore.PendingConfirm(
+            1L, 2L, 3L, 4L, "reply-1",
+            List.of(new AiConfirmPendingStore.PendingToolCall("call-1", "plan_exit", null, "")),
+            List.of(new AiConfirmPendingStore.PendingDecision("call-1", false, false, "再改改")),
+            "2026-11-29T10:00:00", Boolean.TRUE, "plans/1/PLAN.md", "# 研判方案",
+            2, Boolean.FALSE, null);
+
+        String json = JsonUtils.toJsonString(pending);
+        AiConfirmPendingStore.PendingConfirm restored = JsonUtils.parseObject(json, AiConfirmPendingStore.PendingConfirm.class);
+
+        assertEquals(Boolean.TRUE, restored.planEnabled());
+        assertEquals("plans/1/PLAN.md", restored.planPath());
+        assertEquals("# 研判方案", restored.planContent());
+        assertEquals(2, restored.planRejectCount());
+        assertEquals(Boolean.FALSE, restored.planApproved());
+    }
+
+    @Test
+    @DisplayName("历史记录缺 plan 字段时反序列化为 null")
+    void legacyRecordDeserializesWithNullPlanFields() {
+        String legacy = "{\"sessionId\":1,\"messageId\":2,\"agentId\":3,\"userId\":4,\"replyId\":\"reply-1\","
+            + "\"toolCalls\":[{\"toolCallId\":\"call-1\",\"toolName\":\"execute\",\"input\":{},\"content\":\"\"}],"
+            + "\"decisions\":[],\"createdAt\":\"2026-11-01T10:00:00\",\"expertResume\":null}";
+
+        AiConfirmPendingStore.PendingConfirm restored = JsonUtils.parseObject(legacy, AiConfirmPendingStore.PendingConfirm.class);
+
+        assertNull(restored.planEnabled());
+        assertNull(restored.planPath());
+        assertNull(restored.planContent());
+        assertNull(restored.planRejectCount());
+        assertNull(restored.planApproved());
+        assertEquals("execute", restored.toolCalls().get(0).toolName());
+    }
+
+    @Test
+    @DisplayName("非计划暂停的恢复段判定:plan 字段为 null 即非计划暂停")
+    void nullPlanFieldsMeansNotPlanPause() {
+        AiConfirmPendingStore.PendingConfirm pending = new AiConfirmPendingStore.PendingConfirm(
+            1L, 2L, 3L, 4L, "reply-1", List.of(), List.of(), "t",
+            null, null, null, null, null, null);
+        assertNull(pending.planEnabled());
+        // 恢复段的计划上限判定:planRejectCount 为 null 时不触发(与 AiChatFacade 口径一致)
+        boolean overLimit = pending.planRejectCount() != null && pending.planRejectCount() >= 3;
+        org.junit.jupiter.api.Assertions.assertFalse(overLimit);
+    }
+}

+ 74 - 0
ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/PlanModeAssemblySignatureTest.java

@@ -0,0 +1,74 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import com.zsjz.ai.module.ai.mapper.AiModelConfigMapper;
+import com.zsjz.ai.module.ai.domain.AiExpertAgent;
+import com.zsjz.ai.module.ai.domain.AiTool;
+import com.zsjz.ai.module.ai.domain.bo.AiCompactionConfigBo;
+import com.zsjz.ai.module.ai.domain.bo.AiMemoryConfigBo;
+import com.zsjz.ai.module.ai.domain.dto.McpClientAssembly;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.mockito.Mockito.mock;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 计划模式装配签名单元测试:指纹与缓存键按「计划开关 × 会话」区分(对齐上游 1.1.2)。
+ *
+ * <p>计划文件目录按会话分桶(plans/&lt;sessionId&gt;),故 plan on 的指纹必须含会话主键,
+ * 不同会话不得复用装配实例;plan off 不含会话段,保持既有缓存命中行为。</p>
+ *
+ * @author BizBuddy
+ */
+@DisplayName("计划模式装配签名")
+class PlanModeAssemblySignatureTest {
+
+    private final AgentFingerprintCalculator calculator =
+        new AgentFingerprintCalculator(mock(AiModelConfigMapper.class));
+
+    @Test
+    @DisplayName("plan on 指纹含会话主键;plan off 不含")
+    void fingerprintContainsSessionOnlyWhenPlanOn() {
+        AiExpertAgent definition = new AiExpertAgent();
+        definition.setId(1L);
+        definition.setAgentCode("entry");
+        definition.setStatus("0");
+
+        String on = calculator.buildFingerprint(definition, List.<AiTool>of(), List.of(),
+            "model-sig", new AiCompactionConfigBo(), new AiMemoryConfigBo(),
+            List.of(), McpClientAssembly.empty(), "", true, 123L);
+        assertTrue(on.contains("|plan=true|session=123"), "plan on 指纹应含会话主键:" + on);
+
+        String off = calculator.buildFingerprint(definition, List.<AiTool>of(), List.of(),
+            "model-sig", new AiCompactionConfigBo(), new AiMemoryConfigBo(),
+            List.of(), McpClientAssembly.empty(), "", false, null);
+        assertFalse(off.contains("|session="), "plan off 指纹不应含会话段:" + off);
+    }
+
+    @Test
+    @DisplayName("不同会话的 plan on 指纹不同")
+    void fingerprintDiffersAcrossSessions() {
+        AiExpertAgent definition = new AiExpertAgent();
+        definition.setId(1L);
+        definition.setAgentCode("entry");
+        definition.setStatus("0");
+
+        String first = calculator.buildFingerprint(definition, List.<AiTool>of(), List.of(),
+            "model-sig", new AiCompactionConfigBo(), new AiMemoryConfigBo(),
+            List.of(), McpClientAssembly.empty(), "", true, 1L);
+        String second = calculator.buildFingerprint(definition, List.<AiTool>of(), List.of(),
+            "model-sig", new AiCompactionConfigBo(), new AiMemoryConfigBo(),
+            List.of(), McpClientAssembly.empty(), "", true, 2L);
+        assertFalse(first.equals(second), "不同会话的 plan on 指纹必须不同,否则会复用指向错误计划目录的实例");
+    }
+
+    @Test
+    @DisplayName("计划文件目录按会话分桶")
+    void planDirectoryIsSessionBucketed() {
+        assertTrue(AgentAssembler.PLAN_FILE_DIR_PREFIX.equals("plans"));
+    }
+}

+ 84 - 0
ai-server/src/test/java/com/zsjz/ai/module/ai/core/agent/PlanWriteGuardMiddlewareTest.java

@@ -0,0 +1,84 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import io.agentscope.core.tool.AgentTool;
+import io.agentscope.core.tool.Toolkit;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * {@link PlanWriteGuardMiddleware} 工具分类口径单元测试(对齐上游 1.1.2)。
+ *
+ * <p>覆盖三类边界:计划工具始终放行;变更类与子智能体工具无条件拒绝;
+ * 其余工具按 {@code isReadOnly} 判定,未知工具 fail-closed。</p>
+ *
+ * @author BizBuddy
+ */
+@DisplayName("计划写守卫")
+class PlanWriteGuardMiddlewareTest {
+
+    private final PlanWriteGuardMiddleware middleware = new PlanWriteGuardMiddleware();
+
+    @Test
+    @DisplayName("计划与任务清单工具在 PLAN 阶段放行")
+    void permitsPlanTools() {
+        assertTrue(middleware.isPermitted(null, "plan_enter"));
+        assertTrue(middleware.isPermitted(null, "plan_write"));
+        assertTrue(middleware.isPermitted(null, "plan_exit"));
+        assertTrue(middleware.isPermitted(null, "todo_write"));
+        assertTrue(middleware.isPermitted(null, "todo_read"));
+        assertTrue(middleware.isPermitted(null, "task_output"));
+        assertTrue(middleware.isPermitted(null, "task_list"));
+    }
+
+    @Test
+    @DisplayName("命令执行与文件变更工具无条件拒绝")
+    void deniesWriteTools() {
+        assertFalse(middleware.isPermitted(toolkitWith("execute", true), "execute"));
+        assertFalse(middleware.isPermitted(null, "shell"));
+        assertFalse(middleware.isPermitted(null, "bash"));
+        assertFalse(middleware.isPermitted(toolkitWith("write_file", true), "write_file"));
+        assertFalse(middleware.isPermitted(null, "edit_file"));
+        assertFalse(middleware.isPermitted(null, "append_file"));
+        assertFalse(middleware.isPermitted(null, "delete_file"));
+        assertFalse(middleware.isPermitted(null, "move_file"));
+        assertFalse(middleware.isPermitted(null, "copy_file"));
+        assertFalse(middleware.isPermitted(null, "create_directory"));
+    }
+
+    @Test
+    @DisplayName("子智能体工具在 PLAN 阶段拒绝(子智能体不继承计划状态)")
+    void deniesSubagentTools() {
+        assertFalse(middleware.isPermitted(toolkitWith("agent_spawn", true), "agent_spawn"));
+        assertFalse(middleware.isPermitted(toolkitWith("agent_send", true), "agent_send"));
+    }
+
+    @Test
+    @DisplayName("只读工具放行,写工具与未知工具拒绝")
+    void decidesByReadOnlyFlag() {
+        assertTrue(middleware.isPermitted(toolkitWith("read_file", true), "read_file"));
+        assertFalse(middleware.isPermitted(toolkitWith("dangerous_tool", false), "dangerous_tool"));
+        // 工具集里查不到(未注册 / 空名称)按 fail-closed 拒绝
+        assertFalse(middleware.isPermitted(null, "unknown_tool"));
+        assertFalse(middleware.isPermitted(null, null));
+    }
+
+    /**
+     * 构造只含一个工具的工具集。
+     *
+     * @param name     工具编码
+     * @param readOnly 是否只读
+     * @return 工具集
+     */
+    private Toolkit toolkitWith(String name, boolean readOnly) {
+        Toolkit toolkit = mock(Toolkit.class);
+        AgentTool tool = mock(AgentTool.class);
+        when(tool.isReadOnly()).thenReturn(readOnly);
+        when(toolkit.getTool(name)).thenReturn(tool);
+        return toolkit;
+    }
+}