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
|
@@ -193,6 +193,7 @@ function loadYamlConfig(projectRoot, options = {}) {
|
|
|
193
193
|
llm: { ...userConfig.llm, ...projectConfig.llm },
|
|
194
194
|
agent: { ...userConfig.agent, ...projectConfig.agent },
|
|
195
195
|
embedding: { ...userConfig.embedding, ...projectConfig.embedding },
|
|
196
|
+
retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
|
|
196
197
|
rerank: { ...userConfig.rerank, ...projectConfig.rerank },
|
|
197
198
|
git: { ...userConfig.git, ...projectConfig.git },
|
|
198
199
|
codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
|
|
@@ -1374,6 +1375,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
|
|
|
1374
1375
|
lease_owner TEXT,
|
|
1375
1376
|
lease_expires_at INTEGER,
|
|
1376
1377
|
last_error TEXT,
|
|
1378
|
+
attempted INTEGER NOT NULL DEFAULT 0,
|
|
1379
|
+
succeeded INTEGER NOT NULL DEFAULT 0,
|
|
1380
|
+
failed INTEGER NOT NULL DEFAULT 0,
|
|
1381
|
+
remaining INTEGER NOT NULL DEFAULT 0,
|
|
1382
|
+
progress_recorded INTEGER NOT NULL DEFAULT 0,
|
|
1383
|
+
rerun_requested INTEGER NOT NULL DEFAULT 0,
|
|
1377
1384
|
created_at INTEGER NOT NULL,
|
|
1378
1385
|
updated_at INTEGER NOT NULL,
|
|
1379
1386
|
completed_at INTEGER
|
|
@@ -1794,6 +1801,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
|
|
|
1794
1801
|
ON task_continuity_events(project_id, task_id, event_key)
|
|
1795
1802
|
WHERE event_key IS NOT NULL`);
|
|
1796
1803
|
}
|
|
1804
|
+
},
|
|
1805
|
+
{
|
|
1806
|
+
id: "1.11-maintenance-progress",
|
|
1807
|
+
apply: (db2) => {
|
|
1808
|
+
addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
|
|
1809
|
+
addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
|
|
1810
|
+
addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
|
|
1811
|
+
addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
|
|
1812
|
+
addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
|
|
1813
|
+
}
|
|
1814
|
+
},
|
|
1815
|
+
{
|
|
1816
|
+
id: "1.11-maintenance-rerun",
|
|
1817
|
+
apply: (db2) => {
|
|
1818
|
+
addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
|
|
1819
|
+
}
|
|
1797
1820
|
}
|
|
1798
1821
|
];
|
|
1799
1822
|
_dbCache = /* @__PURE__ */ new Map();
|
|
@@ -2273,6 +2296,7 @@ function mergeTomlConfig(base, override) {
|
|
|
2273
2296
|
llm: { ...base.memory?.llm, ...override.memory?.llm }
|
|
2274
2297
|
},
|
|
2275
2298
|
embedding: { ...base.embedding, ...override.embedding },
|
|
2299
|
+
retrieval: { ...base.retrieval, ...override.retrieval },
|
|
2276
2300
|
rerank: { ...base.rerank, ...override.rerank },
|
|
2277
2301
|
hooks: { ...base.hooks, ...override.hooks },
|
|
2278
2302
|
git: { ...base.git, ...override.git },
|
|
@@ -2362,6 +2386,32 @@ var init_toml_loader = __esm({
|
|
|
2362
2386
|
}
|
|
2363
2387
|
});
|
|
2364
2388
|
|
|
2389
|
+
// src/config/retrieval-strategy.ts
|
|
2390
|
+
function isCjkHeavyQuery(query) {
|
|
2391
|
+
if (!query) return false;
|
|
2392
|
+
const matches = query.match(CJK);
|
|
2393
|
+
return (matches?.length ?? 0) / query.length > 0.3;
|
|
2394
|
+
}
|
|
2395
|
+
function normalizeRetrievalStrategy(value) {
|
|
2396
|
+
if (value === "vector" || value === "hybrid") return value;
|
|
2397
|
+
return void 0;
|
|
2398
|
+
}
|
|
2399
|
+
function firstRetrievalStrategy(fallback, ...values) {
|
|
2400
|
+
for (const value of values) {
|
|
2401
|
+
const normalized = normalizeRetrievalStrategy(value);
|
|
2402
|
+
if (normalized) return normalized;
|
|
2403
|
+
}
|
|
2404
|
+
return fallback;
|
|
2405
|
+
}
|
|
2406
|
+
var CJK;
|
|
2407
|
+
var init_retrieval_strategy = __esm({
|
|
2408
|
+
"src/config/retrieval-strategy.ts"() {
|
|
2409
|
+
"use strict";
|
|
2410
|
+
init_esm_shims();
|
|
2411
|
+
CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
|
|
2412
|
+
}
|
|
2413
|
+
});
|
|
2414
|
+
|
|
2365
2415
|
// src/config/resolved-config.ts
|
|
2366
2416
|
var resolved_config_exports = {};
|
|
2367
2417
|
__export(resolved_config_exports, {
|
|
@@ -2471,6 +2521,10 @@ function getResolvedConfig(options = {}) {
|
|
|
2471
2521
|
apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
|
|
2472
2522
|
dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
|
|
2473
2523
|
},
|
|
2524
|
+
retrieval: {
|
|
2525
|
+
cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
|
|
2526
|
+
ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
|
|
2527
|
+
},
|
|
2474
2528
|
rerank: resolveRerankLane({
|
|
2475
2529
|
toml,
|
|
2476
2530
|
yaml,
|
|
@@ -2592,6 +2646,8 @@ function getEnvSourceNames() {
|
|
|
2592
2646
|
"MEMORIX_EMBEDDING_BASE_URL",
|
|
2593
2647
|
"MEMORIX_EMBEDDING_MODEL",
|
|
2594
2648
|
"MEMORIX_EMBEDDING_DIMENSIONS",
|
|
2649
|
+
"MEMORIX_RETRIEVAL_CJK",
|
|
2650
|
+
"MEMORIX_RETRIEVAL_ASCII",
|
|
2595
2651
|
"MEMORIX_RERANK_PROVIDER",
|
|
2596
2652
|
"MEMORIX_RERANK_MODEL",
|
|
2597
2653
|
"MEMORIX_RERANK_BASE_URL",
|
|
@@ -2700,6 +2756,7 @@ var init_resolved_config = __esm({
|
|
|
2700
2756
|
init_toml_loader();
|
|
2701
2757
|
init_yaml_loader();
|
|
2702
2758
|
init_dotenv_loader();
|
|
2759
|
+
init_retrieval_strategy();
|
|
2703
2760
|
}
|
|
2704
2761
|
});
|
|
2705
2762
|
|
|
@@ -3482,8 +3539,8 @@ async function loadCacheJsonl(filePath) {
|
|
|
3482
3539
|
loaded = cache3.size;
|
|
3483
3540
|
} catch {
|
|
3484
3541
|
}
|
|
3485
|
-
if (onDiskCount %
|
|
3486
|
-
await new Promise((resolve2) =>
|
|
3542
|
+
if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
|
|
3543
|
+
await new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
3487
3544
|
}
|
|
3488
3545
|
}
|
|
3489
3546
|
diskCacheEntryCount = onDiskCount;
|
|
@@ -3812,6 +3869,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
|
|
|
3812
3869
|
if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
|
|
3813
3870
|
throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
|
|
3814
3871
|
}
|
|
3872
|
+
if (options.retry !== false && attempt < MAX_RETRIES2) {
|
|
3873
|
+
const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
|
|
3874
|
+
console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
|
|
3875
|
+
await waitForRetry(delay3, options.signal);
|
|
3876
|
+
return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
|
|
3877
|
+
}
|
|
3815
3878
|
throw err;
|
|
3816
3879
|
}
|
|
3817
3880
|
try {
|
|
@@ -3890,7 +3953,7 @@ async function waitForRetry(waitMs, signal) {
|
|
|
3890
3953
|
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
3891
3954
|
});
|
|
3892
3955
|
}
|
|
3893
|
-
var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, EmbeddingAPIError, APIEmbeddingProvider;
|
|
3956
|
+
var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, CACHE_LOAD_YIELD_EVERY, EmbeddingAPIError, APIEmbeddingProvider;
|
|
3894
3957
|
var init_api_provider = __esm({
|
|
3895
3958
|
"src/embedding/api-provider.ts"() {
|
|
3896
3959
|
"use strict";
|
|
@@ -3918,6 +3981,7 @@ var init_api_provider = __esm({
|
|
|
3918
3981
|
DASHSCOPE_MAX_BATCH_SIZE = 10;
|
|
3919
3982
|
MAX_RETRIES2 = 3;
|
|
3920
3983
|
BASE_DELAY_MS = 500;
|
|
3984
|
+
CACHE_LOAD_YIELD_EVERY = 32;
|
|
3921
3985
|
EmbeddingAPIError = class extends Error {
|
|
3922
3986
|
status;
|
|
3923
3987
|
constructor(status, detail) {
|
|
@@ -3969,7 +4033,7 @@ var init_api_provider = __esm({
|
|
|
3969
4033
|
console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
|
|
3970
4034
|
}
|
|
3971
4035
|
if (allowNetworkProbe) {
|
|
3972
|
-
startDiskCacheLoad
|
|
4036
|
+
setImmediate(startDiskCacheLoad);
|
|
3973
4037
|
}
|
|
3974
4038
|
return new _APIEmbeddingProvider(config, probeDimensions);
|
|
3975
4039
|
}
|
|
@@ -4041,10 +4105,8 @@ var init_api_provider = __esm({
|
|
|
4041
4105
|
return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
|
|
4042
4106
|
}
|
|
4043
4107
|
const hash4 = textHash2(normalized, this.cacheKeyNamespace);
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
if (cached) return cached;
|
|
4047
|
-
}
|
|
4108
|
+
const cached = cache3.get(hash4);
|
|
4109
|
+
if (cached) return cached;
|
|
4048
4110
|
const apiCall = async () => {
|
|
4049
4111
|
const body = {
|
|
4050
4112
|
model: this.config.model,
|
|
@@ -4069,8 +4131,8 @@ var init_api_provider = __esm({
|
|
|
4069
4131
|
let embedding;
|
|
4070
4132
|
if (!diskCacheLoaded && diskCacheLoadPromise) {
|
|
4071
4133
|
const cacheRace = diskCacheLoadPromise.then(() => {
|
|
4072
|
-
const
|
|
4073
|
-
if (
|
|
4134
|
+
const cached2 = cache3.get(hash4);
|
|
4135
|
+
if (cached2) return cached2;
|
|
4074
4136
|
return null;
|
|
4075
4137
|
});
|
|
4076
4138
|
const result = await Promise.race([
|
|
@@ -5776,6 +5838,7 @@ var sqlite_store_exports = {};
|
|
|
5776
5838
|
__export(sqlite_store_exports, {
|
|
5777
5839
|
SqliteBackend: () => SqliteBackend
|
|
5778
5840
|
});
|
|
5841
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
5779
5842
|
import path7 from "path";
|
|
5780
5843
|
import fs4 from "fs";
|
|
5781
5844
|
function obsToRow(obs) {
|
|
@@ -6164,6 +6227,32 @@ var init_sqlite_store = __esm({
|
|
|
6164
6227
|
}, "Observation atomic write");
|
|
6165
6228
|
try {
|
|
6166
6229
|
const tx = {
|
|
6230
|
+
enqueueMaintenanceJob: async (input) => {
|
|
6231
|
+
const payloadJson = JSON.stringify(input.payload ?? {});
|
|
6232
|
+
const existing = this.db.prepare(`
|
|
6233
|
+
SELECT id, status FROM maintenance_jobs
|
|
6234
|
+
WHERE project_id = ? AND kind = ? AND dedupe_key = ?
|
|
6235
|
+
AND status IN ('pending', 'running', 'retry')
|
|
6236
|
+
LIMIT 1
|
|
6237
|
+
`).get(input.projectId, input.kind, input.dedupeKey);
|
|
6238
|
+
if (existing) {
|
|
6239
|
+
if (existing.status === "running") {
|
|
6240
|
+
this.db.prepare(`
|
|
6241
|
+
UPDATE maintenance_jobs
|
|
6242
|
+
SET rerun_requested = 1, payload_json = ?, updated_at = ?
|
|
6243
|
+
WHERE id = ?
|
|
6244
|
+
`).run(payloadJson, Date.now(), existing.id);
|
|
6245
|
+
}
|
|
6246
|
+
return;
|
|
6247
|
+
}
|
|
6248
|
+
const now3 = Date.now();
|
|
6249
|
+
this.db.prepare(`
|
|
6250
|
+
INSERT INTO maintenance_jobs (
|
|
6251
|
+
id, project_id, kind, dedupe_key, payload_json, status, attempts,
|
|
6252
|
+
max_attempts, run_after, created_at, updated_at
|
|
6253
|
+
) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
|
|
6254
|
+
`).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
|
|
6255
|
+
},
|
|
6167
6256
|
loadAll: async () => this.rawLoadAll(),
|
|
6168
6257
|
getById: async (id) => this.rawGetById(id),
|
|
6169
6258
|
findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
|
|
@@ -6234,6 +6323,7 @@ __export(obs_store_exports, {
|
|
|
6234
6323
|
DegradedBackend: () => DegradedBackend,
|
|
6235
6324
|
createObservationStore: () => createObservationStore,
|
|
6236
6325
|
getObservationStore: () => getObservationStore,
|
|
6326
|
+
getObservationStoreDataDir: () => getObservationStoreDataDir,
|
|
6237
6327
|
initObservationStore: () => initObservationStore,
|
|
6238
6328
|
resetObservationStore: () => resetObservationStore,
|
|
6239
6329
|
setObservationStore: () => setObservationStore
|
|
@@ -6244,6 +6334,12 @@ function getObservationStore() {
|
|
|
6244
6334
|
}
|
|
6245
6335
|
return _store2;
|
|
6246
6336
|
}
|
|
6337
|
+
function getObservationStoreDataDir() {
|
|
6338
|
+
if (!_store2 || !_storeDataDir) {
|
|
6339
|
+
throw new Error("[memorix] ObservationStore data directory is not bound");
|
|
6340
|
+
}
|
|
6341
|
+
return _storeDataDir;
|
|
6342
|
+
}
|
|
6247
6343
|
function setObservationStore(store) {
|
|
6248
6344
|
_store2 = store;
|
|
6249
6345
|
}
|
|
@@ -6422,6 +6518,9 @@ async function loadLanceDb() {
|
|
|
6422
6518
|
return null;
|
|
6423
6519
|
}
|
|
6424
6520
|
}
|
|
6521
|
+
async function isSemanticIndexAvailable() {
|
|
6522
|
+
return await loadLanceDb() !== null;
|
|
6523
|
+
}
|
|
6425
6524
|
function semanticIndexEnabled() {
|
|
6426
6525
|
return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
|
|
6427
6526
|
}
|
|
@@ -6551,6 +6650,22 @@ async function listSemanticVectorIds(dataDir, profile) {
|
|
|
6551
6650
|
const rows = await state.table.query().select(["observation_id"]).toArray();
|
|
6552
6651
|
return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
|
|
6553
6652
|
}
|
|
6653
|
+
async function getSemanticIndexStats(dataDir, profile) {
|
|
6654
|
+
const state = await getState(dataDir, profile);
|
|
6655
|
+
if (!state?.table) return null;
|
|
6656
|
+
return {
|
|
6657
|
+
rowCount: await state.table.countRows(),
|
|
6658
|
+
version: typeof state.table.version === "function" ? await state.table.version() : 0
|
|
6659
|
+
};
|
|
6660
|
+
}
|
|
6661
|
+
function optimizeSemanticIndex(dataDir, profile) {
|
|
6662
|
+
const key = stateKey(dataDir, profile);
|
|
6663
|
+
return queueOperation(key, async () => {
|
|
6664
|
+
const state = await getState(dataDir, profile);
|
|
6665
|
+
if (state) await optimizeState(state);
|
|
6666
|
+
mutationCounts.set(key, 0);
|
|
6667
|
+
});
|
|
6668
|
+
}
|
|
6554
6669
|
function resolveIndexThreshold() {
|
|
6555
6670
|
const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
|
|
6556
6671
|
return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_INDEX_THRESHOLD;
|
|
@@ -6602,6 +6717,20 @@ async function searchSemanticVectors(options) {
|
|
|
6602
6717
|
distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
|
|
6603
6718
|
})).filter((row) => Number.isFinite(row.distance));
|
|
6604
6719
|
}
|
|
6720
|
+
async function closeSemanticIndexProfile(dataDir, profile) {
|
|
6721
|
+
const key = stateKey(dataDir, profile);
|
|
6722
|
+
await flushPendingVectorBatch(key);
|
|
6723
|
+
await writeQueues.get(key);
|
|
6724
|
+
const state = await statePromises.get(key)?.catch(() => null);
|
|
6725
|
+
try {
|
|
6726
|
+
state?.connection?.close?.();
|
|
6727
|
+
} catch {
|
|
6728
|
+
}
|
|
6729
|
+
statePromises.delete(key);
|
|
6730
|
+
writeQueues.delete(key);
|
|
6731
|
+
indexBuilds.delete(key);
|
|
6732
|
+
mutationCounts.delete(key);
|
|
6733
|
+
}
|
|
6605
6734
|
var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, DEFAULT_WRITE_BATCH_SIZE, DEFAULT_WRITE_FLUSH_MS, DEFAULT_OPTIMIZE_EVERY, DEFAULT_VERSION_RETENTION_MS, statePromises, writeQueues, indexBuilds, mutationCounts, pendingVectorBatches, availability, requireFromHere2;
|
|
6606
6735
|
var init_semantic_index = __esm({
|
|
6607
6736
|
"src/search/semantic-index.ts"() {
|
|
@@ -6624,6 +6753,59 @@ var init_semantic_index = __esm({
|
|
|
6624
6753
|
}
|
|
6625
6754
|
});
|
|
6626
6755
|
|
|
6756
|
+
// src/search/semantic-view.ts
|
|
6757
|
+
function createSemanticDerivedView(dataDir, profile) {
|
|
6758
|
+
return {
|
|
6759
|
+
async status() {
|
|
6760
|
+
if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
|
|
6761
|
+
const stats = await getSemanticIndexStats(dataDir, profile);
|
|
6762
|
+
return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
|
|
6763
|
+
},
|
|
6764
|
+
async refresh(records) {
|
|
6765
|
+
if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
|
|
6766
|
+
else await upsertSemanticVectors(dataDir, profile, records);
|
|
6767
|
+
},
|
|
6768
|
+
rebuild: () => ensureSemanticIndex(dataDir, profile),
|
|
6769
|
+
compact: () => optimizeSemanticIndex(dataDir, profile),
|
|
6770
|
+
close: () => closeSemanticIndexProfile(dataDir, profile)
|
|
6771
|
+
};
|
|
6772
|
+
}
|
|
6773
|
+
var init_semantic_view = __esm({
|
|
6774
|
+
"src/search/semantic-view.ts"() {
|
|
6775
|
+
"use strict";
|
|
6776
|
+
init_esm_shims();
|
|
6777
|
+
init_semantic_index();
|
|
6778
|
+
}
|
|
6779
|
+
});
|
|
6780
|
+
|
|
6781
|
+
// src/core/retrieval-contracts.ts
|
|
6782
|
+
function createRetrievalPlan(options) {
|
|
6783
|
+
const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
|
|
6784
|
+
const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
|
|
6785
|
+
return {
|
|
6786
|
+
query: options.query.trim(),
|
|
6787
|
+
quality: options.quality ?? "balanced",
|
|
6788
|
+
limit: Math.max(1, Math.min(1e4, requestedLimit)),
|
|
6789
|
+
...options.projectId ? { projectId: options.projectId } : {},
|
|
6790
|
+
status: options.status ?? "active",
|
|
6791
|
+
...options.source ? { source: options.source } : {},
|
|
6792
|
+
...options.type ? { type: options.type } : {},
|
|
6793
|
+
...options.since ? { since: options.since } : {},
|
|
6794
|
+
...options.until ? { until: options.until } : {},
|
|
6795
|
+
maxTokens: Math.max(0, requestedTokens),
|
|
6796
|
+
trackAccess: options.trackAccess !== false,
|
|
6797
|
+
reader: options.reader,
|
|
6798
|
+
surfacedIds: [...options.surfacedIds ?? []],
|
|
6799
|
+
signal: options.signal
|
|
6800
|
+
};
|
|
6801
|
+
}
|
|
6802
|
+
var init_retrieval_contracts = __esm({
|
|
6803
|
+
"src/core/retrieval-contracts.ts"() {
|
|
6804
|
+
"use strict";
|
|
6805
|
+
init_esm_shims();
|
|
6806
|
+
}
|
|
6807
|
+
});
|
|
6808
|
+
|
|
6627
6809
|
// src/memory/secret-filter.ts
|
|
6628
6810
|
function applyRedaction(text2) {
|
|
6629
6811
|
if (!text2) return text2;
|
|
@@ -7284,6 +7466,7 @@ var orama_store_exports = {};
|
|
|
7284
7466
|
__export(orama_store_exports, {
|
|
7285
7467
|
_classifyQueryTier: () => classifyQueryTier,
|
|
7286
7468
|
batchGenerateEmbeddings: () => batchGenerateEmbeddings,
|
|
7469
|
+
countIndexedDocuments: () => countIndexedDocuments,
|
|
7287
7470
|
createSearchTokenizer: () => createSearchTokenizer,
|
|
7288
7471
|
generateEmbedding: () => generateEmbedding,
|
|
7289
7472
|
generateEmbeddingInput: () => generateEmbeddingInput,
|
|
@@ -7309,6 +7492,7 @@ __export(orama_store_exports, {
|
|
|
7309
7492
|
resetDb: () => resetDb,
|
|
7310
7493
|
resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
|
|
7311
7494
|
searchObservations: () => searchObservations,
|
|
7495
|
+
searchObservationsDetailed: () => searchObservationsDetailed,
|
|
7312
7496
|
updateObservationMetadata: () => updateObservationMetadata
|
|
7313
7497
|
});
|
|
7314
7498
|
import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
|
|
@@ -7497,6 +7681,46 @@ async function searchPersistentLexically(options, projectIds, limit2) {
|
|
|
7497
7681
|
return null;
|
|
7498
7682
|
}
|
|
7499
7683
|
}
|
|
7684
|
+
async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
|
|
7685
|
+
try {
|
|
7686
|
+
const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
|
|
7687
|
+
const dataDir = getObservationDataDir2();
|
|
7688
|
+
if (!dataDir) return null;
|
|
7689
|
+
const vectorHits = await searchSemanticVectors({
|
|
7690
|
+
dataDir,
|
|
7691
|
+
profile: createSemanticIndexProfile(provider2),
|
|
7692
|
+
vector: queryVector,
|
|
7693
|
+
projectId: projectIds ?? options.projectId,
|
|
7694
|
+
status: "all",
|
|
7695
|
+
limit: Math.min(1e4, Math.max(limit2, 1) * 4)
|
|
7696
|
+
});
|
|
7697
|
+
if (!vectorHits || vectorHits.length === 0) return null;
|
|
7698
|
+
const store = getObservationStore();
|
|
7699
|
+
const hits = [];
|
|
7700
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7701
|
+
for (const hit of vectorHits) {
|
|
7702
|
+
if (seen.has(hit.observationId)) continue;
|
|
7703
|
+
seen.add(hit.observationId);
|
|
7704
|
+
const observation = await store.getById(hit.observationId);
|
|
7705
|
+
if (!observation) continue;
|
|
7706
|
+
if (projectIds && !projectIds.includes(observation.projectId)) continue;
|
|
7707
|
+
if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
|
|
7708
|
+
if (options.type && observation.type !== options.type) continue;
|
|
7709
|
+
if (options.source && observation.source !== options.source) continue;
|
|
7710
|
+
const document2 = observationToSearchDocument(observation);
|
|
7711
|
+
hits.push({
|
|
7712
|
+
id: document2.id,
|
|
7713
|
+
score: 1 / (1 + hits.length),
|
|
7714
|
+
document: document2
|
|
7715
|
+
});
|
|
7716
|
+
if (hits.length >= limit2) break;
|
|
7717
|
+
}
|
|
7718
|
+
if (hits.length === 0) return null;
|
|
7719
|
+
return { count: hits.length, hits };
|
|
7720
|
+
} catch {
|
|
7721
|
+
return null;
|
|
7722
|
+
}
|
|
7723
|
+
}
|
|
7500
7724
|
async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
|
|
7501
7725
|
try {
|
|
7502
7726
|
const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
|
|
@@ -7661,6 +7885,9 @@ async function getDb(options = {}) {
|
|
|
7661
7885
|
}
|
|
7662
7886
|
}
|
|
7663
7887
|
}
|
|
7888
|
+
async function countIndexedDocuments(database) {
|
|
7889
|
+
return count(database ?? await getDb({ allowNetworkProbe: false }));
|
|
7890
|
+
}
|
|
7664
7891
|
async function resetDb() {
|
|
7665
7892
|
dbGeneration++;
|
|
7666
7893
|
db = null;
|
|
@@ -7690,7 +7917,7 @@ async function queueSemanticVector(dataDir, record80) {
|
|
|
7690
7917
|
const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
|
|
7691
7918
|
if (!profile) return;
|
|
7692
7919
|
try {
|
|
7693
|
-
await
|
|
7920
|
+
await createSemanticDerivedView(dataDir, profile).refresh([record80]);
|
|
7694
7921
|
} catch {
|
|
7695
7922
|
}
|
|
7696
7923
|
}
|
|
@@ -7781,7 +8008,7 @@ async function attachCachedVectors(database, observations2) {
|
|
|
7781
8008
|
}
|
|
7782
8009
|
}
|
|
7783
8010
|
if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
|
|
7784
|
-
void
|
|
8011
|
+
void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
|
|
7785
8012
|
});
|
|
7786
8013
|
}
|
|
7787
8014
|
await new Promise((resolve2) => setImmediate(resolve2));
|
|
@@ -7892,7 +8119,9 @@ async function removeObservation(oramaId) {
|
|
|
7892
8119
|
const database = await getDb();
|
|
7893
8120
|
await remove2(database, oramaId);
|
|
7894
8121
|
}
|
|
7895
|
-
async function
|
|
8122
|
+
async function searchObservationsDetailed(options) {
|
|
8123
|
+
const retrievalPlan = createRetrievalPlan(options);
|
|
8124
|
+
options = { ...options, ...retrievalPlan };
|
|
7896
8125
|
const searchStartedAt = Date.now();
|
|
7897
8126
|
const perf = !!process.env.MEMORIX_PERF;
|
|
7898
8127
|
const t0 = perf ? performance.now() : 0;
|
|
@@ -7906,10 +8135,12 @@ async function searchObservations(options) {
|
|
|
7906
8135
|
const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
|
|
7907
8136
|
const quality = options.quality ?? "balanced";
|
|
7908
8137
|
const database = await getDb();
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
8138
|
+
let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
|
|
8139
|
+
const setMode = (mode) => {
|
|
8140
|
+
requestMode = mode;
|
|
8141
|
+
rememberSearchMode(modeKey, mode);
|
|
8142
|
+
};
|
|
8143
|
+
setMode(requestMode);
|
|
7913
8144
|
let projectIds = null;
|
|
7914
8145
|
if (options.projectId) {
|
|
7915
8146
|
try {
|
|
@@ -7930,7 +8161,7 @@ async function searchObservations(options) {
|
|
|
7930
8161
|
filters["source"] = options.source;
|
|
7931
8162
|
}
|
|
7932
8163
|
const hasQuery = options.query && options.query.trim().length > 0;
|
|
7933
|
-
const originalQuery =
|
|
8164
|
+
const originalQuery = retrievalPlan.query;
|
|
7934
8165
|
const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
|
|
7935
8166
|
mark(`tier=${tier}`);
|
|
7936
8167
|
if (quality === "thorough" && hasQuery) {
|
|
@@ -7984,10 +8215,7 @@ async function searchObservations(options) {
|
|
|
7984
8215
|
embeddingUnavailable = true;
|
|
7985
8216
|
fallbackUsed = true;
|
|
7986
8217
|
fallbackReason = "embedding dimension mismatch; lexical search used";
|
|
7987
|
-
|
|
7988
|
-
modeKey,
|
|
7989
|
-
`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`
|
|
7990
|
-
);
|
|
8218
|
+
setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
|
|
7991
8219
|
console.error(
|
|
7992
8220
|
`[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
|
|
7993
8221
|
);
|
|
@@ -8009,7 +8237,7 @@ async function searchObservations(options) {
|
|
|
8009
8237
|
mark("embedding");
|
|
8010
8238
|
const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
|
|
8011
8239
|
const isCJKHeavy = cjkRatio > 0.3;
|
|
8012
|
-
|
|
8240
|
+
setMode("hybrid");
|
|
8013
8241
|
searchParams = {
|
|
8014
8242
|
...searchParams,
|
|
8015
8243
|
mode: "hybrid",
|
|
@@ -8032,32 +8260,41 @@ async function searchObservations(options) {
|
|
|
8032
8260
|
embeddingUnavailable = true;
|
|
8033
8261
|
fallbackUsed = true;
|
|
8034
8262
|
fallbackReason = "embedding failed or timed out; lexical search used";
|
|
8035
|
-
|
|
8263
|
+
setMode("fulltext (embedding unavailable)");
|
|
8036
8264
|
console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
|
|
8037
8265
|
}
|
|
8038
8266
|
}
|
|
8039
8267
|
mark("preSearch");
|
|
8040
8268
|
let results;
|
|
8269
|
+
const retrieval = getResolvedConfig().retrieval;
|
|
8270
|
+
const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
|
|
8271
|
+
let lanceOrderUsed = false;
|
|
8272
|
+
let persistent = null;
|
|
8273
|
+
if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
|
|
8274
|
+
persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
|
|
8275
|
+
if (persistent) lanceOrderUsed = true;
|
|
8276
|
+
else {
|
|
8277
|
+
fallbackUsed = true;
|
|
8278
|
+
fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
|
|
8279
|
+
}
|
|
8280
|
+
}
|
|
8041
8281
|
const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
|
|
8042
8282
|
const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector && (quality === "fast" || tier === "fast" || !embeddingEnabled || embeddingUnavailable);
|
|
8043
|
-
|
|
8283
|
+
if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
|
|
8044
8284
|
const durableStore = getOptionalObservationStore();
|
|
8045
8285
|
if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
|
|
8046
8286
|
persistent = await searchPersistentLexically(options, projectIds, requestLimit);
|
|
8047
8287
|
}
|
|
8048
8288
|
if (persistent) {
|
|
8049
8289
|
results = persistent;
|
|
8050
|
-
|
|
8051
|
-
modeKey,
|
|
8052
|
-
queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
|
|
8053
|
-
);
|
|
8290
|
+
setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
|
|
8054
8291
|
mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
|
|
8055
8292
|
} else {
|
|
8056
8293
|
try {
|
|
8057
8294
|
results = await search(database, searchParams);
|
|
8058
8295
|
} catch (error) {
|
|
8059
8296
|
if (queryVector && isVectorDimensionMismatchError(error)) {
|
|
8060
|
-
|
|
8297
|
+
setMode("fulltext (embedding dimension mismatch)");
|
|
8061
8298
|
console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
|
|
8062
8299
|
results = await search(database, stripVectorSearchParams(searchParams));
|
|
8063
8300
|
} else {
|
|
@@ -8080,7 +8317,7 @@ async function searchObservations(options) {
|
|
|
8080
8317
|
},
|
|
8081
8318
|
similarity: 0.25
|
|
8082
8319
|
};
|
|
8083
|
-
|
|
8320
|
+
setMode("vector-only (hybrid empty fallback)");
|
|
8084
8321
|
fallbackUsed = true;
|
|
8085
8322
|
fallbackReason = "hybrid search returned no results; vector-only fallback used";
|
|
8086
8323
|
results = await search(database, vectorOnlyParams);
|
|
@@ -8325,7 +8562,7 @@ async function searchObservations(options) {
|
|
|
8325
8562
|
const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
|
|
8326
8563
|
if (rerankedTop.length > 0) {
|
|
8327
8564
|
intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
|
|
8328
|
-
|
|
8565
|
+
setMode(requestMode + " + neural rerank");
|
|
8329
8566
|
mark("rerank(usedNeural=true)");
|
|
8330
8567
|
}
|
|
8331
8568
|
}
|
|
@@ -8342,7 +8579,7 @@ async function searchObservations(options) {
|
|
|
8342
8579
|
);
|
|
8343
8580
|
mark(`rerank(usedLLM=${usedLLM})`);
|
|
8344
8581
|
if (usedLLM) {
|
|
8345
|
-
|
|
8582
|
+
setMode(requestMode + " + LLM rerank");
|
|
8346
8583
|
const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
|
|
8347
8584
|
if (rerankedTop.length > 0) {
|
|
8348
8585
|
intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
|
|
@@ -8405,9 +8642,9 @@ async function searchObservations(options) {
|
|
|
8405
8642
|
if (options.maxTokens && options.maxTokens > 0) {
|
|
8406
8643
|
entries = applyTokenBudget(entries, options.maxTokens);
|
|
8407
8644
|
}
|
|
8408
|
-
|
|
8645
|
+
const diagnostics = {
|
|
8409
8646
|
version: "1",
|
|
8410
|
-
mode:
|
|
8647
|
+
mode: requestMode,
|
|
8411
8648
|
rawCandidateCount: results.hits.length,
|
|
8412
8649
|
candidateCount,
|
|
8413
8650
|
selectedCount: entries.length,
|
|
@@ -8416,14 +8653,25 @@ async function searchObservations(options) {
|
|
|
8416
8653
|
fallbackUsed,
|
|
8417
8654
|
...fallbackReason ? { fallbackReason } : {},
|
|
8418
8655
|
elapsedMs: Math.max(0, Date.now() - searchStartedAt)
|
|
8419
|
-
}
|
|
8420
|
-
|
|
8421
|
-
|
|
8656
|
+
};
|
|
8657
|
+
rememberSearchDiagnostics(modeKey, diagnostics);
|
|
8658
|
+
const recordAccess = (selected) => {
|
|
8659
|
+
if (options.trackAccess === false || selected.length === 0) return;
|
|
8660
|
+
const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
|
|
8422
8661
|
const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
|
|
8423
8662
|
recordAccessBatch(hitDocs).catch(() => {
|
|
8424
8663
|
});
|
|
8664
|
+
};
|
|
8665
|
+
const derivedViews = getSearchDerivedViews();
|
|
8666
|
+
if (fallbackUsed && fallbackReason) {
|
|
8667
|
+
derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
|
|
8425
8668
|
}
|
|
8426
|
-
return entries;
|
|
8669
|
+
return { entries, diagnostics, derivedViews, recordAccess };
|
|
8670
|
+
}
|
|
8671
|
+
async function searchObservations(options) {
|
|
8672
|
+
const result = await searchObservationsDetailed(options);
|
|
8673
|
+
result.recordAccess?.(result.entries);
|
|
8674
|
+
return result.entries;
|
|
8427
8675
|
}
|
|
8428
8676
|
async function getObservationsByIds(ids, projectId) {
|
|
8429
8677
|
const database = await getDb();
|
|
@@ -8548,6 +8796,10 @@ var init_orama_store = __esm({
|
|
|
8548
8796
|
init_policy();
|
|
8549
8797
|
init_timeout();
|
|
8550
8798
|
init_obs_store();
|
|
8799
|
+
init_resolved_config();
|
|
8800
|
+
init_retrieval_strategy();
|
|
8801
|
+
init_semantic_view();
|
|
8802
|
+
init_retrieval_contracts();
|
|
8551
8803
|
init_semantic_index();
|
|
8552
8804
|
init_derived_view_receipt();
|
|
8553
8805
|
db = null;
|
|
@@ -8674,6 +8926,24 @@ var init_entity_extractor = __esm({
|
|
|
8674
8926
|
}
|
|
8675
8927
|
});
|
|
8676
8928
|
|
|
8929
|
+
// src/core/maintenance-result.ts
|
|
8930
|
+
function assertMaintenanceProgress(progress) {
|
|
8931
|
+
if (!progress) return;
|
|
8932
|
+
const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
|
|
8933
|
+
if (counts.some((count2) => !Number.isSafeInteger(count2) || count2 < 0)) {
|
|
8934
|
+
throw new Error("maintenance progress must contain non-negative safe integers");
|
|
8935
|
+
}
|
|
8936
|
+
if (progress.succeeded + progress.failed > progress.attempted) {
|
|
8937
|
+
throw new Error("maintenance progress outcomes exceed attempted work");
|
|
8938
|
+
}
|
|
8939
|
+
}
|
|
8940
|
+
var init_maintenance_result = __esm({
|
|
8941
|
+
"src/core/maintenance-result.ts"() {
|
|
8942
|
+
"use strict";
|
|
8943
|
+
init_esm_shims();
|
|
8944
|
+
}
|
|
8945
|
+
});
|
|
8946
|
+
|
|
8677
8947
|
// src/runtime/maintenance-jobs.ts
|
|
8678
8948
|
var maintenance_jobs_exports = {};
|
|
8679
8949
|
__export(maintenance_jobs_exports, {
|
|
@@ -8683,7 +8953,7 @@ __export(maintenance_jobs_exports, {
|
|
|
8683
8953
|
MaintenanceJobWorker: () => MaintenanceJobWorker,
|
|
8684
8954
|
getMaintenanceRetryDelayMs: () => getMaintenanceRetryDelayMs
|
|
8685
8955
|
});
|
|
8686
|
-
import { randomUUID as
|
|
8956
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
8687
8957
|
function parsePayload(raw) {
|
|
8688
8958
|
if (typeof raw !== "string" || !raw) return {};
|
|
8689
8959
|
try {
|
|
@@ -8707,6 +8977,12 @@ function rowToJob(row) {
|
|
|
8707
8977
|
...row.lease_owner ? { leaseOwner: row.lease_owner } : {},
|
|
8708
8978
|
...row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {},
|
|
8709
8979
|
...row.last_error ? { lastError: row.last_error } : {},
|
|
8980
|
+
...Number(row.progress_recorded ?? 0) === 1 ? { progress: {
|
|
8981
|
+
attempted: Number(row.attempted ?? 0),
|
|
8982
|
+
succeeded: Number(row.succeeded ?? 0),
|
|
8983
|
+
failed: Number(row.failed ?? 0),
|
|
8984
|
+
remaining: Number(row.remaining ?? 0)
|
|
8985
|
+
} } : {},
|
|
8710
8986
|
createdAt: Number(row.created_at),
|
|
8711
8987
|
updatedAt: Number(row.updated_at),
|
|
8712
8988
|
...row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}
|
|
@@ -8732,6 +9008,7 @@ var init_maintenance_jobs = __esm({
|
|
|
8732
9008
|
"src/runtime/maintenance-jobs.ts"() {
|
|
8733
9009
|
"use strict";
|
|
8734
9010
|
init_esm_shims();
|
|
9011
|
+
init_maintenance_result();
|
|
8735
9012
|
init_sqlite_db();
|
|
8736
9013
|
init_secret_filter();
|
|
8737
9014
|
MAINTENANCE_JOB_KINDS = [
|
|
@@ -8742,6 +9019,7 @@ var init_maintenance_jobs = __esm({
|
|
|
8742
9019
|
"consolidation",
|
|
8743
9020
|
"codegraph-refresh",
|
|
8744
9021
|
"observation-qualify",
|
|
9022
|
+
"observation-project",
|
|
8745
9023
|
"claim-derive",
|
|
8746
9024
|
"claim-requalification",
|
|
8747
9025
|
"knowledge-compile",
|
|
@@ -8780,6 +9058,16 @@ var init_maintenance_jobs = __esm({
|
|
|
8780
9058
|
this.commit();
|
|
8781
9059
|
return rowToJob(existing);
|
|
8782
9060
|
}
|
|
9061
|
+
if (existing.status === "running") {
|
|
9062
|
+
this.db.prepare(`
|
|
9063
|
+
UPDATE maintenance_jobs
|
|
9064
|
+
SET rerun_requested = 1, payload_json = ?, updated_at = ?
|
|
9065
|
+
WHERE id = ?
|
|
9066
|
+
`).run(payloadJson, now3, existing.id);
|
|
9067
|
+
const updated2 = this.getRow(existing.id);
|
|
9068
|
+
this.commit();
|
|
9069
|
+
return rowToJob(updated2);
|
|
9070
|
+
}
|
|
8783
9071
|
const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
|
|
8784
9072
|
this.db.prepare(`
|
|
8785
9073
|
UPDATE maintenance_jobs
|
|
@@ -8810,7 +9098,7 @@ var init_maintenance_jobs = __esm({
|
|
|
8810
9098
|
return rowToJob(revived);
|
|
8811
9099
|
}
|
|
8812
9100
|
}
|
|
8813
|
-
const id =
|
|
9101
|
+
const id = randomUUID3();
|
|
8814
9102
|
this.db.prepare(`
|
|
8815
9103
|
INSERT INTO maintenance_jobs (
|
|
8816
9104
|
id, project_id, kind, dedupe_key, payload_json, status, attempts,
|
|
@@ -8907,8 +9195,10 @@ var init_maintenance_jobs = __esm({
|
|
|
8907
9195
|
this.db.prepare(`
|
|
8908
9196
|
UPDATE maintenance_jobs
|
|
8909
9197
|
SET
|
|
8910
|
-
status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'retry' END,
|
|
8911
|
-
run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE ? END,
|
|
9198
|
+
status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
|
|
9199
|
+
run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
|
|
9200
|
+
attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
|
|
9201
|
+
rerun_requested = 0,
|
|
8912
9202
|
lease_owner = NULL,
|
|
8913
9203
|
lease_expires_at = NULL,
|
|
8914
9204
|
last_error = COALESCE(last_error, 'worker lease expired'),
|
|
@@ -8971,14 +9261,55 @@ var init_maintenance_jobs = __esm({
|
|
|
8971
9261
|
`).run(expiresAt, now3, id, workerId);
|
|
8972
9262
|
return Number(result.changes) > 0;
|
|
8973
9263
|
}
|
|
8974
|
-
complete(id, workerId, now3 = Date.now()) {
|
|
8975
|
-
|
|
8976
|
-
|
|
8977
|
-
|
|
8978
|
-
|
|
8979
|
-
|
|
8980
|
-
|
|
8981
|
-
|
|
9264
|
+
complete(id, workerId, now3 = Date.now(), progress) {
|
|
9265
|
+
assertMaintenanceProgress(progress);
|
|
9266
|
+
this.begin();
|
|
9267
|
+
try {
|
|
9268
|
+
const current = this.db.prepare(`
|
|
9269
|
+
SELECT rerun_requested FROM maintenance_jobs
|
|
9270
|
+
WHERE id = ? AND status = 'running' AND lease_owner = ?
|
|
9271
|
+
`).get(id, workerId);
|
|
9272
|
+
if (!current) {
|
|
9273
|
+
this.commit();
|
|
9274
|
+
return void 0;
|
|
9275
|
+
}
|
|
9276
|
+
if (Number(current.rerun_requested) === 1) {
|
|
9277
|
+
this.db.prepare(`
|
|
9278
|
+
UPDATE maintenance_jobs
|
|
9279
|
+
SET status = 'pending', attempts = 0, run_after = ?,
|
|
9280
|
+
rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
|
|
9281
|
+
attempted = 0, succeeded = 0, failed = 0, remaining = 0,
|
|
9282
|
+
progress_recorded = 0, last_error = NULL, completed_at = NULL,
|
|
9283
|
+
updated_at = ?
|
|
9284
|
+
WHERE id = ?
|
|
9285
|
+
`).run(now3, now3, id);
|
|
9286
|
+
} else {
|
|
9287
|
+
this.db.prepare(`
|
|
9288
|
+
UPDATE maintenance_jobs
|
|
9289
|
+
SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
|
|
9290
|
+
attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
|
|
9291
|
+
failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
|
|
9292
|
+
progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
|
|
9293
|
+
completed_at = ?, updated_at = ?
|
|
9294
|
+
WHERE id = ?
|
|
9295
|
+
`).run(
|
|
9296
|
+
progress?.attempted ?? null,
|
|
9297
|
+
progress?.succeeded ?? null,
|
|
9298
|
+
progress?.failed ?? null,
|
|
9299
|
+
progress?.remaining ?? null,
|
|
9300
|
+
progress ? 1 : 0,
|
|
9301
|
+
now3,
|
|
9302
|
+
now3,
|
|
9303
|
+
id
|
|
9304
|
+
);
|
|
9305
|
+
}
|
|
9306
|
+
const updated = this.get(id);
|
|
9307
|
+
this.commit();
|
|
9308
|
+
return updated;
|
|
9309
|
+
} catch (error) {
|
|
9310
|
+
this.rollback();
|
|
9311
|
+
throw error;
|
|
9312
|
+
}
|
|
8982
9313
|
}
|
|
8983
9314
|
reschedule(id, workerId, options) {
|
|
8984
9315
|
const now3 = options.now ?? Date.now();
|
|
@@ -8987,22 +9318,37 @@ var init_maintenance_jobs = __esm({
|
|
|
8987
9318
|
const status = options.status === "retry" ? "retry" : "pending";
|
|
8988
9319
|
const hasLastError = options.lastError !== void 0;
|
|
8989
9320
|
const lastError = hasLastError ? errorText(options.lastError) : null;
|
|
9321
|
+
const progress = options.progress;
|
|
9322
|
+
assertMaintenanceProgress(progress);
|
|
8990
9323
|
this.db.prepare(`
|
|
8991
9324
|
UPDATE maintenance_jobs
|
|
8992
|
-
SET status = ?,
|
|
8993
|
-
|
|
9325
|
+
SET status = ?,
|
|
9326
|
+
run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
|
|
9327
|
+
attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
|
|
9328
|
+
payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
|
|
9329
|
+
attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
|
|
9330
|
+
failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
|
|
9331
|
+
progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
|
|
8994
9332
|
last_error = CASE
|
|
8995
9333
|
WHEN ? THEN NULL
|
|
8996
9334
|
WHEN ? THEN ?
|
|
8997
9335
|
ELSE last_error
|
|
8998
9336
|
END,
|
|
8999
|
-
lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
9337
|
+
rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
9000
9338
|
WHERE id = ? AND status = 'running' AND lease_owner = ?
|
|
9001
9339
|
`).run(
|
|
9002
9340
|
status,
|
|
9341
|
+
status === "retry" ? 1 : 0,
|
|
9342
|
+
now3,
|
|
9003
9343
|
now3 + delayMs,
|
|
9344
|
+
status === "retry" ? 1 : 0,
|
|
9004
9345
|
options.resetAttempts ? 1 : 0,
|
|
9005
9346
|
payloadJson,
|
|
9347
|
+
progress?.attempted ?? null,
|
|
9348
|
+
progress?.succeeded ?? null,
|
|
9349
|
+
progress?.failed ?? null,
|
|
9350
|
+
progress?.remaining ?? null,
|
|
9351
|
+
progress ? 1 : 0,
|
|
9006
9352
|
options.clearLastError ? 1 : 0,
|
|
9007
9353
|
hasLastError ? 1 : 0,
|
|
9008
9354
|
lastError,
|
|
@@ -9020,6 +9366,15 @@ var init_maintenance_jobs = __esm({
|
|
|
9020
9366
|
`).run(now3, now3, projectId, dedupeKey);
|
|
9021
9367
|
return Number(result.changes ?? 0);
|
|
9022
9368
|
}
|
|
9369
|
+
/** A successful foreground projection can acknowledge its pending outbox row. */
|
|
9370
|
+
acknowledgePending(projectId, kind, dedupeKey, now3 = Date.now()) {
|
|
9371
|
+
const result = this.db.prepare(`
|
|
9372
|
+
UPDATE maintenance_jobs
|
|
9373
|
+
SET status = 'completed', completed_at = ?, updated_at = ?
|
|
9374
|
+
WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
|
|
9375
|
+
`).run(now3, now3, projectId, kind, dedupeKey);
|
|
9376
|
+
return Number(result.changes ?? 0);
|
|
9377
|
+
}
|
|
9023
9378
|
fail(id, workerId, error, now3 = Date.now()) {
|
|
9024
9379
|
this.begin();
|
|
9025
9380
|
try {
|
|
@@ -9032,15 +9387,18 @@ var init_maintenance_jobs = __esm({
|
|
|
9032
9387
|
return void 0;
|
|
9033
9388
|
}
|
|
9034
9389
|
const attempts = Number(current.attempts);
|
|
9035
|
-
const
|
|
9390
|
+
const rerunRequested = Number(current.rerun_requested) === 1;
|
|
9391
|
+
const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
|
|
9036
9392
|
const status = exhausted ? "failed" : "retry";
|
|
9037
9393
|
const runAfter = exhausted ? Number(current.run_after) : now3 + getMaintenanceRetryDelayMs(attempts);
|
|
9394
|
+
const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
|
|
9038
9395
|
this.db.prepare(`
|
|
9039
9396
|
UPDATE maintenance_jobs
|
|
9040
|
-
SET status = ?, run_after = ?,
|
|
9397
|
+
SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
|
|
9398
|
+
lease_owner = NULL, lease_expires_at = NULL,
|
|
9041
9399
|
last_error = ?, updated_at = ?
|
|
9042
9400
|
WHERE id = ?
|
|
9043
|
-
`).run(status, runAfter, errorText(error), now3, id);
|
|
9401
|
+
`).run(status, runAfter, nextAttempts, errorText(error), now3, id);
|
|
9044
9402
|
const updated = this.getRow(id);
|
|
9045
9403
|
this.commit();
|
|
9046
9404
|
return rowToJob(updated);
|
|
@@ -9069,7 +9427,7 @@ var init_maintenance_jobs = __esm({
|
|
|
9069
9427
|
constructor(store, handler, options = {}) {
|
|
9070
9428
|
this.store = store;
|
|
9071
9429
|
this.handler = handler;
|
|
9072
|
-
this.workerId = options.workerId ?? `memorix-${process.pid}-${
|
|
9430
|
+
this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID3().slice(0, 8)}`;
|
|
9073
9431
|
this.leaseMs = clampPositiveInteger(options.leaseMs, DEFAULT_LEASE_MS);
|
|
9074
9432
|
this.pollIntervalMs = clampPositiveInteger(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS);
|
|
9075
9433
|
this.projectId = options.projectId;
|
|
@@ -9118,12 +9476,16 @@ var init_maintenance_jobs = __esm({
|
|
|
9118
9476
|
status: result.status,
|
|
9119
9477
|
lastError: result.lastError,
|
|
9120
9478
|
clearLastError: result.clearLastError,
|
|
9479
|
+
progress: result.progress,
|
|
9121
9480
|
now: now3
|
|
9122
9481
|
});
|
|
9123
9482
|
return { state: "rescheduled", job: updated2 };
|
|
9124
9483
|
}
|
|
9125
|
-
|
|
9126
|
-
|
|
9484
|
+
if (result?.progress && result.progress.remaining > 0) {
|
|
9485
|
+
throw new Error("maintenance job reported completion with remaining work");
|
|
9486
|
+
}
|
|
9487
|
+
const updated = this.store.complete(job.id, this.workerId, now3, result?.progress);
|
|
9488
|
+
return { state: updated?.status === "pending" ? "rescheduled" : "completed", job: updated };
|
|
9127
9489
|
} catch (error) {
|
|
9128
9490
|
const updated = this.store.fail(job.id, this.workerId, error, now3);
|
|
9129
9491
|
return { state: "failed", job: updated };
|
|
@@ -9221,7 +9583,12 @@ var init_lifecycle = __esm({
|
|
|
9221
9583
|
});
|
|
9222
9584
|
|
|
9223
9585
|
// src/store/evidence-store.ts
|
|
9224
|
-
|
|
9586
|
+
var evidence_store_exports = {};
|
|
9587
|
+
__export(evidence_store_exports, {
|
|
9588
|
+
EvidenceCardStore: () => EvidenceCardStore,
|
|
9589
|
+
buildEvidenceCardId: () => buildEvidenceCardId
|
|
9590
|
+
});
|
|
9591
|
+
import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
|
|
9225
9592
|
function safeJson(value, fallback) {
|
|
9226
9593
|
if (typeof value !== "string" || value.length === 0) return fallback;
|
|
9227
9594
|
try {
|
|
@@ -9270,6 +9637,9 @@ function sourceKind(observation) {
|
|
|
9270
9637
|
if (observation.sourceDetail === "hook") return "hook";
|
|
9271
9638
|
return observation.source ?? "agent";
|
|
9272
9639
|
}
|
|
9640
|
+
function buildEvidenceCardId(projectId, candidateKind, candidateId) {
|
|
9641
|
+
return `evidence:${candidateKind}:${projectId}:${candidateId}`;
|
|
9642
|
+
}
|
|
9273
9643
|
var EvidenceCardStore;
|
|
9274
9644
|
var init_evidence_store = __esm({
|
|
9275
9645
|
"src/store/evidence-store.ts"() {
|
|
@@ -9410,7 +9780,7 @@ var init_evidence_store = __esm({
|
|
|
9410
9780
|
}
|
|
9411
9781
|
recordEvent(projectId, cardId, kind, detail) {
|
|
9412
9782
|
const event = {
|
|
9413
|
-
id:
|
|
9783
|
+
id: randomUUID4(),
|
|
9414
9784
|
projectId,
|
|
9415
9785
|
cardId,
|
|
9416
9786
|
kind,
|
|
@@ -9491,7 +9861,7 @@ var init_maintenance_targets = __esm({
|
|
|
9491
9861
|
});
|
|
9492
9862
|
|
|
9493
9863
|
// src/knowledge/workspace-store.ts
|
|
9494
|
-
import { randomUUID as
|
|
9864
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
9495
9865
|
function arrayValue(raw) {
|
|
9496
9866
|
if (typeof raw !== "string" || !raw) return [];
|
|
9497
9867
|
try {
|
|
@@ -9632,7 +10002,7 @@ var init_workspace_store = __esm({
|
|
|
9632
10002
|
}
|
|
9633
10003
|
createProposal(input) {
|
|
9634
10004
|
const proposal = {
|
|
9635
|
-
id: input.id ??
|
|
10005
|
+
id: input.id ?? randomUUID5(),
|
|
9636
10006
|
...input,
|
|
9637
10007
|
status: input.status ?? "pending",
|
|
9638
10008
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -9918,11 +10288,11 @@ __export(consolidation_exports, {
|
|
|
9918
10288
|
});
|
|
9919
10289
|
function tokenize(text2) {
|
|
9920
10290
|
return new Set(
|
|
9921
|
-
text2.toLowerCase().replace(/[
|
|
10291
|
+
text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
|
|
9922
10292
|
);
|
|
9923
10293
|
}
|
|
9924
10294
|
function jaccardSimilarity(a, b) {
|
|
9925
|
-
if (a.size === 0 && b.size === 0) return
|
|
10295
|
+
if (a.size === 0 && b.size === 0) return 0;
|
|
9926
10296
|
let intersection = 0;
|
|
9927
10297
|
for (const token of a) {
|
|
9928
10298
|
if (b.has(token)) intersection++;
|
|
@@ -10288,7 +10658,7 @@ Respond in JSON only:
|
|
|
10288
10658
|
});
|
|
10289
10659
|
|
|
10290
10660
|
// src/media/media-store.ts
|
|
10291
|
-
import { randomUUID as
|
|
10661
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
10292
10662
|
function asOptionalText(value) {
|
|
10293
10663
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
10294
10664
|
}
|
|
@@ -10458,7 +10828,7 @@ var init_media_store = __esm({
|
|
|
10458
10828
|
return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
|
|
10459
10829
|
}
|
|
10460
10830
|
const asset = {
|
|
10461
|
-
id:
|
|
10831
|
+
id: randomUUID6(),
|
|
10462
10832
|
...input,
|
|
10463
10833
|
createdAt: now3,
|
|
10464
10834
|
updatedAt: now3
|
|
@@ -10538,7 +10908,7 @@ var init_media_store = __esm({
|
|
|
10538
10908
|
`).get(input.assetId, input.observationId ?? null, input.role);
|
|
10539
10909
|
if (existing) return rowToLink(existing);
|
|
10540
10910
|
const link = {
|
|
10541
|
-
id:
|
|
10911
|
+
id: randomUUID6(),
|
|
10542
10912
|
assetId: input.assetId,
|
|
10543
10913
|
projectId: input.projectId,
|
|
10544
10914
|
...input.observationId !== void 0 ? { observationId: input.observationId } : {},
|
|
@@ -10577,7 +10947,7 @@ var init_media_store = __esm({
|
|
|
10577
10947
|
return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
|
|
10578
10948
|
}
|
|
10579
10949
|
const derivation = {
|
|
10580
|
-
id:
|
|
10950
|
+
id: randomUUID6(),
|
|
10581
10951
|
...input,
|
|
10582
10952
|
content,
|
|
10583
10953
|
...error ? { error } : {},
|
|
@@ -10664,7 +11034,7 @@ var init_media_store = __esm({
|
|
|
10664
11034
|
createJob(input) {
|
|
10665
11035
|
const now3 = Date.now();
|
|
10666
11036
|
const job = {
|
|
10667
|
-
id:
|
|
11037
|
+
id: randomUUID6(),
|
|
10668
11038
|
projectId: input.projectId,
|
|
10669
11039
|
kind: input.kind,
|
|
10670
11040
|
status: "queued",
|
|
@@ -10826,7 +11196,7 @@ var init_types2 = __esm({
|
|
|
10826
11196
|
});
|
|
10827
11197
|
|
|
10828
11198
|
// src/media/asset-store.ts
|
|
10829
|
-
import { createHash as createHash7, randomUUID as
|
|
11199
|
+
import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
|
|
10830
11200
|
import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
|
|
10831
11201
|
import path11 from "path";
|
|
10832
11202
|
function mediaRoot(dataDir) {
|
|
@@ -10897,7 +11267,7 @@ async function destinationExists(destination) {
|
|
|
10897
11267
|
async function persistBuffer(bytes, destination) {
|
|
10898
11268
|
await mkdir3(path11.dirname(destination), { recursive: true });
|
|
10899
11269
|
if (await destinationExists(destination)) return false;
|
|
10900
|
-
const temporary = `${destination}.${
|
|
11270
|
+
const temporary = `${destination}.${randomUUID7()}.tmp`;
|
|
10901
11271
|
try {
|
|
10902
11272
|
await writeFile3(temporary, bytes, { flag: "wx" });
|
|
10903
11273
|
await rename2(temporary, destination);
|
|
@@ -63799,7 +64169,7 @@ var require_gaxios = __commonJS({
|
|
|
63799
64169
|
var retry_js_1 = require_retry3();
|
|
63800
64170
|
var stream_1 = __require("stream");
|
|
63801
64171
|
var interceptor_js_1 = require_interceptor();
|
|
63802
|
-
var
|
|
64172
|
+
var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
|
|
63803
64173
|
var HTTP_STATUS_NO_CONTENT = 204;
|
|
63804
64174
|
var Gaxios = class {
|
|
63805
64175
|
agentCache = /* @__PURE__ */ new Map();
|
|
@@ -64072,7 +64442,7 @@ var require_gaxios = __commonJS({
|
|
|
64072
64442
|
*/
|
|
64073
64443
|
["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
|
|
64074
64444
|
if (opts.multipart?.length) {
|
|
64075
|
-
const boundary = await
|
|
64445
|
+
const boundary = await randomUUID17();
|
|
64076
64446
|
preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
|
|
64077
64447
|
opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
|
|
64078
64448
|
} else if (shouldDirectlyPassData) {
|
|
@@ -144827,14 +145197,23 @@ var init_audio_jobs = __esm({
|
|
|
144827
145197
|
}
|
|
144828
145198
|
});
|
|
144829
145199
|
|
|
144830
|
-
// src/
|
|
145200
|
+
// src/core/retrieval-policy.ts
|
|
144831
145201
|
function feedbackWeightMultiplier(weight) {
|
|
144832
145202
|
return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
|
|
144833
145203
|
}
|
|
145204
|
+
var init_retrieval_policy = __esm({
|
|
145205
|
+
"src/core/retrieval-policy.ts"() {
|
|
145206
|
+
"use strict";
|
|
145207
|
+
init_esm_shims();
|
|
145208
|
+
}
|
|
145209
|
+
});
|
|
145210
|
+
|
|
145211
|
+
// src/memory/feedback-model.ts
|
|
144834
145212
|
var init_feedback_model = __esm({
|
|
144835
145213
|
"src/memory/feedback-model.ts"() {
|
|
144836
145214
|
"use strict";
|
|
144837
145215
|
init_esm_shims();
|
|
145216
|
+
init_retrieval_policy();
|
|
144838
145217
|
}
|
|
144839
145218
|
});
|
|
144840
145219
|
|
|
@@ -144846,7 +145225,7 @@ __export(feedback_exports, {
|
|
|
144846
145225
|
applyMemoryFeedback: () => applyMemoryFeedback,
|
|
144847
145226
|
feedbackWeightMultiplier: () => feedbackWeightMultiplier
|
|
144848
145227
|
});
|
|
144849
|
-
import { randomUUID as
|
|
145228
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
144850
145229
|
function applyMemoryFeedback(current, event) {
|
|
144851
145230
|
const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
|
|
144852
145231
|
const weight = Math.max(0, Math.min(2, current.weight + delta));
|
|
@@ -144964,7 +145343,7 @@ var init_feedback = __esm({
|
|
|
144964
145343
|
if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
|
|
144965
145344
|
}
|
|
144966
145345
|
const event = {
|
|
144967
|
-
id:
|
|
145346
|
+
id: randomUUID8(),
|
|
144968
145347
|
projectId: input.projectId,
|
|
144969
145348
|
candidateKind: input.candidateKind,
|
|
144970
145349
|
candidateId: input.candidateId,
|
|
@@ -145352,7 +145731,7 @@ var init_retention = __esm({
|
|
|
145352
145731
|
});
|
|
145353
145732
|
|
|
145354
145733
|
// src/memory/owner.ts
|
|
145355
|
-
import { randomUUID as
|
|
145734
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
145356
145735
|
import { promises as fs9 } from "fs";
|
|
145357
145736
|
import path17 from "path";
|
|
145358
145737
|
function ownerPath(dataDir) {
|
|
@@ -145382,7 +145761,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
|
|
|
145382
145761
|
await fs9.mkdir(path17.dirname(filePath), { recursive: true });
|
|
145383
145762
|
const created = {
|
|
145384
145763
|
version: 1,
|
|
145385
|
-
id: "local-" +
|
|
145764
|
+
id: "local-" + randomUUID9(),
|
|
145386
145765
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
145387
145766
|
};
|
|
145388
145767
|
try {
|
|
@@ -145405,7 +145784,7 @@ var init_owner = __esm({
|
|
|
145405
145784
|
});
|
|
145406
145785
|
|
|
145407
145786
|
// src/memory/long-term-store.ts
|
|
145408
|
-
import { randomUUID as
|
|
145787
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
145409
145788
|
function optionalText2(value) {
|
|
145410
145789
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
145411
145790
|
}
|
|
@@ -145565,7 +145944,7 @@ var init_long_term_store = __esm({
|
|
|
145565
145944
|
}
|
|
145566
145945
|
insertEvidence(input) {
|
|
145567
145946
|
const evidence = {
|
|
145568
|
-
id:
|
|
145947
|
+
id: randomUUID10(),
|
|
145569
145948
|
...input,
|
|
145570
145949
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
145571
145950
|
};
|
|
@@ -145592,7 +145971,7 @@ var init_long_term_store = __esm({
|
|
|
145592
145971
|
}
|
|
145593
145972
|
recordEvent(input) {
|
|
145594
145973
|
const event = {
|
|
145595
|
-
id:
|
|
145974
|
+
id: randomUUID10(),
|
|
145596
145975
|
...input,
|
|
145597
145976
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
145598
145977
|
};
|
|
@@ -145682,7 +146061,7 @@ __export(long_term_exports, {
|
|
|
145682
146061
|
selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
|
|
145683
146062
|
supersedeLongTermMemory: () => supersedeLongTermMemory
|
|
145684
146063
|
});
|
|
145685
|
-
import { randomUUID as
|
|
146064
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
145686
146065
|
function isOneOf(value, values) {
|
|
145687
146066
|
return typeof value === "string" && values.includes(value);
|
|
145688
146067
|
}
|
|
@@ -145864,7 +146243,7 @@ async function createManualLongTermMemory(input) {
|
|
|
145864
146243
|
const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
|
|
145865
146244
|
if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
|
|
145866
146245
|
assertScope(input.scope);
|
|
145867
|
-
const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" +
|
|
146246
|
+
const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
|
|
145868
146247
|
return createLongTermMemoryWithDataDir({
|
|
145869
146248
|
dataDir: input.dataDir,
|
|
145870
146249
|
originProjectId: input.projectId,
|
|
@@ -145919,7 +146298,7 @@ async function createLongTermMemoryWithDataDir(input) {
|
|
|
145919
146298
|
assertPortableEvidence(input.scope, portability, evidenceInputs);
|
|
145920
146299
|
const now3 = (/* @__PURE__ */ new Date()).toISOString();
|
|
145921
146300
|
const memory = {
|
|
145922
|
-
id:
|
|
146301
|
+
id: randomUUID11(),
|
|
145923
146302
|
originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
|
|
145924
146303
|
ownerId: compactText(input.ownerId, "owner id", 160),
|
|
145925
146304
|
scope: input.scope,
|
|
@@ -146274,7 +146653,7 @@ var store_exports = {};
|
|
|
146274
146653
|
__export(store_exports, {
|
|
146275
146654
|
CodeGraphStore: () => CodeGraphStore
|
|
146276
146655
|
});
|
|
146277
|
-
import { randomUUID as
|
|
146656
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
146278
146657
|
import { posix as pathPosix } from "path";
|
|
146279
146658
|
function rowToFile(row) {
|
|
146280
146659
|
return {
|
|
@@ -147203,7 +147582,7 @@ var init_store = __esm({
|
|
|
147203
147582
|
* so an interrupted scan cannot be advertised as complete.
|
|
147204
147583
|
*/
|
|
147205
147584
|
recordCodeStateSnapshot(input) {
|
|
147206
|
-
const id =
|
|
147585
|
+
const id = randomUUID12();
|
|
147207
147586
|
let snapshot;
|
|
147208
147587
|
let compactNeeded = false;
|
|
147209
147588
|
const tx = this.db.transaction(() => {
|
|
@@ -148436,7 +148815,7 @@ var claim_store_exports = {};
|
|
|
148436
148815
|
__export(claim_store_exports, {
|
|
148437
148816
|
ClaimStore: () => ClaimStore
|
|
148438
148817
|
});
|
|
148439
|
-
import { createHash as createHash12, randomUUID as
|
|
148818
|
+
import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
|
|
148440
148819
|
function optionalText3(value) {
|
|
148441
148820
|
return typeof value === "string" && value ? value : void 0;
|
|
148442
148821
|
}
|
|
@@ -148620,7 +148999,7 @@ var init_claim_store = __esm({
|
|
|
148620
148999
|
locator, capturedHash, evidenceKey, createdAt
|
|
148621
149000
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
148622
149001
|
`).run(
|
|
148623
|
-
|
|
149002
|
+
randomUUID13(),
|
|
148624
149003
|
input.claimId,
|
|
148625
149004
|
input.evidenceKind,
|
|
148626
149005
|
input.evidenceId,
|
|
@@ -148642,7 +149021,7 @@ var init_claim_store = __esm({
|
|
|
148642
149021
|
}
|
|
148643
149022
|
recordEvent(input) {
|
|
148644
149023
|
const event = {
|
|
148645
|
-
id:
|
|
149024
|
+
id: randomUUID13(),
|
|
148646
149025
|
...input,
|
|
148647
149026
|
...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
|
|
148648
149027
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -148687,7 +149066,7 @@ __export(claims_exports, {
|
|
|
148687
149066
|
supersedeClaim: () => supersedeClaim,
|
|
148688
149067
|
writeClaim: () => writeClaim
|
|
148689
149068
|
});
|
|
148690
|
-
import { createHash as createHash13, randomUUID as
|
|
149069
|
+
import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
|
|
148691
149070
|
function compactText2(value, field) {
|
|
148692
149071
|
if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
|
|
148693
149072
|
const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
|
|
@@ -148773,7 +149152,7 @@ function normalizeClaimInput(input) {
|
|
|
148773
149152
|
const now3 = (/* @__PURE__ */ new Date()).toISOString();
|
|
148774
149153
|
return {
|
|
148775
149154
|
claim: {
|
|
148776
|
-
id:
|
|
149155
|
+
id: randomUUID14(),
|
|
148777
149156
|
projectId,
|
|
148778
149157
|
subject,
|
|
148779
149158
|
predicate,
|
|
@@ -149858,7 +150237,7 @@ var init_workflow_sync = __esm({
|
|
|
149858
150237
|
});
|
|
149859
150238
|
|
|
149860
150239
|
// src/knowledge/workflow-store.ts
|
|
149861
|
-
import { randomUUID as
|
|
150240
|
+
import { randomUUID as randomUUID15 } from "crypto";
|
|
149862
150241
|
function parseJson(value, fallback) {
|
|
149863
150242
|
if (typeof value !== "string" || !value) return fallback;
|
|
149864
150243
|
try {
|
|
@@ -149958,7 +150337,7 @@ var init_workflow_store = __esm({
|
|
|
149958
150337
|
}
|
|
149959
150338
|
recordRun(input) {
|
|
149960
150339
|
const run = {
|
|
149961
|
-
id:
|
|
150340
|
+
id: randomUUID15(),
|
|
149962
150341
|
workflowId: input.workflowId,
|
|
149963
150342
|
projectId: input.projectId,
|
|
149964
150343
|
task: input.task.trim(),
|
|
@@ -150026,7 +150405,7 @@ var init_outcome_types = __esm({
|
|
|
150026
150405
|
});
|
|
150027
150406
|
|
|
150028
150407
|
// src/knowledge/outcome-store.ts
|
|
150029
|
-
import { randomUUID as
|
|
150408
|
+
import { randomUUID as randomUUID16 } from "crypto";
|
|
150030
150409
|
function optionalText5(value) {
|
|
150031
150410
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
150032
150411
|
}
|
|
@@ -150070,7 +150449,7 @@ var init_outcome_store = __esm({
|
|
|
150070
150449
|
}
|
|
150071
150450
|
record(input) {
|
|
150072
150451
|
const signal = {
|
|
150073
|
-
id:
|
|
150452
|
+
id: randomUUID16(),
|
|
150074
150453
|
projectId: text(input.projectId, "project id"),
|
|
150075
150454
|
candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
|
|
150076
150455
|
candidateId: text(input.candidateId, "candidate id"),
|
|
@@ -150904,6 +151283,15 @@ function observationId(payload) {
|
|
|
150904
151283
|
const value = payload.observationId;
|
|
150905
151284
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
150906
151285
|
}
|
|
151286
|
+
async function automaticCleanupEnabled(projectRoot) {
|
|
151287
|
+
if (!projectRoot) return true;
|
|
151288
|
+
try {
|
|
151289
|
+
const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
|
|
151290
|
+
return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
|
|
151291
|
+
} catch {
|
|
151292
|
+
return true;
|
|
151293
|
+
}
|
|
151294
|
+
}
|
|
150907
151295
|
function workspaceMode(payload) {
|
|
150908
151296
|
return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
|
|
150909
151297
|
}
|
|
@@ -150992,6 +151380,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
150992
151380
|
if (job.projectId !== projectId) {
|
|
150993
151381
|
return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
|
|
150994
151382
|
}
|
|
151383
|
+
if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
|
|
151384
|
+
return { action: "complete" };
|
|
151385
|
+
}
|
|
150995
151386
|
if (job.kind === "media-video-generation") {
|
|
150996
151387
|
const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
|
|
150997
151388
|
return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
|
|
@@ -151084,6 +151475,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151084
151475
|
});
|
|
151085
151476
|
return { action: "complete" };
|
|
151086
151477
|
}
|
|
151478
|
+
if (job.kind === "observation-project") {
|
|
151479
|
+
if (!projectRoot) {
|
|
151480
|
+
throw new Error(`Observation projection requires a project root for ${projectId}`);
|
|
151481
|
+
}
|
|
151482
|
+
const id = observationId(job.payload);
|
|
151483
|
+
if (!id) return { action: "complete" };
|
|
151484
|
+
const [
|
|
151485
|
+
{ CodeGraphStore: CodeGraphStore2 },
|
|
151486
|
+
{ bindObservationToCode: bindObservationToCode2 },
|
|
151487
|
+
{ EvidenceCardStore: EvidenceCardStore2 },
|
|
151488
|
+
{ getObservationStore: getObservationStore2 }
|
|
151489
|
+
] = await Promise.all([
|
|
151490
|
+
Promise.resolve().then(() => (init_store(), store_exports)),
|
|
151491
|
+
Promise.resolve().then(() => (init_binder(), binder_exports)),
|
|
151492
|
+
Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
|
|
151493
|
+
Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
|
|
151494
|
+
]);
|
|
151495
|
+
const observation = await getObservationStore2().getById(id);
|
|
151496
|
+
if (!observation || observation.projectId !== projectId) return { action: "complete" };
|
|
151497
|
+
const codeStore = new CodeGraphStore2();
|
|
151498
|
+
await codeStore.init(projectDir2);
|
|
151499
|
+
await bindObservationToCode2(codeStore, observation);
|
|
151500
|
+
const evidence = new EvidenceCardStore2();
|
|
151501
|
+
await evidence.init(projectDir2);
|
|
151502
|
+
evidence.upsertObservation(observation);
|
|
151503
|
+
return { action: "complete" };
|
|
151504
|
+
}
|
|
151087
151505
|
if (job.kind === "observation-qualify") {
|
|
151088
151506
|
const [
|
|
151089
151507
|
{ CodeGraphStore: CodeGraphStore2 },
|
|
@@ -151291,7 +151709,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151291
151709
|
const after = getVectorStatus2(projectId);
|
|
151292
151710
|
if (after.missing === 0) {
|
|
151293
151711
|
resolveSupersededVectorFailures(projectDir2, projectId);
|
|
151294
|
-
return {
|
|
151712
|
+
return {
|
|
151713
|
+
action: "complete",
|
|
151714
|
+
progress: {
|
|
151715
|
+
attempted: result.attempted,
|
|
151716
|
+
succeeded: result.succeeded,
|
|
151717
|
+
failed: result.failed,
|
|
151718
|
+
remaining: 0
|
|
151719
|
+
}
|
|
151720
|
+
};
|
|
151295
151721
|
}
|
|
151296
151722
|
if (result.failed > 0 && result.succeeded === 0) {
|
|
151297
151723
|
const streak = vectorBackfillFailureStreak(job.payload) + 1;
|
|
@@ -151306,6 +151732,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151306
151732
|
...job.payload,
|
|
151307
151733
|
vectorBackfillFailureStreak: streak
|
|
151308
151734
|
},
|
|
151735
|
+
progress: {
|
|
151736
|
+
attempted: result.attempted,
|
|
151737
|
+
succeeded: result.succeeded,
|
|
151738
|
+
failed: result.failed,
|
|
151739
|
+
remaining: after.missing
|
|
151740
|
+
},
|
|
151309
151741
|
lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
|
|
151310
151742
|
};
|
|
151311
151743
|
}
|
|
@@ -151315,6 +151747,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151315
151747
|
action: "reschedule",
|
|
151316
151748
|
delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
|
|
151317
151749
|
resetAttempts: result.succeeded > 0,
|
|
151750
|
+
progress: {
|
|
151751
|
+
attempted: result.attempted,
|
|
151752
|
+
succeeded: result.succeeded,
|
|
151753
|
+
failed: result.failed,
|
|
151754
|
+
remaining: after.missing
|
|
151755
|
+
},
|
|
151318
151756
|
...result.succeeded > 0 ? {
|
|
151319
151757
|
...priorFailureStreak > 0 ? { payload } : {},
|
|
151320
151758
|
...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
|
|
@@ -151723,24 +152161,40 @@ function queueVectorBackfill(projectId, options = {}) {
|
|
|
151723
152161
|
});
|
|
151724
152162
|
}
|
|
151725
152163
|
async function bindObservationCodeRefsBestEffort(observation) {
|
|
151726
|
-
if (!projectDir) return;
|
|
152164
|
+
if (!projectDir) return true;
|
|
151727
152165
|
try {
|
|
151728
152166
|
const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
|
|
151729
152167
|
const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
|
|
151730
152168
|
const codeStore = new CodeGraphStore2();
|
|
151731
152169
|
await codeStore.init(projectDir);
|
|
151732
152170
|
await bindObservationToCode2(codeStore, observation);
|
|
152171
|
+
return true;
|
|
151733
152172
|
} catch {
|
|
152173
|
+
return false;
|
|
151734
152174
|
}
|
|
151735
152175
|
}
|
|
151736
152176
|
async function persistEvidenceCard(observation) {
|
|
151737
|
-
if (!projectDir) return;
|
|
152177
|
+
if (!projectDir) return true;
|
|
151738
152178
|
try {
|
|
151739
152179
|
const evidence = new EvidenceCardStore();
|
|
151740
152180
|
await evidence.init(projectDir);
|
|
151741
152181
|
evidence.upsertObservation(observation);
|
|
152182
|
+
return true;
|
|
151742
152183
|
} catch (error) {
|
|
151743
152184
|
console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
152185
|
+
return false;
|
|
152186
|
+
}
|
|
152187
|
+
}
|
|
152188
|
+
async function acknowledgeObservationProjection(observation) {
|
|
152189
|
+
if (!projectDir) return;
|
|
152190
|
+
try {
|
|
152191
|
+
const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
|
|
152192
|
+
new MaintenanceJobStore2(projectDir).acknowledgePending(
|
|
152193
|
+
observation.projectId,
|
|
152194
|
+
"observation-project",
|
|
152195
|
+
"observation-project:" + observation.id
|
|
152196
|
+
);
|
|
152197
|
+
} catch {
|
|
151744
152198
|
}
|
|
151745
152199
|
}
|
|
151746
152200
|
function queueClaimDerivation(observation) {
|
|
@@ -151769,6 +152223,41 @@ function queueObservationQualification(observation) {
|
|
|
151769
152223
|
} catch {
|
|
151770
152224
|
}
|
|
151771
152225
|
}
|
|
152226
|
+
async function enqueueObservationDerivedWork(tx, observation) {
|
|
152227
|
+
if (!tx.enqueueMaintenanceJob) return false;
|
|
152228
|
+
if (!isEmbeddingExplicitlyDisabled()) {
|
|
152229
|
+
await tx.enqueueMaintenanceJob({
|
|
152230
|
+
projectId: observation.projectId,
|
|
152231
|
+
kind: "vector-backfill",
|
|
152232
|
+
dedupeKey: "vector-backfill",
|
|
152233
|
+
payload: { limit: 12 }
|
|
152234
|
+
});
|
|
152235
|
+
}
|
|
152236
|
+
if (observation.admissionState === "candidate") {
|
|
152237
|
+
await tx.enqueueMaintenanceJob({
|
|
152238
|
+
projectId: observation.projectId,
|
|
152239
|
+
kind: "observation-qualify",
|
|
152240
|
+
dedupeKey: "observation-qualify",
|
|
152241
|
+
payload: { source: "automatic-capture:" + observation.id, limit: 100 }
|
|
152242
|
+
});
|
|
152243
|
+
}
|
|
152244
|
+
const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
|
|
152245
|
+
if (claimSource && resolveObservationVisibility(observation) === "project") {
|
|
152246
|
+
await tx.enqueueMaintenanceJob({
|
|
152247
|
+
projectId: observation.projectId,
|
|
152248
|
+
kind: "claim-derive",
|
|
152249
|
+
dedupeKey: "claim-derive:" + observation.id,
|
|
152250
|
+
payload: { observationId: observation.id }
|
|
152251
|
+
});
|
|
152252
|
+
}
|
|
152253
|
+
await tx.enqueueMaintenanceJob({
|
|
152254
|
+
projectId: observation.projectId,
|
|
152255
|
+
kind: "observation-project",
|
|
152256
|
+
dedupeKey: "observation-project:" + observation.id,
|
|
152257
|
+
payload: { observationId: observation.id }
|
|
152258
|
+
});
|
|
152259
|
+
return true;
|
|
152260
|
+
}
|
|
151772
152261
|
function isVectorCompatibleWithCurrentIndex(embedding) {
|
|
151773
152262
|
if (!embedding) return false;
|
|
151774
152263
|
const vectorDimensions = getVectorDimensions();
|
|
@@ -151947,7 +152436,6 @@ async function storeObservation(input) {
|
|
|
151947
152436
|
throw new Error("Cannot update a memory outside this session's write scope.");
|
|
151948
152437
|
}
|
|
151949
152438
|
const observation2 = await upsertObservation(existing, input, now3);
|
|
151950
|
-
await input.onPersisted?.(observation2);
|
|
151951
152439
|
return { observation: observation2, upserted: true };
|
|
151952
152440
|
}
|
|
151953
152441
|
}
|
|
@@ -151974,6 +152462,7 @@ async function storeObservation(input) {
|
|
|
151974
152462
|
let upsertedInsideLock = false;
|
|
151975
152463
|
let reloadCacheAfterCommit = false;
|
|
151976
152464
|
let persistedCallbackInvoked = false;
|
|
152465
|
+
let derivedJobsCommitted = false;
|
|
151977
152466
|
const assignAndPersist = async () => {
|
|
151978
152467
|
if (projectDir) {
|
|
151979
152468
|
const store = getObservationStore();
|
|
@@ -152029,6 +152518,7 @@ async function storeObservation(input) {
|
|
|
152029
152518
|
writeGeneration: transactionGeneration + 1
|
|
152030
152519
|
};
|
|
152031
152520
|
await tx.insert(observation);
|
|
152521
|
+
derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
|
|
152032
152522
|
await input.onPersisted?.(observation);
|
|
152033
152523
|
persistedCallbackInvoked = true;
|
|
152034
152524
|
await tx.saveIdCounter(id + 1);
|
|
@@ -152127,15 +152617,17 @@ async function storeObservation(input) {
|
|
|
152127
152617
|
await assignAndPersist();
|
|
152128
152618
|
if (upsertedInsideLock) {
|
|
152129
152619
|
const updated = await upsertObservation(observation, input, now3);
|
|
152130
|
-
await input.onPersisted?.(updated);
|
|
152131
152620
|
return { observation: updated, upserted: true };
|
|
152132
152621
|
}
|
|
152133
152622
|
if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
|
|
152134
|
-
await bindObservationCodeRefsBestEffort(observation);
|
|
152135
|
-
await persistEvidenceCard(observation);
|
|
152136
|
-
|
|
152137
|
-
if (
|
|
152138
|
-
|
|
152623
|
+
const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
|
|
152624
|
+
const evidenceProjected = await persistEvidenceCard(observation);
|
|
152625
|
+
if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
|
|
152626
|
+
if (!derivedJobsCommitted) {
|
|
152627
|
+
queueObservationQualification(observation);
|
|
152628
|
+
if (resolveObservationVisibility(observation) === "project") {
|
|
152629
|
+
queueClaimDerivation(observation);
|
|
152630
|
+
}
|
|
152139
152631
|
}
|
|
152140
152632
|
scheduleObservationEmbedding({
|
|
152141
152633
|
observationId: observation.id,
|
|
@@ -152157,86 +152649,115 @@ async function upsertObservation(existing, input, now3) {
|
|
|
152157
152649
|
}
|
|
152158
152650
|
const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
|
|
152159
152651
|
const tokens = countTextTokens(fullText);
|
|
152160
|
-
|
|
152161
|
-
|
|
152162
|
-
|
|
152163
|
-
|
|
152164
|
-
|
|
152165
|
-
|
|
152166
|
-
|
|
152167
|
-
|
|
152168
|
-
|
|
152169
|
-
|
|
152170
|
-
|
|
152171
|
-
|
|
152172
|
-
|
|
152173
|
-
|
|
152174
|
-
|
|
152175
|
-
|
|
152176
|
-
|
|
152177
|
-
|
|
152178
|
-
|
|
152179
|
-
|
|
152180
|
-
|
|
152652
|
+
const applyUpdate = (current) => ({
|
|
152653
|
+
...current,
|
|
152654
|
+
entityName: input.entityName,
|
|
152655
|
+
type: input.type,
|
|
152656
|
+
title: input.title,
|
|
152657
|
+
narrative: input.narrative,
|
|
152658
|
+
facts: input.facts ?? [],
|
|
152659
|
+
attachments: input.attachments,
|
|
152660
|
+
filesModified: enrichedFiles,
|
|
152661
|
+
concepts: enrichedConcepts,
|
|
152662
|
+
tokens,
|
|
152663
|
+
updatedAt: now3,
|
|
152664
|
+
hasCausalLanguage: extracted.hasCausalLanguage,
|
|
152665
|
+
revisionCount: (current.revisionCount ?? 1) + 1,
|
|
152666
|
+
status: "active",
|
|
152667
|
+
...input.sessionId ? { sessionId: input.sessionId } : {},
|
|
152668
|
+
...input.progress ? { progress: input.progress } : {},
|
|
152669
|
+
...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
|
|
152670
|
+
...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
|
|
152671
|
+
...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
|
|
152672
|
+
...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
|
|
152673
|
+
...input.visibility !== void 0 ? { visibility: input.visibility } : {},
|
|
152674
|
+
...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
|
|
152675
|
+
});
|
|
152676
|
+
let updated = applyUpdate(existing);
|
|
152677
|
+
let derivedJobsCommitted = false;
|
|
152678
|
+
if (projectDir) {
|
|
152679
|
+
const store = getObservationStore();
|
|
152680
|
+
await store.atomic(async (tx) => {
|
|
152681
|
+
const current = await tx.getById(existing.id);
|
|
152682
|
+
if (!current || current.projectId !== existing.projectId) {
|
|
152683
|
+
throw new Error("Topic observation changed before update");
|
|
152684
|
+
}
|
|
152685
|
+
updated = applyUpdate(current);
|
|
152686
|
+
updated.writeGeneration = await tx.getGeneration() + 1;
|
|
152687
|
+
await tx.update(updated);
|
|
152688
|
+
derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
|
|
152689
|
+
await input.onPersisted?.(updated);
|
|
152690
|
+
});
|
|
152691
|
+
updated.writeGeneration = store.getGeneration();
|
|
152692
|
+
} else {
|
|
152693
|
+
await input.onPersisted?.(updated);
|
|
152694
|
+
}
|
|
152695
|
+
if (corpusLoaded) {
|
|
152696
|
+
const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
|
|
152697
|
+
if (cacheIndex >= 0) observations[cacheIndex] = updated;
|
|
152698
|
+
}
|
|
152181
152699
|
const doc = {
|
|
152182
|
-
id: makeOramaObservationId(
|
|
152183
|
-
observationId:
|
|
152184
|
-
entityName:
|
|
152185
|
-
type:
|
|
152186
|
-
title:
|
|
152187
|
-
narrative:
|
|
152188
|
-
facts:
|
|
152700
|
+
id: makeOramaObservationId(updated.projectId, updated.id),
|
|
152701
|
+
observationId: updated.id,
|
|
152702
|
+
entityName: updated.entityName,
|
|
152703
|
+
type: updated.type,
|
|
152704
|
+
title: updated.title,
|
|
152705
|
+
narrative: updated.narrative,
|
|
152706
|
+
facts: updated.facts.join("\n"),
|
|
152189
152707
|
filesModified: enrichedFiles.join("\n"),
|
|
152190
152708
|
concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
|
|
152191
|
-
attachments: formatAttachmentProvenance(
|
|
152709
|
+
attachments: formatAttachmentProvenance(updated.attachments),
|
|
152192
152710
|
tokens,
|
|
152193
|
-
createdAt:
|
|
152194
|
-
projectId:
|
|
152711
|
+
createdAt: updated.createdAt,
|
|
152712
|
+
projectId: updated.projectId,
|
|
152195
152713
|
accessCount: 0,
|
|
152196
152714
|
lastAccessedAt: "",
|
|
152197
152715
|
status: "active",
|
|
152198
|
-
source:
|
|
152199
|
-
sourceDetail:
|
|
152200
|
-
valueCategory:
|
|
152201
|
-
admissionState:
|
|
152202
|
-
admissionReason:
|
|
152203
|
-
visibility:
|
|
152204
|
-
createdByAgentId:
|
|
152205
|
-
sharedWithAgentIds: JSON.stringify(
|
|
152206
|
-
};
|
|
152207
|
-
|
|
152208
|
-
|
|
152209
|
-
const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
|
|
152210
|
-
await removeObservation2(oramaId);
|
|
152211
|
-
} catch {
|
|
152212
|
-
}
|
|
152213
|
-
try {
|
|
152214
|
-
await insertObservation(doc);
|
|
152215
|
-
} catch {
|
|
152716
|
+
source: updated.source ?? "agent",
|
|
152717
|
+
sourceDetail: updated.sourceDetail ?? "",
|
|
152718
|
+
valueCategory: updated.valueCategory ?? "",
|
|
152719
|
+
admissionState: updated.admissionState ?? "",
|
|
152720
|
+
admissionReason: updated.admissionReason ?? "",
|
|
152721
|
+
visibility: updated.visibility ?? "project",
|
|
152722
|
+
createdByAgentId: updated.createdByAgentId ?? "",
|
|
152723
|
+
sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
|
|
152724
|
+
};
|
|
152725
|
+
if (corpusLoaded) {
|
|
152726
|
+
const oramaId = makeOramaObservationId(updated.projectId, updated.id);
|
|
152216
152727
|
try {
|
|
152217
|
-
|
|
152218
|
-
|
|
152728
|
+
try {
|
|
152729
|
+
await removeObservation(oramaId);
|
|
152730
|
+
} catch {
|
|
152731
|
+
}
|
|
152219
152732
|
await insertObservation(doc);
|
|
152220
152733
|
} catch {
|
|
152734
|
+
try {
|
|
152735
|
+
try {
|
|
152736
|
+
await removeObservation(oramaId);
|
|
152737
|
+
} catch {
|
|
152738
|
+
}
|
|
152739
|
+
await insertObservation(doc);
|
|
152740
|
+
} catch (error) {
|
|
152741
|
+
console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
|
|
152742
|
+
}
|
|
152221
152743
|
}
|
|
152222
152744
|
}
|
|
152223
|
-
|
|
152224
|
-
|
|
152225
|
-
|
|
152226
|
-
|
|
152227
|
-
|
|
152228
|
-
|
|
152229
|
-
|
|
152230
|
-
|
|
152231
|
-
queueClaimDerivation(existing);
|
|
152745
|
+
const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
|
|
152746
|
+
const evidenceProjected = await persistEvidenceCard(updated);
|
|
152747
|
+
if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
|
|
152748
|
+
if (!derivedJobsCommitted) {
|
|
152749
|
+
queueObservationQualification(updated);
|
|
152750
|
+
if (resolveObservationVisibility(updated) === "project") {
|
|
152751
|
+
queueClaimDerivation(updated);
|
|
152752
|
+
}
|
|
152232
152753
|
}
|
|
152233
152754
|
scheduleObservationEmbedding({
|
|
152234
|
-
observationId:
|
|
152235
|
-
projectId:
|
|
152755
|
+
observationId: updated.id,
|
|
152756
|
+
projectId: updated.projectId,
|
|
152236
152757
|
searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
|
|
152237
152758
|
doc
|
|
152238
152759
|
});
|
|
152239
|
-
return
|
|
152760
|
+
return updated;
|
|
152240
152761
|
}
|
|
152241
152762
|
function getObservation(id, projectId) {
|
|
152242
152763
|
return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
|
|
@@ -152580,7 +153101,7 @@ function getSearchIndexStatus(projectId) {
|
|
|
152580
153101
|
};
|
|
152581
153102
|
}
|
|
152582
153103
|
async function probeSearchIndex(projectId) {
|
|
152583
|
-
await
|
|
153104
|
+
const result = await searchObservationsDetailed({
|
|
152584
153105
|
query: "semantic memory retrieval status",
|
|
152585
153106
|
projectId,
|
|
152586
153107
|
reader: { projectId },
|
|
@@ -152588,7 +153109,7 @@ async function probeSearchIndex(projectId) {
|
|
|
152588
153109
|
status: "all",
|
|
152589
153110
|
trackAccess: false
|
|
152590
153111
|
});
|
|
152591
|
-
return
|
|
153112
|
+
return result.diagnostics.mode;
|
|
152592
153113
|
}
|
|
152593
153114
|
async function backfillVectorEmbeddings(options = {}) {
|
|
152594
153115
|
if (vectorBackfillRunning) {
|