@vellumai/assistant 0.5.13 → 0.5.15
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/.env.example +1 -6
- package/AGENTS.md +4 -0
- package/ARCHITECTURE.md +0 -1
- package/bunfig.toml +1 -0
- package/docs/architecture/memory.md +3 -3
- package/openapi.yaml +127 -22
- package/package.json +1 -1
- package/src/__tests__/access-request-decision.test.ts +2 -32
- package/src/__tests__/actor-token-service.test.ts +1 -31
- package/src/__tests__/anthropic-provider.test.ts +53 -40
- package/src/__tests__/app-git-history.test.ts +9 -17
- package/src/__tests__/app-git-service.test.ts +14 -20
- package/src/__tests__/app-store-dir-names.test.ts +10 -20
- package/src/__tests__/approval-cascade.test.ts +2 -19
- package/src/__tests__/approval-primitive.test.ts +2 -27
- package/src/__tests__/approval-routes-http.test.ts +2 -30
- package/src/__tests__/assistant-events-sse-hardening.test.ts +2 -28
- package/src/__tests__/assistant-feature-flags-integration.test.ts +2 -45
- package/src/__tests__/attachments-store.test.ts +5 -32
- package/src/__tests__/audit-log-rotation.test.ts +5 -36
- package/src/__tests__/avatar-e2e.test.ts +1 -9
- package/src/__tests__/avatar-generator.test.ts +1 -7
- package/src/__tests__/browser-fill-credential.test.ts +0 -4
- package/src/__tests__/browser-manager.test.ts +0 -6
- package/src/__tests__/call-controller.test.ts +1 -22
- package/src/__tests__/call-conversation-messages.test.ts +0 -21
- package/src/__tests__/call-domain.test.ts +0 -25
- package/src/__tests__/call-pointer-messages.test.ts +0 -21
- package/src/__tests__/call-recovery.test.ts +0 -22
- package/src/__tests__/call-routes-http.test.ts +0 -24
- package/src/__tests__/call-store.test.ts +0 -21
- package/src/__tests__/cancel-resolves-conversation-key.test.ts +0 -24
- package/src/__tests__/canonical-guardian-store.test.ts +48 -21
- package/src/__tests__/channel-approval-routes.test.ts +6 -26
- package/src/__tests__/channel-approvals.test.ts +1 -38
- package/src/__tests__/channel-delivery-store.test.ts +0 -21
- package/src/__tests__/channel-guardian.test.ts +0 -26
- package/src/__tests__/channel-reply-delivery.test.ts +5 -0
- package/src/__tests__/channel-retry-sweep.test.ts +0 -21
- package/src/__tests__/checker.test.ts +26 -61
- package/src/__tests__/clawhub.test.ts +9 -25
- package/src/__tests__/cli-command-risk-guard.test.ts +0 -18
- package/src/__tests__/config-loader-backfill.test.ts +9 -28
- package/src/__tests__/config-schema-cmd.test.ts +5 -25
- package/src/__tests__/config-schema.test.ts +21 -40
- package/src/__tests__/config-watcher.test.ts +4 -91
- package/src/__tests__/confirmation-request-guardian-bridge.test.ts +0 -21
- package/src/__tests__/contacts-tools.test.ts +0 -21
- package/src/__tests__/context-memory-e2e.test.ts +0 -21
- package/src/__tests__/context-window-manager.test.ts +130 -3
- package/src/__tests__/conversation-abort-tool-results.test.ts +0 -4
- package/src/__tests__/conversation-agent-loop-overflow.test.ts +0 -4
- package/src/__tests__/conversation-agent-loop.test.ts +0 -4
- package/src/__tests__/conversation-attachments.test.ts +1 -24
- package/src/__tests__/conversation-attention-store.test.ts +0 -21
- package/src/__tests__/conversation-attention-telegram.test.ts +0 -22
- package/src/__tests__/conversation-clear-safety.test.ts +0 -22
- package/src/__tests__/conversation-confirmation-signals.test.ts +2 -21
- package/src/__tests__/conversation-delete-schedule-cleanup.test.ts +0 -24
- package/src/__tests__/conversation-disk-view-integration.test.ts +1 -23
- package/src/__tests__/conversation-disk-view.test.ts +5 -27
- package/src/__tests__/conversation-error.test.ts +1 -1
- package/src/__tests__/conversation-fork-crud.test.ts +1 -33
- package/src/__tests__/conversation-fork-route.test.ts +0 -27
- package/src/__tests__/conversation-history-web-search.test.ts +23 -16
- package/src/__tests__/conversation-init.benchmark.test.ts +22 -43
- package/src/__tests__/conversation-key-store-disk-view.test.ts +8 -34
- package/src/__tests__/conversation-load-history-repair.test.ts +0 -4
- package/src/__tests__/conversation-pre-run-repair.test.ts +0 -4
- package/src/__tests__/conversation-provider-retry-repair.test.ts +0 -4
- package/src/__tests__/conversation-queue.test.ts +8 -8
- package/src/__tests__/conversation-routes-disk-view.test.ts +13 -51
- package/src/__tests__/conversation-runtime-assembly.test.ts +64 -38
- package/src/__tests__/conversation-slash-commands.test.ts +5 -0
- package/src/__tests__/conversation-slash-queue.test.ts +0 -4
- package/src/__tests__/conversation-slash-unknown.test.ts +0 -4
- package/src/__tests__/conversation-speed-override.test.ts +326 -0
- package/src/__tests__/conversation-starter-routes.test.ts +0 -23
- package/src/__tests__/conversation-store.test.ts +0 -21
- package/src/__tests__/conversation-unread-route.test.ts +0 -24
- package/src/__tests__/conversation-usage.test.ts +56 -21
- package/src/__tests__/conversation-wipe.test.ts +0 -21
- package/src/__tests__/conversation-workspace-cache-state.test.ts +0 -4
- package/src/__tests__/conversation-workspace-injection.test.ts +0 -4
- package/src/__tests__/conversation-workspace-tool-tracking.test.ts +0 -4
- package/src/__tests__/credential-execution-shell-lockdown.test.ts +8 -5
- package/src/__tests__/credential-vault-unit.test.ts +9 -428
- package/src/__tests__/credentials-cli.test.ts +10 -10
- package/src/__tests__/daemon-assistant-events.test.ts +0 -19
- package/src/__tests__/date-context.test.ts +77 -97
- package/src/__tests__/db-conversation-fork-lineage-migration.test.ts +7 -24
- package/src/__tests__/db-llm-request-log-provider-migration.test.ts +29 -42
- package/src/__tests__/delete-managed-skill-tool.test.ts +2 -10
- package/src/__tests__/deterministic-verification-control-plane.test.ts +1 -26
- package/src/__tests__/docker-signing-key-bootstrap.test.ts +61 -15
- package/src/__tests__/dynamic-skill-workflow-prompt.test.ts +2 -36
- package/src/__tests__/email-cli.test.ts +6 -6
- package/src/__tests__/ephemeral-permissions.test.ts +5 -17
- package/src/__tests__/first-greeting.test.ts +4 -32
- package/src/__tests__/followup-tools.test.ts +0 -21
- package/src/__tests__/gateway-only-enforcement.test.ts +0 -20
- package/src/__tests__/guardian-action-conversation-turn.test.ts +0 -23
- package/src/__tests__/guardian-action-followup-executor.test.ts +0 -23
- package/src/__tests__/guardian-action-followup-store.test.ts +0 -21
- package/src/__tests__/guardian-action-grant-mint-consume.test.ts +0 -21
- package/src/__tests__/guardian-action-late-reply.test.ts +0 -21
- package/src/__tests__/guardian-action-store.test.ts +0 -21
- package/src/__tests__/guardian-action-sweep.test.ts +0 -21
- package/src/__tests__/guardian-binding-drift-heal.test.ts +0 -23
- package/src/__tests__/guardian-decision-primitive-canonical.test.ts +172 -22
- package/src/__tests__/guardian-dispatch.test.ts +0 -21
- package/src/__tests__/guardian-grant-minting.test.ts +0 -22
- package/src/__tests__/guardian-outbound-http.test.ts +0 -22
- package/src/__tests__/guardian-principal-id-roundtrip.test.ts +0 -23
- package/src/__tests__/guardian-routing-invariants.test.ts +0 -22
- package/src/__tests__/guardian-routing-state.test.ts +0 -22
- package/src/__tests__/guardian-verification-voice-binding.test.ts +0 -24
- package/src/__tests__/headless-browser-interactions.test.ts +0 -4
- package/src/__tests__/headless-browser-navigate.test.ts +0 -4
- package/src/__tests__/headless-browser-read-tools.test.ts +0 -4
- package/src/__tests__/headless-browser-snapshot.test.ts +0 -4
- package/src/__tests__/heartbeat-service.test.ts +99 -26
- package/src/__tests__/hooks-blocking.test.ts +3 -3
- package/src/__tests__/hooks-config.test.ts +7 -7
- package/src/__tests__/hooks-discovery.test.ts +3 -3
- package/src/__tests__/hooks-integration.test.ts +5 -5
- package/src/__tests__/hooks-manager.test.ts +3 -3
- package/src/__tests__/hooks-runner.test.ts +5 -23
- package/src/__tests__/hooks-settings.test.ts +3 -3
- package/src/__tests__/hooks-templates.test.ts +3 -3
- package/src/__tests__/http-conversation-lineage.test.ts +0 -27
- package/src/__tests__/identity-intro-cache.test.ts +0 -4
- package/src/__tests__/inbound-invite-redemption.test.ts +0 -22
- package/src/__tests__/inline-skill-load-permissions.test.ts +5 -16
- package/src/__tests__/intent-routing.test.ts +2 -55
- package/src/__tests__/invite-redemption-service.test.ts +0 -21
- package/src/__tests__/invite-routes-http.test.ts +0 -21
- package/src/__tests__/jobs-store-qdrant-breaker.test.ts +0 -17
- package/src/__tests__/journal-context.test.ts +8 -75
- package/src/__tests__/list-messages-attachments.test.ts +0 -22
- package/src/__tests__/llm-context-route-provider.test.ts +0 -21
- package/src/__tests__/llm-request-log-turn-query.test.ts +46 -28
- package/src/__tests__/llm-usage-store.test.ts +0 -21
- package/src/__tests__/log-export-workspace.test.ts +1 -1
- package/src/__tests__/managed-skill-lifecycle.test.ts +1 -1
- package/src/__tests__/managed-store.test.ts +1 -1
- package/src/__tests__/mcp-cli.test.ts +7 -10
- package/src/__tests__/memory-context-benchmark.benchmark.test.ts +0 -21
- package/src/__tests__/memory-jobs-worker-backoff.test.ts +0 -11
- package/src/__tests__/memory-lifecycle-e2e.test.ts +0 -21
- package/src/__tests__/memory-recall-log-store.test.ts +0 -27
- package/src/__tests__/memory-recall-quality.test.ts +0 -21
- package/src/__tests__/memory-regressions.experimental.test.ts +31 -30
- package/src/__tests__/memory-regressions.test.ts +282 -70
- package/src/__tests__/memory-retrieval.benchmark.test.ts +0 -21
- package/src/__tests__/memory-upsert-concurrency.test.ts +0 -21
- package/src/__tests__/messaging-send-tool.test.ts +201 -0
- package/src/__tests__/migration-cross-version-compatibility.test.ts +18 -13
- package/src/__tests__/migration-export-http.test.ts +7 -1
- package/src/__tests__/migration-import-commit-http.test.ts +16 -14
- package/src/__tests__/migration-import-preflight-http.test.ts +27 -44
- package/src/__tests__/migration-validate-http.test.ts +1 -28
- package/src/__tests__/native-web-search.test.ts +25 -22
- package/src/__tests__/non-member-access-request.test.ts +0 -22
- package/src/__tests__/notification-guardian-path.test.ts +0 -21
- package/src/__tests__/notification-schedule-dedup.test.ts +1 -25
- package/src/__tests__/oauth-apps-routes.test.ts +103 -2
- package/src/__tests__/oauth-cli.test.ts +52 -0
- package/src/__tests__/oauth-provider-profiles.test.ts +0 -16
- package/src/__tests__/oauth-provider-serializer.test.ts +232 -0
- package/src/__tests__/oauth-providers-routes.test.ts +257 -0
- package/src/__tests__/oauth-store.test.ts +0 -21
- package/src/__tests__/onboarding-template-contract.test.ts +2 -2
- package/src/__tests__/openai-provider.test.ts +261 -0
- package/src/__tests__/pairing-concurrent.test.ts +6 -6
- package/src/__tests__/pairing-routes.test.ts +7 -1
- package/src/__tests__/path-policy.test.ts +1 -1
- package/src/__tests__/platform.test.ts +64 -88
- package/src/__tests__/playbook-execution.test.ts +0 -21
- package/src/__tests__/playbook-tools.test.ts +0 -21
- package/src/__tests__/pricing.test.ts +100 -0
- package/src/__tests__/relay-server.test.ts +1 -25
- package/src/__tests__/runtime-attachment-metadata.test.ts +0 -24
- package/src/__tests__/runtime-events-sse-parity.test.ts +2 -24
- package/src/__tests__/runtime-events-sse.test.ts +0 -24
- package/src/__tests__/sandbox-diagnostics.test.ts +2 -1
- package/src/__tests__/scaffold-managed-skill-tool.test.ts +1 -1
- package/src/__tests__/schedule-store.test.ts +0 -21
- package/src/__tests__/schedule-tools.test.ts +0 -21
- package/src/__tests__/scheduler-recurrence.test.ts +0 -21
- package/src/__tests__/scoped-approval-grants.test.ts +0 -21
- package/src/__tests__/scoped-grant-security-matrix.test.ts +0 -21
- package/src/__tests__/secret-allowlist.test.ts +1 -1
- package/src/__tests__/secret-ingress-channel.test.ts +0 -5
- package/src/__tests__/secret-ingress-cli.test.ts +0 -6
- package/src/__tests__/secret-ingress-http.test.ts +0 -5
- package/src/__tests__/secret-ingress.test.ts +0 -5
- package/src/__tests__/send-endpoint-busy.test.ts +0 -24
- package/src/__tests__/sequence-store.test.ts +0 -21
- package/src/__tests__/server-history-render.test.ts +0 -24
- package/src/__tests__/shell-tool-proxy-mode.test.ts +0 -4
- package/src/__tests__/skill-load-inline-command.test.ts +9 -0
- package/src/__tests__/skill-load-inline-includes.test.ts +9 -0
- package/src/__tests__/skill-load-tool.test.ts +11 -0
- package/src/__tests__/skills-uninstall.test.ts +10 -8
- package/src/__tests__/skills.test.ts +1 -1
- package/src/__tests__/slack-channel-config.test.ts +1 -1
- package/src/__tests__/slack-inbound-verification.test.ts +0 -22
- package/src/__tests__/starter-bundle.test.ts +4 -1
- package/src/__tests__/suggestion-routes.test.ts +2 -0
- package/src/__tests__/system-prompt.test.ts +1 -1
- package/src/__tests__/terminal-tools.test.ts +1 -1
- package/src/__tests__/test-preload.ts +31 -0
- package/src/__tests__/tool-execution-abort-cleanup.test.ts +1 -1
- package/src/__tests__/tool-execution-pipeline.benchmark.test.ts +1 -1
- package/src/__tests__/tool-executor.test.ts +0 -20
- package/src/__tests__/tool-input-summary.test.ts +124 -0
- package/src/__tests__/tool-preview-lifecycle.test.ts +2 -1
- package/src/__tests__/trust-store.test.ts +7 -1
- package/src/__tests__/trusted-contact-inline-approval-integration.test.ts +1 -1
- package/src/__tests__/trusted-contact-lifecycle-notifications.test.ts +1 -1
- package/src/__tests__/trusted-contact-multichannel.test.ts +1 -1
- package/src/__tests__/trusted-contact-verification.test.ts +1 -1
- package/src/__tests__/turn-boundary-resolution.test.ts +1 -1
- package/src/__tests__/twilio-routes.test.ts +1 -1
- package/src/__tests__/update-bulletin.test.ts +1 -1
- package/src/__tests__/vbundle-pax-and-symlink.test.ts +1 -1
- package/src/__tests__/vellum-self-knowledge-inline-command.test.ts +1 -0
- package/src/__tests__/voice-scoped-grant-consumer.test.ts +1 -1
- package/src/__tests__/voice-session-bridge.test.ts +1 -1
- package/src/__tests__/workspace-migration-009-backfill-conversation-disk-view.test.ts +4 -4
- package/src/__tests__/workspace-migration-013-repair-conversation-disk-view.test.ts +1 -1
- package/src/__tests__/workspace-migration-down-functions.test.ts +15 -3
- package/src/__tests__/workspace-migration-seed-device-id.test.ts +40 -4
- package/src/agent/loop.ts +6 -9
- package/src/approvals/guardian-decision-primitive.ts +46 -18
- package/src/approvals/guardian-request-resolvers.ts +19 -2
- package/src/calls/active-call-lease.ts +2 -2
- package/src/cli/AGENTS.md +1 -1
- package/src/cli/commands/doctor.ts +9 -9
- package/src/cli/commands/memory.ts +142 -0
- package/src/cli/commands/oauth/__tests__/connect.test.ts +13 -11
- package/src/cli/commands/oauth/__tests__/ping.test.ts +1 -1
- package/src/cli/commands/oauth/connect.ts +13 -12
- package/src/cli/commands/oauth/index.ts +1 -1
- package/src/cli/commands/oauth/providers.ts +47 -62
- package/src/cli/commands/platform/__tests__/connect.test.ts +72 -46
- package/src/cli/commands/platform/__tests__/disconnect.test.ts +54 -1
- package/src/cli/commands/platform/__tests__/status.test.ts +36 -0
- package/src/cli/commands/platform/connect.ts +17 -7
- package/src/cli/commands/platform/disconnect.ts +28 -3
- package/src/cli/commands/platform/index.ts +3 -3
- package/src/cli.ts +1 -299
- package/src/config/assistant-feature-flags.ts +23 -15
- package/src/config/bundled-skills/app-builder/TOOLS.json +16 -0
- package/src/config/bundled-skills/app-builder/tools/app-create.ts +4 -0
- package/src/config/bundled-skills/app-builder/tools/app-delete.ts +5 -1
- package/src/config/bundled-skills/app-builder/tools/app-generate-icon.ts +9 -1
- package/src/config/bundled-skills/app-builder/tools/app-refresh.ts +5 -1
- package/src/config/bundled-skills/contacts/TOOLS.json +8 -0
- package/src/config/bundled-skills/contacts/tools/contact-search.ts +10 -1
- package/src/config/bundled-skills/contacts/tools/contact-upsert.ts +16 -2
- package/src/config/bundled-skills/media-processing/tools/ingest-media.ts +1 -0
- package/src/config/bundled-skills/messaging/SKILL.md +7 -7
- package/src/config/bundled-skills/messaging/tools/messaging-send.ts +37 -0
- package/src/config/bundled-skills/slack/SKILL.md +18 -0
- package/src/config/env-registry.ts +15 -11
- package/src/config/env.ts +1 -11
- package/src/config/feature-flag-registry.json +16 -0
- package/src/config/schema.ts +4 -0
- package/src/config/schemas/heartbeat.ts +6 -1
- package/src/config/schemas/inference.ts +14 -3
- package/src/config/schemas/memory-processing.ts +16 -8
- package/src/config/schemas/memory-retrieval.ts +3 -3
- package/src/config/skills.ts +1 -1
- package/src/context/window-manager.ts +174 -51
- package/src/credential-execution/executable-discovery.ts +2 -2
- package/src/daemon/approved-devices-store.ts +2 -2
- package/src/daemon/assistant-attachments.ts +2 -0
- package/src/daemon/config-watcher.ts +4 -50
- package/src/daemon/conversation-agent-loop-handlers.ts +9 -1
- package/src/daemon/conversation-agent-loop.ts +12 -0
- package/src/daemon/conversation-error.ts +3 -5
- package/src/daemon/conversation-history.ts +7 -3
- package/src/daemon/conversation-lifecycle.ts +16 -0
- package/src/daemon/conversation-messaging.ts +1 -0
- package/src/daemon/conversation-notifiers.ts +67 -30
- package/src/daemon/conversation-process.ts +161 -2
- package/src/daemon/conversation-queue-manager.ts +2 -0
- package/src/daemon/conversation-runtime-assembly.ts +33 -11
- package/src/daemon/conversation-slash.ts +14 -3
- package/src/daemon/conversation-tool-setup.ts +2 -0
- package/src/daemon/conversation-usage.ts +32 -4
- package/src/daemon/conversation.ts +33 -1
- package/src/daemon/daemon-control.ts +32 -16
- package/src/daemon/date-context.ts +47 -45
- package/src/daemon/dictation-profile-store.ts +2 -2
- package/src/daemon/handlers/conversations.ts +19 -0
- package/src/daemon/handlers/shared.ts +14 -21
- package/src/daemon/lifecycle.ts +5 -7
- package/src/daemon/message-types/conversations.ts +2 -0
- package/src/daemon/message-types/guardian-actions.ts +3 -17
- package/src/daemon/message-types/integrations.ts +11 -1
- package/src/daemon/message-types/messages.ts +1 -0
- package/src/daemon/pairing-store.ts +2 -79
- package/src/daemon/server.ts +154 -8
- package/src/daemon/watch-handler.ts +65 -21
- package/src/email/guardrails.ts +3 -3
- package/src/heartbeat/heartbeat-service.ts +14 -7
- package/src/hooks/cli.ts +2 -2
- package/src/hooks/config.ts +2 -2
- package/src/hooks/discovery.ts +2 -2
- package/src/hooks/manager.ts +2 -2
- package/src/hooks/runner.ts +5 -2
- package/src/hooks/templates.ts +2 -2
- package/src/memory/admin.ts +181 -2
- package/src/memory/app-git-service.ts +61 -4
- package/src/memory/attachments-store.ts +2 -0
- package/src/memory/canonical-guardian-store.ts +16 -0
- package/src/memory/db-init.ts +8 -0
- package/src/memory/embedding-local.ts +5 -2
- package/src/memory/indexer.ts +44 -26
- package/src/memory/items-extractor.ts +34 -82
- package/src/memory/job-handlers/batch-extraction.ts +741 -0
- package/src/memory/job-handlers/journal-carry-forward.test.ts +383 -0
- package/src/memory/job-handlers/journal-carry-forward.ts +255 -0
- package/src/memory/jobs-store.ts +28 -0
- package/src/memory/jobs-worker.ts +56 -9
- package/src/memory/lifecycle-events-store.ts +4 -2
- package/src/memory/llm-request-log-store.ts +40 -2
- package/src/memory/llm-usage-store.ts +4 -3
- package/src/memory/migrations/199-guardian-request-enrichment-columns.ts +71 -0
- package/src/memory/migrations/200-usage-llm-call-count.ts +20 -0
- package/src/memory/migrations/index.ts +2 -0
- package/src/memory/query-expansion.ts +83 -0
- package/src/memory/retriever.test.ts +119 -0
- package/src/memory/retriever.ts +513 -105
- package/src/memory/schema/guardian.ts +4 -0
- package/src/memory/schema/infrastructure.ts +1 -0
- package/src/memory/search/formatting.test.ts +140 -0
- package/src/memory/search/formatting.ts +143 -198
- package/src/memory/search/mmr.ts +136 -0
- package/src/memory/search/staleness.ts +0 -15
- package/src/memory/search/tier-classifier.ts +10 -21
- package/src/memory/search/types.ts +17 -0
- package/src/messaging/providers/slack/adapter.ts +51 -5
- package/src/notifications/broadcaster.ts +13 -0
- package/src/notifications/copy-composer.ts +8 -0
- package/src/oauth/connect-orchestrator.ts +1 -1
- package/src/oauth/connection-resolver.ts +2 -2
- package/src/oauth/provider-serializer.ts +116 -0
- package/src/permissions/trust-store.ts +24 -7
- package/src/prompts/__tests__/build-cli-reference-section.test.ts +5 -0
- package/src/prompts/journal-context.ts +50 -35
- package/src/prompts/persona-resolver.ts +1 -1
- package/src/prompts/system-prompt.ts +27 -28
- package/src/prompts/templates/BOOTSTRAP.md +14 -1
- package/src/prompts/templates/HEARTBEAT.md +10 -0
- package/src/prompts/templates/NOW.md +19 -25
- package/src/prompts/templates/SOUL.md +13 -1
- package/src/prompts/templates/UPDATES.md +12 -0
- package/src/prompts/update-bulletin.ts +1 -1
- package/src/providers/anthropic/client.ts +89 -18
- package/src/providers/model-catalog.ts +22 -2
- package/src/providers/model-intents.ts +2 -2
- package/src/providers/openai/client.ts +40 -1
- package/src/providers/retry.ts +23 -4
- package/src/providers/types.ts +2 -0
- package/src/runtime/assistant-scope.ts +1 -1
- package/src/runtime/auth/__tests__/credential-service.test.ts +1 -0
- package/src/runtime/auth/route-policy.ts +1 -0
- package/src/runtime/auth/token-service.ts +51 -29
- package/src/runtime/confirmation-request-guardian-bridge.ts +3 -1
- package/src/runtime/guardian-decision-types.ts +16 -10
- package/src/runtime/http-server.ts +3 -14
- package/src/runtime/http-types.ts +1 -0
- package/src/runtime/migrations/vbundle-builder.ts +7 -4
- package/src/runtime/migrations/vbundle-import-analyzer.ts +0 -4
- package/src/runtime/migrations/vbundle-importer.ts +1 -1
- package/src/runtime/routes/conversation-query-routes.ts +40 -8
- package/src/runtime/routes/conversation-routes.ts +125 -3
- package/src/runtime/routes/guardian-action-routes.ts +9 -3
- package/src/runtime/routes/identity-routes.ts +25 -4
- package/src/runtime/routes/llm-context-normalization.ts +1 -0
- package/src/runtime/routes/log-export-routes.ts +34 -12
- package/src/runtime/routes/migration-routes.ts +6 -10
- package/src/runtime/routes/oauth-apps.ts +2 -9
- package/src/runtime/routes/oauth-providers.ts +60 -0
- package/src/runtime/routes/pairing-routes.ts +0 -8
- package/src/runtime/routes/settings-routes.ts +0 -1
- package/src/runtime/routes/telemetry-routes.ts +16 -4
- package/src/security/encrypted-store.ts +2 -2
- package/src/security/secret-allowlist.ts +3 -3
- package/src/signals/emit-event.ts +42 -0
- package/src/signals/user-message.ts +37 -0
- package/src/telemetry/usage-telemetry-reporter.test.ts +83 -19
- package/src/telemetry/usage-telemetry-reporter.ts +23 -17
- package/src/tools/browser/runtime-check.ts +2 -2
- package/src/tools/credentials/vault.ts +2 -249
- package/src/tools/memory/definitions.ts +1 -1
- package/src/tools/memory/handlers.test.ts +50 -8
- package/src/tools/memory/handlers.ts +3 -1
- package/src/tools/side-effects.ts +1 -6
- package/src/tools/terminal/safe-env.ts +3 -2
- package/src/tools/terminal/shell.ts +11 -14
- package/src/tools/tool-approval-handler.ts +20 -1
- package/src/tools/tool-input-summary.ts +66 -0
- package/src/tools/types.ts +4 -0
- package/src/usage/types.ts +4 -0
- package/src/util/device-id.ts +10 -10
- package/src/util/platform.ts +71 -33
- package/src/util/pricing.ts +19 -6
- package/src/util/strip-comment-lines.ts +28 -0
- package/src/workspace/git-service.ts +8 -18
- package/src/workspace/migrations/003-seed-device-id.ts +6 -4
- package/src/workspace/migrations/016-extract-feature-flags-to-protected.ts +7 -1
- package/src/workspace/migrations/017-seed-persona-dirs.ts +2 -4
- package/src/workspace/migrations/021-move-signals-to-workspace.ts +84 -0
- package/src/workspace/migrations/022-move-hooks-to-workspace.ts +94 -0
- package/src/workspace/migrations/023-move-config-files-to-workspace.ts +86 -0
- package/src/workspace/migrations/024-move-runtime-files-to-workspace.ts +126 -0
- package/src/workspace/migrations/migrate-to-workspace-volume.ts +3 -6
- package/src/workspace/migrations/registry.ts +8 -0
- package/src/signals/confirm.ts +0 -82
- package/src/signals/trust-rule.ts +0 -174
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
import { and, asc, desc, eq, gt, or, sql } from "drizzle-orm";
|
|
2
|
+
import { v4 as uuid } from "uuid";
|
|
3
|
+
|
|
4
|
+
import { estimateTextTokens } from "../../context/token-estimator.js";
|
|
5
|
+
import { getAssistantName } from "../../daemon/identity-helpers.js";
|
|
6
|
+
import { resolveGuardianPersona } from "../../prompts/persona-resolver.js";
|
|
7
|
+
import {
|
|
8
|
+
extractToolUse,
|
|
9
|
+
getConfiguredProvider,
|
|
10
|
+
userMessage,
|
|
11
|
+
} from "../../providers/provider-send-message.js";
|
|
12
|
+
import { BackendUnavailableError, ProviderError } from "../../util/errors.js";
|
|
13
|
+
import { getLogger } from "../../util/logger.js";
|
|
14
|
+
import {
|
|
15
|
+
getMemoryCheckpoint,
|
|
16
|
+
setMemoryCheckpoint,
|
|
17
|
+
} from "../checkpoints.js";
|
|
18
|
+
import { getConversationMemoryScopeId } from "../conversation-crud.js";
|
|
19
|
+
import { getDb } from "../db.js";
|
|
20
|
+
import { computeMemoryFingerprint } from "../fingerprint.js";
|
|
21
|
+
import {
|
|
22
|
+
buildExtractionSystemPrompt,
|
|
23
|
+
deduplicateItems,
|
|
24
|
+
type ExtractedItem,
|
|
25
|
+
EXTRACTION_KINDS,
|
|
26
|
+
KIND_MIGRATION_MAP,
|
|
27
|
+
type MemoryItemKind,
|
|
28
|
+
type OverrideConfidence,
|
|
29
|
+
parseScore,
|
|
30
|
+
SUPERSEDE_KINDS,
|
|
31
|
+
VALID_KINDS,
|
|
32
|
+
VALID_OVERRIDE_CONFIDENCES,
|
|
33
|
+
} from "../items-extractor.js";
|
|
34
|
+
import { asString } from "../job-utils.js";
|
|
35
|
+
import { enqueueMemoryJob, type MemoryJob } from "../jobs-store.js";
|
|
36
|
+
import { extractTextFromStoredMessageContent } from "../message-content.js";
|
|
37
|
+
import { withQdrantBreaker } from "../qdrant-circuit-breaker.js";
|
|
38
|
+
import { getQdrantClient } from "../qdrant-client.js";
|
|
39
|
+
import {
|
|
40
|
+
memoryItems,
|
|
41
|
+
memoryItemSources,
|
|
42
|
+
memorySummaries,
|
|
43
|
+
messages,
|
|
44
|
+
} from "../schema.js";
|
|
45
|
+
import { isConversationFailed } from "../task-memory-cleanup.js";
|
|
46
|
+
import { clampUnitInterval } from "../validation.js";
|
|
47
|
+
|
|
48
|
+
const log = getLogger("memory-batch-extraction");
|
|
49
|
+
|
|
50
|
+
interface LLMBatchExtractedItem {
|
|
51
|
+
kind: string;
|
|
52
|
+
subject: string;
|
|
53
|
+
statement: string;
|
|
54
|
+
confidence: number;
|
|
55
|
+
importance: number;
|
|
56
|
+
supersedes: string | null;
|
|
57
|
+
overrideConfidence: string;
|
|
58
|
+
source_role?: "user" | "assistant";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface BatchExtractResult {
|
|
62
|
+
items: LLMBatchExtractedItem[];
|
|
63
|
+
extraction_summary: string;
|
|
64
|
+
conversation_summary: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function batchExtractJob(job: MemoryJob): Promise<void> {
|
|
68
|
+
const conversationId = asString(job.payload.conversationId);
|
|
69
|
+
const payloadScopeId = asString(job.payload.scopeId);
|
|
70
|
+
if (!conversationId) return;
|
|
71
|
+
|
|
72
|
+
// If the conversation has been marked as failed, skip extraction entirely.
|
|
73
|
+
if (isConversationFailed(conversationId)) {
|
|
74
|
+
log.info(
|
|
75
|
+
{ conversationId },
|
|
76
|
+
"Skipping batch extraction for failed conversation",
|
|
77
|
+
);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const db = getDb();
|
|
82
|
+
|
|
83
|
+
// Resolve scopeId: prefer payload, fall back to conversation's stored scope
|
|
84
|
+
const scopeId =
|
|
85
|
+
payloadScopeId ?? getConversationMemoryScopeId(conversationId);
|
|
86
|
+
|
|
87
|
+
// ── Load unextracted messages ────────────────────────────────────────
|
|
88
|
+
const lastMessageIdKey = `batch_extract:${conversationId}:last_message_id`;
|
|
89
|
+
const lastExtractedMessageId = getMemoryCheckpoint(lastMessageIdKey);
|
|
90
|
+
|
|
91
|
+
let unextractedMessages: Array<{
|
|
92
|
+
id: string;
|
|
93
|
+
role: string;
|
|
94
|
+
content: string;
|
|
95
|
+
createdAt: number;
|
|
96
|
+
}>;
|
|
97
|
+
|
|
98
|
+
if (lastExtractedMessageId) {
|
|
99
|
+
// Get the createdAt of the last extracted message so we can find messages after it
|
|
100
|
+
const lastMsg = db
|
|
101
|
+
.select({ id: messages.id, createdAt: messages.createdAt })
|
|
102
|
+
.from(messages)
|
|
103
|
+
.where(eq(messages.id, lastExtractedMessageId))
|
|
104
|
+
.get();
|
|
105
|
+
|
|
106
|
+
if (lastMsg) {
|
|
107
|
+
// Compound cursor: createdAt > X OR (createdAt = X AND id > Y)
|
|
108
|
+
// Avoids skipping messages that share the same timestamp as the checkpoint
|
|
109
|
+
unextractedMessages = db
|
|
110
|
+
.select({
|
|
111
|
+
id: messages.id,
|
|
112
|
+
role: messages.role,
|
|
113
|
+
content: messages.content,
|
|
114
|
+
createdAt: messages.createdAt,
|
|
115
|
+
})
|
|
116
|
+
.from(messages)
|
|
117
|
+
.where(
|
|
118
|
+
and(
|
|
119
|
+
eq(messages.conversationId, conversationId),
|
|
120
|
+
or(
|
|
121
|
+
gt(messages.createdAt, lastMsg.createdAt),
|
|
122
|
+
and(
|
|
123
|
+
eq(messages.createdAt, lastMsg.createdAt),
|
|
124
|
+
gt(messages.id, lastMsg.id),
|
|
125
|
+
),
|
|
126
|
+
),
|
|
127
|
+
),
|
|
128
|
+
)
|
|
129
|
+
.orderBy(asc(messages.createdAt), asc(messages.id))
|
|
130
|
+
.all();
|
|
131
|
+
} else {
|
|
132
|
+
// Checkpoint references a deleted message — fetch all
|
|
133
|
+
unextractedMessages = db
|
|
134
|
+
.select({
|
|
135
|
+
id: messages.id,
|
|
136
|
+
role: messages.role,
|
|
137
|
+
content: messages.content,
|
|
138
|
+
createdAt: messages.createdAt,
|
|
139
|
+
})
|
|
140
|
+
.from(messages)
|
|
141
|
+
.where(eq(messages.conversationId, conversationId))
|
|
142
|
+
.orderBy(asc(messages.createdAt), asc(messages.id))
|
|
143
|
+
.all();
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
// No checkpoint — process all messages in the conversation
|
|
147
|
+
unextractedMessages = db
|
|
148
|
+
.select({
|
|
149
|
+
id: messages.id,
|
|
150
|
+
role: messages.role,
|
|
151
|
+
content: messages.content,
|
|
152
|
+
createdAt: messages.createdAt,
|
|
153
|
+
})
|
|
154
|
+
.from(messages)
|
|
155
|
+
.where(eq(messages.conversationId, conversationId))
|
|
156
|
+
.orderBy(asc(messages.createdAt), asc(messages.id))
|
|
157
|
+
.all();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (unextractedMessages.length === 0) {
|
|
161
|
+
log.debug({ conversationId }, "No unextracted messages for batch extraction");
|
|
162
|
+
// Reset pending count since there's nothing to extract
|
|
163
|
+
setMemoryCheckpoint(
|
|
164
|
+
`batch_extract:${conversationId}:pending_count`,
|
|
165
|
+
"0",
|
|
166
|
+
);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ── Load running extraction summary ─────────────────────────────────
|
|
171
|
+
const existingExtractionSummary = db
|
|
172
|
+
.select({ summary: memorySummaries.summary })
|
|
173
|
+
.from(memorySummaries)
|
|
174
|
+
.where(
|
|
175
|
+
and(
|
|
176
|
+
eq(memorySummaries.scope, "extraction_context"),
|
|
177
|
+
eq(memorySummaries.scopeKey, conversationId),
|
|
178
|
+
),
|
|
179
|
+
)
|
|
180
|
+
.get();
|
|
181
|
+
|
|
182
|
+
// ── Load existing global items for supersession ─────────────────────
|
|
183
|
+
// When fullReextract is set (re-extraction pass), load all active items
|
|
184
|
+
// so the LLM can supersede as many old flat-fact memories as possible.
|
|
185
|
+
const fullReextract = Boolean(job.payload.fullReextract);
|
|
186
|
+
const existingItemsLimit = fullReextract ? 200 : 20;
|
|
187
|
+
|
|
188
|
+
const existingItems = db
|
|
189
|
+
.select({
|
|
190
|
+
id: memoryItems.id,
|
|
191
|
+
kind: memoryItems.kind,
|
|
192
|
+
subject: memoryItems.subject,
|
|
193
|
+
statement: memoryItems.statement,
|
|
194
|
+
})
|
|
195
|
+
.from(memoryItems)
|
|
196
|
+
.where(
|
|
197
|
+
and(
|
|
198
|
+
eq(memoryItems.scopeId, scopeId),
|
|
199
|
+
eq(memoryItems.status, "active"),
|
|
200
|
+
),
|
|
201
|
+
)
|
|
202
|
+
.orderBy(desc(memoryItems.lastSeenAt))
|
|
203
|
+
.limit(existingItemsLimit)
|
|
204
|
+
.all();
|
|
205
|
+
|
|
206
|
+
// ── Build the batch extraction prompt ───────────────────────────────
|
|
207
|
+
const userPersona = resolveGuardianPersona();
|
|
208
|
+
const baseSystemPrompt = buildExtractionSystemPrompt(
|
|
209
|
+
existingItems,
|
|
210
|
+
"user", // batch processes both roles
|
|
211
|
+
userPersona,
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
let systemPrompt = baseSystemPrompt;
|
|
215
|
+
systemPrompt += `\n\nIMPORTANT: You are processing a batch of messages from a single conversation window, not individual messages. Extract items from the entire batch — look for cross-message patterns, evolving themes, and composite facts that only emerge from reading multiple messages together.`;
|
|
216
|
+
|
|
217
|
+
if (existingExtractionSummary?.summary) {
|
|
218
|
+
systemPrompt += `\n\nPreviously extracted from this conversation:\n${existingExtractionSummary.summary}`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ── Build user message from unextracted messages ────────────────────
|
|
222
|
+
const assistantName = getAssistantName() ?? "the assistant";
|
|
223
|
+
const messageParts: string[] = [];
|
|
224
|
+
for (const msg of unextractedMessages) {
|
|
225
|
+
const text = extractTextFromStoredMessageContent(msg.content);
|
|
226
|
+
if (text.length === 0) continue;
|
|
227
|
+
const roleLabel = msg.role === "assistant" ? assistantName : "user";
|
|
228
|
+
const timestamp = new Date(msg.createdAt).toISOString();
|
|
229
|
+
messageParts.push(`[${timestamp}] [${roleLabel}]: ${text}`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (messageParts.length === 0) {
|
|
233
|
+
log.debug(
|
|
234
|
+
{ conversationId },
|
|
235
|
+
"All unextracted messages have empty text content",
|
|
236
|
+
);
|
|
237
|
+
setMemoryCheckpoint(
|
|
238
|
+
`batch_extract:${conversationId}:pending_count`,
|
|
239
|
+
"0",
|
|
240
|
+
);
|
|
241
|
+
// Still update the last message ID checkpoint
|
|
242
|
+
const lastMsg = unextractedMessages[unextractedMessages.length - 1];
|
|
243
|
+
setMemoryCheckpoint(lastMessageIdKey, lastMsg.id);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const userContent = messageParts.join("\n\n");
|
|
248
|
+
|
|
249
|
+
// ── Call LLM ────────────────────────────────────────────────────────
|
|
250
|
+
const provider = await getConfiguredProvider();
|
|
251
|
+
if (!provider) {
|
|
252
|
+
throw new BackendUnavailableError(
|
|
253
|
+
"Provider unavailable for batch memory extraction",
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const response = await provider.sendMessage(
|
|
258
|
+
[userMessage(userContent)],
|
|
259
|
+
[
|
|
260
|
+
{
|
|
261
|
+
name: "batch_extract_results",
|
|
262
|
+
description:
|
|
263
|
+
"Store extracted memory items and summaries from the conversation batch",
|
|
264
|
+
input_schema: {
|
|
265
|
+
type: "object" as const,
|
|
266
|
+
properties: {
|
|
267
|
+
items: {
|
|
268
|
+
type: "array",
|
|
269
|
+
items: {
|
|
270
|
+
type: "object",
|
|
271
|
+
properties: {
|
|
272
|
+
kind: {
|
|
273
|
+
type: "string",
|
|
274
|
+
enum: EXTRACTION_KINDS,
|
|
275
|
+
description: "Category of memory item",
|
|
276
|
+
},
|
|
277
|
+
subject: {
|
|
278
|
+
type: "string",
|
|
279
|
+
description:
|
|
280
|
+
"Short label (2-8 words) for what this is about",
|
|
281
|
+
},
|
|
282
|
+
statement: {
|
|
283
|
+
type: "string",
|
|
284
|
+
description:
|
|
285
|
+
"Relationship-rich factual statement to remember (1-2 sentences). Include relational context.",
|
|
286
|
+
},
|
|
287
|
+
confidence: {
|
|
288
|
+
type: "number",
|
|
289
|
+
description: "Confidence that this is accurate (0.0-1.0)",
|
|
290
|
+
},
|
|
291
|
+
importance: {
|
|
292
|
+
type: "number",
|
|
293
|
+
description: "How valuable this is to remember (0.0-1.0)",
|
|
294
|
+
},
|
|
295
|
+
supersedes: {
|
|
296
|
+
type: ["string", "null"],
|
|
297
|
+
description:
|
|
298
|
+
"ID of the existing memory item this replaces, or null if not replacing anything",
|
|
299
|
+
},
|
|
300
|
+
overrideConfidence: {
|
|
301
|
+
type: "string",
|
|
302
|
+
enum: ["explicit", "tentative", "inferred"],
|
|
303
|
+
description:
|
|
304
|
+
"How confident you are that this overrides an existing item",
|
|
305
|
+
},
|
|
306
|
+
source_role: {
|
|
307
|
+
type: "string",
|
|
308
|
+
enum: ["user", "assistant"],
|
|
309
|
+
description:
|
|
310
|
+
"Which speaker's message this item was primarily extracted from",
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
required: [
|
|
314
|
+
"kind",
|
|
315
|
+
"subject",
|
|
316
|
+
"statement",
|
|
317
|
+
"confidence",
|
|
318
|
+
"importance",
|
|
319
|
+
"supersedes",
|
|
320
|
+
"overrideConfidence",
|
|
321
|
+
"source_role",
|
|
322
|
+
],
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
extraction_summary: {
|
|
326
|
+
type: "string",
|
|
327
|
+
description:
|
|
328
|
+
"Updated summary of what has been extracted from this conversation so far",
|
|
329
|
+
},
|
|
330
|
+
conversation_summary: {
|
|
331
|
+
type: "string",
|
|
332
|
+
description: "Updated summary of the conversation so far",
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
required: ["items", "extraction_summary", "conversation_summary"],
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
],
|
|
339
|
+
systemPrompt,
|
|
340
|
+
{
|
|
341
|
+
config: {
|
|
342
|
+
modelIntent: "quality-optimized" as const,
|
|
343
|
+
tool_choice: {
|
|
344
|
+
type: "tool" as const,
|
|
345
|
+
name: "batch_extract_results",
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
);
|
|
350
|
+
|
|
351
|
+
const toolBlock = extractToolUse(response);
|
|
352
|
+
if (!toolBlock) {
|
|
353
|
+
throw new ProviderError(
|
|
354
|
+
"No tool_use block in batch extraction LLM response",
|
|
355
|
+
"unknown",
|
|
356
|
+
502,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const input = toolBlock.input as unknown as BatchExtractResult;
|
|
361
|
+
if (!Array.isArray(input.items)) {
|
|
362
|
+
throw new ProviderError(
|
|
363
|
+
"Invalid items structure in batch extraction LLM response",
|
|
364
|
+
"unknown",
|
|
365
|
+
502,
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Guard: re-check after the async LLM call
|
|
370
|
+
if (isConversationFailed(conversationId)) {
|
|
371
|
+
log.info(
|
|
372
|
+
{ conversationId },
|
|
373
|
+
"Skipping upsert — conversation marked failed during batch extraction",
|
|
374
|
+
);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ── Validate and process extracted items ────────────────────────────
|
|
379
|
+
const existingItemIds = new Set(existingItems.map((e) => e.id));
|
|
380
|
+
|
|
381
|
+
const validatedItems: ExtractedItem[] = [];
|
|
382
|
+
for (const raw of input.items) {
|
|
383
|
+
const resolvedKind = KIND_MIGRATION_MAP[raw.kind] ?? raw.kind;
|
|
384
|
+
if (resolvedKind === "journal") continue;
|
|
385
|
+
if (!VALID_KINDS.has(resolvedKind)) continue;
|
|
386
|
+
if (!raw.subject || !raw.statement) continue;
|
|
387
|
+
const subject = String(raw.subject).trim();
|
|
388
|
+
const statement = String(raw.statement).trim();
|
|
389
|
+
const confidence = clampUnitInterval(parseScore(raw.confidence, 0.5));
|
|
390
|
+
const importance = clampUnitInterval(parseScore(raw.importance, 0.5));
|
|
391
|
+
const fingerprint = computeMemoryFingerprint(
|
|
392
|
+
scopeId,
|
|
393
|
+
resolvedKind,
|
|
394
|
+
subject,
|
|
395
|
+
statement,
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
const rawSupersedes =
|
|
399
|
+
typeof raw.supersedes === "string" && raw.supersedes.length > 0
|
|
400
|
+
? raw.supersedes
|
|
401
|
+
: null;
|
|
402
|
+
const supersedes =
|
|
403
|
+
rawSupersedes && existingItemIds.has(rawSupersedes)
|
|
404
|
+
? rawSupersedes
|
|
405
|
+
: null;
|
|
406
|
+
const supersedesRejected = !!rawSupersedes && !supersedes;
|
|
407
|
+
const overrideConfidence = VALID_OVERRIDE_CONFIDENCES.has(
|
|
408
|
+
raw.overrideConfidence,
|
|
409
|
+
)
|
|
410
|
+
? (raw.overrideConfidence as OverrideConfidence)
|
|
411
|
+
: "inferred";
|
|
412
|
+
|
|
413
|
+
const sourceRole =
|
|
414
|
+
raw.source_role === "user" || raw.source_role === "assistant"
|
|
415
|
+
? raw.source_role
|
|
416
|
+
: undefined;
|
|
417
|
+
|
|
418
|
+
validatedItems.push({
|
|
419
|
+
kind: resolvedKind as MemoryItemKind,
|
|
420
|
+
subject,
|
|
421
|
+
statement,
|
|
422
|
+
confidence,
|
|
423
|
+
importance,
|
|
424
|
+
fingerprint,
|
|
425
|
+
supersedes,
|
|
426
|
+
overrideConfidence,
|
|
427
|
+
supersedesRejected,
|
|
428
|
+
sourceRole,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const dedupedItems = deduplicateItems(validatedItems);
|
|
433
|
+
|
|
434
|
+
// ── Upsert extracted items ──────────────────────────────────────────
|
|
435
|
+
const lastMessage = unextractedMessages[unextractedMessages.length - 1];
|
|
436
|
+
let upserted = 0;
|
|
437
|
+
|
|
438
|
+
for (const item of dedupedItems) {
|
|
439
|
+
const seenAt = lastMessage.createdAt;
|
|
440
|
+
const itemRole = item.sourceRole ?? lastMessage.role;
|
|
441
|
+
const existing = db
|
|
442
|
+
.select()
|
|
443
|
+
.from(memoryItems)
|
|
444
|
+
.where(
|
|
445
|
+
and(
|
|
446
|
+
eq(memoryItems.fingerprint, item.fingerprint),
|
|
447
|
+
eq(memoryItems.scopeId, scopeId),
|
|
448
|
+
),
|
|
449
|
+
)
|
|
450
|
+
.get();
|
|
451
|
+
|
|
452
|
+
let memoryItemId: string;
|
|
453
|
+
let effectiveStatus: string = "active";
|
|
454
|
+
if (existing) {
|
|
455
|
+
memoryItemId = existing.id;
|
|
456
|
+
effectiveStatus = "active";
|
|
457
|
+
const effectiveSourceType =
|
|
458
|
+
existing.sourceType === "tool"
|
|
459
|
+
? "tool"
|
|
460
|
+
: existing.sourceType === "journal_carry_forward"
|
|
461
|
+
? "journal_carry_forward"
|
|
462
|
+
: "extraction";
|
|
463
|
+
const effectiveVerificationState =
|
|
464
|
+
itemRole === "user" || existing.verificationState === "user_reported"
|
|
465
|
+
? "user_reported"
|
|
466
|
+
: existing.verificationState === "user_confirmed"
|
|
467
|
+
? "user_confirmed"
|
|
468
|
+
: "assistant_inferred";
|
|
469
|
+
|
|
470
|
+
db.update(memoryItems)
|
|
471
|
+
.set({
|
|
472
|
+
status: effectiveStatus,
|
|
473
|
+
confidence: clampUnitInterval(
|
|
474
|
+
Math.max(existing.confidence, item.confidence),
|
|
475
|
+
),
|
|
476
|
+
importance: clampUnitInterval(
|
|
477
|
+
fullReextract
|
|
478
|
+
? item.importance
|
|
479
|
+
: Math.max(existing.importance ?? 0, item.importance),
|
|
480
|
+
),
|
|
481
|
+
lastSeenAt: Math.max(existing.lastSeenAt, seenAt),
|
|
482
|
+
sourceType: effectiveSourceType,
|
|
483
|
+
sourceMessageRole: itemRole,
|
|
484
|
+
verificationState: effectiveVerificationState,
|
|
485
|
+
})
|
|
486
|
+
.where(eq(memoryItems.id, existing.id))
|
|
487
|
+
.run();
|
|
488
|
+
} else {
|
|
489
|
+
memoryItemId = uuid();
|
|
490
|
+
db.insert(memoryItems)
|
|
491
|
+
.values({
|
|
492
|
+
id: memoryItemId,
|
|
493
|
+
kind: item.kind,
|
|
494
|
+
subject: item.subject,
|
|
495
|
+
statement: item.statement,
|
|
496
|
+
status: "active",
|
|
497
|
+
confidence: item.confidence,
|
|
498
|
+
importance: item.importance,
|
|
499
|
+
fingerprint: item.fingerprint,
|
|
500
|
+
sourceType: "extraction",
|
|
501
|
+
verificationState:
|
|
502
|
+
itemRole === "user" ? "user_reported" : "assistant_inferred",
|
|
503
|
+
sourceMessageRole: itemRole,
|
|
504
|
+
scopeId,
|
|
505
|
+
firstSeenAt: lastMessage.createdAt,
|
|
506
|
+
lastSeenAt: seenAt,
|
|
507
|
+
lastUsedAt: null,
|
|
508
|
+
supersedes: item.supersedes,
|
|
509
|
+
overrideConfidence: item.overrideConfidence,
|
|
510
|
+
})
|
|
511
|
+
.run();
|
|
512
|
+
upserted += 1;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// Handle LLM-directed supersession based on overrideConfidence
|
|
516
|
+
if (
|
|
517
|
+
item.supersedes &&
|
|
518
|
+
item.supersedes !== memoryItemId &&
|
|
519
|
+
item.overrideConfidence === "explicit" &&
|
|
520
|
+
effectiveStatus === "active"
|
|
521
|
+
) {
|
|
522
|
+
const oldItem = db
|
|
523
|
+
.select({ id: memoryItems.id })
|
|
524
|
+
.from(memoryItems)
|
|
525
|
+
.where(
|
|
526
|
+
and(
|
|
527
|
+
eq(memoryItems.id, item.supersedes),
|
|
528
|
+
eq(memoryItems.scopeId, scopeId),
|
|
529
|
+
eq(memoryItems.status, "active"),
|
|
530
|
+
),
|
|
531
|
+
)
|
|
532
|
+
.get();
|
|
533
|
+
|
|
534
|
+
if (oldItem) {
|
|
535
|
+
db.update(memoryItems)
|
|
536
|
+
.set({
|
|
537
|
+
status: "superseded",
|
|
538
|
+
supersededBy: memoryItemId,
|
|
539
|
+
})
|
|
540
|
+
.where(eq(memoryItems.id, oldItem.id))
|
|
541
|
+
.run();
|
|
542
|
+
|
|
543
|
+
db.update(memoryItems)
|
|
544
|
+
.set({ supersedes: oldItem.id })
|
|
545
|
+
.where(eq(memoryItems.id, memoryItemId))
|
|
546
|
+
.run();
|
|
547
|
+
|
|
548
|
+
try {
|
|
549
|
+
const qdrant = getQdrantClient();
|
|
550
|
+
await withQdrantBreaker(() =>
|
|
551
|
+
qdrant.deleteByTarget("item", oldItem.id),
|
|
552
|
+
);
|
|
553
|
+
} catch (err) {
|
|
554
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
555
|
+
log.warn(
|
|
556
|
+
{ err: errMsg, oldItemId: oldItem.id },
|
|
557
|
+
"Failed to remove superseded item from Qdrant — will be cleaned up by index maintenance",
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
log.debug(
|
|
562
|
+
{ newItemId: memoryItemId, oldItemId: oldItem.id },
|
|
563
|
+
"Explicitly superseded memory item (batch)",
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
} else if (item.supersedes && item.overrideConfidence === "tentative") {
|
|
567
|
+
log.debug(
|
|
568
|
+
{
|
|
569
|
+
newItemId: memoryItemId,
|
|
570
|
+
supersedes: item.supersedes,
|
|
571
|
+
overrideConfidence: "tentative",
|
|
572
|
+
},
|
|
573
|
+
"Tentative override — both items coexist (batch)",
|
|
574
|
+
);
|
|
575
|
+
} else if (item.supersedes && item.overrideConfidence === "inferred") {
|
|
576
|
+
log.debug(
|
|
577
|
+
{
|
|
578
|
+
newItemId: memoryItemId,
|
|
579
|
+
supersedes: item.supersedes,
|
|
580
|
+
overrideConfidence: "inferred",
|
|
581
|
+
},
|
|
582
|
+
"Inferred override — both items coexist (batch)",
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// Fallback subject-match supersession
|
|
587
|
+
if (
|
|
588
|
+
!item.supersedes &&
|
|
589
|
+
!item.supersedesRejected &&
|
|
590
|
+
SUPERSEDE_KINDS.has(item.kind) &&
|
|
591
|
+
effectiveStatus === "active"
|
|
592
|
+
) {
|
|
593
|
+
db.update(memoryItems)
|
|
594
|
+
.set({ status: "superseded" })
|
|
595
|
+
.where(
|
|
596
|
+
and(
|
|
597
|
+
eq(memoryItems.kind, item.kind),
|
|
598
|
+
eq(memoryItems.subject, item.subject),
|
|
599
|
+
eq(memoryItems.status, "active"),
|
|
600
|
+
eq(memoryItems.scopeId, scopeId),
|
|
601
|
+
sql`${memoryItems.id} <> ${memoryItemId}`,
|
|
602
|
+
),
|
|
603
|
+
)
|
|
604
|
+
.run();
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Record source linkage for the last message in the batch
|
|
608
|
+
db.insert(memoryItemSources)
|
|
609
|
+
.values({
|
|
610
|
+
memoryItemId,
|
|
611
|
+
messageId: lastMessage.id,
|
|
612
|
+
evidence: item.statement,
|
|
613
|
+
createdAt: Date.now(),
|
|
614
|
+
})
|
|
615
|
+
.onConflictDoNothing()
|
|
616
|
+
.run();
|
|
617
|
+
|
|
618
|
+
enqueueMemoryJob("embed_item", { itemId: memoryItemId });
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// ── Update running extraction summary ───────────────────────────────
|
|
622
|
+
if (input.extraction_summary) {
|
|
623
|
+
const now = Date.now();
|
|
624
|
+
const summaryId =
|
|
625
|
+
existingExtractionSummary
|
|
626
|
+
? db
|
|
627
|
+
.select({ id: memorySummaries.id })
|
|
628
|
+
.from(memorySummaries)
|
|
629
|
+
.where(
|
|
630
|
+
and(
|
|
631
|
+
eq(memorySummaries.scope, "extraction_context"),
|
|
632
|
+
eq(memorySummaries.scopeKey, conversationId),
|
|
633
|
+
),
|
|
634
|
+
)
|
|
635
|
+
.get()?.id ?? uuid()
|
|
636
|
+
: uuid();
|
|
637
|
+
|
|
638
|
+
db.insert(memorySummaries)
|
|
639
|
+
.values({
|
|
640
|
+
id: summaryId,
|
|
641
|
+
scope: "extraction_context",
|
|
642
|
+
scopeKey: conversationId,
|
|
643
|
+
scopeId,
|
|
644
|
+
summary: input.extraction_summary,
|
|
645
|
+
tokenEstimate: estimateTextTokens(input.extraction_summary),
|
|
646
|
+
version: 1,
|
|
647
|
+
startAt: unextractedMessages[0].createdAt,
|
|
648
|
+
endAt: lastMessage.createdAt,
|
|
649
|
+
createdAt: now,
|
|
650
|
+
updatedAt: now,
|
|
651
|
+
})
|
|
652
|
+
.onConflictDoUpdate({
|
|
653
|
+
target: [memorySummaries.scope, memorySummaries.scopeKey],
|
|
654
|
+
set: {
|
|
655
|
+
summary: input.extraction_summary,
|
|
656
|
+
tokenEstimate: estimateTextTokens(input.extraction_summary),
|
|
657
|
+
version: sql`${memorySummaries.version} + 1`,
|
|
658
|
+
scopeId,
|
|
659
|
+
endAt: lastMessage.createdAt,
|
|
660
|
+
updatedAt: now,
|
|
661
|
+
},
|
|
662
|
+
})
|
|
663
|
+
.run();
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// ── Update conversation summary ─────────────────────────────────────
|
|
667
|
+
if (input.conversation_summary) {
|
|
668
|
+
const now = Date.now();
|
|
669
|
+
const existingConvSummary = db
|
|
670
|
+
.select({ id: memorySummaries.id })
|
|
671
|
+
.from(memorySummaries)
|
|
672
|
+
.where(
|
|
673
|
+
and(
|
|
674
|
+
eq(memorySummaries.scope, "conversation"),
|
|
675
|
+
eq(memorySummaries.scopeKey, conversationId),
|
|
676
|
+
),
|
|
677
|
+
)
|
|
678
|
+
.get();
|
|
679
|
+
|
|
680
|
+
const convSummaryId = existingConvSummary?.id ?? uuid();
|
|
681
|
+
|
|
682
|
+
db.insert(memorySummaries)
|
|
683
|
+
.values({
|
|
684
|
+
id: convSummaryId,
|
|
685
|
+
scope: "conversation",
|
|
686
|
+
scopeKey: conversationId,
|
|
687
|
+
scopeId,
|
|
688
|
+
summary: input.conversation_summary,
|
|
689
|
+
tokenEstimate: estimateTextTokens(input.conversation_summary),
|
|
690
|
+
version: 1,
|
|
691
|
+
startAt: unextractedMessages[0].createdAt,
|
|
692
|
+
endAt: lastMessage.createdAt,
|
|
693
|
+
createdAt: now,
|
|
694
|
+
updatedAt: now,
|
|
695
|
+
})
|
|
696
|
+
.onConflictDoUpdate({
|
|
697
|
+
target: [memorySummaries.scope, memorySummaries.scopeKey],
|
|
698
|
+
set: {
|
|
699
|
+
summary: input.conversation_summary,
|
|
700
|
+
tokenEstimate: estimateTextTokens(input.conversation_summary),
|
|
701
|
+
version: sql`${memorySummaries.version} + 1`,
|
|
702
|
+
scopeId,
|
|
703
|
+
endAt: lastMessage.createdAt,
|
|
704
|
+
updatedAt: now,
|
|
705
|
+
},
|
|
706
|
+
})
|
|
707
|
+
.run();
|
|
708
|
+
|
|
709
|
+
// Re-query to get the persisted row ID and enqueue embed job
|
|
710
|
+
const actualRow = db
|
|
711
|
+
.select({ id: memorySummaries.id })
|
|
712
|
+
.from(memorySummaries)
|
|
713
|
+
.where(
|
|
714
|
+
and(
|
|
715
|
+
eq(memorySummaries.scope, "conversation"),
|
|
716
|
+
eq(memorySummaries.scopeKey, conversationId),
|
|
717
|
+
),
|
|
718
|
+
)
|
|
719
|
+
.get();
|
|
720
|
+
if (actualRow) {
|
|
721
|
+
enqueueMemoryJob("embed_summary", { summaryId: actualRow.id });
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// ── Update checkpoints ──────────────────────────────────────────────
|
|
726
|
+
setMemoryCheckpoint(lastMessageIdKey, lastMessage.id);
|
|
727
|
+
setMemoryCheckpoint(
|
|
728
|
+
`batch_extract:${conversationId}:pending_count`,
|
|
729
|
+
"0",
|
|
730
|
+
);
|
|
731
|
+
|
|
732
|
+
log.info(
|
|
733
|
+
{
|
|
734
|
+
conversationId,
|
|
735
|
+
messagesProcessed: unextractedMessages.length,
|
|
736
|
+
itemsExtracted: dedupedItems.length,
|
|
737
|
+
itemsUpserted: upserted,
|
|
738
|
+
},
|
|
739
|
+
"Batch extraction completed",
|
|
740
|
+
);
|
|
741
|
+
}
|