diff --git a/CHANGELOG.md b/CHANGELOG.md index 28cef905..0245d20b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ the end of this file for historical context. ## [Unreleased] +### Recall response size + +- MCP recall defaults to budgeted context and 8 concise hits, with optional + `k` and `verbose: true` for full nodes and diagnostic traces. +- CLI recall supports `--brief` for concise JSON and `--full` for its existing + detailed structure. Recall vectors require explicit `include_vectors: true` + in verbose MCP output or `--include-vectors` in detailed CLI output. +- CLI hits include observation dates; CLI and MCP share hit formatting. + ### Python SDK and package registry migration - Added `packages/longmemory-py`, a zero-runtime-dependency Python HTTP client diff --git a/docs/cli.md b/docs/cli.md index c5eb8762..44564fbf 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -126,6 +126,26 @@ longmemory recall \ `--mode` is required and accepts `strict`, `historical`, `associative`, or `world_grounded`. Optional flags include `--recorded-time`, `--at`, `--world`, and `--k`. +For agent queries, use `--brief`: + +```bash +longmemory recall "release checklist" --project my-project --mode strict \ + --k 5 --token-budget 300 --brief --json +``` + +Brief JSON contains `ok`, `mode`, `query`, `context` (`text`, `tokens_used`, +`budget`) and `hits` (`id`, `observed_at`, `score`, `status`, `text`). Dates are +epoch milliseconds. Brief output defaults to 8 hits; `--k` accepts 1–1000. +`--token-budget` bounds context text, not the total response or hit text. +Historical brief output keeps the first `k` chronological timeline entries +and builds budgeted context from them. + +The default detailed JSON fields remain available for existing scripts; +`--full` explicitly selects this output. Recall omits nested vectors by +default. Use `--full --include-vectors` to include them for diagnostics. +`--brief` cannot be combined with `--full` or `--include-vectors`. +The existing global `--compact` flag continues to control JSON whitespace. + ## Explain ```bash diff --git a/docs/mcp.md b/docs/mcp.md index fa7e7683..2e4c53c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -79,6 +79,35 @@ versions, bindings, or archive versions. CodeGraph is read-only and provides symbol search, callers, callees, and reverse impact paths from persisted source snapshots. +### Recall output + +`longmemory_recall` returns `context` (`text`, `tokens_used`, `budget`) and +`hits` (`id`, `observed_at`, `score`, `status`, `text`) by default. +`observed_at` is epoch milliseconds. Pass `k` (1–1000) to limit hits; compact +output defaults to 8. `token_budget` limits context text, while each hit keeps +its summary or raw text, so it is not a total response size limit. + +```json +{ + "project_id": "my-project", + "query": "release checklist", + "mode": "strict", + "k": 5, + "token_budget": 300 +} +``` + +Clients that consume full nodes or traces should pass `verbose: true`. This +returns the existing `items`/`context`/`trace` structure, or `timeline`/`trace` +for historical recall, with the existing permission filtering. Without `k`, +verbose output keeps the engine's candidate count. Vectors are omitted from +recall responses unless both `verbose: true` and `include_vectors: true` are +set, including when `LONGMEMORY_MCP_INCLUDE_VECTORS` is enabled globally. + +Historical recall keeps the engine's chronological ordering. Its compact +output applies `k` to the first timeline entries and builds budgeted context +from them; verbose output returns the complete timeline. + Asset catalog calls discover governed Chat Memory, Skill, LLM-Wiki, and CodeGraph records or assemble a target-specific loadout. Asset management is a write tool, requires owner or explicit `manage` ACL, and is blocked by MCP diff --git a/src/cli/cli_app.ts b/src/cli/cli_app.ts index f0850bba..4fbcb64a 100644 --- a/src/cli/cli_app.ts +++ b/src/cli/cli_app.ts @@ -82,7 +82,7 @@ const help = { global_flags: ['--db ', '--project ', '--user ', '--json', '--jsonl', '--pretty', '--compact', '--no-color', '--silent', '--interactive', '--dry-run', '--token-budget ', '--cwd '], commands: [ 'status', 'init', 'doctor', 'serve [--host ] [--port ] [--mcp-http]', 'mcp [--read-only]', - 'ingest "memory" [--stdin] [--type ] [--source ]', 'recall "query" [--mode ]', 'explain ', + 'ingest "memory" [--stdin] [--type ] [--source ]', 'recall "query" --mode [--k ] [--brief | --full] [--include-vectors]', 'explain ', 'timeline ', 'memory list [--limit ] [--status ]', 'maintenance decay [--limit ] [--all]', 'maintenance reinforce ', 'bench', 'project ', @@ -135,4 +135,4 @@ export async function run_cli_app(argv = process.argv.slice(2), env: NodeJS.Proc } export const registered_commands = () => [...commands.keys()]; -export const register_cli_command = (name: string, command: cli_command) => commands.set(name, async () => command); \ No newline at end of file +export const register_cli_command = (name: string, command: cli_command) => commands.set(name, async () => command); diff --git a/src/cli/commands/recall.ts b/src/cli/commands/recall.ts index 1ef06551..fb0bfc45 100644 --- a/src/cli/commands/recall.ts +++ b/src/cli/commands/recall.ts @@ -14,37 +14,46 @@ import type { cli_command } from '../context/cli_context.js'; -import { command_flags, flag, mode_flag, number_flag, positional, require_value, time_flag, with_read_memory } from '../context/cli_context.js'; +import { command_flags, flag, has, mode_flag, number_flag, positional, require_value, time_flag, with_read_memory } from '../context/cli_context.js'; import { badge } from '../theme/badges.js'; import { emit, section } from '../output/pretty.js'; import { panel } from '../output/panel.js'; import { table } from '../output/table.js'; import { resolve_project_scope } from '../context/project_scope.js'; +import { compact_recall, recall_hits, strip_vectors_replacer } from '../../core/recall/response.js'; +import { cli_error, exit_codes } from '../output/errors.js'; export const recall_command: cli_command = async (context) => { - command_flags(context, ['query', 'mode', 'valid-time', 'recorded-time', 'at', 'k', 'world']); + command_flags(context, ['query', 'mode', 'valid-time', 'recorded-time', 'at', 'k', 'world', 'brief', 'full', 'include-vectors']); const query = require_value(positional(context) ?? flag(context, 'query'), 'recall query'); const mode = mode_flag(context); + const brief = has(context, 'brief'); + if (brief && (has(context, 'full') || has(context, 'include-vectors'))) { + throw new cli_error('validation_error', '--brief cannot be combined with --full or --include-vectors', exit_codes.validation); + } + const k = number_flag(context, 'k', brief ? 8 : undefined); + if (k !== undefined && (!Number.isInteger(k) || k < 1 || k > 1000)) { + throw new cli_error('validation_error', '--k must be an integer between 1 and 1000', exit_codes.validation); + } const raw = await with_read_memory(context, async (memory) => { const scope = await resolve_project_scope(memory, context.project_id); return memory.recall({ - text: query, mode, token_budget: context.token_budget, k: number_flag(context, 'k'), world_id: flag(context, 'world') ?? scope.root?.id, + text: query, mode, token_budget: context.token_budget, k, world_id: flag(context, 'world') ?? scope.root?.id, valid_time: time_flag(context, 'valid-time'), recorded_time: time_flag(context, 'recorded-time'), at: time_flag(context, 'at'), permission_context: { user_id: context.user_id, project_ids: [context.project_id] } }); }); const source = raw as Record; - const values: any[] = Array.isArray(source.items) ? source.items : Array.isArray(source.timeline?.entries) ? source.timeline.entries : []; - const hits = values.map((item) => { - const node = item.node; - return { id: node.id, text: node.content.summary || node.content.raw, status: node.state.status, score: item.score ?? item.grounding_score ?? (item.is_current ? 1 : 0.5), grounded: Boolean(node.grounding.worlddb_ref), citation: node.provenance.source_trace[0]?.ref ?? null }; - }); + const hits = recall_hits(raw, brief ? k : undefined); const result = { ok: true, mode, query, context_packet: source.context ?? source.timeline ?? null, hits, citations: hits.flatMap((hit) => hit.citation ? [{ memory_id: hit.id, source: hit.citation }] : []), debug_trace: source.trace ?? {}, ...(source.items ? { items: source.items } : {}), ...(source.timeline ? { timeline: source.timeline } : {}) }; - emit(context, result, () => [ + let output: unknown = result; + if (brief) output = { ok: true, mode, query, ...compact_recall(raw, k, context.token_budget) }; + else if (!has(context, 'include-vectors')) output = JSON.parse(JSON.stringify(result, strip_vectors_replacer)); + emit(context, output, () => [ panel(query, context.colors, { title: 'Recall', kind: 'info', width: context.terminal_width, rows: [['Mode', badge(mode === 'world_grounded' ? 'WORLD' : mode.toUpperCase() as any, true, context.colors)], ['Hits', hits.length], ['Budget', context.token_budget]] }), '', hits.length ? section(context, 'Memory hits', table(hits.map((hit) => ({ status: badge(hit.status === 'active' ? 'ACTIVE' : hit.status === 'superseded' ? 'SUPERSEDED' : 'STALE', true, context.colors), score: Number(hit.score).toFixed(3), memory: hit.text, source: hit.citation ?? '—' })), [ { key: 'status', label: 'STATUS', width: 13 }, { key: 'score', label: 'SCORE', width: 7 }, { key: 'memory', label: 'MEMORY', min: 15 }, { key: 'source', label: 'SOURCE', min: 8 }, ], context.colors, context.terminal_width)) : context.colors.muted('No memories passed the selected recall gates.'), context.debug ? `\n${section(context, 'Debug trace', JSON.stringify(result.debug_trace, null, 2))}` : '', ].filter(Boolean).join('\n')); -}; \ No newline at end of file +}; diff --git a/src/cli/context/config_loader.ts b/src/cli/context/config_loader.ts index 38abfe57..0c83d112 100644 --- a/src/cli/context/config_loader.ts +++ b/src/cli/context/config_loader.ts @@ -24,7 +24,7 @@ export type local_cli_config = { connectors?: Record>; }; -const bool_flags = new Set(['json', 'jsonl', 'pretty', 'compact', 'no-color', 'silent', 'interactive', 'dry-run', 'help', 'version', 'debug', 'mcp-http', 'read-only', 'all', 'stdin', 'force']); +const bool_flags = new Set(['json', 'jsonl', 'pretty', 'compact', 'no-color', 'silent', 'interactive', 'dry-run', 'help', 'version', 'debug', 'mcp-http', 'read-only', 'all', 'stdin', 'force', 'brief', 'full', 'include-vectors']); const global_flags = new Set(['db', 'project', 'user', 'json', 'jsonl', 'pretty', 'compact', 'no-color', 'silent', 'interactive', 'dry-run', 'token-budget', 'cwd', 'help', 'version', 'debug']); export function parse_argv(argv: string[]): parsed_cli { @@ -88,4 +88,4 @@ export function resolved_config(args: parsed_cli, env: NodeJS.ProcessEnv) { user_id: flag_value(args, 'user') ?? env.LONGMEMORY_USER_ID ?? local.user_id ?? 'default', token_budget: budget, }; -} \ No newline at end of file +} diff --git a/src/core/recall/response.ts b/src/core/recall/response.ts new file mode 100644 index 00000000..501505da --- /dev/null +++ b/src/core/recall/response.ts @@ -0,0 +1,46 @@ +/* +* __ __ ___ +* / / ____ ____ ____ _/ |/ /__ ____ ___ ____ _______ __ +* / / / __ \/ __ \/ __ `/ /|_/ / _ \/ __ `__ \/ __ \/ ___/ / / / +* / /___/ /_/ / / / / /_/ / / / / __/ / / / / / /_/ / / / /_/ / +* /_____/\____/_/ /_/\__, /_/ /_/\___/_/ /_/ /_/\____/_/ \__, / + /____/ /____/ + * + * cavira oss (c) 2026 - nullure (c) 2026 + * ---------------------------------------------------------- + * file : src/core/recall/response.ts + * usage : formats recall responses for CLI and MCP clients + */ + +import type { long_memory } from '../create_memory.js'; +import { build_context_packet } from './context_builder.js'; + +type recall_result = Awaited>; + +export const strip_vectors_replacer = (key: string, value: unknown) => key === 'vectors' ? undefined : value; + +export function recall_hits(result: recall_result, limit?: number) { + const items = 'items' in result ? result.items : result.timeline.entries; + return items.slice(0, limit).map((item) => { + const node = item.node; + let score: number; + if ('score' in item) score = item.score; + else if ('grounding_score' in item) score = item.grounding_score; + else score = item.is_current ? 1 : 0.5; + return { + id: node.id, observed_at: node.temporal.observed_at, score, + status: node.state.status, text: node.content.summary || node.content.raw, + grounded: Boolean(node.grounding.worlddb_ref), citation: node.provenance.source_trace[0]?.ref ?? null, + }; + }); +} + +export function compact_recall(result: recall_result, limit = 8, token_budget = 2048) { + const context = 'context' in result + ? result.context + : build_context_packet(result.timeline.entries.slice(0, limit), token_budget); + return { + context: { text: context.text, tokens_used: context.tokens_used, budget: context.budget }, + hits: recall_hits(result, limit).map(({ id, observed_at, score, status, text }) => ({ id, observed_at, score, status, text })), + }; +} diff --git a/src/mcp/schemas/tool_schemas.ts b/src/mcp/schemas/tool_schemas.ts index 9df608d0..daf2a426 100644 --- a/src/mcp/schemas/tool_schemas.ts +++ b/src/mcp/schemas/tool_schemas.ts @@ -59,7 +59,9 @@ export const recall_schema = { user_id: optional_text, mode: z.enum(['strict', 'historical', 'associative', 'world_grounded']), token_budget, - include_vectors: z.boolean().optional().describe('Include raw embedding vectors in the response (default false)'), + k: z.number().int().min(1).max(1000).optional().describe('Maximum hits (default 8 in compact output); historical mode limits compact hits only'), + verbose: z.boolean().optional().describe('Return full recall items or timeline and diagnostic trace (default false)'), + include_vectors: z.boolean().optional().default(false).describe('Include raw embedding vectors with verbose output (default false)'), }; export const ingest_schema = { @@ -147,4 +149,3 @@ export const manage_asset_schema = { expires_at: z.number().finite().optional(), labels: z.array(z.string().trim().min(1)).max(100).optional(), payload: z.record(z.string(), z.unknown()).optional(), metadata: z.record(z.string(), z.unknown()).optional(), }; - diff --git a/src/mcp/tools/common.ts b/src/mcp/tools/common.ts index b946548b..d4f58b11 100644 --- a/src/mcp/tools/common.ts +++ b/src/mcp/tools/common.ts @@ -17,11 +17,7 @@ import type { CallToolResult as call_tool_result } from '@modelcontextprotocol/s import type { mcp_runtime } from '../runtime.js'; import { assert_tool_allowed } from '../security/permissions.js'; import type { mcp_tool_name } from '../security/tool_allowlist.js'; - -// Raw embedding vectors are not useful to an MCP client (similarity is already -// exposed via score/breakdown) and can be thousands of tokens per node, repeated -// across every place a node is nested in a response. Hidden by default. -const strip_vectors_replacer = (key: string, value: unknown) => key === 'vectors' ? undefined : value; +import { strip_vectors_replacer } from '../../core/recall/response.js'; const include_vectors_by_default = (env: NodeJS.ProcessEnv = process.env) => { const raw = env.LONGMEMORY_MCP_INCLUDE_VECTORS?.trim().toLowerCase(); @@ -79,4 +75,4 @@ export async function run_audited_tool( }); throw error; } -} \ No newline at end of file +} diff --git a/src/mcp/tools/recall.ts b/src/mcp/tools/recall.ts index 4f2edeef..a48c0ba8 100644 --- a/src/mcp/tools/recall.ts +++ b/src/mcp/tools/recall.ts @@ -18,6 +18,7 @@ import type { mcp_runtime } from '../runtime.js'; import { recall_schema } from '../schemas/tool_schemas.js'; import { recall_permission, resolve_project } from '../security/permissions.js'; import { run_audited_tool } from './common.js'; +import { compact_recall } from '../../core/recall/response.js'; const sanitize_recall = (result: unknown): unknown => { if (!result || typeof result !== 'object') return result; @@ -49,19 +50,21 @@ const sanitize_recall = (result: unknown): unknown => { export function register_recall_tool(server: mcp_server_sdk, runtime: mcp_runtime): void { server.registerTool('longmemory_recall', { - description: 'Recall memory through the selected Hydrograph mode without bypassing gates.', + description: 'Recall memory as budgeted context and concise hits. Use k to limit hits and verbose for full diagnostics; recall gates always apply.', inputSchema: recall_schema, annotations: { readOnlyHint: true, idempotentHint: true }, }, async (input) => run_audited_tool(runtime, 'longmemory_recall', input, async () => { const project_id = resolve_project(runtime.access, input.project_id); const world_id = project_id ? (await runtime.project(project_id)).getProject(project_id).root_world_id : undefined; + const k = input.k ?? (input.verbose ? undefined : 8); const result = await runtime.memory.recall({ text: input.query, mode: input.mode, token_budget: input.token_budget, + k, world_id, permission_context: recall_permission(runtime.access, input.user_id, project_id ?? undefined), }); - return sanitize_recall(result); + return input.verbose ? sanitize_recall(result) : compact_recall(result, k, input.token_budget); })); -} \ No newline at end of file +} diff --git a/tools/check-recall.ts b/tools/check-recall.ts index 6ddce9ab..b5169e88 100644 --- a/tools/check-recall.ts +++ b/tools/check-recall.ts @@ -14,6 +14,112 @@ import assert from 'node:assert/strict'; import { createMemory } from '../src/index.js'; +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { resolve, join } from 'node:path'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { create_longmemory_mcp } from '../src/mcp/mcp_server.js'; +import { run_cli_app } from '../src/cli/cli_app.js'; + +async function cli(db_path: string, args: string[], expected_code = 0) { + const stdout: string[] = []; + const stderr: string[] = []; + const code = await run_cli_app([...args, '--db', db_path, '--project', 'recall-check', '--json'], {}, { + stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value), terminal: false, + }); + assert.equal(code, expected_code, stderr.join('\n')); + return JSON.parse((code === 0 ? stdout : stderr).join('\n')); +} + +async function check_cli_output(db_path: string) { + const args = ['recall', 'release checklist', '--mode', 'strict', '--k', '2', '--token-budget', '300']; + const full = await cli(db_path, [...args, '--full']); + const brief = await cli(db_path, [...args, '--brief']); + const vectors = await cli(db_path, [...args, '--include-vectors']); + assert.equal(full.hits.length, 2); + assert.equal(brief.hits.length, 2); + assert.equal(brief.context.text, full.context_packet.text); + assert.equal(brief.context.tokens_used, full.context_packet.tokens_used); + assert.ok(brief.context.tokens_used <= 300); + assert.deepEqual(brief.hits.map((hit: any) => hit.id), full.hits.map((hit: any) => hit.id)); + assert.ok(brief.hits.every((hit: any) => Number.isFinite(hit.observed_at) && hit.text)); + assert.ok(!('items' in brief) && !('debug_trace' in brief)); + assert.ok(!JSON.stringify(full).includes('"vectors":')); + assert.ok(vectors.items[0].node.vectors.semantic.length > 0); + assert.ok(vectors.context_packet.items[0].vectors.semantic.length > 0); + assert.ok(JSON.stringify(brief).length < JSON.stringify(full).length / 2); + assert.equal((await cli(db_path, ['recall', 'release checklist', '--mode', 'strict', '--brief'])).hits.length, 8); + for (const mode of ['historical', 'associative', 'world_grounded']) { + const result = await cli(db_path, ['recall', 'release checklist', '--mode', mode, '--brief', '--k', '1', '--token-budget', '64']); + assert.ok(result.hits.length <= 1); + assert.ok(result.context.tokens_used <= 64); + } + for (const invalid of [['--brief', '--full'], ['--brief', '--include-vectors'], ['--k', '0'], ['--k', '1.5']]) { + await cli(db_path, [...args, ...invalid], 2); + } +} + +async function check_mcp_output(db_path: string) { + const { server, runtime } = create_longmemory_mcp({ db_path, project_id: 'recall-check', read_only: true, audit_path: null, env: {} }); + const client = new Client({ name: 'recall-check', version: '1' }); + const [client_transport, server_transport] = InMemoryTransport.createLinkedPair(); + await server.connect(server_transport); + await client.connect(client_transport); + const call = async (extra: Record = {}) => { + const result = await client.callTool({ name: 'longmemory_recall', arguments: { query: 'release checklist', mode: 'strict', token_budget: 300, ...extra } }); + assert.ok(!result.isError, JSON.stringify(result)); + const content = (result.content as Array<{ type: string; text: string }>).find((item) => item.type === 'text'); + assert.ok(content); + return JSON.parse(content.text); + }; + try { + assert.equal((await call()).hits.length, 8); + const compact = await call({ k: 2 }); + const verbose = await call({ k: 2, verbose: true }); + assert.equal(compact.hits.length, 2); + assert.equal(verbose.items.length, 2); + assert.equal(compact.context.text, verbose.context.text); + assert.deepEqual(compact.hits.map((hit: any) => hit.id), verbose.items.map((item: any) => item.node.id)); + assert.ok(!('items' in compact) && !('trace' in compact)); + assert.ok(!JSON.stringify(verbose).includes('"vectors":')); + assert.ok((await call({ k: 2, verbose: true, include_vectors: true })).items[0].node.vectors.semantic.length > 0); + assert.ok((await call({ verbose: true })).items.length > 8); + for (const mode of ['historical', 'associative', 'world_grounded']) { + const result = await call({ mode, k: 1, token_budget: 64 }); + assert.ok(result.hits.length <= 1); + assert.ok(result.context.tokens_used <= 64); + const full = await call({ mode, verbose: true }); + assert.ok('trace' in full); + assert.ok(!JSON.stringify(full).includes('"vectors":')); + } + const empty = await call({ mode: 'historical', query: 'qzxnonexistent' }); + assert.equal(empty.hits.length, 0); + assert.equal(empty.context.text, ''); + for (const extra of [{ k: 0 }, { k: 1.5 }, { project_id: 'other-project' }, { user_id: 'other-user' }]) { + const denied = await client.callTool({ name: 'longmemory_recall', arguments: { query: 'release checklist', mode: 'strict', ...extra } }); + assert.equal(denied.isError, true); + } + } finally { + await client.close(); + await server.close(); + await runtime.close(); + } +} + +async function check_recall_transports() { + const temporary_root = resolve('tmp'); + mkdirSync(temporary_root, { recursive: true }); + const directory = mkdtempSync(join(temporary_root, 'recall-check-')); + const db_path = join(directory, 'memory.db'); + try { + await cli(db_path, ['project', 'init']); + for (const topic of ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel', 'india', 'juliet']) { + await cli(db_path, ['ingest', `The ${topic} release checklist lives in docs/${topic}.md.`, '--external=true']); + } + await check_cli_output(db_path); + await check_mcp_output(db_path); + } finally { rmSync(directory, { recursive: true, force: true }); } +} async function main() { const memory = createMemory({ store: 'memory', embedding_dimension: 2 }); @@ -56,7 +162,8 @@ async function main() { const latest = await preferences.recall({ text: 'Which mode do I prefer now?', mode: 'associative', vector: [1, 0], k: 1 }); assert.ok('context' in latest && latest.context.evidence[0].text.includes('high contrast'), 'current questions should follow transitive supersession chains'); } finally { await preferences.close(); } - console.log('recall:check: ingest, strict, historical, and associative recall all behaved as expected.'); + await check_recall_transports(); + console.log('recall:check: core recall, CLI and MCP output, limits, vectors and scope checks passed.'); } main().catch((error) => {