|
|
@@ -0,0 +1,168 @@
|
|
|
+package com.zsjz.ai.module.agent.memory;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.nio.file.Files;
|
|
|
+import java.nio.file.Path;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.regex.Matcher;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+import java.util.stream.Stream;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 旧记忆路径迁移:把 MEMORY.md / memory/*.md 里指向「历史会话 outputs 目录」的绝对路径
|
|
|
+ * 改写为会话工作区相对路径 {@code outputs/...}。
|
|
|
+ *
|
|
|
+ * <h3>为什么需要</h3>
|
|
|
+ * 工作区按会话隔离后,{@code {工作区}/{sessionId}} 才是模型当前可见的目录。但共享记忆
|
|
|
+ * (用户级 {@code MEMORY.md})里留存的是旧布局的绝对路径,例如:
|
|
|
+ * <pre>
|
|
|
+ * ...\ai\agents\2117980519456473089\1\outputs
|
|
|
+ * </pre>
|
|
|
+ * 模型照抄后会把交付物写到会话目录之外,回合末扫描器认领不到,产物栏就看不到文件。
|
|
|
+ *
|
|
|
+ * <h3>迁移口径(保守)</h3>
|
|
|
+ * <ul>
|
|
|
+ * <li>只改写<b>以当前 agent 工作区为前缀、且含 {@code /outputs} 段</b>的绝对路径;</li>
|
|
|
+ * <li>技能缓存、subagents 等其它工作区路径不动,避免破坏工具/技能的定位;</li>
|
|
|
+ * <li>改写结果只保留 {@code outputs/...}(相对路径,按当前会话解析);</li>
|
|
|
+ * <li>幂等:迁移后的文本不再匹配绝对路径,重复执行无副作用。</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+public final class AgentMemoryPathMigrator {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 路径 token:盘符绝对路径、POSIX 绝对路径,以及模型常用的省略前缀写法
|
|
|
+ * {@code ...\ai\agents\...}(记忆里实际出现的就是这种)。
|
|
|
+ * 遇到空白/引号/括号/常见中英文标点即结束。
|
|
|
+ */
|
|
|
+ private static final Pattern ABSOLUTE_PATH = Pattern.compile(
|
|
|
+ "(?<![\\w])((?:[A-Za-z]:|/|\\.{3}[\\\\/]|…[\\\\/])"
|
|
|
+ + "[^\\s\"'`<>|,;)\\]},。;:、)】》]+)");
|
|
|
+
|
|
|
+ private AgentMemoryPathMigrator() {
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 迁移某个用户在该 agent 工作区下的记忆文件。
|
|
|
+ *
|
|
|
+ * @param agentWorkspace 未命名工作区根({@code cases/{caseId}/ai/agents/{agentRowId}})
|
|
|
+ * @param userId 登录用户 ID(共享记忆目录 = {@code agentWorkspace/{userId}})
|
|
|
+ * @return 改写的文件数
|
|
|
+ */
|
|
|
+ public static int migrate(Path agentWorkspace, String userId) {
|
|
|
+ if (agentWorkspace == null || userId == null || userId.isBlank()) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ Path sharedUserDir = agentWorkspace.resolve(userId.trim());
|
|
|
+ if (!Files.isDirectory(sharedUserDir)) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ List<Path> files = new ArrayList<>();
|
|
|
+ Path memoryMd = sharedUserDir.resolve("MEMORY.md");
|
|
|
+ if (Files.isRegularFile(memoryMd)) {
|
|
|
+ files.add(memoryMd);
|
|
|
+ }
|
|
|
+ Path memoryDir = sharedUserDir.resolve("memory");
|
|
|
+ if (Files.isDirectory(memoryDir)) {
|
|
|
+ try (Stream<Path> stream = Files.list(memoryDir)) {
|
|
|
+ stream.filter(Files::isRegularFile)
|
|
|
+ .filter(p -> {
|
|
|
+ String name = p.getFileName().toString().toLowerCase();
|
|
|
+ return name.endsWith(".md") || name.endsWith(".txt");
|
|
|
+ })
|
|
|
+ .limit(500)
|
|
|
+ .forEach(files::add);
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.info("扫描记忆目录失败: dir={}, error={}", memoryDir, e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ String workspacePrefix = normalize(agentWorkspace.toAbsolutePath().normalize().toString());
|
|
|
+ int migrated = 0;
|
|
|
+ for (Path file : files) {
|
|
|
+ try {
|
|
|
+ String content = Files.readString(file, StandardCharsets.UTF_8);
|
|
|
+ String rewritten = rewrite(content, workspacePrefix);
|
|
|
+ if (!rewritten.equals(content)) {
|
|
|
+ Files.writeString(file, rewritten, StandardCharsets.UTF_8);
|
|
|
+ migrated++;
|
|
|
+ log.info("已迁移记忆中的历史产物路径: file={}", file);
|
|
|
+ }
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.info("迁移记忆路径失败(不影响启动): file={}, error={}", file, e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return migrated;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 把文本中位于 {@code workspacePrefix} 之下、且含 {@code /outputs} 段的绝对路径
|
|
|
+ * 改写为相对路径 {@code outputs/...};其它内容原样保留。
|
|
|
+ */
|
|
|
+ static String rewrite(String text, String workspacePrefix) {
|
|
|
+ if (text == null || text.isEmpty() || workspacePrefix == null || workspacePrefix.isEmpty()) {
|
|
|
+ return text;
|
|
|
+ }
|
|
|
+ Matcher matcher = ABSOLUTE_PATH.matcher(text);
|
|
|
+ StringBuilder out = new StringBuilder(text.length());
|
|
|
+ int last = 0;
|
|
|
+ while (matcher.find()) {
|
|
|
+ String token = matcher.group(1);
|
|
|
+ String normalized = normalize(token);
|
|
|
+ int outputsIdx = indexOfOutputs(normalized);
|
|
|
+ if (outputsIdx < 0) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ String prefixBeforeOutputs = normalized.substring(0, outputsIdx);
|
|
|
+ String lowerPrefix = prefixBeforeOutputs.toLowerCase(java.util.Locale.ROOT);
|
|
|
+ // 两条判定口径:
|
|
|
+ // 1) 完整绝对路径且以当前工作区为前缀;
|
|
|
+ // 2) 模型/旧文档常用的省略写法(...\ai\agents\...)——只要前缀里出现 agents/ 段,
|
|
|
+ // 就视为同一案件工作区下的历史产物路径(这类路径在会话外,读写都会落错位置)。
|
|
|
+ boolean underWorkspace = lowerPrefix.startsWith(workspacePrefix.toLowerCase(java.util.Locale.ROOT));
|
|
|
+ boolean agentWorkspacePath = lowerPrefix.contains("/ai/agents/")
|
|
|
+ || lowerPrefix.contains("/agents/");
|
|
|
+ if (!underWorkspace && !agentWorkspacePath) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ String suffix = normalized.substring(outputsIdx + "outputs".length());
|
|
|
+ // suffix 只能是空串或以 / 开头(确保是 outputs 目录本身,而不是 outputs2)
|
|
|
+ if (!suffix.isEmpty() && !suffix.startsWith("/")) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ out.append(text, last, matcher.start());
|
|
|
+ out.append("outputs").append(suffix);
|
|
|
+ last = matcher.end();
|
|
|
+ }
|
|
|
+ if (last == 0) {
|
|
|
+ return text;
|
|
|
+ }
|
|
|
+ return out.append(text.substring(last)).toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 找到路径中 {@code /outputs} 段的位置(返回 "outputs" 的起始下标)。
|
|
|
+ */
|
|
|
+ private static int indexOfOutputs(String normalizedPath) {
|
|
|
+ String lower = normalizedPath.toLowerCase();
|
|
|
+ int idx = lower.indexOf("/outputs");
|
|
|
+ while (idx >= 0) {
|
|
|
+ int end = idx + "/outputs".length();
|
|
|
+ // 必须是独立目录段:路径结束或紧跟分隔符
|
|
|
+ if (end == lower.length() || lower.charAt(end) == '/') {
|
|
|
+ return idx + 1;
|
|
|
+ }
|
|
|
+ idx = lower.indexOf("/outputs", idx + 1);
|
|
|
+ }
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String normalize(String path) {
|
|
|
+ return path.replace('\\', '/');
|
|
|
+ }
|
|
|
+}
|