memorix 1.10.3 → 1.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +62 -1
- package/dist/cli/index.js +1886 -1273
- package/dist/index.js +1724 -1088
- package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
- package/dist/maintenance-runner.d.ts +1 -1
- package/dist/maintenance-runner.js +694 -172
- package/dist/media-audio-runner.js +685 -164
- package/dist/media-video-runner.js +693 -172
- package/dist/memcode-runtime/CHANGELOG.md +44 -1
- package/dist/sdk.js +13952 -13345
- package/dist/vector-backfill-runner.d.ts +1 -1
- package/dist/vector-backfill-runner.js +693 -172
- package/docs/ARCHITECTURE.md +219 -0
- package/docs/CONFIGURATION.md +15 -0
- package/docs/DESIGN_DECISIONS.md +37 -0
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/MODULES.md +7 -1
- package/docs/PERFORMANCE.md +14 -0
- package/docs/README.md +1 -1
- package/docs/ROADMAP-1.9.12-2.0.md +18 -2
- package/package.json +1 -1
- package/plugins/antigravity/memorix/plugin.json +1 -1
- package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
- package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
- package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
- package/plugins/copilot/memorix/plugin.json +1 -1
- package/plugins/gemini/memorix/gemini-extension.json +1 -1
- package/plugins/hermes/memorix/plugin.yaml +1 -1
- package/plugins/omp/memorix/package.json +1 -1
- package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
- package/plugins/pi/memorix/package.json +1 -1
- package/server.json +2 -2
- package/src/cli/tui/chat-service.ts +6 -9
- package/src/cli/tui/data.ts +2 -2
- package/src/codegraph/auto-context.ts +9 -2
- package/src/codegraph/derived-view.ts +63 -0
- package/src/compact/engine.ts +10 -33
- package/src/config/resolved-config.ts +11 -0
- package/src/config/retrieval-strategy.ts +22 -0
- package/src/config/toml-loader.ts +5 -0
- package/src/config/yaml-loader.ts +7 -0
- package/src/core/derived-view.ts +15 -0
- package/src/core/maintenance-result.ts +33 -0
- package/src/core/retrieval-contracts.ts +57 -0
- package/src/core/retrieval-facade.ts +18 -0
- package/src/core/retrieval-policy.ts +44 -0
- package/src/core/runtime-context.ts +42 -0
- package/src/embedding/api-provider.ts +18 -8
- package/src/knowledge/workset.ts +0 -2
- package/src/memory/consolidation.ts +3 -2
- package/src/memory/feedback-model.ts +1 -4
- package/src/memory/observations.ts +165 -87
- package/src/runtime/control-plane-maintenance.ts +1 -0
- package/src/runtime/isolated-maintenance.ts +1 -0
- package/src/runtime/maintenance-jobs.ts +123 -32
- package/src/runtime/project-maintenance.ts +69 -1
- package/src/sdk.ts +3 -2
- package/src/search/fts-view.ts +53 -0
- package/src/search/orama-view.ts +40 -0
- package/src/search/retrieval-facade.ts +38 -0
- package/src/search/semantic-index.ts +13 -0
- package/src/search/semantic-view.ts +34 -0
- package/src/server.ts +19 -7
- package/src/store/obs-store.ts +15 -0
- package/src/store/orama-store.ts +116 -42
- package/src/store/sqlite-db.ts +22 -0
- package/src/store/sqlite-store.ts +27 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { DerivedView } from '../core/derived-view.js';
|
|
2
|
+
import { closeDatabase } from '../store/sqlite-db.js';
|
|
3
|
+
import { CodeGraphStore } from './store.js';
|
|
4
|
+
import { refreshProjectLite } from './lite-provider.js';
|
|
5
|
+
|
|
6
|
+
export interface CodeGraphRefreshInput {
|
|
7
|
+
projectId: string;
|
|
8
|
+
projectRoot: string;
|
|
9
|
+
exclude?: readonly string[];
|
|
10
|
+
maxFiles?: number;
|
|
11
|
+
maxFileBytes?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** CodeGraph Memory lifecycle adapter over the canonical SQLite graph tables. */
|
|
15
|
+
export function createCodeGraphDerivedView(dataDir: string): DerivedView<CodeGraphRefreshInput> {
|
|
16
|
+
let store: CodeGraphStore | undefined;
|
|
17
|
+
let lastInput: CodeGraphRefreshInput | undefined;
|
|
18
|
+
|
|
19
|
+
const getStore = async (): Promise<CodeGraphStore> => {
|
|
20
|
+
if (!store) {
|
|
21
|
+
store = new CodeGraphStore();
|
|
22
|
+
await store.init(dataDir);
|
|
23
|
+
}
|
|
24
|
+
return store;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
async status() {
|
|
29
|
+
if (!lastInput) return { state: 'missing' };
|
|
30
|
+
try {
|
|
31
|
+
const status = (await getStore()).status(lastInput.projectId);
|
|
32
|
+
return status.indexedAt
|
|
33
|
+
? { state: 'ready', generation: status.latestSnapshot?.sourceEpoch, rowCount: status.files }
|
|
34
|
+
: { state: 'missing', rowCount: status.files };
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return { state: 'degraded', reason: error instanceof Error ? error.message : String(error) };
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
async refresh(input) {
|
|
40
|
+
lastInput = { ...input, ...(input.exclude ? { exclude: [...input.exclude] } : {}) };
|
|
41
|
+
await refreshProjectLite(await getStore(), {
|
|
42
|
+
...lastInput,
|
|
43
|
+
exclude: lastInput.exclude ? [...lastInput.exclude] : undefined,
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
async rebuild() {
|
|
47
|
+
if (!lastInput) return false;
|
|
48
|
+
await refreshProjectLite(await getStore(), {
|
|
49
|
+
...lastInput,
|
|
50
|
+
exclude: lastInput.exclude ? [...lastInput.exclude] : undefined,
|
|
51
|
+
});
|
|
52
|
+
return true;
|
|
53
|
+
},
|
|
54
|
+
async compact() {
|
|
55
|
+
store?.compactStorage();
|
|
56
|
+
},
|
|
57
|
+
async close() {
|
|
58
|
+
closeDatabase(dataDir);
|
|
59
|
+
store = undefined;
|
|
60
|
+
lastInput = undefined;
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
package/src/compact/engine.ts
CHANGED
|
@@ -11,14 +11,11 @@
|
|
|
11
11
|
|
|
12
12
|
import type { SearchOptions, IndexEntry, TimelineContext, MemorixDocument, ObservationRef, MemoryRef, MiniSkill, SourceSnapshot, ObservationReader } from '../types.js';
|
|
13
13
|
import {
|
|
14
|
-
searchObservations,
|
|
15
14
|
getTimeline,
|
|
16
15
|
getObservationsByIds,
|
|
17
16
|
makeOramaObservationId,
|
|
18
|
-
getLastSearchMode,
|
|
19
|
-
getLastSearchDiagnostics,
|
|
20
|
-
getSearchDerivedViews,
|
|
21
17
|
} from '../store/orama-store.js';
|
|
18
|
+
import { retrievalFacade } from '../search/retrieval-facade.js';
|
|
22
19
|
import { getObservation, getAllObservations } from '../memory/observations.js';
|
|
23
20
|
import { ensureFreshIndex } from '../memory/freshness.js';
|
|
24
21
|
import { formatIndexTable, formatTimeline, formatObservationDetail, type RetrievalSurface } from './index-format.js';
|
|
@@ -30,8 +27,6 @@ import { getMiniSkillStore } from '../store/mini-skill-store.js';
|
|
|
30
27
|
import { miniSkillToDocument, resolveProvenanceStatus, type ProvenanceStatus } from '../skills/mini-skills.js';
|
|
31
28
|
import { redactCredentials } from '../memory/secret-filter.js';
|
|
32
29
|
import { canReadObservation, filterReadableObservations } from '../memory/visibility.js';
|
|
33
|
-
import { getProjectDataDir } from '../store/persistence.js';
|
|
34
|
-
import { MemoryFeedbackStore, feedbackWeightMultiplier } from '../memory/feedback.js';
|
|
35
30
|
|
|
36
31
|
export function normalizeMemoryBrowseQuery(query: string): string {
|
|
37
32
|
const trimmed = query.trim();
|
|
@@ -78,8 +73,10 @@ export interface CompactSearchReceipt {
|
|
|
78
73
|
selectedCount: number;
|
|
79
74
|
omittedCount: number;
|
|
80
75
|
omittedByTokenBudget: number;
|
|
76
|
+
omittedByFeedback: number;
|
|
81
77
|
fallbackUsed: boolean;
|
|
82
78
|
fallbackReason?: string;
|
|
79
|
+
degradedReasons?: string[];
|
|
83
80
|
derivedViews: import('../search/derived-view-receipt.js').RetrievalDerivedViews;
|
|
84
81
|
tokenCount: number;
|
|
85
82
|
elapsedMs: number;
|
|
@@ -98,32 +95,10 @@ export async function compactSearch(options: SearchOptions, surface: RetrievalSu
|
|
|
98
95
|
const startedAt = Date.now();
|
|
99
96
|
await ensureFreshIndex({ loadCorpus: false });
|
|
100
97
|
const searchOptions = { ...options, query: normalizeMemoryBrowseQuery(options.query) };
|
|
101
|
-
|
|
98
|
+
const execution = await retrievalFacade.search(searchOptions);
|
|
99
|
+
const entries = execution.entries.map((entry) =>
|
|
102
100
|
entry.projectId || !options.projectId ? entry : { ...entry, projectId: options.projectId },
|
|
103
101
|
);
|
|
104
|
-
if (options.projectId) {
|
|
105
|
-
try {
|
|
106
|
-
const feedback = new MemoryFeedbackStore();
|
|
107
|
-
await feedback.init(await getProjectDataDir(options.projectId));
|
|
108
|
-
const states = feedback.weights(options.projectId, 'observation');
|
|
109
|
-
entries = entries
|
|
110
|
-
.map((entry) => {
|
|
111
|
-
const state = states.get(String(entry.id));
|
|
112
|
-
if (!state) return entry;
|
|
113
|
-
return {
|
|
114
|
-
...entry,
|
|
115
|
-
score: (entry.score ?? 0) * feedbackWeightMultiplier(state.weight),
|
|
116
|
-
feedbackWeight: state.weight,
|
|
117
|
-
feedbackStatus: state.status,
|
|
118
|
-
};
|
|
119
|
-
})
|
|
120
|
-
.filter((entry) => entry.feedbackStatus !== 'archived' || options.status === 'all')
|
|
121
|
-
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
|
|
122
|
-
} catch {
|
|
123
|
-
// Feedback is an enrichment lane. Retrieval remains available if an old
|
|
124
|
-
// local database has not yet run the 1.8 schema migration.
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
102
|
let formatted = formatIndexTable(entries, searchOptions.query, !options.projectId, surface);
|
|
128
103
|
|
|
129
104
|
if (entries.length === 0 && options.projectId) {
|
|
@@ -157,8 +132,8 @@ export async function compactSearch(options: SearchOptions, surface: RetrievalSu
|
|
|
157
132
|
}
|
|
158
133
|
|
|
159
134
|
const totalTokens = countTextTokens(formatted);
|
|
160
|
-
const diagnostics =
|
|
161
|
-
const derivedViews =
|
|
135
|
+
const diagnostics = execution.receipt;
|
|
136
|
+
const derivedViews = execution.views;
|
|
162
137
|
if (diagnostics?.fallbackUsed && diagnostics.fallbackReason) {
|
|
163
138
|
derivedViews.embedding = {
|
|
164
139
|
freshness: 'stale',
|
|
@@ -173,14 +148,16 @@ export async function compactSearch(options: SearchOptions, surface: RetrievalSu
|
|
|
173
148
|
totalTokens,
|
|
174
149
|
receipt: {
|
|
175
150
|
version: '1',
|
|
176
|
-
mode:
|
|
151
|
+
mode: diagnostics.mode,
|
|
177
152
|
resultCount: entries.length,
|
|
178
153
|
candidateCount: diagnostics?.candidateCount ?? entries.length,
|
|
179
154
|
selectedCount: diagnostics?.selectedCount ?? entries.length,
|
|
180
155
|
omittedCount: diagnostics?.omittedCount ?? 0,
|
|
181
156
|
omittedByTokenBudget: diagnostics?.omittedByTokenBudget ?? 0,
|
|
157
|
+
omittedByFeedback: diagnostics.omittedByFeedback ?? 0,
|
|
182
158
|
fallbackUsed: diagnostics?.fallbackUsed ?? false,
|
|
183
159
|
...(diagnostics?.fallbackReason ? { fallbackReason: diagnostics.fallbackReason } : {}),
|
|
160
|
+
...(diagnostics?.degradedReasons ? { degradedReasons: diagnostics.degradedReasons } : {}),
|
|
184
161
|
derivedViews,
|
|
185
162
|
tokenCount: totalTokens,
|
|
186
163
|
elapsedMs: Math.max(0, Date.now() - startedAt),
|
|
@@ -12,6 +12,7 @@ import { loadFileConfig } from './legacy-loader.js';
|
|
|
12
12
|
import { loadTomlConfig, type MemorixTomlConfig } from './toml-loader.js';
|
|
13
13
|
import { loadYamlConfig, type MemorixYamlConfig } from './yaml-loader.js';
|
|
14
14
|
import { loadDotenv } from './dotenv-loader.js';
|
|
15
|
+
import { firstRetrievalStrategy, type RetrievalStrategy } from './retrieval-strategy.js';
|
|
15
16
|
|
|
16
17
|
export interface ResolvedLaneOptions {
|
|
17
18
|
projectRoot?: string | null;
|
|
@@ -44,6 +45,10 @@ export interface ResolvedMemorixConfig {
|
|
|
44
45
|
apiKey?: string;
|
|
45
46
|
dimensions?: number;
|
|
46
47
|
};
|
|
48
|
+
retrieval: {
|
|
49
|
+
cjk: RetrievalStrategy;
|
|
50
|
+
ascii: RetrievalStrategy;
|
|
51
|
+
};
|
|
47
52
|
rerank: {
|
|
48
53
|
provider: 'off' | 'http';
|
|
49
54
|
model?: string;
|
|
@@ -191,6 +196,10 @@ export function getResolvedConfig(options: ResolvedLaneOptions = {}): ResolvedMe
|
|
|
191
196
|
apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
|
|
192
197
|
dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions),
|
|
193
198
|
},
|
|
199
|
+
retrieval: {
|
|
200
|
+
cjk: firstRetrievalStrategy('vector', process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
|
|
201
|
+
ascii: firstRetrievalStrategy('hybrid', process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii),
|
|
202
|
+
},
|
|
194
203
|
rerank: resolveRerankLane({
|
|
195
204
|
toml,
|
|
196
205
|
yaml,
|
|
@@ -327,6 +336,8 @@ function getEnvSourceNames(): string[] {
|
|
|
327
336
|
'MEMORIX_EMBEDDING_BASE_URL',
|
|
328
337
|
'MEMORIX_EMBEDDING_MODEL',
|
|
329
338
|
'MEMORIX_EMBEDDING_DIMENSIONS',
|
|
339
|
+
'MEMORIX_RETRIEVAL_CJK',
|
|
340
|
+
'MEMORIX_RETRIEVAL_ASCII',
|
|
330
341
|
'MEMORIX_RERANK_PROVIDER',
|
|
331
342
|
'MEMORIX_RERANK_MODEL',
|
|
332
343
|
'MEMORIX_RERANK_BASE_URL',
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type RetrievalStrategy = 'vector' | 'hybrid';
|
|
2
|
+
|
|
3
|
+
const CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
|
|
4
|
+
|
|
5
|
+
export function isCjkHeavyQuery(query: string): boolean {
|
|
6
|
+
if (!query) return false;
|
|
7
|
+
const matches = query.match(CJK);
|
|
8
|
+
return (matches?.length ?? 0) / query.length > 0.3;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function normalizeRetrievalStrategy(value: unknown): RetrievalStrategy | undefined {
|
|
12
|
+
if (value === 'vector' || value === 'hybrid') return value;
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function firstRetrievalStrategy(fallback: RetrievalStrategy, ...values: unknown[]): RetrievalStrategy {
|
|
17
|
+
for (const value of values) {
|
|
18
|
+
const normalized = normalizeRetrievalStrategy(value);
|
|
19
|
+
if (normalized) return normalized;
|
|
20
|
+
}
|
|
21
|
+
return fallback;
|
|
22
|
+
}
|
|
@@ -28,6 +28,10 @@ export interface MemorixTomlConfig {
|
|
|
28
28
|
api_key?: string;
|
|
29
29
|
dimensions?: number;
|
|
30
30
|
};
|
|
31
|
+
retrieval?: {
|
|
32
|
+
cjk?: 'vector' | 'hybrid' | string;
|
|
33
|
+
ascii?: 'vector' | 'hybrid' | string;
|
|
34
|
+
};
|
|
31
35
|
/** Optional HTTP rerank against a compatible /rerank API. */
|
|
32
36
|
rerank?: {
|
|
33
37
|
provider?: 'off' | 'http' | string;
|
|
@@ -105,6 +109,7 @@ function mergeTomlConfig(base: MemorixTomlConfig, override: MemorixTomlConfig):
|
|
|
105
109
|
llm: { ...base.memory?.llm, ...override.memory?.llm },
|
|
106
110
|
},
|
|
107
111
|
embedding: { ...base.embedding, ...override.embedding },
|
|
112
|
+
retrieval: { ...base.retrieval, ...override.retrieval },
|
|
108
113
|
rerank: { ...base.rerank, ...override.rerank },
|
|
109
114
|
hooks: { ...base.hooks, ...override.hooks },
|
|
110
115
|
git: { ...base.git, ...override.git },
|
|
@@ -48,6 +48,12 @@ export interface MemorixYamlConfig {
|
|
|
48
48
|
dimensions?: number;
|
|
49
49
|
};
|
|
50
50
|
|
|
51
|
+
/** Which ranker to use for CJK vs ASCII queries. */
|
|
52
|
+
retrieval?: {
|
|
53
|
+
cjk?: 'vector' | 'hybrid' | string;
|
|
54
|
+
ascii?: 'vector' | 'hybrid' | string;
|
|
55
|
+
};
|
|
56
|
+
|
|
51
57
|
/** Remote neural rerank (HTTP only) */
|
|
52
58
|
rerank?: {
|
|
53
59
|
provider?: 'off' | 'http' | string;
|
|
@@ -210,6 +216,7 @@ export function loadYamlConfig(projectRoot?: string | null, options: LoadYamlOpt
|
|
|
210
216
|
llm: { ...userConfig.llm, ...projectConfig.llm },
|
|
211
217
|
agent: { ...userConfig.agent, ...projectConfig.agent },
|
|
212
218
|
embedding: { ...userConfig.embedding, ...projectConfig.embedding },
|
|
219
|
+
retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
|
|
213
220
|
rerank: { ...userConfig.rerank, ...projectConfig.rerank },
|
|
214
221
|
git: { ...userConfig.git, ...projectConfig.git },
|
|
215
222
|
codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface DerivedViewStatus {
|
|
2
|
+
state: 'ready' | 'missing' | 'stale' | 'degraded' | 'rebuilding' | 'unavailable';
|
|
3
|
+
generation?: number;
|
|
4
|
+
rowCount?: number;
|
|
5
|
+
reason?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** A derived index can fail or be rebuilt without changing canonical records. */
|
|
9
|
+
export interface DerivedView<RefreshInput> {
|
|
10
|
+
status(): Promise<DerivedViewStatus>;
|
|
11
|
+
refresh(input: RefreshInput): Promise<void>;
|
|
12
|
+
rebuild(): Promise<boolean>;
|
|
13
|
+
compact(): Promise<void>;
|
|
14
|
+
close(): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Counts from one bounded maintenance attempt, never cumulative lifetime totals. */
|
|
2
|
+
export interface MaintenanceProgress {
|
|
3
|
+
attempted: number;
|
|
4
|
+
succeeded: number;
|
|
5
|
+
failed: number;
|
|
6
|
+
remaining: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The kernel's durable background-work result, independent of its runner. */
|
|
10
|
+
export type MaintenanceResult =
|
|
11
|
+
| { action: 'complete'; progress?: MaintenanceProgress }
|
|
12
|
+
| {
|
|
13
|
+
action: 'reschedule';
|
|
14
|
+
delayMs: number;
|
|
15
|
+
resetAttempts?: boolean;
|
|
16
|
+
payload?: Record<string, unknown>;
|
|
17
|
+
status?: 'pending' | 'retry';
|
|
18
|
+
lastError?: string;
|
|
19
|
+
clearLastError?: boolean;
|
|
20
|
+
progress?: MaintenanceProgress;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Reject progress that would make a completed or retrying job look healthier than it is. */
|
|
24
|
+
export function assertMaintenanceProgress(progress: MaintenanceProgress | undefined): void {
|
|
25
|
+
if (!progress) return;
|
|
26
|
+
const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
|
|
27
|
+
if (counts.some((count) => !Number.isSafeInteger(count) || count < 0)) {
|
|
28
|
+
throw new Error('maintenance progress must contain non-negative safe integers');
|
|
29
|
+
}
|
|
30
|
+
if (progress.succeeded + progress.failed > progress.attempted) {
|
|
31
|
+
throw new Error('maintenance progress outcomes exceed attempted work');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ObservationReader, RetrievalQuality, SearchOptions } from '../types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Host-independent retrieval intent. Hosts may add presentation details, but
|
|
5
|
+
* the search engine receives one normalized plan before choosing derived views.
|
|
6
|
+
*/
|
|
7
|
+
export interface RetrievalPlan {
|
|
8
|
+
query: string;
|
|
9
|
+
quality: RetrievalQuality;
|
|
10
|
+
limit: number;
|
|
11
|
+
projectId?: string;
|
|
12
|
+
status: SearchOptions['status'];
|
|
13
|
+
source?: SearchOptions['source'];
|
|
14
|
+
type?: SearchOptions['type'];
|
|
15
|
+
since?: string;
|
|
16
|
+
until?: string;
|
|
17
|
+
maxTokens: number;
|
|
18
|
+
trackAccess: boolean;
|
|
19
|
+
reader?: ObservationReader;
|
|
20
|
+
surfacedIds: number[];
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RetrievalReceipt {
|
|
25
|
+
version: '1';
|
|
26
|
+
mode: string;
|
|
27
|
+
candidateCount: number;
|
|
28
|
+
selectedCount: number;
|
|
29
|
+
omittedCount: number;
|
|
30
|
+
omittedByTokenBudget: number;
|
|
31
|
+
omittedByFeedback?: number;
|
|
32
|
+
degradedReasons?: string[];
|
|
33
|
+
fallbackUsed: boolean;
|
|
34
|
+
fallbackReason?: string;
|
|
35
|
+
elapsedMs: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createRetrievalPlan(options: SearchOptions): RetrievalPlan {
|
|
39
|
+
const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
|
|
40
|
+
const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
|
|
41
|
+
return {
|
|
42
|
+
query: options.query.trim(),
|
|
43
|
+
quality: options.quality ?? 'balanced',
|
|
44
|
+
limit: Math.max(1, Math.min(10_000, requestedLimit)),
|
|
45
|
+
...(options.projectId ? { projectId: options.projectId } : {}),
|
|
46
|
+
status: options.status ?? 'active',
|
|
47
|
+
...(options.source ? { source: options.source } : {}),
|
|
48
|
+
...(options.type ? { type: options.type } : {}),
|
|
49
|
+
...(options.since ? { since: options.since } : {}),
|
|
50
|
+
...(options.until ? { until: options.until } : {}),
|
|
51
|
+
maxTokens: Math.max(0, requestedTokens),
|
|
52
|
+
trackAccess: options.trackAccess !== false,
|
|
53
|
+
reader: options.reader,
|
|
54
|
+
surfacedIds: [...(options.surfacedIds ?? [])],
|
|
55
|
+
signal: options.signal,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { IndexEntry, SearchOptions } from '../types.js';
|
|
2
|
+
import { createRetrievalPlan, type RetrievalPlan, type RetrievalReceipt } from './retrieval-contracts.js';
|
|
3
|
+
|
|
4
|
+
export interface RetrievalExecution<Views> {
|
|
5
|
+
entries: IndexEntry[];
|
|
6
|
+
receipt: RetrievalReceipt;
|
|
7
|
+
views: Views;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function createRetrievalFacade<Views>(
|
|
11
|
+
run: (plan: RetrievalPlan) => Promise<RetrievalExecution<Views>>,
|
|
12
|
+
): { search(options: SearchOptions): Promise<RetrievalExecution<Views>> } {
|
|
13
|
+
return {
|
|
14
|
+
search(options) {
|
|
15
|
+
return run(createRetrievalPlan(options));
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { IndexEntry, SearchOptions } from '../types.js';
|
|
2
|
+
import type { RetrievalExecution } from './retrieval-facade.js';
|
|
3
|
+
|
|
4
|
+
export interface RetrievalFeedbackState {
|
|
5
|
+
weight: number;
|
|
6
|
+
status: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Pure feedback weight used by retrieval and retention. */
|
|
10
|
+
export function feedbackWeightMultiplier(weight: number): number {
|
|
11
|
+
return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Apply project feedback to one result set and keep its receipt truthful. */
|
|
15
|
+
export function applyRetrievalFeedback<Views>(
|
|
16
|
+
execution: RetrievalExecution<Views>,
|
|
17
|
+
states: ReadonlyMap<string, RetrievalFeedbackState>,
|
|
18
|
+
status: SearchOptions['status'],
|
|
19
|
+
): RetrievalExecution<Views> {
|
|
20
|
+
const scored = execution.entries.map((entry): IndexEntry => {
|
|
21
|
+
const state = states.get(String(entry.id));
|
|
22
|
+
if (!state) return entry;
|
|
23
|
+
return {
|
|
24
|
+
...entry,
|
|
25
|
+
score: (entry.score ?? 0) * feedbackWeightMultiplier(state.weight),
|
|
26
|
+
feedbackWeight: state.weight,
|
|
27
|
+
feedbackStatus: state.status as IndexEntry['feedbackStatus'],
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
const entries = scored
|
|
31
|
+
.filter((entry) => entry.feedbackStatus !== 'archived' || status === 'all')
|
|
32
|
+
.sort((left, right) => (right.score ?? 0) - (left.score ?? 0));
|
|
33
|
+
const omittedByFeedback = scored.length - entries.length;
|
|
34
|
+
return {
|
|
35
|
+
...execution,
|
|
36
|
+
entries,
|
|
37
|
+
receipt: {
|
|
38
|
+
...execution.receipt,
|
|
39
|
+
selectedCount: entries.length,
|
|
40
|
+
omittedCount: Math.max(0, execution.receipt.candidateCount - entries.length),
|
|
41
|
+
omittedByFeedback,
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import type { ResolvedMemorixConfig } from '../config/resolved-config.js';
|
|
3
|
+
|
|
4
|
+
type Frozen<T> = T extends readonly (infer Item)[]
|
|
5
|
+
? readonly Frozen<Item>[]
|
|
6
|
+
: T extends object
|
|
7
|
+
? { readonly [Key in keyof T]: Frozen<T[Key]> }
|
|
8
|
+
: T;
|
|
9
|
+
|
|
10
|
+
export interface RuntimeContext {
|
|
11
|
+
readonly projectId: string;
|
|
12
|
+
readonly projectRoot: string;
|
|
13
|
+
readonly dataDir: string;
|
|
14
|
+
readonly config: Frozen<ResolvedMemorixConfig>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function freezeTree<T>(value: T): Frozen<T> {
|
|
18
|
+
if (value && typeof value === 'object') {
|
|
19
|
+
for (const child of Object.values(value)) freezeTree(child);
|
|
20
|
+
Object.freeze(value);
|
|
21
|
+
}
|
|
22
|
+
return value as Frozen<T>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Capture one verified project and its resolved config for a request. */
|
|
26
|
+
export function createRuntimeContext(input: {
|
|
27
|
+
projectId: string;
|
|
28
|
+
projectRoot: string;
|
|
29
|
+
dataDir: string;
|
|
30
|
+
config: ResolvedMemorixConfig;
|
|
31
|
+
}): RuntimeContext {
|
|
32
|
+
const projectId = input.projectId.trim();
|
|
33
|
+
if (!projectId || !input.projectRoot.trim() || !input.dataDir.trim()) {
|
|
34
|
+
throw new Error('Runtime context requires a resolved project and data directory');
|
|
35
|
+
}
|
|
36
|
+
return Object.freeze({
|
|
37
|
+
projectId,
|
|
38
|
+
projectRoot: path.resolve(input.projectRoot),
|
|
39
|
+
dataDir: path.resolve(input.dataDir),
|
|
40
|
+
config: freezeTree(structuredClone(input.config)),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -180,6 +180,7 @@ const DEFAULT_MAX_BATCH_SIZE = 2048;
|
|
|
180
180
|
const DASHSCOPE_MAX_BATCH_SIZE = 10;
|
|
181
181
|
const MAX_RETRIES = 3;
|
|
182
182
|
const BASE_DELAY_MS = 500;
|
|
183
|
+
const CACHE_LOAD_YIELD_EVERY = 32;
|
|
183
184
|
|
|
184
185
|
function normalizeText(text: string): string {
|
|
185
186
|
return text.replace(/\s+/g, ' ').trim().slice(0, MAX_INPUT_CHARS);
|
|
@@ -480,8 +481,10 @@ async function loadCacheJsonl(filePath: string): Promise<number> {
|
|
|
480
481
|
} catch {
|
|
481
482
|
// Skip a corrupt line; the rest of the cache remains usable.
|
|
482
483
|
}
|
|
483
|
-
if (onDiskCount %
|
|
484
|
-
|
|
484
|
+
if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
|
|
485
|
+
// Timers are the formation budget's watchdog. A check-phase-only yield
|
|
486
|
+
// can keep a long cache restore ahead of timers on a busy control plane.
|
|
487
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
|
485
488
|
}
|
|
486
489
|
}
|
|
487
490
|
diskCacheEntryCount = onDiskCount;
|
|
@@ -996,7 +999,9 @@ export class APIEmbeddingProvider implements EmbeddingProvider {
|
|
|
996
999
|
// after search already printed. getCachedEmbeddings() still loads the
|
|
997
1000
|
// cache when a later hybrid/attach path actually needs vectors.
|
|
998
1001
|
if (allowNetworkProbe) {
|
|
999
|
-
|
|
1002
|
+
// Let the request that initialized the provider reach its first await
|
|
1003
|
+
// before parsing a large cache on this process's event loop.
|
|
1004
|
+
setImmediate(startDiskCacheLoad);
|
|
1000
1005
|
}
|
|
1001
1006
|
|
|
1002
1007
|
return new APIEmbeddingProvider(config, probeDimensions);
|
|
@@ -1086,11 +1091,10 @@ export class APIEmbeddingProvider implements EmbeddingProvider {
|
|
|
1086
1091
|
}
|
|
1087
1092
|
const hash = textHash(normalized, this.cacheKeyNamespace);
|
|
1088
1093
|
|
|
1089
|
-
// Fast path:
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
}
|
|
1094
|
+
// Fast path: a vector generated earlier in this process is valid even
|
|
1095
|
+
// while the disk cache is still restoring in the background.
|
|
1096
|
+
const cached = cache.get(hash);
|
|
1097
|
+
if (cached) return cached;
|
|
1094
1098
|
|
|
1095
1099
|
// Cold-start path: cache is still loading in background.
|
|
1096
1100
|
// Race the cache completion (may have a hit) against the API call.
|
|
@@ -1354,6 +1358,12 @@ async function fetchWithRetry(
|
|
|
1354
1358
|
if (err instanceof Error && (err.name === 'AbortError' || controller.signal.aborted || options.signal?.aborted)) {
|
|
1355
1359
|
throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
|
|
1356
1360
|
}
|
|
1361
|
+
if (options.retry !== false && attempt < MAX_RETRIES) {
|
|
1362
|
+
const delay = BASE_DELAY_MS * Math.pow(2, attempt);
|
|
1363
|
+
console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES} in ${delay}ms`);
|
|
1364
|
+
await waitForRetry(delay, options.signal);
|
|
1365
|
+
return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
|
|
1366
|
+
}
|
|
1357
1367
|
throw err;
|
|
1358
1368
|
}
|
|
1359
1369
|
|
package/src/knowledge/workset.ts
CHANGED
|
@@ -27,7 +27,6 @@ import type { WorkflowSelection } from './workflow-types.js';
|
|
|
27
27
|
import type { ObservationReader } from '../types.js';
|
|
28
28
|
import type { LongTermMemory, LongTermMemoryEvidence } from '../memory/long-term-types.js';
|
|
29
29
|
import type { TaskContinuityLedger } from './task-continuity.js';
|
|
30
|
-
import { getSearchDerivedViews } from '../store/orama-store.js';
|
|
31
30
|
import type { RetrievalDerivedViews } from '../search/derived-view-receipt.js';
|
|
32
31
|
|
|
33
32
|
export type WorksetCautionKind =
|
|
@@ -1250,7 +1249,6 @@ export async function buildTaskWorkset(input: BuildTaskWorksetInput): Promise<Ta
|
|
|
1250
1249
|
});
|
|
1251
1250
|
const omittedReceipt = receiptOmissions(rendered.omittedItems, base.hiddenCautionMemoryCount);
|
|
1252
1251
|
const derivedViews: RetrievalDerivedViews = {
|
|
1253
|
-
...getSearchDerivedViews(),
|
|
1254
1252
|
...(input.retrieval?.derivedViews ?? {}),
|
|
1255
1253
|
};
|
|
1256
1254
|
const retrieval = {
|
|
@@ -41,8 +41,9 @@ const MAX_BATCH_SIZE = 500;
|
|
|
41
41
|
function tokenize(text: string): Set<string> {
|
|
42
42
|
return new Set(
|
|
43
43
|
text
|
|
44
|
+
.normalize('NFKC')
|
|
44
45
|
.toLowerCase()
|
|
45
|
-
.replace(/[
|
|
46
|
+
.replace(/[^\p{L}\p{N}\s-]/gu, ' ')
|
|
46
47
|
.split(/\s+/)
|
|
47
48
|
.filter(t => t.length > 1),
|
|
48
49
|
);
|
|
@@ -52,7 +53,7 @@ function tokenize(text: string): Set<string> {
|
|
|
52
53
|
* Compute Jaccard similarity between two sets of tokens.
|
|
53
54
|
*/
|
|
54
55
|
function jaccardSimilarity(a: Set<string>, b: Set<string>): number {
|
|
55
|
-
if (a.size === 0 && b.size === 0) return
|
|
56
|
+
if (a.size === 0 && b.size === 0) return 0;
|
|
56
57
|
let intersection = 0;
|
|
57
58
|
for (const token of a) {
|
|
58
59
|
if (b.has(token)) intersection++;
|
|
@@ -1,4 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export function feedbackWeightMultiplier(weight: number): number {
|
|
3
|
-
return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
|
|
4
|
-
}
|
|
1
|
+
export { feedbackWeightMultiplier } from '../core/retrieval-policy.js';
|