nova-personal-agent-server 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { EntryRevisionSchema, retrievalEvidence, effectiveEvidence, processingStamp, fileDerivedInference } from './store.js';
|
|
3
|
+
const vectorSchema = z.array(z.number().finite()).min(1).max(4096).refine(vector => vector.some(value => value !== 0), 'zero embedding');
|
|
4
|
+
const key = z.string().min(1).max(512);
|
|
5
|
+
const latest = `SELECT r.entry_id,r.revision,r.payload_json FROM memory_revisions r JOIN (SELECT entry_id,MAX(revision) revision FROM memory_revisions GROUP BY entry_id) l USING(entry_id,revision)`;
|
|
6
|
+
export function initializeRetrieval(db) {
|
|
7
|
+
db.exec('CREATE TABLE IF NOT EXISTS memory_vectors(entry_id TEXT NOT NULL,revision INTEGER NOT NULL,provider TEXT NOT NULL,vector_json TEXT NOT NULL,PRIMARY KEY(entry_id,provider))');
|
|
8
|
+
}
|
|
9
|
+
function active(entry) { return entry.op !== 'tombstone' && (entry.valid_until === null || Date.parse(entry.valid_until) > Date.now()); }
|
|
10
|
+
function hasEvidence(db, entry) { return entry.evidence_refs.some(id => retrievalEvidence(db, id) !== null); }
|
|
11
|
+
function consented(db, entry, provider) {
|
|
12
|
+
const live = entry.evidence_refs.map(id => retrievalEvidence(db, id)).filter(value => value !== null);
|
|
13
|
+
return live.length === entry.evidence_refs.length && live.every(value => effectiveEvidence(db, value.id, { purpose: 'embedding', provider }) !== null);
|
|
14
|
+
}
|
|
15
|
+
export function memoryRetrieval(db, operation, input) {
|
|
16
|
+
const value = z.record(z.string(), z.unknown()).parse(input);
|
|
17
|
+
const prefix = key.parse(value.entry_prefix);
|
|
18
|
+
const provider = key.parse(value.provider);
|
|
19
|
+
if (operation === 'write_vectors') {
|
|
20
|
+
const batch = z.array(z.object({ entry_id: key, revision: z.number().int().positive(), vector: vectorSchema, stamp: z.string().min(1).max(128) }).strict()).max(100).parse(value.entries);
|
|
21
|
+
let count = 0;
|
|
22
|
+
for (const item of batch) {
|
|
23
|
+
if (!item.entry_id.startsWith(prefix))
|
|
24
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
25
|
+
const raw = db.prepare(`SELECT payload_json FROM (${latest}) WHERE entry_id=?`).get(item.entry_id);
|
|
26
|
+
if (!raw)
|
|
27
|
+
continue;
|
|
28
|
+
const entry = EntryRevisionSchema.parse(JSON.parse(String(raw.payload_json)));
|
|
29
|
+
if (item.stamp !== processingStamp(db, entry.evidence_refs, 'embedding', provider) || entry.revision !== item.revision || !active(entry) || !hasEvidence(db, entry) || !consented(db, entry, provider))
|
|
30
|
+
continue;
|
|
31
|
+
db.prepare('INSERT INTO memory_vectors VALUES(?,?,?,?) ON CONFLICT(entry_id,provider) DO UPDATE SET revision=excluded.revision,vector_json=excluded.vector_json').run(item.entry_id, item.revision, provider, JSON.stringify(item.vector));
|
|
32
|
+
count++;
|
|
33
|
+
}
|
|
34
|
+
return count;
|
|
35
|
+
}
|
|
36
|
+
const limit = operation === 'pending_vectors' ? z.number().int().min(1).max(100).parse(value.limit ?? 100) : value.scope === 'recent' ? 200 : 5000;
|
|
37
|
+
const excludeFileInferences = z.boolean().parse(value.exclude_file_inferences ?? false);
|
|
38
|
+
const fileClause = excludeFileInferences ? `AND NOT (json_extract(r.payload_json,'$.origin')='inferred' AND json_extract(r.payload_json,'$.written_by')<>'user_correction' AND EXISTS (SELECT 1 FROM json_each(r.payload_json,'$.evidence_refs') ref JOIN memory_evidence e ON e.id=ref.value WHERE json_extract(e.payload_json,'$.source_kind')='file'))` : '';
|
|
39
|
+
// ponytail: scan the bounded current namespace in the existing Worker; add ANN only beyond 5000 active entries.
|
|
40
|
+
const candidates = db.prepare(`SELECT r.payload_json,v.vector_json FROM (${latest}) r LEFT JOIN memory_vectors v ON v.entry_id=r.entry_id AND v.revision=r.revision AND v.provider=? WHERE substr(r.entry_id,1,length(?))=? AND json_extract(r.payload_json,'$.op')<>'tombstone' AND (json_extract(r.payload_json,'$.valid_until') IS NULL OR julianday(json_extract(r.payload_json,'$.valid_until'))>julianday(?)) ${fileClause} ${operation === 'pending_vectors' ? 'AND v.entry_id IS NULL' : ''} ORDER BY json_extract(r.payload_json,'$.recorded_at') DESC,r.entry_id LIMIT ?`).all(provider, prefix, prefix, new Date().toISOString(), limit + 1);
|
|
41
|
+
const extractionProvider = value.extraction_provider === undefined ? null : key.parse(value.extraction_provider);
|
|
42
|
+
const kind = value.kind === undefined ? null : key.parse(value.kind);
|
|
43
|
+
const usable = candidates.slice(0, limit).map(row => ({ entry: EntryRevisionSchema.parse(JSON.parse(String(row.payload_json))), vector: row.vector_json === null ? null : vectorSchema.parse(JSON.parse(String(row.vector_json))) })).filter(row => row.entry.kind !== 'memory_summary' && hasEvidence(db, row.entry) && (kind === null || row.entry.kind === kind) && (!excludeFileInferences || !fileDerivedInference(db, row.entry))).map(row => ({ ...row, extraction_stamp: extractionProvider ? processingStamp(db, row.entry.evidence_refs, 'extraction', extractionProvider) : null })).filter(row => extractionProvider === null || row.extraction_stamp !== null);
|
|
44
|
+
if (operation === 'pending_vectors')
|
|
45
|
+
return usable.filter(row => consented(db, row.entry, provider)).map(row => row.entry);
|
|
46
|
+
const query = z.string().min(1).max(4000).parse(value.query);
|
|
47
|
+
const k = z.number().int().min(1).max(20).parse(value.limit ?? 8);
|
|
48
|
+
const queryVector = value.vector === null ? null : vectorSchema.parse(value.vector);
|
|
49
|
+
const scores = bm25(query, usable.map(row => Object.values(row.entry.content).filter(value => typeof value === 'string').join(' ')));
|
|
50
|
+
const lexical = usable.map((row, index) => ({ row, score: scores[index] })).filter(item => item.score > 0).sort((a, b) => b.score - a.score).slice(0, 50);
|
|
51
|
+
const semantic = queryVector ? usable.flatMap(row => row.vector?.length === queryVector.length && consented(db, row.entry, provider) ? [{ row, score: cosine(queryVector, row.vector) }] : []).filter(item => item.score > 0).sort((a, b) => b.score - a.score).slice(0, 50) : [];
|
|
52
|
+
const fused = new Map();
|
|
53
|
+
for (const ranking of [semantic, lexical])
|
|
54
|
+
for (const [index, item] of ranking.entries()) {
|
|
55
|
+
const old = fused.get(item.row.entry.entry_id);
|
|
56
|
+
fused.set(item.row.entry.entry_id, { entry: item.row.entry, score: (old?.score ?? 0) + 1 / (60 + index + 1), ...(item.row.extraction_stamp ? { extraction_stamp: item.row.extraction_stamp } : {}) });
|
|
57
|
+
}
|
|
58
|
+
return { hits: [...fused.values()].sort((a, b) => b.score - a.score || a.entry.entry_id.localeCompare(b.entry.entry_id)).slice(0, k), degraded: queryVector === null || candidates.length > limit || usable.some(row => row.vector?.length !== queryVector.length || !consented(db, row.entry, provider)) };
|
|
59
|
+
}
|
|
60
|
+
function cosine(a, b) {
|
|
61
|
+
let dot = 0, left = 0, right = 0;
|
|
62
|
+
for (let i = 0; i < a.length; i++) {
|
|
63
|
+
dot += a[i] * b[i];
|
|
64
|
+
left += a[i] * a[i];
|
|
65
|
+
right += b[i] * b[i];
|
|
66
|
+
}
|
|
67
|
+
return left === 0 || right === 0 ? -1 : dot / Math.sqrt(left * right);
|
|
68
|
+
}
|
|
69
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: 'word' });
|
|
70
|
+
function tokens(text) { return [...segmenter.segment(text.normalize('NFKC').toLowerCase())].filter(part => part.isWordLike).map(part => part.segment); }
|
|
71
|
+
/** BM25 lexical ranking shares the hybrid retrieval path; tokens rank candidates, never decide intent or identity. */
|
|
72
|
+
export function bm25(query, documents) {
|
|
73
|
+
const terms = [...new Set(tokens(query))].slice(0, 24), docs = documents.map(tokens);
|
|
74
|
+
const average = docs.reduce((sum, doc) => sum + doc.length, 0) / (docs.length || 1) || 1;
|
|
75
|
+
const frequencies = new Map(terms.map(term => [term, docs.filter(doc => doc.includes(term)).length]));
|
|
76
|
+
return docs.map(doc => terms.reduce((score, term) => {
|
|
77
|
+
const frequency = doc.filter(token => token === term).length;
|
|
78
|
+
if (!frequency)
|
|
79
|
+
return score;
|
|
80
|
+
const found = frequencies.get(term);
|
|
81
|
+
const idf = Math.log(1 + (docs.length - found + 0.5) / (found + 0.5));
|
|
82
|
+
return score + idf * frequency * 2.2 / (frequency + 1.2 * (0.25 + 0.75 * doc.length / average));
|
|
83
|
+
}, 0));
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=retrieval.js.map
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { resolutionContextSchema } from './resolution.js';
|
|
2
|
+
import { syncStatusSchema } from './source-state.js';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { canonicalJson } from '../text/canonical-json.js';
|
|
5
|
+
import { EvidenceRecordSchema, CandidateSchema, EntryRevisionSchema, processingStamp } from './store.js';
|
|
6
|
+
import { connectionSchema, readConnection, sourceObjectSchema, sourceIdSchema, revisionSchema, fenceSchema, connectorSourceId, sha256, readProcessingGrant, processingGrantSchema, extractionTicketSchema, sourceObjectFor } from './source-state.js';
|
|
7
|
+
const changeSchema = z.object({ object_key: sourceIdSchema, source_id: sourceIdSchema, semantic_hash: sourceIdSchema, metadata: z.record(z.string(), z.json()), evidence: z.array(z.lazy(() => EvidenceRecordSchema)).max(256), status: z.enum(['current', 'coverage_removed', 'provider_deleted']) }).strict();
|
|
8
|
+
export const applyPageSchema = z.object({ fence: fenceSchema, batch_id: z.string().regex(/^[1-9][0-9]{0,14}$/u), page_id: sourceIdSchema, changes: z.array(changeSchema).max(200), pending_ids: z.array(sourceIdSchema).max(200), continuation: z.json(), checkpoint: z.json(), complete: z.boolean() }).strict();
|
|
9
|
+
export function sourceRevision(db) { return Number(db.prepare('SELECT revision FROM source_clock WHERE id=1').get().revision); }
|
|
10
|
+
export function advanceSourceRevision(db) { db.exec('UPDATE source_clock SET revision=revision+1 WHERE id=1'); return sourceRevision(db); }
|
|
11
|
+
function save(db, c) { db.prepare('INSERT INTO source_connections VALUES(?,?) ON CONFLICT(id) DO UPDATE SET payload_json=excluded.payload_json').run(c.fence.connection_id, canonicalJson(connectionSchema.parse(c))); }
|
|
12
|
+
function withdrawObjects(db, c, run, generation = c.fence.generation) {
|
|
13
|
+
let after = '';
|
|
14
|
+
for (;;) {
|
|
15
|
+
const rows = db.prepare('SELECT payload_json FROM source_objects WHERE connection_id=? AND generation=? AND object_key>? ORDER BY object_key LIMIT 200').all(c.fence.connection_id, generation, after);
|
|
16
|
+
for (const row of rows) {
|
|
17
|
+
const object = sourceObjectSchema.parse(JSON.parse(String(row.payload_json)));
|
|
18
|
+
after = object.object_key;
|
|
19
|
+
const ids = object.current_evidence_ids;
|
|
20
|
+
object.current_evidence_ids = [];
|
|
21
|
+
object.status = 'coverage_removed';
|
|
22
|
+
object.activation_revision++;
|
|
23
|
+
db.prepare('UPDATE source_objects SET payload_json=? WHERE connection_id=? AND generation=? AND object_key=?').run(canonicalJson(object), object.connection_id, object.generation, object.object_key);
|
|
24
|
+
run('invalidate_evidence', { ids });
|
|
25
|
+
}
|
|
26
|
+
if (rows.length < 200)
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function sourceOperation(db, operation, input, run) {
|
|
31
|
+
const v = z.record(z.string(), z.unknown()).parse(input);
|
|
32
|
+
if (operation === 'source_events') {
|
|
33
|
+
const q = z.object({ prefix: sourceIdSchema, provider: sourceIdSchema, after: revisionSchema.optional(), ack: z.object({ revision: revisionSchema, phase: z.enum(['invalidated', 'ready']) }).strict().optional() }).strict().parse(v);
|
|
34
|
+
const rows = q.ack ? db.prepare("SELECT connection_id,batch_id,page_id,result_json FROM source_pages WHERE substr(connection_id,1,length(?))=? AND json_extract(result_json,'$.revision')=?").all(q.prefix, q.prefix, q.ack.revision) : db.prepare("SELECT connection_id,batch_id,page_id,result_json FROM source_pages WHERE substr(connection_id,1,length(?))=? AND coalesce(json_extract(result_json,'$.ready'),0)=0 AND json_extract(result_json,'$.revision')>? ORDER BY json_extract(result_json,'$.revision') LIMIT 200").all(q.prefix, q.prefix, q.after ?? 0);
|
|
35
|
+
const events = [];
|
|
36
|
+
for (const row of rows) {
|
|
37
|
+
const r = JSON.parse(String(row.result_json));
|
|
38
|
+
if (q.ack) {
|
|
39
|
+
if (r.revision === q.ack.revision) {
|
|
40
|
+
r[q.ack.phase] = true;
|
|
41
|
+
db.prepare('UPDATE source_pages SET result_json=? WHERE connection_id=? AND batch_id=? AND page_id=?').run(canonicalJson(r), String(row.connection_id), String(row.batch_id), String(row.page_id));
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (!r.invalidated) {
|
|
46
|
+
events.push({ revision: r.revision, phase: 'invalidated' });
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (r.ready)
|
|
50
|
+
continue;
|
|
51
|
+
let ready = true;
|
|
52
|
+
for (const activation of r.activations) {
|
|
53
|
+
const objectRow = db.prepare('SELECT payload_json FROM source_objects WHERE connection_id=? AND generation=? AND object_key=?').get(String(row.connection_id), r.fence.generation, activation.object_key);
|
|
54
|
+
if (!objectRow)
|
|
55
|
+
continue;
|
|
56
|
+
const object = sourceObjectSchema.parse(JSON.parse(String(objectRow.payload_json)));
|
|
57
|
+
if (object.activation_revision !== activation.revision)
|
|
58
|
+
continue;
|
|
59
|
+
for (const id of object.current_evidence_ids)
|
|
60
|
+
if (!run('processing_evidence', { id, purpose: 'extraction', provider: q.provider }) || sourceOperation(db, 'extraction_ticket', { evidence_id: id, provider: q.provider }, run) !== null) {
|
|
61
|
+
ready = false;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
if (!ready)
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
if (ready)
|
|
68
|
+
events.push({ revision: r.revision, phase: 'ready' });
|
|
69
|
+
}
|
|
70
|
+
return { events: events.sort((a, b) => a.revision - b.revision), next: rows.length === 200 ? JSON.parse(String(rows.at(-1).result_json)).revision : null };
|
|
71
|
+
}
|
|
72
|
+
if (operation === 'extraction_ticket') {
|
|
73
|
+
const q = z.object({ evidence_id: z.string().min(1).max(512), provider: sourceIdSchema, force: z.boolean().optional() }).strict().parse(v);
|
|
74
|
+
const raw = run('processing_evidence', { id: q.evidence_id, purpose: 'extraction', provider: q.provider });
|
|
75
|
+
if (!raw)
|
|
76
|
+
return null;
|
|
77
|
+
const e = EvidenceRecordSchema.parse(raw);
|
|
78
|
+
if (!e.raw_text || e.source_kind === 'user_correction')
|
|
79
|
+
return null;
|
|
80
|
+
const object = sourceObjectFor(db, e.source_id), grant = readProcessingGrant(db, e.source_id);
|
|
81
|
+
const ticket = { evidence_id: e.id, activation: object ? { object_key: object.object_key, revision: object.activation_revision } : null, consent_revision: grant.revision, extraction_provider: q.provider, fence: object ? readConnection(db, object.connection_id).fence : null };
|
|
82
|
+
if (!q.force && (db.prepare('SELECT 1 FROM source_extractions WHERE ticket_key=?').get(sha256(canonicalJson(ticket))) || (!object && db.prepare('SELECT 1 FROM memory_extractions WHERE evidence_id=? LIMIT 1').get(e.id))))
|
|
83
|
+
return null;
|
|
84
|
+
return ticket;
|
|
85
|
+
}
|
|
86
|
+
if (operation === 'commit_extraction') {
|
|
87
|
+
const q = z.object({ ticket: extractionTicketSchema, candidates: z.array(CandidateSchema).max(9), contexts: z.array(resolutionContextSchema).max(20).default([]), extracted: z.record(z.string(), z.json()) }).strict().parse(v);
|
|
88
|
+
const current = sourceOperation(db, 'extraction_ticket', { evidence_id: q.ticket.evidence_id, provider: q.ticket.extraction_provider, force: true }, run);
|
|
89
|
+
if (!current || canonicalJson(current) !== canonicalJson(q.ticket))
|
|
90
|
+
return { applied: false };
|
|
91
|
+
for (const context of q.contexts) {
|
|
92
|
+
const row = db.prepare('SELECT payload_json FROM memory_revisions WHERE entry_id=? ORDER BY revision DESC LIMIT 1').get(context.entry_id);
|
|
93
|
+
if (!row)
|
|
94
|
+
throw Error('STORE_STALE_REVISION');
|
|
95
|
+
const entry = EntryRevisionSchema.parse(JSON.parse(String(row.payload_json)));
|
|
96
|
+
if (entry.revision !== context.revision || entry.op === 'tombstone' || (entry.valid_until !== null && Date.parse(entry.valid_until) <= Date.now()))
|
|
97
|
+
throw Error('STORE_STALE_REVISION');
|
|
98
|
+
if (processingStamp(db, entry.evidence_refs, 'extraction', q.ticket.extraction_provider) !== context.stamp)
|
|
99
|
+
return { applied: false };
|
|
100
|
+
}
|
|
101
|
+
for (const candidate of q.candidates) {
|
|
102
|
+
if (!candidate.evidence_refs.includes(q.ticket.evidence_id))
|
|
103
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
104
|
+
for (const id of candidate.evidence_refs)
|
|
105
|
+
if (!run('processing_evidence', { id, purpose: 'extraction', provider: q.ticket.extraction_provider }))
|
|
106
|
+
return { applied: false };
|
|
107
|
+
}
|
|
108
|
+
for (const candidate of q.candidates)
|
|
109
|
+
run('merge', candidate);
|
|
110
|
+
// The ticket and all candidates share the enclosing worker transaction.
|
|
111
|
+
const key = sha256(canonicalJson(q.ticket));
|
|
112
|
+
run('record_extraction', { evidence_id: q.ticket.evidence_id, attempt_id: key, extracted: q.extracted });
|
|
113
|
+
db.prepare('INSERT OR IGNORE INTO source_extractions VALUES(?,?)').run(key, canonicalJson({ ticket: q.ticket }));
|
|
114
|
+
return { applied: true };
|
|
115
|
+
}
|
|
116
|
+
if (operation === 'source_revision')
|
|
117
|
+
return sourceRevision(db);
|
|
118
|
+
if (operation === 'source_grant') {
|
|
119
|
+
const q = z.object({ source_id: z.string().min(1).max(512), action: z.literal('get').optional(), expected_revision: revisionSchema.optional(), grant: processingGrantSchema.optional() }).strict().parse(v);
|
|
120
|
+
const old = readProcessingGrant(db, q.source_id);
|
|
121
|
+
if (q.action === 'get')
|
|
122
|
+
return old;
|
|
123
|
+
if (!q.grant || q.expected_revision !== (old?.revision ?? 0) || q.grant.revision <= q.expected_revision)
|
|
124
|
+
throw Error('STORE_STALE_REVISION');
|
|
125
|
+
db.prepare('INSERT INTO source_grants VALUES(?,?) ON CONFLICT(source_id) DO UPDATE SET payload_json=excluded.payload_json').run(q.source_id, canonicalJson(q.grant));
|
|
126
|
+
db.prepare("DELETE FROM memory_extractions WHERE attempt_id<>'knowledge-index' AND evidence_id IN (SELECT id FROM memory_evidence WHERE source_id=?)").run(q.source_id);
|
|
127
|
+
db.prepare("DELETE FROM memory_vectors WHERE entry_id IN (SELECT r.entry_id FROM memory_revisions r,json_each(r.payload_json,'$.evidence_refs') refs JOIN memory_evidence e ON e.id=refs.value WHERE e.source_id=?)").run(q.source_id);
|
|
128
|
+
return q.grant;
|
|
129
|
+
}
|
|
130
|
+
if (operation === 'source_connection') {
|
|
131
|
+
if (v.action === 'list') {
|
|
132
|
+
const q = z.object({ action: z.literal('list'), prefix: sourceIdSchema, after: sourceIdSchema.nullable().optional(), limit: z.number().int().min(1).max(100).default(100) }).strict().parse(v);
|
|
133
|
+
const rows = db.prepare('SELECT payload_json FROM source_connections WHERE substr(id,1,length(?))=? AND id>? ORDER BY id LIMIT ?').all(q.prefix, q.prefix, q.after ?? '', q.limit + 1);
|
|
134
|
+
const connections = rows.slice(0, q.limit).map(row => connectionSchema.parse(JSON.parse(String(row.payload_json))));
|
|
135
|
+
return { connections, next: rows.length > q.limit ? connections.at(-1).fence.connection_id : null };
|
|
136
|
+
}
|
|
137
|
+
const id = sourceIdSchema.parse(v.id), c = readConnection(db, id);
|
|
138
|
+
if (v.action === 'get')
|
|
139
|
+
return c;
|
|
140
|
+
if (v.action === 'create') {
|
|
141
|
+
const q = z.object({ action: z.literal('create'), id: sourceIdSchema, namespace: sourceIdSchema }).strict().parse(v);
|
|
142
|
+
if (c) {
|
|
143
|
+
if (c.namespace !== q.namespace)
|
|
144
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
145
|
+
return c;
|
|
146
|
+
}
|
|
147
|
+
const fresh = { fence: { connection_id: id, generation: 0, epoch: 0, scope_revision: 0 }, namespace: q.namespace, state: 'paused', scope: null, checkpoint: null, continuation: null, pending_ids: [], batch: 0, completed_batch: 0, deleting: [] };
|
|
148
|
+
save(db, fresh);
|
|
149
|
+
return fresh;
|
|
150
|
+
}
|
|
151
|
+
if (!c)
|
|
152
|
+
throw Error('STORE_NOT_FOUND');
|
|
153
|
+
if (v.action === 'sync_status') {
|
|
154
|
+
const q = z.object({ action: z.literal('sync_status'), id: sourceIdSchema, expected_epoch: revisionSchema, status: syncStatusSchema }).strict().parse(v);
|
|
155
|
+
if (q.expected_epoch !== c.fence.epoch)
|
|
156
|
+
throw Error('STORE_STALE_REVISION');
|
|
157
|
+
c.sync_status = q.status;
|
|
158
|
+
save(db, c);
|
|
159
|
+
return c;
|
|
160
|
+
}
|
|
161
|
+
if (v.action === 'reset_sync') {
|
|
162
|
+
const q = z.object({ action: z.literal('reset_sync'), id: sourceIdSchema, expected_epoch: revisionSchema }).strict().parse(v);
|
|
163
|
+
if (q.expected_epoch !== c.fence.epoch)
|
|
164
|
+
throw Error('STORE_STALE_REVISION');
|
|
165
|
+
c.fence.epoch++;
|
|
166
|
+
c.pending_ids = [];
|
|
167
|
+
c.continuation = null;
|
|
168
|
+
c.checkpoint = null;
|
|
169
|
+
c.completed_batch = c.batch;
|
|
170
|
+
save(db, c);
|
|
171
|
+
return c;
|
|
172
|
+
}
|
|
173
|
+
if (v.action === 'scope') {
|
|
174
|
+
const q = z.object({ action: z.literal('scope'), id: sourceIdSchema, expected_scope_revision: revisionSchema, scope: z.json() }).strict().parse(v);
|
|
175
|
+
if (q.expected_scope_revision !== c.fence.scope_revision)
|
|
176
|
+
throw Error('STORE_STALE_REVISION');
|
|
177
|
+
c.scope = q.scope;
|
|
178
|
+
c.fence.scope_revision++;
|
|
179
|
+
c.fence.epoch++;
|
|
180
|
+
c.pending_ids = [];
|
|
181
|
+
c.continuation = null;
|
|
182
|
+
c.checkpoint = null;
|
|
183
|
+
c.completed_batch = c.batch;
|
|
184
|
+
save(db, c);
|
|
185
|
+
withdrawObjects(db, c, run);
|
|
186
|
+
advanceSourceRevision(db);
|
|
187
|
+
return c;
|
|
188
|
+
}
|
|
189
|
+
if (v.action === 'delete_begin') {
|
|
190
|
+
const q = z.object({ action: z.literal('delete_begin'), id: sourceIdSchema, expected_epoch: revisionSchema }).strict().parse(v);
|
|
191
|
+
if (q.expected_epoch !== c.fence.epoch)
|
|
192
|
+
throw Error('STORE_STALE_REVISION');
|
|
193
|
+
c.deleting.push(c.fence.generation);
|
|
194
|
+
c.fence.generation++;
|
|
195
|
+
c.fence.epoch++;
|
|
196
|
+
c.state = 'paused';
|
|
197
|
+
c.pending_ids = [];
|
|
198
|
+
c.continuation = null;
|
|
199
|
+
c.checkpoint = null;
|
|
200
|
+
c.completed_batch = c.batch;
|
|
201
|
+
save(db, c);
|
|
202
|
+
withdrawObjects(db, c, run, c.fence.generation - 1);
|
|
203
|
+
advanceSourceRevision(db);
|
|
204
|
+
return c;
|
|
205
|
+
}
|
|
206
|
+
if (v.action === 'delete_step') {
|
|
207
|
+
const q = z.object({ action: z.literal('delete_step'), id: sourceIdSchema, limit: z.number().int().min(1).max(200).default(200) }).strict().parse(v);
|
|
208
|
+
const generation = c.deleting[0];
|
|
209
|
+
if (generation === undefined)
|
|
210
|
+
return { remaining: false };
|
|
211
|
+
if (generation >= c.fence.generation)
|
|
212
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
213
|
+
const rows = db.prepare('SELECT payload_json FROM source_objects WHERE connection_id=? AND generation=? ORDER BY object_key LIMIT ?').all(q.id, generation, q.limit);
|
|
214
|
+
for (const row of rows) {
|
|
215
|
+
const object = sourceObjectSchema.parse(JSON.parse(String(row.payload_json)));
|
|
216
|
+
run('delete_source', { source_id: object.source_id });
|
|
217
|
+
db.prepare('DELETE FROM source_grants WHERE source_id=?').run(object.source_id);
|
|
218
|
+
db.prepare('DELETE FROM source_objects WHERE connection_id=? AND generation=? AND object_key=?').run(q.id, generation, object.object_key);
|
|
219
|
+
}
|
|
220
|
+
if (!db.prepare('SELECT 1 FROM source_objects WHERE connection_id=? AND generation=? LIMIT 1').get(q.id, generation))
|
|
221
|
+
c.deleting.shift();
|
|
222
|
+
save(db, c);
|
|
223
|
+
return { remaining: c.deleting.length > 0 };
|
|
224
|
+
}
|
|
225
|
+
if (v.action === 'fence') {
|
|
226
|
+
const q = z.object({ action: z.literal('fence'), id: sourceIdSchema, state: z.enum(['connected', 'paused', 'disconnected']), expected_epoch: revisionSchema }).strict().parse(v);
|
|
227
|
+
if (q.expected_epoch !== c.fence.epoch)
|
|
228
|
+
throw Error('STORE_STALE_REVISION');
|
|
229
|
+
c.fence.epoch++;
|
|
230
|
+
c.state = q.state;
|
|
231
|
+
save(db, c);
|
|
232
|
+
return c;
|
|
233
|
+
}
|
|
234
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
235
|
+
}
|
|
236
|
+
if (operation === 'source_pending') {
|
|
237
|
+
const q = z.object({ id: sourceIdSchema, after: sourceIdSchema.optional(), object_key: sourceIdSchema.optional(), limit: z.number().int().min(1).max(200).default(200) }).strict().parse(v);
|
|
238
|
+
const c = readConnection(db, q.id);
|
|
239
|
+
if (!c)
|
|
240
|
+
throw Error('STORE_NOT_FOUND');
|
|
241
|
+
const objects = db.prepare('SELECT payload_json FROM source_objects WHERE connection_id=? AND generation=? AND object_key>? ORDER BY object_key LIMIT ?').all(q.id, c.fence.generation, q.after ?? '', q.limit + 1).map(row => sourceObjectSchema.parse(JSON.parse(String(row.payload_json))));
|
|
242
|
+
return { connection: c, objects: objects.slice(0, q.limit).filter(o => !q.object_key || o.object_key === q.object_key), next: objects.length > q.limit ? objects[q.limit - 1].object_key : null };
|
|
243
|
+
}
|
|
244
|
+
if (operation === 'source_apply_page') {
|
|
245
|
+
if (Buffer.byteLength(JSON.stringify(v)) > 5 * 1024 * 1024)
|
|
246
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
247
|
+
const q = applyPageSchema.parse(v), c = readConnection(db, q.fence.connection_id);
|
|
248
|
+
if (c?.state !== 'connected' || canonicalJson(c.fence) !== canonicalJson(q.fence))
|
|
249
|
+
throw Error('STORE_STALE_REVISION');
|
|
250
|
+
const hash = sha256(canonicalJson(q));
|
|
251
|
+
const receipt = db.prepare('SELECT payload_hash,result_json FROM source_pages WHERE connection_id=? AND batch_id=? AND page_id=?').get(q.fence.connection_id, q.batch_id, q.page_id);
|
|
252
|
+
if (receipt) {
|
|
253
|
+
if (receipt.payload_hash !== hash)
|
|
254
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
255
|
+
return { ...JSON.parse(String(receipt.result_json)), applied: false };
|
|
256
|
+
}
|
|
257
|
+
const batch = Number(q.batch_id);
|
|
258
|
+
if (batch < c.batch || batch <= c.completed_batch || (batch > c.batch && c.batch !== c.completed_batch))
|
|
259
|
+
throw Error('STORE_STALE_REVISION');
|
|
260
|
+
if (q.complete && q.pending_ids.length)
|
|
261
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
262
|
+
const appliedKeys = new Set(q.changes.map(change => change.object_key));
|
|
263
|
+
if (c.pending_ids.some(id => !q.pending_ids.includes(id) && !appliedKeys.has(id)))
|
|
264
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
265
|
+
const activations = [];
|
|
266
|
+
const seen = new Set();
|
|
267
|
+
for (const change of q.changes) {
|
|
268
|
+
if (seen.has(change.object_key))
|
|
269
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
270
|
+
seen.add(change.object_key);
|
|
271
|
+
if (change.source_id !== connectorSourceId(c.namespace, c.fence.generation, change.object_key) || change.evidence.some(e => e.source_id !== change.source_id) || ((change.status === 'current') !== (change.evidence.length > 0)))
|
|
272
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
273
|
+
const oldRow = db.prepare('SELECT payload_json FROM source_objects WHERE connection_id=? AND generation=? AND object_key=?').get(q.fence.connection_id, q.fence.generation, change.object_key);
|
|
274
|
+
const old = oldRow ? sourceObjectSchema.parse(JSON.parse(String(oldRow.payload_json))) : null;
|
|
275
|
+
const changed = old?.semantic_hash !== change.semantic_hash || old.status !== change.status;
|
|
276
|
+
// Metadata-only updates must not replace the content-addressed current set.
|
|
277
|
+
if (!changed && canonicalJson(old.current_evidence_ids) !== canonicalJson(change.evidence.map(e => e.id)))
|
|
278
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
279
|
+
for (const evidence of change.evidence)
|
|
280
|
+
run('append_evidence', evidence);
|
|
281
|
+
const next = sourceObjectSchema.parse({ connection_id: q.fence.connection_id, generation: q.fence.generation, object_key: change.object_key, source_id: change.source_id, semantic_hash: change.semantic_hash, metadata: change.metadata, current_evidence_ids: change.evidence.map(e => e.id), activation_revision: (old?.activation_revision ?? 0) + Number(changed), status: change.status, observed_at: new Date().toISOString() });
|
|
282
|
+
db.prepare('INSERT INTO source_objects VALUES(?,?,?,?) ON CONFLICT(connection_id,generation,object_key) DO UPDATE SET payload_json=excluded.payload_json').run(next.connection_id, next.generation, next.object_key, canonicalJson(next));
|
|
283
|
+
if (changed) {
|
|
284
|
+
activations.push({ object_key: next.object_key, revision: next.activation_revision });
|
|
285
|
+
run('invalidate_evidence', { ids: old?.current_evidence_ids ?? [] });
|
|
286
|
+
for (const id of next.current_evidence_ids)
|
|
287
|
+
db.prepare('DELETE FROM memory_extractions WHERE evidence_id=?').run(id);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
c.pending_ids = q.pending_ids;
|
|
291
|
+
c.continuation = q.continuation;
|
|
292
|
+
c.batch = Number(q.batch_id);
|
|
293
|
+
if (q.complete) {
|
|
294
|
+
c.checkpoint = q.checkpoint;
|
|
295
|
+
c.completed_batch = c.batch;
|
|
296
|
+
}
|
|
297
|
+
save(db, c);
|
|
298
|
+
const result = { revision: advanceSourceRevision(db), applied: true, activations };
|
|
299
|
+
db.prepare('INSERT INTO source_pages VALUES(?,?,?,?,?)').run(q.fence.connection_id, q.batch_id, q.page_id, hash, canonicalJson({ ...result, fence: q.fence }));
|
|
300
|
+
if (q.complete)
|
|
301
|
+
db.prepare("DELETE FROM source_pages WHERE connection_id=? AND CAST(batch_id AS INTEGER)<? AND json_extract(result_json,'$.ready')=1").run(q.fence.connection_id, c.completed_batch - 1);
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
305
|
+
}
|
|
306
|
+
//# sourceMappingURL=source-operations.js.map
|