nova-personal-agent-server 0.4.0 → 1.0.2
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 +674 -201
- package/README.md +12 -2
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +13 -6
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
1
3
|
import { Worker } from 'node:worker_threads';
|
|
4
|
+
import { hasOnlyKeys, isRecord } from '../core/guards.js';
|
|
2
5
|
const clientErrorMessages = {
|
|
3
6
|
CLIENT_CLOSED: 'memory ledger store client is closed',
|
|
4
7
|
WORKER_ERROR: 'memory ledger worker failed',
|
|
5
8
|
WORKER_EXITED: 'memory ledger worker exited',
|
|
6
9
|
WORKER_PROTOCOL_FAILURE: 'memory ledger worker protocol failure',
|
|
10
|
+
WORKER_RECYCLED: 'memory ledger worker was replaced after a stuck request',
|
|
11
|
+
REQUEST_ABORTED: 'memory ledger request was aborted',
|
|
7
12
|
STORE_ALREADY_OPEN: 'memory ledger store is already open',
|
|
8
13
|
STORE_CLOSED: 'memory ledger store is closed',
|
|
9
14
|
STORE_IDEMPOTENCY_CONFLICT: 'memory ledger observation replay conflict',
|
|
@@ -36,12 +41,40 @@ const nullResult = value => {
|
|
|
36
41
|
if (value !== null)
|
|
37
42
|
throw new TypeError('invalid null RPC result');
|
|
38
43
|
};
|
|
44
|
+
const priorityRank = { interactive: 0, normal: 1, background: 2, close: 3 };
|
|
45
|
+
const backgroundContext = new AsyncLocalStorage();
|
|
46
|
+
/** Memory requests issued anywhere inside `work`, including after awaits, yield to everything else. */
|
|
47
|
+
export function runInMemoryBackground(work) {
|
|
48
|
+
return backgroundContext.run(true, work);
|
|
49
|
+
}
|
|
50
|
+
/** A synchronous worker op cannot be cancelled; after this grace the worker is replaced instead. */
|
|
51
|
+
const STUCK_GRACE_MS = 30_000;
|
|
52
|
+
const CLOSE_TIMEOUT_MS = 5_000;
|
|
53
|
+
// Include compound operations: they may change evidence, revisions, or consumer grants internally.
|
|
54
|
+
const recallAuthorityMutations = new Set([
|
|
55
|
+
'space_source_input', 'explicit_write', 'source_processing', 'append_evidence_batch',
|
|
56
|
+
'invalidate_message', 'purge_index_complete', 'purge', 'enable_files', 'commit_diary',
|
|
57
|
+
'commit_consolidation', 'life_load', 'life_mutate', 'life_capture_im', 'append_evidence', 'merge',
|
|
58
|
+
'delete_source', 'forget', 'record_extraction', 'record_evidence_batch',
|
|
59
|
+
'migrate_legacy', 'source_connection', 'source_apply_page', 'invalidate_evidence',
|
|
60
|
+
'source_grant', 'commit_extraction',
|
|
61
|
+
]);
|
|
39
62
|
export class MemoryLedgerClient {
|
|
40
63
|
#workerFactory;
|
|
41
64
|
#workerUrl = new URL('./store-worker.js', import.meta.url);
|
|
42
65
|
#workerData;
|
|
43
66
|
#worker;
|
|
67
|
+
#authorizationFence = randomUUID();
|
|
44
68
|
#pending = new Map();
|
|
69
|
+
#queue = [];
|
|
70
|
+
#inService = null;
|
|
71
|
+
#dropped = new Set();
|
|
72
|
+
#abandonedInService = null;
|
|
73
|
+
#recycleTimer = null;
|
|
74
|
+
#reopenTimer = null;
|
|
75
|
+
#recycleFailures = 0;
|
|
76
|
+
#recallAuthorityRevision = 0;
|
|
77
|
+
#observedAuthorityEpoch;
|
|
45
78
|
#nextRequestId = 1;
|
|
46
79
|
#failed = false;
|
|
47
80
|
#closed = false;
|
|
@@ -57,13 +90,46 @@ export class MemoryLedgerClient {
|
|
|
57
90
|
?? ((url, configured) => new Worker(url, configured));
|
|
58
91
|
this.#worker = this.#spawnWorker();
|
|
59
92
|
}
|
|
60
|
-
|
|
61
|
-
|
|
93
|
+
recallAuthorityRevision() { return this.#recallAuthorityRevision; }
|
|
94
|
+
async lifeAuthorizationRevision(namespace, signal) {
|
|
95
|
+
const fence = this.#authorizationFence;
|
|
96
|
+
const revision = await this.#request('life_authorization_revision', { namespace }, value => {
|
|
97
|
+
const counter = (item) => typeof item === 'number' && Number.isSafeInteger(item) && item >= 0;
|
|
98
|
+
if (!Array.isArray(value) || value.length !== 4 || (value[0] !== null && !counter(value[0])) || !counter(value[1]) || !counter(value[2])
|
|
99
|
+
|| !Array.isArray(value[3]) || value[3].length > 256 || !value[3].every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === 'string' && item[0].length > 0 && item[0].length <= 512 && !item[0].includes('\0') && counter(item[1])))
|
|
100
|
+
throw new TypeError('invalid life authorization revision');
|
|
101
|
+
return value;
|
|
102
|
+
}, priorityRank.interactive, signal);
|
|
103
|
+
if (fence !== this.#authorizationFence)
|
|
104
|
+
throw new MemoryLedgerClientError('WORKER_RECYCLED');
|
|
105
|
+
return createHash('sha256').update(JSON.stringify([fence, revision])).digest('hex');
|
|
106
|
+
}
|
|
107
|
+
memory(operation, input, options = {}) {
|
|
108
|
+
const priority = options.priority ?? (backgroundContext.getStore() ? 'background' : 'normal');
|
|
109
|
+
// Evidence reads run expiry maintenance; no-op expiry must not invalidate every consume.
|
|
110
|
+
if (operation === 'expire')
|
|
111
|
+
return this.#request('memory', { memoryOperation: operation, input }, value => value, priorityRank[priority], options.signal)
|
|
112
|
+
.then(result => { if (typeof result === 'number' && result > 0)
|
|
113
|
+
this.#recallAuthorityRevision++; return result; });
|
|
114
|
+
const mutates = recallAuthorityMutations.has(operation)
|
|
115
|
+
&& !(operation === 'source_grant' && isRecord(input) && input.action === 'get')
|
|
116
|
+
&& !(operation === 'source_connection' && isRecord(input) && ['get', 'list'].includes(String(input.action)))
|
|
117
|
+
&& !(operation === 'life_load' && isRecord(input) && input.legacy === undefined);
|
|
118
|
+
if (!mutates)
|
|
119
|
+
return this.#request('memory', { memoryOperation: operation, input }, value => value, priorityRank[priority], options.signal);
|
|
120
|
+
// Fence both newly queued and previously in-flight mutations, including failed/partial writes.
|
|
121
|
+
this.#recallAuthorityRevision++;
|
|
122
|
+
return this.#request('memory', { memoryOperation: operation, input }, value => value, priorityRank[priority], options.signal)
|
|
123
|
+
.finally(() => { this.#recallAuthorityRevision++; });
|
|
62
124
|
}
|
|
63
125
|
async open() {
|
|
64
126
|
if (this.#closed || this.#failed)
|
|
65
127
|
throw new MemoryLedgerClientError('CLIENT_CLOSED');
|
|
66
|
-
this.#opening ??= this.#request('open', {}, nullResult)
|
|
128
|
+
this.#opening ??= this.#request('open', {}, nullResult).catch((error) => {
|
|
129
|
+
// A transient open failure must not memoize a dead client; the next admission retries.
|
|
130
|
+
this.#opening = null;
|
|
131
|
+
throw error;
|
|
132
|
+
});
|
|
67
133
|
await this.#opening;
|
|
68
134
|
}
|
|
69
135
|
close() {
|
|
@@ -77,10 +143,25 @@ export class MemoryLedgerClient {
|
|
|
77
143
|
}
|
|
78
144
|
async #closeFresh() {
|
|
79
145
|
this.#closed = true;
|
|
80
|
-
if (
|
|
81
|
-
|
|
82
|
-
|
|
146
|
+
if (this.#recycleTimer !== null) {
|
|
147
|
+
clearTimeout(this.#recycleTimer);
|
|
148
|
+
this.#recycleTimer = null;
|
|
83
149
|
}
|
|
150
|
+
if (this.#reopenTimer !== null) {
|
|
151
|
+
clearTimeout(this.#reopenTimer);
|
|
152
|
+
this.#reopenTimer = null;
|
|
153
|
+
}
|
|
154
|
+
// An abandoned in-service op will never free its slot; do not wait for a close RPC behind it.
|
|
155
|
+
const abandonedInService = this.#inService !== null && this.#dropped.has(this.#inService);
|
|
156
|
+
this.#abandonedInService = null;
|
|
157
|
+
if (!this.#failed && !abandonedInService) {
|
|
158
|
+
// Drain queued work and its lock cleanup before termination; bound a stuck worker.
|
|
159
|
+
await Promise.race([
|
|
160
|
+
this.#requestWhileClosing('close', {}, nullResult).catch(() => undefined),
|
|
161
|
+
new Promise(resolve => { const timer = setTimeout(resolve, CLOSE_TIMEOUT_MS); timer.unref?.(); }),
|
|
162
|
+
]);
|
|
163
|
+
}
|
|
164
|
+
this.#dropped.clear();
|
|
84
165
|
this.#expectedExit = true;
|
|
85
166
|
try {
|
|
86
167
|
await this.#worker.terminate();
|
|
@@ -88,36 +169,127 @@ export class MemoryLedgerClient {
|
|
|
88
169
|
catch {
|
|
89
170
|
// A worker that already exited is closed for client lifecycle purposes.
|
|
90
171
|
}
|
|
91
|
-
|
|
92
|
-
for (const pending of this.#pending.values())
|
|
93
|
-
pending.reject(error);
|
|
94
|
-
this.#pending.clear();
|
|
172
|
+
this.#rejectAll(new MemoryLedgerClientError('CLIENT_CLOSED'));
|
|
95
173
|
}
|
|
96
|
-
#request(operation, payload, validateResult) {
|
|
174
|
+
#request(operation, payload, validateResult, rank = priorityRank.normal, signal) {
|
|
97
175
|
if (this.#closed || this.#failed) {
|
|
98
176
|
return Promise.reject(new MemoryLedgerClientError('CLIENT_CLOSED'));
|
|
99
177
|
}
|
|
100
|
-
return this.#send(operation, payload, validateResult);
|
|
178
|
+
return this.#send(operation, payload, validateResult, rank, signal);
|
|
101
179
|
}
|
|
102
180
|
#requestWhileClosing(operation, payload, validateResult) {
|
|
103
181
|
if (this.#failed)
|
|
104
182
|
return Promise.reject(new MemoryLedgerClientError('CLIENT_CLOSED'));
|
|
105
|
-
|
|
183
|
+
// Nothing is accepted once closing starts, so the lowest rank makes close the last request served.
|
|
184
|
+
return this.#send(operation, payload, validateResult, priorityRank.close);
|
|
106
185
|
}
|
|
107
|
-
#send(operation, payload, validateResult) {
|
|
186
|
+
#send(operation, payload, validateResult, rank, signal) {
|
|
108
187
|
const requestId = this.#nextRequestId;
|
|
109
188
|
this.#nextRequestId += 1;
|
|
110
|
-
const
|
|
111
|
-
|
|
189
|
+
const message = { kind: 'request', request_id: requestId, operation, ...payload };
|
|
190
|
+
let detach = () => { };
|
|
191
|
+
const promise = new Promise((resolve, reject) => {
|
|
112
192
|
this.#pending.set(requestId, { resolve: value => resolve(value), reject, validateResult });
|
|
193
|
+
// Stable: equal ranks keep arrival order.
|
|
194
|
+
const at = this.#queue.findIndex(queued => queued.rank > rank);
|
|
195
|
+
this.#queue.splice(at < 0 ? this.#queue.length : at, 0, { requestId, rank, message });
|
|
196
|
+
const onAbort = () => {
|
|
197
|
+
if (!this.#pending.has(requestId))
|
|
198
|
+
return;
|
|
199
|
+
this.#pending.delete(requestId);
|
|
200
|
+
reject(new MemoryLedgerClientError('REQUEST_ABORTED'));
|
|
201
|
+
const queuedIndex = this.#queue.findIndex(queued => queued.requestId === requestId);
|
|
202
|
+
if (queuedIndex >= 0) {
|
|
203
|
+
this.#queue.splice(queuedIndex, 1);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
// The worker is synchronous: mark the response as dropped and replace the worker if it
|
|
207
|
+
// still has not answered after the grace period, so the next read is not stuck behind it.
|
|
208
|
+
if (this.#inService === requestId) {
|
|
209
|
+
this.#dropped.add(requestId);
|
|
210
|
+
this.#abandonedInService = requestId;
|
|
211
|
+
this.#armRecycleTimer();
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
215
|
+
detach = () => signal?.removeEventListener('abort', onAbort);
|
|
216
|
+
if (signal?.aborted === true)
|
|
217
|
+
onAbort();
|
|
218
|
+
this.#dispatch();
|
|
219
|
+
});
|
|
220
|
+
return signal === undefined ? promise : promise.finally(detach);
|
|
221
|
+
}
|
|
222
|
+
#armRecycleTimer() {
|
|
223
|
+
if (this.#recycleTimer !== null)
|
|
224
|
+
return;
|
|
225
|
+
this.#recycleTimer = setTimeout(() => {
|
|
226
|
+
this.#recycleTimer = null;
|
|
227
|
+
if (this.#abandonedInService === null || this.#closed)
|
|
228
|
+
return;
|
|
229
|
+
this.#recycleWorker('WORKER_RECYCLED');
|
|
230
|
+
}, STUCK_GRACE_MS);
|
|
231
|
+
this.#recycleTimer.unref?.();
|
|
232
|
+
}
|
|
233
|
+
/** Replace a worker stuck on a synchronous op; the next `open()` re-establishes the store. */
|
|
234
|
+
#recycleWorker(code) {
|
|
235
|
+
if (this.#closed || this.#expectedExit)
|
|
236
|
+
return;
|
|
237
|
+
// Reopening loses TEMP session consent even when the persistent authority epoch is unchanged.
|
|
238
|
+
this.#recallAuthorityRevision++;
|
|
239
|
+
const previous = this.#worker;
|
|
240
|
+
this.#abandonedInService = null;
|
|
241
|
+
if (this.#recycleTimer !== null) {
|
|
242
|
+
clearTimeout(this.#recycleTimer);
|
|
243
|
+
this.#recycleTimer = null;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
this.#worker = this.#spawnWorker();
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
this.#fail('WORKER_ERROR');
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
this.#opening = null;
|
|
253
|
+
this.#dropped.clear();
|
|
254
|
+
this.#rejectAll(new MemoryLedgerClientError(code));
|
|
255
|
+
void previous.terminate().catch(() => undefined);
|
|
256
|
+
// The resource is opened once at assembly, so a replaced worker must reopen itself; otherwise
|
|
257
|
+
// every later read would stay STORE_CLOSED for the rest of the process. A transient lock/sync
|
|
258
|
+
// failure is retried with bounded backoff instead of waiting for a caller that never opens.
|
|
259
|
+
this.#scheduleReopen(250);
|
|
260
|
+
}
|
|
261
|
+
#scheduleReopen(delayMs) {
|
|
262
|
+
if (this.#closed || this.#failed || this.#reopenTimer !== null)
|
|
263
|
+
return;
|
|
264
|
+
this.#reopenTimer = setTimeout(() => {
|
|
265
|
+
this.#reopenTimer = null;
|
|
266
|
+
if (this.#closed || this.#failed)
|
|
267
|
+
return;
|
|
268
|
+
this.open().catch(() => this.#scheduleReopen(Math.min(5_000, delayMs * 2)));
|
|
269
|
+
}, delayMs);
|
|
270
|
+
this.#reopenTimer.unref?.();
|
|
271
|
+
}
|
|
272
|
+
#dispatch() {
|
|
273
|
+
while (this.#inService === null && !this.#failed) {
|
|
274
|
+
const next = this.#queue.shift();
|
|
275
|
+
if (next === undefined)
|
|
276
|
+
return;
|
|
113
277
|
try {
|
|
114
|
-
this.#worker.postMessage(
|
|
278
|
+
this.#worker.postMessage(next.message);
|
|
279
|
+
this.#inService = next.requestId;
|
|
115
280
|
}
|
|
116
281
|
catch {
|
|
117
|
-
this.#pending.
|
|
118
|
-
|
|
282
|
+
this.#pending.get(next.requestId)?.reject(new MemoryLedgerClientError('WORKER_PROTOCOL_FAILURE'));
|
|
283
|
+
this.#pending.delete(next.requestId);
|
|
119
284
|
}
|
|
120
|
-
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
#rejectAll(error) {
|
|
288
|
+
this.#queue.length = 0;
|
|
289
|
+
this.#inService = null;
|
|
290
|
+
for (const pending of this.#pending.values())
|
|
291
|
+
pending.reject(error);
|
|
292
|
+
this.#pending.clear();
|
|
121
293
|
}
|
|
122
294
|
#handleMessage(worker, message) {
|
|
123
295
|
if (worker !== this.#worker)
|
|
@@ -127,14 +299,34 @@ export class MemoryLedgerClient {
|
|
|
127
299
|
this.#fail('WORKER_PROTOCOL_FAILURE');
|
|
128
300
|
return;
|
|
129
301
|
}
|
|
302
|
+
this.#recycleFailures = 0;
|
|
303
|
+
// Apply committed implicit writes before resolving (or dropping) even a nominal read.
|
|
304
|
+
if (response.authority_epoch !== undefined) {
|
|
305
|
+
if (response.authority_epoch !== this.#observedAuthorityEpoch)
|
|
306
|
+
this.#recallAuthorityRevision++;
|
|
307
|
+
this.#observedAuthorityEpoch = response.authority_epoch;
|
|
308
|
+
}
|
|
309
|
+
if (response.authority_changed)
|
|
310
|
+
this.#recallAuthorityRevision++;
|
|
311
|
+
if (this.#dropped.delete(response.request_id)) {
|
|
312
|
+
// An abandoned read finished late; free its service slot without delivering a result.
|
|
313
|
+
if (this.#inService === response.request_id)
|
|
314
|
+
this.#inService = null;
|
|
315
|
+
if (this.#abandonedInService === response.request_id)
|
|
316
|
+
this.#abandonedInService = null;
|
|
317
|
+
this.#dispatch();
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
130
320
|
const pending = this.#pending.get(response.request_id);
|
|
131
|
-
if (pending === undefined) {
|
|
321
|
+
if (pending === undefined || response.request_id !== this.#inService) {
|
|
132
322
|
this.#fail('WORKER_PROTOCOL_FAILURE');
|
|
133
323
|
return;
|
|
134
324
|
}
|
|
135
325
|
if (!response.ok) {
|
|
136
326
|
this.#pending.delete(response.request_id);
|
|
327
|
+
this.#inService = null;
|
|
137
328
|
pending.reject(new MemoryLedgerClientError(response.error_code));
|
|
329
|
+
this.#dispatch();
|
|
138
330
|
return;
|
|
139
331
|
}
|
|
140
332
|
let result;
|
|
@@ -146,18 +338,18 @@ export class MemoryLedgerClient {
|
|
|
146
338
|
return;
|
|
147
339
|
}
|
|
148
340
|
this.#pending.delete(response.request_id);
|
|
341
|
+
this.#inService = null;
|
|
149
342
|
pending.resolve(result);
|
|
343
|
+
this.#dispatch();
|
|
150
344
|
}
|
|
151
345
|
#fail(code) {
|
|
152
346
|
if (this.#failed || this.#expectedExit)
|
|
153
347
|
return;
|
|
154
348
|
this.#failed = true;
|
|
155
|
-
|
|
156
|
-
for (const pending of this.#pending.values())
|
|
157
|
-
pending.reject(error);
|
|
158
|
-
this.#pending.clear();
|
|
349
|
+
this.#rejectAll(new MemoryLedgerClientError(code));
|
|
159
350
|
}
|
|
160
351
|
#spawnWorker() {
|
|
352
|
+
this.#authorizationFence = randomUUID();
|
|
161
353
|
const worker = this.#workerFactory(this.#workerUrl, { workerData: this.#workerData });
|
|
162
354
|
worker.on('message', message => this.#handleMessage(worker, message));
|
|
163
355
|
worker.on('error', () => this.#handleWorkerFailure(worker, 'WORKER_ERROR'));
|
|
@@ -170,29 +362,42 @@ export class MemoryLedgerClient {
|
|
|
170
362
|
#handleWorkerFailure(worker, code) {
|
|
171
363
|
if (worker !== this.#worker || this.#failed || this.#expectedExit)
|
|
172
364
|
return;
|
|
173
|
-
this.#
|
|
365
|
+
if (this.#closed) {
|
|
366
|
+
this.#rejectAll(new MemoryLedgerClientError(code));
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
// Bound a crash loop (bad module, thread exhaustion) instead of respawning forever.
|
|
370
|
+
if (this.#recycleFailures >= 3) {
|
|
371
|
+
this.#fail('WORKER_ERROR');
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
this.#recycleFailures += 1;
|
|
375
|
+
this.#recycleWorker(code);
|
|
174
376
|
}
|
|
175
377
|
}
|
|
176
378
|
function parseWorkerResponse(message) {
|
|
177
379
|
if (!isRecord(message)
|
|
178
380
|
|| message.kind !== 'response'
|
|
179
381
|
|| !Number.isSafeInteger(message.request_id)
|
|
180
|
-
|| message.request_id <= 0
|
|
382
|
+
|| message.request_id <= 0
|
|
383
|
+
|| (message.authority_epoch !== undefined && (!Number.isSafeInteger(message.authority_epoch) || message.authority_epoch < 0))
|
|
384
|
+
|| (message.authority_changed !== undefined && typeof message.authority_changed !== 'boolean')) {
|
|
181
385
|
return undefined;
|
|
182
386
|
}
|
|
183
387
|
if (message.ok === true && 'result' in message) {
|
|
184
|
-
if (!hasOnlyKeys(message, ['kind', 'request_id', 'ok', 'result']))
|
|
388
|
+
if (!hasOnlyKeys(message, ['kind', 'request_id', 'ok', 'result', 'authority_changed', 'authority_epoch']))
|
|
185
389
|
return undefined;
|
|
186
|
-
return { kind: 'response', request_id: message.request_id, ok: true, result: message.result };
|
|
390
|
+
return { kind: 'response', request_id: message.request_id, ok: true, result: message.result, ...(message.authority_epoch === undefined ? {} : { authority_epoch: message.authority_epoch }), ...(message.authority_changed === undefined ? {} : { authority_changed: message.authority_changed }) };
|
|
187
391
|
}
|
|
188
392
|
if (message.ok === false && isStoreErrorCode(message.error_code)) {
|
|
189
|
-
if (!hasOnlyKeys(message, ['kind', 'request_id', 'ok', 'error_code']))
|
|
393
|
+
if (!hasOnlyKeys(message, ['kind', 'request_id', 'ok', 'error_code', 'authority_changed', 'authority_epoch']))
|
|
190
394
|
return undefined;
|
|
191
395
|
return {
|
|
192
396
|
kind: 'response',
|
|
193
397
|
request_id: message.request_id,
|
|
194
398
|
ok: false,
|
|
195
399
|
error_code: message.error_code,
|
|
400
|
+
...(message.authority_epoch === undefined ? {} : { authority_epoch: message.authority_epoch }), ...(message.authority_changed === undefined ? {} : { authority_changed: message.authority_changed }),
|
|
196
401
|
};
|
|
197
402
|
}
|
|
198
403
|
return undefined;
|
|
@@ -200,11 +405,4 @@ function parseWorkerResponse(message) {
|
|
|
200
405
|
function isStoreErrorCode(value) {
|
|
201
406
|
return typeof value === 'string' && value in clientErrorMessages && value.startsWith('STORE_');
|
|
202
407
|
}
|
|
203
|
-
function isRecord(value) {
|
|
204
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
205
|
-
}
|
|
206
|
-
function hasOnlyKeys(value, allowed) {
|
|
207
|
-
const allowedKeys = new Set(allowed);
|
|
208
|
-
return Object.keys(value).every(key => allowedKeys.has(key));
|
|
209
|
-
}
|
|
210
408
|
//# sourceMappingURL=store-client.js.map
|
|
@@ -5,6 +5,7 @@ import { preparePrivateDatabasePath, secureSidecar } from '../storage/private-da
|
|
|
5
5
|
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
6
6
|
import { DatabaseSync } from 'node:sqlite';
|
|
7
7
|
import { MemoryLedgerStore, MemoryLedgerStoreError } from './store.js';
|
|
8
|
+
import { isRecord } from '../core/guards.js';
|
|
8
9
|
if (isMainThread || parentPort === null) {
|
|
9
10
|
throw new Error('memory ledger worker cannot run on the main thread');
|
|
10
11
|
}
|
|
@@ -22,8 +23,9 @@ port.on('message', message => {
|
|
|
22
23
|
port.postMessage({ kind: 'protocol_error' });
|
|
23
24
|
return;
|
|
24
25
|
}
|
|
26
|
+
const authorityRevision = store.recallAuthorityRevision();
|
|
25
27
|
try {
|
|
26
|
-
const result = store.withMemoryFilesLock(() => {
|
|
28
|
+
const result = request.operation === 'life_authorization_revision' ? execute(request) : store.withMemoryFilesLock(() => {
|
|
27
29
|
if (request.operation !== 'memory' && request.operation !== 'close')
|
|
28
30
|
store.syncMemoryFiles();
|
|
29
31
|
const response = execute(request);
|
|
@@ -31,7 +33,7 @@ port.on('message', message => {
|
|
|
31
33
|
store.flushMemoryFiles();
|
|
32
34
|
return response;
|
|
33
35
|
});
|
|
34
|
-
port.postMessage({ kind: 'response', request_id: request.request_id, ok: true, result });
|
|
36
|
+
port.postMessage({ kind: 'response', request_id: request.request_id, ok: true, result, authority_changed: store.recallAuthorityRevision() !== authorityRevision, authority_epoch: store.recallAuthorityEpoch() });
|
|
35
37
|
}
|
|
36
38
|
catch (error) {
|
|
37
39
|
port.postMessage({
|
|
@@ -39,11 +41,15 @@ port.on('message', message => {
|
|
|
39
41
|
request_id: request.request_id,
|
|
40
42
|
ok: false,
|
|
41
43
|
error_code: safeErrorCode(error),
|
|
44
|
+
authority_changed: store.recallAuthorityRevision() !== authorityRevision,
|
|
45
|
+
authority_epoch: store.recallAuthorityEpoch(),
|
|
42
46
|
});
|
|
43
47
|
}
|
|
44
48
|
});
|
|
45
49
|
function execute(request) {
|
|
46
50
|
switch (request.operation) {
|
|
51
|
+
case 'life_authorization_revision':
|
|
52
|
+
return store.lifeAuthorizationRevision(stringField(request, 'namespace'));
|
|
47
53
|
case 'memory': {
|
|
48
54
|
const operation = stringField(request, 'memoryOperation');
|
|
49
55
|
return store.memory(operation, request.input, path => new DatabaseSync(path, { readOnly: true, allowExtension: false }));
|
|
@@ -93,9 +99,6 @@ function stringField(request, key) {
|
|
|
93
99
|
function safeErrorCode(error) {
|
|
94
100
|
return error instanceof MemoryLedgerStoreError ? error.code : error instanceof Error && error.message.startsWith('MEMORY_MARKDOWN_') ? 'STORE_MEMORY_CONFLICT' : 'STORE_WRITE_FAILED';
|
|
95
101
|
}
|
|
96
|
-
function isRecord(value) {
|
|
97
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
98
|
-
}
|
|
99
102
|
/** Upgrade owner-held ledger files before they can receive raw personal evidence. */
|
|
100
103
|
function privateLedgerPath(input) {
|
|
101
104
|
// macOS exposes system temp directories through fixed OS-owned aliases.
|
|
@@ -134,6 +134,8 @@ export class MemoryLedgerStore {
|
|
|
134
134
|
#databaseFactory;
|
|
135
135
|
#database;
|
|
136
136
|
#memoryLockHeld = false;
|
|
137
|
+
#recallAuthorityRevision = 0;
|
|
138
|
+
#recallAuthorityEpoch = 0;
|
|
137
139
|
#fileRepository;
|
|
138
140
|
constructor(path, databaseFactory, options = {}) {
|
|
139
141
|
this.#path = path;
|
|
@@ -145,12 +147,15 @@ export class MemoryLedgerStore {
|
|
|
145
147
|
if (this.#database !== undefined)
|
|
146
148
|
throw new MemoryLedgerStoreError('STORE_ALREADY_OPEN');
|
|
147
149
|
let database;
|
|
150
|
+
let trackingAuthority = false;
|
|
148
151
|
try {
|
|
149
152
|
database = this.#databaseFactory(this.#path);
|
|
150
153
|
database.exec('PRAGMA busy_timeout=1000');
|
|
151
154
|
database.exec('PRAGMA foreign_keys=ON');
|
|
152
155
|
this.#migrate(database);
|
|
153
156
|
initializeMemory(database);
|
|
157
|
+
this.#trackRecallAuthority(database);
|
|
158
|
+
trackingAuthority = true;
|
|
154
159
|
recoverMemoryPurges(database, this.#path);
|
|
155
160
|
const authoritative = hasMemoryFileAuthority(database, this.#path + '.memory');
|
|
156
161
|
if (authoritative) {
|
|
@@ -181,6 +186,10 @@ export class MemoryLedgerStore {
|
|
|
181
186
|
}
|
|
182
187
|
catch (error) {
|
|
183
188
|
try {
|
|
189
|
+
if (database && trackingAuthority) {
|
|
190
|
+
this.#recallAuthorityRevision = this.#readRecallAuthorityRevision(database);
|
|
191
|
+
this.#recallAuthorityEpoch = this.#readRecallAuthorityEpoch(database);
|
|
192
|
+
}
|
|
184
193
|
database?.close();
|
|
185
194
|
}
|
|
186
195
|
catch {
|
|
@@ -193,6 +202,80 @@ export class MemoryLedgerStore {
|
|
|
193
202
|
throw new MemoryLedgerStoreError('STORE_MIGRATION_FAILED');
|
|
194
203
|
}
|
|
195
204
|
}
|
|
205
|
+
/** Shared transactional epoch; older clients' writes also fire these persistent triggers. */
|
|
206
|
+
#trackRecallAuthority(db) {
|
|
207
|
+
db.exec('BEGIN IMMEDIATE');
|
|
208
|
+
try {
|
|
209
|
+
db.exec(`CREATE TABLE IF NOT EXISTS recall_authority_epoch(
|
|
210
|
+
slot INTEGER PRIMARY KEY CHECK(slot=1), value INTEGER NOT NULL
|
|
211
|
+
) STRICT;
|
|
212
|
+
INSERT OR IGNORE INTO recall_authority_epoch VALUES(1,0)`);
|
|
213
|
+
const tables = [
|
|
214
|
+
'memory_evidence', 'memory_message_heads', 'memory_revisions', 'memory_suppressed',
|
|
215
|
+
'memory_deleted_sources', 'memory_legacy_suppressed', 'memory_purged_ids',
|
|
216
|
+
'source_grants', 'source_connections', 'source_objects', 'processing_profiles',
|
|
217
|
+
];
|
|
218
|
+
for (const table of tables)
|
|
219
|
+
this.#createAuthorityTriggers(db, table, false);
|
|
220
|
+
db.exec('COMMIT');
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
rollback(db);
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
// Session consent is genuinely connection-local and cannot use a persistent trigger.
|
|
227
|
+
db.exec(`CREATE TEMP TABLE recall_authority_revision(value INTEGER NOT NULL);
|
|
228
|
+
INSERT INTO recall_authority_revision VALUES(${this.#recallAuthorityRevision})`);
|
|
229
|
+
this.#createAuthorityTriggers(db, 'source_session_consents', true);
|
|
230
|
+
}
|
|
231
|
+
#createAuthorityTriggers(db, table, temporary) {
|
|
232
|
+
const changed = db.prepare(`PRAGMA table_info(${table})`).all()
|
|
233
|
+
.map(column => `OLD.${String(column.name)} IS NOT NEW.${String(column.name)}`).join(' OR ');
|
|
234
|
+
for (const event of ['INSERT', 'UPDATE', 'DELETE'])
|
|
235
|
+
db.exec(`
|
|
236
|
+
CREATE ${temporary ? 'TEMP' : ''} TRIGGER IF NOT EXISTS recall_authority_${table}_${event}
|
|
237
|
+
AFTER ${event} ON ${temporary ? 'temp' : 'main'}.${table}
|
|
238
|
+
${event === 'UPDATE' ? `WHEN ${changed}` : ''}
|
|
239
|
+
BEGIN UPDATE ${temporary ? 'recall_authority_revision' : 'recall_authority_epoch'} SET value=value+1; END`);
|
|
240
|
+
}
|
|
241
|
+
#readRecallAuthorityEpoch(db) {
|
|
242
|
+
return Number(db.prepare('SELECT value FROM main.recall_authority_epoch WHERE slot=1').get()?.value ?? this.#recallAuthorityEpoch);
|
|
243
|
+
}
|
|
244
|
+
recallAuthorityEpoch() {
|
|
245
|
+
return this.#database ? this.#readRecallAuthorityEpoch(this.#database) : this.#recallAuthorityEpoch;
|
|
246
|
+
}
|
|
247
|
+
#readRecallAuthorityRevision(db) {
|
|
248
|
+
return Number(db.prepare('SELECT value FROM temp.recall_authority_revision').get()?.value ?? this.#recallAuthorityRevision);
|
|
249
|
+
}
|
|
250
|
+
recallAuthorityRevision() {
|
|
251
|
+
return this.#database ? this.#readRecallAuthorityRevision(this.#database) : this.#recallAuthorityRevision;
|
|
252
|
+
}
|
|
253
|
+
/** Indexed metadata only; consumers must separately revalidate purely time-sensitive evidence eligibility. */
|
|
254
|
+
lifeAuthorizationRevision(namespace) {
|
|
255
|
+
z.string().min(1).max(256).endsWith(':life:').parse(namespace);
|
|
256
|
+
try {
|
|
257
|
+
const row = this.#requireDatabase().prepare(`SELECT
|
|
258
|
+
EXISTS(SELECT 1 FROM memory_life_meta WHERE namespace=?) AS life_present,
|
|
259
|
+
(SELECT json_type(payload_json,'$.revision') FROM memory_life_meta WHERE namespace=?) AS life_type,
|
|
260
|
+
(SELECT json_extract(payload_json,'$.revision') FROM memory_life_meta WHERE namespace=?) AS life_revision,
|
|
261
|
+
(SELECT value FROM main.recall_authority_epoch WHERE slot=1) AS authority_epoch,
|
|
262
|
+
(SELECT value FROM temp.recall_authority_revision) AS session_revision,
|
|
263
|
+
(SELECT json_group_array(json_array(provider,revision)) FROM
|
|
264
|
+
(SELECT provider,revision FROM processing_profiles WHERE prefix=? ORDER BY provider LIMIT 257)) AS products
|
|
265
|
+
`).get(namespace, namespace, namespace, namespace.slice(0, -'life:'.length));
|
|
266
|
+
const counter = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
267
|
+
if (!row || !counter(row.authority_epoch) || !counter(row.session_revision)
|
|
268
|
+
|| (row.life_present === 1 ? (!['integer', 'real'].includes(String(row.life_type)) || !counter(row.life_revision)) : row.life_revision !== null))
|
|
269
|
+
throw Error('invalid_authority');
|
|
270
|
+
const products = JSON.parse(String(row.products));
|
|
271
|
+
if (!Array.isArray(products) || products.length > 256 || !products.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === 'string' && item[0].length > 0 && item[0].length <= 512 && !item[0].includes('\0') && counter(item[1])))
|
|
272
|
+
throw Error('invalid_product_authority');
|
|
273
|
+
return [row.life_present === 1 ? row.life_revision : null, row.authority_epoch, row.session_revision, products];
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
throw new MemoryLedgerStoreError('STORE_READ_FAILED');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
196
279
|
memory(operation, input, openLegacy) {
|
|
197
280
|
return this.withMemoryFilesLock(() => {
|
|
198
281
|
if (operation === 'enable_files') {
|
|
@@ -201,12 +284,17 @@ export class MemoryLedgerStore {
|
|
|
201
284
|
return { enabled: true };
|
|
202
285
|
}
|
|
203
286
|
try {
|
|
287
|
+
if (operation === 'flush_files') {
|
|
288
|
+
z.object({}).strict().parse(input);
|
|
289
|
+
this.#joinMemoryFileAuthority();
|
|
290
|
+
return { flushed: flushMemoryFiles(this.#requireDatabase()) };
|
|
291
|
+
}
|
|
204
292
|
if (operation === 'purge')
|
|
205
293
|
return purgeEntry(this.#requireDatabase(), this.#path, input);
|
|
206
294
|
if (operation === 'purge_index_complete')
|
|
207
295
|
return completePurgeIndex(this.#requireDatabase(), this.#path, input);
|
|
208
296
|
if (operation === 'purge_status')
|
|
209
|
-
return purgeStatus(this.#requireDatabase(), z.object({ entry_prefix: z.string().min(1) }).strict().parse(input).entry_prefix);
|
|
297
|
+
return purgeStatus(this.#requireDatabase(), z.object({ entry_prefix: z.string().min(1) }).strict().parse(input).entry_prefix, this.#path);
|
|
210
298
|
this.#joinMemoryFileAuthority();
|
|
211
299
|
return operation === 'migrate_legacy' ? migrateLegacyMemory(this.#requireDatabase(), input, openLegacy ?? (() => { throw new Error('STORE_INVALID_OPERATION'); })) : memoryOperation(this.#requireDatabase(), operation, input);
|
|
212
300
|
}
|
|
@@ -249,6 +337,8 @@ export class MemoryLedgerStore {
|
|
|
249
337
|
if (this.#database === undefined)
|
|
250
338
|
return;
|
|
251
339
|
const database = this.#database;
|
|
340
|
+
this.#recallAuthorityRevision = this.#readRecallAuthorityRevision(database);
|
|
341
|
+
this.#recallAuthorityEpoch = this.#readRecallAuthorityEpoch(database);
|
|
252
342
|
this.#database = undefined;
|
|
253
343
|
try {
|
|
254
344
|
database.close();
|