Version: 0.9.76.dev.260505

后端:
1.阶段 6 agent / memory 服务化收口
- 新增 cmd/agent 独立进程入口,承载 agent zrpc server、agent outbox relay / consumer 和运行时依赖初始化
- 补齐 services/agent/rpc 的 Chat stream 与 conversation meta/list/timeline、schedule-preview、context-stats、schedule-state unary RPC
- 新增 gateway/client/agent 与 shared/contracts/agent,将 /api/v1/agent chat 和非 chat 门面切到 agent zrpc
- 收缩 gateway 本地 AgentService 装配,双 RPC 开关开启时不再初始化本地 agent 编排、LLM、RAG 和 memory reader fallback
- 将 backend/memory 物理迁入 services/memory,私有实现收入 internal,保留 module/model/observe 作为 memory 服务门面
- 调整 memory outbox、memory reader 和 agent 记忆渲染链路的 import 与服务边界,cmd/memory 独占 memory worker / consumer
- 关闭 gateway 侧 agent outbox worker 所有权,agent relay / consumer 由 cmd/agent 独占,gateway 仅保留 HTTP/SSE 门面与迁移期开关回退
- 更新阶段 6 文档,记录 agent / memory 当前切流点、smoke 结果,以及 backend/client 与 gateway/shared 的目录收口口径
This commit is contained in:
Losita
2026-05-05 19:31:39 +08:00
parent d7184b776b
commit 2a96f4c6f9
72 changed files with 2775 additions and 291 deletions

View File

@@ -0,0 +1,115 @@
package utils
import (
"fmt"
memorymodel "github.com/LoveLosita/smartflow/backend/services/memory/model"
)
// AggregateComparisons 把一轮 LLM 比对结果汇总为最终动作。
//
// 职责边界:
// 1. 纯确定性逻辑,不调 LLM不调外部服务
// 2. 按优先级从高到低判定duplicate > update > conflict > unrelated
// 3. 多条 update 时选 Score 最高的候选执行 UPDATE。
//
// 汇总规则:
// 1. 出现 duplicate → 最终动作 NONE新 fact 完全重复,不需要写入);
// 2. 出现 update → 最终动作 UPDATE更新 Score 最高的那条旧记忆);
// 3. 出现 conflict → 最终动作 DELETE + 后续按 ADD 处理(旧记忆过时,先删旧的再写新的);
// 4. 全部 unrelated → 最终动作 ADD没有相关旧记忆直接新增
func AggregateComparisons(
fact memorymodel.NormalizedFact,
comparisons []memorymodel.ComparisonResult,
candidates []memorymodel.CandidateSnapshot,
) *memorymodel.FinalDecision {
// 1. 无候选时直接 ADD无需走任何判断。
if len(comparisons) == 0 {
return &memorymodel.FinalDecision{
Action: memorymodel.DecisionActionAdd,
Reason: "无相关旧记忆,直接新增",
}
}
// 2. 建立 memoryID → CandidateSnapshot 映射,用于查找 Score。
snapshotMap := make(map[int64]memorymodel.CandidateSnapshot, len(candidates))
for _, c := range candidates {
snapshotMap[c.MemoryID] = c
}
hasDuplicate := false
var bestUpdate *memorymodel.ComparisonResult
bestUpdateScore := -1.0
var conflictResult *memorymodel.ComparisonResult
for i := range comparisons {
comp := &comparisons[i]
switch comp.Relation {
case memorymodel.RelationDuplicate:
// 3. 出现一条 duplicate 即可确定最终动作为 NONE。
hasDuplicate = true
case memorymodel.RelationUpdate:
// 4. 多条 update 时,选 Score 最高的那条执行 UPDATE。
snapshot, ok := snapshotMap[comp.MemoryID]
score := 0.0
if ok {
score = snapshot.Score
}
if score > bestUpdateScore {
bestUpdateScore = score
bestUpdate = comp
}
case memorymodel.RelationConflict:
// 5. 记录第一条 conflict用于后续 DELETE + ADD 处理。
if conflictResult == nil {
conflictResult = comp
}
}
}
// 6. 按优先级判定最终动作。
if hasDuplicate {
return &memorymodel.FinalDecision{
Action: memorymodel.DecisionActionNone,
Reason: "存在完全重复的旧记忆,跳过写入",
}
}
if bestUpdate != nil {
// 7. UPDATE 动作:使用 LLM 提供的合并后内容。
title := bestUpdate.UpdatedTitle
if title == "" {
title = fact.Title
}
content := bestUpdate.UpdatedContent
reason := bestUpdate.Reason
if reason == "" {
reason = "新事实是对旧记忆的修正或补充"
}
return &memorymodel.FinalDecision{
Action: memorymodel.DecisionActionUpdate,
TargetID: bestUpdate.MemoryID,
Title: title,
Content: content,
Reason: fmt.Sprintf("更新旧记忆(id=%d): %s", bestUpdate.MemoryID, reason),
}
}
if conflictResult != nil {
// 8. conflict → 先 DELETE 旧记忆,后续由上层按 ADD 写入新 fact。
return &memorymodel.FinalDecision{
Action: memorymodel.DecisionActionDelete,
TargetID: conflictResult.MemoryID,
Reason: fmt.Sprintf("旧记忆(id=%d)与新事实冲突,删除后新增: %s", conflictResult.MemoryID, conflictResult.Reason),
}
}
// 9. 全部 unrelated → 直接 ADD。
return &memorymodel.FinalDecision{
Action: memorymodel.DecisionActionAdd,
Reason: "无相关旧记忆,直接新增",
}
}

View File

@@ -0,0 +1,77 @@
package utils
import (
"encoding/json"
"strings"
"github.com/LoveLosita/smartflow/backend/model"
)
const (
// AuditOperationCreate 表示系统新建一条记忆。
AuditOperationCreate = "create"
// AuditOperationUpdate 表示决策层更新已有记忆的内容。
AuditOperationUpdate = "update"
// AuditOperationArchive 表示治理层把重复记忆归档。
AuditOperationArchive = "archive"
// AuditOperationDelete 表示对已有记忆做软删除。
AuditOperationDelete = "delete"
// AuditOperationRestore 表示把已删除/归档记忆恢复为 active。
AuditOperationRestore = "restore"
)
// BuildItemAuditLog 构造记忆变更审计日志。
//
// 职责边界:
// 1. 负责把 before/after 快照统一序列化为审计日志结构;
// 2. 不负责决定“是否应该写审计”,该决策由上层 service/worker 控制;
// 3. 不负责落库,调用方仍需显式调用 AuditRepo。
func BuildItemAuditLog(
memoryID int64,
userID int,
operation string,
operatorType string,
reason string,
before *model.MemoryItem,
after *model.MemoryItem,
) model.MemoryAuditLog {
return model.MemoryAuditLog{
MemoryID: memoryID,
UserID: userID,
Operation: strings.TrimSpace(operation),
OperatorType: NormalizeOperatorType(operatorType),
Reason: strings.TrimSpace(reason),
BeforeJSON: marshalMemoryItemSnapshot(before),
AfterJSON: marshalMemoryItemSnapshot(after),
}
}
// NormalizeOperatorType 统一规整审计操作者类型。
//
// 规则说明:
// 1. 目前只接受 user/system 两类固定值;
// 2. 空值或未知值统一回退为 user避免把脏值直接写进审计表
// 3. 若后续扩展 admin/tool 等类型,再在这里集中放开即可。
func NormalizeOperatorType(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "system":
return "system"
default:
return "user"
}
}
func marshalMemoryItemSnapshot(item *model.MemoryItem) *string {
if item == nil {
return nil
}
raw, err := json.Marshal(item)
if err != nil {
empty := "{}"
return &empty
}
value := string(raw)
return &value
}

View File

@@ -0,0 +1,49 @@
package utils
import (
"fmt"
"strings"
memorymodel "github.com/LoveLosita/smartflow/backend/services/memory/model"
)
// 合法关系类型集合,用于校验 LLM 输出的 relation 字段。
var validRelations = map[string]struct{}{
memorymodel.RelationDuplicate: {},
memorymodel.RelationUpdate: {},
memorymodel.RelationConflict: {},
memorymodel.RelationUnrelated: {},
}
// ValidateComparisonResult 校验单次比对结果的基本合法性。
//
// 职责边界:
// 1. 只校验 LLM 输出的结构合法性,不校验业务语义;
// 2. relation 必须是四种合法值之一update 时必须有 UpdatedContent
// 3. 校验失败直接返回 error调用方决定丢弃或重试。
func ValidateComparisonResult(result *memorymodel.ComparisonResult) error {
if result == nil {
return fmt.Errorf("比对结果不能为空")
}
// 1. MemoryID 必须大于 0确保能定位到旧记忆。
if result.MemoryID <= 0 {
return fmt.Errorf("比对结果 memory_id 无效: %d", result.MemoryID)
}
// 2. relation 必须是四种合法值之一,防止 LLM 输出非法值。
relation := strings.TrimSpace(strings.ToLower(result.Relation))
if _, ok := validRelations[relation]; !ok {
return fmt.Errorf("比对结果 relation 非法: %s", result.Relation)
}
// 3. relation=update 时UpdatedContent 不能为空。
// 原因update 需要合并后的完整内容,不能只写差异部分。
if relation == memorymodel.RelationUpdate {
if strings.TrimSpace(result.UpdatedContent) == "" {
return fmt.Errorf("relation=update 时 updated_content 不能为空")
}
}
return nil
}

View File

@@ -0,0 +1,104 @@
package utils
import (
"encoding/json"
"errors"
"regexp"
"strings"
)
var fencedJSONPattern = regexp.MustCompile("(?s)```(?:json)?\\s*([\\[{].*[\\]}])\\s*```")
// ExtractJSON 从模型输出中提取 JSON 文本(兼容代码块包裹)。
//
// 步骤:
// 1. 先判断整段文本是否本身就是合法 JSON
// 2. 再尝试匹配 ```json ... ``` 代码块;
// 3. 最后做一次“首个 JSON 对象/数组”扫描提取。
func ExtractJSON(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return "", errors.New("empty model output")
}
// 1. 直接 JSON 命中时,避免做额外启发式扫描。
if json.Valid([]byte(trimmed)) {
return trimmed, nil
}
// 2. 兼容 markdown 代码块包裹 JSON。
matches := fencedJSONPattern.FindStringSubmatch(trimmed)
if len(matches) > 1 {
candidate := strings.TrimSpace(matches[1])
if json.Valid([]byte(candidate)) {
return candidate, nil
}
}
// 3. 兜底扫描首个完整 JSON 片段,尽量提升容错能力。
if candidate, ok := findFirstJSONSegment(trimmed); ok {
return candidate, nil
}
return "", errors.New("json not found in model output")
}
func findFirstJSONSegment(raw string) (string, bool) {
start := -1
var open, close rune
for i, ch := range raw {
if ch == '{' {
start = i
open = '{'
close = '}'
break
}
if ch == '[' {
start = i
open = '['
close = ']'
break
}
}
if start < 0 {
return "", false
}
depth := 0
inString := false
escaped := false
for i, ch := range raw[start:] {
if inString {
if escaped {
escaped = false
continue
}
if ch == '\\' {
escaped = true
continue
}
if ch == '"' {
inString = false
}
continue
}
if ch == '"' {
inString = true
continue
}
if ch == open {
depth++
continue
}
if ch == close {
depth--
if depth == 0 {
candidate := strings.TrimSpace(raw[start : start+i+1])
if json.Valid([]byte(candidate)) {
return candidate, true
}
return "", false
}
}
}
return "", false
}

View File

@@ -0,0 +1,133 @@
package utils
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
memorymodel "github.com/LoveLosita/smartflow/backend/services/memory/model"
)
const (
maxTitleLength = 64
maxContentLength = 1000
)
// NormalizeFacts 对候选事实做标准化与过滤。
//
// 步骤:
// 1. 标准化 memory_type 与文本字段,丢弃空值和非法类型;
// 2. 对超长内容截断,避免脏数据污染后续链路;
// 3. 基于“类型+标准化内容”做去重,避免同一轮重复写入。
func NormalizeFacts(candidates []memorymodel.FactCandidate) []memorymodel.NormalizedFact {
if len(candidates) == 0 {
return nil
}
result := make([]memorymodel.NormalizedFact, 0, len(candidates))
seen := make(map[string]struct{}, len(candidates))
for _, candidate := range candidates {
memoryType := memorymodel.NormalizeMemoryType(candidate.MemoryType)
if memoryType == "" {
continue
}
content := normalizeWhitespace(candidate.Content)
if content == "" {
continue
}
content = truncateByRune(content, maxContentLength)
title := normalizeWhitespace(candidate.Title)
if title == "" {
title = truncateByRune(content, maxTitleLength)
}
title = truncateByRune(title, maxTitleLength)
confidence := clamp01(candidate.Confidence)
if confidence == 0 {
confidence = 0.6
}
importance := clamp01(candidate.Importance)
if importance == 0 {
importance = defaultImportanceByType(memoryType)
}
sensitivityLevel := clampInt(candidate.SensitivityLevel, 0, 2)
normalizedContent := strings.ToLower(content)
contentHash := HashContent(memoryType, normalizedContent)
dedupKey := fmt.Sprintf("%s:%s", memoryType, contentHash)
if _, exists := seen[dedupKey]; exists {
continue
}
seen[dedupKey] = struct{}{}
result = append(result, memorymodel.NormalizedFact{
MemoryType: memoryType,
Title: title,
Content: content,
NormalizedContent: normalizedContent,
ContentHash: contentHash,
Confidence: confidence,
Importance: importance,
SensitivityLevel: sensitivityLevel,
IsExplicit: candidate.IsExplicit,
})
}
return result
}
func normalizeWhitespace(raw string) string {
return strings.Join(strings.Fields(strings.TrimSpace(raw)), " ")
}
func truncateByRune(raw string, max int) string {
if max <= 0 {
return ""
}
runes := []rune(raw)
if len(runes) <= max {
return raw
}
return string(runes[:max])
}
func clamp01(v float64) float64 {
if v < 0 {
return 0
}
if v > 1 {
return 1
}
return v
}
func clampInt(v, minValue, maxValue int) int {
if v < minValue {
return minValue
}
if v > maxValue {
return maxValue
}
return v
}
func defaultImportanceByType(memoryType string) float64 {
switch memoryType {
case memorymodel.MemoryTypePreference:
return 0.85
case memorymodel.MemoryTypeConstraint:
return 0.95
default:
return 0.6
}
}
// HashContent 计算记忆内容的去重哈希。
// 算法sha256(memoryType + "::" + normalizedContent)
// 说明:导出此函数是为了让决策层 apply_actions 也能复用同一算法,避免哈希不一致导致去重失效。
func HashContent(memoryType, normalizedContent string) string {
sum := sha256.Sum256([]byte(memoryType + "::" + normalizedContent))
return hex.EncodeToString(sum[:])
}

View File

@@ -0,0 +1,81 @@
package utils
import (
"github.com/LoveLosita/smartflow/backend/model"
memorymodel "github.com/LoveLosita/smartflow/backend/services/memory/model"
)
// EffectiveUserSetting 返回用户记忆设置的生效值。
//
// 规则说明:
// 1. 用户未显式配置时,走系统默认值;
// 2. 默认允许普通记忆和隐式记忆,但默认关闭敏感记忆;
// 3. 返回值始终是完整对象,方便调用方直接使用,不再分支判空。
func EffectiveUserSetting(setting *model.MemoryUserSetting, userID int) model.MemoryUserSetting {
if setting == nil {
return model.MemoryUserSetting{
UserID: userID,
MemoryEnabled: true,
ImplicitMemoryEnabled: true,
SensitiveMemoryEnabled: false,
}
}
return *setting
}
// FilterFactsBySetting 按用户记忆开关过滤候选事实。
func FilterFactsBySetting(facts []memorymodel.NormalizedFact, setting model.MemoryUserSetting) []memorymodel.NormalizedFact {
if !setting.MemoryEnabled || len(facts) == 0 {
return nil
}
result := make([]memorymodel.NormalizedFact, 0, len(facts))
for _, fact := range facts {
if !setting.ImplicitMemoryEnabled && !fact.IsExplicit {
continue
}
if !setting.SensitiveMemoryEnabled && fact.SensitivityLevel > 0 {
continue
}
result = append(result, fact)
}
return result
}
// FilterItemsBySetting 按用户记忆开关过滤已入库记忆。
func FilterItemsBySetting(items []model.MemoryItem, setting model.MemoryUserSetting) []model.MemoryItem {
if !setting.MemoryEnabled || len(items) == 0 {
return nil
}
result := make([]model.MemoryItem, 0, len(items))
for _, item := range items {
if !setting.ImplicitMemoryEnabled && !item.IsExplicit {
continue
}
if !setting.SensitiveMemoryEnabled && item.SensitivityLevel > 0 {
continue
}
result = append(result, item)
}
return result
}
// FilterFactsByConfidence 按置信度阈值过滤候选事实。
//
// 说明:
// 1. minConfidence <= 0 时不做过滤,保持向后兼容;
// 2. 过滤在 FilterFactsBySetting 之后执行,是写入链路的第二道程序化门槛;
// 3. 阈值由 memory.write.minConfidence 配置控制,默认 0.5。
func FilterFactsByConfidence(facts []memorymodel.NormalizedFact, minConfidence float64) []memorymodel.NormalizedFact {
if minConfidence <= 0 || len(facts) == 0 {
return facts
}
result := make([]memorymodel.NormalizedFact, 0, len(facts))
for _, fact := range facts {
if fact.Confidence >= minConfidence {
result = append(result, fact)
}
}
return result
}