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
10 changes: 9 additions & 1 deletion src/cli/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,15 @@ export default defineCommand({
}
const limit = parsePositiveInt(args.limit as string | undefined, 10);
const quality = coerceRetrievalQuality(args.quality as string | undefined);
const result = await compactSearch({ query, limit, quality, projectId: project.id, reader }, 'cli');
const status = args.status ? coerceObservationStatus(args.status) : undefined;
const result = await compactSearch({
query,
limit,
quality,
projectId: project.id,
reader,
...(status ? { status } : {}),
}, 'cli');
emitResult({ project, entries: result.entries, retrieval: result.receipt }, result.formatted, asJson);
return;
}
Expand Down
2 changes: 2 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,15 @@ const main = defineCommand({
query: { type: 'string', description: 'Search query (also accepts the first positional argument)', required: false },
limit: { type: 'string', description: 'Maximum results' },
quality: { type: 'string', description: 'Retrieval profile: fast, balanced (default), or thorough' },
status: { type: 'string', description: 'Observation status: active, resolved, or archived' },
json: { type: 'boolean', description: 'Emit machine-readable JSON output' },
},
async run({ args }) {
await runMemoryShortcut('search', {
query: args.query ?? (args._ as string[] | undefined)?.[0],
limit: args.limit,
quality: args.quality,
status: args.status,
json: args.json,
});
},
Expand Down
78 changes: 78 additions & 0 deletions src/search/match-reasons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* 向量排序留下和纯词法 fuzzy 分开的标记。
* mode 为 vector 或 vector-only 时,没有字段贴上就标 vector,不再只剩 fuzzy。
*/
export function labelMatchReasons(fieldHits: readonly string[], mode: string): string[] {
const reasons = [...fieldHits];
const rankedByVector = mode === 'vector' || mode.startsWith('vector-only') || mode.startsWith('vector ');
if (reasons.length === 0) reasons.push(rankedByVector ? 'vector' : 'fuzzy');
else if (rankedByVector && !reasons.includes('vector')) reasons.push('vector');
return reasons;
}

const OVERLAP_SYNONYMS: Array<[string, string[]]> = [
['密钥', ['凭据', 'credential', 'secret']],
['泄露', ['leak']],
['复盘', ['收尾']],
];

export function queryOverlapTokens(query: string): string[] {
const raw = query.normalize('NFKC').toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [];
const tokens = new Set<string>();
for (const token of raw) {
if (token.length > 1) tokens.add(token);
for (const run of token.match(/[\u4e00-\u9fff]+/gu) ?? []) {
for (let index = 0; index < run.length - 1; index += 1) tokens.add(run.slice(index, index + 2));
for (const [needle, extras] of OVERLAP_SYNONYMS) {
if (!run.includes(needle)) continue;
for (const extra of extras) tokens.add(extra);
}
}
}
return [...tokens];
}

export function textOverlap(text: string, tokens: readonly string[]): number {
const haystack = text.toLowerCase();
return tokens.reduce((count, token) => count + (haystack.includes(token) ? 1 : 0), 0);
}

/**
* 窗口里词重叠更少的位置,换成窗口外重叠严格更多的近邻。
* 第 1 名保持不动。重叠数相同则保持原来的顺序。
*/
export function promoteOverlappingNeighbors<T extends { title?: string; entityName?: string }>(
entries: readonly T[],
limit: number,
tokens: readonly string[],
): T[] {
const next = [...entries];
if (tokens.length === 0 || limit <= 1) return next;
const overlapOf = (entry: T) => textOverlap(`${entry.title ?? ''} ${entry.entityName ?? ''}`, tokens);
for (;;) {
let weakestIndex = -1;
let weakestOverlap = Number.POSITIVE_INFINITY;
const window = Math.min(limit, next.length);
for (let index = 1; index < window; index += 1) {
const overlap = overlapOf(next[index]);
if (overlap < weakestOverlap) {
weakestOverlap = overlap;
weakestIndex = index;
}
}
let strongestIndex = -1;
let strongestOverlap = -1;
for (let index = limit; index < next.length; index += 1) {
const overlap = overlapOf(next[index]);
if (overlap > strongestOverlap) {
strongestOverlap = overlap;
strongestIndex = index;
}
}
if (weakestIndex === -1 || strongestIndex === -1 || strongestOverlap <= weakestOverlap) break;
const displaced = next[weakestIndex];
next[weakestIndex] = next[strongestIndex];
next[strongestIndex] = displaced;
}
return next;
}
48 changes: 44 additions & 4 deletions src/store/orama-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { withTimeout, withTimeoutSignal } from '../timeout.js';
import { getObservationStore } from './obs-store.js';
import { getResolvedConfig } from '../config/resolved-config.js';
import { isCjkHeavyQuery } from '../config/retrieval-strategy.js';
import { labelMatchReasons, promoteOverlappingNeighbors, queryOverlapTokens } from '../search/match-reasons.js';
import { createSemanticDerivedView } from '../search/semantic-view.js';
import { createRetrievalPlan, type RetrievalReceipt } from '../core/retrieval-contracts.js';
import {
Expand Down Expand Up @@ -1098,7 +1099,7 @@ export async function searchObservationsDetailed(options: SearchOptions): Promis
// Session dedup demotes already-surfaced entries after ranking, so it needs
// the same headroom to let unseen candidates rise into the final limit.
const requestLimit = projectIds || (options.surfacedIds && options.surfacedIds.length > 0)
? (options.limit ?? 20) * 3
? Math.max((options.limit ?? 20) * 3, 40)
: (options.limit ?? 20);

// Default field boosts — overridden by intent-specific boosts when detected
Expand Down Expand Up @@ -1513,6 +1514,45 @@ export async function searchObservationsDetailed(options: SearchOptions): Promis
intermediate = intermediate.filter(e => new Date(e.rawTime).getTime() <= untilDate);
}

// 近邻只补向量序。词法和 hybrid 自己的候选已经在窗口里,再搜一次会把
// probe、个人可见性和会话去重的基线改掉。补进来的词法行仍走同一套可见性过滤。
if (hasQuery && originalQuery && projectIds && lanceOrderUsed) {
const overlapTokens = queryOverlapTokens(originalQuery);
const lexical = await searchPersistentLexically(options, projectIds, (options.limit ?? 20) * 3);
for (const hit of lexical?.hits ?? []) {
const doc = hit.document as unknown as MemorixDocument;
if (!projectIds.includes(doc.projectId)) continue;
if (!canReadObservation(doc, options.reader, projectIds)) continue;
if (statusFilter !== 'all' && (doc.status || 'active') !== statusFilter) continue;
if (options.type === 'probe' ? doc.type !== 'probe' : doc.type === 'probe') continue;
if (options.type && options.type !== 'probe' && doc.type !== options.type) continue;
if (options.source && doc.source !== options.source) continue;
const candidateKey = makeEntryKey(doc.projectId, doc.observationId);
if (intermediate.some((entry) => makeEntryKey(entry.projectId, entry.id) === candidateKey)) continue;
intermediate.push({
id: doc.observationId,
time: formatTime(doc.createdAt),
rawTime: doc.createdAt,
type: doc.type as ObservationType,
icon: OBSERVATION_ICONS[doc.type as ObservationType] ?? '[UNKNOWN]',
title: doc.title,
tokens: doc.tokens,
score: hit.score ?? 0,
projectId: doc.projectId,
source: (doc.source || 'agent') as 'agent' | 'git' | 'manual',
sourceDetail: (doc.sourceDetail || undefined) as 'explicit' | 'hook' | 'git-ingest' | undefined,
valueCategory: (doc.valueCategory || undefined) as 'core' | 'contextual' | 'ephemeral' | undefined,
admissionState: (doc.admissionState || undefined) as IndexEntry['admissionState'],
visibility: (doc.visibility || undefined) as IndexEntry['visibility'],
entityName: doc.entityName || undefined,
documentType: (doc.documentType || 'observation') as 'observation' | 'mini-skill',
knowledgeLayer: (doc.knowledgeLayer || 'project-truth') as KnowledgeLayer,
_isCommandLog: isCommandLogEntry(doc.title),
});
}
intermediate = promoteOverlappingNeighbors(intermediate, options.limit ?? 20, overlapTokens);
}

// Apply original limit after post-filtering (we intentionally over-requested when project filtering is active)
if (projectIds) {
intermediate = intermediate.slice(0, options.limit ?? 20);
Expand Down Expand Up @@ -1704,16 +1744,16 @@ export async function searchObservationsDetailed(options: SearchOptions): Promis
const entry = entryMap.get(makeEntryKey(doc.projectId, doc.observationId));
if (!entry) continue;

const reasons: string[] = [];
const fieldHits: string[] = [];
const fields: [string, string][] = [
['title', doc.title], ['entity', doc.entityName], ['concept', doc.concepts],
['narrative', doc.narrative], ['fact', doc.facts], ['file', doc.filesModified],
];
for (const [name, value] of fields) {
const valueLower = value.toLowerCase();
if (queryTokens.some(t => valueLower.includes(t))) reasons.push(name);
if (queryTokens.some(t => valueLower.includes(t))) fieldHits.push(name);
}
if (reasons.length === 0) reasons.push('fuzzy');
const reasons = labelMatchReasons(fieldHits, requestMode);

// Prepend a single evidence-type tag (max 1) ahead of field-match labels.
// Priority: git evidence > synthesized > core core
Expand Down
60 changes: 60 additions & 0 deletions tests/search/match-reasons.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, expect, it } from 'vitest';
import { labelMatchReasons, promoteOverlappingNeighbors, queryOverlapTokens } from '../../src/search/match-reasons.js';

describe('labelMatchReasons', () => {
it('marks a vector hit that shares no field tokens as vector, not fuzzy', () => {
expect(labelMatchReasons([], 'vector')).toEqual(['vector']);
});

it('keeps a lexical miss as fuzzy when the mode is hybrid', () => {
expect(labelMatchReasons([], 'hybrid')).toEqual(['fuzzy']);
});

it('appends vector beside real field hits', () => {
expect(labelMatchReasons(['title', 'narrative'], 'vector')).toEqual(['title', 'narrative', 'vector']);
});

it('treats vector-only fallback as vector ranking', () => {
expect(labelMatchReasons([], 'vector-only (hybrid empty fallback)')).toEqual(['vector']);
});
});

describe('promoteOverlappingNeighbors', () => {
it('swaps a zero-overlap card inside the window with an overlapping neighbor outside it', () => {
const entries = [
{ title: 'clash yaml 双端' },
{ title: 'Ollama pull insecure' },
{ title: 'CMFA 导入 yaml' },
];
const promoted = promoteOverlappingNeighbors(entries, 2, ['clash', 'yaml', '导入']);
expect(promoted.map((entry) => entry.title)[1]).toBe('CMFA 导入 yaml');
});

it('keeps the first hit and replaces a weaker later hit with a stronger neighbor', () => {
const entries = [
{ title: '语义第一名没有这些词' },
{ title: 'clash' },
{ title: 'clash yaml dialer proxy CMFA 导入' },
];
const promoted = promoteOverlappingNeighbors(entries, 2, ['clash', 'yaml', 'dialer', 'proxy', 'cmfa', '导入']);
expect(promoted[0].title).toBe('语义第一名没有这些词');
expect(promoted[1].title).toBe('clash yaml dialer proxy CMFA 导入');
});

it('keeps a zero-overlap first hit when nothing outside the window shares a query token', () => {
const entries = [
{ title: '语义改写没有共同词' },
{ title: '另一个零重叠' },
];
expect(promoteOverlappingNeighbors(entries, 1, ['完全不同的词'])).toEqual(entries);
});
});

describe('queryOverlapTokens', () => {
it('bridges 密钥泄露复盘 to the words on the secrets-scan card', () => {
const tokens = queryOverlapTokens('提交代码前没有拦住密钥泄露怎么复盘');
expect(tokens).toContain('凭据');
expect(tokens).toContain('收尾');
expect(tokens).toContain('credential');
});
});
Loading