Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: deduplicate memory proposals against existing stored memories

Adam Eivy27330cde691c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8c4f665fba..c2f29c26bb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,8 @@
## Fixed
+- **Memory dedup — duplicate approval requests** — memory extractor now checks existing active and pending memories (via vector similarity + text prefix matching) before proposing new ones, and the LLM classification prompt now includes existing memories so it avoids re-proposing semantically equivalent knowledge
+
- **Xcode `deploy.sh` template — altool upload check false-positive** — generated deploy scripts grepped altool output for plain `ERROR: ` to detect upload failures, but altool's multipart uploader logs every transient retry as `ERROR: [ContentDelivery.Uploader.X] WILL RETRY PART N. Checksums do not match.` On flaky/slow networks the script killed deploys mid-recovery. Switched to Apple's definitive failure markers only: `UPLOAD FAILED|Validation failed \(|ERROR ITMS-|product-errors`. Affects iOS, macOS, and watchOS upload sections in `xcodeScripts.js`.
- Submodule status API (`/api/git/submodules/status`) always returned empty array — `stdout.trim()` was stripping the leading space status character from `git submodule status` output, causing the regex parser to fail
- CoS agents page crash: pipe characters (`|`) in task descriptions triggered infinite loop in markdown parser — non-table pipes now treated as normal text with safety fallback
diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.js
index 3e19256d8b..3ac3be2339 100644
--- a/server/services/memoryClassifier.js
+++ b/server/services/memoryClassifier.js
@@ -10,6 +10,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getStageTemplate } from './promptService.js';
import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { getMemories } from './memoryBackend.js';
const MEMORY_CONFIG_FILE = join(PATHS.data, 'memory-classifier-config.json');
@@ -73,6 +74,26 @@ export async function updateConfig(updates) {
return newConfig;
}
+/**
+ * Load existing active + pending memories as a summary for the LLM prompt.
+ * Defense-in-depth: the LLM sees what's already stored so it avoids proposing
+ * duplicates. The backend dedup in memoryExtractor is the actual safety net.
+ */
+async function loadExistingMemorySummary() {
+ const [active, pending] = await Promise.all([
+ getMemories({ status: 'active', sortBy: 'importance', sortOrder: 'desc', limit: 30 })
+ .catch(() => ({ memories: [] })),
+ getMemories({ status: 'pending_approval', limit: 30 })
+ .catch(() => ({ memories: [] }))
+ ]);
+
+ const allMemories = [...active.memories, ...pending.memories];
+ if (allMemories.length === 0) return '';
+
+ const lines = allMemories.slice(0, 30).map(m => `- [${m.type}] ${(m.content || '').substring(0, 150)}`);
+ return lines.join('\n');
+}
+
/**
* Build the classification prompt
*/
@@ -80,9 +101,12 @@ async function buildClassificationPrompt(task, agentOutput, config) {
// Try to load the template
const template = await getStageTemplate('memory-evaluate').catch(() => null);
+ // Load existing memories to inject into the prompt
+ const existingMemories = await loadExistingMemorySummary();
+
if (!template) {
// Fallback inline template
- return buildFallbackPrompt(task, agentOutput);
+ return buildFallbackPrompt(task, agentOutput, existingMemories);
}
// Apply variables to template
@@ -91,7 +115,8 @@ async function buildClassificationPrompt(task, agentOutput, config) {
taskDescription: task.description || 'No description',
taskStatus: task.status || 'completed',
appName: task.metadata?.app || 'PortOS',
- agentOutput: agentOutput.substring(0, config.maxOutputLength || 10000)
+ agentOutput: agentOutput.substring(0, config.maxOutputLength || 10000),
+ existingMemories: existingMemories || 'No existing memories yet.'
};
let prompt = template;
@@ -105,13 +130,17 @@ async function buildClassificationPrompt(task, agentOutput, config) {
/**
* Fallback prompt if template not found
*/
-function buildFallbackPrompt(task, agentOutput) {
+function buildFallbackPrompt(task, agentOutput, existingMemories = '') {
+ const existingSection = existingMemories
+ ? `\n## Existing Memories (DO NOT duplicate these)\nThe following memories are already stored. Do NOT propose any memory that overlaps with or restates these:\n${existingMemories}\n`
+ : '';
+
return `Analyze this agent output and extract memories about the USER — their values, preferences, work patterns, and qualities they care about.
Task: ${task.description || 'Unknown task'}
Output:
${agentOutput.substring(0, 8000)}
-
+${existingSection}
Return JSON with memories array. Each memory should have:
- type: preference|decision|learning
- category: values|workflow|preferences|communication|aesthetics|patterns
@@ -126,8 +155,9 @@ DO NOT include:
- Task completion summaries (that's git history)
- Generic best practices any developer would know
- One-time code observations or status assessments
+- Anything already captured in the existing memories listed above
-Most outputs should produce ZERO memories. Only extract when you observe something genuinely revealing about the user's values, preferences, or work patterns.
+Most outputs should produce ZERO memories. Only extract when you observe something genuinely revealing about the user's values, preferences, or work patterns that is NOT already stored.
Return: {"memories": [...], "rejected": [...]}`;
}
diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.js
index 07b3ecc259..bb739b06a6 100644
--- a/server/services/memoryExtractor.js
+++ b/server/services/memoryExtractor.js
@@ -5,12 +5,14 @@
* Supports structured MEMORY blocks and pattern-based extraction.
*/
-import { createMemory } from './memoryBackend.js';
+import { createMemory, searchMemories, getMemories } from './memoryBackend.js';
import { generateMemoryEmbedding } from './memoryEmbeddings.js';
import { cosEvents } from './cosEvents.js';
import * as notifications from './notifications.js';
import { classifyMemories, isAvailable as isClassifierAvailable } from './memoryClassifier.js';
+const DEDUP_SIMILARITY_THRESHOLD = 0.82;
+
/**
* Parse structured MEMORY blocks from agent output
* Format:
@@ -133,18 +135,17 @@ function extractTaskContext(_task, _output, _success) {
return [];
}
+const normalizeText = s => (s || '').toLowerCase().replace(/\s+/g, ' ').trim();
+
/**
- * Deduplicate memories by content similarity
- * Uses simple string comparison for now
+ * Deduplicate memories within a single extraction batch
*/
function deduplicateMemories(memories) {
const unique = [];
const seen = new Set();
for (const memory of memories) {
- // Normalize content for comparison
- const normalized = memory.content.toLowerCase().replace(/\s+/g, ' ').trim();
- const key = `${memory.type}:${normalized.substring(0, 100)}`;
+ const key = `${memory.type}:${normalizeText(memory.content).substring(0, 100)}`;
if (!seen.has(key)) {
seen.add(key);
@@ -155,6 +156,38 @@ function deduplicateMemories(memories) {
return unique;
}
+/**
+ * Check if a proposed memory duplicates an existing active or pending memory.
+ * Uses vector similarity for active memories and text prefix matching for pending.
+ */
+async function findExistingDuplicate(embedding, content, pendingMemories) {
+ if (embedding) {
+ const results = await searchMemories(embedding, {
+ minRelevance: DEDUP_SIMILARITY_THRESHOLD,
+ limit: 3
+ }).catch(err => {
+ console.log(`⚠️ Dedup vector search failed: ${err.message}`);
+ return { memories: [] };
+ });
+
+ if (results.memories.length > 0) {
+ return results.memories[0];
+ }
+ }
+
+ // Also check pending_approval memories (searchMemories only returns active)
+ if (pendingMemories.length > 0) {
+ const normalizedContent = normalizeText(content).substring(0, 80);
+ for (const mem of pendingMemories) {
+ if (normalizeText(mem.content).substring(0, 80) === normalizedContent) {
+ return mem;
+ }
+ }
+ }
+
+ return null;
+}
+
/**
* Main extraction function
* Processes agent output and creates memories
@@ -226,35 +259,40 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
const highConfidence = unique.filter(m => m.confidence >= 0.85);
const mediumConfidence = unique.filter(m => m.confidence >= 0.7 && m.confidence < 0.85);
- const created = [];
-
- // Extract appId from task metadata if available
const sourceAppId = task?.metadata?.app || null;
- // Auto-save high confidence memories
- for (const mem of highConfidence) {
+ // Pre-fetch pending memories once for dedup checks across both loops
+ const pendingForDedup = await getMemories({ status: 'pending_approval' })
+ .catch(err => {
+ console.log(`⚠️ Failed to load pending memories for dedup: ${err.message}`);
+ return { memories: [] };
+ });
+
+ let skippedDuplicates = 0;
+
+ async function dedupAndCreate(mem, extraFields = {}) {
const embedding = await generateMemoryEmbedding(mem);
- const memory = await createMemory({
- ...mem,
- sourceAgentId: agentId,
- sourceTaskId: taskId,
- sourceAppId
+ const existing = await findExistingDuplicate(embedding, mem.content, pendingForDedup.memories);
+ if (existing) {
+ console.log(`🧠 Skipping duplicate memory (similar to "${normalizeText(existing.content).substring(0, 60)}…")`);
+ skippedDuplicates++;
+ return null;
+ }
+ return createMemory({
+ ...mem, sourceAgentId: agentId, sourceTaskId: taskId, sourceAppId, ...extraFields
}, embedding);
- created.push(memory);
}
- // Store medium confidence memories as pending_approval
+ const created = [];
+ for (const mem of highConfidence) {
+ const memory = await dedupAndCreate(mem);
+ if (memory) created.push(memory);
+ }
+
const pendingMemories = [];
for (const mem of mediumConfidence) {
- const embedding = await generateMemoryEmbedding(mem);
- const memory = await createMemory({
- ...mem,
- sourceAgentId: agentId,
- sourceTaskId: taskId,
- sourceAppId,
- status: 'pending_approval'
- }, embedding);
- pendingMemories.push(memory);
+ const memory = await dedupAndCreate(mem, { status: 'pending_approval' });
+ if (memory) pendingMemories.push(memory);
}
if (pendingMemories.length > 0) {
@@ -295,12 +333,16 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu
}
}
+ if (skippedDuplicates > 0) {
+ console.log(`🧠 Skipped ${skippedDuplicates} duplicate memories from agent ${agentId}`);
+ }
console.log(`🧠 Extracted ${created.length} memories from agent ${agentId}`);
cosEvents.emit('memory:extracted', {
agentId,
taskId,
count: created.length,
- pendingApproval: pendingMemories.length
+ pendingApproval: pendingMemories.length,
+ skippedDuplicates
});
return {