@effect-agent/storage-memory 0.1.0-beta.12 → 0.1.0-beta.120

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