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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/.rush/temp/{b82cf6bdece20481260e6bab946179eeec9d7b46.tar.log → cbbdbe09515171b4eba8f2592be2dace1e4e8142.tar.log} +14 -2
  2. package/.rush/temp/chunked-rush-logs/ts-agent-memory.build.chunks.jsonl +2 -2
  3. package/.rush/temp/operation/build/all.log +2 -2
  4. package/.rush/temp/operation/build/log-chunks.jsonl +2 -2
  5. package/.rush/temp/operation/build/state.json +1 -1
  6. package/dist/packlets/converters/envelopeConverter.js +17 -3
  7. package/dist/packlets/converters/envelopeConverter.js.map +1 -1
  8. package/dist/packlets/index/memoryIndex.js +58 -10
  9. package/dist/packlets/index/memoryIndex.js.map +1 -1
  10. package/dist/packlets/ingest/cycleGuard.js +13 -6
  11. package/dist/packlets/ingest/cycleGuard.js.map +1 -1
  12. package/dist/packlets/ingest/hostStages.js.map +1 -1
  13. package/dist/packlets/ingest/model.js.map +1 -1
  14. package/dist/packlets/ingest/orchestrator.js +94 -49
  15. package/dist/packlets/ingest/orchestrator.js.map +1 -1
  16. package/dist/packlets/retrieve/hybridRetriever.js +13 -2
  17. package/dist/packlets/retrieve/hybridRetriever.js.map +1 -1
  18. package/dist/packlets/retrieve/linkTraversalRetriever.js +46 -57
  19. package/dist/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
  20. package/dist/packlets/retrieve/recencyRetriever.js +3 -3
  21. package/dist/packlets/retrieve/recencyRetriever.js.map +1 -1
  22. package/dist/packlets/retrieve/retriever.js +50 -7
  23. package/dist/packlets/retrieve/retriever.js.map +1 -1
  24. package/dist/packlets/retrieve/semanticRetriever.js +9 -3
  25. package/dist/packlets/retrieve/semanticRetriever.js.map +1 -1
  26. package/dist/packlets/retrieve/structuredFilterRetriever.js +3 -3
  27. package/dist/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
  28. package/dist/packlets/retrieve/tagRetriever.js +3 -3
  29. package/dist/packlets/retrieve/tagRetriever.js.map +1 -1
  30. package/dist/packlets/retrieve/temporalRetrievers.js +3 -3
  31. package/dist/packlets/retrieve/temporalRetrievers.js.map +1 -1
  32. package/dist/packlets/store/fileTreeMemoryStore.js +72 -16
  33. package/dist/packlets/store/fileTreeMemoryStore.js.map +1 -1
  34. package/dist/packlets/tools/memoryTools.js +104 -21
  35. package/dist/packlets/tools/memoryTools.js.map +1 -1
  36. package/dist/packlets/types/envelope.js +13 -1
  37. package/dist/packlets/types/envelope.js.map +1 -1
  38. package/dist/packlets/vector/inMemoryCosineIndex.js +22 -17
  39. package/dist/packlets/vector/inMemoryCosineIndex.js.map +1 -1
  40. package/dist/packlets/vector/vectorIndex.js.map +1 -1
  41. package/dist/test/unit/converters/antagonistRoundTrip.test.js +3 -3
  42. package/dist/test/unit/converters/antagonistRoundTrip.test.js.map +1 -1
  43. package/dist/test/unit/converters/envelopeConverter.test.js +125 -8
  44. package/dist/test/unit/converters/envelopeConverter.test.js.map +1 -1
  45. package/dist/test/unit/index/memoryIndex.test.js +87 -25
  46. package/dist/test/unit/index/memoryIndex.test.js.map +1 -1
  47. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js +20 -16
  48. package/dist/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -1
  49. package/dist/test/unit/ingest/cycleGuard.test.js +28 -1
  50. package/dist/test/unit/ingest/cycleGuard.test.js.map +1 -1
  51. package/dist/test/unit/ingest/orchestrator.test.js +187 -45
  52. package/dist/test/unit/ingest/orchestrator.test.js.map +1 -1
  53. package/dist/test/unit/retrieve/linkTraversalRetriever.test.js +106 -31
  54. package/dist/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -1
  55. package/dist/test/unit/retrieve/retrievers.test.js +299 -37
  56. package/dist/test/unit/retrieve/retrievers.test.js.map +1 -1
  57. package/dist/test/unit/store/embedOnWrite.test.js +69 -12
  58. package/dist/test/unit/store/embedOnWrite.test.js.map +1 -1
  59. package/dist/test/unit/store/listScoped.test.js +109 -0
  60. package/dist/test/unit/store/listScoped.test.js.map +1 -0
  61. package/dist/test/unit/store/rankAxis.test.js +254 -0
  62. package/dist/test/unit/store/rankAxis.test.js.map +1 -0
  63. package/dist/test/unit/tools/memoryTools.test.js +280 -11
  64. package/dist/test/unit/tools/memoryTools.test.js.map +1 -1
  65. package/dist/test/unit/types/writePolicy.test.js +9 -2
  66. package/dist/test/unit/types/writePolicy.test.js.map +1 -1
  67. package/dist/test/unit/vector/inMemoryCosineIndex.test.js +95 -35
  68. package/dist/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -1
  69. package/dist/test/unit/vector/vectorIndex.test.js +24 -15
  70. package/dist/test/unit/vector/vectorIndex.test.js.map +1 -1
  71. package/dist/ts-agent-memory.d.ts +384 -97
  72. package/etc/ts-agent-memory.api.md +64 -22
  73. package/lib/packlets/converters/envelopeConverter.d.ts +8 -1
  74. package/lib/packlets/converters/envelopeConverter.d.ts.map +1 -1
  75. package/lib/packlets/converters/envelopeConverter.js +18 -4
  76. package/lib/packlets/converters/envelopeConverter.js.map +1 -1
  77. package/lib/packlets/index/memoryIndex.d.ts +42 -10
  78. package/lib/packlets/index/memoryIndex.d.ts.map +1 -1
  79. package/lib/packlets/index/memoryIndex.js +58 -10
  80. package/lib/packlets/index/memoryIndex.js.map +1 -1
  81. package/lib/packlets/ingest/cycleGuard.d.ts +5 -5
  82. package/lib/packlets/ingest/cycleGuard.d.ts.map +1 -1
  83. package/lib/packlets/ingest/cycleGuard.js +13 -6
  84. package/lib/packlets/ingest/cycleGuard.js.map +1 -1
  85. package/lib/packlets/ingest/hostStages.d.ts +3 -3
  86. package/lib/packlets/ingest/hostStages.d.ts.map +1 -1
  87. package/lib/packlets/ingest/hostStages.js.map +1 -1
  88. package/lib/packlets/ingest/model.d.ts +25 -14
  89. package/lib/packlets/ingest/model.d.ts.map +1 -1
  90. package/lib/packlets/ingest/model.js.map +1 -1
  91. package/lib/packlets/ingest/orchestrator.d.ts +18 -4
  92. package/lib/packlets/ingest/orchestrator.d.ts.map +1 -1
  93. package/lib/packlets/ingest/orchestrator.js +93 -48
  94. package/lib/packlets/ingest/orchestrator.js.map +1 -1
  95. package/lib/packlets/retrieve/hybridRetriever.d.ts.map +1 -1
  96. package/lib/packlets/retrieve/hybridRetriever.js +12 -1
  97. package/lib/packlets/retrieve/hybridRetriever.js.map +1 -1
  98. package/lib/packlets/retrieve/linkTraversalRetriever.d.ts +18 -23
  99. package/lib/packlets/retrieve/linkTraversalRetriever.d.ts.map +1 -1
  100. package/lib/packlets/retrieve/linkTraversalRetriever.js +45 -56
  101. package/lib/packlets/retrieve/linkTraversalRetriever.js.map +1 -1
  102. package/lib/packlets/retrieve/recencyRetriever.js +2 -2
  103. package/lib/packlets/retrieve/recencyRetriever.js.map +1 -1
  104. package/lib/packlets/retrieve/retriever.d.ts +70 -11
  105. package/lib/packlets/retrieve/retriever.d.ts.map +1 -1
  106. package/lib/packlets/retrieve/retriever.js +52 -7
  107. package/lib/packlets/retrieve/retriever.js.map +1 -1
  108. package/lib/packlets/retrieve/semanticRetriever.d.ts.map +1 -1
  109. package/lib/packlets/retrieve/semanticRetriever.js +9 -3
  110. package/lib/packlets/retrieve/semanticRetriever.js.map +1 -1
  111. package/lib/packlets/retrieve/structuredFilterRetriever.js +2 -2
  112. package/lib/packlets/retrieve/structuredFilterRetriever.js.map +1 -1
  113. package/lib/packlets/retrieve/tagRetriever.js +2 -2
  114. package/lib/packlets/retrieve/tagRetriever.js.map +1 -1
  115. package/lib/packlets/retrieve/temporalRetrievers.js +3 -3
  116. package/lib/packlets/retrieve/temporalRetrievers.js.map +1 -1
  117. package/lib/packlets/store/fileTreeMemoryStore.d.ts +57 -3
  118. package/lib/packlets/store/fileTreeMemoryStore.d.ts.map +1 -1
  119. package/lib/packlets/store/fileTreeMemoryStore.js +72 -16
  120. package/lib/packlets/store/fileTreeMemoryStore.js.map +1 -1
  121. package/lib/packlets/tools/memoryTools.d.ts +24 -0
  122. package/lib/packlets/tools/memoryTools.d.ts.map +1 -1
  123. package/lib/packlets/tools/memoryTools.js +104 -21
  124. package/lib/packlets/tools/memoryTools.js.map +1 -1
  125. package/lib/packlets/types/envelope.d.ts +61 -8
  126. package/lib/packlets/types/envelope.d.ts.map +1 -1
  127. package/lib/packlets/types/envelope.js +14 -0
  128. package/lib/packlets/types/envelope.js.map +1 -1
  129. package/lib/packlets/vector/inMemoryCosineIndex.d.ts +9 -5
  130. package/lib/packlets/vector/inMemoryCosineIndex.d.ts.map +1 -1
  131. package/lib/packlets/vector/inMemoryCosineIndex.js +22 -17
  132. package/lib/packlets/vector/inMemoryCosineIndex.js.map +1 -1
  133. package/lib/packlets/vector/vectorIndex.d.ts +46 -20
  134. package/lib/packlets/vector/vectorIndex.d.ts.map +1 -1
  135. package/lib/packlets/vector/vectorIndex.js.map +1 -1
  136. package/lib/test/unit/converters/antagonistRoundTrip.test.js +3 -3
  137. package/lib/test/unit/converters/antagonistRoundTrip.test.js.map +1 -1
  138. package/lib/test/unit/converters/envelopeConverter.test.js +124 -7
  139. package/lib/test/unit/converters/envelopeConverter.test.js.map +1 -1
  140. package/lib/test/unit/index/memoryIndex.test.js +86 -24
  141. package/lib/test/unit/index/memoryIndex.test.js.map +1 -1
  142. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js +20 -16
  143. package/lib/test/unit/ingest/antagonistCycleAndParity.test.js.map +1 -1
  144. package/lib/test/unit/ingest/cycleGuard.test.js +28 -1
  145. package/lib/test/unit/ingest/cycleGuard.test.js.map +1 -1
  146. package/lib/test/unit/ingest/orchestrator.test.js +186 -44
  147. package/lib/test/unit/ingest/orchestrator.test.js.map +1 -1
  148. package/lib/test/unit/retrieve/linkTraversalRetriever.test.js +106 -31
  149. package/lib/test/unit/retrieve/linkTraversalRetriever.test.js.map +1 -1
  150. package/lib/test/unit/retrieve/retrievers.test.js +298 -36
  151. package/lib/test/unit/retrieve/retrievers.test.js.map +1 -1
  152. package/lib/test/unit/store/embedOnWrite.test.js +68 -11
  153. package/lib/test/unit/store/embedOnWrite.test.js.map +1 -1
  154. package/lib/test/unit/store/listScoped.test.d.ts +2 -0
  155. package/lib/test/unit/store/listScoped.test.d.ts.map +1 -0
  156. package/lib/test/unit/store/listScoped.test.js +111 -0
  157. package/lib/test/unit/store/listScoped.test.js.map +1 -0
  158. package/lib/test/unit/store/rankAxis.test.d.ts +2 -0
  159. package/lib/test/unit/store/rankAxis.test.d.ts.map +1 -0
  160. package/lib/test/unit/store/rankAxis.test.js +256 -0
  161. package/lib/test/unit/store/rankAxis.test.js.map +1 -0
  162. package/lib/test/unit/tools/memoryTools.test.js +280 -11
  163. package/lib/test/unit/tools/memoryTools.test.js.map +1 -1
  164. package/lib/test/unit/types/writePolicy.test.js +9 -2
  165. package/lib/test/unit/types/writePolicy.test.js.map +1 -1
  166. package/lib/test/unit/vector/inMemoryCosineIndex.test.js +95 -35
  167. package/lib/test/unit/vector/inMemoryCosineIndex.test.js.map +1 -1
  168. package/lib/test/unit/vector/vectorIndex.test.js +24 -15
  169. package/lib/test/unit/vector/vectorIndex.test.js.map +1 -1
  170. package/package.json +7 -7
  171. package/rush-logs/ts-agent-memory.build.cache.log +1 -1
  172. package/rush-logs/ts-agent-memory.build.log +2 -2
  173. package/src/packlets/converters/envelopeConverter.ts +27 -4
  174. package/src/packlets/index/memoryIndex.ts +86 -22
  175. package/src/packlets/ingest/cycleGuard.ts +22 -11
  176. package/src/packlets/ingest/hostStages.ts +3 -3
  177. package/src/packlets/ingest/model.ts +25 -14
  178. package/src/packlets/ingest/orchestrator.ts +143 -67
  179. package/src/packlets/retrieve/hybridRetriever.ts +14 -1
  180. package/src/packlets/retrieve/linkTraversalRetriever.ts +51 -62
  181. package/src/packlets/retrieve/recencyRetriever.ts +3 -3
  182. package/src/packlets/retrieve/retriever.ts +97 -13
  183. package/src/packlets/retrieve/semanticRetriever.ts +10 -5
  184. package/src/packlets/retrieve/structuredFilterRetriever.ts +3 -3
  185. package/src/packlets/retrieve/tagRetriever.ts +3 -3
  186. package/src/packlets/retrieve/temporalRetrievers.ts +3 -3
  187. package/src/packlets/store/fileTreeMemoryStore.ts +117 -12
  188. package/src/packlets/tools/memoryTools.ts +152 -25
  189. package/src/packlets/types/envelope.ts +66 -8
  190. package/src/packlets/vector/inMemoryCosineIndex.ts +45 -22
  191. package/src/packlets/vector/vectorIndex.ts +47 -20
  192. package/src/test/unit/converters/antagonistRoundTrip.test.ts +3 -3
  193. package/src/test/unit/converters/envelopeConverter.test.ts +168 -11
  194. package/src/test/unit/index/memoryIndex.test.ts +99 -14
  195. package/src/test/unit/ingest/antagonistCycleAndParity.test.ts +23 -18
  196. package/src/test/unit/ingest/cycleGuard.test.ts +44 -2
  197. package/src/test/unit/ingest/orchestrator.test.ts +234 -41
  198. package/src/test/unit/retrieve/linkTraversalRetriever.test.ts +134 -35
  199. package/src/test/unit/retrieve/retrievers.test.ts +381 -25
  200. package/src/test/unit/store/embedOnWrite.test.ts +83 -11
  201. package/src/test/unit/store/listScoped.test.ts +138 -0
  202. package/src/test/unit/store/rankAxis.test.ts +349 -0
  203. package/src/test/unit/tools/memoryTools.test.ts +362 -13
  204. package/src/test/unit/types/writePolicy.test.ts +11 -2
  205. package/src/test/unit/vector/inMemoryCosineIndex.test.ts +115 -39
  206. package/src/test/unit/vector/vectorIndex.test.ts +33 -17
  207. package/temp/build/lint/_eslint-5eVG3S6w.json +41 -33
  208. package/temp/build/typescript/ts_8nwakTlr.json +1 -1
  209. package/temp/ts-agent-memory.api.json +1080 -136
  210. package/temp/ts-agent-memory.api.md +64 -22
@@ -20,11 +20,24 @@ export const DEFAULT_MEMORY_TOOLS = ['memory_search', 'memory_context'];
20
20
  // NONE of these declare a `scope` (or scope-widening) property — the adoption
21
21
  // gate is enforced structurally and asserted in the tests.
22
22
  // ---------------------------------------------------------------------------
23
+ /**
24
+ * The scope-qualified target of a link edge authored by the agent on a write.
25
+ * `scope` is optional: when omitted it defaults to the writing record's OWN
26
+ * resolved scope (the common same-conversation case); supply it explicitly to
27
+ * point an edge at a record in a different scope.
28
+ */
29
+ // eslint-disable-next-line @rushstack/typedef-var
30
+ const linkTargetSchema = JsonSchema.object({
31
+ id: JsonSchema.string({ description: 'The MemoryId of the record this edge points at.' }),
32
+ scope: JsonSchema.optional(JsonSchema.string({
33
+ description: "The target record's scope. Defaults to the writing record's own scope when omitted."
34
+ }))
35
+ });
23
36
  /** A single attributed link edge as authored by the agent on a write. */
24
37
  // eslint-disable-next-line @rushstack/typedef-var
25
38
  const linkEdgeSchema = JsonSchema.object({
26
39
  type: JsonSchema.string({ description: 'The relation type of the link.' }),
27
- target: JsonSchema.string({ description: 'The MemoryId this edge points at.' }),
40
+ target: linkTargetSchema,
28
41
  confidence: JsonSchema.optional(JsonSchema.number({ description: 'Optional confidence in [0, 1].' }))
29
42
  });
30
43
  // eslint-disable-next-line @rushstack/typedef-var
@@ -40,7 +53,8 @@ const writeSchema = JsonSchema.object({
40
53
  // eslint-disable-next-line @rushstack/typedef-var
41
54
  const readSchema = JsonSchema.object({
42
55
  kind: JsonSchema.string({ description: 'The record kind.' }),
43
- entityId: JsonSchema.string({ description: 'The domain entity id to read.' })
56
+ entityId: JsonSchema.string({ description: 'The domain entity id to read.' }),
57
+ detail: JsonSchema.optional(JsonSchema.enumOf(['gist', 'full'], { description: "'gist' | 'full' (default)." }))
44
58
  });
45
59
  // eslint-disable-next-line @rushstack/typedef-var
46
60
  const deleteSchema = JsonSchema.object({
@@ -52,15 +66,33 @@ const searchSchema = JsonSchema.object({
52
66
  kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to this kind.' })),
53
67
  tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict to records carrying this tag.' })),
54
68
  semantic: JsonSchema.optional(JsonSchema.string({ description: 'Semantic query text (requires a semantic-capable retriever).' })),
55
- limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
69
+ limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' })),
70
+ offset: JsonSchema.optional(JsonSchema.integer({ description: 'Number of results to skip after ordering, before limit. Default 0.' })),
71
+ detail: JsonSchema.optional(JsonSchema.enumOf(['gist', 'full'], { description: "'gist' (default) | 'full'." }))
72
+ });
73
+ /**
74
+ * The scope-qualified seed a `memory_context` traversal starts from. Nested
75
+ * `{ id, scope }` shape like a link target, but — unlike a write edge — there is
76
+ * no writing record to default the scope from, so `scope` is REQUIRED to
77
+ * disambiguate the seed across scopes (a bare stem like `turn-3` is otherwise
78
+ * ambiguous). It is schema-required (not just runtime-required) so the wire
79
+ * schema an LLM reads never advertises an optionality the tool does not honor.
80
+ */
81
+ // eslint-disable-next-line @rushstack/typedef-var
82
+ const contextSeedSchema = JsonSchema.object({
83
+ id: JsonSchema.string({ description: 'The MemoryId of the seed record to traverse links from.' }),
84
+ scope: JsonSchema.string({
85
+ description: 'The scope of the seed record (required — a bare seed id is ambiguous across scopes).'
86
+ })
56
87
  });
57
88
  // eslint-disable-next-line @rushstack/typedef-var
58
89
  const contextSchema = JsonSchema.object({
59
- from: JsonSchema.string({ description: 'The seed MemoryId to traverse links from.' }),
90
+ from: contextSeedSchema,
60
91
  kind: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records to this kind.' })),
61
92
  tag: JsonSchema.optional(JsonSchema.string({ description: 'Restrict reached records carrying this tag.' })),
62
93
  hops: JsonSchema.optional(JsonSchema.integer({ description: 'BFS hop count (default 1).' })),
63
- limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' }))
94
+ limit: JsonSchema.optional(JsonSchema.integer({ description: 'Maximum number of results to return.' })),
95
+ detail: JsonSchema.optional(JsonSchema.enumOf(['gist', 'full'], { description: "'gist' (default) | 'full'." }))
64
96
  });
65
97
  // ---------------------------------------------------------------------------
66
98
  // Behavior annotations (Component 4) — host-advisory hints; never serialized to
@@ -102,8 +134,16 @@ function resolveOptionalKind(ctx, kindStr) {
102
134
  }
103
135
  return assertKindEnabled(ctx, kindStr);
104
136
  }
105
- /** Project a record into an agent-visible result item, applying the host handle hook when present. */
106
- function projectItem(ctx, record) {
137
+ /**
138
+ * Resolve the requested detail tier from the optional tool `detail` string.
139
+ * `'full'` is the only opt-in value; every other input (absent, or an
140
+ * unrecognized string) resolves safely to the bounded default `'gist'`.
141
+ */
142
+ function resolveDetail(detail) {
143
+ return detail === 'full' ? 'full' : 'gist';
144
+ }
145
+ /** The built-in default projection: full body plus the guarded host handle. Ignores the detail tier. */
146
+ function defaultProjectItem(ctx, record) {
107
147
  // `handleFor` is a host callback; guard it so a throw degrades to the raw id rather than
108
148
  // escaping the Result chain (and crashing the whole search/context call).
109
149
  const handle = ctx.handleFor !== undefined
@@ -117,6 +157,22 @@ function projectItem(ctx, record) {
117
157
  body: record.body
118
158
  };
119
159
  }
160
+ /**
161
+ * Project a record into an agent-visible result item at the requested detail
162
+ * tier. When a host {@link ICreateMemoryToolsParams.projectItem | projectItem}
163
+ * is supplied it owns the projection; otherwise the built-in
164
+ * {@link defaultProjectItem} (full body) is used. The host callback is guarded
165
+ * like `handleFor` — a throw degrades to the default full-body projection for
166
+ * that item rather than failing the whole search/context call.
167
+ */
168
+ function projectItem(ctx, record, detail) {
169
+ if (ctx.projectItem === undefined) {
170
+ return defaultProjectItem(ctx, record);
171
+ }
172
+ // Guard the host projector like `handleFor`: a throw degrades to the built-in
173
+ // full-body projection (itself throw-safe) rather than escaping the chain.
174
+ return captureResult(() => ctx.projectItem(record, detail)).orDefault(defaultProjectItem(ctx, record));
175
+ }
120
176
  /** Resolve the identity codec used by `memory_write` to derive the storage id. */
121
177
  function codecForWrite(ctx, kind) {
122
178
  var _a, _b;
@@ -127,11 +183,16 @@ function codecForWrite(ctx, kind) {
127
183
  return succeed(codec);
128
184
  }
129
185
  /** Build the record to persist from validated write args (store stamps txn-time metadata). */
130
- function buildWriteRecord(typed, kind, entityId, idStem) {
186
+ function buildWriteRecord(typed, kind, entityId, idStem, sourceScope) {
131
187
  var _a, _b;
132
188
  // Plain shapes handed to `envelopeConverter`, which validates each field
133
- // (type → LinkType, target → MemoryId) and produces the branded IEdge[].
134
- const links = ((_a = typed.links) !== null && _a !== void 0 ? _a : []).map((link) => (Object.assign({ type: link.type, target: link.target }, (link.confidence !== undefined ? { confidence: link.confidence } : {}))));
189
+ // (type → LinkType, target → { scope, id }) and produces the branded IEdge[].
190
+ // An edge target with no explicit `scope` defaults to the writing record's own
191
+ // resolved scope — the same-conversation case authors just an id.
192
+ const links = ((_a = typed.links) !== null && _a !== void 0 ? _a : []).map((link) => {
193
+ var _a;
194
+ return (Object.assign({ type: link.type, target: { scope: (_a = link.target.scope) !== null && _a !== void 0 ? _a : sourceScope, id: link.target.id } }, (link.confidence !== undefined ? { confidence: link.confidence } : {})));
195
+ });
135
196
  return envelopeConverter
136
197
  .convert({
137
198
  id: idStem,
@@ -154,7 +215,7 @@ function prepareWrite(ctx, typed) {
154
215
  if (addr.isVersioned) {
155
216
  return fail(`memory_write: versioned/temporal kind '${kind}' is not supported`);
156
217
  }
157
- return buildWriteRecord(typed, kind, entityId, addr.idStem).onSuccess((record) => succeed({ kind, entityId, record }));
218
+ return buildWriteRecord(typed, kind, entityId, addr.idStem, addr.scope).onSuccess((record) => succeed({ kind, entityId, record }));
158
219
  }))));
159
220
  }
160
221
  /**
@@ -226,10 +287,15 @@ function buildReadTool(ctx) {
226
287
  execute: async (args) => readSchema
227
288
  .convert(args)
228
289
  .withErrorFormat((msg) => `memory_read: invalid arguments: ${msg}`)
229
- .onSuccess((typed) => assertKindEnabled(ctx, typed.kind).onSuccess((kind) => Convert.entityId.convert(typed.entityId).onSuccess((entityId) => succeed({ kind, entityId }))))
230
- .thenOnSuccess(async ({ kind, entityId }) => (await ctx.store.get(kind, entityId)).onSuccess((record) => record === undefined
290
+ .onSuccess((typed) => assertKindEnabled(ctx, typed.kind).onSuccess((kind) => Convert.entityId.convert(typed.entityId).onSuccess((entityId) => {
291
+ // `memory_read` is the explicit drill-in path, so its detail default is
292
+ // INVERTED vs search/context: `'full'` unless the caller opts down to `'gist'`.
293
+ const detail = typed.detail === 'gist' ? 'gist' : 'full';
294
+ return succeed({ kind, entityId, detail });
295
+ })))
296
+ .thenOnSuccess(async ({ kind, entityId, detail }) => (await ctx.store.get(kind, entityId)).onSuccess((record) => record === undefined
231
297
  ? succeed({ found: false })
232
- : succeed({ found: true, item: projectItem(ctx, record) })))
298
+ : succeed({ found: true, item: projectItem(ctx, record, detail) })))
233
299
  };
234
300
  }
235
301
  function buildSearchTool(ctx) {
@@ -246,8 +312,9 @@ function buildSearchTool(ctx) {
246
312
  .withErrorFormat((msg) => `memory_search: invalid arguments: ${msg}`)
247
313
  .onSuccess((typed) => resolveOptionalKind(ctx, typed.kind).onSuccess((kind) => resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, kind, tag }))))
248
314
  .thenOnSuccess(async ({ typed, kind, tag }) => {
249
- const query = Object.assign(Object.assign(Object.assign(Object.assign({}, (kind !== undefined ? { kind } : {})), (tag !== undefined ? { tag } : {})), (typed.semantic !== undefined ? { semantic: typed.semantic } : {})), (typed.limit !== undefined ? { limit: typed.limit } : {}));
250
- return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r)) }));
315
+ const detail = resolveDetail(typed.detail);
316
+ const query = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (kind !== undefined ? { kind } : {})), (tag !== undefined ? { tag } : {})), (typed.semantic !== undefined ? { semantic: typed.semantic } : {})), (typed.limit !== undefined ? { limit: typed.limit } : {})), (typed.offset !== undefined ? { offset: typed.offset } : {}));
317
+ return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r, detail)) }));
251
318
  })
252
319
  };
253
320
  }
@@ -263,12 +330,15 @@ function buildContextTool(ctx) {
263
330
  execute: async (args) => contextSchema
264
331
  .convert(args)
265
332
  .withErrorFormat((msg) => `memory_context: invalid arguments: ${msg}`)
266
- .onSuccess((typed) => Convert.memoryId
267
- .convert(typed.from)
268
- .onSuccess((from) => resolveOptionalKind(ctx, typed.kind).onSuccess((kind) => resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag })))))
333
+ .onSuccess((typed) => resolveContextSeed(typed.from).onSuccess((from) => resolveOptionalKind(ctx, typed.kind).onSuccess((kind) => resolveOptionalTag(typed.tag).onSuccess((tag) => succeed({ typed, from, kind, tag })))))
269
334
  .thenOnSuccess(async ({ typed, from, kind, tag }) => {
335
+ const detail = resolveDetail(typed.detail);
270
336
  const query = Object.assign(Object.assign(Object.assign(Object.assign({ linkedFrom: from }, (kind !== undefined ? { kind } : {})), (tag !== undefined ? { tag } : {})), (typed.hops !== undefined ? { hops: typed.hops } : {})), (typed.limit !== undefined ? { limit: typed.limit } : {}));
271
- return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({ seed: from, count: records.length, results: records.map((r) => projectItem(ctx, r)) }));
337
+ return (await ctx.retriever.retrieve(query)).onSuccess((records) => succeed({
338
+ seed: from,
339
+ count: records.length,
340
+ results: records.map((r) => projectItem(ctx, r, detail))
341
+ }));
272
342
  })
273
343
  };
274
344
  }
@@ -288,6 +358,18 @@ function buildDeleteTool(ctx) {
288
358
  .thenOnSuccess(async ({ kind, entityId }) => (await ctx.store.delete(kind, entityId)).onSuccess((id) => succeed({ deleted: true, id, entityId, kind })))
289
359
  };
290
360
  }
361
+ /**
362
+ * Resolve a `memory_context` seed argument into a scope-qualified
363
+ * {@link IEdgeTarget}. Both `id` and `scope` are present here — the tool's
364
+ * `parametersSchema` ({@link contextSeedSchema}) makes `scope` schema-required —
365
+ * so this only brands the two fields; a malformed value fails via the branded
366
+ * converters (e.g. a path-unsafe seed id).
367
+ */
368
+ function resolveContextSeed(from) {
369
+ return Convert.memoryId
370
+ .convert(from.id)
371
+ .onSuccess((id) => Convert.scopeKey.convert(from.scope).onSuccess((scope) => succeed({ scope, id })));
372
+ }
291
373
  /** Validate an optional `tag` string (`undefined` passes through). */
292
374
  function resolveOptionalTag(tagStr) {
293
375
  if (tagStr === undefined) {
@@ -329,7 +411,8 @@ export function createMemoryTools(params) {
329
411
  kinds: params.kinds,
330
412
  codecs: params.codecs,
331
413
  defaultCodec: params.defaultCodec,
332
- handleFor: params.handleFor
414
+ handleFor: params.handleFor,
415
+ projectItem: params.projectItem
333
416
  };
334
417
  const selected = new Set((_a = params.tools) !== null && _a !== void 0 ? _a : DEFAULT_MEMORY_TOOLS);
335
418
  return TOOL_BUILDERS.filter((builder) => selected.has(builder.name)).map((builder) => builder.build(ctx));
@@ -1 +1 @@
1
- {"version":3,"file":"memoryTools.js","sourceRoot":"","sources":["../../../src/packlets/tools/memoryTools.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,OAAO,EAAgE,MAAM,UAAU,CAAC;AACjG,OAAO,EAA0B,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAgB1E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAkC,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAsHvG,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2DAA2D;AAC3D,8EAA8E;AAE9E,yEAAyE;AACzE,kDAAkD;AAClD,MAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC;IACvC,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,gCAAgC,EAAE,CAAC;IAC1E,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mCAAmC,EAAE,CAAC;IAC/E,UAAU,EAAE,UAAU,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,E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AACrC,CAAC;AAED,iEAAiE;AACjE,MAAM,aAAa,GAGd;IACH,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,cAAc,EAAE;IAC/C,EAAE,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE,aAAa,EAAE;IAC7C,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE;IACjD,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,gBAAgB,EAAE;IACnD,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,eAAe,EAAE;CAClD,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAgC;;IAChE,MAAM,GAAG,GAAiB;QACxB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,SAAS,EAAE,MAAM,CAAC,SAAS;KAC5B,CAAC;IACF,MAAM,QAAQ,GAAgC,IAAI,GAAG,CAAiB,MAAA,MAAM,CAAC,KAAK,mCAAI,oBAAoB,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, 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\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}\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/** 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: JsonSchema.string({ description: 'The MemoryId this edge points at.' }),\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});\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});\n\n// eslint-disable-next-line @rushstack/typedef-var\nconst contextSchema = JsonSchema.object({\n from: JsonSchema.string({ description: 'The seed MemoryId to traverse links from.' }),\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});\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/** Project a record into an agent-visible result item, applying the host handle hook when present. */\nfunction projectItem(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/** 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): Result<IMemoryRecord<unknown>> {\n // Plain shapes handed to `envelopeConverter`, which validates each field\n // (type → LinkType, target → MemoryId) and produces the branded IEdge[].\n const links: ReadonlyArray<Record<string, unknown>> = (typed.links ?? []).map((link) => ({\n type: link.type,\n target: link.target,\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).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) => succeed({ kind, entityId }))\n )\n )\n .thenOnSuccess(async ({ kind, entityId }) =>\n (await ctx.store.get(kind, entityId)).onSuccess((record) =>\n record === undefined\n ? succeed({ found: false })\n : succeed({ found: true, item: projectItem(ctx, record) })\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 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 };\n return (await ctx.retriever.retrieve(query)).onSuccess((records) =>\n succeed({ count: records.length, results: records.map((r) => projectItem(ctx, r)) })\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 Convert.memoryId\n .convert(typed.from)\n .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 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({ seed: from, count: records.length, results: records.map((r) => projectItem(ctx, r)) })\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/** 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 };\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;AAEH,OAAO,EAAU,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAE,OAAO,EAA6E,MAAM,UAAU,CAAC;AAC9G,OAAO,EAA0B,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAgB1E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAkC,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAgJv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AAS;QAC3B,WAAW,EAAE,MAAM,CAAC,WAAW;KAChC,CAAC;IACF,MAAM,QAAQ,GAAgC,IAAI,GAAG,CAAiB,MAAA,MAAM,CAAC,KAAK,mCAAI,oBAAoB,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(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"]}
@@ -2,5 +2,17 @@
2
2
  * Copyright (c) 2026 Erik Fortune
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
- export {};
5
+ /**
6
+ * The canonical composite-key string for an {@link IEdgeTarget}: scope + id,
7
+ * NUL-separated. NUL is excluded from both components (scope segments are
8
+ * filename-safe; {@link MemoryId} is portable-filename-safe), so it is a
9
+ * collision-proof separator. This is the ONE canonicalization every consumer
10
+ * that keys on a scoped target uses — the backlink index, the cycle guard, and
11
+ * the ingest edge-validation path all route through it so their notions of
12
+ * "same target" cannot drift.
13
+ * @public
14
+ */
15
+ export function edgeTargetKey(target) {
16
+ return `${target.scope}\0${target.id}`;
17
+ }
6
18
  //# sourceMappingURL=envelope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../src/packlets/types/envelope.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n * SPDX-License-Identifier: MIT\n */\n\nimport { EntityId, Kind, LinkType, MemoryId, 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 /** Back-link to the source experience record. Enables the cross-kind provenance spine. */\n readonly derivedFrom?: MemoryId;\n /** Opaque extension payload — consumer-owned, never interpreted by the store. */\n readonly [key: string]: unknown;\n}\n\n/**\n * An attributed link between two records. Carries the relation type, the\n * target id, and optional confidence / provenance / world-truth validity.\n * Replaces bare string references (e.g. PersonAIlity's `IMtmRef` becomes an\n * `IEdge` with `type: LinkType('mtm-ref')`).\n * @public\n */\nexport interface IEdge {\n /** Open-vocabulary relation type. */\n readonly type: LinkType;\n /** The linked-to record. */\n readonly target: MemoryId;\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 /** 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"]}
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../src/packlets/types/envelope.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAyDH;;;;;;;;;GASG;AACH,MAAM,UAAU,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 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 * @public\n */\nexport type RankProjector = (record: IMemoryRecord<unknown>) => number;\n"]}
@@ -3,6 +3,7 @@
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
5
  import { fail, succeed } from '@fgv/ts-utils';
6
+ import { edgeTargetKey } from '../types';
6
7
  /**
7
8
  * The brute-force, in-memory cosine {@link IVectorIndex}. Stores one
8
9
  * `Float32Array` per record and answers a query by computing cosine similarity
@@ -40,26 +41,28 @@ export class InMemoryCosineIndex {
40
41
  return succeed(new InMemoryCosineIndex());
41
42
  }
42
43
  /** {@inheritDoc IVectorIndex.add} */
43
- add(id, vector) {
44
+ add(target, vector) {
45
+ const key = edgeTargetKey(target);
44
46
  if (vector.length === 0) {
45
- return Promise.resolve(fail(`vector index: cannot add '${id}': empty vector`));
47
+ return Promise.resolve(fail(`vector index: cannot add '${key}': empty vector`));
46
48
  }
47
49
  if (this._dimension === undefined) {
48
50
  this._dimension = vector.length;
49
51
  }
50
52
  else if (vector.length !== this._dimension) {
51
- return Promise.resolve(fail(`vector index: cannot add '${id}': dimension ${vector.length} does not match index dimension ${this._dimension}`));
53
+ return Promise.resolve(fail(`vector index: cannot add '${key}': dimension ${vector.length} does not match index dimension ${this._dimension}`));
52
54
  }
53
55
  // Defensive copy: the caller may reuse or mutate the buffer after `add`, and
54
56
  // the index must keep serving the embedding it was given.
55
- this._vectors.set(id, Float32Array.from(vector));
56
- // The in-memory index keys entries by id, so the id IS the entry reference.
57
- return Promise.resolve(succeed(id));
57
+ this._vectors.set(key, { target, vector: Float32Array.from(vector) });
58
+ // The in-memory index keys entries by the canonical scoped-target string, so
59
+ // that key IS the entry reference.
60
+ return Promise.resolve(succeed(key));
58
61
  }
59
62
  /** {@inheritDoc IVectorIndex.remove} */
60
- remove(id) {
61
- this._vectors.delete(id);
62
- return Promise.resolve(succeed(id));
63
+ remove(target) {
64
+ this._vectors.delete(edgeTargetKey(target));
65
+ return Promise.resolve(succeed(target));
63
66
  }
64
67
  /** {@inheritDoc IVectorIndex.query} */
65
68
  query(vector, topK) {
@@ -71,8 +74,11 @@ export class InMemoryCosineIndex {
71
74
  }
72
75
  const queryMagnitude = InMemoryCosineIndex._magnitude(vector);
73
76
  const hits = [];
74
- for (const [id, stored] of this._vectors) {
75
- hits.push({ id, score: InMemoryCosineIndex._cosine(vector, queryMagnitude, stored) });
77
+ for (const stored of this._vectors.values()) {
78
+ hits.push({
79
+ target: stored.target,
80
+ score: InMemoryCosineIndex._cosine(vector, queryMagnitude, stored.vector)
81
+ });
76
82
  }
77
83
  // Descending by score; a `seq`-free tiebreak is unnecessary here because the
78
84
  // caller (SemanticRetriever) re-resolves hits against the record index.
@@ -89,8 +95,7 @@ export class InMemoryCosineIndex {
89
95
  * rather than left in a partially-rebuilt state — a caller that retries a query
90
96
  * after a failed rebuild sees a clean empty index, never a half-populated one.
91
97
  *
92
- * @param source - The record source to re-embed (an {@link IMemoryStore}
93
- * satisfies this structurally).
98
+ * @param source - The scope-qualified record source to re-embed.
94
99
  * @param embed - The embedder applied to each record.
95
100
  */
96
101
  async rebuild(source, embed) {
@@ -102,13 +107,13 @@ export class InMemoryCosineIndex {
102
107
  if (listed.isFailure()) {
103
108
  return fail(`vector index rebuild: failed to list records: ${listed.message}`);
104
109
  }
105
- for (const record of listed.value) {
106
- const embedded = await embed(record);
110
+ for (const scoped of listed.value) {
111
+ const embedded = await embed(scoped.record);
107
112
  if (embedded.isFailure()) {
108
113
  this._reset();
109
- return fail(`vector index rebuild: embedding '${record.envelope.id}' failed: ${embedded.message}`);
114
+ return fail(`vector index rebuild: embedding '${edgeTargetKey(scoped.target)}' failed: ${embedded.message}`);
110
115
  }
111
- const added = await this.add(record.envelope.id, embedded.value);
116
+ const added = await this.add(scoped.target, embedded.value);
112
117
  if (added.isFailure()) {
113
118
  this._reset();
114
119
  return fail(`vector index rebuild: ${added.message}`);