@fgv/ts-agent-memory 5.1.0-36 → 5.1.0-39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.rush/temp/{f6a88bfdd66517ccb98c2c7ae1be6e6fe9e15d38.tar.log → b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log} +116 -2
  2. package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +4 -4
  3. package/.rush/temp/operation/build/all.log +4 -4
  4. package/.rush/temp/operation/build/log-chunks.jsonl +4 -4
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/.rush/temp/shrinkwrap-deps.json +222 -221
  7. package/config/jest.config.json +1 -1
  8. package/dist/index.js +2 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/packlets/ingest/cycleGuard.js +111 -0
  11. package/dist/packlets/ingest/cycleGuard.js.map +1 -0
  12. package/dist/packlets/ingest/hostStages.js +6 -0
  13. package/dist/packlets/ingest/hostStages.js.map +1 -0
  14. package/dist/packlets/ingest/index.js +9 -0
  15. package/dist/packlets/ingest/index.js.map +1 -0
  16. package/dist/packlets/ingest/model.js +6 -0
  17. package/dist/packlets/ingest/model.js.map +1 -0
  18. package/dist/packlets/ingest/orchestrator.js +438 -0
  19. package/dist/packlets/ingest/orchestrator.js.map +1 -0
  20. package/dist/packlets/retrieve/index.js +1 -0
  21. package/dist/packlets/retrieve/index.js.map +1 -1
  22. package/dist/packlets/retrieve/temporalRetrievers.js +172 -0
  23. package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -0
  24. package/dist/packlets/store/fileTreeMemoryStore.js +323 -41
  25. package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
  26. package/dist/packlets/tools/index.js +6 -0
  27. package/dist/packlets/tools/index.js.map +1 -0
  28. package/dist/packlets/tools/memoryTools.js +337 -0
  29. package/dist/packlets/tools/memoryTools.js.map +1 -0
  30. package/dist/packlets/types/identityCodec.js +115 -0
  31. package/dist/packlets/types/identityCodec.js.map +1 -1
  32. package/dist/packlets/types/index.js +1 -0
  33. package/dist/packlets/types/index.js.map +1 -1
  34. package/dist/packlets/types/temporal.js +85 -0
  35. package/dist/packlets/types/temporal.js.map +1 -0
  36. package/dist/packlets/types/writePolicy.js +96 -0
  37. package/dist/packlets/types/writePolicy.js.map +1 -1
  38. package/dist/test/unit/converters/antagonistRoundTrip.test.js +95 -0
  39. package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  40. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +273 -0
  41. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  42. package/dist/test/unit/ingest/cycleGuard.test.js +54 -0
  43. package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -0
  44. package/dist/test/unit/ingest/orchestrator.test.js +913 -0
  45. package/dist/test/unit/ingest/orchestrator.test.js.map +1 -0
  46. package/dist/test/unit/retrieve/temporalRetrievers.test.js +182 -0
  47. package/dist/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  48. package/dist/test/unit/store/antagonistTemporalBoundary.test.js +120 -0
  49. package/dist/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  50. package/dist/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  51. package/dist/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  52. package/dist/test/unit/store/temporalStore.test.js +398 -0
  53. package/dist/test/unit/store/temporalStore.test.js.map +1 -0
  54. package/dist/test/unit/tools/memoryTools.test.js +572 -0
  55. package/dist/test/unit/tools/memoryTools.test.js.map +1 -0
  56. package/dist/test/unit/types/temporalCodec.test.js +203 -0
  57. package/dist/test/unit/types/temporalCodec.test.js.map +1 -0
  58. package/dist/test/unit/types/temporalPolicy.test.js +62 -0
  59. package/dist/test/unit/types/temporalPolicy.test.js.map +1 -0
  60. package/dist/ts-agent-memory.d.ts +1042 -10
  61. package/dist/tsdoc-metadata.json +1 -1
  62. package/etc/ts-agent-memory.api.md +284 -0
  63. package/lib/index.d.ts +2 -0
  64. package/lib/index.d.ts.map +1 -1
  65. package/lib/index.js +2 -0
  66. package/lib/index.js.map +1 -1
  67. package/lib/packlets/ingest/cycleGuard.d.ts +41 -0
  68. package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -0
  69. package/lib/packlets/ingest/cycleGuard.js +115 -0
  70. package/lib/packlets/ingest/cycleGuard.js.map +1 -0
  71. package/lib/packlets/ingest/hostStages.d.ts +88 -0
  72. package/lib/packlets/ingest/hostStages.d.ts.map +1 -0
  73. package/lib/packlets/ingest/hostStages.js +7 -0
  74. package/lib/packlets/ingest/hostStages.js.map +1 -0
  75. package/lib/packlets/ingest/index.d.ts +5 -0
  76. package/lib/packlets/ingest/index.d.ts.map +1 -0
  77. package/lib/packlets/ingest/index.js +25 -0
  78. package/lib/packlets/ingest/index.js.map +1 -0
  79. package/lib/packlets/ingest/model.d.ts +177 -0
  80. package/lib/packlets/ingest/model.d.ts.map +1 -0
  81. package/lib/packlets/ingest/model.js +7 -0
  82. package/lib/packlets/ingest/model.js.map +1 -0
  83. package/lib/packlets/ingest/orchestrator.d.ts +206 -0
  84. package/lib/packlets/ingest/orchestrator.d.ts.map +1 -0
  85. package/lib/packlets/ingest/orchestrator.js +442 -0
  86. package/lib/packlets/ingest/orchestrator.js.map +1 -0
  87. package/lib/packlets/retrieve/index.d.ts +1 -0
  88. package/lib/packlets/retrieve/index.d.ts.map +1 -1
  89. package/lib/packlets/retrieve/index.js +1 -0
  90. package/lib/packlets/retrieve/index.js.map +1 -1
  91. package/lib/packlets/retrieve/temporalRetrievers.d.ts +78 -0
  92. package/lib/packlets/retrieve/temporalRetrievers.d.ts.map +1 -0
  93. package/lib/packlets/retrieve/temporalRetrievers.js +178 -0
  94. package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -0
  95. package/lib/packlets/store/fileTreeMemoryStore.d.ts +118 -9
  96. package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
  97. package/lib/packlets/store/fileTreeMemoryStore.js +322 -40
  98. package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
  99. package/lib/packlets/tools/index.d.ts +2 -0
  100. package/lib/packlets/tools/index.d.ts.map +1 -0
  101. package/lib/packlets/tools/index.js +22 -0
  102. package/lib/packlets/tools/index.js.map +1 -0
  103. package/lib/packlets/tools/memoryTools.d.ts +139 -0
  104. package/lib/packlets/tools/memoryTools.d.ts.map +1 -0
  105. package/lib/packlets/tools/memoryTools.js +341 -0
  106. package/lib/packlets/tools/memoryTools.js.map +1 -0
  107. package/lib/packlets/types/identityCodec.d.ts +86 -0
  108. package/lib/packlets/types/identityCodec.d.ts.map +1 -1
  109. package/lib/packlets/types/identityCodec.js +118 -1
  110. package/lib/packlets/types/identityCodec.js.map +1 -1
  111. package/lib/packlets/types/index.d.ts +1 -0
  112. package/lib/packlets/types/index.d.ts.map +1 -1
  113. package/lib/packlets/types/index.js +1 -0
  114. package/lib/packlets/types/index.js.map +1 -1
  115. package/lib/packlets/types/temporal.d.ts +40 -0
  116. package/lib/packlets/types/temporal.d.ts.map +1 -0
  117. package/lib/packlets/types/temporal.js +92 -0
  118. package/lib/packlets/types/temporal.js.map +1 -0
  119. package/lib/packlets/types/writePolicy.d.ts +49 -0
  120. package/lib/packlets/types/writePolicy.d.ts.map +1 -1
  121. package/lib/packlets/types/writePolicy.js +98 -1
  122. package/lib/packlets/types/writePolicy.js.map +1 -1
  123. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts +10 -0
  124. package/lib/test/unit/converters/antagonistRoundTrip.test.d.ts.map +1 -0
  125. package/lib/test/unit/converters/antagonistRoundTrip.test.js +97 -0
  126. package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -0
  127. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts +9 -0
  128. package/lib/test/unit/ingest/antagonistCycleAndParity.test.d.ts.map +1 -0
  129. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +275 -0
  130. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -0
  131. package/lib/test/unit/ingest/cycleGuard.test.d.ts +2 -0
  132. package/lib/test/unit/ingest/cycleGuard.test.d.ts.map +1 -0
  133. package/lib/test/unit/ingest/cycleGuard.test.js +56 -0
  134. package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -0
  135. package/lib/test/unit/ingest/orchestrator.test.d.ts +2 -0
  136. package/lib/test/unit/ingest/orchestrator.test.d.ts.map +1 -0
  137. package/lib/test/unit/ingest/orchestrator.test.js +915 -0
  138. package/lib/test/unit/ingest/orchestrator.test.js.map +1 -0
  139. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts +2 -0
  140. package/lib/test/unit/retrieve/temporalRetrievers.test.d.ts.map +1 -0
  141. package/lib/test/unit/retrieve/temporalRetrievers.test.js +184 -0
  142. package/lib/test/unit/retrieve/temporalRetrievers.test.js.map +1 -0
  143. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts +9 -0
  144. package/lib/test/unit/store/antagonistTemporalBoundary.test.d.ts.map +1 -0
  145. package/lib/test/unit/store/antagonistTemporalBoundary.test.js +122 -0
  146. package/lib/test/unit/store/antagonistTemporalBoundary.test.js.map +1 -0
  147. package/lib/test/unit/store/fileTreeMemoryStore.test.js +74 -7
  148. package/lib/test/unit/store/fileTreeMemoryStore.test.js.map +1 -1
  149. package/lib/test/unit/store/temporalStore.test.d.ts +2 -0
  150. package/lib/test/unit/store/temporalStore.test.d.ts.map +1 -0
  151. package/lib/test/unit/store/temporalStore.test.js +400 -0
  152. package/lib/test/unit/store/temporalStore.test.js.map +1 -0
  153. package/lib/test/unit/tools/memoryTools.test.d.ts +2 -0
  154. package/lib/test/unit/tools/memoryTools.test.d.ts.map +1 -0
  155. package/lib/test/unit/tools/memoryTools.test.js +574 -0
  156. package/lib/test/unit/tools/memoryTools.test.js.map +1 -0
  157. package/lib/test/unit/types/temporalCodec.test.d.ts +2 -0
  158. package/lib/test/unit/types/temporalCodec.test.d.ts.map +1 -0
  159. package/lib/test/unit/types/temporalCodec.test.js +205 -0
  160. package/lib/test/unit/types/temporalCodec.test.js.map +1 -0
  161. package/lib/test/unit/types/temporalPolicy.test.d.ts +2 -0
  162. package/lib/test/unit/types/temporalPolicy.test.d.ts.map +1 -0
  163. package/lib/test/unit/types/temporalPolicy.test.js +64 -0
  164. package/lib/test/unit/types/temporalPolicy.test.js.map +1 -0
  165. package/package.json +19 -19
  166. package/rush-logs/ts-agent-memory.build.cache.log +1 -1
  167. package/rush-logs/ts-agent-memory.build.log +4 -4
  168. package/src/index.ts +2 -0
  169. package/src/packlets/ingest/cycleGuard.ts +142 -0
  170. package/src/packlets/ingest/hostStages.ts +111 -0
  171. package/src/packlets/ingest/index.ts +9 -0
  172. package/src/packlets/ingest/model.ts +184 -0
  173. package/src/packlets/ingest/orchestrator.ts +797 -0
  174. package/src/packlets/retrieve/index.ts +1 -0
  175. package/src/packlets/retrieve/temporalRetrievers.ts +210 -0
  176. package/src/packlets/store/fileTreeMemoryStore.ts +460 -66
  177. package/src/packlets/tools/index.ts +6 -0
  178. package/src/packlets/tools/memoryTools.ts +579 -0
  179. package/src/packlets/types/identityCodec.ts +184 -0
  180. package/src/packlets/types/index.ts +1 -0
  181. package/src/packlets/types/temporal.ts +96 -0
  182. package/src/packlets/types/writePolicy.ts +127 -0
  183. package/src/test/unit/converters/antagonistRoundTrip.test.ts +110 -0
  184. package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +362 -0
  185. package/src/test/unit/ingest/cycleGuard.test.ts +68 -0
  186. package/src/test/unit/ingest/orchestrator.test.ts +1158 -0
  187. package/src/test/unit/retrieve/temporalRetrievers.test.ts +226 -0
  188. package/src/test/unit/store/antagonistTemporalBoundary.test.ts +158 -0
  189. package/src/test/unit/store/fileTreeMemoryStore.test.ts +98 -7
  190. package/src/test/unit/store/temporalStore.test.ts +469 -0
  191. package/src/test/unit/tools/memoryTools.test.ts +771 -0
  192. package/src/test/unit/types/temporalCodec.test.ts +259 -0
  193. package/src/test/unit/types/temporalPolicy.test.ts +96 -0
  194. package/temp/build/lint/_eslint-5eVG3S6w.json +122 -46
  195. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  196. package/temp/ts-agent-memory.api.json +11984 -6314
  197. package/temp/ts-agent-memory.api.md +284 -0
@@ -0,0 +1,579 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ import { Result, captureResult, fail, succeed } from '@fgv/ts-utils';
7
+ import { JsonSchema } from '@fgv/ts-json-base';
8
+ import { AiAssist } from '@fgv/ts-extras';
9
+ import { Convert, EntityId, IIdentityCodec, IMemoryRecord, Kind, MemoryId, Tag } from '../types';
10
+ import { IBodyConverterRegistry, envelopeConverter } from '../converters';
11
+ import { IMemoryStore } from '../store';
12
+ import { IMemoryQuery, IMemoryRetriever } from '../retrieve';
13
+
14
+ /**
15
+ * The names of the five proof-set memory tools. A caller selects a subset via
16
+ * {@link ICreateMemoryToolsParams.tools | tools}.
17
+ * @public
18
+ */
19
+ export type MemoryToolName =
20
+ | 'memory_write'
21
+ | 'memory_read'
22
+ | 'memory_search'
23
+ | 'memory_context'
24
+ | 'memory_delete';
25
+
26
+ /**
27
+ * The default tool subset when {@link ICreateMemoryToolsParams.tools | tools} is
28
+ * omitted: the read-only set. Mutating tools (`memory_write` / `memory_delete`)
29
+ * are **off by default** and must be named explicitly — writes stay
30
+ * curation-mediated unless the host opts in.
31
+ * @public
32
+ */
33
+ export const DEFAULT_MEMORY_TOOLS: ReadonlyArray<MemoryToolName> = ['memory_search', 'memory_context'];
34
+
35
+ /**
36
+ * Discriminates the outcome of a {@link createMemoryTools | memory_write} call so
37
+ * the agent can reason about what its write actually did.
38
+ *
39
+ * @remarks
40
+ * - `written` — a new record was persisted, or an existing entity was updated.
41
+ * - `deduped` — the content already existed (content-hash dedup no-op); the
42
+ * store returned the existing record unchanged.
43
+ *
44
+ * The store's public `put` return does not surface cap-cull evictions, so a
45
+ * `culled` outcome is not distinguishable at this layer without an L1 change or
46
+ * observer wiring (both out of scope for L2). The writer's own record is always
47
+ * `written` even when the write triggers a cull of older siblings.
48
+ * @public
49
+ */
50
+ export type MemoryWriteOutcome = 'written' | 'deduped';
51
+
52
+ /**
53
+ * The success value returned by `memory_write.execute`.
54
+ * @public
55
+ */
56
+ export interface IMemoryWriteResult {
57
+ /** What the write did — see {@link MemoryWriteOutcome}. */
58
+ readonly outcome: MemoryWriteOutcome;
59
+ /** The stored record's {@link MemoryId}. */
60
+ readonly id: MemoryId;
61
+ /** The domain {@link EntityId} the write targeted. */
62
+ readonly entityId: EntityId;
63
+ /** The record's {@link Kind}. */
64
+ readonly kind: Kind;
65
+ }
66
+
67
+ /**
68
+ * A single agent-visible search / context result item. The agent-facing key is
69
+ * {@link IMemoryToolResultItem.handle | handle}: the host mnemonic when a
70
+ * {@link ICreateMemoryToolsParams.handleFor | handleFor} hook is supplied, else
71
+ * the raw {@link MemoryId}.
72
+ * @public
73
+ */
74
+ export interface IMemoryToolResultItem {
75
+ /** The agent-visible key (host handle when supplied, raw {@link MemoryId} otherwise). */
76
+ readonly handle: string;
77
+ /** The record's {@link Kind}. */
78
+ readonly kind: Kind;
79
+ /** The record's domain {@link EntityId}. */
80
+ readonly entityId: EntityId;
81
+ /** The record's tags. */
82
+ readonly tags: ReadonlyArray<string>;
83
+ /** The record body (a markdown string in B1). */
84
+ readonly body: unknown;
85
+ }
86
+
87
+ /**
88
+ * Parameters for {@link createMemoryTools}.
89
+ *
90
+ * @remarks
91
+ * **Scope isolation is constructor-fixed.** The {@link
92
+ * ICreateMemoryToolsParams.store | store} is the sole scope authority — it is the
93
+ * actor's own, pre-scoped memory root. No tool's `parametersSchema` declares a
94
+ * `scope` (or any scope-widening) property, so an LLM cannot steer a tool at
95
+ * another actor's memory.
96
+ * @public
97
+ */
98
+ export interface ICreateMemoryToolsParams {
99
+ /**
100
+ * The pre-scoped memory store (the actor's own memory root). Sole scope
101
+ * authority — backs `memory_write` / `memory_read` / `memory_delete`.
102
+ */
103
+ readonly store: IMemoryStore;
104
+ /** Retriever backing `memory_search` (and `memory_context` via link traversal). */
105
+ readonly retriever: IMemoryRetriever;
106
+ /** Body converter registry — gates the toolable kinds via `has(kind)`. */
107
+ readonly registry: IBodyConverterRegistry;
108
+ /**
109
+ * The per-tool enable subset. Defaults to {@link DEFAULT_MEMORY_TOOLS} (the
110
+ * read-only set). Name `memory_write` / `memory_delete` here to opt into the
111
+ * mutating tools.
112
+ */
113
+ readonly tools?: ReadonlyArray<MemoryToolName>;
114
+ /**
115
+ * Optional whitelist of toolable kinds. When present, a tool `kind` argument
116
+ * outside this set is rejected. When absent, {@link
117
+ * IBodyConverterRegistry.has | registry.has} is the sole kind gate.
118
+ */
119
+ readonly kinds?: ReadonlyArray<Kind>;
120
+ /**
121
+ * Per-kind identity codecs, used by `memory_write` to map the domain
122
+ * {@link EntityId} to the record's storage id (the store resolves codecs
123
+ * internally for `get` / `delete`, so read / delete do not need them). Absent
124
+ * → `memory_write` uses {@link ICreateMemoryToolsParams.defaultCodec |
125
+ * defaultCodec}, and fails loudly for a kind with no resolvable codec. The
126
+ * read-only default tool set needs no codecs.
127
+ */
128
+ readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;
129
+ /** Default identity codec for kinds without an explicit {@link ICreateMemoryToolsParams.codecs | codecs} entry. */
130
+ readonly defaultCodec?: IIdentityCodec;
131
+ /**
132
+ * Optional host hook mapping a record to its agent-visible handle (an evocative
133
+ * mnemonic tag). When supplied, `memory_search` / `memory_context` results use
134
+ * the returned handle as the agent-visible key; when absent the raw
135
+ * {@link MemoryId} is used.
136
+ */
137
+ readonly handleFor?: (record: IMemoryRecord<unknown>) => string;
138
+ }
139
+
140
+ /** The resolved factory context threaded into each tool's `execute`. */
141
+ interface IToolContext {
142
+ readonly store: IMemoryStore;
143
+ readonly retriever: IMemoryRetriever;
144
+ readonly registry: IBodyConverterRegistry;
145
+ readonly kinds?: ReadonlyArray<Kind>;
146
+ readonly codecs?: ReadonlyMap<Kind, IIdentityCodec>;
147
+ readonly defaultCodec?: IIdentityCodec;
148
+ readonly handleFor?: (record: IMemoryRecord<unknown>) => string;
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Parameter schemas — authored once via JsonSchema.object(...); the schema IS
153
+ // both the wire schema (.toJson()) and the runtime validator (.convert()).
154
+ // NONE of these declare a `scope` (or scope-widening) property — the adoption
155
+ // gate is enforced structurally and asserted in the tests.
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /** A single attributed link edge as authored by the agent on a write. */
159
+ // eslint-disable-next-line @rushstack/typedef-var
160
+ const linkEdgeSchema = JsonSchema.object({
161
+ type: JsonSchema.string({ description: 'The relation type of the link.' }),
162
+ target: JsonSchema.string({ description: 'The MemoryId this edge points at.' }),
163
+ confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))
164
+ });
165
+
166
+ // eslint-disable-next-line @rushstack/typedef-var
167
+ const writeSchema = JsonSchema.object({
168
+ kind: JsonSchema.string({ description: 'The record kind (must be an enabled, registered kind).' }),
169
+ entityId: JsonSchema.string({
170
+ description:
171
+ 'The domain entity id. For composite (e.g. medium-term) kinds this is the full composite key.'
172
+ }),
173
+ body: JsonSchema.string({ description: "The serialized record body; validated by the kind's converter." }),
174
+ tags: JsonSchema.optional(JsonSchema.array(JsonSchema.string({ description: 'A tag label.' }))),
175
+ links: JsonSchema.optional(JsonSchema.array(linkEdgeSchema))
176
+ });
177
+ type WriteArgs = JsonSchema.Static<typeof writeSchema>;
178
+
179
+ // eslint-disable-next-line @rushstack/typedef-var
180
+ const readSchema = JsonSchema.object({
181
+ kind: JsonSchema.string({ description: 'The record kind.' }),
182
+ entityId: JsonSchema.string({ description: 'The domain entity id to read.' })
183
+ });
184
+
185
+ // eslint-disable-next-line @rushstack/typedef-var
186
+ const deleteSchema = JsonSchema.object({
187
+ kind: JsonSchema.string({ description: 'The record kind.' }),
188
+ entityId: JsonSchema.string({ description: 'The domain entity id to delete.' })
189
+ });
190
+
191
+ // eslint-disable-next-line @rushstack/typedef-var
192
+ const searchSchema = JsonSchema.object({
193
+ kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),
194
+ tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),
195
+ semantic: JsonSchema.optional(
196
+ JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })
197
+ ),
198
+ limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
199
+ });
200
+
201
+ // eslint-disable-next-line @rushstack/typedef-var
202
+ const contextSchema = JsonSchema.object({
203
+ from: JsonSchema.string({ description: 'The seed MemoryId to traverse links from.' }),
204
+ kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),
205
+ tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),
206
+ hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),
207
+ limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
208
+ });
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Behavior annotations (Component 4) — host-advisory hints; never serialized to
212
+ // the model. openWorldHint is false throughout (a closed, local store).
213
+ // ---------------------------------------------------------------------------
214
+
215
+ const READ_ONLY_ANNOTATIONS: AiAssist.IAiToolAnnotations = {
216
+ readOnlyHint: true,
217
+ openWorldHint: false
218
+ };
219
+
220
+ const WRITE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {
221
+ destructiveHint: false,
222
+ idempotentHint: false,
223
+ openWorldHint: false
224
+ };
225
+
226
+ const DELETE_ANNOTATIONS: AiAssist.IAiToolAnnotations = {
227
+ destructiveHint: true,
228
+ idempotentHint: true,
229
+ openWorldHint: false
230
+ };
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Shared validation / projection helpers
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /** Validate a `kind` string and assert it is an enabled, registered toolable kind. */
237
+ function assertKindEnabled(ctx: IToolContext, kindStr: string): Result<Kind> {
238
+ return Convert.kind.convert(kindStr).onSuccess((kind) => {
239
+ if (!ctx.registry.has(kind)) {
240
+ return fail(`memory tools: kind '${kind}' has no registered body converter`);
241
+ }
242
+ if (ctx.kinds !== undefined && !ctx.kinds.includes(kind)) {
243
+ return fail(`memory tools: kind '${kind}' is not enabled for memory tools`);
244
+ }
245
+ return succeed(kind);
246
+ });
247
+ }
248
+
249
+ /** Validate an optional `kind` string (enabled when present; `undefined` passes through). */
250
+ function resolveOptionalKind(ctx: IToolContext, kindStr?: string): Result<Kind | undefined> {
251
+ if (kindStr === undefined) {
252
+ return succeed(undefined);
253
+ }
254
+ return assertKindEnabled(ctx, kindStr);
255
+ }
256
+
257
+ /** Project a record into an agent-visible result item, applying the host handle hook when present. */
258
+ function projectItem(ctx: IToolContext, record: IMemoryRecord<unknown>): IMemoryToolResultItem {
259
+ // `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than
260
+ // escaping the Result chain (and crashing the whole search/context call).
261
+ const handle =
262
+ ctx.handleFor !== undefined
263
+ ? captureResult(() => ctx.handleFor!(record)).orDefault(record.envelope.id)
264
+ : record.envelope.id;
265
+ return {
266
+ handle,
267
+ kind: record.envelope.kind,
268
+ entityId: record.envelope.entityId,
269
+ tags: record.envelope.tags,
270
+ body: record.body
271
+ };
272
+ }
273
+
274
+ /** Resolve the identity codec used by `memory_write` to derive the storage id. */
275
+ function codecForWrite(ctx: IToolContext, kind: Kind): Result<IIdentityCodec> {
276
+ const codec: IIdentityCodec | undefined = ctx.codecs?.get(kind) ?? ctx.defaultCodec;
277
+ if (codec === undefined) {
278
+ return fail(`memory_write: no identity codec available for kind '${kind}'`);
279
+ }
280
+ return succeed(codec);
281
+ }
282
+
283
+ /** Build the record to persist from validated write args (store stamps txn-time metadata). */
284
+ function buildWriteRecord(
285
+ typed: WriteArgs,
286
+ kind: Kind,
287
+ entityId: EntityId,
288
+ idStem: string
289
+ ): Result<IMemoryRecord<unknown>> {
290
+ // Plain shapes handed to `envelopeConverter`, which validates each field
291
+ // (type → LinkType, target → MemoryId) and produces the branded IEdge[].
292
+ const links: ReadonlyArray<Record<string, unknown>> = (typed.links ?? []).map((link) => ({
293
+ type: link.type,
294
+ target: link.target,
295
+ ...(link.confidence !== undefined ? { confidence: link.confidence } : {})
296
+ }));
297
+ return envelopeConverter
298
+ .convert({
299
+ id: idStem,
300
+ entityId,
301
+ kind,
302
+ tags: typed.tags ?? [],
303
+ links,
304
+ created: 0,
305
+ updated: 0,
306
+ seq: 0,
307
+ contentHash: '',
308
+ provenance: { source: 'agent' }
309
+ })
310
+ .withErrorFormat((msg) => `memory_write: invalid record: ${msg}`)
311
+ .onSuccess((envelope) => succeed({ envelope, body: typed.body }));
312
+ }
313
+
314
+ /** Resolve the validated write args into the storage id + record (all synchronous). */
315
+ function prepareWrite(
316
+ ctx: IToolContext,
317
+ typed: WriteArgs
318
+ ): Result<{ readonly kind: Kind; readonly entityId: EntityId; readonly record: IMemoryRecord<unknown> }> {
319
+ return assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>
320
+ Convert.entityId.convert(typed.entityId).onSuccess((entityId) =>
321
+ codecForWrite(ctx, kind).onSuccess((codec) =>
322
+ codec.encode(entityId).onSuccess((addr) => {
323
+ if (addr.isVersioned) {
324
+ return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);
325
+ }
326
+ return buildWriteRecord(typed, kind, entityId, addr.idStem).onSuccess((record) =>
327
+ succeed({ kind, entityId, record })
328
+ );
329
+ })
330
+ )
331
+ )
332
+ );
333
+ }
334
+
335
+ /**
336
+ * Discriminate the write outcome from a pre-put snapshot and the returned record.
337
+ * A dedup no-op returns either a different entity (content-scope dedup) or the
338
+ * same-id record with an unchanged `seq` (entity-scope re-put); a fresh write or
339
+ * update advances `seq`.
340
+ */
341
+ function writeOutcome(
342
+ before: IMemoryRecord<unknown> | undefined,
343
+ written: IMemoryRecord<unknown>,
344
+ entityId: EntityId
345
+ ): MemoryWriteOutcome {
346
+ if (written.envelope.entityId !== entityId) {
347
+ return 'deduped';
348
+ }
349
+ if (before !== undefined && written.envelope.seq === before.envelope.seq) {
350
+ return 'deduped';
351
+ }
352
+ return 'written';
353
+ }
354
+
355
+ // ---------------------------------------------------------------------------
356
+ // Tool builders — config with a JsonSchema.object(...) parametersSchema; execute
357
+ // validates/narrows → delegates to store/retriever → returns the Result (never
358
+ // swallowed), following the ts-extras-mcp adapter shape.
359
+ //
360
+ // Each `execute` re-runs its own `parametersSchema.convert(args)` even though the
361
+ // `executeClientToolTurn` harness already validates against the same schema. This
362
+ // is deliberate: the factory returns a heterogeneous `ReadonlyArray<IAiClientTool>`
363
+ // (TParams erased to `unknown`, since the members carry different param shapes), so
364
+ // `execute` receives `unknown` and must narrow it back to the typed args. The
365
+ // re-validation is also the narrowing step exercised by the direct-call tests (which
366
+ // invoke `execute` with raw args, bypassing the harness). Re-validating an
367
+ // already-conforming shape is a cheap, side-effect-free identity.
368
+ // ---------------------------------------------------------------------------
369
+
370
+ function buildWriteTool(ctx: IToolContext): AiAssist.IAiClientTool {
371
+ return {
372
+ config: {
373
+ type: 'client_tool',
374
+ name: 'memory_write',
375
+ description:
376
+ 'Store a new memory record or update an existing one by (kind, entityId). ' +
377
+ 'Identical content is a no-op that returns the existing record.',
378
+ parametersSchema: writeSchema,
379
+ annotations: WRITE_ANNOTATIONS
380
+ },
381
+ execute: async (args: unknown): Promise<Result<unknown>> =>
382
+ writeSchema
383
+ .convert(args)
384
+ .withErrorFormat((msg) => `memory_write: invalid arguments: ${msg}`)
385
+ .onSuccess((typed) => prepareWrite(ctx, typed))
386
+ .thenOnSuccess(async ({ kind, entityId, record }) =>
387
+ // Read the prior record to discriminate written-vs-deduped. A `Failure`
388
+ // here (corrupt file, I/O error, codec round-trip failure) is a real
389
+ // condition distinct from the "not found" success (`undefined`); propagate
390
+ // it rather than defaulting it away, so a genuine store fault surfaces
391
+ // instead of being masked as a normal write.
392
+ (await ctx.store.get(kind, entityId)).thenOnSuccess(async (before) =>
393
+ (await ctx.store.put(record)).onSuccess((persisted) =>
394
+ succeed<IMemoryWriteResult>({
395
+ outcome: writeOutcome(before, persisted, entityId),
396
+ id: persisted.envelope.id,
397
+ entityId,
398
+ kind
399
+ })
400
+ )
401
+ )
402
+ )
403
+ };
404
+ }
405
+
406
+ function buildReadTool(ctx: IToolContext): AiAssist.IAiClientTool {
407
+ return {
408
+ config: {
409
+ type: 'client_tool',
410
+ name: 'memory_read',
411
+ description: 'Read a specific memory record by (kind, entityId).',
412
+ parametersSchema: readSchema,
413
+ annotations: READ_ONLY_ANNOTATIONS
414
+ },
415
+ execute: async (args: unknown): Promise<Result<unknown>> =>
416
+ readSchema
417
+ .convert(args)
418
+ .withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)
419
+ .onSuccess((typed) =>
420
+ assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>
421
+ Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))
422
+ )
423
+ )
424
+ .thenOnSuccess(async ({ kind, entityId }) =>
425
+ (await ctx.store.get(kind, entityId)).onSuccess((record) =>
426
+ record === undefined
427
+ ? succeed({ found: false })
428
+ : succeed({ found: true, item: projectItem(ctx, record) })
429
+ )
430
+ )
431
+ };
432
+ }
433
+
434
+ function buildSearchTool(ctx: IToolContext): AiAssist.IAiClientTool {
435
+ return {
436
+ config: {
437
+ type: 'client_tool',
438
+ name: 'memory_search',
439
+ description: 'Search memories by tag, kind, or semantic text. Returns ranked results.',
440
+ parametersSchema: searchSchema,
441
+ annotations: READ_ONLY_ANNOTATIONS
442
+ },
443
+ execute: async (args: unknown): Promise<Result<unknown>> =>
444
+ searchSchema
445
+ .convert(args)
446
+ .withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)
447
+ .onSuccess((typed) =>
448
+ resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>
449
+ resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))
450
+ )
451
+ )
452
+ .thenOnSuccess(async ({ typed, kind, tag }) => {
453
+ const query: IMemoryQuery = {
454
+ ...(kind !== undefined ? { kind } : {}),
455
+ ...(tag !== undefined ? { tag } : {}),
456
+ ...(typed.semantic !== undefined ? { semantic: typed.semantic } : {}),
457
+ ...(typed.limit !== undefined ? { limit: typed.limit } : {})
458
+ };
459
+ return (await ctx.retriever.retrieve(query)).onSuccess((records) =>
460
+ succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r)) })
461
+ );
462
+ })
463
+ };
464
+ }
465
+
466
+ function buildContextTool(ctx: IToolContext): AiAssist.IAiClientTool {
467
+ return {
468
+ config: {
469
+ type: 'client_tool',
470
+ name: 'memory_context',
471
+ description:
472
+ 'Build a context graph from a seed memory: returns the records linked from the seed, up to `hops` hops.',
473
+ parametersSchema: contextSchema,
474
+ annotations: READ_ONLY_ANNOTATIONS
475
+ },
476
+ execute: async (args: unknown): Promise<Result<unknown>> =>
477
+ contextSchema
478
+ .convert(args)
479
+ .withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)
480
+ .onSuccess((typed) =>
481
+ Convert.memoryId
482
+ .convert(typed.from)
483
+ .onSuccess((from) =>
484
+ resolveOptionalKind(ctx, typed.kind).onSuccess((kind) =>
485
+ resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag }))
486
+ )
487
+ )
488
+ )
489
+ .thenOnSuccess(async ({ typed, from, kind, tag }) => {
490
+ const query: IMemoryQuery = {
491
+ linkedFrom: from,
492
+ ...(kind !== undefined ? { kind } : {}),
493
+ ...(tag !== undefined ? { tag } : {}),
494
+ ...(typed.hops !== undefined ? { hops: typed.hops } : {}),
495
+ ...(typed.limit !== undefined ? { limit: typed.limit } : {})
496
+ };
497
+ return (await ctx.retriever.retrieve(query)).onSuccess((records) =>
498
+ succeed({ seed: from, count: records.length, results: records.map((r) => projectItem(ctx, r)) })
499
+ );
500
+ })
501
+ };
502
+ }
503
+
504
+ function buildDeleteTool(ctx: IToolContext): AiAssist.IAiClientTool {
505
+ return {
506
+ config: {
507
+ type: 'client_tool',
508
+ name: 'memory_delete',
509
+ description: 'Delete a memory record by (kind, entityId). Destructive for non-temporal kinds.',
510
+ parametersSchema: deleteSchema,
511
+ annotations: DELETE_ANNOTATIONS
512
+ },
513
+ execute: async (args: unknown): Promise<Result<unknown>> =>
514
+ deleteSchema
515
+ .convert(args)
516
+ .withErrorFormat((msg) => `memory_delete: invalid arguments: ${msg}`)
517
+ .onSuccess((typed) =>
518
+ assertKindEnabled(ctx, typed.kind).onSuccess((kind) =>
519
+ Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))
520
+ )
521
+ )
522
+ .thenOnSuccess(async ({ kind, entityId }) =>
523
+ (await ctx.store.delete(kind, entityId)).onSuccess((id) =>
524
+ succeed({ deleted: true, id, entityId, kind })
525
+ )
526
+ )
527
+ };
528
+ }
529
+
530
+ /** Validate an optional `tag` string (`undefined` passes through). */
531
+ function resolveOptionalTag(tagStr?: string): Result<Tag | undefined> {
532
+ if (tagStr === undefined) {
533
+ return succeed(undefined);
534
+ }
535
+ return Convert.tag.convert(tagStr);
536
+ }
537
+
538
+ /** Ordered registry of the five tool builders, keyed by name. */
539
+ const TOOL_BUILDERS: ReadonlyArray<{
540
+ readonly name: MemoryToolName;
541
+ readonly build: (ctx: IToolContext) => AiAssist.IAiClientTool;
542
+ }> = [
543
+ { name: 'memory_write', build: buildWriteTool },
544
+ { name: 'memory_read', build: buildReadTool },
545
+ { name: 'memory_search', build: buildSearchTool },
546
+ { name: 'memory_context', build: buildContextTool },
547
+ { name: 'memory_delete', build: buildDeleteTool }
548
+ ];
549
+
550
+ /**
551
+ * Build the selected suite of memory `AiAssist.IAiClientTool`s over a
552
+ * pre-scoped store — ready to hand to `AiAssist.executeClientToolTurn` (and, via
553
+ * the shared `JsonSchema.object(...)` schemas, `@fgv/ts-extras-mcp`).
554
+ *
555
+ * @remarks
556
+ * **Scope isolation is make-or-break.** The returned tools close over the
557
+ * pre-scoped {@link ICreateMemoryToolsParams.store | store}; no tool's
558
+ * `parametersSchema` declares a `scope` (or any scope-widening) property, so an
559
+ * LLM cannot steer a tool at another actor's memory. The store instance is the
560
+ * sole scope authority.
561
+ *
562
+ * The default selection is {@link DEFAULT_MEMORY_TOOLS} (the read-only set) —
563
+ * `memory_write` / `memory_delete` are included only when named in
564
+ * {@link ICreateMemoryToolsParams.tools | tools}.
565
+ * @public
566
+ */
567
+ export function createMemoryTools(params: ICreateMemoryToolsParams): ReadonlyArray<AiAssist.IAiClientTool> {
568
+ const ctx: IToolContext = {
569
+ store: params.store,
570
+ retriever: params.retriever,
571
+ registry: params.registry,
572
+ kinds: params.kinds,
573
+ codecs: params.codecs,
574
+ defaultCodec: params.defaultCodec,
575
+ handleFor: params.handleFor
576
+ };
577
+ const selected: ReadonlySet<MemoryToolName> = new Set<MemoryToolName>(params.tools ?? DEFAULT_MEMORY_TOOLS);
578
+ return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));
579
+ }