@aislop-inc/opencode-mem 0.0.0-stage → 2.41.1
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/LICENSE +21 -0
- package/README.md +811 -2
- package/dist/config.d.ts +577 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +1141 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1268 -0
- package/dist/plugin.d.ts +10 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +10 -0
- package/dist/services/ai/ai-provider-factory.d.ts +8 -0
- package/dist/services/ai/ai-provider-factory.d.ts.map +1 -0
- package/dist/services/ai/ai-provider-factory.js +61 -0
- package/dist/services/ai/api-key-placeholder.d.ts +2 -0
- package/dist/services/ai/api-key-placeholder.d.ts.map +1 -0
- package/dist/services/ai/api-key-placeholder.js +14 -0
- package/dist/services/ai/internal-capture-sessions.d.ts +7 -0
- package/dist/services/ai/internal-capture-sessions.d.ts.map +1 -0
- package/dist/services/ai/internal-capture-sessions.js +31 -0
- package/dist/services/ai/opencode-diagnostics.d.ts +8 -0
- package/dist/services/ai/opencode-diagnostics.d.ts.map +1 -0
- package/dist/services/ai/opencode-diagnostics.js +36 -0
- package/dist/services/ai/opencode-host-config.d.ts +11 -0
- package/dist/services/ai/opencode-host-config.d.ts.map +1 -0
- package/dist/services/ai/opencode-host-config.js +51 -0
- package/dist/services/ai/opencode-provider-loader.d.ts +4 -0
- package/dist/services/ai/opencode-provider-loader.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider-loader.js +4 -0
- package/dist/services/ai/opencode-provider.d.ts +154 -0
- package/dist/services/ai/opencode-provider.d.ts.map +1 -0
- package/dist/services/ai/opencode-provider.js +731 -0
- package/dist/services/ai/opencode-sdk-client.d.ts +7 -0
- package/dist/services/ai/opencode-sdk-client.d.ts.map +1 -0
- package/dist/services/ai/opencode-sdk-client.js +38 -0
- package/dist/services/ai/profile-llm-client.d.ts +3 -0
- package/dist/services/ai/profile-llm-client.d.ts.map +1 -0
- package/dist/services/ai/profile-llm-client.js +29 -0
- package/dist/services/ai/provider-config.d.ts +19 -0
- package/dist/services/ai/provider-config.d.ts.map +1 -0
- package/dist/services/ai/provider-config.js +36 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts +35 -0
- package/dist/services/ai/providers/anthropic-messages.d.ts.map +1 -0
- package/dist/services/ai/providers/anthropic-messages.js +220 -0
- package/dist/services/ai/providers/api-route.d.ts +49 -0
- package/dist/services/ai/providers/api-route.d.ts.map +1 -0
- package/dist/services/ai/providers/api-route.js +57 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts +51 -0
- package/dist/services/ai/providers/atlas-cloud.d.ts.map +1 -0
- package/dist/services/ai/providers/atlas-cloud.js +59 -0
- package/dist/services/ai/providers/base-provider.d.ts +33 -0
- package/dist/services/ai/providers/base-provider.d.ts.map +1 -0
- package/dist/services/ai/providers/base-provider.js +24 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts +50 -0
- package/dist/services/ai/providers/cheaper-inference.d.ts.map +1 -0
- package/dist/services/ai/providers/cheaper-inference.js +58 -0
- package/dist/services/ai/providers/cloudgpu.d.ts +52 -0
- package/dist/services/ai/providers/cloudgpu.d.ts.map +1 -0
- package/dist/services/ai/providers/cloudgpu.js +60 -0
- package/dist/services/ai/providers/google-gemini.d.ts +16 -0
- package/dist/services/ai/providers/google-gemini.d.ts.map +1 -0
- package/dist/services/ai/providers/google-gemini.js +228 -0
- package/dist/services/ai/providers/minimax.d.ts +38 -0
- package/dist/services/ai/providers/minimax.d.ts.map +1 -0
- package/dist/services/ai/providers/minimax.js +57 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts +30 -0
- package/dist/services/ai/providers/openai-chat-completion.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-chat-completion.js +532 -0
- package/dist/services/ai/providers/openai-responses.d.ts +14 -0
- package/dist/services/ai/providers/openai-responses.d.ts.map +1 -0
- package/dist/services/ai/providers/openai-responses.js +182 -0
- package/dist/services/ai/providers/orcarouter.d.ts +52 -0
- package/dist/services/ai/providers/orcarouter.d.ts.map +1 -0
- package/dist/services/ai/providers/orcarouter.js +66 -0
- package/dist/services/ai/providers/runcrate.d.ts +49 -0
- package/dist/services/ai/providers/runcrate.d.ts.map +1 -0
- package/dist/services/ai/providers/runcrate.js +57 -0
- package/dist/services/ai/session/ai-session-manager.d.ts +25 -0
- package/dist/services/ai/session/ai-session-manager.d.ts.map +1 -0
- package/dist/services/ai/session/ai-session-manager.js +180 -0
- package/dist/services/ai/session/session-types.d.ts +43 -0
- package/dist/services/ai/session/session-types.d.ts.map +1 -0
- package/dist/services/ai/session/session-types.js +1 -0
- package/dist/services/ai/tools/tool-schema.d.ts +41 -0
- package/dist/services/ai/tools/tool-schema.d.ts.map +1 -0
- package/dist/services/ai/tools/tool-schema.js +24 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts +13 -0
- package/dist/services/ai/validators/user-profile-validator.d.ts.map +1 -0
- package/dist/services/ai/validators/user-profile-validator.js +114 -0
- package/dist/services/api-handlers.d.ts +277 -0
- package/dist/services/api-handlers.d.ts.map +1 -0
- package/dist/services/api-handlers.js +1740 -0
- package/dist/services/auth-token.d.ts +11 -0
- package/dist/services/auth-token.d.ts.map +1 -0
- package/dist/services/auth-token.js +44 -0
- package/dist/services/auto-capture-config-status.d.ts +15 -0
- package/dist/services/auto-capture-config-status.d.ts.map +1 -0
- package/dist/services/auto-capture-config-status.js +31 -0
- package/dist/services/auto-capture.d.ts +33 -0
- package/dist/services/auto-capture.d.ts.map +1 -0
- package/dist/services/auto-capture.js +906 -0
- package/dist/services/auto-update.d.ts +28 -0
- package/dist/services/auto-update.d.ts.map +1 -0
- package/dist/services/auto-update.js +197 -0
- package/dist/services/capture-evidence-events.d.ts +3 -0
- package/dist/services/capture-evidence-events.d.ts.map +1 -0
- package/dist/services/capture-evidence-events.js +15 -0
- package/dist/services/capture-evidence.d.ts +21 -0
- package/dist/services/capture-evidence.d.ts.map +1 -0
- package/dist/services/capture-evidence.js +168 -0
- package/dist/services/capture-tool-evidence.d.ts +21 -0
- package/dist/services/capture-tool-evidence.d.ts.map +1 -0
- package/dist/services/capture-tool-evidence.js +109 -0
- package/dist/services/cleanup-service.d.ts +26 -0
- package/dist/services/cleanup-service.d.ts.map +1 -0
- package/dist/services/cleanup-service.js +199 -0
- package/dist/services/client.d.ts +167 -0
- package/dist/services/client.d.ts.map +1 -0
- package/dist/services/client.js +535 -0
- package/dist/services/context.d.ts +15 -0
- package/dist/services/context.d.ts.map +1 -0
- package/dist/services/context.js +44 -0
- package/dist/services/cors.d.ts +13 -0
- package/dist/services/cors.d.ts.map +1 -0
- package/dist/services/cors.js +52 -0
- package/dist/services/deduplication-service.d.ts +29 -0
- package/dist/services/deduplication-service.d.ts.map +1 -0
- package/dist/services/deduplication-service.js +113 -0
- package/dist/services/dreaming-lock.d.ts +6 -0
- package/dist/services/dreaming-lock.d.ts.map +1 -0
- package/dist/services/dreaming-lock.js +84 -0
- package/dist/services/dreaming-service.d.ts +96 -0
- package/dist/services/dreaming-service.d.ts.map +1 -0
- package/dist/services/dreaming-service.js +626 -0
- package/dist/services/embedding.d.ts +92 -0
- package/dist/services/embedding.d.ts.map +1 -0
- package/dist/services/embedding.js +467 -0
- package/dist/services/injected-prompt-filter.d.ts +49 -0
- package/dist/services/injected-prompt-filter.d.ts.map +1 -0
- package/dist/services/injected-prompt-filter.js +79 -0
- package/dist/services/jsonc.d.ts +7 -0
- package/dist/services/jsonc.d.ts.map +1 -0
- package/dist/services/jsonc.js +110 -0
- package/dist/services/language-detector.d.ts +3 -0
- package/dist/services/language-detector.d.ts.map +1 -0
- package/dist/services/language-detector.js +33 -0
- package/dist/services/logger.d.ts +15 -0
- package/dist/services/logger.d.ts.map +1 -0
- package/dist/services/logger.js +171 -0
- package/dist/services/markdown/backend.d.ts +35 -0
- package/dist/services/markdown/backend.d.ts.map +1 -0
- package/dist/services/markdown/backend.js +111 -0
- package/dist/services/markdown/document.d.ts +44 -0
- package/dist/services/markdown/document.d.ts.map +1 -0
- package/dist/services/markdown/document.js +159 -0
- package/dist/services/markdown/reconcile.d.ts +26 -0
- package/dist/services/markdown/reconcile.d.ts.map +1 -0
- package/dist/services/markdown/reconcile.js +333 -0
- package/dist/services/markdown/vault.d.ts +32 -0
- package/dist/services/markdown/vault.d.ts.map +1 -0
- package/dist/services/markdown/vault.js +142 -0
- package/dist/services/markdown/watcher.d.ts +22 -0
- package/dist/services/markdown/watcher.d.ts.map +1 -0
- package/dist/services/markdown/watcher.js +131 -0
- package/dist/services/memory-portability-service.d.ts +38 -0
- package/dist/services/memory-portability-service.d.ts.map +1 -0
- package/dist/services/memory-portability-service.js +372 -0
- package/dist/services/memory-provenance.d.ts +16 -0
- package/dist/services/memory-provenance.d.ts.map +1 -0
- package/dist/services/memory-provenance.js +115 -0
- package/dist/services/memory-recall.d.ts +49 -0
- package/dist/services/memory-recall.d.ts.map +1 -0
- package/dist/services/memory-recall.js +196 -0
- package/dist/services/memory-scope.d.ts +17 -0
- package/dist/services/memory-scope.d.ts.map +1 -0
- package/dist/services/memory-scope.js +43 -0
- package/dist/services/migration-service.d.ts +43 -0
- package/dist/services/migration-service.d.ts.map +1 -0
- package/dist/services/migration-service.js +333 -0
- package/dist/services/onnxruntime-resolve.d.ts +25 -0
- package/dist/services/onnxruntime-resolve.d.ts.map +1 -0
- package/dist/services/onnxruntime-resolve.js +176 -0
- package/dist/services/privacy.d.ts +38 -0
- package/dist/services/privacy.d.ts.map +1 -0
- package/dist/services/privacy.js +156 -0
- package/dist/services/request-timeouts.d.ts +4 -0
- package/dist/services/request-timeouts.d.ts.map +1 -0
- package/dist/services/request-timeouts.js +5 -0
- package/dist/services/runtime-require.d.ts +18 -0
- package/dist/services/runtime-require.d.ts.map +1 -0
- package/dist/services/runtime-require.js +75 -0
- package/dist/services/secret-resolver.d.ts +2 -0
- package/dist/services/secret-resolver.d.ts.map +1 -0
- package/dist/services/secret-resolver.js +65 -0
- package/dist/services/shard-inventory-service.d.ts +70 -0
- package/dist/services/shard-inventory-service.d.ts.map +1 -0
- package/dist/services/shard-inventory-service.js +315 -0
- package/dist/services/shard-path-migration-service.d.ts +32 -0
- package/dist/services/shard-path-migration-service.d.ts.map +1 -0
- package/dist/services/shard-path-migration-service.js +386 -0
- package/dist/services/skills/skills-manager.d.ts +39 -0
- package/dist/services/skills/skills-manager.d.ts.map +1 -0
- package/dist/services/skills/skills-manager.js +231 -0
- package/dist/services/skills/types.d.ts +32 -0
- package/dist/services/skills/types.d.ts.map +1 -0
- package/dist/services/skills/types.js +5 -0
- package/dist/services/stats-service.d.ts +71 -0
- package/dist/services/stats-service.d.ts.map +1 -0
- package/dist/services/stats-service.js +288 -0
- package/dist/services/tags.d.ts +30 -0
- package/dist/services/tags.d.ts.map +1 -0
- package/dist/services/tags.js +245 -0
- package/dist/services/transformers-resolve.d.ts +17 -0
- package/dist/services/transformers-resolve.d.ts.map +1 -0
- package/dist/services/transformers-resolve.js +142 -0
- package/dist/services/turso/connection-manager.d.ts +66 -0
- package/dist/services/turso/connection-manager.d.ts.map +1 -0
- package/dist/services/turso/connection-manager.js +408 -0
- package/dist/services/turso/encryption-key.d.ts +17 -0
- package/dist/services/turso/encryption-key.d.ts.map +1 -0
- package/dist/services/turso/encryption-key.js +111 -0
- package/dist/services/turso/encryption-migrator.d.ts +6 -0
- package/dist/services/turso/encryption-migrator.d.ts.map +1 -0
- package/dist/services/turso/encryption-migrator.js +234 -0
- package/dist/services/turso/engine-migrator.d.ts +6 -0
- package/dist/services/turso/engine-migrator.d.ts.map +1 -0
- package/dist/services/turso/engine-migrator.js +318 -0
- package/dist/services/turso/error-classifiers.d.ts +4 -0
- package/dist/services/turso/error-classifiers.d.ts.map +1 -0
- package/dist/services/turso/error-classifiers.js +19 -0
- package/dist/services/turso/legacy-migrator.d.ts +2 -0
- package/dist/services/turso/legacy-migrator.d.ts.map +1 -0
- package/dist/services/turso/legacy-migrator.js +535 -0
- package/dist/services/turso/lifecycle.d.ts +11 -0
- package/dist/services/turso/lifecycle.d.ts.map +1 -0
- package/dist/services/turso/lifecycle.js +32 -0
- package/dist/services/turso/operation-lock.d.ts +26 -0
- package/dist/services/turso/operation-lock.d.ts.map +1 -0
- package/dist/services/turso/operation-lock.js +188 -0
- package/dist/services/turso/plugin-refs.d.ts +13 -0
- package/dist/services/turso/plugin-refs.d.ts.map +1 -0
- package/dist/services/turso/plugin-refs.js +43 -0
- package/dist/services/turso/ready.d.ts +3 -0
- package/dist/services/turso/ready.d.ts.map +1 -0
- package/dist/services/turso/ready.js +32 -0
- package/dist/services/turso/schema-migrations.d.ts +24 -0
- package/dist/services/turso/schema-migrations.d.ts.map +1 -0
- package/dist/services/turso/schema-migrations.js +367 -0
- package/dist/services/turso/shard-manager.d.ts +41 -0
- package/dist/services/turso/shard-manager.d.ts.map +1 -0
- package/dist/services/turso/shard-manager.js +419 -0
- package/dist/services/turso/sqlite-handle-release.d.ts +31 -0
- package/dist/services/turso/sqlite-handle-release.d.ts.map +1 -0
- package/dist/services/turso/sqlite-handle-release.js +101 -0
- package/dist/services/turso/turso-db.d.ts +61 -0
- package/dist/services/turso/turso-db.d.ts.map +1 -0
- package/dist/services/turso/turso-db.js +214 -0
- package/dist/services/turso/types.d.ts +52 -0
- package/dist/services/turso/types.d.ts.map +1 -0
- package/dist/services/turso/types.js +1 -0
- package/dist/services/turso/vector-search.d.ts +63 -0
- package/dist/services/turso/vector-search.d.ts.map +1 -0
- package/dist/services/turso/vector-search.js +510 -0
- package/dist/services/turso/vector-utils.d.ts +16 -0
- package/dist/services/turso/vector-utils.d.ts.map +1 -0
- package/dist/services/turso/vector-utils.js +98 -0
- package/dist/services/turso/wal-index-recovery.d.ts +51 -0
- package/dist/services/turso/wal-index-recovery.d.ts.map +1 -0
- package/dist/services/turso/wal-index-recovery.js +248 -0
- package/dist/services/update-on-capture.d.ts +77 -0
- package/dist/services/update-on-capture.d.ts.map +1 -0
- package/dist/services/update-on-capture.js +116 -0
- package/dist/services/user-memory-learning.d.ts +137 -0
- package/dist/services/user-memory-learning.d.ts.map +1 -0
- package/dist/services/user-memory-learning.js +787 -0
- package/dist/services/user-profile/ai-cleanup.d.ts +59 -0
- package/dist/services/user-profile/ai-cleanup.d.ts.map +1 -0
- package/dist/services/user-profile/ai-cleanup.js +488 -0
- package/dist/services/user-profile/learning-lock.d.ts +41 -0
- package/dist/services/user-profile/learning-lock.d.ts.map +1 -0
- package/dist/services/user-profile/learning-lock.js +619 -0
- package/dist/services/user-profile/profile-context.d.ts +2 -0
- package/dist/services/user-profile/profile-context.d.ts.map +1 -0
- package/dist/services/user-profile/profile-context.js +105 -0
- package/dist/services/user-profile/profile-utils.d.ts +17 -0
- package/dist/services/user-profile/profile-utils.d.ts.map +1 -0
- package/dist/services/user-profile/profile-utils.js +77 -0
- package/dist/services/user-profile/types.d.ts +93 -0
- package/dist/services/user-profile/types.d.ts.map +1 -0
- package/dist/services/user-profile/types.js +1 -0
- package/dist/services/user-profile/user-profile-manager.d.ts +106 -0
- package/dist/services/user-profile/user-profile-manager.d.ts.map +1 -0
- package/dist/services/user-profile/user-profile-manager.js +1793 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts +64 -0
- package/dist/services/user-prompt/user-prompt-manager.d.ts.map +1 -0
- package/dist/services/user-prompt/user-prompt-manager.js +428 -0
- package/dist/services/web-api-auth.d.ts +4 -0
- package/dist/services/web-api-auth.d.ts.map +1 -0
- package/dist/services/web-api-auth.js +24 -0
- package/dist/services/web-auth.d.ts +47 -0
- package/dist/services/web-auth.d.ts.map +1 -0
- package/dist/services/web-auth.js +105 -0
- package/dist/services/web-server.d.ts +58 -0
- package/dist/services/web-server.d.ts.map +1 -0
- package/dist/services/web-server.js +774 -0
- package/dist/shared/api/index.d.ts +5 -0
- package/dist/shared/api/index.d.ts.map +1 -0
- package/dist/shared/api/index.js +2 -0
- package/dist/shared/api/portability-schemas.d.ts +57 -0
- package/dist/shared/api/portability-schemas.d.ts.map +1 -0
- package/dist/shared/api/portability-schemas.js +39 -0
- package/dist/shared/api/schemas.d.ts +296 -0
- package/dist/shared/api/schemas.d.ts.map +1 -0
- package/dist/shared/api/schemas.js +134 -0
- package/dist/shared/api/types.d.ts +29 -0
- package/dist/shared/api/types.d.ts.map +1 -0
- package/dist/shared/api/types.js +1 -0
- package/dist/tui.d.ts +10 -0
- package/dist/tui.d.ts.map +1 -0
- package/dist/tui.js +17 -0
- package/dist/types/index.d.ts +19 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +1 -0
- package/dist/utils/context-limit.d.ts +11 -0
- package/dist/utils/context-limit.d.ts.map +1 -0
- package/dist/utils/context-limit.js +43 -0
- package/dist/utils/math.d.ts +8 -0
- package/dist/utils/math.d.ts.map +1 -0
- package/dist/utils/math.js +48 -0
- package/dist/utils/profile.d.ts +3 -0
- package/dist/utils/profile.d.ts.map +1 -0
- package/dist/utils/profile.js +15 -0
- package/dist/v2/adapter.d.ts +3 -0
- package/dist/v2/adapter.d.ts.map +1 -0
- package/dist/v2/adapter.js +217 -0
- package/dist/v2/legacy-client.d.ts +22 -0
- package/dist/v2/legacy-client.d.ts.map +1 -0
- package/dist/v2/legacy-client.js +410 -0
- package/dist/v2/plugin.d.ts +4 -0
- package/dist/v2/plugin.d.ts.map +1 -0
- package/dist/v2/plugin.js +34 -0
- package/dist/v2/toast-rpc.d.ts +43 -0
- package/dist/v2/toast-rpc.d.ts.map +1 -0
- package/dist/v2/toast-rpc.js +26 -0
- package/dist/web/accent-preview.html +444 -0
- package/dist/web/assets/index-mTgxOb5l.css +2 -0
- package/dist/web/assets/index-ysje17yK.js +109 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +11 -0
- package/dist/web/index.html +29 -0
- package/dist/web/opencode-mem-icon.png +0 -0
- package/package.json +122 -4
|
@@ -0,0 +1,1793 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { closeSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { tursoConnectionManager } from "../turso/connection-manager.js";
|
|
5
|
+
import { CONFIG } from "../../config.js";
|
|
6
|
+
import { safeArray } from "./profile-utils.js";
|
|
7
|
+
import { EmbeddingService } from "../embedding.js";
|
|
8
|
+
import { log } from "../logger.js";
|
|
9
|
+
import { cosineSimilarityNumbers, l2Normalize } from "../../utils/math.js";
|
|
10
|
+
import { loadOpencodeProvider } from "../ai/opencode-provider-loader.js";
|
|
11
|
+
const CENTROID_EMA_WEIGHT = 0.85;
|
|
12
|
+
const CENTROID_EMA_WEIGHT_COMPLEMENT = 0.15;
|
|
13
|
+
const THREE_WAY_CENTROID_W1 = 0.45;
|
|
14
|
+
const THREE_WAY_CENTROID_W2 = 0.45;
|
|
15
|
+
const THREE_WAY_CENTROID_W3 = 0.1;
|
|
16
|
+
const DIRECTION_VALIDATION_TOLERANCE = 0.03;
|
|
17
|
+
/** Mirrors config.outerStructuredOutputTimeoutMs; kept local so fixture mocks of config.js stay minimal. */
|
|
18
|
+
function outerStructuredTimeoutMs(configured) {
|
|
19
|
+
return (configured ?? 90_000) + 30_000;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Gamma sampler (Marsaglia-Tsang 2000).
|
|
23
|
+
* Used by sampleBeta for Thompson Sampling weak-hit upgrades.
|
|
24
|
+
*/
|
|
25
|
+
function sampleGamma(shape) {
|
|
26
|
+
if (shape < 1) {
|
|
27
|
+
const u = Math.random();
|
|
28
|
+
return sampleGamma(shape + 1) * Math.pow(u, 1 / shape);
|
|
29
|
+
}
|
|
30
|
+
const d = shape - 1 / 3;
|
|
31
|
+
const c = 1 / Math.sqrt(9 * d);
|
|
32
|
+
while (true) {
|
|
33
|
+
let x, v;
|
|
34
|
+
do {
|
|
35
|
+
x = randn();
|
|
36
|
+
v = 1 + c * x;
|
|
37
|
+
} while (v <= 0);
|
|
38
|
+
v = v * v * v;
|
|
39
|
+
const u = Math.random();
|
|
40
|
+
if (u < 1 - 0.0331 * x * x * x * x)
|
|
41
|
+
return d * v;
|
|
42
|
+
if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v)))
|
|
43
|
+
return d * v;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function randn() {
|
|
47
|
+
let u = 0, v = 0;
|
|
48
|
+
while (u === 0)
|
|
49
|
+
u = Math.random();
|
|
50
|
+
while (v === 0)
|
|
51
|
+
v = Math.random();
|
|
52
|
+
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
|
|
53
|
+
}
|
|
54
|
+
function sampleBeta(alpha, beta) {
|
|
55
|
+
const x = sampleGamma(alpha);
|
|
56
|
+
const y = sampleGamma(beta);
|
|
57
|
+
return x / (x + y);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Language-agnostic text normalization for embedding comparison.
|
|
61
|
+
* Strips punctuation and collapses whitespace — the embedding model
|
|
62
|
+
* handles semantic similarity naturally without word-level rules.
|
|
63
|
+
*/
|
|
64
|
+
function normalizeDescription(text) {
|
|
65
|
+
return text
|
|
66
|
+
.trim()
|
|
67
|
+
.replace(/[,,。!?;;::、\n\r.]/g, " ")
|
|
68
|
+
.replace(/\s+/g, " ")
|
|
69
|
+
.trim();
|
|
70
|
+
}
|
|
71
|
+
const USER_PROFILES_DB_NAME = "user-profiles.db";
|
|
72
|
+
const COLD_BUFFER_DEFAULT_KEY = "__unattributed__";
|
|
73
|
+
export class UserProfileManager {
|
|
74
|
+
db = null;
|
|
75
|
+
dbPath;
|
|
76
|
+
initPromise = null;
|
|
77
|
+
// Cold-start buffers are keyed by profileId so items observed for one user never
|
|
78
|
+
// drain into another user's merge (cross-user contamination). The unattributed bucket
|
|
79
|
+
// (COLD_BUFFER_DEFAULT_KEY) only holds items from merges that ran without a profileId.
|
|
80
|
+
coldBuffers;
|
|
81
|
+
coldBufferPath;
|
|
82
|
+
/**
|
|
83
|
+
* Set when the last disk read of cold-buffer.json failed in a way that means
|
|
84
|
+
* "unknown on-disk state" (permission error, unparseable JSON, bad schema).
|
|
85
|
+
* A merge round must then fail closed instead of treating the data as empty
|
|
86
|
+
* and overwriting it. The constructor stays fail-safe: a non-critical cache
|
|
87
|
+
* read error must never crash the plugin import path, so it is only recorded.
|
|
88
|
+
*/
|
|
89
|
+
coldBufferLoadError = null;
|
|
90
|
+
dedupCheckedCache = new Set();
|
|
91
|
+
constructor() {
|
|
92
|
+
this.dbPath = join(CONFIG.storagePath || "", USER_PROFILES_DB_NAME);
|
|
93
|
+
this.coldBufferPath = join(CONFIG.storagePath || "", "cold-buffer.json");
|
|
94
|
+
this.coldBuffers = this.loadColdBuffersFailSafe();
|
|
95
|
+
}
|
|
96
|
+
reset() {
|
|
97
|
+
this.db = null;
|
|
98
|
+
this.initPromise = null;
|
|
99
|
+
this.dbPath = join(CONFIG.storagePath || "", USER_PROFILES_DB_NAME);
|
|
100
|
+
this.coldBufferPath = join(CONFIG.storagePath || "", "cold-buffer.json");
|
|
101
|
+
// The new storage starts from its own on-disk snapshot. Keeping the old
|
|
102
|
+
// map would resurrect the previous storage's buckets on the next save.
|
|
103
|
+
this.coldBuffers = this.loadColdBuffersFailSafe();
|
|
104
|
+
this.coldBufferLoadError = null;
|
|
105
|
+
}
|
|
106
|
+
async initialize() {
|
|
107
|
+
if (this.initPromise) {
|
|
108
|
+
return this.initPromise;
|
|
109
|
+
}
|
|
110
|
+
this.initPromise = (async () => {
|
|
111
|
+
try {
|
|
112
|
+
this.dbPath = join(CONFIG.storagePath || "", USER_PROFILES_DB_NAME);
|
|
113
|
+
const newColdBufferPath = join(CONFIG.storagePath || "", "cold-buffer.json");
|
|
114
|
+
if (newColdBufferPath !== this.coldBufferPath) {
|
|
115
|
+
// storagePath changed since construction — do not keep draining or
|
|
116
|
+
// saving the previous storage's buckets.
|
|
117
|
+
this.coldBufferPath = newColdBufferPath;
|
|
118
|
+
this.coldBuffers = this.loadColdBuffersFailSafe();
|
|
119
|
+
}
|
|
120
|
+
this.db = await tursoConnectionManager.getConnection(this.dbPath);
|
|
121
|
+
await this.initDatabase();
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
this.initPromise = null;
|
|
125
|
+
this.db = null;
|
|
126
|
+
log("user-profile-manager: db init failed", { error: String(error) });
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
})();
|
|
130
|
+
return this.initPromise;
|
|
131
|
+
}
|
|
132
|
+
async ready() {
|
|
133
|
+
await this.initialize();
|
|
134
|
+
// Connection manager is authoritative: another plugin instance's dispose
|
|
135
|
+
// may close/replace the pooled handle underneath a cached TursoDb (#443).
|
|
136
|
+
if (this.db) {
|
|
137
|
+
const current = await tursoConnectionManager.getConnection(this.dbPath);
|
|
138
|
+
if (current === this.db) {
|
|
139
|
+
return this.db;
|
|
140
|
+
}
|
|
141
|
+
this.reset();
|
|
142
|
+
await this.initialize();
|
|
143
|
+
}
|
|
144
|
+
if (!this.db) {
|
|
145
|
+
throw new Error("UserProfileManager: database not initialized");
|
|
146
|
+
}
|
|
147
|
+
return this.db;
|
|
148
|
+
}
|
|
149
|
+
emptyColdBuffer() {
|
|
150
|
+
return { preferences: [], patterns: [], workflows: [] };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Fail-safe wrapper for the constructor / reset() path. A non-critical cache
|
|
154
|
+
* read error must not crash plugin import, so the error is recorded and an
|
|
155
|
+
* empty map is returned; the next merge round then fails closed.
|
|
156
|
+
*/
|
|
157
|
+
loadColdBuffersFailSafe() {
|
|
158
|
+
try {
|
|
159
|
+
return this.loadColdBuffers();
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
this.coldBufferLoadError = e instanceof Error ? e : new Error(String(e));
|
|
163
|
+
return new Map();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Reads the complete cold-buffer snapshot from disk, strictly.
|
|
168
|
+
*
|
|
169
|
+
* A missing file (ENOENT) legitimately means "empty snapshot". Any other
|
|
170
|
+
* failure (permissions, unparseable JSON, malformed schema) means the
|
|
171
|
+
* on-disk state is unknown and MUST be thrown to the caller — treating it
|
|
172
|
+
* as empty would persist an empty snapshot over data we never read.
|
|
173
|
+
*/
|
|
174
|
+
loadColdBuffers() {
|
|
175
|
+
const map = new Map();
|
|
176
|
+
let raw;
|
|
177
|
+
try {
|
|
178
|
+
raw = readFileSync(this.coldBufferPath, "utf-8");
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
if (e?.code === "ENOENT")
|
|
182
|
+
return map;
|
|
183
|
+
throw new Error(`profile cold buffer: unreadable (${this.coldBufferPath}): ${String(e)}`, {
|
|
184
|
+
cause: e,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
let data;
|
|
188
|
+
try {
|
|
189
|
+
data = JSON.parse(raw);
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
throw new Error(`profile cold buffer: corrupt JSON, refusing to overwrite (${this.coldBufferPath}): ${String(e)}`, { cause: e });
|
|
193
|
+
}
|
|
194
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) {
|
|
195
|
+
throw new Error(`profile cold buffer: unexpected schema, refusing to overwrite (${this.coldBufferPath})`);
|
|
196
|
+
}
|
|
197
|
+
// Explicit legacy detection: the flat format is exactly the three category
|
|
198
|
+
// keys (each an array, at least one present) and nothing else. Anything
|
|
199
|
+
// else containing those keys is an unknown shape, not "legacy".
|
|
200
|
+
const legacyKeys = ["preferences", "patterns", "workflows"];
|
|
201
|
+
const presentLegacyKeys = legacyKeys.filter((k) => k in data);
|
|
202
|
+
if (presentLegacyKeys.length > 0) {
|
|
203
|
+
const onlyLegacyKeys = Object.keys(data).every((k) => legacyKeys.includes(k));
|
|
204
|
+
const allArrays = legacyKeys.every((k) => !(k in data) || Array.isArray(data[k]));
|
|
205
|
+
if (onlyLegacyKeys && allArrays) {
|
|
206
|
+
// Legacy flat format ({ preferences, patterns, workflows }) is
|
|
207
|
+
// cross-user contaminated and cannot be attributed to a profile, so
|
|
208
|
+
// it is dropped rather than replayed. This is the documented
|
|
209
|
+
// migration path, not a silent data loss: the format predates
|
|
210
|
+
// per-profile buckets.
|
|
211
|
+
log("profile cold buffer: dropping legacy unattributed buffer", {
|
|
212
|
+
keys: presentLegacyKeys,
|
|
213
|
+
});
|
|
214
|
+
return map;
|
|
215
|
+
}
|
|
216
|
+
throw new Error(`profile cold buffer: legacy keys with unknown shape, refusing to overwrite (${this.coldBufferPath})`);
|
|
217
|
+
}
|
|
218
|
+
// Per-profile buckets: every key must be a bucket whose category arrays
|
|
219
|
+
// hold real items. An invalid entry means the on-disk state is unknown —
|
|
220
|
+
// coercing it to [] would persist "known empty" over data we never read.
|
|
221
|
+
let loaded = 0;
|
|
222
|
+
for (const [pid, v] of Object.entries(data)) {
|
|
223
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) {
|
|
224
|
+
throw new Error(`profile cold buffer: bucket "${pid}" is not an object, refusing to overwrite (${this.coldBufferPath})`);
|
|
225
|
+
}
|
|
226
|
+
const bucket = {
|
|
227
|
+
preferences: [],
|
|
228
|
+
patterns: [],
|
|
229
|
+
workflows: [],
|
|
230
|
+
};
|
|
231
|
+
for (const category of ["preferences", "patterns", "workflows"]) {
|
|
232
|
+
const items = v[category];
|
|
233
|
+
if (items === undefined)
|
|
234
|
+
continue;
|
|
235
|
+
if (!Array.isArray(items)) {
|
|
236
|
+
throw new Error(`profile cold buffer: bucket "${pid}.${category}" is not an array, refusing to overwrite (${this.coldBufferPath})`);
|
|
237
|
+
}
|
|
238
|
+
for (const item of items) {
|
|
239
|
+
if (item === null || typeof item !== "object" || Array.isArray(item)) {
|
|
240
|
+
throw new Error(`profile cold buffer: bucket "${pid}.${category}" holds a non-object item, refusing to overwrite (${this.coldBufferPath})`);
|
|
241
|
+
}
|
|
242
|
+
if (typeof item.description !== "string") {
|
|
243
|
+
throw new Error(`profile cold buffer: bucket "${pid}.${category}" holds an item without a string description, refusing to overwrite (${this.coldBufferPath})`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
bucket[category] = items;
|
|
247
|
+
}
|
|
248
|
+
map.set(pid, bucket);
|
|
249
|
+
loaded++;
|
|
250
|
+
}
|
|
251
|
+
if (loaded > 0) {
|
|
252
|
+
log("profile cold buffer: loaded from disk", { profiles: loaded });
|
|
253
|
+
}
|
|
254
|
+
return map;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Starts a merge round from the freshest complete on-disk snapshot.
|
|
258
|
+
*
|
|
259
|
+
* Cooperative learners take the learning lock, then re-read the snapshot at
|
|
260
|
+
* the start of every merge round, so a peer's persisted buckets are never
|
|
261
|
+
* clobbered by a stale in-memory map (mtime comparison cannot be trusted:
|
|
262
|
+
* same-mtime writes and clock rollback both hide peer updates). The loaded
|
|
263
|
+
* map is fixed for the whole round: every buffer mutation and save in this
|
|
264
|
+
* round goes through the same reference, so pending unsaved increments are
|
|
265
|
+
* never dropped by a mid-round reference swap.
|
|
266
|
+
*/
|
|
267
|
+
beginColdBufferRound() {
|
|
268
|
+
try {
|
|
269
|
+
this.coldBuffers = this.loadColdBuffers();
|
|
270
|
+
this.coldBufferLoadError = null;
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
// Fail closed: the on-disk state is unknown, so no mutation may proceed.
|
|
274
|
+
this.coldBufferLoadError = e instanceof Error ? e : new Error(String(e));
|
|
275
|
+
throw this.coldBufferLoadError;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
getColdBuffer(profileId) {
|
|
279
|
+
const key = profileId || COLD_BUFFER_DEFAULT_KEY;
|
|
280
|
+
let buf = this.coldBuffers.get(key);
|
|
281
|
+
if (!buf) {
|
|
282
|
+
buf = this.emptyColdBuffer();
|
|
283
|
+
this.coldBuffers.set(key, buf);
|
|
284
|
+
}
|
|
285
|
+
return buf;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Persists the current snapshot atomically: write a unique tmp file with
|
|
289
|
+
* O_EXCL (wx) and mode 0600, then rename over the target. Failures are
|
|
290
|
+
* thrown to the caller — swallowing them would let a round that never
|
|
291
|
+
* reached disk be reported as a successful learning merge.
|
|
292
|
+
*/
|
|
293
|
+
saveColdBuffers() {
|
|
294
|
+
const obj = {};
|
|
295
|
+
for (const [pid, v] of this.coldBuffers.entries()) {
|
|
296
|
+
if (v.preferences.length || v.patterns.length || v.workflows.length) {
|
|
297
|
+
obj[pid] = v;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const tmpPath = `${this.coldBufferPath}.${randomUUID()}.tmp`;
|
|
301
|
+
let fd;
|
|
302
|
+
try {
|
|
303
|
+
fd = openSync(tmpPath, "wx", 0o600);
|
|
304
|
+
// Byte-accurate payload: the string overload's third arg is a file
|
|
305
|
+
// position, not a string offset, and payload.length counts UTF-16
|
|
306
|
+
// units — both would corrupt multi-byte content on short writes.
|
|
307
|
+
const payload = Buffer.from(JSON.stringify(obj), "utf8");
|
|
308
|
+
let written = 0;
|
|
309
|
+
while (written < payload.length) {
|
|
310
|
+
// Buffer overload: (fd, buffer, offset, length) — append at the
|
|
311
|
+
// current position; n <= 0 means no forward progress is possible.
|
|
312
|
+
const n = writeSync(fd, payload, written, payload.length - written);
|
|
313
|
+
if (!(n > 0)) {
|
|
314
|
+
throw new Error(`profile cold buffer: write stalled after ${written} bytes`);
|
|
315
|
+
}
|
|
316
|
+
written += n;
|
|
317
|
+
}
|
|
318
|
+
closeSync(fd);
|
|
319
|
+
fd = undefined;
|
|
320
|
+
renameSync(tmpPath, this.coldBufferPath);
|
|
321
|
+
}
|
|
322
|
+
catch (e) {
|
|
323
|
+
if (fd !== undefined) {
|
|
324
|
+
try {
|
|
325
|
+
closeSync(fd);
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
// best effort — the rename below is the cleanup that matters
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
unlinkSync(tmpPath);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
// tmp file may never have been created
|
|
336
|
+
}
|
|
337
|
+
throw new Error(`profile cold buffer: save failed (${this.coldBufferPath}): ${String(e)}`, {
|
|
338
|
+
cause: e,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
async initDatabase() {
|
|
343
|
+
const db = this.db;
|
|
344
|
+
const { applySchemaMigrations, USER_PROFILES_MIGRATIONS } = await import("../turso/schema-migrations.js");
|
|
345
|
+
await applySchemaMigrations(db, USER_PROFILES_MIGRATIONS, {
|
|
346
|
+
dbPath: this.dbPath,
|
|
347
|
+
label: "user-profiles.db",
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
async getActiveProfile(userId) {
|
|
351
|
+
const db = await this.ready();
|
|
352
|
+
const row = await db.get(`
|
|
353
|
+
SELECT * FROM user_profiles
|
|
354
|
+
WHERE user_id = ? AND is_active = 1
|
|
355
|
+
LIMIT 1
|
|
356
|
+
`, [userId]);
|
|
357
|
+
if (!row)
|
|
358
|
+
return null;
|
|
359
|
+
return this.rowToProfile(row);
|
|
360
|
+
}
|
|
361
|
+
async createProfile(userId, displayName, userName, userEmail, profileData, promptsAnalyzed) {
|
|
362
|
+
const db = await this.ready();
|
|
363
|
+
const id = `profile_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
|
|
364
|
+
const now = Date.now();
|
|
365
|
+
const cleanedData = {
|
|
366
|
+
preferences: safeArray(profileData.preferences),
|
|
367
|
+
patterns: safeArray(profileData.patterns),
|
|
368
|
+
workflows: safeArray(profileData.workflows),
|
|
369
|
+
...(profileData.learning_paths ? { learning_paths: profileData.learning_paths } : {}),
|
|
370
|
+
};
|
|
371
|
+
await db.run(`
|
|
372
|
+
INSERT INTO user_profiles (
|
|
373
|
+
id, user_id, display_name, user_name, user_email,
|
|
374
|
+
profile_data, version, created_at, last_analyzed_at,
|
|
375
|
+
total_prompts_analyzed, is_active
|
|
376
|
+
)
|
|
377
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, 1)
|
|
378
|
+
`, [
|
|
379
|
+
id,
|
|
380
|
+
userId,
|
|
381
|
+
displayName,
|
|
382
|
+
userName,
|
|
383
|
+
userEmail,
|
|
384
|
+
JSON.stringify(cleanedData),
|
|
385
|
+
now,
|
|
386
|
+
now,
|
|
387
|
+
promptsAnalyzed,
|
|
388
|
+
]);
|
|
389
|
+
await this.addChangelog(id, 1, "create", "Initial profile creation", cleanedData);
|
|
390
|
+
return id;
|
|
391
|
+
}
|
|
392
|
+
async updateProfile(profileId, profileData, additionalPromptsAnalyzed, changeSummary) {
|
|
393
|
+
const db = await this.ready();
|
|
394
|
+
const now = Date.now();
|
|
395
|
+
const cleanedData = {
|
|
396
|
+
preferences: safeArray(profileData.preferences),
|
|
397
|
+
patterns: safeArray(profileData.patterns),
|
|
398
|
+
workflows: safeArray(profileData.workflows),
|
|
399
|
+
...(profileData.learning_paths ? { learning_paths: profileData.learning_paths } : {}),
|
|
400
|
+
};
|
|
401
|
+
const versionRow = await db.get(`SELECT version FROM user_profiles WHERE id = ?`, [profileId]);
|
|
402
|
+
const currentVersion = Number(versionRow?.version ?? 0);
|
|
403
|
+
const newVersion = currentVersion + 1;
|
|
404
|
+
const changes = await db.run(`
|
|
405
|
+
UPDATE user_profiles
|
|
406
|
+
SET profile_data = ?,
|
|
407
|
+
version = ?,
|
|
408
|
+
last_analyzed_at = ?,
|
|
409
|
+
total_prompts_analyzed = total_prompts_analyzed + ?
|
|
410
|
+
WHERE id = ? AND version = ?
|
|
411
|
+
`, [
|
|
412
|
+
JSON.stringify(cleanedData),
|
|
413
|
+
newVersion,
|
|
414
|
+
now,
|
|
415
|
+
additionalPromptsAnalyzed,
|
|
416
|
+
profileId,
|
|
417
|
+
currentVersion,
|
|
418
|
+
]);
|
|
419
|
+
if (changes === 0) {
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
await this.addChangelog(profileId, newVersion, "update", changeSummary, cleanedData);
|
|
423
|
+
await this.cleanupOldChangelogs(profileId);
|
|
424
|
+
return true;
|
|
425
|
+
}
|
|
426
|
+
async addChangelog(profileId, version, changeType, changeSummary, profileData) {
|
|
427
|
+
const db = await this.ready();
|
|
428
|
+
const id = `changelog_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
|
|
429
|
+
const now = Date.now();
|
|
430
|
+
await db.run(`
|
|
431
|
+
INSERT INTO user_profile_changelogs (
|
|
432
|
+
id, profile_id, version, change_type, change_summary,
|
|
433
|
+
profile_data_snapshot, created_at
|
|
434
|
+
)
|
|
435
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
436
|
+
`, [id, profileId, version, changeType, changeSummary, JSON.stringify(profileData), now]);
|
|
437
|
+
}
|
|
438
|
+
async cleanupOldChangelogs(profileId) {
|
|
439
|
+
const db = await this.ready();
|
|
440
|
+
const retentionCount = CONFIG.userProfileChangelogRetentionCount;
|
|
441
|
+
await db.run(`
|
|
442
|
+
DELETE FROM user_profile_changelogs
|
|
443
|
+
WHERE profile_id = ?
|
|
444
|
+
AND id NOT IN (
|
|
445
|
+
SELECT id FROM user_profile_changelogs
|
|
446
|
+
WHERE profile_id = ?
|
|
447
|
+
ORDER BY version DESC
|
|
448
|
+
LIMIT ?
|
|
449
|
+
)
|
|
450
|
+
`, [profileId, profileId, retentionCount]);
|
|
451
|
+
}
|
|
452
|
+
async getProfileChangelogs(profileId, limit = 10) {
|
|
453
|
+
const db = await this.ready();
|
|
454
|
+
const rows = await db.all(`
|
|
455
|
+
SELECT * FROM user_profile_changelogs
|
|
456
|
+
WHERE profile_id = ?
|
|
457
|
+
ORDER BY version DESC
|
|
458
|
+
LIMIT ?
|
|
459
|
+
`, [profileId, limit]);
|
|
460
|
+
return rows.map((row) => this.rowToChangelog(row));
|
|
461
|
+
}
|
|
462
|
+
async getChangelogById(id) {
|
|
463
|
+
const db = await this.ready();
|
|
464
|
+
const row = await db.get(`SELECT * FROM user_profile_changelogs WHERE id = ?`, [id]);
|
|
465
|
+
if (!row)
|
|
466
|
+
return undefined;
|
|
467
|
+
return this.rowToChangelog(row);
|
|
468
|
+
}
|
|
469
|
+
decayInMemory(data) {
|
|
470
|
+
const now = Date.now();
|
|
471
|
+
const prefResult = this.decayItems(data.preferences, now);
|
|
472
|
+
const patResult = this.decayItems(data.patterns, now);
|
|
473
|
+
const wfResult = this.decayItems(data.workflows, now);
|
|
474
|
+
return {
|
|
475
|
+
data: {
|
|
476
|
+
...data,
|
|
477
|
+
preferences: prefResult.items,
|
|
478
|
+
patterns: patResult.items,
|
|
479
|
+
workflows: wfResult.items,
|
|
480
|
+
},
|
|
481
|
+
hasChanges: prefResult.hasChanges || patResult.hasChanges || wfResult.hasChanges,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
decayItems(items, now) {
|
|
485
|
+
const before = items.length;
|
|
486
|
+
let hasChanges = false;
|
|
487
|
+
const filtered = items.filter((item) => {
|
|
488
|
+
this.lazyMigrateAlpha(item);
|
|
489
|
+
if (item.lastSeen === undefined)
|
|
490
|
+
item.lastSeen = now;
|
|
491
|
+
if (item.evidence === undefined)
|
|
492
|
+
item.evidence = [];
|
|
493
|
+
const oldConf = item.confidence;
|
|
494
|
+
this.syncConfidence(item);
|
|
495
|
+
if (item.confidence !== oldConf)
|
|
496
|
+
hasChanges = true;
|
|
497
|
+
const age = now - (item.lastSeen || now);
|
|
498
|
+
const ageDays = age / (24 * 60 * 60 * 1000);
|
|
499
|
+
const staleDays = CONFIG.userProfileStaleDays ?? 2;
|
|
500
|
+
const minEvidence = CONFIG.userProfileMinEvidenceForRetention ?? 3;
|
|
501
|
+
const evidenceCount = Array.isArray(item.evidence)
|
|
502
|
+
? item.evidence.length
|
|
503
|
+
: 0;
|
|
504
|
+
// Remove inactive, low-evidence items using configured retention thresholds.
|
|
505
|
+
if (ageDays > staleDays && evidenceCount < minEvidence) {
|
|
506
|
+
log("profile decay: removed stale", {
|
|
507
|
+
cat: item.category || item.description?.substring(0, 30),
|
|
508
|
+
evidenceCount,
|
|
509
|
+
minEvidence,
|
|
510
|
+
ageDays: Math.round(ageDays),
|
|
511
|
+
staleDays,
|
|
512
|
+
});
|
|
513
|
+
hasChanges = true;
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
return true;
|
|
517
|
+
});
|
|
518
|
+
return { items: filtered, hasChanges, before, removed: before - filtered.length };
|
|
519
|
+
}
|
|
520
|
+
async deleteProfile(profileId) {
|
|
521
|
+
const db = await this.ready();
|
|
522
|
+
await db.run(`DELETE FROM user_profiles WHERE id = ?`, [profileId]);
|
|
523
|
+
// Re-read the current on-disk snapshot before deleting the bucket: a
|
|
524
|
+
// stale in-memory map (peer wrote meanwhile) would resurrect the deleted
|
|
525
|
+
// profile's bucket in the very save that is supposed to remove it.
|
|
526
|
+
this.beginColdBufferRound();
|
|
527
|
+
if (this.coldBuffers.delete(profileId)) {
|
|
528
|
+
this.saveColdBuffers();
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
async getProfileById(profileId) {
|
|
532
|
+
const db = await this.ready();
|
|
533
|
+
const row = await db.get(`SELECT * FROM user_profiles WHERE id = ?`, [profileId]);
|
|
534
|
+
if (!row)
|
|
535
|
+
return null;
|
|
536
|
+
return this.rowToProfile(row);
|
|
537
|
+
}
|
|
538
|
+
async getAllActiveProfiles() {
|
|
539
|
+
const db = await this.ready();
|
|
540
|
+
const rows = await db.all(`SELECT * FROM user_profiles WHERE is_active = 1`);
|
|
541
|
+
return rows.map((row) => this.rowToProfile(row));
|
|
542
|
+
}
|
|
543
|
+
rowToProfile(row) {
|
|
544
|
+
return {
|
|
545
|
+
id: row.id,
|
|
546
|
+
userId: row.user_id,
|
|
547
|
+
displayName: row.display_name,
|
|
548
|
+
userName: row.user_name,
|
|
549
|
+
userEmail: row.user_email,
|
|
550
|
+
profileData: row.profile_data,
|
|
551
|
+
version: row.version,
|
|
552
|
+
createdAt: row.created_at,
|
|
553
|
+
lastAnalyzedAt: row.last_analyzed_at,
|
|
554
|
+
totalPromptsAnalyzed: row.total_prompts_analyzed,
|
|
555
|
+
isActive: row.is_active === 1,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
rowToChangelog(row) {
|
|
559
|
+
return {
|
|
560
|
+
id: row.id,
|
|
561
|
+
profileId: row.profile_id,
|
|
562
|
+
version: row.version,
|
|
563
|
+
changeType: row.change_type,
|
|
564
|
+
changeSummary: row.change_summary,
|
|
565
|
+
profileDataSnapshot: row.profile_data_snapshot,
|
|
566
|
+
createdAt: row.created_at,
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
async mergeProfileData(existing, updates, embedService, profileId) {
|
|
570
|
+
// Cross-process safety: cooperative learners hold the learning lock and
|
|
571
|
+
// start every round from the freshest complete on-disk snapshot. Fails
|
|
572
|
+
// closed when the on-disk state is unknown (see beginColdBufferRound).
|
|
573
|
+
// The snapshot is fixed for the whole round — getColdBuffer/saveColdBuffers
|
|
574
|
+
// never swap the map mid-round, so pending unsaved increments survive.
|
|
575
|
+
this.beginColdBufferRound();
|
|
576
|
+
const merged = {
|
|
577
|
+
preferences: this.ensureArray(existing?.preferences),
|
|
578
|
+
patterns: this.ensureArray(existing?.patterns),
|
|
579
|
+
workflows: this.ensureArray(existing?.workflows),
|
|
580
|
+
};
|
|
581
|
+
if (updates.preferences) {
|
|
582
|
+
merged.preferences = await this.mergeItems(merged.preferences, this.ensureArray(updates.preferences), "preference", embedService, profileId);
|
|
583
|
+
}
|
|
584
|
+
if (updates.patterns) {
|
|
585
|
+
merged.patterns = await this.mergeItems(merged.patterns, this.ensureArray(updates.patterns), "pattern", embedService, profileId);
|
|
586
|
+
}
|
|
587
|
+
if (updates.workflows) {
|
|
588
|
+
merged.workflows = await this.mergeItems(merged.workflows, this.ensureArray(updates.workflows), "workflow", embedService, profileId);
|
|
589
|
+
}
|
|
590
|
+
if (profileId) {
|
|
591
|
+
if (merged.preferences.length >= 2) {
|
|
592
|
+
await this.detectConflicts(merged.preferences, "preference", profileId);
|
|
593
|
+
await this.deduplicateItems(merged.preferences, "preference", profileId);
|
|
594
|
+
}
|
|
595
|
+
if (merged.patterns.length >= 2) {
|
|
596
|
+
await this.detectConflicts(merged.patterns, "pattern", profileId);
|
|
597
|
+
await this.deduplicateItems(merged.patterns, "pattern", profileId);
|
|
598
|
+
}
|
|
599
|
+
if (merged.workflows.length >= 2) {
|
|
600
|
+
await this.detectConflicts(merged.workflows, "workflow", profileId);
|
|
601
|
+
await this.deduplicateItems(merged.workflows, "workflow", profileId);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return merged;
|
|
605
|
+
}
|
|
606
|
+
async mergeItems(existing, incoming, itemType, embedService, profileId) {
|
|
607
|
+
const embed = embedService ?? EmbeddingService.getInstance();
|
|
608
|
+
const useEmbedding = embed.isWarmedUp;
|
|
609
|
+
const minDescLen = CONFIG.userProfileEmbeddingMinDescriptionLength;
|
|
610
|
+
const sameCatStrong = CONFIG.userProfileEmbeddingThresholdSameCat;
|
|
611
|
+
const sameCatWeak = CONFIG.userProfileEmbeddingThresholdSameCatWeak;
|
|
612
|
+
const crossCatStrong = CONFIG.userProfileEmbeddingThresholdCrossCat;
|
|
613
|
+
const crossCatWeak = CONFIG.userProfileEmbeddingThresholdCrossCatWeak;
|
|
614
|
+
const driftThreshold = CONFIG.userProfileCentroidDriftThreshold;
|
|
615
|
+
if (!useEmbedding) {
|
|
616
|
+
log("profile embedding skipped: model not warmed up");
|
|
617
|
+
}
|
|
618
|
+
for (const item of existing) {
|
|
619
|
+
this.lazyMigrateAlpha(item);
|
|
620
|
+
if (item.lastSeen === undefined)
|
|
621
|
+
item.lastSeen = item.lastUpdated || Date.now();
|
|
622
|
+
if (item.evidence === undefined)
|
|
623
|
+
item.evidence = [];
|
|
624
|
+
if (useEmbedding && item.description.length >= minDescLen && !item.centroid) {
|
|
625
|
+
try {
|
|
626
|
+
const emb = await embed.embed(normalizeDescription(item.description), {
|
|
627
|
+
task: "document",
|
|
628
|
+
});
|
|
629
|
+
const arr = Array.from(emb);
|
|
630
|
+
item.centroid = arr;
|
|
631
|
+
item.anchor = arr;
|
|
632
|
+
log("profile centroid migrated", { desc: item.description.substring(0, 30) });
|
|
633
|
+
}
|
|
634
|
+
catch (e) {
|
|
635
|
+
log("profile centroid migration failed", {
|
|
636
|
+
desc: item.description.substring(0, 30),
|
|
637
|
+
error: String(e),
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
let matchCount = 0;
|
|
643
|
+
let newCount = 0;
|
|
644
|
+
// Scope the cold buffer to this profile so we only drain items observed for the
|
|
645
|
+
// same user (see COLD_BUFFER_DEFAULT_KEY for the unattributed case).
|
|
646
|
+
const coldBuffer = this.getColdBuffer(profileId);
|
|
647
|
+
if (useEmbedding && coldBuffer[itemType + "s"].length > 0) {
|
|
648
|
+
const buffered = [...coldBuffer[itemType + "s"]];
|
|
649
|
+
coldBuffer[itemType + "s"] = [];
|
|
650
|
+
this.saveColdBuffers();
|
|
651
|
+
log("profile cold start: draining buffer", {
|
|
652
|
+
type: itemType,
|
|
653
|
+
profileId: profileId || COLD_BUFFER_DEFAULT_KEY,
|
|
654
|
+
bufferSize: buffered.length,
|
|
655
|
+
});
|
|
656
|
+
incoming = [...buffered, ...incoming];
|
|
657
|
+
}
|
|
658
|
+
log("profile merge start", {
|
|
659
|
+
type: itemType,
|
|
660
|
+
existingCount: existing.length,
|
|
661
|
+
incomingCount: incoming.length,
|
|
662
|
+
embeddingReady: useEmbedding,
|
|
663
|
+
});
|
|
664
|
+
for (const newItem of incoming) {
|
|
665
|
+
const exactIdx = existing.findIndex((e) => e.category === newItem.category && e.description === newItem.description);
|
|
666
|
+
if (exactIdx >= 0) {
|
|
667
|
+
const oldFreq = existing[exactIdx].frequency || 1;
|
|
668
|
+
existing[exactIdx] = this.mergeConfirmedMatch(existing[exactIdx], newItem, itemType, true);
|
|
669
|
+
matchCount++;
|
|
670
|
+
log("profile matched: exact", {
|
|
671
|
+
type: itemType,
|
|
672
|
+
idx: exactIdx,
|
|
673
|
+
cat: newItem.category,
|
|
674
|
+
frequency: `${oldFreq}→${existing[exactIdx].frequency || "?"}`,
|
|
675
|
+
});
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if (useEmbedding && newItem.description.length >= minDescLen) {
|
|
679
|
+
let top1Score = 0;
|
|
680
|
+
let top1Idx = -1;
|
|
681
|
+
let top1SameCat = false;
|
|
682
|
+
let top1Band = null;
|
|
683
|
+
let top2Score = 0;
|
|
684
|
+
let top2Idx = -1;
|
|
685
|
+
let top2SameCat = false;
|
|
686
|
+
let top2Band = null;
|
|
687
|
+
const newEmb = await embed.embed(normalizeDescription(newItem.description), {
|
|
688
|
+
task: "document",
|
|
689
|
+
});
|
|
690
|
+
for (let i = 0; i < existing.length; i++) {
|
|
691
|
+
const existingItem = existing[i];
|
|
692
|
+
if (!existingItem)
|
|
693
|
+
continue;
|
|
694
|
+
const centroid = existingItem.centroid;
|
|
695
|
+
if (!centroid)
|
|
696
|
+
continue;
|
|
697
|
+
const score = cosineSimilarityNumbers(Array.from(newEmb), centroid);
|
|
698
|
+
const sameCat = existingItem.category === newItem.category;
|
|
699
|
+
const strongThreshold = sameCat ? sameCatStrong : crossCatStrong;
|
|
700
|
+
const weakThreshold = sameCat ? sameCatWeak : crossCatWeak;
|
|
701
|
+
let band;
|
|
702
|
+
if (score >= strongThreshold) {
|
|
703
|
+
band = "strong";
|
|
704
|
+
}
|
|
705
|
+
else if (score >= weakThreshold) {
|
|
706
|
+
band = "weak";
|
|
707
|
+
}
|
|
708
|
+
else {
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (score > top1Score) {
|
|
712
|
+
top2Score = top1Score;
|
|
713
|
+
top2Idx = top1Idx;
|
|
714
|
+
top2SameCat = top1SameCat;
|
|
715
|
+
top2Band = top1Band;
|
|
716
|
+
top1Score = score;
|
|
717
|
+
top1Idx = i;
|
|
718
|
+
top1SameCat = sameCat;
|
|
719
|
+
top1Band = band;
|
|
720
|
+
}
|
|
721
|
+
else if (score > top2Score) {
|
|
722
|
+
top2Score = score;
|
|
723
|
+
top2Idx = i;
|
|
724
|
+
top2SameCat = sameCat;
|
|
725
|
+
top2Band = band;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (top1Idx >= 0 &&
|
|
729
|
+
top1Band === "strong" &&
|
|
730
|
+
top2Idx >= 0 &&
|
|
731
|
+
top2Band === "strong" &&
|
|
732
|
+
top1SameCat &&
|
|
733
|
+
top2SameCat) {
|
|
734
|
+
const item1 = existing[top1Idx];
|
|
735
|
+
const item2 = existing[top2Idx];
|
|
736
|
+
const newEmbArr = Array.from(newEmb);
|
|
737
|
+
const threeWayResult = this.combineThree(item1, item2, newItem, itemType, newEmbArr, top1Score);
|
|
738
|
+
existing[top1Idx] = threeWayResult;
|
|
739
|
+
const removeIdx = top2Idx;
|
|
740
|
+
existing.splice(removeIdx, 1);
|
|
741
|
+
matchCount += 2;
|
|
742
|
+
log("profile matched: three-way merge", {
|
|
743
|
+
type: itemType,
|
|
744
|
+
idx1: top1Idx,
|
|
745
|
+
idx2: removeIdx,
|
|
746
|
+
cat: item1.category,
|
|
747
|
+
score1: Math.round(top1Score * 100) / 100,
|
|
748
|
+
score2: Math.round(top2Score * 100) / 100,
|
|
749
|
+
freq1: item1.frequency,
|
|
750
|
+
freq2: item2.frequency,
|
|
751
|
+
combinedFreq: threeWayResult.frequency,
|
|
752
|
+
});
|
|
753
|
+
if (this.isMilestone(threeWayResult.frequency || 1) &&
|
|
754
|
+
threeWayResult.evidence?.length >= this.minEvidenceForEvolve(itemType)) {
|
|
755
|
+
await this.evolveAndUpdate(threeWayResult, itemType, profileId);
|
|
756
|
+
}
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
if (top1Idx >= 0 && top1Band === "strong") {
|
|
760
|
+
const existingItem = existing[top1Idx];
|
|
761
|
+
const oldFreq = existingItem.frequency || 1;
|
|
762
|
+
const centroid = existingItem.centroid;
|
|
763
|
+
const anchor = existingItem.anchor;
|
|
764
|
+
const newEmbArr = Array.from(newEmb);
|
|
765
|
+
const updatedCentroid = l2Normalize(centroid.map((v, i) => CENTROID_EMA_WEIGHT * v + CENTROID_EMA_WEIGHT_COMPLEMENT * (newEmbArr[i] ?? 0)));
|
|
766
|
+
let driftBelowCount = existingItem.driftBelowCount || 0;
|
|
767
|
+
if (anchor && anchor.length === updatedCentroid.length) {
|
|
768
|
+
const driftScore = cosineSimilarityNumbers(updatedCentroid, anchor);
|
|
769
|
+
if (driftScore < driftThreshold) {
|
|
770
|
+
driftBelowCount++;
|
|
771
|
+
}
|
|
772
|
+
else {
|
|
773
|
+
driftBelowCount = 0;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (driftBelowCount >= 2) {
|
|
777
|
+
const driftCentroid = Array.from(newEmb);
|
|
778
|
+
const driftAnchor = driftCentroid;
|
|
779
|
+
const frozenItem = { ...existingItem };
|
|
780
|
+
frozenItem.centroid = centroid;
|
|
781
|
+
frozenItem.driftBelowCount = driftBelowCount;
|
|
782
|
+
existing[top1Idx] = frozenItem;
|
|
783
|
+
existing.push(this.initItem(newItem, itemType, driftCentroid, driftAnchor));
|
|
784
|
+
newCount++;
|
|
785
|
+
log("profile drift fuse: frozen existing, new item created", {
|
|
786
|
+
type: itemType,
|
|
787
|
+
idx: top1Idx,
|
|
788
|
+
driftBelowCount,
|
|
789
|
+
driftScore: anchor
|
|
790
|
+
? Math.round(cosineSimilarityNumbers(updatedCentroid, anchor) * 100) / 100
|
|
791
|
+
: null,
|
|
792
|
+
});
|
|
793
|
+
continue;
|
|
794
|
+
}
|
|
795
|
+
const combined = this.mergeConfirmedMatch(existingItem, newItem, itemType, top1SameCat);
|
|
796
|
+
combined.centroid = updatedCentroid;
|
|
797
|
+
combined.anchor = anchor;
|
|
798
|
+
combined.driftBelowCount = driftBelowCount;
|
|
799
|
+
combined.weakHitCount = 0;
|
|
800
|
+
combined.lastWeakHitAt = null;
|
|
801
|
+
if (top1Score > 0.9 &&
|
|
802
|
+
top1SameCat &&
|
|
803
|
+
newItem.description.length < existingItem.description?.length) {
|
|
804
|
+
combined.description = newItem.description;
|
|
805
|
+
}
|
|
806
|
+
existing[top1Idx] = combined;
|
|
807
|
+
matchCount++;
|
|
808
|
+
if (top1SameCat) {
|
|
809
|
+
const mergeIndices = [];
|
|
810
|
+
for (let j = 0; j < existing.length; j++) {
|
|
811
|
+
if (j === top1Idx)
|
|
812
|
+
continue;
|
|
813
|
+
const other = existing[j];
|
|
814
|
+
if (!other || other.category !== existingItem.category)
|
|
815
|
+
continue;
|
|
816
|
+
const otherCentroid = other.centroid;
|
|
817
|
+
if (!otherCentroid)
|
|
818
|
+
continue;
|
|
819
|
+
const crossScore = cosineSimilarityNumbers(Array.from(newEmb), otherCentroid);
|
|
820
|
+
if (crossScore >= sameCatStrong) {
|
|
821
|
+
mergeIndices.push(j);
|
|
822
|
+
this.lazyMigrateAlpha(combined);
|
|
823
|
+
this.lazyMigrateAlpha(other);
|
|
824
|
+
combined.alpha += other.alpha || 1;
|
|
825
|
+
combined.beta = (combined.beta || 1) + (other.beta || 1);
|
|
826
|
+
const oldFreq = combined.frequency || 1;
|
|
827
|
+
combined.frequency += other.frequency || 1;
|
|
828
|
+
combined.evidence = [
|
|
829
|
+
...new Set([
|
|
830
|
+
...this.ensureArray(combined.evidence),
|
|
831
|
+
...this.ensureArray(other.evidence),
|
|
832
|
+
]),
|
|
833
|
+
].slice(0, 10);
|
|
834
|
+
const combinedCentroid = combined.centroid;
|
|
835
|
+
const w1 = oldFreq / (oldFreq + (other.frequency || 1));
|
|
836
|
+
const w2 = (other.frequency || 1) / (oldFreq + (other.frequency || 1));
|
|
837
|
+
const mergedCentroid = l2Normalize(combinedCentroid.map((v, i) => w1 * v + w2 * (otherCentroid[i] ?? 0)));
|
|
838
|
+
combined.centroid = mergedCentroid;
|
|
839
|
+
this.syncConfidence(combined);
|
|
840
|
+
matchCount++;
|
|
841
|
+
log("profile matched: cross-validation merge", {
|
|
842
|
+
type: itemType,
|
|
843
|
+
idx: top1Idx,
|
|
844
|
+
mergedIdx: j,
|
|
845
|
+
cat: other.category,
|
|
846
|
+
crossScore: Math.round(crossScore * 100) / 100,
|
|
847
|
+
mergedAlpha: Math.round(combined.alpha),
|
|
848
|
+
combinedFreq: combined.frequency,
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
for (let i = mergeIndices.length - 1; i >= 0; i--) {
|
|
853
|
+
existing.splice(mergeIndices[i], 1);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
const driftInfo = anchor && anchor.length === updatedCentroid.length
|
|
857
|
+
? {
|
|
858
|
+
driftScore: Math.round(cosineSimilarityNumbers(updatedCentroid, anchor) * 100) / 100,
|
|
859
|
+
driftBelowCount,
|
|
860
|
+
}
|
|
861
|
+
: {};
|
|
862
|
+
log("profile matched: embedding strong", {
|
|
863
|
+
type: itemType,
|
|
864
|
+
idx: top1Idx,
|
|
865
|
+
cat: existingItem.category,
|
|
866
|
+
score: Math.round(top1Score * 100) / 100,
|
|
867
|
+
sameCat: top1SameCat,
|
|
868
|
+
frequency: `${oldFreq}→${combined.frequency || "?"}`,
|
|
869
|
+
...driftInfo,
|
|
870
|
+
});
|
|
871
|
+
const newFreq = combined.frequency || 1;
|
|
872
|
+
if (this.isMilestone(newFreq) &&
|
|
873
|
+
combined.evidence?.length >= this.minEvidenceForEvolve(itemType)) {
|
|
874
|
+
await this.evolveAndUpdate(combined, itemType, profileId);
|
|
875
|
+
}
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
if (top1Idx >= 0 && top1Band === "weak") {
|
|
879
|
+
const existingItem = existing[top1Idx];
|
|
880
|
+
if (top1SameCat) {
|
|
881
|
+
const existingDriftBelow = existingItem.driftBelowCount || 0;
|
|
882
|
+
const centroid = existingItem.centroid;
|
|
883
|
+
const anchor = existingItem.anchor;
|
|
884
|
+
const newEmbArr = Array.from(newEmb);
|
|
885
|
+
const updatedCentroid = l2Normalize(centroid.map((v, i) => CENTROID_EMA_WEIGHT * v + CENTROID_EMA_WEIGHT_COMPLEMENT * (newEmbArr[i] ?? 0)));
|
|
886
|
+
let driftBelowCount = existingDriftBelow;
|
|
887
|
+
if (anchor && anchor.length === updatedCentroid.length) {
|
|
888
|
+
const driftScore = cosineSimilarityNumbers(updatedCentroid, anchor);
|
|
889
|
+
if (driftScore < driftThreshold) {
|
|
890
|
+
driftBelowCount = existingDriftBelow + 1;
|
|
891
|
+
}
|
|
892
|
+
else {
|
|
893
|
+
driftBelowCount = 0;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (driftBelowCount >= 2) {
|
|
897
|
+
const driftCentroid = Array.from(newEmb);
|
|
898
|
+
const driftAnchor = driftCentroid;
|
|
899
|
+
const frozenItem = { ...existingItem };
|
|
900
|
+
frozenItem.centroid = centroid;
|
|
901
|
+
frozenItem.driftBelowCount = driftBelowCount;
|
|
902
|
+
existing[top1Idx] = frozenItem;
|
|
903
|
+
existing.push(this.initItem(newItem, itemType, driftCentroid, driftAnchor));
|
|
904
|
+
newCount++;
|
|
905
|
+
log("profile drift fuse: forced merge path, frozen existing", {
|
|
906
|
+
type: itemType,
|
|
907
|
+
idx: top1Idx,
|
|
908
|
+
driftBelowCount,
|
|
909
|
+
driftScore: anchor
|
|
910
|
+
? Math.round(cosineSimilarityNumbers(updatedCentroid, anchor) * 100) / 100
|
|
911
|
+
: null,
|
|
912
|
+
});
|
|
913
|
+
continue;
|
|
914
|
+
}
|
|
915
|
+
const combined = { ...existingItem };
|
|
916
|
+
combined.alpha = (existingItem.alpha || 1) + top1Score * 1.0;
|
|
917
|
+
combined.frequency = (existingItem.frequency || 1) + 1;
|
|
918
|
+
combined.evidence = [
|
|
919
|
+
...new Set([
|
|
920
|
+
newItem.description || newItem.description,
|
|
921
|
+
...this.ensureArray(newItem.evidence),
|
|
922
|
+
...this.ensureArray(existingItem.evidence),
|
|
923
|
+
]),
|
|
924
|
+
].slice(0, 10);
|
|
925
|
+
combined.weakAlpha = 1;
|
|
926
|
+
combined.weakBeta = 1;
|
|
927
|
+
combined.weakHitCount = 0;
|
|
928
|
+
combined.lastWeakHitAt = null;
|
|
929
|
+
combined.lastMatchTime = Date.now();
|
|
930
|
+
combined.centroid = updatedCentroid;
|
|
931
|
+
combined.anchor = anchor;
|
|
932
|
+
combined.driftBelowCount = driftBelowCount;
|
|
933
|
+
this.syncConfidence(combined);
|
|
934
|
+
existing[top1Idx] = combined;
|
|
935
|
+
matchCount++;
|
|
936
|
+
const driftInfo = anchor && anchor.length === updatedCentroid.length
|
|
937
|
+
? {
|
|
938
|
+
driftScore: Math.round(cosineSimilarityNumbers(updatedCentroid, anchor) * 100) / 100,
|
|
939
|
+
driftBelowCount,
|
|
940
|
+
}
|
|
941
|
+
: {};
|
|
942
|
+
log("profile matched: same-cat forced merge", {
|
|
943
|
+
type: itemType,
|
|
944
|
+
idx: top1Idx,
|
|
945
|
+
cat: existingItem.category,
|
|
946
|
+
score: Math.round(top1Score * 100) / 100,
|
|
947
|
+
confidence: `${Math.round((existingItem.confidence || 0) * 100) / 100}→${Math.round(combined.confidence * 100) / 100}`,
|
|
948
|
+
frequency: `${existingItem.frequency || 1}→${combined.frequency || "?"}`,
|
|
949
|
+
...driftInfo,
|
|
950
|
+
});
|
|
951
|
+
const newFreq = combined.frequency || 1;
|
|
952
|
+
if (this.isMilestone(newFreq) &&
|
|
953
|
+
combined.evidence?.length >= this.minEvidenceForEvolve(itemType)) {
|
|
954
|
+
await this.evolveAndUpdate(combined, itemType, profileId);
|
|
955
|
+
}
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
const weakAlpha = (existingItem.weakAlpha || 1) + top1Score;
|
|
959
|
+
const weakBeta = (existingItem.weakBeta || 1) + (1 - top1Score);
|
|
960
|
+
const effectiveAlpha = weakAlpha;
|
|
961
|
+
const effectiveBeta = weakBeta;
|
|
962
|
+
const upgraded = effectiveAlpha + effectiveBeta > 7
|
|
963
|
+
? effectiveAlpha / (effectiveAlpha + effectiveBeta) >= 0.45
|
|
964
|
+
: sampleBeta(effectiveAlpha, effectiveBeta) >= 0.5;
|
|
965
|
+
if (upgraded) {
|
|
966
|
+
const oldFreq = existingItem.frequency || 1;
|
|
967
|
+
const centroid = existingItem.centroid;
|
|
968
|
+
const anchor = existingItem.anchor;
|
|
969
|
+
const newEmbArr = Array.from(newEmb);
|
|
970
|
+
const updatedCentroid = l2Normalize(centroid.map((v, i) => CENTROID_EMA_WEIGHT * v + CENTROID_EMA_WEIGHT_COMPLEMENT * (newEmbArr[i] ?? 0)));
|
|
971
|
+
const combined = this.mergeConfirmedMatch(existingItem, newItem, itemType, false);
|
|
972
|
+
combined.centroid = updatedCentroid;
|
|
973
|
+
combined.anchor = anchor;
|
|
974
|
+
combined.alpha += 0.5;
|
|
975
|
+
combined.weakAlpha = 1;
|
|
976
|
+
combined.weakBeta = 1;
|
|
977
|
+
combined.driftBelowCount = existingItem.driftBelowCount || 0;
|
|
978
|
+
this.syncConfidence(combined);
|
|
979
|
+
existing[top1Idx] = combined;
|
|
980
|
+
matchCount++;
|
|
981
|
+
log("profile matched: weak upgrade (thompson)", {
|
|
982
|
+
type: itemType,
|
|
983
|
+
idx: top1Idx,
|
|
984
|
+
cat: existingItem.category,
|
|
985
|
+
score: Math.round(top1Score * 100) / 100,
|
|
986
|
+
weakAlpha: Math.round(weakAlpha * 100) / 100,
|
|
987
|
+
weakBeta: Math.round(weakBeta * 100) / 100,
|
|
988
|
+
forced: effectiveAlpha + effectiveBeta > 7,
|
|
989
|
+
frequency: `${oldFreq}→${combined.frequency || "?"}`,
|
|
990
|
+
incomingDesc: (newItem.description || "").substring(0, 40),
|
|
991
|
+
});
|
|
992
|
+
const newFreq = combined.frequency || 1;
|
|
993
|
+
if (this.isMilestone(newFreq) &&
|
|
994
|
+
combined.evidence?.length >= this.minEvidenceForEvolve(itemType)) {
|
|
995
|
+
await this.evolveAndUpdate(combined, itemType, profileId);
|
|
996
|
+
}
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (effectiveAlpha + effectiveBeta <= 7) {
|
|
1000
|
+
existingItem.weakAlpha = effectiveAlpha;
|
|
1001
|
+
existingItem.weakBeta = effectiveBeta;
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
existingItem.weakAlpha = 1;
|
|
1005
|
+
existingItem.weakBeta = 1;
|
|
1006
|
+
}
|
|
1007
|
+
existingItem.lastSeen = Date.now();
|
|
1008
|
+
existingItem.lastWeakHitAt = Date.now();
|
|
1009
|
+
log("profile weak hit (thompson)", {
|
|
1010
|
+
type: itemType,
|
|
1011
|
+
idx: top1Idx,
|
|
1012
|
+
cat: existingItem.category,
|
|
1013
|
+
score: Math.round(top1Score * 100) / 100,
|
|
1014
|
+
weakAlpha: Math.round(weakAlpha * 100) / 100,
|
|
1015
|
+
weakBeta: Math.round(weakBeta * 100) / 100,
|
|
1016
|
+
forcedReset: effectiveAlpha + effectiveBeta > 7,
|
|
1017
|
+
incomingDesc: (newItem.description || "").substring(0, 40),
|
|
1018
|
+
});
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
if (!useEmbedding && newItem.description.length >= minDescLen) {
|
|
1023
|
+
const isExplicit = newItem.category === "explicit" ||
|
|
1024
|
+
(Array.isArray(newItem.evidence) &&
|
|
1025
|
+
newItem.evidence.includes("manual-write"));
|
|
1026
|
+
if (!isExplicit) {
|
|
1027
|
+
coldBuffer[itemType + "s"].push(newItem);
|
|
1028
|
+
if (coldBuffer[itemType + "s"].length > 50) {
|
|
1029
|
+
coldBuffer[itemType + "s"].shift();
|
|
1030
|
+
}
|
|
1031
|
+
this.saveColdBuffers();
|
|
1032
|
+
log("profile cold start: buffered", {
|
|
1033
|
+
type: itemType,
|
|
1034
|
+
profileId: profileId || COLD_BUFFER_DEFAULT_KEY,
|
|
1035
|
+
cat: newItem.category,
|
|
1036
|
+
bufferSize: coldBuffer[itemType + "s"].length,
|
|
1037
|
+
});
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
let initCentroid;
|
|
1042
|
+
let initAnchor;
|
|
1043
|
+
if (useEmbedding && newItem.description.length >= minDescLen) {
|
|
1044
|
+
try {
|
|
1045
|
+
const emb = await embed.embed(normalizeDescription(newItem.description), {
|
|
1046
|
+
task: "document",
|
|
1047
|
+
});
|
|
1048
|
+
initCentroid = Array.from(emb);
|
|
1049
|
+
initAnchor = initCentroid;
|
|
1050
|
+
}
|
|
1051
|
+
catch {
|
|
1052
|
+
// keep the item without an embedding centroid
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
existing.push(this.initItem(newItem, itemType, initCentroid, initAnchor));
|
|
1056
|
+
newCount++;
|
|
1057
|
+
log("profile no match: appended new", {
|
|
1058
|
+
type: itemType,
|
|
1059
|
+
cat: newItem.category,
|
|
1060
|
+
desc: (newItem.description || "").substring(0, 40),
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
log("profile merge done", {
|
|
1064
|
+
type: itemType,
|
|
1065
|
+
matched: matchCount,
|
|
1066
|
+
appended: newCount,
|
|
1067
|
+
existingAfter: existing.length,
|
|
1068
|
+
});
|
|
1069
|
+
return existing;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Merge a new confirmed observation into an existing profile entry.
|
|
1073
|
+
* ONLY call for confirmed matches (exact, strong sameCat/crossCat, Thompson upgrade).
|
|
1074
|
+
* Do NOT call for forced merge or cross-validation — those handle fields directly.
|
|
1075
|
+
*/
|
|
1076
|
+
mergeConfirmedMatch(existing, newItem, itemType, sameCat) {
|
|
1077
|
+
this.lazyMigrateAlpha(existing);
|
|
1078
|
+
const evidence = [
|
|
1079
|
+
...new Set([
|
|
1080
|
+
newItem.description,
|
|
1081
|
+
...this.ensureArray(newItem.evidence),
|
|
1082
|
+
...this.ensureArray(existing.evidence),
|
|
1083
|
+
]),
|
|
1084
|
+
].slice(0, 10);
|
|
1085
|
+
if (sameCat) {
|
|
1086
|
+
const result = {
|
|
1087
|
+
...existing,
|
|
1088
|
+
alpha: existing.alpha + 1,
|
|
1089
|
+
beta: existing.beta ?? 1,
|
|
1090
|
+
weakAlpha: 1,
|
|
1091
|
+
weakBeta: 1,
|
|
1092
|
+
frequency: (existing.frequency || 1) + 1,
|
|
1093
|
+
evidence,
|
|
1094
|
+
lastSeen: Date.now(),
|
|
1095
|
+
lastMatchTime: Date.now(),
|
|
1096
|
+
...(itemType === "workflow" && newItem.steps?.length ? { steps: newItem.steps } : {}),
|
|
1097
|
+
};
|
|
1098
|
+
this.syncConfidence(result);
|
|
1099
|
+
return result;
|
|
1100
|
+
}
|
|
1101
|
+
const result = {
|
|
1102
|
+
...existing,
|
|
1103
|
+
alpha: existing.alpha + 0.5,
|
|
1104
|
+
beta: existing.beta ?? 1,
|
|
1105
|
+
weakAlpha: 1,
|
|
1106
|
+
weakBeta: 1,
|
|
1107
|
+
evidence,
|
|
1108
|
+
lastSeen: Date.now(),
|
|
1109
|
+
lastMatchTime: Date.now(),
|
|
1110
|
+
...(itemType === "workflow" && newItem.steps?.length ? { steps: newItem.steps } : {}),
|
|
1111
|
+
};
|
|
1112
|
+
this.syncConfidence(result);
|
|
1113
|
+
return result;
|
|
1114
|
+
}
|
|
1115
|
+
initItem(newItem, itemType, centroid, anchor) {
|
|
1116
|
+
const hasEvidence = Array.isArray(newItem.evidence) && newItem.evidence.length > 0;
|
|
1117
|
+
const item = {
|
|
1118
|
+
...newItem,
|
|
1119
|
+
alpha: hasEvidence ? 1 : 0.3,
|
|
1120
|
+
beta: hasEvidence ? 1 : 1.5,
|
|
1121
|
+
weakAlpha: 1,
|
|
1122
|
+
weakBeta: 1,
|
|
1123
|
+
confidence: hasEvidence ? (newItem.confidence ?? 0.5) : 0.2,
|
|
1124
|
+
frequency: 1,
|
|
1125
|
+
lastSeen: Date.now(),
|
|
1126
|
+
lastMatchTime: Date.now(),
|
|
1127
|
+
firstSeen: Date.now(),
|
|
1128
|
+
evidence: newItem.evidence ?? [],
|
|
1129
|
+
weakHitCount: 0,
|
|
1130
|
+
driftBelowCount: 0,
|
|
1131
|
+
pendingValidation: true,
|
|
1132
|
+
centroid,
|
|
1133
|
+
anchor,
|
|
1134
|
+
...(itemType === "workflow" && newItem.steps?.length ? { steps: newItem.steps } : {}),
|
|
1135
|
+
};
|
|
1136
|
+
this.syncConfidence(item);
|
|
1137
|
+
return item;
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Three-way merge: item1 + item2 + newItem → single combined entry.
|
|
1141
|
+
* Called when top-1 and top-2 both strongly match the same new observation
|
|
1142
|
+
* within the same category, confirming they describe the same behavior.
|
|
1143
|
+
*/
|
|
1144
|
+
combineThree(item1, item2, newItem, itemType, newEmb, top1Score) {
|
|
1145
|
+
this.lazyMigrateAlpha(item1);
|
|
1146
|
+
this.lazyMigrateAlpha(item2);
|
|
1147
|
+
const freq = (item1.frequency || 1) + (item2.frequency || 1) + 1;
|
|
1148
|
+
const evidenceSources = [
|
|
1149
|
+
...this.ensureArray(newItem.evidence),
|
|
1150
|
+
...this.ensureArray(item1.evidence),
|
|
1151
|
+
...this.ensureArray(item2.evidence),
|
|
1152
|
+
];
|
|
1153
|
+
const evidence = [...new Set(evidenceSources)].slice(0, 10);
|
|
1154
|
+
const centroid = l2Normalize(item1.centroid.map((v, i) => THREE_WAY_CENTROID_W1 * v +
|
|
1155
|
+
THREE_WAY_CENTROID_W2 * (item2.centroid[i] ?? 0) +
|
|
1156
|
+
THREE_WAY_CENTROID_W3 * (newEmb[i] ?? 0)));
|
|
1157
|
+
const anchor = item1.anchor;
|
|
1158
|
+
const newIsShorter = newItem.description.length < (item1.description?.length || Infinity);
|
|
1159
|
+
const description = top1Score > 0.9 && newIsShorter ? newItem.description : item1.description;
|
|
1160
|
+
const steps = itemType === "workflow" && (item1.steps || item2.steps)
|
|
1161
|
+
? item1.steps?.length && item1.steps.length >= (item2.steps?.length || 0)
|
|
1162
|
+
? item1.steps
|
|
1163
|
+
: item2.steps
|
|
1164
|
+
: newItem.steps;
|
|
1165
|
+
const result = {
|
|
1166
|
+
...item1,
|
|
1167
|
+
description,
|
|
1168
|
+
frequency: freq,
|
|
1169
|
+
evidence,
|
|
1170
|
+
centroid,
|
|
1171
|
+
anchor,
|
|
1172
|
+
alpha: (item1.alpha || 1) + (item2.alpha || 1) + 1,
|
|
1173
|
+
beta: (item1.beta || 1) + (item2.beta || 1),
|
|
1174
|
+
weakAlpha: 1,
|
|
1175
|
+
weakBeta: 1,
|
|
1176
|
+
weakHitCount: 0,
|
|
1177
|
+
driftBelowCount: 0,
|
|
1178
|
+
lastSeen: Date.now(),
|
|
1179
|
+
lastMatchTime: Date.now(),
|
|
1180
|
+
...(steps ? { steps } : {}),
|
|
1181
|
+
};
|
|
1182
|
+
this.syncConfidence(result);
|
|
1183
|
+
return result;
|
|
1184
|
+
}
|
|
1185
|
+
ensureArray(val) {
|
|
1186
|
+
if (typeof val === "string") {
|
|
1187
|
+
try {
|
|
1188
|
+
const parsed = JSON.parse(val);
|
|
1189
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
1190
|
+
}
|
|
1191
|
+
catch (e) {
|
|
1192
|
+
log("ensureArray: failed to parse JSON string, returning []", {
|
|
1193
|
+
val: String(val).substring(0, 100),
|
|
1194
|
+
error: String(e),
|
|
1195
|
+
});
|
|
1196
|
+
return [];
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return Array.isArray(val) ? val : [];
|
|
1200
|
+
}
|
|
1201
|
+
isMilestone(frequency) {
|
|
1202
|
+
if (frequency <= 20)
|
|
1203
|
+
return [2, 5, 10, 20].includes(frequency);
|
|
1204
|
+
return frequency % 20 === 0;
|
|
1205
|
+
}
|
|
1206
|
+
minEvidenceForEvolve(_itemType) {
|
|
1207
|
+
return 4;
|
|
1208
|
+
}
|
|
1209
|
+
syncConfidence(item) {
|
|
1210
|
+
const alpha = item.alpha ?? 1;
|
|
1211
|
+
const beta = item.beta ?? 1;
|
|
1212
|
+
const betaMean = alpha / (alpha + beta);
|
|
1213
|
+
const decayThreshold = CONFIG.userProfileConfidenceDecayDays * 24 * 60 * 60 * 1000;
|
|
1214
|
+
const freq = item.frequency || 1;
|
|
1215
|
+
const halfLife = decayThreshold * (1 + Math.log2(1 + freq));
|
|
1216
|
+
const age = Date.now() - (item.lastSeen || Date.now());
|
|
1217
|
+
const ageMs = Math.max(0, age - decayThreshold);
|
|
1218
|
+
const timeFactor = Math.exp((-Math.LN2 * ageMs) / halfLife);
|
|
1219
|
+
const matchTime = item.lastMatchTime || item.lastSeen || Date.now();
|
|
1220
|
+
const matchAge = (Date.now() - matchTime) / (24 * 60 * 60 * 1000);
|
|
1221
|
+
const trendMultiplier = 0.8 + 0.2 * Math.exp(-matchAge / 30);
|
|
1222
|
+
item.confidence = betaMean * Math.min(timeFactor, trendMultiplier);
|
|
1223
|
+
}
|
|
1224
|
+
lazyMigrateAlpha(item) {
|
|
1225
|
+
const needsAlphaMigration = item.alpha === undefined || (item.alpha === 0.5 && item.beta === 1.5);
|
|
1226
|
+
if (needsAlphaMigration) {
|
|
1227
|
+
const conf = Math.max(0, Math.min(1, item.confidence ?? 1.0));
|
|
1228
|
+
item.alpha = conf / (1 - conf + 0.01);
|
|
1229
|
+
item.beta = 1;
|
|
1230
|
+
}
|
|
1231
|
+
item.weakAlpha = item.weakAlpha ?? 1;
|
|
1232
|
+
item.weakBeta = item.weakBeta ?? 1;
|
|
1233
|
+
item.lastMatchTime = item.lastMatchTime ?? item.lastSeen ?? Date.now();
|
|
1234
|
+
item.firstSeen = item.firstSeen ?? item.lastSeen ?? Date.now();
|
|
1235
|
+
if (item.pendingValidation === undefined) {
|
|
1236
|
+
item.pendingValidation = false;
|
|
1237
|
+
}
|
|
1238
|
+
this.syncConfidence(item);
|
|
1239
|
+
}
|
|
1240
|
+
async detectConflicts(items, itemType, _profileId) {
|
|
1241
|
+
const candidates = [];
|
|
1242
|
+
const limit = items.length;
|
|
1243
|
+
for (let i = 0; i < limit; i++) {
|
|
1244
|
+
for (let j = i + 1; j < limit; j++) {
|
|
1245
|
+
if (items[i].category !== items[j].category)
|
|
1246
|
+
continue;
|
|
1247
|
+
const c1 = items[i].centroid;
|
|
1248
|
+
const c2 = items[j].centroid;
|
|
1249
|
+
if (!c1 || !c2)
|
|
1250
|
+
continue;
|
|
1251
|
+
const cos = cosineSimilarityNumbers(c1, c2);
|
|
1252
|
+
if (cos >= 0.65 && cos < 0.9) {
|
|
1253
|
+
candidates.push({ a: items[i], b: items[j], cos });
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
if (candidates.length === 0)
|
|
1258
|
+
return;
|
|
1259
|
+
const maxChecks = 3;
|
|
1260
|
+
candidates.sort((x, y) => y.cos - x.cos);
|
|
1261
|
+
let checked = 0;
|
|
1262
|
+
const removeIndices = [];
|
|
1263
|
+
for (const { a, b, cos } of candidates) {
|
|
1264
|
+
if (checked >= maxChecks)
|
|
1265
|
+
break;
|
|
1266
|
+
if (removeIndices.includes(items.indexOf(a)) || removeIndices.includes(items.indexOf(b)))
|
|
1267
|
+
continue;
|
|
1268
|
+
const conflict = await this.checkConflict(a.description, b.description);
|
|
1269
|
+
if (conflict) {
|
|
1270
|
+
checked++;
|
|
1271
|
+
const keeper = (a.frequency || 0) >= (b.frequency || 0) ? a : b;
|
|
1272
|
+
const removed = keeper === a ? b : a;
|
|
1273
|
+
this.lazyMigrateAlpha(keeper);
|
|
1274
|
+
this.lazyMigrateAlpha(removed);
|
|
1275
|
+
const oldAlpha = keeper.alpha || 1;
|
|
1276
|
+
keeper.alpha *= 0.75;
|
|
1277
|
+
keeper.beta = (keeper.beta || 1) + 0.25 * oldAlpha;
|
|
1278
|
+
keeper.alpha += removed.alpha || 0;
|
|
1279
|
+
keeper.frequency = (keeper.frequency || 0) + (removed.frequency || 0);
|
|
1280
|
+
keeper.evidence = [
|
|
1281
|
+
...new Set([...this.ensureArray(keeper.evidence), ...this.ensureArray(removed.evidence)]),
|
|
1282
|
+
].slice(0, 10);
|
|
1283
|
+
if (itemType === "workflow") {
|
|
1284
|
+
keeper.steps =
|
|
1285
|
+
keeper.steps?.length >= (removed.steps?.length || 0) ? keeper.steps : removed.steps;
|
|
1286
|
+
}
|
|
1287
|
+
const removedIdx = items.indexOf(removed);
|
|
1288
|
+
if (removedIdx >= 0)
|
|
1289
|
+
removeIndices.push(removedIdx);
|
|
1290
|
+
this.syncConfidence(keeper);
|
|
1291
|
+
log("profile conflict detected: resolved", {
|
|
1292
|
+
type: itemType,
|
|
1293
|
+
keeper: (keeper.description || "").substring(0, 40),
|
|
1294
|
+
removed: (removed.description || "").substring(0, 40),
|
|
1295
|
+
cos: Math.round(cos * 100) / 100,
|
|
1296
|
+
alphaDrop: `${Math.round(oldAlpha)}→${Math.round(keeper.alpha)}`,
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
for (let i = removeIndices.length - 1; i >= 0; i--) {
|
|
1301
|
+
items.splice(removeIndices[i], 1);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async checkSemanticDuplicate(descA, descB) {
|
|
1305
|
+
const prompt = `Do these two descriptions refer to the same user behavior, preference, or pattern? Answer only whether they are semantically equivalent (same meaning, different wording).
|
|
1306
|
+
|
|
1307
|
+
A: "${descA}"
|
|
1308
|
+
B: "${descB}"
|
|
1309
|
+
|
|
1310
|
+
Answer JSON only: { "duplicate": true|false, "reason": "one sentence explanation" }`;
|
|
1311
|
+
if (CONFIG.opencodeProvider && CONFIG.opencodeModel) {
|
|
1312
|
+
try {
|
|
1313
|
+
const { z } = await import("zod");
|
|
1314
|
+
const { generateStructuredOutput } = await loadOpencodeProvider();
|
|
1315
|
+
const { getOpenCodeClient } = await import("../ai/profile-llm-client.js");
|
|
1316
|
+
let v2Client;
|
|
1317
|
+
try {
|
|
1318
|
+
v2Client = await getOpenCodeClient();
|
|
1319
|
+
}
|
|
1320
|
+
catch (e) {
|
|
1321
|
+
log("profile dedup check: native provider not connected", { error: String(e) });
|
|
1322
|
+
}
|
|
1323
|
+
if (v2Client) {
|
|
1324
|
+
const result = await Promise.race([
|
|
1325
|
+
generateStructuredOutput({
|
|
1326
|
+
client: v2Client,
|
|
1327
|
+
providerID: CONFIG.opencodeProvider,
|
|
1328
|
+
modelID: CONFIG.opencodeModel,
|
|
1329
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
1330
|
+
systemPrompt: "You are a semantic duplicate detector. Output valid JSON.",
|
|
1331
|
+
userPrompt: prompt,
|
|
1332
|
+
schema: z.object({ duplicate: z.boolean(), reason: z.string() }),
|
|
1333
|
+
}),
|
|
1334
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("dedup check timeout")), 30000)),
|
|
1335
|
+
]);
|
|
1336
|
+
return result.duplicate || false;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
catch (e) {
|
|
1340
|
+
log("profile dedup check: native provider failed", { error: String(e) });
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
if (CONFIG.memoryModel && CONFIG.memoryApiUrl) {
|
|
1344
|
+
try {
|
|
1345
|
+
const response = await fetch(`${CONFIG.memoryApiUrl}/chat/completions`, {
|
|
1346
|
+
method: "POST",
|
|
1347
|
+
headers: {
|
|
1348
|
+
"Content-Type": "application/json",
|
|
1349
|
+
Authorization: `Bearer ${CONFIG.memoryApiKey || ""}`,
|
|
1350
|
+
},
|
|
1351
|
+
body: JSON.stringify({
|
|
1352
|
+
model: CONFIG.memoryModel,
|
|
1353
|
+
messages: [
|
|
1354
|
+
{
|
|
1355
|
+
role: "system",
|
|
1356
|
+
content: "You are a semantic duplicate detector. Output valid JSON.",
|
|
1357
|
+
},
|
|
1358
|
+
{ role: "user", content: prompt },
|
|
1359
|
+
],
|
|
1360
|
+
temperature: 0,
|
|
1361
|
+
response_format: { type: "json_object" },
|
|
1362
|
+
}),
|
|
1363
|
+
signal: AbortSignal.timeout(30000),
|
|
1364
|
+
});
|
|
1365
|
+
if (!response.ok)
|
|
1366
|
+
return false;
|
|
1367
|
+
const data = await response.json();
|
|
1368
|
+
const content = data.choices?.[0]?.message?.content;
|
|
1369
|
+
if (!content)
|
|
1370
|
+
return false;
|
|
1371
|
+
const parsed = JSON.parse(content);
|
|
1372
|
+
return parsed.duplicate || false;
|
|
1373
|
+
}
|
|
1374
|
+
catch (e) {
|
|
1375
|
+
log("profile dedup check: external API failed", { error: String(e) });
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
return false;
|
|
1379
|
+
}
|
|
1380
|
+
async deduplicateItems(items, itemType, profileId) {
|
|
1381
|
+
if (!profileId || items.length < 2)
|
|
1382
|
+
return;
|
|
1383
|
+
const checkedPairs = this.dedupCheckedCache;
|
|
1384
|
+
const maxLLMCalls = 5;
|
|
1385
|
+
let llmCalls = 0;
|
|
1386
|
+
let skippedCached = 0;
|
|
1387
|
+
const byCategory = new Map();
|
|
1388
|
+
for (const item of items) {
|
|
1389
|
+
const cat = item.category || "_uncategorized";
|
|
1390
|
+
if (!byCategory.has(cat))
|
|
1391
|
+
byCategory.set(cat, []);
|
|
1392
|
+
byCategory.get(cat).push(item);
|
|
1393
|
+
}
|
|
1394
|
+
for (const [, group] of byCategory) {
|
|
1395
|
+
if (group.length < 2)
|
|
1396
|
+
continue;
|
|
1397
|
+
const candidates = [];
|
|
1398
|
+
for (let i = 0; i < group.length; i++) {
|
|
1399
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
1400
|
+
const c1 = group[i].centroid;
|
|
1401
|
+
const c2 = group[j].centroid;
|
|
1402
|
+
if (!c1 || !c2)
|
|
1403
|
+
continue;
|
|
1404
|
+
const cos = cosineSimilarityNumbers(c1, c2);
|
|
1405
|
+
if (cos >= 0.5) {
|
|
1406
|
+
candidates.push({ a: group[i], b: group[j], cos });
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
if (candidates.length === 0)
|
|
1411
|
+
continue;
|
|
1412
|
+
candidates.sort((x, y) => y.cos - x.cos);
|
|
1413
|
+
const removeIndices = [];
|
|
1414
|
+
let candidateIdx = 0;
|
|
1415
|
+
for (const { a, b, cos } of candidates) {
|
|
1416
|
+
candidateIdx++;
|
|
1417
|
+
if (llmCalls >= maxLLMCalls) {
|
|
1418
|
+
log("profile dedup: LLM call limit reached", {
|
|
1419
|
+
itemType,
|
|
1420
|
+
skipped: candidates.length - candidateIdx + 1,
|
|
1421
|
+
});
|
|
1422
|
+
break;
|
|
1423
|
+
}
|
|
1424
|
+
if (removeIndices.includes(items.indexOf(a)) || removeIndices.includes(items.indexOf(b)))
|
|
1425
|
+
continue;
|
|
1426
|
+
const pairKey = [a.description, b.description].sort().join("||").substring(0, 100);
|
|
1427
|
+
if (checkedPairs.has(pairKey)) {
|
|
1428
|
+
skippedCached++;
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
llmCalls++;
|
|
1432
|
+
const isDuplicate = await this.checkSemanticDuplicate(a.description, b.description);
|
|
1433
|
+
if (isDuplicate) {
|
|
1434
|
+
const keeper = (a.frequency || 0) >= (b.frequency || 0) ? a : b;
|
|
1435
|
+
const removed = keeper === a ? b : a;
|
|
1436
|
+
keeper.frequency = (keeper.frequency || 0) + (removed.frequency || 0);
|
|
1437
|
+
this.lazyMigrateAlpha(keeper);
|
|
1438
|
+
this.lazyMigrateAlpha(removed);
|
|
1439
|
+
keeper.alpha += removed.alpha || 0;
|
|
1440
|
+
keeper.beta = (keeper.beta || 1) + (removed.beta || 1);
|
|
1441
|
+
keeper.weakAlpha = (keeper.weakAlpha || 1) + ((removed.weakAlpha || 1) - 1);
|
|
1442
|
+
keeper.weakBeta = (keeper.weakBeta || 1) + ((removed.weakBeta || 1) - 1);
|
|
1443
|
+
keeper.lastSeen = Math.max(keeper.lastSeen || 0, removed.lastSeen || 0);
|
|
1444
|
+
keeper.lastMatchTime = Math.max(keeper.lastMatchTime || 0, removed.lastMatchTime || 0);
|
|
1445
|
+
this.syncConfidence(keeper);
|
|
1446
|
+
keeper.evidence = [
|
|
1447
|
+
...new Set([
|
|
1448
|
+
...this.ensureArray(keeper.evidence),
|
|
1449
|
+
...this.ensureArray(removed.evidence),
|
|
1450
|
+
]),
|
|
1451
|
+
].slice(0, 10);
|
|
1452
|
+
keeper.pendingValidation = !!keeper.pendingValidation && !!removed.pendingValidation;
|
|
1453
|
+
if (itemType === "workflow") {
|
|
1454
|
+
keeper.steps =
|
|
1455
|
+
keeper.steps?.length >= (removed.steps?.length || 0) ? keeper.steps : removed.steps;
|
|
1456
|
+
}
|
|
1457
|
+
const removedIdx = items.indexOf(removed);
|
|
1458
|
+
if (removedIdx >= 0)
|
|
1459
|
+
removeIndices.push(removedIdx);
|
|
1460
|
+
checkedPairs.delete(pairKey);
|
|
1461
|
+
log("profile dedup: merged duplicate", {
|
|
1462
|
+
type: itemType,
|
|
1463
|
+
keeper: (keeper.description || "").substring(0, 40),
|
|
1464
|
+
removed: (removed.description || "").substring(0, 40),
|
|
1465
|
+
cos: Math.round(cos * 100) / 100,
|
|
1466
|
+
mergedFreq: keeper.frequency,
|
|
1467
|
+
});
|
|
1468
|
+
}
|
|
1469
|
+
else {
|
|
1470
|
+
checkedPairs.add(pairKey);
|
|
1471
|
+
log("profile dedup: no duplicate confirmed", {
|
|
1472
|
+
type: itemType,
|
|
1473
|
+
cos: Math.round(cos * 100) / 100,
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
for (let i = removeIndices.length - 1; i >= 0; i--) {
|
|
1478
|
+
items.splice(removeIndices[i], 1);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
log("profile dedup complete", {
|
|
1482
|
+
type: itemType,
|
|
1483
|
+
llmCalls,
|
|
1484
|
+
skippedCached,
|
|
1485
|
+
itemsAfter: items.length,
|
|
1486
|
+
});
|
|
1487
|
+
if (this.dedupCheckedCache.size > 1000) {
|
|
1488
|
+
const entries = [...this.dedupCheckedCache];
|
|
1489
|
+
this.dedupCheckedCache = new Set(entries.slice(500));
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
async checkConflict(descA, descB) {
|
|
1493
|
+
const prompt = `Are these two user preferences contradictory (opposing, incompatible)?
|
|
1494
|
+
|
|
1495
|
+
A: "${descA}"
|
|
1496
|
+
B: "${descB}"
|
|
1497
|
+
|
|
1498
|
+
Answer JSON only: { "conflict": true|false, "reason": "one sentence explanation" }`;
|
|
1499
|
+
if (CONFIG.opencodeProvider && CONFIG.opencodeModel) {
|
|
1500
|
+
try {
|
|
1501
|
+
const { z } = await import("zod");
|
|
1502
|
+
const { generateStructuredOutput } = await loadOpencodeProvider();
|
|
1503
|
+
const { getOpenCodeClient } = await import("../ai/profile-llm-client.js");
|
|
1504
|
+
let v2Client;
|
|
1505
|
+
try {
|
|
1506
|
+
v2Client = await getOpenCodeClient();
|
|
1507
|
+
}
|
|
1508
|
+
catch (e) {
|
|
1509
|
+
log("profile conflict check: native provider not connected", { error: String(e) });
|
|
1510
|
+
}
|
|
1511
|
+
if (v2Client) {
|
|
1512
|
+
const result = await Promise.race([
|
|
1513
|
+
generateStructuredOutput({
|
|
1514
|
+
client: v2Client,
|
|
1515
|
+
providerID: CONFIG.opencodeProvider,
|
|
1516
|
+
modelID: CONFIG.opencodeModel,
|
|
1517
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
1518
|
+
systemPrompt: "You are a preference contradiction detector. Output valid JSON.",
|
|
1519
|
+
userPrompt: prompt,
|
|
1520
|
+
schema: z.object({ conflict: z.boolean(), reason: z.string() }),
|
|
1521
|
+
}),
|
|
1522
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("conflict check timeout")), 30000)),
|
|
1523
|
+
]);
|
|
1524
|
+
return result.conflict || false;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
catch (e) {
|
|
1528
|
+
log("profile conflict check: native provider failed", { error: String(e) });
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
if (CONFIG.memoryModel && CONFIG.memoryApiUrl) {
|
|
1532
|
+
try {
|
|
1533
|
+
const response = await fetch(`${CONFIG.memoryApiUrl}/chat/completions`, {
|
|
1534
|
+
method: "POST",
|
|
1535
|
+
headers: {
|
|
1536
|
+
"Content-Type": "application/json",
|
|
1537
|
+
Authorization: `Bearer ${CONFIG.memoryApiKey || ""}`,
|
|
1538
|
+
},
|
|
1539
|
+
body: JSON.stringify({
|
|
1540
|
+
model: CONFIG.memoryModel,
|
|
1541
|
+
messages: [
|
|
1542
|
+
{
|
|
1543
|
+
role: "system",
|
|
1544
|
+
content: "You are a preference contradiction detector. Output valid JSON.",
|
|
1545
|
+
},
|
|
1546
|
+
{ role: "user", content: prompt },
|
|
1547
|
+
],
|
|
1548
|
+
temperature: 0,
|
|
1549
|
+
response_format: { type: "json_object" },
|
|
1550
|
+
}),
|
|
1551
|
+
signal: AbortSignal.timeout(30000),
|
|
1552
|
+
});
|
|
1553
|
+
if (!response.ok)
|
|
1554
|
+
return false;
|
|
1555
|
+
const data = await response.json();
|
|
1556
|
+
const content = data.choices?.[0]?.message?.content;
|
|
1557
|
+
if (!content)
|
|
1558
|
+
return false;
|
|
1559
|
+
const parsed = (() => {
|
|
1560
|
+
try {
|
|
1561
|
+
return JSON.parse(content);
|
|
1562
|
+
}
|
|
1563
|
+
catch {
|
|
1564
|
+
const repaired = content
|
|
1565
|
+
.replace(/([\u4e00-\u9fff\u3000-\u303f\uff00-\uffef])"([\u4e00-\u9fff\u3000-\u303f\uff00-\uffef])/g, '$1\\"$2')
|
|
1566
|
+
.replace(/([\u4e00-\u9fff\u3000-\u303f\uff00-\uffef])"(?=\s*[,}\]])/g, '$1\\"');
|
|
1567
|
+
return JSON.parse(repaired);
|
|
1568
|
+
}
|
|
1569
|
+
})();
|
|
1570
|
+
return parsed.conflict || false;
|
|
1571
|
+
}
|
|
1572
|
+
catch (e) {
|
|
1573
|
+
log("profile conflict check: external API failed", { error: String(e) });
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
return false;
|
|
1577
|
+
}
|
|
1578
|
+
async evolveDescription(item, itemType, profileId) {
|
|
1579
|
+
if (!profileId) {
|
|
1580
|
+
log("profile description evolution blocked: no profileId");
|
|
1581
|
+
return null;
|
|
1582
|
+
}
|
|
1583
|
+
const evidence = item.evidence;
|
|
1584
|
+
if (!Array.isArray(evidence) || evidence.length < this.minEvidenceForEvolve(itemType)) {
|
|
1585
|
+
if (Array.isArray(evidence) && evidence.length > 0) {
|
|
1586
|
+
log("profile description evolution skipped: insufficient evidence", {
|
|
1587
|
+
type: itemType,
|
|
1588
|
+
evidenceCount: evidence.length,
|
|
1589
|
+
required: this.minEvidenceForEvolve(itemType),
|
|
1590
|
+
});
|
|
1591
|
+
}
|
|
1592
|
+
return null;
|
|
1593
|
+
}
|
|
1594
|
+
log("profile description evolution attempt", {
|
|
1595
|
+
type: itemType,
|
|
1596
|
+
desc: (item.description || "").substring(0, 40),
|
|
1597
|
+
frequency: item.frequency,
|
|
1598
|
+
evidenceCount: evidence.length,
|
|
1599
|
+
});
|
|
1600
|
+
const evidenceList = evidence.map((e, i) => `${i + 1}. ${e}`).join("\n");
|
|
1601
|
+
const systemPrompt = `You are a user profile description optimizer. Return ONLY a JSON object with a single "description" field: {"description": "..."}
|
|
1602
|
+
Based on multiple independent observations of the same user behavior, generate a more precise description.
|
|
1603
|
+
Rules:
|
|
1604
|
+
- Describe the user's behavioral tendency in general terms
|
|
1605
|
+
- Natural length — not artificially shortened or inflated
|
|
1606
|
+
- Same language as the observations
|
|
1607
|
+
- Do not over-infer beyond what the evidence shows
|
|
1608
|
+
- Do not include technical implementation details, parameter values, algorithm names, tool names, product names, library names, file paths, error messages, or transient conversation content`;
|
|
1609
|
+
const userPrompt = `Current description: ${item.description}
|
|
1610
|
+
|
|
1611
|
+
Independent observations:
|
|
1612
|
+
${evidenceList}
|
|
1613
|
+
|
|
1614
|
+
Generate a concise, abstract description of the user's general behavioral tendency.`;
|
|
1615
|
+
let newDescription = null;
|
|
1616
|
+
if (CONFIG.opencodeProvider && CONFIG.opencodeModel) {
|
|
1617
|
+
try {
|
|
1618
|
+
newDescription = await this.callOpencodeProvider(systemPrompt, userPrompt);
|
|
1619
|
+
}
|
|
1620
|
+
catch (e) {
|
|
1621
|
+
log("profile description evolution: native provider failed, trying external API", {
|
|
1622
|
+
error: String(e),
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (!newDescription && CONFIG.memoryModel && CONFIG.memoryApiUrl) {
|
|
1627
|
+
try {
|
|
1628
|
+
newDescription = await this.callExternalAPI(systemPrompt, userPrompt);
|
|
1629
|
+
}
|
|
1630
|
+
catch (e) {
|
|
1631
|
+
log("profile description evolution: external API failed", { error: String(e) });
|
|
1632
|
+
return null;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (!newDescription || newDescription === item.description) {
|
|
1636
|
+
if (!newDescription) {
|
|
1637
|
+
log("profile description evolution blocked: no provider available");
|
|
1638
|
+
}
|
|
1639
|
+
else {
|
|
1640
|
+
log("profile description evolution skipped: no change", { type: itemType });
|
|
1641
|
+
}
|
|
1642
|
+
return null;
|
|
1643
|
+
}
|
|
1644
|
+
return newDescription;
|
|
1645
|
+
}
|
|
1646
|
+
async evolveAndUpdate(item, itemType, profileId) {
|
|
1647
|
+
if (!profileId)
|
|
1648
|
+
return;
|
|
1649
|
+
try {
|
|
1650
|
+
const evolved = await this.evolveDescription(item, itemType, profileId);
|
|
1651
|
+
if (evolved && evolved !== item.description) {
|
|
1652
|
+
const embed = EmbeddingService.getInstance();
|
|
1653
|
+
if (embed.isWarmedUp) {
|
|
1654
|
+
const evidence = this.ensureArray(item.evidence)
|
|
1655
|
+
.filter((e) => typeof e === "string" && e.length >= 10)
|
|
1656
|
+
.slice(0, 8);
|
|
1657
|
+
if (evidence.length >= 3) {
|
|
1658
|
+
const oldDesc = item.description;
|
|
1659
|
+
const evEmbs = await Promise.all(evidence.map((e) => embed.embed(normalizeDescription(e), { task: "document" })));
|
|
1660
|
+
const sumVec = evEmbs.reduce((acc, e) => {
|
|
1661
|
+
const arr = Array.from(e);
|
|
1662
|
+
return acc.map((v, i) => v + (arr[i] ?? 0));
|
|
1663
|
+
}, new Array(evEmbs[0].length).fill(0));
|
|
1664
|
+
const evCentroid = l2Normalize(sumVec);
|
|
1665
|
+
let adopted = false;
|
|
1666
|
+
const oldEmb = await embed.embed(normalizeDescription(item.description), {
|
|
1667
|
+
task: "document",
|
|
1668
|
+
});
|
|
1669
|
+
const newEmb = await embed.embed(normalizeDescription(evolved), { task: "document" });
|
|
1670
|
+
const cosOld = cosineSimilarityNumbers(Array.from(oldEmb), evCentroid);
|
|
1671
|
+
const cosNew = cosineSimilarityNumbers(Array.from(newEmb), evCentroid);
|
|
1672
|
+
if (cosNew < cosOld - DIRECTION_VALIDATION_TOLERANCE) {
|
|
1673
|
+
log("profile description evolution rejected: direction drift", {
|
|
1674
|
+
type: itemType,
|
|
1675
|
+
cosOld: Math.round(cosOld * 1000) / 1000,
|
|
1676
|
+
cosNew: Math.round(cosNew * 1000) / 1000,
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
else {
|
|
1680
|
+
item.description = evolved;
|
|
1681
|
+
adopted = true;
|
|
1682
|
+
}
|
|
1683
|
+
if (adopted) {
|
|
1684
|
+
const newCentroid = evCentroid;
|
|
1685
|
+
const oldCentroid = item.centroid;
|
|
1686
|
+
item.centroid = newCentroid;
|
|
1687
|
+
item.anchor = newCentroid;
|
|
1688
|
+
item.driftBelowCount = 0;
|
|
1689
|
+
if (oldCentroid) {
|
|
1690
|
+
log("profile centroid rebuilt from evidence after evolve", {
|
|
1691
|
+
type: itemType,
|
|
1692
|
+
cosShift: Math.round(cosineSimilarityNumbers(oldCentroid, newCentroid) * 1000) / 1000,
|
|
1693
|
+
evidenceCount: evidence.length,
|
|
1694
|
+
validated: evidence.length >= 3,
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
log("profile description evolved", {
|
|
1699
|
+
type: itemType,
|
|
1700
|
+
oldDescription: oldDesc,
|
|
1701
|
+
newDescription: item.description,
|
|
1702
|
+
adopted: oldDesc !== item.description,
|
|
1703
|
+
frequency: item.frequency,
|
|
1704
|
+
});
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
else {
|
|
1709
|
+
log("profile description evolution: embedding not warmed up, skipping validation", {
|
|
1710
|
+
type: itemType,
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
const oldDesc = item.description;
|
|
1714
|
+
item.description = evolved;
|
|
1715
|
+
log("profile description evolved", {
|
|
1716
|
+
type: itemType,
|
|
1717
|
+
oldDescription: oldDesc,
|
|
1718
|
+
newDescription: evolved,
|
|
1719
|
+
adopted: true,
|
|
1720
|
+
frequency: item.frequency,
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
catch (e) {
|
|
1725
|
+
log("profile description evolve error", { type: itemType, error: String(e) });
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
async callOpencodeProvider(systemPrompt, userPrompt) {
|
|
1729
|
+
const { generateStructuredOutput } = await loadOpencodeProvider();
|
|
1730
|
+
const { getOpenCodeClient } = await import("../ai/profile-llm-client.js");
|
|
1731
|
+
let v2Client;
|
|
1732
|
+
try {
|
|
1733
|
+
v2Client = await getOpenCodeClient();
|
|
1734
|
+
}
|
|
1735
|
+
catch (e) {
|
|
1736
|
+
log("profile description evolution: native provider not connected", {
|
|
1737
|
+
provider: CONFIG.opencodeProvider,
|
|
1738
|
+
error: String(e),
|
|
1739
|
+
});
|
|
1740
|
+
return null;
|
|
1741
|
+
}
|
|
1742
|
+
const { z } = await import("zod");
|
|
1743
|
+
const schema = z.object({ description: z.string() });
|
|
1744
|
+
const result = await Promise.race([
|
|
1745
|
+
generateStructuredOutput({
|
|
1746
|
+
client: v2Client,
|
|
1747
|
+
providerID: CONFIG.opencodeProvider,
|
|
1748
|
+
modelID: CONFIG.opencodeModel,
|
|
1749
|
+
...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}),
|
|
1750
|
+
systemPrompt,
|
|
1751
|
+
userPrompt,
|
|
1752
|
+
schema,
|
|
1753
|
+
}),
|
|
1754
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("evolve description timeout")), outerStructuredTimeoutMs(CONFIG.opencodeTimeoutMs))),
|
|
1755
|
+
]);
|
|
1756
|
+
return result.description || null;
|
|
1757
|
+
}
|
|
1758
|
+
async callExternalAPI(systemPrompt, userPrompt) {
|
|
1759
|
+
const t0 = Date.now();
|
|
1760
|
+
const response = await fetch(`${CONFIG.memoryApiUrl}/chat/completions`, {
|
|
1761
|
+
method: "POST",
|
|
1762
|
+
headers: {
|
|
1763
|
+
"Content-Type": "application/json",
|
|
1764
|
+
Authorization: `Bearer ${CONFIG.memoryApiKey || ""}`,
|
|
1765
|
+
},
|
|
1766
|
+
body: JSON.stringify({
|
|
1767
|
+
model: CONFIG.memoryModel,
|
|
1768
|
+
messages: [
|
|
1769
|
+
{ role: "system", content: systemPrompt },
|
|
1770
|
+
{ role: "user", content: userPrompt },
|
|
1771
|
+
],
|
|
1772
|
+
temperature: 0.3,
|
|
1773
|
+
response_format: { type: "json_object" },
|
|
1774
|
+
}),
|
|
1775
|
+
signal: AbortSignal.timeout(60000),
|
|
1776
|
+
});
|
|
1777
|
+
log("profile description evolution: external API http done", {
|
|
1778
|
+
httpMs: Date.now() - t0,
|
|
1779
|
+
status: response.status,
|
|
1780
|
+
});
|
|
1781
|
+
if (!response.ok) {
|
|
1782
|
+
const text = await response.text().catch(() => "");
|
|
1783
|
+
throw new Error(`External API error: ${response.status} ${text}`);
|
|
1784
|
+
}
|
|
1785
|
+
const data = await response.json();
|
|
1786
|
+
const content = data.choices?.[0]?.message?.content;
|
|
1787
|
+
if (!content)
|
|
1788
|
+
throw new Error("No content in API response");
|
|
1789
|
+
const parsed = JSON.parse(content);
|
|
1790
|
+
return parsed.description || null;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
export const userProfileManager = new UserProfileManager();
|