@fgv/ts-agent-memory 5.1.0-36 → 5.1.0-39
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/.rush/temp/{f6a88bfdd66517ccb98c2c7ae1be6e6fe9e15d38.tar.log → b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log} +116 -2
- package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +4 -4
- package/.rush/temp/operation/build/all.log +4 -4
- package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
- package/.rush/temp/operation/build/state.json +1 -1
- package/.rush/temp/shrinkwrap-deps.json +222 -221
- package/config/jest.config.json +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/packlets/ingest/cycleGuard.js +111 -0
- package/dist/packlets/ingest/cycleGuard.js.map +1 -0
- package/dist/packlets/ingest/hostStages.js +6 -0
- package/dist/packlets/ingest/hostStages.js.map +1 -0
- package/dist/packlets/ingest/index.js +9 -0
- package/dist/packlets/ingest/index.js.map +1 -0
- package/dist/packlets/ingest/model.js +6 -0
- package/dist/packlets/ingest/model.js.map +1 -0
- package/dist/packlets/ingest/orchestrator.js +438 -0
- package/dist/packlets/ingest/orchestrator.js.map +1 -0
- package/dist/packlets/retrieve/index.js +1 -0
- package/dist/packlets/retrieve/index.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +172 -0
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -0
- package/dist/packlets/store/fileTreeMemoryStore.js +323 -41
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/tools/index.js +6 -0
- package/dist/packlets/tools/index.js.map +1 -0
- package/dist/packlets/tools/memoryTools.js +337 -0
- package/dist/packlets/tools/memoryTools.js.map +1 -0
- package/dist/packlets/types/identityCodec.js +115 -0
- package/dist/packlets/types/identityCodec.js.map +1 -1
- package/dist/packlets/types/index.js +1 -0
- package/dist/packlets/types/index.js.map +1 -1
- package/dist/packlets/types/temporal.js +85 -0
- package/dist/packlets/types/temporal.js.map +1 -0
- package/dist/packlets/types/writePolicy.js +96 -0
- package/dist/packlets/types/writePolicy.js.map +1 -1
- package/dist/test/unit/converters/antagonistRoundTrip.test.js +95 -0
- package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +273 -0
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
- package/dist/test/unit/ingest/cycleGuard.test.js +54 -0
- package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -0
- package/dist/test/unit/ingest/orchestrator.test.js +913 -0
- package/dist/test/unit/ingest/orchestrator.test.js.map +1 -0
- package/dist/test/unit/retrieve/temporalRetrievers.test.js +182 -0
- package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js +120 -0
- package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
- package/dist/test/unit/store/fileTreeMemoryStore.test.js +74 -7
- package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
- package/dist/test/unit/store/temporalStore.test.js +398 -0
- package/dist/test/unit/store/temporalStore.test.js.map +1 -0
- package/dist/test/unit/tools/memoryTools.test.js +572 -0
- package/dist/test/unit/tools/memoryTools.test.js.map +1 -0
- package/dist/test/unit/types/temporalCodec.test.js +203 -0
- package/dist/test/unit/types/temporalCodec.test.js.map +1 -0
- package/dist/test/unit/types/temporalPolicy.test.js +62 -0
- package/dist/test/unit/types/temporalPolicy.test.js.map +1 -0
- package/dist/ts-agent-memory.d.ts +1042 -10
- package/dist/tsdoc-metadata.json +1 -1
- package/etc/ts-agent-memory.api.md +284 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +2 -0
- package/lib/index.js.map +1 -1
- package/lib/packlets/ingest/cycleGuard.d.ts +41 -0
- package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -0
- package/lib/packlets/ingest/cycleGuard.js +115 -0
- package/lib/packlets/ingest/cycleGuard.js.map +1 -0
- package/lib/packlets/ingest/hostStages.d.ts +88 -0
- package/lib/packlets/ingest/hostStages.d.ts.map +1 -0
- package/lib/packlets/ingest/hostStages.js +7 -0
- package/lib/packlets/ingest/hostStages.js.map +1 -0
- package/lib/packlets/ingest/index.d.ts +5 -0
- package/lib/packlets/ingest/index.d.ts.map +1 -0
- package/lib/packlets/ingest/index.js +25 -0
- package/lib/packlets/ingest/index.js.map +1 -0
- package/lib/packlets/ingest/model.d.ts +177 -0
- package/lib/packlets/ingest/model.d.ts.map +1 -0
- package/lib/packlets/ingest/model.js +7 -0
- package/lib/packlets/ingest/model.js.map +1 -0
- package/lib/packlets/ingest/orchestrator.d.ts +206 -0
- package/lib/packlets/ingest/orchestrator.d.ts.map +1 -0
- package/lib/packlets/ingest/orchestrator.js +442 -0
- package/lib/packlets/ingest/orchestrator.js.map +1 -0
- package/lib/packlets/retrieve/index.d.ts +1 -0
- package/lib/packlets/retrieve/index.d.ts.map +1 -1
- package/lib/packlets/retrieve/index.js +1 -0
- package/lib/packlets/retrieve/index.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.d.ts +78 -0
- package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -0
- package/lib/packlets/retrieve/temporalRetrievers.js +178 -0
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -0
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +118 -9
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +322 -40
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/tools/index.d.ts +2 -0
- package/lib/packlets/tools/index.d.ts.map +1 -0
- package/lib/packlets/tools/index.js +22 -0
- package/lib/packlets/tools/index.js.map +1 -0
- package/lib/packlets/tools/memoryTools.d.ts +139 -0
- package/lib/packlets/tools/memoryTools.d.ts.map +1 -0
- package/lib/packlets/tools/memoryTools.js +341 -0
- package/lib/packlets/tools/memoryTools.js.map +1 -0
- package/lib/packlets/types/identityCodec.d.ts +86 -0
- package/lib/packlets/types/identityCodec.d.ts.map +1 -1
- package/lib/packlets/types/identityCodec.js +118 -1
- package/lib/packlets/types/identityCodec.js.map +1 -1
- package/lib/packlets/types/index.d.ts +1 -0
- package/lib/packlets/types/index.d.ts.map +1 -1
- package/lib/packlets/types/index.js +1 -0
- package/lib/packlets/types/index.js.map +1 -1
- package/lib/packlets/types/temporal.d.ts +40 -0
- package/lib/packlets/types/temporal.d.ts.map +1 -0
- package/lib/packlets/types/temporal.js +92 -0
- package/lib/packlets/types/temporal.js.map +1 -0
- package/lib/packlets/types/writePolicy.d.ts +49 -0
- package/lib/packlets/types/writePolicy.d.ts.map +1 -1
- package/lib/packlets/types/writePolicy.js +98 -1
- package/lib/packlets/types/writePolicy.js.map +1 -1
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +10 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +1 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.js +97 -0
- package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +9 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +275 -0
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
- package/lib/test/unit/ingest/cycleGuard.test.d.ts +2 -0
- package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/cycleGuard.test.js +56 -0
- package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -0
- package/lib/test/unit/ingest/orchestrator.test.d.ts +2 -0
- package/lib/test/unit/ingest/orchestrator.test.d.ts.map +1 -0
- package/lib/test/unit/ingest/orchestrator.test.js +915 -0
- package/lib/test/unit/ingest/orchestrator.test.js.map +1 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +2 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +1 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.js +184 -0
- package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +9 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +1 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js +122 -0
- package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
- package/lib/test/unit/store/fileTreeMemoryStore.test.js +74 -7
- package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
- package/lib/test/unit/store/temporalStore.test.d.ts +2 -0
- package/lib/test/unit/store/temporalStore.test.d.ts.map +1 -0
- package/lib/test/unit/store/temporalStore.test.js +400 -0
- package/lib/test/unit/store/temporalStore.test.js.map +1 -0
- package/lib/test/unit/tools/memoryTools.test.d.ts +2 -0
- package/lib/test/unit/tools/memoryTools.test.d.ts.map +1 -0
- package/lib/test/unit/tools/memoryTools.test.js +574 -0
- package/lib/test/unit/tools/memoryTools.test.js.map +1 -0
- package/lib/test/unit/types/temporalCodec.test.d.ts +2 -0
- package/lib/test/unit/types/temporalCodec.test.d.ts.map +1 -0
- package/lib/test/unit/types/temporalCodec.test.js +205 -0
- package/lib/test/unit/types/temporalCodec.test.js.map +1 -0
- package/lib/test/unit/types/temporalPolicy.test.d.ts +2 -0
- package/lib/test/unit/types/temporalPolicy.test.d.ts.map +1 -0
- package/lib/test/unit/types/temporalPolicy.test.js +64 -0
- package/lib/test/unit/types/temporalPolicy.test.js.map +1 -0
- package/package.json +19 -19
- package/rush-logs/ts-agent-memory.build.cache.log +1 -1
- package/rush-logs/ts-agent-memory.build.log +4 -4
- package/src/index.ts +2 -0
- package/src/packlets/ingest/cycleGuard.ts +142 -0
- package/src/packlets/ingest/hostStages.ts +111 -0
- package/src/packlets/ingest/index.ts +9 -0
- package/src/packlets/ingest/model.ts +184 -0
- package/src/packlets/ingest/orchestrator.ts +797 -0
- package/src/packlets/retrieve/index.ts +1 -0
- package/src/packlets/retrieve/temporalRetrievers.ts +210 -0
- package/src/packlets/store/fileTreeMemoryStore.ts +460 -66
- package/src/packlets/tools/index.ts +6 -0
- package/src/packlets/tools/memoryTools.ts +579 -0
- package/src/packlets/types/identityCodec.ts +184 -0
- package/src/packlets/types/index.ts +1 -0
- package/src/packlets/types/temporal.ts +96 -0
- package/src/packlets/types/writePolicy.ts +127 -0
- package/src/test/unit/converters/antagonistRoundTrip.test.ts +110 -0
- package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +362 -0
- package/src/test/unit/ingest/cycleGuard.test.ts +68 -0
- package/src/test/unit/ingest/orchestrator.test.ts +1158 -0
- package/src/test/unit/retrieve/temporalRetrievers.test.ts +226 -0
- package/src/test/unit/store/antagonistTemporalBoundary.test.ts +158 -0
- package/src/test/unit/store/fileTreeMemoryStore.test.ts +98 -7
- package/src/test/unit/store/temporalStore.test.ts +469 -0
- package/src/test/unit/tools/memoryTools.test.ts +771 -0
- package/src/test/unit/types/temporalCodec.test.ts +259 -0
- package/src/test/unit/types/temporalPolicy.test.ts +96 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +122 -46
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/ts-agent-memory.api.json +11984 -6314
- package/temp/ts-agent-memory.api.md +284 -0
|
@@ -0,0 +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,EAaP,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAIlB,OAA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,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 EntityId,\n IEdge,\n IIdentityCodec,\n IIdentityCodecResult,\n IMemoryEnvelope,\n IMemoryRecord,\n IProvenance,\n Kind,\n LinkType,\n MemoryId,\n MemoryScopeKey,\n Tag,\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/** 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 /** 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 const byId: ReadonlyMap<MemoryId, IMemoryRecord<unknown>> = MemoryIngestOrchestrator._indexById(snapshot);\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, byId);\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 snapshot,\n byId\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 byId: ReadonlyMap<MemoryId, 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, byId)).onSuccess((verdict) =>\n this._planFromVerdict(item, candidate, addr, verdict, byId)\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 byId: ReadonlyMap<MemoryId, 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 verdict\n })\n );\n }\n // duplicate-of | supersede | merge-into: the target must exist and share the\n // candidate's kind.\n const target: IMemoryRecord<unknown> | undefined = byId.get(verdict.target);\n if (target === undefined) {\n return fail(\n `ingest '${item.id}': ${verdict.verdict} target '${verdict.target}' 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 '${verdict.target}' 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 return this._resolveAddress(targetEntityId, target.envelope.kind)\n .withErrorFormat((msg) => `ingest '${item.id}': ${msg}`)\n .onSuccess((targetAddr) =>\n Convert.memoryId.convert(targetAddr.idStem).onSuccess((refId) =>\n succeed({\n candidate,\n writeAddress: targetAddr,\n writeEntityId: targetEntityId,\n 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 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` (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 byId: ReadonlyMap<MemoryId, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return this._findExactMatch(kind, body, addr.scope, snapshot).thenOnSuccess(async (matchId) => {\n if (matchId !== undefined) {\n return succeed({ verdict: 'duplicate-of', target: 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, byId);\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 byId: ReadonlyMap<MemoryId, IMemoryRecord<unknown>>\n ): Promise<Result<ResolutionVerdict>> {\n return MemoryIngestOrchestrator._provisionalRecord(candidate, addr.idStem, body).thenOnSuccess(\n (provisional) => this._resolveViaSimilarityEmbedded(candidate, addr, wiring, byId, 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 byId: ReadonlyMap<MemoryId, 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 if (hit.score < this._similarityThreshold || hit.id === addr.idStem) {\n continue;\n }\n const record: IMemoryRecord<unknown> | undefined = byId.get(hit.id);\n if (record !== undefined) {\n similar.push({ id: hit.id, 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 in `scope` whose `{ kind, body }` hash matches the\n * candidate's (layer-1 exact dedup). Invalidated temporal versions are excluded\n * — only a live (non-temporal or current) record deduplicates a candidate.\n */\n private _findExactMatch(\n kind: Kind,\n body: string,\n scope: MemoryScopeKey,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>\n ): Result<MemoryId | undefined> {\n // Same-kind, same-scope, LIVE (non-temporal or current) records are the exact\n // cohort. `_resolveAddress(...).map(...).orDefault()` collapses an unresolved\n // codec to a non-matching scope with no explicit failure branch.\n const cohort: ReadonlyArray<IMemoryRecord<unknown>> = snapshot.filter(\n (record) =>\n record.envelope.kind === kind &&\n !(isTemporalRecord(record) && !isVersionCurrent(record)) &&\n this._resolveAddress(record.envelope.entityId, record.envelope.kind)\n .onSuccess((addr) => succeed(addr.scope))\n .orDefault() === scope\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), validate edges, and run the write-time cycle guard. */\n private async _relate(\n item: IIngestItem,\n writablePlans: ReadonlyArray<ICandidatePlan>,\n snapshot: ReadonlyArray<IMemoryRecord<unknown>>,\n byId: ReadonlyMap<MemoryId, IMemoryRecord<unknown>>\n ): Promise<Result<ReadonlyArray<ICandidateEdge>>> {\n const relationCandidates: IRelationCandidate[] = writablePlans.map((plan) => ({\n candidate: plan.candidate,\n id: plan.refId\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 const refIds: ReadonlySet<string> = new Set<string>(writablePlans.map((plan) => plan.refId));\n const validation: Result<true> = this._validateEdges(item, proposed.value, refIds, byId);\n if (validation.isFailure()) {\n return fail(validation.message);\n }\n if (this._cycleGuard === 'reject') {\n const guard: Result<true> = assertNoCycles(\n MemoryIngestOrchestrator._existingEdges(snapshot),\n proposed.value.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(proposed.value);\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.\n */\n private _validateEdges(\n item: IIngestItem,\n edges: ReadonlyArray<ICandidateEdge>,\n refIds: ReadonlySet<string>,\n byId: ReadonlyMap<MemoryId, IMemoryRecord<unknown>>\n ): Result<true> {\n return mapResults(\n edges.map((edge) => {\n if (!refIds.has(edge.source)) {\n return fail(`ingest '${item.id}': edge source '${edge.source}' is not a candidate being written`);\n }\n if (!refIds.has(edge.edge.target) && byId.get(edge.edge.target) === undefined) {\n return fail(\n `ingest '${item.id}': edge target '${edge.edge.target}' 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 myEdges: ReadonlyArray<ICandidateEdge> = allEdges.filter((e) => e.source === plan.refId);\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,\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 /** Index a record snapshot by id (last write wins on an id collision across scopes). */\n private static _indexById(\n records: ReadonlyArray<IMemoryRecord<unknown>>\n ): ReadonlyMap<MemoryId, IMemoryRecord<unknown>> {\n const byId: Map<MemoryId, IMemoryRecord<unknown>> = new Map<MemoryId, IMemoryRecord<unknown>>();\n for (const record of records) {\n byId.set(record.envelope.id, record);\n }\n return byId;\n }\n\n /** Every existing outbound edge in the snapshot, as cycle-guard edges. */\n private static _existingEdges(\n records: ReadonlyArray<IMemoryRecord<unknown>>\n ): ReadonlyArray<ICycleGuardEdge> {\n const edges: ICycleGuardEdge[] = [];\n for (const record of records) {\n for (const edge of record.envelope.links) {\n edges.push({ source: record.envelope.id, target: edge.target, type: edge.type });\n }\n }\n return edges;\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"]}
|
|
@@ -8,5 +8,6 @@ export * from './linkTraversalRetriever';
|
|
|
8
8
|
export * from './tagRetriever';
|
|
9
9
|
export * from './structuredFilterRetriever';
|
|
10
10
|
export * from './semanticRetriever';
|
|
11
|
+
export * from './temporalRetrievers';
|
|
11
12
|
export * from './hybridRetriever';
|
|
12
13
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,aAAa,CAAC;AAC5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,0BAA0B,CAAC;AACzC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './retriever';\nexport * from './recencyRetriever';\nexport * from './linkTraversalRetriever';\nexport * from './tagRetriever';\nexport * from './structuredFilterRetriever';\nexport * from './semanticRetriever';\nexport * from './hybridRetriever';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,aAAa,CAAC;AAC5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,0BAA0B,CAAC;AACzC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './retriever';\nexport * from './recencyRetriever';\nexport * from './linkTraversalRetriever';\nexport * from './tagRetriever';\nexport * from './structuredFilterRetriever';\nexport * from './semanticRetriever';\nexport * from './temporalRetrievers';\nexport * from './hybridRetriever';\n"]}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
import { succeed } from '@fgv/ts-utils';
|
|
6
|
+
import { isTemporalRecord, selectCurrentVersion, selectVersionAsOf } from '../types';
|
|
7
|
+
import { guardRetrieverCapabilities, indexedRecordMatchesQuery, limitRecords, recencyCompare } from './retriever';
|
|
8
|
+
/**
|
|
9
|
+
* The capabilities every temporal retriever exposes: temporal "as-of" queries
|
|
10
|
+
* are operational (semantic recall and link traversal are not this retriever's
|
|
11
|
+
* concern).
|
|
12
|
+
* @public
|
|
13
|
+
*/
|
|
14
|
+
export const TEMPORAL_CAPABILITIES = {
|
|
15
|
+
supportsSemanticRecall: false,
|
|
16
|
+
supportsTemporalQuery: true,
|
|
17
|
+
supportsLinkTraversal: false
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Group the temporal records surviving a query's scope / kind / tag / predicate
|
|
21
|
+
* pre-filter by entity (`kind` + `entityId`). Non-temporal records are excluded —
|
|
22
|
+
* the temporal retrievers operate only over versioned entities. The map values
|
|
23
|
+
* are each entity's versions (unordered).
|
|
24
|
+
*/
|
|
25
|
+
function groupTemporalVersionsByEntity(index, query) {
|
|
26
|
+
const groups = new Map();
|
|
27
|
+
for (const entry of index.entries()) {
|
|
28
|
+
if (!isTemporalRecord(entry.record) || !indexedRecordMatchesQuery(entry, query)) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const key = `${entry.record.envelope.kind}\0${entry.record.envelope.entityId}`;
|
|
32
|
+
const existing = groups.get(key);
|
|
33
|
+
if (existing === undefined) {
|
|
34
|
+
groups.set(key, [entry.record]);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
existing.push(entry.record);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return groups;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Temporal retriever returning the **current** version of each temporal entity
|
|
44
|
+
* matching the query (the newest version whose `invalid_at` is null/absent),
|
|
45
|
+
* recency-ordered and limited. A fully-invalidated (soft-deleted) entity
|
|
46
|
+
* contributes nothing. Non-temporal records are not this retriever's concern.
|
|
47
|
+
* @public
|
|
48
|
+
*/
|
|
49
|
+
export class CurrentValidRetriever {
|
|
50
|
+
constructor(index) {
|
|
51
|
+
this._index = index;
|
|
52
|
+
}
|
|
53
|
+
/** {@inheritDoc IMemoryRetriever.capabilities} */
|
|
54
|
+
get capabilities() {
|
|
55
|
+
return TEMPORAL_CAPABILITIES;
|
|
56
|
+
}
|
|
57
|
+
/** Family-convention factory. */
|
|
58
|
+
static create(index) {
|
|
59
|
+
return succeed(new CurrentValidRetriever(index));
|
|
60
|
+
}
|
|
61
|
+
/** {@inheritDoc IMemoryRetriever.retrieve} */
|
|
62
|
+
retrieve(query) {
|
|
63
|
+
return Promise.resolve(guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => {
|
|
64
|
+
const selected = [];
|
|
65
|
+
for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {
|
|
66
|
+
const current = selectCurrentVersion(versions);
|
|
67
|
+
if (current !== undefined) {
|
|
68
|
+
selected.push(current);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
selected.sort(recencyCompare);
|
|
72
|
+
return succeed(limitRecords(selected, query.limit));
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Temporal retriever returning, for each temporal entity matching the query, the
|
|
78
|
+
* version valid at `query.asOf` (epoch ms). `asOf` is this retriever's axis: a
|
|
79
|
+
* query without it yields an empty success (a no-op contribution to a
|
|
80
|
+
* {@link HybridRetriever}, not a failure). Results are recency-ordered and
|
|
81
|
+
* limited.
|
|
82
|
+
* @public
|
|
83
|
+
*/
|
|
84
|
+
export class AsOfRetriever {
|
|
85
|
+
constructor(index) {
|
|
86
|
+
this._index = index;
|
|
87
|
+
}
|
|
88
|
+
/** {@inheritDoc IMemoryRetriever.capabilities} */
|
|
89
|
+
get capabilities() {
|
|
90
|
+
return TEMPORAL_CAPABILITIES;
|
|
91
|
+
}
|
|
92
|
+
/** Family-convention factory. */
|
|
93
|
+
static create(index) {
|
|
94
|
+
return succeed(new AsOfRetriever(index));
|
|
95
|
+
}
|
|
96
|
+
/** {@inheritDoc IMemoryRetriever.retrieve} */
|
|
97
|
+
retrieve(query) {
|
|
98
|
+
return Promise.resolve(guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => {
|
|
99
|
+
if (query.asOf === undefined) {
|
|
100
|
+
return succeed([]);
|
|
101
|
+
}
|
|
102
|
+
const asOf = query.asOf;
|
|
103
|
+
const selected = [];
|
|
104
|
+
for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {
|
|
105
|
+
const valid = selectVersionAsOf(versions, asOf);
|
|
106
|
+
if (valid !== undefined) {
|
|
107
|
+
selected.push(valid);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
selected.sort(recencyCompare);
|
|
111
|
+
return succeed(limitRecords(selected, query.limit));
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Temporal retriever returning **every** version of each temporal entity matching
|
|
117
|
+
* the query, ordered ascending by `valid_at` (then `seq` as a stable tiebreak) —
|
|
118
|
+
* the entity's full history. Limited after ordering.
|
|
119
|
+
*
|
|
120
|
+
* @remarks
|
|
121
|
+
* When the query matches more than one entity, the result is a single
|
|
122
|
+
* CROSS-entity list globally sorted by `valid_at` — versions of different
|
|
123
|
+
* entities interleave, NOT grouped per entity — so `limit` truncates that
|
|
124
|
+
* globally-sorted list. Constrain to one entity (e.g. via `query.scope`) for a
|
|
125
|
+
* single entity's contiguous history.
|
|
126
|
+
* @public
|
|
127
|
+
*/
|
|
128
|
+
export class HistoryRetriever {
|
|
129
|
+
constructor(index) {
|
|
130
|
+
this._index = index;
|
|
131
|
+
}
|
|
132
|
+
/** {@inheritDoc IMemoryRetriever.capabilities} */
|
|
133
|
+
get capabilities() {
|
|
134
|
+
return TEMPORAL_CAPABILITIES;
|
|
135
|
+
}
|
|
136
|
+
/** Family-convention factory. */
|
|
137
|
+
static create(index) {
|
|
138
|
+
return succeed(new HistoryRetriever(index));
|
|
139
|
+
}
|
|
140
|
+
/** {@inheritDoc IMemoryRetriever.retrieve} */
|
|
141
|
+
retrieve(query) {
|
|
142
|
+
return Promise.resolve(guardRetrieverCapabilities(query, this.capabilities).onSuccess(() => {
|
|
143
|
+
const history = [];
|
|
144
|
+
for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {
|
|
145
|
+
history.push(...versions);
|
|
146
|
+
}
|
|
147
|
+
history.sort(HistoryRetriever._byValidAtAscending);
|
|
148
|
+
return succeed(limitRecords(history, query.limit));
|
|
149
|
+
}));
|
|
150
|
+
}
|
|
151
|
+
/** A version's world-truth start: its `valid_at`, defaulting to `created` when absent. */
|
|
152
|
+
static _startOf(record) {
|
|
153
|
+
var _a;
|
|
154
|
+
const temporal = record.envelope.temporal;
|
|
155
|
+
/* c8 ignore next 3 -- unreachable: HistoryRetriever orders only temporal records (pre-filtered by isTemporalRecord), so `temporal` is always present; the guard keeps the type honest */
|
|
156
|
+
if (temporal === undefined) {
|
|
157
|
+
return record.envelope.created;
|
|
158
|
+
}
|
|
159
|
+
return (_a = temporal.valid_at) !== null && _a !== void 0 ? _a : record.envelope.created;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Ascending-by-`valid_at` comparator (a version's `valid_at` defaults to its
|
|
163
|
+
* `created` when absent), with `seq` as a stable ascending tiebreak so
|
|
164
|
+
* same-instant versions order by write sequence.
|
|
165
|
+
*/
|
|
166
|
+
static _byValidAtAscending(a, b) {
|
|
167
|
+
const aStart = HistoryRetriever._startOf(a);
|
|
168
|
+
const bStart = HistoryRetriever._startOf(b);
|
|
169
|
+
return aStart !== bStart ? aStart - bStart : a.envelope.seq - b.envelope.seq;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=temporalRetrievers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"temporalRetrievers.js","sourceRoot":"","sources":["../../../src/packlets/retrieve/temporalRetrievers.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAiB,gBAAgB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEpG,OAAO,EAIL,0BAA0B,EAC1B,yBAAyB,EACzB,YAAY,EACZ,cAAc,EACf,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAiC;IACjE,sBAAsB,EAAE,KAAK;IAC7B,qBAAqB,EAAE,IAAI;IAC3B,qBAAqB,EAAE,KAAK;CAC7B,CAAC;AAEF;;;;;GAKG;AACH,SAAS,6BAA6B,CACpC,KAAmB,EACnB,KAAmB;IAEnB,MAAM,MAAM,GAA0C,IAAI,GAAG,EAAoC,CAAC;IAClG,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC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CAAC,MAA8B;;QACpD,MAAM,QAAQ,GAAmD,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC1F,yLAAyL;QACzL,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,OAAO,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;QACjC,CAAC;QACD,OAAO,MAAA,QAAQ,CAAC,QAAQ,mCAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;IACtD,CAAC;IAED;;;;OAIG;IACK,MAAM,CAAC,mBAAmB,CAAC,CAAyB,EAAE,CAAyB;QACrF,MAAM,MAAM,GAAW,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QACpD,MAAM,MAAM,GAAW,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QACpD,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC;IAC/E,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, isTemporalRecord, selectCurrentVersion, selectVersionAsOf } from '../types';\nimport { IMemoryIndex } from '../index';\nimport {\n IMemoryQuery,\n IMemoryRetriever,\n IMemoryRetrieverCapabilities,\n guardRetrieverCapabilities,\n indexedRecordMatchesQuery,\n limitRecords,\n recencyCompare\n} from './retriever';\n\n/**\n * The capabilities every temporal retriever exposes: temporal \"as-of\" queries\n * are operational (semantic recall and link traversal are not this retriever's\n * concern).\n * @public\n */\nexport const TEMPORAL_CAPABILITIES: IMemoryRetrieverCapabilities = {\n supportsSemanticRecall: false,\n supportsTemporalQuery: true,\n supportsLinkTraversal: false\n};\n\n/**\n * Group the temporal records surviving a query's scope / kind / tag / predicate\n * pre-filter by entity (`kind` + `entityId`). Non-temporal records are excluded —\n * the temporal retrievers operate only over versioned entities. The map values\n * are each entity's versions (unordered).\n */\nfunction groupTemporalVersionsByEntity(\n index: IMemoryIndex,\n query: IMemoryQuery\n): Map<string, IMemoryRecord<unknown>[]> {\n const groups: Map<string, IMemoryRecord<unknown>[]> = new Map<string, IMemoryRecord<unknown>[]>();\n for (const entry of index.entries()) {\n if (!isTemporalRecord(entry.record) || !indexedRecordMatchesQuery(entry, query)) {\n continue;\n }\n const key: string = `${entry.record.envelope.kind}\\0${entry.record.envelope.entityId}`;\n const existing: IMemoryRecord<unknown>[] | undefined = groups.get(key);\n if (existing === undefined) {\n groups.set(key, [entry.record]);\n } else {\n existing.push(entry.record);\n }\n }\n return groups;\n}\n\n/**\n * Temporal retriever returning the **current** version of each temporal entity\n * matching the query (the newest version whose `invalid_at` is null/absent),\n * recency-ordered and limited. A fully-invalidated (soft-deleted) entity\n * contributes nothing. Non-temporal records are not this retriever's concern.\n * @public\n */\nexport class CurrentValidRetriever 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 TEMPORAL_CAPABILITIES;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<CurrentValidRetriever> {\n return succeed(new CurrentValidRetriever(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 selected: IMemoryRecord<unknown>[] = [];\n for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {\n const current: IMemoryRecord<unknown> | undefined = selectCurrentVersion(versions);\n if (current !== undefined) {\n selected.push(current);\n }\n }\n selected.sort(recencyCompare);\n return succeed(limitRecords(selected, query.limit));\n })\n );\n }\n}\n\n/**\n * Temporal retriever returning, for each temporal entity matching the query, the\n * version valid at `query.asOf` (epoch ms). `asOf` is this retriever's axis: a\n * query without it yields an empty success (a no-op contribution to a\n * {@link HybridRetriever}, not a failure). Results are recency-ordered and\n * limited.\n * @public\n */\nexport class AsOfRetriever 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 TEMPORAL_CAPABILITIES;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<AsOfRetriever> {\n return succeed(new AsOfRetriever(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 if (query.asOf === undefined) {\n return succeed([]);\n }\n const asOf: number = query.asOf;\n const selected: IMemoryRecord<unknown>[] = [];\n for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {\n const valid: IMemoryRecord<unknown> | undefined = selectVersionAsOf(versions, asOf);\n if (valid !== undefined) {\n selected.push(valid);\n }\n }\n selected.sort(recencyCompare);\n return succeed(limitRecords(selected, query.limit));\n })\n );\n }\n}\n\n/**\n * Temporal retriever returning **every** version of each temporal entity matching\n * the query, ordered ascending by `valid_at` (then `seq` as a stable tiebreak) —\n * the entity's full history. Limited after ordering.\n *\n * @remarks\n * When the query matches more than one entity, the result is a single\n * CROSS-entity list globally sorted by `valid_at` — versions of different\n * entities interleave, NOT grouped per entity — so `limit` truncates that\n * globally-sorted list. Constrain to one entity (e.g. via `query.scope`) for a\n * single entity's contiguous history.\n * @public\n */\nexport class HistoryRetriever 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 TEMPORAL_CAPABILITIES;\n }\n\n /** Family-convention factory. */\n public static create(index: IMemoryIndex): Result<HistoryRetriever> {\n return succeed(new HistoryRetriever(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 history: IMemoryRecord<unknown>[] = [];\n for (const versions of groupTemporalVersionsByEntity(this._index, query).values()) {\n history.push(...versions);\n }\n history.sort(HistoryRetriever._byValidAtAscending);\n return succeed(limitRecords(history, query.limit));\n })\n );\n }\n\n /** A version's world-truth start: its `valid_at`, defaulting to `created` when absent. */\n private static _startOf(record: IMemoryRecord<unknown>): number {\n const temporal: IMemoryRecord<unknown>['envelope']['temporal'] = record.envelope.temporal;\n /* c8 ignore next 3 -- unreachable: HistoryRetriever orders only temporal records (pre-filtered by isTemporalRecord), so `temporal` is always present; the guard keeps the type honest */\n if (temporal === undefined) {\n return record.envelope.created;\n }\n return temporal.valid_at ?? record.envelope.created;\n }\n\n /**\n * Ascending-by-`valid_at` comparator (a version's `valid_at` defaults to its\n * `created` when absent), with `seq` as a stable ascending tiebreak so\n * same-instant versions order by write sequence.\n */\n private static _byValidAtAscending(a: IMemoryRecord<unknown>, b: IMemoryRecord<unknown>): number {\n const aStart: number = HistoryRetriever._startOf(a);\n const bStart: number = HistoryRetriever._startOf(b);\n return aStart !== bStart ? aStart - bStart : a.envelope.seq - b.envelope.seq;\n }\n}\n"]}
|