@systemfsoftware/agent-storage-memory 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs +609 -0
  3. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs.map +1 -0
  4. package/dist/MemoryMessageDeliveryStore-BmLntoBA.d.mts +18 -0
  5. package/dist/MemoryMessageDeliveryStore.d.mts +2 -0
  6. package/dist/MemoryMessageDeliveryStore.mjs +1 -0
  7. package/dist/MemoryScheduleStore-Bb85CXg1.mjs +163 -0
  8. package/dist/MemoryScheduleStore-Bb85CXg1.mjs.map +1 -0
  9. package/dist/MemoryScheduleStore-C_ll7Xyr.d.mts +8 -0
  10. package/dist/MemoryScheduleStore.d.mts +2 -0
  11. package/dist/MemoryScheduleStore.mjs +1 -0
  12. package/dist/MemorySemanticIndex-DYljUBy4.mjs +224 -0
  13. package/dist/MemorySemanticIndex-DYljUBy4.mjs.map +1 -0
  14. package/dist/MemorySemanticIndex-DrcJ7UG4.d.mts +20 -0
  15. package/dist/MemorySemanticIndex.d.mts +2 -0
  16. package/dist/MemorySemanticIndex.mjs +1 -0
  17. package/dist/MemorySubmissionLedger-DO-F22Gu.d.mts +28 -0
  18. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs +1566 -0
  19. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs.map +1 -0
  20. package/dist/MemorySubmissionLedger.d.mts +2 -0
  21. package/dist/MemorySubmissionLedger.mjs +1 -0
  22. package/dist/MemorySubscriptionStore-BWZ9lcIY.d.mts +7 -0
  23. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs +929 -0
  24. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs.map +1 -0
  25. package/dist/MemorySubscriptionStore.d.mts +2 -0
  26. package/dist/MemorySubscriptionStore.mjs +1 -0
  27. package/dist/MemoryThreadStore-BX3sRYhE.d.mts +21 -0
  28. package/dist/MemoryThreadStore-Dtwe-7h4.mjs +1415 -0
  29. package/dist/MemoryThreadStore-Dtwe-7h4.mjs.map +1 -0
  30. package/dist/MemoryThreadStore.d.mts +2 -0
  31. package/dist/MemoryThreadStore.mjs +1 -0
  32. package/dist/MemoryThreadStoreKernel-5ya9AJvL.d.mts +85 -0
  33. package/dist/WorkSelection-Xr9mCon_.mjs +29 -0
  34. package/dist/WorkSelection-Xr9mCon_.mjs.map +1 -0
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.mjs +7 -0
  37. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  38. package/package.json +67 -5
  39. package/src/MemoryMessageDeliveryStore.ts +1004 -0
  40. package/src/MemoryScheduleStore.ts +324 -0
  41. package/src/MemorySemanticIndex.ts +360 -0
  42. package/src/MemorySubmissionLedger.ts +3590 -0
  43. package/src/MemorySubscriptionStore.ts +1762 -0
  44. package/src/MemoryThreadStore.ts +2810 -0
  45. package/src/index.ts +6 -0
  46. package/src/internal/MemoryThreadStoreKernel.ts +156 -0
  47. package/src/internal/WorkSelection.ts +29 -0
  48. package/README.md +0 -3
@@ -0,0 +1,324 @@
1
+ import {
2
+ defaultSchedulingLimits,
3
+ ScheduleCapacityError,
4
+ ScheduleChange,
5
+ ScheduleConflict,
6
+ ScheduleDueCursor,
7
+ ScheduleFailpoint,
8
+ ScheduleKey,
9
+ ScheduleNotFound,
10
+ ScheduleOwner,
11
+ SchedulePageRequest,
12
+ ScheduleRecord,
13
+ ScheduleStorageError,
14
+ ScheduleStore,
15
+ } from '@systemfsoftware/agent/schedule'
16
+ import {
17
+ applyScheduleChange,
18
+ compareScheduleKeys,
19
+ compareScheduleNames,
20
+ scheduleDeadline,
21
+ scheduleKeyOf,
22
+ scheduleKeyString,
23
+ scheduleOwnerKey,
24
+ scheduleUsesCapacity,
25
+ } from '@systemfsoftware/agent/schedule-transition'
26
+ import * as Effect from 'effect/Effect'
27
+ import * as Layer from 'effect/Layer'
28
+ import * as Ref from 'effect/Ref'
29
+ import * as Result from 'effect/Result'
30
+ import * as Schema from 'effect/Schema'
31
+
32
+ interface MemoryScheduleState {
33
+ readonly records: ReadonlyMap<string, string>
34
+ }
35
+
36
+ const storageError = (operation: string, reason: 'unavailable' | 'corrupt') =>
37
+ ScheduleStorageError.make({ operation, reason })
38
+
39
+ const encodeRecord = (operation: string, record: ScheduleRecord) =>
40
+ Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(
41
+ Effect.mapError(() => storageError(operation, 'corrupt')),
42
+ )
43
+
44
+ const decodeRecord = (operation: string, encoded: string) =>
45
+ Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(encoded).pipe(
46
+ Effect.mapError(() => storageError(operation, 'corrupt')),
47
+ )
48
+
49
+ const decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>
50
+ Schema.decodeUnknownEffect(schema)(value).pipe(
51
+ Effect.mapError(() => storageError(operation, 'corrupt')),
52
+ )
53
+
54
+ const sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>
55
+ scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner)
56
+
57
+ const makeScheduleStore = Effect.gen(function*() {
58
+ const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() })
59
+ const failpoint = yield* ScheduleFailpoint
60
+
61
+ const insert: ScheduleStore['Service']['insert'] = Effect.fnUntraced(
62
+ function*(record, ownerLimit) {
63
+ const encoded = yield* encodeRecord('insert', record)
64
+
65
+ yield* failpoint.hit('schedule:insert:before')
66
+
67
+ const decision = yield* Effect.uninterruptible(
68
+ Ref.modify(
69
+ state,
70
+ (
71
+ current,
72
+ ): readonly [
73
+ Result.Result<
74
+ ScheduleRecord,
75
+ ScheduleConflict | ScheduleCapacityError | ScheduleStorageError
76
+ >,
77
+ MemoryScheduleState,
78
+ ] => {
79
+ const key = scheduleKeyString(record)
80
+ const existingText = current.records.get(key)
81
+
82
+ if (existingText !== undefined) {
83
+ const decoded = Result.try({
84
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),
85
+ catch: () => storageError('insert', 'corrupt'),
86
+ })
87
+
88
+ if (Result.isFailure(decoded)) {
89
+ return [Result.fail(decoded.failure), current]
90
+ }
91
+ if (decoded.success.creationFingerprint === record.creationFingerprint) {
92
+ return [Result.succeed(decoded.success), current]
93
+ }
94
+
95
+ return [
96
+ Result.fail(
97
+ ScheduleConflict.make({ reason: 'creation', key: scheduleKeyOf(record) }),
98
+ ),
99
+ current,
100
+ ]
101
+ }
102
+
103
+ let ownerCount = 0
104
+
105
+ for (const text of current.records.values()) {
106
+ const decoded = Result.try({
107
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),
108
+ catch: () => storageError('insert', 'corrupt'),
109
+ })
110
+
111
+ if (Result.isFailure(decoded)) {
112
+ return [Result.fail(decoded.failure), current]
113
+ }
114
+ if (sameOwner(decoded.success, record.owner) && scheduleUsesCapacity(decoded.success)) {
115
+ ownerCount += 1
116
+ }
117
+ }
118
+ if (ownerCount >= ownerLimit) {
119
+ return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current]
120
+ }
121
+ const records = new Map(current.records)
122
+
123
+ records.set(key, encoded)
124
+ const next = { records }
125
+
126
+ return [Result.succeed(record), next]
127
+ },
128
+ ),
129
+ )
130
+
131
+ const inserted = yield* Effect.fromResult(decision)
132
+
133
+ yield* failpoint.hit('schedule:insert:after')
134
+
135
+ return yield* decodeRecord('insert', yield* encodeRecord('insert', inserted))
136
+ },
137
+ )
138
+
139
+ const get: ScheduleStore['Service']['get'] = Effect.fnUntraced(function*(key) {
140
+ const decodedKey = yield* decodeInput('get', ScheduleKey, key)
141
+ const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey))
142
+
143
+ return text === undefined ? null : yield* decodeRecord('get', text)
144
+ })
145
+
146
+ const list: ScheduleStore['Service']['list'] = Effect.fnUntraced(function*(request) {
147
+ const decodedRequest = yield* decodeInput('list', SchedulePageRequest, request)
148
+ const records: Array<ScheduleRecord> = []
149
+
150
+ for (const text of (yield* Ref.get(state)).records.values()) {
151
+ const record = yield* decodeRecord('list', text)
152
+
153
+ if (
154
+ sameOwner(record, decodedRequest.owner) &&
155
+ (decodedRequest.after === undefined ||
156
+ compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)
157
+ ) {
158
+ records.push(record)
159
+ }
160
+ }
161
+ records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId))
162
+ const hasNext = records.length > decodedRequest.limit
163
+ const items = records.slice(0, decodedRequest.limit)
164
+
165
+ return {
166
+ items,
167
+ next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,
168
+ }
169
+ })
170
+
171
+ const change: ScheduleStore['Service']['change'] = Effect.fnUntraced(function*(
172
+ key,
173
+ command,
174
+ ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,
175
+ ) {
176
+ const decodedKey = yield* decodeInput('change', ScheduleKey, key)
177
+ const decodedCommand = yield* decodeInput('change', ScheduleChange, command)
178
+
179
+ yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`)
180
+
181
+ const decision = yield* Effect.uninterruptible(
182
+ Ref.modify(
183
+ state,
184
+ (
185
+ current,
186
+ ): readonly [
187
+ Result.Result<
188
+ ScheduleRecord,
189
+ ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError
190
+ >,
191
+ MemoryScheduleState,
192
+ ] => {
193
+ const storageKey = scheduleKeyString(decodedKey)
194
+ const text = current.records.get(storageKey)
195
+
196
+ if (text === undefined) {
197
+ return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current]
198
+ }
199
+
200
+ const decoded = Result.try({
201
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),
202
+ catch: () => storageError('change', 'corrupt'),
203
+ })
204
+
205
+ if (Result.isFailure(decoded)) {
206
+ return [Result.fail(decoded.failure), current]
207
+ }
208
+ const applied = applyScheduleChange(decoded.success, decodedCommand)
209
+
210
+ if (Result.isFailure(applied)) {
211
+ return [Result.fail(applied.failure), current]
212
+ }
213
+ if (applied.success === decoded.success) {
214
+ return [Result.succeed(decoded.success), current]
215
+ }
216
+ if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {
217
+ let count = 0
218
+
219
+ for (const text of current.records.values()) {
220
+ const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(text)
221
+
222
+ if (Result.isFailure(candidate)) {
223
+ return [Result.fail(storageError('change', 'corrupt')), current]
224
+ }
225
+ if (
226
+ sameOwner(candidate.success, decodedKey.owner) &&
227
+ scheduleUsesCapacity(candidate.success)
228
+ ) {
229
+ count += 1
230
+ }
231
+ }
232
+ if (count >= ownerLimit) {
233
+ return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current]
234
+ }
235
+ }
236
+
237
+ const encoded = Result.try({
238
+ try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),
239
+ catch: () => storageError('change', 'corrupt'),
240
+ })
241
+
242
+ if (Result.isFailure(encoded)) {
243
+ return [Result.fail(encoded.failure), current]
244
+ }
245
+ const records = new Map(current.records)
246
+
247
+ records.set(storageKey, encoded.success)
248
+ const next = { records }
249
+
250
+ return [Result.succeed(applied.success), next]
251
+ },
252
+ ),
253
+ )
254
+
255
+ const changed = yield* Effect.fromResult(decision)
256
+
257
+ yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`)
258
+
259
+ return yield* decodeRecord('change', yield* encodeRecord('change', changed))
260
+ })
261
+
262
+ const due: ScheduleStore['Service']['due'] = Effect.fnUntraced(
263
+ function*(nowMillis, limit, owner, after) {
264
+ const decodedOwner = owner === undefined ? undefined : yield* decodeInput('due', ScheduleOwner, owner)
265
+
266
+ const cursor = after === undefined ? undefined : yield* decodeInput('due', ScheduleDueCursor, after)
267
+
268
+ const records: Array<ScheduleDueCursor> = []
269
+
270
+ for (const text of (yield* Ref.get(state)).records.values()) {
271
+ const record = yield* decodeRecord('due', text)
272
+ const deadline = scheduleDeadline(record)
273
+
274
+ if (
275
+ deadline !== null &&
276
+ deadline <= nowMillis &&
277
+ (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&
278
+ (cursor === undefined ||
279
+ deadline > cursor.deadlineAtMillis ||
280
+ (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))
281
+ ) {
282
+ records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline })
283
+ }
284
+ }
285
+ records.sort((left, right) => {
286
+ const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis
287
+
288
+ return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right)
289
+ })
290
+
291
+ return records.slice(0, limit)
292
+ },
293
+ )
294
+
295
+ const nextDeadline: ScheduleStore['Service']['nextDeadline'] = Effect.fnUntraced(
296
+ function*(owner) {
297
+ const decodedOwner = owner === undefined ? undefined : yield* decodeInput('nextDeadline', ScheduleOwner, owner)
298
+
299
+ let earliest: number | null = null
300
+
301
+ for (const text of (yield* Ref.get(state)).records.values()) {
302
+ const record = yield* decodeRecord('nextDeadline', text)
303
+
304
+ if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue
305
+ const deadline = scheduleDeadline(record)
306
+
307
+ if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline
308
+ }
309
+
310
+ return earliest
311
+ },
312
+ )
313
+
314
+ return ScheduleStore.of({ insert, get, list, change, due, nextDeadline })
315
+ })
316
+
317
+ export const memoryScheduleStoreLayer: Layer.Layer<ScheduleStore> = Layer.fresh(
318
+ Layer.effect(ScheduleStore, makeScheduleStore),
319
+ )
320
+
321
+ export const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore> = Layer.effect(
322
+ ScheduleStore,
323
+ makeScheduleStore,
324
+ )
@@ -0,0 +1,360 @@
1
+ import { MemoryKey } from '@systemfsoftware/agent/memory-store'
2
+ import {
3
+ MemoryIndexCandidate,
4
+ MemoryIndexError,
5
+ MemoryIndexQuery,
6
+ MemoryIndexReplacement,
7
+ MemoryIndexSearch,
8
+ MemoryIndexSource,
9
+ SemanticMemoryChunk,
10
+ SemanticMemoryIndex,
11
+ SemanticMemoryProfile,
12
+ } from '@systemfsoftware/agent/semantic-memory-index'
13
+ import * as Clock from 'effect/Clock'
14
+ import * as Effect from 'effect/Effect'
15
+ import * as Hex from 'effect/encoding/Hex'
16
+ import * as Layer from 'effect/Layer'
17
+ import * as Ref from 'effect/Ref'
18
+ import * as Schema from 'effect/Schema'
19
+
20
+ const PositiveCapacity = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_536 }))
21
+ const MaxStoredVectorComponents = 16_777_216
22
+
23
+ /**
24
+ * Hard per-Layer bounds for disposable semantic index state. maxChunks times profile dimensions
25
+ * must not exceed 16,777,216 vector components. maxSourceBytes bounds the aggregate UTF-8 JSON
26
+ * of retained source identities and defaults to 16 MiB; it is not a general heap limit.
27
+ */
28
+ export class InMemorySemanticIndexCapacity extends Schema.Class<InMemorySemanticIndexCapacity>(
29
+ '@effect-agent/storage-memory/InMemorySemanticIndexCapacity',
30
+ )({
31
+ maxSources: PositiveCapacity,
32
+ maxChunks: PositiveCapacity,
33
+ maxSourceBytes: Schema.optionalKey(
34
+ Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 67_108_864 })),
35
+ ),
36
+ }) {}
37
+
38
+ type StoredEntry =
39
+ & {
40
+ readonly source: MemoryIndexSource
41
+ readonly sourceBytes: number
42
+ }
43
+ & (
44
+ | {
45
+ readonly _tag: 'Indexed'
46
+ readonly chunks: ReadonlyArray<SemanticMemoryChunk>
47
+ readonly indexedAt: number
48
+ }
49
+ | { readonly _tag: 'Withdrawn' }
50
+ )
51
+
52
+ interface IndexData {
53
+ readonly closed: boolean
54
+ readonly entries: ReadonlyMap<string, StoredEntry>
55
+ readonly sourceBytes: number
56
+ }
57
+
58
+ const sameProfile = Schema.toEquivalence(SemanticMemoryProfile)
59
+ const sameSource = Schema.toEquivalence(MemoryIndexSource.Wire)
60
+
61
+ const error = (operation: string, reason: MemoryIndexError['reason']): MemoryIndexError =>
62
+ MemoryIndexError.make({ operation, reason })
63
+
64
+ const keyString = (key: MemoryKey): string => JSON.stringify([key.namespace.address, key.id])
65
+
66
+ const sourceIdentityBytes = (source: MemoryIndexSource): number => Hex.encode(JSON.stringify(source)).length / 2
67
+
68
+ const decodeBoundary = <A, I>(
69
+ schema: Schema.Codec<A, I, never>,
70
+ value: unknown,
71
+ operation: string,
72
+ ): Effect.Effect<A, MemoryIndexError> =>
73
+ Schema.decodeUnknownEffect(schema)(value).pipe(
74
+ Effect.flatMap((decoded) => Schema.encodeEffect(schema)(decoded).pipe(Effect.as(decoded))),
75
+ Effect.mapError(() => error(operation, 'invalid-input')),
76
+ )
77
+
78
+ const freezeSource = (source: MemoryIndexSource): MemoryIndexSource =>
79
+ Object.freeze(
80
+ MemoryIndexSource.make({
81
+ key: Object.freeze(
82
+ MemoryKey.make({
83
+ ...source.key,
84
+ namespace: Object.freeze({ address: source.key.namespace.address }),
85
+ }),
86
+ ),
87
+ source: Object.freeze({ ...source.source }),
88
+ sourceGeneration: source.sourceGeneration,
89
+ }),
90
+ )
91
+
92
+ const freezeChunk = (chunk: SemanticMemoryChunk): SemanticMemoryChunk =>
93
+ Object.freeze(SemanticMemoryChunk.make({ ...chunk, vector: Object.freeze([...chunk.vector]) }))
94
+
95
+ const sourceIsFenced = (source: MemoryIndexSource, existing: StoredEntry): boolean =>
96
+ source.sourceGeneration < existing.source.sourceGeneration ||
97
+ (source.sourceGeneration === existing.source.sourceGeneration &&
98
+ !sameSource(source, existing.source))
99
+
100
+ const squaredNorm = (vector: ReadonlyArray<number>): number | null => {
101
+ let sum = 0
102
+
103
+ for (const value of vector) {
104
+ sum += value * value
105
+ if (!Number.isFinite(sum)) return null
106
+ }
107
+
108
+ return sum > 0 ? sum : null
109
+ }
110
+
111
+ const validVector = (vector: ReadonlyArray<number>, profile: SemanticMemoryProfile): boolean =>
112
+ vector.length === profile.dimensions && squaredNorm(vector) !== null
113
+
114
+ const validateChunks = Effect.fnUntraced(function*(
115
+ chunks: ReadonlyArray<SemanticMemoryChunk>,
116
+ profile: SemanticMemoryProfile,
117
+ operation: string,
118
+ ): Effect.fn.Return<void, MemoryIndexError> {
119
+ let nextByte = 0
120
+ const passageIds = new Set<string>()
121
+
122
+ for (let index = 0; index < chunks.length; index++) {
123
+ const chunk = chunks[index]
124
+ const byteLength = Hex.encode(chunk.text).length / 2
125
+
126
+ if (
127
+ chunk.ordinal !== index ||
128
+ chunk.startByte !== nextByte ||
129
+ chunk.endByte <= chunk.startByte ||
130
+ chunk.endByte - chunk.startByte !== byteLength ||
131
+ byteLength > profile.maxChunkBytes ||
132
+ passageIds.has(chunk.passageId) ||
133
+ !validVector(chunk.vector, profile)
134
+ ) {
135
+ return yield* error(operation, 'invalid-input')
136
+ }
137
+ passageIds.add(chunk.passageId)
138
+ nextByte = chunk.endByte
139
+ }
140
+ })
141
+
142
+ const cosine = (left: ReadonlyArray<number>, right: ReadonlyArray<number>): number => {
143
+ const leftNorm = Math.sqrt(squaredNorm(left) ?? 1)
144
+ const rightNorm = Math.sqrt(squaredNorm(right) ?? 1)
145
+ let score = 0
146
+
147
+ for (let index = 0; index < left.length; index++) {
148
+ score += (left[index] / leftNorm) * (right[index] / rightNorm)
149
+ }
150
+ const bounded = Math.max(-1, Math.min(1, score))
151
+
152
+ return bounded === 0 ? 0 : bounded
153
+ }
154
+
155
+ const compareText = (left: string, right: string): number => left < right ? -1 : left > right ? 1 : 0
156
+
157
+ const makeIndex = Effect.fnUntraced(function*(
158
+ rawProfile: SemanticMemoryProfile,
159
+ rawCapacity: InMemorySemanticIndexCapacity,
160
+ ) {
161
+ const profile = Object.freeze(
162
+ SemanticMemoryProfile.make({
163
+ ...(yield* decodeBoundary(
164
+ SemanticMemoryProfile,
165
+ rawProfile,
166
+ 'configure semantic memory index',
167
+ )),
168
+ }),
169
+ )
170
+
171
+ const capacity = yield* decodeBoundary(
172
+ InMemorySemanticIndexCapacity,
173
+ rawCapacity,
174
+ 'configure semantic memory index',
175
+ )
176
+
177
+ if (capacity.maxChunks * profile.dimensions > MaxStoredVectorComponents) {
178
+ return yield* error('configure semantic memory index', 'invalid-input')
179
+ }
180
+ const maxSourceBytes = capacity.maxSourceBytes ?? 16_777_216
181
+ const data = yield* Ref.make<IndexData>({ closed: false, entries: new Map(), sourceBytes: 0 })
182
+
183
+ yield* Effect.addFinalizer(() => Ref.set(data, { closed: true, entries: new Map(), sourceBytes: 0 }))
184
+
185
+ const ensureOpen = Effect.fnUntraced(function*(operation: string) {
186
+ if ((yield* Ref.get(data)).closed) return yield* error(operation, 'unavailable')
187
+ })
188
+
189
+ const replace: SemanticMemoryIndex['Service']['replace'] = Effect.fnUntraced(
190
+ function*(rawRequest) {
191
+ const operation = 'replace semantic memory source'
192
+
193
+ yield* ensureOpen(operation)
194
+ const request = yield* decodeBoundary(MemoryIndexReplacement.Wire, rawRequest, operation)
195
+ const source = freezeSource(request.source)
196
+ const sourceBytes = sourceIdentityBytes(source)
197
+ const chunks = Object.freeze(request.chunks.map(freezeChunk))
198
+
199
+ if (source.source.id !== source.key.id) return yield* error(operation, 'invalid-input')
200
+ if (!sameProfile(request.profile, profile)) return yield* error(operation, 'incompatible')
201
+ yield* validateChunks(chunks, profile, operation)
202
+ const indexedAt = yield* Clock.currentTimeMillis
203
+
204
+ const failure = yield* Ref.modify(
205
+ data,
206
+ (current): readonly [MemoryIndexError | undefined, IndexData] => {
207
+ if (current.closed) return [error(operation, 'unavailable'), current]
208
+ const id = keyString(source.key)
209
+ const existing = current.entries.get(id)
210
+
211
+ if (
212
+ existing !== undefined &&
213
+ (existing._tag === 'Withdrawn' || sourceIsFenced(source, existing))
214
+ ) {
215
+ return [error(operation, 'fenced'), current]
216
+ }
217
+ if (existing === undefined && current.entries.size >= capacity.maxSources) {
218
+ return [error(operation, 'budget'), current]
219
+ }
220
+ const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes
221
+
222
+ if (nextSourceBytes > maxSourceBytes) return [error(operation, 'budget'), current]
223
+ let count = chunks.length
224
+
225
+ for (const [entryId, entry] of current.entries) {
226
+ if (entryId !== id && entry._tag === 'Indexed') count += entry.chunks.length
227
+ }
228
+ if (count > capacity.maxChunks) return [error(operation, 'budget'), current]
229
+ const entries = new Map(current.entries)
230
+
231
+ entries.set(id, { _tag: 'Indexed', source, sourceBytes, chunks, indexedAt })
232
+
233
+ return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }]
234
+ },
235
+ )
236
+
237
+ if (failure !== undefined) return yield* failure
238
+ },
239
+ )
240
+
241
+ const withdraw: SemanticMemoryIndex['Service']['withdraw'] = Effect.fnUntraced(
242
+ function*(rawSource) {
243
+ const operation = 'withdraw semantic memory source'
244
+
245
+ yield* ensureOpen(operation)
246
+
247
+ const source = freezeSource(
248
+ yield* decodeBoundary(MemoryIndexSource.Wire, rawSource, operation),
249
+ )
250
+
251
+ const sourceBytes = sourceIdentityBytes(source)
252
+
253
+ if (source.source.id !== source.key.id) return yield* error(operation, 'invalid-input')
254
+
255
+ const failure = yield* Ref.modify(
256
+ data,
257
+ (current): readonly [MemoryIndexError | undefined, IndexData] => {
258
+ if (current.closed) return [error(operation, 'unavailable'), current]
259
+ const id = keyString(source.key)
260
+ const existing = current.entries.get(id)
261
+
262
+ if (existing !== undefined) {
263
+ if (existing._tag === 'Withdrawn') {
264
+ return [
265
+ sameSource(source, existing.source) ? undefined : error(operation, 'fenced'),
266
+ current,
267
+ ]
268
+ }
269
+ if (sourceIsFenced(source, existing)) return [error(operation, 'fenced'), current]
270
+ } else if (current.entries.size >= capacity.maxSources) {
271
+ return [error(operation, 'budget'), current]
272
+ }
273
+ const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes
274
+
275
+ if (nextSourceBytes > maxSourceBytes) return [error(operation, 'budget'), current]
276
+ const entries = new Map(current.entries)
277
+
278
+ entries.set(id, { _tag: 'Withdrawn', source, sourceBytes })
279
+
280
+ return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }]
281
+ },
282
+ )
283
+
284
+ if (failure !== undefined) return yield* failure
285
+ },
286
+ )
287
+
288
+ const search = Effect.fnUntraced(function*(rawQuery: MemoryIndexQuery) {
289
+ const operation = 'search semantic memory index'
290
+
291
+ yield* ensureOpen(operation)
292
+ const query = yield* decodeBoundary(MemoryIndexQuery.Wire, rawQuery, operation)
293
+ const vector = Object.freeze([...query.vector])
294
+
295
+ if (!validVector(vector, profile)) return yield* error(operation, 'invalid-input')
296
+ const current = yield* Ref.get(data)
297
+
298
+ if (current.closed) return yield* error(operation, 'unavailable')
299
+ let scannedChunks = 0
300
+ let inspectedSources = 0
301
+ const candidates: Array<MemoryIndexCandidate> = []
302
+
303
+ for (const entry of current.entries.values()) {
304
+ inspectedSources += 1
305
+ if (inspectedSources % 128 === 0) yield* Effect.yieldNow
306
+ if (
307
+ entry.source.key.namespace.address !== query.namespace.address ||
308
+ entry._tag !== 'Indexed'
309
+ ) {
310
+ continue
311
+ }
312
+ scannedChunks += entry.chunks.length
313
+ if (scannedChunks > query.maxScannedChunks) return yield* error(operation, 'budget')
314
+ }
315
+ for (const entry of current.entries.values()) {
316
+ if (
317
+ entry.source.key.namespace.address !== query.namespace.address ||
318
+ entry._tag !== 'Indexed'
319
+ ) {
320
+ continue
321
+ }
322
+ yield* Effect.yieldNow
323
+ for (const chunk of entry.chunks) {
324
+ const score = cosine(vector, chunk.vector)
325
+
326
+ if (score < query.minScore) continue
327
+ candidates.push(
328
+ MemoryIndexCandidate.make({
329
+ ...entry.source,
330
+ passageId: chunk.passageId,
331
+ ordinal: chunk.ordinal,
332
+ startByte: chunk.startByte,
333
+ endByte: chunk.endByte,
334
+ text: chunk.text,
335
+ score,
336
+ indexedAt: entry.indexedAt,
337
+ }),
338
+ )
339
+ }
340
+ }
341
+ candidates.sort(
342
+ (left, right) =>
343
+ right.score - left.score ||
344
+ compareText(left.key.id, right.key.id) ||
345
+ compareText(left.source.revision, right.source.revision) ||
346
+ left.ordinal - right.ordinal,
347
+ )
348
+ yield* ensureOpen(operation)
349
+
350
+ return MemoryIndexSearch.make({ candidates: candidates.slice(0, query.limit), scannedChunks })
351
+ })
352
+
353
+ return SemanticMemoryIndex.fromAdapter({ profile, replace, withdraw, search })
354
+ })
355
+
356
+ /** Scoped disposable semantic index. No persistent build or recovery state is retained. */
357
+ export const inMemorySemanticIndexLayer = (
358
+ profile: SemanticMemoryProfile,
359
+ capacity: InMemorySemanticIndexCapacity,
360
+ ): Layer.Layer<SemanticMemoryIndex, MemoryIndexError> => Layer.effect(SemanticMemoryIndex, makeIndex(profile, capacity))