Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/cli/cli_app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const help = {
global_flags: ['--db <path>', '--project <id>', '--user <id>', '--json', '--jsonl', '--pretty', '--compact', '--no-color', '--silent', '--interactive', '--dry-run', '--token-budget <number>', '--cwd <path>'],
commands: [
'status', 'init', 'doctor', 'serve [--host <host>] [--port <port>] [--mcp-http]', 'mcp [--read-only]',
'ingest "memory" [--stdin] [--type <type>] [--source <source>]', 'recall "query" [--mode <mode>]', 'explain <memory-id>',
'ingest "memory" [--stdin] [--type <type>] [--source <source>]', 'recall "query" --mode <mode> [--k <n>] [--brief | --full] [--include-vectors]', 'explain <memory-id>',
'timeline <entity|project|memory>', 'memory list [--limit <n>] [--status <status>]',
'maintenance decay [--limit <n>] [--all]', 'maintenance reinforce <memory-id>',
'bench', 'project <init|context|handoff|decisions|tasks|conflicts>',
Expand Down Expand Up @@ -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);
export const register_cli_command = (name: string, command: cli_command) => commands.set(name, async () => command);
29 changes: 19 additions & 10 deletions src/cli/commands/recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any>;
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'));
};
};
4 changes: 2 additions & 2 deletions src/cli/context/config_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export type local_cli_config = {
connectors?: Record<string, Record<string, unknown>>;
};

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 {
Expand Down Expand Up @@ -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,
};
}
}
46 changes: 46 additions & 0 deletions src/core/recall/response.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<long_memory['recall']>>;

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 })),
};
}
5 changes: 3 additions & 2 deletions src/mcp/schemas/tool_schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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(),
};

8 changes: 2 additions & 6 deletions src/mcp/tools/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -79,4 +75,4 @@ export async function run_audited_tool(
});
throw error;
}
}
}
9 changes: 6 additions & 3 deletions src/mcp/tools/recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}));
}
}
Loading
Loading