@fgv/ts-agent-memory 5.1.0-47 → 5.1.0-49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/packlets/ingest/orchestrator.js +11 -1
- package/dist/packlets/ingest/orchestrator.js.map +1 -1
- package/dist/packlets/observe/memoryObservationStore.js +6 -0
- package/dist/packlets/observe/memoryObservationStore.js.map +1 -1
- package/dist/packlets/observe/observer.js.map +1 -1
- package/dist/packlets/retrieve/linkTraversalRetriever.js +1 -1
- package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/dist/packlets/retrieve/retriever.js +11 -5
- package/dist/packlets/retrieve/retriever.js.map +1 -1
- package/dist/packlets/retrieve/structuredFilterRetriever.js +27 -5
- package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/dist/packlets/retrieve/tagRetriever.js +1 -1
- package/dist/packlets/retrieve/tagRetriever.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/dist/packlets/store/fileTreeMemoryStore.js +152 -132
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/store/vectorMaintenance.js +251 -0
- package/dist/packlets/store/vectorMaintenance.js.map +1 -0
- package/dist/packlets/types/envelope.js.map +1 -1
- package/dist/packlets/vector/inMemoryCosineIndex.js +81 -18
- package/dist/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/dist/packlets/vector/inMemoryFragmentCosineIndex.js +7 -0
- package/dist/packlets/vector/inMemoryFragmentCosineIndex.js.map +1 -1
- package/dist/packlets/vector/vectorIndex.js.map +1 -1
- package/dist/ts-agent-memory.d.ts +431 -79
- package/lib/packlets/ingest/orchestrator.d.ts.map +1 -1
- package/lib/packlets/ingest/orchestrator.js +11 -1
- package/lib/packlets/ingest/orchestrator.js.map +1 -1
- package/lib/packlets/observe/memoryObservationStore.d.ts.map +1 -1
- package/lib/packlets/observe/memoryObservationStore.js +6 -0
- package/lib/packlets/observe/memoryObservationStore.js.map +1 -1
- package/lib/packlets/observe/observer.d.ts +61 -0
- package/lib/packlets/observe/observer.d.ts.map +1 -1
- package/lib/packlets/observe/observer.js.map +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/lib/packlets/retrieve/recencyRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/lib/packlets/retrieve/retriever.d.ts +26 -7
- package/lib/packlets/retrieve/retriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/retriever.js +11 -5
- package/lib/packlets/retrieve/retriever.js.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts +26 -4
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.js +27 -5
- package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/lib/packlets/retrieve/tagRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/tagRetriever.js +1 -1
- package/lib/packlets/retrieve/tagRetriever.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +135 -59
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +151 -131
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/store/vectorMaintenance.d.ts +149 -0
- package/lib/packlets/store/vectorMaintenance.d.ts.map +1 -0
- package/lib/packlets/store/vectorMaintenance.js +255 -0
- package/lib/packlets/store/vectorMaintenance.js.map +1 -0
- package/lib/packlets/types/envelope.d.ts +11 -0
- package/lib/packlets/types/envelope.d.ts.map +1 -1
- package/lib/packlets/types/envelope.js.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts +30 -7
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.js +80 -17
- package/lib/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.d.ts +7 -0
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.d.ts.map +1 -1
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.js +7 -0
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.js.map +1 -1
- package/lib/packlets/vector/vectorIndex.d.ts +129 -1
- package/lib/packlets/vector/vectorIndex.d.ts.map +1 -1
- package/lib/packlets/vector/vectorIndex.js.map +1 -1
- package/package.json +17 -7
- package/.rush/temp/5667e36f1c0cc503a5c20a3ebff76e7b9a702d41.tar.log +0 -468
- package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +0 -9
- package/.rush/temp/operation/build/all.log +0 -9
- package/.rush/temp/operation/build/log-chunks.jsonl +0 -9
- package/.rush/temp/operation/build/state.json +0 -3
- package/.rush/temp/shrinkwrap-deps.json +0 -689
- package/config/api-extractor.json +0 -343
- package/config/jest.config.json +0 -14
- package/config/rig.json +0 -4
- package/dist/test/unit/converters/antagonistRoundTrip.test.js +0 -95
- package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +0 -1
- package/dist/test/unit/converters/bodyConverterRegistry.test.js +0 -72
- package/dist/test/unit/converters/bodyConverterRegistry.test.js.map +0 -1
- package/dist/test/unit/converters/envelopeConverter.test.js +0 -313
- package/dist/test/unit/converters/envelopeConverter.test.js.map +0 -1
- package/dist/test/unit/index/memoryIndex.test.js +0 -214
- package/dist/test/unit/index/memoryIndex.test.js.map +0 -1
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +0 -277
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +0 -1
- package/dist/test/unit/ingest/cycleGuard.test.js +0 -81
- package/dist/test/unit/ingest/cycleGuard.test.js.map +0 -1
- package/dist/test/unit/ingest/dedupScope.test.js +0 -434
- package/dist/test/unit/ingest/dedupScope.test.js.map +0 -1
- package/dist/test/unit/ingest/orchestrator.test.js +0 -1058
- package/dist/test/unit/ingest/orchestrator.test.js.map +0 -1
- package/dist/test/unit/observe/memoryObservationStore.test.js +0 -118
- package/dist/test/unit/observe/memoryObservationStore.test.js.map +0 -1
- package/dist/test/unit/retrieve/fragmentSemanticRetriever.test.js +0 -116
- package/dist/test/unit/retrieve/fragmentSemanticRetriever.test.js.map +0 -1
- package/dist/test/unit/retrieve/linkTraversalRetriever.test.js +0 -257
- package/dist/test/unit/retrieve/linkTraversalRetriever.test.js.map +0 -1
- package/dist/test/unit/retrieve/retrievers.test.js +0 -768
- package/dist/test/unit/retrieve/retrievers.test.js.map +0 -1
- package/dist/test/unit/retrieve/temporalRetrievers.test.js +0 -182
- package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +0 -1
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js +0 -120
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +0 -1
- package/dist/test/unit/store/embedOnWrite.test.js +0 -317
- package/dist/test/unit/store/embedOnWrite.test.js.map +0 -1
- package/dist/test/unit/store/fileTreeMemoryStore.test.js +0 -778
- package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +0 -1
- package/dist/test/unit/store/fragmentEmbedOnWrite.test.js +0 -255
- package/dist/test/unit/store/fragmentEmbedOnWrite.test.js.map +0 -1
- package/dist/test/unit/store/indexInjection.test.js +0 -432
- package/dist/test/unit/store/indexInjection.test.js.map +0 -1
- package/dist/test/unit/store/lenientOpen.test.js +0 -248
- package/dist/test/unit/store/lenientOpen.test.js.map +0 -1
- package/dist/test/unit/store/listScoped.test.js +0 -109
- package/dist/test/unit/store/listScoped.test.js.map +0 -1
- package/dist/test/unit/store/observations.test.js +0 -239
- package/dist/test/unit/store/observations.test.js.map +0 -1
- package/dist/test/unit/store/rankAxis.test.js +0 -254
- package/dist/test/unit/store/rankAxis.test.js.map +0 -1
- package/dist/test/unit/store/scopeEncoding.test.js +0 -24
- package/dist/test/unit/store/scopeEncoding.test.js.map +0 -1
- package/dist/test/unit/store/temporalStore.test.js +0 -398
- package/dist/test/unit/store/temporalStore.test.js.map +0 -1
- package/dist/test/unit/tools/memoryTools.test.js +0 -842
- package/dist/test/unit/tools/memoryTools.test.js.map +0 -1
- package/dist/test/unit/types/identityCodec.test.js +0 -187
- package/dist/test/unit/types/identityCodec.test.js.map +0 -1
- package/dist/test/unit/types/ids.test.js +0 -84
- package/dist/test/unit/types/ids.test.js.map +0 -1
- package/dist/test/unit/types/temporalCodec.test.js +0 -203
- package/dist/test/unit/types/temporalCodec.test.js.map +0 -1
- package/dist/test/unit/types/temporalPolicy.test.js +0 -83
- package/dist/test/unit/types/temporalPolicy.test.js.map +0 -1
- package/dist/test/unit/types/writePolicy.test.js +0 -331
- package/dist/test/unit/types/writePolicy.test.js.map +0 -1
- package/dist/test/unit/vector/fragmentConverters.test.js +0 -58
- package/dist/test/unit/vector/fragmentConverters.test.js.map +0 -1
- package/dist/test/unit/vector/inMemoryCosineIndex.test.js +0 -252
- package/dist/test/unit/vector/inMemoryCosineIndex.test.js.map +0 -1
- package/dist/test/unit/vector/inMemoryFragmentCosineIndex.test.js +0 -362
- package/dist/test/unit/vector/inMemoryFragmentCosineIndex.test.js.map +0 -1
- package/dist/test/unit/vector/vectorIndex.test.js +0 -51
- package/dist/test/unit/vector/vectorIndex.test.js.map +0 -1
- package/eslint.config.js +0 -15
- package/etc/ts-agent-memory.api.md +0 -940
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +0 -10
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +0 -1
- package/lib/test/unit/converters/antagonistRoundTrip.test.js +0 -97
- package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +0 -1
- package/lib/test/unit/converters/bodyConverterRegistry.test.d.ts +0 -2
- package/lib/test/unit/converters/bodyConverterRegistry.test.d.ts.map +0 -1
- package/lib/test/unit/converters/bodyConverterRegistry.test.js +0 -74
- package/lib/test/unit/converters/bodyConverterRegistry.test.js.map +0 -1
- package/lib/test/unit/converters/envelopeConverter.test.d.ts +0 -2
- package/lib/test/unit/converters/envelopeConverter.test.d.ts.map +0 -1
- package/lib/test/unit/converters/envelopeConverter.test.js +0 -315
- package/lib/test/unit/converters/envelopeConverter.test.js.map +0 -1
- package/lib/test/unit/index/memoryIndex.test.d.ts +0 -2
- package/lib/test/unit/index/memoryIndex.test.d.ts.map +0 -1
- package/lib/test/unit/index/memoryIndex.test.js +0 -216
- package/lib/test/unit/index/memoryIndex.test.js.map +0 -1
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +0 -9
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +0 -1
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +0 -279
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +0 -1
- package/lib/test/unit/ingest/cycleGuard.test.d.ts +0 -2
- package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +0 -1
- package/lib/test/unit/ingest/cycleGuard.test.js +0 -83
- package/lib/test/unit/ingest/cycleGuard.test.js.map +0 -1
- package/lib/test/unit/ingest/dedupScope.test.d.ts +0 -2
- package/lib/test/unit/ingest/dedupScope.test.d.ts.map +0 -1
- package/lib/test/unit/ingest/dedupScope.test.js +0 -436
- package/lib/test/unit/ingest/dedupScope.test.js.map +0 -1
- package/lib/test/unit/ingest/orchestrator.test.d.ts +0 -2
- package/lib/test/unit/ingest/orchestrator.test.d.ts.map +0 -1
- package/lib/test/unit/ingest/orchestrator.test.js +0 -1060
- package/lib/test/unit/ingest/orchestrator.test.js.map +0 -1
- package/lib/test/unit/observe/memoryObservationStore.test.d.ts +0 -2
- package/lib/test/unit/observe/memoryObservationStore.test.d.ts.map +0 -1
- package/lib/test/unit/observe/memoryObservationStore.test.js +0 -120
- package/lib/test/unit/observe/memoryObservationStore.test.js.map +0 -1
- package/lib/test/unit/retrieve/fragmentSemanticRetriever.test.d.ts +0 -2
- package/lib/test/unit/retrieve/fragmentSemanticRetriever.test.d.ts.map +0 -1
- package/lib/test/unit/retrieve/fragmentSemanticRetriever.test.js +0 -118
- package/lib/test/unit/retrieve/fragmentSemanticRetriever.test.js.map +0 -1
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.d.ts +0 -2
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.d.ts.map +0 -1
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.js +0 -259
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.js.map +0 -1
- package/lib/test/unit/retrieve/retrievers.test.d.ts +0 -2
- package/lib/test/unit/retrieve/retrievers.test.d.ts.map +0 -1
- package/lib/test/unit/retrieve/retrievers.test.js +0 -770
- package/lib/test/unit/retrieve/retrievers.test.js.map +0 -1
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +0 -2
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +0 -1
- package/lib/test/unit/retrieve/temporalRetrievers.test.js +0 -184
- package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +0 -1
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +0 -9
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +0 -1
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js +0 -122
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +0 -1
- package/lib/test/unit/store/embedOnWrite.test.d.ts +0 -2
- package/lib/test/unit/store/embedOnWrite.test.d.ts.map +0 -1
- package/lib/test/unit/store/embedOnWrite.test.js +0 -319
- package/lib/test/unit/store/embedOnWrite.test.js.map +0 -1
- package/lib/test/unit/store/fileTreeMemoryStore.test.d.ts +0 -2
- package/lib/test/unit/store/fileTreeMemoryStore.test.d.ts.map +0 -1
- package/lib/test/unit/store/fileTreeMemoryStore.test.js +0 -780
- package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +0 -1
- package/lib/test/unit/store/fragmentEmbedOnWrite.test.d.ts +0 -2
- package/lib/test/unit/store/fragmentEmbedOnWrite.test.d.ts.map +0 -1
- package/lib/test/unit/store/fragmentEmbedOnWrite.test.js +0 -257
- package/lib/test/unit/store/fragmentEmbedOnWrite.test.js.map +0 -1
- package/lib/test/unit/store/indexInjection.test.d.ts +0 -2
- package/lib/test/unit/store/indexInjection.test.d.ts.map +0 -1
- package/lib/test/unit/store/indexInjection.test.js +0 -434
- package/lib/test/unit/store/indexInjection.test.js.map +0 -1
- package/lib/test/unit/store/lenientOpen.test.d.ts +0 -2
- package/lib/test/unit/store/lenientOpen.test.d.ts.map +0 -1
- package/lib/test/unit/store/lenientOpen.test.js +0 -250
- package/lib/test/unit/store/lenientOpen.test.js.map +0 -1
- package/lib/test/unit/store/listScoped.test.d.ts +0 -2
- package/lib/test/unit/store/listScoped.test.d.ts.map +0 -1
- package/lib/test/unit/store/listScoped.test.js +0 -111
- package/lib/test/unit/store/listScoped.test.js.map +0 -1
- package/lib/test/unit/store/observations.test.d.ts +0 -2
- package/lib/test/unit/store/observations.test.d.ts.map +0 -1
- package/lib/test/unit/store/observations.test.js +0 -241
- package/lib/test/unit/store/observations.test.js.map +0 -1
- package/lib/test/unit/store/rankAxis.test.d.ts +0 -2
- package/lib/test/unit/store/rankAxis.test.d.ts.map +0 -1
- package/lib/test/unit/store/rankAxis.test.js +0 -256
- package/lib/test/unit/store/rankAxis.test.js.map +0 -1
- package/lib/test/unit/store/scopeEncoding.test.d.ts +0 -2
- package/lib/test/unit/store/scopeEncoding.test.d.ts.map +0 -1
- package/lib/test/unit/store/scopeEncoding.test.js +0 -26
- package/lib/test/unit/store/scopeEncoding.test.js.map +0 -1
- package/lib/test/unit/store/temporalStore.test.d.ts +0 -2
- package/lib/test/unit/store/temporalStore.test.d.ts.map +0 -1
- package/lib/test/unit/store/temporalStore.test.js +0 -400
- package/lib/test/unit/store/temporalStore.test.js.map +0 -1
- package/lib/test/unit/tools/memoryTools.test.d.ts +0 -2
- package/lib/test/unit/tools/memoryTools.test.d.ts.map +0 -1
- package/lib/test/unit/tools/memoryTools.test.js +0 -844
- package/lib/test/unit/tools/memoryTools.test.js.map +0 -1
- package/lib/test/unit/types/identityCodec.test.d.ts +0 -2
- package/lib/test/unit/types/identityCodec.test.d.ts.map +0 -1
- package/lib/test/unit/types/identityCodec.test.js +0 -189
- package/lib/test/unit/types/identityCodec.test.js.map +0 -1
- package/lib/test/unit/types/ids.test.d.ts +0 -2
- package/lib/test/unit/types/ids.test.d.ts.map +0 -1
- package/lib/test/unit/types/ids.test.js +0 -86
- package/lib/test/unit/types/ids.test.js.map +0 -1
- package/lib/test/unit/types/temporalCodec.test.d.ts +0 -2
- package/lib/test/unit/types/temporalCodec.test.d.ts.map +0 -1
- package/lib/test/unit/types/temporalCodec.test.js +0 -205
- package/lib/test/unit/types/temporalCodec.test.js.map +0 -1
- package/lib/test/unit/types/temporalPolicy.test.d.ts +0 -2
- package/lib/test/unit/types/temporalPolicy.test.d.ts.map +0 -1
- package/lib/test/unit/types/temporalPolicy.test.js +0 -85
- package/lib/test/unit/types/temporalPolicy.test.js.map +0 -1
- package/lib/test/unit/types/writePolicy.test.d.ts +0 -2
- package/lib/test/unit/types/writePolicy.test.d.ts.map +0 -1
- package/lib/test/unit/types/writePolicy.test.js +0 -333
- package/lib/test/unit/types/writePolicy.test.js.map +0 -1
- package/lib/test/unit/vector/fragmentConverters.test.d.ts +0 -2
- package/lib/test/unit/vector/fragmentConverters.test.d.ts.map +0 -1
- package/lib/test/unit/vector/fragmentConverters.test.js +0 -60
- package/lib/test/unit/vector/fragmentConverters.test.js.map +0 -1
- package/lib/test/unit/vector/inMemoryCosineIndex.test.d.ts +0 -2
- package/lib/test/unit/vector/inMemoryCosineIndex.test.d.ts.map +0 -1
- package/lib/test/unit/vector/inMemoryCosineIndex.test.js +0 -254
- package/lib/test/unit/vector/inMemoryCosineIndex.test.js.map +0 -1
- package/lib/test/unit/vector/inMemoryFragmentCosineIndex.test.d.ts +0 -2
- package/lib/test/unit/vector/inMemoryFragmentCosineIndex.test.d.ts.map +0 -1
- package/lib/test/unit/vector/inMemoryFragmentCosineIndex.test.js +0 -364
- package/lib/test/unit/vector/inMemoryFragmentCosineIndex.test.js.map +0 -1
- package/lib/test/unit/vector/vectorIndex.test.d.ts +0 -2
- package/lib/test/unit/vector/vectorIndex.test.d.ts.map +0 -1
- package/lib/test/unit/vector/vectorIndex.test.js +0 -53
- package/lib/test/unit/vector/vectorIndex.test.js.map +0 -1
- package/rush-logs/ts-agent-memory.build.cache.log +0 -3
- package/rush-logs/ts-agent-memory.build.log +0 -9
- package/src/index.ts +0 -14
- package/src/packlets/converters/bodyConverterRegistry.ts +0 -105
- package/src/packlets/converters/envelopeConverter.ts +0 -233
- package/src/packlets/converters/index.ts +0 -7
- package/src/packlets/index/index.ts +0 -6
- package/src/packlets/index/memoryIndex.ts +0 -332
- package/src/packlets/ingest/cycleGuard.ts +0 -153
- package/src/packlets/ingest/hostStages.ts +0 -111
- package/src/packlets/ingest/index.ts +0 -9
- package/src/packlets/ingest/model.ts +0 -195
- package/src/packlets/ingest/orchestrator.ts +0 -968
- package/src/packlets/observe/index.ts +0 -7
- package/src/packlets/observe/memoryObservationStore.ts +0 -153
- package/src/packlets/observe/observer.ts +0 -119
- package/src/packlets/retrieve/fragmentSemanticRetriever.ts +0 -138
- package/src/packlets/retrieve/hybridRetriever.ts +0 -194
- package/src/packlets/retrieve/index.ts +0 -14
- package/src/packlets/retrieve/linkTraversalRetriever.ts +0 -158
- package/src/packlets/retrieve/recencyRetriever.ts +0 -54
- package/src/packlets/retrieve/retriever.ts +0 -291
- package/src/packlets/retrieve/semanticRetriever.ts +0 -152
- package/src/packlets/retrieve/structuredFilterRetriever.ts +0 -58
- package/src/packlets/retrieve/tagRetriever.ts +0 -58
- package/src/packlets/retrieve/temporalRetrievers.ts +0 -210
- package/src/packlets/store/fileTreeMemoryStore.ts +0 -1872
- package/src/packlets/store/index.ts +0 -7
- package/src/packlets/store/scopeEncoding.ts +0 -36
- package/src/packlets/tools/index.ts +0 -6
- package/src/packlets/tools/memoryTools.ts +0 -706
- package/src/packlets/types/envelope.ts +0 -196
- package/src/packlets/types/filenameSafety.ts +0 -57
- package/src/packlets/types/identityCodec.ts +0 -447
- package/src/packlets/types/ids.ts +0 -124
- package/src/packlets/types/index.ts +0 -11
- package/src/packlets/types/temporal.ts +0 -96
- package/src/packlets/types/writePolicy.ts +0 -612
- package/src/packlets/vector/fragmentConverters.ts +0 -55
- package/src/packlets/vector/inMemoryCosineIndex.ts +0 -196
- package/src/packlets/vector/inMemoryFragmentCosineIndex.ts +0 -289
- package/src/packlets/vector/index.ts +0 -9
- package/src/packlets/vector/vectorIndex.ts +0 -273
- package/src/test/unit/converters/antagonistRoundTrip.test.ts +0 -110
- package/src/test/unit/converters/bodyConverterRegistry.test.ts +0 -89
- package/src/test/unit/converters/envelopeConverter.test.ts +0 -418
- package/src/test/unit/index/memoryIndex.test.ts +0 -272
- package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +0 -367
- package/src/test/unit/ingest/cycleGuard.test.ts +0 -110
- package/src/test/unit/ingest/dedupScope.test.ts +0 -542
- package/src/test/unit/ingest/orchestrator.test.ts +0 -1355
- package/src/test/unit/observe/memoryObservationStore.test.ts +0 -158
- package/src/test/unit/retrieve/fragmentSemanticRetriever.test.ts +0 -163
- package/src/test/unit/retrieve/linkTraversalRetriever.test.ts +0 -329
- package/src/test/unit/retrieve/retrievers.test.ts +0 -1018
- package/src/test/unit/retrieve/temporalRetrievers.test.ts +0 -226
- package/src/test/unit/store/antagonistTemporalBoundary.test.ts +0 -158
- package/src/test/unit/store/embedOnWrite.test.ts +0 -418
- package/src/test/unit/store/fileTreeMemoryStore.test.ts +0 -1041
- package/src/test/unit/store/fragmentEmbedOnWrite.test.ts +0 -349
- package/src/test/unit/store/indexInjection.test.ts +0 -550
- package/src/test/unit/store/lenientOpen.test.ts +0 -292
- package/src/test/unit/store/listScoped.test.ts +0 -138
- package/src/test/unit/store/observations.test.ts +0 -290
- package/src/test/unit/store/rankAxis.test.ts +0 -349
- package/src/test/unit/store/scopeEncoding.test.ts +0 -37
- package/src/test/unit/store/temporalStore.test.ts +0 -469
- package/src/test/unit/tools/memoryTools.test.ts +0 -1121
- package/src/test/unit/types/identityCodec.test.ts +0 -266
- package/src/test/unit/types/ids.test.ts +0 -94
- package/src/test/unit/types/temporalCodec.test.ts +0 -259
- package/src/test/unit/types/temporalPolicy.test.ts +0 -124
- package/src/test/unit/types/writePolicy.test.ts +0 -446
- package/src/test/unit/vector/fragmentConverters.test.ts +0 -80
- package/src/test/unit/vector/inMemoryCosineIndex.test.ts +0 -318
- package/src/test/unit/vector/inMemoryFragmentCosineIndex.test.ts +0 -477
- package/src/test/unit/vector/vectorIndex.test.ts +0 -64
- package/temp/build/lint/_eslint-5eVG3S6w.json +0 -306
- package/temp/build/typescript/ts_8nwakTlr.json +0 -1
- package/temp/ts-agent-memory.api.json +0 -21030
- package/temp/ts-agent-memory.api.md +0 -940
- package/tsconfig.json +0 -8
|
@@ -243,7 +243,17 @@ export class MemoryIngestOrchestrator {
|
|
|
243
243
|
if (embedded.isFailure()) {
|
|
244
244
|
return fail(embedded.message);
|
|
245
245
|
}
|
|
246
|
-
|
|
246
|
+
// The embedder deliberately declined this candidate, so there is no vector to
|
|
247
|
+
// search with and layer-2 similarity dedup cannot run for it. That is the same
|
|
248
|
+
// position as a search that found nothing similar — `'new'` — and not an
|
|
249
|
+
// error: declining to embed a kind must not make it un-ingestable.
|
|
250
|
+
if (embedded.value === undefined) {
|
|
251
|
+
return succeed({ verdict: 'new' });
|
|
252
|
+
}
|
|
253
|
+
// Hoisted: the `undefined` check above does not narrow across the callback
|
|
254
|
+
// boundary below, and a local keeps the non-null assertion out of the code.
|
|
255
|
+
const vector = embedded.value;
|
|
256
|
+
const queried = await this._capture(() => wiring.vectorIndex.query(vector, this._similarityTopK), `ingest '${candidate.envelope.entityId}': similarity query`);
|
|
247
257
|
if (queried.isFailure()) {
|
|
248
258
|
return fail(queried.message);
|
|
249
259
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../../src/packlets/ingest/orchestrator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAU,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EACL,OAAO,EAcP,aAAa,EACb,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAIlB,OAAO,EAAmB,cAAc,EAAE,MAAM,cAAc,CAAC;AAoB/D;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAW,aAAa,CAAC;AAEnE;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAa,aAAyB,CAAC;AAEzE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAW,IAAI,CAAC;AAEzD;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAW,CAAC,CAAC;AAsHlD;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IAenC,YAAoB,MAA6C;;QAC/D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,MAAA,MAAM,CAAC,MAAM,mCAAI,IAAI,GAAG,EAAwB,CAAC;QAChE,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC;QACzC,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,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,EAAE,SAA2B;QACzE,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACvC,OAAO,IAAI,CACT,WAAW,IAAI,CAAC,EAAE,+BAChB,SAAS,CAAC,QAAQ,CAAC,IACrB,2BAA2B,OAAO,SAAS,CAAC,IAAI,GAAG,CACpD,CAAC;QACJ,CAAC;QACD,OAAO,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Hash, Logging, Result, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport {\n Convert,\n DedupScope,\n EntityId,\n IEdge,\n IEdgeTarget,\n IIdentityCodec,\n IIdentityCodecResult,\n IMemoryEnvelope,\n IMemoryRecord,\n IProvenance,\n Kind,\n LinkType,\n MemoryId,\n Tag,\n edgeTargetKey,\n isTemporalRecord,\n isVersionCurrent\n} from '../types';\nimport { IBodyConverterRegistry } from '../converters';\nimport { IMemoryStore } from '../store';\nimport { IVectorIndex, MemoryEmbedder } from '../vector';\nimport { ICycleGuardEdge, assertNoCycles } from './cycleGuard';\nimport {\n IEntityResolver,\n IFactExtractor,\n IMemoryClassifier,\n IRelationCandidate,\n IRelationExtractor\n} from './hostStages';\nimport {\n ICandidateEdge,\n ICandidateRecord,\n IEntityResolutionCandidate,\n IIngestItem,\n IIngestItemResult,\n IIngestedRecordResult,\n IMemoryClassification,\n IngestDisposition,\n ResolutionVerdict\n} from './model';\n\n/**\n * The provenance source stamped on every record the ingest pipeline writes.\n * @public\n */\nexport const HOST_INGEST_PROVENANCE_SOURCE: string = 'host-ingest';\n\n/**\n * The link type whose presence on a temporal-kind candidate fires the\n * contradicts→temporal-versioned interlock.\n * @public\n */\nexport const CONTRADICTS_LINK_TYPE: LinkType = 'contradicts' as LinkType;\n\n/**\n * The default stage-4 layer-2 cosine similarity threshold (design note §2). A\n * near-duplicate candidate is surfaced to the {@link IEntityResolver} only when\n * its nearest neighbor scores `>= 0.85`.\n * @public\n */\nexport const DEFAULT_SIMILARITY_THRESHOLD: number = 0.85;\n\n/**\n * The default top-K for stage-4 layer-2 similarity candidate generation.\n * @public\n */\nexport const DEFAULT_SIMILARITY_TOP_K: number = 5;\n\n/**\n * How the write-time cycle guard behaves: `'reject'` (default — a cycle-inducing\n * edge fails the ingest) or `'off'` (no acyclicity constraint, for deployments\n * whose link graphs are legitimately cyclic — e.g. mutual associative links).\n * @public\n */\nexport type CycleGuardMode = 'reject' | 'off';\n\n/**\n * The fgv-owned six-stage ingest orchestrator. Composes the host's staged\n * classify / extract / (optional) resolve / relate machinery around fgv's owned\n * validation boundary, dedup, edge + cycle safety, provenance stamping, and the\n * contradicts→temporal interlock.\n * @public\n */\nexport interface IMemoryIngestOrchestrator {\n /**\n * Ingest a SINGLE item end-to-end (the first-class per-turn streaming path).\n */\n ingestItem(item: IIngestItem): Promise<Result<IIngestItemResult>>;\n\n /**\n * Ingest a batch of items. A convenience loop over {@link\n * IMemoryIngestOrchestrator.ingestItem | ingestItem} — items are processed in\n * order and the first failure aborts the batch.\n */\n ingestBatch(items: ReadonlyArray<IIngestItem>): Promise<Result<ReadonlyArray<IIngestItemResult>>>;\n}\n\n/**\n * Parameters for {@link MemoryIngestOrchestrator.create}.\n * @public\n */\nexport interface IMemoryIngestOrchestratorCreateParams {\n /** The store every write bottoms out in (stage 6). */\n readonly store: IMemoryStore;\n /** Per-kind body converter registry — the stage-3 typed validation boundary. */\n readonly registry: IBodyConverterRegistry;\n /** Per-kind identity codecs (maps a candidate `entityId` to its storage address). */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default identity codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /** Stage 2 — the host's classifier. */\n readonly classifier: IMemoryClassifier;\n /** Stage 3 — the host's fact extractor. */\n readonly extractor: IFactExtractor;\n /** Stage 5 — the host's relation extractor. */\n readonly relationExtractor: IRelationExtractor;\n /**\n * Stage 4 (optional, OQ-13) — the host's entity resolver. Absent → stage-4\n * dedup is exact-`{ kind, body }`-hash only (the deterministic-identity path).\n */\n readonly entityResolver?: IEntityResolver;\n /**\n * Optional vector index for stage-4 layer-2 similarity candidate-gen. Wired\n * together with {@link IMemoryIngestOrchestratorCreateParams.embed | embed} AND\n * {@link IMemoryIngestOrchestratorCreateParams.entityResolver | entityResolver};\n * absent (or either co-requisite absent) → layer-2 is skipped and dedup is\n * exact-only.\n */\n readonly vectorIndex?: IVectorIndex;\n /** Optional embedder used to embed a candidate for layer-2 similarity search. */\n readonly embed?: MemoryEmbedder;\n /**\n * Stage-4 layer-2 cosine threshold. Defaults to {@link\n * DEFAULT_SIMILARITY_THRESHOLD} (`0.85`).\n */\n readonly similarityThreshold?: number;\n /**\n * Stage-4 layer-2 top-K. Defaults to {@link DEFAULT_SIMILARITY_TOP_K} (`5`).\n */\n readonly similarityTopK?: number;\n /** Write-time cycle guard mode. Defaults to `'reject'`. */\n readonly cycleGuard?: CycleGuardMode;\n /** Diagnostic logger (defaults to a no-op). */\n readonly logger?: Logging.ILogger;\n}\n\n/** The fully-wired stage-4 layer-2 dependencies (present only when all three are supplied). */\ninterface ISimilarityWiring {\n readonly resolver: IEntityResolver;\n readonly vectorIndex: IVectorIndex;\n readonly embed: MemoryEmbedder;\n}\n\n/** A snapshot record paired with its resolved scope-qualified `(scope, id)` address. */\ninterface IScopedRecord {\n readonly address: IEdgeTarget;\n readonly record: IMemoryRecord<unknown>;\n}\n\n/** Internal per-candidate plan threaded through the pipeline. */\ninterface ICandidatePlan {\n readonly candidate: ICandidateRecord;\n /** The write target's storage address (re-addressed to the target for merge-into). */\n readonly writeAddress: IIdentityCodecResult;\n /** The write target's entity id (re-addressed for merge-into). */\n readonly writeEntityId: EntityId;\n /** The reference id used in stage-5 edges (the write target's `idStem`). */\n readonly refId: MemoryId;\n /**\n * The scope-qualified reference used in stage-5 edges: the write target's\n * `(scope, idStem)`. Stage-5 sources / dedup all key on this scoped address so\n * two candidates that share a stem across scopes never collide.\n */\n readonly refTarget: IEdgeTarget;\n /** The resolution verdict; carries the target id on its target-bearing arms. */\n readonly verdict: ResolutionVerdict;\n /**\n * The pre-ingest target record for a `merge-into` write — its existing\n * `tags` / `links` / `provenance` are UNIONed with the candidate's at stage 6\n * so a wholesale-replace merge never wipes them.\n */\n readonly mergeTarget?: IMemoryRecord<unknown>;\n}\n\n/**\n * Default {@link IMemoryIngestOrchestrator}.\n * @public\n */\nexport class MemoryIngestOrchestrator implements IMemoryIngestOrchestrator {\n private readonly _store: IMemoryStore;\n private readonly _registry: IBodyConverterRegistry;\n private readonly _codecs: ReadonlyMap<Kind, IIdentityCodec>;\n private readonly _defaultCodec: IIdentityCodec | undefined;\n private readonly _classifier: IMemoryClassifier;\n private readonly _extractor: IFactExtractor;\n private readonly _relationExtractor: IRelationExtractor;\n private readonly _similarity: ISimilarityWiring | undefined;\n private readonly _similarityThreshold: number;\n private readonly _similarityTopK: number;\n private readonly _cycleGuard: CycleGuardMode;\n private readonly _logger: Logging.ILogger;\n private readonly _hasher: Hash.Crc32Normalizer;\n\n private constructor(params: IMemoryIngestOrchestratorCreateParams) {\n this._store = params.store;\n this._registry = params.registry;\n this._codecs = params.codecs ?? new Map<Kind, IIdentityCodec>();\n this._defaultCodec = params.defaultCodec;\n this._classifier = params.classifier;\n this._extractor = params.extractor;\n this._relationExtractor = params.relationExtractor;\n this._similarity =\n params.entityResolver !== undefined && params.vectorIndex !== undefined && params.embed !== undefined\n ? { resolver: params.entityResolver, vectorIndex: params.vectorIndex, embed: params.embed }\n : undefined;\n this._similarityThreshold = params.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;\n this._similarityTopK = params.similarityTopK ?? DEFAULT_SIMILARITY_TOP_K;\n this._cycleGuard = params.cycleGuard ?? 'reject';\n this._logger = params.logger ?? new Logging.NoOpLogger();\n this._hasher = new Hash.Crc32Normalizer();\n }\n\n /** Family-convention factory. */\n public static create(params: IMemoryIngestOrchestratorCreateParams): Result<MemoryIngestOrchestrator> {\n return succeed(new MemoryIngestOrchestrator(params));\n }\n\n /** {@inheritDoc IMemoryIngestOrchestrator.ingestItem} */\n public async ingestItem(item: IIngestItem): Promise<Result<IIngestItemResult>> {\n return (await this._classify(item))\n .thenOnSuccess((classification) => this._extract(item, classification))\n .thenOnSuccess((candidates) => this._processCandidates(item, candidates));\n }\n\n /** {@inheritDoc IMemoryIngestOrchestrator.ingestBatch} */\n public async ingestBatch(\n items: ReadonlyArray<IIngestItem>\n ): Promise<Result<ReadonlyArray<IIngestItemResult>>> {\n const results: IIngestItemResult[] = [];\n for (const item of items) {\n const result: Result<IIngestItemResult> = await this.ingestItem(item);\n if (result.isFailure()) {\n return fail(result.message);\n }\n results.push(result.value);\n }\n return succeed(results);\n }\n\n /** Stage 2 — classify (host), normalizing a rejected promise into a Failure. */\n private async _classify(item: IIngestItem): Promise<Result<IMemoryClassification>> {\n return this._capture(() => this._classifier.classify(item), `ingest '${item.id}': classify`);\n }\n\n /** Stage 3 — extract (host), normalizing a rejected promise into a Failure. */\n private async _extract(\n item: IIngestItem,\n classification: IMemoryClassification\n ): Promise<Result<ReadonlyArray<ICandidateRecord>>> {\n return this._capture(() => this._extractor.extract(item, classification), `ingest '${item.id}': extract`);\n }\n\n /**\n * Stages 3b-6 over the extracted candidates: validate bodies, resolve/dedup\n * (stage 4), relate + cycle guard (stage 5), and load-with-provenance (stage 6).\n */\n private async _processCandidates(\n item: IIngestItem,\n candidates: ReadonlyArray<ICandidateRecord>\n ): Promise<Result<IIngestItemResult>> {\n // Snapshot the store once; stage-4 resolution and the cycle guard reason over\n // the pre-ingest state.\n const snapshotResult: Result<ReadonlyArray<IMemoryRecord<unknown>>> = await this._store.list();\n if (snapshotResult.isFailure()) {\n return fail(`ingest '${item.id}': failed to snapshot store: ${snapshotResult.message}`);\n }\n const snapshot: ReadonlyArray<IMemoryRecord<unknown>> = snapshotResult.value;\n // Resolve every snapshot record's scope-qualified address ONCE, then index it\n // by the canonical scoped key. The single `byKey` view drives BOTH the edge\n // path (validation + cycle guard) AND the verdict/similarity target lookups —\n // so a filename stem reused across scopes never aliases on any path.\n const scopedResult: Result<ReadonlyArray<IScopedRecord>> = this._scopeRecords(snapshot);\n if (scopedResult.isFailure()) {\n return fail(`ingest '${item.id}': ${scopedResult.message}`);\n }\n const scoped: ReadonlyArray<IScopedRecord> = scopedResult.value;\n const byKey: ReadonlyMap<string, IMemoryRecord<unknown>> = new Map<string, IMemoryRecord<unknown>>(\n scoped.map((s) => [edgeTargetKey(s.address), s.record])\n );\n\n // Stage 3b + 4: validate each body and resolve a verdict/plan.\n const plans: ICandidatePlan[] = [];\n for (const candidate of candidates) {\n const planResult: Result<ICandidatePlan> = await this._planCandidate(item, candidate, snapshot, byKey);\n if (planResult.isFailure()) {\n return fail(planResult.message);\n }\n plans.push(planResult.value);\n }\n\n // Stage 5: relate over the writable candidates, validate + cycle-guard.\n const writablePlans: ICandidatePlan[] = plans.filter((plan) => plan.verdict.verdict !== 'duplicate-of');\n const edgesResult: Result<ReadonlyArray<ICandidateEdge>> = await this._relate(\n item,\n writablePlans,\n MemoryIngestOrchestrator._collapseRedirects(plans),\n scoped,\n byKey\n );\n if (edgesResult.isFailure()) {\n return fail(edgesResult.message);\n }\n const edges: ReadonlyArray<ICandidateEdge> = edgesResult.value;\n\n // Stage 6: load-with-provenance, in extraction order.\n const records: IIngestedRecordResult[] = [];\n for (const plan of plans) {\n const outcome: Result<IIngestedRecordResult> = await this._loadCandidate(item, plan, edges);\n if (outcome.isFailure()) {\n return fail(outcome.message);\n }\n records.push(outcome.value);\n }\n return succeed({ item, records });\n }\n\n /** Stage 3b + 4 for one candidate: validate body, resolve address, resolve verdict. */\n private async _planCandidate(\n item: IIngestItem,\n candidate: ICandidateRecord,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ICandidatePlan>> {\n const kind: Kind = candidate.envelope.kind;\n // Stage 3b: the typed validation boundary — no unchecked host body reaches the store.\n const bodyResult: Result<string> = this._registry\n .convert(kind, candidate.body)\n .withErrorFormat((msg) => `ingest '${item.id}': candidate body for kind '${kind}' is invalid: ${msg}`)\n .onSuccess(() => MemoryIngestOrchestrator._asStringBody(item, candidate));\n if (bodyResult.isFailure()) {\n return fail(bodyResult.message);\n }\n const body: string = bodyResult.value;\n\n const addrResult: Result<IIdentityCodecResult> = this._resolveAddress(candidate.envelope.entityId, kind);\n if (addrResult.isFailure()) {\n return fail(`ingest '${item.id}': ${addrResult.message}`);\n }\n const addr: IIdentityCodecResult = addrResult.value;\n\n return (await this._resolveVerdict(candidate, kind, body, addr, snapshot, byKey)).onSuccess((verdict) =>\n this._planFromVerdict(item, candidate, addr, verdict, byKey)\n );\n }\n\n /**\n * Turn a resolved verdict into a candidate plan. A `new` verdict writes under the\n * candidate's own address. Every TARGET-bearing verdict\n * (`duplicate-of` / `supersede` / `merge-into`) is validated uniformly: the\n * target must be a real store record (fgv owns validation — a non-compliant host\n * resolver never smuggles a bogus id through) AND its kind must equal the\n * candidate's kind (a cross-kind target would write to the wrong scope). Only\n * `merge-into` re-addresses the write to the target's entity.\n */\n private _planFromVerdict(\n item: IIngestItem,\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n verdict: ResolutionVerdict,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Result<ICandidatePlan> {\n if (verdict.verdict === 'new') {\n return Convert.memoryId.convert(addr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: addr,\n writeEntityId: candidate.envelope.entityId,\n refId,\n refTarget: { scope: addr.scope, id: refId },\n verdict\n })\n );\n }\n // duplicate-of | supersede | merge-into: the target must exist and share the\n // candidate's kind. Lookup is on the canonical scoped key, so a stem reused\n // across scopes binds only the record the verdict actually named.\n const target: IMemoryRecord<unknown> | undefined = byKey.get(edgeTargetKey(verdict.target));\n if (target === undefined) {\n return fail(\n `ingest '${item.id}': ${verdict.verdict} target '${MemoryIngestOrchestrator._formatTarget(\n verdict.target\n )}' does not exist in the store`\n );\n }\n if (target.envelope.kind !== candidate.envelope.kind) {\n return fail(\n `ingest '${item.id}': ${verdict.verdict} target '${MemoryIngestOrchestrator._formatTarget(\n verdict.target\n )}' is kind '${target.envelope.kind}' but the candidate is kind '${candidate.envelope.kind}'`\n );\n }\n if (verdict.verdict === 'merge-into') {\n // Re-address the write to the target's entity, carrying the target record so\n // stage 6 can UNION its existing tags/links (never overwrite them).\n const targetEntityId: EntityId = target.envelope.entityId;\n // The merge target is a snapshot record, and `_scopeRecords` already proved\n // every snapshot record's address resolves before planning runs — so this\n // re-resolve (needed for the full codec result: scope + idStem + isVersioned)\n // cannot fail. No error-context wrap is warranted; a failure here would be a\n // logic contradiction, not a user-facing condition.\n return this._resolveAddress(targetEntityId, target.envelope.kind).onSuccess((targetAddr) =>\n Convert.memoryId.convert(targetAddr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: targetAddr,\n writeEntityId: targetEntityId,\n refId,\n refTarget: { scope: targetAddr.scope, id: refId },\n verdict,\n mergeTarget: target\n })\n )\n );\n }\n // duplicate-of | supersede: write under the candidate's own address.\n return Convert.memoryId.convert(addr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: addr,\n writeEntityId: candidate.envelope.entityId,\n refId,\n refTarget: { scope: addr.scope, id: refId },\n verdict\n })\n );\n }\n\n /**\n * Stage 4 — resolve a dedup verdict. Layer 1: an exact `{ kind, body }` match in\n * the candidate's scope is a `duplicate-of`, at the granularity the kind's\n * {@link DedupScope} declares — scope-wide for `'content'`, restricted to the\n * candidate's own entity for `'entity'` (design note §1). Layer 2 (only when\n * a resolver + vector index + embedder are all wired): embed the candidate,\n * surface over-threshold neighbors, and dispatch to the {@link IEntityResolver}.\n * Otherwise the verdict is `new` (the exact-only fall-back path).\n */\n private async _resolveVerdict(\n candidate: ICandidateRecord,\n kind: Kind,\n body: string,\n addr: IIdentityCodecResult,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return this._findExactMatch(kind, body, addr, snapshot).thenOnSuccess(async (matchId) => {\n if (matchId !== undefined) {\n // The exact-match cohort is filtered to `addr.scope`, so the match lives\n // under that scope — its scope-qualified target is `(addr.scope, matchId)`.\n return succeed({ verdict: 'duplicate-of', target: { scope: addr.scope, id: matchId } });\n }\n const layer2: ISimilarityWiring | undefined = this._similarity;\n if (layer2 === undefined) {\n // No layer-2: exact-only fall-back (the deterministic-identity host path).\n return succeed({ verdict: 'new' });\n }\n return this._resolveViaSimilarity(candidate, addr, body, layer2, byKey);\n });\n }\n\n /** Layer-2 similarity candidate-gen + resolver dispatch. */\n private async _resolveViaSimilarity(\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n body: string,\n wiring: ISimilarityWiring,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return MemoryIngestOrchestrator._provisionalRecord(candidate, addr.idStem, body).thenOnSuccess(\n (provisional) => this._resolveViaSimilarityEmbedded(candidate, addr, wiring, byKey, provisional)\n );\n }\n\n /** Layer-2 continuation once the candidate has a provisional record to embed. */\n private async _resolveViaSimilarityEmbedded(\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n wiring: ISimilarityWiring,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>,\n provisional: IMemoryRecord<unknown>\n ): Promise<Result<ResolutionVerdict>> {\n const embedded: Result<Float32Array> = await this._capture(\n () => wiring.embed(provisional),\n `ingest '${candidate.envelope.entityId}': embed candidate`\n );\n if (embedded.isFailure()) {\n return fail(embedded.message);\n }\n const queried = await this._capture(\n () => wiring.vectorIndex.query(embedded.value, this._similarityTopK),\n `ingest '${candidate.envelope.entityId}': similarity query`\n );\n if (queried.isFailure()) {\n return fail(queried.message);\n }\n const similar: IEntityResolutionCandidate[] = [];\n for (const hit of queried.value) {\n // Skip below-threshold hits and the candidate's OWN scope-qualified address\n // (a re-ingest of the same entity must not dedup against its prior version).\n // Both the scope AND the id must match to be \"self\" — a same-stem record in\n // another scope is a legitimate distinct neighbor. This field-equality is\n // exactly equivalent to comparing `edgeTargetKey(hit.target)` against the\n // candidate's own key (edgeTargetKey is pure and injective on `(scope, id)`),\n // so this one site reads the components directly rather than re-keying.\n const isSelf: boolean = hit.target.scope === addr.scope && hit.target.id === addr.idStem;\n if (hit.score < this._similarityThreshold || isSelf) {\n continue;\n }\n const record: IMemoryRecord<unknown> | undefined = byKey.get(edgeTargetKey(hit.target));\n if (record !== undefined) {\n similar.push({ target: hit.target, record, score: hit.score });\n }\n }\n if (similar.length === 0) {\n return succeed({ verdict: 'new' });\n }\n return this._capture(\n () => wiring.resolver.resolve(candidate, similar),\n `ingest '${candidate.envelope.entityId}': resolve`\n );\n }\n\n /**\n * Find an existing record whose `{ kind, body }` hash matches the candidate's\n * (layer-1 exact dedup, design note §1). Invalidated temporal versions are\n * excluded — only a live (non-temporal or current) record deduplicates a\n * candidate.\n *\n * @remarks\n * The cohort's granularity is the kind's DECLARED {@link DedupScope}, read\n * through {@link IMemoryStore.dedupScopeFor} so this layer and the store's own\n * write path can never disagree:\n *\n * - `'content'` — every live same-kind record in the candidate's scope,\n * regardless of entity. A cross-id body collision IS a duplicate (the\n * knowledge family; unchanged behavior).\n * - `'entity'` — only records at the candidate's OWN entity address. Two\n * distinct entities with byte-identical bodies never collapse into one\n * another, which is what the declaration has always meant on the direct-put\n * path and now means here too.\n *\n * The same-id collapse itself remains the store's job — this layer only decides\n * whether a cross-id body collision is eligible to be a `duplicate-of` at all.\n */\n private _findExactMatch(\n kind: Kind,\n body: string,\n addr: IIdentityCodecResult,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<MemoryId | undefined> {\n const dedupScope: DedupScope = this._store.dedupScopeFor(kind);\n // Same-kind, same-scope, LIVE (non-temporal or current) records are the exact\n // cohort, narrowed to the candidate's own entity address under `'entity'`\n // granularity. `_resolveAddress(...).orDefault()` collapses an unresolved\n // codec to `undefined` — a non-matching address — with no explicit failure\n // branch, exactly as the scope-only filter did before.\n const cohort: ReadonlyArray<IMemoryRecord<unknown>> = snapshot.filter((record) => {\n if (record.envelope.kind !== kind || (isTemporalRecord(record) && !isVersionCurrent(record))) {\n return false;\n }\n const recordAddr: IIdentityCodecResult | undefined = this._resolveAddress(\n record.envelope.entityId,\n record.envelope.kind\n ).orDefault();\n if (recordAddr === undefined || recordAddr.scope !== addr.scope) {\n return false;\n }\n return dedupScope === 'content' || recordAddr.idStem === addr.idStem;\n });\n return this._exactKey(kind, body).onSuccess((key) =>\n mapResults(\n cohort.map((record) =>\n MemoryIngestOrchestrator._recordBodyString(record).onSuccess((recordBody) =>\n this._exactKey(record.envelope.kind, recordBody).onSuccess((recordKey) =>\n succeed({ id: record.envelope.id, key: recordKey })\n )\n )\n )\n ).onSuccess((keyed) => succeed(keyed.find((entry) => entry.key === key)?.id))\n );\n }\n\n /**\n * The body of a persisted record, required to be a string (the store persists\n * only string bodies). Fails loudly rather than blind-casting an `unknown` body\n * into the exact-dedup hash — a non-string existing body is a store-integrity\n * fault, surfaced with context, not a silent miscompute.\n */\n private static _recordBodyString(record: IMemoryRecord<unknown>): Result<string> {\n if (typeof record.body !== 'string') {\n return fail(\n `ingest: stored record '${record.envelope.id}' has a non-string body (got ${typeof record.body})`\n );\n }\n return succeed(record.body);\n }\n\n /** The stage-4 exact-dedup key over `{ kind, body }` (design note §1). */\n private _exactKey(kind: Kind, body: string): Result<string> {\n return this._hasher.computeHash({ kind, body });\n }\n\n /** Stage 5 — relate (host), redirect collapsed targets, validate edges, and run the write-time cycle guard. */\n private async _relate(\n item: IIngestItem,\n writablePlans: ReadonlyArray<ICandidatePlan>,\n redirects: ReadonlyMap<string, IEdgeTarget>,\n scoped: ReadonlyArray<IScopedRecord>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ReadonlyArray<ICandidateEdge>>> {\n const relationCandidates: IRelationCandidate[] = writablePlans.map((plan) => ({\n candidate: plan.candidate,\n id: plan.refTarget\n }));\n const proposed: Result<ReadonlyArray<ICandidateEdge>> = await this._capture(\n () => this._relationExtractor.relate({ item, candidates: relationCandidates }),\n `ingest '${item.id}': relate`\n );\n if (proposed.isFailure()) {\n return proposed;\n }\n // Redirect BEFORE validation and BEFORE the cycle guard: an edge naming a\n // collapsed candidate must be judged — and persisted — against the record it\n // collapsed into, not against the address that no longer gets written.\n const edges: ReadonlyArray<ICandidateEdge> = MemoryIngestOrchestrator._redirectEdges(\n proposed.value,\n redirects\n );\n // refIds and the existing-record view (`byKey`, shared with the verdict path)\n // both key on the canonical scoped address, so a stem reused across scopes\n // never aliases.\n const refIds: ReadonlySet<string> = new Set<string>(\n writablePlans.map((plan) => edgeTargetKey(plan.refTarget))\n );\n const validation: Result<true> = this._validateEdges(item, edges, refIds, byKey);\n if (validation.isFailure()) {\n return fail(validation.message);\n }\n if (this._cycleGuard === 'reject') {\n const guard: Result<true> = assertNoCycles(\n MemoryIngestOrchestrator._existingEdges(scoped),\n edges.map((e) => ({ source: e.source, target: e.edge.target, type: e.edge.type }))\n );\n if (guard.isFailure()) {\n return fail(`ingest '${item.id}': ${guard.message}`);\n }\n }\n return succeed(edges);\n }\n\n /**\n * The stage-5 edge-target redirect map for this pass: every `duplicate-of`\n * candidate's OWN scoped address, mapped to the address of the record its\n * verdict collapsed it into (design note §3).\n *\n * @remarks\n * A `duplicate-of` verdict means \"this candidate IS that record\". The candidate\n * is therefore not written, and its address never becomes a live reference — so\n * a sibling edge built against it in the same pass would resolve to neither a\n * written candidate nor an existing record and would fail the WHOLE ingest item.\n * That is a second-order hazard of collapsing, not a defect in the edge: the\n * host related two candidates it was correctly told about, and one of them\n * turned out to already exist.\n *\n * Redirecting is the honest repair, and it is independent of {@link DedupScope}\n * — it applies equally to a `'content'` kind, where the collapse is exactly\n * right and the ingest still must not fail.\n *\n * The map cannot chain: {@link MemoryIngestOrchestrator._planFromVerdict}\n * requires every target-bearing verdict's target to already exist in the store\n * snapshot, so a redirect destination is always a persisted record and never\n * another collapsed candidate. One pass is sufficient by construction.\n */\n private static _collapseRedirects(plans: ReadonlyArray<ICandidatePlan>): ReadonlyMap<string, IEdgeTarget> {\n const redirects: Map<string, IEdgeTarget> = new Map<string, IEdgeTarget>();\n for (const plan of plans) {\n if (plan.verdict.verdict === 'duplicate-of') {\n redirects.set(edgeTargetKey(plan.refTarget), plan.verdict.target);\n }\n }\n return redirects;\n }\n\n /**\n * Rewrite each edge whose TARGET names a collapsed candidate to point at the\n * record that candidate collapsed into.\n *\n * @remarks\n * Only the target is redirected. An edge whose SOURCE is a collapsed candidate\n * stays untouched and is still rejected by {@link\n * MemoryIngestOrchestrator._validateEdges}: sources are the records an edge is\n * written ONTO, a collapsed candidate is never written, and the relation\n * extractor is only ever offered writable candidates as edge sources in the\n * first place. Silently relocating such an edge onto an existing record would\n * attribute a link the host never asked for — the loud failure is correct there.\n */\n private static _redirectEdges(\n edges: ReadonlyArray<ICandidateEdge>,\n redirects: ReadonlyMap<string, IEdgeTarget>\n ): ReadonlyArray<ICandidateEdge> {\n if (redirects.size === 0) {\n return edges;\n }\n return edges.map((e) => {\n const to: IEdgeTarget | undefined = redirects.get(edgeTargetKey(e.edge.target));\n return to === undefined ? e : { ...e, edge: { ...e.edge, target: to } };\n });\n }\n\n /**\n * Validate stage-5 edges: each `source` must be a candidate being written; each\n * `target` must resolve to a sibling candidate or an existing store record. All\n * matching is on the canonical scope-qualified address.\n */\n private _validateEdges(\n item: IIngestItem,\n edges: ReadonlyArray<ICandidateEdge>,\n refIds: ReadonlySet<string>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Result<true> {\n return mapResults(\n edges.map((edge) => {\n if (!refIds.has(edgeTargetKey(edge.source))) {\n return fail(\n `ingest '${item.id}': edge source '${MemoryIngestOrchestrator._formatTarget(\n edge.source\n )}' is not a candidate being written`\n );\n }\n const targetKey: string = edgeTargetKey(edge.edge.target);\n if (!refIds.has(targetKey) && byKey.get(targetKey) === undefined) {\n return fail(\n `ingest '${item.id}': edge target '${MemoryIngestOrchestrator._formatTarget(\n edge.edge.target\n )}' resolves to neither a sibling candidate nor an existing record`\n );\n }\n return succeed(true);\n })\n ).onSuccess(() => succeed(true));\n }\n\n /** Stage 6 — stamp provenance + edges, admit through the store, record the outcome. */\n private async _loadCandidate(\n item: IIngestItem,\n plan: ICandidatePlan,\n allEdges: ReadonlyArray<ICandidateEdge>\n ): Promise<Result<IIngestedRecordResult>> {\n const refKey: string = edgeTargetKey(plan.refTarget);\n const myEdges: ReadonlyArray<ICandidateEdge> = allEdges.filter((e) => edgeTargetKey(e.source) === refKey);\n if (plan.verdict.verdict === 'duplicate-of') {\n // No write: the existing target satisfied the candidate. The target id is a\n // typed field of the narrowed `duplicate-of` verdict — no cast, no guard.\n return succeed({\n candidate: plan.candidate,\n resolution: plan.verdict,\n disposition: 'deduped',\n id: plan.verdict.target.id,\n edges: myEdges\n });\n }\n return this._buildRecord(item, plan, myEdges).thenOnSuccess(async (record) =>\n (await this._store.put(record))\n .withErrorFormat((msg) => `ingest '${item.id}': write failed: ${msg}`)\n .onSuccess((persisted) => {\n const disposition: IngestDisposition = plan.verdict.verdict === 'merge-into' ? 'merged' : 'written';\n const interlock: 'temporal-versioned' | undefined =\n plan.writeAddress.isVersioned && myEdges.some((e) => e.edge.type === CONTRADICTS_LINK_TYPE)\n ? 'temporal-versioned'\n : undefined;\n return succeed({\n candidate: plan.candidate,\n resolution: plan.verdict,\n disposition,\n id: persisted.envelope.id,\n record: persisted,\n edges: myEdges,\n ...(interlock !== undefined ? { interlock } : {})\n });\n })\n );\n }\n\n /** Build the fully-stamped record to persist (provenance + edges + placeholder txn fields). */\n private _buildRecord(\n item: IIngestItem,\n plan: ICandidatePlan,\n myEdges: ReadonlyArray<ICandidateEdge>\n ): Result<IMemoryRecord<unknown>> {\n const base: Omit<IMemoryEnvelope, 'id' | 'seq' | 'contentHash' | 'created' | 'updated'> =\n plan.candidate.envelope;\n // For merge-into the store's `applyUpdate` REPLACES array fields wholesale, so\n // the persisted envelope must already carry the UNION of the target's existing\n // tags/links/provenance and the candidate's — otherwise the merge silently\n // wipes the target's prior links/tags.\n const target: IMemoryRecord<unknown> | undefined = plan.mergeTarget;\n const priorLinks: ReadonlyArray<IEdge> = target !== undefined ? target.envelope.links : [];\n const priorTags: ReadonlyArray<Tag> = target !== undefined ? target.envelope.tags : [];\n const priorProvenance: IProvenance = target !== undefined ? target.envelope.provenance : { source: '' };\n return Convert.memoryId.convert(plan.writeAddress.idStem).onSuccess((id) =>\n // Dedup the combined links by canonical edge key: the target's prior links, the\n // candidate's own links, and the stage-5 edges (two candidates that resolve\n // merge-into the SAME target share a `refId` — hence the same `myEdges` — and a\n // relation extractor may repeat an edge) each appear exactly once.\n this._dedupEdges([...priorLinks, ...base.links, ...myEdges.map((e) => e.edge)]).onSuccess((links) => {\n const provenance: IProvenance = {\n // Preserve the target's provenance extension keys, overlay the candidate's,\n // then stamp the host-ingest source + derivedFrom (target present only for\n // merge-into; otherwise the seed is inert).\n ...(target !== undefined ? priorProvenance : {}),\n ...base.provenance,\n source: HOST_INGEST_PROVENANCE_SOURCE,\n ...(item.sourceId !== undefined ? { derivedFrom: item.sourceId } : {})\n };\n const envelope: IMemoryEnvelope = {\n ...base,\n id,\n entityId: plan.writeEntityId,\n seq: 0,\n contentHash: '',\n created: 0,\n updated: 0,\n provenance,\n tags: MemoryIngestOrchestrator._unionTags(priorTags, base.tags),\n links\n };\n return succeed({ envelope, body: plan.candidate.body });\n })\n );\n }\n\n /** Union two tag lists, de-duplicated, preserving first-occurrence order. */\n private static _unionTags(prior: ReadonlyArray<Tag>, incoming: ReadonlyArray<Tag>): ReadonlyArray<Tag> {\n const seen: Set<string> = new Set<string>();\n const out: Tag[] = [];\n for (const tag of [...prior, ...incoming]) {\n if (!seen.has(tag)) {\n seen.add(tag);\n out.push(tag);\n }\n }\n return out;\n }\n\n /** De-duplicate a link list by canonical edge hash, preserving first-occurrence order. */\n private _dedupEdges(edges: ReadonlyArray<IEdge>): Result<ReadonlyArray<IEdge>> {\n const seen: Set<string> = new Set<string>();\n const deduped: IEdge[] = [];\n return mapResults(\n edges.map((edge) =>\n this._hasher.computeHash(edge).onSuccess((key) => {\n if (!seen.has(key)) {\n seen.add(key);\n deduped.push(edge);\n }\n return succeed(key);\n })\n )\n ).onSuccess(() => succeed(deduped));\n }\n\n /** Resolve a `(kind, entityId)` to its storage address via the registered codec. */\n private _resolveAddress(entityId: EntityId, kind: Kind): Result<IIdentityCodecResult> {\n const codec: IIdentityCodec | undefined = this._codecs.get(kind) ?? this._defaultCodec;\n if (codec === undefined) {\n return fail(`no identity codec registered for kind '${kind}'`);\n }\n return codec.encode(entityId);\n }\n\n /** Run a host hook, normalizing a thrown/rejected hook into a Failure (never throws across the seam). */\n private async _capture<T>(op: () => Promise<Result<T>>, label: string): Promise<Result<T>> {\n try {\n return await op();\n } catch (err) {\n const message: string = `${label} threw: ${String(err)}`;\n this._logger.warn(message);\n return fail(message);\n }\n }\n\n /**\n * Every existing outbound edge in the snapshot, as cycle-guard edges. The\n * source is the record's own scope-qualified address (already resolved by\n * {@link MemoryIngestOrchestrator._scopeRecords}); the target is the edge's\n * own scoped target. Both ends are scoped so the guard never conflates a stem\n * shared across scopes into one graph node.\n */\n private static _existingEdges(scoped: ReadonlyArray<IScopedRecord>): ReadonlyArray<ICycleGuardEdge> {\n const edges: ICycleGuardEdge[] = [];\n for (const s of scoped) {\n for (const edge of s.record.envelope.links) {\n edges.push({ source: s.address, target: edge.target, type: edge.type });\n }\n }\n return edges;\n }\n\n /**\n * Resolve every snapshot record's scope-qualified `(scope, id)` address via its\n * registered codec. Fails loudly if a record's kind has no resolvable codec —\n * the edge path cannot place an un-scopeable record in the graph, and a missing\n * codec for a stored kind is a real misconfiguration, not something to paper over.\n */\n private _scopeRecords(\n records: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<ReadonlyArray<IScopedRecord>> {\n return mapResults(\n records.map((record) =>\n this._resolveAddress(record.envelope.entityId, record.envelope.kind)\n .withErrorFormat((msg) => `cannot resolve scope for stored record '${record.envelope.id}': ${msg}`)\n .onSuccess((addr) => succeed({ address: { scope: addr.scope, id: record.envelope.id }, record }))\n )\n );\n }\n\n /** Human-readable `scope/id` rendering of a scoped target for edge-validation diagnostics. */\n private static _formatTarget(target: IEdgeTarget): string {\n return `${target.scope}/${target.id}`;\n }\n\n /** A provisional record for embedding a candidate (placeholder txn-time fields). */\n private static _provisionalRecord(\n candidate: ICandidateRecord,\n idStem: string,\n body: string\n ): Result<IMemoryRecord<unknown>> {\n return Convert.memoryId.convert(idStem).onSuccess((id) => {\n const envelope: IMemoryEnvelope = {\n ...candidate.envelope,\n id,\n seq: 0,\n contentHash: '',\n created: 0,\n updated: 0\n };\n return succeed({ envelope, body });\n });\n }\n\n /** Require a candidate body to be a string (the store persists only string bodies). */\n private static _asStringBody(item: IIngestItem, candidate: ICandidateRecord): Result<string> {\n if (typeof candidate.body !== 'string') {\n return fail(\n `ingest '${item.id}': candidate body for kind '${\n candidate.envelope.kind\n }' must be a string (got ${typeof candidate.body})`\n );\n }\n return succeed(candidate.body);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../../src/packlets/ingest/orchestrator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAU,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EACL,OAAO,EAcP,aAAa,EACb,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAIlB,OAAO,EAAmB,cAAc,EAAE,MAAM,cAAc,CAAC;AAoB/D;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAW,aAAa,CAAC;AAEnE;;;;GAIG;AACH,MAAM,CAAC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E,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,CACpG,CACF,CAAC;IACJ,CAAC;IAED,8FAA8F;IACtF,MAAM,CAAC,aAAa,CAAC,MAAmB;QAC9C,OAAO,GAAG,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;IACxC,CAAC;IAED,oFAAoF;IAC5E,MAAM,CAAC,kBAAkB,CAC/B,SAA2B,EAC3B,MAAc,EACd,IAAY;QAEZ,OAAO,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE;YACvD,MAAM,QAAQ,mCACT,SAAS,CAAC,QAAQ,KACrB,EAAE,EACF,GAAG,EAAE,CAAC,EACN,WAAW,EAAE,EAAE,EACf,OAAO,EAAE,CAAC,EACV,OAAO,EAAE,CAAC,GACX,CAAC;YACF,OAAO,OAAO,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,uFAAuF;IAC/E,MAAM,CAAC,aAAa,CAAC,IAAiB,EAAE,SAA2B;QACzE,IAAI,OAAO,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACvC,OAAO,IAAI,CACT,WAAW,IAAI,CAAC,EAAE,+BAChB,SAAS,CAAC,QAAQ,CAAC,IACrB,2BAA2B,OAAO,SAAS,CAAC,IAAI,GAAG,CACpD,CAAC;QACJ,CAAC;QACD,OAAO,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACjC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Hash, Logging, Result, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport {\n Convert,\n DedupScope,\n EntityId,\n IEdge,\n IEdgeTarget,\n IIdentityCodec,\n IIdentityCodecResult,\n IMemoryEnvelope,\n IMemoryRecord,\n IProvenance,\n Kind,\n LinkType,\n MemoryId,\n Tag,\n edgeTargetKey,\n isTemporalRecord,\n isVersionCurrent\n} from '../types';\nimport { IBodyConverterRegistry } from '../converters';\nimport { IMemoryStore } from '../store';\nimport { IVectorIndex, MemoryEmbedder } from '../vector';\nimport { ICycleGuardEdge, assertNoCycles } from './cycleGuard';\nimport {\n IEntityResolver,\n IFactExtractor,\n IMemoryClassifier,\n IRelationCandidate,\n IRelationExtractor\n} from './hostStages';\nimport {\n ICandidateEdge,\n ICandidateRecord,\n IEntityResolutionCandidate,\n IIngestItem,\n IIngestItemResult,\n IIngestedRecordResult,\n IMemoryClassification,\n IngestDisposition,\n ResolutionVerdict\n} from './model';\n\n/**\n * The provenance source stamped on every record the ingest pipeline writes.\n * @public\n */\nexport const HOST_INGEST_PROVENANCE_SOURCE: string = 'host-ingest';\n\n/**\n * The link type whose presence on a temporal-kind candidate fires the\n * contradicts→temporal-versioned interlock.\n * @public\n */\nexport const CONTRADICTS_LINK_TYPE: LinkType = 'contradicts' as LinkType;\n\n/**\n * The default stage-4 layer-2 cosine similarity threshold (design note §2). A\n * near-duplicate candidate is surfaced to the {@link IEntityResolver} only when\n * its nearest neighbor scores `>= 0.85`.\n * @public\n */\nexport const DEFAULT_SIMILARITY_THRESHOLD: number = 0.85;\n\n/**\n * The default top-K for stage-4 layer-2 similarity candidate generation.\n * @public\n */\nexport const DEFAULT_SIMILARITY_TOP_K: number = 5;\n\n/**\n * How the write-time cycle guard behaves: `'reject'` (default — a cycle-inducing\n * edge fails the ingest) or `'off'` (no acyclicity constraint, for deployments\n * whose link graphs are legitimately cyclic — e.g. mutual associative links).\n * @public\n */\nexport type CycleGuardMode = 'reject' | 'off';\n\n/**\n * The fgv-owned six-stage ingest orchestrator. Composes the host's staged\n * classify / extract / (optional) resolve / relate machinery around fgv's owned\n * validation boundary, dedup, edge + cycle safety, provenance stamping, and the\n * contradicts→temporal interlock.\n * @public\n */\nexport interface IMemoryIngestOrchestrator {\n /**\n * Ingest a SINGLE item end-to-end (the first-class per-turn streaming path).\n */\n ingestItem(item: IIngestItem): Promise<Result<IIngestItemResult>>;\n\n /**\n * Ingest a batch of items. A convenience loop over {@link\n * IMemoryIngestOrchestrator.ingestItem | ingestItem} — items are processed in\n * order and the first failure aborts the batch.\n */\n ingestBatch(items: ReadonlyArray<IIngestItem>): Promise<Result<ReadonlyArray<IIngestItemResult>>>;\n}\n\n/**\n * Parameters for {@link MemoryIngestOrchestrator.create}.\n * @public\n */\nexport interface IMemoryIngestOrchestratorCreateParams {\n /** The store every write bottoms out in (stage 6). */\n readonly store: IMemoryStore;\n /** Per-kind body converter registry — the stage-3 typed validation boundary. */\n readonly registry: IBodyConverterRegistry;\n /** Per-kind identity codecs (maps a candidate `entityId` to its storage address). */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default identity codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /** Stage 2 — the host's classifier. */\n readonly classifier: IMemoryClassifier;\n /** Stage 3 — the host's fact extractor. */\n readonly extractor: IFactExtractor;\n /** Stage 5 — the host's relation extractor. */\n readonly relationExtractor: IRelationExtractor;\n /**\n * Stage 4 (optional, OQ-13) — the host's entity resolver. Absent → stage-4\n * dedup is exact-`{ kind, body }`-hash only (the deterministic-identity path).\n */\n readonly entityResolver?: IEntityResolver;\n /**\n * Optional vector index for stage-4 layer-2 similarity candidate-gen. Wired\n * together with {@link IMemoryIngestOrchestratorCreateParams.embed | embed} AND\n * {@link IMemoryIngestOrchestratorCreateParams.entityResolver | entityResolver};\n * absent (or either co-requisite absent) → layer-2 is skipped and dedup is\n * exact-only.\n */\n readonly vectorIndex?: IVectorIndex;\n /** Optional embedder used to embed a candidate for layer-2 similarity search. */\n readonly embed?: MemoryEmbedder;\n /**\n * Stage-4 layer-2 cosine threshold. Defaults to {@link\n * DEFAULT_SIMILARITY_THRESHOLD} (`0.85`).\n */\n readonly similarityThreshold?: number;\n /**\n * Stage-4 layer-2 top-K. Defaults to {@link DEFAULT_SIMILARITY_TOP_K} (`5`).\n */\n readonly similarityTopK?: number;\n /** Write-time cycle guard mode. Defaults to `'reject'`. */\n readonly cycleGuard?: CycleGuardMode;\n /** Diagnostic logger (defaults to a no-op). */\n readonly logger?: Logging.ILogger;\n}\n\n/** The fully-wired stage-4 layer-2 dependencies (present only when all three are supplied). */\ninterface ISimilarityWiring {\n readonly resolver: IEntityResolver;\n readonly vectorIndex: IVectorIndex;\n readonly embed: MemoryEmbedder;\n}\n\n/** A snapshot record paired with its resolved scope-qualified `(scope, id)` address. */\ninterface IScopedRecord {\n readonly address: IEdgeTarget;\n readonly record: IMemoryRecord<unknown>;\n}\n\n/** Internal per-candidate plan threaded through the pipeline. */\ninterface ICandidatePlan {\n readonly candidate: ICandidateRecord;\n /** The write target's storage address (re-addressed to the target for merge-into). */\n readonly writeAddress: IIdentityCodecResult;\n /** The write target's entity id (re-addressed for merge-into). */\n readonly writeEntityId: EntityId;\n /** The reference id used in stage-5 edges (the write target's `idStem`). */\n readonly refId: MemoryId;\n /**\n * The scope-qualified reference used in stage-5 edges: the write target's\n * `(scope, idStem)`. Stage-5 sources / dedup all key on this scoped address so\n * two candidates that share a stem across scopes never collide.\n */\n readonly refTarget: IEdgeTarget;\n /** The resolution verdict; carries the target id on its target-bearing arms. */\n readonly verdict: ResolutionVerdict;\n /**\n * The pre-ingest target record for a `merge-into` write — its existing\n * `tags` / `links` / `provenance` are UNIONed with the candidate's at stage 6\n * so a wholesale-replace merge never wipes them.\n */\n readonly mergeTarget?: IMemoryRecord<unknown>;\n}\n\n/**\n * Default {@link IMemoryIngestOrchestrator}.\n * @public\n */\nexport class MemoryIngestOrchestrator implements IMemoryIngestOrchestrator {\n private readonly _store: IMemoryStore;\n private readonly _registry: IBodyConverterRegistry;\n private readonly _codecs: ReadonlyMap<Kind, IIdentityCodec>;\n private readonly _defaultCodec: IIdentityCodec | undefined;\n private readonly _classifier: IMemoryClassifier;\n private readonly _extractor: IFactExtractor;\n private readonly _relationExtractor: IRelationExtractor;\n private readonly _similarity: ISimilarityWiring | undefined;\n private readonly _similarityThreshold: number;\n private readonly _similarityTopK: number;\n private readonly _cycleGuard: CycleGuardMode;\n private readonly _logger: Logging.ILogger;\n private readonly _hasher: Hash.Crc32Normalizer;\n\n private constructor(params: IMemoryIngestOrchestratorCreateParams) {\n this._store = params.store;\n this._registry = params.registry;\n this._codecs = params.codecs ?? new Map<Kind, IIdentityCodec>();\n this._defaultCodec = params.defaultCodec;\n this._classifier = params.classifier;\n this._extractor = params.extractor;\n this._relationExtractor = params.relationExtractor;\n this._similarity =\n params.entityResolver !== undefined && params.vectorIndex !== undefined && params.embed !== undefined\n ? { resolver: params.entityResolver, vectorIndex: params.vectorIndex, embed: params.embed }\n : undefined;\n this._similarityThreshold = params.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;\n this._similarityTopK = params.similarityTopK ?? DEFAULT_SIMILARITY_TOP_K;\n this._cycleGuard = params.cycleGuard ?? 'reject';\n this._logger = params.logger ?? new Logging.NoOpLogger();\n this._hasher = new Hash.Crc32Normalizer();\n }\n\n /** Family-convention factory. */\n public static create(params: IMemoryIngestOrchestratorCreateParams): Result<MemoryIngestOrchestrator> {\n return succeed(new MemoryIngestOrchestrator(params));\n }\n\n /** {@inheritDoc IMemoryIngestOrchestrator.ingestItem} */\n public async ingestItem(item: IIngestItem): Promise<Result<IIngestItemResult>> {\n return (await this._classify(item))\n .thenOnSuccess((classification) => this._extract(item, classification))\n .thenOnSuccess((candidates) => this._processCandidates(item, candidates));\n }\n\n /** {@inheritDoc IMemoryIngestOrchestrator.ingestBatch} */\n public async ingestBatch(\n items: ReadonlyArray<IIngestItem>\n ): Promise<Result<ReadonlyArray<IIngestItemResult>>> {\n const results: IIngestItemResult[] = [];\n for (const item of items) {\n const result: Result<IIngestItemResult> = await this.ingestItem(item);\n if (result.isFailure()) {\n return fail(result.message);\n }\n results.push(result.value);\n }\n return succeed(results);\n }\n\n /** Stage 2 — classify (host), normalizing a rejected promise into a Failure. */\n private async _classify(item: IIngestItem): Promise<Result<IMemoryClassification>> {\n return this._capture(() => this._classifier.classify(item), `ingest '${item.id}': classify`);\n }\n\n /** Stage 3 — extract (host), normalizing a rejected promise into a Failure. */\n private async _extract(\n item: IIngestItem,\n classification: IMemoryClassification\n ): Promise<Result<ReadonlyArray<ICandidateRecord>>> {\n return this._capture(() => this._extractor.extract(item, classification), `ingest '${item.id}': extract`);\n }\n\n /**\n * Stages 3b-6 over the extracted candidates: validate bodies, resolve/dedup\n * (stage 4), relate + cycle guard (stage 5), and load-with-provenance (stage 6).\n */\n private async _processCandidates(\n item: IIngestItem,\n candidates: ReadonlyArray<ICandidateRecord>\n ): Promise<Result<IIngestItemResult>> {\n // Snapshot the store once; stage-4 resolution and the cycle guard reason over\n // the pre-ingest state.\n const snapshotResult: Result<ReadonlyArray<IMemoryRecord<unknown>>> = await this._store.list();\n if (snapshotResult.isFailure()) {\n return fail(`ingest '${item.id}': failed to snapshot store: ${snapshotResult.message}`);\n }\n const snapshot: ReadonlyArray<IMemoryRecord<unknown>> = snapshotResult.value;\n // Resolve every snapshot record's scope-qualified address ONCE, then index it\n // by the canonical scoped key. The single `byKey` view drives BOTH the edge\n // path (validation + cycle guard) AND the verdict/similarity target lookups —\n // so a filename stem reused across scopes never aliases on any path.\n const scopedResult: Result<ReadonlyArray<IScopedRecord>> = this._scopeRecords(snapshot);\n if (scopedResult.isFailure()) {\n return fail(`ingest '${item.id}': ${scopedResult.message}`);\n }\n const scoped: ReadonlyArray<IScopedRecord> = scopedResult.value;\n const byKey: ReadonlyMap<string, IMemoryRecord<unknown>> = new Map<string, IMemoryRecord<unknown>>(\n scoped.map((s) => [edgeTargetKey(s.address), s.record])\n );\n\n // Stage 3b + 4: validate each body and resolve a verdict/plan.\n const plans: ICandidatePlan[] = [];\n for (const candidate of candidates) {\n const planResult: Result<ICandidatePlan> = await this._planCandidate(item, candidate, snapshot, byKey);\n if (planResult.isFailure()) {\n return fail(planResult.message);\n }\n plans.push(planResult.value);\n }\n\n // Stage 5: relate over the writable candidates, validate + cycle-guard.\n const writablePlans: ICandidatePlan[] = plans.filter((plan) => plan.verdict.verdict !== 'duplicate-of');\n const edgesResult: Result<ReadonlyArray<ICandidateEdge>> = await this._relate(\n item,\n writablePlans,\n MemoryIngestOrchestrator._collapseRedirects(plans),\n scoped,\n byKey\n );\n if (edgesResult.isFailure()) {\n return fail(edgesResult.message);\n }\n const edges: ReadonlyArray<ICandidateEdge> = edgesResult.value;\n\n // Stage 6: load-with-provenance, in extraction order.\n const records: IIngestedRecordResult[] = [];\n for (const plan of plans) {\n const outcome: Result<IIngestedRecordResult> = await this._loadCandidate(item, plan, edges);\n if (outcome.isFailure()) {\n return fail(outcome.message);\n }\n records.push(outcome.value);\n }\n return succeed({ item, records });\n }\n\n /** Stage 3b + 4 for one candidate: validate body, resolve address, resolve verdict. */\n private async _planCandidate(\n item: IIngestItem,\n candidate: ICandidateRecord,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ICandidatePlan>> {\n const kind: Kind = candidate.envelope.kind;\n // Stage 3b: the typed validation boundary — no unchecked host body reaches the store.\n const bodyResult: Result<string> = this._registry\n .convert(kind, candidate.body)\n .withErrorFormat((msg) => `ingest '${item.id}': candidate body for kind '${kind}' is invalid: ${msg}`)\n .onSuccess(() => MemoryIngestOrchestrator._asStringBody(item, candidate));\n if (bodyResult.isFailure()) {\n return fail(bodyResult.message);\n }\n const body: string = bodyResult.value;\n\n const addrResult: Result<IIdentityCodecResult> = this._resolveAddress(candidate.envelope.entityId, kind);\n if (addrResult.isFailure()) {\n return fail(`ingest '${item.id}': ${addrResult.message}`);\n }\n const addr: IIdentityCodecResult = addrResult.value;\n\n return (await this._resolveVerdict(candidate, kind, body, addr, snapshot, byKey)).onSuccess((verdict) =>\n this._planFromVerdict(item, candidate, addr, verdict, byKey)\n );\n }\n\n /**\n * Turn a resolved verdict into a candidate plan. A `new` verdict writes under the\n * candidate's own address. Every TARGET-bearing verdict\n * (`duplicate-of` / `supersede` / `merge-into`) is validated uniformly: the\n * target must be a real store record (fgv owns validation — a non-compliant host\n * resolver never smuggles a bogus id through) AND its kind must equal the\n * candidate's kind (a cross-kind target would write to the wrong scope). Only\n * `merge-into` re-addresses the write to the target's entity.\n */\n private _planFromVerdict(\n item: IIngestItem,\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n verdict: ResolutionVerdict,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Result<ICandidatePlan> {\n if (verdict.verdict === 'new') {\n return Convert.memoryId.convert(addr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: addr,\n writeEntityId: candidate.envelope.entityId,\n refId,\n refTarget: { scope: addr.scope, id: refId },\n verdict\n })\n );\n }\n // duplicate-of | supersede | merge-into: the target must exist and share the\n // candidate's kind. Lookup is on the canonical scoped key, so a stem reused\n // across scopes binds only the record the verdict actually named.\n const target: IMemoryRecord<unknown> | undefined = byKey.get(edgeTargetKey(verdict.target));\n if (target === undefined) {\n return fail(\n `ingest '${item.id}': ${verdict.verdict} target '${MemoryIngestOrchestrator._formatTarget(\n verdict.target\n )}' does not exist in the store`\n );\n }\n if (target.envelope.kind !== candidate.envelope.kind) {\n return fail(\n `ingest '${item.id}': ${verdict.verdict} target '${MemoryIngestOrchestrator._formatTarget(\n verdict.target\n )}' is kind '${target.envelope.kind}' but the candidate is kind '${candidate.envelope.kind}'`\n );\n }\n if (verdict.verdict === 'merge-into') {\n // Re-address the write to the target's entity, carrying the target record so\n // stage 6 can UNION its existing tags/links (never overwrite them).\n const targetEntityId: EntityId = target.envelope.entityId;\n // The merge target is a snapshot record, and `_scopeRecords` already proved\n // every snapshot record's address resolves before planning runs — so this\n // re-resolve (needed for the full codec result: scope + idStem + isVersioned)\n // cannot fail. No error-context wrap is warranted; a failure here would be a\n // logic contradiction, not a user-facing condition.\n return this._resolveAddress(targetEntityId, target.envelope.kind).onSuccess((targetAddr) =>\n Convert.memoryId.convert(targetAddr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: targetAddr,\n writeEntityId: targetEntityId,\n refId,\n refTarget: { scope: targetAddr.scope, id: refId },\n verdict,\n mergeTarget: target\n })\n )\n );\n }\n // duplicate-of | supersede: write under the candidate's own address.\n return Convert.memoryId.convert(addr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: addr,\n writeEntityId: candidate.envelope.entityId,\n refId,\n refTarget: { scope: addr.scope, id: refId },\n verdict\n })\n );\n }\n\n /**\n * Stage 4 — resolve a dedup verdict. Layer 1: an exact `{ kind, body }` match in\n * the candidate's scope is a `duplicate-of`, at the granularity the kind's\n * {@link DedupScope} declares — scope-wide for `'content'`, restricted to the\n * candidate's own entity for `'entity'` (design note §1). Layer 2 (only when\n * a resolver + vector index + embedder are all wired): embed the candidate,\n * surface over-threshold neighbors, and dispatch to the {@link IEntityResolver}.\n * Otherwise the verdict is `new` (the exact-only fall-back path).\n */\n private async _resolveVerdict(\n candidate: ICandidateRecord,\n kind: Kind,\n body: string,\n addr: IIdentityCodecResult,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return this._findExactMatch(kind, body, addr, snapshot).thenOnSuccess(async (matchId) => {\n if (matchId !== undefined) {\n // The exact-match cohort is filtered to `addr.scope`, so the match lives\n // under that scope — its scope-qualified target is `(addr.scope, matchId)`.\n return succeed({ verdict: 'duplicate-of', target: { scope: addr.scope, id: matchId } });\n }\n const layer2: ISimilarityWiring | undefined = this._similarity;\n if (layer2 === undefined) {\n // No layer-2: exact-only fall-back (the deterministic-identity host path).\n return succeed({ verdict: 'new' });\n }\n return this._resolveViaSimilarity(candidate, addr, body, layer2, byKey);\n });\n }\n\n /** Layer-2 similarity candidate-gen + resolver dispatch. */\n private async _resolveViaSimilarity(\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n body: string,\n wiring: ISimilarityWiring,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return MemoryIngestOrchestrator._provisionalRecord(candidate, addr.idStem, body).thenOnSuccess(\n (provisional) => this._resolveViaSimilarityEmbedded(candidate, addr, wiring, byKey, provisional)\n );\n }\n\n /** Layer-2 continuation once the candidate has a provisional record to embed. */\n private async _resolveViaSimilarityEmbedded(\n candidate: ICandidateRecord,\n addr: IIdentityCodecResult,\n wiring: ISimilarityWiring,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>,\n provisional: IMemoryRecord<unknown>\n ): Promise<Result<ResolutionVerdict>> {\n const embedded: Result<Float32Array | undefined> = await this._capture(\n () => wiring.embed(provisional),\n `ingest '${candidate.envelope.entityId}': embed candidate`\n );\n if (embedded.isFailure()) {\n return fail(embedded.message);\n }\n // The embedder deliberately declined this candidate, so there is no vector to\n // search with and layer-2 similarity dedup cannot run for it. That is the same\n // position as a search that found nothing similar — `'new'` — and not an\n // error: declining to embed a kind must not make it un-ingestable.\n if (embedded.value === undefined) {\n return succeed({ verdict: 'new' });\n }\n // Hoisted: the `undefined` check above does not narrow across the callback\n // boundary below, and a local keeps the non-null assertion out of the code.\n const vector: Float32Array = embedded.value;\n const queried = await this._capture(\n () => wiring.vectorIndex.query(vector, this._similarityTopK),\n `ingest '${candidate.envelope.entityId}': similarity query`\n );\n if (queried.isFailure()) {\n return fail(queried.message);\n }\n const similar: IEntityResolutionCandidate[] = [];\n for (const hit of queried.value) {\n // Skip below-threshold hits and the candidate's OWN scope-qualified address\n // (a re-ingest of the same entity must not dedup against its prior version).\n // Both the scope AND the id must match to be \"self\" — a same-stem record in\n // another scope is a legitimate distinct neighbor. This field-equality is\n // exactly equivalent to comparing `edgeTargetKey(hit.target)` against the\n // candidate's own key (edgeTargetKey is pure and injective on `(scope, id)`),\n // so this one site reads the components directly rather than re-keying.\n const isSelf: boolean = hit.target.scope === addr.scope && hit.target.id === addr.idStem;\n if (hit.score < this._similarityThreshold || isSelf) {\n continue;\n }\n const record: IMemoryRecord<unknown> | undefined = byKey.get(edgeTargetKey(hit.target));\n if (record !== undefined) {\n similar.push({ target: hit.target, record, score: hit.score });\n }\n }\n if (similar.length === 0) {\n return succeed({ verdict: 'new' });\n }\n return this._capture(\n () => wiring.resolver.resolve(candidate, similar),\n `ingest '${candidate.envelope.entityId}': resolve`\n );\n }\n\n /**\n * Find an existing record whose `{ kind, body }` hash matches the candidate's\n * (layer-1 exact dedup, design note §1). Invalidated temporal versions are\n * excluded — only a live (non-temporal or current) record deduplicates a\n * candidate.\n *\n * @remarks\n * The cohort's granularity is the kind's DECLARED {@link DedupScope}, read\n * through {@link IMemoryStore.dedupScopeFor} so this layer and the store's own\n * write path can never disagree:\n *\n * - `'content'` — every live same-kind record in the candidate's scope,\n * regardless of entity. A cross-id body collision IS a duplicate (the\n * knowledge family; unchanged behavior).\n * - `'entity'` — only records at the candidate's OWN entity address. Two\n * distinct entities with byte-identical bodies never collapse into one\n * another, which is what the declaration has always meant on the direct-put\n * path and now means here too.\n *\n * The same-id collapse itself remains the store's job — this layer only decides\n * whether a cross-id body collision is eligible to be a `duplicate-of` at all.\n */\n private _findExactMatch(\n kind: Kind,\n body: string,\n addr: IIdentityCodecResult,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<MemoryId | undefined> {\n const dedupScope: DedupScope = this._store.dedupScopeFor(kind);\n // Same-kind, same-scope, LIVE (non-temporal or current) records are the exact\n // cohort, narrowed to the candidate's own entity address under `'entity'`\n // granularity. `_resolveAddress(...).orDefault()` collapses an unresolved\n // codec to `undefined` — a non-matching address — with no explicit failure\n // branch, exactly as the scope-only filter did before.\n const cohort: ReadonlyArray<IMemoryRecord<unknown>> = snapshot.filter((record) => {\n if (record.envelope.kind !== kind || (isTemporalRecord(record) && !isVersionCurrent(record))) {\n return false;\n }\n const recordAddr: IIdentityCodecResult | undefined = this._resolveAddress(\n record.envelope.entityId,\n record.envelope.kind\n ).orDefault();\n if (recordAddr === undefined || recordAddr.scope !== addr.scope) {\n return false;\n }\n return dedupScope === 'content' || recordAddr.idStem === addr.idStem;\n });\n return this._exactKey(kind, body).onSuccess((key) =>\n mapResults(\n cohort.map((record) =>\n MemoryIngestOrchestrator._recordBodyString(record).onSuccess((recordBody) =>\n this._exactKey(record.envelope.kind, recordBody).onSuccess((recordKey) =>\n succeed({ id: record.envelope.id, key: recordKey })\n )\n )\n )\n ).onSuccess((keyed) => succeed(keyed.find((entry) => entry.key === key)?.id))\n );\n }\n\n /**\n * The body of a persisted record, required to be a string (the store persists\n * only string bodies). Fails loudly rather than blind-casting an `unknown` body\n * into the exact-dedup hash — a non-string existing body is a store-integrity\n * fault, surfaced with context, not a silent miscompute.\n */\n private static _recordBodyString(record: IMemoryRecord<unknown>): Result<string> {\n if (typeof record.body !== 'string') {\n return fail(\n `ingest: stored record '${record.envelope.id}' has a non-string body (got ${typeof record.body})`\n );\n }\n return succeed(record.body);\n }\n\n /** The stage-4 exact-dedup key over `{ kind, body }` (design note §1). */\n private _exactKey(kind: Kind, body: string): Result<string> {\n return this._hasher.computeHash({ kind, body });\n }\n\n /** Stage 5 — relate (host), redirect collapsed targets, validate edges, and run the write-time cycle guard. */\n private async _relate(\n item: IIngestItem,\n writablePlans: ReadonlyArray<ICandidatePlan>,\n redirects: ReadonlyMap<string, IEdgeTarget>,\n scoped: ReadonlyArray<IScopedRecord>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Promise<Result<ReadonlyArray<ICandidateEdge>>> {\n const relationCandidates: IRelationCandidate[] = writablePlans.map((plan) => ({\n candidate: plan.candidate,\n id: plan.refTarget\n }));\n const proposed: Result<ReadonlyArray<ICandidateEdge>> = await this._capture(\n () => this._relationExtractor.relate({ item, candidates: relationCandidates }),\n `ingest '${item.id}': relate`\n );\n if (proposed.isFailure()) {\n return proposed;\n }\n // Redirect BEFORE validation and BEFORE the cycle guard: an edge naming a\n // collapsed candidate must be judged — and persisted — against the record it\n // collapsed into, not against the address that no longer gets written.\n const edges: ReadonlyArray<ICandidateEdge> = MemoryIngestOrchestrator._redirectEdges(\n proposed.value,\n redirects\n );\n // refIds and the existing-record view (`byKey`, shared with the verdict path)\n // both key on the canonical scoped address, so a stem reused across scopes\n // never aliases.\n const refIds: ReadonlySet<string> = new Set<string>(\n writablePlans.map((plan) => edgeTargetKey(plan.refTarget))\n );\n const validation: Result<true> = this._validateEdges(item, edges, refIds, byKey);\n if (validation.isFailure()) {\n return fail(validation.message);\n }\n if (this._cycleGuard === 'reject') {\n const guard: Result<true> = assertNoCycles(\n MemoryIngestOrchestrator._existingEdges(scoped),\n edges.map((e) => ({ source: e.source, target: e.edge.target, type: e.edge.type }))\n );\n if (guard.isFailure()) {\n return fail(`ingest '${item.id}': ${guard.message}`);\n }\n }\n return succeed(edges);\n }\n\n /**\n * The stage-5 edge-target redirect map for this pass: every `duplicate-of`\n * candidate's OWN scoped address, mapped to the address of the record its\n * verdict collapsed it into (design note §3).\n *\n * @remarks\n * A `duplicate-of` verdict means \"this candidate IS that record\". The candidate\n * is therefore not written, and its address never becomes a live reference — so\n * a sibling edge built against it in the same pass would resolve to neither a\n * written candidate nor an existing record and would fail the WHOLE ingest item.\n * That is a second-order hazard of collapsing, not a defect in the edge: the\n * host related two candidates it was correctly told about, and one of them\n * turned out to already exist.\n *\n * Redirecting is the honest repair, and it is independent of {@link DedupScope}\n * — it applies equally to a `'content'` kind, where the collapse is exactly\n * right and the ingest still must not fail.\n *\n * The map cannot chain: {@link MemoryIngestOrchestrator._planFromVerdict}\n * requires every target-bearing verdict's target to already exist in the store\n * snapshot, so a redirect destination is always a persisted record and never\n * another collapsed candidate. One pass is sufficient by construction.\n */\n private static _collapseRedirects(plans: ReadonlyArray<ICandidatePlan>): ReadonlyMap<string, IEdgeTarget> {\n const redirects: Map<string, IEdgeTarget> = new Map<string, IEdgeTarget>();\n for (const plan of plans) {\n if (plan.verdict.verdict === 'duplicate-of') {\n redirects.set(edgeTargetKey(plan.refTarget), plan.verdict.target);\n }\n }\n return redirects;\n }\n\n /**\n * Rewrite each edge whose TARGET names a collapsed candidate to point at the\n * record that candidate collapsed into.\n *\n * @remarks\n * Only the target is redirected. An edge whose SOURCE is a collapsed candidate\n * stays untouched and is still rejected by {@link\n * MemoryIngestOrchestrator._validateEdges}: sources are the records an edge is\n * written ONTO, a collapsed candidate is never written, and the relation\n * extractor is only ever offered writable candidates as edge sources in the\n * first place. Silently relocating such an edge onto an existing record would\n * attribute a link the host never asked for — the loud failure is correct there.\n */\n private static _redirectEdges(\n edges: ReadonlyArray<ICandidateEdge>,\n redirects: ReadonlyMap<string, IEdgeTarget>\n ): ReadonlyArray<ICandidateEdge> {\n if (redirects.size === 0) {\n return edges;\n }\n return edges.map((e) => {\n const to: IEdgeTarget | undefined = redirects.get(edgeTargetKey(e.edge.target));\n return to === undefined ? e : { ...e, edge: { ...e.edge, target: to } };\n });\n }\n\n /**\n * Validate stage-5 edges: each `source` must be a candidate being written; each\n * `target` must resolve to a sibling candidate or an existing store record. All\n * matching is on the canonical scope-qualified address.\n */\n private _validateEdges(\n item: IIngestItem,\n edges: ReadonlyArray<ICandidateEdge>,\n refIds: ReadonlySet<string>,\n byKey: ReadonlyMap<string, IMemoryRecord<unknown>>\n ): Result<true> {\n return mapResults(\n edges.map((edge) => {\n if (!refIds.has(edgeTargetKey(edge.source))) {\n return fail(\n `ingest '${item.id}': edge source '${MemoryIngestOrchestrator._formatTarget(\n edge.source\n )}' is not a candidate being written`\n );\n }\n const targetKey: string = edgeTargetKey(edge.edge.target);\n if (!refIds.has(targetKey) && byKey.get(targetKey) === undefined) {\n return fail(\n `ingest '${item.id}': edge target '${MemoryIngestOrchestrator._formatTarget(\n edge.edge.target\n )}' resolves to neither a sibling candidate nor an existing record`\n );\n }\n return succeed(true);\n })\n ).onSuccess(() => succeed(true));\n }\n\n /** Stage 6 — stamp provenance + edges, admit through the store, record the outcome. */\n private async _loadCandidate(\n item: IIngestItem,\n plan: ICandidatePlan,\n allEdges: ReadonlyArray<ICandidateEdge>\n ): Promise<Result<IIngestedRecordResult>> {\n const refKey: string = edgeTargetKey(plan.refTarget);\n const myEdges: ReadonlyArray<ICandidateEdge> = allEdges.filter((e) => edgeTargetKey(e.source) === refKey);\n if (plan.verdict.verdict === 'duplicate-of') {\n // No write: the existing target satisfied the candidate. The target id is a\n // typed field of the narrowed `duplicate-of` verdict — no cast, no guard.\n return succeed({\n candidate: plan.candidate,\n resolution: plan.verdict,\n disposition: 'deduped',\n id: plan.verdict.target.id,\n edges: myEdges\n });\n }\n return this._buildRecord(item, plan, myEdges).thenOnSuccess(async (record) =>\n (await this._store.put(record))\n .withErrorFormat((msg) => `ingest '${item.id}': write failed: ${msg}`)\n .onSuccess((persisted) => {\n const disposition: IngestDisposition = plan.verdict.verdict === 'merge-into' ? 'merged' : 'written';\n const interlock: 'temporal-versioned' | undefined =\n plan.writeAddress.isVersioned && myEdges.some((e) => e.edge.type === CONTRADICTS_LINK_TYPE)\n ? 'temporal-versioned'\n : undefined;\n return succeed({\n candidate: plan.candidate,\n resolution: plan.verdict,\n disposition,\n id: persisted.envelope.id,\n record: persisted,\n edges: myEdges,\n ...(interlock !== undefined ? { interlock } : {})\n });\n })\n );\n }\n\n /** Build the fully-stamped record to persist (provenance + edges + placeholder txn fields). */\n private _buildRecord(\n item: IIngestItem,\n plan: ICandidatePlan,\n myEdges: ReadonlyArray<ICandidateEdge>\n ): Result<IMemoryRecord<unknown>> {\n const base: Omit<IMemoryEnvelope, 'id' | 'seq' | 'contentHash' | 'created' | 'updated'> =\n plan.candidate.envelope;\n // For merge-into the store's `applyUpdate` REPLACES array fields wholesale, so\n // the persisted envelope must already carry the UNION of the target's existing\n // tags/links/provenance and the candidate's — otherwise the merge silently\n // wipes the target's prior links/tags.\n const target: IMemoryRecord<unknown> | undefined = plan.mergeTarget;\n const priorLinks: ReadonlyArray<IEdge> = target !== undefined ? target.envelope.links : [];\n const priorTags: ReadonlyArray<Tag> = target !== undefined ? target.envelope.tags : [];\n const priorProvenance: IProvenance = target !== undefined ? target.envelope.provenance : { source: '' };\n return Convert.memoryId.convert(plan.writeAddress.idStem).onSuccess((id) =>\n // Dedup the combined links by canonical edge key: the target's prior links, the\n // candidate's own links, and the stage-5 edges (two candidates that resolve\n // merge-into the SAME target share a `refId` — hence the same `myEdges` — and a\n // relation extractor may repeat an edge) each appear exactly once.\n this._dedupEdges([...priorLinks, ...base.links, ...myEdges.map((e) => e.edge)]).onSuccess((links) => {\n const provenance: IProvenance = {\n // Preserve the target's provenance extension keys, overlay the candidate's,\n // then stamp the host-ingest source + derivedFrom (target present only for\n // merge-into; otherwise the seed is inert).\n ...(target !== undefined ? priorProvenance : {}),\n ...base.provenance,\n source: HOST_INGEST_PROVENANCE_SOURCE,\n ...(item.sourceId !== undefined ? { derivedFrom: item.sourceId } : {})\n };\n const envelope: IMemoryEnvelope = {\n ...base,\n id,\n entityId: plan.writeEntityId,\n seq: 0,\n contentHash: '',\n created: 0,\n updated: 0,\n provenance,\n tags: MemoryIngestOrchestrator._unionTags(priorTags, base.tags),\n links\n };\n return succeed({ envelope, body: plan.candidate.body });\n })\n );\n }\n\n /** Union two tag lists, de-duplicated, preserving first-occurrence order. */\n private static _unionTags(prior: ReadonlyArray<Tag>, incoming: ReadonlyArray<Tag>): ReadonlyArray<Tag> {\n const seen: Set<string> = new Set<string>();\n const out: Tag[] = [];\n for (const tag of [...prior, ...incoming]) {\n if (!seen.has(tag)) {\n seen.add(tag);\n out.push(tag);\n }\n }\n return out;\n }\n\n /** De-duplicate a link list by canonical edge hash, preserving first-occurrence order. */\n private _dedupEdges(edges: ReadonlyArray<IEdge>): Result<ReadonlyArray<IEdge>> {\n const seen: Set<string> = new Set<string>();\n const deduped: IEdge[] = [];\n return mapResults(\n edges.map((edge) =>\n this._hasher.computeHash(edge).onSuccess((key) => {\n if (!seen.has(key)) {\n seen.add(key);\n deduped.push(edge);\n }\n return succeed(key);\n })\n )\n ).onSuccess(() => succeed(deduped));\n }\n\n /** Resolve a `(kind, entityId)` to its storage address via the registered codec. */\n private _resolveAddress(entityId: EntityId, kind: Kind): Result<IIdentityCodecResult> {\n const codec: IIdentityCodec | undefined = this._codecs.get(kind) ?? this._defaultCodec;\n if (codec === undefined) {\n return fail(`no identity codec registered for kind '${kind}'`);\n }\n return codec.encode(entityId);\n }\n\n /** Run a host hook, normalizing a thrown/rejected hook into a Failure (never throws across the seam). */\n private async _capture<T>(op: () => Promise<Result<T>>, label: string): Promise<Result<T>> {\n try {\n return await op();\n } catch (err) {\n const message: string = `${label} threw: ${String(err)}`;\n this._logger.warn(message);\n return fail(message);\n }\n }\n\n /**\n * Every existing outbound edge in the snapshot, as cycle-guard edges. The\n * source is the record's own scope-qualified address (already resolved by\n * {@link MemoryIngestOrchestrator._scopeRecords}); the target is the edge's\n * own scoped target. Both ends are scoped so the guard never conflates a stem\n * shared across scopes into one graph node.\n */\n private static _existingEdges(scoped: ReadonlyArray<IScopedRecord>): ReadonlyArray<ICycleGuardEdge> {\n const edges: ICycleGuardEdge[] = [];\n for (const s of scoped) {\n for (const edge of s.record.envelope.links) {\n edges.push({ source: s.address, target: edge.target, type: edge.type });\n }\n }\n return edges;\n }\n\n /**\n * Resolve every snapshot record's scope-qualified `(scope, id)` address via its\n * registered codec. Fails loudly if a record's kind has no resolvable codec —\n * the edge path cannot place an un-scopeable record in the graph, and a missing\n * codec for a stored kind is a real misconfiguration, not something to paper over.\n */\n private _scopeRecords(\n records: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<ReadonlyArray<IScopedRecord>> {\n return mapResults(\n records.map((record) =>\n this._resolveAddress(record.envelope.entityId, record.envelope.kind)\n .withErrorFormat((msg) => `cannot resolve scope for stored record '${record.envelope.id}': ${msg}`)\n .onSuccess((addr) => succeed({ address: { scope: addr.scope, id: record.envelope.id }, record }))\n )\n );\n }\n\n /** Human-readable `scope/id` rendering of a scoped target for edge-validation diagnostics. */\n private static _formatTarget(target: IEdgeTarget): string {\n return `${target.scope}/${target.id}`;\n }\n\n /** A provisional record for embedding a candidate (placeholder txn-time fields). */\n private static _provisionalRecord(\n candidate: ICandidateRecord,\n idStem: string,\n body: string\n ): Result<IMemoryRecord<unknown>> {\n return Convert.memoryId.convert(idStem).onSuccess((id) => {\n const envelope: IMemoryEnvelope = {\n ...candidate.envelope,\n id,\n seq: 0,\n contentHash: '',\n created: 0,\n updated: 0\n };\n return succeed({ envelope, body });\n });\n }\n\n /** Require a candidate body to be a string (the store persists only string bodies). */\n private static _asStringBody(item: IIngestItem, candidate: ICandidateRecord): Result<string> {\n if (typeof candidate.body !== 'string') {\n return fail(\n `ingest '${item.id}': candidate body for kind '${\n candidate.envelope.kind\n }' must be a string (got ${typeof candidate.body})`\n );\n }\n return succeed(candidate.body);\n }\n}\n"]}
|
|
@@ -113,6 +113,12 @@ export class MemoryObservationStore {
|
|
|
113
113
|
if (criteria.outcome !== undefined && record.outcome !== criteria.outcome) {
|
|
114
114
|
return false;
|
|
115
115
|
}
|
|
116
|
+
// A record carrying no embed outcome never matches an `embed` criterion —
|
|
117
|
+
// "the question did not apply here" is not the same answer as any of the
|
|
118
|
+
// four, and matching it would put unwired writes in a coverage-gap report.
|
|
119
|
+
if (criteria.embed !== undefined && record.embed !== criteria.embed) {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
116
122
|
return true;
|
|
117
123
|
}
|
|
118
124
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoryObservationStore.js","sourceRoot":"","sources":["../../../src/packlets/observe/memoryObservationStore.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAU,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAenE;;;;;;;;;;;;;;;;;;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eed } from '@fgv/ts-utils';\nimport { IMemoryObservationQuery, IMemoryObservationRecord, IMemoryObserver } from './observer';\n\n/**\n * Construction options for {@link MemoryObservationStore.create}.\n * @public\n */\nexport interface IMemoryObservationStoreCreateParams {\n /**\n * Maximum number of observation records retained before the oldest is\n * overwritten. Defaults to `1000`. Must be a positive integer if supplied.\n */\n readonly maxRecords?: number;\n}\n\n/**\n * The default in-memory observation store: an {@link IMemoryObserver} that\n * retains the records it observes in a bounded ring and answers schema-aware\n * {@link MemoryObservationStore.query | queries} over them.\n *\n * @remarks\n * **Privacy posture — this store is most-permissive by design.** It retains\n * every field of every record verbatim, including any `provenance` and\n * `querySnapshot`. The library bakes in **no** redaction, retention, or\n * field-stripping policy — that is deployment policy, not library policy. A\n * deployment that must redact wraps this store with its own\n * {@link IMemoryObserver} that transforms records before forwarding, or\n * substitutes a different observer entirely. Size is the only bounded\n * dimension, via `maxRecords`.\n *\n * The store composes `RetainingRingBuffer` from `@fgv/ts-utils` (it does not\n * hand-roll a ring) and implements {@link IMemoryObserver} directly — `observe`\n * (the hook) and `query` (the read surface) live on the same class. Wire it via\n * {@link IFileTreeMemoryStoreCreateParams.observers}. `seq` and `timestamp` are\n * assigned by the firing authority (the store) before `observe`, so this store\n * never mints them.\n * @public\n */\nexport class MemoryObservationStore implements IMemoryObserver {\n /**\n * The bounded ring of observed records. The firing authority assigns each\n * record's `seq`, so the ring's monotonic-`seq` cursor contract is satisfied\n * by that authority's per-instance counter.\n * @internal\n */\n private readonly _buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>;\n\n /**\n * @param buffer - The pre-constructed backing ring buffer.\n * @internal\n */\n private constructor(buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>) {\n this._buffer = buffer;\n }\n\n /**\n * The highest `seq` observed so far. Hold this value and pass it as\n * `sinceSeq` to {@link MemoryObservationStore.query | query} to page only\n * records observed afterward. Stable across ring eviction and\n * {@link MemoryObservationStore.clear | clear}.\n */\n public get lastSeq(): number {\n return this._buffer.lastSeq;\n }\n\n /**\n * The number of records currently retained.\n */\n public get size(): number {\n return this._buffer.size;\n }\n\n /**\n * Family-convention factory.\n * @param params - {@link IMemoryObservationStoreCreateParams | Construction options}.\n * @returns On success, a new store. Fails if `maxRecords` is supplied and is\n * not a positive integer.\n */\n public static create(params?: IMemoryObservationStoreCreateParams): Result<MemoryObservationStore> {\n const maxRecords: number | undefined = params?.maxRecords;\n if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {\n return fail(`MemoryObservationStore: maxRecords must be a positive integer (got ${maxRecords})`);\n }\n return succeed(\n new MemoryObservationStore(\n new Collections.RetainingRingBuffer<IMemoryObservationRecord>({ maxRecords })\n )\n );\n }\n\n /**\n * {@inheritDoc IMemoryObserver.observe}\n */\n public observe(record: IMemoryObservationRecord): Promise<Result<unknown>> {\n this._buffer.push(record);\n return Promise.resolve(succeed(record));\n }\n\n /**\n * Returns retained records, oldest-first, narrowed by the supplied criteria.\n * @param criteria - {@link IMemoryObservationQuery | AND-combined filter criteria}.\n * @returns The matching records, oldest-first.\n */\n public query(criteria?: IMemoryObservationQuery): ReadonlyArray<IMemoryObservationRecord> {\n return this._buffer.query({\n sinceSeq: criteria?.sinceSeq,\n limit: criteria?.limit,\n filter:\n criteria === undefined ? undefined : (record) => MemoryObservationStore._matches(record, criteria)\n });\n }\n\n /**\n * Clears all retained records. Does NOT reset\n * {@link MemoryObservationStore.lastSeq | lastSeq}, so a held `sinceSeq`\n * cursor never re-sees a sequence number.\n */\n public clear(): void {\n this._buffer.clear();\n }\n\n /**\n * Tests a record against the non-`seq`/`limit` criteria (those are applied by\n * the ring buffer itself).\n * @internal\n */\n private static _matches(record: IMemoryObservationRecord, criteria: IMemoryObservationQuery): boolean {\n if (criteria.since !== undefined && record.timestamp < criteria.since) {\n return false;\n }\n if (criteria.until !== undefined && record.timestamp > criteria.until) {\n return false;\n }\n if (criteria.scope !== undefined && record.scope !== criteria.scope) {\n return false;\n }\n if (criteria.kind !== undefined && record.kind !== criteria.kind) {\n return false;\n }\n if (criteria.phase !== undefined && record.phase !== criteria.phase) {\n return false;\n }\n if (criteria.outcome !== undefined && record.outcome !== criteria.outcome) {\n return false;\n }\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"memoryObservationStore.js","sourceRoot":"","sources":["../../../src/packlets/observe/memoryObservationStore.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAU,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAenE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,sBAAsB;IASjC;;;OAGG;IACH,YAAoB,MAAiE;QACnF,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,IAAW,OAAO;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,IAAW,IAAI;QACb,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,MAA4C;QAC/D,MAAM,UAAU,GAAuB,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,UAAU,CAAC;QAC1D,IAAI,UAAU,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,CAAC,EAAE,CAAC;YAClF,OAAO,IAAI,CAAC,sEAAsE,UAAU,GAAG,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,OAAO,CACZ,IAAI,sBAAsB,CACxB,IAAI,WAAW,CAAC,mBAAmB,CAA2B,EAAE,UAAU,EAAE,CAAC,CAC9E,CACF,CAAC;IACJ,CAAC;IAED;;OAEG;IACI,OAAO,CAAC,MAAgC;QAC7C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC1B,OAAO,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IAAI,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,CAAC;YACpE,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,QAAQ,CAAC,OAAO,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO,EAAE,CAAC;YAC1E,OAAO,KAAK,CAAC;QACf,CAAC;QACD,0EAA0E;QAC1E,yEAAyE;QACzE,2EAA2E;QAC3E,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,CAAC;YACpE,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Collections, Result, fail, succeed } from '@fgv/ts-utils';\nimport { IMemoryObservationQuery, IMemoryObservationRecord, IMemoryObserver } from './observer';\n\n/**\n * Construction options for {@link MemoryObservationStore.create}.\n * @public\n */\nexport interface IMemoryObservationStoreCreateParams {\n /**\n * Maximum number of observation records retained before the oldest is\n * overwritten. Defaults to `1000`. Must be a positive integer if supplied.\n */\n readonly maxRecords?: number;\n}\n\n/**\n * The default in-memory observation store: an {@link IMemoryObserver} that\n * retains the records it observes in a bounded ring and answers schema-aware\n * {@link MemoryObservationStore.query | queries} over them.\n *\n * @remarks\n * **Privacy posture — this store is most-permissive by design.** It retains\n * every field of every record verbatim, including any `provenance` and\n * `querySnapshot`. The library bakes in **no** redaction, retention, or\n * field-stripping policy — that is deployment policy, not library policy. A\n * deployment that must redact wraps this store with its own\n * {@link IMemoryObserver} that transforms records before forwarding, or\n * substitutes a different observer entirely. Size is the only bounded\n * dimension, via `maxRecords`.\n *\n * The store composes `RetainingRingBuffer` from `@fgv/ts-utils` (it does not\n * hand-roll a ring) and implements {@link IMemoryObserver} directly — `observe`\n * (the hook) and `query` (the read surface) live on the same class. Wire it via\n * {@link IFileTreeMemoryStoreCreateParams.observers}. `seq` and `timestamp` are\n * assigned by the firing authority (the store) before `observe`, so this store\n * never mints them.\n * @public\n */\nexport class MemoryObservationStore implements IMemoryObserver {\n /**\n * The bounded ring of observed records. The firing authority assigns each\n * record's `seq`, so the ring's monotonic-`seq` cursor contract is satisfied\n * by that authority's per-instance counter.\n * @internal\n */\n private readonly _buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>;\n\n /**\n * @param buffer - The pre-constructed backing ring buffer.\n * @internal\n */\n private constructor(buffer: Collections.RetainingRingBuffer<IMemoryObservationRecord>) {\n this._buffer = buffer;\n }\n\n /**\n * The highest `seq` observed so far. Hold this value and pass it as\n * `sinceSeq` to {@link MemoryObservationStore.query | query} to page only\n * records observed afterward. Stable across ring eviction and\n * {@link MemoryObservationStore.clear | clear}.\n */\n public get lastSeq(): number {\n return this._buffer.lastSeq;\n }\n\n /**\n * The number of records currently retained.\n */\n public get size(): number {\n return this._buffer.size;\n }\n\n /**\n * Family-convention factory.\n * @param params - {@link IMemoryObservationStoreCreateParams | Construction options}.\n * @returns On success, a new store. Fails if `maxRecords` is supplied and is\n * not a positive integer.\n */\n public static create(params?: IMemoryObservationStoreCreateParams): Result<MemoryObservationStore> {\n const maxRecords: number | undefined = params?.maxRecords;\n if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {\n return fail(`MemoryObservationStore: maxRecords must be a positive integer (got ${maxRecords})`);\n }\n return succeed(\n new MemoryObservationStore(\n new Collections.RetainingRingBuffer<IMemoryObservationRecord>({ maxRecords })\n )\n );\n }\n\n /**\n * {@inheritDoc IMemoryObserver.observe}\n */\n public observe(record: IMemoryObservationRecord): Promise<Result<unknown>> {\n this._buffer.push(record);\n return Promise.resolve(succeed(record));\n }\n\n /**\n * Returns retained records, oldest-first, narrowed by the supplied criteria.\n * @param criteria - {@link IMemoryObservationQuery | AND-combined filter criteria}.\n * @returns The matching records, oldest-first.\n */\n public query(criteria?: IMemoryObservationQuery): ReadonlyArray<IMemoryObservationRecord> {\n return this._buffer.query({\n sinceSeq: criteria?.sinceSeq,\n limit: criteria?.limit,\n filter:\n criteria === undefined ? undefined : (record) => MemoryObservationStore._matches(record, criteria)\n });\n }\n\n /**\n * Clears all retained records. Does NOT reset\n * {@link MemoryObservationStore.lastSeq | lastSeq}, so a held `sinceSeq`\n * cursor never re-sees a sequence number.\n */\n public clear(): void {\n this._buffer.clear();\n }\n\n /**\n * Tests a record against the non-`seq`/`limit` criteria (those are applied by\n * the ring buffer itself).\n * @internal\n */\n private static _matches(record: IMemoryObservationRecord, criteria: IMemoryObservationQuery): boolean {\n if (criteria.since !== undefined && record.timestamp < criteria.since) {\n return false;\n }\n if (criteria.until !== undefined && record.timestamp > criteria.until) {\n return false;\n }\n if (criteria.scope !== undefined && record.scope !== criteria.scope) {\n return false;\n }\n if (criteria.kind !== undefined && record.kind !== criteria.kind) {\n return false;\n }\n if (criteria.phase !== undefined && record.phase !== criteria.phase) {\n return false;\n }\n if (criteria.outcome !== undefined && record.outcome !== criteria.outcome) {\n return false;\n }\n // A record carrying no embed outcome never matches an `embed` criterion —\n // \"the question did not apply here\" is not the same answer as any of the\n // four, and matching it would put unwired writes in a coverage-gap report.\n if (criteria.embed !== undefined && record.embed !== criteria.embed) {\n return false;\n }\n return true;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observer.js","sourceRoot":"","sources":["../../../src/packlets/observe/observer.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { IProvenance, Kind, MemoryId, MemoryScopeKey } from '../types';\n\n/**\n * The store/retriever operation an observation record describes.\n *\n * @remarks\n * `'read'` / `'write'` / `'delete'` are fired post-op by\n * {@link FileTreeMemoryStore} (on `get` / `put` / `delete` respectively) when\n * observers are wired. `'retrieve'` is reserved for retriever-fired\n * observations; no B2 retriever fires one (a single seq authority per\n * observation store is the supported topology), so it never appears in B2 but\n * is part of the vocabulary so a future retriever-firing hook is additive.\n * @public\n */\nexport type MemoryObservationPhase = 'read' | 'write' | 'delete' | 'retrieve';\n\n/**\n * The outcome of the observed operation.\n * @public\n */\nexport type MemoryObservationOutcome = 'success' | 'failure';\n\n/**\n * A single audit record produced by an observed store (or retriever) operation.\n *\n * @remarks\n * `seq` and `timestamp` are assigned by the firing authority (the store) before\n * fan-out, so the same record carries the same `seq` across every observer it\n * lands in. `seq` is strictly increasing per authority, satisfying the\n * `RetainingRingBuffer` cursor contract that {@link MemoryObservationStore}\n * relies on.\n * @public\n */\nexport interface IMemoryObservationRecord {\n /**\n * Monotonic 1-based sequence number assigned by the firing authority, stable\n * across a store's ring eviction. The ordering / paging key.\n */\n readonly seq: number;\n /** Milliseconds since epoch when the firing authority produced the record. */\n readonly timestamp: number;\n /** Which operation this record describes. */\n readonly phase: MemoryObservationPhase;\n /** The scope the operation touched, when resolvable. */\n readonly scope?: MemoryScopeKey;\n /** The record id the operation touched, when resolvable. */\n readonly id?: MemoryId;\n /** The kind the operation targeted, when known. */\n readonly kind?: Kind;\n /** Whether the operation succeeded. */\n readonly outcome: MemoryObservationOutcome;\n /** Present on failure: the failure `Result`'s message. */\n readonly error?: string;\n /** Structured provenance of the write, when the operation carried one. */\n readonly provenance?: IProvenance;\n /**\n * For `'retrieve'` observations: an opaque snapshot of the query that drove\n * the retrieval. Carried verbatim; never interpreted by the store.\n */\n readonly querySnapshot?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Single-method async observer hook. The store fires `observe` once per public\n * `get` / `put` / `delete` call when observers are wired.\n *\n * @remarks\n * Observer errors never affect the store operation — the store swallows a\n * failed `Result` or a thrown / rejected `observe`, logging it to the injected\n * diagnostic logger at `warn`.\n * @public\n */\nexport interface IMemoryObserver {\n /**\n * When `true`, the store dispatches `observe` without awaiting it, so a slow\n * remote observer (SIEM, network sink) does not extend the store operation's\n * latency. Defaults to `false` (awaited), which is correct for the cheap\n * in-memory default {@link MemoryObservationStore}. Errors are swallowed\n * either way.\n */\n readonly fireAndForget?: boolean;\n /**\n * Receives a fully-formed observation record.\n * @param record - The observation record.\n * @returns A `Result` whose failure is swallowed (logged to the store's\n * diagnostic logger). A rejected promise is likewise swallowed.\n */\n observe(record: IMemoryObservationRecord): Promise<Result<unknown>>;\n}\n\n/**\n * Query criteria for {@link MemoryObservationStore.query}. All supplied criteria\n * are AND-combined.\n * @public\n */\nexport interface IMemoryObservationQuery {\n /** Only records with `seq > sinceSeq` (incremental paging cursor). */\n readonly sinceSeq?: number;\n /** Return at most this many records — the most-recent N, still oldest-first. */\n readonly limit?: number;\n /** Only records with `timestamp >= since`. */\n readonly since?: number;\n /** Only records with `timestamp <= until`. */\n readonly until?: number;\n /** Only records that touched this scope. */\n readonly scope?: MemoryScopeKey;\n /** Only records that targeted this kind. */\n readonly kind?: Kind;\n /** Only records of this phase. */\n readonly phase?: MemoryObservationPhase;\n /** Only records with this outcome. */\n readonly outcome?: MemoryObservationOutcome;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"observer.js","sourceRoot":"","sources":["../../../src/packlets/observe/observer.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { IProvenance, Kind, MemoryId, MemoryScopeKey } from '../types';\n\n/**\n * The store/retriever operation an observation record describes.\n *\n * @remarks\n * `'read'` / `'write'` / `'delete'` are fired post-op by\n * {@link FileTreeMemoryStore} (on `get` / `put` / `delete` respectively) when\n * observers are wired. `'retrieve'` is reserved for retriever-fired\n * observations; no B2 retriever fires one (a single seq authority per\n * observation store is the supported topology), so it never appears in B2 but\n * is part of the vocabulary so a future retriever-firing hook is additive.\n * @public\n */\nexport type MemoryObservationPhase = 'read' | 'write' | 'delete' | 'retrieve';\n\n/**\n * The outcome of the observed operation.\n * @public\n */\nexport type MemoryObservationOutcome = 'success' | 'failure';\n\n/**\n * What the record-granular vector index did about a written record.\n *\n * @remarks\n * This exists because **`embeddingRef` absence is three-ways ambiguous**: a\n * record with no reference may have been declined, excluded, or genuinely\n * failed to embed, and the `put`'s own `outcome` cannot tell you which — it is\n * `'success'` in all three, because embed-on-write is best-effort by design and\n * never fails a durable write. Deriving index coverage from the absent field\n * alone therefore cannot distinguish a policy decision from an outage.\n *\n * - `'embedded'` — embedded and added; the record carries an `embeddingRef`.\n * - `'declined'` — the {@link MemoryEmbedder} resolved `undefined`: deliberately\n * not embedded. Not a fault.\n * - `'excluded'` — the record's kind is outside the store's `embedKinds`\n * declaration, so the embedder was never called. Also not a fault, and the\n * cheaper of the two.\n * - `'failed'` — the embedder returned a `Failure` (or threw), **or** the index\n * `add` did. Both are faults, and what they leave behind depends on whether\n * the record had been embedded before: a **first** write ends up with no\n * `embeddingRef` and nothing in the index, while an **update** keeps the\n * reference and vector it already had — so the index goes on answering on the\n * record's **previous** content until a `rebuild` reconciles it. Stale, not\n * absent. The store's diagnostic logger names which fault it was, because the\n * remediation differs (an embedder outage versus an index outage) while the\n * coverage answer — \"this record needs a re-embed\" — does not.\n *\n * Absent on a write observation means **no outcome is being reported**, which\n * covers three cases:\n *\n * 1. no vector index / embedder is wired, so there is no index for the record to\n * be absent from;\n * 2. the `put` was a dedup no-op, which attempted nothing;\n * 3. the `put` **failed** (`outcome: 'failure'`). An embed step may well have run\n * before the failure — a record can even have been added to the index and then\n * lost its durable write, leaving an orphan vector that a later `rebuild`\n * reconciles. That is deliberately not reported here: the field answers\n * \"is this *stored* record in the index?\", and on a failed write there is no\n * stored record for it to be a statement about.\n *\n * So `embed` is a property of successful writes. Never present on `'read'` /\n * `'delete'` / `'retrieve'`.\n *\n * Record-granular only. The fragment path is independent and reports nothing\n * here — a record may be fragment-embedded while its record-level outcome is\n * `'excluded'`.\n * @public\n */\nexport type MemoryEmbedOutcome = 'embedded' | 'declined' | 'excluded' | 'failed';\n\n/**\n * A single audit record produced by an observed store (or retriever) operation.\n *\n * @remarks\n * `seq` and `timestamp` are assigned by the firing authority (the store) before\n * fan-out, so the same record carries the same `seq` across every observer it\n * lands in. `seq` is strictly increasing per authority, satisfying the\n * `RetainingRingBuffer` cursor contract that {@link MemoryObservationStore}\n * relies on.\n * @public\n */\nexport interface IMemoryObservationRecord {\n /**\n * Monotonic 1-based sequence number assigned by the firing authority, stable\n * across a store's ring eviction. The ordering / paging key.\n */\n readonly seq: number;\n /** Milliseconds since epoch when the firing authority produced the record. */\n readonly timestamp: number;\n /** Which operation this record describes. */\n readonly phase: MemoryObservationPhase;\n /** The scope the operation touched, when resolvable. */\n readonly scope?: MemoryScopeKey;\n /** The record id the operation touched, when resolvable. */\n readonly id?: MemoryId;\n /** The kind the operation targeted, when known. */\n readonly kind?: Kind;\n /** Whether the operation succeeded. */\n readonly outcome: MemoryObservationOutcome;\n /** Present on failure: the failure `Result`'s message. */\n readonly error?: string;\n /** Structured provenance of the write, when the operation carried one. */\n readonly provenance?: IProvenance;\n /**\n * For `'write'` observations: what the record-granular vector index did about\n * this record. Absent when the question does not apply — see\n * {@link MemoryEmbedOutcome}.\n */\n readonly embed?: MemoryEmbedOutcome;\n /**\n * For `'retrieve'` observations: an opaque snapshot of the query that drove\n * the retrieval. Carried verbatim; never interpreted by the store.\n */\n readonly querySnapshot?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Single-method async observer hook. The store fires `observe` once per public\n * `get` / `put` / `delete` call when observers are wired.\n *\n * @remarks\n * Observer errors never affect the store operation — the store swallows a\n * failed `Result` or a thrown / rejected `observe`, logging it to the injected\n * diagnostic logger at `warn`.\n * @public\n */\nexport interface IMemoryObserver {\n /**\n * When `true`, the store dispatches `observe` without awaiting it, so a slow\n * remote observer (SIEM, network sink) does not extend the store operation's\n * latency. Defaults to `false` (awaited), which is correct for the cheap\n * in-memory default {@link MemoryObservationStore}. Errors are swallowed\n * either way.\n */\n readonly fireAndForget?: boolean;\n /**\n * Receives a fully-formed observation record.\n * @param record - The observation record.\n * @returns A `Result` whose failure is swallowed (logged to the store's\n * diagnostic logger). A rejected promise is likewise swallowed.\n */\n observe(record: IMemoryObservationRecord): Promise<Result<unknown>>;\n}\n\n/**\n * Query criteria for {@link MemoryObservationStore.query}. All supplied criteria\n * are AND-combined.\n * @public\n */\nexport interface IMemoryObservationQuery {\n /** Only records with `seq > sinceSeq` (incremental paging cursor). */\n readonly sinceSeq?: number;\n /** Return at most this many records — the most-recent N, still oldest-first. */\n readonly limit?: number;\n /** Only records with `timestamp >= since`. */\n readonly since?: number;\n /** Only records with `timestamp <= until`. */\n readonly until?: number;\n /** Only records that touched this scope. */\n readonly scope?: MemoryScopeKey;\n /** Only records that targeted this kind. */\n readonly kind?: Kind;\n /** Only records of this phase. */\n readonly phase?: MemoryObservationPhase;\n /** Only records with this outcome. */\n readonly outcome?: MemoryObservationOutcome;\n /**\n * Only `'write'` records with this embed outcome. Records carrying no embed\n * outcome never match, so `embed: 'failed'` answers \"which writes left the\n * index short?\" without a full scan of every record's `embeddingRef`.\n */\n readonly embed?: MemoryEmbedOutcome;\n}\n"]}
|
|
@@ -37,7 +37,7 @@ export const LINK_TRAVERSAL_NO_SEED_MESSAGE = 'link traversal requires a seed id
|
|
|
37
37
|
* is the exact, collision-free cycle key — no structural hashing (e.g.
|
|
38
38
|
* `Crc32Normalizer`) is needed. A self-loop or any multi-hop cycle terminates
|
|
39
39
|
* because a revisited node is never re-expanded.
|
|
40
|
-
* - **Post-filter.** The scope / kind / tag / predicate axes of the query are
|
|
40
|
+
* - **Post-filter.** The scope / kind / tag / provenance-source / predicate axes of the query are
|
|
41
41
|
* applied to the reached records (the link axes are the traversal itself).
|
|
42
42
|
* @public
|
|
43
43
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkTraversalRetriever.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/linkTraversalRetriever.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA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AI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;gBAC/C,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,kGAAkG;IAC1F,QAAQ,CAAC,IAAiB;QAChC,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\nimport { IEdgeTarget, IMemoryRecord, edgeTargetKey } from '../types';\nimport { IIndexedMemoryRecord, IMemoryIndex } from '../index';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n guardRetrieverCapabilities,\n indexedRecordMatchesQuery,\n limitRecords,\n orderingCompare\n} from './retriever';\n\n/** The capabilities a link-traversal retriever exposes (link traversal only). */\nconst LINK_TRAVERSAL_CAPABILITIES: IMemoryRetrieverCapabilities = {\n supportsSemanticRecall: false,\n supportsTemporalQuery: false,\n supportsLinkTraversal: true\n};\n\n/** Default BFS hop count when `query.hops` is not supplied. */\nconst DEFAULT_HOPS: number = 1;\n\n/**\n * The loud-degradation message returned when a link-traversal query supplies no\n * seed (`linkedFrom` / `linkedTo`).\n * @public\n */\nexport const LINK_TRAVERSAL_NO_SEED_MESSAGE: string =\n 'link traversal requires a seed id (linkedFrom or linkedTo)';\n\n/**\n * Breadth-first link-traversal retriever. From a scope-qualified\n * {@link IEdgeTarget} seed it walks the link graph up to `query.hops` levels and\n * returns the records reached (excluding the seed), recency-ordered and limited.\n *\n * @remarks\n * - **Direction.** `linkedFrom` walks OUTBOUND edges (each record's\n * `envelope.links[].target`); `linkedTo` walks INBOUND edges (the index's\n * `backlinks`). Exactly one is the seed; `linkedFrom` wins if both are set.\n * - **Scope-qualified nodes.** Every graph node is an {@link IEdgeTarget}\n * `(scope, id)` pair, so following an edge to `turn-3` reaches ONLY the record\n * in the edge's own scope — never a same-stem record in another scope.\n * - **Bound + cycle safety.** Traversal is bounded by `hops` (default `1` — a\n * single hop) and a visited-set guard. Nodes are canonicalized to their\n * `(scope, id)` string via {@link edgeTargetKey}, so a `Set<string>` visited-set\n * is the exact, collision-free cycle key — no structural hashing (e.g.\n * `Crc32Normalizer`) is needed. A self-loop or any multi-hop cycle terminates\n * because a revisited node is never re-expanded.\n * - **Post-filter.** The scope / kind / tag / predicate axes of the query are\n * applied to the reached records (the link axes are the traversal itself).\n * @public\n */\nexport class LinkTraversalRetriever implements IMemoryRetriever {\n private readonly _index: IMemoryIndex;\n\n private constructor(index: IMemoryIndex) {\n this._index = index;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<LinkTraversalRetriever> {\n return succeed(new LinkTraversalRetriever(index));\n }\n\n /** {@inheritDoc IMemoryRetriever.capabilities} */\n public get capabilities(): IMemoryRetrieverCapabilities {\n return LINK_TRAVERSAL_CAPABILITIES;\n }\n\n /** {@inheritDoc IMemoryRetriever.retrieve} */\n public retrieve(query: IMemoryQuery): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n return Promise.resolve(\n guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => this._traverse(query))\n );\n }\n\n /** Run the bounded, cycle-safe BFS and post-filter the reached records. */\n private _traverse(query: IMemoryQuery): Result<ReadonlyArray<IMemoryRecord<unknown>>> {\n const outbound: boolean = query.linkedFrom !== undefined;\n const seed: IEdgeTarget | undefined = query.linkedFrom ?? query.linkedTo;\n if (seed === undefined) {\n return fail(LINK_TRAVERSAL_NO_SEED_MESSAGE);\n }\n const hops: number = query.hops ?? DEFAULT_HOPS;\n const byKey: ReadonlyMap<string, IIndexedMemoryRecord> = this._indexByKey();\n\n // The visited-set IS the cycle guard: nodes are canonicalized to their\n // `(scope, id)` string, so set membership is an exact identity check. The\n // seed is pre-marked so it is never re-added.\n const visited: Set<string> = new Set<string>([edgeTargetKey(seed)]);\n const reached: IEdgeTarget[] = [];\n let frontier: IEdgeTarget[] = [seed];\n for (let hop = 0; hop < hops && frontier.length > 0; hop++) {\n const next: IEdgeTarget[] = [];\n for (const node of frontier) {\n for (const neighbor of outbound ? this._outbound(node, byKey) : this._inbound(node)) {\n const neighborKey: string = edgeTargetKey(neighbor);\n if (!visited.has(neighborKey)) {\n visited.add(neighborKey);\n reached.push(neighbor);\n next.push(neighbor);\n }\n }\n }\n frontier = next;\n }\n\n const entries: IIndexedMemoryRecord[] = [];\n for (const node of reached) {\n const match: IIndexedMemoryRecord | undefined = byKey.get(edgeTargetKey(node));\n if (match !== undefined) {\n entries.push(match);\n }\n }\n const ordered: IMemoryRecord<unknown>[] = entries\n .filter((entry) => indexedRecordMatchesQuery(entry, query))\n .map((entry) => entry.record)\n .sort(orderingCompare(query.orderBy));\n return succeed(limitRecords(ordered, query.limit, query.offset));\n }\n\n /**\n * Group the index's entries by their scope-qualified {@link edgeTargetKey}\n * `(scope, id)` composite. Each composite is the index's primary key, so it maps\n * to exactly one entry — two records that reuse a filename stem across scopes\n * (e.g. `turn-0` in two conversations) get distinct keys and never collide.\n */\n private _indexByKey(): ReadonlyMap<string, IIndexedMemoryRecord> {\n const byKey: Map<string, IIndexedMemoryRecord> = new Map<string, IIndexedMemoryRecord>();\n for (const entry of this._index.entries()) {\n byKey.set(edgeTargetKey({ scope: entry.scope, id: entry.record.envelope.id }), entry);\n }\n return byKey;\n }\n\n /** Outbound neighbors: the scope-qualified targets of every edge on the record at `node`. */\n private _outbound(node: IEdgeTarget, byKey: ReadonlyMap<string, IIndexedMemoryRecord>): IEdgeTarget[] {\n const targets: IEdgeTarget[] = [];\n const match: IIndexedMemoryRecord | undefined = byKey.get(edgeTargetKey(node));\n if (match !== undefined) {\n for (const edge of match.record.envelope.links) {\n targets.push(edge.target);\n }\n }\n return targets;\n }\n\n /** Inbound neighbors: the scope-qualified sources whose edges point AT `node` (the backlinks). */\n private _inbound(node: IEdgeTarget): ReadonlyArray<IEdgeTarget> {\n return this._index.backlinks(node);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"linkTraversalRetriever.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/linkTraversalRetriever.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAA8B,aAAa,EAAE,MAAM,UAAU,CAAC;AAErE,OAAO,EAIL,0BAA0B,EAC1B,yBAAyB,EACzB,YAAY,EACZ,eAAe,EAChB,MAAM,aAAa,CAAC;AAErB,iFAAiF;AACjF,MAAM,2BAA2B,GAAiC;IAChE,sBAAsB,EAAE,KAAK;IAC7B,qBAAqB,EAAE,KAAK;IAC5B,qBAAqB,EAAE,IAAI;CAC5B,CAAC;AAEF,+DAA+D;AAC/D,MAAM,YAAY,GAAW,CAAC,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,8BAA8B,GACzC,4DAA4D,CAAC;AAE/D;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,sBAAsB;IAGjC,YAAoB,KAAmB;QACrC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,iCAAiC;IAC1B,MAAM,CAAC,MAAM,CAAC,KAAmB;QACtC,OAAO,OAAO,CAAC,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC;IACpD,CAAC;IAED,kDAAkD;IAClD,IAAW,YAAY;QACrB,OAAO,2BAA2B,CAAC;IACrC,CAAC;IAED,8CAA8C;IACvC,QAAQ,CAAC,KAAmB;QACjC,OAAO,OAAO,CAAC,OAAO,CACpB,0BAA0B,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAC5F,CAAC;IACJ,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AAiB,EAAE,KAAgD;QACnF,MAAM,OAAO,GAAkB,EAAE,CAAC;QAClC,MAAM,KAAK,GAAqC,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/E,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;gBAC/C,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,kGAAkG;IAC1F,QAAQ,CAAC,IAAiB;QAChC,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\nimport { IEdgeTarget, IMemoryRecord, edgeTargetKey } from '../types';\nimport { IIndexedMemoryRecord, IMemoryIndex } from '../index';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n guardRetrieverCapabilities,\n indexedRecordMatchesQuery,\n limitRecords,\n orderingCompare\n} from './retriever';\n\n/** The capabilities a link-traversal retriever exposes (link traversal only). */\nconst LINK_TRAVERSAL_CAPABILITIES: IMemoryRetrieverCapabilities = {\n supportsSemanticRecall: false,\n supportsTemporalQuery: false,\n supportsLinkTraversal: true\n};\n\n/** Default BFS hop count when `query.hops` is not supplied. */\nconst DEFAULT_HOPS: number = 1;\n\n/**\n * The loud-degradation message returned when a link-traversal query supplies no\n * seed (`linkedFrom` / `linkedTo`).\n * @public\n */\nexport const LINK_TRAVERSAL_NO_SEED_MESSAGE: string =\n 'link traversal requires a seed id (linkedFrom or linkedTo)';\n\n/**\n * Breadth-first link-traversal retriever. From a scope-qualified\n * {@link IEdgeTarget} seed it walks the link graph up to `query.hops` levels and\n * returns the records reached (excluding the seed), recency-ordered and limited.\n *\n * @remarks\n * - **Direction.** `linkedFrom` walks OUTBOUND edges (each record's\n * `envelope.links[].target`); `linkedTo` walks INBOUND edges (the index's\n * `backlinks`). Exactly one is the seed; `linkedFrom` wins if both are set.\n * - **Scope-qualified nodes.** Every graph node is an {@link IEdgeTarget}\n * `(scope, id)` pair, so following an edge to `turn-3` reaches ONLY the record\n * in the edge's own scope — never a same-stem record in another scope.\n * - **Bound + cycle safety.** Traversal is bounded by `hops` (default `1` — a\n * single hop) and a visited-set guard. Nodes are canonicalized to their\n * `(scope, id)` string via {@link edgeTargetKey}, so a `Set<string>` visited-set\n * is the exact, collision-free cycle key — no structural hashing (e.g.\n * `Crc32Normalizer`) is needed. A self-loop or any multi-hop cycle terminates\n * because a revisited node is never re-expanded.\n * - **Post-filter.** The scope / kind / tag / provenance-source / predicate axes of the query are\n * applied to the reached records (the link axes are the traversal itself).\n * @public\n */\nexport class LinkTraversalRetriever implements IMemoryRetriever {\n private readonly _index: IMemoryIndex;\n\n private constructor(index: IMemoryIndex) {\n this._index = index;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<LinkTraversalRetriever> {\n return succeed(new LinkTraversalRetriever(index));\n }\n\n /** {@inheritDoc IMemoryRetriever.capabilities} */\n public get capabilities(): IMemoryRetrieverCapabilities {\n return LINK_TRAVERSAL_CAPABILITIES;\n }\n\n /** {@inheritDoc IMemoryRetriever.retrieve} */\n public retrieve(query: IMemoryQuery): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n return Promise.resolve(\n guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => this._traverse(query))\n );\n }\n\n /** Run the bounded, cycle-safe BFS and post-filter the reached records. */\n private _traverse(query: IMemoryQuery): Result<ReadonlyArray<IMemoryRecord<unknown>>> {\n const outbound: boolean = query.linkedFrom !== undefined;\n const seed: IEdgeTarget | undefined = query.linkedFrom ?? query.linkedTo;\n if (seed === undefined) {\n return fail(LINK_TRAVERSAL_NO_SEED_MESSAGE);\n }\n const hops: number = query.hops ?? DEFAULT_HOPS;\n const byKey: ReadonlyMap<string, IIndexedMemoryRecord> = this._indexByKey();\n\n // The visited-set IS the cycle guard: nodes are canonicalized to their\n // `(scope, id)` string, so set membership is an exact identity check. The\n // seed is pre-marked so it is never re-added.\n const visited: Set<string> = new Set<string>([edgeTargetKey(seed)]);\n const reached: IEdgeTarget[] = [];\n let frontier: IEdgeTarget[] = [seed];\n for (let hop = 0; hop < hops && frontier.length > 0; hop++) {\n const next: IEdgeTarget[] = [];\n for (const node of frontier) {\n for (const neighbor of outbound ? this._outbound(node, byKey) : this._inbound(node)) {\n const neighborKey: string = edgeTargetKey(neighbor);\n if (!visited.has(neighborKey)) {\n visited.add(neighborKey);\n reached.push(neighbor);\n next.push(neighbor);\n }\n }\n }\n frontier = next;\n }\n\n const entries: IIndexedMemoryRecord[] = [];\n for (const node of reached) {\n const match: IIndexedMemoryRecord | undefined = byKey.get(edgeTargetKey(node));\n if (match !== undefined) {\n entries.push(match);\n }\n }\n const ordered: IMemoryRecord<unknown>[] = entries\n .filter((entry) => indexedRecordMatchesQuery(entry, query))\n .map((entry) => entry.record)\n .sort(orderingCompare(query.orderBy));\n return succeed(limitRecords(ordered, query.limit, query.offset));\n }\n\n /**\n * Group the index's entries by their scope-qualified {@link edgeTargetKey}\n * `(scope, id)` composite. Each composite is the index's primary key, so it maps\n * to exactly one entry — two records that reuse a filename stem across scopes\n * (e.g. `turn-0` in two conversations) get distinct keys and never collide.\n */\n private _indexByKey(): ReadonlyMap<string, IIndexedMemoryRecord> {\n const byKey: Map<string, IIndexedMemoryRecord> = new Map<string, IIndexedMemoryRecord>();\n for (const entry of this._index.entries()) {\n byKey.set(edgeTargetKey({ scope: entry.scope, id: entry.record.envelope.id }), entry);\n }\n return byKey;\n }\n\n /** Outbound neighbors: the scope-qualified targets of every edge on the record at `node`. */\n private _outbound(node: IEdgeTarget, byKey: ReadonlyMap<string, IIndexedMemoryRecord>): IEdgeTarget[] {\n const targets: IEdgeTarget[] = [];\n const match: IIndexedMemoryRecord | undefined = byKey.get(edgeTargetKey(node));\n if (match !== undefined) {\n for (const edge of match.record.envelope.links) {\n targets.push(edge.target);\n }\n }\n return targets;\n }\n\n /** Inbound neighbors: the scope-qualified sources whose edges point AT `node` (the backlinks). */\n private _inbound(node: IEdgeTarget): ReadonlyArray<IEdgeTarget> {\n return this._index.backlinks(node);\n }\n}\n"]}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { succeed } from '@fgv/ts-utils';
|
|
6
6
|
import { NON_SEMANTIC_CAPABILITIES, guardRetrieverCapabilities, limitRecords, orderingCompare, selectByQuery } from './retriever';
|
|
7
7
|
/**
|
|
8
|
-
* Returns records matching the query's scope / kind / tag / predicate filters,
|
|
8
|
+
* Returns records matching the query's scope / kind / tag / provenance-source / predicate filters,
|
|
9
9
|
* ordered most-recently-updated first. The universal v1 retriever — an empty
|
|
10
10
|
* query returns the whole vault in recency order.
|
|
11
11
|
* @public
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recencyRetriever.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/recencyRetriever.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAIL,yBAAyB,EACzB,0BAA0B,EAC1B,YAAY,EACZ,eAAe,EACf,aAAa,EACd,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AACH,MAAM,OAAO,gBAAgB;IAG3B,YAAoB,KAAmB;QACrC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,kDAAkD;IAClD,IAAW,YAAY;QACrB,OAAO,yBAAyB,CAAC;IACnC,CAAC;IAED,iCAAiC;IAC1B,MAAM,CAAC,MAAM,CAAC,KAAmB;QACtC,OAAO,OAAO,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,8CAA8C;IACvC,QAAQ,CAAC,KAAmB;QACjC,OAAO,OAAO,CAAC,OAAO,CACpB,0BAA0B,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE;YAClE,MAAM,OAAO,GAA6B,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC,IAAI,CACxF,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/B,CAAC;YACF,OAAO,OAAO,CAAC,YAAY,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;QACnE,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, succeed } from '@fgv/ts-utils';\nimport { IMemoryRecord } from '../types';\nimport { IMemoryIndex } from '../index';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n NON_SEMANTIC_CAPABILITIES,\n guardRetrieverCapabilities,\n limitRecords,\n orderingCompare,\n selectByQuery\n} from './retriever';\n\n/**\n * Returns records matching the query's scope / kind / tag / predicate filters,\n * ordered most-recently-updated first. The universal v1 retriever — an empty\n * query returns the whole vault in recency order.\n * @public\n */\nexport class RecencyRetriever implements IMemoryRetriever {\n private readonly _index: IMemoryIndex;\n\n private constructor(index: IMemoryIndex) {\n this._index = index;\n }\n\n /** {@inheritDoc IMemoryRetriever.capabilities} */\n public get capabilities(): IMemoryRetrieverCapabilities {\n return NON_SEMANTIC_CAPABILITIES;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<RecencyRetriever> {\n return succeed(new RecencyRetriever(index));\n }\n\n /** {@inheritDoc IMemoryRetriever.retrieve} */\n public retrieve(query: IMemoryQuery): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n return Promise.resolve(\n guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => {\n const ordered: IMemoryRecord<unknown>[] = selectByQuery(this._index.entries(), query).sort(\n orderingCompare(query.orderBy)\n );\n return succeed(limitRecords(ordered, query.limit, query.offset));\n })\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recencyRetriever.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/recencyRetriever.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAIL,yBAAyB,EACzB,0BAA0B,EAC1B,YAAY,EACZ,eAAe,EACf,aAAa,EACd,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AACH,MAAM,OAAO,gBAAgB;IAG3B,YAAoB,KAAmB;QACrC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,kDAAkD;IAClD,IAAW,YAAY;QACrB,OAAO,yBAAyB,CAAC;IACnC,CAAC;IAED,iCAAiC;IAC1B,MAAM,CAAC,MAAM,CAAC,KAAmB;QACtC,OAAO,OAAO,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,8CAA8C;IACvC,QAAQ,CAAC,KAAmB;QACjC,OAAO,OAAO,CAAC,OAAO,CACpB,0BAA0B,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE;YAClE,MAAM,OAAO,GAA6B,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC,IAAI,CACxF,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,CAC/B,CAAC;YACF,OAAO,OAAO,CAAC,YAAY,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;QACnE,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, succeed } from '@fgv/ts-utils';\nimport { IMemoryRecord } from '../types';\nimport { IMemoryIndex } from '../index';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n NON_SEMANTIC_CAPABILITIES,\n guardRetrieverCapabilities,\n limitRecords,\n orderingCompare,\n selectByQuery\n} from './retriever';\n\n/**\n * Returns records matching the query's scope / kind / tag / provenance-source / predicate filters,\n * ordered most-recently-updated first. The universal v1 retriever — an empty\n * query returns the whole vault in recency order.\n * @public\n */\nexport class RecencyRetriever implements IMemoryRetriever {\n private readonly _index: IMemoryIndex;\n\n private constructor(index: IMemoryIndex) {\n this._index = index;\n }\n\n /** {@inheritDoc IMemoryRetriever.capabilities} */\n public get capabilities(): IMemoryRetrieverCapabilities {\n return NON_SEMANTIC_CAPABILITIES;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<RecencyRetriever> {\n return succeed(new RecencyRetriever(index));\n }\n\n /** {@inheritDoc IMemoryRetriever.retrieve} */\n public retrieve(query: IMemoryQuery): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n return Promise.resolve(\n guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => {\n const ordered: IMemoryRecord<unknown>[] = selectByQuery(this._index.entries(), query).sort(\n orderingCompare(query.orderBy)\n );\n return succeed(limitRecords(ordered, query.limit, query.offset));\n })\n );\n }\n}\n"]}
|
|
@@ -93,9 +93,10 @@ export function orderingCompare(orderBy) {
|
|
|
93
93
|
return orderBy === 'rank' ? rankCompare : recencyCompare;
|
|
94
94
|
}
|
|
95
95
|
/**
|
|
96
|
-
* Whether an indexed entry satisfies a query's scope / kind / tag /
|
|
97
|
-
* pre-filter (the axes shared by every v1
|
|
98
|
-
* link axes are NOT applied here — those
|
|
96
|
+
* Whether an indexed entry satisfies a query's scope / kind / tag /
|
|
97
|
+
* provenance-source / predicate pre-filter (the axes shared by every v1
|
|
98
|
+
* retriever). The `semantic` / `asOf` / link axes are NOT applied here — those
|
|
99
|
+
* are each retriever's own concern.
|
|
99
100
|
* @public
|
|
100
101
|
*/
|
|
101
102
|
export function indexedRecordMatchesQuery(entry, query) {
|
|
@@ -111,14 +112,19 @@ export function indexedRecordMatchesQuery(entry, query) {
|
|
|
111
112
|
if (query.tag !== undefined && !entry.record.envelope.tags.includes(query.tag)) {
|
|
112
113
|
return false;
|
|
113
114
|
}
|
|
115
|
+
if (query.provenanceSource !== undefined &&
|
|
116
|
+
entry.record.envelope.provenance.source !== query.provenanceSource) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
114
119
|
if (query.filter !== undefined && !query.filter(entry.record)) {
|
|
115
120
|
return false;
|
|
116
121
|
}
|
|
117
122
|
return true;
|
|
118
123
|
}
|
|
119
124
|
/**
|
|
120
|
-
* Apply the shared scope / kind / tag / predicate pre-filter
|
|
121
|
-
* entries, returning the surviving records (unordered,
|
|
125
|
+
* Apply the shared scope / kind / tag / provenance-source / predicate pre-filter
|
|
126
|
+
* to a set of indexed entries, returning the surviving records (unordered,
|
|
127
|
+
* unlimited).
|
|
122
128
|
* @public
|
|
123
129
|
*/
|
|
124
130
|
export function selectByQuery(entries, query) {
|