memorywrite

package
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package memorywrite provides shared transactional write helpers for durable memory surfaces. Mutating helpers keep ctx_agent_memory.version and changelog entries in the same transaction.

Index

Constants

View Source
const KnowledgeRestoreWindow = 90 * 24 * time.Hour

Variables

View Source
var (
	ErrFactNotRestorable    = errors.New("fact is not restorable")
	ErrFactRestoreBadCaller = errors.New("fact restore requires restored_by")
	ErrFactRestoreExpired   = errors.New("fact restore window expired")
	ErrFactDuplicateContent = errors.New("active knowledge already has this content")
)
View Source
var ErrFactNotFound = errors.New("fact not found")

Functions

func AddConstraint

func AddConstraint(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, userID string, agentID string, text string) ([]memory.ConstraintEntry, error)

AddConstraint appends a new constraint entry transactionally, bumps version, and records a changelog entry with scope='constraint', action='create'.

func AddProfileEntry added in v0.42.0

func AddProfileEntry(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, userID, agentID, text string) ([]memory.ProfileEntry, error)

AddProfileEntry appends an auto-generated dated entry to the profile_entries column, bumps version, and records a changelog entry. The manual profile content column is never touched.

func ApplyFactBatch added in v0.60.0

func ApplyFactBatch(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, userID string, agentID string, ops []FactBatchOperation) ([]memory.Fact, error)

ApplyFactBatch applies a batch of fact writes under one memory advisory lock and one database transaction. If any operation fails, all prior writes in the batch are rolled back.

func CreateFact added in v0.60.0

func CreateFact(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, in memory.FactWrite) (memory.Fact, error)

CreateFact inserts an active fact, bumps the shared user-agent memory version, and records the fact state in ctx_agent_memory_changelog.

func CreateKnowledge added in v0.60.0

func CreateKnowledge(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, in KnowledgeCreateInput) (memory.Fact, error)

CreateKnowledge creates a trimmed, manually owned world fact.

func DeprecateKnowledge added in v0.60.0

func DeprecateKnowledge(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, in KnowledgeDeprecateInput) (memory.Fact, error)

DeprecateKnowledge manually retires an active world fact and records its operator.

func GetConstraints

func GetConstraints(ctx context.Context, q *sqlc.Queries, userID string, agentID string) ([]memory.ConstraintEntry, error)

GetConstraints reads the constraints JSON array from the DB row. Returns an empty slice (not an error) when no row exists or constraints is empty/default.

func GetGroupMemory added in v0.42.0

func GetGroupMemory(ctx context.Context, q *sqlc.Queries, groupID string) (string, error)

GetGroupMemory reads the shared memory content for a group. Returns ("", nil) when no row exists.

func GetProfileEntries added in v0.42.0

func GetProfileEntries(ctx context.Context, q *sqlc.Queries, userID, agentID string) ([]memory.ProfileEntry, error)

GetProfileEntries reads the auto-generated dated profile entries from a user's memory row. Returns an empty slice when no row or entries exist.

func ListActiveFacts added in v0.60.0

func ListActiveFacts(ctx context.Context, q *sqlc.Queries, userID string, agentID string, subject memory.FactSubject) ([]memory.Fact, error)

ListActiveFacts returns the current active facts for one subject.

func ListActiveFactsAt added in v0.60.0

func ListActiveFactsAt(ctx context.Context, q *sqlc.Queries, userID string, agentID string, subject memory.FactSubject, version int64) ([]memory.Fact, error)

ListActiveFactsAt reconstructs active facts at a frozen memory version from fact changelog payloads.

func ListActiveFactsAtSnapshot added in v0.60.0

func ListActiveFactsAtSnapshot(ctx context.Context, q *sqlc.Queries, userID string, agentID string, subject memory.FactSubject, version int64) ([]memory.Fact, bool, error)

ListActiveFactsAtSnapshot reconstructs active facts and reports whether any fact changelog existed for that subject. Callers use the flag to distinguish "facts prove this version is empty" from "this snapshot predates facts".

func ParseConstraintsJSON

func ParseConstraintsJSON(raw string) ([]memory.ConstraintEntry, error)

ParseConstraintsJSON parses a constraints JSON string into a slice. Returns empty slice for "", "[]", or null.

func ParseProfileEntriesJSON added in v0.42.0

func ParseProfileEntriesJSON(raw string) ([]memory.ProfileEntry, error)

ParseProfileEntriesJSON parses profile entries JSON. Returns empty slice for "", "[]", or "null".

func RemoveConstraint

func RemoveConstraint(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, userID string, agentID string, id string) ([]memory.ConstraintEntry, error)

RemoveConstraint removes a constraint by ID transactionally, bumps version, and records a changelog entry with scope='constraint', action='delete'.

func ReplaceFact added in v0.60.0

func ReplaceFact(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, oldFactID string, in memory.FactWrite) (memory.Fact, error)

ReplaceFact deprecates an existing fact and creates a new active fact that points at the old row through supersedes.

func ReplaceKnowledge added in v0.60.0

func ReplaceKnowledge(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, in KnowledgeReplaceInput) (memory.Fact, error)

ReplaceKnowledge atomically retires one active world fact and writes its manual successor.

func ResetUserAgentMemory added in v0.60.0

func ResetUserAgentMemory(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, userID string, agentID string) error

ResetUserAgentMemory resets the user-agent memory surface: it deprecates all active fact-backed memories, then clears the legacy memory row columns (constraints and profile entries) in place. The row itself is kept so the version clock stays monotonic; deleting it would restart versions at 1 and let frozen sessions replay stale fact changelog state.

func SetGroupMemory added in v0.42.0

func SetGroupMemory(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, groupID string, content string) error

SetGroupMemory writes a group's shared memory content, incrementing version atomically. Group memory has no auth_user FK — it is keyed solely by group_id. This function MUST NOT be called from DM write paths; the type-level separation between group and user writers enforces the private→group wall.

func SetSingletonFact added in v0.60.0

func SetSingletonFact(ctx context.Context, db *pgxpool.Pool, q *sqlc.Queries, in memory.FactWrite) (memory.Fact, error)

SetSingletonFact creates or replaces the single active fact for subject=user or subject=agent under the same advisory lock used for the write itself.

Types

type FactBatchAction added in v0.60.0

type FactBatchAction string
const (
	FactBatchSetSingleton  FactBatchAction = "set_singleton"
	FactBatchCreate        FactBatchAction = "create"
	FactBatchReplaceMany   FactBatchAction = "replace_many"
	FactBatchDeprecateMany FactBatchAction = "deprecate_many"
)

type FactBatchOperation added in v0.60.0

type FactBatchOperation struct {
	Action        FactBatchAction
	Subject       memory.FactSubject
	Content       string
	Metadata      json.RawMessage
	TargetFactIDs []string
	// TargetUsageLastUsedAt optionally makes deprecate_many skip targets whose
	// Reflect knowledge usage changed since candidate selection. Curator uses
	// this to avoid retiring facts that were used while an armed run was pending.
	TargetUsageLastUsedAt map[string]time.Time
	// RequireEligibleActivityAfterUsage makes curator deprecation recheck that
	// the owning user-agent pair still has a review-eligible conversation after
	// the locked usage timestamp.
	RequireEligibleActivityAfterUsage bool
}

FactBatchOperation describes one transaction-scoped fact mutation. Reflect uses this helper so profile/soul/knowledge writes can fail closed as one fact line instead of committing partial writes.

type KnowledgeCreateInput added in v0.60.0

type KnowledgeCreateInput struct{ UserID, AgentID, Content string }

type KnowledgeCursor added in v0.60.0

type KnowledgeCursor struct {
	Timestamp time.Time
	ID        string
}

KnowledgeCursor identifies the last visible row in a stable lifecycle page.

type KnowledgeDeprecateInput added in v0.60.0

type KnowledgeDeprecateInput struct{ FactID, UserID, AgentID, DeprecatedBy string }

type KnowledgeItem added in v0.60.0

type KnowledgeItem struct {
	Fact            memory.Fact
	RemovalSource   KnowledgeRemovalSource
	DeprecatedAt    *time.Time
	RestoreDeadline *time.Time
	IsRestorable    bool
}

type KnowledgeListQuery added in v0.60.0

type KnowledgeListQuery struct {
	UserID  string
	AgentID string
	State   KnowledgeState
	Limit   int32
	Now     time.Time
	Cursor  *KnowledgeCursor
}

type KnowledgePage added in v0.60.0

type KnowledgePage struct {
	Items      []KnowledgeItem
	Total      int64
	HasMore    bool
	NextCursor *KnowledgeCursor
}

func ListKnowledge added in v0.60.0

func ListKnowledge(ctx context.Context, q *sqlc.Queries, in KnowledgeListQuery) (KnowledgePage, error)

ListKnowledge returns one deterministic active or eligible removed knowledge page.

type KnowledgeRemovalSource added in v0.60.0

type KnowledgeRemovalSource string
const (
	KnowledgeRemovalManual  KnowledgeRemovalSource = "manual"
	KnowledgeRemovalCurator KnowledgeRemovalSource = "curator"
)

type KnowledgeReplaceInput added in v0.60.0

type KnowledgeReplaceInput struct{ FactID, UserID, AgentID, Content string }

type KnowledgeRestoreInput added in v0.60.0

type KnowledgeRestoreInput struct {
	FactID, UserID, AgentID, RestoredBy string
	Now                                 time.Time
}

type KnowledgeRestoreResult added in v0.60.0

type KnowledgeRestoreResult struct {
	Fact     memory.Fact
	Restored bool
}

func RestoreKnowledge added in v0.60.0

RestoreKnowledge restores an eligible removed world fact within its 90-day window.

type KnowledgeState added in v0.60.0

type KnowledgeState string
const (
	KnowledgeStateActive  KnowledgeState = "active"
	KnowledgeStateRemoved KnowledgeState = "removed"
)

type ManagementService added in v0.60.0

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

ManagementService is the narrow application port for the user-facing memory management surface. It owns persistence and logical-history projection so HTTP handlers never depend on raw SQL queries.

func NewManagementService added in v0.60.0

func NewManagementService(db *pgxpool.Pool, changelog memory.ChangelogPageReader) *ManagementService

func (*ManagementService) CreateKnowledge added in v0.60.0

func (s *ManagementService) CreateKnowledge(ctx context.Context, in KnowledgeCreateInput) (memory.Fact, error)

func (*ManagementService) DeprecateKnowledge added in v0.60.0

func (s *ManagementService) DeprecateKnowledge(ctx context.Context, in KnowledgeDeprecateInput) (memory.Fact, error)

func (*ManagementService) ListKnowledge added in v0.60.0

func (*ManagementService) ReadChangelogPage added in v0.60.0

func (s *ManagementService) ReadChangelogPage(
	ctx context.Context,
	userID string,
	agentID string,
	scope string,
	cursor *memory.ChangelogCursor,
	limit int,
) ([]memory.ChangeEntry, error)

ReadChangelogPage returns one logical page source. Profile and Soul remain provider-owned projections; Knowledge and Constraints are projected here.

func (*ManagementService) ReplaceKnowledge added in v0.60.0

func (s *ManagementService) ReplaceKnowledge(ctx context.Context, in KnowledgeReplaceInput) (memory.Fact, error)

func (*ManagementService) RestoreKnowledge added in v0.60.0

RestoreKnowledge checks the authorized owner tuple before applying the lifecycle transition, keeping cross-owner existence hidden from transports.

type RestoreCuratorDeprecatedKnowledgeFactInput added in v0.60.0

type RestoreCuratorDeprecatedKnowledgeFactInput struct {
	FactID     string
	UserID     string
	AgentID    string
	RestoredBy string
	Reason     string
}

type RestoreCuratorDeprecatedKnowledgeFactResult added in v0.60.0

type RestoreCuratorDeprecatedKnowledgeFactResult struct {
	Fact     memory.Fact
	Restored bool
}

func RestoreCuratorDeprecatedKnowledgeFact added in v0.60.0

RestoreCuratorDeprecatedKnowledgeFact restores a Reflect-owned world fact that was deprecated by the usage curator. It intentionally refuses other deprecates: manual/semantic deprecations need a different review path.

Jump to

Keyboard shortcuts

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