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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: record which memories were injected into each agent run's prompt (#10495)
[._.]/ Adam Eivyc43bcdc357d8
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 379a12f064..d3cc37a767 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -40,6 +40,7 @@ import { useSocketResource } from '../../../hooks/useSocketResource';import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { AgentProgress, AgentRuntimeStatus } from './AgentRuntimeStatus';+import AgentMemoriesUsed from './AgentMemoriesUsed';import { agentIssueLinkifier } from '../../../lib/issueRefs';import { harnessLabel, providerHarnessId } from '../../../utils/providerHarnesses';@@ -924,6 +925,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,pid={agent.pid}/><TaskDescription agent={agent} remote={remote} />+ <AgentMemoriesUsed injectedMemories={agent.metadata?.injectedMemories} />{/* JIRA ticket info */}{agent.metadata?.jiraTicketId && (diff --git a/client/src/components/cos/tabs/AgentMemoriesUsed.jsx b/client/src/components/cos/tabs/AgentMemoriesUsed.jsxnew file mode 100644index 0000000000..60817dfe47--- /dev/null+++ b/client/src/components/cos/tabs/AgentMemoriesUsed.jsx@@ -0,0 +1,35 @@+import { Link } from 'react-router';+import { Brain } from 'lucide-react';+import { formatPercent } from '../../../utils/formatters';++/**+ * "Memories used" — the memories whose text was injected into this run's prompt+ * (`agent.metadata.injectedMemories`, #10495). Each links to the Memory tab's+ * detail view. Renders nothing for a run that had none, and for a record+ * written before the field existed.+ */+export default function AgentMemoriesUsed({ injectedMemories }) {+ if (!Array.isArray(injectedMemories) || injectedMemories.length === 0) return null;+ return (+ <details className="mb-2 text-xs text-gray-400">+ <summary className="cursor-pointer min-h-[32px] inline-flex items-center gap-1.5 select-none hover:text-gray-200">+ <Brain size={12} aria-hidden="true" />+ Memories used ({injectedMemories.length})+ </summary>+ <ul className="mt-1 flex flex-wrap gap-1.5">+ {injectedMemories.map(m => (+ <li key={m.id}>+ <Link+ to={`/cos/memory/${encodeURIComponent(m.id)}`}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-port-border font-mono text-port-accent hover:text-port-accent/80"+ title={m.relevance != null ? `Relevance ${formatPercent(m.relevance * 100, { decimals: 0 })}` : 'Open memory'}+ >+ {m.id.slice(0, 8)}+ {m.version != null && <span className="text-gray-500">v{m.version}</span>}+ </Link>+ </li>+ ))}+ </ul>+ </details>+ );+}diff --git a/client/src/components/cos/tabs/AgentMemoriesUsed.test.jsx b/client/src/components/cos/tabs/AgentMemoriesUsed.test.jsxnew file mode 100644index 0000000000..66b5420e34--- /dev/null+++ b/client/src/components/cos/tabs/AgentMemoriesUsed.test.jsx@@ -0,0 +1,19 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import AgentMemoriesUsed from './AgentMemoriesUsed';++const renderList = (injectedMemories) => render(<MemoryRouter><AgentMemoriesUsed injectedMemories={injectedMemories} /></MemoryRouter>);++describe('AgentMemoriesUsed', () => {+ it('links each injected memory to its Memory tab detail route', () => {+ renderList([{ id: 'abcdef12-0000', version: null, relevance: 0.5 }]);+ expect(screen.getByText('Memories used (1)')).toBeTruthy();+ expect(screen.getByRole('link', { name: /abcdef12/ }).getAttribute('href')).toBe('/cos/memory/abcdef12-0000');+ });++ it('renders nothing for an empty list or a record that predates the field', () => {+ expect(renderList([]).container.innerHTML).toBe('');+ expect(renderList(undefined).container.innerHTML).toBe('');+ });+});diff --git a/client/src/components/cos/tabs/MemoryEditModal.jsx b/client/src/components/cos/tabs/MemoryEditModal.jsxindex aafa8647bf..21b8a2cecb 100644--- a/client/src/components/cos/tabs/MemoryEditModal.jsx+++ b/client/src/components/cos/tabs/MemoryEditModal.jsx@@ -6,6 +6,7 @@ import { FormField } from '../../ui/FormField';import * as api from '../../../services/api';import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';import { getAppName, formatPercent } from '../../../utils/formatters';+import MemoryRunsUsedBy from './MemoryRunsUsedBy';export default function MemoryEditModal({ memory, apps, onSave, onClose }) {const [formData, setFormData] = useState({@@ -248,6 +249,8 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {</div></div>+ {memory.id && <MemoryRunsUsedBy memoryId={memory.id} />}+{/* Importance and Confidence */}<div className="flex flex-col sm:flex-row gap-4"><FormFielddiff --git a/client/src/components/cos/tabs/MemoryRunsUsedBy.jsx b/client/src/components/cos/tabs/MemoryRunsUsedBy.jsxnew file mode 100644index 0000000000..2b1cbfcd33--- /dev/null+++ b/client/src/components/cos/tabs/MemoryRunsUsedBy.jsx@@ -0,0 +1,39 @@+import { useState, useEffect } from 'react';+import { Link } from 'react-router';+import * as api from '../../../services/api';+import { formatDateTime } from '../../../utils/formatters';++/**+ * "Used by recent runs" — agent runs whose prompt included this memory, from a+ * bounded scan of recent run records (GET /api/memory/:id/runs, #10495).+ */+export default function MemoryRunsUsedBy({ memoryId }) {+ const [runs, setRuns] = useState(null);++ useEffect(() => {+ let active = true;+ setRuns(null);+ api.getMemoryRuns(memoryId, { silent: true })+ .then(res => { if (active) setRuns(res?.runs || []); })+ .catch(() => { if (active) setRuns([]); });+ return () => { active = false; };+ }, [memoryId]);++ if (!runs || runs.length === 0) return null;+ return (+ <div>+ <span className="block text-sm text-gray-400 mb-2">Used by recent runs</span>+ <ul className="space-y-1 text-xs text-gray-400">+ {runs.map(run => (+ <li key={run.runId} className="flex flex-wrap items-center gap-2">+ {run.agentId+ ? <Link to={`/cos/agents/${encodeURIComponent(run.agentId)}`} className="font-mono text-port-accent hover:text-port-accent/80">{run.agentId.slice(0, 8)}</Link>+ : <span className="font-mono">{run.runId.slice(0, 8)}</span>}+ {run.startTime && <span>{formatDateTime(run.startTime)}</span>}+ {run.success === false && <span className="text-port-error">failed</span>}+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsxindex 162591aae4..3985bde445 100644--- a/client/src/components/cos/tabs/MemoryTab.jsx+++ b/client/src/components/cos/tabs/MemoryTab.jsx@@ -1,5 +1,5 @@-import { useState, useEffect, useCallback, useRef, lazy, Suspense } from 'react';-import { useSearchParams } from 'react-router';+import { useState, useEffect, useCallback, useRef, useMemo, lazy, Suspense } from 'react';+import { useNavigate, useParams, useSearchParams } from 'react-router';import {Trash2, X, Check, XCircle, Pencil, AlertTriangle, Brain, Bot} from 'lucide-react';import toast from '../../ui/Toast';import Banner from '../../ui/Banner';@@ -41,6 +41,16 @@ export default function MemoryTab({ apps = [] }) {const [embeddingStatus, setEmbeddingStatus] = useState(null);const [backendStatus, setBackendStatus] = useState(null);const [editingMemory, setEditingMemory] = useState(null);+ // /cos/memory/:id deep-links one memory (e.g. from an agent card's "Memories+ // used"). The shared `cos/:tab/:agentId` route names that segment `agentId`.+ const { agentId: linkedMemoryId } = useParams();+ const navigate = useNavigate();+ const linkedMemory = useMemo(() => (linkedMemoryId ? { id: linkedMemoryId } : null), [linkedMemoryId]);+ const openMemory = editingMemory || linkedMemory;+ const closeMemory = useCallback(() => {+ setEditingMemory(null);+ if (linkedMemoryId) navigate('/cos/memory', { replace: true });+ }, [linkedMemoryId, navigate]);const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();// Embedding provider/model configuration@@ -503,15 +513,16 @@ export default function MemoryTab({ apps = [] }) {)}{/* Edit Modal */}- {editingMemory && (+ {openMemory && (<MemoryEditModal- memory={editingMemory}+ key={openMemory.id}+ memory={openMemory}apps={apps}onSave={() => {- setEditingMemory(null);+ closeMemory();fetchData();}}- onClose={() => setEditingMemory(null)}+ onClose={closeMemory}/>)}</div>diff --git a/client/src/services/apiMemory.js b/client/src/services/apiMemory.jsindex 51c838fdc1..4c6fcc16cd 100644--- a/client/src/services/apiMemory.js+++ b/client/src/services/apiMemory.js@@ -16,6 +16,7 @@ export const getMemories = (options = {}) => {return request(`/memory?${params}`);};export const getMemory = (id) => request(`/memory/${id}`);+export const getMemoryRuns = (id, options) => request(`/memory/${id}/runs`, options);export const updateMemory = (id, data, options = {}) => request(`/memory/${id}`, {method: 'PUT',body: JSON.stringify(data),diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 7f340fc94d..1a9ee340f6 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -62,6 +62,7 @@ export function buildAgentRegistration({executionMode,publicReviewPosture,resolvedAppName,+ injectedMemories = [],}) {return {instanceId,@@ -259,6 +260,9 @@ export function buildAgentRegistration({// to avoid provisioning a nested worktree. Preserve that distinction in// the run record so completion diagnostics cannot mistake the claim path// for the generic commit-only handoff.+ // Which memories steered this run's prompt ([{ id, version, relevance }]).+ // Empty for a run whose prompt carried none; absent only on a pre-#10495 record.+ injectedMemories,configClaimFlow: claimFlowTask,// The claim branch this run owns (or `claimPicksOwnBranch` when it picks one// itself, as a swarm orchestrator does). The `claim-*` tree is cut by thediff --git a/server/routes/memory.js b/server/routes/memory.jsindex 99a08710ed..b9cb555945 100644--- a/server/routes/memory.js+++ b/server/routes/memory.js@@ -7,6 +7,7 @@ import * as memory from '../services/memoryBackend.js';import { ensureBackend } from '../services/memoryBackend.js';import * as embeddings from '../services/memoryEmbeddings.js';import * as memorySync from '../services/memorySync.js';+import { findRecentRunsUsingMemory } from '../services/memoryRunUsage.js';import { checkHealth } from '../lib/db.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, parsePagination } from '../lib/validation.js';@@ -179,6 +180,12 @@ router.get('/:id/related', asyncHandler(async (req, res) => {res.json(related);}));+// GET /api/memory/:id/runs - Recent agent runs whose prompt included this memory+router.get('/:id/runs', asyncHandler(async (req, res) => {+ const { id } = validateRequest(memoryIdParamSchema, req.params);+ res.json({ runs: await findRecentRunsUsingMemory(id) });+}));+// PUT /api/memory/:id - Update a memoryrouter.put('/:id', asyncHandler(async (req, res) => {const data = validateRequest(memoryUpdateSchema, req.body);diff --git a/server/routes/memory.test.js b/server/routes/memory.test.jsindex 51b685f909..b771ffd35b 100644--- a/server/routes/memory.test.js+++ b/server/routes/memory.test.js@@ -40,6 +40,10 @@ vi.mock('../services/memoryEmbeddings.js', () => ({checkAvailability: vi.fn()}));+vi.mock('../services/memoryRunUsage.js', () => ({+ findRecentRunsUsingMemory: vi.fn()+}));+// Mock the sync servicevi.mock('../services/memorySync.js', () => ({getChangesSince: vi.fn(),@@ -49,8 +53,19 @@ vi.mock('../services/memorySync.js', () => ({import { ensureBackend, getMemories, getTimeline, archiveMemory, purgeMemory, applyDecay } from '../services/memoryBackend.js';import { checkHealth } from '../lib/db.js';import * as memorySync from '../services/memorySync.js';+import { findRecentRunsUsingMemory } from '../services/memoryRunUsage.js';describe('Memory Routes', () => {+ it('GET /:id/runs lists recent runs that used the memory (#10495)', async () => {+ const app = express();+ app.use('/api/memory', memoryRoutes);+ findRecentRunsUsingMemory.mockResolvedValue([{ runId: 'r1', agentId: 'a1' }]);+ const res = await request(app).get('/api/memory/mem-1/runs');+ expect(res.status).toBe(200);+ expect(res.body.runs).toEqual([{ runId: 'r1', agentId: 'a1' }]);+ expect(findRecentRunsUsingMemory).toHaveBeenCalledWith('mem-1');+ });+let app;beforeEach(() => {diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 12b69736b0..87db61fe7e 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -344,6 +344,9 @@ function fillReconcileAgentId(task, agentId) {* `{ userPrompt, systemPrompt }` (see `buildLightContextPromptParts`) instead* of a single string, for providers spawned with `--append-system-prompt-file`.* Ignored on the full/api path, which always returns a string.+ * @param {object} [options.promptTrace] - Out-parameter: the full path sets+ * `promptTrace.injectedMemories` to the `[{ id, version, relevance }]` list+ * whose text went into the prompt. Untouched on the light path (no memory).*/export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, options = {}) {// Undo the queue-path description/context split so a round-tripped generated@@ -437,9 +440,11 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// Architect doctrine for an orchestrated run (#5992). '' for every direct-mode// task, which is the default, so this is inert unless a profile is configured.const orchestrationSection = buildOrchestrationDoctrineSection(task);- const { memorySection, agentInstructionsSection, digitalTwinSection } = await loadDeveloperContext(+ const { memorySection, injectedMemories, agentInstructionsSection, digitalTwinSection } = await loadDeveloperContext(task, config, workspaceDir, skipDevContext,);+ // Hand the memory lineage to the caller that creates the run record (#10495).+ if (options.promptTrace) options.promptTrace.injectedMemories = injectedMemories;// Build context compaction section if task is retrying after a context-limit failureconst compactionSection = task.metadata?.compaction?.needed ? buildCompactionSection(task) : '';@@ -649,10 +654,14 @@ function resolveTaskMetadataFlags(task, worktreeInfo) {/** Load independent developer context concurrently, unless this is a content-only task. */async function loadDeveloperContext(task, config, workspaceDir, skipDevContext) {if (skipDevContext) {- return { memorySection: null, agentInstructionsSection: null, digitalTwinSection: null };+ return { memorySection: null, injectedMemories: [], agentInstructionsSection: null, digitalTwinSection: null };}+ let injectedMemories = [];const [memorySection, agentInstructionsSection, digitalTwinSection] = await Promise.all([- getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })+ getMemorySection(task, {+ maxTokens: config.memory?.maxContextTokens || 2000,+ onInjected: (injected) => { injectedMemories = injected; },+ }).catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),getAgentInstructionsContext(workspaceDir).catch(err => { console.log(`⚠️ Agent instructions retrieval failed: ${err.message}`); return null; }),@@ -660,7 +669,7 @@ async function loadDeveloperContext(task, config, workspaceDir, skipDevContext)getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000, personaId: 'active' }).catch(err => { console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`); return null; }),]);- return { memorySection, agentInstructionsSection, digitalTwinSection };+ return { memorySection, injectedMemories, agentInstructionsSection, digitalTwinSection };}/**diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 4cd5825426..a4e88b4a7b 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -3105,7 +3105,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {}, '/r', null, { providerType: 'api' });expect(prompt).toContain('Example Global Instructions');expect(prompt).toMatch(/^## Instructions$/m);- expect(getMemorySection).toHaveBeenLastCalledWith(expect.anything(), { maxTokens: 2000 });+ expect(getMemorySection).toHaveBeenLastCalledWith(expect.anything(), { maxTokens: 2000, onInjected: expect.any(Function) });expect(getDigitalTwinForPrompt).toHaveBeenLastCalledWith({ maxTokens: 1200, personaId: 'active' });expect(log).toHaveBeenCalledWith('⚠️ Memory retrieval failed: memory unavailable');expect(log).toHaveBeenCalledWith('⚠️ Digital twin context retrieval failed: twin unavailable');@@ -3131,6 +3131,22 @@ describe('discardWorktree (reasoning-only) completion contract', () => {vi.mocked(getToolsSummaryForPrompt).mockResolvedValue('');});+ it('reports the memories retrieval injected through promptTrace for the run record (#10495)', async () => {+ const injected = [{ id: 'mem-1', version: null, relevance: 0.8 }];+ vi.mocked(getMemorySection).mockClear().mockImplementationOnce(async (_task, opts) => {+ opts.onInjected(injected);+ return '## Memory Context\nTRACE_MEMORY_SENTINEL';+ });+ const promptTrace = {};+ const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, { providerType: 'api', promptTrace });+ expect(prompt).toContain('TRACE_MEMORY_SENTINEL');+ expect(promptTrace.injectedMemories).toEqual(injected);++ const emptyTrace = {};+ await buildAgentPrompt(makeTask(), {}, '/r', null, { providerType: 'api', promptTrace: emptyTrace });+ expect(emptyTrace.injectedMemories).toEqual([]);+ });+it('a CD scratch cwd does not leak repo AGENTS.md into getAgentInstructionsContext', async () => {// Mirrors the fixture-pinning in this block: a dir with no CLAUDE.md// (the CD scratch shape) must not surface content that lives in a siblingdiff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex a0b25d922b..4ad5e4c6c9 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -26,8 +26,11 @@ const RUNS_DIR = PATHS.runs;* @param {{ id: string, name: string, defaultModel?: string }} options.provider* @param {string} options.workspacePath* @param {string} [options.appName] - Defaults to 'portos'.+ * @param {Array<{ id: string, version: number|null, relevance: number|null }>} [options.injectedMemories]+ * The memories whose text went into the prompt. Always stored (empty list+ * when none) so a missing field only ever means a pre-upgrade record.*/-export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName }) {+export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName, injectedMemories }) {const runId = uuidv4();const runDir = join(RUNS_DIR, runId);@@ -50,6 +53,7 @@ export async function createAgentRun({ agentId, task, model, provider, workspace// Full prompt size (chars) for input-token estimation on completion —// `prompt` above is truncated for display.promptLength: (task.description || '').length,+ injectedMemories: Array.isArray(injectedMemories) ? injectedMemories : [],startTime: new Date().toISOString(),endTime: null,duration: null,diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex bb1f891491..dc148b6e1b 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -117,7 +117,9 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {const privatePrompt = privateSecurity? await import('./privateSecurityAssessment.js').then(({ preparePrivateSecurityAssessment }) => preparePrivateSecurityAssessment(task, provider, selectedModel)): null;+ const promptTrace = {};const promptResult = privateSecurity ? privatePrompt : await buildAgentPrompt(task, config, workspacePath, worktreeInfo, {+ promptTrace,providerType: provider.type,providerId: provider.id,providerCommand: provider.command,@@ -178,6 +180,7 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {: resolveRepoForgeTarget(workspacePath),sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,]);+ const injectedMemories = promptTrace.injectedMemories || [];let systemPromptFile = null;const agentDir = join(AGENTS_DIR, agentId);const { runId } = await withBackupAssetPublication(async () => {@@ -196,6 +199,7 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {provider,workspacePath,appName: resolvedAppName,+ injectedMemories,});await registerAgent(agentId, task.id, buildAgentRegistration({task,@@ -221,6 +225,7 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {executionMode,publicReviewPosture,resolvedAppName,+ injectedMemories,}));return { runId };});diff --git a/server/services/memoryLineage.test.js b/server/services/memoryLineage.test.jsnew file mode 100644index 0000000000..0d3f4f90e7--- /dev/null+++ b/server/services/memoryLineage.test.js@@ -0,0 +1,67 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, readFile, rm } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ return makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('memory-lineage-') });+});+vi.mock('./memoryBackend.js', () => ({+ DEFAULT_MEMORY_CONFIG: { maxContextTokens: 2000, minRelevanceThreshold: 0.5 },+ getMemories: vi.fn(),+ getMemory: vi.fn(async id => ({ id, type: 'preference', content: `content of ${id}`, importance: 0.9 })),+ searchMemories: vi.fn(), hybridSearchMemories: vi.fn(),+}));+vi.mock('./memoryEmbeddings.js', () => ({+ estimateTokens: text => Math.ceil(text.length / 4),+ generateQueryEmbedding: vi.fn(), truncateToTokens: vi.fn(),+}));+vi.mock('./usage.js', () => ({ recordSession: async () => {} }));+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent: async () => {} }));++const { PATHS } = await import('../lib/fileUtils.js');+const { getMemories } = await import('./memoryBackend.js');+const { getMemorySection } = await import('./memoryRetriever.js');+const { createAgentRun } = await import('./agentRunTracking.js');+const { findRecentRunsUsingMemory } = await import('./memoryRunUsage.js');++const provider = { id: 'example-provider', name: 'Example', defaultModel: 'example-model' };+const spawn = async (agentId, injectedMemories) => {+ const { runDir } = await createAgentRun({ agentId, task: { id: `task-${agentId}`, description: 'Example prompt' }, provider, injectedMemories });+ return JSON.parse(await readFile(join(runDir, 'metadata.json'), 'utf8'));+};++beforeEach(async () => {+ await rm(PATHS.data, { recursive: true, force: true });+ await mkdir(PATHS.runs, { recursive: true });+});+afterAll(cleanupTempDataRoots);++describe('memory lineage: retrieval -> run record (#10495)', () => {+ it('stores the ids that went into the prompt section on the run, and finds the run from the memory', async () => {+ vi.mocked(getMemories).mockResolvedValue({ memories: [{ id: 'mem-a' }, { id: 'mem-b' }] });+ let injected = [];+ const section = await getMemorySection({}, { onInjected: list => { injected = list; } });+ expect(injected.map(m => m.id)).toEqual(['mem-a', 'mem-b']);+ expect(injected[0]).toEqual({ id: 'mem-a', version: null, relevance: 0.9 });+ for (const m of injected) expect(section).toContain(`content of ${m.id}`);++ const metadata = await spawn('agent-1', injected);+ expect(metadata.injectedMemories).toEqual(injected);++ const runs = await findRecentRunsUsingMemory('mem-b');+ expect(runs).toHaveLength(1);+ expect(runs[0]).toMatchObject({ runId: metadata.id, agentId: 'agent-1' });+ expect(await findRecentRunsUsingMemory('mem-unused')).toEqual([]);+ });++ it('stores an empty list (not a missing field) when no memory was injected', async () => {+ vi.mocked(getMemories).mockResolvedValue({ memories: [] });+ let injected;+ expect(await getMemorySection({}, { onInjected: list => { injected = list; } })).toBeNull();+ expect(injected).toEqual([]);+ expect((await spawn('agent-2', injected)).injectedMemories).toEqual([]);+ expect((await spawn('agent-3', undefined)).injectedMemories).toEqual([]);+ });+});diff --git a/server/services/memoryRetriever.js b/server/services/memoryRetriever.jsindex 39c7a49669..d336dbe0fc 100644--- a/server/services/memoryRetriever.js+++ b/server/services/memoryRetriever.js@@ -13,6 +13,9 @@ import { DEFAULT_MEMORY_CONFIG } from './memoryBackend.js';// Search mode preference: 'hybrid' (FTS + vector) or 'vector' (embedding-only)const SEARCH_MODE = 'hybrid';+// The memory types formatForPrompt renders; any other type is left out of the prompt.+const FORMATTED_TYPES = new Set(['preference', 'fact', 'learning', 'observation', 'decision', 'context']);+/*** Get relevant memories for a task* Returns formatted text ready for injection into agent prompt@@ -228,11 +231,32 @@ export function formatForPrompt(memories, maxTokens = DEFAULT_MEMORY_CONFIG.maxC* Main entry point for subAgentSpawner integration*/export async function getMemorySection(task, options = {}) {+ const { section, injected } = await getMemoryInjection(task, options);+ // Lets a caller that builds a run record (agentPromptBuilder) capture the+ // lineage without changing this function's string-or-null return contract.+ if (typeof options.onInjected === 'function') options.onInjected(injected);+ return section;+}++/**+ * Same retrieval as getMemorySection, but also reports WHICH memories made it+ * into the prompt text: `injected: [{ id, version, relevance }]`. `version` is+ * null until memory versioning lands. Only memories the formatter actually+ * renders are listed (an unrecognised type is dropped from the prompt, so it is+ * dropped here too); `section` is null when nothing relevant was found.+ */+async function getMemoryInjection(task, options = {}) {const memories = await getRelevantMemories(task, options);if (memories.length === 0) {- return null;+ return { section: null, injected: [] };}- return formatForPrompt(memories, options.maxTokens);+ const section = formatForPrompt(memories, options.maxTokens);+ const injected = section+ ? memories+ .filter(m => FORMATTED_TYPES.has(m.type || 'context'))+ .map(m => ({ id: m.id, version: m.version ?? null, relevance: m.relevance ?? null }))+ : [];+ return { section: section || null, injected };}diff --git a/server/services/memoryRunUsage.js b/server/services/memoryRunUsage.jsnew file mode 100644index 0000000000..e9b4e3d177--- /dev/null+++ b/server/services/memoryRunUsage.js@@ -0,0 +1,47 @@+/**+ * Memory → runs lineage: which recent agent runs had a memory injected into+ * their prompt. Run records are files (`data/runs/<runId>/metadata.json`), so+ * this is a bounded scan of the newest run directories rather than an index.+ * Records written before #10495 have no `injectedMemories` and never match.+ */++import { join } from 'path';+import { readdir, stat } from 'fs/promises';+import { PATHS, readJSONFile } from '../lib/fileUtils.js';++export const DEFAULT_RUN_SCAN_LIMIT = 200;++/**+ * @param {string} memoryId+ * @param {{ scanLimit?: number, limit?: number }} [options] - `scanLimit` caps how+ * many of the newest run records are read; `limit` caps matches returned.+ * @returns {Promise<Array<{ runId: string, agentId: string|null, taskId: string|null, startTime: string|null, success: boolean|null, version: number|null, relevance: number|null }>>}+ */+export async function findRecentRunsUsingMemory(memoryId, { scanLimit = DEFAULT_RUN_SCAN_LIMIT, limit = 20 } = {}) {+ const entries = await readdir(PATHS.runs, { withFileTypes: true }).catch(() => []);+ const dirs = await Promise.all(entries+ .filter(e => e.isDirectory())+ .map(async e => ({ name: e.name, mtimeMs: (await stat(join(PATHS.runs, e.name)).catch(() => null))?.mtimeMs ?? 0 })));+ const newest = dirs.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, scanLimit);++ const records = await Promise.all(newest.map(d => readJSONFile(join(PATHS.runs, d.name, 'metadata.json'), null)));+ const matches = [];+ for (const meta of records) {+ const hit = Array.isArray(meta?.injectedMemories)+ ? meta.injectedMemories.find(m => m?.id === memoryId)+ : null;+ if (!hit) continue;+ matches.push({+ runId: meta.id,+ agentId: meta.agentId ?? null,+ taskId: meta.taskId ?? null,+ startTime: meta.startTime ?? null,+ success: meta.success ?? null,+ version: hit.version ?? null,+ relevance: hit.relevance ?? null,+ });+ }+ return matches+ .sort((a, b) => String(b.startTime).localeCompare(String(a.startTime)))+ .slice(0, limit);+}