synabun 2.4.0 → 2.4.2
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 +47 -0
- package/README.md +1 -1
- package/browser-extension/content.js +73 -11
- package/browser-extension/engine.js +196 -15
- package/browser-extension/manifest.json +4 -2
- package/browser-extension/popup-strings.js +10 -4
- package/browser-extension/popup-view.js +1 -1
- package/browser-extension/popup.css +1 -0
- package/browser-extension/popup.html +4 -1
- package/browser-extension/popup.js +22 -10
- package/browser-extension/protocol.js +102 -11
- package/browser-extension/service-worker.js +20 -4
- package/browser-extension/tokens.css +1 -1
- package/docs/browser-extension-bridge.md +25 -5
- package/lib/data-home-files.js +47 -0
- package/lib/data-home-migration.js +34 -58
- package/lib/first-launch-protection.js +8 -2
- package/lib/update-snapshot.js +11 -4
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +25 -2
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +62 -17
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-bench.d.ts +22 -22
- package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
- package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-maintenance.js +34 -45
- package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
- package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
- package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-copy.js +467 -0
- package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
- package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/memory-migration-worker.js +60 -0
- package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
- package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-retrieval.js +188 -40
- package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
- package/mcp-server/dist/services/memory-schema.d.ts +58 -2
- package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-schema.js +190 -13
- package/mcp-server/dist/services/memory-schema.js.map +1 -1
- package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
- package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-sessions.js +56 -20
- package/mcp-server/dist/services/memory-sessions.js.map +1 -1
- package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
- package/mcp-server/dist/services/memory-verification.js +8 -5
- package/mcp-server/dist/services/memory-verification.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +6 -0
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +19 -2
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
- package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
- package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
- package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
- package/mcp-server/dist/services/retrieval-reader.js +145 -0
- package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
- package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
- package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
- package/mcp-server/dist/services/sqlite-write.js +94 -0
- package/mcp-server/dist/services/sqlite-write.js.map +1 -0
- package/mcp-server/dist/services/sqlite.d.ts +39 -0
- package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
- package/mcp-server/dist/services/sqlite.js +249 -8
- package/mcp-server/dist/services/sqlite.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
- package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
- package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe-config.js +32 -10
- package/mcp-server/dist/services/typesafe-config.js.map +1 -1
- package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
- package/mcp-server/dist/services/typesafe.js +9 -7
- package/mcp-server/dist/services/typesafe.js.map +1 -1
- package/mcp-server/dist/services/vector-cache.d.ts +32 -0
- package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
- package/mcp-server/dist/services/vector-cache.js +161 -8
- package/mcp-server/dist/services/vector-cache.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
- package/mcp-server/dist/tools/agents.d.ts +13 -8
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +35 -15
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +10 -3
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
- package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
- package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
- package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
- package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-interact.js +6 -1
- package/mcp-server/dist/tools/browser-interact.js.map +1 -1
- package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +20 -2
- package/mcp-server/src/index.ts +59 -17
- package/mcp-server/src/services/memory-maintenance.ts +31 -28
- package/mcp-server/src/services/memory-migration-copy.ts +419 -0
- package/mcp-server/src/services/memory-migration-worker.ts +55 -0
- package/mcp-server/src/services/memory-retrieval.ts +173 -32
- package/mcp-server/src/services/memory-schema.ts +194 -12
- package/mcp-server/src/services/memory-sessions.ts +54 -21
- package/mcp-server/src/services/memory-verification.ts +7 -4
- package/mcp-server/src/services/neural-interface.ts +23 -2
- package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
- package/mcp-server/src/services/retrieval-reader.ts +131 -0
- package/mcp-server/src/services/sqlite-write.ts +60 -0
- package/mcp-server/src/services/sqlite.ts +246 -8
- package/mcp-server/src/services/typesafe-config.ts +25 -6
- package/mcp-server/src/services/typesafe.ts +9 -7
- package/mcp-server/src/services/vector-cache.ts +154 -9
- package/mcp-server/src/tools/agents.ts +33 -14
- package/mcp-server/src/tools/browser-advanced.ts +10 -3
- package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
- package/mcp-server/src/tools/browser-interact.ts +5 -1
- package/neural-interface/i18n/en.json +266 -2
- package/neural-interface/i18n/pt-BR.json +267 -3
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/registry.js +60 -15
- package/neural-interface/lib/agents/resolve.js +69 -10
- package/neural-interface/lib/agents/split.js +32 -4
- package/neural-interface/lib/assistant-api.js +19 -8
- package/neural-interface/lib/assistant-brains/claude.js +2 -0
- package/neural-interface/lib/assistant-brains/opencode.js +60 -11
- package/neural-interface/lib/assistant-catalog.js +2 -2
- package/neural-interface/lib/assistant-config.js +0 -7
- package/neural-interface/lib/assistant-dispatch.js +384 -119
- package/neural-interface/lib/assistant-persona.js +17 -5
- package/neural-interface/lib/assistant-pricing.js +65 -14
- package/neural-interface/lib/assistant-router.js +181 -54
- package/neural-interface/lib/assistant-run-wait.js +45 -28
- package/neural-interface/lib/assistant-runtime.js +48 -34
- package/neural-interface/lib/backup-contents.js +158 -0
- package/neural-interface/lib/backup-crypto-io.js +330 -0
- package/neural-interface/lib/backup-crypto-worker.js +130 -0
- package/neural-interface/lib/backup-crypto.js +525 -0
- package/neural-interface/lib/backup-download.js +268 -0
- package/neural-interface/lib/backup-encryption.js +318 -0
- package/neural-interface/lib/backup-groups.js +287 -0
- package/neural-interface/lib/backup-restore-session.js +176 -0
- package/neural-interface/lib/backup-restore-stage.js +60 -0
- package/neural-interface/lib/backup-service.js +836 -322
- package/neural-interface/lib/backup-zip-reader.js +30 -18
- package/neural-interface/lib/backup-zip-writer.js +34 -10
- package/neural-interface/lib/browser-extension-adapter.js +109 -24
- package/neural-interface/lib/browser-extension-bridge.js +42 -8
- package/neural-interface/lib/claude-agent-bridge.js +1 -0
- package/neural-interface/lib/claude-session-cleanup.js +5 -1
- package/neural-interface/lib/cli-update-planner.js +105 -6
- package/neural-interface/lib/client-diagnostics.js +42 -0
- package/neural-interface/lib/confined-fs.js +7 -2
- package/neural-interface/lib/coordination/README.md +8 -2
- package/neural-interface/lib/coordination/contract.js +161 -0
- package/neural-interface/lib/coordination/database.js +999 -0
- package/neural-interface/lib/coordination/operations.js +436 -0
- package/neural-interface/lib/coordination/service.js +68 -537
- package/neural-interface/lib/coordination/storage-worker.js +101 -0
- package/neural-interface/lib/coordination/store.js +219 -1111
- package/neural-interface/lib/db.js +70 -32
- package/neural-interface/lib/health-count.js +37 -0
- package/neural-interface/lib/loop-stall.js +139 -0
- package/neural-interface/lib/maritaca/client.js +2 -2
- package/neural-interface/lib/maritaca/models.js +12 -17
- package/neural-interface/lib/maritaca/opencode.js +4 -2
- package/neural-interface/lib/memory-api.js +9 -1
- package/neural-interface/lib/memory-session-capture.js +42 -10
- package/neural-interface/lib/memory-store-gate.js +313 -0
- package/neural-interface/lib/memory-store-migrate.js +65 -0
- package/neural-interface/lib/memory-timers.js +7 -7
- package/neural-interface/lib/native-loop-providers.js +13 -16
- package/neural-interface/lib/native-loop-runtime.js +34 -14
- package/neural-interface/lib/opencode-build-preflight.js +30 -8
- package/neural-interface/lib/opencode-native-boundary.js +69 -8
- package/neural-interface/lib/opencode-provider-view.js +14 -3
- package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
- package/neural-interface/lib/opencode2-client.js +2 -1
- package/neural-interface/lib/peer-identity.js +13 -8
- package/neural-interface/lib/recall-impact.js +122 -0
- package/neural-interface/lib/scratch-evidence.js +420 -0
- package/neural-interface/lib/scratch-process-guard.js +139 -0
- package/neural-interface/lib/scratch-references.js +279 -0
- package/neural-interface/lib/scratch-retention-core.js +385 -0
- package/neural-interface/lib/scratch-retention-worker.js +37 -0
- package/neural-interface/lib/scratch-retention.js +151 -0
- package/neural-interface/lib/session-cache-builder.js +70 -44
- package/neural-interface/lib/session-cache-worker.js +157 -0
- package/neural-interface/lib/session-indexer.js +28 -21
- package/neural-interface/lib/session-search-index.js +85 -0
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
- package/neural-interface/lib/style-guide/store.js +43 -3
- package/neural-interface/lib/system-restore.js +50 -0
- package/neural-interface/lib/teams/api.js +15 -6
- package/neural-interface/lib/teams/claims.js +67 -31
- package/neural-interface/lib/teams/index.js +7 -7
- package/neural-interface/lib/teams/integration.js +40 -40
- package/neural-interface/lib/teams/landing.js +6 -6
- package/neural-interface/lib/teams/recovery.js +24 -23
- package/neural-interface/lib/teams/scheduler.js +196 -97
- package/neural-interface/lib/teams/schema.js +1 -1
- package/neural-interface/lib/teams/state.js +14 -14
- package/neural-interface/lib/teams/worktrees.js +27 -27
- package/neural-interface/lib/whatsapp/bridge.js +2 -1
- package/neural-interface/lib/worker-confinement.js +47 -2
- package/neural-interface/lib/worker-mcp-channel.js +2 -0
- package/neural-interface/lib/worker-resume.js +5 -0
- package/neural-interface/lib/worker-stop.js +86 -0
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +260 -0
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/onboarding.html +259 -34
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
- package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
- package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
- package/neural-interface/public/shared/agy/agy-options.js +11 -0
- package/neural-interface/public/shared/agy/agy-panel.js +29 -10
- package/neural-interface/public/shared/agy/agy-styles.js +14 -12
- package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
- package/neural-interface/public/shared/api.js +3 -2
- package/neural-interface/public/shared/assistant/asst-api.js +3 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
- package/neural-interface/public/shared/assistant/asst-control.js +2 -0
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
- package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
- package/neural-interface/public/shared/assistant/asst-render.js +106 -38
- package/neural-interface/public/shared/assistant/asst-route.js +102 -21
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
- package/neural-interface/public/shared/assistant/asst-state.js +11 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
- package/neural-interface/public/shared/assistant/route-identity.js +2 -1
- package/neural-interface/public/shared/cc-dropdown.js +21 -15
- package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
- package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
- package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
- package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
- package/neural-interface/public/shared/client-diagnostics.js +94 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-styles.js +1 -1
- package/neural-interface/public/shared/effort-i18n.js +118 -0
- package/neural-interface/public/shared/html-shell.js +4 -51
- package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
- package/neural-interface/public/shared/memory-store-wait.js +52 -0
- package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
- package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
- package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
- package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
- package/neural-interface/public/shared/output-format.js +294 -0
- package/neural-interface/public/shared/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- package/neural-interface/public/shared/provider-icons.js +6 -0
- package/neural-interface/public/shared/schedules-view.js +2 -1
- package/neural-interface/public/shared/server-presence.js +77 -0
- package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
- package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
- package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
- package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
- package/neural-interface/public/shared/settings/settings-ia.js +1 -1
- package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
- package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
- package/neural-interface/public/shared/start-bridge.js +2 -2
- package/neural-interface/public/shared/studio-attention.js +6 -0
- package/neural-interface/public/shared/styles.css +354 -438
- package/neural-interface/public/shared/transcript-rows.js +28 -3
- package/neural-interface/public/shared/tray-auto-close.js +18 -5
- package/neural-interface/public/shared/ui-agents.js +1 -2
- package/neural-interface/public/shared/ui-automation-studio.js +168 -108
- package/neural-interface/public/shared/ui-claude-panel.js +42 -65
- package/neural-interface/public/shared/ui-loading.js +185 -25
- package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
- package/neural-interface/public/shared/ui-navbar.js +2 -1
- package/neural-interface/public/shared/ui-output.js +533 -0
- package/neural-interface/public/shared/ui-owner-authority.js +48 -25
- package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
- package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
- package/neural-interface/public/shared/ui-sessions.js +2 -2
- package/neural-interface/public/shared/ui-settings-entry.js +18 -0
- package/neural-interface/public/shared/ui-settings.js +234 -67
- package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
- package/neural-interface/public/shared/ui-sync.js +1 -0
- package/neural-interface/public/shared/ui-tooltip.js +16 -0
- package/neural-interface/public/shared/ui-tutorial.js +5 -6
- package/neural-interface/public/shared/ui-worker-end.js +27 -8
- package/neural-interface/public/shared/worker-end.js +9 -4
- package/neural-interface/public/sw.js +4 -3
- package/neural-interface/public/variant/2d/main.js +5 -0
- package/neural-interface/public/variant/3d/app.js +10 -0
- package/neural-interface/public/variant/3d/main.js +17 -4
- package/neural-interface/scripts/scratch-retention.mjs +20 -0
- package/neural-interface/server.js +507 -160
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/scripts/restore-data-home-from-backup.mjs +175 -8
- package/setup.js +18 -4
|
@@ -6,6 +6,8 @@ import { judgeHistoricalQuery, judgeRelevance, orderByJudgedScore, RELEVANCE_CAN
|
|
|
6
6
|
import { generateEmbedding, EMBEDDING_VERSION } from './local-embeddings.js';
|
|
7
7
|
import { projectAliases } from '../config.js';
|
|
8
8
|
import { judgedStale } from './edit-stale.js';
|
|
9
|
+
import { readRows } from './retrieval-reader.js';
|
|
10
|
+
import { withMemoryWrite } from './sqlite-write.js';
|
|
9
11
|
|
|
10
12
|
export interface RecallOptions {
|
|
11
13
|
query: string; project?: string; currentProject?: string; category?: string; tags?: string[];
|
|
@@ -36,14 +38,18 @@ const recentTimes: number[]=[];
|
|
|
36
38
|
const filterCache=new Map<string,Set<string>>();
|
|
37
39
|
let filterConnection: ReturnType<typeof getDb> | null=null;
|
|
38
40
|
let filterEpoch=-1;
|
|
39
|
-
|
|
41
|
+
// The memories a filter allows, kept per filter until a filtered column changes (the 'memory_filters' journal).
|
|
42
|
+
// Built on the retrieval reader's thread: reading every memory row took 15-35 ms of the caller's event loop.
|
|
43
|
+
async function memoryIds(sql:string,params:(string|number)[]) {
|
|
40
44
|
const d=getDb();
|
|
41
45
|
const epoch=Number(d.prepare("SELECT COALESCE(MAX(seq),0) AS n FROM memory_changes WHERE entity='memory_filters'").get()?.n || 0);
|
|
42
46
|
if(d!==filterConnection || epoch!==filterEpoch){filterCache.clear();filterConnection=d;filterEpoch=epoch;}
|
|
43
47
|
const key=JSON.stringify([sql,params]);
|
|
44
48
|
let ids=filterCache.get(key);
|
|
45
49
|
if(!ids) {
|
|
46
|
-
ids=new Set(
|
|
50
|
+
ids=new Set((await readRows(`SELECT m.id FROM memories m WHERE ${sql}`,params)).map(r=>String(r.id)));
|
|
51
|
+
// A newer filter epoch or another connection arrived while this was read: answer, keep nothing.
|
|
52
|
+
if(getDb()!==filterConnection || epoch!==filterEpoch)return ids;
|
|
47
53
|
filterCache.set(key,ids);
|
|
48
54
|
let total=0;for(const value of filterCache.values())total+=value.size;
|
|
49
55
|
while(filterCache.size>32 || (total>100000 && filterCache.size>1)) {
|
|
@@ -52,6 +58,93 @@ function memoryIds(sql:string,params:(string|number)[]) {
|
|
|
52
58
|
}
|
|
53
59
|
return ids;
|
|
54
60
|
}
|
|
61
|
+
// The session chunks a session filter allows, kept per filter and brought up
|
|
62
|
+
// to date from the change journal. Building it meant reading every chunk row
|
|
63
|
+
// (149k: ~150-300 ms of main thread) on each recall that searched sessions.
|
|
64
|
+
// The filter reads only the chunk row and the memory row with the same id, and
|
|
65
|
+
// both tables journal every insert, update and delete (memory-schema.ts), so
|
|
66
|
+
// each journalled id is checked again on its own. Built and replayed in pages
|
|
67
|
+
// that yield, so recall never holds the event loop for the whole table.
|
|
68
|
+
interface SessionIdSet { ids: Set<string>; seq: number; busy: Promise<void> }
|
|
69
|
+
const sessionIdCache = new Map<string, SessionIdSet>();
|
|
70
|
+
let sessionIdConnection: ReturnType<typeof getDb> | null = null;
|
|
71
|
+
const SESSION_ID_CACHE_ENTRIES = 4;
|
|
72
|
+
// Rowids of session_chunks read per statement (on the reader) while a filter's ids are built.
|
|
73
|
+
const SESSION_ID_WINDOW = 5000;
|
|
74
|
+
const yieldIfDue = async (slice: { at: number }) => {
|
|
75
|
+
if (performance.now() - slice.at < 8) return;
|
|
76
|
+
await new Promise<void>(done => setImmediate(done));
|
|
77
|
+
slice.at = performance.now();
|
|
78
|
+
};
|
|
79
|
+
export async function sessionChunkIds(sql: string, params: (string | number)[]): Promise<Set<string>> {
|
|
80
|
+
const d = getDb();
|
|
81
|
+
if (d !== sessionIdConnection) { sessionIdCache.clear(); sessionIdConnection = d; }
|
|
82
|
+
const key = JSON.stringify([sql, params]);
|
|
83
|
+
let entry = sessionIdCache.get(key);
|
|
84
|
+
if (entry) { sessionIdCache.delete(key); sessionIdCache.set(key, entry); }
|
|
85
|
+
else {
|
|
86
|
+
entry = { ids: new Set(), seq: -1, busy: Promise.resolve() };
|
|
87
|
+
sessionIdCache.set(key, entry);
|
|
88
|
+
while (sessionIdCache.size > SESSION_ID_CACHE_ENTRIES) sessionIdCache.delete(sessionIdCache.keys().next().value!);
|
|
89
|
+
}
|
|
90
|
+
const current = entry;
|
|
91
|
+
// One update at a time per filter; a caller that arrives meanwhile waits for it and then catches up.
|
|
92
|
+
const update = current.busy.then(async () => {
|
|
93
|
+
if (getDb() !== d) return;
|
|
94
|
+
const readHead = () => Number((d.prepare('SELECT COALESCE(MAX(seq),0) AS seq FROM memory_changes').get() as { seq: number }).seq);
|
|
95
|
+
let head = readHead();
|
|
96
|
+
const slice = { at: performance.now() };
|
|
97
|
+
if (current.seq < 0) {
|
|
98
|
+
// Rows changed behind the pages already read are journalled after `head` and replayed just below.
|
|
99
|
+
// (A build that failed part way starts again from nothing.)
|
|
100
|
+
current.ids.clear();
|
|
101
|
+
// Read on the retrieval reader's thread, in fixed rowid windows (not "the next N matches": a selective filter, a
|
|
102
|
+
// small project, would otherwise read the whole table in one statement). A cold 2 GB store took ~100 ms of this
|
|
103
|
+
// thread per 1,000 rows. Each window starts at the next row that exists (rowids can have gaps).
|
|
104
|
+
// Anonymous placeholders only: node:sqlite before Node 24 cannot bind numbered ones (?1) positionally, and the
|
|
105
|
+
// desktop app runs Node 22.
|
|
106
|
+
const window = `SELECT m.id,(SELECT MIN(rowid) FROM session_chunks WHERE rowid>?) AS next FROM session_chunks m
|
|
107
|
+
WHERE m.rowid>? AND m.rowid<=? AND ${sql}`;
|
|
108
|
+
const first = await readRows('SELECT MIN(rowid) AS r FROM session_chunks', []);
|
|
109
|
+
for (let from = first[0]?.r == null ? null : Number(first[0].r) - 1; from !== null;) {
|
|
110
|
+
const to = from + SESSION_ID_WINDOW;
|
|
111
|
+
const rows = await readRows(window, [to, from, to, ...params]);
|
|
112
|
+
if (getDb() !== d) return;
|
|
113
|
+
for (const row of rows) current.ids.add(String(row.id));
|
|
114
|
+
// No match in a window: ask for the next row that exists directly.
|
|
115
|
+
const next = rows.length ? rows[0].next : (await readRows('SELECT MIN(rowid) AS r FROM session_chunks WHERE rowid>?', [from + SESSION_ID_WINDOW]))[0]?.r;
|
|
116
|
+
from = next == null ? null : Number(next) - 1;
|
|
117
|
+
await yieldIfDue(slice);
|
|
118
|
+
if (getDb() !== d) return;
|
|
119
|
+
}
|
|
120
|
+
current.seq = head;
|
|
121
|
+
head = readHead();
|
|
122
|
+
}
|
|
123
|
+
if (current.seq < head) {
|
|
124
|
+
// The journalled ids are checked again a page at a time on the reader (one statement per page, never one per id).
|
|
125
|
+
for (let after = current.seq, rows = await readRows(CHANGES, [after, head]); rows.length; rows = await readRows(CHANGES, [after, head])) {
|
|
126
|
+
if (getDb() !== d) return;
|
|
127
|
+
const ids = [...new Set(rows.map(r => String(r.id)))];
|
|
128
|
+
const allowed = new Set((await readRows(`SELECT m.id FROM session_chunks m WHERE m.id IN (${ids.map(() => '?').join(',')}) AND ${sql}`, [...ids, ...params])).map(r => String(r.id)));
|
|
129
|
+
if (getDb() !== d) return;
|
|
130
|
+
for (const id of ids) { if (allowed.has(id)) current.ids.add(id); else current.ids.delete(id); }
|
|
131
|
+
after = Number(rows[rows.length - 1].seq);
|
|
132
|
+
await yieldIfDue(slice);
|
|
133
|
+
}
|
|
134
|
+
current.seq = head;
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
current.busy = update.catch(() => {});
|
|
138
|
+
await update;
|
|
139
|
+
if (getDb() !== d) return new Set((await readRows(`SELECT m.id FROM session_chunks m WHERE ${sql}`, params)).map(r => String(r.id)));
|
|
140
|
+
return current.ids;
|
|
141
|
+
}
|
|
142
|
+
const CHANGES = `SELECT seq,id FROM memory_changes WHERE seq>? AND seq<=? AND entity IN ('session_chunks','memories') ORDER BY seq LIMIT 1000`;
|
|
143
|
+
/** Startup warm-up of the vector caches every recall reads (session chunks are loaded on first use, as before). */
|
|
144
|
+
export async function warmRetrievalCaches(): Promise<void> {
|
|
145
|
+
await memoryVectors.ready();
|
|
146
|
+
await passages.ready();
|
|
147
|
+
}
|
|
55
148
|
export function retrievalMetrics() {
|
|
56
149
|
const sorted=[...recentTimes].sort((a,b)=>a-b);
|
|
57
150
|
return { ...metrics, p50_ms:sorted[Math.floor(sorted.length*.5)] ?? 0, p95_ms:sorted[Math.floor(sorted.length*.95)] ?? 0 };
|
|
@@ -146,28 +239,38 @@ export async function retrieveMemory(o: RecallOptions, embed = generateEmbedding
|
|
|
146
239
|
else { hit.reasons.push(reason); found.set(key, hit); }
|
|
147
240
|
ranks.set(key, (ranks.get(key) || 0) + 1 / (60 + rank));
|
|
148
241
|
}
|
|
149
|
-
|
|
242
|
+
// The full-text search: one FTS5 statement that cannot yield, so it runs on the retrieval reader's thread
|
|
243
|
+
// (retrieval-reader.ts). Started early, applied where the synchronous search used to run, so the order hits are
|
|
244
|
+
// added in (and with it every reason list and rank) is unchanged.
|
|
245
|
+
type KeywordRows = Record<string, any>[] | null | { failed: true };
|
|
246
|
+
function keywordRows(session: boolean): Promise<KeywordRows> {
|
|
247
|
+
if (!terms.length) return Promise.resolve(null);
|
|
150
248
|
const table = session ? 'session_chunks' : 'memories';
|
|
151
249
|
const filter = session ? sessionFilter : memoryFilter;
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
250
|
+
const fts = session ? 'chunk_search' : 'memory_search';
|
|
251
|
+
return readRows(`SELECT m.* FROM ${fts} f JOIN ${table} m ON m.id=f.id
|
|
252
|
+
WHERE ${fts} MATCH ? AND ${filter.sql} ORDER BY bm25(${fts}) LIMIT ?`,
|
|
253
|
+
[terms.map(t => `"${t.replace(/"/g,'""')}"`).join(' OR '), ...filter.params, k])
|
|
254
|
+
.catch(() => ({ failed: true as const }));
|
|
255
|
+
}
|
|
256
|
+
function applyKeyword(session: boolean, rows: KeywordRows) {
|
|
257
|
+
if (!rows) return;
|
|
258
|
+
try {
|
|
259
|
+
if (!Array.isArray(rows)) throw new Error('keyword search failed');
|
|
260
|
+
rows.forEach((row, i) => {
|
|
261
|
+
const h = hydrate(row, session);
|
|
262
|
+
const body = `${h.content} ${h.payload.related_files || h.payload.files_modified || ''}`.toLowerCase();
|
|
263
|
+
const covered = terms.filter(t => body.includes(t)).length / terms.length;
|
|
264
|
+
h.score = covered;
|
|
265
|
+
if (covered >= min) add(h, i + 1, 'keyword');
|
|
266
|
+
});
|
|
267
|
+
} catch (error) { degraded.push(`Keyword index unavailable (${session ? 'sessions' : 'memories'}).`); }
|
|
268
|
+
}
|
|
269
|
+
function search(session: boolean, ids: Set<string> | undefined, sessionHits?: Array<{ id: string; score: number }>) {
|
|
270
|
+
const table = session ? 'session_chunks' : 'memories';
|
|
271
|
+
const filter = session ? sessionFilter : memoryFilter;
|
|
272
|
+
if (vector) {
|
|
273
|
+
const hits = session && sessionHits ? sessionHits : (session ? chunkVectors : memoryVectors).topK(vector, k, hybrid ? min : min * 0.5, ids);
|
|
171
274
|
const hydrateRow = d.prepare(`SELECT m.* FROM ${table} m WHERE m.id=? AND ${filter.sql}`);
|
|
172
275
|
hits.forEach((hit, i) => {
|
|
173
276
|
const row = hydrateRow.get(hit.id,...filter.params);
|
|
@@ -175,21 +278,40 @@ export async function retrieveMemory(o: RecallOptions, embed = generateEmbedding
|
|
|
175
278
|
});
|
|
176
279
|
}
|
|
177
280
|
}
|
|
178
|
-
|
|
281
|
+
const pendingMemoryKeyword = hybrid ? keywordRows(false) : null;
|
|
282
|
+
// The memory id list is needed only with a vector; asked now so it reads while the query is embedded.
|
|
283
|
+
const pendingMemoryIds = memoryIds(memoryFilter.sql, memoryFilter.params);
|
|
284
|
+
pendingMemoryIds.catch(() => {});
|
|
285
|
+
if (pendingMemoryKeyword) applyKeyword(false, await pendingMemoryKeyword);
|
|
179
286
|
mark('keyword');
|
|
180
287
|
vector=await pendingEmbedding;
|
|
181
288
|
mark('embedding_wait');
|
|
289
|
+
// Everything the vector searches below read is brought up to date here, in
|
|
290
|
+
// slices that yield. Each synchronous topK() below follows a ready() of its own
|
|
291
|
+
// cache with no await in between, so it finds (almost) no journal left to replay.
|
|
292
|
+
const sessionsPossible = o.include_sessions !== false;
|
|
293
|
+
let sessionIds: Set<string> | null = null;
|
|
294
|
+
let allowedMemories: Set<string> | undefined;
|
|
295
|
+
if (vector) {
|
|
296
|
+
[allowedMemories] = await Promise.all([pendingMemoryIds, memoryVectors.ready(), hybrid ? passages.ready() : null, sessionsPossible ? chunkVectors.ready() : null]);
|
|
297
|
+
if (sessionsPossible) sessionIds = await sessionChunkIds(sessionFilter.sql, sessionFilter.params);
|
|
298
|
+
// Anything journalled while the session ids were brought up to date is replayed in slices here, never by the
|
|
299
|
+
// synchronous topK() below (more than 2,048 changes would make it reload the whole matrix).
|
|
300
|
+
await memoryVectors.ready();
|
|
301
|
+
mark('vector_ready');
|
|
302
|
+
}
|
|
182
303
|
if(!vector)degraded.push('Local embeddings unavailable; keyword retrieval used.');
|
|
183
|
-
search(false,
|
|
304
|
+
search(false, allowedMemories);
|
|
184
305
|
mark('document_vectors');
|
|
185
|
-
if (!hybrid && (!vector || found.size < limit))
|
|
306
|
+
if (!hybrid && (!vector || found.size < limit)) applyKeyword(false, await keywordRows(false));
|
|
186
307
|
if (hybrid && vector && found.size) {
|
|
187
308
|
const parents=[...found.values()].filter(r=>r.type==='memory').map(r=>r.id).slice(0,100);
|
|
188
|
-
const ids = new Set(
|
|
309
|
+
const ids = new Set((await readRows(`SELECT p.id FROM memory_passages p INDEXED BY memory_passages_parent CROSS JOIN memories m ON m.id=p.memory_id
|
|
189
310
|
JOIN memory_metadata md ON md.memory_id=m.id WHERE p.memory_id IN (${parents.map(()=>'?').join(',')}) AND ${memoryFilter.sql} AND p.model=? AND p.content_hash=md.content_hash
|
|
190
|
-
AND NOT EXISTS(SELECT 1 FROM memory_jobs j WHERE j.entity_id=m.id AND j.kind='index' AND j.status!='complete')
|
|
191
|
-
|
|
311
|
+
AND NOT EXISTS(SELECT 1 FROM memory_jobs j WHERE j.entity_id=m.id AND j.kind='index' AND j.status!='complete')`,
|
|
312
|
+
[...parents,...memoryFilter.params, EMBEDDING_VERSION])).map(r => String(r.id)));
|
|
192
313
|
mark('passage_filter');
|
|
314
|
+
await passages.ready();
|
|
193
315
|
const parentRow = d.prepare('SELECT m.* FROM memory_passages p JOIN memories m ON m.id=p.memory_id WHERE p.id=? AND m.trashed_at IS NULL');
|
|
194
316
|
for (const [i, hit] of passages.topK(vector, k, min, ids).entries()) {
|
|
195
317
|
const row = parentRow.get(hit.id);
|
|
@@ -197,10 +319,20 @@ export async function retrieveMemory(o: RecallOptions, embed = generateEmbedding
|
|
|
197
319
|
}
|
|
198
320
|
}
|
|
199
321
|
mark('passage_vectors');
|
|
200
|
-
if (
|
|
322
|
+
if (sessionsPossible && (wantedSessions || found.size < 3)) {
|
|
323
|
+
// Scoring every session chunk (149k: ~60 ms) runs in slices that yield, while the reader searches their text.
|
|
324
|
+
const pendingSessionKeyword = keywordRows(true);
|
|
325
|
+
const sessionHits = vector && sessionIds ? await chunkVectors.topKAsync(vector, k, hybrid ? min : min * 0.5, sessionIds) : undefined;
|
|
326
|
+
const sessionAllowed = vector && !sessionHits
|
|
327
|
+
? new Set((await readRows(`SELECT m.id FROM session_chunks m WHERE ${sessionFilter.sql}`, sessionFilter.params)).map(r => String(r.id))) : undefined;
|
|
328
|
+
search(true, sessionAllowed, sessionHits);
|
|
329
|
+
applyKeyword(true, await pendingSessionKeyword);
|
|
330
|
+
}
|
|
331
|
+
mark('sessions');
|
|
201
332
|
// Preserve actual document cosine even for a keyword-only candidate. Fusion
|
|
202
333
|
// rank is not a probability and must never substitute for semantic evidence.
|
|
203
334
|
if (vector) {
|
|
335
|
+
await memoryVectors.ready();
|
|
204
336
|
const ids = new Set([...found.values()].filter(h=>h.type==='memory').map(h=>h.id));
|
|
205
337
|
for (const h of memoryVectors.topK(vector, ids.size, -Infinity, ids)) {
|
|
206
338
|
const candidate = found.get(`memory:${h.id}`);
|
|
@@ -253,6 +385,7 @@ export async function retrieveMemory(o: RecallOptions, embed = generateEmbedding
|
|
|
253
385
|
const results: RecallHit[] = [];
|
|
254
386
|
const seen = new Set<string>();
|
|
255
387
|
const byHash = new Map<string,string>();
|
|
388
|
+
const verifyLater: string[] = [];
|
|
256
389
|
for (const h of sorted) {
|
|
257
390
|
if (o.min_semantic_score !== undefined && Math.max(h.semantic_score ?? -Infinity, h.passage_score ?? -Infinity) < o.min_semantic_score) continue;
|
|
258
391
|
if(!hybrid && results.filter(r=>r.type===h.type).length >= (h.type==='memory' ? limit : Math.max(3,Math.floor(limit/2))))continue;
|
|
@@ -279,14 +412,21 @@ export async function retrieveMemory(o: RecallOptions, embed = generateEmbedding
|
|
|
279
412
|
// An edit-time judgment found this revision no longer matches its file.
|
|
280
413
|
if(verification?.stale_verdicts && judgedStale(verification.stale_verdicts,h.revision))h.flags.push('judged stale');
|
|
281
414
|
if(verification?.verified_revision!==h.revision || Date.now()-Date.parse(String(verification?.checked_at || ''))>300000 || !verification?.checked_at) {
|
|
282
|
-
|
|
283
|
-
ON CONFLICT(kind,entity_id) DO UPDATE SET status=CASE WHEN status='running' THEN status ELSE 'pending' END,attempts=0,updated_at=excluded.updated_at`)
|
|
284
|
-
.run(`verify:${h.id}`,h.id,new Date().toISOString());
|
|
415
|
+
verifyLater.push(h.id);
|
|
285
416
|
}
|
|
286
417
|
}
|
|
287
418
|
results.push(h);
|
|
288
419
|
if (hybrid && results.length >= collect) break;
|
|
289
420
|
}
|
|
421
|
+
// Queued after the loop, through the async writer: a plain run() here slept in SQLite's busy handler on the
|
|
422
|
+
// caller's event loop whenever the session-cache worker held the write lock. Best effort: a later recall queues again.
|
|
423
|
+
if (verifyLater.length) {
|
|
424
|
+
await withMemoryWrite(d, () => {
|
|
425
|
+
const queue = d.prepare(`INSERT INTO memory_jobs(id,kind,entity_id,updated_at) VALUES(?,'verify',?,?)
|
|
426
|
+
ON CONFLICT(kind,entity_id) DO UPDATE SET status=CASE WHEN status='running' THEN status ELSE 'pending' END,attempts=0,updated_at=excluded.updated_at`);
|
|
427
|
+
for (const id of verifyLater) queue.run(`verify:${id}`, id, new Date().toISOString());
|
|
428
|
+
}).catch(() => {});
|
|
429
|
+
}
|
|
290
430
|
if (collect > limit && results.length > 1) {
|
|
291
431
|
// Rank after fusion, not instead of it. A missing or partial judgment
|
|
292
432
|
// leaves the fusion order in place; only judged hits move.
|
|
@@ -347,3 +487,4 @@ export function compactRecall(result: RecallResult, query: string, budget = 1500
|
|
|
347
487
|
if (lines.length === 1 && !result.results.length) lines.push('No relevant evidence found.');
|
|
348
488
|
return estimateTokens(lines.join('\n\n')) <= budget ? lines.join('\n\n') : '';
|
|
349
489
|
}
|
|
490
|
+
export { closeRetrievalReader, retrievalReaderStats } from './retrieval-reader.js';
|
|
@@ -1,38 +1,199 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
+
import {
|
|
4
|
+
MemoryMigrationError, acquireMigrationLock, assertRoomForCopy, defaultMigrationLog, findReusableCopy, hasInterruptedCopies,
|
|
5
|
+
makeVerifiedCopy, sweepInterruptedCopies, tryMigrationLock,
|
|
6
|
+
type MigrationLock, type MigrationLog, type SpaceOptions, type SweepOptions,
|
|
7
|
+
} from './memory-migration-copy.js';
|
|
3
8
|
|
|
4
9
|
// Published migration numbers are immutable. Later additions must run even if
|
|
5
10
|
// an earlier build already marked its own schema version complete.
|
|
6
|
-
|
|
11
|
+
// `optional`: this build reads and writes correctly without it (an index, nothing it selects by name). Only such a
|
|
12
|
+
// migration is put off when its safety copy cannot be made for lack of disk space; any other stops the open.
|
|
13
|
+
const migrations: Array<{ version: number; apply: (d: DatabaseSync) => void; optional?: boolean }> = [
|
|
7
14
|
{ version: 2, apply: migrateV2 },
|
|
8
15
|
{ version: 3, apply: migrateV3 },
|
|
9
16
|
{ version: 4, apply: migrateV4 },
|
|
10
17
|
{ version: 5, apply: migrateV5 },
|
|
11
18
|
{ version: 6, apply: migrateV6 },
|
|
12
19
|
{ version: 7, apply: migrateV7 },
|
|
20
|
+
{ version: 8, apply: migrateV8, optional: true },
|
|
13
21
|
];
|
|
14
22
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
23
|
+
/** What a database of this store holds: a file without them is not a copy of it. */
|
|
24
|
+
const COPY_TABLES = ['memories', 'session_chunks'] as const;
|
|
25
|
+
|
|
26
|
+
export interface MigrateMemoryOptions extends SpaceOptions, Pick<SweepOptions, 'isAlive' | 'startedMs'> {
|
|
27
|
+
log?: MigrationLog;
|
|
28
|
+
/** How long to wait for another process that is copying or migrating (default 30 minutes). */
|
|
29
|
+
lockTimeoutMs?: number;
|
|
30
|
+
now?: () => number;
|
|
31
|
+
/** Test seam: called on the migrating thread as each step of a copied migration is reached. */
|
|
32
|
+
step?: (step: 'locked' | 'written' | 'published' | 'applied', file?: string) => void;
|
|
33
|
+
/**
|
|
34
|
+
* Put optional migrations off without looking: no lock, no copy, no log line. For the thread of a server whose
|
|
35
|
+
* migration worker already answered that they wait (sqlite.ts getDb): it must not start the copy itself.
|
|
36
|
+
*/
|
|
37
|
+
deferOptional?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* This thread never makes the copy (sqlite.ts setMemoryMigrationHost: a host migrates the store elsewhere). What is
|
|
40
|
+
* still pending and cannot be put off is refused, with the database as it was.
|
|
41
|
+
*/
|
|
42
|
+
neverCopy?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface MigrateMemoryResult {
|
|
46
|
+
/** The versions this call applied. */
|
|
47
|
+
applied: number[];
|
|
48
|
+
/** The safety copy they were applied behind; null when none was needed (an empty or in-memory store). */
|
|
49
|
+
backup: string | null;
|
|
50
|
+
/** Optional versions left for a later start, with the reason (no room for the copy, another process at it, a failure). */
|
|
51
|
+
deferred?: { versions: number[]; reason: string };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const optionalOnly = (versions: number[]) => versions.length > 0 && versions.every(version => migrations.find(migration => migration.version === version)?.optional === true);
|
|
55
|
+
|
|
56
|
+
/** The versions `d` has not applied, in order. Creates nothing: a store without the record has applied none. */
|
|
57
|
+
export function pendingMemoryMigrations(d: DatabaseSync): number[] {
|
|
58
|
+
let applied: Set<number>;
|
|
59
|
+
try { applied = new Set(d.prepare('SELECT version FROM memory_migrations').all().map(row => Number(row.version))); }
|
|
60
|
+
catch { applied = new Set(); }
|
|
61
|
+
return migrations.filter(migration => !applied.has(migration.version)).map(migration => migration.version);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** True when `d` holds memories or session evidence, or ever migrated: migrating it needs a safety copy first. */
|
|
65
|
+
export function memoryStorePopulated(d: DatabaseSync): boolean {
|
|
66
|
+
try { if (d.prepare('SELECT 1 FROM memory_migrations LIMIT 1').get()) return true; }
|
|
67
|
+
catch { /* no record yet */ }
|
|
68
|
+
try { return Boolean(d.prepare('SELECT EXISTS(SELECT 1 FROM memories) OR EXISTS(SELECT 1 FROM session_chunks) AS populated').get()?.populated); }
|
|
69
|
+
catch { return false; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const recordedCopies = (d: DatabaseSync) => d.prepare('SELECT backup FROM memory_migrations WHERE backup IS NOT NULL').all().map(row => String(row.backup));
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* What a store holds, as one value a copy can be compared by: where its change journal stands (every insert, update
|
|
76
|
+
* and delete of a memory, a session chunk or a passage moves it: the triggers of v2), how many of each there are, and
|
|
77
|
+
* which migrations it has. Null for a store without the journal (from before v2): nothing says what it holds.
|
|
78
|
+
*/
|
|
79
|
+
function storePosition(d: DatabaseSync): string | null {
|
|
80
|
+
try {
|
|
81
|
+
if (!d.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='memory_changes'").get()) return null;
|
|
82
|
+
const journal = Number(d.prepare("SELECT seq FROM sqlite_sequence WHERE name='memory_changes'").get()?.seq ?? 0);
|
|
83
|
+
const counts = d.prepare('SELECT (SELECT count(*) FROM memories) AS memories, (SELECT count(*) FROM session_chunks) AS chunks').get();
|
|
84
|
+
const versions = d.prepare('SELECT version FROM memory_migrations ORDER BY version').all().map(row => Number(row.version));
|
|
85
|
+
return JSON.stringify([journal, Number(counts?.memories), Number(counts?.chunks), versions]);
|
|
86
|
+
} catch { return null; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Additive migrations. Triggers also cover legacy/direct SQL writers.
|
|
91
|
+
*
|
|
92
|
+
* A populated store is migrated only behind a complete, checked copy of itself, and across every process on the
|
|
93
|
+
* machine one process makes that copy (memory-migration-copy.ts): this call takes the migration lock. The lock is held
|
|
94
|
+
* from the copy to the commit; a holder that ends anywhere in between gives it up with its process, and the next one
|
|
95
|
+
* removes its unfinished copy or uses its finished one. BEGIN IMMEDIATE still serializes the DDL itself, also against
|
|
96
|
+
* builds from before the lock.
|
|
97
|
+
*
|
|
98
|
+
* A process that finds the lock held makes no copy. What it does then depends on what is pending:
|
|
99
|
+
* - a migration this build needs: it waits (lockTimeoutMs, 30 minutes by default), then finds nothing left to do,
|
|
100
|
+
* or takes over when the holder ended without finishing;
|
|
101
|
+
* - only `optional` ones (indexes): it does not wait. They are put off (`deferred`), the store is used on the
|
|
102
|
+
* schema it has, and the holder applies them for everybody.
|
|
103
|
+
*
|
|
104
|
+
* Synchronous: it holds its thread for as long as the copy takes. A server calls ensureDatabase() (sqlite.ts), which
|
|
105
|
+
* runs this on the migration worker; a script or a test may call it directly.
|
|
106
|
+
*
|
|
107
|
+
* Throws MemoryMigrationError, with the database as it was, when a migration this build needs cannot be made: the
|
|
108
|
+
* copy has no room (NO_SPACE), cannot be made or checked (COPY_FAILED), the lock cannot be used (LOCK_UNAVAILABLE),
|
|
109
|
+
* or another process kept it too long (BUSY). When everything pending is optional none of these stops the open, and
|
|
110
|
+
* neither does a failure of the migration itself (it is rolled back): they are put off, with the reason.
|
|
111
|
+
*/
|
|
112
|
+
export function migrateMemory(d: DatabaseSync, dbPath: string, options: MigrateMemoryOptions = {}): MigrateMemoryResult {
|
|
113
|
+
const log = options.log ?? defaultMigrationLog;
|
|
17
114
|
d.exec('CREATE TABLE IF NOT EXISTS memory_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL, backup TEXT)');
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
if (!
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
115
|
+
const onDisk = dbPath !== ':memory:';
|
|
116
|
+
const sweep = () => sweepInterruptedCopies(dbPath, { recorded: recordedCopies(d), log, isAlive: options.isAlive, startedMs: options.startedMs });
|
|
117
|
+
if (!pendingMemoryMigrations(d).length) {
|
|
118
|
+
// Nothing to migrate: still the moment to remove what an interrupted copy left, unless somebody is migrating now.
|
|
119
|
+
if (onDisk && hasInterruptedCopies(dbPath)) {
|
|
120
|
+
let lock: MigrationLock | null = null;
|
|
121
|
+
try { lock = tryMigrationLock(dbPath); }
|
|
122
|
+
catch (error) { log(`what interrupted copies left was not looked at: ${error instanceof Error ? error.message : error}`); }
|
|
123
|
+
if (lock) {
|
|
124
|
+
try { sweep(); }
|
|
125
|
+
catch (error) { log(`what interrupted copies left was not removed: ${error instanceof Error ? error.message : error}`); }
|
|
126
|
+
finally { lock.release(); }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { applied: [], backup: null };
|
|
130
|
+
}
|
|
131
|
+
if (!onDisk || !memoryStorePopulated(d)) return { applied: applyPending(d, null), backup: null };
|
|
132
|
+
|
|
133
|
+
/** Leave what is pending (all of it optional) for a later start. */
|
|
134
|
+
const putOff = (why: string, quiet = false): MigrateMemoryResult => {
|
|
135
|
+
const versions = pendingMemoryMigrations(d);
|
|
136
|
+
if (!versions.length) return { applied: [], backup: null };
|
|
137
|
+
const reason = `${why} Migration(s) ${versions.join(', ')} only add indexes: the store is used as it is and they are tried again at the next start.`;
|
|
138
|
+
if (!quiet) log(reason);
|
|
139
|
+
return { applied: [], backup: null, deferred: { versions, reason } };
|
|
140
|
+
};
|
|
141
|
+
const optional = optionalOnly(pendingMemoryMigrations(d));
|
|
142
|
+
if (optional && options.deferOptional) return putOff('Put off earlier in this process.', true);
|
|
143
|
+
if (options.neverCopy) {
|
|
144
|
+
throw new MemoryMigrationError('MEMORY_MIGRATION_COPY_FAILED',
|
|
145
|
+
`The memory database was not opened: migration(s) ${pendingMemoryMigrations(d).join(', ')} are pending and are not made on this thread. Nothing was changed.`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
let lock: MigrationLock | null;
|
|
149
|
+
try {
|
|
150
|
+
lock = optional
|
|
151
|
+
? tryMigrationLock(dbPath)
|
|
152
|
+
: acquireMigrationLock(dbPath, { timeoutMs: options.lockTimeoutMs, log, stillNeeded: () => pendingMemoryMigrations(d).length > 0 });
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (optional && error instanceof MemoryMigrationError) return putOff(error.message);
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
// Held by another process. A needed migration was waited for and is applied now; an optional one is not waited for.
|
|
158
|
+
if (!lock) return optional ? putOff('Another SynaBun process is copying or upgrading the memory database; this one makes no copy and does not wait for it.') : { applied: [], backup: null };
|
|
159
|
+
try {
|
|
160
|
+
const pending = pendingMemoryMigrations(d);
|
|
161
|
+
if (!pending.length) return { applied: [], backup: null };
|
|
162
|
+
options.step?.('locked');
|
|
163
|
+
sweep();
|
|
164
|
+
let backup = findReusableCopy(dbPath, pending[0], { recorded: recordedCopies(d), tables: COPY_TABLES, log, now: options.now, position: storePosition, current: d });
|
|
165
|
+
if (!backup) {
|
|
166
|
+
assertRoomForCopy(dbPath, { freeBytes: options.freeBytes });
|
|
167
|
+
backup = makeVerifiedCopy(d, dbPath, pending[0], { tables: COPY_TABLES, log, now: options.now, written: file => options.step?.('written', file) });
|
|
168
|
+
}
|
|
169
|
+
options.step?.('published', backup);
|
|
170
|
+
const applied = applyPending(d, backup);
|
|
171
|
+
options.step?.('applied', backup);
|
|
172
|
+
if (applied.length) log(`applied migration(s) ${applied.join(', ')} to ${dbPath}; the copy from before is ${backup}`);
|
|
173
|
+
else log(`${backup} was not needed: another process applied the migration meanwhile. It is a complete copy and was left in place.`);
|
|
174
|
+
return { applied, backup: applied.length ? backup : null };
|
|
175
|
+
} catch (error) {
|
|
176
|
+
// The database is as it was: the copy is made beside it, and a migration that fails is rolled back.
|
|
177
|
+
if (!optionalOnly(pendingMemoryMigrations(d))) throw error;
|
|
178
|
+
return putOff(error instanceof MemoryMigrationError ? error.message : `The memory database was not upgraded: ${error instanceof Error ? error.message : error}. Nothing was changed.`);
|
|
179
|
+
} finally { lock.release(); }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Apply what is still pending, in one transaction, and record each version with `backup`. Returns what it applied. */
|
|
183
|
+
function applyPending(d: DatabaseSync, backup: string | null): number[] {
|
|
184
|
+
const applied: number[] = [];
|
|
26
185
|
d.exec('BEGIN IMMEDIATE');
|
|
27
186
|
try {
|
|
28
|
-
for (const migration of
|
|
187
|
+
for (const migration of migrations) {
|
|
29
188
|
if (d.prepare('SELECT 1 FROM memory_migrations WHERE version = ?').get(migration.version)) continue;
|
|
30
189
|
migration.apply(d);
|
|
31
190
|
d.prepare('INSERT INTO memory_migrations(version,applied_at,backup) VALUES(?,?,?)')
|
|
32
191
|
.run(migration.version, new Date().toISOString(), backup);
|
|
192
|
+
applied.push(migration.version);
|
|
33
193
|
}
|
|
34
194
|
d.exec('COMMIT');
|
|
35
195
|
} catch (error) { d.exec('ROLLBACK'); throw error; }
|
|
196
|
+
return applied;
|
|
36
197
|
}
|
|
37
198
|
|
|
38
199
|
const columns = ['content','category','subcategory','project','tags','importance','source','created_at','updated_at',
|
|
@@ -201,6 +362,27 @@ function migrateV7(d: DatabaseSync): void {
|
|
|
201
362
|
}
|
|
202
363
|
}
|
|
203
364
|
|
|
365
|
+
/**
|
|
366
|
+
* Indexes for statements that ran on the server's one thread for seconds each (2026-11-21, [loop-stall] lines of
|
|
367
|
+
* 0.6 to 2.8 s while a backup kept the disk busy). Each of them walked the memories table itself, whose rows carry
|
|
368
|
+
* the vectors, or scanned memory_metadata from end to end. With these they read a few small index pages instead:
|
|
369
|
+
*
|
|
370
|
+
* idx_mem_live every statement that asks about the live memories only: their count, their ids
|
|
371
|
+
* (JOIN memory_metadata ... WHERE m.trashed_at IS NULL) and the list stamp
|
|
372
|
+
* (COUNT, SUM(access_count), MAX(accessed_at), MAX(updated_at))
|
|
373
|
+
* idx_mem_project_live the live ids of a project (the duplicate gate before every remember)
|
|
374
|
+
* idx_memory_metadata_source_ref the memories of one run or conversation (WHERE source_ref = ?)
|
|
375
|
+
*
|
|
376
|
+
* Additive: nothing is rewritten, and a build without them still reads the same answers, slower.
|
|
377
|
+
*/
|
|
378
|
+
function migrateV8(d: DatabaseSync): void {
|
|
379
|
+
d.exec(`
|
|
380
|
+
CREATE INDEX IF NOT EXISTS idx_mem_live ON memories(trashed_at, id, access_count, accessed_at, updated_at);
|
|
381
|
+
CREATE INDEX IF NOT EXISTS idx_mem_project_live ON memories(lower(project), trashed_at, id);
|
|
382
|
+
CREATE INDEX IF NOT EXISTS idx_memory_metadata_source_ref ON memory_metadata(source_ref) WHERE source_ref IS NOT NULL;
|
|
383
|
+
`);
|
|
384
|
+
}
|
|
385
|
+
|
|
204
386
|
/**
|
|
205
387
|
* `duplicate_of` is directional: the NEWER memory points at the older one, so
|
|
206
388
|
* a pair judged from either end collides on one row. Earlier builds relied on
|
|
@@ -76,33 +76,66 @@ export function normalizeMemoryEvents(host: MemoryEvent['host'], records: any[],
|
|
|
76
76
|
|
|
77
77
|
/** Durable intake: immediately keyword searchable, semantic work queued.
|
|
78
78
|
* Stable source keys make replay and partial imports idempotent. */
|
|
79
|
-
|
|
79
|
+
/**
|
|
80
|
+
* How the session-cache worker paces its intake (lib/memory-session-capture.js, lib/session-cache-builder.js).
|
|
81
|
+
* Every other writer of the store waits for the one SQLite write lock, and the Neural Interface's synchronous writes
|
|
82
|
+
* wait for it on the event loop, polling every 1-25 ms at first and then every 50-100 ms (SQLite's busy handler).
|
|
83
|
+
* A capture that held the lock for 25 whole events (20-100+ ms each, more with long tool output) and let go of it for
|
|
84
|
+
* 8 ms kept such a writer, and the whole server, waiting for seconds. A transaction now ends after
|
|
85
|
+
* CAPTURE_TRANSACTION_MS (whole events: one long event can still exceed it), and the lock stays free for
|
|
86
|
+
* CAPTURE_PAUSE_MS, longer than the busy handler's polling interval for the first 128 ms of a wait.
|
|
87
|
+
*/
|
|
88
|
+
export const CAPTURE_TRANSACTION_MS = 20;
|
|
89
|
+
export const CAPTURE_PAUSE_MS = 25;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* `maxTransactionMs`: commit once a transaction has run this long and return; `consumed` says how many of `events`
|
|
93
|
+
* were handled (the caller passes the rest again after a pause). Without it every event is handled.
|
|
94
|
+
*/
|
|
95
|
+
export function ingestMemoryEvents(events: MemoryEvent[], { maxTransactionMs }: { maxTransactionMs?: number } = {}) {
|
|
80
96
|
const d = getDb();
|
|
97
|
+
if (!events.length) return { indexed: 0, consumed: 0 };
|
|
98
|
+
const priorSource = d.prepare('SELECT content_hash,chunk_id FROM memory_session_sources WHERE host=? AND session_id=? AND source_id=?');
|
|
99
|
+
const putChunk = d.prepare(`INSERT INTO session_chunks(id,vector,content,summary,session_id,project,cwd,start_timestamp,end_timestamp,tools_used,files_modified,indexed_at)
|
|
100
|
+
VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET vector=excluded.vector,content=excluded.content,summary=excluded.summary,
|
|
101
|
+
project=excluded.project,cwd=excluded.cwd,start_timestamp=excluded.start_timestamp,end_timestamp=excluded.end_timestamp,
|
|
102
|
+
tools_used=excluded.tools_used,files_modified=excluded.files_modified,indexed_at=excluded.indexed_at`);
|
|
103
|
+
const putSource = d.prepare(`INSERT INTO memory_session_sources VALUES(?,?,?,?,?) ON CONFLICT(host,session_id,source_id)
|
|
104
|
+
DO UPDATE SET content_hash=excluded.content_hash`);
|
|
105
|
+
const queue = d.prepare(`INSERT INTO memory_jobs(id,kind,entity_id,updated_at) VALUES(?,'session',?,?)
|
|
106
|
+
ON CONFLICT(kind,entity_id) DO UPDATE SET status='pending',attempts=0,error=NULL,updated_at=excluded.updated_at`);
|
|
107
|
+
const emptyVector = new Uint8Array(384 * 4);
|
|
81
108
|
let indexed = 0;
|
|
82
|
-
for (let offset=0; offset<events.length; offset+=50) {
|
|
109
|
+
for (let offset = 0; offset < events.length; offset += 50) {
|
|
110
|
+
// Prepare statements and hash/encode the batch before taking SQLite's single writer lock.
|
|
111
|
+
const batch = events.slice(offset, offset + 50).map(event => ({
|
|
112
|
+
event,
|
|
113
|
+
hash: createHash('sha256').update(JSON.stringify(event)).digest('hex'),
|
|
114
|
+
id: stableId(`${event.host}:${event.session_id}:${event.source_id}`),
|
|
115
|
+
tools: JSON.stringify(event.tools || []),
|
|
116
|
+
files: JSON.stringify(event.files || []),
|
|
117
|
+
}));
|
|
83
118
|
d.exec('BEGIN IMMEDIATE');
|
|
119
|
+
const began = performance.now();
|
|
120
|
+
let handled = batch.length;
|
|
84
121
|
try {
|
|
85
|
-
for (const
|
|
86
|
-
const hash =
|
|
87
|
-
const prior =
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
d.prepare(`INSERT INTO memory_session_sources VALUES(?,?,?,?,?) ON CONFLICT(host,session_id,source_id)
|
|
99
|
-
DO UPDATE SET content_hash=excluded.content_hash`).run(event.host,event.session_id,event.source_id,hash,id);
|
|
100
|
-
d.prepare(`INSERT INTO memory_jobs(id,kind,entity_id,updated_at) VALUES(?,'session',?,?)
|
|
101
|
-
ON CONFLICT(kind,entity_id) DO UPDATE SET status='pending',attempts=0,error=NULL,updated_at=excluded.updated_at`).run(`session:${id}`,id,now);
|
|
102
|
-
indexed++;
|
|
122
|
+
for (const [index, item] of batch.entries()) {
|
|
123
|
+
const { event, hash } = item;
|
|
124
|
+
const prior = priorSource.get(event.host, event.session_id, event.source_id);
|
|
125
|
+
if (prior?.content_hash !== hash) {
|
|
126
|
+
const id = prior?.chunk_id ? String(prior.chunk_id) : item.id;
|
|
127
|
+
const now = new Date().toISOString();
|
|
128
|
+
putChunk.run(id, emptyVector, event.text, `${event.role}: ${event.text.slice(0,500)}`, `${event.host}:${event.session_id}`,
|
|
129
|
+
event.project, event.cwd || null, event.timestamp, event.timestamp, item.tools, item.files, now);
|
|
130
|
+
putSource.run(event.host, event.session_id, event.source_id, hash, id);
|
|
131
|
+
queue.run(`session:${id}`, id, now);
|
|
132
|
+
indexed++;
|
|
133
|
+
}
|
|
134
|
+
if (maxTransactionMs !== undefined && index < batch.length - 1 && performance.now() - began >= maxTransactionMs) { handled = index + 1; break; }
|
|
103
135
|
}
|
|
104
136
|
d.exec('COMMIT');
|
|
105
137
|
} catch (error) {d.exec('ROLLBACK');throw error;}
|
|
138
|
+
if (handled < batch.length || (maxTransactionMs !== undefined && offset + 50 < events.length)) return { indexed, consumed: offset + handled };
|
|
106
139
|
}
|
|
107
|
-
return { indexed };
|
|
140
|
+
return { indexed, consumed: events.length };
|
|
108
141
|
}
|