@xopcai/xopc 0.0.170 → 0.0.172
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/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/gateway/static/root/assets/{activity-store-CkUp1qvf.js → activity-store-C3Y-bESI.js} +1 -1
- package/dist/gateway/static/root/assets/{agent-avatar-dicebear-DDuem4HM.js → agent-avatar-dicebear-CPyev9P7.js} +1 -1
- package/dist/gateway/static/root/assets/agents-Bf_kK2Ay.js +2 -0
- package/dist/gateway/static/root/assets/{api-BnuPQhJW.js → api-B7qEr_Rw.js} +1 -1
- package/dist/gateway/static/root/assets/{app-management-settings-panel-DdZw8Hi1.js → app-management-settings-panel-Br_9-7fs.js} +1 -1
- package/dist/gateway/static/root/assets/{appearance-settings-BN8Vk2bX.js → appearance-settings-uyLcRPai.js} +1 -1
- package/dist/gateway/static/root/assets/apps-page-DXFCP5-1.js +1 -0
- package/dist/gateway/static/root/assets/{archive-plugin-C82MaDQj.js → archive-plugin-B19REnR5.js} +1 -1
- package/dist/gateway/static/root/assets/{attachment-load-uilrwSdW.js → attachment-load-DLWCC4Yi.js} +1 -1
- package/dist/gateway/static/root/assets/{automation-suggestion-card-CkDZjAmy.js → automation-suggestion-card-ky5S5lly.js} +1 -1
- package/dist/gateway/static/root/assets/automations-page-D8pT1o2O.js +6 -0
- package/dist/gateway/static/root/assets/{binary-plugins-B7NTL0_T.js → binary-plugins-CtPEzLlo.js} +1 -1
- package/dist/gateway/static/root/assets/{block-editor-D_LDNlB-.js → block-editor-CQVR4Xij.js} +32 -32
- package/dist/gateway/static/root/assets/browser-settings-page-Bav_skKN.js +8 -0
- package/dist/gateway/static/root/assets/{browser-workflow-inputs-UFVUzn4v.js → browser-workflow-inputs-CimCGbhq.js} +1 -1
- package/dist/gateway/static/root/assets/{browser-workflows-page-CGgC0N92.js → browser-workflows-page-DewuCw3p.js} +2 -2
- package/dist/gateway/static/root/assets/capabilities-settings-panel-BHaYYo9E.js +7 -0
- package/dist/gateway/static/root/assets/{capability-presets-api-DUIorGUd.js → capability-presets-api-B5RTs-Az.js} +1 -1
- package/dist/gateway/static/root/assets/{capability-presets-settings-panel-PTz00nR4.js → capability-presets-settings-panel-BgchTh81.js} +1 -1
- package/dist/gateway/static/root/assets/{channel-recipient-api-BYwSB8c6.js → channel-recipient-api-Czu0YzIZ.js} +1 -1
- package/dist/gateway/static/root/assets/channels-settings-BP0e62wt.js +1 -0
- package/dist/gateway/static/root/assets/channels-status-swr-DBWKfeGe.js +1 -0
- package/dist/gateway/static/root/assets/connector-logo-Di3gnR_D.js +1 -0
- package/dist/gateway/static/root/assets/connectors-page-CC5kh0de.js +2 -0
- package/dist/gateway/static/root/assets/{desktop-pet-CkT98fPT.js → desktop-pet-D-ZUNHhn.js} +1 -1
- package/dist/gateway/static/root/assets/{desktop-pet-settings-DkbIzdA3.js → desktop-pet-settings-C3L6AI8_.js} +1 -1
- package/dist/gateway/static/root/assets/{directory-picker-path-field-dBQvj1sG.js → directory-picker-path-field-Dvq4iG6P.js} +1 -1
- package/dist/gateway/static/root/assets/dreaming-settings-D9i54kWO.js +3 -0
- package/dist/gateway/static/root/assets/{extension-debug-page-BfxoIiNo.js → extension-debug-page-BecQjU0J.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-page-EIJ3wIb7.js → extension-page-BeVkPSm-.js} +1 -1
- package/dist/gateway/static/root/assets/{extension-settings-page-DBBec51N.js → extension-settings-page-DMoo2mKx.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-config-api-4_u53Ufq.js → gateway-config-api-Bthb3_6v.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-settings-v9kJM59H.js → gateway-settings-Bh8nPvJQ.js} +1 -1
- package/dist/gateway/static/root/assets/{gateway-startup-retry-CXITih5d.js → gateway-startup-retry-D3USVm9D.js} +1 -1
- package/dist/gateway/static/root/assets/goal-create-dialog-Dp0AyDHI.js +1 -0
- package/dist/gateway/static/root/assets/goal-detail-page-CNt7nrdS.js +4 -0
- package/dist/gateway/static/root/assets/{goals-config-api-D54YQPon.js → goals-config-api-C_2QWBtb.js} +1 -1
- package/dist/gateway/static/root/assets/goals-page-Bm_NZFiZ.js +2 -0
- package/dist/gateway/static/root/assets/{goals-settings-DDezXaVi.js → goals-settings-DhL643tc.js} +1 -1
- package/dist/gateway/static/root/assets/{heartbeat-settings-CRsIUeZN.js → heartbeat-settings-COVFwp7C.js} +1 -1
- package/dist/gateway/static/root/assets/{image-generation-api-CY6cQUHL.js → image-generation-api-BNQlnwpU.js} +1 -1
- package/dist/gateway/static/root/assets/index-C_XSKOH6.css +1 -0
- package/dist/gateway/static/root/assets/{index-Dfq2laZe.js → index-DUasAutC.js} +67 -67
- package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-D9k7EDdY.js → keyboard-shortcuts-settings-DfdJRJVy.js} +1 -1
- package/dist/gateway/static/root/assets/local-app-workbench-page-DZwkD1co.js +2 -0
- package/dist/gateway/static/root/assets/{local-apps-page-DbaiBolh.js → local-apps-page-BvCPOgoi.js} +1 -1
- package/dist/gateway/static/root/assets/{locale-store-Dqp9H2Uf.js → locale-store-BP0vD37A.js} +1 -1
- package/dist/gateway/static/root/assets/{logs-page-DoCY0Mm9.js → logs-page-dNL0Y1dA.js} +3 -3
- package/dist/gateway/static/root/assets/{markdown-split-BGlQR-Be.js → markdown-split-YO1rDk9m.js} +1 -1
- package/dist/gateway/static/root/assets/{media-plugins-BpaeV6f_.js → media-plugins-CU_RRf-q.js} +1 -1
- package/dist/gateway/static/root/assets/messages-BWtP5TFz.js +3 -0
- package/dist/gateway/static/root/assets/{notes-page-Cd2HpciM.js → notes-page-CeFiOK3S.js} +1 -1
- package/dist/gateway/static/root/assets/notes-workbench-B8MKxpZb.js +4 -0
- package/dist/gateway/static/root/assets/{page-tabs-DyimBUp_.js → page-tabs-tiHmRJUA.js} +1 -1
- package/dist/gateway/static/root/assets/{preview-open-alternatives-BKZulEYr.js → preview-open-alternatives-CU6XgaCz.js} +1 -1
- package/dist/gateway/static/root/assets/{product-open-page-Bjz9BxBY.js → product-open-page-Dn4_qor4.js} +1 -1
- package/dist/gateway/static/root/assets/project-detail-page-CWBuuX-S.js +1 -0
- package/dist/gateway/static/root/assets/projects-page-BJSsLsXH.js +1 -0
- package/dist/gateway/static/root/assets/remote-access-hub-DXJDb8vB.js +1 -0
- package/dist/gateway/static/root/assets/{save-bar-controls-BPTqb2_r.js → save-bar-controls-edDUIbXo.js} +1 -1
- package/dist/gateway/static/root/assets/{schedule-field-YN0D81Dk.js → schedule-field-DqJO_5Yb.js} +1 -1
- package/dist/gateway/static/root/assets/{schema-form-BmY5PSS2.js → schema-form-CMh0jzy5.js} +1 -1
- package/dist/gateway/static/root/assets/sessions-page-DeHpWgxM.js +1 -0
- package/dist/gateway/static/root/assets/settings-advanced-gate-Cf-TEYUd.js +1 -0
- package/dist/gateway/static/root/assets/{settings-form-section-B-RhgD_p.js → settings-form-section-Bb0Bc3nJ.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-loading-skeleton-DkPupX2B.js → settings-loading-skeleton-DQhADvz1.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-2QBMvaxj.js → settings-page-b0M5HukN.js} +1 -1
- package/dist/gateway/static/root/assets/{settings-page-layout-CtrW-LD6.js → settings-page-layout-hvjtIjvh.js} +1 -1
- package/dist/gateway/static/root/assets/setup-status-panel-BFyfed_g.js +1 -0
- package/dist/gateway/static/root/assets/{share-preview-page-BezIW1n9.js → share-preview-page-rbeaOpTg.js} +1 -1
- package/dist/gateway/static/root/assets/shares-settings-CYnH9sTt.js +1 -0
- package/dist/gateway/static/root/assets/skill-reload-api-Cr8_m-jS.js +1 -0
- package/dist/gateway/static/root/assets/skills-page-Chtc1xDO.js +2 -0
- package/dist/gateway/static/root/assets/{system-settings-panel-WAFhKyAu.js → system-settings-panel-BHo_hgnL.js} +1 -1
- package/dist/gateway/static/root/assets/{theme-store-BiC0gIBa.js → theme-store-C3KnnjcU.js} +1 -1
- package/dist/gateway/static/root/assets/time-picker-D-G-uwVJ.js +1 -0
- package/dist/gateway/static/root/assets/{typed-models-lib-WAQO3F_8.js → typed-models-lib-DtRnG-YI.js} +1 -1
- package/dist/gateway/static/root/assets/{use-channel-catalog-CKlfsSeU.js → use-channel-catalog-CWWItX2g.js} +1 -1
- package/dist/gateway/static/root/assets/user-context-page-D7qMR26X.js +1 -0
- package/dist/gateway/static/root/assets/{voice-api-key-field-BAFHF0_v.js → voice-api-key-field-BTnltQHZ.js} +1 -1
- package/dist/gateway/static/root/assets/work-discovery-page-CpqFZze9.js +1 -0
- package/dist/gateway/static/root/assets/work-item-detail-page-t4dXpGC0.js +1 -0
- package/dist/gateway/static/root/assets/work-page-BXwDKiMZ.js +1 -0
- package/dist/gateway/static/root/assets/{workflow-run-setup-panel-1OP4HyvS.js → workflow-run-setup-panel-D7vKChFZ.js} +2 -2
- package/dist/gateway/static/root/assets/workflows-page-Bos9HyqT.js +11 -0
- package/dist/gateway/static/root/index.html +7 -7
- package/dist/package.js +1 -1
- package/dist/src/agent/embedded/run-for-session.js +71 -24
- package/dist/src/agent/embedded/run-turn.js +68 -4
- package/dist/src/agent/inbound/inbound-loop.d.ts +0 -2
- package/dist/src/agent/inbound/inbound-loop.js +0 -2
- package/dist/src/agent/memory/builtin-provider.js +4 -4
- package/dist/src/agent/memory/compaction-planner.d.ts +16 -0
- package/dist/src/agent/memory/compaction-planner.js +152 -0
- package/dist/src/agent/memory/compaction-policy.d.ts +10 -0
- package/dist/src/agent/memory/compaction-policy.js +24 -0
- package/dist/src/agent/memory/compaction.d.ts +21 -22
- package/dist/src/agent/memory/compaction.js +220 -194
- package/dist/src/agent/memory/context-budget.d.ts +40 -0
- package/dist/src/agent/memory/context-budget.js +106 -0
- package/dist/src/agent/memory/manager.d.ts +4 -1
- package/dist/src/agent/memory/manager.js +8 -3
- package/dist/src/agent/memory/understanding/service.d.ts +2 -0
- package/dist/src/agent/memory/understanding/service.js +11 -9
- package/dist/src/agent/orchestration/context-overflow.d.ts +1 -0
- package/dist/src/agent/orchestration/context-overflow.js +19 -0
- package/dist/src/agent/orchestration/loop-guard.js +13 -9
- package/dist/src/agent/reply/post-compaction-context.d.ts +4 -0
- package/dist/src/agent/reply/post-compaction-context.js +5 -3
- package/dist/src/agent/service/process-direct-one-shot.js +1 -2
- package/dist/src/agent/service/process-direct-streaming.js +1 -2
- package/dist/src/agent/service.d.ts +1 -2
- package/dist/src/agent/service.js +16 -44
- package/dist/src/agent/session/session-inspector.js +10 -2
- package/dist/src/automations/domain/validation.d.ts +8 -8
- package/dist/src/automations/draft/automation-draft-validator.d.ts +1 -1
- package/dist/src/cli/commands/doctor/checks/database-schema.js +1 -1
- package/dist/src/config/schema.d.ts +17 -1
- package/dist/src/connectors/composio-sessions.d.ts +1 -0
- package/dist/src/connectors/composio-sessions.js +14 -5
- package/dist/src/connectors/composio-triggers.d.ts +1 -1
- package/dist/src/connectors/composio-triggers.js +4 -3
- package/dist/src/connectors/composio.js +1 -0
- package/dist/src/connectors/{connector-memory-sync.d.ts → connected-source-ingestion.d.ts} +11 -4
- package/dist/src/connectors/{connector-memory-sync.js → connected-source-ingestion.js} +49 -101
- package/dist/src/connectors/connected-source-normalizers.d.ts +15 -0
- package/dist/src/connectors/connected-source-normalizers.js +186 -0
- package/dist/src/connectors/connector-identity.d.ts +2 -0
- package/dist/src/connectors/connector-identity.js +29 -0
- package/dist/src/connectors/learning-coordinator.d.ts +25 -0
- package/dist/src/connectors/learning-coordinator.js +214 -0
- package/dist/src/connectors/learning-recipes.d.ts +22 -0
- package/dist/src/connectors/learning-recipes.js +121 -0
- package/dist/src/connectors/runtime-status.d.ts +1 -8
- package/dist/src/connectors/runtime-status.js +4 -29
- package/dist/src/gateway/hono/lib/config-payload.d.ts +23 -0
- package/dist/src/gateway/hono/lib/config-payload.js +3 -0
- package/dist/src/gateway/hono/routes/config-patch/misc.d.ts +1 -1
- package/dist/src/gateway/hono/routes/config-patch/misc.js +28 -0
- package/dist/src/gateway/hono/routes/connectors.js +76 -118
- package/dist/src/gateway/hono/routes/models.js +24 -0
- package/dist/src/gateway/hono/routes/public-gateway.js +3 -2
- package/dist/src/gateway/hono/routes/sessions.js +17 -42
- package/dist/src/gateway/hono/routes/you.js +86 -5
- package/dist/src/gateway/service/sessions-api.d.ts +2 -3
- package/dist/src/gateway/service/sessions-api.js +4 -7
- package/dist/src/gateway/service.d.ts +5 -2
- package/dist/src/gateway/service.js +16 -11
- package/dist/src/knowledge/connected-understanding-pipeline.d.ts +19 -0
- package/dist/src/knowledge/connected-understanding-pipeline.js +268 -0
- package/dist/src/knowledge/index.d.ts +1 -0
- package/dist/src/knowledge/index.js +2 -1
- package/dist/src/knowledge/ingestion-service.d.ts +6 -4
- package/dist/src/knowledge/ingestion-service.js +13 -10
- package/dist/src/knowledge/local-folder-adapter.js +1 -0
- package/dist/src/knowledge/people-graph.js +43 -110
- package/dist/src/knowledge/types.d.ts +3 -0
- package/dist/src/providers/xopc-cloud-account-service.d.ts +40 -0
- package/dist/src/providers/xopc-cloud-account-service.js +65 -0
- package/dist/src/session/index.d.ts +1 -2
- package/dist/src/session/index.js +1 -2
- package/dist/src/session/init-session-turn.d.ts +0 -1
- package/dist/src/session/init-session-turn.js +1 -2
- package/dist/src/session/manager.d.ts +11 -17
- package/dist/src/session/manager.js +11 -14
- package/dist/src/session/session-context-for-llm.d.ts +19 -1
- package/dist/src/session/session-context-for-llm.js +87 -129
- package/dist/src/session/store.d.ts +28 -23
- package/dist/src/session/store.js +94 -83
- package/dist/src/session/transcript-format.d.ts +2 -8
- package/dist/src/session/types.d.ts +8 -6
- package/dist/src/session/user-round-delete.d.ts +3 -6
- package/dist/src/session/user-round-delete.js +12 -16
- package/dist/src/storage/sqlite/connector-learning-repository.d.ts +47 -0
- package/dist/src/storage/sqlite/connector-learning-repository.js +110 -0
- package/dist/src/storage/sqlite/index.d.ts +4 -2
- package/dist/src/storage/sqlite/index.js +5 -3
- package/dist/src/storage/sqlite/knowledge-repository.d.ts +4 -2
- package/dist/src/storage/sqlite/knowledge-repository.js +24 -13
- package/dist/src/storage/sqlite/migrations/060_remove_runtime_transcript_messages.sql +45 -0
- package/dist/src/storage/sqlite/migrations/061_drop_compaction_checkpoints.sql +2 -0
- package/dist/src/storage/sqlite/migrations/062_connector_learning_jobs.sql +27 -0
- package/dist/src/storage/sqlite/migrations/063_knowledge_collection_scopes.sql +14 -0
- package/dist/src/storage/sqlite/migrations/064_user_claims.sql +60 -0
- package/dist/src/storage/sqlite/migrations/065_knowledge_item_scope_identity.sql +116 -0
- package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
- package/dist/src/storage/sqlite/migrations/runner.js +3 -3
- package/dist/src/storage/sqlite/migrations/runner.ts +1 -1
- package/dist/src/storage/sqlite/schema.js +1 -1
- package/dist/src/storage/sqlite/schema.sql +0 -19
- package/dist/src/storage/sqlite/transcript-repository.d.ts +6 -11
- package/dist/src/storage/sqlite/transcript-repository.js +90 -84
- package/dist/src/storage/sqlite/user-claims-repository.d.ts +101 -0
- package/dist/src/storage/sqlite/user-claims-repository.js +241 -0
- package/dist/src/user-context/config.d.ts +67 -2
- package/dist/src/user-context/config.js +36 -3
- package/dist/src/user-context/projection.d.ts +36 -1
- package/dist/src/user-context/projection.js +84 -6
- package/dist/src/work-discovery/service.js +1 -0
- package/package.json +1 -1
- package/dist/gateway/static/root/assets/agents-BiaQhiQp.js +0 -2
- package/dist/gateway/static/root/assets/apps-page-CuL8Q4yF.js +0 -1
- package/dist/gateway/static/root/assets/automations-page-TZOluRNp.js +0 -6
- package/dist/gateway/static/root/assets/browser-settings-page-C-l6O68Z.js +0 -8
- package/dist/gateway/static/root/assets/capabilities-settings-panel-BW8c0xPp.js +0 -7
- package/dist/gateway/static/root/assets/channels-settings-h9CsE0GT.js +0 -1
- package/dist/gateway/static/root/assets/channels-status-swr-C058Mcfr.js +0 -1
- package/dist/gateway/static/root/assets/connector-logo-CsbegNqi.js +0 -1
- package/dist/gateway/static/root/assets/connectors-page-BWALafGW.js +0 -2
- package/dist/gateway/static/root/assets/dreaming-settings-DkdnKMZx.js +0 -3
- package/dist/gateway/static/root/assets/goal-create-dialog-y2Y3p7_k.js +0 -1
- package/dist/gateway/static/root/assets/goal-detail-page-DuzL-alv.js +0 -4
- package/dist/gateway/static/root/assets/goals-page-OeLtfKI2.js +0 -2
- package/dist/gateway/static/root/assets/index-o4uaOGKT.css +0 -1
- package/dist/gateway/static/root/assets/local-app-workbench-page-3ssYIEK6.js +0 -2
- package/dist/gateway/static/root/assets/messages-KEk-hTFt.js +0 -3
- package/dist/gateway/static/root/assets/notes-workbench-CatZNAPc.js +0 -4
- package/dist/gateway/static/root/assets/project-detail-page-DJUOgqm4.js +0 -1
- package/dist/gateway/static/root/assets/projects-page-BQQAD_nu.js +0 -1
- package/dist/gateway/static/root/assets/remote-access-hub-fIGXTTnA.js +0 -1
- package/dist/gateway/static/root/assets/sessions-page-BuU-8FCe.js +0 -1
- package/dist/gateway/static/root/assets/settings-advanced-gate-DlKoeZm3.js +0 -1
- package/dist/gateway/static/root/assets/setup-status-panel-BSUcDFnb.js +0 -1
- package/dist/gateway/static/root/assets/shares-settings-Bk2-SwGJ.js +0 -1
- package/dist/gateway/static/root/assets/skill-reload-api-e_Fx1kVC.js +0 -1
- package/dist/gateway/static/root/assets/skills-page-D_cCADfj.js +0 -2
- package/dist/gateway/static/root/assets/time-picker-fqRXpNJV.js +0 -1
- package/dist/gateway/static/root/assets/user-context-page-9Ov4htPW.js +0 -1
- package/dist/gateway/static/root/assets/work-discovery-page-DGN2FxWv.js +0 -1
- package/dist/gateway/static/root/assets/work-item-detail-page-HmyWSgUo.js +0 -1
- package/dist/gateway/static/root/assets/work-page-D3iKVjFq.js +0 -1
- package/dist/gateway/static/root/assets/workflows-page-B5L4SFw4.js +0 -11
- package/dist/src/agent/lifecycle/handlers/compaction.d.ts +0 -13
- package/dist/src/agent/lifecycle/handlers/compaction.js +0 -18
- package/dist/src/connectors/memory-sync-coordinator.d.ts +0 -28
- package/dist/src/connectors/memory-sync-coordinator.js +0 -162
- package/dist/src/connectors/memory-sync-profile.d.ts +0 -13
- package/dist/src/connectors/memory-sync-profile.js +0 -73
- package/dist/src/session/compaction-checkpoints.d.ts +0 -8
- package/dist/src/session/compaction-checkpoints.js +0 -19
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { getSqliteDatabase, runSqliteWriteTransaction } from "./transaction.js";
|
|
2
|
-
import { buildSessionContextForLlm } from "../../session/session-context-for-llm.js";
|
|
2
|
+
import { buildSessionContextForLlm, isRuntimeOnlyTranscriptMessage } from "../../session/session-context-for-llm.js";
|
|
3
3
|
import { classifyStoredRow, estimateTokensFromMessages, extractFtsContent, transcriptEntryRowToStoredRow } from "./row-mappers.js";
|
|
4
4
|
import { getCurrentSessionId, readCurrentSessionId } from "./session-repository.js";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
6
|
//#region src/storage/sqlite/transcript-repository.ts
|
|
7
|
-
const MAX_CHECKPOINTS_PER_TRANSCRIPT = 15;
|
|
8
7
|
function nextSeq(db, sessionId) {
|
|
9
8
|
return (db.prepare(`SELECT COALESCE(MAX(seq), 0) AS max_seq FROM transcript_entries WHERE session_id = ?`).get(sessionId).max_seq ?? 0) + 1;
|
|
10
9
|
}
|
|
@@ -34,6 +33,7 @@ function isUserMessageRow(row) {
|
|
|
34
33
|
return classified.entryKind === "message" && classified.role === "user";
|
|
35
34
|
}
|
|
36
35
|
function appendTranscriptEntry(sessionKey, row, opts) {
|
|
36
|
+
if (isRuntimeOnlyTranscriptMessage(row)) throw new Error("Runtime-only messages cannot be persisted in a session transcript");
|
|
37
37
|
return runSqliteWriteTransaction((db) => {
|
|
38
38
|
const sessionId = opts?.sessionId ?? readCurrentSessionId(db, sessionKey);
|
|
39
39
|
if (!sessionId) throw new Error(`Session not found: ${sessionKey}`);
|
|
@@ -58,6 +58,31 @@ function appendTranscriptEntry(sessionKey, row, opts) {
|
|
|
58
58
|
return inserted;
|
|
59
59
|
});
|
|
60
60
|
}
|
|
61
|
+
function appendCompactionBoundary(sessionKey, row) {
|
|
62
|
+
return runSqliteWriteTransaction((db) => {
|
|
63
|
+
const sessionId = readCurrentSessionId(db, sessionKey);
|
|
64
|
+
if (!sessionId) throw new Error(`Session not found: ${sessionKey}`);
|
|
65
|
+
const boundary = {
|
|
66
|
+
...row,
|
|
67
|
+
baseSeq: nextSeq(db, sessionId) - 1
|
|
68
|
+
};
|
|
69
|
+
const inserted = insertEntry(db, {
|
|
70
|
+
sessionId,
|
|
71
|
+
sessionKey,
|
|
72
|
+
row: boundary
|
|
73
|
+
});
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
db.prepare(`UPDATE sessions SET
|
|
76
|
+
message_count = ?,
|
|
77
|
+
estimated_tokens = ?,
|
|
78
|
+
compacted_count = compacted_count + 1,
|
|
79
|
+
updated_at = ?,
|
|
80
|
+
last_accessed_at = ?,
|
|
81
|
+
last_interaction_at = ?
|
|
82
|
+
WHERE session_key = ?`).run(boundary.messages.length, boundary.tokensAfter, now, now, now, sessionKey);
|
|
83
|
+
return inserted;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
61
86
|
function loadTranscriptRowsForSession(sessionKey) {
|
|
62
87
|
const sessionId = getCurrentSessionId(sessionKey);
|
|
63
88
|
if (!sessionId) return [];
|
|
@@ -79,25 +104,30 @@ function loadTranscriptRows(sessionId) {
|
|
|
79
104
|
ORDER BY seq ASC`).all(sessionId).map(transcriptEntryRowToStoredRow);
|
|
80
105
|
}
|
|
81
106
|
function loadLlmMessagesForSession(sessionKey) {
|
|
82
|
-
|
|
107
|
+
const sessionId = getCurrentSessionId(sessionKey);
|
|
108
|
+
if (!sessionId) return [];
|
|
109
|
+
return buildSessionContextForLlm(getSqliteDatabase().prepare(`SELECT entry_id, session_id, seq, entry_kind, role, payload_json, created_at
|
|
110
|
+
FROM transcript_entries
|
|
111
|
+
WHERE session_id = ?
|
|
112
|
+
AND seq >= COALESCE(
|
|
113
|
+
(SELECT MAX(seq) FROM transcript_entries WHERE session_id = ? AND entry_kind = 'compaction'),
|
|
114
|
+
1
|
|
115
|
+
)
|
|
116
|
+
ORDER BY seq ASC`).all(sessionId, sessionId).map(transcriptEntryRowToStoredRow));
|
|
83
117
|
}
|
|
84
|
-
function replaceTranscriptRows(sessionKey, rows
|
|
118
|
+
function replaceTranscriptRows(sessionKey, rows) {
|
|
119
|
+
if (rows.some(isRuntimeOnlyTranscriptMessage)) throw new Error("Runtime-only messages cannot be persisted in a session transcript");
|
|
85
120
|
runSqliteWriteTransaction((db) => {
|
|
86
121
|
const sessionId = readCurrentSessionId(db, sessionKey);
|
|
87
122
|
if (!sessionId) throw new Error(`Session not found: ${sessionKey}`);
|
|
88
123
|
db.prepare(`DELETE FROM transcript_fts WHERE session_id = ?`).run(sessionId);
|
|
89
124
|
db.prepare(`DELETE FROM transcript_entries WHERE session_id = ?`).run(sessionId);
|
|
90
|
-
const
|
|
91
|
-
if (opts?.appendCompaction) toWrite.push({
|
|
92
|
-
type: "compaction",
|
|
93
|
-
...opts.appendCompaction
|
|
94
|
-
});
|
|
95
|
-
for (const row of toWrite) insertEntry(db, {
|
|
125
|
+
for (const row of rows) insertEntry(db, {
|
|
96
126
|
sessionId,
|
|
97
127
|
sessionKey,
|
|
98
128
|
row
|
|
99
129
|
});
|
|
100
|
-
const llm = buildSessionContextForLlm(
|
|
130
|
+
const llm = buildSessionContextForLlm(rows);
|
|
101
131
|
const now = Date.now();
|
|
102
132
|
const hiddenUpdate = llm.some((message) => message.role === "user") ? `hidden_from_session_list = 0,` : "";
|
|
103
133
|
db.prepare(`UPDATE sessions SET
|
|
@@ -110,14 +140,6 @@ function replaceTranscriptRows(sessionKey, rows, opts) {
|
|
|
110
140
|
WHERE session_key = ?`).run(llm.length, estimateTokensFromMessages(llm), now, now, now, sessionKey);
|
|
111
141
|
});
|
|
112
142
|
}
|
|
113
|
-
function loadCheckpointRows(sessionKey, checkpointId) {
|
|
114
|
-
const db = getSqliteDatabase();
|
|
115
|
-
if (!db.prepare(`SELECT checkpoint_id FROM compaction_checkpoints
|
|
116
|
-
WHERE session_key = ? AND checkpoint_id = ?`).get(sessionKey, checkpointId)) return [];
|
|
117
|
-
return db.prepare(`SELECT payload_json FROM checkpoint_entries
|
|
118
|
-
WHERE checkpoint_id = ?
|
|
119
|
-
ORDER BY seq ASC`).all(checkpointId).map((entry) => JSON.parse(entry.payload_json));
|
|
120
|
-
}
|
|
121
143
|
function paginateTranscriptMessages(sessionKey, options = {}) {
|
|
122
144
|
const sessionId = getCurrentSessionId(sessionKey);
|
|
123
145
|
if (!sessionId) return {
|
|
@@ -171,86 +193,70 @@ function paginateTranscriptMessages(sessionKey, options = {}) {
|
|
|
171
193
|
endSeq: rows[rows.length - 1]?.seq ?? 0
|
|
172
194
|
};
|
|
173
195
|
}
|
|
174
|
-
function
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
196
|
+
function listCompactionBoundaries(sessionKey) {
|
|
197
|
+
const db = getSqliteDatabase();
|
|
198
|
+
const sessionId = getCurrentSessionId(sessionKey);
|
|
199
|
+
if (!sessionId) return [];
|
|
200
|
+
return db.prepare(`SELECT entry_id, seq, payload_json, created_at
|
|
201
|
+
FROM transcript_entries
|
|
202
|
+
WHERE session_id = ? AND entry_kind = 'compaction'
|
|
203
|
+
ORDER BY seq DESC`).all(sessionId).map((row) => {
|
|
204
|
+
const payload = JSON.parse(row.payload_json);
|
|
205
|
+
return {
|
|
206
|
+
id: row.entry_id,
|
|
207
|
+
seq: row.seq,
|
|
208
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
209
|
+
messageCount: payload.messages.length,
|
|
210
|
+
tokensBefore: payload.tokensBefore,
|
|
211
|
+
tokensAfter: payload.tokensAfter,
|
|
212
|
+
summaryPreview: payload.summary.slice(0, 500),
|
|
213
|
+
restoredFromCompactionId: payload.restoredFromCompactionId
|
|
214
|
+
};
|
|
193
215
|
});
|
|
194
216
|
}
|
|
195
|
-
function
|
|
196
|
-
const rows = db.prepare(`SELECT checkpoint_id FROM compaction_checkpoints
|
|
197
|
-
WHERE session_id = ?
|
|
198
|
-
ORDER BY created_at ASC`).all(sessionId);
|
|
199
|
-
if (rows.length <= MAX_CHECKPOINTS_PER_TRANSCRIPT) return;
|
|
200
|
-
const toDelete = rows.slice(0, rows.length - MAX_CHECKPOINTS_PER_TRANSCRIPT);
|
|
201
|
-
const del = db.prepare(`DELETE FROM compaction_checkpoints WHERE checkpoint_id = ?`);
|
|
202
|
-
for (const row of toDelete) del.run(row.checkpoint_id);
|
|
203
|
-
}
|
|
204
|
-
function listCompactionCheckpoints(sessionKey) {
|
|
205
|
-
return getSqliteDatabase().prepare(`SELECT checkpoint_id, created_at, message_count, size_bytes
|
|
206
|
-
FROM compaction_checkpoints
|
|
207
|
-
WHERE session_key = ?
|
|
208
|
-
ORDER BY created_at DESC`).all(sessionKey).map((row) => ({
|
|
209
|
-
id: row.checkpoint_id,
|
|
210
|
-
sizeBytes: row.size_bytes,
|
|
211
|
-
modifiedAt: new Date(row.created_at).toISOString()
|
|
212
|
-
}));
|
|
213
|
-
}
|
|
214
|
-
function getCompactionCheckpointDetail(sessionKey, checkpointId) {
|
|
215
|
-
const row = getSqliteDatabase().prepare(`SELECT checkpoint_id, created_at, message_count, size_bytes
|
|
216
|
-
FROM compaction_checkpoints
|
|
217
|
-
WHERE session_key = ? AND checkpoint_id = ?`).get(sessionKey, checkpointId);
|
|
218
|
-
if (!row) return null;
|
|
219
|
-
return {
|
|
220
|
-
id: row.checkpoint_id,
|
|
221
|
-
sizeBytes: row.size_bytes,
|
|
222
|
-
modifiedAt: new Date(row.created_at).toISOString(),
|
|
223
|
-
messageCount: row.message_count
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
function restoreCompactionCheckpoint(sessionKey, checkpointId) {
|
|
217
|
+
function restoreBeforeCompactionBoundary(sessionKey, compactionId) {
|
|
227
218
|
runSqliteWriteTransaction((db) => {
|
|
228
219
|
const sessionId = readCurrentSessionId(db, sessionKey);
|
|
229
220
|
if (!sessionId) throw new Error(`Session not found: ${sessionKey}`);
|
|
230
|
-
|
|
231
|
-
WHERE
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
221
|
+
const boundary = db.prepare(`SELECT seq FROM transcript_entries
|
|
222
|
+
WHERE session_id = ? AND entry_id = ? AND entry_kind = 'compaction'`).get(sessionId, compactionId);
|
|
223
|
+
if (!boundary) throw new Error(`Compaction boundary not found: ${compactionId}`);
|
|
224
|
+
const restoredMessages = buildSessionContextForLlm(db.prepare(`SELECT entry_id, session_id, seq, entry_kind, role, payload_json, created_at
|
|
225
|
+
FROM transcript_entries
|
|
226
|
+
WHERE session_id = ? AND seq < ?
|
|
227
|
+
ORDER BY seq ASC`).all(sessionId, boundary.seq).map(transcriptEntryRowToStoredRow));
|
|
228
|
+
if (restoredMessages.length === 0) throw new Error(`No restorable context exists before compaction boundary: ${compactionId}`);
|
|
229
|
+
const current = db.prepare(`SELECT estimated_tokens FROM sessions WHERE session_key = ?`).get(sessionKey);
|
|
230
|
+
const tokensAfter = estimateTokensFromMessages(restoredMessages);
|
|
231
|
+
const baseSeq = nextSeq(db, sessionId) - 1;
|
|
232
|
+
insertEntry(db, {
|
|
239
233
|
sessionId,
|
|
240
234
|
sessionKey,
|
|
241
|
-
row:
|
|
242
|
-
|
|
235
|
+
row: {
|
|
236
|
+
type: "compaction",
|
|
237
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
238
|
+
baseSeq,
|
|
239
|
+
plannerVersion: 2,
|
|
240
|
+
summaryModelRef: "logical-restore",
|
|
241
|
+
qualityAudit: "disabled",
|
|
242
|
+
summary: `Restored the effective context that existed before compaction boundary ${compactionId}.`,
|
|
243
|
+
messages: restoredMessages,
|
|
244
|
+
firstKeptIndex: 0,
|
|
245
|
+
tokensBefore: current.estimated_tokens,
|
|
246
|
+
tokensAfter,
|
|
247
|
+
restoredFromCompactionId: compactionId
|
|
248
|
+
}
|
|
243
249
|
});
|
|
244
|
-
const llm = buildSessionContextForLlm(entries.map((e) => JSON.parse(e.payload_json)));
|
|
245
250
|
const now = Date.now();
|
|
246
251
|
db.prepare(`UPDATE sessions SET
|
|
247
252
|
message_count = ?,
|
|
248
253
|
estimated_tokens = ?,
|
|
254
|
+
compacted_count = compacted_count + 1,
|
|
249
255
|
updated_at = ?,
|
|
250
256
|
last_accessed_at = ?,
|
|
251
257
|
last_interaction_at = ?
|
|
252
|
-
WHERE session_key = ?`).run(
|
|
258
|
+
WHERE session_key = ?`).run(restoredMessages.length, tokensAfter, now, now, now, sessionKey);
|
|
253
259
|
});
|
|
254
260
|
}
|
|
255
261
|
//#endregion
|
|
256
|
-
export {
|
|
262
|
+
export { appendCompactionBoundary, appendTranscriptEntry, listCompactionBoundaries, loadLlmMessagesForSession, loadTranscriptHistoryRowsForSession, loadTranscriptRows, loadTranscriptRowsForSession, paginateTranscriptMessages, replaceTranscriptRows, restoreBeforeCompactionBoundary };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
export type UserEntityType = 'person' | 'project' | 'organization';
|
|
2
|
+
export type UserEntityHandleType = 'email' | 'provider_user' | 'display_name';
|
|
3
|
+
export type UserClaimClass = 'relationship' | 'project' | 'routine';
|
|
4
|
+
export type UserClaimState = 'provisional' | 'active' | 'rejected' | 'stale';
|
|
5
|
+
export type UserClaimUserState = 'auto' | 'confirmed' | 'rejected';
|
|
6
|
+
export type UserEntity = {
|
|
7
|
+
id: string;
|
|
8
|
+
type: UserEntityType;
|
|
9
|
+
canonicalLabel: string;
|
|
10
|
+
createdAt: string;
|
|
11
|
+
updatedAt: string;
|
|
12
|
+
};
|
|
13
|
+
export type UserClaim = {
|
|
14
|
+
id: string;
|
|
15
|
+
agentId: string;
|
|
16
|
+
class: UserClaimClass;
|
|
17
|
+
key: string;
|
|
18
|
+
subjectEntityId?: string;
|
|
19
|
+
value: Record<string, unknown>;
|
|
20
|
+
state: UserClaimState;
|
|
21
|
+
userState: UserClaimUserState;
|
|
22
|
+
confidence: number;
|
|
23
|
+
independentEvidenceCount: number;
|
|
24
|
+
activeDayCount: number;
|
|
25
|
+
firstObservedAt: string;
|
|
26
|
+
lastReinforcedAt: string;
|
|
27
|
+
memoryRecordId?: string;
|
|
28
|
+
createdAt: string;
|
|
29
|
+
updatedAt: string;
|
|
30
|
+
};
|
|
31
|
+
export declare function resolveUserEntity(input: {
|
|
32
|
+
type: UserEntityType;
|
|
33
|
+
canonicalLabel: string;
|
|
34
|
+
handles: Array<{
|
|
35
|
+
type: UserEntityHandleType;
|
|
36
|
+
value: string;
|
|
37
|
+
sourceScope: string;
|
|
38
|
+
verified: boolean;
|
|
39
|
+
}>;
|
|
40
|
+
nowMs?: number;
|
|
41
|
+
}): UserEntity;
|
|
42
|
+
export declare function reinforceUserClaim(input: {
|
|
43
|
+
agentId: string;
|
|
44
|
+
class: UserClaimClass;
|
|
45
|
+
key: string;
|
|
46
|
+
subjectEntityId?: string;
|
|
47
|
+
value: Record<string, unknown>;
|
|
48
|
+
evidence: Array<{
|
|
49
|
+
logicalEventKey: string;
|
|
50
|
+
sourceItemId: string;
|
|
51
|
+
sourceInstanceId: string;
|
|
52
|
+
relation: 'supports' | 'contradicts';
|
|
53
|
+
observedAt: string;
|
|
54
|
+
}>;
|
|
55
|
+
nowMs?: number;
|
|
56
|
+
}): UserClaim;
|
|
57
|
+
export declare function removeUserClaimEvidenceForSource(sourceInstanceId: string): {
|
|
58
|
+
deletedClaimCount: number;
|
|
59
|
+
deletedMemoryRecordIds: string[];
|
|
60
|
+
retainedClaims: Array<{
|
|
61
|
+
memoryRecordId: string;
|
|
62
|
+
state: UserClaimState;
|
|
63
|
+
}>;
|
|
64
|
+
};
|
|
65
|
+
export declare function setUserClaimDecision(claimId: string, userState: Exclude<UserClaimUserState, 'auto'>): UserClaim | undefined;
|
|
66
|
+
export declare function linkUserClaimMemoryRecord(claimId: string, memoryRecordId: string): void;
|
|
67
|
+
export declare function getUserClaim(claimId: string): UserClaim | undefined;
|
|
68
|
+
export declare function listUserClaims(options?: {
|
|
69
|
+
agentId?: string;
|
|
70
|
+
state?: UserClaimState;
|
|
71
|
+
limit?: number;
|
|
72
|
+
}): UserClaim[];
|
|
73
|
+
export declare function listUserClaimEvidence(claimId: string): Array<{
|
|
74
|
+
logicalEventKey: string;
|
|
75
|
+
sourceItemId: string;
|
|
76
|
+
sourceInstanceId: string;
|
|
77
|
+
relation: string;
|
|
78
|
+
observedAt: string;
|
|
79
|
+
}>;
|
|
80
|
+
export declare function listUserPeopleGraphRows(): {
|
|
81
|
+
people: Array<UserEntity & {
|
|
82
|
+
handles: Array<{
|
|
83
|
+
type: UserEntityHandleType;
|
|
84
|
+
value: string;
|
|
85
|
+
}>;
|
|
86
|
+
}>;
|
|
87
|
+
edges: Array<{
|
|
88
|
+
entityId: string;
|
|
89
|
+
sourceInstanceId: string;
|
|
90
|
+
mentionCount: number;
|
|
91
|
+
lastObservedAt: string;
|
|
92
|
+
}>;
|
|
93
|
+
evidenceCount: number;
|
|
94
|
+
};
|
|
95
|
+
export declare function listUserClaimStatsBySource(): Record<string, {
|
|
96
|
+
evidenceCount: number;
|
|
97
|
+
provisionalClaims: number;
|
|
98
|
+
activeClaims: number;
|
|
99
|
+
resolvedEntities: number;
|
|
100
|
+
lastEvidenceAt?: string;
|
|
101
|
+
}>;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { getSqliteDatabase, runSqliteWriteTransaction } from "./transaction.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
//#region src/storage/sqlite/user-claims-repository.ts
|
|
4
|
+
function entityFromRow(row) {
|
|
5
|
+
return {
|
|
6
|
+
id: row.entity_id,
|
|
7
|
+
type: row.entity_type,
|
|
8
|
+
canonicalLabel: row.canonical_label,
|
|
9
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
10
|
+
updatedAt: new Date(row.updated_at).toISOString()
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function claimFromRow(row) {
|
|
14
|
+
return {
|
|
15
|
+
id: row.claim_id,
|
|
16
|
+
agentId: row.agent_id,
|
|
17
|
+
class: row.claim_class,
|
|
18
|
+
key: row.claim_key,
|
|
19
|
+
...row.subject_entity_id ? { subjectEntityId: row.subject_entity_id } : {},
|
|
20
|
+
value: JSON.parse(row.value_json),
|
|
21
|
+
state: row.state,
|
|
22
|
+
userState: row.user_state,
|
|
23
|
+
confidence: row.confidence,
|
|
24
|
+
independentEvidenceCount: row.independent_evidence_count,
|
|
25
|
+
activeDayCount: row.active_day_count,
|
|
26
|
+
firstObservedAt: new Date(row.first_observed_at).toISOString(),
|
|
27
|
+
lastReinforcedAt: new Date(row.last_reinforced_at).toISOString(),
|
|
28
|
+
...row.memory_record_id ? { memoryRecordId: row.memory_record_id } : {},
|
|
29
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
30
|
+
updatedAt: new Date(row.updated_at).toISOString()
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function resolveUserEntity(input) {
|
|
34
|
+
const now = input.nowMs ?? Date.now();
|
|
35
|
+
return runSqliteWriteTransaction((db) => {
|
|
36
|
+
const handles = input.handles.map((handle) => ({
|
|
37
|
+
...handle,
|
|
38
|
+
value: handle.value.trim().toLowerCase()
|
|
39
|
+
})).filter((handle) => handle.value);
|
|
40
|
+
const strong = handles.filter((handle) => handle.verified);
|
|
41
|
+
let row;
|
|
42
|
+
for (const handle of strong) {
|
|
43
|
+
row = db.prepare(`SELECT e.* FROM user_entities e JOIN user_entity_handles h ON h.entity_id = e.entity_id
|
|
44
|
+
WHERE h.handle_type = ? AND h.normalized_value = ? AND h.source_scope = ?`).get(handle.type, handle.value, handle.sourceScope);
|
|
45
|
+
if (row) break;
|
|
46
|
+
}
|
|
47
|
+
if (!row) {
|
|
48
|
+
const fallback = handles[0];
|
|
49
|
+
if (fallback) row = db.prepare(`SELECT e.* FROM user_entities e JOIN user_entity_handles h ON h.entity_id = e.entity_id
|
|
50
|
+
WHERE h.handle_type = ? AND h.normalized_value = ? AND h.source_scope = ?`).get(fallback.type, fallback.value, fallback.sourceScope);
|
|
51
|
+
}
|
|
52
|
+
const entityId = row?.entity_id ?? randomUUID();
|
|
53
|
+
if (!row) db.prepare(`INSERT INTO user_entities (entity_id, entity_type, canonical_label, created_at, updated_at)
|
|
54
|
+
VALUES (?, ?, ?, ?, ?)`).run(entityId, input.type, input.canonicalLabel, now, now);
|
|
55
|
+
else {
|
|
56
|
+
const incomingHumanName = input.canonicalLabel.includes(" ") && !input.canonicalLabel.includes("@");
|
|
57
|
+
const existingHumanName = row.canonical_label.includes(" ") && !row.canonical_label.includes("@");
|
|
58
|
+
if (incomingHumanName && (!existingHumanName || input.canonicalLabel.length > row.canonical_label.length)) db.prepare("UPDATE user_entities SET canonical_label = ?, updated_at = ? WHERE entity_id = ?").run(input.canonicalLabel, now, entityId);
|
|
59
|
+
}
|
|
60
|
+
for (const handle of handles) db.prepare(`INSERT OR IGNORE INTO user_entity_handles
|
|
61
|
+
(entity_id, handle_type, normalized_value, source_scope, verified, created_at)
|
|
62
|
+
VALUES (?, ?, ?, ?, ?, ?)`).run(entityId, handle.type, handle.value, handle.sourceScope, handle.verified ? 1 : 0, now);
|
|
63
|
+
return entityFromRow(db.prepare("SELECT * FROM user_entities WHERE entity_id = ?").get(entityId));
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function thresholds(claimClass) {
|
|
67
|
+
return claimClass === "routine" ? {
|
|
68
|
+
evidence: 3,
|
|
69
|
+
days: 3
|
|
70
|
+
} : {
|
|
71
|
+
evidence: 3,
|
|
72
|
+
days: 2
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function refreshUserClaim(db, row, now) {
|
|
76
|
+
const stats = db.prepare(`SELECT
|
|
77
|
+
SUM(CASE WHEN relation = 'supports' THEN 1 ELSE 0 END) AS evidence_count,
|
|
78
|
+
SUM(CASE WHEN relation = 'contradicts' THEN 1 ELSE 0 END) AS contradiction_count,
|
|
79
|
+
COUNT(DISTINCT CASE WHEN relation = 'supports' THEN date(observed_at / 1000, 'unixepoch') END) AS active_days,
|
|
80
|
+
MAX(observed_at) AS last_observed
|
|
81
|
+
FROM user_claim_evidence WHERE claim_id = ?`).get(row.claim_id);
|
|
82
|
+
const evidenceCount = stats.evidence_count ?? 0;
|
|
83
|
+
const contradictionCount = stats.contradiction_count ?? 0;
|
|
84
|
+
const limit = thresholds(row.claim_class);
|
|
85
|
+
const state = row.user_state === "rejected" ? "rejected" : row.user_state === "confirmed" ? "active" : contradictionCount >= evidenceCount && contradictionCount > 0 ? "stale" : evidenceCount >= limit.evidence && stats.active_days >= limit.days ? "active" : "provisional";
|
|
86
|
+
const confidence = Math.max(.1, Math.min(.92, .48 + Math.min(evidenceCount, 8) * .035 + Math.min(stats.active_days, 5) * .045 - Math.min(contradictionCount, 5) * .08));
|
|
87
|
+
db.prepare(`UPDATE user_claims SET state = ?, confidence = ?, independent_evidence_count = ?,
|
|
88
|
+
active_day_count = ?, last_reinforced_at = ?, updated_at = ? WHERE claim_id = ?`).run(state, confidence, evidenceCount, stats.active_days, stats.last_observed ?? row.last_reinforced_at, now, row.claim_id);
|
|
89
|
+
return claimFromRow(db.prepare("SELECT * FROM user_claims WHERE claim_id = ?").get(row.claim_id));
|
|
90
|
+
}
|
|
91
|
+
function reinforceUserClaim(input) {
|
|
92
|
+
const now = input.nowMs ?? Date.now();
|
|
93
|
+
return runSqliteWriteTransaction((db) => {
|
|
94
|
+
let row = db.prepare("SELECT * FROM user_claims WHERE agent_id = ? AND claim_class = ? AND claim_key = ?").get(input.agentId, input.class, input.key);
|
|
95
|
+
const claimId = row?.claim_id ?? randomUUID();
|
|
96
|
+
if (!row) {
|
|
97
|
+
const firstObserved = Math.min(...input.evidence.map((item) => Date.parse(item.observedAt)), now);
|
|
98
|
+
db.prepare(`INSERT INTO user_claims (
|
|
99
|
+
claim_id, agent_id, claim_class, claim_key, subject_entity_id, value_json, state, user_state,
|
|
100
|
+
confidence, independent_evidence_count, active_day_count, first_observed_at, last_reinforced_at,
|
|
101
|
+
created_at, updated_at
|
|
102
|
+
) VALUES (?, ?, ?, ?, ?, ?, 'provisional', 'auto', 0, 0, 0, ?, ?, ?, ?)`).run(claimId, input.agentId, input.class, input.key, input.subjectEntityId ?? null, JSON.stringify(input.value), firstObserved, now, now, now);
|
|
103
|
+
}
|
|
104
|
+
for (const evidence of input.evidence) db.prepare(`INSERT INTO user_claim_evidence (
|
|
105
|
+
claim_id, logical_event_key, source_item_id, source_instance_id, relation, observed_at, created_at
|
|
106
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
107
|
+
ON CONFLICT(claim_id, logical_event_key) DO UPDATE SET
|
|
108
|
+
source_item_id = excluded.source_item_id,
|
|
109
|
+
source_instance_id = excluded.source_instance_id,
|
|
110
|
+
relation = excluded.relation,
|
|
111
|
+
observed_at = excluded.observed_at`).run(claimId, evidence.logicalEventKey, evidence.sourceItemId, evidence.sourceInstanceId, evidence.relation, Date.parse(evidence.observedAt), now);
|
|
112
|
+
db.prepare("UPDATE user_claims SET subject_entity_id = ?, value_json = ? WHERE claim_id = ?").run(input.subjectEntityId ?? null, JSON.stringify(input.value), claimId);
|
|
113
|
+
row = db.prepare("SELECT * FROM user_claims WHERE claim_id = ?").get(claimId);
|
|
114
|
+
return refreshUserClaim(db, row, now);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function removeUserClaimEvidenceForSource(sourceInstanceId) {
|
|
118
|
+
return runSqliteWriteTransaction((db) => {
|
|
119
|
+
const affected = db.prepare(`SELECT DISTINCT c.* FROM user_claims c
|
|
120
|
+
JOIN user_claim_evidence e ON e.claim_id = c.claim_id
|
|
121
|
+
WHERE e.source_instance_id = ?`).all(sourceInstanceId);
|
|
122
|
+
db.prepare("DELETE FROM user_claim_evidence WHERE source_instance_id = ?").run(sourceInstanceId);
|
|
123
|
+
const deletedMemoryRecordIds = [];
|
|
124
|
+
const retainedClaims = [];
|
|
125
|
+
let deletedClaimCount = 0;
|
|
126
|
+
const now = Date.now();
|
|
127
|
+
for (const row of affected) {
|
|
128
|
+
if (db.prepare("SELECT COUNT(*) AS count FROM user_claim_evidence WHERE claim_id = ?").get(row.claim_id).count === 0) {
|
|
129
|
+
if (row.memory_record_id) deletedMemoryRecordIds.push(row.memory_record_id);
|
|
130
|
+
db.prepare("DELETE FROM user_claims WHERE claim_id = ?").run(row.claim_id);
|
|
131
|
+
deletedClaimCount += 1;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const claim = refreshUserClaim(db, row, now);
|
|
135
|
+
if (claim.memoryRecordId) retainedClaims.push({
|
|
136
|
+
memoryRecordId: claim.memoryRecordId,
|
|
137
|
+
state: claim.state
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
deletedClaimCount,
|
|
142
|
+
deletedMemoryRecordIds,
|
|
143
|
+
retainedClaims
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function setUserClaimDecision(claimId, userState) {
|
|
148
|
+
runSqliteWriteTransaction((db) => {
|
|
149
|
+
db.prepare(`UPDATE user_claims SET user_state = ?, state = ?, updated_at = ? WHERE claim_id = ?`).run(userState, userState === "confirmed" ? "active" : "rejected", Date.now(), claimId);
|
|
150
|
+
});
|
|
151
|
+
return getUserClaim(claimId);
|
|
152
|
+
}
|
|
153
|
+
function linkUserClaimMemoryRecord(claimId, memoryRecordId) {
|
|
154
|
+
runSqliteWriteTransaction((db) => {
|
|
155
|
+
db.prepare("UPDATE user_claims SET memory_record_id = ?, updated_at = ? WHERE claim_id = ?").run(memoryRecordId, Date.now(), claimId);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
function getUserClaim(claimId) {
|
|
159
|
+
const row = getSqliteDatabase().prepare("SELECT * FROM user_claims WHERE claim_id = ?").get(claimId);
|
|
160
|
+
return row ? claimFromRow(row) : void 0;
|
|
161
|
+
}
|
|
162
|
+
function listUserClaims(options = {}) {
|
|
163
|
+
const where = [];
|
|
164
|
+
const params = [];
|
|
165
|
+
if (options.agentId) {
|
|
166
|
+
where.push("agent_id = ?");
|
|
167
|
+
params.push(options.agentId);
|
|
168
|
+
}
|
|
169
|
+
if (options.state) {
|
|
170
|
+
where.push("state = ?");
|
|
171
|
+
params.push(options.state);
|
|
172
|
+
}
|
|
173
|
+
const limit = Math.max(1, Math.min(options.limit ?? 100, 500));
|
|
174
|
+
return getSqliteDatabase().prepare(`SELECT * FROM user_claims
|
|
175
|
+
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
176
|
+
ORDER BY confidence DESC, last_reinforced_at DESC LIMIT ?`).all(...params, limit).map(claimFromRow);
|
|
177
|
+
}
|
|
178
|
+
function listUserClaimEvidence(claimId) {
|
|
179
|
+
return getSqliteDatabase().prepare(`SELECT logical_event_key, source_item_id, source_instance_id, relation, observed_at
|
|
180
|
+
FROM user_claim_evidence WHERE claim_id = ? ORDER BY observed_at DESC`).all(claimId).map((row) => ({
|
|
181
|
+
logicalEventKey: row.logical_event_key,
|
|
182
|
+
sourceItemId: row.source_item_id,
|
|
183
|
+
sourceInstanceId: row.source_instance_id,
|
|
184
|
+
relation: row.relation,
|
|
185
|
+
observedAt: new Date(row.observed_at).toISOString()
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
function listUserPeopleGraphRows() {
|
|
189
|
+
const db = getSqliteDatabase();
|
|
190
|
+
const entities = db.prepare(`SELECT * FROM user_entities e WHERE entity_type = 'person'
|
|
191
|
+
AND EXISTS (SELECT 1 FROM user_claims c JOIN user_claim_evidence ce ON ce.claim_id = c.claim_id
|
|
192
|
+
WHERE c.subject_entity_id = e.entity_id)`).all();
|
|
193
|
+
const handles = db.prepare(`SELECT entity_id, handle_type, normalized_value FROM user_entity_handles
|
|
194
|
+
WHERE entity_id IN (SELECT entity_id FROM user_entities WHERE entity_type = 'person')`).all();
|
|
195
|
+
const byEntity = /* @__PURE__ */ new Map();
|
|
196
|
+
for (const handle of handles) {
|
|
197
|
+
const values = byEntity.get(handle.entity_id) ?? [];
|
|
198
|
+
values.push({
|
|
199
|
+
type: handle.handle_type,
|
|
200
|
+
value: handle.normalized_value
|
|
201
|
+
});
|
|
202
|
+
byEntity.set(handle.entity_id, values);
|
|
203
|
+
}
|
|
204
|
+
const edgeRows = db.prepare(`SELECT c.subject_entity_id AS entity_id, e.source_instance_id,
|
|
205
|
+
COUNT(*) AS mention_count, MAX(e.observed_at) AS last_observed_at
|
|
206
|
+
FROM user_claims c JOIN user_claim_evidence e ON e.claim_id = c.claim_id
|
|
207
|
+
WHERE c.claim_class = 'relationship' AND c.subject_entity_id IS NOT NULL AND e.relation = 'supports'
|
|
208
|
+
GROUP BY c.subject_entity_id, e.source_instance_id`).all();
|
|
209
|
+
return {
|
|
210
|
+
people: entities.map((row) => ({
|
|
211
|
+
...entityFromRow(row),
|
|
212
|
+
handles: byEntity.get(row.entity_id) ?? []
|
|
213
|
+
})),
|
|
214
|
+
edges: edgeRows.map((row) => ({
|
|
215
|
+
entityId: row.entity_id,
|
|
216
|
+
sourceInstanceId: row.source_instance_id,
|
|
217
|
+
mentionCount: row.mention_count,
|
|
218
|
+
lastObservedAt: new Date(row.last_observed_at).toISOString()
|
|
219
|
+
})),
|
|
220
|
+
evidenceCount: edgeRows.reduce((sum, row) => sum + row.mention_count, 0)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function listUserClaimStatsBySource() {
|
|
224
|
+
const rows = getSqliteDatabase().prepare(`SELECT e.source_instance_id,
|
|
225
|
+
COUNT(*) AS evidence_count,
|
|
226
|
+
COUNT(DISTINCT CASE WHEN c.state = 'provisional' THEN c.claim_id END) AS provisional_claims,
|
|
227
|
+
COUNT(DISTINCT CASE WHEN c.state = 'active' THEN c.claim_id END) AS active_claims,
|
|
228
|
+
COUNT(DISTINCT c.subject_entity_id) AS resolved_entities,
|
|
229
|
+
MAX(e.observed_at) AS last_evidence_at
|
|
230
|
+
FROM user_claim_evidence e JOIN user_claims c ON c.claim_id = e.claim_id
|
|
231
|
+
GROUP BY e.source_instance_id`).all();
|
|
232
|
+
return Object.fromEntries(rows.map((row) => [row.source_instance_id, {
|
|
233
|
+
evidenceCount: row.evidence_count,
|
|
234
|
+
provisionalClaims: row.provisional_claims,
|
|
235
|
+
activeClaims: row.active_claims,
|
|
236
|
+
resolvedEntities: row.resolved_entities,
|
|
237
|
+
...row.last_evidence_at == null ? {} : { lastEvidenceAt: new Date(row.last_evidence_at).toISOString() }
|
|
238
|
+
}]));
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
export { getUserClaim, linkUserClaimMemoryRecord, listUserClaimEvidence, listUserClaimStatsBySource, listUserClaims, listUserPeopleGraphRows, reinforceUserClaim, removeUserClaimEvidenceForSource, resolveUserEntity, setUserClaimDecision };
|