agentmemory

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package agentmemory 实现 Agent memory runtime 的持久化存储层。

本包在现有 internal/memory.Record 之上引入 canonical runtime view,增加 principal、scope、source、supersession、conflict、proposal、handoff 和 feedback。 所有 schema 变更都是 additive:只新增表和 nullable 列,不 rename/drop/narrow 现有 schema。

Index

Constants

View Source
const DefaultLocalPrincipalID = "local-owner"

DefaultLocalPrincipalID 是旧 memory rows 的默认 principal。 旧 ledger 没有 principal 概念,映射时统一归到 local owner。

Variables

This section is empty.

Functions

func DefaultLocalScope

func DefaultLocalScope(workspaceID string) agentprotocol.Scope

DefaultLocalScope 是旧 memory rows 的默认 scope。 旧 ledger 没有 scope 概念,映射时统一归到 workspace scope。

func EnsureLegacyViewed

func EnsureLegacyViewed(ctx context.Context, s *Store, records []LegacyRecord, workspaceID string) ([]agentprotocol.MemoryRecord, error)

EnsureLegacyViewed 将旧 records 的 protocol 视图映射为 list,供 read path 使用。 不静默 backfill 到 agent_memory_records 表。

func LegacyKindMap

func LegacyKindMap(oldType string) agentprotocol.MemoryKind

LegacyKindMap 将旧 Type 映射到新 MemoryKind。 未知 type 映射为 fact(向前兼容),不失败。

func LegacyStateMap

func LegacyStateMap(oldStatus string) agentprotocol.LifecycleState

LegacyStateMap 将旧 Status 映射到新 LifecycleState。

func MapLegacyRecord

func MapLegacyRecord(rec LegacyRecord, workspaceID string) agentprotocol.MemoryRecord

MapLegacyRecord 将一条旧 memory row 映射为新 protocol MemoryRecord。 不写回数据库——这只是 read mapping。 legacyID 映射到 LegacyRecordID,保持双向追溯。

func TableNames

func TableNames() []string

TableNames 返回所有 agent memory 表名(用于 migration receipt 和 observability)。

Types

type AgentConflictRow

type AgentConflictRow struct {
	ID            string    `gorm:"primaryKey;column:id" json:"id"`
	MemoryID      string    `gorm:"index;column:memory_id" json:"memory_id"`
	ConflictsWith string    `gorm:"index;column:conflicts_with" json:"conflicts_with"`
	Reason        string    `gorm:"column:reason" json:"reason,omitempty"`
	CreatedAt     time.Time `gorm:"column:created_at" json:"created_at"`
}

AgentConflictRow 记录 memory 之间的冲突关系。

func (AgentConflictRow) TableName

func (AgentConflictRow) TableName() string

type AgentFeedbackRow

type AgentFeedbackRow struct {
	FeedbackID        string    `gorm:"primaryKey;column:feedback_id" json:"feedback_id"`
	PrincipalID       string    `gorm:"index;column:principal_id" json:"principal_id"`
	ScopeKind         string    `gorm:"index;column:scope_kind" json:"scope_kind"`
	ScopeID           string    `gorm:"index;column:scope_id" json:"scope_id"`
	Kind              string    `gorm:"index;column:kind" json:"kind"`
	MemoryID          string    `gorm:"index;column:memory_id" json:"memory_id,omitempty"`
	ContextRequestRef string    `gorm:"column:context_request_ref" json:"context_request_ref,omitempty"`
	Comment           string    `gorm:"column:comment" json:"comment,omitempty"`
	CreatedAt         time.Time `gorm:"column:created_at" json:"created_at"`
}

AgentFeedbackRow 持久化 recall feedback。

func (AgentFeedbackRow) TableName

func (AgentFeedbackRow) TableName() string

type AgentHandoffRow

type AgentHandoffRow struct {
	HandoffID               string    `gorm:"primaryKey;column:handoff_id" json:"handoff_id"`
	FromPrincipal           string    `gorm:"index;column:from_principal" json:"from_principal"`
	ToPrincipal             string    `gorm:"index;column:to_principal" json:"to_principal"`
	ScopeKind               string    `gorm:"column:scope_kind" json:"scope_kind"`
	ScopeID                 string    `gorm:"column:scope_id" json:"scope_id"`
	Objective               string    `gorm:"column:objective" json:"objective"`
	CurrentState            string    `gorm:"column:current_state" json:"current_state,omitempty"`
	Decisions               string    `gorm:"column:decisions" json:"decisions,omitempty"`           // newline-separated
	CompletedWork           string    `gorm:"column:completed_work" json:"completed_work,omitempty"` // newline-separated
	Blockers                string    `gorm:"column:blockers" json:"blockers,omitempty"`
	Verification            string    `gorm:"column:verification" json:"verification,omitempty"`
	FollowUps               string    `gorm:"column:follow_ups" json:"follow_ups,omitempty"`
	RequestedNextCapability string    `gorm:"column:requested_next_capability" json:"requested_next_capability,omitempty"`
	CreatedAt               time.Time `gorm:"column:created_at" json:"created_at"`
}

AgentHandoffRow 持久化 cross-agent handoff。

func (AgentHandoffRow) TableName

func (AgentHandoffRow) TableName() string

type AgentMemoryRow

type AgentMemoryRow struct {
	ID             string     `gorm:"primaryKey;column:id" json:"id"`
	Kind           string     `gorm:"index;column:kind" json:"kind"`
	ScopeKind      string     `gorm:"index;column:scope_kind" json:"scope_kind"`
	ScopeID        string     `gorm:"index;column:scope_id" json:"scope_id"`
	State          string     `gorm:"index;column:state" json:"state"`
	Subject        string     `gorm:"index;column:subject" json:"subject,omitempty"`
	Predicate      string     `gorm:"column:predicate" json:"predicate,omitempty"`
	Object         string     `gorm:"column:object_row" json:"object,omitempty"`
	Summary        string     `gorm:"column:summary" json:"summary,omitempty"`
	Confidence     string     `gorm:"index;column:confidence" json:"confidence,omitempty"`
	CreatorID      string     `gorm:"index;column:creator_id" json:"creator_id"`
	SupersedesID   string     `gorm:"column:supersedes_id" json:"supersedes_id,omitempty"`
	ExpiresAt      *time.Time `gorm:"column:expires_at" json:"expires_at,omitempty"`
	LegacyRecordID string     `gorm:"index;column:legacy_record_id" json:"legacy_record_id,omitempty"`
	CreatedAt      time.Time  `gorm:"column:created_at" json:"created_at"`
	UpdatedAt      time.Time  `gorm:"column:updated_at" json:"updated_at"`
}

AgentMemoryRow 是 Agent memory record 的持久化行。 LegacyRecordID nullable 引用旧 internal/memory.Record.ID,用于兼容映射。

func FromProtocol

FromProtocol 将 protocol DTO 转换为持久化行(不含 sources/conflicts,这些存独立表)。

func (AgentMemoryRow) TableName

func (AgentMemoryRow) TableName() string

func (AgentMemoryRow) ToProtocol

func (r AgentMemoryRow) ToProtocol(sources []agentprotocol.SourceRef, conflicts []string) agentprotocol.MemoryRecord

ToProtocol 将持久化行转换为 protocol DTO。

type AgentPrincipalRow

type AgentPrincipalRow struct {
	PrincipalID  string    `gorm:"primaryKey;column:principal_id" json:"principal_id"`
	Runtime      string    `gorm:"column:runtime" json:"runtime,omitempty"`
	AgentID      string    `gorm:"column:agent_id" json:"agent_id,omitempty"`
	OwnerID      string    `gorm:"index;column:owner_id" json:"owner_id,omitempty"`
	WorkspaceID  string    `gorm:"index;column:workspace_id" json:"workspace_id,omitempty"`
	Trust        string    `gorm:"column:trust" json:"trust"`
	Capabilities string    `gorm:"column:capabilities" json:"capabilities,omitempty"` // comma-separated
	CreatedAt    time.Time `gorm:"column:created_at" json:"created_at"`
	UpdatedAt    time.Time `gorm:"column:updated_at" json:"updated_at"`
}

AgentPrincipalRow 记录已注册的 principal。

func (AgentPrincipalRow) TableName

func (AgentPrincipalRow) TableName() string

type AgentProposalRow

type AgentProposalRow struct {
	ProposalID        string     `gorm:"primaryKey;column:proposal_id" json:"proposal_id"`
	PrincipalID       string     `gorm:"index;column:principal_id" json:"principal_id"`
	ScopeKind         string     `gorm:"index;column:scope_kind" json:"scope_kind"`
	ScopeID           string     `gorm:"index;column:scope_id" json:"scope_id"`
	Kind              string     `gorm:"column:kind" json:"kind"`
	Subject           string     `gorm:"column:subject" json:"subject,omitempty"`
	Summary           string     `gorm:"column:summary" json:"summary,omitempty"`
	Object            string     `gorm:"column:object_row" json:"object,omitempty"`
	RequestedState    string     `gorm:"column:requested_state" json:"requested_state"`
	Risk              string     `gorm:"column:risk" json:"risk,omitempty"`
	Reason            string     `gorm:"column:reason" json:"reason,omitempty"`
	Status            string     `gorm:"index;column:status" json:"status"`
	ReviewReason      string     `gorm:"column:review_reason" json:"review_reason,omitempty"`
	ResultingMemoryID string     `gorm:"column:resulting_memory_id" json:"resulting_memory_id,omitempty"`
	CreatedAt         time.Time  `gorm:"column:created_at" json:"created_at"`
	ReviewedAt        *time.Time `gorm:"column:reviewed_at" json:"reviewed_at,omitempty"`
}

AgentProposalRow 持久化 memory proposal。

func (AgentProposalRow) TableName

func (AgentProposalRow) TableName() string

type AgentSourceRow

type AgentSourceRow struct {
	ID        string    `gorm:"primaryKey;column:id" json:"id"`
	MemoryID  string    `gorm:"index;column:memory_id" json:"memory_id"`
	Kind      string    `gorm:"index;column:kind" json:"kind"`
	Ref       string    `gorm:"index;column:ref" json:"ref"`
	Label     string    `gorm:"column:label" json:"label,omitempty"`
	Span      string    `gorm:"column:span" json:"span,omitempty"`
	CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
}

AgentSourceRow 是 Agent memory record 的 source 引用。

func (AgentSourceRow) TableName

func (AgentSourceRow) TableName() string

type LegacyRecord

type LegacyRecord struct {
	ID           string
	Type         string
	Subject      string
	Predicate    string
	Object       string
	Body         string
	Status       string
	Confidence   string
	SourceURI    string
	SupersedesID string
}

LegacyRecord 是旧 internal/memory.Record 的最小投影。 用于在不引入 import cycle 的情况下映射旧 row。

type LifecycleService

type LifecycleService struct {
	// contains filtered or unexported fields
}

LifecycleService 校验和执行 memory lifecycle 转换。 非法转换返回稳定 code;conflict 不静默覆盖。

func NewLifecycleService

func NewLifecycleService(s *Store) *LifecycleService

NewLifecycleService 构造 lifecycle service。

func (*LifecycleService) ConfirmProposed

func (ls *LifecycleService) ConfirmProposed(ctx context.Context, memoryID string, now time.Time) (agentprotocol.MemoryRecord, error)

ConfirmProposed 将一条 proposed memory 转为 confirmed。 要求 source 非空(unsourced memory 不能自动 confirm)。

func (*LifecycleService) Expire

func (ls *LifecycleService) Expire(ctx context.Context, memoryID string, now time.Time) error

Expire 将一条 memory 标记为 expired(基于 ExpiresAt 或显式操作)。

func (*LifecycleService) MarkConflicted

func (ls *LifecycleService) MarkConflicted(ctx context.Context, memoryIDs []string, reason string, now time.Time) error

MarkConflicted 将一组 confirmed memory 标记为互相冲突。 冲突 memory 保持可见(recallable),不静默覆盖。

func (*LifecycleService) ResolveConflict

func (ls *LifecycleService) ResolveConflict(ctx context.Context, winnerID string, now time.Time) error

ResolveConflict 将一条 conflicted memory 转回 confirmed, 同时将其余冲突方标记为 superseded。

func (*LifecycleService) RollbackSupersede

func (ls *LifecycleService) RollbackSupersede(ctx context.Context, supersededID string, now time.Time) error

RollbackSupersede 将一条 superseded memory 恢复为 confirmed(显式回滚)。

func (*LifecycleService) Supersede

func (ls *LifecycleService) Supersede(ctx context.Context, oldID, replacementID string, now time.Time) error

Supersede 将一条 confirmed memory 标记为 superseded,由 replacement 接替。 旧 record 不被删除;replacement.SupersedesID 指向旧 record。

func (*LifecycleService) ValidateTransition

func (ls *LifecycleService) ValidateTransition(from, to agentprotocol.LifecycleState) error

ValidateTransition 检查从 from 到 to 的转换是否合法。 返回 nil 表示合法,否则返回 StableError。

type MigrationReceipt

type MigrationReceipt struct {
	SchemaVersion string    `json:"schema_version"`
	ReceiptID     string    `json:"receipt_id"`
	Kind          string    `json:"kind"`   // agent_memory_migration
	Action        string    `json:"action"` // auto_migrate
	TableNames    []string  `json:"table_names"`
	Status        string    `json:"status"` // success, rolled_back
	CreatedAt     time.Time `json:"created_at"`
}

MigrationReceipt 是首次持久化 agent memory state 时写的脱敏 schema receipt。

type Policy

type Policy struct {
	// AllowAutoConfirm 控制是否允许在 propose 时自动 confirm。
	// 默认 false:adapter proposal 始终需要 review。
	AllowAutoConfirm bool
}

Policy 定义 Agent memory runtime 的授权规则。 adapter 默认只能 propose;unsourced preference 不能自动 confirm; confirmed mutation 需要 owner capability 或显式 policy 授权。

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy 返回保守的默认策略。

func (Policy) CheckApprove

func (p Policy) CheckApprove(principal agentprotocol.Principal) error

CheckApprove 检查 principal 是否被允许 approve proposal(confirm 结果)。

func (Policy) CheckConfirm

func (p Policy) CheckConfirm(principal agentprotocol.Principal) error

CheckConfirm 检查 principal 是否被允许直接 confirm memory。 只有 owner trust 或显式 confirm capability 才允许。 adapter 默认不能 confirm——必须走 proposal → review → approve 流程。

func (Policy) CheckFeedback

func (p Policy) CheckFeedback(principal agentprotocol.Principal) error

CheckFeedback 检查 principal 是否被允许提交 feedback。

func (Policy) CheckHandoff

func (p Policy) CheckHandoff(principal agentprotocol.Principal) error

CheckHandoff 检查 principal 是否被允许创建 handoff。

func (Policy) CheckPropose

func (p Policy) CheckPropose(principal agentprotocol.Principal) error

CheckPropose 检查 principal 是否被允许提交 proposal。 adapter trust 默认有 propose capability;如果没有则拒绝。

func (Policy) CheckReview

func (p Policy) CheckReview(principal agentprotocol.Principal) error

CheckReview 检查 principal 是否被允许 review proposal。

func (Policy) EvaluateProposal

EvaluateProposal 运行 proposal 的 source、scope、duplicate、conflict 和 policy 检查。 返回 review 结论(status + reason)。

type RecallQuery

type RecallQuery struct {
	Scope  agentprotocol.Scope
	Text   string
	Kinds  []agentprotocol.MemoryKind
	States []agentprotocol.LifecycleState
	Limit  int
}

RecallQuery 描述一次 memory recall 查询。 Text 是可选的子串匹配(subject/summary/object);Scope 必填; Kinds 和 States 是可选过滤器。

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store 是 Agent memory runtime 的持久化仓库。 它管理自己的 `agent_memory.sqlite` 数据库,不直接修改旧 `ledger.sqlite`。 旧 memory rows 通过 LegacyView 映射读取,不静默 backfill。

func Open

func Open(root string) (*Store, error)

Open 打开或创建指定 vault root 下的 agent memory store。

func OpenDB

func OpenDB(db *gorm.DB) (*Store, error)

OpenDB 从已有 gorm.DB 构造 store(用于测试和共享连接)。

func (*Store) Close

func (s *Store) Close() error

Close 关闭数据库连接。

func (*Store) CountByScope

func (s *Store) CountByScope(ctx context.Context, scope agentprotocol.Scope) (map[agentprotocol.LifecycleState]int, error)

CountByScope 返回某 scope 下各 state 的 memory 计数(用于 status/observability)。

func (*Store) DB

func (s *Store) DB() *gorm.DB

DB 返回底层 gorm.DB(用于高级查询和测试)。

func (*Store) GetMemory

func (s *Store) GetMemory(ctx context.Context, id string) (agentprotocol.MemoryRecord, error)

GetMemory 读取单个 memory record(含 sources 和 conflicts)。

func (*Store) ListFeedback

func (s *Store) ListFeedback(ctx context.Context, scope agentprotocol.Scope) ([]AgentFeedbackRow, error)

ListFeedback 按 scope 列出 feedback。

func (*Store) ListHandoffs

func (s *Store) ListHandoffs(ctx context.Context, scope agentprotocol.Scope) ([]AgentHandoffRow, error)

ListHandoffs 按 scope 列出 handoff。

func (*Store) ListMemories

ListMemories 按 scope 列出 memory(可选 state 过滤)。

func (*Store) ListProposals

func (s *Store) ListProposals(ctx context.Context, scope agentprotocol.Scope) ([]AgentProposalRow, error)

ListProposals 按 scope 列出 proposal。

func (*Store) Recall

Recall 按 query 检索 memory records。 默认只返回 recallable states(confirmed/conflicted),除非 States 显式指定。 raw SQL 只用于 LIKE 匹配,不拼业务逻辑。

func (*Store) SaveFeedback

func (s *Store) SaveFeedback(ctx context.Context, f agentprotocol.Feedback) error

SaveFeedback 保存 feedback。

func (*Store) SaveHandoff

func (s *Store) SaveHandoff(ctx context.Context, h agentprotocol.Handoff) error

SaveHandoff 保存 handoff。

func (*Store) SaveMemory

func (s *Store) SaveMemory(ctx context.Context, m agentprotocol.MemoryRecord) error

SaveMemory 在事务中写入 memory record 及其 sources 和 conflicts。

func (*Store) SavePrincipal

func (s *Store) SavePrincipal(ctx context.Context, p agentprotocol.Principal) error

SavePrincipal 注册或更新 principal。

func (*Store) SaveProposal

SaveProposal 保存 proposal。

func (*Store) UpdateProposalStatus

func (s *Store) UpdateProposalStatus(ctx context.Context, proposalID string, status agentprotocol.ProposalStatus, reviewReason agentprotocol.ProposalStatusReason, resultingMemoryID string) error

UpdateProposalStatus 更新 proposal 的 review 结果。

func (*Store) WriteMigrationReceipt

func (s *Store) WriteMigrationReceipt(ctx context.Context, receipt MigrationReceipt) error

WriteMigrationReceipt 在首次持久化新 runtime state 时写脱敏 receipt。 receipt 不包含正文或 secret。失败时返回 stable error,不损坏旧 ledger。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL