@vellumai/assistant 0.10.10-dev.202607202034.986455b → 0.10.10-dev.202607202225.8cbddff

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.10-dev.202607202034.986455b",
3
+ "version": "0.10.10-dev.202607202225.8cbddff",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -32,7 +32,7 @@ function stubProvider(sendMessage: Provider["sendMessage"]): Provider {
32
32
 
33
33
  function toolResponse(
34
34
  inputBlock: Record<string, unknown>,
35
- name = "turn_decision",
35
+ name = "ack",
36
36
  ): ProviderResponse {
37
37
  return {
38
38
  content: [{ type: "tool_use", id: "tu_1", name, input: inputBlock }],
@@ -42,33 +42,48 @@ function toolResponse(
42
42
  };
43
43
  }
44
44
 
45
+ function textResponse(text: string): ProviderResponse {
46
+ return {
47
+ content: [{ type: "text", text }],
48
+ model: "stub-model",
49
+ usage: { inputTokens: 1, outputTokens: 1 },
50
+ stopReason: "end_turn",
51
+ };
52
+ }
53
+
45
54
  describe("createVoiceFrontDecider — decideEndpoint", () => {
46
- test("tool result complete:false → hold", async () => {
55
+ test('answer "0" → hold', async () => {
47
56
  const decider = createVoiceFrontDecider({
48
57
  config,
49
- getProvider: async () =>
50
- stubProvider(async () => toolResponse({ complete: false })),
58
+ getProvider: async () => stubProvider(async () => textResponse("0")),
51
59
  });
52
60
  expect(await decider.decideEndpoint(input)).toEqual({ action: "hold" });
53
61
  });
54
62
 
55
- test("tool result complete:true → release", async () => {
63
+ test('answer "1" → release', async () => {
56
64
  const decider = createVoiceFrontDecider({
57
65
  config,
58
- getProvider: async () =>
59
- stubProvider(async () => toolResponse({ complete: true })),
66
+ getProvider: async () => stubProvider(async () => textResponse("1")),
60
67
  });
61
68
  expect(await decider.decideEndpoint(input)).toEqual({ action: "release" });
62
69
  });
63
70
 
64
- test("sends transcript, forced turn_decision tool, and call-site config", async () => {
71
+ test('answer "0" with trailing delimiter → hold', async () => {
72
+ const decider = createVoiceFrontDecider({
73
+ config,
74
+ getProvider: async () => stubProvider(async () => textResponse(" 0\n")),
75
+ });
76
+ expect(await decider.decideEndpoint(input)).toEqual({ action: "hold" });
77
+ });
78
+
79
+ test("sends transcript, tight token budget, no tools, and call-site config", async () => {
65
80
  let captured: Parameters<Provider["sendMessage"]> | undefined;
66
81
  const decider = createVoiceFrontDecider({
67
82
  config,
68
83
  getProvider: async () =>
69
84
  stubProvider(async (...args) => {
70
85
  captured = args;
71
- return toolResponse({ complete: true });
86
+ return textResponse("1");
72
87
  }),
73
88
  });
74
89
  await decider.decideEndpoint({ ...input, latestPartial: "and then" });
@@ -79,12 +94,14 @@ describe("createVoiceFrontDecider — decideEndpoint", () => {
79
94
  expect(text).toContain("so what I was thinking is");
80
95
  expect(text).toContain("and then");
81
96
  expect(options?.config).toMatchObject({
82
- max_tokens: 64,
97
+ max_tokens: 4,
83
98
  callSite: "voiceFrontDecision",
84
- tool_choice: { type: "tool", name: "turn_decision" },
85
99
  disableCache: true,
86
100
  });
87
- expect(options?.tools?.map((t) => t.name)).toEqual(["turn_decision"]);
101
+ // Single-token text protocol: no tool schema in the prompt, no forced
102
+ // tool call in the output — the latency-critical path stays minimal.
103
+ expect(options?.tools).toBeUndefined();
104
+ expect(options?.config?.tool_choice).toBeUndefined();
88
105
  expect(options?.systemPrompt).toContain("finished");
89
106
  });
90
107
 
@@ -163,21 +180,28 @@ describe("createVoiceFrontDecider — decideEndpoint", () => {
163
180
  expect(Date.now() - start).toBeLessThan(1000);
164
181
  });
165
182
 
166
- test("missing/foreign tool block → release", async () => {
183
+ test("response without a text block → release", async () => {
167
184
  const decider = createVoiceFrontDecider({
168
185
  config,
169
186
  getProvider: async () =>
170
- stubProvider(async () =>
171
- toolResponse({ complete: false }, "some_other_tool"),
172
- ),
187
+ stubProvider(async () => toolResponse({ complete: false })),
173
188
  });
174
189
  expect(await decider.decideEndpoint(input)).toEqual({ action: "release" });
175
190
  });
176
191
 
177
- test("malformed tool input (complete not boolean) → release", async () => {
192
+ test("empty text answer → release", async () => {
178
193
  const decider = createVoiceFrontDecider({
179
194
  config,
180
- getProvider: async () => stubProvider(async () => toolResponse({})),
195
+ getProvider: async () => stubProvider(async () => textResponse(" ")),
196
+ });
197
+ expect(await decider.decideEndpoint(input)).toEqual({ action: "release" });
198
+ });
199
+
200
+ test("non-protocol prose answer → release (fail-open)", async () => {
201
+ const decider = createVoiceFrontDecider({
202
+ config,
203
+ getProvider: async () =>
204
+ stubProvider(async () => textResponse("The speaker seems unsure")),
181
205
  });
182
206
  expect(await decider.decideEndpoint(input)).toEqual({ action: "release" });
183
207
  });
@@ -20,14 +20,15 @@
20
20
 
21
21
  import type { LiveVoiceFrontModelConfig } from "../config/schemas/live-voice.js";
22
22
  import {
23
+ extractText,
23
24
  extractToolUse,
24
25
  getConfiguredProvider,
25
26
  userMessage,
26
27
  } from "../providers/provider-send-message.js";
27
28
  import type {
28
29
  Provider,
30
+ ProviderResponse,
29
31
  ToolDefinition,
30
- ToolUseContent,
31
32
  } from "../providers/types.js";
32
33
  import { createAbortReason } from "../util/abort-reasons.js";
33
34
  import { getLogger } from "../util/logger.js";
@@ -85,30 +86,37 @@ export interface VoiceFrontDecider {
85
86
  const RELEASE: VoiceEndpointDecision = { action: "release" };
86
87
  const HOLD: VoiceEndpointDecision = { action: "hold" };
87
88
 
88
- const TURN_DECISION_TOOL_NAME = "turn_decision";
89
+ // Single-token wire protocol: the model answers with one bare character
90
+ // instead of a forced tool call. A tool call spends 10-15 output tokens on
91
+ // name + JSON scaffolding to convey one bit; a bare digit is one token, and
92
+ // dropping the tool schema also shrinks the prompt. Only an exact leading
93
+ // "0" holds — every other output (including non-compliance) releases, so the
94
+ // fail-open contract carries the parsing risk.
95
+ const HOLD_TOKEN = "0";
89
96
 
90
- const TURN_DECISION_TOOL: ToolDefinition = {
91
- name: TURN_DECISION_TOOL_NAME,
92
- description:
93
- "Record whether the speaker's turn is complete. Call this exactly once.",
94
- input_schema: {
95
- type: "object",
96
- properties: {
97
- complete: {
98
- type: "boolean",
99
- description:
100
- "true when the speaker has finished their thought; false when they are mid-thought and more speech is likely coming.",
101
- },
102
- },
103
- required: ["complete"],
104
- },
105
- };
97
+ // Output budget for the single-character answer: one token for the digit
98
+ // plus headroom for a stray delimiter. Deliberately tiny — a model that
99
+ // starts writing prose gets cut off and the unparseable prefix releases.
100
+ const ENDPOINT_DECISION_MAX_TOKENS = 4;
106
101
 
102
+ // Tie-break is 0 (hold): a wrong hold costs one bounded extension of silence
103
+ // and self-corrects on the replay, while a wrong release cuts the speaker off
104
+ // mid-thought — the failure this feature exists to prevent. The extension
105
+ // ratchet below keeps chronic uncertainty from burning every extension. This
106
+ // is deliberately the opposite of the code-level fail-open (timeouts and
107
+ // failures still release) — that one protects turn-taking from outages.
107
108
  const SYSTEM_PROMPT =
108
- "You decide whether the speaker has finished their thought or is mid-thought/thinking. " +
109
- "You see a live-voice transcript captured up to a pause. Treat trailing conjunctions, " +
110
- "dangling prepositions, or an obviously unfinished clause as mid-thought. " +
111
- "Bias toward finished: when in doubt, mark the turn complete.";
109
+ "You classify end-of-turn for a live voice assistant from a transcript captured up " +
110
+ "to a pause. Respond with exactly one character: 0 if the speaker is mid-thought, " +
111
+ "1 if finished. Never answer or explain.\n" +
112
+ "0 when the wording signals more speech: a trailing conjunction (and, but, or, so, " +
113
+ "because), dangling preposition or article, hesitation filler (um, uh, like, let me " +
114
+ "think), unfinished list, or clause cut off before its verb or object.\n" +
115
+ "1 when the wording stands alone: a complete sentence, question, command, or short " +
116
+ "reply (yes, no, stop).\n" +
117
+ "Judge wording only, not content. Missing punctuation or casing is not mid-thought. " +
118
+ "Longer pauses and more prior extensions favor 1. When unclear, answer 0 — a brief " +
119
+ "extra pause beats cutting the speaker off.";
112
120
 
113
121
  const ACK_TOOL_NAME = "ack";
114
122
 
@@ -194,20 +202,21 @@ function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
194
202
  }
195
203
 
196
204
  /**
197
- * One bounded front-model call with a forced tool: arm the `timeoutMs` bound
198
- * first, then resolve the provider and the request both raced against it (and
199
- * the caller's signal, when given), and return the response's tool_use block.
200
- * Provider resolution can await lazy initialization, so it must sit inside
201
- * the timeout — otherwise a stalled resolver would breach the contract that
202
- * every call settles within `timeoutMs`. `undefined` when no provider is
203
- * configured or the response carries no tool block; throws on provider
204
- * failure, timeout, or abort — callers map every failure to their fail-open
205
- * value.
205
+ * One bounded front-model call: arm the `timeoutMs` bound first, then resolve
206
+ * the provider and the request both raced against it (and the caller's
207
+ * signal, when given), and return the raw response. When `tool` is given the
208
+ * call forces that tool (`tool_choice`); otherwise it is a plain text
209
+ * request. Provider resolution can await lazy initialization, so it must sit
210
+ * inside the timeout — otherwise a stalled resolver would breach the
211
+ * contract that every call settles within `timeoutMs`. `undefined` when no
212
+ * provider is configured; throws on provider failure, timeout, or abort —
213
+ * callers map every failure to their fail-open value.
206
214
  */
207
- async function requestForcedToolUse(args: {
215
+ async function requestBoundedResponse(args: {
208
216
  getProvider: () => Promise<Provider | null>;
209
217
  timeoutMs: number;
210
- tool: ToolDefinition;
218
+ maxTokens: number;
219
+ tool?: ToolDefinition;
211
220
  systemPrompt: string;
212
221
  prompt: string;
213
222
  signal?: AbortSignal;
@@ -218,7 +227,7 @@ async function requestForcedToolUse(args: {
218
227
  * roundtrip was slow" without changing this function's return contract.
219
228
  */
220
229
  onProviderResolved?: (elapsedMs: number, provider: Provider | null) => void;
221
- }): Promise<ToolUseContent | undefined> {
230
+ }): Promise<ProviderResponse | undefined> {
222
231
  // Deadline abort carries a tagged AbortReason: the provider catch-site
223
232
  // classifies untagged caller aborts as retryable transport failures, so a
224
233
  // plain-signal timeout would log an ERROR per expired budget and then be
@@ -246,19 +255,21 @@ async function requestForcedToolUse(args: {
246
255
  }
247
256
  const response = await raceAbort(
248
257
  provider.sendMessage([userMessage(args.prompt)], {
249
- tools: [args.tool],
258
+ ...(args.tool ? { tools: [args.tool] } : {}),
250
259
  systemPrompt: args.systemPrompt,
251
260
  config: {
252
- max_tokens: 64,
261
+ max_tokens: args.maxTokens,
253
262
  callSite: "voiceFrontDecision",
254
- tool_choice: { type: "tool", name: args.tool.name },
263
+ ...(args.tool
264
+ ? { tool_choice: { type: "tool", name: args.tool.name } }
265
+ : {}),
255
266
  disableCache: true,
256
267
  },
257
268
  signal: combinedSignal,
258
269
  }),
259
270
  combinedSignal,
260
271
  );
261
- return extractToolUse(response);
272
+ return response;
262
273
  } finally {
263
274
  cleanup();
264
275
  }
@@ -285,10 +296,10 @@ export function createVoiceFrontDecider(options: {
285
296
  let providerResolveMs: number | null = null;
286
297
  let providerName: string | null = null;
287
298
  try {
288
- const toolBlock = await requestForcedToolUse({
299
+ const response = await requestBoundedResponse({
289
300
  getProvider,
290
301
  timeoutMs: config.endpointDecisionTimeoutMs,
291
- tool: TURN_DECISION_TOOL,
302
+ maxTokens: ENDPOINT_DECISION_MAX_TOKENS,
292
303
  systemPrompt: SYSTEM_PROMPT,
293
304
  prompt: buildPrompt(input),
294
305
  signal,
@@ -297,19 +308,18 @@ export function createVoiceFrontDecider(options: {
297
308
  providerName = provider?.name ?? null;
298
309
  },
299
310
  });
300
- const held =
301
- toolBlock?.name === TURN_DECISION_TOOL_NAME &&
302
- (toolBlock.input as { complete?: unknown }).complete === false;
311
+ const answer = response ? extractText(response) : "";
312
+ const held = answer.startsWith(HOLD_TOKEN);
303
313
  log.info(
304
314
  {
305
315
  action: held ? "hold" : "release",
306
316
  // "model" = the LLM answered; "no-provider" = call site resolved
307
- // nothing; "no-tool-block" = provider answered without the tool.
308
- cause: toolBlock
317
+ // nothing; "no-text" = provider answered without a text block.
318
+ cause: answer
309
319
  ? "model"
310
320
  : providerName === null
311
321
  ? "no-provider"
312
- : "no-tool-block",
322
+ : "no-text",
313
323
  providerName,
314
324
  providerResolveMs,
315
325
  totalMs: Math.round(performance.now() - startedAt),
@@ -321,8 +331,8 @@ export function createVoiceFrontDecider(options: {
321
331
  if (held) {
322
332
  return HOLD;
323
333
  }
324
- // No provider, `complete: true`, a missing/foreign tool block, or a
325
- // malformed input all release — only an explicit "not finished" holds.
334
+ // No provider, "1", an empty response, or any non-protocol output
335
+ // all release — only an explicit leading "0" holds.
326
336
  return RELEASE;
327
337
  } catch (error) {
328
338
  // providerResolveMs null here means resolution itself never settled
@@ -349,9 +359,10 @@ export function createVoiceFrontDecider(options: {
349
359
  const startedAt = performance.now();
350
360
  let providerResolveMs: number | null = null;
351
361
  try {
352
- const toolBlock = await requestForcedToolUse({
362
+ const response = await requestBoundedResponse({
353
363
  getProvider,
354
364
  timeoutMs: config.ackGenerationTimeoutMs,
365
+ maxTokens: 64,
355
366
  tool: ACK_TOOL,
356
367
  systemPrompt: ACK_SYSTEM_PROMPT,
357
368
  prompt: buildAckPrompt(input),
@@ -360,6 +371,7 @@ export function createVoiceFrontDecider(options: {
360
371
  providerResolveMs = Math.round(elapsedMs);
361
372
  },
362
373
  });
374
+ const toolBlock = response ? extractToolUse(response) : undefined;
363
375
  if (toolBlock?.name !== ACK_TOOL_NAME) {
364
376
  return null;
365
377
  }
@@ -1515,6 +1515,85 @@ describe("orchestrate — injection gate", () => {
1515
1515
  ).toBeGreaterThan(0);
1516
1516
  });
1517
1517
 
1518
+ test("the recall-safe fallback (omitted ids) records selector_kept_all: true", async () => {
1519
+ const lanes = await buildLanes();
1520
+ // The model omitting `ids` keeps the whole pool — indistinguishable from an
1521
+ // explicit large selection by `selected_count` alone. This is the flag that
1522
+ // separates "gave up judging" from "judged everything relevant".
1523
+ denseHits = [{ article: "topic-b", section: 0, score: 0.9 }];
1524
+ providerStub = {
1525
+ name: "stub",
1526
+ sendMessage: async () => toolUseResponse({}), // omitted ids → keep all
1527
+ };
1528
+
1529
+ await orchestrate(
1530
+ makeTurn(1, "apple"),
1531
+ depsOf(lanes, {
1532
+ coreSlugs: ["topic-c"],
1533
+ denseK: 100,
1534
+ gateConfig: gateConfigOf(),
1535
+ }),
1536
+ );
1537
+
1538
+ expect(recordedSelectionEvents).toHaveLength(1);
1539
+ expect(recordedSelectionEvents[0]!.detail).toMatchObject({
1540
+ selector_ran: true,
1541
+ selector_kept_all: true,
1542
+ });
1543
+ });
1544
+
1545
+ test("an explicit selection records selector_kept_all: false", async () => {
1546
+ const lanes = await buildLanes();
1547
+ denseHits = [{ article: "topic-b", section: 0, score: 0.9 }];
1548
+ providerStub = selectProvider(["topic-a"]);
1549
+
1550
+ await orchestrate(
1551
+ makeTurn(1, "apple"),
1552
+ depsOf(lanes, { denseK: 100, gateConfig: gateConfigOf() }),
1553
+ );
1554
+
1555
+ expect(recordedSelectionEvents[0]!.detail).toMatchObject({
1556
+ selector_kept_all: false,
1557
+ });
1558
+ });
1559
+
1560
+ test("net_new_count counts only selections not already live in the conversation", async () => {
1561
+ const lanes = await buildLanes();
1562
+ denseHits = [{ article: "topic-b", section: 0, score: 0.9 }];
1563
+ // Selector picks topic-a and topic-b; topic-a is already resident, so only
1564
+ // topic-b is a net-new injection this turn.
1565
+ providerStub = selectProvider(["topic-a", "topic-b"]);
1566
+
1567
+ await orchestrate(
1568
+ makeTurn(1, "apple"),
1569
+ depsOf(lanes, {
1570
+ denseK: 100,
1571
+ activeSlugs: new Set<Slug>(["topic-a"]),
1572
+ gateConfig: gateConfigOf(),
1573
+ }),
1574
+ );
1575
+
1576
+ expect(recordedSelectionEvents[0]!.detail).toMatchObject({
1577
+ selected_count: 2,
1578
+ net_new_count: 1,
1579
+ });
1580
+ });
1581
+
1582
+ test("net_new_count is omitted when activeSlugs is not threaded", async () => {
1583
+ const lanes = await buildLanes();
1584
+ denseHits = [{ article: "topic-b", section: 0, score: 0.9 }];
1585
+ providerStub = selectProvider(["topic-a"]);
1586
+
1587
+ await orchestrate(
1588
+ makeTurn(1, "apple"),
1589
+ depsOf(lanes, { denseK: 100, gateConfig: gateConfigOf() }),
1590
+ );
1591
+
1592
+ expect(recordedSelectionEvents[0]!.detail).not.toHaveProperty(
1593
+ "net_new_count",
1594
+ );
1595
+ });
1596
+
1518
1597
  test("an empty pool is not a selector judgment", async () => {
1519
1598
  const lanes = await buildLanes();
1520
1599
  // `selectPool` returns [] before it ever reaches the provider when the pool
@@ -219,10 +219,11 @@ describe("selectPool — id mapping", () => {
219
219
  toolUseResponse({ ids: [3, 1], pinned_ids: [1] }),
220
220
  );
221
221
  const result = await selectPool(makePool(), makeTurn("how's the rollout?"));
222
- expect(result).toEqual([
222
+ expect(result.pages).toEqual([
223
223
  { slug: "topic-x", pinned: false },
224
224
  { slug: "page-a", pinned: true },
225
225
  ]);
226
+ expect(result.keptAll).toBe(false);
226
227
  });
227
228
 
228
229
  test("a page selected as both card and finder line dedupes to one slug, pinned ORed", async () => {
@@ -232,35 +233,42 @@ describe("selectPool — id mapping", () => {
232
233
  toolUseResponse({ ids: [1, 4], pinned_ids: [4] }),
233
234
  );
234
235
  const result = await selectPool(makePool(), makeTurn("the alpha plan"));
235
- expect(result).toEqual([{ slug: "page-a", pinned: true }]);
236
+ expect(result.pages).toEqual([{ slug: "page-a", pinned: true }]);
237
+ expect(result.keptAll).toBe(false);
236
238
  });
237
239
 
238
- test("omitted ids keeps ALL candidates, deduped by slug (recall-safe)", async () => {
240
+ test("omitted ids keeps ALL candidates, deduped by slug (recall-safe), flags keptAll", async () => {
239
241
  providerStub = makeProvider(toolUseResponse({}));
240
242
  const result = await selectPool(makePool(), makeTurn("anything"));
241
- expect(result).toEqual([
243
+ expect(result.pages).toEqual([
242
244
  { slug: "page-a", pinned: false },
243
245
  { slug: "page-b", pinned: false },
244
246
  { slug: "topic-x", pinned: false },
245
247
  ]);
248
+ // The fallback fired — the model gave up judging, not "selected everything".
249
+ expect(result.keptAll).toBe(true);
246
250
  });
247
251
 
248
- test("explicit empty ids keeps no candidates (abstention)", async () => {
252
+ test("explicit empty ids keeps no candidates (abstention), not keptAll", async () => {
249
253
  providerStub = makeProvider(toolUseResponse({ ids: [] }));
250
254
  const result = await selectPool(makePool(), makeTurn("nothing relevant"));
251
- expect(result).toEqual([]);
255
+ expect(result.pages).toEqual([]);
256
+ // An explicit [] is a judgment, not the recall-safe fallback.
257
+ expect(result.keptAll).toBe(false);
252
258
  });
253
259
 
254
260
  test("out-of-range and duplicate IDs are ignored without throwing", async () => {
255
261
  providerStub = makeProvider(toolUseResponse({ ids: [2, 99, 0, -1, 2] }));
256
262
  const result = await selectPool(makePool(), makeTurn("the metrics"));
257
- expect(result).toEqual([{ slug: "page-b", pinned: false }]);
263
+ expect(result.pages).toEqual([{ slug: "page-b", pinned: false }]);
264
+ expect(result.keptAll).toBe(false);
258
265
  });
259
266
 
260
267
  test("empty pool returns no pages and never calls the provider", async () => {
261
268
  providerStub = makeProvider(toolUseResponse({ ids: [1] }));
262
269
  const result = await selectPool({ stable: [], finder: [] }, makeTurn("hi"));
263
- expect(result).toEqual([]);
270
+ expect(result.pages).toEqual([]);
271
+ expect(result.keptAll).toBe(false);
264
272
  expect(providerCalls).toHaveLength(0);
265
273
  });
266
274
  });
@@ -447,7 +455,8 @@ describe("selectPool — infrastructure failures throw", () => {
447
455
  toolUseResponse({ ids: [2] }),
448
456
  ]);
449
457
  const result = await selectPool(makePool(), makeTurn("the metrics"));
450
- expect(result).toEqual([{ slug: "page-b", pinned: false }]);
458
+ expect(result.pages).toEqual([{ slug: "page-b", pinned: false }]);
459
+ expect(result.keptAll).toBe(false);
451
460
  expect(providerCalls).toHaveLength(2);
452
461
  });
453
462
  });
@@ -230,6 +230,13 @@ export interface OrchestrateDeps {
230
230
  * `MEMORY_V3_FULL_PROFILE_MIN_PAGES`; omitted drops the field from the
231
231
  * telemetry detail (the gate itself never reads it). */
232
232
  realConceptPageCount?: number;
233
+ /** Slugs already live in this conversation (prior turns' injected cards). Used
234
+ * ONLY to compute the `net_new_count` telemetry field — selections minus this
235
+ * set are what the injector actually renders. Read-only and side-effect-free:
236
+ * selection never consults it, and omitting it just drops the field. The
237
+ * injector reads the same store, so the two agree for a turn that has not yet
238
+ * committed. */
239
+ activeSlugs?: ReadonlySet<Slug>;
233
240
  }
234
241
 
235
242
  /** A finder-lane candidate: the slug, the descriptor that justified it, and
@@ -325,13 +332,24 @@ export async function orchestrate(
325
332
  // Run the selector over a pool, or pass its candidates straight through when
326
333
  // the selector LLM is disabled (`selectorEnabled: false`, the new-user
327
334
  // profile). Shared by the normal step-3 selection and the gate's
328
- // bypass-to-stable path so the two cannot diverge.
329
- const runSelection = async (pool: SelectorPool): Promise<SelectedPage[]> =>
330
- timeLatencySubSpan("v3_selection", "Memory selection", () =>
331
- deps.selectorEnabled === false
332
- ? selectAllPoolCandidates(pool)
333
- : selectPool(pool, turn, deps.selectorPrompt),
334
- );
335
+ // bypass-to-stable path so the two cannot diverge. `keptAll` marks the
336
+ // selector's recall-safe fallback ONLY — the disabled passthrough is not a
337
+ // selector judgment, so it reports `false` (its turns are excluded from any
338
+ // relevance read by `selector_ran` anyway).
339
+ const runSelection = (
340
+ pool: SelectorPool,
341
+ ): Promise<{ selections: SelectedPage[]; keptAll: boolean }> =>
342
+ timeLatencySubSpan("v3_selection", "Memory selection", async () => {
343
+ if (deps.selectorEnabled === false) {
344
+ return { selections: selectAllPoolCandidates(pool), keptAll: false };
345
+ }
346
+ const { pages, keptAll } = await selectPool(
347
+ pool,
348
+ turn,
349
+ deps.selectorPrompt,
350
+ );
351
+ return { selections: pages, keptAll };
352
+ });
335
353
 
336
354
  // Step 1: needle (sync BM25) and the enabled dense lane (async embed +
337
355
  // Qdrant) run in parallel. Both return distinct articles each tagged with
@@ -545,17 +563,35 @@ export async function orchestrate(
545
563
  // The last is why `poolSize` decides this rather than each call site: an empty
546
564
  // pool is not a judgment that nothing was relevant, and no caller has to
547
565
  // remember that.
566
+ // `selector_kept_all` and `net_new_count` separate what the selector JUDGED
567
+ // from what actually reaches the turn, which `selected_count` alone conflates:
568
+ // - kept_all: the recall-safe fallback fired (model omitted `ids`), so every
569
+ // candidate was kept without a real judgment. Distinguishes "kept the whole
570
+ // pool because it gave up" from "explicitly selected a large set", which
571
+ // otherwise look identical and inflate the same way.
572
+ // - net_new: selections not already live in the conversation — the injector
573
+ // renders only these (prior turns' cards ride history), so it is the real
574
+ // incremental injection, where `selected_count` re-counts the whole
575
+ // standing set every turn. Omitted when the caller did not supply
576
+ // `activeSlugs` (tests, shadow-less paths).
548
577
  const recordSelection = (
549
578
  selections: SelectedPage[],
550
579
  poolSize: number,
580
+ keptAll: boolean,
551
581
  ): void => {
552
582
  const detail: Record<string, unknown> = {
553
583
  gate_reason: gateOutcome?.reason ?? null,
554
584
  gate_pass: gateOutcome?.pass ?? null,
555
585
  selector_ran: deps.selectorEnabled !== false && poolSize > 0,
586
+ selector_kept_all: keptAll,
556
587
  selected_count: selections.length,
557
588
  pool_size: poolSize,
558
589
  };
590
+ if (deps.activeSlugs !== undefined) {
591
+ detail.net_new_count = selections.filter(
592
+ (s) => !deps.activeSlugs!.has(s.slug),
593
+ ).length;
594
+ }
559
595
  if (deps.realConceptPageCount !== undefined) {
560
596
  detail.real_concept_page_count = deps.realConceptPageCount;
561
597
  }
@@ -633,17 +669,17 @@ export async function orchestrate(
633
669
  // `denseK > 0` (the dense-gated gate only runs with dense hits; the
634
670
  // new-user profile sets `denseK: 0`, so the gate never runs for it).
635
671
  const stableOnly = buildStable();
636
- const bypassed = await runSelection({
672
+ const { selections: bypassed, keptAll } = await runSelection({
637
673
  stable: stableOnly,
638
674
  finder: [],
639
675
  });
640
- recordSelection(bypassed, stableOnly.length);
676
+ recordSelection(bypassed, stableOnly.length, keptAll);
641
677
  return closed(bypassed);
642
678
  }
643
679
  // Hard skip: the selector is never consulted, so this is a zero
644
680
  // selection BY CONSTRUCTION, not a judgment that nothing was relevant.
645
681
  // `selector_ran: false` keeps it out of any relevance rate.
646
- recordSelection([], 0);
682
+ recordSelection([], 0, false);
647
683
  return closed([]);
648
684
  }
649
685
  }
@@ -741,8 +777,8 @@ export async function orchestrate(
741
777
  "Gate & edge expansion",
742
778
  Date.now() - expandStartedAt,
743
779
  );
744
- const selections = await runSelection(pool);
745
- recordSelection(selections, stable.length + finderTail.length);
780
+ const { selections, keptAll } = await runSelection(pool);
781
+ recordSelection(selections, stable.length + finderTail.length, keptAll);
746
782
 
747
783
  return {
748
784
  selections,
@@ -124,22 +124,27 @@ describe("selectPool", () => {
124
124
  input: { ids: [1] },
125
125
  },
126
126
  ]);
127
- expect(await selectPool(pool, turn)).toEqual([
128
- { slug: "page-a", pinned: false },
129
- ]);
127
+ expect(await selectPool(pool, turn)).toEqual({
128
+ pages: [{ slug: "page-a", pinned: false }],
129
+ keptAll: false,
130
+ });
130
131
  });
131
132
 
132
- test("omitted ids keep all candidates (recall-safe)", async () => {
133
+ test("omitted ids keep all candidates (recall-safe) and flag keptAll", async () => {
133
134
  sendMessageImpl = async () =>
134
135
  response([
135
136
  { type: "tool_use", id: "call-1", name: "select_pages", input: {} },
136
137
  ]);
137
- expect(await selectPool(pool, turn)).toEqual([
138
- { slug: "page-a", pinned: false },
139
- ]);
138
+ expect(await selectPool(pool, turn)).toEqual({
139
+ pages: [{ slug: "page-a", pinned: false }],
140
+ keptAll: true,
141
+ });
140
142
  });
141
143
 
142
144
  test("an empty candidate pool returns no selections", async () => {
143
- expect(await selectPool({ stable: [], finder: [] }, turn)).toEqual([]);
145
+ expect(await selectPool({ stable: [], finder: [] }, turn)).toEqual({
146
+ pages: [],
147
+ keptAll: false,
148
+ });
144
149
  });
145
150
  });
@@ -363,15 +363,26 @@ export function selectAllPoolCandidates(pool: SelectorPool): SelectedPage[] {
363
363
  return dedupeBySlug(ordered.map((slug) => ({ slug, pinned: false })));
364
364
  }
365
365
 
366
+ /** A selection plus whether it came from the recall-safe keep-all fallback. */
367
+ export interface PoolSelection {
368
+ pages: SelectedPage[];
369
+ /** True only when the model OMITTED `ids` and every candidate was kept as the
370
+ * recall-safe fallback — NOT when it explicitly selected a large set. The two
371
+ * produce the same pages but mean different things (the model gave up judging
372
+ * vs it judged everything relevant), and only telemetry can tell them apart. */
373
+ keptAll: boolean;
374
+ }
375
+
366
376
  /**
367
377
  * Run the single forced-tool selector over the unified candidate pool. Returns
368
378
  * the pages to inject, deduped by slug (a page that appeared as both a card
369
- * and a finder line yields one entry, pinned flags ORed).
379
+ * and a finder line yields one entry, pinned flags ORed), plus a `keptAll` flag
380
+ * marking the recall-safe fallback.
370
381
  *
371
382
  * An omitted `ids` keeps ALL candidates (the recall-safe "all of these are
372
- * relevant" signal); an explicit `[]` keeps none; an infrastructure failure
373
- * (after a short re-prompt retry) keeps none, degrading to the deterministic
374
- * recall lanes the orchestrator unions in.
383
+ * relevant" signal, `keptAll: true`); an explicit `[]` keeps none; an
384
+ * infrastructure failure (after a short re-prompt retry) keeps none, degrading
385
+ * to the deterministic recall lanes the orchestrator unions in.
375
386
  *
376
387
  * `systemPrompt` is the selector's instruction scaffold; it defaults to the
377
388
  * bundled {@link SYSTEM_PROMPT} and is overridable via `memory.v3.selectorPromptPath`
@@ -381,14 +392,14 @@ export async function selectPool(
381
392
  pool: SelectorPool,
382
393
  turn: MemoryRoutingTurn,
383
394
  systemPrompt: string = SYSTEM_PROMPT,
384
- ): Promise<SelectedPage[]> {
395
+ ): Promise<PoolSelection> {
385
396
  // The concatenated numbering: ids 1…m are the stable-prefix cards, ids
386
397
  // m+1… are the finder lines.
387
398
  const ordered: Slug[] = [
388
399
  ...pool.stable.map((c) => c.slug),
389
400
  ...pool.finder.map((c) => c.slug),
390
401
  ];
391
- if (ordered.length === 0) return [];
402
+ if (ordered.length === 0) return { pages: [], keptAll: false };
392
403
 
393
404
  const keepAll = (): SelectedPage[] => selectAllPoolCandidates(pool);
394
405
 
@@ -570,7 +581,7 @@ export async function selectPool(
570
581
  }
571
582
 
572
583
  // Omitted `ids` is the recall-safe "keep all candidates" signal.
573
- if (parsed.ids === undefined) return keepAll();
584
+ if (parsed.ids === undefined) return { pages: keepAll(), keptAll: true };
574
585
 
575
586
  const pinned = new Set(parsed.pinned_ids ?? []);
576
587
 
@@ -581,5 +592,5 @@ export async function selectPool(
581
592
  if (id < 1 || id > ordered.length) continue;
582
593
  selected.push({ slug: ordered[id - 1]!, pinned: pinned.has(id) });
583
594
  }
584
- return dedupeBySlug(selected);
595
+ return { pages: dedupeBySlug(selected), keptAll: false };
585
596
  }
@@ -47,6 +47,7 @@ import type { EdgeGraph } from "./edge.js";
47
47
  import { buildEdgeGraph } from "./edge.js";
48
48
  import type { EntityIndex } from "./entity-lane.js";
49
49
  import { buildEntityIndex } from "./entity-lane.js";
50
+ import { getActiveSlugs } from "./ever-injected-store.js";
50
51
  import { computeFreshSet } from "./fresh-set.js";
51
52
  import { isMemoryV3InjectionGateEnabled } from "./gate-flag.js";
52
53
  import { computeHotSet } from "./hot-set.js";
@@ -661,6 +662,10 @@ export async function observeTurn(
661
662
  needleK: tuning.needleK,
662
663
  denseK: tuning.denseK,
663
664
  realConceptPageCount: lanes.realConceptPageCount,
665
+ // Read-only: lets orchestrate compute the `net_new_count` telemetry field
666
+ // against the same store the injector renders from. This turn has not
667
+ // committed yet, so the set matches what the injector will see.
668
+ activeSlugs: getActiveSlugs(conversationId),
664
669
  entityCap: v3.entity.cap,
665
670
  replyQueryK: tuning.replyQueryK,
666
671
  edgeSeeds: tuning.edgeSeedCount,