Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(memory): add forced consolidation feature and related i18n updates
wizardchenfda037e7f3e0
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 5202803ac..be9b7756a 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1650,6 +1650,7 @@ export default {consolidateTooFewItems: 'Too few memories to be worth tidying yet',consolidateNoCandidates: 'No memories looked close enough to merge',consolidateModelDeclined: 'The model looked and found these are different things, so nothing was merged',+ consolidateTooSoon: 'A tidy-up just ran. Please try again in a moment.',consolidateModelUnavailable: 'The model was unavailable, so nothing was changed rather than risk a wrong merge',consolidateFailed: 'Failed to tidy up',clear: 'Clear all',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 15e53bdb4..d77773116 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -4692,6 +4692,7 @@ export default {consolidateTooFewItems: '기억이 아직 적어 정리할 필요가 없습니다',consolidateNoCandidates: '뜻이 비슷해 합칠 만한 기억이 없습니다',consolidateModelDeclined: '모델이 확인한 결과 서로 다른 내용이라 합치지 않았습니다',+ consolidateTooSoon: '방금 정리했습니다. 잠시 후 다시 시도해 주세요.',consolidateModelUnavailable: '모델을 사용할 수 없어 잘못 합치지 않도록 아무것도 바꾸지 않았습니다',consolidateFailed: '정리하지 못했습니다',clear: '전체 삭제',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex d536b1c43..0c69d62f9 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -4692,6 +4692,7 @@ export default {consolidateTooFewItems: 'Записей пока слишком мало, наводить порядок рано',consolidateNoCandidates: 'Похожих по смыслу записей для объединения не нашлось',consolidateModelDeclined: 'Модель посмотрела: это разные вещи, объединять нечего',+ consolidateTooSoon: 'Разбор только что выполнялся. Повторите чуть позже.',consolidateModelUnavailable: 'Модель недоступна, поэтому ничего не изменено — чтобы не объединить лишнего',consolidateFailed: 'Не удалось навести порядок',clear: 'Очистить всё',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 14b3c4873..60db6c8e5 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4694,6 +4694,7 @@ export default {consolidateTooFewItems: '记忆还太少,暂时没有整理的必要',consolidateNoCandidates: '没有发现意思相近的记忆,无需合并',consolidateModelDeclined: '模型看过了,这些记忆说的不是同一件事,未做合并',+ consolidateTooSoon: '刚整理过,请稍后再试',consolidateModelUnavailable: '模型不可用,为避免误合并,本次没有改动任何记忆',consolidateFailed: '整理失败',clear: '清空',diff --git a/frontend/src/views/settings/MemorySettings.vue b/frontend/src/views/settings/MemorySettings.vueindex 2c4f7d499..26fdc96d0 100644--- a/frontend/src/views/settings/MemorySettings.vue+++ b/frontend/src/views/settings/MemorySettings.vue@@ -798,6 +798,7 @@ const consolidateSkipMessage: Record<string, string> = {too_few_items: 'memorySettings.consolidateTooFewItems',no_candidates: 'memorySettings.consolidateNoCandidates',model_declined: 'memorySettings.consolidateModelDeclined',+ too_soon: 'memorySettings.consolidateTooSoon',}const handleConsolidate = async () => {diff --git a/internal/application/repository/memory.go b/internal/application/repository/memory.goindex b9807664b..4b10bb80b 100644--- a/internal/application/repository/memory.go+++ b/internal/application/repository/memory.go@@ -642,6 +642,15 @@ func (r *memoryRepository) MarkConsolidated(Updates(map[string]interface{}{"consolidated_at": now, "updated_at": now}).Error}+func (r *memoryRepository) MarkForcedConsolidated(+ ctx context.Context, scope interfaces.MemoryScope,+) error {+ now := time.Now()+ return r.scoped(ctx, scope).+ Model(&types.MemorySubject{}).+ Updates(map[string]interface{}{"forced_consolidated_at": now, "updated_at": now}).Error+}+func (r *memoryRepository) SetItemStatus(ctx context.Context, scope interfaces.MemoryScope, id, status string,) error {diff --git a/internal/application/service/memory/consolidate.go b/internal/application/service/memory/consolidate.goindex 896341687..c14a44cc0 100644--- a/internal/application/service/memory/consolidate.go+++ b/internal/application/service/memory/consolidate.go@@ -18,6 +18,11 @@ const (// is maintenance, not a feature the user is waiting on, and every run costs// a model call, so it is deliberately infrequent.consolidateInterval = 24 * time.Hour+ // forcedConsolidateInterval is the floor between two reviews one person+ // asks for. Short enough that a real retry — fix the model, press again —+ // is not blocked, long enough that the button cannot be scripted into a+ // stream of model calls.+ forcedConsolidateInterval = time.Minute// consolidateMinItems is the store size below which there is nothing worth// reviewing: a handful of memories cannot have drifted into contradiction.consolidateMinItems = 6@@ -90,13 +95,33 @@ func (s *Service) reviewStore(force bool,) *types.MemoryConsolidationResult {result := &types.MemoryConsolidationResult{}- if !force {- subject, err := s.repo.GetSubject(ctx, scope)- if err != nil || subject == nil {- return result+ subject, err := s.repo.GetSubject(ctx, scope)+ if err != nil || subject == nil {+ if err != nil {+ logger.Warnf(ctx, "memory: load subject for consolidation failed: %v", err)+ }+ return result+ }+ // Two clocks, because the two callers are rate limited for different+ // reasons and must not silence each other. The daily pass is maintenance+ // nobody asked for, so it waits a day. A review someone pressed a button+ // for waits only long enough that the button cannot be held down: the+ // endpoint is Viewer-level and each press is worth up to forcedMaxClusters+ // model calls, which a store the model keeps declining would repeat+ // indefinitely.+ last, interval := subject.ConsolidatedAt, consolidateInterval+ if force {+ last, interval = subject.ForcedConsolidatedAt, forcedConsolidateInterval+ }+ if last != nil && time.Since(*last) < interval {+ if force {+ result.Skipped = types.MemoryConsolidationSkipTooSoon}- if subject.ConsolidatedAt != nil && time.Since(*subject.ConsolidatedAt) < consolidateInterval {- return result+ return result+ }+ if force {+ if err := s.repo.MarkForcedConsolidated(ctx, scope); err != nil {+ logger.Warnf(ctx, "memory: mark forced consolidation failed: %v", err)}}@@ -110,7 +135,15 @@ func (s *Service) reviewStore(}}- items, _, err := s.repo.ListItems(ctx, scope, types.MemoryStatusActive, 200, 0)+ // The whole store, not a page of it. A fixed 200 used to bound this, which+ // meant two duplicates that were both old could never meet: the pass only+ // ever saw the newest rows, and consolidation is the one stage whose job is+ // to notice things that drifted apart over weeks.+ //+ // Reading more costs no model calls. Candidate selection is local — token+ // overlap plus the vectors recall already stored — and the number of groups+ // actually put to a model is capped separately by maxClusters.+ items, _, err := s.repo.ListItems(ctx, scope, types.MemoryStatusActive, cfg.EffectiveMaxItems(), 0)if err != nil {logger.Warnf(ctx, "memory: consolidation list failed: %v", err)return result@@ -272,17 +305,21 @@ func (s *Service) mergeCandidates(items []*types.MemoryItem,minOverlap, minCosine float64,) [][]*types.MemoryItem {- tokens := make(map[string][]string, len(items))+ // Sets rather than slices: clustering compares every surviving pair, so a+ // store at the 2000-item cap runs this predicate a couple of million times+ // and rebuilding both token sets inside each call is what would make+ // reviewing the whole store too slow to do on a request.+ tokens := make(map[string]map[string]struct{}, len(items))for _, item := range items {if item == nil {continue}- tokens[item.ID] = tokenize(item.Topic + " " + item.Content)+ tokens[item.ID] = tokenSet(tokenize(item.Topic + " " + item.Content))}vectors := s.storedVectors(ctx, scope, cfg, items)return clusterBy(items, func(a, b *types.MemoryItem) bool {- if jaccard(tokens[a.ID], tokens[b.ID]) >= minOverlap {+ if jaccardSets(tokens[a.ID], tokens[b.ID]) >= minOverlap {return true}va, vb := vectors[a.ID], vectors[b.ID]@@ -366,27 +403,37 @@ func clusterBy(return clusters}-// jaccard is the overlap between two token sets.+// jaccard is the overlap between two token lists.func jaccard(a, b []string) float64 {+ return jaccardSets(tokenSet(a), tokenSet(b))+}++// tokenSet deduplicates tokens so repeated comparisons of the same memory do+// not rebuild its side of the overlap each time.+func tokenSet(tokens []string) map[string]struct{} {+ set := make(map[string]struct{}, len(tokens))+ for _, token := range tokens {+ set[token] = struct{}{}+ }+ return set+}++// jaccardSets is the overlap between two prepared token sets.+func jaccardSets(a, b map[string]struct{}) float64 {if len(a) == 0 || len(b) == 0 {return 0}- set := make(map[string]struct{}, len(a))- for _, token := range a {- set[token] = struct{}{}+ // Walk the smaller side; the result is symmetric either way.+ if len(b) < len(a) {+ a, b = b, a}shared := 0- seen := make(map[string]struct{}, len(b))- for _, token := range b {- if _, dup := seen[token]; dup {- continue- }- seen[token] = struct{}{}- if _, ok := set[token]; ok {+ for token := range a {+ if _, ok := b[token]; ok {shared++}}- union := len(set) + len(seen) - shared+ union := len(a) + len(b) - sharedif union == 0 {return 0}diff --git a/internal/application/service/memory/consolidate_test.go b/internal/application/service/memory/consolidate_test.goindex 27fffe6f5..d55d72388 100644--- a/internal/application/service/memory/consolidate_test.go+++ b/internal/application/service/memory/consolidate_test.go@@ -156,6 +156,47 @@ func TestAReviewThatChangesNothingSaysWhy(t *testing.T) {require.Equal(t, 2, result.Reviewed)}+// The button is Viewer-level and each press is worth up to forcedMaxClusters+// model calls, which a store the model keeps declining would repeat forever.+func TestASecondReviewRightAwayIsRefused(t *testing.T) {+ svc, tenantRepo, models := newConsolidationHarness(t)+ ctx := enabledCtx(t, tenantRepo, 1, "alice")+ scope := scopeFor(t, ctx)+ _, err := svc.repo.EnsureSubject(ctx, scope)+ require.NoError(t, err)+ seedSimilarPreferences(t, svc, ctx, scope)++ first, err := svc.ConsolidateNow(ctx)+ require.NoError(t, err)+ require.Equal(t, 1, first.Merged)+ callsAfterFirst := models.callCount()++ second, err := svc.ConsolidateNow(ctx)+ require.NoError(t, err)+ require.Equal(t, types.MemoryConsolidationSkipTooSoon, second.Skipped)+ require.Equal(t, callsAfterFirst, models.callCount(),+ "a refused review must not reach the model at all")+}++// The two clocks are separate so that the maintenance pass, which runs on its+// own schedule and marks the subject consolidated, cannot make the button+// report that the person only just asked for something they never asked for.+func TestTheDailyPassDoesNotRateLimitTheButton(t *testing.T) {+ svc, tenantRepo, _ := newConsolidationHarness(t)+ ctx := enabledCtx(t, tenantRepo, 1, "alice")+ scope := scopeFor(t, ctx)+ _, err := svc.repo.EnsureSubject(ctx, scope)+ require.NoError(t, err)+ seedSimilarPreferences(t, svc, ctx, scope)++ svc.consolidateIfDue(ctx, scope, svc.workspaceConfig(ctx, 1), "chat-1")++ result, err := svc.ConsolidateNow(ctx)+ require.NoError(t, err)+ require.NotEqual(t, types.MemoryConsolidationSkipTooSoon, result.Skipped)+ require.Equal(t, 1, result.Merged)+}+func TestScheduledConsolidationIgnoresAHandfulOfMemories(t *testing.T) {svc, tenantRepo, models := newConsolidationHarness(t)ctx := enabledCtx(t, tenantRepo, 1, "alice")diff --git a/internal/types/interfaces/memory.go b/internal/types/interfaces/memory.goindex 9897fdfed..a30a89ed0 100644--- a/internal/types/interfaces/memory.go+++ b/internal/types/interfaces/memory.go@@ -95,6 +95,10 @@ type MemoryRepository interface {// MarkConsolidated records that this subject's whole store was just// reviewed, so the next review waits out the interval.MarkConsolidated(ctx context.Context, scope MemoryScope) error+ // MarkForcedConsolidated records that this subject asked for a review+ // themselves. Kept apart from MarkConsolidated so the daily pass and the+ // button rate limit each other independently.+ MarkForcedConsolidated(ctx context.Context, scope MemoryScope) error// UpsertItemEmbedding stores or replaces the vector for one memory.UpsertItemEmbedding(ctx context.Context, scope MemoryScope, embedding *types.MemoryItemEmbedding) error// DeleteItemEmbedding drops one memory's vector. What a memory embeds todiff --git a/internal/types/memory.go b/internal/types/memory.goindex 87db290bf..2dd3bbed0 100644--- a/internal/types/memory.go+++ b/internal/types/memory.go@@ -205,8 +205,13 @@ type MemorySubject struct {// newest conversation, so nothing else notices that five turns over three// weeks have said the same thing five slightly different ways.ConsolidatedAt *time.Time `json:"consolidated_at" gorm:"column:consolidated_at"`- CreatedAt time.Time `json:"created_at"`- UpdatedAt time.Time `json:"updated_at"`+ // ForcedConsolidatedAt is when this person last asked for a review+ // themselves. It is a separate clock from ConsolidatedAt on purpose: the+ // daily pass having just run must not refuse someone who presses the+ // button, so the two cannot share one timestamp.+ ForcedConsolidatedAt *time.Time `json:"forced_consolidated_at" gorm:"column:forced_consolidated_at"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`}// MemoryPendingSessions is the persisted queue of sessions awaiting@@ -987,6 +992,10 @@ const (// MemoryConsolidationSkipModelDeclined: the model looked and said these// records are different things after all.MemoryConsolidationSkipModelDeclined = "model_declined"+ // MemoryConsolidationSkipTooSoon: this person asked for a review moments+ // ago. Only a review someone requested can report this; the daily pass has+ // its own, much longer interval and simply stays quiet.+ MemoryConsolidationSkipTooSoon = "too_soon")// MemoryConsolidationResult is what a whole-store review did. Zeroes mean thediff --git a/migrations/sqlite/000004_memory.up.sql b/migrations/sqlite/000004_memory.up.sqlindex 6ffb205df..f5a21a863 100644--- a/migrations/sqlite/000004_memory.up.sql+++ b/migrations/sqlite/000004_memory.up.sql@@ -99,6 +99,7 @@ ALTER TABLE tenants ADD COLUMN memory_config TEXT;ALTER TABLE messages ADD COLUMN used_memories TEXT;ALTER TABLE memory_subjects ADD COLUMN consolidated_at DATETIME;+ALTER TABLE memory_subjects ADD COLUMN forced_consolidated_at DATETIME;ALTER TABLE memory_topic_stats ADD COLUMN aliases TEXT NOT NULL DEFAULT '[]';diff --git a/migrations/versioned/000084_memory.up.sql b/migrations/versioned/000084_memory.up.sqlindex 1b0badd6d..3178978b7 100644--- a/migrations/versioned/000084_memory.up.sql+++ b/migrations/versioned/000084_memory.up.sql@@ -140,6 +140,10 @@ ALTER TABLE messages ADD COLUMN IF NOT EXISTS used_memories JSONB;ALTER TABLE memory_subjects ADD COLUMN IF NOT EXISTS consolidated_at TIMESTAMP WITH TIME ZONE;+-- A review someone asked for is rate limited separately from the daily pass:+-- one clock for both would let the daily pass refuse the button.+ALTER TABLE memory_subjects ADD COLUMN IF NOT EXISTS forced_consolidated_at TIMESTAMP WITH TIME ZONE;+ALTER TABLE memory_topic_stats ADD COLUMN IF NOT EXISTS aliases JSONB NOT NULL DEFAULT '[]';-- Vectors live apart from the items so that listing, capacity enforcement and