@unblocklabs/unblock-memory 0.12.0 → 0.12.2

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/README.md CHANGED
@@ -115,7 +115,7 @@ Everything below is off until you configure it.
115
115
  | --- | --- |
116
116
  | [Session indexing](docs/retrieval.md#sessions) | Makes past conversations searchable. Group and channel chats by default; DMs only if you add them. |
117
117
  | [Skill Whisperer](docs/retrieval.md#skill-whisperer) | Suggests one relevant skill for a user message. Never runs it. Turns on when you add a `skills` corpus; works without TypeSafe. |
118
- | [Memory Whisperer](docs/retrieval.md#memory-whisperer) | Adds up to two relevant past excerpts before the agent replies. Needs TypeSafe and a self-hosted query-generation API. |
118
+ | [Memory Whisperer](docs/retrieval.md#memory-whisperer) | Adds up to three relevant past excerpts before the agent replies. Needs TypeSafe; optionally uses a self-hosted query-generation API with local fallback. |
119
119
  | [Safety Whisperer](docs/configuration.md#safety-whisperer) | Reminds the agent not to share sensitive topics, such as one person's salary, with requestors you haven't approved. A prompt-level guardrail, not access control; fails open if TypeSafe is unavailable. |
120
120
  | [My Turn](docs/configuration.md#my-turn) | Asks Jev whether a group/channel conversation needs this agent's response. Advises `NO_REPLY` only when silence is clearly favored; the agent keeps the final say. Opt-in; failures leave the turn unchanged. |
121
121
  | [People dossiers](docs/peoplesql.md) | Lets the agent keep a short, evidence-backed note about each person it works with. |
@@ -87,8 +87,8 @@ const DEFAULT_SKILL_WHISPERER = {
87
87
  cooldownTurns: 10,
88
88
  };
89
89
  const DEFAULT_MEMORY_WHISPERER = {
90
- enabled: false, complementaryHints: false, corpora: [], minUsefulness: 0.7,
91
- maxHints: 2, cooldownTurns: 10, timeoutMs: 3000,
90
+ enabled: false, complementaryHints: false, corpora: [], minUsefulness: 0.5,
91
+ maxHints: 3, cooldownTurns: 10, timeoutMs: 3000,
92
92
  api: { endpoint: "http://192.168.1.191:18087" },
93
93
  };
94
94
  function resolveQueryApi(value) {
@@ -156,7 +156,7 @@ function resolveMemoryWhisperer(value, corpora) {
156
156
  }
157
157
  return {
158
158
  enabled, complementaryHints, corpora: [...new Set(selected)], cooldownTurns, minUsefulness,
159
- maxHints: positiveInteger(config.maxHints, 2, "memoryWhisperer.maxHints", 2),
159
+ maxHints: positiveInteger(config.maxHints, DEFAULT_MEMORY_WHISPERER.maxHints, "memoryWhisperer.maxHints", 3),
160
160
  timeoutMs: positiveInteger(config.timeoutMs, 3000, "memoryWhisperer.timeoutMs", 10_000),
161
161
  api: resolveQueryApi(config.api),
162
162
  };
@@ -1,6 +1,6 @@
1
1
  import { RetrievalTelemetry } from "./retrieval-telemetry.js";
2
2
  type Whisperer = "skill" | "memory" | "safety" | "myTurn";
3
- type Outcome = "missing_key" | "typesafe_disabled" | "no_candidates" | "rejected" | "cooldown" | "emitted" | "failed" | "timed_out" | "cancelled" | "unavailable" | "payload_limit" | "redundancy_unavailable" | "recall_not_needed" | "queries_generated" | "judge_candidate_failed" | "input_too_large" | "excluded" | "no_scenarios" | "empty_request" | "no_match" | "flagged" | "missing_identity" | "partial_response";
3
+ type Outcome = "missing_key" | "typesafe_disabled" | "no_candidates" | "rejected" | "cooldown" | "emitted" | "failed" | "timed_out" | "cancelled" | "unavailable" | "payload_limit" | "redundancy_unavailable" | "queries_generated" | "generation_fallback" | "judge_candidate_failed" | "input_too_large" | "excluded" | "no_scenarios" | "empty_request" | "no_match" | "flagged" | "missing_identity" | "partial_response";
4
4
  /** Process-local, content-free and bounded. Agent IDs are keys, never included in snapshots. */
5
5
  export declare class WhispererDiagnostics {
6
6
  #private;
@@ -24,8 +24,8 @@ export declare class WhispererDiagnostics {
24
24
  unavailable?: number | undefined;
25
25
  payload_limit?: number | undefined;
26
26
  redundancy_unavailable?: number | undefined;
27
- recall_not_needed?: number | undefined;
28
27
  queries_generated?: number | undefined;
28
+ generation_fallback?: number | undefined;
29
29
  judge_candidate_failed?: number | undefined;
30
30
  input_too_large?: number | undefined;
31
31
  excluded?: number | undefined;
@@ -49,8 +49,8 @@ export declare class WhispererDiagnostics {
49
49
  unavailable?: number | undefined;
50
50
  payload_limit?: number | undefined;
51
51
  redundancy_unavailable?: number | undefined;
52
- recall_not_needed?: number | undefined;
53
52
  queries_generated?: number | undefined;
53
+ generation_fallback?: number | undefined;
54
54
  judge_candidate_failed?: number | undefined;
55
55
  input_too_large?: number | undefined;
56
56
  excluded?: number | undefined;
@@ -74,8 +74,8 @@ export declare class WhispererDiagnostics {
74
74
  unavailable?: number | undefined;
75
75
  payload_limit?: number | undefined;
76
76
  redundancy_unavailable?: number | undefined;
77
- recall_not_needed?: number | undefined;
78
77
  queries_generated?: number | undefined;
78
+ generation_fallback?: number | undefined;
79
79
  judge_candidate_failed?: number | undefined;
80
80
  input_too_large?: number | undefined;
81
81
  excluded?: number | undefined;
@@ -102,8 +102,8 @@ export declare class WhispererDiagnostics {
102
102
  unavailable?: number | undefined;
103
103
  payload_limit?: number | undefined;
104
104
  redundancy_unavailable?: number | undefined;
105
- recall_not_needed?: number | undefined;
106
105
  queries_generated?: number | undefined;
106
+ generation_fallback?: number | undefined;
107
107
  judge_candidate_failed?: number | undefined;
108
108
  input_too_large?: number | undefined;
109
109
  excluded?: number | undefined;
@@ -150,11 +150,10 @@ export declare class WhispererDiagnostics {
150
150
  otherMs?: number | undefined;
151
151
  retrievalMs?: number | undefined;
152
152
  judgeMs?: number | undefined;
153
+ generationMs?: number | undefined;
153
154
  metadataReloads?: number | undefined;
154
155
  vectorScanAttempts?: number | undefined;
155
156
  elapsedMs?: number | undefined;
156
- gateMs?: number | undefined;
157
- generationMs?: number | undefined;
158
157
  candidates?: number | undefined;
159
158
  eligible?: number | undefined;
160
159
  results?: number | undefined;
@@ -4,7 +4,7 @@ export class WhispererDiagnostics {
4
4
  static shared() {
5
5
  const scope = globalThis;
6
6
  // Bump the version whenever the shape changes so an older loaded copy is never reused.
7
- const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.v4");
7
+ const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.v5");
8
8
  return (scope[symbol] ??= new WhispererDiagnostics());
9
9
  }
10
10
  #agents = new Map();
@@ -84,11 +84,10 @@ export declare class QmdMemoryManager implements MemorySearchManagerContract {
84
84
  otherMs?: number | undefined;
85
85
  retrievalMs?: number | undefined;
86
86
  judgeMs?: number | undefined;
87
+ generationMs?: number | undefined;
87
88
  metadataReloads?: number | undefined;
88
89
  vectorScanAttempts?: number | undefined;
89
90
  elapsedMs?: number | undefined;
90
- gateMs?: number | undefined;
91
- generationMs?: number | undefined;
92
91
  candidates?: number | undefined;
93
92
  eligible?: number | undefined;
94
93
  results?: number | undefined;
@@ -840,6 +840,7 @@ export class QmdMemoryManager {
840
840
  return this.#allowedPaths(collections, opts.sessionFilter);
841
841
  });
842
842
  const store = await timeStage("storeSetupMs", timings, signal, () => this.#getAnalysisStore());
843
+ const RRF_K = 60;
843
844
  const hits = new Map();
844
845
  // Serialize native QMD work. Cancellation prevents further queries/collections.
845
846
  for (const lane of ["lex", "vec"]) {
@@ -853,15 +854,33 @@ export class QmdMemoryManager {
853
854
  timings.vectorOtherMs = unaccounted(timings.vectorMs, timings, vectorParts);
854
855
  }
855
856
  }
856
- for (const hit of candidates) {
857
- const key = JSON.stringify([hit.file, hit.bestChunkPos, hit.bestChunk]);
858
- if (!hits.has(key))
859
- hits.set(key, { file: hit.file, body: hit.body, bestChunk: hit.bestChunk,
860
- chunkPos: hit.bestChunkPos, chunkLen: hit.bestChunk.length, displayPath: hit.file, score: hit.score });
857
+ for (const [index, hit] of candidates.entries()) {
858
+ const rank = hit.bm25?.rank ?? hit.vector?.rank ?? index + 1;
859
+ const contribution = 1 / (RRF_K + rank);
860
+ const key = JSON.stringify([hit.file, hit.bestChunkPos, hit.bestChunk.trim()]);
861
+ const existing = hits.get(key);
862
+ if (existing) {
863
+ existing.rrfScore += contribution;
864
+ existing.topRank = Math.min(existing.topRank, rank);
865
+ }
866
+ else {
867
+ hits.set(key, {
868
+ hit: { file: hit.file, body: hit.body, bestChunk: hit.bestChunk,
869
+ chunkPos: hit.bestChunkPos, chunkLen: hit.bestChunk.length, displayPath: hit.file, score: 0 },
870
+ rrfScore: contribution,
871
+ topRank: rank,
872
+ });
873
+ }
861
874
  }
862
875
  }
876
+ // Passage-level RRF (k=60) with QMD's top-rank bonuses so rank-1 single-lane
877
+ // hits compete cleanly alongside dual-lane matches before any candidate cap.
878
+ const fused = [...hits.values()].map(entry => ({
879
+ ...entry.hit,
880
+ score: entry.rrfScore + (entry.topRank === 1 ? 0.05 : entry.topRank <= 3 ? 0.02 : 0),
881
+ })).sort((a, b) => b.score - a.score);
863
882
  opts.signal?.throwIfAborted();
864
- return timeStage("passageMs", timings, signal, () => this.#renderSearchHits([...hits.values()], store, opts, true));
883
+ return timeStage("passageMs", timings, signal, () => this.#renderSearchHits(fused, store, opts, true));
865
884
  });
866
885
  }
867
886
  finally {
@@ -25,6 +25,8 @@ export declare function searchMemory(manager: MemoryCandidateManager, queries: Q
25
25
  asOf?: string;
26
26
  /** Only explicit, agent-requested search opts in. Automatic injection stays strict. */
27
27
  allowRetrievalFallback?: boolean;
28
+ /** Cap top retrieval-ranked candidates sent to TypeSafe (after dedup and cooldown filtering). */
29
+ maxJudgeCandidates?: number;
28
30
  minUsefulness?: number;
29
31
  excludedPassages?: ReadonlyMap<string, number>;
30
32
  onCandidates?: (observation: MemorySearchObservation) => void;
@@ -48,9 +48,8 @@ export async function searchMemory(manager, queries, options) {
48
48
  options.onCandidates?.(observation);
49
49
  const fallback = (reason) => ({
50
50
  ...timings, ...observation, rankingMode: "retrieval", fallbackReason: reason,
51
- // Discovery is a lexical-first union, not a ranking. Stable reciprocal-rank
52
- // ordering lets strong vector-only hits compete before maxResults truncation.
53
- // These original lane scores are not fused ranks or usefulness probabilities.
51
+ // Stable retrieval-score ordering (fused RRF scores from discovery) before maxResults truncation.
52
+ // These retrieval scores are not TypeSafe usefulness probabilities.
54
53
  results: [...candidates].sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5),
55
54
  });
56
55
  if (!options.apiKey) {
@@ -59,11 +58,17 @@ export async function searchMemory(manager, queries, options) {
59
58
  return fallback("key_unavailable");
60
59
  return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: [] };
61
60
  }
61
+ const maxJudge = typeof options.maxJudgeCandidates === "number" && Number.isFinite(options.maxJudgeCandidates)
62
+ ? Math.max(0, Math.floor(options.maxJudgeCandidates))
63
+ : undefined;
64
+ const judgePool = maxJudge !== undefined
65
+ ? [...candidates].sort((a, b) => b.score - a.score).slice(0, maxJudge)
66
+ : candidates;
62
67
  const apiKey = options.apiKey;
63
68
  const endJudge = startTiming("judgeMs", timings, signal);
64
69
  let judged;
65
70
  try {
66
- judged = (await Promise.all(candidates.map(async (hit, candidateIndex) => {
71
+ judged = (await Promise.all(judgePool.map(async (hit, candidateIndex) => {
67
72
  const requestStarted = performance.now();
68
73
  try {
69
74
  const { probability } = await judgeMemoryPassage(memoryUsefulnessRequest(options.conversation, {
@@ -92,7 +97,7 @@ export async function searchMemory(manager, queries, options) {
92
97
  }
93
98
  signal?.throwIfAborted();
94
99
  observation.judgeMs = timings.judgeMs ?? 0;
95
- if (options.allowRetrievalFallback && candidates.length && !observation.requestsSucceeded)
100
+ if (options.allowRetrievalFallback && judgePool.length && !observation.requestsSucceeded)
96
101
  return fallback("all_judgments_failed");
97
102
  return { ...timings, ...observation, rankingMode: "typesafe_usefulness", results: judged.filter(hit => hit.score >= (options.minUsefulness ?? 0.7))
98
103
  .sort((a, b) => b.score - a.score).slice(0, options.maxResults ?? 5) };
@@ -1,10 +1,15 @@
1
1
  import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
2
2
  import { complementaryIndices, reviewMemoryRedundancy } from "./typesafe-review.js";
3
- import { ApiQueryGenerator, QueryApiError, queryConversation } from "./query-generator.js";
4
- import { judgeTrainingInput, TRAINING_GATE_THRESHOLD } from "./training-gate.js";
3
+ import { ApiQueryGenerator, compactJudgeConversation, fallbackQueries, QueryApiError, queryConversation } from "./query-generator.js";
5
4
  import { QueryInputBudgetError } from "./query-contract.js";
6
5
  import { searchMemory, memoryPassageId } from "./memory-search.js";
7
- import { timeStage } from "./retrieval-timing.js";
6
+ import { startTiming, timeStage } from "./retrieval-timing.js";
7
+ const MAX_JUDGE_CANDIDATES = 6;
8
+ const MAX_GENERATION_TIMEOUT_MS = 1_500;
9
+ const MAX_PAYLOAD_CHARS = 5_000;
10
+ function encodeHints(items) {
11
+ return JSON.stringify(items).replace(/</gu, "\\u003c").replace(/>/gu, "\\u003e");
12
+ }
8
13
  export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnostics) {
9
14
  if (!config.enabled || !typesafe.enabled)
10
15
  return;
@@ -26,7 +31,7 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
26
31
  const asOf = new Date().toISOString();
27
32
  const measurement = { outcome: "skipped", elapsedMs: 0 };
28
33
  let stage = "input", reason = "completed";
29
- let recallProbability, queryCount;
34
+ let queryCount, queryFallback = false;
30
35
  let requestsSucceeded = 0, requestsFailed = 0;
31
36
  const log = (level, event, fields) => api.logger[level]("unblock-memory memory_whisperer " + JSON.stringify({ event, agentId, runId, sessionId, stage, ...fields }));
32
37
  const failureFields = (error) => error instanceof TypeSafeRequestError || error instanceof QueryApiError
@@ -43,8 +48,6 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
43
48
  }
44
49
  const { signal } = state.controller;
45
50
  let timedOut = false;
46
- let recallRejected = false;
47
- let gateFailed = false;
48
51
  const timer = setTimeout(() => { timedOut = true; state.controller.abort(); }, config.timeoutMs);
49
52
  let onAbort = () => { };
50
53
  const aborted = new Promise(resolve => {
@@ -62,152 +65,132 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
62
65
  diagnostics?.record(agentId, "memory", "missing_key");
63
66
  return;
64
67
  }
65
- const gateStarted = performance.now();
66
- const gateSignal = AbortSignal.any([signal, AbortSignal.timeout(typesafe.timeoutMs)]);
67
- // Speculation is intentional: neither model generation nor QMD waits for the recall judgment.
68
- const gate = judgeTrainingInput(conversation, apiKey, gateSignal)
69
- .then(result => {
68
+ let queries;
69
+ stage = "generation";
70
+ const generationStarted = performance.now();
71
+ const endGeneration = startTiming("generationMs", measurement, signal);
72
+ const generationTimeoutMs = Math.min(MAX_GENERATION_TIMEOUT_MS, Math.max(1, Math.floor(config.timeoutMs / 2)));
73
+ const generationSignal = AbortSignal.any([signal, AbortSignal.timeout(generationTimeoutMs)]);
74
+ try {
75
+ queries = await generator.generate(conversation, generationSignal);
70
76
  if (signal.aborted)
71
- return false;
72
- measurement.gateMs = performance.now() - gateStarted;
73
- recallProbability = result.probability;
74
- if (result.probability >= TRAINING_GATE_THRESHOLD)
75
- return true;
76
- recallRejected = true;
77
- diagnostics?.record(agentId, "memory", "recall_not_needed");
78
- state.controller.abort();
79
- return false;
80
- }).catch(error => {
81
- if (!signal.aborted) {
82
- measurement.gateMs = performance.now() - gateStarted;
83
- log("warn", "recall_failed", { stage: "recall", elapsedMs: measurement.gateMs, timeoutMs: typesafe.timeoutMs,
84
- ...failureFields(error instanceof TypeSafeRequestError ? error :
85
- new TypeSafeRequestError("Recall judgment failed", "invalid_response")) });
86
- gateFailed = true;
87
- diagnostics?.record(agentId, "memory", "failed");
88
- state.controller.abort();
89
- }
90
- return false;
91
- });
92
- const retrieveAndJudge = async () => {
93
- let queries;
94
- stage = "generation";
95
- const generationStarted = performance.now();
96
- try {
97
- queries = await generator.generate(conversation, signal);
98
- if (signal.aborted)
99
- return;
100
- queryCount = 2;
101
- diagnostics?.record(agentId, "memory", "queries_generated");
102
- }
103
- catch (error) {
104
- if (signal.aborted)
105
- return;
106
- reason = "generation_failed";
107
- measurement.outcome = "failed";
108
- log("warn", "generation_failed", { ...failureFields(error), elapsedMs: performance.now() - generationStarted });
109
- diagnostics?.record(agentId, "memory", "failed");
110
77
  return;
111
- }
112
- finally {
113
- measurement.generationMs = performance.now() - generationStarted;
114
- }
115
- stage = "retrieval";
116
- const { manager } = await timeStage("setupMs", measurement, signal, () => runtime.getMemorySearchManager({ cfg: api.config, agentId }));
78
+ diagnostics?.record(agentId, "memory", "queries_generated");
79
+ }
80
+ catch (error) {
117
81
  if (signal.aborted)
118
82
  return;
119
- if (!manager) {
120
- reason = "unavailable";
121
- diagnostics?.record(agentId, "memory", "unavailable");
122
- return;
123
- }
124
- const search = await searchMemory(manager, queries, {
125
- corpora, signal, apiKey, timeoutMs: typesafe.timeoutMs, conversation, asOf, timings: measurement,
126
- minUsefulness: config.minUsefulness, maxResults: 4, excludedPassages: state.recent,
127
- onCandidates: observation => {
128
- measurement.retrievalMs = observation.retrievalMs;
129
- measurement.candidates = observation.candidates;
130
- measurement.eligible = observation.eligible;
131
- measurement.outcome = "empty";
132
- stage = "judgment";
133
- },
134
- onJudgment: ({ candidateIndex, elapsedMs, error }) => {
135
- const fields = { stage: "judgment", candidateIndex, elapsedMs, timeoutMs: typesafe.timeoutMs };
136
- if (error !== undefined) {
137
- requestsFailed++;
138
- diagnostics?.record(agentId, "memory", "judge_candidate_failed");
139
- log("warn", "candidate_failed", { ...fields, ...failureFields(error) });
140
- }
141
- else {
142
- requestsSucceeded++;
143
- log("info", "candidate_completed", fields);
144
- }
145
- },
146
- });
147
- if (signal.aborted || sessions.get(key) !== state)
148
- return;
149
- measurement.judgeMs = search.judgeMs;
150
- if (!search.eligible) {
151
- reason = "no_candidates";
152
- diagnostics?.record(agentId, "memory", "no_candidates");
153
- return;
154
- }
155
- if (!await gate || signal.aborted || sessions.get(key) !== state)
156
- return;
157
- if (!search.requestsSucceeded) {
158
- reason = "all_candidates_failed";
159
- measurement.outcome = "failed";
160
- diagnostics?.record(agentId, "memory", "failed");
161
- return;
162
- }
163
- const ranked = search.results.map(hit => ({ hit, excerpt: hit.snippet, id: memoryPassageId(hit.snippet) }));
164
- let selected = ranked.slice(0, config.maxHints);
165
- if (!selected.length) {
166
- reason = "rejected";
167
- diagnostics?.record(agentId, "memory", "rejected");
168
- return;
169
- }
170
- if (config.complementaryHints && config.maxHints > 1 && ranked.length > 1) {
171
- stage = "redundancy";
172
- try {
173
- const pairs = await reviewMemoryRedundancy({ apiKey, timeoutMs: typesafe.timeoutMs, signal,
174
- excerpts: ranked.map(candidate => candidate.excerpt) });
175
- selected = complementaryIndices(ranked.length, pairs, config.maxHints).map(index => ranked[index]);
83
+ queryFallback = true;
84
+ queries = fallbackQueries(conversation);
85
+ log("warn", "generation_fallback", { ...failureFields(error), elapsedMs: performance.now() - generationStarted,
86
+ timeoutMs: generationTimeoutMs });
87
+ diagnostics?.record(agentId, "memory", "generation_fallback");
88
+ }
89
+ finally {
90
+ endGeneration();
91
+ }
92
+ queryCount = 2;
93
+ stage = "retrieval";
94
+ const { manager } = await timeStage("setupMs", measurement, signal, () => runtime.getMemorySearchManager({ cfg: api.config, agentId }));
95
+ if (signal.aborted)
96
+ return;
97
+ if (!manager) {
98
+ reason = "unavailable";
99
+ diagnostics?.record(agentId, "memory", "unavailable");
100
+ return;
101
+ }
102
+ const search = await searchMemory(manager, queries, {
103
+ corpora, signal, apiKey, timeoutMs: typesafe.timeoutMs, conversation: compactJudgeConversation(conversation),
104
+ asOf, timings: measurement, minUsefulness: config.minUsefulness, maxResults: 4,
105
+ maxJudgeCandidates: MAX_JUDGE_CANDIDATES, excludedPassages: state.recent,
106
+ onCandidates: observation => {
107
+ measurement.retrievalMs = observation.retrievalMs;
108
+ measurement.candidates = observation.candidates;
109
+ measurement.eligible = observation.eligible;
110
+ measurement.outcome = "empty";
111
+ stage = "judgment";
112
+ },
113
+ onJudgment: ({ candidateIndex, elapsedMs, error }) => {
114
+ const fields = { stage: "judgment", candidateIndex, elapsedMs, timeoutMs: typesafe.timeoutMs };
115
+ if (error !== undefined) {
116
+ requestsFailed++;
117
+ diagnostics?.record(agentId, "memory", "judge_candidate_failed");
118
+ log("warn", "candidate_failed", { ...fields, ...failureFields(error) });
176
119
  }
177
- catch (error) {
178
- // Preserve the original useful candidates when the optional refinement is unavailable.
179
- if (!signal.aborted) {
180
- diagnostics?.record(agentId, "memory", "redundancy_unavailable");
181
- log("warn", "redundancy_unavailable", failureFields(error));
182
- }
120
+ else {
121
+ requestsSucceeded++;
122
+ log("info", "candidate_completed", fields);
183
123
  }
124
+ },
125
+ });
126
+ if (signal.aborted || sessions.get(key) !== state)
127
+ return;
128
+ measurement.judgeMs = search.judgeMs;
129
+ if (!search.eligible) {
130
+ reason = "no_candidates";
131
+ diagnostics?.record(agentId, "memory", "no_candidates");
132
+ return;
133
+ }
134
+ if (!search.requestsSucceeded) {
135
+ reason = "all_candidates_failed";
136
+ measurement.outcome = "failed";
137
+ diagnostics?.record(agentId, "memory", "failed");
138
+ return;
139
+ }
140
+ const ranked = search.results.map(hit => ({ hit, excerpt: hit.snippet, id: memoryPassageId(hit.snippet) }));
141
+ let selected = ranked.slice(0, config.maxHints);
142
+ if (!selected.length) {
143
+ reason = "rejected";
144
+ diagnostics?.record(agentId, "memory", "rejected");
145
+ return;
146
+ }
147
+ if (config.complementaryHints && config.maxHints > 1 && ranked.length > 1) {
148
+ stage = "redundancy";
149
+ try {
150
+ const pairs = await reviewMemoryRedundancy({ apiKey, timeoutMs: typesafe.timeoutMs, signal,
151
+ excerpts: ranked.map(candidate => candidate.excerpt) });
152
+ selected = complementaryIndices(ranked.length, pairs, config.maxHints).map(index => ranked[index]);
184
153
  }
185
- if (signal.aborted || sessions.get(key) !== state)
186
- return;
187
- stage = "render";
188
- const hints = selected.map(({ hit, excerpt }) => ({
189
- source: hit.path, lines: `${hit.startLine}-${hit.endLine}`, body: excerpt,
190
- }));
191
- // Bound the complete injected payload, including source metadata.
192
- // Preserve exact JSON values while keeping source text inside its prompt tags.
193
- const rendered = JSON.stringify(hints).replace(/</gu, "\\u003c").replace(/>/gu, "\\u003e");
194
- if (rendered.length > 5000) {
195
- reason = "payload_limit";
196
- diagnostics?.record(agentId, "memory", "payload_limit");
197
- return;
154
+ catch (error) {
155
+ // Preserve the original useful candidates when the optional refinement is unavailable.
156
+ if (!signal.aborted) {
157
+ diagnostics?.record(agentId, "memory", "redundancy_unavailable");
158
+ log("warn", "redundancy_unavailable", failureFields(error));
159
+ }
198
160
  }
199
- for (const candidate of selected)
200
- state.recent.set(candidate.id, state.turn);
201
- diagnostics?.record(agentId, "memory", "emitted");
202
- const appendContext = `<memory>\n${rendered}\n</memory>`;
203
- measurement.outcome = "ok";
204
- reason = "emitted";
205
- measurement.results = selected.length;
206
- measurement.contextChars = appendContext.length;
207
- return { appendContext };
208
- };
209
- const [, result] = await Promise.all([gate, retrieveAndJudge()]);
210
- return result;
161
+ }
162
+ if (signal.aborted || sessions.get(key) !== state)
163
+ return;
164
+ stage = "render";
165
+ // Bound the complete injected payload without slicing individual excerpts into misleading prefixes.
166
+ const emitted = [];
167
+ const hints = [];
168
+ let rendered = "";
169
+ for (const candidate of selected) {
170
+ const nextHint = {
171
+ source: candidate.hit.path, lines: `${candidate.hit.startLine}-${candidate.hit.endLine}`, body: candidate.excerpt,
172
+ };
173
+ const nextRendered = encodeHints([...hints, nextHint]);
174
+ if (nextRendered.length > MAX_PAYLOAD_CHARS)
175
+ continue;
176
+ emitted.push(candidate);
177
+ hints.push(nextHint);
178
+ rendered = nextRendered;
179
+ }
180
+ if (!emitted.length) {
181
+ reason = "payload_limit";
182
+ diagnostics?.record(agentId, "memory", "payload_limit");
183
+ return;
184
+ }
185
+ for (const candidate of emitted)
186
+ state.recent.set(candidate.id, state.turn);
187
+ diagnostics?.record(agentId, "memory", "emitted");
188
+ const appendContext = `<memory>\n${rendered}\n</memory>`;
189
+ measurement.outcome = "ok";
190
+ reason = "emitted";
191
+ measurement.results = emitted.length;
192
+ measurement.contextChars = appendContext.length;
193
+ return { appendContext };
211
194
  };
212
195
  // Prompt rebuilds need the same context, not another retrieval or an empty hook result.
213
196
  state.result = (async () => {
@@ -232,14 +215,14 @@ export function registerMemoryWhisperer(api, runtime, config, typesafe, diagnost
232
215
  finally {
233
216
  measurement.elapsedMs = performance.now() - started;
234
217
  if (signal.aborted) {
235
- measurement.outcome = gateFailed ? "failed" : recallRejected ? "skipped" : timedOut ? "timed_out" : "cancelled";
236
- reason = gateFailed ? "recall_failed" : recallRejected ? "recall_not_needed" : timedOut ? "deadline" : "cancelled";
218
+ measurement.outcome = timedOut ? "timed_out" : "cancelled";
219
+ reason = timedOut ? "deadline" : "cancelled";
237
220
  }
238
221
  diagnostics?.measureMemory(agentId, measurement);
239
- log("info", "completed", { ...measurement, reason, recallProbability, queryCount, requestsSucceeded, requestsFailed,
222
+ log("info", "completed", { ...measurement, reason, queryCount, queryFallback, requestsSucceeded, requestsFailed,
240
223
  judgedCandidates: requestsSucceeded, partial: requestsSucceeded > 0 && requestsFailed > 0, timeoutMs: config.timeoutMs,
241
224
  requestTimeoutMs: typesafe.timeoutMs });
242
- if (signal.aborted && !recallRejected && !gateFailed)
225
+ if (signal.aborted)
243
226
  diagnostics?.record(agentId, "memory", timedOut ? "timed_out" : "cancelled");
244
227
  clearTimeout(timer);
245
228
  signal.removeEventListener("abort", onAbort);
@@ -138,7 +138,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
138
138
  finally {
139
139
  measurement.elapsedMs = performance.now() - started;
140
140
  measurement.setupMs ??= measurement.elapsedMs;
141
- // Manual search is sequential. Whisperer stages overlap and cannot use this subtraction.
141
+ // Residual overhead for manual search; whisperer tracks stage timings separately without a whole-run residual.
142
142
  measurement.otherMs = Math.max(0, measurement.elapsedMs - measurement.setupMs -
143
143
  (measurement.retrievalMs ?? 0) - (measurement.candidatePrepMs ?? 0) - (measurement.judgeMs ?? 0));
144
144
  if (signal?.aborted)
@@ -2,10 +2,14 @@ import type { UnblockMemoryConfig } from "./config.js";
2
2
  import { type QueryConversation, type QueryPair } from "./query-contract.js";
3
3
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
4
4
  export declare function queryConversation(prompt: string, messages: readonly unknown[]): QueryConversation;
5
+ /** Deterministic query pair used when the resident query API fails or times out. */
6
+ export declare function fallbackQueries(conversation: QueryConversation): QueryPair;
7
+ /** Bound conversation context repeated across automatic passage usefulness judgments. */
8
+ export declare function compactJudgeConversation(conversation: QueryConversation): QueryConversation;
5
9
  export declare class QueryApiError extends Error {
6
- readonly code: "credentials" | "http_error" | "invalid_response" | "unavailable";
10
+ readonly code: "credentials" | "http_error" | "invalid_response" | "timeout" | "unavailable";
7
11
  readonly status?: number | undefined;
8
- constructor(code: "credentials" | "http_error" | "invalid_response" | "unavailable", status?: number | undefined);
12
+ constructor(code: "credentials" | "http_error" | "invalid_response" | "timeout" | "unavailable", status?: number | undefined);
9
13
  }
10
14
  /** The host owns model warmth/lifecycle; the plugin only sends bounded, cancellable requests. */
11
15
  export declare class ApiQueryGenerator {
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
- import { abortable } from "./abortable.js";
3
+ import { abortable, abortedByTimeout } from "./abortable.js";
4
4
  import { messageText } from "./whisperer-context.js";
5
5
  import { conversationUserText } from "./response-text.js";
6
6
  import { parseQueryPair, prepareQueryConversation } from "./query-contract.js";
@@ -54,6 +54,134 @@ export function queryConversation(prompt, messages) {
54
54
  visible.pop();
55
55
  return prepareQueryConversation(visible, currentRequest).conversation;
56
56
  }
57
+ const FALLBACK_STOP_WORDS = new Set(("a about all also am an and any are as at be been before being but by can could did do does doing done " +
58
+ "for from get got had has have having he her here hers him his how i if in into is it its just know " +
59
+ "like make may me more most my no not now of on one only or other our out over please said say see " +
60
+ "she should so some still such than that the their them then there these they think this those through " +
61
+ "to too under up very was we were what whats when where which who why will with would you your").split(" "));
62
+ const MAX_FALLBACK_LEX_TERMS = 12;
63
+ const MAX_FALLBACK_TERM_CHARS = 64;
64
+ const MAX_FALLBACK_LEX_CHARS = 256;
65
+ const MAX_FALLBACK_VEC_CHARS = 450;
66
+ const MAX_JUDGE_HISTORY_MESSAGES = 2;
67
+ const MAX_JUDGE_CONVERSATION_CHARS = 1_500;
68
+ const MIN_COMPACT_HISTORY_CHARS = 80;
69
+ function sliceHeadSafe(text, maxChars) {
70
+ if (maxChars <= 0)
71
+ return "";
72
+ if (text.length <= maxChars)
73
+ return text;
74
+ let end = maxChars;
75
+ const last = text.charCodeAt(end - 1);
76
+ if (last >= 0xd800 && last <= 0xdbff)
77
+ end--;
78
+ return text.slice(0, end);
79
+ }
80
+ function sliceTailSafe(text, maxChars) {
81
+ if (maxChars <= 0)
82
+ return "";
83
+ if (text.length <= maxChars)
84
+ return text;
85
+ let start = text.length - maxChars;
86
+ const first = text.charCodeAt(start);
87
+ if (first >= 0xdc00 && first <= 0xdfff)
88
+ start++;
89
+ return text.slice(start);
90
+ }
91
+ function extractFallbackTerms(text) {
92
+ const seen = new Set();
93
+ const terms = [];
94
+ for (const token of text.match(/[\p{L}\p{N}_]+/gu) ?? []) {
95
+ const lower = token.toLowerCase();
96
+ if (token.length > MAX_FALLBACK_TERM_CHARS || (lower.length === 1 && /^[a-z]$/u.test(lower)) ||
97
+ seen.has(lower) || FALLBACK_STOP_WORDS.has(lower))
98
+ continue;
99
+ seen.add(lower);
100
+ terms.push(token);
101
+ if (terms.length >= MAX_FALLBACK_LEX_TERMS)
102
+ break;
103
+ }
104
+ return terms;
105
+ }
106
+ function joinBoundedTerms(tokens) {
107
+ const parts = [];
108
+ let length = 0;
109
+ for (const token of tokens) {
110
+ const bounded = sliceHeadSafe(token, MAX_FALLBACK_TERM_CHARS);
111
+ if (!bounded)
112
+ continue;
113
+ const added = bounded.length + (parts.length ? 1 : 0);
114
+ if (length + added > MAX_FALLBACK_LEX_CHARS)
115
+ break;
116
+ parts.push(bounded);
117
+ length += added;
118
+ }
119
+ return parts.join(" ");
120
+ }
121
+ /** Deterministic query pair used when the resident query API fails or times out. */
122
+ export function fallbackQueries(conversation) {
123
+ const request = conversation.currentRequest.trim();
124
+ if (!request)
125
+ throw new Error("Missing or unparseable current request");
126
+ const requestTerms = extractFallbackTerms(request);
127
+ const terms = [...requestTerms];
128
+ const seen = new Set(terms.map(term => term.toLowerCase()));
129
+ const recentUsers = conversation.history.filter(message => message.role === "user").slice(-2);
130
+ if (terms.length < 4) {
131
+ for (let index = recentUsers.length - 1; index >= 0 && terms.length < MAX_FALLBACK_LEX_TERMS; index--) {
132
+ for (const token of extractFallbackTerms(recentUsers[index].content)) {
133
+ const lower = token.toLowerCase();
134
+ if (seen.has(lower))
135
+ continue;
136
+ seen.add(lower);
137
+ terms.push(token);
138
+ if (terms.length >= MAX_FALLBACK_LEX_TERMS)
139
+ break;
140
+ }
141
+ }
142
+ }
143
+ const rawTokens = [...new Set((request.match(/[\p{L}\p{N}_]+/gu) ?? [])
144
+ .map(token => sliceHeadSafe(token, MAX_FALLBACK_TERM_CHARS).toLowerCase())
145
+ .filter(Boolean))].slice(0, MAX_FALLBACK_LEX_TERMS);
146
+ const lex = (joinBoundedTerms(terms) || joinBoundedTerms(rawTokens) || sliceHeadSafe(request, MAX_FALLBACK_LEX_CHARS)).trim();
147
+ const vecSource = requestTerms.length < 4 && recentUsers.length
148
+ ? `${recentUsers.at(-1).content.trim()}\n${request}`
149
+ : request;
150
+ const vec = (vecSource.length <= MAX_FALLBACK_VEC_CHARS
151
+ ? vecSource
152
+ : request.length >= MAX_FALLBACK_VEC_CHARS
153
+ ? sliceHeadSafe(request, MAX_FALLBACK_VEC_CHARS)
154
+ : sliceTailSafe(vecSource, MAX_FALLBACK_VEC_CHARS)).trim();
155
+ return { lex, vec };
156
+ }
157
+ function clampHeadTail(text, maxChars) {
158
+ if (text.length <= maxChars)
159
+ return text;
160
+ const ellipsis = "\n…\n";
161
+ const half = Math.floor((maxChars - ellipsis.length) / 2);
162
+ return `${sliceHeadSafe(text, half).trimEnd()}${ellipsis}${sliceTailSafe(text, half).trimStart()}`;
163
+ }
164
+ /** Bound conversation context repeated across automatic passage usefulness judgments. */
165
+ export function compactJudgeConversation(conversation) {
166
+ const currentRequest = clampHeadTail(conversation.currentRequest, MAX_JUDGE_CONVERSATION_CHARS);
167
+ let remaining = MAX_JUDGE_CONVERSATION_CHARS - currentRequest.length;
168
+ const history = [];
169
+ for (let index = conversation.history.length - 1; index >= 0 && history.length < MAX_JUDGE_HISTORY_MESSAGES && remaining > 0; index--) {
170
+ const message = conversation.history[index];
171
+ if (message.content.length <= remaining) {
172
+ history.unshift(message);
173
+ remaining -= message.content.length;
174
+ }
175
+ else if (remaining >= MIN_COMPACT_HISTORY_CHARS) {
176
+ history.unshift({ role: message.role, content: clampHeadTail(message.content, remaining) });
177
+ remaining = 0;
178
+ }
179
+ else {
180
+ break;
181
+ }
182
+ }
183
+ return { history, currentRequest };
184
+ }
57
185
  export class QueryApiError extends Error {
58
186
  code;
59
187
  status;
@@ -64,6 +192,11 @@ export class QueryApiError extends Error {
64
192
  this.name = "QueryApiError";
65
193
  }
66
194
  }
195
+ function throwIfQueryAborted(signal) {
196
+ if (abortedByTimeout(signal))
197
+ throw new QueryApiError("timeout");
198
+ signal.throwIfAborted();
199
+ }
67
200
  /** The host owns model warmth/lifecycle; the plugin only sends bounded, cancellable requests. */
68
201
  export class ApiQueryGenerator {
69
202
  config;
@@ -71,30 +204,34 @@ export class ApiQueryGenerator {
71
204
  this.config = config;
72
205
  }
73
206
  async generate(conversation, signal) {
74
- signal = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
75
- signal.throwIfAborted();
207
+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
208
+ throwIfQueryAborted(requestSignal);
76
209
  if (!this.config.apiKeyFile)
77
210
  throw new QueryApiError("credentials");
78
211
  let token;
79
212
  try {
80
- token = (await readFile(this.config.apiKeyFile, { encoding: "utf8", signal })).trim();
213
+ token = (await readFile(this.config.apiKeyFile, { encoding: "utf8", signal: requestSignal })).trim();
81
214
  }
82
215
  catch {
216
+ if (abortedByTimeout(requestSignal))
217
+ throw new QueryApiError("timeout");
83
218
  throw new QueryApiError("credentials");
84
219
  }
85
220
  if (!token || /\s/u.test(token))
86
221
  throw new QueryApiError("credentials");
87
- signal.throwIfAborted();
222
+ throwIfQueryAborted(requestSignal);
88
223
  const id = randomUUID();
89
224
  let response;
90
225
  try {
91
226
  response = await fetch(`${this.config.endpoint}/generate`, {
92
- method: "POST", redirect: "error", signal,
227
+ method: "POST", redirect: "error", signal: requestSignal,
93
228
  headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
94
229
  body: JSON.stringify({ id, conversation }),
95
230
  });
96
231
  }
97
232
  catch {
233
+ if (abortedByTimeout(requestSignal))
234
+ throw new QueryApiError("timeout");
98
235
  throw new QueryApiError("unavailable");
99
236
  }
100
237
  if (!response.ok) {
@@ -109,7 +246,7 @@ export class ApiQueryGenerator {
109
246
  const chunks = [];
110
247
  let size = 0;
111
248
  for (;;) {
112
- const { done, value } = await abortable(reader.read(), signal);
249
+ const { done, value } = await abortable(reader.read(), requestSignal);
113
250
  if (done)
114
251
  break;
115
252
  size += value.byteLength;
@@ -117,7 +254,7 @@ export class ApiQueryGenerator {
117
254
  throw new QueryApiError("invalid_response");
118
255
  chunks.push(value);
119
256
  }
120
- signal.throwIfAborted();
257
+ throwIfQueryAborted(requestSignal);
121
258
  const envelope = record(JSON.parse(Buffer.concat(chunks).toString("utf8")));
122
259
  const result = record(envelope?.response);
123
260
  if (result?.id !== id || typeof result.text !== "string" || result.error !== undefined) {
@@ -125,7 +262,11 @@ export class ApiQueryGenerator {
125
262
  }
126
263
  return parseQueryPair(JSON.parse(result.text));
127
264
  }
128
- catch {
265
+ catch (error) {
266
+ if (error instanceof QueryApiError)
267
+ throw error;
268
+ if (abortedByTimeout(requestSignal))
269
+ throw new QueryApiError("timeout");
129
270
  throw new QueryApiError("invalid_response");
130
271
  }
131
272
  finally {
@@ -1,7 +1,7 @@
1
1
  import { type RetrievalTimings } from "./retrieval-timing.js";
2
2
  type RetrievalOperation = "vector" | "memoryWhisperer" | "memorySearch";
3
3
  type RetrievalOutcome = "ok" | "partial" | "empty" | "failed" | "cancelled" | "timed_out" | "skipped" | "degraded";
4
- declare const fields: readonly ["elapsedMs", "retrievalMs", "judgeMs", "gateMs", "generationMs", "setupMs", "queueWaitMs", "metadataMs", "storeSetupMs", "bm25Ms", "vectorMs", "vectorIndexCheckMs", "vectorScopeMs", "embeddingMs", "vectorScanMs", "hydrationMs", "vectorMappingMs", "vectorOtherMs", "passageMs", "candidatePrepMs", "retrievalOtherMs", "otherMs", "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars", "requestsSucceeded", "requestsFailed", "fallbackKeyUnavailable", "fallbackAllJudgmentsFailed"];
4
+ declare const fields: readonly ["elapsedMs", "retrievalMs", "judgeMs", "generationMs", "setupMs", "queueWaitMs", "metadataMs", "storeSetupMs", "bm25Ms", "vectorMs", "vectorIndexCheckMs", "vectorScopeMs", "embeddingMs", "vectorScanMs", "hydrationMs", "vectorMappingMs", "vectorOtherMs", "passageMs", "candidatePrepMs", "retrievalOtherMs", "otherMs", "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars", "requestsSucceeded", "requestsFailed", "fallbackKeyUnavailable", "fallbackAllJudgmentsFailed"];
5
5
  type Field = typeof fields[number];
6
6
  export type RetrievalObservation = {
7
7
  outcome: RetrievalOutcome;
@@ -47,11 +47,10 @@ export declare class RetrievalTelemetry {
47
47
  otherMs?: number | undefined;
48
48
  retrievalMs?: number | undefined;
49
49
  judgeMs?: number | undefined;
50
+ generationMs?: number | undefined;
50
51
  metadataReloads?: number | undefined;
51
52
  vectorScanAttempts?: number | undefined;
52
53
  elapsedMs?: number | undefined;
53
- gateMs?: number | undefined;
54
- generationMs?: number | undefined;
55
54
  candidates?: number | undefined;
56
55
  eligible?: number | undefined;
57
56
  results?: number | undefined;
@@ -1,5 +1,5 @@
1
1
  import { timingFields } from "./retrieval-timing.js";
2
- const fields = ["elapsedMs", "retrievalMs", "judgeMs", "gateMs", "generationMs", ...timingFields,
2
+ const fields = ["elapsedMs", "retrievalMs", "judgeMs", "generationMs", ...timingFields,
3
3
  "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars",
4
4
  "requestsSucceeded", "requestsFailed", "fallbackKeyUnavailable", "fallbackAllJudgmentsFailed"];
5
5
  const recentLimit = 256;
@@ -1,6 +1,6 @@
1
1
  import type { VectorSearchTrace } from "@unblocklabs/qmd";
2
2
  export declare const timingFields: readonly ["setupMs", "queueWaitMs", "metadataMs", "storeSetupMs", "bm25Ms", "vectorMs", "vectorIndexCheckMs", "vectorScopeMs", "embeddingMs", "vectorScanMs", "hydrationMs", "vectorMappingMs", "vectorOtherMs", "passageMs", "candidatePrepMs", "retrievalOtherMs", "otherMs"];
3
- type TimingField = typeof timingFields[number] | "retrievalMs" | "judgeMs";
3
+ type TimingField = typeof timingFields[number] | "retrievalMs" | "judgeMs" | "generationMs";
4
4
  export type RetrievalTimings = Partial<Record<TimingField | "metadataReloads" | "vectorScanAttempts", number>>;
5
5
  /** Freeze in-flight duration at abort, without changing the work's cancellation behavior. */
6
6
  export declare function startTiming(field: TimingField, timings?: RetrievalTimings, signal?: AbortSignal): () => void;
@@ -15,7 +15,7 @@ settings; a rotated credential file is reread without a restart.
15
15
  | `memory_search` | Installed/enabled memory slot; configured corpora | Local retrieval-ranked leads with degraded warning | Successful judged siblings returned with a partial warning; total judging failure or unreadable key uses local retrieval fallback |
16
16
  | `memory_get` | Installed/enabled memory slot; configured corpora | Unchanged local indexed reads | Unchanged; its own indexing errors still matter |
17
17
  | Skill Whisperer | `skillWhisperer.enabled`, skills corpus, host hooks | Best local vector candidate meeting `minScore` | Exclude failed candidates; successful siblings may qualify; no vector fallback |
18
- | Memory Whisperer | `memoryWhisperer.enabled`, explicit approved corpora, host hooks | No hints | Exclude failed candidates; recall/deadline failures still suppress the turn |
18
+ | Memory Whisperer | `memoryWhisperer.enabled`, explicit approved corpora, host hooks | No hints | Exclude failed candidates; deadline failures still suppress the turn; query-API failures fall back to deterministic local queries before TypeSafe judging |
19
19
  | Complementary hints | Enabled Memory Whisperer + `complementaryHints` | No additional judgment; base hints also require a key | Keep baseline hints unless the total deadline expires |
20
20
  | Safety Whisperer | `safetyWhisperer.enabled`, at least one scenario, host hooks (conversation access and prompt injection) | Could not check: the turn proceeds without safety prompts (fails open) | Fails open; recorded as could-not-check, never as no match |
21
21
  | People store/tools | `people.enabled` | Available; automatic save review needs primer/key or verified manual alternative | Storage/inspection still available |
@@ -42,7 +42,7 @@ All plugin TypeSafe features use `plugins.entries.unblock-memory.config.typesafe
42
42
 
43
43
  Candidate scoring uses **one HTTP request per candidate**, with ranking done in code.
44
44
  Related questions about the same candidate can share a request (for example, quality
45
- noise and evidence). Memory Whisperer launches all eligible candidate requests together;
45
+ noise and evidence). Memory Whisperer launches up to six top fused eligible candidate requests together;
46
46
  the shared account's request/token limits still apply across simultaneous conversations
47
47
  and nodes. There is no automatic retry in the latency-sensitive whisperers.
48
48
 
@@ -228,10 +228,10 @@ contract; these tables explain their effects.
228
228
  | `memoryWhisperer.enabled` | `false` | Requires explicit approved non-skill corpora, TypeSafe key and host hooks |
229
229
  | `memoryWhisperer.corpora` | `[]` | Explicit known corpus names; required nonempty when enabled; no `all` or skills |
230
230
  | `memoryWhisperer.api.endpoint` | `http://192.168.1.191:18087` | Resident V2 query-model API base URL. Override with `http://127.0.0.1:18087` for a node hosting its own API (e.g. Theo). |
231
- | `memoryWhisperer.api.apiKeyFile` | unset | Absolute path to a file containing the API bearer token. Missing credentials/API failure skips the hint; no local-model fallback. |
231
+ | `memoryWhisperer.api.apiKeyFile` | unset | Absolute path to a file containing the API bearer token. Missing credentials, timeouts, or API failures fall back to deterministic local queries before TypeSafe judging. |
232
232
  | `memoryWhisperer.mlx` | unset | Deprecated: old absolute `{pythonPath, modelPath}` values are accepted but ignored for upgrade compatibility. Remove after configuring `api`. |
233
- | `memoryWhisperer.minUsefulness` | `0.7` | 0–1, minimum Noul yes-probability per candidate; explicit overrides are preserved |
234
- | `memoryWhisperer.maxHints` | `2` | 1–2 |
233
+ | `memoryWhisperer.minUsefulness` | `0.5` | 0–1, minimum Noul yes-probability per candidate; explicit overrides are preserved |
234
+ | `memoryWhisperer.maxHints` | `3` | 1–3 |
235
235
  | `memoryWhisperer.cooldownTurns` | `10` | 0–1,000; recently injected evidence |
236
236
  | `memoryWhisperer.timeoutMs` | `3000` | 1–10,000 total whisper deadline, not just the provider timeout |
237
237
  | `memoryWhisperer.complementaryHints` | `false` | Optional extra redundancy judgment; does not expand retrieval or enable the feature |
@@ -381,7 +381,7 @@ boundary, not multi-tenant authorization. Approve sources for the agent's audien
381
381
  | Feature | Evidence sent when explicitly enabled/approved |
382
382
  | --- | --- |
383
383
  | Skill selection | Bounded visible current/recent conversation + shortlisted skill names/descriptions; not skill procedures or source-path fields |
384
- | Memory hints | Same 8,192-token/24,000-byte visible conversation as training goes to the configured query API and recall gate; one complete excerpt (up to 1,200 characters), corpus/source path, represented-message timestamps and evaluation time per passage judgment. V2 retrieves at most 10 BM25 + 10 vector candidates across the approved scope. All indexed sessions in approved corpora are eligible; `chatTypes` controls DMs. |
384
+ | Memory hints | Same 8,192-token/24,000-byte visible conversation as training goes to the configured query API (when available); TypeSafe passage judging receives the compacted conversation (current request plus at most two prior visible messages, bounded to 1,500 characters) plus one complete excerpt (up to 1,200 characters), corpus/source path, represented-message timestamps and evaluation time per candidate, capped at the top 6 RRF-fused eligible passages from at most 10 BM25 + 10 vector candidates across the approved scope. All indexed sessions in approved corpora are eligible; `chatTypes` controls DMs. |
385
385
  | Complementarity | Up to 4 already-qualified excerpts for pairwise redundancy checks |
386
386
  | People primer | Person identity, agent name, approved retrieved excerpts and source/session metadata; all indexed sessions eligible if approved, not just the current chat |
387
387
  | Dossier save/draft review | Proposed blurb, person/agent names and 1–3 exact approved indexed evidence ranges, at most 6,000 characters total; existing dossier is not evidence |
package/docs/retrieval.md CHANGED
@@ -23,12 +23,12 @@ Example tool input (the `memory` corpus exists by default):
23
23
  Results use compact JSON and carry `path`, `startLine`, `endLine`, `snippet`,
24
24
  `corpus`, and a `score`. With `rankingMode: "typesafe_usefulness"`, this is a
25
25
  usefulness probability rounded to hundredths; ranking and threshold filtering
26
- still use full precision. With `rankingMode: "retrieval"`, the original QMD
27
- per-lane reciprocal-rank score is preserved without rounding, then sorted highest
28
- first (discovery order breaks ties); this is not a probability or fused RRF score.
29
- Discovery is a lexical-first union, so sorting prevents vector-only top matches
30
- from being buried below the lexical lane before `maxResults` truncation. A hit
31
- found in both lanes retains its first-discovered score; lane scores are not summed.
26
+ still use full precision. With `rankingMode: "retrieval"`, passage-level
27
+ reciprocal rank fusion (RRF, `k = 60`, with QMD's top-rank bonuses) scores
28
+ across the BM25 and vector lanes are preserved without rounding and sorted
29
+ highest first (discovery order breaks ties); this is not a usefulness
30
+ probability. Dual-lane matches combine their per-lane RRF contributions while
31
+ rank-1 single-lane hits remain competitive before `maxResults` truncation.
32
32
  `scoreMeaning` and `minUsefulnessApplied` identify the score contract explicitly.
33
33
  The constant `source` and top-level `provider`
34
34
  fields are omitted; `path` plus line numbers replace the redundant `citation`.
@@ -121,8 +121,8 @@ Both `memorySearch` and `memoryWhisperer` also report per-call stage measurement
121
121
  - `passageMs`: rendering merged candidates; `candidatePrepMs`: eligibility checks and deduplication
122
122
  before disclosure to TypeSafe. `judgeMs` covers the concurrent candidate judgments, not their sum.
123
123
  - `vectorOtherMs` and `retrievalOtherMs` expose time outside measured child stages. `otherMs` accounts
124
- for the remaining manual tool execution. Whisperer stages overlap, so no additive whole-run
125
- residual is reported for it. Parent durations must not be added to their child durations.
124
+ for the remaining manual tool execution; Whisperer tracks individual stage timings without a
125
+ separate whole-run residual. Parent durations must not be added to their child durations.
126
126
 
127
127
  Each measurement includes lifetime totals/sample counts and p50/p95 over up to 256 recent calls.
128
128
  `slowestRecent` contains the five slowest calls **within that same window**, each with its outcome
@@ -309,8 +309,8 @@ or `memory_get`. Enable it in the plugin config with an explicit corpus allowlis
309
309
  "memoryWhisperer": {
310
310
  "enabled": true,
311
311
  "corpora": ["knowledge"],
312
- "minUsefulness": 0.7,
313
- "maxHints": 2,
312
+ "minUsefulness": 0.5,
313
+ "maxHints": 3,
314
314
  "cooldownTurns": 10,
315
315
  "timeoutMs": 3000
316
316
  }
@@ -330,41 +330,40 @@ indexing/sync schedule.
330
330
  The example is a plugin config fragment; `knowledge` must already be configured.
331
331
  For a complete corpus example, use the [configuration profiles](configuration.md#example-profiles).
332
332
 
333
- The initial TypeSafe recall gate is instructed to reject requests constrained to a
334
- specific date or time window (for example, "what did we talk about 13 days ago?").
335
- Whisperer's QMD retrieval has no date filters, so topic relevance cannot establish
336
- that an excerpt belongs to the requested period. Incidental dates, such as a future
337
- deadline on a topic-based request, do not trigger this exclusion. The gate is shared
338
- with offline training; this policy is versioned as `historical-recall-v2`.
339
-
340
- Using the configured V2 query API, QMD searches its independent `lex` and `vec` queries
341
- through BM25 and vectors respectively, retrieving ten candidates per backend across
342
- the complete approved collection scope (not ten per collection). The lexical adapter
333
+ Memory Whisperer runs directly on user turns without a pre-retrieval recall-gate
334
+ classifier (the `historical-recall-v2` gate remains offline-training-only in
335
+ `memory-training`). Using the configured V2 query API — or deterministic local
336
+ `lex`/`vec` query extraction if the query API fails, times out, or has no
337
+ credentials — QMD searches its independent `lex` and `vec` queries through BM25
338
+ and vectors respectively, retrieving ten candidates per backend across the
339
+ complete approved collection scope (not ten per collection) and fusing them via
340
+ passage-level RRF (`k = 60`, with QMD top-rank bonuses). The lexical adapter
343
341
  uses literal OR keywords; quotation marks do not enable exact-phrase matching.
344
- API or generated-output failures skip the hint; there is no direct-vector fallback.
345
- After query generation Whisperer uses the same discovery, deduplication and
346
- ranking core as `memory_search`, but judges against the bounded conversation
347
- rather than the explicit tool's semantic query alone. TypeSafe evaluates one independent
348
- Noul question per candidate in its own concurrent HTTP request: would a careful
349
- assistant use a specific factual detail from the excerpt when answering the current
350
- request? Partial answers and concrete leads count; repeated facts, topic/name matches
351
- without answer content, unrelated details, and unsupported speculation do not.
342
+ After deduplication and cooldown filtering, Whisperer sends at most the top **six**
343
+ fused candidates to TypeSafe, paired with a compact conversation context (the
344
+ current request plus at most the last two visible messages, bounded to 1,500
345
+ characters). TypeSafe evaluates one independent Noul question per candidate in
346
+ its own concurrent HTTP request: would a careful assistant use a specific factual
347
+ detail from the excerpt when answering the current request? Partial answers and
348
+ concrete leads count; repeated facts, topic/name matches without answer content,
349
+ unrelated details, and unsupported speculation do not.
352
350
  This is the sole versioned Memory Whisperer usefulness prompt, shared by runtime
353
351
  and offline training. Generated queries, ranks, retrieval scores, and other candidates
354
352
  are never included in the passage judge's state.
355
- `minUsefulness` defaults to `0.7` and
353
+ `minUsefulness` defaults to `0.5` and
356
354
  thresholds the probability of yes, not a calibrated guarantee of accuracy.
357
355
  Explicit configured thresholds are preserved. Evaluate it on your own conversations.
358
356
 
359
- **Privacy and budgets:** training and runtime prepare the same visible conversation:
360
- at most 8,192 pinned-LFM tokens and 24,000 UTF-8 bytes after serialization. The whole
357
+ **Privacy and budgets:** query generation prepares the visible conversation up to
358
+ 8,192 pinned-LFM tokens and 24,000 UTF-8 bytes after serialization. The whole
361
359
  current request and most recent whole messages are retained; an oversized current
362
- request skips automatic memory before query generation or the TypeSafe recall gate.
360
+ request skips automatic memory before query generation or retrieval.
363
361
  Diagnostics count `input_too_large`; completed logs report `outcome: "skipped"` and
364
- `reason: "input_too_large"`, without recording the input. The judge receives that
365
- conversation plus one complete 1,200-character excerpt, its corpus/source path, all represented message timestamps,
366
- and the request's evaluation time per HTTP request. A v2 query pair can therefore
367
- produce up to twenty passage requests before deduplication and eligibility filtering.
362
+ `reason: "input_too_large"`, without recording the input. Each TypeSafe usefulness
363
+ request receives the compacted conversation (at most 1,500 characters across the
364
+ current request and up to two prior visible messages) plus one complete
365
+ 1,200-character excerpt, its corpus/source path, all represented message timestamps,
366
+ and the request's evaluation time, capped at six candidate requests per turn.
368
367
  Dates record when source messages were said, without inferring event dates.
369
368
  Session excerpts retain a complete turn or message when it fits,
370
369
  otherwise the complete matched chunk. Chunks exceeding the excerpt budget are
@@ -376,9 +375,9 @@ already have compacted the available context. System messages, thinking blocks,
376
375
  images, and tool-result messages are omitted;
377
376
  anything quoted in ordinary user/assistant text can still be transmitted.
378
377
 
379
- At most two qualifying excerpts are appended after the current user prompt via
380
- `appendContext`, as a JSON array inside `<memory>` tags within one `<unblock_memory>`
381
- block. Each entry contains
378
+ At most three qualifying excerpts (default `maxHints: 3`, configurable `1–3`) are
379
+ appended after the current user prompt via `appendContext`, as a JSON array inside
380
+ `<memory>` tags within one `<unblock_memory>` block. Each entry contains
382
381
  only `source` (the QMD path), `lines` (for example, `27-30`), and `body` (the verbatim
383
382
  excerpt). No instruction paragraph or required `memory_get` call is
384
383
  added. This is still part of the same user message, not a separate message.
@@ -387,7 +386,10 @@ and overlapping source lines; recently injected content has a ten-user-turn cool
387
386
  by default. Cooldown state is in memory and resets on session end or Gateway restart.
388
387
  Memory and Skill Whisperer reuse their result when the host rebuilds the same run's
389
388
  prompt, without repeating retrieval or advancing cooldown.
390
- The complete hint payload is capped at 5,000 characters plus the wrapper tags.
389
+ The complete hint payload is capped at 5,000 characters plus the wrapper tags;
390
+ when multiple selected hints exceed that limit after JSON escaping, Memory
391
+ Whisperer emits the highest-ranked complete hints that fit rather than slicing
392
+ excerpts or dropping everything, and only records cooldown for emitted hints.
391
393
 
392
394
  All whisperer contributions share that appended block, in this order: `<memory>`,
393
395
  `<skill>`, then `<people>` when People Whisperer has an eligible blurb. Empty sections
@@ -441,56 +443,59 @@ between that private worker protocol and the HTTP API below.
441
443
  `POST /generate` accepts `{id, conversation: {history, currentRequest}}` and returns
442
444
  `{response: {id, text}}`, where `text` is JSON with exactly two nonempty strings,
443
445
  `lex` and `vec`. The request ID must match. Redirects, malformed/oversized responses,
444
- missing credentials and HTTP failures skip hints; no retries or local fallback.
446
+ missing credentials, timeouts (capped at half the whisperer deadline, up to 1.5s),
447
+ and HTTP failures log `generation_fallback` and fall back to deterministic local
448
+ `lex`/`vec` extraction rather than aborting retrieval; all fallback hits still pass
449
+ through TypeSafe usefulness judging.
445
450
  Turn cancellation aborts HTTP and prevents late hints; already-running server-side
446
451
  generation may finish independently. Gateway shutdown does not stop the shared API.
447
452
  Old `mlx` config is accepted but ignored; remove it after migrating.
448
453
 
449
- Two branches start together: TypeSafe's historical-recall judgment and API
450
- generation requesting exactly one `{"lex":"keywords","vec":"semantic query"}` object.
451
- Generation uses visible user/assistant text,
452
- the exact model prompt/template, greedy decoding and a 256-token output ceiling.
453
- It keeps the whole current request, drops oldest whole history messages to fit a
454
- shared 8,192-token and 24,000-byte input budgets, and excludes oversized/ambiguous
455
- inputs. The old fixed `historyMessages` limit is not used by memory input preparation.
454
+ Query generation requests one `{"lex":"keywords","vec":"semantic query"}` object
455
+ using visible user/assistant text, the exact model prompt/template, greedy decoding,
456
+ and a 256-token output ceiling. It keeps the whole current request, drops oldest
457
+ whole history messages to fit the shared 8,192-token and 24,000-byte input budgets,
458
+ and excludes oversized/ambiguous inputs. The old fixed `historyMessages` limit is
459
+ not used by memory input preparation.
456
460
 
457
461
  The `lex` query retrieves ten BM25 matches and `vec` retrieves ten vector matches
458
- across the approved scope. All unique eligible passages proceed to the shared usefulness
459
- judge, with one HTTP request per passage, all launched together, without a merged
460
- passage-count cap or groups of eight. Each request contains the original conversation
461
- and only its own passage. Successful judgments remain eligible if another
462
+ across the approved scope, then fuses them with passage-level RRF (`k = 60` plus
463
+ QMD top-rank bonuses). After deduplication and cooldown filtering, up to the top
464
+ **six** fused passages proceed to the shared usefulness judge, with one HTTP request
465
+ per passage launched concurrently. Each request contains the compacted conversation
466
+ (up to 1,500 characters across the current request and at most two prior visible
467
+ messages) and only its own passage. Successful judgments remain eligible if another
462
468
  request times out, fails HTTP/network delivery, or returns invalid answers. Scores
463
469
  stay paired with their original passages; failed candidates are excluded, not scored
464
- as zero. If all requests fail, nothing is injected. Recall approval, the total
465
- deadline, and session cancellation still apply to every result. No retries are
466
- added to the latency-sensitive hook.
467
- The 1,200-character complete-excerpt limit, corpus checks, citations, cooldown and
468
- two-hint/5,000-character injection budget still apply. The judge sees only the
469
- original conversation and passages, never generated queries or retrieval scores.
470
- This can send more passages to TypeSafe than the legacy eight-candidate path.
471
-
472
- Recall probability below 0.7 discards/cancels the speculative branch immediately;
473
- no results are used until recall is approved. A recall error also emits no hint.
470
+ as zero. If all requests fail, nothing is injected. The total deadline and session
471
+ cancellation still apply to every result. No retries are added to the
472
+ latency-sensitive hook.
473
+ The 1,200-character complete-excerpt limit, corpus checks, citations, cooldown, and
474
+ three-hint/5,000-character complete-hint packing budget still apply. The judge sees
475
+ only the compacted conversation and passages, never generated queries or retrieval
476
+ scores.
477
+
474
478
  Query output requires exactly the two nonempty string fields `lex` and `vec`;
475
- surrounding whitespace is trimmed. Old query arrays are not accepted. Unparseable or
476
- unavailable v2 output skips automatic memory for that turn rather than switching to
477
- untrained queries. Successful output still requires recall approval and passage judgments.
478
- Nothing changes in manual `memory_search`. The default total deadline remains
479
- three seconds; measure the full path before choosing a larger explicit budget.
479
+ surrounding whitespace is trimmed. Old query arrays are not accepted. Unparseable,
480
+ timed-out, or unavailable v2 output falls back to deterministic local `lex`/`vec`
481
+ queries for that turn and still requires TypeSafe passage judgments.
482
+ Nothing changes in manual `memory_search` beyond passage-level RRF scoring in
483
+ shared candidate discovery. The default total deadline remains three seconds;
484
+ measure the full path before choosing a larger explicit budget.
480
485
  Already-running native retrieval may finish after cancellation, but cannot inject.
481
486
 
482
- Diagnostics distinguish `queries_generated`, `failed`,
483
- `recall_not_needed`, and `judge_candidate_failed`. Gateway logs prefixed
487
+ Diagnostics distinguish `queries_generated`, `generation_fallback`, `failed`,
488
+ and `judge_candidate_failed`. Gateway logs prefixed
484
489
  `unblock-memory memory_whisperer` contain structured JSON with agent/run/session
485
490
  IDs, candidate index, elapsed time, request timeout, and safe
486
491
  failure codes (`timeout`, `cancelled`, `http_error`, `network_error`,
487
- `invalid_response`; HTTP failures include the status). Unexpected local errors
488
- identify the failed stage without dumping the exception. A single completion
489
- record per run includes its outcome/reason, available stage timings, recall
490
- probability, query/candidate counts, `requestsSucceeded`/`requestsFailed`, partial-result
491
- flag, and emitted hint count. Prompt rebuilds reuse the result without duplicate
492
- logs. Logs never include queries, prompts, excerpts, credentials, provider bodies,
493
- or raw exceptions; exact query text is not retained by this telemetry.
492
+ `invalid_response`, `credentials`, `unavailable`; HTTP failures include the status).
493
+ Unexpected local errors identify the failed stage without dumping the exception.
494
+ A single completion record per run includes its outcome/reason, available stage
495
+ timings, query/candidate counts, `queryFallback` flag, `requestsSucceeded`/`requestsFailed`,
496
+ partial-result flag, and emitted hint count. Prompt rebuilds reuse the result without
497
+ duplicate logs. Logs never include queries, prompts, excerpts, credentials, provider
498
+ bodies, or raw exceptions; exact query text is not retained by this telemetry.
494
499
 
495
500
  ## Skill Whisperer
496
501
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "unblock-memory",
3
3
  "name": "Unblock Memory",
4
- "version": "0.12.0",
4
+ "version": "0.12.2",
5
5
  "description": "Indexes, retrieves, and analyzes configured workspace memory with existing QMD vectors.",
6
6
  "kind": "memory",
7
7
  "activation": { "onStartup": true },
@@ -91,7 +91,7 @@
91
91
  },
92
92
  "memoryWhisperer.enabled": {
93
93
  "label": "Memory Whisperer",
94
- "help": "Append up to two TypeSafe-approved historical excerpts after the user prompt. Requires explicit corpora, TypeSafe and query API credentials, and hook conversation access. Disabled by default."
94
+ "help": "Append up to three TypeSafe-approved historical excerpts after the user prompt. Requires explicit corpora, TypeSafe credentials, and hook conversation access. Disabled by default."
95
95
  },
96
96
  "memoryWhisperer.corpora": {
97
97
  "label": "Approved Hint Corpora",
@@ -350,7 +350,7 @@
350
350
  "description": "Authenticated resident query-model API. Override endpoint with a loopback URL for nodes outside the Studio LAN.",
351
351
  "properties": {
352
352
  "endpoint": { "type": "string", "pattern": "^https?://", "default": "http://192.168.1.191:18087" },
353
- "apiKeyFile": { "type": "string", "pattern": "^/", "description": "Absolute path to the API bearer token file; required to generate queries." }
353
+ "apiKeyFile": { "type": "string", "pattern": "^/", "description": "Absolute path to the API bearer token file. When unset or unreadable, Memory Whisperer falls back to deterministic local queries." }
354
354
  },
355
355
  "default": { "endpoint": "http://192.168.1.191:18087" }
356
356
  },
@@ -366,14 +366,14 @@
366
366
  "complementaryHints": { "type": "boolean", "default": false, "description": "Optionally remove confidently redundant hints with up to six concurrent TypeSafe requests, one per directional pair. Uncertainty retains hints." },
367
367
  "enabled": { "type": "boolean", "default": false },
368
368
  "corpora": { "type": "array", "items": { "type": "string", "pattern": "\\S" }, "default": [] },
369
- "minUsefulness": { "type": "number", "minimum": 0, "maximum": 1, "default": 0.7 },
370
- "maxHints": { "type": "integer", "minimum": 1, "maximum": 2, "default": 2 },
369
+ "minUsefulness": { "type": "number", "minimum": 0, "maximum": 1, "default": 0.5 },
370
+ "maxHints": { "type": "integer", "minimum": 1, "maximum": 3, "default": 3 },
371
371
  "cooldownTurns": { "type": "integer", "minimum": 0, "maximum": 1000, "default": 10 },
372
372
  "timeoutMs": { "type": "integer", "minimum": 1, "maximum": 10000, "default": 3000 }
373
373
  },
374
374
  "default": {
375
- "enabled": false, "corpora": [], "minUsefulness": 0.7,
376
- "maxHints": 2, "cooldownTurns": 10, "timeoutMs": 3000,
375
+ "enabled": false, "corpora": [], "minUsefulness": 0.5,
376
+ "maxHints": 3, "cooldownTurns": 10, "timeoutMs": 3000,
377
377
  "api": { "endpoint": "http://192.168.1.191:18087" }
378
378
  }
379
379
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unblocklabs/unblock-memory",
3
- "version": "0.12.0",
3
+ "version": "0.12.2",
4
4
  "description": "Workspace-native memory for OpenClaw, powered by QMD",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@huggingface/tokenizers": "0.2.0",
54
- "@unblocklabs/qmd": "3.0.2",
54
+ "@unblocklabs/qmd": "3.0.4",
55
55
  "chokidar": "5.0.0",
56
56
  "js-tiktoken": "1.0.21",
57
57
  "picomatch": "^4.0.5",