@fgv/ts-agent-memory 5.1.0-48 → 5.1.0-49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/packlets/retrieve/linkTraversalRetriever.js +1 -1
- package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/dist/packlets/retrieve/retriever.js +11 -5
- package/dist/packlets/retrieve/retriever.js.map +1 -1
- package/dist/packlets/retrieve/structuredFilterRetriever.js +27 -5
- package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/dist/packlets/retrieve/tagRetriever.js +1 -1
- package/dist/packlets/retrieve/tagRetriever.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/dist/packlets/store/fileTreeMemoryStore.js +100 -1
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/types/envelope.js.map +1 -1
- package/dist/ts-agent-memory.d.ts +134 -13
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/lib/packlets/retrieve/recencyRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/lib/packlets/retrieve/retriever.d.ts +26 -7
- package/lib/packlets/retrieve/retriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/retriever.js +11 -5
- package/lib/packlets/retrieve/retriever.js.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts +26 -4
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.js +27 -5
- package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/lib/packlets/retrieve/tagRetriever.d.ts +1 -1
- package/lib/packlets/retrieve/tagRetriever.js +1 -1
- package/lib/packlets/retrieve/tagRetriever.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +69 -0
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +99 -0
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/types/envelope.d.ts +11 -0
- package/lib/packlets/types/envelope.d.ts.map +1 -1
- package/lib/packlets/types/envelope.js.map +1 -1
- package/package.json +7 -7
|
@@ -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,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAEL,mBAAmB,EAUnB,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,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAsC,WAAW,EAAE,MAAM,UAAU,CAAC;AAgB3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,sDAAsD;AACtD,MAAM,qBAAqB,GAAW,KAAK,CAAC;AAwZ5C;;;;;;;;;;;;;GAaG;AAC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identifier: MIT\n */\n\nimport { Hash, Logging, Result, fail, mapResults, mapSuccess, 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 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 { VectorMaintenance } from './vectorMaintenance';\nimport { IIndexedMemoryRecord, IMemoryIndex, MemoryIndex } from '../index';\nimport {\n IMemoryObservationRecord,\n IMemoryObserver,\n MemoryEmbedOutcome,\n MemoryObservationOutcome,\n MemoryObservationPhase\n} from '../observe';\nimport {\n FragmentEmbedder,\n IFragmentVectorIndex,\n IMemoryRecordSource,\n IScopedMemoryRecord,\n IVectorIndex,\n MemoryEmbedder\n} 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 * Policy for how {@link FileTreeMemoryStore.create}'s initial vault walk reacts\n * to a record that fails to parse or validate.\n *\n * - `'fail'` (the default) — one unreadable record fails the whole open. The\n * walk collapses per-record results with `mapResults`, so any single failure\n * aborts `create()`. This is the historical behavior, preserved byte-for-byte.\n * - `'skip'` — an unreadable record is quarantined (not indexed) rather than\n * failing the open. Every record that DOES parse loads normally; each skip is\n * logged at `warn` and surfaced structurally on\n * {@link FileTreeMemoryStore.skippedRecords}. The offending file is never\n * deleted or mutated, so a later open (after the body converter is fixed)\n * re-indexes it. A vault holds every kind in one store, so a required-field\n * migration on one kind must not make every other record unreadable.\n * @public\n */\nexport type MemoryRecordErrorMode = 'skip' | 'fail';\n\n/**\n * A record that {@link FileTreeMemoryStore.create} could not load and\n * quarantined (only produced in {@link MemoryRecordErrorMode | `'skip'` mode}).\n * The `path` identifies WHICH record was skipped so a host can repair it.\n * @public\n */\nexport interface ISkippedRecord {\n /** The record file's path within the vault (`<scope>/<filename>.md`). */\n readonly path: string;\n /** The scope the record lives under (its parent directory path). */\n readonly scope: MemoryScopeKey;\n /** The parse/validation failure message (includes the record path). */\n readonly error: string;\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},\n * **filtered to the kinds {@link IMemoryStore.embedsKind | embedsKind} reports** —\n * this source exists to feed the record vector index, so a kind excluded from\n * that index is excluded here too, and a reopen does not re-embed records the\n * index will never return. With no\n * {@link IFileTreeMemoryStoreCreateParams.embedKinds | embedKinds} declaration\n * every kind participates and the filter is the identity. `listScoped` itself is\n * **not** filtered and remains the whole-vault surface.\n *\n * The 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 * The EFFECTIVE {@link DedupScope} for `kind` — the granularity at which a\n * write for this kind deduplicates against the existing vault.\n *\n * @remarks\n * This is a **read accessor over the store's already-injected write policies**,\n * and it is the single place any caller — the store's own write path included —\n * asks what a kind's dedup granularity is. It resolves the full chain the store\n * applies on write: the kind's registered {@link IWritePolicy}, falling back to\n * the store's default policy, then that policy's\n * {@link IWritePolicy.dedupScope | dedupScope}, falling back to\n * {@link DEFAULT_DEDUP_SCOPE}. Note the store's default policy is a\n * {@link KnowledgeLwwPolicy}, which declares `'content'` — so a kind with NO\n * registered policy resolves to `'content'`, not to `DEFAULT_DEDUP_SCOPE`.\n *\n * It exists so a caller that must agree with the store about dedup granularity\n * — notably the ingest orchestrator's stage-4 layer-1 exact match — can read the\n * declaration through this seam instead of being handed a second copy of the\n * policy map. A second declaration site is precisely the defect this accessor\n * was added to remove.\n *\n * Deliberately synchronous, total, and NOT `Result`-returning: it reads\n * constructor-injected configuration, touches no I/O, and cannot fail (every\n * link in the fallback chain has a total default). It exposes only the scope,\n * never the {@link IWritePolicy} itself, so it can never become a back door for\n * invoking admission or merge logic out of band.\n */\n dedupScopeFor(kind: Kind): DedupScope;\n\n /**\n * Whether records of `kind` participate in the **record-granular** vector index.\n *\n * @remarks\n * A read accessor over the store's injected {@link IFileTreeMemoryStoreCreateParams.embedKinds | embedKinds}\n * declaration, in the same spirit as {@link IMemoryStore.dedupScopeFor} — one\n * place to ask, so the store's write path and any caller reasoning about index\n * coverage cannot disagree. `true` for every kind when no declaration was made.\n *\n * **This is distinct from a {@link MemoryEmbedder} decline, and the difference is\n * cost.** An embedder that returns `undefined` has already been called: the\n * round trip is paid, and on a locally-hosted model that round trip is the\n * expense. A kind excluded here is never handed to the embedder at all. The\n * decline makes the intent *expressible*; this makes it *free*.\n *\n * Deliberately synchronous, total, and NOT `Result`-returning: it reads\n * constructor-injected configuration, touches no I/O, and cannot fail.\n */\n embedsKind(kind: Kind): boolean;\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 /**\n * The kinds whose records participate in the **record-granular** vector index.\n *\n * @remarks\n * **Absent means every kind participates**, which is the pre-existing behavior —\n * so omitting this is byte-identical to before it existed. Supplying it makes the\n * set an allowlist: a kind outside it is never handed to the {@link MemoryEmbedder}\n * on write, and is omitted from {@link IMemoryStore.asRecordSource | asRecordSource},\n * so a rebuild driven from this store does not pay for it either.\n *\n * Two costs motivate it, and the second is the one that is easy to miss:\n *\n * - **Embedder work on the critical path.** Embed-on-write is synchronous with\n * the write. A bookkeeping row — a status, a counter, a lease — that no query\n * will ever return still pays a full embedding round trip, and on a\n * locally-hosted model the first call after a restart pays a cold model load\n * on top.\n * - **Un-queried kinds crowd the `topK` window.** `IVectorIndex.query` applies\n * `topK` *before* any kind filter the retriever adds, so vectors that can never\n * be returned still occupy candidate slots. Over-fetching to compensate hides\n * this until the un-queried kinds start scoring well — at which point recall is\n * silently lost. Restricting what is indexed fixes the recall problem, not just\n * the cost.\n *\n * Applies to the record-granular path only. The fragment path\n * ({@link IFileTreeMemoryStoreCreateParams.fragmentIndex | fragmentIndex} /\n * `fragmentEmbedder`) is independent and unaffected — a kind may legitimately be\n * fragment-embedded and not record-embedded, which is the right shape for a long\n * document whose whole body exceeds the model's context.\n */\n readonly embedKinds?: ReadonlySet<Kind>;\n /** Default codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /**\n * Optional derived-index implementation. Defaults to a fresh {@link MemoryIndex} —\n * omitting this parameter is byte-identical to the store's behavior before the\n * parameter existed. When supplied, the store uses it for EVERY index operation\n * it performs and never holds a second index, so an injected index is the store's\n * only view of its own records:\n *\n * - `rebuild` — once, from the initial vault walk in `create()`.\n * - `patch` — on every persisted write, delete, version invalidation, and\n * cap-cull eviction.\n * - `entries` — behind {@link IMemoryStore.list | list} /\n * {@link IMemoryStore.listScoped | listScoped}, the keyed temporal reads, the\n * write path's content-hash dedup and write-policy admission cohort, AND the\n * temporal (versioned) write and delete paths, which resolve an entity's\n * version history entirely from the index.\n *\n * That last group is the one to weigh before injecting anything other than a\n * pass-through decorator: an index that filters, reorders, or otherwise reshapes\n * `entries()` changes WRITE semantics, not just what reads return. Concretely,\n * on a versioned kind the store derives an entity's whole version history from\n * `entries()` filtered by scope, and that derivation decides which version a\n * `put` treats as current (so what it dedups against and what it merges its\n * patch over), which prior versions it stamps `invalid_at` on, what the\n * admission cohort is, and which versions a `delete` tombstones. An index that\n * hides a version makes it invisible to all of those — the FileTree still holds\n * it, but the store will not supersede, invalidate, or tombstone it. On flat\n * kinds the same reshaping changes what dedups and what a cap-cull policy\n * evicts. A faithful delegating decorator — the intended use below — has no such\n * effect. Note the store's keyed reads ({@link IMemoryStore.get | get} on a flat\n * kind, and {@link IMemoryStore.getById | getById}) go to the FileTree, not the\n * index; the FileTree remains the source of truth and the index stays a derived\n * view.\n *\n * @remarks\n * **This is an instrumentation seam, NOT a resident-memory fix.** The intended\n * use is wrapping the shipped {@link MemoryIndex} in a decorator that counts and\n * times the calls the store makes — resident bytes by kind, open cost against\n * vault size, where the curve actually bends — so a decision about a partial-read\n * redesign can be driven by measurements instead of estimates.\n *\n * It does NOT lower the store's resident-memory ceiling, and injecting a\n * \"persisted\" or \"lazy\" index will not change that. {@link IMemoryIndex}'s read\n * surface returns whole records by construction: `entries()` yields\n * {@link IIndexedMemoryRecord}s and `byKind` / `byTag` / `byRecency` / `byRank`\n * yield `IMemoryRecord<unknown>` — `{ envelope, body }` pairs with the body\n * materialized. Any implementation satisfying the current contract must therefore\n * be able to produce every body on demand. An injected index changes WHERE records\n * come from; it does not change WHETHER bodies are held. Lowering the ceiling\n * requires a partial-read (id-or-envelope-only) redesign of `IMemoryIndex` itself,\n * which is separate, breaking, design-first work and is deliberately not part of\n * this seam.\n */\n readonly index?: IMemoryIndex;\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 * Optional fragment-granular vector index for sub-document semantic search.\n * Wired together with\n * {@link IFileTreeMemoryStoreCreateParams.fragmentEmbedder | fragmentEmbedder}:\n * when both are present the store chunks + embeds each written record and\n * maintains the fragment index on `put` / `delete` / cap-cull eviction — the\n * \"discovery\" half of a search-then-read contract, queried through a\n * {@link FragmentSemanticRetriever}. Independent of the record-granular\n * {@link IFileTreeMemoryStoreCreateParams.vectorIndex | vectorIndex} pair: a\n * store may wire record vectors, fragment vectors, both, or neither. Absent (or\n * `fragmentEmbedder` absent) → no fragment work happens and the store behaves\n * byte-identically (the additive, zero-overhead-when-unwired default).\n */\n readonly fragmentIndex?: IFragmentVectorIndex;\n /**\n * Optional fragment embedder applied to each record on write, wired together\n * with {@link IFileTreeMemoryStoreCreateParams.fragmentIndex | fragmentIndex}.\n * The consumer owns the chunking policy (window size, overlap) and the embedding\n * call; the store stays chunking- and embedder-agnostic. Fragment index\n * maintenance is **best-effort**, exactly like the record-vector path: a failed\n * (or throwing) `fragmentEmbedder` / `addFragments` / `remove` is logged at\n * `warn` and the record operation still succeeds — the fragment index is a\n * derived view a later `rebuild` reconciles.\n */\n readonly fragmentEmbedder?: FragmentEmbedder;\n /**\n * How the initial vault walk reacts to a record that fails to parse or\n * validate. Defaults to `'fail'` — one bad record fails the whole open, the\n * historical behavior, preserved byte-for-byte. Set `'skip'` to quarantine\n * unreadable records instead: valid records still load, each skip is logged\n * at `warn` and surfaced on {@link FileTreeMemoryStore.skippedRecords}, and\n * the offending file is left untouched for a later (post-fix) re-index. See\n * {@link MemoryRecordErrorMode}.\n */\n readonly onRecordError?: MemoryRecordErrorMode;\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 * What the record-granular index did about this write, for the `'write'`\n * observation. Absent whenever no outcome is being reported — nothing wired,\n * a dedup no-op that attempted nothing, or a failed write. See\n * `MemoryEmbedOutcome`.\n */\n readonly embed?: MemoryEmbedOutcome;\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 /** `undefined` = no declaration = every kind participates in the vector index. */\n readonly embedKinds: ReadonlySet<Kind> | undefined;\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 readonly fragmentIndex?: IFragmentVectorIndex;\n readonly fragmentEmbedder?: FragmentEmbedder;\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 /** `undefined` = no declaration = every kind participates. */\n private readonly _embedKinds: ReadonlySet<Kind> | undefined;\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 /** Record- and fragment-vector maintenance; every operation is best-effort. */\n private readonly _vectors: VectorMaintenance;\n private readonly _logger: Logging.ILogger;\n /**\n * Records the initial walk could not load. Populated during `create()` in\n * {@link MemoryRecordErrorMode | `'skip'` mode}; empty otherwise.\n */\n private readonly _skippedRecords: ISkippedRecord[];\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._embedKinds = params.embedKinds ?? undefined;\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._vectors = new VectorMaintenance({\n vectorIndex: params.vectorIndex,\n embed: params.embed,\n fragmentIndex: params.fragmentIndex,\n fragmentEmbedder: params.fragmentEmbedder,\n warn: (message) => this._warnSwallowed(message),\n embedsKind: (kind) => this.embedsKind(kind)\n });\n this._skippedRecords = [];\n this._seq = 0;\n this._observationSeq = 0;\n this._writeTail = Promise.resolve();\n }\n\n /**\n * Records the initial vault walk could not parse or validate and quarantined\n * (not indexed). Non-empty only when the store was opened with\n * {@link MemoryRecordErrorMode | `onRecordError: 'skip'`} AND at least one\n * record failed to load. Each entry identifies the offending file so a host\n * can repair it; the file itself is never deleted or mutated, so a later open\n * (after the body converter is fixed) re-indexes it.\n */\n public get skippedRecords(): ReadonlyArray<ISkippedRecord> {\n return this._skippedRecords;\n }\n\n /**\n * Family-convention factory. Resolves the derived index (the caller's\n * {@link IFileTreeMemoryStoreCreateParams.index | index} when supplied, a fresh\n * {@link MemoryIndex} otherwise) and a default LWW policy, then performs an\n * initial FileTree walk so an existing vault is indexed (and the `seq` counter\n * resumes past the highest persisted `seq`).\n */\n public static create(params: IFileTreeMemoryStoreCreateParams): Result<FileTreeMemoryStore> {\n return KnowledgeLwwPolicy.create().onSuccess((defaultPolicy) =>\n FileTreeMemoryStore._resolveIndex(params.index).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 embedKinds: params.embedKinds,\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 fragmentIndex: params.fragmentIndex,\n fragmentEmbedder: params.fragmentEmbedder\n });\n return store._initialIndex(params.onRecordError ?? 'fail').onSuccess(() => succeed(store));\n })\n );\n }\n\n /**\n * Resolve the derived index for a `create()`: the caller's injected\n * {@link IMemoryIndex} verbatim, or a fresh {@link MemoryIndex} when none was\n * supplied (the default that keeps an omitting caller byte-identical).\n */\n private static _resolveIndex(index: IMemoryIndex | undefined): Result<IMemoryIndex> {\n // Nullish rather than strictly-undefined, matching how every sibling optional\n // param in `create()` handles absence (`params.codecs ?? new Map()`, and so on).\n // A JS caller — or a TS caller arriving through an `unknown` escape hatch —\n // passing `null` otherwise gets `null` installed as the store's index and fails\n // later inside `entries()` with a message that names neither the param nor the\n // cause.\n return index ? succeed(index) : MemoryIndex.create();\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 {\n // Filtered to the kinds that participate in the record vector index. This\n // source exists to drive `IVectorIndex` rebuilds, so a kind excluded from the\n // index has no business being re-embedded on open — which is where the cost\n // is worst, since a rebuild embeds the whole vault serially. With no\n // `embedKinds` declaration every kind passes and this is the identity filter.\n list: async (): Promise<Result<ReadonlyArray<IScopedMemoryRecord>>> =>\n (await this.listScoped()).onSuccess((scoped: ReadonlyArray<IScopedMemoryRecord>) =>\n succeed(scoped.filter((s) => this.embedsKind(s.record.envelope.kind)))\n )\n };\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 embed: result.isSuccess() ? result.value.embed : 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 readonly embed?: MemoryEmbedOutcome;\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 embed: details.embed\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 // Read through the public accessor so the write path and every external\n // caller (the ingest orchestrator's layer-1) resolve dedup granularity from\n // ONE place — there is no second declaration site.\n const dedupScope: DedupScope = this.dedupScopeFor(record.envelope.kind);\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._vectors.embedOnWrite(built, scope))\n .thenOnSuccess(async (embedded) =>\n (await this._vectors.embedFragmentsOnWrite(embedded.record, scope)).onSuccess((withFragments) =>\n succeed({ ...embedded, record: withFragments })\n )\n )\n .onSuccess((embedded) =>\n this._persist(embedded.record, scope, idStem).onSuccess((persisted) =>\n succeed({ persisted, stale: embedded.stale, embed: embedded.embed })\n )\n )\n .thenOnSuccess(async ({ persisted, stale, embed }) => {\n // Everything after the authoritative `_persist` commit is best-effort and\n // never turns a committed write into a `Failure`:\n // - a stale vector superseded by a decline is pruned here rather than at\n // the point of the decline, because a `_persist` that fails leaves the\n // PREVIOUS content on disk — content that vector is still an accurate\n // embedding of. Pruning early would delete a correct vector on behalf\n // of a write that never landed;\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 await this._vectors.pruneStaleVector(stale);\n const evicted: ReadonlyArray<MemoryId> = this._applyEvictions(decision, scope);\n await this._vectors.removeEvictedVectors(evicted, scope);\n return succeed({ record: persisted, evicted, embed });\n });\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 * 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._vectors.removeAll({ 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 // Same single-owner read as the flat path (see `_writeResolved`).\n const dedupScope: DedupScope = this.dedupScopeFor(kind);\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._vectors.embedOnWrite(built, scope))\n .thenOnSuccess(async (embedded) =>\n (await this._vectors.embedFragmentsOnWrite(embedded.record, scope)).onSuccess(\n (withFragments) => succeed({ ...embedded, record: withFragments })\n )\n )\n .onSuccess((embedded) =>\n this._persist(embedded.record, scope, versionStem).onSuccess((persisted) =>\n succeed({ persisted, stale: embedded.stale, embed: embedded.embed })\n )\n )\n .onSuccess(({ persisted, stale, embed }) =>\n this._invalidateCurrents(scope, priorCurrents, validAt, now).onSuccess(() =>\n succeed({ persisted, stale, embed })\n )\n )\n // Post-commit and best-effort, exactly as on the flat path.\n .thenOnSuccess(async ({ persisted, stale, embed }) => {\n await this._vectors.pruneStaleVector(stale);\n return succeed({ record: persisted, evicted: [], embed });\n })\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 /** {@inheritDoc IMemoryStore.dedupScopeFor} */\n public dedupScopeFor(kind: Kind): DedupScope {\n return this._policyFor(kind).dedupScope ?? DEFAULT_DEDUP_SCOPE;\n }\n\n /** {@inheritDoc IMemoryStore.embedsKind} */\n public embedsKind(kind: Kind): boolean {\n // No declaration means every kind participates — the behavior that predates\n // this param, so an existing consumer is unaffected.\n return this._embedKinds === undefined || this._embedKinds.has(kind);\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 * In `'skip'` mode each per-record failure is captured structurally on\n * `this._skippedRecords` (path + scope + path-tagged error) at its failure\n * site and logged at `warn`; the walk keeps every record that loaded.\n */\n private _initialIndex(onRecordError: MemoryRecordErrorMode): Result<true> {\n return this._collectEntries(this._root, [], onRecordError).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 onRecordError: MemoryRecordErrorMode\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], onRecordError);\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 this._loadRecordFile(scope, child, onRecordError);\n });\n // `'skip'` mode: keep every record that parsed, drop the ones that failed\n // in a single pass (each failure is captured on `this._skippedRecords` and\n // warn-logged at its site in `_loadRecordFile`). `.orDefault([])` covers\n // the all-invalid-subtree edge where `mapSuccess` returns Failure because\n // no element succeeded. `'fail'` mode: `mapResults` fails the whole open on\n // any bad record — byte-identical to the historical load path.\n if (onRecordError === 'skip') {\n return succeed<ReadonlyArray<IIndexedMemoryRecord>>(mapSuccess(results).orDefault([]).flat());\n }\n return mapResults(results).onSuccess((perChild) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>(perChild.flat())\n );\n });\n }\n\n /**\n * Load and verify one record file. On failure in `'skip'` mode, records the\n * structured {@link ISkippedRecord} identity (path + scope + path-tagged\n * error) and logs the skip at `warn`; the failure is still returned so the\n * caller's `mapSuccess` drops it from the loaded set. In `'fail'` mode the\n * failure passes through untouched so the historical error is byte-identical.\n */\n private _loadRecordFile(\n scope: MemoryScopeKey,\n child: FileTree.IFileTreeFileItem,\n onRecordError: MemoryRecordErrorMode\n ): Result<ReadonlyArray<IIndexedMemoryRecord>> {\n return child\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, child, parsedRecord))\n .onSuccess((verified) => succeed<ReadonlyArray<IIndexedMemoryRecord>>([{ scope, record: verified }]))\n .onFailure((message) => {\n if (onRecordError === 'skip') {\n const path: string = `${scope}/${child.name}`;\n const error: string = `memory record '${path}': ${message}`;\n this._skippedRecords.push({ path, scope, error });\n this._warnSwallowed(error);\n }\n return fail(message);\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,UAAU,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAEL,mBAAmB,EAUnB,kBAAkB,EAKlB,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAEL,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAsC,WAAW,EAAE,MAAM,UAAU,CAAC;AAgB3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAE7D,sDAAsD;AACtD,MAAM,qBAAqB,GAAW,KAAK,CAAC;AAub5C;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO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;;;;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, mapSuccess, 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 RankProjector,\n Tag,\n isTemporalIdentityCodec,\n isTemporalRecord,\n isVersionCurrent,\n selectCurrentVersion,\n selectVersionAsOf\n} from '../types';\nimport {\n IBodyConverterRegistry as IRegistry,\n parseMemoryFile,\n serializeMemoryFile,\n splitFrontmatter\n} from '../converters';\nimport { VectorMaintenance } from './vectorMaintenance';\nimport { IIndexedMemoryRecord, IMemoryIndex, MemoryIndex } from '../index';\nimport {\n IMemoryObservationRecord,\n IMemoryObserver,\n MemoryEmbedOutcome,\n MemoryObservationOutcome,\n MemoryObservationPhase\n} from '../observe';\nimport {\n FragmentEmbedder,\n IFragmentVectorIndex,\n IMemoryRecordSource,\n IScopedMemoryRecord,\n IVectorIndex,\n MemoryEmbedder\n} 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 * Policy for how {@link FileTreeMemoryStore.create}'s initial vault walk reacts\n * to a record that fails to parse or validate.\n *\n * - `'fail'` (the default) — one unreadable record fails the whole open. The\n * walk collapses per-record results with `mapResults`, so any single failure\n * aborts `create()`. This is the historical behavior, preserved byte-for-byte.\n * - `'skip'` — an unreadable record is quarantined (not indexed) rather than\n * failing the open. Every record that DOES parse loads normally; each skip is\n * logged at `warn` and surfaced structurally on\n * {@link FileTreeMemoryStore.skippedRecords}. The offending file is never\n * deleted or mutated, so a later open (after the body converter is fixed)\n * re-indexes it. A vault holds every kind in one store, so a required-field\n * migration on one kind must not make every other record unreadable.\n * @public\n */\nexport type MemoryRecordErrorMode = 'skip' | 'fail';\n\n/**\n * A record that {@link FileTreeMemoryStore.create} could not load and\n * quarantined (only produced in {@link MemoryRecordErrorMode | `'skip'` mode}).\n * The `path` identifies WHICH record was skipped so a host can repair it.\n * @public\n */\nexport interface ISkippedRecord {\n /** The record file's path within the vault (`<scope>/<filename>.md`). */\n readonly path: string;\n /** The scope the record lives under (its parent directory path). */\n readonly scope: MemoryScopeKey;\n /** The parse/validation failure message (includes the record path). */\n readonly error: string;\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},\n * **filtered to the kinds {@link IMemoryStore.embedsKind | embedsKind} reports** —\n * this source exists to feed the record vector index, so a kind excluded from\n * that index is excluded here too, and a reopen does not re-embed records the\n * index will never return. With no\n * {@link IFileTreeMemoryStoreCreateParams.embedKinds | embedKinds} declaration\n * every kind participates and the filter is the identity. `listScoped` itself is\n * **not** filtered and remains the whole-vault surface.\n *\n * The 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 * The EFFECTIVE {@link DedupScope} for `kind` — the granularity at which a\n * write for this kind deduplicates against the existing vault.\n *\n * @remarks\n * This is a **read accessor over the store's already-injected write policies**,\n * and it is the single place any caller — the store's own write path included —\n * asks what a kind's dedup granularity is. It resolves the full chain the store\n * applies on write: the kind's registered {@link IWritePolicy}, falling back to\n * the store's default policy, then that policy's\n * {@link IWritePolicy.dedupScope | dedupScope}, falling back to\n * {@link DEFAULT_DEDUP_SCOPE}. Note the store's default policy is a\n * {@link KnowledgeLwwPolicy}, which declares `'content'` — so a kind with NO\n * registered policy resolves to `'content'`, not to `DEFAULT_DEDUP_SCOPE`.\n *\n * It exists so a caller that must agree with the store about dedup granularity\n * — notably the ingest orchestrator's stage-4 layer-1 exact match — can read the\n * declaration through this seam instead of being handed a second copy of the\n * policy map. A second declaration site is precisely the defect this accessor\n * was added to remove.\n *\n * Deliberately synchronous, total, and NOT `Result`-returning: it reads\n * constructor-injected configuration, touches no I/O, and cannot fail (every\n * link in the fallback chain has a total default). It exposes only the scope,\n * never the {@link IWritePolicy} itself, so it can never become a back door for\n * invoking admission or merge logic out of band.\n */\n dedupScopeFor(kind: Kind): DedupScope;\n\n /**\n * Whether records of `kind` participate in the **record-granular** vector index.\n *\n * @remarks\n * A read accessor over the store's injected {@link IFileTreeMemoryStoreCreateParams.embedKinds | embedKinds}\n * declaration, in the same spirit as {@link IMemoryStore.dedupScopeFor} — one\n * place to ask, so the store's write path and any caller reasoning about index\n * coverage cannot disagree. `true` for every kind when no declaration was made.\n *\n * **This is distinct from a {@link MemoryEmbedder} decline, and the difference is\n * cost.** An embedder that returns `undefined` has already been called: the\n * round trip is paid, and on a locally-hosted model that round trip is the\n * expense. A kind excluded here is never handed to the embedder at all. The\n * decline makes the intent *expressible*; this makes it *free*.\n *\n * Deliberately synchronous, total, and NOT `Result`-returning: it reads\n * constructor-injected configuration, touches no I/O, and cannot fail.\n */\n embedsKind(kind: Kind): boolean;\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 * Re-apply the kind's {@link RankProjector} to every record of `kind` already\n * in the store, restamping {@link IMemoryEnvelope.rank}. Returns the number of\n * records whose `rank` actually changed.\n *\n * @remarks\n * **This exists because `rank` is otherwise new-store-only, and fails in a way\n * that looks like it works.** The projector runs on the write path only, so\n * registering one against a populated store ranks nothing already written —\n * and because an absent `rank` sorts *last*, every pre-registration record\n * lands below every post-registration one no matter what the projector would\n * have scored it. The ordering is not merely partial; it is **inverted with\n * respect to the projector's own intent**, with no failure anywhere to say so.\n *\n * Deliberately **does not** touch `created` / `updated` / `seq`, and fires no\n * `'write'` observation. Routing a reconcile through {@link IMemoryStore.put}\n * would bump transaction time on every record — trading a wrong `rank` order\n * for a wrong recency order, and flooding any wired observer with writes that\n * are not writes. The body is re-serialized verbatim from the file's own\n * bytes; only the envelope's `rank` moves.\n *\n * Fails loudly if `kind` has no registered projector: asking to reconcile a\n * kind you never configured is a caller error, not a no-op.\n *\n * **Not atomic, and safe for it.** A failure part-way leaves earlier records\n * restamped. That is benign because restamping is idempotent — re-running\n * converges — which is also why no report shape is offered here. A count is\n * enough.\n */\n reconcileRank(kind: Kind): Promise<Result<number>>;\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 /**\n * The kinds whose records participate in the **record-granular** vector index.\n *\n * @remarks\n * **Absent means every kind participates**, which is the pre-existing behavior —\n * so omitting this is byte-identical to before it existed. Supplying it makes the\n * set an allowlist: a kind outside it is never handed to the {@link MemoryEmbedder}\n * on write, and is omitted from {@link IMemoryStore.asRecordSource | asRecordSource},\n * so a rebuild driven from this store does not pay for it either.\n *\n * Two costs motivate it, and the second is the one that is easy to miss:\n *\n * - **Embedder work on the critical path.** Embed-on-write is synchronous with\n * the write. A bookkeeping row — a status, a counter, a lease — that no query\n * will ever return still pays a full embedding round trip, and on a\n * locally-hosted model the first call after a restart pays a cold model load\n * on top.\n * - **Un-queried kinds crowd the `topK` window.** `IVectorIndex.query` applies\n * `topK` *before* any kind filter the retriever adds, so vectors that can never\n * be returned still occupy candidate slots. Over-fetching to compensate hides\n * this until the un-queried kinds start scoring well — at which point recall is\n * silently lost. Restricting what is indexed fixes the recall problem, not just\n * the cost.\n *\n * Applies to the record-granular path only. The fragment path\n * ({@link IFileTreeMemoryStoreCreateParams.fragmentIndex | fragmentIndex} /\n * `fragmentEmbedder`) is independent and unaffected — a kind may legitimately be\n * fragment-embedded and not record-embedded, which is the right shape for a long\n * document whose whole body exceeds the model's context.\n */\n readonly embedKinds?: ReadonlySet<Kind>;\n /** Default codec for kinds without an explicit entry. */\n readonly defaultCodec?: IIdentityCodec;\n /**\n * Optional derived-index implementation. Defaults to a fresh {@link MemoryIndex} —\n * omitting this parameter is byte-identical to the store's behavior before the\n * parameter existed. When supplied, the store uses it for EVERY index operation\n * it performs and never holds a second index, so an injected index is the store's\n * only view of its own records:\n *\n * - `rebuild` — once, from the initial vault walk in `create()`.\n * - `patch` — on every persisted write, delete, version invalidation, and\n * cap-cull eviction.\n * - `entries` — behind {@link IMemoryStore.list | list} /\n * {@link IMemoryStore.listScoped | listScoped}, the keyed temporal reads, the\n * write path's content-hash dedup and write-policy admission cohort, AND the\n * temporal (versioned) write and delete paths, which resolve an entity's\n * version history entirely from the index.\n *\n * That last group is the one to weigh before injecting anything other than a\n * pass-through decorator: an index that filters, reorders, or otherwise reshapes\n * `entries()` changes WRITE semantics, not just what reads return. Concretely,\n * on a versioned kind the store derives an entity's whole version history from\n * `entries()` filtered by scope, and that derivation decides which version a\n * `put` treats as current (so what it dedups against and what it merges its\n * patch over), which prior versions it stamps `invalid_at` on, what the\n * admission cohort is, and which versions a `delete` tombstones. An index that\n * hides a version makes it invisible to all of those — the FileTree still holds\n * it, but the store will not supersede, invalidate, or tombstone it. On flat\n * kinds the same reshaping changes what dedups and what a cap-cull policy\n * evicts. A faithful delegating decorator — the intended use below — has no such\n * effect. Note the store's keyed reads ({@link IMemoryStore.get | get} on a flat\n * kind, and {@link IMemoryStore.getById | getById}) go to the FileTree, not the\n * index; the FileTree remains the source of truth and the index stays a derived\n * view.\n *\n * @remarks\n * **This is an instrumentation seam, NOT a resident-memory fix.** The intended\n * use is wrapping the shipped {@link MemoryIndex} in a decorator that counts and\n * times the calls the store makes — resident bytes by kind, open cost against\n * vault size, where the curve actually bends — so a decision about a partial-read\n * redesign can be driven by measurements instead of estimates.\n *\n * It does NOT lower the store's resident-memory ceiling, and injecting a\n * \"persisted\" or \"lazy\" index will not change that. {@link IMemoryIndex}'s read\n * surface returns whole records by construction: `entries()` yields\n * {@link IIndexedMemoryRecord}s and `byKind` / `byTag` / `byRecency` / `byRank`\n * yield `IMemoryRecord<unknown>` — `{ envelope, body }` pairs with the body\n * materialized. Any implementation satisfying the current contract must therefore\n * be able to produce every body on demand. An injected index changes WHERE records\n * come from; it does not change WHETHER bodies are held. Lowering the ceiling\n * requires a partial-read (id-or-envelope-only) redesign of `IMemoryIndex` itself,\n * which is separate, breaking, design-first work and is deliberately not part of\n * this seam.\n */\n readonly index?: IMemoryIndex;\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 * Optional fragment-granular vector index for sub-document semantic search.\n * Wired together with\n * {@link IFileTreeMemoryStoreCreateParams.fragmentEmbedder | fragmentEmbedder}:\n * when both are present the store chunks + embeds each written record and\n * maintains the fragment index on `put` / `delete` / cap-cull eviction — the\n * \"discovery\" half of a search-then-read contract, queried through a\n * {@link FragmentSemanticRetriever}. Independent of the record-granular\n * {@link IFileTreeMemoryStoreCreateParams.vectorIndex | vectorIndex} pair: a\n * store may wire record vectors, fragment vectors, both, or neither. Absent (or\n * `fragmentEmbedder` absent) → no fragment work happens and the store behaves\n * byte-identically (the additive, zero-overhead-when-unwired default).\n */\n readonly fragmentIndex?: IFragmentVectorIndex;\n /**\n * Optional fragment embedder applied to each record on write, wired together\n * with {@link IFileTreeMemoryStoreCreateParams.fragmentIndex | fragmentIndex}.\n * The consumer owns the chunking policy (window size, overlap) and the embedding\n * call; the store stays chunking- and embedder-agnostic. Fragment index\n * maintenance is **best-effort**, exactly like the record-vector path: a failed\n * (or throwing) `fragmentEmbedder` / `addFragments` / `remove` is logged at\n * `warn` and the record operation still succeeds — the fragment index is a\n * derived view a later `rebuild` reconciles.\n */\n readonly fragmentEmbedder?: FragmentEmbedder;\n /**\n * How the initial vault walk reacts to a record that fails to parse or\n * validate. Defaults to `'fail'` — one bad record fails the whole open, the\n * historical behavior, preserved byte-for-byte. Set `'skip'` to quarantine\n * unreadable records instead: valid records still load, each skip is logged\n * at `warn` and surfaced on {@link FileTreeMemoryStore.skippedRecords}, and\n * the offending file is left untouched for a later (post-fix) re-index. See\n * {@link MemoryRecordErrorMode}.\n */\n readonly onRecordError?: MemoryRecordErrorMode;\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 * What the record-granular index did about this write, for the `'write'`\n * observation. Absent whenever no outcome is being reported — nothing wired,\n * a dedup no-op that attempted nothing, or a failed write. See\n * `MemoryEmbedOutcome`.\n */\n readonly embed?: MemoryEmbedOutcome;\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 /** `undefined` = no declaration = every kind participates in the vector index. */\n readonly embedKinds: ReadonlySet<Kind> | undefined;\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 readonly fragmentIndex?: IFragmentVectorIndex;\n readonly fragmentEmbedder?: FragmentEmbedder;\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 /** `undefined` = no declaration = every kind participates. */\n private readonly _embedKinds: ReadonlySet<Kind> | undefined;\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 /** Record- and fragment-vector maintenance; every operation is best-effort. */\n private readonly _vectors: VectorMaintenance;\n private readonly _logger: Logging.ILogger;\n /**\n * Records the initial walk could not load. Populated during `create()` in\n * {@link MemoryRecordErrorMode | `'skip'` mode}; empty otherwise.\n */\n private readonly _skippedRecords: ISkippedRecord[];\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._embedKinds = params.embedKinds ?? undefined;\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._vectors = new VectorMaintenance({\n vectorIndex: params.vectorIndex,\n embed: params.embed,\n fragmentIndex: params.fragmentIndex,\n fragmentEmbedder: params.fragmentEmbedder,\n warn: (message) => this._warnSwallowed(message),\n embedsKind: (kind) => this.embedsKind(kind)\n });\n this._skippedRecords = [];\n this._seq = 0;\n this._observationSeq = 0;\n this._writeTail = Promise.resolve();\n }\n\n /**\n * Records the initial vault walk could not parse or validate and quarantined\n * (not indexed). Non-empty only when the store was opened with\n * {@link MemoryRecordErrorMode | `onRecordError: 'skip'`} AND at least one\n * record failed to load. Each entry identifies the offending file so a host\n * can repair it; the file itself is never deleted or mutated, so a later open\n * (after the body converter is fixed) re-indexes it.\n */\n public get skippedRecords(): ReadonlyArray<ISkippedRecord> {\n return this._skippedRecords;\n }\n\n /**\n * Family-convention factory. Resolves the derived index (the caller's\n * {@link IFileTreeMemoryStoreCreateParams.index | index} when supplied, a fresh\n * {@link MemoryIndex} otherwise) and a default LWW policy, then performs an\n * initial FileTree walk so an existing vault is indexed (and the `seq` counter\n * resumes past the highest persisted `seq`).\n */\n public static create(params: IFileTreeMemoryStoreCreateParams): Result<FileTreeMemoryStore> {\n return KnowledgeLwwPolicy.create().onSuccess((defaultPolicy) =>\n FileTreeMemoryStore._resolveIndex(params.index).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 embedKinds: params.embedKinds,\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 fragmentIndex: params.fragmentIndex,\n fragmentEmbedder: params.fragmentEmbedder\n });\n return store._initialIndex(params.onRecordError ?? 'fail').onSuccess(() => succeed(store));\n })\n );\n }\n\n /**\n * Resolve the derived index for a `create()`: the caller's injected\n * {@link IMemoryIndex} verbatim, or a fresh {@link MemoryIndex} when none was\n * supplied (the default that keeps an omitting caller byte-identical).\n */\n private static _resolveIndex(index: IMemoryIndex | undefined): Result<IMemoryIndex> {\n // Nullish rather than strictly-undefined, matching how every sibling optional\n // param in `create()` handles absence (`params.codecs ?? new Map()`, and so on).\n // A JS caller — or a TS caller arriving through an `unknown` escape hatch —\n // passing `null` otherwise gets `null` installed as the store's index and fails\n // later inside `entries()` with a message that names neither the param nor the\n // cause.\n return index ? succeed(index) : MemoryIndex.create();\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 {\n // Filtered to the kinds that participate in the record vector index. This\n // source exists to drive `IVectorIndex` rebuilds, so a kind excluded from the\n // index has no business being re-embedded on open — which is where the cost\n // is worst, since a rebuild embeds the whole vault serially. With no\n // `embedKinds` declaration every kind passes and this is the identity filter.\n list: async (): Promise<Result<ReadonlyArray<IScopedMemoryRecord>>> =>\n (await this.listScoped()).onSuccess((scoped: ReadonlyArray<IScopedMemoryRecord>) =>\n succeed(scoped.filter((s) => this.embedsKind(s.record.envelope.kind)))\n )\n };\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.reconcileRank} */\n public async reconcileRank(kind: Kind): Promise<Result<number>> {\n return this._enqueue(() => this._reconcileRankLocked(kind));\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 embed: result.isSuccess() ? result.value.embed : 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 readonly embed?: MemoryEmbedOutcome;\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 embed: details.embed\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 // Read through the public accessor so the write path and every external\n // caller (the ingest orchestrator's layer-1) resolve dedup granularity from\n // ONE place — there is no second declaration site.\n const dedupScope: DedupScope = this.dedupScopeFor(record.envelope.kind);\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._vectors.embedOnWrite(built, scope))\n .thenOnSuccess(async (embedded) =>\n (await this._vectors.embedFragmentsOnWrite(embedded.record, scope)).onSuccess((withFragments) =>\n succeed({ ...embedded, record: withFragments })\n )\n )\n .onSuccess((embedded) =>\n this._persist(embedded.record, scope, idStem).onSuccess((persisted) =>\n succeed({ persisted, stale: embedded.stale, embed: embedded.embed })\n )\n )\n .thenOnSuccess(async ({ persisted, stale, embed }) => {\n // Everything after the authoritative `_persist` commit is best-effort and\n // never turns a committed write into a `Failure`:\n // - a stale vector superseded by a decline is pruned here rather than at\n // the point of the decline, because a `_persist` that fails leaves the\n // PREVIOUS content on disk — content that vector is still an accurate\n // embedding of. Pruning early would delete a correct vector on behalf\n // of a write that never landed;\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 await this._vectors.pruneStaleVector(stale);\n const evicted: ReadonlyArray<MemoryId> = this._applyEvictions(decision, scope);\n await this._vectors.removeEvictedVectors(evicted, scope);\n return succeed({ record: persisted, evicted, embed });\n });\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 * 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._vectors.removeAll({ 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 // Same single-owner read as the flat path (see `_writeResolved`).\n const dedupScope: DedupScope = this.dedupScopeFor(kind);\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._vectors.embedOnWrite(built, scope))\n .thenOnSuccess(async (embedded) =>\n (await this._vectors.embedFragmentsOnWrite(embedded.record, scope)).onSuccess(\n (withFragments) => succeed({ ...embedded, record: withFragments })\n )\n )\n .onSuccess((embedded) =>\n this._persist(embedded.record, scope, versionStem).onSuccess((persisted) =>\n succeed({ persisted, stale: embedded.stale, embed: embedded.embed })\n )\n )\n .onSuccess(({ persisted, stale, embed }) =>\n this._invalidateCurrents(scope, priorCurrents, validAt, now).onSuccess(() =>\n succeed({ persisted, stale, embed })\n )\n )\n // Post-commit and best-effort, exactly as on the flat path.\n .thenOnSuccess(async ({ persisted, stale, embed }) => {\n await this._vectors.pruneStaleVector(stale);\n return succeed({ record: persisted, evicted: [], embed });\n })\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 * The locked body of {@link FileTreeMemoryStore.reconcileRank}.\n *\n * @remarks\n * Re-reads each record's file rather than trusting the in-memory index, for\n * two reasons: the index holds converted bodies on some paths and raw ones on\n * others, and re-serializing a *converted* body could change the bytes on disk\n * — a reconcile of an ordering field has no business rewriting content.\n * `splitFrontmatter` hands back the body text unconverted, so the round trip\n * carries the authored characters through untouched and only the envelope\n * moves. The parsed record is additionally put through `_verifyLoaded`, the\n * same id-vs-filename and scope-derived-entityId check the load paths apply —\n * without it, reconcile would be the one path that accepts and rewrites a file\n * the store would refuse to load.\n *\n * \"Untouched\" is not quite \"byte-identical\", and the exception is line\n * endings: `splitFrontmatter` strips a trailing `\\r` per line and\n * `joinFrontmatter` writes `\\n` delimiters, so a CRLF-authored file comes back\n * LF-normalized. That is **the store's behavior on every write path, not\n * something reconcile introduces** — an ordinary `put` normalizes the same way\n * — so reconcile does not rewrite content that a subsequent write would have\n * left alone. The property being claimed here is the narrower and load-bearing\n * one: no body is round-tripped through its registered Converter.\n *\n * The projector is fed an `IMemoryRecord<string>` carrying that raw body,\n * which is exactly the shape {@link FileTreeMemoryStore._stampRank} hands it\n * on the write path — so a projector cannot see one thing on a write and\n * another on a reconcile. `_stampRank` itself is reused verbatim, which also\n * inherits its throw semantics (logged at `warn`, `rank` cleared).\n */\n private async _reconcileRankLocked(kind: Kind): Promise<Result<number>> {\n if (!this._rankProjectors.has(kind)) {\n return fail(`memory reconcileRank '${kind}': no rank projector is registered for this kind`);\n }\n const targets: ReadonlyArray<IIndexedMemoryRecord> = this._index\n .entries()\n .filter((entry) => entry.record.envelope.kind === kind);\n let restamped: number = 0;\n for (const target of targets) {\n const applied: Result<boolean> = this._restampOne(target.scope, target.record.envelope.id);\n if (applied.isFailure()) {\n return fail(`memory reconcileRank '${kind}': ${applied.message}`);\n }\n if (applied.value) {\n restamped++;\n }\n }\n return succeed(restamped);\n }\n\n /**\n * Re-apply the rank projector to one record on disk. Returns whether `rank`\n * actually changed — an unchanged rank writes nothing, so a reconcile over an\n * already-consistent store touches no files.\n */\n private _restampOne(scope: MemoryScopeKey, id: MemoryId): Result<boolean> {\n return this._resolveScopeDir(scope).onSuccess((scopeDir) => {\n /* c8 ignore next 3 - defensive: the scope dir exists for any indexed record */\n if (scopeDir === undefined) {\n return fail(`'${id}': scope '${scope}' not found`);\n }\n return scopeDir.getChildren().onSuccess((children) => {\n const targetName: string = `${id}${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 /* c8 ignore next 3 - defensive: the file exists for any indexed record */\n if (file === undefined) {\n return fail(`'${id}': file not found`);\n }\n return file.getRawContents().onSuccess((raw) =>\n // `parseMemoryFile` validates the body through the registered Converter,\n // so a corrupt record is refused rather than silently rewritten, and\n // `_verifyLoaded` re-applies the same id-vs-filename and\n // scope-derived-entityId checks the two load paths apply. Reconcile is a\n // read-then-write, and a file can change on disk after the index was\n // built, so skipping them would make this the one path that accepts —\n // and rewrites — a record the store would otherwise refuse to load.\n // `splitFrontmatter` then supplies the body text for the write.\n parseMemoryFile(raw, this._registry)\n .withErrorFormat((msg) => `'${id}': ${msg}`)\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, file, parsedRecord))\n .onSuccess((parsed) =>\n splitFrontmatter(raw)\n .withErrorFormat((msg) => `'${id}': ${msg}`)\n .onSuccess((parts) => {\n const before: number | undefined = parsed.envelope.rank;\n const stamped: IMemoryRecord<string> = this._stampRank({\n envelope: parsed.envelope,\n body: parts.body\n });\n if (stamped.envelope.rank === before) {\n return succeed(false);\n }\n return this._persist(stamped, scope, id).onSuccess(() => succeed(true));\n })\n )\n );\n });\n });\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 /** {@inheritDoc IMemoryStore.dedupScopeFor} */\n public dedupScopeFor(kind: Kind): DedupScope {\n return this._policyFor(kind).dedupScope ?? DEFAULT_DEDUP_SCOPE;\n }\n\n /** {@inheritDoc IMemoryStore.embedsKind} */\n public embedsKind(kind: Kind): boolean {\n // No declaration means every kind participates — the behavior that predates\n // this param, so an existing consumer is unaffected.\n return this._embedKinds === undefined || this._embedKinds.has(kind);\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 * In `'skip'` mode each per-record failure is captured structurally on\n * `this._skippedRecords` (path + scope + path-tagged error) at its failure\n * site and logged at `warn`; the walk keeps every record that loaded.\n */\n private _initialIndex(onRecordError: MemoryRecordErrorMode): Result<true> {\n return this._collectEntries(this._root, [], onRecordError).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 onRecordError: MemoryRecordErrorMode\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], onRecordError);\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 this._loadRecordFile(scope, child, onRecordError);\n });\n // `'skip'` mode: keep every record that parsed, drop the ones that failed\n // in a single pass (each failure is captured on `this._skippedRecords` and\n // warn-logged at its site in `_loadRecordFile`). `.orDefault([])` covers\n // the all-invalid-subtree edge where `mapSuccess` returns Failure because\n // no element succeeded. `'fail'` mode: `mapResults` fails the whole open on\n // any bad record — byte-identical to the historical load path.\n if (onRecordError === 'skip') {\n return succeed<ReadonlyArray<IIndexedMemoryRecord>>(mapSuccess(results).orDefault([]).flat());\n }\n return mapResults(results).onSuccess((perChild) =>\n succeed<ReadonlyArray<IIndexedMemoryRecord>>(perChild.flat())\n );\n });\n }\n\n /**\n * Load and verify one record file. On failure in `'skip'` mode, records the\n * structured {@link ISkippedRecord} identity (path + scope + path-tagged\n * error) and logs the skip at `warn`; the failure is still returned so the\n * caller's `mapSuccess` drops it from the loaded set. In `'fail'` mode the\n * failure passes through untouched so the historical error is byte-identical.\n */\n private _loadRecordFile(\n scope: MemoryScopeKey,\n child: FileTree.IFileTreeFileItem,\n onRecordError: MemoryRecordErrorMode\n ): Result<ReadonlyArray<IIndexedMemoryRecord>> {\n return child\n .getRawContents()\n .onSuccess((raw) => parseMemoryFile(raw, this._registry))\n .onSuccess((parsedRecord) => this._verifyLoaded(scope, child, parsedRecord))\n .onSuccess((verified) => succeed<ReadonlyArray<IIndexedMemoryRecord>>([{ scope, record: verified }]))\n .onFailure((message) => {\n if (onRecordError === 'skip') {\n const path: string = `${scope}/${child.name}`;\n const error: string = `memory record '${path}': ${message}`;\n this._skippedRecords.push({ path, scope, error });\n this._warnSwallowed(error);\n }\n return fail(message);\n });\n }\n}\n"]}
|