@stigmer/runner 3.12.8 → 3.12.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.build-fingerprint +1 -1
- package/dist/activities/execute-cursor/fetch-interceptor.js +29 -16
- package/dist/activities/execute-cursor/fetch-interceptor.js.map +1 -1
- package/dist/activities/execute-cursor/index.d.ts +14 -0
- package/dist/activities/execute-cursor/index.js +55 -5
- package/dist/activities/execute-cursor/index.js.map +1 -1
- package/dist/activities/execute-cursor/message-translator.d.ts +15 -9
- package/dist/activities/execute-cursor/message-translator.js +15 -9
- package/dist/activities/execute-cursor/message-translator.js.map +1 -1
- package/dist/activities/execute-deep-agent/index.js +9 -0
- package/dist/activities/execute-deep-agent/index.js.map +1 -1
- package/dist/activities/execute-deep-agent/setup.d.ts +10 -1
- package/dist/activities/execute-deep-agent/setup.js +20 -3
- package/dist/activities/execute-deep-agent/setup.js.map +1 -1
- package/dist/payload-codecs.d.ts +1 -1
- package/dist/payload-codecs.js +6 -4
- package/dist/payload-codecs.js.map +1 -1
- package/dist/shared/memory-retrieval.d.ts +126 -0
- package/dist/shared/memory-retrieval.js +293 -0
- package/dist/shared/memory-retrieval.js.map +1 -0
- package/dist/shared/runner-credential-keys.js +2 -1
- package/dist/shared/runner-credential-keys.js.map +1 -1
- package/package.json +3 -2
- package/src/__tests__/history-encryption-e2e.test.ts +1 -1
- package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +40 -1
- package/src/activities/execute-cursor/__tests__/fetch-interceptor.test.ts +49 -15
- package/src/activities/execute-cursor/fetch-interceptor.ts +37 -16
- package/src/activities/execute-cursor/index.ts +58 -5
- package/src/activities/execute-cursor/message-translator.ts +15 -9
- package/src/activities/execute-deep-agent/index.ts +10 -0
- package/src/activities/execute-deep-agent/setup.ts +34 -6
- package/src/payload-codecs.ts +12 -9
- package/src/shared/__tests__/memory-retrieval.test.ts +310 -0
- package/src/shared/memory-retrieval.ts +383 -0
- package/src/shared/runner-credential-keys.ts +2 -1
- package/dist/claimcheck/compressor.d.ts +0 -2
- package/dist/claimcheck/compressor.js +0 -8
- package/dist/claimcheck/compressor.js.map +0 -1
- package/dist/claimcheck/config.d.ts +0 -7
- package/dist/claimcheck/config.js +0 -10
- package/dist/claimcheck/config.js.map +0 -1
- package/dist/claimcheck/index.d.ts +0 -3
- package/dist/claimcheck/index.js +0 -4
- package/dist/claimcheck/index.js.map +0 -1
- package/dist/claimcheck/payload-codec.d.ts +0 -23
- package/dist/claimcheck/payload-codec.js +0 -105
- package/dist/claimcheck/payload-codec.js.map +0 -1
- package/dist/encryption/config.d.ts +0 -64
- package/dist/encryption/config.js +0 -113
- package/dist/encryption/config.js.map +0 -1
- package/dist/encryption/index.d.ts +0 -3
- package/dist/encryption/index.js +0 -3
- package/dist/encryption/index.js.map +0 -1
- package/dist/encryption/payload-codec.d.ts +0 -41
- package/dist/encryption/payload-codec.js +0 -130
- package/dist/encryption/payload-codec.js.map +0 -1
- package/src/__tests__/claimcheck-codec.test.ts +0 -256
- package/src/__tests__/encryption-codec.test.ts +0 -287
- package/src/__tests__/fixtures/encrypted-payload-fixture.json +0 -15
- package/src/claimcheck/compressor.ts +0 -9
- package/src/claimcheck/config.ts +0 -20
- package/src/claimcheck/index.ts +0 -3
- package/src/claimcheck/payload-codec.ts +0 -139
- package/src/encryption/config.ts +0 -161
- package/src/encryption/index.ts +0 -3
- package/src/encryption/payload-codec.ts +0 -152
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for the memory-retrieval module (stigmer/stigmer#293 Phase 3a,
|
|
3
|
+
* DD-008). What is pinned here, path by path:
|
|
4
|
+
*
|
|
5
|
+
* - The activation threshold: selection runs ONLY above RETRIEVAL_K
|
|
6
|
+
* candidates; at or below it there is NO embeddings call (most users
|
|
7
|
+
* never touch the embeddings API — the DD-008 D3 activation contract).
|
|
8
|
+
* - Top-k correctness and the presentation contract: selection is by
|
|
9
|
+
* relevance, presentation is snapshot order, ties break toward the
|
|
10
|
+
* lower snapshot index (deterministic across invocations).
|
|
11
|
+
* - The failure posture: every degraded path — no embedder, embed error,
|
|
12
|
+
* malformed response — injects wholesale with an honest
|
|
13
|
+
* selection_active=false report, never a throw into prompt build.
|
|
14
|
+
* - The written-once replay: a prior report (either polarity) replays
|
|
15
|
+
* without an embeddings call, so a re-invocation can never inject a
|
|
16
|
+
* different subset than the first invocation did.
|
|
17
|
+
* - The report contract: a report exists exactly when facts are injected;
|
|
18
|
+
* no injection, no report (absent report = wholesale by construction).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
22
|
+
import { create } from "@bufbuild/protobuf";
|
|
23
|
+
import { RecalledMemoriesSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/spec_pb";
|
|
24
|
+
import { RecalledMemoriesReportSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
selectRecalledFacts,
|
|
28
|
+
RETRIEVAL_K,
|
|
29
|
+
EMBEDDING_MODEL,
|
|
30
|
+
QUERY_MAX_CHARS,
|
|
31
|
+
type EmbedFn,
|
|
32
|
+
} from "../memory-retrieval.js";
|
|
33
|
+
|
|
34
|
+
const QUERY = "How should I deploy the payments service?";
|
|
35
|
+
|
|
36
|
+
/** Snapshot of `count` facts: mem_0..mem_{count-1}, "fact 0".."fact N". */
|
|
37
|
+
function snapshot(count: number) {
|
|
38
|
+
return create(RecalledMemoriesSchema, {
|
|
39
|
+
enabled: true,
|
|
40
|
+
facts: Array.from({ length: count }, (_, i) => ({
|
|
41
|
+
memoryId: `mem_${i}`,
|
|
42
|
+
content: `fact ${i}`,
|
|
43
|
+
})),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A deterministic embedder over 2D unit vectors: the query embeds to
|
|
49
|
+
* [1, 0]; fact i embeds to an angle that grows with i, so relevance order
|
|
50
|
+
* is exactly snapshot order (fact 0 most similar) unless a test overrides
|
|
51
|
+
* per-input vectors.
|
|
52
|
+
*/
|
|
53
|
+
function angularEmbedder(overrides?: Map<string, number[]>): EmbedFn & {
|
|
54
|
+
calls: string[][];
|
|
55
|
+
} {
|
|
56
|
+
const calls: string[][] = [];
|
|
57
|
+
const fn: EmbedFn = async (inputs) => {
|
|
58
|
+
calls.push([...inputs]);
|
|
59
|
+
return inputs.map((input, position) => {
|
|
60
|
+
const override = overrides?.get(input);
|
|
61
|
+
if (override) return override;
|
|
62
|
+
if (position === 0) return [1, 0];
|
|
63
|
+
const angle = (position / (inputs.length + 1)) * (Math.PI / 2);
|
|
64
|
+
return [Math.cos(angle), Math.sin(angle)];
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
return Object.assign(fn, { calls });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function baseOptions(embed: EmbedFn) {
|
|
71
|
+
return {
|
|
72
|
+
proxyEndpoint: null,
|
|
73
|
+
stigmerToken: null,
|
|
74
|
+
executionId: "exec_test",
|
|
75
|
+
embed,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
afterEach(() => {
|
|
80
|
+
vi.unstubAllEnvs();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
describe("selectRecalledFacts — no injection, no report", () => {
|
|
84
|
+
it("answers nothing for an absent snapshot (pre-Phase-2 executions)", async () => {
|
|
85
|
+
const embed = angularEmbedder();
|
|
86
|
+
const result = await selectRecalledFacts(undefined, QUERY, baseOptions(embed));
|
|
87
|
+
expect(result.content).toBeUndefined();
|
|
88
|
+
expect(result.report).toBeUndefined();
|
|
89
|
+
expect(embed.calls).toHaveLength(0);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("answers nothing when recall is disabled or enabled-with-zero-facts", async () => {
|
|
93
|
+
const embed = angularEmbedder();
|
|
94
|
+
const disabled = create(RecalledMemoriesSchema, {
|
|
95
|
+
enabled: false,
|
|
96
|
+
facts: [{ memoryId: "mem_0", content: "fact 0" }],
|
|
97
|
+
});
|
|
98
|
+
expect(
|
|
99
|
+
(await selectRecalledFacts(disabled, QUERY, baseOptions(embed))).report,
|
|
100
|
+
).toBeUndefined();
|
|
101
|
+
const empty = create(RecalledMemoriesSchema, { enabled: true });
|
|
102
|
+
expect(
|
|
103
|
+
(await selectRecalledFacts(empty, QUERY, baseOptions(embed))).report,
|
|
104
|
+
).toBeUndefined();
|
|
105
|
+
expect(embed.calls).toHaveLength(0);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("selectRecalledFacts — activation threshold (DD-008 D3)", () => {
|
|
110
|
+
it("injects wholesale with NO embeddings call at exactly k candidates", async () => {
|
|
111
|
+
const embed = angularEmbedder();
|
|
112
|
+
const result = await selectRecalledFacts(
|
|
113
|
+
snapshot(RETRIEVAL_K),
|
|
114
|
+
QUERY,
|
|
115
|
+
baseOptions(embed),
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
expect(embed.calls).toHaveLength(0);
|
|
119
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K);
|
|
120
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
121
|
+
expect(result.report?.injectedMemoryIds).toEqual([]);
|
|
122
|
+
expect(result.report?.embeddingModel).toBe("");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("activates selection at k+1: one batched call, k facts injected", async () => {
|
|
126
|
+
const embed = angularEmbedder();
|
|
127
|
+
const result = await selectRecalledFacts(
|
|
128
|
+
snapshot(RETRIEVAL_K + 1),
|
|
129
|
+
QUERY,
|
|
130
|
+
baseOptions(embed),
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
expect(embed.calls).toHaveLength(1);
|
|
134
|
+
expect(embed.calls[0]).toHaveLength(RETRIEVAL_K + 2); // query + all candidates
|
|
135
|
+
expect(embed.calls[0][0]).toBe(QUERY);
|
|
136
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K);
|
|
137
|
+
expect(result.report?.selectionActive).toBe(true);
|
|
138
|
+
expect(result.report?.injectedMemoryIds).toHaveLength(RETRIEVAL_K);
|
|
139
|
+
expect(result.report?.embeddingModel).toBe(EMBEDDING_MODEL);
|
|
140
|
+
// The angular embedder makes the LAST fact least relevant.
|
|
141
|
+
expect(result.report?.injectedMemoryIds).not.toContain(`mem_${RETRIEVAL_K}`);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("counts only renderable candidates toward the threshold (blank facts dropped, the read-boundary semantics)", async () => {
|
|
145
|
+
const embed = angularEmbedder();
|
|
146
|
+
const recalled = create(RecalledMemoriesSchema, {
|
|
147
|
+
enabled: true,
|
|
148
|
+
facts: [
|
|
149
|
+
...Array.from({ length: RETRIEVAL_K }, (_, i) => ({
|
|
150
|
+
memoryId: `mem_${i}`,
|
|
151
|
+
content: `fact ${i}`,
|
|
152
|
+
})),
|
|
153
|
+
{ memoryId: "mem_blank", content: " " },
|
|
154
|
+
],
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
const result = await selectRecalledFacts(recalled, QUERY, baseOptions(embed));
|
|
158
|
+
|
|
159
|
+
expect(embed.calls).toHaveLength(0); // 20 renderable ≤ k → wholesale
|
|
160
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K);
|
|
161
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe("selectRecalledFacts — ranking and presentation", () => {
|
|
166
|
+
it("selects by relevance but presents in snapshot order, ids parallel to facts", async () => {
|
|
167
|
+
// Invert relevance: the LAST fact is the most similar, fact 0 the least.
|
|
168
|
+
const count = RETRIEVAL_K + 5;
|
|
169
|
+
const overrides = new Map<string, number[]>();
|
|
170
|
+
for (let i = 0; i < count; i++) {
|
|
171
|
+
const angle = ((count - i) / (count + 1)) * (Math.PI / 2);
|
|
172
|
+
overrides.set(`fact ${i}`, [Math.cos(angle), Math.sin(angle)]);
|
|
173
|
+
}
|
|
174
|
+
const embed = angularEmbedder(overrides);
|
|
175
|
+
|
|
176
|
+
const result = await selectRecalledFacts(
|
|
177
|
+
snapshot(count),
|
|
178
|
+
QUERY,
|
|
179
|
+
baseOptions(embed),
|
|
180
|
+
);
|
|
181
|
+
|
|
182
|
+
// The 5 least relevant under inversion are the FIRST five snapshot facts.
|
|
183
|
+
const expectedIndices = Array.from({ length: RETRIEVAL_K }, (_, i) => i + 5);
|
|
184
|
+
expect(result.content?.facts).toEqual(expectedIndices.map((i) => `fact ${i}`));
|
|
185
|
+
expect(result.report?.injectedMemoryIds).toEqual(
|
|
186
|
+
expectedIndices.map((i) => `mem_${i}`),
|
|
187
|
+
);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("breaks ties toward the lower snapshot index — equal scores never reorder across invocations", async () => {
|
|
191
|
+
// Every input embeds identically: all scores tie.
|
|
192
|
+
const count = RETRIEVAL_K + 3;
|
|
193
|
+
const overrides = new Map<string, number[]>([[QUERY, [1, 0]]]);
|
|
194
|
+
for (let i = 0; i < count; i++) {
|
|
195
|
+
overrides.set(`fact ${i}`, [1, 0]);
|
|
196
|
+
}
|
|
197
|
+
const embed = angularEmbedder(overrides);
|
|
198
|
+
|
|
199
|
+
const first = await selectRecalledFacts(snapshot(count), QUERY, baseOptions(embed));
|
|
200
|
+
const second = await selectRecalledFacts(snapshot(count), QUERY, baseOptions(embed));
|
|
201
|
+
|
|
202
|
+
const expected = Array.from({ length: RETRIEVAL_K }, (_, i) => `mem_${i}`);
|
|
203
|
+
expect(first.report?.injectedMemoryIds).toEqual(expected);
|
|
204
|
+
expect(second.report?.injectedMemoryIds).toEqual(expected);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("truncates the query at QUERY_MAX_CHARS — a giant paste must not 400 the whole batch", async () => {
|
|
208
|
+
const embed = angularEmbedder();
|
|
209
|
+
const giant = "x".repeat(QUERY_MAX_CHARS + 500);
|
|
210
|
+
|
|
211
|
+
await selectRecalledFacts(snapshot(RETRIEVAL_K + 1), giant, baseOptions(embed));
|
|
212
|
+
|
|
213
|
+
expect(embed.calls[0][0]).toHaveLength(QUERY_MAX_CHARS);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
describe("selectRecalledFacts — failure posture (never worse than Phase 2)", () => {
|
|
218
|
+
it("degrades to wholesale with an honest report when the embedder throws", async () => {
|
|
219
|
+
const embed: EmbedFn = async () => {
|
|
220
|
+
throw new Error("connect ETIMEDOUT");
|
|
221
|
+
};
|
|
222
|
+
const result = await selectRecalledFacts(
|
|
223
|
+
snapshot(RETRIEVAL_K + 1),
|
|
224
|
+
QUERY,
|
|
225
|
+
baseOptions(embed),
|
|
226
|
+
);
|
|
227
|
+
|
|
228
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K + 1);
|
|
229
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
230
|
+
expect(result.report?.injectedMemoryIds).toEqual([]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("degrades to wholesale when the embedder answers the wrong vector count", async () => {
|
|
234
|
+
const embed: EmbedFn = async () => [[1, 0]];
|
|
235
|
+
const result = await selectRecalledFacts(
|
|
236
|
+
snapshot(RETRIEVAL_K + 1),
|
|
237
|
+
QUERY,
|
|
238
|
+
baseOptions(embed),
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K + 1);
|
|
242
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("injects wholesale when no embedder resolves (no proxy, no OpenAI key — the Anthropic-only OSS posture)", async () => {
|
|
246
|
+
vi.stubEnv("OPENAI_API_KEY", "");
|
|
247
|
+
|
|
248
|
+
const result = await selectRecalledFacts(snapshot(RETRIEVAL_K + 1), QUERY, {
|
|
249
|
+
proxyEndpoint: null,
|
|
250
|
+
stigmerToken: null,
|
|
251
|
+
executionId: "exec_test",
|
|
252
|
+
// No embed injected: the module resolves — and finds — nothing.
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K + 1);
|
|
256
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
describe("selectRecalledFacts — written-once replay across re-invocations", () => {
|
|
261
|
+
it("replays a selection-active prior report without an embeddings call", async () => {
|
|
262
|
+
const embed = angularEmbedder();
|
|
263
|
+
const prior = create(RecalledMemoriesReportSchema, {
|
|
264
|
+
selectionActive: true,
|
|
265
|
+
injectedMemoryIds: ["mem_1", "mem_3"],
|
|
266
|
+
embeddingModel: EMBEDDING_MODEL,
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
const result = await selectRecalledFacts(snapshot(RETRIEVAL_K + 1), QUERY, {
|
|
270
|
+
...baseOptions(embed),
|
|
271
|
+
priorReport: prior,
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
expect(embed.calls).toHaveLength(0);
|
|
275
|
+
expect(result.content?.facts).toEqual(["fact 1", "fact 3"]);
|
|
276
|
+
expect(result.report).toBe(prior);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("replays a wholesale prior report as wholesale — a recorded embed failure is never retried into a different prompt", async () => {
|
|
280
|
+
const embed = angularEmbedder();
|
|
281
|
+
const prior = create(RecalledMemoriesReportSchema, { selectionActive: false });
|
|
282
|
+
|
|
283
|
+
const result = await selectRecalledFacts(snapshot(RETRIEVAL_K + 1), QUERY, {
|
|
284
|
+
...baseOptions(embed),
|
|
285
|
+
priorReport: prior,
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
expect(embed.calls).toHaveLength(0);
|
|
289
|
+
expect(result.content?.facts).toHaveLength(RETRIEVAL_K + 1);
|
|
290
|
+
expect(result.report?.selectionActive).toBe(false);
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it("re-selects when a recorded id does not resolve against the snapshot (structurally impossible, defended anyway)", async () => {
|
|
294
|
+
const embed = angularEmbedder();
|
|
295
|
+
const prior = create(RecalledMemoriesReportSchema, {
|
|
296
|
+
selectionActive: true,
|
|
297
|
+
injectedMemoryIds: ["mem_1", "mem_never_existed"],
|
|
298
|
+
embeddingModel: EMBEDDING_MODEL,
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
const result = await selectRecalledFacts(snapshot(RETRIEVAL_K + 1), QUERY, {
|
|
302
|
+
...baseOptions(embed),
|
|
303
|
+
priorReport: prior,
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
expect(embed.calls).toHaveLength(1);
|
|
307
|
+
expect(result.report?.selectionActive).toBe(true);
|
|
308
|
+
expect(result.report?.injectedMemoryIds).toHaveLength(RETRIEVAL_K);
|
|
309
|
+
});
|
|
310
|
+
});
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Semantic selection of recalled memories (stigmer/stigmer#293 Phase 3a,
|
|
3
|
+
* DD-008): when a subject's confirmed-fact set outgrows what wholesale
|
|
4
|
+
* injection should carry, select the most relevant facts for THIS
|
|
5
|
+
* execution instead of injecting everything.
|
|
6
|
+
*
|
|
7
|
+
* Sibling of recalled-memories.ts (which owns presentation) — this module
|
|
8
|
+
* owns SELECTION: which subset of the server-composed candidate set
|
|
9
|
+
* (`spec.recalled_memories`, the auditable snapshot both editions' compose
|
|
10
|
+
* steps stamp) actually rides the prompt. The compose steps never change;
|
|
11
|
+
* selection is a runner concern because the runner owns prompt assembly,
|
|
12
|
+
* provider credentials, and the metered proxy lane (DD-008 D1 — the
|
|
13
|
+
* titling-convergence doctrine: control-plane-adjacent LLM work runs once,
|
|
14
|
+
* in the shared runner, for both editions).
|
|
15
|
+
*
|
|
16
|
+
* Mechanism (DD-008 D2/D3): embed-on-read, no stored vectors anywhere.
|
|
17
|
+
* Selection activates ONLY above RETRIEVAL_K candidates; below that,
|
|
18
|
+
* top-k degenerates to wholesale, so no embeddings call is made and the
|
|
19
|
+
* shipped Phase 2 path runs untouched. When active: ONE batched
|
|
20
|
+
* embeddings call (query + all candidates), in-process cosine ranking,
|
|
21
|
+
* top-k by relevance, presented in snapshot order (relevance order would
|
|
22
|
+
* carry no information the model needs and would churn the prompt prefix).
|
|
23
|
+
* The query is the execution's `spec.message` — the current turn.
|
|
24
|
+
*
|
|
25
|
+
* The audit contract (DD-008 D5): the selection outcome is recorded in a
|
|
26
|
+
* runner-owned `RecalledMemoriesReport` on the execution status (the
|
|
27
|
+
* streaming_usage posture — one writer, written at prompt build). A report
|
|
28
|
+
* is returned whenever facts are injected, wholesale or selected; when
|
|
29
|
+
* nothing is injected (recall absent/disabled/empty) there is no report —
|
|
30
|
+
* absent report = wholesale, true by construction, so pre-3a executions
|
|
31
|
+
* read identically.
|
|
32
|
+
*
|
|
33
|
+
* Written-once across re-invocations: the same execution's prompt is
|
|
34
|
+
* rebuilt on approval resume (native) and fresh-agent recovery (cursor).
|
|
35
|
+
* Re-running selection there could pick a DIFFERENT subset mid-execution —
|
|
36
|
+
* so when the loaded execution already carries a report, this module
|
|
37
|
+
* REPLAYS it (selected ids resolved against the snapshot, or wholesale
|
|
38
|
+
* for a selection_active=false report) instead of re-embedding. Selection
|
|
39
|
+
* is computed at most once per execution, by construction.
|
|
40
|
+
*
|
|
41
|
+
* Failure posture: selection is an optimization. ANY failure — no
|
|
42
|
+
* embedder, HTTP error, timeout, malformed response — degrades to
|
|
43
|
+
* wholesale injection with a selection_active=false report, never a
|
|
44
|
+
* failed or degraded execution (DD-008 D3). Deployments with no
|
|
45
|
+
* embeddings-capable credential (Anthropic-only, Cursor-only OSS) run
|
|
46
|
+
* Phase 2 behavior unchanged, forever.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
import { create } from "@bufbuild/protobuf";
|
|
50
|
+
import type { RecalledMemories } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/spec_pb";
|
|
51
|
+
import {
|
|
52
|
+
RecalledMemoriesReportSchema,
|
|
53
|
+
type RecalledMemoriesReport,
|
|
54
|
+
} from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
|
|
55
|
+
import type { RecalledMemoriesContent } from "./recalled-memories.js";
|
|
56
|
+
import { resolveProxyBaseUrl, buildProxyHeaders } from "./llm-proxy.js";
|
|
57
|
+
import { checkDirectCredentials } from "./llm-backend.js";
|
|
58
|
+
import { getRunnerSecret } from "./runner-credential-store.js";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Selection activates only when the candidate set EXCEEDS this many facts;
|
|
62
|
+
* at or below it, top-k degenerates to wholesale and no embeddings call is
|
|
63
|
+
* made. 20 is comfortably above the dozens-scale where wholesale is fine
|
|
64
|
+
* (activation is rare) and comfortably below the 100-record cap (activation
|
|
65
|
+
* is meaningful): at 500-char facts, 20 facts ≈ 10KB of prompt. One
|
|
66
|
+
* constant, one place, deliberately not adaptive or per-org configurable
|
|
67
|
+
* in v1 (DD-008 D3).
|
|
68
|
+
*/
|
|
69
|
+
export const RETRIEVAL_K = 20;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The v1 embedder (DD-008 D4). OpenAI-only: resolved through the Stigmer
|
|
73
|
+
* proxy when one is configured (cloud — platform key, metered), else the
|
|
74
|
+
* operator's direct OpenAI key (OSS). NOTE: llm-proxy's `inferProvider`
|
|
75
|
+
* does not know the `text-*` prefix — this module never infers; the
|
|
76
|
+
* provider is fixed alongside the model.
|
|
77
|
+
*/
|
|
78
|
+
export const EMBEDDING_MODEL = "text-embedding-3-small";
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Upper bound on the query text sent to the embedder. Facts are write-time
|
|
82
|
+
* capped at 500 chars, but the query is `spec.message` — unbounded. A giant
|
|
83
|
+
* pasted message would blow the embedder's per-input token limit (8192 for
|
|
84
|
+
* text-embedding-3-small) and 400 the WHOLE batched call, silently forcing
|
|
85
|
+
* wholesale on exactly the executions where selection matters. 20K chars
|
|
86
|
+
* sits safely under the limit at worst-case chars-per-token; selection
|
|
87
|
+
* intent is dominated by the message head, and a truncated query beats no
|
|
88
|
+
* selection.
|
|
89
|
+
*/
|
|
90
|
+
export const QUERY_MAX_CHARS = 20_000;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Bound on the single embeddings round trip. Generous relative to the
|
|
94
|
+
* observed 200–400ms typical latency: this exists to keep a hung
|
|
95
|
+
* connection from stalling prompt build, not to race the provider.
|
|
96
|
+
*/
|
|
97
|
+
const EMBED_TIMEOUT_MS = 15_000;
|
|
98
|
+
|
|
99
|
+
/** The OpenAI SDK-default base, used only in direct (unproxied) mode. */
|
|
100
|
+
const DIRECT_OPENAI_BASE_URL = "https://api.openai.com/v1";
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* One batched embeddings call: one vector per input, in input order.
|
|
104
|
+
* The seam unit tests inject through, and the boundary a stored-vector
|
|
105
|
+
* optimization would slot behind if caps ever grow (DD-008 D2).
|
|
106
|
+
*/
|
|
107
|
+
export type EmbedFn = (inputs: readonly string[]) => Promise<number[][]>;
|
|
108
|
+
|
|
109
|
+
export interface MemoryRetrievalOptions {
|
|
110
|
+
/** Null/undefined when the deployment has no proxy (direct mode). */
|
|
111
|
+
readonly proxyEndpoint: string | null | undefined;
|
|
112
|
+
/** Bearer for proxy mode; unused in direct mode. */
|
|
113
|
+
readonly stigmerToken: string | null | undefined;
|
|
114
|
+
/** Scopes the proxied call for FGA authorization and billing attribution. */
|
|
115
|
+
readonly executionId: string;
|
|
116
|
+
/**
|
|
117
|
+
* The report a PREVIOUS invocation of this same execution recorded, if
|
|
118
|
+
* any (`execution.status.recalled_memories_report`). Presence replays
|
|
119
|
+
* the recorded outcome instead of re-selecting — the written-once rule.
|
|
120
|
+
*/
|
|
121
|
+
readonly priorReport?: RecalledMemoriesReport;
|
|
122
|
+
/** Test seam; defaults to the proxy/direct embedder resolution. */
|
|
123
|
+
readonly embed?: EmbedFn;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface MemorySelectionResult {
|
|
127
|
+
/**
|
|
128
|
+
* The facts to inject, in snapshot order — undefined when recall is
|
|
129
|
+
* absent, disabled, or empty (render nothing, exactly the
|
|
130
|
+
* readRecalledMemories contract).
|
|
131
|
+
*/
|
|
132
|
+
readonly content: RecalledMemoriesContent | undefined;
|
|
133
|
+
/**
|
|
134
|
+
* The injection outcome to stamp on the execution status. Undefined
|
|
135
|
+
* exactly when `content` is undefined: no injection, no report.
|
|
136
|
+
*/
|
|
137
|
+
readonly report: RecalledMemoriesReport | undefined;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** A candidate fact: the snapshot entry with its audit identity intact. */
|
|
141
|
+
interface Candidate {
|
|
142
|
+
readonly memoryId: string;
|
|
143
|
+
readonly content: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Select the facts to inject for one execution.
|
|
148
|
+
*
|
|
149
|
+
* This is the ONE entry point both harnesses call at prompt build, replacing
|
|
150
|
+
* their direct `readRecalledMemories` reads on the injection path (the read
|
|
151
|
+
* function remains the presentation-side authority; this module reads the
|
|
152
|
+
* proto itself because selection needs `memory_id`, which the render
|
|
153
|
+
* boundary deliberately strips).
|
|
154
|
+
*
|
|
155
|
+
* Never throws: every failure path returns wholesale.
|
|
156
|
+
*/
|
|
157
|
+
export async function selectRecalledFacts(
|
|
158
|
+
recalled: RecalledMemories | undefined,
|
|
159
|
+
queryText: string,
|
|
160
|
+
options: MemoryRetrievalOptions,
|
|
161
|
+
): Promise<MemorySelectionResult> {
|
|
162
|
+
const candidates = readCandidates(recalled);
|
|
163
|
+
if (candidates.length === 0) {
|
|
164
|
+
return { content: undefined, report: undefined };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Written-once: a prior invocation of this execution already decided.
|
|
168
|
+
if (options.priorReport !== undefined) {
|
|
169
|
+
const replayed = replayReport(candidates, options.priorReport);
|
|
170
|
+
if (replayed !== undefined) {
|
|
171
|
+
return replayed;
|
|
172
|
+
}
|
|
173
|
+
// Unreplayable (recorded ids missing from the immutable snapshot —
|
|
174
|
+
// structurally impossible, defended anyway): fall through and select
|
|
175
|
+
// fresh rather than inject nothing.
|
|
176
|
+
log(
|
|
177
|
+
`prior report for execution ${options.executionId} did not resolve ` +
|
|
178
|
+
`against the snapshot; re-selecting`,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (candidates.length <= RETRIEVAL_K) {
|
|
183
|
+
return wholesale(candidates);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const embed = options.embed ?? resolveEmbedder(options);
|
|
187
|
+
if (embed === undefined) {
|
|
188
|
+
// No embeddings-capable credential: the recorded no-embedder posture
|
|
189
|
+
// (DD-008 D4) — Phase 2 behavior, honestly reported.
|
|
190
|
+
return wholesale(candidates);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
const query = queryText.slice(0, QUERY_MAX_CHARS);
|
|
195
|
+
const vectors = await embed([query, ...candidates.map((c) => c.content)]);
|
|
196
|
+
if (vectors.length !== candidates.length + 1) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
`embedder returned ${vectors.length} vectors for ` +
|
|
199
|
+
`${candidates.length + 1} inputs`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
const [queryVector, ...factVectors] = vectors;
|
|
203
|
+
const selected = topKBySimilarity(queryVector, factVectors, RETRIEVAL_K);
|
|
204
|
+
return {
|
|
205
|
+
content: { facts: selected.map((i) => candidates[i].content) },
|
|
206
|
+
report: create(RecalledMemoriesReportSchema, {
|
|
207
|
+
selectionActive: true,
|
|
208
|
+
injectedMemoryIds: selected.map((i) => candidates[i].memoryId),
|
|
209
|
+
embeddingModel: EMBEDDING_MODEL,
|
|
210
|
+
}),
|
|
211
|
+
};
|
|
212
|
+
} catch (err) {
|
|
213
|
+
log(
|
|
214
|
+
`selection failed for execution ${options.executionId}, degrading to ` +
|
|
215
|
+
`wholesale: ${err instanceof Error ? err.message : String(err)}`,
|
|
216
|
+
);
|
|
217
|
+
return wholesale(candidates);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The snapshot's renderable candidates, in snapshot order. Same semantics
|
|
223
|
+
* as readRecalledMemories (disabled → none; blank contents dropped
|
|
224
|
+
* defensively) but keeping `memory_id` — the report's audit link.
|
|
225
|
+
*/
|
|
226
|
+
function readCandidates(recalled: RecalledMemories | undefined): Candidate[] {
|
|
227
|
+
if (!recalled?.enabled) {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
return (recalled.facts ?? [])
|
|
231
|
+
.map((fact) => ({
|
|
232
|
+
memoryId: fact.memoryId ?? "",
|
|
233
|
+
content: fact.content?.trim() ?? "",
|
|
234
|
+
}))
|
|
235
|
+
.filter((c) => c.content !== "");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Replay a previously recorded outcome so a re-invocation injects exactly
|
|
240
|
+
* what the first invocation did. A selection_active=false report replays
|
|
241
|
+
* as wholesale (including the case where a transient embed failure was
|
|
242
|
+
* recorded — retrying could select a subset and diverge the prompt).
|
|
243
|
+
* Returns undefined when a recorded id no longer resolves.
|
|
244
|
+
*/
|
|
245
|
+
function replayReport(
|
|
246
|
+
candidates: Candidate[],
|
|
247
|
+
prior: RecalledMemoriesReport,
|
|
248
|
+
): MemorySelectionResult | undefined {
|
|
249
|
+
if (!prior.selectionActive) {
|
|
250
|
+
return wholesale(candidates);
|
|
251
|
+
}
|
|
252
|
+
const byId = new Map(candidates.map((c) => [c.memoryId, c.content]));
|
|
253
|
+
const facts: string[] = [];
|
|
254
|
+
for (const id of prior.injectedMemoryIds) {
|
|
255
|
+
const content = byId.get(id);
|
|
256
|
+
if (content === undefined) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
facts.push(content);
|
|
260
|
+
}
|
|
261
|
+
if (facts.length === 0) {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
return { content: { facts }, report: prior };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Wholesale injection of the full candidate set, honestly reported. */
|
|
268
|
+
function wholesale(candidates: Candidate[]): MemorySelectionResult {
|
|
269
|
+
return {
|
|
270
|
+
content: { facts: candidates.map((c) => c.content) },
|
|
271
|
+
report: create(RecalledMemoriesReportSchema, { selectionActive: false }),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The credential lanes, in the platform's standing precedence (the
|
|
277
|
+
* titling-lane idiom): proxy when configured — the runner authenticates
|
|
278
|
+
* with its Stigmer token and the proxy owns the provider key — else the
|
|
279
|
+
* operator's direct OpenAI key, else no embedder.
|
|
280
|
+
*/
|
|
281
|
+
function resolveEmbedder(options: MemoryRetrievalOptions): EmbedFn | undefined {
|
|
282
|
+
if (options.proxyEndpoint) {
|
|
283
|
+
return fetchEmbedder(
|
|
284
|
+
resolveProxyBaseUrl(options.proxyEndpoint, "openai"),
|
|
285
|
+
buildProxyHeaders(options.stigmerToken ?? "", {
|
|
286
|
+
executionId: options.executionId,
|
|
287
|
+
}),
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
if (checkDirectCredentials("openai") === null) {
|
|
291
|
+
return fetchEmbedder(DIRECT_OPENAI_BASE_URL, {
|
|
292
|
+
Authorization: `Bearer ${getRunnerSecret("OPENAI_API_KEY") ?? ""}`,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The real embedder: one POST {base}/embeddings. A plain typed fetch, not
|
|
300
|
+
* LangChain's OpenAIEmbeddings — the SDK wrapper discards the response
|
|
301
|
+
* `usage` block and adds nothing over a single request. Proxy-side
|
|
302
|
+
* metering reads the JSON usage from the relayed body.
|
|
303
|
+
*/
|
|
304
|
+
function fetchEmbedder(baseUrl: string, headers: Record<string, string>): EmbedFn {
|
|
305
|
+
return async (inputs) => {
|
|
306
|
+
const response = await fetch(`${baseUrl}/embeddings`, {
|
|
307
|
+
method: "POST",
|
|
308
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
309
|
+
body: JSON.stringify({ model: EMBEDDING_MODEL, input: inputs }),
|
|
310
|
+
signal: AbortSignal.timeout(EMBED_TIMEOUT_MS),
|
|
311
|
+
});
|
|
312
|
+
if (!response.ok) {
|
|
313
|
+
const body = await response.text().catch(() => "");
|
|
314
|
+
throw new Error(
|
|
315
|
+
`embeddings request failed: HTTP ${response.status} ${body.slice(0, 300)}`,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
const parsed = (await response.json()) as {
|
|
319
|
+
data?: Array<{ index?: number; embedding?: number[] }>;
|
|
320
|
+
};
|
|
321
|
+
if (!Array.isArray(parsed.data)) {
|
|
322
|
+
throw new Error("embeddings response carries no data array");
|
|
323
|
+
}
|
|
324
|
+
// Place by the response's own index field — the API documents input
|
|
325
|
+
// order, but the contract names the index as authoritative.
|
|
326
|
+
const vectors: number[][] = new Array(inputs.length);
|
|
327
|
+
for (const item of parsed.data) {
|
|
328
|
+
const index = item.index ?? -1;
|
|
329
|
+
if (index < 0 || index >= inputs.length || !Array.isArray(item.embedding)) {
|
|
330
|
+
throw new Error("embeddings response entry is malformed");
|
|
331
|
+
}
|
|
332
|
+
vectors[index] = item.embedding;
|
|
333
|
+
}
|
|
334
|
+
if (vectors.some((v) => v === undefined)) {
|
|
335
|
+
throw new Error("embeddings response is missing entries");
|
|
336
|
+
}
|
|
337
|
+
return vectors;
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Indices of the top-k facts by cosine similarity to the query, returned
|
|
343
|
+
* ASCENDING — i.e. re-sorted to snapshot order (DD-008 D3: selection is by
|
|
344
|
+
* relevance, presentation stays oldest-first). Ties break toward the lower
|
|
345
|
+
* snapshot index, so equal scores never reorder across invocations.
|
|
346
|
+
*/
|
|
347
|
+
function topKBySimilarity(
|
|
348
|
+
queryVector: number[],
|
|
349
|
+
factVectors: number[][],
|
|
350
|
+
k: number,
|
|
351
|
+
): number[] {
|
|
352
|
+
return factVectors
|
|
353
|
+
.map((vector, index) => ({ index, score: cosineSimilarity(queryVector, vector) }))
|
|
354
|
+
.sort((a, b) => b.score - a.score || a.index - b.index)
|
|
355
|
+
.slice(0, k)
|
|
356
|
+
.map((entry) => entry.index)
|
|
357
|
+
.sort((a, b) => a - b);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Plain cosine. OpenAI embeddings arrive unit-normalized (a dot product
|
|
362
|
+
* would suffice today), but normalizing here keeps ranking correct under
|
|
363
|
+
* any future embedder without a silent provider assumption.
|
|
364
|
+
*/
|
|
365
|
+
function cosineSimilarity(a: number[], b: number[]): number {
|
|
366
|
+
let dot = 0;
|
|
367
|
+
let normA = 0;
|
|
368
|
+
let normB = 0;
|
|
369
|
+
const length = Math.min(a.length, b.length);
|
|
370
|
+
for (let i = 0; i < length; i++) {
|
|
371
|
+
dot += a[i] * b[i];
|
|
372
|
+
normA += a[i] * a[i];
|
|
373
|
+
normB += b[i] * b[i];
|
|
374
|
+
}
|
|
375
|
+
if (normA === 0 || normB === 0) {
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function log(msg: string): void {
|
|
382
|
+
console.warn(`[memory-retrieval] ${msg}`);
|
|
383
|
+
}
|