@fgv/ts-agent-memory 5.1.0-49 → 5.1.0-51
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/index/memoryIndex.js +23 -16
- package/dist/packlets/index/memoryIndex.js.map +1 -1
- package/dist/packlets/ingest/orchestrator.js +13 -1
- package/dist/packlets/ingest/orchestrator.js.map +1 -1
- package/dist/packlets/retrieve/fragmentSemanticRetriever.js +94 -5
- package/dist/packlets/retrieve/fragmentSemanticRetriever.js.map +1 -1
- package/dist/packlets/retrieve/linkTraversalRetriever.js +12 -26
- package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/dist/packlets/retrieve/recencyRetriever.js +7 -7
- package/dist/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/dist/packlets/retrieve/retriever.js +91 -10
- package/dist/packlets/retrieve/retriever.js.map +1 -1
- package/dist/packlets/retrieve/semanticRetriever.js +16 -16
- package/dist/packlets/retrieve/semanticRetriever.js.map +1 -1
- package/dist/packlets/retrieve/structuredFilterRetriever.js +7 -7
- package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/dist/packlets/retrieve/tagRetriever.js +7 -7
- package/dist/packlets/retrieve/tagRetriever.js.map +1 -1
- package/dist/packlets/retrieve/temporalRetrievers.js +23 -20
- package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/dist/packlets/store/coverage.js +6 -0
- package/dist/packlets/store/coverage.js.map +1 -0
- package/dist/packlets/store/fileTreeMemoryStore.js +234 -103
- package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/dist/packlets/store/index.js +4 -0
- package/dist/packlets/store/index.js.map +1 -1
- package/dist/packlets/store/listSelection.js +36 -0
- package/dist/packlets/store/listSelection.js.map +1 -0
- package/dist/packlets/store/memoryStore.js +6 -0
- package/dist/packlets/store/memoryStore.js.map +1 -0
- package/dist/packlets/store/reconcile.js +6 -0
- package/dist/packlets/store/reconcile.js.map +1 -0
- package/dist/packlets/store/storeCoverage.js +102 -0
- package/dist/packlets/store/storeCoverage.js.map +1 -0
- package/dist/packlets/store/storeIdentity.js +62 -0
- package/dist/packlets/store/storeIdentity.js.map +1 -0
- package/dist/packlets/store/storeReconcile.js +122 -0
- package/dist/packlets/store/storeReconcile.js.map +1 -0
- package/dist/packlets/store/vectorMaintenance.js +116 -8
- package/dist/packlets/store/vectorMaintenance.js.map +1 -1
- package/dist/packlets/store/vectorRecordSource.js +44 -0
- package/dist/packlets/store/vectorRecordSource.js.map +1 -0
- package/dist/packlets/tools/memoryTools.js +25 -2
- package/dist/packlets/tools/memoryTools.js.map +1 -1
- package/dist/packlets/types/envelope.js +25 -0
- package/dist/packlets/types/envelope.js.map +1 -1
- package/dist/packlets/types/identityResolver.js +6 -0
- package/dist/packlets/types/identityResolver.js.map +1 -0
- package/dist/packlets/types/index.js +2 -0
- package/dist/packlets/types/index.js.map +1 -1
- package/dist/packlets/types/recordResolver.js +6 -0
- package/dist/packlets/types/recordResolver.js.map +1 -0
- package/dist/packlets/types/temporal.js.map +1 -1
- package/dist/packlets/vector/inMemoryCosineIndex.js +39 -18
- package/dist/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/dist/packlets/vector/inMemoryFragmentCosineIndex.js +109 -14
- package/dist/packlets/vector/inMemoryFragmentCosineIndex.js.map +1 -1
- package/dist/packlets/vector/rebuildHelpers.js +38 -0
- package/dist/packlets/vector/rebuildHelpers.js.map +1 -0
- package/dist/packlets/vector/vectorIndex.js.map +1 -1
- package/dist/ts-agent-memory.d.ts +1226 -114
- package/lib/packlets/index/memoryIndex.d.ts +118 -27
- package/lib/packlets/index/memoryIndex.d.ts.map +1 -1
- package/lib/packlets/index/memoryIndex.js +23 -16
- package/lib/packlets/index/memoryIndex.js.map +1 -1
- package/lib/packlets/ingest/orchestrator.d.ts.map +1 -1
- package/lib/packlets/ingest/orchestrator.js +13 -1
- package/lib/packlets/ingest/orchestrator.js.map +1 -1
- package/lib/packlets/retrieve/fragmentSemanticRetriever.d.ts +79 -1
- package/lib/packlets/retrieve/fragmentSemanticRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/fragmentSemanticRetriever.js +94 -5
- package/lib/packlets/retrieve/fragmentSemanticRetriever.js.map +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +3 -10
- package/lib/packlets/retrieve/linkTraversalRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/linkTraversalRetriever.js +11 -25
- package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
- package/lib/packlets/retrieve/recencyRetriever.d.ts +3 -3
- package/lib/packlets/retrieve/recencyRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/recencyRetriever.js +6 -6
- package/lib/packlets/retrieve/recencyRetriever.js.map +1 -1
- package/lib/packlets/retrieve/retriever.d.ts +88 -7
- package/lib/packlets/retrieve/retriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/retriever.js +94 -9
- package/lib/packlets/retrieve/retriever.js.map +1 -1
- package/lib/packlets/retrieve/semanticRetriever.d.ts +3 -5
- package/lib/packlets/retrieve/semanticRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/semanticRetriever.js +15 -15
- package/lib/packlets/retrieve/semanticRetriever.js.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts +3 -3
- package/lib/packlets/retrieve/structuredFilterRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/structuredFilterRetriever.js +6 -6
- package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
- package/lib/packlets/retrieve/tagRetriever.d.ts +3 -3
- package/lib/packlets/retrieve/tagRetriever.d.ts.map +1 -1
- package/lib/packlets/retrieve/tagRetriever.js +6 -6
- package/lib/packlets/retrieve/tagRetriever.js.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.d.ts +7 -5
- package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -1
- package/lib/packlets/retrieve/temporalRetrievers.js +22 -19
- package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -1
- package/lib/packlets/store/coverage.d.ts +102 -0
- package/lib/packlets/store/coverage.d.ts.map +1 -0
- package/lib/packlets/store/coverage.js +7 -0
- package/lib/packlets/store/coverage.js.map +1 -0
- package/lib/packlets/store/fileTreeMemoryStore.d.ts +56 -167
- package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
- package/lib/packlets/store/fileTreeMemoryStore.js +234 -103
- package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
- package/lib/packlets/store/index.d.ts +4 -0
- package/lib/packlets/store/index.d.ts.map +1 -1
- package/lib/packlets/store/index.js +4 -0
- package/lib/packlets/store/index.js.map +1 -1
- package/lib/packlets/store/listSelection.d.ts +101 -0
- package/lib/packlets/store/listSelection.d.ts.map +1 -0
- package/lib/packlets/store/listSelection.js +40 -0
- package/lib/packlets/store/listSelection.js.map +1 -0
- package/lib/packlets/store/memoryStore.d.ts +237 -0
- package/lib/packlets/store/memoryStore.d.ts.map +1 -0
- package/lib/packlets/store/memoryStore.js +7 -0
- package/lib/packlets/store/memoryStore.js.map +1 -0
- package/lib/packlets/store/reconcile.d.ts +82 -0
- package/lib/packlets/store/reconcile.d.ts.map +1 -0
- package/lib/packlets/store/reconcile.js +7 -0
- package/lib/packlets/store/reconcile.js.map +1 -0
- package/lib/packlets/store/storeCoverage.d.ts +45 -0
- package/lib/packlets/store/storeCoverage.d.ts.map +1 -0
- package/lib/packlets/store/storeCoverage.js +105 -0
- package/lib/packlets/store/storeCoverage.js.map +1 -0
- package/lib/packlets/store/storeIdentity.d.ts +38 -0
- package/lib/packlets/store/storeIdentity.d.ts.map +1 -0
- package/lib/packlets/store/storeIdentity.js +67 -0
- package/lib/packlets/store/storeIdentity.js.map +1 -0
- package/lib/packlets/store/storeReconcile.d.ts +41 -0
- package/lib/packlets/store/storeReconcile.d.ts.map +1 -0
- package/lib/packlets/store/storeReconcile.js +125 -0
- package/lib/packlets/store/storeReconcile.js.map +1 -0
- package/lib/packlets/store/vectorMaintenance.d.ts +74 -0
- package/lib/packlets/store/vectorMaintenance.d.ts.map +1 -1
- package/lib/packlets/store/vectorMaintenance.js +117 -8
- package/lib/packlets/store/vectorMaintenance.js.map +1 -1
- package/lib/packlets/store/vectorRecordSource.d.ts +36 -0
- package/lib/packlets/store/vectorRecordSource.d.ts.map +1 -0
- package/lib/packlets/store/vectorRecordSource.js +47 -0
- package/lib/packlets/store/vectorRecordSource.js.map +1 -0
- package/lib/packlets/tools/memoryTools.d.ts.map +1 -1
- package/lib/packlets/tools/memoryTools.js +25 -2
- package/lib/packlets/tools/memoryTools.js.map +1 -1
- package/lib/packlets/types/envelope.d.ts +24 -2
- package/lib/packlets/types/envelope.d.ts.map +1 -1
- package/lib/packlets/types/envelope.js +26 -0
- package/lib/packlets/types/envelope.js.map +1 -1
- package/lib/packlets/types/identityResolver.d.ts +42 -0
- package/lib/packlets/types/identityResolver.d.ts.map +1 -0
- package/lib/packlets/types/identityResolver.js +7 -0
- package/lib/packlets/types/identityResolver.js.map +1 -0
- package/lib/packlets/types/index.d.ts +2 -0
- package/lib/packlets/types/index.d.ts.map +1 -1
- package/lib/packlets/types/index.js +2 -0
- package/lib/packlets/types/index.js.map +1 -1
- package/lib/packlets/types/recordResolver.d.ts +39 -0
- package/lib/packlets/types/recordResolver.d.ts.map +1 -0
- package/lib/packlets/types/recordResolver.js +7 -0
- package/lib/packlets/types/recordResolver.js.map +1 -0
- package/lib/packlets/types/temporal.d.ts +26 -6
- package/lib/packlets/types/temporal.d.ts.map +1 -1
- package/lib/packlets/types/temporal.js.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts +9 -2
- package/lib/packlets/vector/inMemoryCosineIndex.d.ts.map +1 -1
- package/lib/packlets/vector/inMemoryCosineIndex.js +40 -19
- package/lib/packlets/vector/inMemoryCosineIndex.js.map +1 -1
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.d.ts +18 -4
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.d.ts.map +1 -1
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.js +108 -13
- package/lib/packlets/vector/inMemoryFragmentCosineIndex.js.map +1 -1
- package/lib/packlets/vector/rebuildHelpers.d.ts +30 -0
- package/lib/packlets/vector/rebuildHelpers.d.ts.map +1 -0
- package/lib/packlets/vector/rebuildHelpers.js +42 -0
- package/lib/packlets/vector/rebuildHelpers.js.map +1 -0
- package/lib/packlets/vector/vectorIndex.d.ts +326 -20
- package/lib/packlets/vector/vectorIndex.d.ts.map +1 -1
- package/lib/packlets/vector/vectorIndex.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoryTools.js","sourceRoot":"","sources":["../../../src/packlets/tools/memoryTools.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAirBH,8CAaC;AA5rBD,4CAAqE;AACrE,oDAA+C;AAE/C,oCAA8G;AAC9G,8CAA0E;AAgB1E;;;;;;GAMG;AACU,QAAA,oBAAoB,GAAkC,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAgJvG,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2DAA2D;AAC3D,8EAA8E;AAE9E;;;;;GAKG;AACH,kDAAkD;AAClD,MAAM,gBAAgB,GAAG,yBAAU,CAAC,MAAM,CAAC;IACzC,EAAE,EAAE,yBAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACzF,KAAK,EAAE,yBAAU,CAAC,QAAQ,CACxB,yBAAU,CAAC,MAAM,CAAC;QAChB,WAAW,EAAE,qFAAqF;KACnG,CAAC,CACH;CACF,CAAC,CAAC;AAEH,yEAAyE;AACzE,kDAAkD;AAClD,MAAM,cAAc,GAAG,yBAAU,CAAC,MAAM,CAAC;IACvC,IAAI,EAAE,yBAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,gCAAgC,EAAE,CAAC;IA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CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5G,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport { JsonSchema } from '@fgv/ts-json-base';\nimport { AiAssist } from '@fgv/ts-extras';\nimport { Convert, EntityId, IEdgeTarget, IIdentityCodec, IMemoryRecord, Kind, MemoryId, Tag } from '../types';\nimport { IBodyConverterRegistry, envelopeConverter } from '../converters';\nimport { IMemoryStore } from '../store';\nimport { IMemoryQuery, IMemoryRetriever } from '../retrieve';\n\n/**\n * The names of the five proof-set memory tools. A caller selects a subset via\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport type MemoryToolName =\n | 'memory_write'\n | 'memory_read'\n | 'memory_search'\n | 'memory_context'\n | 'memory_delete';\n\n/**\n * The default tool subset when {@link ICreateMemoryToolsParams.tools | tools} is\n * omitted: the read-only set. Mutating tools (`memory_write` / `memory_delete`)\n * are **off by default** and must be named explicitly — writes stay\n * curation-mediated unless the host opts in.\n * @public\n */\nexport const DEFAULT_MEMORY_TOOLS: ReadonlyArray<MemoryToolName> = ['memory_search', 'memory_context'];\n\n/**\n * Discriminates the outcome of a {@link createMemoryTools | memory_write} call so\n * the agent can reason about what its write actually did.\n *\n * @remarks\n * - `written` — a new record was persisted, or an existing entity was updated.\n * - `deduped` — the content already existed (content-hash dedup no-op); the\n * store returned the existing record unchanged.\n *\n * The store's public `put` return does not surface cap-cull evictions, so a\n * `culled` outcome is not distinguishable at this layer without an L1 change or\n * observer wiring (both out of scope for L2). The writer's own record is always\n * `written` even when the write triggers a cull of older siblings.\n * @public\n */\nexport type MemoryWriteOutcome = 'written' | 'deduped';\n\n/**\n * The success value returned by `memory_write.execute`.\n * @public\n */\nexport interface IMemoryWriteResult {\n /** What the write did — see {@link MemoryWriteOutcome}. */\n readonly outcome: MemoryWriteOutcome;\n /** The stored record's {@link MemoryId}. */\n readonly id: MemoryId;\n /** The domain {@link EntityId} the write targeted. */\n readonly entityId: EntityId;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n}\n\n/**\n * A single agent-visible search / context result item. The agent-facing key is\n * {@link IMemoryToolResultItem.handle | handle}: the host mnemonic when a\n * {@link ICreateMemoryToolsParams.handleFor | handleFor} hook is supplied, else\n * the raw {@link MemoryId}.\n * @public\n */\nexport interface IMemoryToolResultItem {\n /** The agent-visible key (host handle when supplied, raw {@link MemoryId} otherwise). */\n readonly handle: string;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n /** The record's domain {@link EntityId}. */\n readonly entityId: EntityId;\n /** The record's tags. */\n readonly tags: ReadonlyArray<string>;\n /** The record body (a markdown string in B1). */\n readonly body: unknown;\n}\n\n/**\n * Parameters for {@link createMemoryTools}.\n *\n * @remarks\n * **Scope isolation is constructor-fixed.** The {@link\n * ICreateMemoryToolsParams.store | store} is the sole scope authority — it is the\n * actor's own, pre-scoped memory root. No tool's `parametersSchema` declares a\n * `scope` (or any scope-widening) property, so an LLM cannot steer a tool at\n * another actor's memory.\n * @public\n */\nexport interface ICreateMemoryToolsParams {\n /**\n * The pre-scoped memory store (the actor's own memory root). Sole scope\n * authority — backs `memory_write` / `memory_read` / `memory_delete`.\n */\n readonly store: IMemoryStore;\n /** Retriever backing `memory_search` (and `memory_context` via link traversal). */\n readonly retriever: IMemoryRetriever;\n /** Body converter registry — gates the toolable kinds via `has(kind)`. */\n readonly registry: IBodyConverterRegistry;\n /**\n * The per-tool enable subset. Defaults to {@link DEFAULT_MEMORY_TOOLS} (the\n * read-only set). Name `memory_write` / `memory_delete` here to opt into the\n * mutating tools.\n */\n readonly tools?: ReadonlyArray<MemoryToolName>;\n /**\n * Optional whitelist of toolable kinds. When present, a tool `kind` argument\n * outside this set is rejected. When absent, {@link\n * IBodyConverterRegistry.has | registry.has} is the sole kind gate.\n */\n readonly kinds?: ReadonlyArray<Kind>;\n /**\n * Per-kind identity codecs, used by `memory_write` to map the domain\n * {@link EntityId} to the record's storage id (the store resolves codecs\n * internally for `get` / `delete`, so read / delete do not need them). Absent\n * → `memory_write` uses {@link ICreateMemoryToolsParams.defaultCodec |\n * defaultCodec}, and fails loudly for a kind with no resolvable codec. The\n * read-only default tool set needs no codecs.\n */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default identity codec for kinds without an explicit {@link ICreateMemoryToolsParams.codecs | codecs} entry. */\n readonly defaultCodec?: IIdentityCodec;\n /**\n * Optional host hook mapping a record to its agent-visible handle (an evocative\n * mnemonic tag). When supplied, `memory_search` / `memory_context` results use\n * the returned handle as the agent-visible key; when absent the raw\n * {@link MemoryId} is used.\n */\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n /**\n * Optional host projector mapping a record (and the requested detail tier) to\n * its agent-visible {@link IMemoryToolResultItem}. When supplied, every\n * `memory_search` / `memory_context` / `memory_read` result item is produced by\n * this callback — the host owns how much of the body a `'gist'` vs `'full'`\n * result carries, so it can bound the default (`'gist'`) path.\n *\n * When absent, the built-in default projection is used (full body plus the\n * {@link ICreateMemoryToolsParams.handleFor | handleFor} handle), which ignores\n * the detail tier — behavior is byte-identical to a build with no projector.\n *\n * The callback is guarded exactly like `handleFor`: a throw degrades to the\n * default full-body projection for that item rather than failing the whole\n * search.\n */\n readonly projectItem?: (record: IMemoryRecord<unknown>, detail: MemoryDetailTier) => IMemoryToolResultItem;\n}\n\n/**\n * The detail tier a `memory_search` / `memory_context` result is projected at.\n * `'gist'` is the default (bounded) path; `'full'` is opt-in. Only meaningful\n * when a host {@link ICreateMemoryToolsParams.projectItem | projectItem} is\n * supplied — the built-in default projection returns the full body regardless.\n * @public\n */\nexport type MemoryDetailTier = 'gist' | 'full';\n\n/** The resolved factory context threaded into each tool's `execute`. */\ninterface IToolContext {\n readonly store: IMemoryStore;\n readonly retriever: IMemoryRetriever;\n readonly registry: IBodyConverterRegistry;\n readonly kinds?: ReadonlyArray<Kind>;\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n readonly defaultCodec?: IIdentityCodec;\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n readonly projectItem?: (record: IMemoryRecord<unknown>, detail: MemoryDetailTier) => IMemoryToolResultItem;\n}\n\n// ---------------------------------------------------------------------------\n// Parameter schemas — authored once via JsonSchema.object(...); the schema IS\n// both the wire schema (.toJson()) and the runtime validator (.convert()).\n// NONE of these declare a `scope` (or scope-widening) property — the adoption\n// gate is enforced structurally and asserted in the tests.\n// ---------------------------------------------------------------------------\n\n/**\n * The scope-qualified target of a link edge authored by the agent on a write.\n * `scope` is optional: when omitted it defaults to the writing record's OWN\n * resolved scope (the common same-conversation case); supply it explicitly to\n * point an edge at a record in a different scope.\n */\n// eslint-disable-next-line @rushstack/typedef-var\nconst linkTargetSchema = JsonSchema.object({\n id: JsonSchema.string({ description: 'The MemoryId of the record this edge points at.' }),\n scope: JsonSchema.optional(\n JsonSchema.string({\n description: \"The target record's scope. Defaults to the writing record's own scope when omitted.\"\n })\n )\n});\n\n/** A single attributed link edge as authored by the agent on a write. */\n// eslint-disable-next-line @rushstack/typedef-var\nconst linkEdgeSchema = JsonSchema.object({\n type: JsonSchema.string({ description: 'The relation type of the link.' }),\n target: linkTargetSchema,\n confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst writeSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind (must be an enabled, registered kind).' }),\n entityId: JsonSchema.string({\n description:\n 'The domain entity id. For composite (e.g. medium-term) kinds this is the full composite key.'\n }),\n body: JsonSchema.string({ description: \"The serialized record body; validated by the kind's converter.\" }),\n tags: JsonSchema.optional(JsonSchema.array(JsonSchema.string({ description: 'A tag label.' }))),\n links: JsonSchema.optional(JsonSchema.array(linkEdgeSchema))\n});\ntype WriteArgs = JsonSchema.Static<typeof writeSchema>;\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst readSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to read.' }),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' | 'full' (default).\" })\n )\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst deleteSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to delete.' })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst searchSchema = JsonSchema.object({\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),\n semantic: JsonSchema.optional(\n JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })\n ),\n limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' })),\n offset: JsonSchema.optional(\n JsonSchema.integer({ description: 'Number of results to skip after ordering, before limit. Default 0.' })\n ),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' (default) | 'full'.\" })\n )\n});\n\n/**\n * The scope-qualified seed a `memory_context` traversal starts from. Nested\n * `{ id, scope }` shape like a link target, but — unlike a write edge — there is\n * no writing record to default the scope from, so `scope` is REQUIRED to\n * disambiguate the seed across scopes (a bare stem like `turn-3` is otherwise\n * ambiguous). It is schema-required (not just runtime-required) so the wire\n * schema an LLM reads never advertises an optionality the tool does not honor.\n */\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSeedSchema = JsonSchema.object({\n id: JsonSchema.string({ description: 'The MemoryId of the seed record to traverse links from.' }),\n scope: JsonSchema.string({\n description: 'The scope of the seed record (required — a bare seed id is ambiguous across scopes).'\n })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSchema = JsonSchema.object({\n from: contextSeedSchema,\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),\n hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),\n limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' })),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' (default) | 'full'.\" })\n )\n});\n\n// ---------------------------------------------------------------------------\n// Behavior annotations (Component 4) — host-advisory hints; never serialized to\n// the model. openWorldHint is false throughout (a closed, local store).\n// ---------------------------------------------------------------------------\n\nconst READ_ONLY_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n readOnlyHint: true,\n openWorldHint: false\n};\n\nconst WRITE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false\n};\n\nconst DELETE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false\n};\n\n// ---------------------------------------------------------------------------\n// Shared validation / projection helpers\n// ---------------------------------------------------------------------------\n\n/** Validate a `kind` string and assert it is an enabled, registered toolable kind. */\nfunction assertKindEnabled(ctx: IToolContext, kindStr: string): Result<Kind> {\n return Convert.kind.convert(kindStr).onSuccess((kind) => {\n if (!ctx.registry.has(kind)) {\n return fail(`memory tools: kind '${kind}' has no registered body converter`);\n }\n if (ctx.kinds !== undefined && !ctx.kinds.includes(kind)) {\n return fail(`memory tools: kind '${kind}' is not enabled for memory tools`);\n }\n return succeed(kind);\n });\n}\n\n/** Validate an optional `kind` string (enabled when present; `undefined` passes through). */\nfunction resolveOptionalKind(ctx: IToolContext, kindStr?: string): Result<Kind | undefined> {\n if (kindStr === undefined) {\n return succeed(undefined);\n }\n return assertKindEnabled(ctx, kindStr);\n}\n\n/**\n * Resolve the requested detail tier from the optional tool `detail` string.\n * `'full'` is the only opt-in value; every other input (absent, or an\n * unrecognized string) resolves safely to the bounded default `'gist'`.\n */\nfunction resolveDetail(detail?: string): MemoryDetailTier {\n return detail === 'full' ? 'full' : 'gist';\n}\n\n/** The built-in default projection: full body plus the guarded host handle. Ignores the detail tier. */\nfunction defaultProjectItem(ctx: IToolContext, record: IMemoryRecord<unknown>): IMemoryToolResultItem {\n // `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than\n // escaping the Result chain (and crashing the whole search/context call).\n const handle =\n ctx.handleFor !== undefined\n ? captureResult(() => ctx.handleFor!(record)).orDefault(record.envelope.id)\n : record.envelope.id;\n return {\n handle,\n kind: record.envelope.kind,\n entityId: record.envelope.entityId,\n tags: record.envelope.tags,\n body: record.body\n };\n}\n\n/**\n * Project a record into an agent-visible result item at the requested detail\n * tier. When a host {@link ICreateMemoryToolsParams.projectItem | projectItem}\n * is supplied it owns the projection; otherwise the built-in\n * {@link defaultProjectItem} (full body) is used. The host callback is guarded\n * like `handleFor` — a throw degrades to the default full-body projection for\n * that item rather than failing the whole search/context call.\n */\nfunction projectItem(\n ctx: IToolContext,\n record: IMemoryRecord<unknown>,\n detail: MemoryDetailTier\n): IMemoryToolResultItem {\n if (ctx.projectItem === undefined) {\n return defaultProjectItem(ctx, record);\n }\n // Guard the host projector like `handleFor`: a throw degrades to the built-in\n // full-body projection (itself throw-safe) rather than escaping the chain.\n return captureResult(() => ctx.projectItem!(record, detail)).orDefault(defaultProjectItem(ctx, record));\n}\n\n/** Resolve the identity codec used by `memory_write` to derive the storage id. */\nfunction codecForWrite(ctx: IToolContext, kind: Kind): Result<IIdentityCodec> {\n const codec: IIdentityCodec | undefined = ctx.codecs?.get(kind) ?? ctx.defaultCodec;\n if (codec === undefined) {\n return fail(`memory_write: no identity codec available for kind '${kind}'`);\n }\n return succeed(codec);\n}\n\n/** Build the record to persist from validated write args (store stamps txn-time metadata). */\nfunction buildWriteRecord(\n typed: WriteArgs,\n kind: Kind,\n entityId: EntityId,\n idStem: string,\n sourceScope: string\n): Result<IMemoryRecord<unknown>> {\n // Plain shapes handed to `envelopeConverter`, which validates each field\n // (type → LinkType, target → { scope, id }) and produces the branded IEdge[].\n // An edge target with no explicit `scope` defaults to the writing record's own\n // resolved scope — the same-conversation case authors just an id.\n const links: ReadonlyArray<Record<string, unknown>> = (typed.links ?? []).map((link) => ({\n type: link.type,\n target: { scope: link.target.scope ?? sourceScope, id: link.target.id },\n ...(link.confidence !== undefined ? { confidence: link.confidence } : {})\n }));\n return envelopeConverter\n .convert({\n id: idStem,\n entityId,\n kind,\n tags: typed.tags ?? [],\n links,\n created: 0,\n updated: 0,\n seq: 0,\n contentHash: '',\n provenance: { source: 'agent' }\n })\n .withErrorFormat((msg) => `memory_write: invalid record: ${msg}`)\n .onSuccess((envelope) => succeed({ envelope, body: typed.body }));\n}\n\n/** Resolve the validated write args into the storage id + record (all synchronous). */\nfunction prepareWrite(\n ctx: IToolContext,\n typed: WriteArgs\n): Result<{ readonly kind: Kind; readonly entityId: EntityId; readonly record: IMemoryRecord<unknown> }> {\n return assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) =>\n codecForWrite(ctx, kind).onSuccess((codec) =>\n codec.encode(entityId).onSuccess((addr) => {\n if (addr.isVersioned) {\n return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);\n }\n return buildWriteRecord(typed, kind, entityId, addr.idStem, addr.scope).onSuccess((record) =>\n succeed({ kind, entityId, record })\n );\n })\n )\n )\n );\n}\n\n/**\n * Discriminate the write outcome from a pre-put snapshot and the returned record.\n * A dedup no-op returns either a different entity (content-scope dedup) or the\n * same-id record with an unchanged `seq` (entity-scope re-put); a fresh write or\n * update advances `seq`.\n */\nfunction writeOutcome(\n before: IMemoryRecord<unknown> | undefined,\n written: IMemoryRecord<unknown>,\n entityId: EntityId\n): MemoryWriteOutcome {\n if (written.envelope.entityId !== entityId) {\n return 'deduped';\n }\n if (before !== undefined && written.envelope.seq === before.envelope.seq) {\n return 'deduped';\n }\n return 'written';\n}\n\n// ---------------------------------------------------------------------------\n// Tool builders — config with a JsonSchema.object(...) parametersSchema; execute\n// validates/narrows → delegates to store/retriever → returns the Result (never\n// swallowed), following the ts-extras-mcp adapter shape.\n//\n// Each `execute` re-runs its own `parametersSchema.convert(args)` even though the\n// `executeClientToolTurn` harness already validates against the same schema. This\n// is deliberate: the factory returns a heterogeneous `ReadonlyArray<IAiClientTool>`\n// (TParams erased to `unknown`, since the members carry different param shapes), so\n// `execute` receives `unknown` and must narrow it back to the typed args. The\n// re-validation is also the narrowing step exercised by the direct-call tests (which\n// invoke `execute` with raw args, bypassing the harness). Re-validating an\n// already-conforming shape is a cheap, side-effect-free identity.\n// ---------------------------------------------------------------------------\n\nfunction buildWriteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_write',\n description:\n 'Store a new memory record or update an existing one by (kind, entityId). ' +\n 'Identical content is a no-op that returns the existing record.',\n parametersSchema: writeSchema,\n annotations: WRITE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n writeSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_write: invalid arguments: ${msg}`)\n .onSuccess((typed) => prepareWrite(ctx, typed))\n .thenOnSuccess(async ({ kind, entityId, record }) =>\n // Read the prior record to discriminate written-vs-deduped. A `Failure`\n // here (corrupt file, I/O error, codec round-trip failure) is a real\n // condition distinct from the \"not found\" success (`undefined`); propagate\n // it rather than defaulting it away, so a genuine store fault surfaces\n // instead of being masked as a normal write.\n (await ctx.store.get(kind, entityId)).thenOnSuccess(async (before) =>\n (await ctx.store.put(record)).onSuccess((persisted) =>\n succeed<IMemoryWriteResult>({\n outcome: writeOutcome(before, persisted, entityId),\n id: persisted.envelope.id,\n entityId,\n kind\n })\n )\n )\n )\n };\n}\n\nfunction buildReadTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_read',\n description: 'Read a specific memory record by (kind, entityId).',\n parametersSchema: readSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n readSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => {\n // `memory_read` is the explicit drill-in path, so its detail default is\n // INVERTED vs search/context: `'full'` unless the caller opts down to `'gist'`.\n const detail: MemoryDetailTier = typed.detail === 'gist' ? 'gist' : 'full';\n return succeed({ kind, entityId, detail });\n })\n )\n )\n .thenOnSuccess(async ({ kind, entityId, detail }) =>\n (await ctx.store.get(kind, entityId)).onSuccess((record) =>\n record === undefined\n ? succeed({ found: false })\n : succeed({ found: true, item: projectItem(ctx, record, detail) })\n )\n )\n };\n}\n\nfunction buildSearchTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_search',\n description: 'Search memories by tag, kind, or semantic text. Returns ranked results.',\n parametersSchema: searchSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n searchSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))\n )\n )\n .thenOnSuccess(async ({ typed, kind, tag }) => {\n const detail: MemoryDetailTier = resolveDetail(typed.detail);\n const query: IMemoryQuery = {\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.semantic !== undefined ? { semantic: typed.semantic } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {}),\n ...(typed.offset !== undefined ? { offset: typed.offset } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r, detail)) })\n );\n })\n };\n}\n\nfunction buildContextTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_context',\n description:\n 'Build a context graph from a seed memory: returns the records linked from the seed, up to `hops` hops.',\n parametersSchema: contextSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n contextSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n resolveContextSeed(typed.from).onSuccess((from) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag }))\n )\n )\n )\n .thenOnSuccess(async ({ typed, from, kind, tag }) => {\n const detail: MemoryDetailTier = resolveDetail(typed.detail);\n const query: IMemoryQuery = {\n linkedFrom: from,\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.hops !== undefined ? { hops: typed.hops } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({\n seed: from,\n count: records.length,\n results: records.map((r) => projectItem(ctx, r, detail))\n })\n );\n })\n };\n}\n\nfunction buildDeleteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_delete',\n description: 'Delete a memory record by (kind, entityId). Destructive for non-temporal kinds.',\n parametersSchema: deleteSchema,\n annotations: DELETE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n deleteSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_delete: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))\n )\n )\n .thenOnSuccess(async ({ kind, entityId }) =>\n (await ctx.store.delete(kind, entityId)).onSuccess((id) =>\n succeed({ deleted: true, id, entityId, kind })\n )\n )\n };\n}\n\n/**\n * Resolve a `memory_context` seed argument into a scope-qualified\n * {@link IEdgeTarget}. Both `id` and `scope` are present here — the tool's\n * `parametersSchema` ({@link contextSeedSchema}) makes `scope` schema-required —\n * so this only brands the two fields; a malformed value fails via the branded\n * converters (e.g. a path-unsafe seed id).\n */\nfunction resolveContextSeed(from: { readonly id: string; readonly scope: string }): Result<IEdgeTarget> {\n return Convert.memoryId\n .convert(from.id)\n .onSuccess((id) => Convert.scopeKey.convert(from.scope).onSuccess((scope) => succeed({ scope, id })));\n}\n\n/** Validate an optional `tag` string (`undefined` passes through). */\nfunction resolveOptionalTag(tagStr?: string): Result<Tag | undefined> {\n if (tagStr === undefined) {\n return succeed(undefined);\n }\n return Convert.tag.convert(tagStr);\n}\n\n/** Ordered registry of the five tool builders, keyed by name. */\nconst TOOL_BUILDERS: ReadonlyArray<{\n readonly name: MemoryToolName;\n readonly build: (ctx: IToolContext) => AiAssist.IAiClientTool;\n}> = [\n { name: 'memory_write', build: buildWriteTool },\n { name: 'memory_read', build: buildReadTool },\n { name: 'memory_search', build: buildSearchTool },\n { name: 'memory_context', build: buildContextTool },\n { name: 'memory_delete', build: buildDeleteTool }\n];\n\n/**\n * Build the selected suite of memory `AiAssist.IAiClientTool`s over a\n * pre-scoped store — ready to hand to `AiAssist.executeClientToolTurn` (and, via\n * the shared `JsonSchema.object(...)` schemas, `@fgv/ts-extras-mcp`).\n *\n * @remarks\n * **Scope isolation is make-or-break.** The returned tools close over the\n * pre-scoped {@link ICreateMemoryToolsParams.store | store}; no tool's\n * `parametersSchema` declares a `scope` (or any scope-widening) property, so an\n * LLM cannot steer a tool at another actor's memory. The store instance is the\n * sole scope authority.\n *\n * The default selection is {@link DEFAULT_MEMORY_TOOLS} (the read-only set) —\n * `memory_write` / `memory_delete` are included only when named in\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport function createMemoryTools(params: ICreateMemoryToolsParams): ReadonlyArray<AiAssist.IAiClientTool> {\n const ctx: IToolContext = {\n store: params.store,\n retriever: params.retriever,\n registry: params.registry,\n kinds: params.kinds,\n codecs: params.codecs,\n defaultCodec: params.defaultCodec,\n handleFor: params.handleFor,\n projectItem: params.projectItem\n };\n const selected: ReadonlySet<MemoryToolName> = new Set<MemoryToolName>(params.tools ?? DEFAULT_MEMORY_TOOLS);\n return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"memoryTools.js","sourceRoot":"","sources":["../../../src/packlets/tools/memoryTools.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAgtBH,8CAaC;AA3tBD,4CAAqE;AACrE,oDAA+C;AAE/C,oCAA8G;AAC9G,8CAA0E;AAgB1E;;;;;;GAMG;AACU,QAAA,oBAAoB,GAAkC,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAgJvG,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2DAA2D;AAC3D,8EAA8E;AAE9E;;;;;GAKG;AACH,kDAAkD;AAClD,MAAM,gBAAgB,GAAG,yBAAU,CAAC,MAAM,CAAC;IACzC,EAAE,EAAE,yBAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACzF,KAAK,EAAE,yBAAU,CAAC,QAAQ,CACxB,yBAAU,CAAC,MAAM,CAAC;QAChB,WAAW,EAAE,qFAAqF;KACnG,CAAC,CACH;CACF,CAAC,CAAC;AAEH,yEAAyE;AACzE,kDAAkD;AAClD,MAAM,cAAc,GAAG,yBAAU,CAAC,MAAM,CAAC;IACvC,IAAI,EAAE,yBAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,gCAAgC,EAAE,CAAC;IAC1E,MAAM,EAAE,gBAAgB;IACxB,UAAU,EAAE,yBAAU,CAAC,QAAQ,CAAC,yBAAU,CAAC,MAAM,CAAC,EAAE,WAAW,E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M,CAAC,KAAK;QACnB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,WAAW,EAAE,MAAM,CAAC,WAAW;KAChC,CAAC;IACF,MAAM,QAAQ,GAAgC,IAAI,GAAG,CAAiB,MAAA,MAAM,CAAC,KAAK,mCAAI,4BAAoB,CAAC,CAAC;IAC5G,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5G,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport { JsonSchema } from '@fgv/ts-json-base';\nimport { AiAssist } from '@fgv/ts-extras';\nimport { Convert, EntityId, IEdgeTarget, IIdentityCodec, IMemoryRecord, Kind, MemoryId, Tag } from '../types';\nimport { IBodyConverterRegistry, envelopeConverter } from '../converters';\nimport { IMemoryStore } from '../store';\nimport { IMemoryQuery, IMemoryRetriever } from '../retrieve';\n\n/**\n * The names of the five proof-set memory tools. A caller selects a subset via\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport type MemoryToolName =\n | 'memory_write'\n | 'memory_read'\n | 'memory_search'\n | 'memory_context'\n | 'memory_delete';\n\n/**\n * The default tool subset when {@link ICreateMemoryToolsParams.tools | tools} is\n * omitted: the read-only set. Mutating tools (`memory_write` / `memory_delete`)\n * are **off by default** and must be named explicitly — writes stay\n * curation-mediated unless the host opts in.\n * @public\n */\nexport const DEFAULT_MEMORY_TOOLS: ReadonlyArray<MemoryToolName> = ['memory_search', 'memory_context'];\n\n/**\n * Discriminates the outcome of a {@link createMemoryTools | memory_write} call so\n * the agent can reason about what its write actually did.\n *\n * @remarks\n * - `written` — a new record was persisted, or an existing entity was updated.\n * - `deduped` — the content already existed (content-hash dedup no-op); the\n * store returned the existing record unchanged.\n *\n * The store's public `put` return does not surface cap-cull evictions, so a\n * `culled` outcome is not distinguishable at this layer without an L1 change or\n * observer wiring (both out of scope for L2). The writer's own record is always\n * `written` even when the write triggers a cull of older siblings.\n * @public\n */\nexport type MemoryWriteOutcome = 'written' | 'deduped';\n\n/**\n * The success value returned by `memory_write.execute`.\n * @public\n */\nexport interface IMemoryWriteResult {\n /** What the write did — see {@link MemoryWriteOutcome}. */\n readonly outcome: MemoryWriteOutcome;\n /** The stored record's {@link MemoryId}. */\n readonly id: MemoryId;\n /** The domain {@link EntityId} the write targeted. */\n readonly entityId: EntityId;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n}\n\n/**\n * A single agent-visible search / context result item. The agent-facing key is\n * {@link IMemoryToolResultItem.handle | handle}: the host mnemonic when a\n * {@link ICreateMemoryToolsParams.handleFor | handleFor} hook is supplied, else\n * the raw {@link MemoryId}.\n * @public\n */\nexport interface IMemoryToolResultItem {\n /** The agent-visible key (host handle when supplied, raw {@link MemoryId} otherwise). */\n readonly handle: string;\n /** The record's {@link Kind}. */\n readonly kind: Kind;\n /** The record's domain {@link EntityId}. */\n readonly entityId: EntityId;\n /** The record's tags. */\n readonly tags: ReadonlyArray<string>;\n /** The record body (a markdown string in B1). */\n readonly body: unknown;\n}\n\n/**\n * Parameters for {@link createMemoryTools}.\n *\n * @remarks\n * **Scope isolation is constructor-fixed.** The {@link\n * ICreateMemoryToolsParams.store | store} is the sole scope authority — it is the\n * actor's own, pre-scoped memory root. No tool's `parametersSchema` declares a\n * `scope` (or any scope-widening) property, so an LLM cannot steer a tool at\n * another actor's memory.\n * @public\n */\nexport interface ICreateMemoryToolsParams {\n /**\n * The pre-scoped memory store (the actor's own memory root). Sole scope\n * authority — backs `memory_write` / `memory_read` / `memory_delete`.\n */\n readonly store: IMemoryStore;\n /** Retriever backing `memory_search` (and `memory_context` via link traversal). */\n readonly retriever: IMemoryRetriever;\n /** Body converter registry — gates the toolable kinds via `has(kind)`. */\n readonly registry: IBodyConverterRegistry;\n /**\n * The per-tool enable subset. Defaults to {@link DEFAULT_MEMORY_TOOLS} (the\n * read-only set). Name `memory_write` / `memory_delete` here to opt into the\n * mutating tools.\n */\n readonly tools?: ReadonlyArray<MemoryToolName>;\n /**\n * Optional whitelist of toolable kinds. When present, a tool `kind` argument\n * outside this set is rejected. When absent, {@link\n * IBodyConverterRegistry.has | registry.has} is the sole kind gate.\n */\n readonly kinds?: ReadonlyArray<Kind>;\n /**\n * Per-kind identity codecs, used by `memory_write` to map the domain\n * {@link EntityId} to the record's storage id (the store resolves codecs\n * internally for `get` / `delete`, so read / delete do not need them). Absent\n * → `memory_write` uses {@link ICreateMemoryToolsParams.defaultCodec |\n * defaultCodec}, and fails loudly for a kind with no resolvable codec. The\n * read-only default tool set needs no codecs.\n */\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n /** Default identity codec for kinds without an explicit {@link ICreateMemoryToolsParams.codecs | codecs} entry. */\n readonly defaultCodec?: IIdentityCodec;\n /**\n * Optional host hook mapping a record to its agent-visible handle (an evocative\n * mnemonic tag). When supplied, `memory_search` / `memory_context` results use\n * the returned handle as the agent-visible key; when absent the raw\n * {@link MemoryId} is used.\n */\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n /**\n * Optional host projector mapping a record (and the requested detail tier) to\n * its agent-visible {@link IMemoryToolResultItem}. When supplied, every\n * `memory_search` / `memory_context` / `memory_read` result item is produced by\n * this callback — the host owns how much of the body a `'gist'` vs `'full'`\n * result carries, so it can bound the default (`'gist'`) path.\n *\n * When absent, the built-in default projection is used (full body plus the\n * {@link ICreateMemoryToolsParams.handleFor | handleFor} handle), which ignores\n * the detail tier — behavior is byte-identical to a build with no projector.\n *\n * The callback is guarded exactly like `handleFor`: a throw degrades to the\n * default full-body projection for that item rather than failing the whole\n * search.\n */\n readonly projectItem?: (record: IMemoryRecord<unknown>, detail: MemoryDetailTier) => IMemoryToolResultItem;\n}\n\n/**\n * The detail tier a `memory_search` / `memory_context` result is projected at.\n * `'gist'` is the default (bounded) path; `'full'` is opt-in. Only meaningful\n * when a host {@link ICreateMemoryToolsParams.projectItem | projectItem} is\n * supplied — the built-in default projection returns the full body regardless.\n * @public\n */\nexport type MemoryDetailTier = 'gist' | 'full';\n\n/** The resolved factory context threaded into each tool's `execute`. */\ninterface IToolContext {\n readonly store: IMemoryStore;\n readonly retriever: IMemoryRetriever;\n readonly registry: IBodyConverterRegistry;\n readonly kinds?: ReadonlyArray<Kind>;\n readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;\n readonly defaultCodec?: IIdentityCodec;\n readonly handleFor?: (record: IMemoryRecord<unknown>) => string;\n readonly projectItem?: (record: IMemoryRecord<unknown>, detail: MemoryDetailTier) => IMemoryToolResultItem;\n}\n\n// ---------------------------------------------------------------------------\n// Parameter schemas — authored once via JsonSchema.object(...); the schema IS\n// both the wire schema (.toJson()) and the runtime validator (.convert()).\n// NONE of these declare a `scope` (or scope-widening) property — the adoption\n// gate is enforced structurally and asserted in the tests.\n// ---------------------------------------------------------------------------\n\n/**\n * The scope-qualified target of a link edge authored by the agent on a write.\n * `scope` is optional: when omitted it defaults to the writing record's OWN\n * resolved scope (the common same-conversation case); supply it explicitly to\n * point an edge at a record in a different scope.\n */\n// eslint-disable-next-line @rushstack/typedef-var\nconst linkTargetSchema = JsonSchema.object({\n id: JsonSchema.string({ description: 'The MemoryId of the record this edge points at.' }),\n scope: JsonSchema.optional(\n JsonSchema.string({\n description: \"The target record's scope. Defaults to the writing record's own scope when omitted.\"\n })\n )\n});\n\n/** A single attributed link edge as authored by the agent on a write. */\n// eslint-disable-next-line @rushstack/typedef-var\nconst linkEdgeSchema = JsonSchema.object({\n type: JsonSchema.string({ description: 'The relation type of the link.' }),\n target: linkTargetSchema,\n confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst writeSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind (must be an enabled, registered kind).' }),\n entityId: JsonSchema.string({\n description:\n 'The domain entity id. For composite (e.g. medium-term) kinds this is the full composite key.'\n }),\n body: JsonSchema.string({ description: \"The serialized record body; validated by the kind's converter.\" }),\n tags: JsonSchema.optional(JsonSchema.array(JsonSchema.string({ description: 'A tag label.' }))),\n links: JsonSchema.optional(JsonSchema.array(linkEdgeSchema))\n});\ntype WriteArgs = JsonSchema.Static<typeof writeSchema>;\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst readSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to read.' }),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' | 'full' (default).\" })\n )\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst deleteSchema = JsonSchema.object({\n kind: JsonSchema.string({ description: 'The record kind.' }),\n entityId: JsonSchema.string({ description: 'The domain entity id to delete.' })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst searchSchema = JsonSchema.object({\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),\n semantic: JsonSchema.optional(\n JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })\n ),\n limit: JsonSchema.optional(\n JsonSchema.integer({\n description:\n 'Maximum number of results to return. At least one of kind, tag, semantic or limit is required.'\n })\n ),\n offset: JsonSchema.optional(\n JsonSchema.integer({ description: 'Number of results to skip after ordering, before limit. Default 0.' })\n ),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' (default) | 'full'.\" })\n )\n});\n\n/**\n * The scope-qualified seed a `memory_context` traversal starts from. Nested\n * `{ id, scope }` shape like a link target, but — unlike a write edge — there is\n * no writing record to default the scope from, so `scope` is REQUIRED to\n * disambiguate the seed across scopes (a bare stem like `turn-3` is otherwise\n * ambiguous). It is schema-required (not just runtime-required) so the wire\n * schema an LLM reads never advertises an optionality the tool does not honor.\n */\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSeedSchema = JsonSchema.object({\n id: JsonSchema.string({ description: 'The MemoryId of the seed record to traverse links from.' }),\n scope: JsonSchema.string({\n description: 'The scope of the seed record (required — a bare seed id is ambiguous across scopes).'\n })\n});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSchema = JsonSchema.object({\n from: contextSeedSchema,\n kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),\n tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),\n hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),\n limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' })),\n detail: JsonSchema.optional(\n JsonSchema.enumOf(['gist', 'full'] as const, { description: \"'gist' (default) | 'full'.\" })\n )\n});\n\n// ---------------------------------------------------------------------------\n// Behavior annotations (Component 4) — host-advisory hints; never serialized to\n// the model. openWorldHint is false throughout (a closed, local store).\n// ---------------------------------------------------------------------------\n\nconst READ_ONLY_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n readOnlyHint: true,\n openWorldHint: false\n};\n\nconst WRITE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false\n};\n\nconst DELETE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false\n};\n\n// ---------------------------------------------------------------------------\n// Shared validation / projection helpers\n// ---------------------------------------------------------------------------\n\n/** Validate a `kind` string and assert it is an enabled, registered toolable kind. */\nfunction assertKindEnabled(ctx: IToolContext, kindStr: string): Result<Kind> {\n return Convert.kind.convert(kindStr).onSuccess((kind) => {\n if (!ctx.registry.has(kind)) {\n return fail(`memory tools: kind '${kind}' has no registered body converter`);\n }\n if (ctx.kinds !== undefined && !ctx.kinds.includes(kind)) {\n return fail(`memory tools: kind '${kind}' is not enabled for memory tools`);\n }\n return succeed(kind);\n });\n}\n\n/** Validate an optional `kind` string (enabled when present; `undefined` passes through). */\nfunction resolveOptionalKind(ctx: IToolContext, kindStr?: string): Result<Kind | undefined> {\n if (kindStr === undefined) {\n return succeed(undefined);\n }\n return assertKindEnabled(ctx, kindStr);\n}\n\n/**\n * Resolve the requested detail tier from the optional tool `detail` string.\n * `'full'` is the only opt-in value; every other input (absent, or an\n * unrecognized string) resolves safely to the bounded default `'gist'`.\n */\nfunction resolveDetail(detail?: string): MemoryDetailTier {\n return detail === 'full' ? 'full' : 'gist';\n}\n\n/** The built-in default projection: full body plus the guarded host handle. Ignores the detail tier. */\nfunction defaultProjectItem(ctx: IToolContext, record: IMemoryRecord<unknown>): IMemoryToolResultItem {\n // `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than\n // escaping the Result chain (and crashing the whole search/context call).\n const handle =\n ctx.handleFor !== undefined\n ? captureResult(() => ctx.handleFor!(record)).orDefault(record.envelope.id)\n : record.envelope.id;\n return {\n handle,\n kind: record.envelope.kind,\n entityId: record.envelope.entityId,\n tags: record.envelope.tags,\n body: record.body\n };\n}\n\n/**\n * Project a record into an agent-visible result item at the requested detail\n * tier. When a host {@link ICreateMemoryToolsParams.projectItem | projectItem}\n * is supplied it owns the projection; otherwise the built-in\n * {@link defaultProjectItem} (full body) is used. The host callback is guarded\n * like `handleFor` — a throw degrades to the default full-body projection for\n * that item rather than failing the whole search/context call.\n */\nfunction projectItem(\n ctx: IToolContext,\n record: IMemoryRecord<unknown>,\n detail: MemoryDetailTier\n): IMemoryToolResultItem {\n if (ctx.projectItem === undefined) {\n return defaultProjectItem(ctx, record);\n }\n // Guard the host projector like `handleFor`: a throw degrades to the built-in\n // full-body projection (itself throw-safe) rather than escaping the chain.\n return captureResult(() => ctx.projectItem!(record, detail)).orDefault(defaultProjectItem(ctx, record));\n}\n\n/** Resolve the identity codec used by `memory_write` to derive the storage id. */\nfunction codecForWrite(ctx: IToolContext, kind: Kind): Result<IIdentityCodec> {\n const codec: IIdentityCodec | undefined = ctx.codecs?.get(kind) ?? ctx.defaultCodec;\n if (codec === undefined) {\n return fail(`memory_write: no identity codec available for kind '${kind}'`);\n }\n return succeed(codec);\n}\n\n/** Build the record to persist from validated write args (store stamps txn-time metadata). */\nfunction buildWriteRecord(\n typed: WriteArgs,\n kind: Kind,\n entityId: EntityId,\n idStem: string,\n sourceScope: string\n): Result<IMemoryRecord<unknown>> {\n // Plain shapes handed to `envelopeConverter`, which validates each field\n // (type → LinkType, target → { scope, id }) and produces the branded IEdge[].\n // An edge target with no explicit `scope` defaults to the writing record's own\n // resolved scope — the same-conversation case authors just an id.\n const links: ReadonlyArray<Record<string, unknown>> = (typed.links ?? []).map((link) => ({\n type: link.type,\n target: { scope: link.target.scope ?? sourceScope, id: link.target.id },\n ...(link.confidence !== undefined ? { confidence: link.confidence } : {})\n }));\n return envelopeConverter\n .convert({\n id: idStem,\n entityId,\n kind,\n tags: typed.tags ?? [],\n links,\n created: 0,\n updated: 0,\n seq: 0,\n contentHash: '',\n provenance: { source: 'agent' }\n })\n .withErrorFormat((msg) => `memory_write: invalid record: ${msg}`)\n .onSuccess((envelope) => succeed({ envelope, body: typed.body }));\n}\n\n/** Resolve the validated write args into the storage id + record (all synchronous). */\nfunction prepareWrite(\n ctx: IToolContext,\n typed: WriteArgs\n): Result<{ readonly kind: Kind; readonly entityId: EntityId; readonly record: IMemoryRecord<unknown> }> {\n return assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) =>\n codecForWrite(ctx, kind).onSuccess((codec) =>\n codec.encode(entityId).onSuccess((addr) => {\n if (addr.isVersioned) {\n return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);\n }\n return buildWriteRecord(typed, kind, entityId, addr.idStem, addr.scope).onSuccess((record) =>\n succeed({ kind, entityId, record })\n );\n })\n )\n )\n );\n}\n\n/**\n * Discriminate the write outcome from a pre-put snapshot and the returned record.\n * A dedup no-op returns either a different entity (content-scope dedup) or the\n * same-id record with an unchanged `seq` (entity-scope re-put); a fresh write or\n * update advances `seq`.\n */\nfunction writeOutcome(\n before: IMemoryRecord<unknown> | undefined,\n written: IMemoryRecord<unknown>,\n entityId: EntityId\n): MemoryWriteOutcome {\n if (written.envelope.entityId !== entityId) {\n return 'deduped';\n }\n if (before !== undefined && written.envelope.seq === before.envelope.seq) {\n return 'deduped';\n }\n return 'written';\n}\n\n// ---------------------------------------------------------------------------\n// Tool builders — config with a JsonSchema.object(...) parametersSchema; execute\n// validates/narrows → delegates to store/retriever → returns the Result (never\n// swallowed), following the ts-extras-mcp adapter shape.\n//\n// Each `execute` re-runs its own `parametersSchema.convert(args)` even though the\n// `executeClientToolTurn` harness already validates against the same schema. This\n// is deliberate: the factory returns a heterogeneous `ReadonlyArray<IAiClientTool>`\n// (TParams erased to `unknown`, since the members carry different param shapes), so\n// `execute` receives `unknown` and must narrow it back to the typed args. The\n// re-validation is also the narrowing step exercised by the direct-call tests (which\n// invoke `execute` with raw args, bypassing the harness). Re-validating an\n// already-conforming shape is a cheap, side-effect-free identity.\n// ---------------------------------------------------------------------------\n\nfunction buildWriteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_write',\n description:\n 'Store a new memory record or update an existing one by (kind, entityId). ' +\n 'Identical content is a no-op that returns the existing record.',\n parametersSchema: writeSchema,\n annotations: WRITE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n writeSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_write: invalid arguments: ${msg}`)\n .onSuccess((typed) => prepareWrite(ctx, typed))\n .thenOnSuccess(async ({ kind, entityId, record }) =>\n // Read the prior record to discriminate written-vs-deduped. A `Failure`\n // here (corrupt file, I/O error, codec round-trip failure) is a real\n // condition distinct from the \"not found\" success (`undefined`); propagate\n // it rather than defaulting it away, so a genuine store fault surfaces\n // instead of being masked as a normal write.\n (await ctx.store.get(kind, entityId)).thenOnSuccess(async (before) =>\n (await ctx.store.put(record)).onSuccess((persisted) =>\n succeed<IMemoryWriteResult>({\n outcome: writeOutcome(before, persisted, entityId),\n id: persisted.envelope.id,\n entityId,\n kind\n })\n )\n )\n )\n };\n}\n\nfunction buildReadTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_read',\n description: 'Read a specific memory record by (kind, entityId).',\n parametersSchema: readSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n readSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => {\n // `memory_read` is the explicit drill-in path, so its detail default is\n // INVERTED vs search/context: `'full'` unless the caller opts down to `'gist'`.\n const detail: MemoryDetailTier = typed.detail === 'gist' ? 'gist' : 'full';\n return succeed({ kind, entityId, detail });\n })\n )\n )\n .thenOnSuccess(async ({ kind, entityId, detail }) =>\n (await ctx.store.get(kind, entityId)).onSuccess((record) =>\n record === undefined\n ? succeed({ found: false })\n : succeed({ found: true, item: projectItem(ctx, record, detail) })\n )\n )\n };\n}\n\nfunction buildSearchTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_search',\n description:\n 'Search memories by tag, kind, or semantic text. Returns ranked results. ' +\n 'At least one of kind, tag, semantic or limit must be supplied.',\n parametersSchema: searchSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n searchSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))\n )\n )\n .onSuccess(({ typed, kind, tag }) => {\n // A search with no axis at all is a whole-vault read issued by a model,\n // and since the index holds envelopes only it materializes every body\n // to answer. An LLM asking for \"everything\" is nearly always an\n // under-specified query rather than an intended full scan, so this\n // refuses instead of serving it — the model can retry with an axis,\n // which is the outcome we want anyway.\n //\n // `limit` counts: an ordered top-N materializes N records rather than\n // the vault (see `resolveQuery`), so it bounds the read as genuinely as\n // `kind` or `tag` does.\n if (\n kind === undefined &&\n tag === undefined &&\n typed.semantic === undefined &&\n typed.limit === undefined\n ) {\n return fail<{ typed: typeof typed; kind: typeof kind; tag: typeof tag }>(\n 'memory_search: supply at least one of kind, tag, semantic or limit — ' +\n 'an unrestricted search reads every record in the vault'\n );\n }\n return succeed({ typed, kind, tag });\n })\n .thenOnSuccess(async ({ typed, kind, tag }) => {\n const detail: MemoryDetailTier = resolveDetail(typed.detail);\n const query: IMemoryQuery = {\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.semantic !== undefined ? { semantic: typed.semantic } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {}),\n ...(typed.offset !== undefined ? { offset: typed.offset } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r, detail)) })\n );\n })\n };\n}\n\nfunction buildContextTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_context',\n description:\n 'Build a context graph from a seed memory: returns the records linked from the seed, up to `hops` hops.',\n parametersSchema: contextSchema,\n annotations: READ_ONLY_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n contextSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n resolveContextSeed(typed.from).onSuccess((from) =>\n resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>\n resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag }))\n )\n )\n )\n .thenOnSuccess(async ({ typed, from, kind, tag }) => {\n const detail: MemoryDetailTier = resolveDetail(typed.detail);\n const query: IMemoryQuery = {\n linkedFrom: from,\n ...(kind !== undefined ? { kind } : {}),\n ...(tag !== undefined ? { tag } : {}),\n ...(typed.hops !== undefined ? { hops: typed.hops } : {}),\n ...(typed.limit !== undefined ? { limit: typed.limit } : {})\n };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({\n seed: from,\n count: records.length,\n results: records.map((r) => projectItem(ctx, r, detail))\n })\n );\n })\n };\n}\n\nfunction buildDeleteTool(ctx: IToolContext): AiAssist.IAiClientTool {\n return {\n config: {\n type: 'client_tool',\n name: 'memory_delete',\n description: 'Delete a memory record by (kind, entityId). Destructive for non-temporal kinds.',\n parametersSchema: deleteSchema,\n annotations: DELETE_ANNOTATIONS\n },\n execute: async (args: unknown): Promise<Result<unknown>> =>\n deleteSchema\n .convert(args)\n .withErrorFormat((msg) => `memory_delete: invalid arguments: ${msg}`)\n .onSuccess((typed) =>\n assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>\n Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))\n )\n )\n .thenOnSuccess(async ({ kind, entityId }) =>\n (await ctx.store.delete(kind, entityId)).onSuccess((id) =>\n succeed({ deleted: true, id, entityId, kind })\n )\n )\n };\n}\n\n/**\n * Resolve a `memory_context` seed argument into a scope-qualified\n * {@link IEdgeTarget}. Both `id` and `scope` are present here — the tool's\n * `parametersSchema` ({@link contextSeedSchema}) makes `scope` schema-required —\n * so this only brands the two fields; a malformed value fails via the branded\n * converters (e.g. a path-unsafe seed id).\n */\nfunction resolveContextSeed(from: { readonly id: string; readonly scope: string }): Result<IEdgeTarget> {\n return Convert.memoryId\n .convert(from.id)\n .onSuccess((id) => Convert.scopeKey.convert(from.scope).onSuccess((scope) => succeed({ scope, id })));\n}\n\n/** Validate an optional `tag` string (`undefined` passes through). */\nfunction resolveOptionalTag(tagStr?: string): Result<Tag | undefined> {\n if (tagStr === undefined) {\n return succeed(undefined);\n }\n return Convert.tag.convert(tagStr);\n}\n\n/** Ordered registry of the five tool builders, keyed by name. */\nconst TOOL_BUILDERS: ReadonlyArray<{\n readonly name: MemoryToolName;\n readonly build: (ctx: IToolContext) => AiAssist.IAiClientTool;\n}> = [\n { name: 'memory_write', build: buildWriteTool },\n { name: 'memory_read', build: buildReadTool },\n { name: 'memory_search', build: buildSearchTool },\n { name: 'memory_context', build: buildContextTool },\n { name: 'memory_delete', build: buildDeleteTool }\n];\n\n/**\n * Build the selected suite of memory `AiAssist.IAiClientTool`s over a\n * pre-scoped store — ready to hand to `AiAssist.executeClientToolTurn` (and, via\n * the shared `JsonSchema.object(...)` schemas, `@fgv/ts-extras-mcp`).\n *\n * @remarks\n * **Scope isolation is make-or-break.** The returned tools close over the\n * pre-scoped {@link ICreateMemoryToolsParams.store | store}; no tool's\n * `parametersSchema` declares a `scope` (or any scope-widening) property, so an\n * LLM cannot steer a tool at another actor's memory. The store instance is the\n * sole scope authority.\n *\n * The default selection is {@link DEFAULT_MEMORY_TOOLS} (the read-only set) —\n * `memory_write` / `memory_delete` are included only when named in\n * {@link ICreateMemoryToolsParams.tools | tools}.\n * @public\n */\nexport function createMemoryTools(params: ICreateMemoryToolsParams): ReadonlyArray<AiAssist.IAiClientTool> {\n const ctx: IToolContext = {\n store: params.store,\n retriever: params.retriever,\n registry: params.registry,\n kinds: params.kinds,\n codecs: params.codecs,\n defaultCodec: params.defaultCodec,\n handleFor: params.handleFor,\n projectItem: params.projectItem\n };\n const selected: ReadonlySet<MemoryToolName> = new Set<MemoryToolName>(params.tools ?? DEFAULT_MEMORY_TOOLS);\n return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));\n}\n"]}
|
|
@@ -139,7 +139,7 @@ export interface IMemoryEnvelope {
|
|
|
139
139
|
* below every subsequently-written one regardless of what the projector would
|
|
140
140
|
* have scored them, so the result is not a partial ordering but one inverted
|
|
141
141
|
* with respect to the projector's intent, with nothing failing to say so. Call
|
|
142
|
-
* `IMemoryStore.
|
|
142
|
+
* `IMemoryStore.reconcile(kind, 'rank')` after registering a projector against a
|
|
143
143
|
* populated store.
|
|
144
144
|
*/
|
|
145
145
|
readonly rank?: number;
|
|
@@ -166,6 +166,28 @@ export interface IMemoryRecord<TBody = unknown> {
|
|
|
166
166
|
/** The per-kind, Converter-validated body. */
|
|
167
167
|
readonly body: TBody;
|
|
168
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* The envelope's embedding reference if it carries a usable one, `undefined`
|
|
171
|
+
* otherwise — **the one place `null`-vs-absent is collapsed.**
|
|
172
|
+
*
|
|
173
|
+
* @remarks
|
|
174
|
+
* {@link IMemoryEnvelope.embeddingRef} is `string | null | undefined`, where
|
|
175
|
+
* `null` and absent both mean *not embedded* (`null` is the explicit sentinel;
|
|
176
|
+
* absent is the backwards-compat seam). That makes the obvious presence check
|
|
177
|
+
* wrong in **both** directions, and both mistakes were shipped before this
|
|
178
|
+
* accessor existed: `!== undefined` counts a `null` as an embedding that is not
|
|
179
|
+
* there, and `=== undefined` misses a `null` when looking for one that is
|
|
180
|
+
* missing. Neither is a type error, and neither is visible to a coverage gate,
|
|
181
|
+
* because the sentinel is a *value* rather than a branch.
|
|
182
|
+
*
|
|
183
|
+
* Returning the reference rather than a boolean is deliberate: a caller that
|
|
184
|
+
* needs the string gets the check for free, so there is no second, weaker way
|
|
185
|
+
* to ask.
|
|
186
|
+
*
|
|
187
|
+
* **Do not test `embeddingRef` for presence directly — call this.**
|
|
188
|
+
* @public
|
|
189
|
+
*/
|
|
190
|
+
export declare function embeddingRefOf(envelope: IMemoryEnvelope): string | undefined;
|
|
169
191
|
/**
|
|
170
192
|
* A per-kind host projection from a fully-resolved (post-merge) memory record
|
|
171
193
|
* to a numeric ordering value. Registered per kind at store construction (see
|
|
@@ -176,7 +198,7 @@ export interface IMemoryRecord<TBody = unknown> {
|
|
|
176
198
|
* for this record" (logged at `warn`), never failing the write.
|
|
177
199
|
*
|
|
178
200
|
* Runs on writes only. To apply a newly-registered projector to records that
|
|
179
|
-
* already exist, call `IMemoryStore.
|
|
201
|
+
* already exist, call `IMemoryStore.reconcile(kind, 'rank')`.
|
|
180
202
|
* @public
|
|
181
203
|
*/
|
|
182
204
|
export type RankProjector = (record: IMemoryRecord<unknown>) => number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../../src/packlets/types/envelope.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAEhF;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG,aAAa,GAAG,OAAO,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAEjF;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC1B,uCAAuC;IACvC,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;IAClC,oEAAoE;IACpE,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,uCAAuC;IACvC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;;OAMG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACnC,iFAAiF;IACjF,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACjC;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW;I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a,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC"}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
7
|
exports.edgeTargetKey = edgeTargetKey;
|
|
8
|
+
exports.embeddingRefOf = embeddingRefOf;
|
|
8
9
|
/**
|
|
9
10
|
* The canonical composite-key string for an {@link IEdgeTarget}: scope + id,
|
|
10
11
|
* NUL-separated. NUL is excluded from both components (scope segments are
|
|
@@ -18,4 +19,29 @@ exports.edgeTargetKey = edgeTargetKey;
|
|
|
18
19
|
function edgeTargetKey(target) {
|
|
19
20
|
return `${target.scope}\0${target.id}`;
|
|
20
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* The envelope's embedding reference if it carries a usable one, `undefined`
|
|
24
|
+
* otherwise — **the one place `null`-vs-absent is collapsed.**
|
|
25
|
+
*
|
|
26
|
+
* @remarks
|
|
27
|
+
* {@link IMemoryEnvelope.embeddingRef} is `string | null | undefined`, where
|
|
28
|
+
* `null` and absent both mean *not embedded* (`null` is the explicit sentinel;
|
|
29
|
+
* absent is the backwards-compat seam). That makes the obvious presence check
|
|
30
|
+
* wrong in **both** directions, and both mistakes were shipped before this
|
|
31
|
+
* accessor existed: `!== undefined` counts a `null` as an embedding that is not
|
|
32
|
+
* there, and `=== undefined` misses a `null` when looking for one that is
|
|
33
|
+
* missing. Neither is a type error, and neither is visible to a coverage gate,
|
|
34
|
+
* because the sentinel is a *value* rather than a branch.
|
|
35
|
+
*
|
|
36
|
+
* Returning the reference rather than a boolean is deliberate: a caller that
|
|
37
|
+
* needs the string gets the check for free, so there is no second, weaker way
|
|
38
|
+
* to ask.
|
|
39
|
+
*
|
|
40
|
+
* **Do not test `embeddingRef` for presence directly — call this.**
|
|
41
|
+
* @public
|
|
42
|
+
*/
|
|
43
|
+
function embeddingRefOf(envelope) {
|
|
44
|
+
var _a;
|
|
45
|
+
return (_a = envelope.embeddingRef) !== null && _a !== void 0 ? _a : undefined;
|
|
46
|
+
}
|
|
21
47
|
//# sourceMappingURL=envelope.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../src/packlets/types/envelope.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAmEH,sCAEC;AAZD;;;;;;;;;GASG;AACH,SAAgB,aAAa,CAAC,MAAmB;IAC/C,OAAO,GAAG,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,EAAE,EAAE,CAAC;AACzC,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { EntityId, Kind, LinkType, MemoryId, MemoryScopeKey, Tag } from './ids';\n\n/**\n * Origin of a provenance attribution. Open vocabulary: the three named\n * sources are conventional, but the `(string & {})` arm admits any other\n * source string without resignature.\n * @public\n */\nexport type ProvenanceSource = 'agent' | 'host-ingest' | 'human' | (string & {});\n\n/**\n * Structured provenance for a record or an edge. Never a flat enum — the\n * `[key: string]: unknown` index signature lets a consumer attach an opaque\n * domain payload (e.g. PersonAIlity's sentiment / epistemic blocks) without\n * changing this interface, while still satisfying the no-`any` rule.\n * @public\n */\nexport interface IProvenance {\n /** Where the attribution came from. */\n readonly source: ProvenanceSource;\n /** Optional human or agent identifier responsible for the write. */\n readonly by?: string;\n /** Optional model identifier, when a model produced the content. */\n readonly model?: string;\n /** Optional confidence in `[0, 1]`. */\n readonly confidence?: number;\n /**\n * Scope-qualified back-link to the source record. Enables the cross-kind\n * provenance spine. A scope-qualified {@link IEdgeTarget} (not a bare\n * {@link MemoryId}) because per-scope codecs (e.g. the MTM codec's `turn-<n>`\n * stems) legally reuse a stem across scopes, so a bare id would be ambiguous —\n * the same reason {@link IEdge.target} is scope-qualified.\n */\n readonly derivedFrom?: IEdgeTarget;\n /** Opaque extension payload — consumer-owned, never interpreted by the store. */\n readonly [key: string]: unknown;\n}\n\n/**\n * The physical address of a linked-to record: the `(scope, id)` pair that\n * uniquely identifies it. Both components are required because a bare\n * {@link MemoryId} is NOT unique across scopes — per-scope codecs (e.g. the\n * medium-term codec's `turn-<n>` stems) legally mint the same stem under\n * different scopes, so an edge that carried only the id would be ambiguous.\n * `(scope, id)` matches the store's `getById(scope, id)` addressing and the\n * index's composite primary key.\n * @public\n */\nexport interface IEdgeTarget {\n /** The scope the target record lives under. */\n readonly scope: MemoryScopeKey;\n /** The target record's stable file-stem id (unique WITHIN {@link IEdgeTarget.scope}). */\n readonly id: MemoryId;\n}\n\n/**\n * The canonical composite-key string for an {@link IEdgeTarget}: scope + id,\n * NUL-separated. NUL is excluded from both components (scope segments are\n * filename-safe; {@link MemoryId} is portable-filename-safe), so it is a\n * collision-proof separator. This is the ONE canonicalization every consumer\n * that keys on a scoped target uses — the backlink index, the cycle guard, and\n * the ingest edge-validation path all route through it so their notions of\n * \"same target\" cannot drift.\n * @public\n */\nexport function edgeTargetKey(target: IEdgeTarget): string {\n return `${target.scope}\\0${target.id}`;\n}\n\n/**\n * An attributed link between two records. Carries the relation type, the\n * scope-qualified {@link IEdgeTarget | target}, and optional confidence /\n * provenance / world-truth validity. Replaces bare string references (e.g.\n * PersonAIlity's `IMtmRef` becomes an `IEdge` with `type: LinkType('mtm-ref')`).\n * @public\n */\nexport interface IEdge {\n /** Open-vocabulary relation type. */\n readonly type: LinkType;\n /** The scope-qualified address of the linked-to record. */\n readonly target: IEdgeTarget;\n /** Optional confidence in `[0, 1]`. */\n readonly confidence?: number;\n /** Optional structured provenance for the link itself. */\n readonly provenance?: IProvenance;\n /** World-truth validity start (epoch ms). Present only on temporal edges. */\n readonly valid_at?: number;\n /**\n * World-truth validity end (epoch ms). `null` = still valid; absent = no\n * temporal extent.\n */\n // eslint-disable-next-line @rushstack/no-new-null -- null is a meaningful value here (still-valid) distinct from absent (no temporal extent); design-lock §2.3\n readonly invalid_at?: number | null;\n}\n\n/**\n * Optional bi-temporal validity block on an envelope. Present only on\n * temporal kinds; absent = zero cost for atemporal kinds.\n * @public\n */\nexport interface ITemporalBlock {\n /** World-truth validity start (epoch ms). */\n readonly valid_at?: number;\n /** World-truth validity end (epoch ms). `null` = still valid. */\n // eslint-disable-next-line @rushstack/no-new-null -- null is a meaningful value here (still-valid) distinct from absent; design-lock §2.4\n readonly invalid_at?: number | null;\n}\n\n/**\n * The invariant identity + transaction-time envelope carried by every memory\n * record, independent of the per-kind body.\n * @public\n */\nexport interface IMemoryEnvelope {\n // --- Core identity ---\n /** Stable file-stem identifier. MUST equal the on-disk filename stem. */\n readonly id: MemoryId;\n /** Consumer-supplied domain key. Equals {@link IMemoryEnvelope.id | id} for non-temporal kinds. */\n readonly entityId: EntityId;\n /** Consumer-registered kind; dispatches the body Converter. */\n readonly kind: Kind;\n /** Open-vocabulary tags. */\n readonly tags: ReadonlyArray<Tag>;\n /** Attributed outbound edges. */\n readonly links: ReadonlyArray<IEdge>;\n\n // --- Transaction-time metadata (always present) ---\n /** Epoch ms of the first write. Immutable after creation. */\n readonly created: number;\n /** Epoch ms of the most recent write. */\n readonly updated: number;\n /**\n * Monotonic write counter within the store instance, assigned by the store\n * on every successful put. Enables stable cursor paging over observation\n * records without a full walk.\n */\n readonly seq: number;\n /**\n * Content hash over the canonical `{ kind, body, links }`. The dedup key:\n * an exact match is a no-op upsert that returns the existing record.\n */\n readonly contentHash: string;\n /**\n * Store-computed host-defined ordering value, produced by the kind's\n * {@link RankProjector} on every put/update and stamped into the envelope in\n * the same pass that recomputes {@link IMemoryEnvelope.contentHash | contentHash}.\n * Absent when the kind has no registered projector (or the projector threw on\n * this record). Ordered retrieval (`orderBy: 'rank'`) and the index's rank view\n * sort by this value descending, placing records with an absent `rank` last.\n *\n * **The projector runs on the write path only — registering one does not rank\n * records already in the store.** Because absent sorts last, those records land\n * below every subsequently-written one regardless of what the projector would\n * have scored them, so the result is not a partial ordering but one inverted\n * with respect to the projector's intent, with nothing failing to say so. Call\n * `IMemoryStore.reconcileRank` after registering a projector against a\n * populated store.\n */\n readonly rank?: number;\n /** Structured provenance (never a flat enum). */\n readonly provenance: IProvenance;\n\n // --- Optional temporal block ---\n /** Bi-temporal validity. Present only on temporal kinds. */\n readonly temporal?: ITemporalBlock;\n\n /**\n * Vector-index entry reference, set by the vector index on write. `null` =\n * not embedded; absent = same as `null` (backwards-compat seam).\n */\n // eslint-disable-next-line @rushstack/no-new-null -- null is the explicit \"not embedded\" sentinel distinct from absent (backwards-compat seam); design-lock §2.5\n readonly embeddingRef?: string | null;\n}\n\n/**\n * A complete memory record: the invariant {@link IMemoryEnvelope} plus the\n * typed, per-kind body. The store's public surface uses\n * `IMemoryRecord<unknown>`; consumers narrow `TBody` by checking\n * `envelope.kind` and validating through the registered Converter.\n * @public\n */\nexport interface IMemoryRecord<TBody = unknown> {\n /** The invariant identity + transaction-time envelope. */\n readonly envelope: IMemoryEnvelope;\n /** The per-kind, Converter-validated body. */\n readonly body: TBody;\n}\n\n/**\n * A per-kind host projection from a fully-resolved (post-merge) memory record\n * to a numeric ordering value. Registered per kind at store construction (see\n * `rankProjectors`); the store runs it on every put/update over the same\n * resolved record whose `contentHash` it computes, stamping the result into\n * {@link IMemoryEnvelope.rank}. The store never interprets the body — the host\n * owns what the number means. A projector that throws is treated as \"no rank\n * for this record\" (logged at `warn`), never failing the write.\n *\n * Runs on writes only. To apply a newly-registered projector to records that\n * already exist, call `IMemoryStore.reconcileRank`.\n * @public\n */\nexport type RankProjector = (record: IMemoryRecord<unknown>) => number;\n"]}
|
|
1
|
+
{"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../src/packlets/types/envelope.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAmEH,sCAEC;AA8ID,wCAEC;AA5JD;;;;;;;;;GASG;AACH,SAAgB,aAAa,CAAC,MAAmB;IAC/C,OAAO,GAAG,MAAM,CAAC,KAAK,KAAK,MAAM,CAAC,EAAE,EAAE,CAAC;AACzC,CAAC;AAyHD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAgB,cAAc,CAAC,QAAyB;;IACtD,OAAO,MAAA,QAAQ,CAAC,YAAY,mCAAI,SAAS,CAAC;AAC5C,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { EntityId, Kind, LinkType, MemoryId, MemoryScopeKey, Tag } from './ids';\n\n/**\n * Origin of a provenance attribution. Open vocabulary: the three named\n * sources are conventional, but the `(string & {})` arm admits any other\n * source string without resignature.\n * @public\n */\nexport type ProvenanceSource = 'agent' | 'host-ingest' | 'human' | (string & {});\n\n/**\n * Structured provenance for a record or an edge. Never a flat enum — the\n * `[key: string]: unknown` index signature lets a consumer attach an opaque\n * domain payload (e.g. PersonAIlity's sentiment / epistemic blocks) without\n * changing this interface, while still satisfying the no-`any` rule.\n * @public\n */\nexport interface IProvenance {\n /** Where the attribution came from. */\n readonly source: ProvenanceSource;\n /** Optional human or agent identifier responsible for the write. */\n readonly by?: string;\n /** Optional model identifier, when a model produced the content. */\n readonly model?: string;\n /** Optional confidence in `[0, 1]`. */\n readonly confidence?: number;\n /**\n * Scope-qualified back-link to the source record. Enables the cross-kind\n * provenance spine. A scope-qualified {@link IEdgeTarget} (not a bare\n * {@link MemoryId}) because per-scope codecs (e.g. the MTM codec's `turn-<n>`\n * stems) legally reuse a stem across scopes, so a bare id would be ambiguous —\n * the same reason {@link IEdge.target} is scope-qualified.\n */\n readonly derivedFrom?: IEdgeTarget;\n /** Opaque extension payload — consumer-owned, never interpreted by the store. */\n readonly [key: string]: unknown;\n}\n\n/**\n * The physical address of a linked-to record: the `(scope, id)` pair that\n * uniquely identifies it. Both components are required because a bare\n * {@link MemoryId} is NOT unique across scopes — per-scope codecs (e.g. the\n * medium-term codec's `turn-<n>` stems) legally mint the same stem under\n * different scopes, so an edge that carried only the id would be ambiguous.\n * `(scope, id)` matches the store's `getById(scope, id)` addressing and the\n * index's composite primary key.\n * @public\n */\nexport interface IEdgeTarget {\n /** The scope the target record lives under. */\n readonly scope: MemoryScopeKey;\n /** The target record's stable file-stem id (unique WITHIN {@link IEdgeTarget.scope}). */\n readonly id: MemoryId;\n}\n\n/**\n * The canonical composite-key string for an {@link IEdgeTarget}: scope + id,\n * NUL-separated. NUL is excluded from both components (scope segments are\n * filename-safe; {@link MemoryId} is portable-filename-safe), so it is a\n * collision-proof separator. This is the ONE canonicalization every consumer\n * that keys on a scoped target uses — the backlink index, the cycle guard, and\n * the ingest edge-validation path all route through it so their notions of\n * \"same target\" cannot drift.\n * @public\n */\nexport function edgeTargetKey(target: IEdgeTarget): string {\n return `${target.scope}\\0${target.id}`;\n}\n\n/**\n * An attributed link between two records. Carries the relation type, the\n * scope-qualified {@link IEdgeTarget | target}, and optional confidence /\n * provenance / world-truth validity. Replaces bare string references (e.g.\n * PersonAIlity's `IMtmRef` becomes an `IEdge` with `type: LinkType('mtm-ref')`).\n * @public\n */\nexport interface IEdge {\n /** Open-vocabulary relation type. */\n readonly type: LinkType;\n /** The scope-qualified address of the linked-to record. */\n readonly target: IEdgeTarget;\n /** Optional confidence in `[0, 1]`. */\n readonly confidence?: number;\n /** Optional structured provenance for the link itself. */\n readonly provenance?: IProvenance;\n /** World-truth validity start (epoch ms). Present only on temporal edges. */\n readonly valid_at?: number;\n /**\n * World-truth validity end (epoch ms). `null` = still valid; absent = no\n * temporal extent.\n */\n // eslint-disable-next-line @rushstack/no-new-null -- null is a meaningful value here (still-valid) distinct from absent (no temporal extent); design-lock §2.3\n readonly invalid_at?: number | null;\n}\n\n/**\n * Optional bi-temporal validity block on an envelope. Present only on\n * temporal kinds; absent = zero cost for atemporal kinds.\n * @public\n */\nexport interface ITemporalBlock {\n /** World-truth validity start (epoch ms). */\n readonly valid_at?: number;\n /** World-truth validity end (epoch ms). `null` = still valid. */\n // eslint-disable-next-line @rushstack/no-new-null -- null is a meaningful value here (still-valid) distinct from absent; design-lock §2.4\n readonly invalid_at?: number | null;\n}\n\n/**\n * The invariant identity + transaction-time envelope carried by every memory\n * record, independent of the per-kind body.\n * @public\n */\nexport interface IMemoryEnvelope {\n // --- Core identity ---\n /** Stable file-stem identifier. MUST equal the on-disk filename stem. */\n readonly id: MemoryId;\n /** Consumer-supplied domain key. Equals {@link IMemoryEnvelope.id | id} for non-temporal kinds. */\n readonly entityId: EntityId;\n /** Consumer-registered kind; dispatches the body Converter. */\n readonly kind: Kind;\n /** Open-vocabulary tags. */\n readonly tags: ReadonlyArray<Tag>;\n /** Attributed outbound edges. */\n readonly links: ReadonlyArray<IEdge>;\n\n // --- Transaction-time metadata (always present) ---\n /** Epoch ms of the first write. Immutable after creation. */\n readonly created: number;\n /** Epoch ms of the most recent write. */\n readonly updated: number;\n /**\n * Monotonic write counter within the store instance, assigned by the store\n * on every successful put. Enables stable cursor paging over observation\n * records without a full walk.\n */\n readonly seq: number;\n /**\n * Content hash over the canonical `{ kind, body, links }`. The dedup key:\n * an exact match is a no-op upsert that returns the existing record.\n */\n readonly contentHash: string;\n /**\n * Store-computed host-defined ordering value, produced by the kind's\n * {@link RankProjector} on every put/update and stamped into the envelope in\n * the same pass that recomputes {@link IMemoryEnvelope.contentHash | contentHash}.\n * Absent when the kind has no registered projector (or the projector threw on\n * this record). Ordered retrieval (`orderBy: 'rank'`) and the index's rank view\n * sort by this value descending, placing records with an absent `rank` last.\n *\n * **The projector runs on the write path only — registering one does not rank\n * records already in the store.** Because absent sorts last, those records land\n * below every subsequently-written one regardless of what the projector would\n * have scored them, so the result is not a partial ordering but one inverted\n * with respect to the projector's intent, with nothing failing to say so. Call\n * `IMemoryStore.reconcile(kind, 'rank')` after registering a projector against a\n * populated store.\n */\n readonly rank?: number;\n /** Structured provenance (never a flat enum). */\n readonly provenance: IProvenance;\n\n // --- Optional temporal block ---\n /** Bi-temporal validity. Present only on temporal kinds. */\n readonly temporal?: ITemporalBlock;\n\n /**\n * Vector-index entry reference, set by the vector index on write. `null` =\n * not embedded; absent = same as `null` (backwards-compat seam).\n */\n // eslint-disable-next-line @rushstack/no-new-null -- null is the explicit \"not embedded\" sentinel distinct from absent (backwards-compat seam); design-lock §2.5\n readonly embeddingRef?: string | null;\n}\n\n/**\n * A complete memory record: the invariant {@link IMemoryEnvelope} plus the\n * typed, per-kind body. The store's public surface uses\n * `IMemoryRecord<unknown>`; consumers narrow `TBody` by checking\n * `envelope.kind` and validating through the registered Converter.\n * @public\n */\nexport interface IMemoryRecord<TBody = unknown> {\n /** The invariant identity + transaction-time envelope. */\n readonly envelope: IMemoryEnvelope;\n /** The per-kind, Converter-validated body. */\n readonly body: TBody;\n}\n\n/**\n * The envelope's embedding reference if it carries a usable one, `undefined`\n * otherwise — **the one place `null`-vs-absent is collapsed.**\n *\n * @remarks\n * {@link IMemoryEnvelope.embeddingRef} is `string | null | undefined`, where\n * `null` and absent both mean *not embedded* (`null` is the explicit sentinel;\n * absent is the backwards-compat seam). That makes the obvious presence check\n * wrong in **both** directions, and both mistakes were shipped before this\n * accessor existed: `!== undefined` counts a `null` as an embedding that is not\n * there, and `=== undefined` misses a `null` when looking for one that is\n * missing. Neither is a type error, and neither is visible to a coverage gate,\n * because the sentinel is a *value* rather than a branch.\n *\n * Returning the reference rather than a boolean is deliberate: a caller that\n * needs the string gets the check for free, so there is no second, weaker way\n * to ask.\n *\n * **Do not test `embeddingRef` for presence directly — call this.**\n * @public\n */\nexport function embeddingRefOf(envelope: IMemoryEnvelope): string | undefined {\n return envelope.embeddingRef ?? undefined;\n}\n\n/**\n * A per-kind host projection from a fully-resolved (post-merge) memory record\n * to a numeric ordering value. Registered per kind at store construction (see\n * `rankProjectors`); the store runs it on every put/update over the same\n * resolved record whose `contentHash` it computes, stamping the result into\n * {@link IMemoryEnvelope.rank}. The store never interprets the body — the host\n * owns what the number means. A projector that throws is treated as \"no rank\n * for this record\" (logged at `warn`), never failing the write.\n *\n * Runs on writes only. To apply a newly-registered projector to records that\n * already exist, call `IMemoryStore.reconcile(kind, 'rank')`.\n * @public\n */\nexport type RankProjector = (record: IMemoryRecord<unknown>) => number;\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Result } from '@fgv/ts-utils';
|
|
2
|
+
import { IIdentityCodecResult } from './identityCodec';
|
|
3
|
+
import { EntityId, Kind } from './ids';
|
|
4
|
+
/**
|
|
5
|
+
* Resolves a consumer-facing `(kind, entityId)` address to the storage address the
|
|
6
|
+
* vault files it under, **without reading the record**.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* This is the resolution `IMemoryStore.get(kind, entityId)` already performs before
|
|
10
|
+
* it reads anything: `kind` selects the kind's `IIdentityCodec`, and the codec's
|
|
11
|
+
* `encode` computes `{ scope, idStem, isVersioned }`. Exposing it separately lets a
|
|
12
|
+
* caller that needs only the *address* — a fragment query narrowing to one record,
|
|
13
|
+
* say — avoid paying for a read it does not want.
|
|
14
|
+
*
|
|
15
|
+
* **The resolution is a function, not a search, and that is the load-bearing
|
|
16
|
+
* property.** A consumer holds an `EntityId`; a vector hit is addressed by a
|
|
17
|
+
* `(scope, id)` pair; and `EntityId` promises no uniqueness beyond a scope, so the
|
|
18
|
+
* same id may legitimately appear in several scopes (a document `acme-corp` under
|
|
19
|
+
* one kind and the entity `acme-corp` under another is the ordinary case, not a
|
|
20
|
+
* pathological one). Supplying `kind` selects one codec, and a codec cannot return
|
|
21
|
+
* two answers — so ambiguity is structurally impossible rather than merely unlikely,
|
|
22
|
+
* and no disambiguation pass is needed anywhere downstream.
|
|
23
|
+
*
|
|
24
|
+
* Narrow by design, mirroring `IMemoryRecordResolver`: a component that needs to
|
|
25
|
+
* turn an entity address into a storage address should depend on this rather than on
|
|
26
|
+
* the whole store.
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
export interface IIdentityResolver {
|
|
30
|
+
/**
|
|
31
|
+
* The storage address `(kind, entityId)` maps to, without reading the record.
|
|
32
|
+
*
|
|
33
|
+
* @param kind - Selects the identity codec. Required: it is what makes the
|
|
34
|
+
* resolution unambiguous.
|
|
35
|
+
* @param entityId - The consumer-supplied domain key.
|
|
36
|
+
* @returns `Success` with the codec's `{ scope, idStem, isVersioned }`, or
|
|
37
|
+
* `Failure` if no codec is registered for `kind` (and no default is wired) or the
|
|
38
|
+
* codec rejects the id. Both are caller errors and both are loud.
|
|
39
|
+
*/
|
|
40
|
+
resolveIdentity(kind: Kind, entityId: EntityId): Result<IIdentityCodecResult>;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=identityResolver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identityResolver.d.ts","sourceRoot":"","sources":["../../../src/packlets/types/identityResolver.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;;;;;OASG;IACH,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;CAC/E"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identityResolver.js","sourceRoot":"","sources":["../../../src/packlets/types/identityResolver.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { IIdentityCodecResult } from './identityCodec';\nimport { EntityId, Kind } from './ids';\n\n/**\n * Resolves a consumer-facing `(kind, entityId)` address to the storage address the\n * vault files it under, **without reading the record**.\n *\n * @remarks\n * This is the resolution `IMemoryStore.get(kind, entityId)` already performs before\n * it reads anything: `kind` selects the kind's `IIdentityCodec`, and the codec's\n * `encode` computes `{ scope, idStem, isVersioned }`. Exposing it separately lets a\n * caller that needs only the *address* — a fragment query narrowing to one record,\n * say — avoid paying for a read it does not want.\n *\n * **The resolution is a function, not a search, and that is the load-bearing\n * property.** A consumer holds an `EntityId`; a vector hit is addressed by a\n * `(scope, id)` pair; and `EntityId` promises no uniqueness beyond a scope, so the\n * same id may legitimately appear in several scopes (a document `acme-corp` under\n * one kind and the entity `acme-corp` under another is the ordinary case, not a\n * pathological one). Supplying `kind` selects one codec, and a codec cannot return\n * two answers — so ambiguity is structurally impossible rather than merely unlikely,\n * and no disambiguation pass is needed anywhere downstream.\n *\n * Narrow by design, mirroring `IMemoryRecordResolver`: a component that needs to\n * turn an entity address into a storage address should depend on this rather than on\n * the whole store.\n * @public\n */\nexport interface IIdentityResolver {\n /**\n * The storage address `(kind, entityId)` maps to, without reading the record.\n *\n * @param kind - Selects the identity codec. Required: it is what makes the\n * resolution unambiguous.\n * @param entityId - The consumer-supplied domain key.\n * @returns `Success` with the codec's `{ scope, idStem, isVersioned }`, or\n * `Failure` if no codec is registered for `kind` (and no default is wired) or the\n * codec rejects the id. Both are caller errors and both are loud.\n */\n resolveIdentity(kind: Kind, entityId: EntityId): Result<IIdentityCodecResult>;\n}\n"]}
|
|
@@ -2,6 +2,8 @@ export * from './ids';
|
|
|
2
2
|
export * from './envelope';
|
|
3
3
|
export * from './filenameSafety';
|
|
4
4
|
export * from './identityCodec';
|
|
5
|
+
export * from './identityResolver';
|
|
6
|
+
export * from './recordResolver';
|
|
5
7
|
export * from './temporal';
|
|
6
8
|
export * from './writePolicy';
|
|
7
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/types/index.ts"],"names":[],"mappings":"AAKA,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/types/index.ts"],"names":[],"mappings":"AAKA,cAAc,OAAO,CAAC;AACtB,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC"}
|
|
@@ -22,6 +22,8 @@ __exportStar(require("./ids"), exports);
|
|
|
22
22
|
__exportStar(require("./envelope"), exports);
|
|
23
23
|
__exportStar(require("./filenameSafety"), exports);
|
|
24
24
|
__exportStar(require("./identityCodec"), exports);
|
|
25
|
+
__exportStar(require("./identityResolver"), exports);
|
|
26
|
+
__exportStar(require("./recordResolver"), exports);
|
|
25
27
|
__exportStar(require("./temporal"), exports);
|
|
26
28
|
__exportStar(require("./writePolicy"), exports);
|
|
27
29
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/types/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;AAEH,wCAAsB;AACtB,6CAA2B;AAC3B,mDAAiC;AACjC,kDAAgC;AAChC,6CAA2B;AAC3B,gDAA8B","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './ids';\nexport * from './envelope';\nexport * from './filenameSafety';\nexport * from './identityCodec';\nexport * from './temporal';\nexport * from './writePolicy';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/types/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;AAEH,wCAAsB;AACtB,6CAA2B;AAC3B,mDAAiC;AACjC,kDAAgC;AAChC,qDAAmC;AACnC,mDAAiC;AACjC,6CAA2B;AAC3B,gDAA8B","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nexport * from './ids';\nexport * from './envelope';\nexport * from './filenameSafety';\nexport * from './identityCodec';\nexport * from './identityResolver';\nexport * from './recordResolver';\nexport * from './temporal';\nexport * from './writePolicy';\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Result } from '@fgv/ts-utils';
|
|
2
|
+
import { IMemoryRecord } from './envelope';
|
|
3
|
+
import { MemoryId, MemoryScopeKey } from './ids';
|
|
4
|
+
/**
|
|
5
|
+
* Materializes one record's body from its scope-qualified address — the other
|
|
6
|
+
* half of the partial-read split, and the narrowest seam that can be.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* The index holds `IIndexedMemoryEntry` (scope + envelope, no body), so anything
|
|
10
|
+
* that *selects* works from envelopes and anything that must *return records*
|
|
11
|
+
* resolves the survivors through this. `FileTreeMemoryStore` implements it over
|
|
12
|
+
* the same read path `getById` uses, so a resolved record is byte-identical to a
|
|
13
|
+
* keyed read, verification included.
|
|
14
|
+
*
|
|
15
|
+
* **Deliberately one method, and deliberately not the store.** A retriever needs
|
|
16
|
+
* exactly this capability; handing it an `IMemoryStore` would hand it `put` and
|
|
17
|
+
* `delete` as well, and would invert the construction direction (the store builds
|
|
18
|
+
* retrievers today, not the reverse). One method also keeps a test double
|
|
19
|
+
* trivial.
|
|
20
|
+
*
|
|
21
|
+
* Synchronous `Result` rather than `Promise<Result>` because every shipped
|
|
22
|
+
* `FileTree` backend resolves without awaiting, and an async signature here would
|
|
23
|
+
* have rippled through retrievers that are otherwise synchronous over the index.
|
|
24
|
+
* A future backend that genuinely needs I/O should be adapted at its own boundary
|
|
25
|
+
* rather than by making this contract async for everyone.
|
|
26
|
+
*
|
|
27
|
+
* Resolving an address the vault does not hold is `succeed(undefined)`, not a
|
|
28
|
+
* failure — an entry can legitimately vanish between selection and
|
|
29
|
+
* materialization (a concurrent delete), and that is a miss rather than a fault.
|
|
30
|
+
* A failure means the record is there and could not be read.
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
export interface IMemoryRecordResolver {
|
|
34
|
+
/**
|
|
35
|
+
* The record at `(scope, id)`, or `undefined` if the vault does not hold one.
|
|
36
|
+
*/
|
|
37
|
+
resolveRecord(scope: MemoryScopeKey, id: MemoryId): Result<IMemoryRecord<unknown> | undefined>;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=recordResolver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recordResolver.d.ts","sourceRoot":"","sources":["../../../src/packlets/types/recordResolver.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,aAAa,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,QAAQ,GAAG,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,CAAC;CAChG"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recordResolver.js","sourceRoot":"","sources":["../../../src/packlets/types/recordResolver.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { Result } from '@fgv/ts-utils';\nimport { IMemoryRecord } from './envelope';\nimport { MemoryId, MemoryScopeKey } from './ids';\n\n/**\n * Materializes one record's body from its scope-qualified address — the other\n * half of the partial-read split, and the narrowest seam that can be.\n *\n * @remarks\n * The index holds `IIndexedMemoryEntry` (scope + envelope, no body), so anything\n * that *selects* works from envelopes and anything that must *return records*\n * resolves the survivors through this. `FileTreeMemoryStore` implements it over\n * the same read path `getById` uses, so a resolved record is byte-identical to a\n * keyed read, verification included.\n *\n * **Deliberately one method, and deliberately not the store.** A retriever needs\n * exactly this capability; handing it an `IMemoryStore` would hand it `put` and\n * `delete` as well, and would invert the construction direction (the store builds\n * retrievers today, not the reverse). One method also keeps a test double\n * trivial.\n *\n * Synchronous `Result` rather than `Promise<Result>` because every shipped\n * `FileTree` backend resolves without awaiting, and an async signature here would\n * have rippled through retrievers that are otherwise synchronous over the index.\n * A future backend that genuinely needs I/O should be adapted at its own boundary\n * rather than by making this contract async for everyone.\n *\n * Resolving an address the vault does not hold is `succeed(undefined)`, not a\n * failure — an entry can legitimately vanish between selection and\n * materialization (a concurrent delete), and that is a miss rather than a fault.\n * A failure means the record is there and could not be read.\n * @public\n */\nexport interface IMemoryRecordResolver {\n /**\n * The record at `(scope, id)`, or `undefined` if the vault does not hold one.\n */\n resolveRecord(scope: MemoryScopeKey, id: MemoryId): Result<IMemoryRecord<unknown> | undefined>;\n}\n"]}
|
|
@@ -1,4 +1,24 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { IMemoryEnvelope } from './envelope';
|
|
2
|
+
/**
|
|
3
|
+
* The minimum a temporal helper needs: something carrying an envelope.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* Every predicate and selector in this module reads `envelope.temporal`,
|
|
7
|
+
* `envelope.created` and `envelope.seq` and **nothing else** — no body has ever
|
|
8
|
+
* been consulted. Taking the structural shape rather than `IMemoryRecord` lets
|
|
9
|
+
* the same helpers serve both an `IMemoryRecord<unknown>` (which satisfies it)
|
|
10
|
+
* and an `IIndexedMemoryEntry` from the index's projected read surface, so the
|
|
11
|
+
* temporal `asOf` projection can run over envelopes and materialize only the
|
|
12
|
+
* versions that survive it.
|
|
13
|
+
*
|
|
14
|
+
* The selectors are generic in this shape so they return exactly what they were
|
|
15
|
+
* given rather than widening to the constraint.
|
|
16
|
+
* @public
|
|
17
|
+
*/
|
|
18
|
+
export interface IEnvelopeCarrier {
|
|
19
|
+
/** The envelope the temporal predicates read. */
|
|
20
|
+
readonly envelope: IMemoryEnvelope;
|
|
21
|
+
}
|
|
2
22
|
/**
|
|
3
23
|
* Whether a record participates in the versioned (temporal) layout. A temporal
|
|
4
24
|
* record always carries a {@link ITemporalBlock | temporal} block (the store
|
|
@@ -7,14 +27,14 @@ import { IMemoryRecord } from './envelope';
|
|
|
7
27
|
* divergence (MTM is flat yet has `entityId !== id`).
|
|
8
28
|
* @public
|
|
9
29
|
*/
|
|
10
|
-
export declare function isTemporalRecord(record:
|
|
30
|
+
export declare function isTemporalRecord(record: IEnvelopeCarrier): boolean;
|
|
11
31
|
/**
|
|
12
32
|
* Whether a temporal record is a *current* version — its `temporal.invalid_at`
|
|
13
33
|
* is `null` or absent (the still-valid sentinel). A non-temporal record is never
|
|
14
34
|
* current in this sense (returns `false`).
|
|
15
35
|
* @public
|
|
16
36
|
*/
|
|
17
|
-
export declare function isVersionCurrent(record:
|
|
37
|
+
export declare function isVersionCurrent(record: IEnvelopeCarrier): boolean;
|
|
18
38
|
/**
|
|
19
39
|
* Whether a temporal record's validity interval contains `asOf` (epoch ms):
|
|
20
40
|
* `valid_at <= asOf` and (`invalid_at` is null/absent OR `asOf < invalid_at`).
|
|
@@ -22,19 +42,19 @@ export declare function isVersionCurrent(record: IMemoryRecord<unknown>): boolea
|
|
|
22
42
|
* record is never "valid at" a point (returns `false`).
|
|
23
43
|
* @public
|
|
24
44
|
*/
|
|
25
|
-
export declare function isVersionValidAt(record:
|
|
45
|
+
export declare function isVersionValidAt(record: IEnvelopeCarrier, asOf: number): boolean;
|
|
26
46
|
/**
|
|
27
47
|
* Select the current version from a set of an entity's versions: the newest
|
|
28
48
|
* (highest `seq`) version whose `invalid_at` is null/absent. `undefined` when the
|
|
29
49
|
* entity has no current version (fully invalidated / soft-deleted, or empty).
|
|
30
50
|
* @public
|
|
31
51
|
*/
|
|
32
|
-
export declare function selectCurrentVersion(versions: ReadonlyArray<
|
|
52
|
+
export declare function selectCurrentVersion<T extends IEnvelopeCarrier>(versions: ReadonlyArray<T>): T | undefined;
|
|
33
53
|
/**
|
|
34
54
|
* Select the version of an entity valid at `asOf` (epoch ms): the newest
|
|
35
55
|
* (highest `seq`) version whose validity interval contains `asOf`. `undefined`
|
|
36
56
|
* when no version was valid at that instant.
|
|
37
57
|
* @public
|
|
38
58
|
*/
|
|
39
|
-
export declare function selectVersionAsOf(versions: ReadonlyArray<
|
|
59
|
+
export declare function selectVersionAsOf<T extends IEnvelopeCarrier>(versions: ReadonlyArray<T>, asOf: number): T | undefined;
|
|
40
60
|
//# sourceMappingURL=temporal.d.ts.map
|