@fgv/ts-agent-memory 5.1.0-39 → 5.1.0-41
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/{b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log → cbbdbe09515171b4eba8f2592be2dace1e4e8142.tar.log} +14 -2
- package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +2 -2
- package/.rush/temp/operation/build/all.log +2 -2
- package/.rush/temp/operation/build/log-chunks.jsonl +2 -2
- package/.rush/temp/operation/build/state.json +1 -1
- package/dist/packlets/converters/envelopeConverter.js +17 -3
- package/dist/packlets/converters/envelopeConverter.js.map +1 -1
- package/dist/packlets/index/memoryIndex.js +58 -10
- package/dist/packlets/index/memoryIndex.js.map +1 -1
- package/dist/packlets/ingest/cycleGuard.js +13 -6
- package/dist/packlets/ingest/cycleGuard.js.map +1 -1
- package/dist/packlets/ingest/hostStages.js.map +1 -1
- package/dist/packlets/ingest/model.js.map +1 -1
- package/dist/packlets/ingest/orchestrator.js +94 -49
- package/dist/packlets/ingest/orchestrator.js.map +1 -1
- package/dist/packlets/retrieve/hybridRetriever.js +13 -2
- package/dist/packlets/retrieve/hybridRetriever.js.map +1 -1
- package/dist/packlets/retrieve/linkTraversalRetriever.js +46 -57
- package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js +3 -3
- package/dist/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/dist/packlets/retrieve/retriever.js +50 -7
- package/dist/packlets/retrieve/retriever.js.map +1 -1
- package/dist/packlets/retrieve/semanticRetriever.js +9 -3
- package/dist/packlets/retrieve/semanticRetriever.js.map +1 -1
- package/dist/packlets/retrieve/structuredFilterRetriever.js +3 -3
- package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/dist/packlets/retrieve/tagRetriever.js +3 -3
- package/dist/packlets/retrieve/tagRetriever.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +3 -3
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/dist/packlets/store/fileTreeMemoryStore.js +72 -16
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/tools/memoryTools.js +104 -21
- package/dist/packlets/tools/memoryTools.js.map +1 -1
- package/dist/packlets/types/envelope.js +13 -1
- package/dist/packlets/types/envelope.js.map +1 -1
- package/dist/packlets/vector/inMemoryCosineIndex.js +22 -17
- package/dist/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/dist/packlets/vector/vectorIndex.js.map +1 -1
- package/dist/test/unit/converters/antagonistRoundTrip.test.js +3 -3
- package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -1
- package/dist/test/unit/converters/envelopeConverter.test.js +125 -8
- package/dist/test/unit/converters/envelopeConverter.test.js.map +1 -1
- package/dist/test/unit/index/memoryIndex.test.js +87 -25
- package/dist/test/unit/index/memoryIndex.test.js.map +1 -1
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +20 -16
- package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -1
- package/dist/test/unit/ingest/cycleGuard.test.js +28 -1
- package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -1
- package/dist/test/unit/ingest/orchestrator.test.js +187 -45
- package/dist/test/unit/ingest/orchestrator.test.js.map +1 -1
- package/dist/test/unit/retrieve/linkTraversalRetriever.test.js +106 -31
- package/dist/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -1
- package/dist/test/unit/retrieve/retrievers.test.js +299 -37
- package/dist/test/unit/retrieve/retrievers.test.js.map +1 -1
- package/dist/test/unit/store/embedOnWrite.test.js +69 -12
- package/dist/test/unit/store/embedOnWrite.test.js.map +1 -1
- package/dist/test/unit/store/listScoped.test.js +109 -0
- package/dist/test/unit/store/listScoped.test.js.map +1 -0
- package/dist/test/unit/store/rankAxis.test.js +254 -0
- package/dist/test/unit/store/rankAxis.test.js.map +1 -0
- package/dist/test/unit/tools/memoryTools.test.js +280 -11
- package/dist/test/unit/tools/memoryTools.test.js.map +1 -1
- package/dist/test/unit/types/writePolicy.test.js +9 -2
- package/dist/test/unit/types/writePolicy.test.js.map +1 -1
- package/dist/test/unit/vector/inMemoryCosineIndex.test.js +95 -35
- package/dist/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -1
- package/dist/test/unit/vector/vectorIndex.test.js +24 -15
- package/dist/test/unit/vector/vectorIndex.test.js.map +1 -1
- package/dist/ts-agent-memory.d.ts +384 -97
- package/etc/ts-agent-memory.api.md +64 -22
- package/lib/packlets/converters/envelopeConverter.d.ts +8 -1
- package/lib/packlets/converters/envelopeConverter.d.ts.map +1 -1
- package/lib/packlets/converters/envelopeConverter.js +18 -4
- package/lib/packlets/converters/envelopeConverter.js.map +1 -1
- package/lib/packlets/index/memoryIndex.d.ts +42 -10
- package/lib/packlets/index/memoryIndex.d.ts.map +1 -1
- package/lib/packlets/index/memoryIndex.js +58 -10
- package/lib/packlets/index/memoryIndex.js.map +1 -1
- package/lib/packlets/ingest/cycleGuard.d.ts +5 -5
- package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -1
- package/lib/packlets/ingest/cycleGuard.js +13 -6
- package/lib/packlets/ingest/cycleGuard.js.map +1 -1
- package/lib/packlets/ingest/hostStages.d.ts +3 -3
- package/lib/packlets/ingest/hostStages.d.ts.map +1 -1
- package/lib/packlets/ingest/hostStages.js.map +1 -1
- package/lib/packlets/ingest/model.d.ts +25 -14
- package/lib/packlets/ingest/model.d.ts.map +1 -1
- package/lib/packlets/ingest/model.js.map +1 -1
- package/lib/packlets/ingest/orchestrator.d.ts +18 -4
- package/lib/packlets/ingest/orchestrator.d.ts.map +1 -1
- package/lib/packlets/ingest/orchestrator.js +93 -48
- package/lib/packlets/ingest/orchestrator.js.map +1 -1
- package/lib/packlets/retrieve/hybridRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/hybridRetriever.js +12 -1
- package/lib/packlets/retrieve/hybridRetriever.js.map +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +18 -23
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js +45 -56
- package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js +2 -2
- package/lib/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/lib/packlets/retrieve/retriever.d.ts +70 -11
- package/lib/packlets/retrieve/retriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/retriever.js +52 -7
- package/lib/packlets/retrieve/retriever.js.map +1 -1
- package/lib/packlets/retrieve/semanticRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/semanticRetriever.js +9 -3
- package/lib/packlets/retrieve/semanticRetriever.js.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.js +2 -2
- package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/lib/packlets/retrieve/tagRetriever.js +2 -2
- package/lib/packlets/retrieve/tagRetriever.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js +3 -3
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +57 -3
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +72 -16
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/tools/memoryTools.d.ts +24 -0
- package/lib/packlets/tools/memoryTools.d.ts.map +1 -1
- package/lib/packlets/tools/memoryTools.js +104 -21
- package/lib/packlets/tools/memoryTools.js.map +1 -1
- package/lib/packlets/types/envelope.d.ts +61 -8
- package/lib/packlets/types/envelope.d.ts.map +1 -1
- package/lib/packlets/types/envelope.js +14 -0
- package/lib/packlets/types/envelope.js.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts +9 -5
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.js +22 -17
- package/lib/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/lib/packlets/vector/vectorIndex.d.ts +46 -20
- package/lib/packlets/vector/vectorIndex.d.ts.map +1 -1
- package/lib/packlets/vector/vectorIndex.js.map +1 -1
- package/lib/test/unit/converters/antagonistRoundTrip.test.js +3 -3
- package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -1
- package/lib/test/unit/converters/envelopeConverter.test.js +124 -7
- package/lib/test/unit/converters/envelopeConverter.test.js.map +1 -1
- package/lib/test/unit/index/memoryIndex.test.js +86 -24
- package/lib/test/unit/index/memoryIndex.test.js.map +1 -1
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +20 -16
- package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -1
- package/lib/test/unit/ingest/cycleGuard.test.js +28 -1
- package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -1
- package/lib/test/unit/ingest/orchestrator.test.js +186 -44
- package/lib/test/unit/ingest/orchestrator.test.js.map +1 -1
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.js +106 -31
- package/lib/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -1
- package/lib/test/unit/retrieve/retrievers.test.js +298 -36
- package/lib/test/unit/retrieve/retrievers.test.js.map +1 -1
- package/lib/test/unit/store/embedOnWrite.test.js +68 -11
- package/lib/test/unit/store/embedOnWrite.test.js.map +1 -1
- package/lib/test/unit/store/listScoped.test.d.ts +2 -0
- package/lib/test/unit/store/listScoped.test.d.ts.map +1 -0
- package/lib/test/unit/store/listScoped.test.js +111 -0
- package/lib/test/unit/store/listScoped.test.js.map +1 -0
- package/lib/test/unit/store/rankAxis.test.d.ts +2 -0
- package/lib/test/unit/store/rankAxis.test.d.ts.map +1 -0
- package/lib/test/unit/store/rankAxis.test.js +256 -0
- package/lib/test/unit/store/rankAxis.test.js.map +1 -0
- package/lib/test/unit/tools/memoryTools.test.js +280 -11
- package/lib/test/unit/tools/memoryTools.test.js.map +1 -1
- package/lib/test/unit/types/writePolicy.test.js +9 -2
- package/lib/test/unit/types/writePolicy.test.js.map +1 -1
- package/lib/test/unit/vector/inMemoryCosineIndex.test.js +95 -35
- package/lib/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -1
- package/lib/test/unit/vector/vectorIndex.test.js +24 -15
- package/lib/test/unit/vector/vectorIndex.test.js.map +1 -1
- package/package.json +7 -7
- package/rush-logs/ts-agent-memory.build.cache.log +1 -1
- package/rush-logs/ts-agent-memory.build.log +2 -2
- package/src/packlets/converters/envelopeConverter.ts +27 -4
- package/src/packlets/index/memoryIndex.ts +86 -22
- package/src/packlets/ingest/cycleGuard.ts +22 -11
- package/src/packlets/ingest/hostStages.ts +3 -3
- package/src/packlets/ingest/model.ts +25 -14
- package/src/packlets/ingest/orchestrator.ts +143 -67
- package/src/packlets/retrieve/hybridRetriever.ts +14 -1
- package/src/packlets/retrieve/linkTraversalRetriever.ts +51 -62
- package/src/packlets/retrieve/recencyRetriever.ts +3 -3
- package/src/packlets/retrieve/retriever.ts +97 -13
- package/src/packlets/retrieve/semanticRetriever.ts +10 -5
- package/src/packlets/retrieve/structuredFilterRetriever.ts +3 -3
- package/src/packlets/retrieve/tagRetriever.ts +3 -3
- package/src/packlets/retrieve/temporalRetrievers.ts +3 -3
- package/src/packlets/store/fileTreeMemoryStore.ts +117 -12
- package/src/packlets/tools/memoryTools.ts +152 -25
- package/src/packlets/types/envelope.ts +66 -8
- package/src/packlets/vector/inMemoryCosineIndex.ts +45 -22
- package/src/packlets/vector/vectorIndex.ts +47 -20
- package/src/test/unit/converters/antagonistRoundTrip.test.ts +3 -3
- package/src/test/unit/converters/envelopeConverter.test.ts +168 -11
- package/src/test/unit/index/memoryIndex.test.ts +99 -14
- package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +23 -18
- package/src/test/unit/ingest/cycleGuard.test.ts +44 -2
- package/src/test/unit/ingest/orchestrator.test.ts +234 -41
- package/src/test/unit/retrieve/linkTraversalRetriever.test.ts +134 -35
- package/src/test/unit/retrieve/retrievers.test.ts +381 -25
- package/src/test/unit/store/embedOnWrite.test.ts +83 -11
- package/src/test/unit/store/listScoped.test.ts +138 -0
- package/src/test/unit/store/rankAxis.test.ts +349 -0
- package/src/test/unit/tools/memoryTools.test.ts +362 -13
- package/src/test/unit/types/writePolicy.test.ts +11 -2
- package/src/test/unit/vector/inMemoryCosineIndex.test.ts +115 -39
- package/src/test/unit/vector/vectorIndex.test.ts +33 -17
- package/temp/build/lint/_eslint-5eVG3S6w.json +41 -33
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/ts-agent-memory.api.json +1080 -136
- package/temp/ts-agent-memory.api.md +64 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileTreeMemoryStore.js","sourceRoot":"","sources":["../../../src/packlets/store/fileTreeMemoryStore.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAU,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAEL,mBAAmB,EAUnB,kBAAkB,EAIlB,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAuC,eAAe,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC1G,OAAO,EAAsC,WAAW,EAAE,MAAM,UAAU,CAAC;AAQ3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,sDAAsD;AACtD,MAAM,qBAAqB,GAAW,KAAK,CAAC;AA0J5C;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,mBAAmB;IA8C9B,YAAoB,MAAuB;QACzC,IAAI,CAAC,KAAK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AG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;qBACxD,SAAS,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,KAAK,EAAE,YAAY,CAAC,CAAC;qBAC3E,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CACtB,OAAO,CAAsC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAC5E,CAAC;YACN,CAAC,CAAC,CAAC;YACH,OAAO,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAChD,OAAO,CAAsC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAC9D,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;;AA5sCD;;;;;;GAMG;AACqB,0CAAsB,GAG1C,IAAI,GAAG,CAAsD;IAC/D,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACvB,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC;IAChC,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC;IAClC,CAAC,YAAY,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC;IAC5C,CAAC,cAAc,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC;CACjD,CAAC,CAAC","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 { FileTree } from '@fgv/ts-json-base';\nimport {\n AdmissionDecision,\n DEFAULT_DEDUP_SCOPE,\n DedupScope,\n EntityId,\n IIdentityCodec,\n IMemoryEnvelope,\n IMemoryRecord,\n IProvenance,\n ITemporalIdentityCodec,\n IWritePolicy,\n Kind,\n KnowledgeLwwPolicy,\n MemoryId,\n MemoryScopeKey,\n Tag,\n isTemporalIdentityCodec,\n isTemporalRecord,\n isVersionCurrent,\n selectCurrentVersion,\n selectVersionAsOf\n} from '../types';\nimport { IBodyConverterRegistry as IRegistry, parseMemoryFile, serializeMemoryFile } from '../converters';\nimport { IIndexedMemoryRecord, IMemoryIndex, MemoryIndex } from '../index';\nimport {\n IMemoryObservationRecord,\n IMemoryObserver,\n MemoryObservationOutcome,\n MemoryObservationPhase\n} from '../observe';\nimport { IVectorIndex, MemoryEmbedder } from '../vector';\nimport { defaultMemoryScopeEncoding } from './scopeEncoding';\n\n/** The on-disk extension for a memory record file. */\nconst MEMORY_FILE_EXTENSION: string = '.md';\n\n/**\n * Filter for {@link IMemoryStore.list}. All present fields are ANDed together.\n * @public\n */\nexport interface IMemoryStoreListFilter {\n /** Restrict to records in this scope. */\n readonly scope?: MemoryScopeKey;\n /** Restrict to records of this kind. */\n readonly kind?: Kind;\n /** Restrict to records carrying this tag (exact match). */\n readonly tag?: Tag;\n /**\n * For temporal (versioned) kinds: collapse each entity to the single version\n * valid at this epoch ms. Non-temporal records are timeless and pass through\n * unchanged. Absent = no temporal projection (every version is returned).\n */\n readonly asOf?: number;\n}\n\n/**\n * The writable, FileTree-backed, content-hash-deduped memory store.\n * @public\n */\nexport interface IMemoryStore {\n /**\n * Keyed read by entity id. Resolves `entityId` to a storage address via the\n * registered {@link IIdentityCodec} for `kind`. Returns `undefined` when no\n * record exists. For a versioned (temporal) kind this returns the current\n * version, resolved from the derived in-memory index (not re-read/re-verified\n * from disk per call — the index is kept in sync with every write).\n */\n get(kind: Kind, entityId: EntityId): Promise<Result<IMemoryRecord<unknown> | undefined>>;\n\n /**\n * Direct read by `(scope, MemoryId)`. Returns `undefined` when not found.\n */\n getById(scope: MemoryScopeKey, id: MemoryId): Promise<Result<IMemoryRecord<unknown> | undefined>>;\n\n /**\n * List records, filtered in-memory over the derived index.\n */\n list(filter?: IMemoryStoreListFilter): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>>;\n\n /**\n * Write a record. Validates the body, computes a content hash, deduplicates\n * (scope-wide, before policy), applies the kind's {@link IWritePolicy}, stamps\n * transaction-time metadata (`created` / `updated` / `seq` / `contentHash`),\n * writes the file, and patches the index. Returns the written record — or the\n * existing record unchanged on a dedup no-op.\n */\n put(record: IMemoryRecord<unknown>): Promise<Result<IMemoryRecord<unknown>>>;\n\n /**\n * Delete a record by `(kind, entityId)`. Non-temporal kinds physically delete\n * the file and return the deleted record's {@link MemoryId}. Temporal\n * (versioned) kinds SOFT-delete: the current version is invalidated\n * (`invalid_at` set), history is retained, and the invalidated version's\n * {@link MemoryId} is returned.\n */\n delete(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>>;\n}\n\n/**\n * Parameters for {@link FileTreeMemoryStore.create}.\n * @public\n */\nexport interface IFileTreeMemoryStoreCreateParams {\n /** Root directory under which scope-encoded sub-trees live. Must be mutable. */\n readonly root: FileTree.IMutableFileTreeDirectoryItem;\n /** Per-kind body converter registry. Gates every body on write and read. */\n readonly registry: IRegistry;\n /** Per-kind write policies. Kinds without an entry use a default LWW policy. */\n readonly writePolicies?: ReadonlyMap<Kind, IWritePolicy>;\n /** Per-kind identity codecs. */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /** Scope encoding. Defaults to {@link defaultMemoryScopeEncoding}. */\n readonly scopeEncoding?: (scope: MemoryScopeKey) => Result<string>;\n /**\n * Transaction-time clock. Defaults to `Date.now`. Injectable so tests can\n * make `created` / `updated` deterministic. Also stamps observation\n * `timestamp`s.\n */\n readonly clock?: () => number;\n /**\n * Optional observers fired once per public `get` / `put` / `delete` call.\n * Purely additive — when absent, no observation records are produced and the\n * store behaves exactly as it did without this parameter. Observer errors\n * never affect the store operation (swallowed, logged to {@link\n * IFileTreeMemoryStoreCreateParams.logger | logger} at `warn`).\n */\n readonly observers?: ReadonlyArray<IMemoryObserver>;\n /**\n * Diagnostic logger for swallowed observer failures. Defaults to a\n * `Logging.NoOpLogger`.\n */\n readonly logger?: Logging.ILogger;\n /**\n * Optional vector index for semantic recall. Wired together with\n * {@link IFileTreeMemoryStoreCreateParams.embed | embed}: when both are present\n * the store embeds each written record and maintains the index on\n * `put` / `delete` / cap-cull eviction. Absent (or `embed` absent) → no\n * embedding work happens and the store behaves exactly as it does without this\n * parameter (the additive, zero-overhead-when-unwired default — mirrors the\n * observer hook).\n */\n readonly vectorIndex?: IVectorIndex;\n /**\n * Optional embedder applied to each record on write, wired together with\n * {@link IFileTreeMemoryStoreCreateParams.vectorIndex | vectorIndex}. The\n * consumer supplies it (e.g. `callProviderEmbedding` or in-process\n * transformers); the store never calls an embedding provider directly, so the\n * core stays embedder-agnostic. Embedding/index maintenance is **best-effort**:\n * a failed (or throwing) `embed` / `add` / `remove` is logged at `warn` via\n * {@link IFileTreeMemoryStoreCreateParams.logger | logger} and the record\n * operation still succeeds — the vector index is a derived view that a later\n * `rebuild` reconciles, so a vector failure never fails an authoritative write.\n */\n readonly embed?: MemoryEmbedder;\n}\n\n/**\n * The internal outcome of a locked `put`: the written (or existing, on a\n * dedup no-op) record plus the {@link MemoryId}s evicted by a `cull-oldest`\n * admission decision. The eviction file-deletes and index patches happen\n * inside the write-lock; the `evicted` ids are surfaced so the public `put`\n * can fire one `'delete'` observation per evicted record AFTER the lock\n * releases — consistent with the post-op firing of the other observation\n * hooks, and avoiding observer re-entrancy into the still-held write-lock.\n */\ninterface IPutOutcome {\n readonly record: IMemoryRecord<unknown>;\n readonly evicted: ReadonlyArray<MemoryId>;\n}\n\ninterface IInternalParams {\n readonly root: FileTree.IMutableFileTreeDirectoryItem;\n readonly registry: IRegistry;\n readonly writePolicies: ReadonlyMap<Kind, IWritePolicy>;\n readonly codecs: ReadonlyMap<Kind, IIdentityCodec>;\n readonly defaultCodec?: IIdentityCodec;\n readonly defaultPolicy: IWritePolicy;\n readonly scopeEncoding: (scope: MemoryScopeKey) => Result<string>;\n readonly clock: () => number;\n readonly index: IMemoryIndex;\n readonly observers: ReadonlyArray<IMemoryObserver>;\n readonly logger: Logging.ILogger;\n readonly vectorIndex?: IVectorIndex;\n readonly embed?: MemoryEmbedder;\n}\n\n/**\n * Flat-layout, FileTree-backed {@link IMemoryStore}. The FileTree is the source\n * of truth; the {@link IMemoryIndex} is a derived in-memory view patched on\n * every write. Concurrent writes are serialized through a per-instance async\n * write-lock so the index and the on-disk files never interleave.\n *\n * @remarks\n * Bodies are string (markdown). Both layouts are supported: flat\n * (one-file-per-entity, non-versioned) and versioned (subtree-per-entity,\n * invalidate-don't-delete), dispatched per kind by the codec's `isVersioned`\n * flag. A kind is flat with zero behavioral impact unless it opts into a\n * {@link ITemporalIdentityCodec}.\n * @public\n */\nexport class FileTreeMemoryStore implements IMemoryStore {\n private readonly _root: FileTree.IMutableFileTreeDirectoryItem;\n private readonly _registry: IRegistry;\n private readonly _writePolicies: ReadonlyMap<Kind, IWritePolicy>;\n private readonly _codecs: ReadonlyMap<Kind, IIdentityCodec>;\n private readonly _defaultCodec: IIdentityCodec | undefined;\n private readonly _defaultPolicy: IWritePolicy;\n private readonly _scopeEncoding: (scope: MemoryScopeKey) => Result<string>;\n private readonly _clock: () => number;\n private readonly _index: IMemoryIndex;\n private readonly _hasher: Hash.Crc32Normalizer;\n private readonly _observers: ReadonlyArray<IMemoryObserver>;\n private readonly _logger: Logging.ILogger;\n private readonly _vectorIndex: IVectorIndex | undefined;\n private readonly _embed: MemoryEmbedder | undefined;\n\n /** Monotonic write counter; incremented inside the write-lock on each put. */\n private _seq: number;\n /**\n * Monotonic observation-sequence counter. A distinct authority from `_seq`\n * (the envelope write counter): it numbers the audit stream so a single\n * {@link MemoryObservationStore} fed by this store sees strictly increasing\n * `seq`, satisfying the ring buffer's cursor contract.\n */\n private _observationSeq: number;\n /** Tail of the write-lock promise chain that serializes mutating ops. */\n private _writeTail: Promise<unknown>;\n\n /**\n * The record-level mutable-field vocabulary: maps a declared mutable field\n * name to its canonical location on a record. Used to project an incoming\n * record into a merge-patch on update. B1 ships the knowledge-LWW surface\n * (body + envelope metadata); body-internal mutable fields (Phase-C cap-cull)\n * extend this map.\n */\n private static readonly _mutableFieldAccessors: ReadonlyMap<\n string,\n (record: IMemoryRecord<unknown>) => unknown\n > = new Map<string, (record: IMemoryRecord<unknown>) => unknown>([\n ['body', (r) => r.body],\n ['tags', (r) => r.envelope.tags],\n ['links', (r) => r.envelope.links],\n ['provenance', (r) => r.envelope.provenance],\n ['embeddingRef', (r) => r.envelope.embeddingRef]\n ]);\n\n private constructor(params: IInternalParams) {\n this._root = params.root;\n this._registry = params.registry;\n this._writePolicies = params.writePolicies;\n this._codecs = params.codecs;\n this._defaultCodec = params.defaultCodec;\n this._defaultPolicy = params.defaultPolicy;\n this._scopeEncoding = params.scopeEncoding;\n this._clock = params.clock;\n this._index = params.index;\n this._hasher = new Hash.Crc32Normalizer();\n this._observers = params.observers;\n this._logger = params.logger;\n this._vectorIndex = params.vectorIndex;\n this._embed = params.embed;\n this._seq = 0;\n this._observationSeq = 0;\n this._writeTail = Promise.resolve();\n }\n\n /**\n * Family-convention factory. Builds the derived index and a default LWW\n * policy, then performs an initial FileTree walk so an existing vault is\n * indexed (and the `seq` counter resumes past the highest persisted `seq`).\n */\n public static create(params: IFileTreeMemoryStoreCreateParams): Result<FileTreeMemoryStore> {\n return KnowledgeLwwPolicy.create().onSuccess((defaultPolicy) =>\n MemoryIndex.create().onSuccess((index) => {\n const store: FileTreeMemoryStore = new FileTreeMemoryStore({\n root: params.root,\n registry: params.registry,\n writePolicies: params.writePolicies ?? new Map<Kind, IWritePolicy>(),\n codecs: params.codecs ?? new Map<Kind, IIdentityCodec>(),\n defaultCodec: params.defaultCodec,\n defaultPolicy,\n scopeEncoding: params.scopeEncoding ?? defaultMemoryScopeEncoding,\n clock: params.clock ?? Date.now,\n index,\n observers: params.observers ?? [],\n logger: params.logger ?? new Logging.NoOpLogger(),\n vectorIndex: params.vectorIndex,\n embed: params.embed\n });\n return store._initialIndex().onSuccess(() => succeed(store));\n })\n );\n }\n\n /** {@inheritDoc IMemoryStore.get} */\n public async get(kind: Kind, entityId: EntityId): Promise<Result<IMemoryRecord<unknown> | undefined>> {\n const result: Result<IMemoryRecord<unknown> | undefined> = this._codecFor(kind).onSuccess((codec) =>\n codec.encode(entityId).onSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return fail(\n `memory get '${entityId}': codec for versioned kind '${kind}' does not implement the temporal codec interface`\n );\n }\n // Versioned keyed read resolves the CURRENT version (highest-seq\n // version whose `invalid_at` is null/absent) from the entity subtree,\n // read off the derived index. `asOf` resolution is via `list({ asOf })`\n // and the temporal retrievers.\n return succeed(this._readVersionedCurrent(addr.scope));\n }\n return this._readRecord(addr.scope, addr.idStem);\n })\n );\n await this._fireObservation('read', kind, entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value?.envelope.id : undefined,\n error: result.isFailure() ? result.message : undefined\n });\n return result;\n }\n\n /** {@inheritDoc IMemoryStore.getById} */\n public async getById(\n scope: MemoryScopeKey,\n id: MemoryId\n ): Promise<Result<IMemoryRecord<unknown> | undefined>> {\n return this._readRecord(scope, id);\n }\n\n /** {@inheritDoc IMemoryStore.list} */\n public async list(filter?: IMemoryStoreListFilter): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n const matches: IMemoryRecord<unknown>[] = this._index\n .entries()\n .filter((entry) => {\n if (filter?.scope !== undefined && entry.scope !== filter.scope) {\n return false;\n }\n if (filter?.kind !== undefined && entry.record.envelope.kind !== filter.kind) {\n return false;\n }\n if (filter?.tag !== undefined && !entry.record.envelope.tags.includes(filter.tag)) {\n return false;\n }\n return true;\n })\n .map((entry) => entry.record);\n if (filter?.asOf === undefined) {\n // No temporal projection requested: byte-identical to the pre-temporal\n // behavior (the flat-path guarantee — every version is returned).\n return succeed(matches);\n }\n return succeed(FileTreeMemoryStore._projectAsOf(matches, filter.asOf));\n }\n\n /**\n * Collapse temporal records to the single version valid at `asOf` per entity;\n * non-temporal records are timeless and pass through unchanged (valid-time\n * `asOf` applies only to versioned kinds; transaction-time / full bi-temporal\n * filtering is deferred — OQ-9). An entity with no version valid at `asOf`\n * contributes nothing.\n */\n private static _projectAsOf(\n records: ReadonlyArray<IMemoryRecord<unknown>>,\n asOf: number\n ): ReadonlyArray<IMemoryRecord<unknown>> {\n const passthrough: IMemoryRecord<unknown>[] = [];\n const groups: Map<string, IMemoryRecord<unknown>[]> = new Map<string, IMemoryRecord<unknown>[]>();\n for (const record of records) {\n if (!isTemporalRecord(record)) {\n passthrough.push(record);\n continue;\n }\n const key: string = `${record.envelope.kind}\\0${record.envelope.entityId}`;\n const existing: IMemoryRecord<unknown>[] | undefined = groups.get(key);\n if (existing === undefined) {\n groups.set(key, [record]);\n } else {\n existing.push(record);\n }\n }\n const result: IMemoryRecord<unknown>[] = [...passthrough];\n for (const versions of groups.values()) {\n const valid: IMemoryRecord<unknown> | undefined = selectVersionAsOf(versions, asOf);\n if (valid !== undefined) {\n result.push(valid);\n }\n }\n return result;\n }\n\n /** {@inheritDoc IMemoryStore.put} */\n public async put(record: IMemoryRecord<unknown>): Promise<Result<IMemoryRecord<unknown>>> {\n const result: Result<IPutOutcome> = await this._enqueue(() => this._putLocked(record));\n await this._fireObservation('write', record.envelope.kind, record.envelope.entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value.record.envelope.id : record.envelope.id,\n provenance: record.envelope.provenance,\n error: result.isFailure() ? result.message : undefined\n });\n // Fire one `'delete'` observation per record evicted by cap-cull. The\n // evicted records are always in the same `(scope, kind)` cohort as the\n // incoming record, so resolving the scope from the incoming `entityId`\n // yields the evicted record's scope; the observation records the evicted\n // record's own `id`. A no-op / first-write / reject path yields no\n // evictions, so this loop is empty there.\n if (result.isSuccess()) {\n for (const evictedId of result.value.evicted) {\n await this._fireObservation('delete', record.envelope.kind, record.envelope.entityId, {\n outcome: 'success',\n id: evictedId\n });\n }\n }\n return result.onSuccess((outcome) => succeed(outcome.record));\n }\n\n /** {@inheritDoc IMemoryStore.delete} */\n public async delete(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>> {\n const result: Result<MemoryId> = await this._enqueue(() => this._deleteLocked(kind, entityId));\n await this._fireObservation('delete', kind, entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value : undefined,\n error: result.isFailure() ? result.message : undefined\n });\n return result;\n }\n\n /**\n * Serialize a mutating task behind the write-lock. Tasks run in submission\n * order; a failed task does not break the chain for subsequent ones.\n */\n private _enqueue<T>(task: () => Promise<Result<T>>): Promise<Result<T>> {\n const result: Promise<Result<T>> = this._writeTail.then(task);\n this._writeTail = result.then(\n () => undefined,\n () => undefined\n );\n return result;\n }\n\n /**\n * Build and fan out one observation record for a completed op. A no-op when no\n * observers are wired (the additive-default path pays nothing). The store is\n * the seq authority — it mints `seq` / `timestamp` so every observer sees the\n * same record. The scope is resolved best-effort via the codec.\n */\n private async _fireObservation(\n phase: MemoryObservationPhase,\n kind: Kind,\n entityId: EntityId,\n details: {\n readonly outcome: MemoryObservationOutcome;\n readonly id?: MemoryId;\n readonly provenance?: IProvenance;\n readonly error?: string;\n }\n ): Promise<void> {\n if (this._observers.length === 0) {\n return;\n }\n const record: IMemoryObservationRecord = {\n seq: ++this._observationSeq,\n timestamp: this._clock(),\n phase,\n scope: this._scopeBestEffort(kind, entityId),\n id: details.id,\n kind,\n outcome: details.outcome,\n error: details.error,\n provenance: details.provenance\n };\n const awaited: Promise<void>[] = [];\n for (const observer of this._observers) {\n if (observer.fireAndForget === true) {\n // Intentionally not awaited: a fire-and-forget observer must not extend\n // the store op's latency. `_safeObserve` swallows internally; the\n // `.catch` keeps the detached promise from being flagged as floating.\n this._safeObserve(observer, record).catch(() => undefined);\n } else {\n awaited.push(this._safeObserve(observer, record));\n }\n }\n await Promise.all(awaited);\n }\n\n /** Invoke one observer, swallowing any failure or throw (logged at `warn`). */\n private async _safeObserve(observer: IMemoryObserver, record: IMemoryObservationRecord): Promise<void> {\n try {\n const observed: Result<unknown> = await observer.observe(record);\n if (observed.isFailure()) {\n this._warnSwallowed(`memory observer failed (swallowed): ${observed.message}`);\n }\n } catch (error) {\n this._warnSwallowed(`memory observer threw (swallowed): ${String(error)}`);\n }\n }\n\n /**\n * Log a swallowed-issue warning (observer failure or best-effort vector\n * maintenance), tolerating a logger that itself throws — diagnostic logging\n * must never make a store op reject.\n */\n private _warnSwallowed(message: string): void {\n try {\n this._logger.warn(message);\n } catch {\n // Diagnostic logging must not affect the store operation.\n }\n }\n\n /** Resolve a scope for an observation, best-effort (undefined when unresolvable). */\n private _scopeBestEffort(kind: Kind, entityId: EntityId): MemoryScopeKey | undefined {\n return this._codecFor(kind)\n .onSuccess((codec) => codec.encode(entityId))\n .onSuccess((addr) => succeed(addr.scope))\n .orDefault();\n }\n\n private async _putLocked(record: IMemoryRecord<unknown>): Promise<Result<IPutOutcome>> {\n const envelope: IMemoryEnvelope = record.envelope;\n if (typeof record.body !== 'string') {\n return fail(\n `memory put '${envelope.id}': only string (markdown) bodies are supported (got ${typeof record.body})`\n );\n }\n const body: string = record.body;\n // Resolve the body converter + codec, then dispatch on layout. The flat\n // (non-versioned) path keeps its exact dedup/policy ordering; the versioned\n // path is a wholly separate branch so the flat path is behaviorally\n // unchanged (the consumer adoption guarantee).\n return this._registry\n .convert(envelope.kind, body)\n .withErrorFormat((msg) => `memory put '${envelope.id}': invalid body: ${msg}`)\n .onSuccess(() => this._codecFor(envelope.kind))\n .thenOnSuccess((codec) =>\n codec.encode(envelope.entityId).thenOnSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return Promise.resolve(\n fail<IPutOutcome>(\n `memory put '${envelope.entityId}': codec for versioned kind '${envelope.kind}' does not implement the temporal codec interface`\n )\n );\n }\n return this._putVersioned(record, body, codec, addr.scope);\n }\n if (envelope.id !== addr.idStem) {\n return Promise.resolve(\n fail<IPutOutcome>(\n `memory put: envelope id '${envelope.id}' does not match codec-derived stem '${addr.idStem}'`\n )\n );\n }\n return this._contentHash(envelope.kind, body, envelope.links).thenOnSuccess((hash) =>\n this._writeResolved(record, body, addr.scope, addr.idStem, hash)\n );\n })\n );\n }\n\n /**\n * Run dedup → policy → stamp → embed → write for a resolved address and content\n * hash. Async because the embed-on-write hook (when wired) does a network call\n * or in-process inference; the whole chain runs inside the write-lock so the\n * vector index, the on-disk file, and the derived index never interleave.\n */\n private async _writeResolved(\n record: IMemoryRecord<unknown>,\n body: string,\n scope: MemoryScopeKey,\n idStem: string,\n hash: string\n ): Promise<Result<IPutOutcome>> {\n const policy: IWritePolicy = this._policyFor(record.envelope.kind);\n const dedupScope: DedupScope = policy.dedupScope ?? DEFAULT_DEDUP_SCOPE;\n // Content-hash dedup runs BEFORE policy. Its granularity is the kind's\n // `dedupScope`:\n // - 'content': an identical { kind, body, links } triple ANYWHERE in the\n // scope (even under a different id) is a no-op (knowledge family).\n // - 'entity' (default): only an identical re-put of the SAME id is a no-op;\n // two distinct entities with identical content never collapse (experience\n // families). The same-id check is folded into the `_readRecord` below.\n // (Tags / provenance are metadata and are NOT part of the hash; see\n // design-lock §2.5.)\n if (dedupScope === 'content') {\n // Cross-id content collapse: an identical { kind, body, links } triple under\n // a DIFFERENT id is a no-op (knowledge family). A same-id match is excluded\n // here and falls through to the LWW path below so a metadata-only revision\n // (tags / provenance — outside the content hash but inside the policy's\n // mutableFields) actually applies. Content-dedup must never shadow LWW for\n // the same entity.\n const duplicate: IMemoryRecord<unknown> | undefined = this._findByContentHash(\n scope,\n hash,\n record.envelope.id\n );\n if (duplicate !== undefined) {\n return succeed({ record: duplicate, evicted: [] });\n }\n }\n return this._readRecord(scope, idStem).thenOnSuccess((existing) => {\n // Same-id re-put is a no-op ONLY when the content hash matches AND the\n // mutable metadata is also unchanged. The content hash covers\n // { kind, body, links }; a matching hash with revised tags/provenance is a\n // real update that must reach applyUpdate, not be swallowed as a duplicate\n // (both dedup scopes).\n if (\n existing !== undefined &&\n existing.envelope.contentHash === hash &&\n this._isMutableMetadataUnchanged(existing, record)\n ) {\n return Promise.resolve(succeed({ record: existing, evicted: [] }));\n }\n // The admission cohort is the set of records the policy's cap applies to:\n // every record in this scope of this kind EXCEPT the target id. On a first\n // write the post-write count is `cohort.length + 1`; on an update the prior\n // same-id record is excluded so the count is still `cohort.length + 1`\n // (a replace, not a grow). The same-id `existing` record is threaded\n // separately into `_buildRecord` for the merge-patch. Knowledge LWW ignores\n // this argument, so its behavior is unchanged by the wider cohort.\n const cohort: ReadonlyArray<IMemoryRecord<unknown>> = this._admissionCohort(\n scope,\n record.envelope.kind,\n idStem\n );\n return policy\n .admit(record, cohort)\n .thenOnSuccess((decision) =>\n this._admitWrite(record, body, scope, idStem, hash, policy, existing, decision)\n );\n });\n }\n\n /**\n * Build → embed → persist → evict for an admitted write.\n *\n * The durable record store is authoritative; the vector index is a **derived,\n * rebuildable** view, so vector maintenance is **best-effort** — a failed embed\n * or `add` is logged and the durable write still succeeds (the index can be\n * rebuilt via {@link InMemoryCosineIndex.rebuild}). Only genuine record-store\n * failures (body/codec/policy, persist, file eviction) fail the `put`.\n *\n * Ordering: the embed + `add` run immediately before the single `_persist` so\n * the index-returned `embeddingRef` lands in one durable write (a post-persist\n * stamp would need a second write whose failure path is effectively untestable).\n * Build and persist the replacement BEFORE evicting the cull-oldest cohort, so a\n * later eviction failure never loses data with nothing written in its place.\n */\n private async _admitWrite(\n record: IMemoryRecord<unknown>,\n body: string,\n scope: MemoryScopeKey,\n idStem: string,\n hash: string,\n policy: IWritePolicy,\n existing: IMemoryRecord<unknown> | undefined,\n decision: AdmissionDecision\n ): Promise<Result<IPutOutcome>> {\n if (decision.decision === 'reject') {\n return fail(`memory put: rejected by policy: ${decision.reason}`);\n }\n return this._buildRecord(record, body, existing, policy, hash)\n .thenOnSuccess((built) => this._embedOnWrite(built))\n .onSuccess((embeddedBuilt) => this._persist(embeddedBuilt, scope, idStem))\n .thenOnSuccess(async (persisted) => {\n // Everything after the authoritative `_persist` commit is best-effort and\n // never turns a committed write into a `Failure`:\n // - a cull-oldest eviction that fails is logged (the per-(scope,kind)\n // cap may be transiently exceeded; the next write's admission restores\n // it), and only the successfully-evicted ids flow onward;\n // - vector pruning of the evicted cohort is likewise best-effort.\n const evicted: ReadonlyArray<MemoryId> = this._applyEvictions(decision, scope);\n await this._removeEvictedVectors(evicted);\n return succeed({ record: persisted, evicted });\n });\n }\n\n /**\n * Best-effort embed-on-write. When a vector index AND an embedder are wired,\n * embeds the built record, `add`s the vector (replace semantics handle a same-id\n * re-embed — no explicit remove), and stamps the returned `embeddingRef`. A\n * failure (returned `fail` OR a thrown/rejected hook) is logged and the\n * unembedded record is returned unchanged — the put still persists, and the\n * derived index is reconciled by a later `rebuild`. A pass-through no-op when\n * unwired (byte-identical record).\n *\n * Always succeeds (`Result` is the chain's shape, never a vector-induced\n * failure).\n */\n private async _embedOnWrite(built: IMemoryRecord<string>): Promise<Result<IMemoryRecord<string>>> {\n if (this._vectorIndex === undefined || this._embed === undefined) {\n return succeed(built);\n }\n const vectorIndex: IVectorIndex = this._vectorIndex;\n const embed: MemoryEmbedder = this._embed;\n const embedded: Result<Float32Array> = await this._tryVectorOp(\n () => embed(built),\n `embedding '${built.envelope.id}'`\n );\n if (embedded.isFailure()) {\n return succeed(built);\n }\n const added: Result<string> = await this._tryVectorOp(\n () => vectorIndex.add(built.envelope.id, embedded.value),\n `vector add for '${built.envelope.id}'`\n );\n if (added.isFailure()) {\n return succeed(built);\n }\n return succeed({ envelope: { ...built.envelope, embeddingRef: added.value }, body: built.body });\n }\n\n /**\n * Evict the records named by a `cull-oldest` decision, best-effort. Runs only\n * after the authoritative `_persist`, so a failed eviction is logged (never\n * fatal) and the cap self-corrects on the next admission. Returns the ids that\n * were actually evicted (so observations / vector pruning cover only those).\n * `accept` / `reject` decisions evict nothing.\n */\n private _applyEvictions(decision: AdmissionDecision, scope: MemoryScopeKey): ReadonlyArray<MemoryId> {\n if (decision.decision !== 'cull-oldest') {\n return [];\n }\n const evicted: MemoryId[] = [];\n for (const id of decision.evict) {\n const result: Result<MemoryId> = this._evict(scope, id);\n if (result.isSuccess()) {\n evicted.push(result.value);\n } else {\n this._warnSwallowed(\n `memory put: best-effort eviction of '${id}' failed (cap may be transiently exceeded; restored on the next write): ${result.message}`\n );\n }\n }\n return evicted;\n }\n\n /** Best-effort vector removal for each evicted record (never fails the put). */\n private async _removeEvictedVectors(evicted: ReadonlyArray<MemoryId>): Promise<void> {\n for (const id of evicted) {\n await this._removeVectorBestEffort(id);\n }\n }\n\n /**\n * Run a consumer-supplied vector hook, normalizing a thrown/rejected hook into a\n * `Failure` and logging any failure at `warn`. Best-effort: the caller proceeds\n * regardless, since the index is rebuildable.\n */\n private async _tryVectorOp<T>(op: () => Promise<Result<T>>, label: string): Promise<Result<T>> {\n let result: Result<T>;\n try {\n result = await op();\n } catch (err) {\n result = fail(`${label} threw: ${String(err)}`);\n }\n if (result.isFailure()) {\n this._warnSwallowed(\n `memory: ${label} failed (best-effort; vector index left for rebuild): ${result.message}`\n );\n }\n return result;\n }\n\n /**\n * Best-effort vector removal. A no-op unless the full vector lifecycle is wired\n * (both an index AND an embedder), so an unwired store does no vector work and\n * behaves byte-identically. Failures are logged, never surfaced — a committed\n * delete/eviction must not fail because a derived index could not be pruned.\n */\n private async _removeVectorBestEffort(id: MemoryId): Promise<void> {\n if (this._vectorIndex === undefined || this._embed === undefined) {\n return;\n }\n const vectorIndex: IVectorIndex = this._vectorIndex;\n await this._tryVectorOp(() => vectorIndex.remove(id), `vector removal for '${id}'`);\n }\n\n /**\n * Build the record to persist. On a first write the incoming envelope is the\n * base (final content equals the incoming content, so the dedup `hash` is\n * reused). On an update the incoming record's mutable fields are projected into\n * a merge-patch and the policy's `applyUpdate` merges them over the existing\n * record (preserving `created`); the persisted body and `contentHash` are then\n * taken from the policy's actual output, so a body-transforming policy is never\n * bypassed and the stored hash always matches the stored `{ kind, body, links }`.\n * The store stamps the transaction-time metadata it owns\n * (`created` / `updated` / `seq` / `contentHash`).\n */\n private _buildRecord(\n incoming: IMemoryRecord<unknown>,\n body: string,\n existing: IMemoryRecord<unknown> | undefined,\n policy: IWritePolicy,\n hash: string\n ): Result<IMemoryRecord<string>> {\n const now: number = this._clock();\n const seq: number = ++this._seq;\n if (existing === undefined) {\n return succeed({\n envelope: { ...incoming.envelope, created: now, updated: now, seq, contentHash: hash },\n body\n });\n }\n const patch: Record<string, unknown> = this._projectMutablePatch(incoming, policy.mutableFields);\n return policy\n .applyUpdate(existing, patch)\n .withErrorFormat((msg) => `memory put '${incoming.envelope.id}': update failed: ${msg}`)\n .onSuccess((updated) => {\n if (typeof updated.body !== 'string') {\n return fail(\n `memory put '${incoming.envelope.id}': policy returned a non-string body (${typeof updated.body})`\n );\n }\n const finalBody: string = updated.body;\n return this._contentHash(updated.envelope.kind, finalBody, updated.envelope.links).onSuccess(\n (finalHash) =>\n succeed({\n envelope: {\n ...updated.envelope,\n created: existing.envelope.created,\n updated: now,\n seq,\n contentHash: finalHash\n },\n body: finalBody\n })\n );\n });\n }\n\n /** Serialize and write a fully-stamped record, then patch the index. */\n private _persist(\n record: IMemoryRecord<string>,\n scope: MemoryScopeKey,\n idStem: string\n ): Result<IMemoryRecord<unknown>> {\n return serializeMemoryFile(record.envelope, record.body)\n .onSuccess((raw) => this._writeFile(scope, idStem, raw))\n .onSuccess(() => this._index.patch('put', { scope, record }))\n .onSuccess(() => succeed(record));\n }\n\n private async _deleteLocked(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>> {\n return this._codecFor(kind).thenOnSuccess((codec) =>\n codec.encode(entityId).thenOnSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return Promise.resolve(\n fail<MemoryId>(\n `memory delete '${entityId}': codec for versioned kind '${kind}' does not implement the temporal codec interface`\n )\n );\n }\n return this._deleteVersioned(entityId, addr.scope);\n }\n return this._deleteFlat(entityId, addr.scope, addr.idStem);\n })\n );\n }\n\n /**\n * Flat (non-versioned) delete: physically remove the record file + index\n * entry, then prune the vector best-effort. Structurally unchanged from the\n * pre-temporal delete path.\n */\n private async _deleteFlat(\n entityId: EntityId,\n scope: MemoryScopeKey,\n idStem: string\n ): Promise<Result<MemoryId>> {\n return this._readRecord(scope, idStem).thenOnSuccess((existing) => {\n if (existing === undefined) {\n return Promise.resolve(fail<MemoryId>(`memory delete '${entityId}': no record found`));\n }\n // Delete the record file + index entry (authoritative), then prune the\n // vector best-effort: a committed delete must not fail because the\n // derived index could not be pruned.\n return this._deleteFile(scope, idStem)\n .onSuccess(() => this._index.patch('delete', { scope, record: existing }))\n .thenOnSuccess(async () => {\n await this._removeVectorBestEffort(existing.envelope.id);\n return succeed(existing.envelope.id);\n });\n });\n }\n\n /**\n * Resolve the current version of a temporal entity from the derived index: the\n * highest-`seq` version under the entity subtree `scope` whose `invalid_at` is\n * null/absent. `undefined` when the entity has no current version (never\n * written, or fully invalidated / soft-deleted).\n */\n private _readVersionedCurrent(scope: MemoryScopeKey): IMemoryRecord<unknown> | undefined {\n return selectCurrentVersion(this._versionsForEntity(scope));\n }\n\n /**\n * Every persisted version of the entity whose subtree is `scope`. All version\n * files for one entity live under exactly that scope (which encodes the\n * entityId), so a scope filter over the index isolates one entity's versions.\n */\n private _versionsForEntity(scope: MemoryScopeKey): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._index\n .entries()\n .filter((entry) => entry.scope === scope)\n .map((entry) => entry.record);\n }\n\n /**\n * Versioned write (invalidate-don't-delete). Builds the new version's content\n * (a first version from the incoming record, or a merge of the incoming patch\n * over the current version), persists it as a NEW version file, then sets\n * `invalid_at` on the prior current version.\n *\n * Durability order: the new version is persisted FIRST. It carries the highest\n * `seq`, so a crash before the prior-version invalidation completes still\n * resolves the new version as current (`selectCurrentVersion` breaks a\n * two-current tie by highest `seq`), and `asOf` reads stay correct because each\n * version's `valid_at` lower-bounds its interval.\n */\n private async _putVersioned(\n record: IMemoryRecord<unknown>,\n body: string,\n codec: ITemporalIdentityCodec,\n scope: MemoryScopeKey\n ): Promise<Result<IPutOutcome>> {\n const envelope: IMemoryEnvelope = record.envelope;\n const entityId: EntityId = envelope.entityId;\n const kind: Kind = envelope.kind;\n // Snapshot the entity's versions BEFORE the write. `priorCurrents` is every\n // still-current version at snapshot time — normally one, but two-or-more if a\n // prior invalidation partially failed; invalidating all of them lets the write\n // self-heal a stuck state (P2-7).\n const versions: ReadonlyArray<IMemoryRecord<unknown>> = this._versionsForEntity(scope);\n const priorCurrents: ReadonlyArray<IMemoryRecord<unknown>> = versions.filter(isVersionCurrent);\n const current: IMemoryRecord<unknown> | undefined = selectCurrentVersion(versions);\n const policy: IWritePolicy = this._policyFor(kind);\n const dedupScope: DedupScope = policy.dedupScope ?? DEFAULT_DEDUP_SCOPE;\n return this._contentHash(kind, body, envelope.links).thenOnSuccess((hash) => {\n // Entity-scoped dedup: a re-put is a no-op only when the CURRENT content AND\n // its mutable metadata are unchanged (does not spawn a redundant version).\n // A metadata-only revision (tags/provenance — declared mutable by\n // TemporalVersionedPolicy) must NOT be swallowed here: it mints a new\n // version via the applyUpdate merge in `_buildVersionedRecord`, mirroring\n // the flat path. Content-scoped dedup is not a versioning concern, so only\n // the entity granularity is honored here.\n if (\n dedupScope === 'entity' &&\n current !== undefined &&\n current.envelope.contentHash === hash &&\n this._isMutableMetadataUnchanged(current, record)\n ) {\n return Promise.resolve(succeed<IPutOutcome>({ record: current, evicted: [] }));\n }\n // On the versioned path the admission cohort is the entity's ENTIRE version\n // history (no target id to exclude — the new version does not exist yet),\n // which differs from the flat path's \"cohort excluding target id\" shape.\n return policy.admit(record, versions).thenOnSuccess((decision) => {\n if (decision.decision === 'reject') {\n return Promise.resolve(fail<IPutOutcome>(`memory put: rejected by policy: ${decision.reason}`));\n }\n // No culling on the versioned path — history is retained (invalidate-don't-delete).\n const now: number = this._clock();\n const seq: number = ++this._seq;\n // World-truth start of the new version. Each prior current version's\n // world-truth interval CLOSES at this same instant (not at `now`) so a\n // backdated/future-dated `valid_at` leaves no gap or overlap on the\n // valid-time axis.\n const validAt: number = envelope.temporal?.valid_at ?? now;\n return codec\n .encodeVersion(entityId, seq)\n .withErrorFormat((msg) => `memory put '${entityId}': ${msg}`)\n .thenOnSuccess((versionStem) =>\n this._buildVersionedRecord(record, body, current, policy, hash, versionStem, validAt, now, seq)\n .thenOnSuccess((built) => this._embedOnWrite(built))\n .onSuccess((embeddedBuilt) => this._persist(embeddedBuilt, scope, versionStem))\n .onSuccess((persisted) =>\n this._invalidateCurrents(scope, priorCurrents, validAt, now).onSuccess(() =>\n succeed(persisted)\n )\n )\n .onSuccess((persisted) => succeed({ record: persisted, evicted: [] }))\n );\n });\n });\n }\n\n /**\n * Invalidate a set of still-current versions (close each world-truth interval at\n * `invalidAt`; stamp transaction-time `updated` = `now`). Chained so a mid-list\n * failure propagates. Invalidating every prior current — not just the\n * highest-`seq` pick — self-heals a state where a previous write's invalidation\n * only partially completed (P2-7).\n */\n private _invalidateCurrents(\n scope: MemoryScopeKey,\n currents: ReadonlyArray<IMemoryRecord<unknown>>,\n invalidAt: number,\n now: number\n ): Result<true> {\n return currents.reduce<Result<true>>(\n (acc, version) =>\n acc.onSuccess(() =>\n this._invalidateVersion(scope, version, invalidAt, now).onSuccess(() => succeed(true))\n ),\n succeed(true)\n );\n }\n\n /**\n * Build the new version to persist. A first version takes the incoming\n * content verbatim (its dedup `hash` is reused); a subsequent version projects\n * the incoming record's mutable fields into a merge-patch and lets the policy\n * merge them over the CURRENT version (the merge-patch-under-versioning\n * contract), recomputing the content hash from the policy's output. Each\n * version is its own record with its own transaction time (`created` = `now`)\n * and a store-minted `id` = the version stem, so `id === filename stem` holds.\n */\n private _buildVersionedRecord(\n incoming: IMemoryRecord<unknown>,\n body: string,\n current: IMemoryRecord<unknown> | undefined,\n policy: IWritePolicy,\n // Reused only for the first-version branch (its content is taken verbatim); a\n // subsequent version recomputes its hash from the merge-patched content.\n firstVersionHash: string,\n versionStem: string,\n validAt: number,\n now: number,\n seq: number\n ): Result<IMemoryRecord<string>> {\n const mintedId: MemoryId = versionStem as MemoryId;\n if (current === undefined) {\n const envelope: IMemoryEnvelope = {\n ...incoming.envelope,\n id: mintedId,\n entityId: incoming.envelope.entityId,\n created: now,\n updated: now,\n seq,\n contentHash: firstVersionHash,\n temporal: { valid_at: validAt }\n };\n return succeed({ envelope, body });\n }\n const patch: Record<string, unknown> = this._projectMutablePatch(incoming, policy.mutableFields);\n return policy\n .applyUpdate(current, patch)\n .withErrorFormat((msg) => `memory put '${incoming.envelope.entityId}': update failed: ${msg}`)\n .onSuccess((updated) => {\n if (typeof updated.body !== 'string') {\n return fail(\n `memory put '${\n incoming.envelope.entityId\n }': policy returned a non-string body (${typeof updated.body})`\n );\n }\n const finalBody: string = updated.body;\n return this._contentHash(updated.envelope.kind, finalBody, updated.envelope.links).onSuccess(\n (finalHash) => {\n const envelope: IMemoryEnvelope = {\n ...updated.envelope,\n id: mintedId,\n entityId: incoming.envelope.entityId,\n created: now,\n updated: now,\n seq,\n contentHash: finalHash,\n temporal: { valid_at: validAt }\n };\n return succeed({ envelope, body: finalBody });\n }\n );\n });\n }\n\n /**\n * Set `invalid_at` on a prior current version (invalidate-don't-delete) and\n * rewrite its file + index entry. The content hash is unchanged — `invalid_at`\n * is temporal metadata, not part of `{ kind, body, links }` — so the version's\n * identity is stable.\n */\n private _invalidateVersion(\n scope: MemoryScopeKey,\n version: IMemoryRecord<unknown>,\n invalidAt: number,\n now: number\n ): Result<IMemoryRecord<unknown>> {\n /* c8 ignore start -- defensive: every persisted version carries a string body (only string bodies are written) */\n if (typeof version.body !== 'string') {\n return fail(`memory put: cannot invalidate version '${version.envelope.id}': non-string body`);\n }\n /* c8 ignore stop */\n // `invalid_at` is the WORLD-TRUTH close of the interval (the superseding version's\n // `valid_at`, or the delete instant); `updated` is the transaction-time stamp.\n const invalidated: IMemoryRecord<string> = {\n envelope: {\n ...version.envelope,\n updated: now,\n temporal: { ...version.envelope.temporal, invalid_at: invalidAt }\n },\n body: version.body\n };\n return this._persist(invalidated, scope, version.envelope.id);\n }\n\n /**\n * Versioned delete: SOFT delete (invalidate-don't-delete). Sets `invalid_at` on\n * the current version, leaving the entity's history intact and the entity with\n * no current version. Returns the invalidated version's {@link MemoryId}. Fails\n * with \"no record found\" when there is no current version — matching the flat\n * delete's not-found semantics. History is retained deliberately: temporal\n * kinds exist to preserve the audit trail (and the L3 `contradicts` interlock\n * builds on it), so a hard delete would defeat the purpose.\n */\n private async _deleteVersioned(entityId: EntityId, scope: MemoryScopeKey): Promise<Result<MemoryId>> {\n const versions: ReadonlyArray<IMemoryRecord<unknown>> = this._versionsForEntity(scope);\n const currents: ReadonlyArray<IMemoryRecord<unknown>> = versions.filter(isVersionCurrent);\n const current: IMemoryRecord<unknown> | undefined = selectCurrentVersion(versions);\n if (current === undefined) {\n return fail(`memory delete '${entityId}': no record found`);\n }\n // A delete closes the world-truth interval at the delete instant (`now` for both\n // the transaction stamp and the `invalid_at` boundary). Every still-current\n // version is invalidated (self-heals a stuck two-current state — P2-7); the\n // highest-`seq` current's id is returned.\n const now: number = this._clock();\n return this._invalidateCurrents(scope, currents, now, now).onSuccess(() => succeed(current.envelope.id));\n }\n\n /** Evict (physically delete) a single record file by id, patching the index. */\n private _evict(scope: MemoryScopeKey, id: MemoryId): Result<MemoryId> {\n return this._readRecord(scope, id).onSuccess((existing) => {\n if (existing === undefined) {\n return fail(`memory put: cannot evict '${id}' in scope '${scope}': not found`);\n }\n return this._deleteFile(scope, id)\n .onSuccess(() => this._index.patch('delete', { scope, record: existing }))\n .onSuccess(() => succeed(id));\n });\n }\n\n /** Project the incoming record's mutable fields into a merge-patch. */\n private _projectMutablePatch(\n record: IMemoryRecord<unknown>,\n mutableFields: ReadonlyArray<string>\n ): Record<string, unknown> {\n const patch: Record<string, unknown> = {};\n for (const field of mutableFields) {\n const accessor: ((record: IMemoryRecord<unknown>) => unknown) | undefined =\n FileTreeMemoryStore._mutableFieldAccessors.get(field);\n if (accessor !== undefined) {\n const value: unknown = accessor(record);\n if (value !== undefined) {\n patch[field] = value;\n }\n }\n }\n return patch;\n }\n\n /**\n * The admission cohort for a write: every indexed record in `scope` of `kind`\n * except the one at `idStem` (the record being written or updated). This is\n * the set a per-kind cap (e.g. {@link MemoryCapCullPolicy}) counts against, so\n * a bounded-ring policy can keep a per-scope/per-kind family within\n * `maxRecords`. Excluding the target id makes the post-write count uniform\n * across first-writes and updates.\n */\n private _admissionCohort(\n scope: MemoryScopeKey,\n kind: Kind,\n idStem: string\n ): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._index\n .entries()\n .filter(\n (entry) =>\n entry.scope === scope && entry.record.envelope.kind === kind && entry.record.envelope.id !== idStem\n )\n .map((entry) => entry.record);\n }\n\n /**\n * Find a record in `scope` whose `contentHash` equals `hash`, if any,\n * optionally excluding a specific id. `excludeId` lets the content-scoped\n * dedup skip the same-id record so it does not shadow the LWW update path.\n */\n private _findByContentHash(\n scope: MemoryScopeKey,\n hash: string,\n excludeId?: string\n ): IMemoryRecord<unknown> | undefined {\n const match: IIndexedMemoryRecord | undefined = this._index\n .entries()\n .find(\n (entry) =>\n entry.scope === scope &&\n entry.record.envelope.contentHash === hash &&\n entry.record.envelope.id !== excludeId\n );\n return match?.record;\n }\n\n /**\n * True when `incoming`'s caller-authored mutable metadata (`tags` / `provenance`)\n * canonically equals `existing`'s. `body` and `links` are covered by the content\n * hash; `embeddingRef` is store-derived (not caller metadata) and is deliberately\n * excluded so a same-content re-put is not treated as changed merely because the\n * store already stamped an embedding. Used to keep an identical re-put a no-op\n * without swallowing a genuine metadata revision.\n *\n * Canonicalization never fails for a validated record (`tags`/`provenance` are\n * always plain JSON); a failure is defaulted to a non-matching sentinel so the\n * write flows to `applyUpdate` (which re-validates) rather than silently\n * no-op-ing on an un-canonicalizable value.\n */\n private _isMutableMetadataUnchanged(\n existing: IMemoryRecord<unknown>,\n incoming: IMemoryRecord<unknown>\n ): boolean {\n const key = (record: IMemoryRecord<unknown>): string =>\n this._hasher\n .canonicalize({ tags: record.envelope.tags, provenance: record.envelope.provenance })\n .orDefault('');\n const existingKey: string = key(existing);\n return existingKey !== '' && existingKey === key(incoming);\n }\n\n private _contentHash(kind: Kind, body: string, links: IMemoryEnvelope['links']): Result<string> {\n return this._hasher.computeHash({ kind, body, links });\n }\n\n private _codecFor(kind: Kind): Result<IIdentityCodec> {\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 succeed(codec);\n }\n\n private _policyFor(kind: Kind): IWritePolicy {\n return this._writePolicies.get(kind) ?? this._defaultPolicy;\n }\n\n /**\n * Read and validate the record at `<scope>/<idStem>.md`, returning `undefined`\n * when the scope directory or file is absent. Verifies the on-disk id ↔\n * filename round-trip on every load.\n */\n private _readRecord(scope: MemoryScopeKey, idStem: string): Result<IMemoryRecord<unknown> | undefined> {\n return this._resolveScopeDir(scope).onSuccess((scopeDir) => {\n if (scopeDir === undefined) {\n return succeed(undefined);\n }\n return scopeDir.getChildren().onSuccess((children) => {\n const targetName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n const file: FileTree.IFileTreeFileItem | undefined = children.find(\n (c): c is FileTree.IFileTreeFileItem => c.type === 'file' && c.name === targetName\n );\n if (file === undefined) {\n return succeed(undefined);\n }\n return file\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, file, parsedRecord));\n });\n });\n }\n\n /**\n * Enforce `envelope.id === filename stem`, the codec round-trip, AND that the\n * envelope's own `entityId` agrees with the id decoded from the subtree scope.\n * The round-trip only validates (scope, stem) consistency; the codec derives\n * `entityId` from the scope path and never reads the envelope's `entityId`\n * field, so a tampered/corrupt file whose frontmatter declares a foreign\n * `entityId` would otherwise load undetected — and `entityId` is trusted\n * verbatim downstream (e.g. merge-into re-addressing). Cross-check it here.\n */\n private _verifyLoaded(\n scope: MemoryScopeKey,\n file: FileTree.IFileTreeFileItem,\n record: IMemoryRecord<unknown>\n ): Result<IMemoryRecord<unknown>> {\n if (record.envelope.id !== file.baseName) {\n return fail(\n `memory file '${file.absolutePath}': envelope id '${record.envelope.id}' does not match filename stem '${file.baseName}'`\n );\n }\n return this._codecFor(record.envelope.kind)\n .onSuccess((codec) =>\n codec.verifyRoundTrip(scope, file.baseName).onSuccess(() => codec.decode(scope, file.baseName))\n )\n .withErrorFormat((msg) => `memory file '${file.absolutePath}': ${msg}`)\n .onSuccess((decodedEntityId) => {\n if (decodedEntityId !== record.envelope.entityId) {\n return fail(\n `memory file '${file.absolutePath}': envelope entityId '${record.envelope.entityId}' does not match scope-derived entityId '${decodedEntityId}'`\n );\n }\n return succeed(record);\n });\n }\n\n /**\n * Resolve the directory for a scope, returning `undefined` when it does not\n * exist. Navigation only — does not create. Folds the path segments through\n * `getChildren` so an absent segment short-circuits to `undefined`.\n */\n private _resolveScopeDir(scope: MemoryScopeKey): Result<FileTree.IFileTreeDirectoryItem | undefined> {\n return this._scopeEncoding(scope).onSuccess((encoded) => {\n const segments: string[] = encoded.split('/').filter((s) => s.length > 0);\n return segments.reduce<Result<FileTree.IFileTreeDirectoryItem | undefined>>(\n (acc, segment) =>\n acc.onSuccess((current) => {\n if (current === undefined) {\n return succeed(undefined);\n }\n return current\n .getChildren()\n .onSuccess((children) =>\n succeed(\n children.find(\n (c): c is FileTree.IFileTreeDirectoryItem => c.type === 'directory' && c.name === segment\n )\n )\n );\n }),\n succeed(this._root)\n );\n });\n }\n\n /** Ensure the scope directory exists, creating segments as needed. */\n private _ensureScopeDir(scope: MemoryScopeKey): Result<FileTree.IMutableFileTreeDirectoryItem> {\n return this._scopeEncoding(scope).onSuccess((encoded) => {\n const segments: string[] = encoded.split('/').filter((s) => s.length > 0);\n return segments.reduce<Result<FileTree.IMutableFileTreeDirectoryItem>>(\n (acc, segment) =>\n acc.onSuccess((current) =>\n current.getChildren().onSuccess((children) => {\n const existing: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'directory' && c.name === segment\n );\n if (existing === undefined) {\n return current.createChildDirectory(segment);\n }\n /* c8 ignore next 3 -- defensive: a child of a mutable in-memory/fs tree is itself mutable; the guard protects against a read-only adapter handed in as root */\n if (!FileTree.isMutableDirectoryItem(existing)) {\n return fail(`${existing.absolutePath}: directory is not mutable`);\n }\n return succeed(existing);\n })\n ),\n succeed(this._root)\n );\n });\n }\n\n /** Write (create or overwrite) `<scope>/<idStem>.md` with `raw`. */\n private _writeFile(scope: MemoryScopeKey, idStem: string, raw: string): Result<true> {\n return this._ensureScopeDir(scope).onSuccess((scopeDir) =>\n scopeDir.getChildren().onSuccess((children) => {\n const fileName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n const existing: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'file' && c.name === fileName\n );\n if (existing === undefined) {\n return scopeDir.createChildFile(fileName, raw).onSuccess(() => succeed(true));\n }\n /* c8 ignore next 3 -- defensive: a file in a mutable tree is mutable; guards a read-only adapter */\n if (!FileTree.isMutableFileItem(existing)) {\n return fail(`${existing.absolutePath}: file is not mutable`);\n }\n return existing.setRawContents(raw).onSuccess(() => succeed(true));\n })\n );\n }\n\n /**\n * Physically delete `<scope>/<idStem>.md`. The scope-missing and file-missing\n * guards are unreachable through the callers (`delete` / `_evict` both read the\n * record first, so the directory and file exist) but are kept so a future\n * direct caller degrades loudly rather than silently.\n */\n private _deleteFile(scope: MemoryScopeKey, idStem: string): Result<true> {\n return this._resolveScopeDir(scope).onSuccess((scopeDir) => {\n /* c8 ignore next 3 -- unreachable: callers read the record (hence the scope dir) first */\n if (scopeDir === undefined) {\n return fail(`memory delete: scope '${scope}' not found`);\n }\n const fileName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n return scopeDir.getChildren().onSuccess((children) => {\n const file: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'file' && c.name === fileName\n );\n /* c8 ignore next 3 -- unreachable: callers read the record (hence the file) first */\n if (file === undefined) {\n return fail(`memory delete: file '${fileName}' not found in scope '${scope}'`);\n }\n /* c8 ignore next 3 -- defensive: a file in a mutable tree is mutable; guards a read-only adapter */\n if (!FileTree.isMutableFileItem(file)) {\n return fail(`${file.absolutePath}: file is not mutable`);\n }\n return file.delete().onSuccess(() => succeed(true));\n });\n });\n }\n\n /**\n * Walk the FileTree once and rebuild the index. Also resumes the `seq`\n * counter past the highest persisted `seq` so new writes stay monotonic.\n */\n private _initialIndex(): Result<true> {\n return this._collectEntries(this._root, []).onSuccess((entries) =>\n this._index.rebuild(entries).onSuccess(() => {\n for (const entry of entries) {\n if (entry.record.envelope.seq > this._seq) {\n this._seq = entry.record.envelope.seq;\n }\n }\n return succeed(true);\n })\n );\n }\n\n /** Recursively collect every `.md` record under `dir` (scope = path segments). */\n private _collectEntries(\n dir: FileTree.IFileTreeDirectoryItem,\n scopeSegments: ReadonlyArray<string>\n ): Result<ReadonlyArray<IIndexedMemoryRecord>> {\n return dir.getChildren().onSuccess((children) => {\n const results: Result<ReadonlyArray<IIndexedMemoryRecord>>[] = children.map((child) => {\n if (child.type === 'directory') {\n return this._collectEntries(child, [...scopeSegments, child.name]);\n }\n if (!child.name.endsWith(MEMORY_FILE_EXTENSION) || scopeSegments.length === 0) {\n // Skip non-record files and any record-shaped file sitting at the root\n // (records always live under at least one scope segment).\n return succeed<ReadonlyArray<IIndexedMemoryRecord>>([]);\n }\n const scope: MemoryScopeKey = scopeSegments.join('/') as MemoryScopeKey;\n return child\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, child, parsedRecord))\n .onSuccess((verified) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>([{ scope, record: verified }])\n );\n });\n return mapResults(results).onSuccess((perChild) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>(perChild.flat())\n );\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileTreeMemoryStore.js","sourceRoot":"","sources":["../../../src/packlets/store/fileTreeMemoryStore.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAU,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAEL,mBAAmB,EAWnB,kBAAkB,EAKlB,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAuC,eAAe,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC1G,OAAO,EAAsC,WAAW,EAAE,MAAM,UAAU,CAAC;AAQ3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,sDAAsD;AACtD,MAAM,qBAAqB,GAAW,KAAK,CAAC;AA4L5C;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,mBAAmB;IA+C9B,YAAoB,MAAuB;QACzC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,cAAc,CAAC;QAC7C,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC;QACzC,IAAI,CAAC,cAAc,GAAG,MAAM,CAAC,aAAa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AAC,QAAQ,CAAC,UAAU,CAAC;IAC5C,CAAC,cAAc,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC;CACjD,CAAC,CAAC","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 { FileTree } from '@fgv/ts-json-base';\nimport {\n AdmissionDecision,\n DEFAULT_DEDUP_SCOPE,\n DedupScope,\n EntityId,\n IEdgeTarget,\n IIdentityCodec,\n IMemoryEnvelope,\n IMemoryRecord,\n IProvenance,\n ITemporalIdentityCodec,\n IWritePolicy,\n Kind,\n KnowledgeLwwPolicy,\n MemoryId,\n MemoryScopeKey,\n RankProjector,\n Tag,\n isTemporalIdentityCodec,\n isTemporalRecord,\n isVersionCurrent,\n selectCurrentVersion,\n selectVersionAsOf\n} from '../types';\nimport { IBodyConverterRegistry as IRegistry, parseMemoryFile, serializeMemoryFile } from '../converters';\nimport { IIndexedMemoryRecord, IMemoryIndex, MemoryIndex } from '../index';\nimport {\n IMemoryObservationRecord,\n IMemoryObserver,\n MemoryObservationOutcome,\n MemoryObservationPhase\n} from '../observe';\nimport { IMemoryRecordSource, IScopedMemoryRecord, IVectorIndex, MemoryEmbedder } from '../vector';\nimport { defaultMemoryScopeEncoding } from './scopeEncoding';\n\n/** The on-disk extension for a memory record file. */\nconst MEMORY_FILE_EXTENSION: string = '.md';\n\n/**\n * Filter for {@link IMemoryStore.list}. All present fields are ANDed together.\n * @public\n */\nexport interface IMemoryStoreListFilter {\n /** Restrict to records in this scope. */\n readonly scope?: MemoryScopeKey;\n /** Restrict to records of this kind. */\n readonly kind?: Kind;\n /** Restrict to records carrying this tag (exact match). */\n readonly tag?: Tag;\n /**\n * For temporal (versioned) kinds: collapse each entity to the single version\n * valid at this epoch ms. Non-temporal records are timeless and pass through\n * unchanged. Absent = no temporal projection (every version is returned).\n */\n readonly asOf?: number;\n}\n\n/**\n * The writable, FileTree-backed, content-hash-deduped memory store.\n * @public\n */\nexport interface IMemoryStore {\n /**\n * Keyed read by entity id. Resolves `entityId` to a storage address via the\n * registered {@link IIdentityCodec} for `kind`. Returns `undefined` when no\n * record exists. For a versioned (temporal) kind this returns the current\n * version, resolved from the derived in-memory index (not re-read/re-verified\n * from disk per call — the index is kept in sync with every write).\n */\n get(kind: Kind, entityId: EntityId): Promise<Result<IMemoryRecord<unknown> | undefined>>;\n\n /**\n * Direct read by `(scope, MemoryId)`. Returns `undefined` when not found.\n */\n getById(scope: MemoryScopeKey, id: MemoryId): Promise<Result<IMemoryRecord<unknown> | undefined>>;\n\n /**\n * List records, filtered in-memory over the derived index.\n */\n list(filter?: IMemoryStoreListFilter): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>>;\n\n /**\n * List EVERY record in the vault, each paired with its scope-qualified\n * `(scope, id)` address — the projection {@link IMemoryRecordSource} requires.\n * Unlike {@link IMemoryStore.list | list}, it takes no filter (whole-vault) and\n * returns {@link IScopedMemoryRecord}s so a re-index keys each entry on the same\n * scoped target the incremental embed-on-write path uses. Two records that share\n * a filename stem across scopes appear as distinct entries.\n */\n listScoped(): Promise<Result<ReadonlyArray<IScopedMemoryRecord>>>;\n\n /**\n * Adapt this store to the {@link IMemoryRecordSource} seam so it can drive\n * {@link IVectorIndex} rebuilds (e.g. `InMemoryCosineIndex.rebuild`). The\n * returned source's `list()` delegates to {@link IMemoryStore.listScoped}. The\n * store cannot implement {@link IMemoryRecordSource} directly because its\n * `list(filter?)` returns bare records (the ergonomic query surface) while the\n * seam's `list()` returns scope-qualified records.\n */\n asRecordSource(): IMemoryRecordSource;\n\n /**\n * Write a record. Validates the body, computes a content hash, deduplicates\n * (scope-wide, before policy), applies the kind's {@link IWritePolicy}, stamps\n * transaction-time metadata (`created` / `updated` / `seq` / `contentHash`),\n * writes the file, and patches the index. Returns the written record — or the\n * existing record unchanged on a dedup no-op.\n */\n put(record: IMemoryRecord<unknown>): Promise<Result<IMemoryRecord<unknown>>>;\n\n /**\n * Delete a record by `(kind, entityId)`. Non-temporal kinds physically delete\n * the file and return the deleted record's {@link MemoryId}. Temporal\n * (versioned) kinds SOFT-delete: the current version is invalidated\n * (`invalid_at` set), history is retained, and the invalidated version's\n * {@link MemoryId} is returned.\n */\n delete(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>>;\n}\n\n/**\n * Parameters for {@link FileTreeMemoryStore.create}.\n * @public\n */\nexport interface IFileTreeMemoryStoreCreateParams {\n /** Root directory under which scope-encoded sub-trees live. Must be mutable. */\n readonly root: FileTree.IMutableFileTreeDirectoryItem;\n /** Per-kind body converter registry. Gates every body on write and read. */\n readonly registry: IRegistry;\n /** Per-kind write policies. Kinds without an entry use a default LWW policy. */\n readonly writePolicies?: ReadonlyMap<Kind, IWritePolicy>;\n /** Per-kind identity codecs. */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /**\n * Optional per-kind host projector map. When a kind has an entry, the store\n * runs the projector on the fully-resolved (post-merge) record on every put\n * AND every update — in the same pass that recomputes `contentHash` — and\n * stamps the numeric result into {@link IMemoryEnvelope.rank}, which the index's\n * rank view and `orderBy: 'rank'` retrieval sort by (descending, absent last).\n * Absent for a kind → that kind's records carry no `rank`. Purely additive and\n * zero-overhead when unwired: an absent map leaves every write byte-identical.\n * The projector is a host callback — a throw is logged at `warn` and the record\n * is stamped with no `rank`, never failing the write (mirrors the store's other\n * guard-host-callbacks conventions).\n */\n readonly rankProjectors?: ReadonlyMap<Kind, RankProjector>;\n /** Default codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /** Scope encoding. Defaults to {@link defaultMemoryScopeEncoding}. */\n readonly scopeEncoding?: (scope: MemoryScopeKey) => Result<string>;\n /**\n * Transaction-time clock. Defaults to `Date.now`. Injectable so tests can\n * make `created` / `updated` deterministic. Also stamps observation\n * `timestamp`s.\n */\n readonly clock?: () => number;\n /**\n * Optional observers fired once per public `get` / `put` / `delete` call.\n * Purely additive — when absent, no observation records are produced and the\n * store behaves exactly as it did without this parameter. Observer errors\n * never affect the store operation (swallowed, logged to {@link\n * IFileTreeMemoryStoreCreateParams.logger | logger} at `warn`).\n */\n readonly observers?: ReadonlyArray<IMemoryObserver>;\n /**\n * Diagnostic logger for swallowed observer failures. Defaults to a\n * `Logging.NoOpLogger`.\n */\n readonly logger?: Logging.ILogger;\n /**\n * Optional vector index for semantic recall. Wired together with\n * {@link IFileTreeMemoryStoreCreateParams.embed | embed}: when both are present\n * the store embeds each written record and maintains the index on\n * `put` / `delete` / cap-cull eviction. Absent (or `embed` absent) → no\n * embedding work happens and the store behaves exactly as it does without this\n * parameter (the additive, zero-overhead-when-unwired default — mirrors the\n * observer hook).\n */\n readonly vectorIndex?: IVectorIndex;\n /**\n * Optional embedder applied to each record on write, wired together with\n * {@link IFileTreeMemoryStoreCreateParams.vectorIndex | vectorIndex}. The\n * consumer supplies it (e.g. `callProviderEmbedding` or in-process\n * transformers); the store never calls an embedding provider directly, so the\n * core stays embedder-agnostic. Embedding/index maintenance is **best-effort**:\n * a failed (or throwing) `embed` / `add` / `remove` is logged at `warn` via\n * {@link IFileTreeMemoryStoreCreateParams.logger | logger} and the record\n * operation still succeeds — the vector index is a derived view that a later\n * `rebuild` reconciles, so a vector failure never fails an authoritative write.\n */\n readonly embed?: MemoryEmbedder;\n}\n\n/**\n * The internal outcome of a locked `put`: the written (or existing, on a\n * dedup no-op) record plus the {@link MemoryId}s evicted by a `cull-oldest`\n * admission decision. The eviction file-deletes and index patches happen\n * inside the write-lock; the `evicted` ids are surfaced so the public `put`\n * can fire one `'delete'` observation per evicted record AFTER the lock\n * releases — consistent with the post-op firing of the other observation\n * hooks, and avoiding observer re-entrancy into the still-held write-lock.\n */\ninterface IPutOutcome {\n readonly record: IMemoryRecord<unknown>;\n readonly evicted: ReadonlyArray<MemoryId>;\n}\n\ninterface IInternalParams {\n readonly root: FileTree.IMutableFileTreeDirectoryItem;\n readonly registry: IRegistry;\n readonly writePolicies: ReadonlyMap<Kind, IWritePolicy>;\n readonly codecs: ReadonlyMap<Kind, IIdentityCodec>;\n readonly rankProjectors: ReadonlyMap<Kind, RankProjector>;\n readonly defaultCodec?: IIdentityCodec;\n readonly defaultPolicy: IWritePolicy;\n readonly scopeEncoding: (scope: MemoryScopeKey) => Result<string>;\n readonly clock: () => number;\n readonly index: IMemoryIndex;\n readonly observers: ReadonlyArray<IMemoryObserver>;\n readonly logger: Logging.ILogger;\n readonly vectorIndex?: IVectorIndex;\n readonly embed?: MemoryEmbedder;\n}\n\n/**\n * Flat-layout, FileTree-backed {@link IMemoryStore}. The FileTree is the source\n * of truth; the {@link IMemoryIndex} is a derived in-memory view patched on\n * every write. Concurrent writes are serialized through a per-instance async\n * write-lock so the index and the on-disk files never interleave.\n *\n * @remarks\n * Bodies are string (markdown). Both layouts are supported: flat\n * (one-file-per-entity, non-versioned) and versioned (subtree-per-entity,\n * invalidate-don't-delete), dispatched per kind by the codec's `isVersioned`\n * flag. A kind is flat with zero behavioral impact unless it opts into a\n * {@link ITemporalIdentityCodec}.\n * @public\n */\nexport class FileTreeMemoryStore implements IMemoryStore {\n private readonly _root: FileTree.IMutableFileTreeDirectoryItem;\n private readonly _registry: IRegistry;\n private readonly _writePolicies: ReadonlyMap<Kind, IWritePolicy>;\n private readonly _codecs: ReadonlyMap<Kind, IIdentityCodec>;\n private readonly _rankProjectors: ReadonlyMap<Kind, RankProjector>;\n private readonly _defaultCodec: IIdentityCodec | undefined;\n private readonly _defaultPolicy: IWritePolicy;\n private readonly _scopeEncoding: (scope: MemoryScopeKey) => Result<string>;\n private readonly _clock: () => number;\n private readonly _index: IMemoryIndex;\n private readonly _hasher: Hash.Crc32Normalizer;\n private readonly _observers: ReadonlyArray<IMemoryObserver>;\n private readonly _logger: Logging.ILogger;\n private readonly _vectorIndex: IVectorIndex | undefined;\n private readonly _embed: MemoryEmbedder | undefined;\n\n /** Monotonic write counter; incremented inside the write-lock on each put. */\n private _seq: number;\n /**\n * Monotonic observation-sequence counter. A distinct authority from `_seq`\n * (the envelope write counter): it numbers the audit stream so a single\n * {@link MemoryObservationStore} fed by this store sees strictly increasing\n * `seq`, satisfying the ring buffer's cursor contract.\n */\n private _observationSeq: number;\n /** Tail of the write-lock promise chain that serializes mutating ops. */\n private _writeTail: Promise<unknown>;\n\n /**\n * The record-level mutable-field vocabulary: maps a declared mutable field\n * name to its canonical location on a record. Used to project an incoming\n * record into a merge-patch on update. B1 ships the knowledge-LWW surface\n * (body + envelope metadata); body-internal mutable fields (Phase-C cap-cull)\n * extend this map.\n */\n private static readonly _mutableFieldAccessors: ReadonlyMap<\n string,\n (record: IMemoryRecord<unknown>) => unknown\n > = new Map<string, (record: IMemoryRecord<unknown>) => unknown>([\n ['body', (r) => r.body],\n ['tags', (r) => r.envelope.tags],\n ['links', (r) => r.envelope.links],\n ['provenance', (r) => r.envelope.provenance],\n ['embeddingRef', (r) => r.envelope.embeddingRef]\n ]);\n\n private constructor(params: IInternalParams) {\n this._root = params.root;\n this._registry = params.registry;\n this._writePolicies = params.writePolicies;\n this._codecs = params.codecs;\n this._rankProjectors = params.rankProjectors;\n this._defaultCodec = params.defaultCodec;\n this._defaultPolicy = params.defaultPolicy;\n this._scopeEncoding = params.scopeEncoding;\n this._clock = params.clock;\n this._index = params.index;\n this._hasher = new Hash.Crc32Normalizer();\n this._observers = params.observers;\n this._logger = params.logger;\n this._vectorIndex = params.vectorIndex;\n this._embed = params.embed;\n this._seq = 0;\n this._observationSeq = 0;\n this._writeTail = Promise.resolve();\n }\n\n /**\n * Family-convention factory. Builds the derived index and a default LWW\n * policy, then performs an initial FileTree walk so an existing vault is\n * indexed (and the `seq` counter resumes past the highest persisted `seq`).\n */\n public static create(params: IFileTreeMemoryStoreCreateParams): Result<FileTreeMemoryStore> {\n return KnowledgeLwwPolicy.create().onSuccess((defaultPolicy) =>\n MemoryIndex.create().onSuccess((index) => {\n const store: FileTreeMemoryStore = new FileTreeMemoryStore({\n root: params.root,\n registry: params.registry,\n writePolicies: params.writePolicies ?? new Map<Kind, IWritePolicy>(),\n codecs: params.codecs ?? new Map<Kind, IIdentityCodec>(),\n rankProjectors: params.rankProjectors ?? new Map<Kind, RankProjector>(),\n defaultCodec: params.defaultCodec,\n defaultPolicy,\n scopeEncoding: params.scopeEncoding ?? defaultMemoryScopeEncoding,\n clock: params.clock ?? Date.now,\n index,\n observers: params.observers ?? [],\n logger: params.logger ?? new Logging.NoOpLogger(),\n vectorIndex: params.vectorIndex,\n embed: params.embed\n });\n return store._initialIndex().onSuccess(() => succeed(store));\n })\n );\n }\n\n /** {@inheritDoc IMemoryStore.get} */\n public async get(kind: Kind, entityId: EntityId): Promise<Result<IMemoryRecord<unknown> | undefined>> {\n const result: Result<IMemoryRecord<unknown> | undefined> = this._codecFor(kind).onSuccess((codec) =>\n codec.encode(entityId).onSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return fail(\n `memory get '${entityId}': codec for versioned kind '${kind}' does not implement the temporal codec interface`\n );\n }\n // Versioned keyed read resolves the CURRENT version (highest-seq\n // version whose `invalid_at` is null/absent) from the entity subtree,\n // read off the derived index. `asOf` resolution is via `list({ asOf })`\n // and the temporal retrievers.\n return succeed(this._readVersionedCurrent(addr.scope));\n }\n return this._readRecord(addr.scope, addr.idStem);\n })\n );\n await this._fireObservation('read', kind, entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value?.envelope.id : undefined,\n error: result.isFailure() ? result.message : undefined\n });\n return result;\n }\n\n /** {@inheritDoc IMemoryStore.getById} */\n public async getById(\n scope: MemoryScopeKey,\n id: MemoryId\n ): Promise<Result<IMemoryRecord<unknown> | undefined>> {\n return this._readRecord(scope, id);\n }\n\n /** {@inheritDoc IMemoryStore.list} */\n public async list(filter?: IMemoryStoreListFilter): Promise<Result<ReadonlyArray<IMemoryRecord<unknown>>>> {\n const matches: IMemoryRecord<unknown>[] = this._index\n .entries()\n .filter((entry) => {\n if (filter?.scope !== undefined && entry.scope !== filter.scope) {\n return false;\n }\n if (filter?.kind !== undefined && entry.record.envelope.kind !== filter.kind) {\n return false;\n }\n if (filter?.tag !== undefined && !entry.record.envelope.tags.includes(filter.tag)) {\n return false;\n }\n return true;\n })\n .map((entry) => entry.record);\n if (filter?.asOf === undefined) {\n // No temporal projection requested: byte-identical to the pre-temporal\n // behavior (the flat-path guarantee — every version is returned).\n return succeed(matches);\n }\n return succeed(FileTreeMemoryStore._projectAsOf(matches, filter.asOf));\n }\n\n /** {@inheritDoc IMemoryStore.listScoped} */\n public async listScoped(): Promise<Result<ReadonlyArray<IScopedMemoryRecord>>> {\n // The derived index already carries each record's scope\n // ({@link IIndexedMemoryRecord.scope}), so the scoped projection is a direct\n // map — the record's `(scope, id)` is exactly the address the vector index\n // keys on. No filter/temporal projection: the seam re-embeds the whole vault.\n return succeed(\n this._index.entries().map((entry) => ({\n target: { scope: entry.scope, id: entry.record.envelope.id },\n record: entry.record\n }))\n );\n }\n\n /** {@inheritDoc IMemoryStore.asRecordSource} */\n public asRecordSource(): IMemoryRecordSource {\n return { list: (): Promise<Result<ReadonlyArray<IScopedMemoryRecord>>> => this.listScoped() };\n }\n\n /**\n * Collapse temporal records to the single version valid at `asOf` per entity;\n * non-temporal records are timeless and pass through unchanged (valid-time\n * `asOf` applies only to versioned kinds; transaction-time / full bi-temporal\n * filtering is deferred — OQ-9). An entity with no version valid at `asOf`\n * contributes nothing.\n */\n private static _projectAsOf(\n records: ReadonlyArray<IMemoryRecord<unknown>>,\n asOf: number\n ): ReadonlyArray<IMemoryRecord<unknown>> {\n const passthrough: IMemoryRecord<unknown>[] = [];\n const groups: Map<string, IMemoryRecord<unknown>[]> = new Map<string, IMemoryRecord<unknown>[]>();\n for (const record of records) {\n if (!isTemporalRecord(record)) {\n passthrough.push(record);\n continue;\n }\n const key: string = `${record.envelope.kind}\\0${record.envelope.entityId}`;\n const existing: IMemoryRecord<unknown>[] | undefined = groups.get(key);\n if (existing === undefined) {\n groups.set(key, [record]);\n } else {\n existing.push(record);\n }\n }\n const result: IMemoryRecord<unknown>[] = [...passthrough];\n for (const versions of groups.values()) {\n const valid: IMemoryRecord<unknown> | undefined = selectVersionAsOf(versions, asOf);\n if (valid !== undefined) {\n result.push(valid);\n }\n }\n return result;\n }\n\n /** {@inheritDoc IMemoryStore.put} */\n public async put(record: IMemoryRecord<unknown>): Promise<Result<IMemoryRecord<unknown>>> {\n const result: Result<IPutOutcome> = await this._enqueue(() => this._putLocked(record));\n await this._fireObservation('write', record.envelope.kind, record.envelope.entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value.record.envelope.id : record.envelope.id,\n provenance: record.envelope.provenance,\n error: result.isFailure() ? result.message : undefined\n });\n // Fire one `'delete'` observation per record evicted by cap-cull. The\n // evicted records are always in the same `(scope, kind)` cohort as the\n // incoming record, so resolving the scope from the incoming `entityId`\n // yields the evicted record's scope; the observation records the evicted\n // record's own `id`. A no-op / first-write / reject path yields no\n // evictions, so this loop is empty there.\n if (result.isSuccess()) {\n for (const evictedId of result.value.evicted) {\n await this._fireObservation('delete', record.envelope.kind, record.envelope.entityId, {\n outcome: 'success',\n id: evictedId\n });\n }\n }\n return result.onSuccess((outcome) => succeed(outcome.record));\n }\n\n /** {@inheritDoc IMemoryStore.delete} */\n public async delete(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>> {\n const result: Result<MemoryId> = await this._enqueue(() => this._deleteLocked(kind, entityId));\n await this._fireObservation('delete', kind, entityId, {\n outcome: result.isSuccess() ? 'success' : 'failure',\n id: result.isSuccess() ? result.value : undefined,\n error: result.isFailure() ? result.message : undefined\n });\n return result;\n }\n\n /**\n * Serialize a mutating task behind the write-lock. Tasks run in submission\n * order; a failed task does not break the chain for subsequent ones.\n */\n private _enqueue<T>(task: () => Promise<Result<T>>): Promise<Result<T>> {\n const result: Promise<Result<T>> = this._writeTail.then(task);\n this._writeTail = result.then(\n () => undefined,\n () => undefined\n );\n return result;\n }\n\n /**\n * Build and fan out one observation record for a completed op. A no-op when no\n * observers are wired (the additive-default path pays nothing). The store is\n * the seq authority — it mints `seq` / `timestamp` so every observer sees the\n * same record. The scope is resolved best-effort via the codec.\n */\n private async _fireObservation(\n phase: MemoryObservationPhase,\n kind: Kind,\n entityId: EntityId,\n details: {\n readonly outcome: MemoryObservationOutcome;\n readonly id?: MemoryId;\n readonly provenance?: IProvenance;\n readonly error?: string;\n }\n ): Promise<void> {\n if (this._observers.length === 0) {\n return;\n }\n const record: IMemoryObservationRecord = {\n seq: ++this._observationSeq,\n timestamp: this._clock(),\n phase,\n scope: this._scopeBestEffort(kind, entityId),\n id: details.id,\n kind,\n outcome: details.outcome,\n error: details.error,\n provenance: details.provenance\n };\n const awaited: Promise<void>[] = [];\n for (const observer of this._observers) {\n if (observer.fireAndForget === true) {\n // Intentionally not awaited: a fire-and-forget observer must not extend\n // the store op's latency. `_safeObserve` swallows internally; the\n // `.catch` keeps the detached promise from being flagged as floating.\n this._safeObserve(observer, record).catch(() => undefined);\n } else {\n awaited.push(this._safeObserve(observer, record));\n }\n }\n await Promise.all(awaited);\n }\n\n /** Invoke one observer, swallowing any failure or throw (logged at `warn`). */\n private async _safeObserve(observer: IMemoryObserver, record: IMemoryObservationRecord): Promise<void> {\n try {\n const observed: Result<unknown> = await observer.observe(record);\n if (observed.isFailure()) {\n this._warnSwallowed(`memory observer failed (swallowed): ${observed.message}`);\n }\n } catch (error) {\n this._warnSwallowed(`memory observer threw (swallowed): ${String(error)}`);\n }\n }\n\n /**\n * Log a swallowed-issue warning (observer failure or best-effort vector\n * maintenance), tolerating a logger that itself throws — diagnostic logging\n * must never make a store op reject.\n */\n private _warnSwallowed(message: string): void {\n try {\n this._logger.warn(message);\n } catch {\n // Diagnostic logging must not affect the store operation.\n }\n }\n\n /** Resolve a scope for an observation, best-effort (undefined when unresolvable). */\n private _scopeBestEffort(kind: Kind, entityId: EntityId): MemoryScopeKey | undefined {\n return this._codecFor(kind)\n .onSuccess((codec) => codec.encode(entityId))\n .onSuccess((addr) => succeed(addr.scope))\n .orDefault();\n }\n\n private async _putLocked(record: IMemoryRecord<unknown>): Promise<Result<IPutOutcome>> {\n const envelope: IMemoryEnvelope = record.envelope;\n if (typeof record.body !== 'string') {\n return fail(\n `memory put '${envelope.id}': only string (markdown) bodies are supported (got ${typeof record.body})`\n );\n }\n const body: string = record.body;\n // Resolve the body converter + codec, then dispatch on layout. The flat\n // (non-versioned) path keeps its exact dedup/policy ordering; the versioned\n // path is a wholly separate branch so the flat path is behaviorally\n // unchanged (the consumer adoption guarantee).\n return this._registry\n .convert(envelope.kind, body)\n .withErrorFormat((msg) => `memory put '${envelope.id}': invalid body: ${msg}`)\n .onSuccess(() => this._codecFor(envelope.kind))\n .thenOnSuccess((codec) =>\n codec.encode(envelope.entityId).thenOnSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return Promise.resolve(\n fail<IPutOutcome>(\n `memory put '${envelope.entityId}': codec for versioned kind '${envelope.kind}' does not implement the temporal codec interface`\n )\n );\n }\n return this._putVersioned(record, body, codec, addr.scope);\n }\n if (envelope.id !== addr.idStem) {\n return Promise.resolve(\n fail<IPutOutcome>(\n `memory put: envelope id '${envelope.id}' does not match codec-derived stem '${addr.idStem}'`\n )\n );\n }\n return this._contentHash(envelope.kind, body, envelope.links).thenOnSuccess((hash) =>\n this._writeResolved(record, body, addr.scope, addr.idStem, hash)\n );\n })\n );\n }\n\n /**\n * Run dedup → policy → stamp → embed → write for a resolved address and content\n * hash. Async because the embed-on-write hook (when wired) does a network call\n * or in-process inference; the whole chain runs inside the write-lock so the\n * vector index, the on-disk file, and the derived index never interleave.\n */\n private async _writeResolved(\n record: IMemoryRecord<unknown>,\n body: string,\n scope: MemoryScopeKey,\n idStem: string,\n hash: string\n ): Promise<Result<IPutOutcome>> {\n const policy: IWritePolicy = this._policyFor(record.envelope.kind);\n const dedupScope: DedupScope = policy.dedupScope ?? DEFAULT_DEDUP_SCOPE;\n // Content-hash dedup runs BEFORE policy. Its granularity is the kind's\n // `dedupScope`:\n // - 'content': an identical { kind, body, links } triple ANYWHERE in the\n // scope (even under a different id) is a no-op (knowledge family).\n // - 'entity' (default): only an identical re-put of the SAME id is a no-op;\n // two distinct entities with identical content never collapse (experience\n // families). The same-id check is folded into the `_readRecord` below.\n // (Tags / provenance are metadata and are NOT part of the hash; see\n // design-lock §2.5.)\n if (dedupScope === 'content') {\n // Cross-id content collapse: an identical { kind, body, links } triple under\n // a DIFFERENT id is a no-op (knowledge family). A same-id match is excluded\n // here and falls through to the LWW path below so a metadata-only revision\n // (tags / provenance — outside the content hash but inside the policy's\n // mutableFields) actually applies. Content-dedup must never shadow LWW for\n // the same entity.\n const duplicate: IMemoryRecord<unknown> | undefined = this._findByContentHash(\n scope,\n hash,\n record.envelope.id\n );\n if (duplicate !== undefined) {\n return succeed({ record: duplicate, evicted: [] });\n }\n }\n return this._readRecord(scope, idStem).thenOnSuccess((existing) => {\n // Same-id re-put is a no-op ONLY when the content hash matches AND the\n // mutable metadata is also unchanged. The content hash covers\n // { kind, body, links }; a matching hash with revised tags/provenance is a\n // real update that must reach applyUpdate, not be swallowed as a duplicate\n // (both dedup scopes).\n if (\n existing !== undefined &&\n existing.envelope.contentHash === hash &&\n this._isMutableMetadataUnchanged(existing, record)\n ) {\n return Promise.resolve(succeed({ record: existing, evicted: [] }));\n }\n // The admission cohort is the set of records the policy's cap applies to:\n // every record in this scope of this kind EXCEPT the target id. On a first\n // write the post-write count is `cohort.length + 1`; on an update the prior\n // same-id record is excluded so the count is still `cohort.length + 1`\n // (a replace, not a grow). The same-id `existing` record is threaded\n // separately into `_buildRecord` for the merge-patch. Knowledge LWW ignores\n // this argument, so its behavior is unchanged by the wider cohort.\n const cohort: ReadonlyArray<IMemoryRecord<unknown>> = this._admissionCohort(\n scope,\n record.envelope.kind,\n idStem\n );\n return policy\n .admit(record, cohort)\n .thenOnSuccess((decision) =>\n this._admitWrite(record, body, scope, idStem, hash, policy, existing, decision)\n );\n });\n }\n\n /**\n * Build → embed → persist → evict for an admitted write.\n *\n * The durable record store is authoritative; the vector index is a **derived,\n * rebuildable** view, so vector maintenance is **best-effort** — a failed embed\n * or `add` is logged and the durable write still succeeds (the index can be\n * rebuilt via {@link InMemoryCosineIndex.rebuild}). Only genuine record-store\n * failures (body/codec/policy, persist, file eviction) fail the `put`.\n *\n * Ordering: the embed + `add` run immediately before the single `_persist` so\n * the index-returned `embeddingRef` lands in one durable write (a post-persist\n * stamp would need a second write whose failure path is effectively untestable).\n * Build and persist the replacement BEFORE evicting the cull-oldest cohort, so a\n * later eviction failure never loses data with nothing written in its place.\n */\n private async _admitWrite(\n record: IMemoryRecord<unknown>,\n body: string,\n scope: MemoryScopeKey,\n idStem: string,\n hash: string,\n policy: IWritePolicy,\n existing: IMemoryRecord<unknown> | undefined,\n decision: AdmissionDecision\n ): Promise<Result<IPutOutcome>> {\n if (decision.decision === 'reject') {\n return fail(`memory put: rejected by policy: ${decision.reason}`);\n }\n return this._buildRecord(record, body, existing, policy, hash)\n .onSuccess((built) => succeed(this._stampRank(built)))\n .thenOnSuccess((built) => this._embedOnWrite(built, scope))\n .onSuccess((embeddedBuilt) => this._persist(embeddedBuilt, scope, idStem))\n .thenOnSuccess(async (persisted) => {\n // Everything after the authoritative `_persist` commit is best-effort and\n // never turns a committed write into a `Failure`:\n // - a cull-oldest eviction that fails is logged (the per-(scope,kind)\n // cap may be transiently exceeded; the next write's admission restores\n // it), and only the successfully-evicted ids flow onward;\n // - vector pruning of the evicted cohort is likewise best-effort.\n const evicted: ReadonlyArray<MemoryId> = this._applyEvictions(decision, scope);\n await this._removeEvictedVectors(evicted, scope);\n return succeed({ record: persisted, evicted });\n });\n }\n\n /**\n * Best-effort embed-on-write. When a vector index AND an embedder are wired,\n * embeds the built record, `add`s the vector (replace semantics handle a same-id\n * re-embed — no explicit remove), and stamps the returned `embeddingRef`. A\n * failure (returned `fail` OR a thrown/rejected hook) is logged and the\n * unembedded record is returned unchanged — the put still persists, and the\n * derived index is reconciled by a later `rebuild`. A pass-through no-op when\n * unwired (byte-identical record).\n *\n * Always succeeds (`Result` is the chain's shape, never a vector-induced\n * failure).\n */\n private async _embedOnWrite(\n built: IMemoryRecord<string>,\n scope: MemoryScopeKey\n ): Promise<Result<IMemoryRecord<string>>> {\n if (this._vectorIndex === undefined || this._embed === undefined) {\n return succeed(built);\n }\n const vectorIndex: IVectorIndex = this._vectorIndex;\n const embed: MemoryEmbedder = this._embed;\n const target: IEdgeTarget = { scope, id: built.envelope.id };\n const embedded: Result<Float32Array> = await this._tryVectorOp(\n () => embed(built),\n `embedding '${built.envelope.id}'`\n );\n if (embedded.isFailure()) {\n return succeed(built);\n }\n const added: Result<string> = await this._tryVectorOp(\n () => vectorIndex.add(target, embedded.value),\n `vector add for '${built.envelope.id}'`\n );\n if (added.isFailure()) {\n return succeed(built);\n }\n return succeed({ envelope: { ...built.envelope, embeddingRef: added.value }, body: built.body });\n }\n\n /**\n * Evict the records named by a `cull-oldest` decision, best-effort. Runs only\n * after the authoritative `_persist`, so a failed eviction is logged (never\n * fatal) and the cap self-corrects on the next admission. Returns the ids that\n * were actually evicted (so observations / vector pruning cover only those).\n * `accept` / `reject` decisions evict nothing.\n */\n private _applyEvictions(decision: AdmissionDecision, scope: MemoryScopeKey): ReadonlyArray<MemoryId> {\n if (decision.decision !== 'cull-oldest') {\n return [];\n }\n const evicted: MemoryId[] = [];\n for (const id of decision.evict) {\n const result: Result<MemoryId> = this._evict(scope, id);\n if (result.isSuccess()) {\n evicted.push(result.value);\n } else {\n this._warnSwallowed(\n `memory put: best-effort eviction of '${id}' failed (cap may be transiently exceeded; restored on the next write): ${result.message}`\n );\n }\n }\n return evicted;\n }\n\n /**\n * Best-effort vector removal for each evicted record (never fails the put).\n * Every evicted record is in the same `scope` as the incoming write (the\n * cull-oldest cohort is the incoming record's `(scope, kind)` cohort), so that\n * scope qualifies each removal target.\n */\n private async _removeEvictedVectors(\n evicted: ReadonlyArray<MemoryId>,\n scope: MemoryScopeKey\n ): Promise<void> {\n for (const id of evicted) {\n await this._removeVectorBestEffort({ scope, id });\n }\n }\n\n /**\n * Run a consumer-supplied vector hook, normalizing a thrown/rejected hook into a\n * `Failure` and logging any failure at `warn`. Best-effort: the caller proceeds\n * regardless, since the index is rebuildable.\n */\n private async _tryVectorOp<T>(op: () => Promise<Result<T>>, label: string): Promise<Result<T>> {\n let result: Result<T>;\n try {\n result = await op();\n } catch (err) {\n result = fail(`${label} threw: ${String(err)}`);\n }\n if (result.isFailure()) {\n this._warnSwallowed(\n `memory: ${label} failed (best-effort; vector index left for rebuild): ${result.message}`\n );\n }\n return result;\n }\n\n /**\n * Best-effort vector removal. A no-op unless the full vector lifecycle is wired\n * (both an index AND an embedder), so an unwired store does no vector work and\n * behaves byte-identically. Failures are logged, never surfaced — a committed\n * delete/eviction must not fail because a derived index could not be pruned.\n */\n private async _removeVectorBestEffort(target: IEdgeTarget): Promise<void> {\n if (this._vectorIndex === undefined || this._embed === undefined) {\n return;\n }\n const vectorIndex: IVectorIndex = this._vectorIndex;\n await this._tryVectorOp(() => vectorIndex.remove(target), `vector removal for '${target.id}'`);\n }\n\n /**\n * Build the record to persist. On a first write the incoming envelope is the\n * base (final content equals the incoming content, so the dedup `hash` is\n * reused). On an update the incoming record's mutable fields are projected into\n * a merge-patch and the policy's `applyUpdate` merges them over the existing\n * record (preserving `created`); the persisted body and `contentHash` are then\n * taken from the policy's actual output, so a body-transforming policy is never\n * bypassed and the stored hash always matches the stored `{ kind, body, links }`.\n * The store stamps the transaction-time metadata it owns\n * (`created` / `updated` / `seq` / `contentHash`).\n */\n private _buildRecord(\n incoming: IMemoryRecord<unknown>,\n body: string,\n existing: IMemoryRecord<unknown> | undefined,\n policy: IWritePolicy,\n hash: string\n ): Result<IMemoryRecord<string>> {\n const now: number = this._clock();\n const seq: number = ++this._seq;\n if (existing === undefined) {\n return succeed({\n envelope: { ...incoming.envelope, created: now, updated: now, seq, contentHash: hash },\n body\n });\n }\n const patch: Record<string, unknown> = this._projectMutablePatch(incoming, policy.mutableFields);\n return policy\n .applyUpdate(existing, patch)\n .withErrorFormat((msg) => `memory put '${incoming.envelope.id}': update failed: ${msg}`)\n .onSuccess((updated) => {\n if (typeof updated.body !== 'string') {\n return fail(\n `memory put '${incoming.envelope.id}': policy returned a non-string body (${typeof updated.body})`\n );\n }\n const finalBody: string = updated.body;\n return this._contentHash(updated.envelope.kind, finalBody, updated.envelope.links).onSuccess(\n (finalHash) =>\n succeed({\n envelope: {\n ...updated.envelope,\n created: existing.envelope.created,\n updated: now,\n seq,\n contentHash: finalHash\n },\n body: finalBody\n })\n );\n });\n }\n\n /** Serialize and write a fully-stamped record, then patch the index. */\n private _persist(\n record: IMemoryRecord<string>,\n scope: MemoryScopeKey,\n idStem: string\n ): Result<IMemoryRecord<unknown>> {\n return serializeMemoryFile(record.envelope, record.body)\n .onSuccess((raw) => this._writeFile(scope, idStem, raw))\n .onSuccess(() => this._index.patch('put', { scope, record }))\n .onSuccess(() => succeed(record));\n }\n\n private async _deleteLocked(kind: Kind, entityId: EntityId): Promise<Result<MemoryId>> {\n return this._codecFor(kind).thenOnSuccess((codec) =>\n codec.encode(entityId).thenOnSuccess((addr) => {\n if (addr.isVersioned) {\n if (!isTemporalIdentityCodec(codec)) {\n return Promise.resolve(\n fail<MemoryId>(\n `memory delete '${entityId}': codec for versioned kind '${kind}' does not implement the temporal codec interface`\n )\n );\n }\n return this._deleteVersioned(entityId, addr.scope);\n }\n return this._deleteFlat(entityId, addr.scope, addr.idStem);\n })\n );\n }\n\n /**\n * Flat (non-versioned) delete: physically remove the record file + index\n * entry, then prune the vector best-effort. Structurally unchanged from the\n * pre-temporal delete path.\n */\n private async _deleteFlat(\n entityId: EntityId,\n scope: MemoryScopeKey,\n idStem: string\n ): Promise<Result<MemoryId>> {\n return this._readRecord(scope, idStem).thenOnSuccess((existing) => {\n if (existing === undefined) {\n return Promise.resolve(fail<MemoryId>(`memory delete '${entityId}': no record found`));\n }\n // Delete the record file + index entry (authoritative), then prune the\n // vector best-effort: a committed delete must not fail because the\n // derived index could not be pruned.\n return this._deleteFile(scope, idStem)\n .onSuccess(() => this._index.patch('delete', { scope, record: existing }))\n .thenOnSuccess(async () => {\n await this._removeVectorBestEffort({ scope, id: existing.envelope.id });\n return succeed(existing.envelope.id);\n });\n });\n }\n\n /**\n * Resolve the current version of a temporal entity from the derived index: the\n * highest-`seq` version under the entity subtree `scope` whose `invalid_at` is\n * null/absent. `undefined` when the entity has no current version (never\n * written, or fully invalidated / soft-deleted).\n */\n private _readVersionedCurrent(scope: MemoryScopeKey): IMemoryRecord<unknown> | undefined {\n return selectCurrentVersion(this._versionsForEntity(scope));\n }\n\n /**\n * Every persisted version of the entity whose subtree is `scope`. All version\n * files for one entity live under exactly that scope (which encodes the\n * entityId), so a scope filter over the index isolates one entity's versions.\n */\n private _versionsForEntity(scope: MemoryScopeKey): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._index\n .entries()\n .filter((entry) => entry.scope === scope)\n .map((entry) => entry.record);\n }\n\n /**\n * Versioned write (invalidate-don't-delete). Builds the new version's content\n * (a first version from the incoming record, or a merge of the incoming patch\n * over the current version), persists it as a NEW version file, then sets\n * `invalid_at` on the prior current version.\n *\n * Durability order: the new version is persisted FIRST. It carries the highest\n * `seq`, so a crash before the prior-version invalidation completes still\n * resolves the new version as current (`selectCurrentVersion` breaks a\n * two-current tie by highest `seq`), and `asOf` reads stay correct because each\n * version's `valid_at` lower-bounds its interval.\n */\n private async _putVersioned(\n record: IMemoryRecord<unknown>,\n body: string,\n codec: ITemporalIdentityCodec,\n scope: MemoryScopeKey\n ): Promise<Result<IPutOutcome>> {\n const envelope: IMemoryEnvelope = record.envelope;\n const entityId: EntityId = envelope.entityId;\n const kind: Kind = envelope.kind;\n // Snapshot the entity's versions BEFORE the write. `priorCurrents` is every\n // still-current version at snapshot time — normally one, but two-or-more if a\n // prior invalidation partially failed; invalidating all of them lets the write\n // self-heal a stuck state (P2-7).\n const versions: ReadonlyArray<IMemoryRecord<unknown>> = this._versionsForEntity(scope);\n const priorCurrents: ReadonlyArray<IMemoryRecord<unknown>> = versions.filter(isVersionCurrent);\n const current: IMemoryRecord<unknown> | undefined = selectCurrentVersion(versions);\n const policy: IWritePolicy = this._policyFor(kind);\n const dedupScope: DedupScope = policy.dedupScope ?? DEFAULT_DEDUP_SCOPE;\n return this._contentHash(kind, body, envelope.links).thenOnSuccess((hash) => {\n // Entity-scoped dedup: a re-put is a no-op only when the CURRENT content AND\n // its mutable metadata are unchanged (does not spawn a redundant version).\n // A metadata-only revision (tags/provenance — declared mutable by\n // TemporalVersionedPolicy) must NOT be swallowed here: it mints a new\n // version via the applyUpdate merge in `_buildVersionedRecord`, mirroring\n // the flat path. Content-scoped dedup is not a versioning concern, so only\n // the entity granularity is honored here.\n if (\n dedupScope === 'entity' &&\n current !== undefined &&\n current.envelope.contentHash === hash &&\n this._isMutableMetadataUnchanged(current, record)\n ) {\n return Promise.resolve(succeed<IPutOutcome>({ record: current, evicted: [] }));\n }\n // On the versioned path the admission cohort is the entity's ENTIRE version\n // history (no target id to exclude — the new version does not exist yet),\n // which differs from the flat path's \"cohort excluding target id\" shape.\n return policy.admit(record, versions).thenOnSuccess((decision) => {\n if (decision.decision === 'reject') {\n return Promise.resolve(fail<IPutOutcome>(`memory put: rejected by policy: ${decision.reason}`));\n }\n // No culling on the versioned path — history is retained (invalidate-don't-delete).\n const now: number = this._clock();\n const seq: number = ++this._seq;\n // World-truth start of the new version. Each prior current version's\n // world-truth interval CLOSES at this same instant (not at `now`) so a\n // backdated/future-dated `valid_at` leaves no gap or overlap on the\n // valid-time axis.\n const validAt: number = envelope.temporal?.valid_at ?? now;\n return codec\n .encodeVersion(entityId, seq)\n .withErrorFormat((msg) => `memory put '${entityId}': ${msg}`)\n .thenOnSuccess((versionStem) =>\n this._buildVersionedRecord(record, body, current, policy, hash, versionStem, validAt, now, seq)\n .onSuccess((built) => succeed(this._stampRank(built)))\n .thenOnSuccess((built) => this._embedOnWrite(built, scope))\n .onSuccess((embeddedBuilt) => this._persist(embeddedBuilt, scope, versionStem))\n .onSuccess((persisted) =>\n this._invalidateCurrents(scope, priorCurrents, validAt, now).onSuccess(() =>\n succeed(persisted)\n )\n )\n .onSuccess((persisted) => succeed({ record: persisted, evicted: [] }))\n );\n });\n });\n }\n\n /**\n * Invalidate a set of still-current versions (close each world-truth interval at\n * `invalidAt`; stamp transaction-time `updated` = `now`). Chained so a mid-list\n * failure propagates. Invalidating every prior current — not just the\n * highest-`seq` pick — self-heals a state where a previous write's invalidation\n * only partially completed (P2-7).\n */\n private _invalidateCurrents(\n scope: MemoryScopeKey,\n currents: ReadonlyArray<IMemoryRecord<unknown>>,\n invalidAt: number,\n now: number\n ): Result<true> {\n return currents.reduce<Result<true>>(\n (acc, version) =>\n acc.onSuccess(() =>\n this._invalidateVersion(scope, version, invalidAt, now).onSuccess(() => succeed(true))\n ),\n succeed(true)\n );\n }\n\n /**\n * Build the new version to persist. A first version takes the incoming\n * content verbatim (its dedup `hash` is reused); a subsequent version projects\n * the incoming record's mutable fields into a merge-patch and lets the policy\n * merge them over the CURRENT version (the merge-patch-under-versioning\n * contract), recomputing the content hash from the policy's output. Each\n * version is its own record with its own transaction time (`created` = `now`)\n * and a store-minted `id` = the version stem, so `id === filename stem` holds.\n */\n private _buildVersionedRecord(\n incoming: IMemoryRecord<unknown>,\n body: string,\n current: IMemoryRecord<unknown> | undefined,\n policy: IWritePolicy,\n // Reused only for the first-version branch (its content is taken verbatim); a\n // subsequent version recomputes its hash from the merge-patched content.\n firstVersionHash: string,\n versionStem: string,\n validAt: number,\n now: number,\n seq: number\n ): Result<IMemoryRecord<string>> {\n const mintedId: MemoryId = versionStem as MemoryId;\n if (current === undefined) {\n const envelope: IMemoryEnvelope = {\n ...incoming.envelope,\n id: mintedId,\n entityId: incoming.envelope.entityId,\n created: now,\n updated: now,\n seq,\n contentHash: firstVersionHash,\n temporal: { valid_at: validAt }\n };\n return succeed({ envelope, body });\n }\n const patch: Record<string, unknown> = this._projectMutablePatch(incoming, policy.mutableFields);\n return policy\n .applyUpdate(current, patch)\n .withErrorFormat((msg) => `memory put '${incoming.envelope.entityId}': update failed: ${msg}`)\n .onSuccess((updated) => {\n if (typeof updated.body !== 'string') {\n return fail(\n `memory put '${\n incoming.envelope.entityId\n }': policy returned a non-string body (${typeof updated.body})`\n );\n }\n const finalBody: string = updated.body;\n return this._contentHash(updated.envelope.kind, finalBody, updated.envelope.links).onSuccess(\n (finalHash) => {\n const envelope: IMemoryEnvelope = {\n ...updated.envelope,\n id: mintedId,\n entityId: incoming.envelope.entityId,\n created: now,\n updated: now,\n seq,\n contentHash: finalHash,\n temporal: { valid_at: validAt }\n };\n return succeed({ envelope, body: finalBody });\n }\n );\n });\n }\n\n /**\n * Set `invalid_at` on a prior current version (invalidate-don't-delete) and\n * rewrite its file + index entry. The content hash is unchanged — `invalid_at`\n * is temporal metadata, not part of `{ kind, body, links }` — so the version's\n * identity is stable.\n */\n private _invalidateVersion(\n scope: MemoryScopeKey,\n version: IMemoryRecord<unknown>,\n invalidAt: number,\n now: number\n ): Result<IMemoryRecord<unknown>> {\n /* c8 ignore start -- defensive: every persisted version carries a string body (only string bodies are written) */\n if (typeof version.body !== 'string') {\n return fail(`memory put: cannot invalidate version '${version.envelope.id}': non-string body`);\n }\n /* c8 ignore stop */\n // `invalid_at` is the WORLD-TRUTH close of the interval (the superseding version's\n // `valid_at`, or the delete instant); `updated` is the transaction-time stamp.\n const invalidated: IMemoryRecord<string> = {\n envelope: {\n ...version.envelope,\n updated: now,\n temporal: { ...version.envelope.temporal, invalid_at: invalidAt }\n },\n body: version.body\n };\n return this._persist(invalidated, scope, version.envelope.id);\n }\n\n /**\n * Versioned delete: SOFT delete (invalidate-don't-delete). Sets `invalid_at` on\n * the current version, leaving the entity's history intact and the entity with\n * no current version. Returns the invalidated version's {@link MemoryId}. Fails\n * with \"no record found\" when there is no current version — matching the flat\n * delete's not-found semantics. History is retained deliberately: temporal\n * kinds exist to preserve the audit trail (and the L3 `contradicts` interlock\n * builds on it), so a hard delete would defeat the purpose.\n */\n private async _deleteVersioned(entityId: EntityId, scope: MemoryScopeKey): Promise<Result<MemoryId>> {\n const versions: ReadonlyArray<IMemoryRecord<unknown>> = this._versionsForEntity(scope);\n const currents: ReadonlyArray<IMemoryRecord<unknown>> = versions.filter(isVersionCurrent);\n const current: IMemoryRecord<unknown> | undefined = selectCurrentVersion(versions);\n if (current === undefined) {\n return fail(`memory delete '${entityId}': no record found`);\n }\n // A delete closes the world-truth interval at the delete instant (`now` for both\n // the transaction stamp and the `invalid_at` boundary). Every still-current\n // version is invalidated (self-heals a stuck two-current state — P2-7); the\n // highest-`seq` current's id is returned.\n const now: number = this._clock();\n return this._invalidateCurrents(scope, currents, now, now).onSuccess(() => succeed(current.envelope.id));\n }\n\n /** Evict (physically delete) a single record file by id, patching the index. */\n private _evict(scope: MemoryScopeKey, id: MemoryId): Result<MemoryId> {\n return this._readRecord(scope, id).onSuccess((existing) => {\n if (existing === undefined) {\n return fail(`memory put: cannot evict '${id}' in scope '${scope}': not found`);\n }\n return this._deleteFile(scope, id)\n .onSuccess(() => this._index.patch('delete', { scope, record: existing }))\n .onSuccess(() => succeed(id));\n });\n }\n\n /** Project the incoming record's mutable fields into a merge-patch. */\n private _projectMutablePatch(\n record: IMemoryRecord<unknown>,\n mutableFields: ReadonlyArray<string>\n ): Record<string, unknown> {\n const patch: Record<string, unknown> = {};\n for (const field of mutableFields) {\n const accessor: ((record: IMemoryRecord<unknown>) => unknown) | undefined =\n FileTreeMemoryStore._mutableFieldAccessors.get(field);\n if (accessor !== undefined) {\n const value: unknown = accessor(record);\n if (value !== undefined) {\n patch[field] = value;\n }\n }\n }\n return patch;\n }\n\n /**\n * The admission cohort for a write: every indexed record in `scope` of `kind`\n * except the one at `idStem` (the record being written or updated). This is\n * the set a per-kind cap (e.g. {@link MemoryCapCullPolicy}) counts against, so\n * a bounded-ring policy can keep a per-scope/per-kind family within\n * `maxRecords`. Excluding the target id makes the post-write count uniform\n * across first-writes and updates.\n */\n private _admissionCohort(\n scope: MemoryScopeKey,\n kind: Kind,\n idStem: string\n ): ReadonlyArray<IMemoryRecord<unknown>> {\n return this._index\n .entries()\n .filter(\n (entry) =>\n entry.scope === scope && entry.record.envelope.kind === kind && entry.record.envelope.id !== idStem\n )\n .map((entry) => entry.record);\n }\n\n /**\n * Find a record in `scope` whose `contentHash` equals `hash`, if any,\n * optionally excluding a specific id. `excludeId` lets the content-scoped\n * dedup skip the same-id record so it does not shadow the LWW update path.\n */\n private _findByContentHash(\n scope: MemoryScopeKey,\n hash: string,\n excludeId?: string\n ): IMemoryRecord<unknown> | undefined {\n const match: IIndexedMemoryRecord | undefined = this._index\n .entries()\n .find(\n (entry) =>\n entry.scope === scope &&\n entry.record.envelope.contentHash === hash &&\n entry.record.envelope.id !== excludeId\n );\n return match?.record;\n }\n\n /**\n * True when `incoming`'s caller-authored mutable metadata (`tags` / `provenance`)\n * canonically equals `existing`'s. `body` and `links` are covered by the content\n * hash; `embeddingRef` is store-derived (not caller metadata) and is deliberately\n * excluded so a same-content re-put is not treated as changed merely because the\n * store already stamped an embedding. Used to keep an identical re-put a no-op\n * without swallowing a genuine metadata revision.\n *\n * Canonicalization never fails for a validated record (`tags`/`provenance` are\n * always plain JSON); a failure is defaulted to a non-matching sentinel so the\n * write flows to `applyUpdate` (which re-validates) rather than silently\n * no-op-ing on an un-canonicalizable value.\n */\n private _isMutableMetadataUnchanged(\n existing: IMemoryRecord<unknown>,\n incoming: IMemoryRecord<unknown>\n ): boolean {\n const key = (record: IMemoryRecord<unknown>): string =>\n this._hasher\n .canonicalize({ tags: record.envelope.tags, provenance: record.envelope.provenance })\n .orDefault('');\n const existingKey: string = key(existing);\n return existingKey !== '' && existingKey === key(incoming);\n }\n\n private _contentHash(kind: Kind, body: string, links: IMemoryEnvelope['links']): Result<string> {\n return this._hasher.computeHash({ kind, body, links });\n }\n\n /**\n * Stamp the store-computed {@link IMemoryEnvelope.rank} onto a fully-built,\n * fully-stamped record by running the kind's registered {@link RankProjector}.\n * Runs on the SAME resolved (post-merge) record whose `contentHash` was just\n * computed, so `rank` is always consistent with the current body — no separate\n * write path and no consumer write-discipline rule. A no-op pass-through\n * (byte-identical record) when the kind has no projector — the additive,\n * zero-overhead-when-unwired default. The projector is a host callback: a throw\n * is logged at `warn` and the record is stamped with NO `rank` (the field is\n * explicitly cleared, so a throw on an update drops a now-stale prior rank rather\n * than preserving it), so a ranking bug never loses an authoritative write.\n */\n private _stampRank(record: IMemoryRecord<string>): IMemoryRecord<string> {\n const projector: RankProjector | undefined = this._rankProjectors.get(record.envelope.kind);\n if (projector === undefined) {\n return record;\n }\n try {\n const rank: number = projector(record);\n return { envelope: { ...record.envelope, rank }, body: record.body };\n } catch (err) {\n this._warnSwallowed(\n `memory put '${record.envelope.id}': rank projector threw (swallowed; rank cleared): ${String(err)}`\n );\n // Explicitly CLEAR `rank` (not `return record`): on an update the merged\n // envelope carries the prior version's `rank` (the write-policy merge does\n // not touch `rank`), so returning it verbatim would keep a stale value\n // inconsistent with the revised body. Clearing honors the staleness\n // contract — an uncomputable rank means the record sorts last as \"unranked\".\n return { envelope: { ...record.envelope, rank: undefined }, body: record.body };\n }\n }\n\n private _codecFor(kind: Kind): Result<IIdentityCodec> {\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 succeed(codec);\n }\n\n private _policyFor(kind: Kind): IWritePolicy {\n return this._writePolicies.get(kind) ?? this._defaultPolicy;\n }\n\n /**\n * Read and validate the record at `<scope>/<idStem>.md`, returning `undefined`\n * when the scope directory or file is absent. Verifies the on-disk id ↔\n * filename round-trip on every load.\n */\n private _readRecord(scope: MemoryScopeKey, idStem: string): Result<IMemoryRecord<unknown> | undefined> {\n return this._resolveScopeDir(scope).onSuccess((scopeDir) => {\n if (scopeDir === undefined) {\n return succeed(undefined);\n }\n return scopeDir.getChildren().onSuccess((children) => {\n const targetName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n const file: FileTree.IFileTreeFileItem | undefined = children.find(\n (c): c is FileTree.IFileTreeFileItem => c.type === 'file' && c.name === targetName\n );\n if (file === undefined) {\n return succeed(undefined);\n }\n return file\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, file, parsedRecord));\n });\n });\n }\n\n /**\n * Enforce `envelope.id === filename stem`, the codec round-trip, AND that the\n * envelope's own `entityId` agrees with the id decoded from the subtree scope.\n * The round-trip only validates (scope, stem) consistency; the codec derives\n * `entityId` from the scope path and never reads the envelope's `entityId`\n * field, so a tampered/corrupt file whose frontmatter declares a foreign\n * `entityId` would otherwise load undetected — and `entityId` is trusted\n * verbatim downstream (e.g. merge-into re-addressing). Cross-check it here.\n */\n private _verifyLoaded(\n scope: MemoryScopeKey,\n file: FileTree.IFileTreeFileItem,\n record: IMemoryRecord<unknown>\n ): Result<IMemoryRecord<unknown>> {\n if (record.envelope.id !== file.baseName) {\n return fail(\n `memory file '${file.absolutePath}': envelope id '${record.envelope.id}' does not match filename stem '${file.baseName}'`\n );\n }\n return this._codecFor(record.envelope.kind)\n .onSuccess((codec) =>\n codec.verifyRoundTrip(scope, file.baseName).onSuccess(() => codec.decode(scope, file.baseName))\n )\n .withErrorFormat((msg) => `memory file '${file.absolutePath}': ${msg}`)\n .onSuccess((decodedEntityId) => {\n if (decodedEntityId !== record.envelope.entityId) {\n return fail(\n `memory file '${file.absolutePath}': envelope entityId '${record.envelope.entityId}' does not match scope-derived entityId '${decodedEntityId}'`\n );\n }\n return succeed(record);\n });\n }\n\n /**\n * Resolve the directory for a scope, returning `undefined` when it does not\n * exist. Navigation only — does not create. Folds the path segments through\n * `getChildren` so an absent segment short-circuits to `undefined`.\n */\n private _resolveScopeDir(scope: MemoryScopeKey): Result<FileTree.IFileTreeDirectoryItem | undefined> {\n return this._scopeEncoding(scope).onSuccess((encoded) => {\n const segments: string[] = encoded.split('/').filter((s) => s.length > 0);\n return segments.reduce<Result<FileTree.IFileTreeDirectoryItem | undefined>>(\n (acc, segment) =>\n acc.onSuccess((current) => {\n if (current === undefined) {\n return succeed(undefined);\n }\n return current\n .getChildren()\n .onSuccess((children) =>\n succeed(\n children.find(\n (c): c is FileTree.IFileTreeDirectoryItem => c.type === 'directory' && c.name === segment\n )\n )\n );\n }),\n succeed(this._root)\n );\n });\n }\n\n /** Ensure the scope directory exists, creating segments as needed. */\n private _ensureScopeDir(scope: MemoryScopeKey): Result<FileTree.IMutableFileTreeDirectoryItem> {\n return this._scopeEncoding(scope).onSuccess((encoded) => {\n const segments: string[] = encoded.split('/').filter((s) => s.length > 0);\n return segments.reduce<Result<FileTree.IMutableFileTreeDirectoryItem>>(\n (acc, segment) =>\n acc.onSuccess((current) =>\n current.getChildren().onSuccess((children) => {\n const existing: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'directory' && c.name === segment\n );\n if (existing === undefined) {\n return current.createChildDirectory(segment);\n }\n /* c8 ignore next 3 -- defensive: a child of a mutable in-memory/fs tree is itself mutable; the guard protects against a read-only adapter handed in as root */\n if (!FileTree.isMutableDirectoryItem(existing)) {\n return fail(`${existing.absolutePath}: directory is not mutable`);\n }\n return succeed(existing);\n })\n ),\n succeed(this._root)\n );\n });\n }\n\n /** Write (create or overwrite) `<scope>/<idStem>.md` with `raw`. */\n private _writeFile(scope: MemoryScopeKey, idStem: string, raw: string): Result<true> {\n return this._ensureScopeDir(scope).onSuccess((scopeDir) =>\n scopeDir.getChildren().onSuccess((children) => {\n const fileName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n const existing: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'file' && c.name === fileName\n );\n if (existing === undefined) {\n return scopeDir.createChildFile(fileName, raw).onSuccess(() => succeed(true));\n }\n /* c8 ignore next 3 -- defensive: a file in a mutable tree is mutable; guards a read-only adapter */\n if (!FileTree.isMutableFileItem(existing)) {\n return fail(`${existing.absolutePath}: file is not mutable`);\n }\n return existing.setRawContents(raw).onSuccess(() => succeed(true));\n })\n );\n }\n\n /**\n * Physically delete `<scope>/<idStem>.md`. The scope-missing and file-missing\n * guards are unreachable through the callers (`delete` / `_evict` both read the\n * record first, so the directory and file exist) but are kept so a future\n * direct caller degrades loudly rather than silently.\n */\n private _deleteFile(scope: MemoryScopeKey, idStem: string): Result<true> {\n return this._resolveScopeDir(scope).onSuccess((scopeDir) => {\n /* c8 ignore next 3 -- unreachable: callers read the record (hence the scope dir) first */\n if (scopeDir === undefined) {\n return fail(`memory delete: scope '${scope}' not found`);\n }\n const fileName: string = `${idStem}${MEMORY_FILE_EXTENSION}`;\n return scopeDir.getChildren().onSuccess((children) => {\n const file: FileTree.FileTreeItem | undefined = children.find(\n (c) => c.type === 'file' && c.name === fileName\n );\n /* c8 ignore next 3 -- unreachable: callers read the record (hence the file) first */\n if (file === undefined) {\n return fail(`memory delete: file '${fileName}' not found in scope '${scope}'`);\n }\n /* c8 ignore next 3 -- defensive: a file in a mutable tree is mutable; guards a read-only adapter */\n if (!FileTree.isMutableFileItem(file)) {\n return fail(`${file.absolutePath}: file is not mutable`);\n }\n return file.delete().onSuccess(() => succeed(true));\n });\n });\n }\n\n /**\n * Walk the FileTree once and rebuild the index. Also resumes the `seq`\n * counter past the highest persisted `seq` so new writes stay monotonic.\n */\n private _initialIndex(): Result<true> {\n return this._collectEntries(this._root, []).onSuccess((entries) =>\n this._index.rebuild(entries).onSuccess(() => {\n for (const entry of entries) {\n if (entry.record.envelope.seq > this._seq) {\n this._seq = entry.record.envelope.seq;\n }\n }\n return succeed(true);\n })\n );\n }\n\n /** Recursively collect every `.md` record under `dir` (scope = path segments). */\n private _collectEntries(\n dir: FileTree.IFileTreeDirectoryItem,\n scopeSegments: ReadonlyArray<string>\n ): Result<ReadonlyArray<IIndexedMemoryRecord>> {\n return dir.getChildren().onSuccess((children) => {\n const results: Result<ReadonlyArray<IIndexedMemoryRecord>>[] = children.map((child) => {\n if (child.type === 'directory') {\n return this._collectEntries(child, [...scopeSegments, child.name]);\n }\n if (!child.name.endsWith(MEMORY_FILE_EXTENSION) || scopeSegments.length === 0) {\n // Skip non-record files and any record-shaped file sitting at the root\n // (records always live under at least one scope segment).\n return succeed<ReadonlyArray<IIndexedMemoryRecord>>([]);\n }\n const scope: MemoryScopeKey = scopeSegments.join('/') as MemoryScopeKey;\n return child\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, child, parsedRecord))\n .onSuccess((verified) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>([{ scope, record: verified }])\n );\n });\n return mapResults(results).onSuccess((perChild) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>(perChild.flat())\n );\n });\n }\n}\n"]}
|