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,326 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { canonicalJson } from '../text/canonical-json.js';
|
|
4
|
+
import { sha256 } from './source-state.js';
|
|
5
|
+
import { effectiveEvidence, processingStamp } from './store.js';
|
|
6
|
+
import { profileDraftSchema } from '../personal-agent/profile-warmup.js';
|
|
7
|
+
const id = z.string().min(1).max(512);
|
|
8
|
+
const cursorSchema = z.object({ seq: z.number().int().nonnegative(), offset: z.number().int().nonnegative() }).strict();
|
|
9
|
+
export const processingRefSchema = z.object({ evidence_id: id, stamp: id, start: z.number().int().nonnegative(), end: z.number().int().positive() }).strict().refine(r => r.end > r.start && r.end - r.start <= 4000);
|
|
10
|
+
export const processingTopicSchema = z.object({ title: z.string().trim().min(1).max(120), summary: z.string().trim().min(1).max(1500), refs: z.array(processingRefSchema).min(1).max(8) }).strict();
|
|
11
|
+
const batchSchema = z.object({ id, prefix: id, provider: id, items: z.array(processingRefSchema).min(1).max(8), end: cursorSchema, status: z.enum(['claimed', 'bound', 'completed', 'failed', 'invalidated']), task_id: id.nullable(), run_id: id.nullable(), created_at: z.string(), result_hash: id.nullable() }).strict();
|
|
12
|
+
const stateSchema = z.object({ cursor: cursorSchema, completed_batches: z.number().int().nonnegative(), processed_chars: z.number().int().nonnegative(), last_success: z.string().nullable() }).strict();
|
|
13
|
+
export const SOURCE_PROCESSING_VERSION = 'source-processing-v2';
|
|
14
|
+
const base = z.object({ prefix: z.string().regex(/^personal:[^:]+:$/u), provider: id, recipe: id.default(SOURCE_PROCESSING_VERSION) });
|
|
15
|
+
const owner = { batch_id: id, task_id: id, run_id: id };
|
|
16
|
+
export const processingRequestSchema = z.discriminatedUnion('action', [
|
|
17
|
+
z.object({ action: z.literal('claim') }).strict(),
|
|
18
|
+
z.object({ action: z.literal('status') }).strict(),
|
|
19
|
+
z.object({ action: z.literal('batch'), batch_id: id }).strict(),
|
|
20
|
+
z.object({ action: z.literal('bind'), ...owner }).strict(),
|
|
21
|
+
z.object({ action: z.literal('read'), batch_id: id }).strict(),
|
|
22
|
+
z.object({ action: z.literal('commit'), ...owner, topics: z.array(processingTopicSchema).max(8) }).strict(),
|
|
23
|
+
z.object({ action: z.literal('fail'), ...owner }).strict(),
|
|
24
|
+
// Host reconciliation only: caller must first verify the Task/Run ledger, never infer termination from a timeout.
|
|
25
|
+
z.object({ action: z.literal('retire'), batch_id: id, task_id: id.nullable(), run_id: id.nullable(), reason: z.enum(['task_terminal', 'no_task_dispatched']) }).strict(),
|
|
26
|
+
z.object({ action: z.literal('topics'), batch_id: id.optional(), after: z.number().int().nonnegative().default(0), limit: z.number().int().min(1).max(100).default(20), query: z.string().trim().max(200).default('') }).strict(),
|
|
27
|
+
z.object({ action: z.literal('evidence'), ...owner, refs: z.array(processingRefSchema).min(1).max(8).refine(refs => refs.reduce((sum, ref) => sum + ref.end - ref.start, 0) <= 16000) }).strict(),
|
|
28
|
+
z.object({ action: z.literal('profile'), batch_id: id.optional() }).strict(),
|
|
29
|
+
z.object({ action: z.literal('publish'), ...owner, expected_revision: z.number().int().nonnegative(), draft: profileDraftSchema, refs: z.array(processingRefSchema).min(1).max(64) }).strict(),
|
|
30
|
+
]);
|
|
31
|
+
/** Transactional outbox: only identifiers, never another copy of original text. */
|
|
32
|
+
export function initializeSourceProcessing(db) {
|
|
33
|
+
db.exec('SAVEPOINT processing_initialize');
|
|
34
|
+
try {
|
|
35
|
+
db.exec(`CREATE TABLE IF NOT EXISTS processing_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,prefix TEXT NOT NULL,evidence_id TEXT NOT NULL);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS processing_events_scope ON processing_events(prefix,seq);
|
|
37
|
+
CREATE TABLE IF NOT EXISTS processing_meta(id INTEGER PRIMARY KEY);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS processing_state(prefix TEXT NOT NULL,provider TEXT NOT NULL,payload_json TEXT NOT NULL,PRIMARY KEY(prefix,provider));
|
|
39
|
+
CREATE TABLE IF NOT EXISTS processing_batches(id TEXT PRIMARY KEY,prefix TEXT NOT NULL,provider TEXT NOT NULL,status TEXT NOT NULL,payload_json TEXT NOT NULL);
|
|
40
|
+
CREATE UNIQUE INDEX IF NOT EXISTS processing_active ON processing_batches(prefix) WHERE status IN ('claimed','bound');
|
|
41
|
+
CREATE TABLE IF NOT EXISTS processing_receipts(prefix TEXT NOT NULL,provider TEXT NOT NULL,ref_key TEXT NOT NULL,evidence_id TEXT NOT NULL,PRIMARY KEY(prefix,provider,ref_key));
|
|
42
|
+
CREATE TABLE IF NOT EXISTS processing_topics(seq INTEGER PRIMARY KEY AUTOINCREMENT,prefix TEXT NOT NULL,provider TEXT NOT NULL,batch_id TEXT NOT NULL,payload_json TEXT NOT NULL);
|
|
43
|
+
CREATE INDEX IF NOT EXISTS processing_topics_scope ON processing_topics(prefix,provider,seq);`);
|
|
44
|
+
db.exec(`CREATE TABLE IF NOT EXISTS processing_heads(key TEXT PRIMARY KEY,revision INTEGER NOT NULL);
|
|
45
|
+
CREATE TABLE IF NOT EXISTS processing_profiles(prefix TEXT NOT NULL,provider TEXT NOT NULL,revision INTEGER NOT NULL,payload_json TEXT NOT NULL,PRIMARY KEY(prefix,provider));
|
|
46
|
+
CREATE TABLE IF NOT EXISTS processing_reads(batch_id TEXT NOT NULL,ref_key TEXT NOT NULL,PRIMARY KEY(batch_id,ref_key));
|
|
47
|
+
CREATE TRIGGER IF NOT EXISTS processing_head_insert AFTER INSERT ON memory_message_heads BEGIN
|
|
48
|
+
INSERT INTO processing_heads VALUES(NEW.key,1) ON CONFLICT(key) DO UPDATE SET revision=revision+1; END;
|
|
49
|
+
CREATE TRIGGER IF NOT EXISTS processing_head_update AFTER UPDATE ON memory_message_heads WHEN OLD.evidence_id<>NEW.evidence_id BEGIN
|
|
50
|
+
INSERT INTO processing_heads VALUES(NEW.key,1) ON CONFLICT(key) DO UPDATE SET revision=revision+1;
|
|
51
|
+
INSERT INTO processing_events(prefix,evidence_id) SELECT substr(source_id,1,9+instr(substr(source_id,10),':')),id FROM memory_evidence WHERE id=NEW.evidence_id; END;`);
|
|
52
|
+
if (!db.prepare('PRAGMA table_info(processing_reads)').all().some(column => column.name === 'payload_json'))
|
|
53
|
+
db.exec('ALTER TABLE processing_reads ADD COLUMN payload_json TEXT');
|
|
54
|
+
// Pre-release ledgers without evidence-linked receipts must conservatively reprocess their affected input.
|
|
55
|
+
if (!db.prepare('PRAGMA table_info(processing_receipts)').all().some(column => column.name === 'evidence_id')) {
|
|
56
|
+
db.exec("ALTER TABLE processing_receipts ADD COLUMN evidence_id TEXT NOT NULL DEFAULT ''; DELETE FROM processing_receipts; DELETE FROM processing_state;");
|
|
57
|
+
}
|
|
58
|
+
const affected = `SELECT json_extract(r.value,'$.evidence_id') FROM processing_topics t,json_each(t.payload_json,'$.refs') r WHERE EXISTS(SELECT 1 FROM json_each(t.payload_json,'$.refs') removed WHERE json_extract(removed.value,'$.evidence_id')=OLD.id)
|
|
59
|
+
UNION SELECT json_extract(r.value,'$.evidence_id') FROM processing_profiles p,json_each(p.payload_json,'$.refs') r WHERE EXISTS(SELECT 1 FROM json_each(p.payload_json,'$.refs') removed WHERE json_extract(removed.value,'$.evidence_id')=OLD.id)`;
|
|
60
|
+
// Erase revoked clauses, retain unrelated profile clauses, and requeue surviving mixed-topic inputs.
|
|
61
|
+
db.exec(`DROP TRIGGER IF EXISTS processing_erase_derived;
|
|
62
|
+
CREATE TRIGGER processing_erase_derived AFTER DELETE ON memory_evidence BEGIN
|
|
63
|
+
INSERT INTO processing_events(prefix,evidence_id) SELECT substr(source_id,1,9+instr(substr(source_id,10),':')),id FROM memory_evidence WHERE id IN (${affected}) AND id<>OLD.id;
|
|
64
|
+
DELETE FROM processing_receipts WHERE evidence_id=OLD.id OR evidence_id IN (${affected});
|
|
65
|
+
DELETE FROM processing_topics WHERE EXISTS(SELECT 1 FROM json_each(processing_topics.payload_json,'$.refs') r WHERE json_extract(r.value,'$.evidence_id')=OLD.id);
|
|
66
|
+
UPDATE processing_profiles SET revision=revision+1,payload_json=json_object('draft',json_object(
|
|
67
|
+
'about',CASE WHEN EXISTS(SELECT 1 FROM json_each(payload_json,'$.draft.about.refs') r WHERE json_extract(r.value,'$.entry_id')=OLD.id) THEN NULL ELSE json_extract(payload_json,'$.draft.about') END,
|
|
68
|
+
'work',json((SELECT json_group_array(json(item.value)) FROM json_each(payload_json,'$.draft.work') item WHERE NOT EXISTS(SELECT 1 FROM json_each(item.value,'$.refs') r WHERE json_extract(r.value,'$.entry_id')=OLD.id))),
|
|
69
|
+
'interests',json((SELECT json_group_array(json(item.value)) FROM json_each(payload_json,'$.draft.interests') item WHERE NOT EXISTS(SELECT 1 FROM json_each(item.value,'$.refs') r WHERE json_extract(r.value,'$.entry_id')=OLD.id)))),
|
|
70
|
+
'refs',json((SELECT json_group_array(json(r.value)) FROM json_each(payload_json,'$.refs') r WHERE json_extract(r.value,'$.evidence_id')<>OLD.id)))
|
|
71
|
+
WHERE EXISTS(SELECT 1 FROM json_each(processing_profiles.payload_json,'$.refs') r WHERE json_extract(r.value,'$.evidence_id')=OLD.id);
|
|
72
|
+
END;`);
|
|
73
|
+
const scope = (source) => `substr(${source},1,9+instr(substr(${source},10),':'))`;
|
|
74
|
+
for (const [event, row] of [['INSERT', 'NEW'], ['UPDATE', 'NEW'], ['DELETE', 'OLD']]) {
|
|
75
|
+
db.exec(`CREATE TRIGGER IF NOT EXISTS processing_evidence_${event.toLowerCase()} AFTER ${event} ON memory_evidence
|
|
76
|
+
BEGIN INSERT INTO processing_events(prefix,evidence_id) VALUES(${scope(row + '.source_id')},${row}.id); END;`);
|
|
77
|
+
}
|
|
78
|
+
for (const [event, row] of [['INSERT', 'NEW'], ['UPDATE', 'NEW'], ['DELETE', 'OLD']]) {
|
|
79
|
+
db.exec(`CREATE TRIGGER IF NOT EXISTS processing_grant_${event.toLowerCase()} AFTER ${event} ON source_grants
|
|
80
|
+
BEGIN INSERT INTO processing_events(prefix,evidence_id) SELECT ${scope('e.source_id')},e.id FROM memory_evidence e
|
|
81
|
+
WHERE e.source_id=${row}.source_id OR e.source_id IN (SELECT json_extract(payload_json,'$.source_id') FROM source_objects WHERE connection_id=${row}.source_id); END;`);
|
|
82
|
+
}
|
|
83
|
+
for (const [table, key] of [['source_objects', "json_extract(NEW.payload_json,'$.source_id')"], ['source_connections', 'NEW.id']]) {
|
|
84
|
+
const where = table === 'source_objects' ? `e.source_id=${key}` : `e.source_id IN (SELECT json_extract(payload_json,'$.source_id') FROM source_objects WHERE connection_id=${key})`;
|
|
85
|
+
const changed = table === 'source_objects' ? "json_extract(OLD.payload_json,'$.activation_revision') IS NOT json_extract(NEW.payload_json,'$.activation_revision')" : "json_extract(OLD.payload_json,'$.fence') IS NOT json_extract(NEW.payload_json,'$.fence') OR json_extract(OLD.payload_json,'$.state') IS NOT json_extract(NEW.payload_json,'$.state')";
|
|
86
|
+
db.exec(`CREATE TRIGGER IF NOT EXISTS processing_${table}_update AFTER UPDATE ON ${table} WHEN ${changed}
|
|
87
|
+
BEGIN INSERT INTO processing_events(prefix,evidence_id) SELECT ${scope('e.source_id')},e.id FROM memory_evidence e WHERE ${where}; END;`);
|
|
88
|
+
}
|
|
89
|
+
// Ledger initialization runs in a transaction. Existing evidence is bootstrapped once.
|
|
90
|
+
db.exec(`INSERT INTO processing_events(prefix,evidence_id) SELECT ${scope('source_id')},id FROM memory_evidence WHERE NOT EXISTS(SELECT 1 FROM processing_meta WHERE id=1);
|
|
91
|
+
INSERT OR IGNORE INTO processing_meta VALUES(1);`);
|
|
92
|
+
db.exec('RELEASE processing_initialize');
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
db.exec('ROLLBACK TO processing_initialize; RELEASE processing_initialize');
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function source(db, prefix, provider, evidenceId, recipe) {
|
|
100
|
+
const record = effectiveEvidence(db, evidenceId, { purpose: 'extraction', provider });
|
|
101
|
+
if (!record?.raw_text || !record.id.startsWith(prefix) || !record.source_id.startsWith(prefix) || !['file', 'mail', 'im'].includes(record.source_kind))
|
|
102
|
+
return null;
|
|
103
|
+
// Content-addressed message versions retain history; only their current head is eligible.
|
|
104
|
+
if (['mail', 'im'].includes(record.source_kind)) {
|
|
105
|
+
const head = db.prepare('SELECT evidence_id FROM memory_message_heads WHERE key=?').get(sha256(canonicalJson([record.source_id, record.locator])));
|
|
106
|
+
if (head?.evidence_id !== undefined && head.evidence_id !== record.id)
|
|
107
|
+
return null;
|
|
108
|
+
if (!head && db.prepare("SELECT 1 FROM memory_evidence WHERE source_id=? AND json_extract(payload_json,'$.locator')=? AND rowid>(SELECT rowid FROM memory_evidence WHERE id=?) LIMIT 1").get(record.source_id, record.locator, record.id))
|
|
109
|
+
return null;
|
|
110
|
+
const m = record.source_metadata;
|
|
111
|
+
if (!m || (record.source_kind === 'im' ? m.sender_id !== m.recipient_id && m.mention !== 'direct' : m.sender_id !== m.account_id))
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const grant = processingStamp(db, [record.id], 'extraction', provider);
|
|
115
|
+
const headRevision = db.prepare('SELECT revision FROM processing_heads WHERE key=?').get(sha256(canonicalJson([record.source_id, record.locator])))?.revision ?? 0;
|
|
116
|
+
return grant ? { record, stamp: sha256(canonicalJson({ record, grant, headRevision, recipe, algorithm: SOURCE_PROCESSING_VERSION })) } : null;
|
|
117
|
+
}
|
|
118
|
+
function readRefs(db, prefix, provider, refs, recipe) {
|
|
119
|
+
const items = [];
|
|
120
|
+
for (const ref of refs) {
|
|
121
|
+
const current = source(db, prefix, provider, ref.evidence_id, recipe);
|
|
122
|
+
if (current?.stamp !== ref.stamp || ref.end > current.record.raw_text.length)
|
|
123
|
+
return null;
|
|
124
|
+
items.push({ ...ref, text: current.record.raw_text.slice(ref.start, ref.end), version: current.record.hash, source_kind: current.record.source_kind, observed_at: current.record.observed_at, source_metadata: current.record.source_metadata ?? null, locator: current.record.locator });
|
|
125
|
+
}
|
|
126
|
+
return { items };
|
|
127
|
+
}
|
|
128
|
+
function saveBatch(db, batch) { db.prepare('INSERT INTO processing_batches VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,payload_json=excluded.payload_json').run(batch.id, batch.prefix, batch.provider, batch.status, canonicalJson(batch)); }
|
|
129
|
+
function saveState(db, prefix, provider, state) { db.prepare('INSERT INTO processing_state VALUES(?,?,?) ON CONFLICT(prefix,provider) DO UPDATE SET payload_json=excluded.payload_json').run(prefix, provider, canonicalJson(state)); }
|
|
130
|
+
/** Runs exclusively inside the memory worker transaction. No timers or model calls. */
|
|
131
|
+
export function sourceProcessingOperation(db, input) {
|
|
132
|
+
const fields = z.record(z.string(), z.unknown()).parse(input), { prefix, provider: consumer, recipe } = base.parse(fields);
|
|
133
|
+
const provider = sha256(canonicalJson({ consumer, recipe, algorithm: SOURCE_PROCESSING_VERSION }));
|
|
134
|
+
const { prefix: ignoredPrefix, provider: ignoredProvider, recipe: ignoredRecipe, ...request } = fields;
|
|
135
|
+
void ignoredPrefix;
|
|
136
|
+
void ignoredProvider;
|
|
137
|
+
void ignoredRecipe;
|
|
138
|
+
const q = processingRequestSchema.parse(request);
|
|
139
|
+
const saved = db.prepare('SELECT payload_json FROM processing_state WHERE prefix=? AND provider=?').get(prefix, provider);
|
|
140
|
+
const state = saved ? stateSchema.parse(JSON.parse(String(saved.payload_json))) : { cursor: { seq: 0, offset: 0 }, completed_batches: 0, processed_chars: 0, last_success: null };
|
|
141
|
+
const active = () => { const row = db.prepare("SELECT payload_json FROM processing_batches WHERE prefix=? AND provider=? AND status IN ('claimed','bound')").get(prefix, provider); return row ? batchSchema.parse(JSON.parse(String(row.payload_json))) : null; };
|
|
142
|
+
if (q.action === 'retire') {
|
|
143
|
+
const row = db.prepare('SELECT payload_json FROM processing_batches WHERE id=? AND prefix=?').get(q.batch_id, prefix);
|
|
144
|
+
if (!row)
|
|
145
|
+
throw Error('STORE_NOT_FOUND');
|
|
146
|
+
const prior = batchSchema.parse(JSON.parse(String(row.payload_json)));
|
|
147
|
+
if (prior.task_id !== q.task_id || prior.run_id !== q.run_id)
|
|
148
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
149
|
+
if (q.reason === 'no_task_dispatched' ? (prior.task_id !== null || prior.run_id !== null) : (prior.task_id === null || prior.run_id === null))
|
|
150
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
151
|
+
if (['claimed', 'bound'].includes(prior.status)) {
|
|
152
|
+
prior.status = 'failed';
|
|
153
|
+
saveBatch(db, prior);
|
|
154
|
+
}
|
|
155
|
+
return { applied: true };
|
|
156
|
+
}
|
|
157
|
+
if (q.action === 'status') {
|
|
158
|
+
const row = db.prepare('SELECT count(*) count,max(seq) high FROM processing_events WHERE prefix=? AND seq>=?').get(prefix, state.cursor.seq + Number(state.cursor.offset === 0));
|
|
159
|
+
const prior = db.prepare("SELECT payload_json FROM processing_batches WHERE prefix=? AND status IN ('claimed','bound')").get(prefix);
|
|
160
|
+
const blocking = prior ? batchSchema.parse(JSON.parse(String(prior.payload_json))) : null;
|
|
161
|
+
return { ...state, recipe: provider, active_batch: blocking, reconciliation_required: !!blocking && blocking.provider !== provider, pending_changes: Number(row.count), high_watermark: Number(row.high ?? state.cursor.seq) };
|
|
162
|
+
}
|
|
163
|
+
if (q.action === 'claim') {
|
|
164
|
+
const existing = active();
|
|
165
|
+
if (existing)
|
|
166
|
+
return existing;
|
|
167
|
+
if (db.prepare("SELECT 1 FROM processing_batches WHERE prefix=? AND status IN ('claimed','bound')").get(prefix))
|
|
168
|
+
throw Error('STORE_OPERATION_CONFLICT');
|
|
169
|
+
const events = db.prepare('SELECT seq,evidence_id FROM processing_events WHERE prefix=? AND seq>=? ORDER BY seq LIMIT 200').all(prefix, state.cursor.seq + Number(state.cursor.offset === 0));
|
|
170
|
+
if (!events.length)
|
|
171
|
+
return null;
|
|
172
|
+
const end = { ...state.cursor }, items = [], seen = new Set();
|
|
173
|
+
let chars = 0;
|
|
174
|
+
for (const event of events) {
|
|
175
|
+
const seq = Number(event.seq), current = source(db, prefix, consumer, String(event.evidence_id), recipe);
|
|
176
|
+
if (!current) {
|
|
177
|
+
end.seq = seq;
|
|
178
|
+
end.offset = 0;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const text = current.record.raw_text;
|
|
182
|
+
let start = seq === end.seq ? end.offset : 0;
|
|
183
|
+
while (start < text.length) {
|
|
184
|
+
const stop = Math.min(start + 4000, text.length), ref = { evidence_id: current.record.id, stamp: current.stamp, start, end: stop }, key = sha256(canonicalJson(ref));
|
|
185
|
+
if (!seen.has(key) && !db.prepare('SELECT 1 FROM processing_receipts WHERE prefix=? AND provider=? AND ref_key=?').get(prefix, provider, key)) {
|
|
186
|
+
if (items.length >= 8 || chars + stop - start > 16000)
|
|
187
|
+
break;
|
|
188
|
+
items.push(ref);
|
|
189
|
+
seen.add(key);
|
|
190
|
+
chars += stop - start;
|
|
191
|
+
}
|
|
192
|
+
start = stop;
|
|
193
|
+
}
|
|
194
|
+
if (start === 0 && text.length > 0 && (items.length >= 8 || chars + Math.min(4000, text.length) > 16000))
|
|
195
|
+
break;
|
|
196
|
+
end.seq = seq;
|
|
197
|
+
end.offset = start === text.length ? 0 : start;
|
|
198
|
+
if (start < text.length)
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
if (!items.length) {
|
|
202
|
+
state.cursor = end;
|
|
203
|
+
saveState(db, prefix, provider, state);
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
const batch = { id: randomUUID(), prefix, provider, items, end, status: 'claimed', task_id: null, run_id: null, created_at: new Date().toISOString(), result_hash: null };
|
|
207
|
+
saveBatch(db, batch);
|
|
208
|
+
return batch;
|
|
209
|
+
}
|
|
210
|
+
const track = (batchId, refs) => { for (const ref of refs)
|
|
211
|
+
db.prepare('INSERT INTO processing_reads(batch_id,ref_key,payload_json) VALUES(?,?,?) ON CONFLICT(batch_id,ref_key) DO UPDATE SET payload_json=excluded.payload_json').run(batchId, sha256(canonicalJson(ref)), canonicalJson(ref)); };
|
|
212
|
+
if (q.action === 'topics') {
|
|
213
|
+
const rows = db.prepare("SELECT seq,payload_json FROM processing_topics WHERE prefix=? AND provider=? AND seq>? AND (?='' OR instr(lower(json_extract(payload_json,'$.title')||' '||json_extract(payload_json,'$.summary')),lower(?))>0) ORDER BY seq LIMIT ?").all(prefix, provider, q.after, q.query, q.query, q.limit + 1);
|
|
214
|
+
const page = rows.slice(0, q.limit);
|
|
215
|
+
return { items: page.flatMap(row => { const topic = processingTopicSchema.parse(JSON.parse(String(row.payload_json))); if (!readRefs(db, prefix, consumer, topic.refs, recipe))
|
|
216
|
+
return []; if (q.batch_id)
|
|
217
|
+
track(q.batch_id, topic.refs); return [{ id: Number(row.seq), ...topic }]; }), next: rows.length > q.limit ? Number(page.at(-1).seq) : null };
|
|
218
|
+
}
|
|
219
|
+
if (q.action === 'profile') {
|
|
220
|
+
const saved = db.prepare('SELECT revision,payload_json FROM processing_profiles WHERE prefix=? AND provider=?').get(prefix, provider);
|
|
221
|
+
if (!saved)
|
|
222
|
+
return { revision: 0, draft: null };
|
|
223
|
+
const content = z.object({ draft: profileDraftSchema, refs: z.array(processingRefSchema) }).parse(JSON.parse(String(saved.payload_json)));
|
|
224
|
+
const valid = (fact) => fact.refs.every(ref => {
|
|
225
|
+
const refs = content.refs.filter(item => item.evidence_id === ref.entry_id);
|
|
226
|
+
return refs.length > 0 && readRefs(db, prefix, consumer, refs, recipe) !== null;
|
|
227
|
+
});
|
|
228
|
+
if (q.batch_id)
|
|
229
|
+
track(q.batch_id, content.refs.filter(ref => readRefs(db, prefix, consumer, [ref], recipe) !== null));
|
|
230
|
+
const draft = { ...content.draft, about: content.draft.about && valid(content.draft.about) ? content.draft.about : null, work: content.draft.work.filter(valid), interests: content.draft.interests.filter(valid) };
|
|
231
|
+
return { revision: Number(saved.revision), draft: draft.about || draft.work.length || draft.interests.length ? draft : null };
|
|
232
|
+
}
|
|
233
|
+
const row = db.prepare('SELECT payload_json FROM processing_batches WHERE id=? AND prefix=? AND provider=?').get(q.batch_id, prefix, provider);
|
|
234
|
+
if (!row)
|
|
235
|
+
throw Error('STORE_NOT_FOUND');
|
|
236
|
+
const batch = batchSchema.parse(JSON.parse(String(row.payload_json)));
|
|
237
|
+
const read = (refs) => {
|
|
238
|
+
const result = readRefs(db, prefix, consumer, refs, recipe);
|
|
239
|
+
if (result)
|
|
240
|
+
track(batch.id, refs);
|
|
241
|
+
return result;
|
|
242
|
+
};
|
|
243
|
+
if (q.action === 'batch') {
|
|
244
|
+
const reads = db.prepare('SELECT payload_json FROM processing_reads WHERE batch_id=?').all(batch.id);
|
|
245
|
+
return { batch, valid: readRefs(db, prefix, consumer, batch.items, recipe) !== null && reads.every(row => row.payload_json && readRefs(db, prefix, consumer, [processingRefSchema.parse(JSON.parse(String(row.payload_json)))], recipe) !== null) };
|
|
246
|
+
}
|
|
247
|
+
if (q.action === 'read')
|
|
248
|
+
return ['claimed', 'bound'].includes(batch.status) ? read(batch.items) : null;
|
|
249
|
+
if (q.action === 'bind') {
|
|
250
|
+
if (batch.task_id === q.task_id && batch.run_id === q.run_id)
|
|
251
|
+
return batch;
|
|
252
|
+
if (batch.task_id || batch.status !== 'claimed')
|
|
253
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
254
|
+
batch.task_id = q.task_id;
|
|
255
|
+
batch.run_id = q.run_id;
|
|
256
|
+
batch.status = 'bound';
|
|
257
|
+
saveBatch(db, batch);
|
|
258
|
+
return batch;
|
|
259
|
+
}
|
|
260
|
+
if (batch.task_id !== q.task_id || batch.run_id !== q.run_id)
|
|
261
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
262
|
+
if (q.action === 'evidence') {
|
|
263
|
+
if (!['bound', 'completed'].includes(batch.status))
|
|
264
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
265
|
+
return read(q.refs);
|
|
266
|
+
}
|
|
267
|
+
if (q.action === 'publish') {
|
|
268
|
+
if (!['bound', 'completed'].includes(batch.status))
|
|
269
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
270
|
+
const saved = db.prepare('SELECT revision,payload_json FROM processing_profiles WHERE prefix=? AND provider=?').get(prefix, provider);
|
|
271
|
+
const revision = Number(saved?.revision ?? 0), payload = canonicalJson({ draft: q.draft, refs: q.refs });
|
|
272
|
+
if (revision === q.expected_revision + 1 && saved?.payload_json === payload)
|
|
273
|
+
return { applied: true, revision };
|
|
274
|
+
if (revision !== q.expected_revision)
|
|
275
|
+
throw Error('STORE_STALE_REVISION');
|
|
276
|
+
const originals = readRefs(db, prefix, consumer, q.refs, recipe);
|
|
277
|
+
if (!originals)
|
|
278
|
+
return { applied: false, revision };
|
|
279
|
+
if (q.refs.some(ref => !db.prepare('SELECT 1 FROM processing_reads WHERE batch_id=? AND ref_key=?').get(batch.id, sha256(canonicalJson(ref)))))
|
|
280
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
281
|
+
const cited = [...(q.draft.about?.refs ?? []), ...q.draft.work.flatMap(item => item.refs), ...q.draft.interests.flatMap(item => item.refs)];
|
|
282
|
+
if (!cited.length || cited.some(ref => !originals.items.some(item => item.evidence_id === ref.entry_id && item.version === ref.version)))
|
|
283
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
284
|
+
db.prepare('INSERT INTO processing_profiles VALUES(?,?,?,?) ON CONFLICT(prefix,provider) DO UPDATE SET revision=excluded.revision,payload_json=excluded.payload_json').run(prefix, provider, revision + 1, payload);
|
|
285
|
+
return { applied: true, revision: revision + 1 };
|
|
286
|
+
}
|
|
287
|
+
if (q.action === 'fail') {
|
|
288
|
+
if (batch.status === 'failed')
|
|
289
|
+
return { applied: true };
|
|
290
|
+
if (batch.status !== 'bound')
|
|
291
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
292
|
+
batch.status = 'failed';
|
|
293
|
+
saveBatch(db, batch);
|
|
294
|
+
return { applied: true };
|
|
295
|
+
}
|
|
296
|
+
const resultHash = sha256(canonicalJson(q.topics));
|
|
297
|
+
if (batch.status === 'completed') {
|
|
298
|
+
if (batch.result_hash !== resultHash)
|
|
299
|
+
throw Error('STORE_IDEMPOTENCY_CONFLICT');
|
|
300
|
+
return { applied: true };
|
|
301
|
+
}
|
|
302
|
+
if (batch.status !== 'bound')
|
|
303
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
304
|
+
const available = new Set(batch.items.map(ref => canonicalJson(ref)));
|
|
305
|
+
if (q.topics.some(topic => topic.refs.some(ref => !available.has(canonicalJson(ref)))))
|
|
306
|
+
throw Error('STORE_INVALID_OPERATION');
|
|
307
|
+
if (!readRefs(db, prefix, consumer, batch.items, recipe)) {
|
|
308
|
+
batch.status = 'invalidated';
|
|
309
|
+
saveBatch(db, batch);
|
|
310
|
+
return { applied: false };
|
|
311
|
+
}
|
|
312
|
+
for (const topic of q.topics)
|
|
313
|
+
db.prepare('INSERT INTO processing_topics(prefix,provider,batch_id,payload_json) VALUES(?,?,?,?)').run(prefix, provider, batch.id, canonicalJson(topic));
|
|
314
|
+
for (const ref of batch.items)
|
|
315
|
+
db.prepare('INSERT OR IGNORE INTO processing_receipts VALUES(?,?,?,?)').run(prefix, provider, sha256(canonicalJson(ref)), ref.evidence_id);
|
|
316
|
+
state.cursor = batch.end;
|
|
317
|
+
state.completed_batches++;
|
|
318
|
+
state.processed_chars += batch.items.reduce((sum, ref) => sum + ref.end - ref.start, 0);
|
|
319
|
+
state.last_success = new Date().toISOString();
|
|
320
|
+
batch.status = 'completed';
|
|
321
|
+
batch.result_hash = resultHash;
|
|
322
|
+
saveBatch(db, batch);
|
|
323
|
+
saveState(db, prefix, provider, state);
|
|
324
|
+
return { applied: true };
|
|
325
|
+
}
|
|
326
|
+
//# sourceMappingURL=source-processing.js.map
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
export const sourceIdSchema = z.string().min(1).max(256);
|
|
4
|
+
export const revisionSchema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
5
|
+
export const fenceSchema = z.object({ connection_id: sourceIdSchema, generation: revisionSchema, epoch: revisionSchema, scope_revision: revisionSchema }).strict();
|
|
6
|
+
export const processingGrantSchema = z.object({ revision: revisionSchema, scope_revision: revisionSchema, extraction_provider: sourceIdSchema.nullable(), embedding_provider: sourceIdSchema.nullable(), conversation_providers: z.array(sourceIdSchema).max(8).optional() }).strict();
|
|
7
|
+
export function readProcessingGrant(db, sourceId) {
|
|
8
|
+
const row = db.prepare('SELECT payload_json FROM source_grants WHERE source_id=?').get(sourceId);
|
|
9
|
+
return row ? processingGrantSchema.parse(JSON.parse(String(row.payload_json))) : null;
|
|
10
|
+
}
|
|
11
|
+
export function allowsProcessing(db, sourceId, purpose, provider) {
|
|
12
|
+
const permitted = (grant) => purpose === 'conversation' ? (grant?.conversation_providers ?? []).includes(provider) : grant?.[purpose === 'extraction' ? 'extraction_provider' : 'embedding_provider'] === provider;
|
|
13
|
+
const grant = readProcessingGrant(db, sourceId);
|
|
14
|
+
if (!grant || !permitted(grant))
|
|
15
|
+
return false;
|
|
16
|
+
const object = sourceObjectFor(db, sourceId);
|
|
17
|
+
if (!object)
|
|
18
|
+
return true;
|
|
19
|
+
const c = readConnection(db, object.connection_id), connectionGrant = readProcessingGrant(db, object.connection_id);
|
|
20
|
+
if (connectionGrant && (connectionGrant.revision !== grant.revision || connectionGrant.scope_revision !== grant.scope_revision || !permitted(connectionGrant)))
|
|
21
|
+
return false;
|
|
22
|
+
return c !== null && c.state === 'connected' && c.fence.scope_revision === grant.scope_revision && c.fence.generation === object.generation;
|
|
23
|
+
}
|
|
24
|
+
export const activationSchema = z.object({ object_key: sourceIdSchema, revision: revisionSchema }).strict();
|
|
25
|
+
export const extractionTicketSchema = z.object({ evidence_id: z.string().min(1).max(512), activation: activationSchema.nullable(), consent_revision: revisionSchema, extraction_provider: sourceIdSchema, fence: fenceSchema.nullable() }).strict();
|
|
26
|
+
const boundedJson = z.json().refine(v => Buffer.byteLength(JSON.stringify(v)) <= 65536, 'source state too large');
|
|
27
|
+
export const syncStatusSchema = z.object({ attempt_at: z.number(), complete_at: z.number().nullable(), error: z.string().max(64).nullable(), failures: z.number().int().nonnegative(), retry_at: z.number() }).strict();
|
|
28
|
+
export const connectionSchema = z.object({ fence: fenceSchema, namespace: sourceIdSchema, state: z.enum(['connected', 'paused', 'disconnected']), scope: boundedJson, checkpoint: boundedJson, continuation: boundedJson, pending_ids: z.array(sourceIdSchema).max(200), batch: revisionSchema, completed_batch: revisionSchema, deleting: z.array(revisionSchema).max(100), sync_status: syncStatusSchema.optional() }).strict();
|
|
29
|
+
export const sourceObjectSchema = z.object({ connection_id: sourceIdSchema, generation: revisionSchema, object_key: sourceIdSchema, source_id: sourceIdSchema, semantic_hash: sourceIdSchema, metadata: z.record(z.string(), z.json()), current_evidence_ids: z.array(z.string().min(1).max(512)).max(256), activation_revision: revisionSchema, status: z.enum(['current', 'coverage_removed', 'provider_deleted']), observed_at: z.iso.datetime({ offset: true }) }).strict();
|
|
30
|
+
export function readConnection(db, id) {
|
|
31
|
+
const row = db.prepare('SELECT payload_json FROM source_connections WHERE id=?').get(id);
|
|
32
|
+
return row ? connectionSchema.parse(JSON.parse(String(row.payload_json))) : null;
|
|
33
|
+
}
|
|
34
|
+
export function sourceObjectFor(db, sourceId) {
|
|
35
|
+
const row = db.prepare("SELECT payload_json FROM source_objects WHERE json_extract(payload_json,'$.source_id')=?").get(sourceId);
|
|
36
|
+
return row ? sourceObjectSchema.parse(JSON.parse(String(row.payload_json))) : null;
|
|
37
|
+
}
|
|
38
|
+
export function isCurrentEvidence(db, evidenceId, sourceId) {
|
|
39
|
+
const object = sourceObjectFor(db, sourceId);
|
|
40
|
+
if (!object)
|
|
41
|
+
return true;
|
|
42
|
+
const connection = readConnection(db, object.connection_id);
|
|
43
|
+
return connection !== null && connection.fence.generation === object.generation && object.status === 'current' && object.current_evidence_ids.includes(evidenceId);
|
|
44
|
+
}
|
|
45
|
+
export const sha256 = (text) => createHash('sha256').update(text).digest('hex');
|
|
46
|
+
export function connectorSourceId(namespace, generation, objectKey) {
|
|
47
|
+
sourceIdSchema.parse(namespace);
|
|
48
|
+
revisionSchema.parse(generation);
|
|
49
|
+
z.string().min(1).max(16384).parse(objectKey);
|
|
50
|
+
const personal = /^personal:[a-f0-9]{64}:/u.exec(namespace)?.[0] ?? '';
|
|
51
|
+
return `${personal}connector:${sha256(namespace)}:${generation}:${sha256(objectKey)}`;
|
|
52
|
+
}
|
|
53
|
+
/** Called by the graph schema migration; also supports isolated in-memory memory tests. */
|
|
54
|
+
export function initializeSourceState(db) {
|
|
55
|
+
db.exec(`
|
|
56
|
+
CREATE TABLE IF NOT EXISTS source_connections(id TEXT PRIMARY KEY,payload_json TEXT NOT NULL) STRICT;
|
|
57
|
+
CREATE TABLE IF NOT EXISTS source_objects(connection_id TEXT NOT NULL,generation INTEGER NOT NULL,object_key TEXT NOT NULL,payload_json TEXT NOT NULL,PRIMARY KEY(connection_id,generation,object_key)) STRICT;
|
|
58
|
+
CREATE TABLE IF NOT EXISTS source_pages(connection_id TEXT NOT NULL,batch_id TEXT NOT NULL,page_id TEXT NOT NULL,payload_hash TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(connection_id,batch_id,page_id)) STRICT;
|
|
59
|
+
CREATE TABLE IF NOT EXISTS source_grants(source_id TEXT PRIMARY KEY,payload_json TEXT NOT NULL) STRICT;
|
|
60
|
+
CREATE TABLE IF NOT EXISTS source_extractions(ticket_key TEXT PRIMARY KEY,payload_json TEXT NOT NULL) STRICT;
|
|
61
|
+
CREATE TABLE IF NOT EXISTS source_clock(id INTEGER PRIMARY KEY CHECK(id=1),revision INTEGER NOT NULL) STRICT;
|
|
62
|
+
INSERT OR IGNORE INTO source_clock VALUES(1,0);
|
|
63
|
+
CREATE INDEX IF NOT EXISTS source_objects_source ON source_objects(json_extract(payload_json,'$.source_id'));
|
|
64
|
+
`);
|
|
65
|
+
}
|
|
66
|
+
export function assertSourceStateSchema(db) {
|
|
67
|
+
const shapes = { source_connections: ['id', 'payload_json'], source_objects: ['connection_id', 'generation', 'object_key', 'payload_json'], source_pages: ['connection_id', 'batch_id', 'page_id', 'payload_hash', 'result_json'], source_grants: ['source_id', 'payload_json'], source_extractions: ['ticket_key', 'payload_json'], source_clock: ['id', 'revision'] };
|
|
68
|
+
for (const [table, columns] of Object.entries(shapes)) {
|
|
69
|
+
const actual = db.prepare(`PRAGMA table_info(${table})`).all();
|
|
70
|
+
const keys = table === 'source_objects' || table === 'source_pages' ? 3 : 1;
|
|
71
|
+
if (actual.length !== columns.length || actual.some((c, i) => c.name !== columns[i] || c.type !== (c.name === 'generation' || table === 'source_clock' ? 'INTEGER' : 'TEXT') || Number(c.pk) !== (i < keys ? i + 1 : 0) || Number(c.notnull) !== (table === 'source_clock' && i === 0 ? 0 : 1)))
|
|
72
|
+
throw Error('STORE_SCHEMA_UNSUPPORTED');
|
|
73
|
+
if (db.prepare('SELECT strict FROM pragma_table_list WHERE name=?').get(table)?.strict !== 1)
|
|
74
|
+
throw Error('STORE_SCHEMA_UNSUPPORTED');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** A manual correction inherits only the intersection of still-authorized source destinations. */
|
|
78
|
+
export function correctionProcessingGrant(db, sourceIds) {
|
|
79
|
+
if (!sourceIds.length)
|
|
80
|
+
return null;
|
|
81
|
+
const sources = [...new Set(sourceIds)], grants = sources.map(source => readProcessingGrant(db, source));
|
|
82
|
+
if (grants.some(grant => grant === null))
|
|
83
|
+
return null;
|
|
84
|
+
const first = grants[0];
|
|
85
|
+
const authorized = (purpose, provider) => provider !== null && sources.every(source => allowsProcessing(db, source, purpose, provider));
|
|
86
|
+
const extraction = authorized('extraction', first.extraction_provider) ? first.extraction_provider : null;
|
|
87
|
+
const embedding = authorized('embedding', first.embedding_provider) ? first.embedding_provider : null;
|
|
88
|
+
const conversations = (first.conversation_providers ?? []).filter(provider => authorized('conversation', provider));
|
|
89
|
+
if (extraction === null && embedding === null && !conversations.length)
|
|
90
|
+
return null;
|
|
91
|
+
return { revision: 1, scope_revision: 0, extraction_provider: extraction, embedding_provider: embedding, conversation_providers: conversations };
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=source-state.js.map
|