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
|
@@ -1177,6 +1177,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
|
|
|
1177
1177
|
lease_owner TEXT,
|
|
1178
1178
|
lease_expires_at INTEGER,
|
|
1179
1179
|
last_error TEXT,
|
|
1180
|
+
attempted INTEGER NOT NULL DEFAULT 0,
|
|
1181
|
+
succeeded INTEGER NOT NULL DEFAULT 0,
|
|
1182
|
+
failed INTEGER NOT NULL DEFAULT 0,
|
|
1183
|
+
remaining INTEGER NOT NULL DEFAULT 0,
|
|
1184
|
+
progress_recorded INTEGER NOT NULL DEFAULT 0,
|
|
1185
|
+
rerun_requested INTEGER NOT NULL DEFAULT 0,
|
|
1180
1186
|
created_at INTEGER NOT NULL,
|
|
1181
1187
|
updated_at INTEGER NOT NULL,
|
|
1182
1188
|
completed_at INTEGER
|
|
@@ -1597,6 +1603,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
|
|
|
1597
1603
|
ON task_continuity_events(project_id, task_id, event_key)
|
|
1598
1604
|
WHERE event_key IS NOT NULL`);
|
|
1599
1605
|
}
|
|
1606
|
+
},
|
|
1607
|
+
{
|
|
1608
|
+
id: "1.11-maintenance-progress",
|
|
1609
|
+
apply: (db2) => {
|
|
1610
|
+
addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
|
|
1611
|
+
addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
|
|
1612
|
+
addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
|
|
1613
|
+
addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
|
|
1614
|
+
addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
|
|
1615
|
+
}
|
|
1616
|
+
},
|
|
1617
|
+
{
|
|
1618
|
+
id: "1.11-maintenance-rerun",
|
|
1619
|
+
apply: (db2) => {
|
|
1620
|
+
addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
|
|
1621
|
+
}
|
|
1600
1622
|
}
|
|
1601
1623
|
];
|
|
1602
1624
|
_dbCache = /* @__PURE__ */ new Map();
|
|
@@ -1741,6 +1763,7 @@ function loadYamlConfig(projectRoot, options = {}) {
|
|
|
1741
1763
|
llm: { ...userConfig.llm, ...projectConfig.llm },
|
|
1742
1764
|
agent: { ...userConfig.agent, ...projectConfig.agent },
|
|
1743
1765
|
embedding: { ...userConfig.embedding, ...projectConfig.embedding },
|
|
1766
|
+
retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
|
|
1744
1767
|
rerank: { ...userConfig.rerank, ...projectConfig.rerank },
|
|
1745
1768
|
git: { ...userConfig.git, ...projectConfig.git },
|
|
1746
1769
|
codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
|
|
@@ -1978,6 +2001,7 @@ function mergeTomlConfig(base, override) {
|
|
|
1978
2001
|
llm: { ...base.memory?.llm, ...override.memory?.llm }
|
|
1979
2002
|
},
|
|
1980
2003
|
embedding: { ...base.embedding, ...override.embedding },
|
|
2004
|
+
retrieval: { ...base.retrieval, ...override.retrieval },
|
|
1981
2005
|
rerank: { ...base.rerank, ...override.rerank },
|
|
1982
2006
|
hooks: { ...base.hooks, ...override.hooks },
|
|
1983
2007
|
git: { ...base.git, ...override.git },
|
|
@@ -2067,6 +2091,32 @@ var init_toml_loader = __esm({
|
|
|
2067
2091
|
}
|
|
2068
2092
|
});
|
|
2069
2093
|
|
|
2094
|
+
// src/config/retrieval-strategy.ts
|
|
2095
|
+
function isCjkHeavyQuery(query) {
|
|
2096
|
+
if (!query) return false;
|
|
2097
|
+
const matches = query.match(CJK);
|
|
2098
|
+
return (matches?.length ?? 0) / query.length > 0.3;
|
|
2099
|
+
}
|
|
2100
|
+
function normalizeRetrievalStrategy(value) {
|
|
2101
|
+
if (value === "vector" || value === "hybrid") return value;
|
|
2102
|
+
return void 0;
|
|
2103
|
+
}
|
|
2104
|
+
function firstRetrievalStrategy(fallback, ...values) {
|
|
2105
|
+
for (const value of values) {
|
|
2106
|
+
const normalized = normalizeRetrievalStrategy(value);
|
|
2107
|
+
if (normalized) return normalized;
|
|
2108
|
+
}
|
|
2109
|
+
return fallback;
|
|
2110
|
+
}
|
|
2111
|
+
var CJK;
|
|
2112
|
+
var init_retrieval_strategy = __esm({
|
|
2113
|
+
"src/config/retrieval-strategy.ts"() {
|
|
2114
|
+
"use strict";
|
|
2115
|
+
init_esm_shims();
|
|
2116
|
+
CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
|
|
2117
|
+
}
|
|
2118
|
+
});
|
|
2119
|
+
|
|
2070
2120
|
// src/config/resolved-config.ts
|
|
2071
2121
|
var resolved_config_exports = {};
|
|
2072
2122
|
__export(resolved_config_exports, {
|
|
@@ -2176,6 +2226,10 @@ function getResolvedConfig(options = {}) {
|
|
|
2176
2226
|
apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
|
|
2177
2227
|
dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
|
|
2178
2228
|
},
|
|
2229
|
+
retrieval: {
|
|
2230
|
+
cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
|
|
2231
|
+
ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
|
|
2232
|
+
},
|
|
2179
2233
|
rerank: resolveRerankLane({
|
|
2180
2234
|
toml,
|
|
2181
2235
|
yaml,
|
|
@@ -2297,6 +2351,8 @@ function getEnvSourceNames() {
|
|
|
2297
2351
|
"MEMORIX_EMBEDDING_BASE_URL",
|
|
2298
2352
|
"MEMORIX_EMBEDDING_MODEL",
|
|
2299
2353
|
"MEMORIX_EMBEDDING_DIMENSIONS",
|
|
2354
|
+
"MEMORIX_RETRIEVAL_CJK",
|
|
2355
|
+
"MEMORIX_RETRIEVAL_ASCII",
|
|
2300
2356
|
"MEMORIX_RERANK_PROVIDER",
|
|
2301
2357
|
"MEMORIX_RERANK_MODEL",
|
|
2302
2358
|
"MEMORIX_RERANK_BASE_URL",
|
|
@@ -2405,6 +2461,7 @@ var init_resolved_config = __esm({
|
|
|
2405
2461
|
init_toml_loader();
|
|
2406
2462
|
init_yaml_loader();
|
|
2407
2463
|
init_dotenv_loader();
|
|
2464
|
+
init_retrieval_strategy();
|
|
2408
2465
|
}
|
|
2409
2466
|
});
|
|
2410
2467
|
|
|
@@ -3275,6 +3332,7 @@ var sqlite_store_exports = {};
|
|
|
3275
3332
|
__export(sqlite_store_exports, {
|
|
3276
3333
|
SqliteBackend: () => SqliteBackend
|
|
3277
3334
|
});
|
|
3335
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
3278
3336
|
import path6 from "path";
|
|
3279
3337
|
import fs3 from "fs";
|
|
3280
3338
|
function obsToRow(obs) {
|
|
@@ -3663,6 +3721,32 @@ var init_sqlite_store = __esm({
|
|
|
3663
3721
|
}, "Observation atomic write");
|
|
3664
3722
|
try {
|
|
3665
3723
|
const tx = {
|
|
3724
|
+
enqueueMaintenanceJob: async (input) => {
|
|
3725
|
+
const payloadJson = JSON.stringify(input.payload ?? {});
|
|
3726
|
+
const existing = this.db.prepare(`
|
|
3727
|
+
SELECT id, status FROM maintenance_jobs
|
|
3728
|
+
WHERE project_id = ? AND kind = ? AND dedupe_key = ?
|
|
3729
|
+
AND status IN ('pending', 'running', 'retry')
|
|
3730
|
+
LIMIT 1
|
|
3731
|
+
`).get(input.projectId, input.kind, input.dedupeKey);
|
|
3732
|
+
if (existing) {
|
|
3733
|
+
if (existing.status === "running") {
|
|
3734
|
+
this.db.prepare(`
|
|
3735
|
+
UPDATE maintenance_jobs
|
|
3736
|
+
SET rerun_requested = 1, payload_json = ?, updated_at = ?
|
|
3737
|
+
WHERE id = ?
|
|
3738
|
+
`).run(payloadJson, Date.now(), existing.id);
|
|
3739
|
+
}
|
|
3740
|
+
return;
|
|
3741
|
+
}
|
|
3742
|
+
const now3 = Date.now();
|
|
3743
|
+
this.db.prepare(`
|
|
3744
|
+
INSERT INTO maintenance_jobs (
|
|
3745
|
+
id, project_id, kind, dedupe_key, payload_json, status, attempts,
|
|
3746
|
+
max_attempts, run_after, created_at, updated_at
|
|
3747
|
+
) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
|
|
3748
|
+
`).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
|
|
3749
|
+
},
|
|
3666
3750
|
loadAll: async () => this.rawLoadAll(),
|
|
3667
3751
|
getById: async (id) => this.rawGetById(id),
|
|
3668
3752
|
findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
|
|
@@ -3733,6 +3817,7 @@ __export(obs_store_exports, {
|
|
|
3733
3817
|
DegradedBackend: () => DegradedBackend,
|
|
3734
3818
|
createObservationStore: () => createObservationStore,
|
|
3735
3819
|
getObservationStore: () => getObservationStore,
|
|
3820
|
+
getObservationStoreDataDir: () => getObservationStoreDataDir,
|
|
3736
3821
|
initObservationStore: () => initObservationStore,
|
|
3737
3822
|
resetObservationStore: () => resetObservationStore,
|
|
3738
3823
|
setObservationStore: () => setObservationStore
|
|
@@ -3743,6 +3828,12 @@ function getObservationStore() {
|
|
|
3743
3828
|
}
|
|
3744
3829
|
return _store;
|
|
3745
3830
|
}
|
|
3831
|
+
function getObservationStoreDataDir() {
|
|
3832
|
+
if (!_store || !_storeDataDir) {
|
|
3833
|
+
throw new Error("[memorix] ObservationStore data directory is not bound");
|
|
3834
|
+
}
|
|
3835
|
+
return _storeDataDir;
|
|
3836
|
+
}
|
|
3746
3837
|
function setObservationStore(store) {
|
|
3747
3838
|
_store = store;
|
|
3748
3839
|
}
|
|
@@ -4725,8 +4816,8 @@ async function loadCacheJsonl(filePath) {
|
|
|
4725
4816
|
loaded = cache3.size;
|
|
4726
4817
|
} catch {
|
|
4727
4818
|
}
|
|
4728
|
-
if (onDiskCount %
|
|
4729
|
-
await new Promise((resolve2) =>
|
|
4819
|
+
if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
|
|
4820
|
+
await new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
4730
4821
|
}
|
|
4731
4822
|
}
|
|
4732
4823
|
diskCacheEntryCount = onDiskCount;
|
|
@@ -5055,6 +5146,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
|
|
|
5055
5146
|
if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
|
|
5056
5147
|
throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
|
|
5057
5148
|
}
|
|
5149
|
+
if (options.retry !== false && attempt < MAX_RETRIES2) {
|
|
5150
|
+
const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
|
|
5151
|
+
console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
|
|
5152
|
+
await waitForRetry(delay3, options.signal);
|
|
5153
|
+
return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
|
|
5154
|
+
}
|
|
5058
5155
|
throw err;
|
|
5059
5156
|
}
|
|
5060
5157
|
try {
|
|
@@ -5133,7 +5230,7 @@ async function waitForRetry(waitMs, signal) {
|
|
|
5133
5230
|
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
5134
5231
|
});
|
|
5135
5232
|
}
|
|
5136
|
-
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;
|
|
5233
|
+
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;
|
|
5137
5234
|
var init_api_provider = __esm({
|
|
5138
5235
|
"src/embedding/api-provider.ts"() {
|
|
5139
5236
|
"use strict";
|
|
@@ -5161,6 +5258,7 @@ var init_api_provider = __esm({
|
|
|
5161
5258
|
DASHSCOPE_MAX_BATCH_SIZE = 10;
|
|
5162
5259
|
MAX_RETRIES2 = 3;
|
|
5163
5260
|
BASE_DELAY_MS = 500;
|
|
5261
|
+
CACHE_LOAD_YIELD_EVERY = 32;
|
|
5164
5262
|
EmbeddingAPIError = class extends Error {
|
|
5165
5263
|
status;
|
|
5166
5264
|
constructor(status, detail) {
|
|
@@ -5212,7 +5310,7 @@ var init_api_provider = __esm({
|
|
|
5212
5310
|
console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
|
|
5213
5311
|
}
|
|
5214
5312
|
if (allowNetworkProbe) {
|
|
5215
|
-
startDiskCacheLoad
|
|
5313
|
+
setImmediate(startDiskCacheLoad);
|
|
5216
5314
|
}
|
|
5217
5315
|
return new _APIEmbeddingProvider(config, probeDimensions);
|
|
5218
5316
|
}
|
|
@@ -5284,10 +5382,8 @@ var init_api_provider = __esm({
|
|
|
5284
5382
|
return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
|
|
5285
5383
|
}
|
|
5286
5384
|
const hash4 = textHash2(normalized, this.cacheKeyNamespace);
|
|
5287
|
-
|
|
5288
|
-
|
|
5289
|
-
if (cached) return cached;
|
|
5290
|
-
}
|
|
5385
|
+
const cached = cache3.get(hash4);
|
|
5386
|
+
if (cached) return cached;
|
|
5291
5387
|
const apiCall = async () => {
|
|
5292
5388
|
const body = {
|
|
5293
5389
|
model: this.config.model,
|
|
@@ -5312,8 +5408,8 @@ var init_api_provider = __esm({
|
|
|
5312
5408
|
let embedding;
|
|
5313
5409
|
if (!diskCacheLoaded && diskCacheLoadPromise) {
|
|
5314
5410
|
const cacheRace = diskCacheLoadPromise.then(() => {
|
|
5315
|
-
const
|
|
5316
|
-
if (
|
|
5411
|
+
const cached2 = cache3.get(hash4);
|
|
5412
|
+
if (cached2) return cached2;
|
|
5317
5413
|
return null;
|
|
5318
5414
|
});
|
|
5319
5415
|
const result = await Promise.race([
|
|
@@ -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,
|
|
@@ -9509,6 +9879,7 @@ var init_isolated_maintenance = __esm({
|
|
|
9509
9879
|
"consolidation",
|
|
9510
9880
|
"codegraph-refresh",
|
|
9511
9881
|
"observation-qualify",
|
|
9882
|
+
"observation-project",
|
|
9512
9883
|
"claim-derive",
|
|
9513
9884
|
"claim-requalification",
|
|
9514
9885
|
"knowledge-compile",
|
|
@@ -9521,7 +9892,7 @@ var init_isolated_maintenance = __esm({
|
|
|
9521
9892
|
});
|
|
9522
9893
|
|
|
9523
9894
|
// src/knowledge/workspace-store.ts
|
|
9524
|
-
import { randomUUID as
|
|
9895
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
9525
9896
|
function arrayValue(raw) {
|
|
9526
9897
|
if (typeof raw !== "string" || !raw) return [];
|
|
9527
9898
|
try {
|
|
@@ -9662,7 +10033,7 @@ var init_workspace_store = __esm({
|
|
|
9662
10033
|
}
|
|
9663
10034
|
createProposal(input) {
|
|
9664
10035
|
const proposal = {
|
|
9665
|
-
id: input.id ??
|
|
10036
|
+
id: input.id ?? randomUUID5(),
|
|
9666
10037
|
...input,
|
|
9667
10038
|
status: input.status ?? "pending",
|
|
9668
10039
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -9948,11 +10319,11 @@ __export(consolidation_exports, {
|
|
|
9948
10319
|
});
|
|
9949
10320
|
function tokenize(text2) {
|
|
9950
10321
|
return new Set(
|
|
9951
|
-
text2.toLowerCase().replace(/[
|
|
10322
|
+
text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
|
|
9952
10323
|
);
|
|
9953
10324
|
}
|
|
9954
10325
|
function jaccardSimilarity(a, b) {
|
|
9955
|
-
if (a.size === 0 && b.size === 0) return
|
|
10326
|
+
if (a.size === 0 && b.size === 0) return 0;
|
|
9956
10327
|
let intersection = 0;
|
|
9957
10328
|
for (const token of a) {
|
|
9958
10329
|
if (b.has(token)) intersection++;
|
|
@@ -10318,7 +10689,7 @@ Respond in JSON only:
|
|
|
10318
10689
|
});
|
|
10319
10690
|
|
|
10320
10691
|
// src/media/media-store.ts
|
|
10321
|
-
import { randomUUID as
|
|
10692
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
10322
10693
|
function asOptionalText(value) {
|
|
10323
10694
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
10324
10695
|
}
|
|
@@ -10488,7 +10859,7 @@ var init_media_store = __esm({
|
|
|
10488
10859
|
return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
|
|
10489
10860
|
}
|
|
10490
10861
|
const asset = {
|
|
10491
|
-
id:
|
|
10862
|
+
id: randomUUID6(),
|
|
10492
10863
|
...input,
|
|
10493
10864
|
createdAt: now3,
|
|
10494
10865
|
updatedAt: now3
|
|
@@ -10568,7 +10939,7 @@ var init_media_store = __esm({
|
|
|
10568
10939
|
`).get(input.assetId, input.observationId ?? null, input.role);
|
|
10569
10940
|
if (existing) return rowToLink(existing);
|
|
10570
10941
|
const link = {
|
|
10571
|
-
id:
|
|
10942
|
+
id: randomUUID6(),
|
|
10572
10943
|
assetId: input.assetId,
|
|
10573
10944
|
projectId: input.projectId,
|
|
10574
10945
|
...input.observationId !== void 0 ? { observationId: input.observationId } : {},
|
|
@@ -10607,7 +10978,7 @@ var init_media_store = __esm({
|
|
|
10607
10978
|
return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
|
|
10608
10979
|
}
|
|
10609
10980
|
const derivation = {
|
|
10610
|
-
id:
|
|
10981
|
+
id: randomUUID6(),
|
|
10611
10982
|
...input,
|
|
10612
10983
|
content,
|
|
10613
10984
|
...error ? { error } : {},
|
|
@@ -10694,7 +11065,7 @@ var init_media_store = __esm({
|
|
|
10694
11065
|
createJob(input) {
|
|
10695
11066
|
const now3 = Date.now();
|
|
10696
11067
|
const job = {
|
|
10697
|
-
id:
|
|
11068
|
+
id: randomUUID6(),
|
|
10698
11069
|
projectId: input.projectId,
|
|
10699
11070
|
kind: input.kind,
|
|
10700
11071
|
status: "queued",
|
|
@@ -10856,7 +11227,7 @@ var init_types2 = __esm({
|
|
|
10856
11227
|
});
|
|
10857
11228
|
|
|
10858
11229
|
// src/media/asset-store.ts
|
|
10859
|
-
import { createHash as createHash7, randomUUID as
|
|
11230
|
+
import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
|
|
10860
11231
|
import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
|
|
10861
11232
|
import path12 from "path";
|
|
10862
11233
|
function mediaRoot(dataDir) {
|
|
@@ -10927,7 +11298,7 @@ async function destinationExists(destination) {
|
|
|
10927
11298
|
async function persistBuffer(bytes, destination) {
|
|
10928
11299
|
await mkdir3(path12.dirname(destination), { recursive: true });
|
|
10929
11300
|
if (await destinationExists(destination)) return false;
|
|
10930
|
-
const temporary = `${destination}.${
|
|
11301
|
+
const temporary = `${destination}.${randomUUID7()}.tmp`;
|
|
10931
11302
|
try {
|
|
10932
11303
|
await writeFile3(temporary, bytes, { flag: "wx" });
|
|
10933
11304
|
await rename2(temporary, destination);
|
|
@@ -63829,7 +64200,7 @@ var require_gaxios = __commonJS({
|
|
|
63829
64200
|
var retry_js_1 = require_retry3();
|
|
63830
64201
|
var stream_1 = __require("stream");
|
|
63831
64202
|
var interceptor_js_1 = require_interceptor();
|
|
63832
|
-
var
|
|
64203
|
+
var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
|
|
63833
64204
|
var HTTP_STATUS_NO_CONTENT = 204;
|
|
63834
64205
|
var Gaxios = class {
|
|
63835
64206
|
agentCache = /* @__PURE__ */ new Map();
|
|
@@ -64102,7 +64473,7 @@ var require_gaxios = __commonJS({
|
|
|
64102
64473
|
*/
|
|
64103
64474
|
["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
|
|
64104
64475
|
if (opts.multipart?.length) {
|
|
64105
|
-
const boundary = await
|
|
64476
|
+
const boundary = await randomUUID17();
|
|
64106
64477
|
preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
|
|
64107
64478
|
opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
|
|
64108
64479
|
} else if (shouldDirectlyPassData) {
|
|
@@ -144857,14 +145228,23 @@ var init_audio_jobs = __esm({
|
|
|
144857
145228
|
}
|
|
144858
145229
|
});
|
|
144859
145230
|
|
|
144860
|
-
// src/
|
|
145231
|
+
// src/core/retrieval-policy.ts
|
|
144861
145232
|
function feedbackWeightMultiplier(weight) {
|
|
144862
145233
|
return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
|
|
144863
145234
|
}
|
|
145235
|
+
var init_retrieval_policy = __esm({
|
|
145236
|
+
"src/core/retrieval-policy.ts"() {
|
|
145237
|
+
"use strict";
|
|
145238
|
+
init_esm_shims();
|
|
145239
|
+
}
|
|
145240
|
+
});
|
|
145241
|
+
|
|
145242
|
+
// src/memory/feedback-model.ts
|
|
144864
145243
|
var init_feedback_model = __esm({
|
|
144865
145244
|
"src/memory/feedback-model.ts"() {
|
|
144866
145245
|
"use strict";
|
|
144867
145246
|
init_esm_shims();
|
|
145247
|
+
init_retrieval_policy();
|
|
144868
145248
|
}
|
|
144869
145249
|
});
|
|
144870
145250
|
|
|
@@ -144876,7 +145256,7 @@ __export(feedback_exports, {
|
|
|
144876
145256
|
applyMemoryFeedback: () => applyMemoryFeedback,
|
|
144877
145257
|
feedbackWeightMultiplier: () => feedbackWeightMultiplier
|
|
144878
145258
|
});
|
|
144879
|
-
import { randomUUID as
|
|
145259
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
144880
145260
|
function applyMemoryFeedback(current, event) {
|
|
144881
145261
|
const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
|
|
144882
145262
|
const weight = Math.max(0, Math.min(2, current.weight + delta));
|
|
@@ -144994,7 +145374,7 @@ var init_feedback = __esm({
|
|
|
144994
145374
|
if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
|
|
144995
145375
|
}
|
|
144996
145376
|
const event = {
|
|
144997
|
-
id:
|
|
145377
|
+
id: randomUUID8(),
|
|
144998
145378
|
projectId: input.projectId,
|
|
144999
145379
|
candidateKind: input.candidateKind,
|
|
145000
145380
|
candidateId: input.candidateId,
|
|
@@ -145382,7 +145762,7 @@ var init_retention = __esm({
|
|
|
145382
145762
|
});
|
|
145383
145763
|
|
|
145384
145764
|
// src/memory/owner.ts
|
|
145385
|
-
import { randomUUID as
|
|
145765
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
145386
145766
|
import { promises as fs9 } from "fs";
|
|
145387
145767
|
import path18 from "path";
|
|
145388
145768
|
function ownerPath(dataDir) {
|
|
@@ -145412,7 +145792,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
|
|
|
145412
145792
|
await fs9.mkdir(path18.dirname(filePath), { recursive: true });
|
|
145413
145793
|
const created = {
|
|
145414
145794
|
version: 1,
|
|
145415
|
-
id: "local-" +
|
|
145795
|
+
id: "local-" + randomUUID9(),
|
|
145416
145796
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
145417
145797
|
};
|
|
145418
145798
|
try {
|
|
@@ -145435,7 +145815,7 @@ var init_owner = __esm({
|
|
|
145435
145815
|
});
|
|
145436
145816
|
|
|
145437
145817
|
// src/memory/long-term-store.ts
|
|
145438
|
-
import { randomUUID as
|
|
145818
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
145439
145819
|
function optionalText2(value) {
|
|
145440
145820
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
145441
145821
|
}
|
|
@@ -145595,7 +145975,7 @@ var init_long_term_store = __esm({
|
|
|
145595
145975
|
}
|
|
145596
145976
|
insertEvidence(input) {
|
|
145597
145977
|
const evidence = {
|
|
145598
|
-
id:
|
|
145978
|
+
id: randomUUID10(),
|
|
145599
145979
|
...input,
|
|
145600
145980
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
145601
145981
|
};
|
|
@@ -145622,7 +146002,7 @@ var init_long_term_store = __esm({
|
|
|
145622
146002
|
}
|
|
145623
146003
|
recordEvent(input) {
|
|
145624
146004
|
const event = {
|
|
145625
|
-
id:
|
|
146005
|
+
id: randomUUID10(),
|
|
145626
146006
|
...input,
|
|
145627
146007
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
145628
146008
|
};
|
|
@@ -145712,7 +146092,7 @@ __export(long_term_exports, {
|
|
|
145712
146092
|
selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
|
|
145713
146093
|
supersedeLongTermMemory: () => supersedeLongTermMemory
|
|
145714
146094
|
});
|
|
145715
|
-
import { randomUUID as
|
|
146095
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
145716
146096
|
function isOneOf(value, values) {
|
|
145717
146097
|
return typeof value === "string" && values.includes(value);
|
|
145718
146098
|
}
|
|
@@ -145894,7 +146274,7 @@ async function createManualLongTermMemory(input) {
|
|
|
145894
146274
|
const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
|
|
145895
146275
|
if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
|
|
145896
146276
|
assertScope(input.scope);
|
|
145897
|
-
const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" +
|
|
146277
|
+
const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
|
|
145898
146278
|
return createLongTermMemoryWithDataDir({
|
|
145899
146279
|
dataDir: input.dataDir,
|
|
145900
146280
|
originProjectId: input.projectId,
|
|
@@ -145949,7 +146329,7 @@ async function createLongTermMemoryWithDataDir(input) {
|
|
|
145949
146329
|
assertPortableEvidence(input.scope, portability, evidenceInputs);
|
|
145950
146330
|
const now3 = (/* @__PURE__ */ new Date()).toISOString();
|
|
145951
146331
|
const memory = {
|
|
145952
|
-
id:
|
|
146332
|
+
id: randomUUID11(),
|
|
145953
146333
|
originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
|
|
145954
146334
|
ownerId: compactText(input.ownerId, "owner id", 160),
|
|
145955
146335
|
scope: input.scope,
|
|
@@ -146304,7 +146684,7 @@ var store_exports = {};
|
|
|
146304
146684
|
__export(store_exports, {
|
|
146305
146685
|
CodeGraphStore: () => CodeGraphStore
|
|
146306
146686
|
});
|
|
146307
|
-
import { randomUUID as
|
|
146687
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
146308
146688
|
import { posix as pathPosix } from "path";
|
|
146309
146689
|
function rowToFile(row) {
|
|
146310
146690
|
return {
|
|
@@ -147233,7 +147613,7 @@ var init_store = __esm({
|
|
|
147233
147613
|
* so an interrupted scan cannot be advertised as complete.
|
|
147234
147614
|
*/
|
|
147235
147615
|
recordCodeStateSnapshot(input) {
|
|
147236
|
-
const id =
|
|
147616
|
+
const id = randomUUID12();
|
|
147237
147617
|
let snapshot;
|
|
147238
147618
|
let compactNeeded = false;
|
|
147239
147619
|
const tx = this.db.transaction(() => {
|
|
@@ -148466,7 +148846,7 @@ var claim_store_exports = {};
|
|
|
148466
148846
|
__export(claim_store_exports, {
|
|
148467
148847
|
ClaimStore: () => ClaimStore
|
|
148468
148848
|
});
|
|
148469
|
-
import { createHash as createHash12, randomUUID as
|
|
148849
|
+
import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
|
|
148470
148850
|
function optionalText3(value) {
|
|
148471
148851
|
return typeof value === "string" && value ? value : void 0;
|
|
148472
148852
|
}
|
|
@@ -148650,7 +149030,7 @@ var init_claim_store = __esm({
|
|
|
148650
149030
|
locator, capturedHash, evidenceKey, createdAt
|
|
148651
149031
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
148652
149032
|
`).run(
|
|
148653
|
-
|
|
149033
|
+
randomUUID13(),
|
|
148654
149034
|
input.claimId,
|
|
148655
149035
|
input.evidenceKind,
|
|
148656
149036
|
input.evidenceId,
|
|
@@ -148672,7 +149052,7 @@ var init_claim_store = __esm({
|
|
|
148672
149052
|
}
|
|
148673
149053
|
recordEvent(input) {
|
|
148674
149054
|
const event = {
|
|
148675
|
-
id:
|
|
149055
|
+
id: randomUUID13(),
|
|
148676
149056
|
...input,
|
|
148677
149057
|
...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
|
|
148678
149058
|
createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -148717,7 +149097,7 @@ __export(claims_exports, {
|
|
|
148717
149097
|
supersedeClaim: () => supersedeClaim,
|
|
148718
149098
|
writeClaim: () => writeClaim
|
|
148719
149099
|
});
|
|
148720
|
-
import { createHash as createHash13, randomUUID as
|
|
149100
|
+
import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
|
|
148721
149101
|
function compactText2(value, field) {
|
|
148722
149102
|
if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
|
|
148723
149103
|
const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
|
|
@@ -148803,7 +149183,7 @@ function normalizeClaimInput(input) {
|
|
|
148803
149183
|
const now3 = (/* @__PURE__ */ new Date()).toISOString();
|
|
148804
149184
|
return {
|
|
148805
149185
|
claim: {
|
|
148806
|
-
id:
|
|
149186
|
+
id: randomUUID14(),
|
|
148807
149187
|
projectId,
|
|
148808
149188
|
subject,
|
|
148809
149189
|
predicate,
|
|
@@ -149888,7 +150268,7 @@ var init_workflow_sync = __esm({
|
|
|
149888
150268
|
});
|
|
149889
150269
|
|
|
149890
150270
|
// src/knowledge/workflow-store.ts
|
|
149891
|
-
import { randomUUID as
|
|
150271
|
+
import { randomUUID as randomUUID15 } from "crypto";
|
|
149892
150272
|
function parseJson(value, fallback) {
|
|
149893
150273
|
if (typeof value !== "string" || !value) return fallback;
|
|
149894
150274
|
try {
|
|
@@ -149988,7 +150368,7 @@ var init_workflow_store = __esm({
|
|
|
149988
150368
|
}
|
|
149989
150369
|
recordRun(input) {
|
|
149990
150370
|
const run = {
|
|
149991
|
-
id:
|
|
150371
|
+
id: randomUUID15(),
|
|
149992
150372
|
workflowId: input.workflowId,
|
|
149993
150373
|
projectId: input.projectId,
|
|
149994
150374
|
task: input.task.trim(),
|
|
@@ -150056,7 +150436,7 @@ var init_outcome_types = __esm({
|
|
|
150056
150436
|
});
|
|
150057
150437
|
|
|
150058
150438
|
// src/knowledge/outcome-store.ts
|
|
150059
|
-
import { randomUUID as
|
|
150439
|
+
import { randomUUID as randomUUID16 } from "crypto";
|
|
150060
150440
|
function optionalText5(value) {
|
|
150061
150441
|
return typeof value === "string" && value.trim() ? value : void 0;
|
|
150062
150442
|
}
|
|
@@ -150100,7 +150480,7 @@ var init_outcome_store = __esm({
|
|
|
150100
150480
|
}
|
|
150101
150481
|
record(input) {
|
|
150102
150482
|
const signal = {
|
|
150103
|
-
id:
|
|
150483
|
+
id: randomUUID16(),
|
|
150104
150484
|
projectId: text(input.projectId, "project id"),
|
|
150105
150485
|
candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
|
|
150106
150486
|
candidateId: text(input.candidateId, "candidate id"),
|
|
@@ -150934,6 +151314,15 @@ function observationId(payload) {
|
|
|
150934
151314
|
const value = payload.observationId;
|
|
150935
151315
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
150936
151316
|
}
|
|
151317
|
+
async function automaticCleanupEnabled(projectRoot) {
|
|
151318
|
+
if (!projectRoot) return true;
|
|
151319
|
+
try {
|
|
151320
|
+
const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
|
|
151321
|
+
return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
|
|
151322
|
+
} catch {
|
|
151323
|
+
return true;
|
|
151324
|
+
}
|
|
151325
|
+
}
|
|
150937
151326
|
function workspaceMode(payload) {
|
|
150938
151327
|
return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
|
|
150939
151328
|
}
|
|
@@ -151022,6 +151411,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151022
151411
|
if (job.projectId !== projectId) {
|
|
151023
151412
|
return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
|
|
151024
151413
|
}
|
|
151414
|
+
if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
|
|
151415
|
+
return { action: "complete" };
|
|
151416
|
+
}
|
|
151025
151417
|
if (job.kind === "media-video-generation") {
|
|
151026
151418
|
const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
|
|
151027
151419
|
return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
|
|
@@ -151114,6 +151506,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151114
151506
|
});
|
|
151115
151507
|
return { action: "complete" };
|
|
151116
151508
|
}
|
|
151509
|
+
if (job.kind === "observation-project") {
|
|
151510
|
+
if (!projectRoot) {
|
|
151511
|
+
throw new Error(`Observation projection requires a project root for ${projectId}`);
|
|
151512
|
+
}
|
|
151513
|
+
const id = observationId(job.payload);
|
|
151514
|
+
if (!id) return { action: "complete" };
|
|
151515
|
+
const [
|
|
151516
|
+
{ CodeGraphStore: CodeGraphStore2 },
|
|
151517
|
+
{ bindObservationToCode: bindObservationToCode2 },
|
|
151518
|
+
{ EvidenceCardStore: EvidenceCardStore2 },
|
|
151519
|
+
{ getObservationStore: getObservationStore2 }
|
|
151520
|
+
] = await Promise.all([
|
|
151521
|
+
Promise.resolve().then(() => (init_store(), store_exports)),
|
|
151522
|
+
Promise.resolve().then(() => (init_binder(), binder_exports)),
|
|
151523
|
+
Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
|
|
151524
|
+
Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
|
|
151525
|
+
]);
|
|
151526
|
+
const observation = await getObservationStore2().getById(id);
|
|
151527
|
+
if (!observation || observation.projectId !== projectId) return { action: "complete" };
|
|
151528
|
+
const codeStore = new CodeGraphStore2();
|
|
151529
|
+
await codeStore.init(projectDir2);
|
|
151530
|
+
await bindObservationToCode2(codeStore, observation);
|
|
151531
|
+
const evidence = new EvidenceCardStore2();
|
|
151532
|
+
await evidence.init(projectDir2);
|
|
151533
|
+
evidence.upsertObservation(observation);
|
|
151534
|
+
return { action: "complete" };
|
|
151535
|
+
}
|
|
151117
151536
|
if (job.kind === "observation-qualify") {
|
|
151118
151537
|
const [
|
|
151119
151538
|
{ CodeGraphStore: CodeGraphStore2 },
|
|
@@ -151321,7 +151740,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151321
151740
|
const after = getVectorStatus2(projectId);
|
|
151322
151741
|
if (after.missing === 0) {
|
|
151323
151742
|
resolveSupersededVectorFailures(projectDir2, projectId);
|
|
151324
|
-
return {
|
|
151743
|
+
return {
|
|
151744
|
+
action: "complete",
|
|
151745
|
+
progress: {
|
|
151746
|
+
attempted: result.attempted,
|
|
151747
|
+
succeeded: result.succeeded,
|
|
151748
|
+
failed: result.failed,
|
|
151749
|
+
remaining: 0
|
|
151750
|
+
}
|
|
151751
|
+
};
|
|
151325
151752
|
}
|
|
151326
151753
|
if (result.failed > 0 && result.succeeded === 0) {
|
|
151327
151754
|
const streak = vectorBackfillFailureStreak(job.payload) + 1;
|
|
@@ -151336,6 +151763,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151336
151763
|
...job.payload,
|
|
151337
151764
|
vectorBackfillFailureStreak: streak
|
|
151338
151765
|
},
|
|
151766
|
+
progress: {
|
|
151767
|
+
attempted: result.attempted,
|
|
151768
|
+
succeeded: result.succeeded,
|
|
151769
|
+
failed: result.failed,
|
|
151770
|
+
remaining: after.missing
|
|
151771
|
+
},
|
|
151339
151772
|
lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
|
|
151340
151773
|
};
|
|
151341
151774
|
}
|
|
@@ -151345,6 +151778,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
|
|
|
151345
151778
|
action: "reschedule",
|
|
151346
151779
|
delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
|
|
151347
151780
|
resetAttempts: result.succeeded > 0,
|
|
151781
|
+
progress: {
|
|
151782
|
+
attempted: result.attempted,
|
|
151783
|
+
succeeded: result.succeeded,
|
|
151784
|
+
failed: result.failed,
|
|
151785
|
+
remaining: after.missing
|
|
151786
|
+
},
|
|
151348
151787
|
...result.succeeded > 0 ? {
|
|
151349
151788
|
...priorFailureStreak > 0 ? { payload } : {},
|
|
151350
151789
|
...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
|
|
@@ -151753,24 +152192,40 @@ function queueVectorBackfill(projectId, options = {}) {
|
|
|
151753
152192
|
});
|
|
151754
152193
|
}
|
|
151755
152194
|
async function bindObservationCodeRefsBestEffort(observation) {
|
|
151756
|
-
if (!projectDir) return;
|
|
152195
|
+
if (!projectDir) return true;
|
|
151757
152196
|
try {
|
|
151758
152197
|
const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
|
|
151759
152198
|
const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
|
|
151760
152199
|
const codeStore = new CodeGraphStore2();
|
|
151761
152200
|
await codeStore.init(projectDir);
|
|
151762
152201
|
await bindObservationToCode2(codeStore, observation);
|
|
152202
|
+
return true;
|
|
151763
152203
|
} catch {
|
|
152204
|
+
return false;
|
|
151764
152205
|
}
|
|
151765
152206
|
}
|
|
151766
152207
|
async function persistEvidenceCard(observation) {
|
|
151767
|
-
if (!projectDir) return;
|
|
152208
|
+
if (!projectDir) return true;
|
|
151768
152209
|
try {
|
|
151769
152210
|
const evidence = new EvidenceCardStore();
|
|
151770
152211
|
await evidence.init(projectDir);
|
|
151771
152212
|
evidence.upsertObservation(observation);
|
|
152213
|
+
return true;
|
|
151772
152214
|
} catch (error) {
|
|
151773
152215
|
console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
152216
|
+
return false;
|
|
152217
|
+
}
|
|
152218
|
+
}
|
|
152219
|
+
async function acknowledgeObservationProjection(observation) {
|
|
152220
|
+
if (!projectDir) return;
|
|
152221
|
+
try {
|
|
152222
|
+
const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
|
|
152223
|
+
new MaintenanceJobStore2(projectDir).acknowledgePending(
|
|
152224
|
+
observation.projectId,
|
|
152225
|
+
"observation-project",
|
|
152226
|
+
"observation-project:" + observation.id
|
|
152227
|
+
);
|
|
152228
|
+
} catch {
|
|
151774
152229
|
}
|
|
151775
152230
|
}
|
|
151776
152231
|
function queueClaimDerivation(observation) {
|
|
@@ -151799,6 +152254,41 @@ function queueObservationQualification(observation) {
|
|
|
151799
152254
|
} catch {
|
|
151800
152255
|
}
|
|
151801
152256
|
}
|
|
152257
|
+
async function enqueueObservationDerivedWork(tx, observation) {
|
|
152258
|
+
if (!tx.enqueueMaintenanceJob) return false;
|
|
152259
|
+
if (!isEmbeddingExplicitlyDisabled()) {
|
|
152260
|
+
await tx.enqueueMaintenanceJob({
|
|
152261
|
+
projectId: observation.projectId,
|
|
152262
|
+
kind: "vector-backfill",
|
|
152263
|
+
dedupeKey: "vector-backfill",
|
|
152264
|
+
payload: { limit: 12 }
|
|
152265
|
+
});
|
|
152266
|
+
}
|
|
152267
|
+
if (observation.admissionState === "candidate") {
|
|
152268
|
+
await tx.enqueueMaintenanceJob({
|
|
152269
|
+
projectId: observation.projectId,
|
|
152270
|
+
kind: "observation-qualify",
|
|
152271
|
+
dedupeKey: "observation-qualify",
|
|
152272
|
+
payload: { source: "automatic-capture:" + observation.id, limit: 100 }
|
|
152273
|
+
});
|
|
152274
|
+
}
|
|
152275
|
+
const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
|
|
152276
|
+
if (claimSource && resolveObservationVisibility(observation) === "project") {
|
|
152277
|
+
await tx.enqueueMaintenanceJob({
|
|
152278
|
+
projectId: observation.projectId,
|
|
152279
|
+
kind: "claim-derive",
|
|
152280
|
+
dedupeKey: "claim-derive:" + observation.id,
|
|
152281
|
+
payload: { observationId: observation.id }
|
|
152282
|
+
});
|
|
152283
|
+
}
|
|
152284
|
+
await tx.enqueueMaintenanceJob({
|
|
152285
|
+
projectId: observation.projectId,
|
|
152286
|
+
kind: "observation-project",
|
|
152287
|
+
dedupeKey: "observation-project:" + observation.id,
|
|
152288
|
+
payload: { observationId: observation.id }
|
|
152289
|
+
});
|
|
152290
|
+
return true;
|
|
152291
|
+
}
|
|
151802
152292
|
function isVectorCompatibleWithCurrentIndex(embedding) {
|
|
151803
152293
|
if (!embedding) return false;
|
|
151804
152294
|
const vectorDimensions = getVectorDimensions();
|
|
@@ -151977,7 +152467,6 @@ async function storeObservation(input) {
|
|
|
151977
152467
|
throw new Error("Cannot update a memory outside this session's write scope.");
|
|
151978
152468
|
}
|
|
151979
152469
|
const observation2 = await upsertObservation(existing, input, now3);
|
|
151980
|
-
await input.onPersisted?.(observation2);
|
|
151981
152470
|
return { observation: observation2, upserted: true };
|
|
151982
152471
|
}
|
|
151983
152472
|
}
|
|
@@ -152004,6 +152493,7 @@ async function storeObservation(input) {
|
|
|
152004
152493
|
let upsertedInsideLock = false;
|
|
152005
152494
|
let reloadCacheAfterCommit = false;
|
|
152006
152495
|
let persistedCallbackInvoked = false;
|
|
152496
|
+
let derivedJobsCommitted = false;
|
|
152007
152497
|
const assignAndPersist = async () => {
|
|
152008
152498
|
if (projectDir) {
|
|
152009
152499
|
const store = getObservationStore();
|
|
@@ -152059,6 +152549,7 @@ async function storeObservation(input) {
|
|
|
152059
152549
|
writeGeneration: transactionGeneration + 1
|
|
152060
152550
|
};
|
|
152061
152551
|
await tx.insert(observation);
|
|
152552
|
+
derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
|
|
152062
152553
|
await input.onPersisted?.(observation);
|
|
152063
152554
|
persistedCallbackInvoked = true;
|
|
152064
152555
|
await tx.saveIdCounter(id + 1);
|
|
@@ -152157,15 +152648,17 @@ async function storeObservation(input) {
|
|
|
152157
152648
|
await assignAndPersist();
|
|
152158
152649
|
if (upsertedInsideLock) {
|
|
152159
152650
|
const updated = await upsertObservation(observation, input, now3);
|
|
152160
|
-
await input.onPersisted?.(updated);
|
|
152161
152651
|
return { observation: updated, upserted: true };
|
|
152162
152652
|
}
|
|
152163
152653
|
if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
|
|
152164
|
-
await bindObservationCodeRefsBestEffort(observation);
|
|
152165
|
-
await persistEvidenceCard(observation);
|
|
152166
|
-
|
|
152167
|
-
if (
|
|
152168
|
-
|
|
152654
|
+
const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
|
|
152655
|
+
const evidenceProjected = await persistEvidenceCard(observation);
|
|
152656
|
+
if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
|
|
152657
|
+
if (!derivedJobsCommitted) {
|
|
152658
|
+
queueObservationQualification(observation);
|
|
152659
|
+
if (resolveObservationVisibility(observation) === "project") {
|
|
152660
|
+
queueClaimDerivation(observation);
|
|
152661
|
+
}
|
|
152169
152662
|
}
|
|
152170
152663
|
scheduleObservationEmbedding({
|
|
152171
152664
|
observationId: observation.id,
|
|
@@ -152187,86 +152680,115 @@ async function upsertObservation(existing, input, now3) {
|
|
|
152187
152680
|
}
|
|
152188
152681
|
const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
|
|
152189
152682
|
const tokens = countTextTokens(fullText);
|
|
152190
|
-
|
|
152191
|
-
|
|
152192
|
-
|
|
152193
|
-
|
|
152194
|
-
|
|
152195
|
-
|
|
152196
|
-
|
|
152197
|
-
|
|
152198
|
-
|
|
152199
|
-
|
|
152200
|
-
|
|
152201
|
-
|
|
152202
|
-
|
|
152203
|
-
|
|
152204
|
-
|
|
152205
|
-
|
|
152206
|
-
|
|
152207
|
-
|
|
152208
|
-
|
|
152209
|
-
|
|
152210
|
-
|
|
152683
|
+
const applyUpdate = (current) => ({
|
|
152684
|
+
...current,
|
|
152685
|
+
entityName: input.entityName,
|
|
152686
|
+
type: input.type,
|
|
152687
|
+
title: input.title,
|
|
152688
|
+
narrative: input.narrative,
|
|
152689
|
+
facts: input.facts ?? [],
|
|
152690
|
+
attachments: input.attachments,
|
|
152691
|
+
filesModified: enrichedFiles,
|
|
152692
|
+
concepts: enrichedConcepts,
|
|
152693
|
+
tokens,
|
|
152694
|
+
updatedAt: now3,
|
|
152695
|
+
hasCausalLanguage: extracted.hasCausalLanguage,
|
|
152696
|
+
revisionCount: (current.revisionCount ?? 1) + 1,
|
|
152697
|
+
status: "active",
|
|
152698
|
+
...input.sessionId ? { sessionId: input.sessionId } : {},
|
|
152699
|
+
...input.progress ? { progress: input.progress } : {},
|
|
152700
|
+
...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
|
|
152701
|
+
...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
|
|
152702
|
+
...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
|
|
152703
|
+
...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
|
|
152704
|
+
...input.visibility !== void 0 ? { visibility: input.visibility } : {},
|
|
152705
|
+
...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
|
|
152706
|
+
});
|
|
152707
|
+
let updated = applyUpdate(existing);
|
|
152708
|
+
let derivedJobsCommitted = false;
|
|
152709
|
+
if (projectDir) {
|
|
152710
|
+
const store = getObservationStore();
|
|
152711
|
+
await store.atomic(async (tx) => {
|
|
152712
|
+
const current = await tx.getById(existing.id);
|
|
152713
|
+
if (!current || current.projectId !== existing.projectId) {
|
|
152714
|
+
throw new Error("Topic observation changed before update");
|
|
152715
|
+
}
|
|
152716
|
+
updated = applyUpdate(current);
|
|
152717
|
+
updated.writeGeneration = await tx.getGeneration() + 1;
|
|
152718
|
+
await tx.update(updated);
|
|
152719
|
+
derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
|
|
152720
|
+
await input.onPersisted?.(updated);
|
|
152721
|
+
});
|
|
152722
|
+
updated.writeGeneration = store.getGeneration();
|
|
152723
|
+
} else {
|
|
152724
|
+
await input.onPersisted?.(updated);
|
|
152725
|
+
}
|
|
152726
|
+
if (corpusLoaded) {
|
|
152727
|
+
const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
|
|
152728
|
+
if (cacheIndex >= 0) observations[cacheIndex] = updated;
|
|
152729
|
+
}
|
|
152211
152730
|
const doc = {
|
|
152212
|
-
id: makeOramaObservationId(
|
|
152213
|
-
observationId:
|
|
152214
|
-
entityName:
|
|
152215
|
-
type:
|
|
152216
|
-
title:
|
|
152217
|
-
narrative:
|
|
152218
|
-
facts:
|
|
152731
|
+
id: makeOramaObservationId(updated.projectId, updated.id),
|
|
152732
|
+
observationId: updated.id,
|
|
152733
|
+
entityName: updated.entityName,
|
|
152734
|
+
type: updated.type,
|
|
152735
|
+
title: updated.title,
|
|
152736
|
+
narrative: updated.narrative,
|
|
152737
|
+
facts: updated.facts.join("\n"),
|
|
152219
152738
|
filesModified: enrichedFiles.join("\n"),
|
|
152220
152739
|
concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
|
|
152221
|
-
attachments: formatAttachmentProvenance(
|
|
152740
|
+
attachments: formatAttachmentProvenance(updated.attachments),
|
|
152222
152741
|
tokens,
|
|
152223
|
-
createdAt:
|
|
152224
|
-
projectId:
|
|
152742
|
+
createdAt: updated.createdAt,
|
|
152743
|
+
projectId: updated.projectId,
|
|
152225
152744
|
accessCount: 0,
|
|
152226
152745
|
lastAccessedAt: "",
|
|
152227
152746
|
status: "active",
|
|
152228
|
-
source:
|
|
152229
|
-
sourceDetail:
|
|
152230
|
-
valueCategory:
|
|
152231
|
-
admissionState:
|
|
152232
|
-
admissionReason:
|
|
152233
|
-
visibility:
|
|
152234
|
-
createdByAgentId:
|
|
152235
|
-
sharedWithAgentIds: JSON.stringify(
|
|
152236
|
-
};
|
|
152237
|
-
|
|
152238
|
-
|
|
152239
|
-
const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
|
|
152240
|
-
await removeObservation2(oramaId);
|
|
152241
|
-
} catch {
|
|
152242
|
-
}
|
|
152243
|
-
try {
|
|
152244
|
-
await insertObservation(doc);
|
|
152245
|
-
} catch {
|
|
152747
|
+
source: updated.source ?? "agent",
|
|
152748
|
+
sourceDetail: updated.sourceDetail ?? "",
|
|
152749
|
+
valueCategory: updated.valueCategory ?? "",
|
|
152750
|
+
admissionState: updated.admissionState ?? "",
|
|
152751
|
+
admissionReason: updated.admissionReason ?? "",
|
|
152752
|
+
visibility: updated.visibility ?? "project",
|
|
152753
|
+
createdByAgentId: updated.createdByAgentId ?? "",
|
|
152754
|
+
sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
|
|
152755
|
+
};
|
|
152756
|
+
if (corpusLoaded) {
|
|
152757
|
+
const oramaId = makeOramaObservationId(updated.projectId, updated.id);
|
|
152246
152758
|
try {
|
|
152247
|
-
|
|
152248
|
-
|
|
152759
|
+
try {
|
|
152760
|
+
await removeObservation(oramaId);
|
|
152761
|
+
} catch {
|
|
152762
|
+
}
|
|
152249
152763
|
await insertObservation(doc);
|
|
152250
152764
|
} catch {
|
|
152765
|
+
try {
|
|
152766
|
+
try {
|
|
152767
|
+
await removeObservation(oramaId);
|
|
152768
|
+
} catch {
|
|
152769
|
+
}
|
|
152770
|
+
await insertObservation(doc);
|
|
152771
|
+
} catch (error) {
|
|
152772
|
+
console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
|
|
152773
|
+
}
|
|
152251
152774
|
}
|
|
152252
152775
|
}
|
|
152253
|
-
|
|
152254
|
-
|
|
152255
|
-
|
|
152256
|
-
|
|
152257
|
-
|
|
152258
|
-
|
|
152259
|
-
|
|
152260
|
-
|
|
152261
|
-
queueClaimDerivation(existing);
|
|
152776
|
+
const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
|
|
152777
|
+
const evidenceProjected = await persistEvidenceCard(updated);
|
|
152778
|
+
if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
|
|
152779
|
+
if (!derivedJobsCommitted) {
|
|
152780
|
+
queueObservationQualification(updated);
|
|
152781
|
+
if (resolveObservationVisibility(updated) === "project") {
|
|
152782
|
+
queueClaimDerivation(updated);
|
|
152783
|
+
}
|
|
152262
152784
|
}
|
|
152263
152785
|
scheduleObservationEmbedding({
|
|
152264
|
-
observationId:
|
|
152265
|
-
projectId:
|
|
152786
|
+
observationId: updated.id,
|
|
152787
|
+
projectId: updated.projectId,
|
|
152266
152788
|
searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
|
|
152267
152789
|
doc
|
|
152268
152790
|
});
|
|
152269
|
-
return
|
|
152791
|
+
return updated;
|
|
152270
152792
|
}
|
|
152271
152793
|
function getObservation(id, projectId) {
|
|
152272
152794
|
return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
|
|
@@ -152610,7 +153132,7 @@ function getSearchIndexStatus(projectId) {
|
|
|
152610
153132
|
};
|
|
152611
153133
|
}
|
|
152612
153134
|
async function probeSearchIndex(projectId) {
|
|
152613
|
-
await
|
|
153135
|
+
const result = await searchObservationsDetailed({
|
|
152614
153136
|
query: "semantic memory retrieval status",
|
|
152615
153137
|
projectId,
|
|
152616
153138
|
reader: { projectId },
|
|
@@ -152618,7 +153140,7 @@ async function probeSearchIndex(projectId) {
|
|
|
152618
153140
|
status: "all",
|
|
152619
153141
|
trackAccess: false
|
|
152620
153142
|
});
|
|
152621
|
-
return
|
|
153143
|
+
return result.diagnostics.mode;
|
|
152622
153144
|
}
|
|
152623
153145
|
async function backfillVectorEmbeddings(options = {}) {
|
|
152624
153146
|
if (vectorBackfillRunning) {
|