@openviking/openclaw-plugin 2026.5.26 → 2026.6.17-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/INSTALL-AGENT.md +355 -355
  2. package/INSTALL-ZH.md +405 -345
  3. package/INSTALL.md +366 -362
  4. package/README.md +364 -338
  5. package/adapters/http-transport.ts +3 -0
  6. package/adapters/resource-packager.ts +141 -0
  7. package/auto-recall.ts +518 -257
  8. package/client.ts +963 -939
  9. package/commands/setup.ts +1169 -1002
  10. package/config/feature-gates.json +10 -0
  11. package/config.ts +819 -476
  12. package/context-engine.ts +408 -1737
  13. package/dist/adapters/http-transport.js +1 -0
  14. package/dist/adapters/resource-packager.js +114 -0
  15. package/dist/auto-recall.js +228 -32
  16. package/dist/client.js +125 -161
  17. package/dist/commands/setup.js +170 -32
  18. package/dist/config.js +285 -64
  19. package/dist/context-engine.js +64 -1179
  20. package/dist/index.js +209 -1470
  21. package/dist/memory-ranking.js +35 -12
  22. package/dist/plugin/command-registration.js +5 -0
  23. package/dist/plugin/openviking-archive-tools.js +210 -0
  24. package/dist/plugin/openviking-bypass-runtime.js +8 -0
  25. package/dist/plugin/openviking-client-runtime.js +28 -0
  26. package/dist/plugin/openviking-command-args.js +146 -0
  27. package/dist/plugin/openviking-command-definitions.js +206 -0
  28. package/dist/plugin/openviking-context-engine-ref.js +11 -0
  29. package/dist/plugin/openviking-context-engine-registration.js +23 -0
  30. package/dist/plugin/openviking-feature-gates.js +250 -0
  31. package/dist/plugin/openviking-import-runtime.js +50 -0
  32. package/dist/plugin/openviking-import-tools.js +86 -0
  33. package/dist/plugin/openviking-lifecycle-hooks.js +33 -0
  34. package/dist/plugin/openviking-memory-recall-tools.js +233 -0
  35. package/dist/plugin/openviking-memory-tools.js +199 -0
  36. package/dist/plugin/openviking-query-config-command.js +203 -0
  37. package/dist/plugin/openviking-query-runtime.js +367 -0
  38. package/dist/plugin/openviking-query-tools.js +91 -0
  39. package/dist/plugin/openviking-recall-trace-runtime.js +387 -0
  40. package/dist/plugin/openviking-recall-trace-tools.js +38 -0
  41. package/dist/plugin/openviking-runtime-state.js +26 -0
  42. package/dist/plugin/openviking-runtime-utils.js +62 -0
  43. package/dist/plugin/openviking-services.js +20 -0
  44. package/dist/plugin/openviking-session-routing-runtime.js +61 -0
  45. package/dist/plugin/openviking-tool-result-tools.js +268 -0
  46. package/dist/plugin/recall-trace-routes.js +77 -0
  47. package/dist/plugin/tool-registration.js +23 -0
  48. package/dist/process-manager.js +5 -17
  49. package/dist/query-config.js +336 -0
  50. package/dist/recall-trace.js +309 -0
  51. package/dist/registries/recall-resource-types.js +58 -0
  52. package/dist/routing/identity-routing.js +152 -0
  53. package/dist/routing/memory-uri.js +7 -0
  54. package/dist/services/context-lifecycle-service.js +847 -0
  55. package/dist/services/context-message-adapter.js +340 -0
  56. package/dist/session-transcript-repair.js +0 -1
  57. package/dist/text-utils.js +14 -31
  58. package/dist/token-estimator.js +51 -0
  59. package/index.ts +408 -1985
  60. package/install-manifest.json +57 -47
  61. package/memory-ranking.ts +303 -267
  62. package/openclaw.plugin.json +497 -335
  63. package/package.json +86 -76
  64. package/plugin/command-registration.ts +34 -0
  65. package/plugin/openviking-archive-tools.ts +301 -0
  66. package/plugin/openviking-bypass-runtime.ts +26 -0
  67. package/plugin/openviking-client-runtime.ts +74 -0
  68. package/plugin/openviking-command-args.ts +187 -0
  69. package/plugin/openviking-command-definitions.ts +294 -0
  70. package/plugin/openviking-context-engine-ref.ts +16 -0
  71. package/plugin/openviking-context-engine-registration.ts +97 -0
  72. package/plugin/openviking-feature-gates.ts +335 -0
  73. package/plugin/openviking-import-runtime.ts +105 -0
  74. package/plugin/openviking-import-tools.ts +133 -0
  75. package/plugin/openviking-lifecycle-hooks.ts +65 -0
  76. package/plugin/openviking-memory-recall-tools.ts +368 -0
  77. package/plugin/openviking-memory-tools.ts +299 -0
  78. package/plugin/openviking-query-config-command.ts +230 -0
  79. package/plugin/openviking-query-formatters.ts +108 -0
  80. package/plugin/openviking-query-runtime.ts +476 -0
  81. package/plugin/openviking-query-tools.ts +161 -0
  82. package/plugin/openviking-recall-trace-runtime.ts +482 -0
  83. package/plugin/openviking-recall-trace-tools.ts +99 -0
  84. package/plugin/openviking-runtime-state.ts +52 -0
  85. package/plugin/openviking-runtime-utils.ts +67 -0
  86. package/plugin/openviking-services.ts +49 -0
  87. package/plugin/openviking-session-routing-runtime.ts +105 -0
  88. package/plugin/openviking-tool-result-tools.ts +397 -0
  89. package/plugin/recall-trace-routes.ts +133 -0
  90. package/plugin/tool-registration.ts +51 -0
  91. package/process-manager.ts +41 -45
  92. package/query-config.ts +400 -0
  93. package/recall-trace.ts +442 -0
  94. package/registries/openviking-tools.ts +84 -0
  95. package/registries/recall-resource-types.ts +74 -0
  96. package/routing/identity-routing.ts +210 -0
  97. package/routing/memory-uri.ts +8 -0
  98. package/runtime-utils.ts +5 -5
  99. package/services/context-lifecycle-service.ts +1209 -0
  100. package/services/context-message-adapter.ts +375 -0
  101. package/services/setup/config-writer.ts +125 -0
  102. package/services/setup/exit-utils.ts +5 -0
  103. package/services/setup/package-metadata.ts +56 -0
  104. package/services/setup/probe-service.ts +143 -0
  105. package/services/setup/setup-flow.ts +306 -0
  106. package/services/setup/version-compatibility.ts +41 -0
  107. package/session-transcript-repair.ts +528 -530
  108. package/skills/install-openviking-memory/SKILL.md +752 -665
  109. package/skills/openviking-context-database/SKILL.md +286 -0
  110. package/text-utils.ts +488 -507
  111. package/token-estimator.ts +65 -0
  112. package/tool-call-id.ts +331 -331
package/memory-ranking.ts CHANGED
@@ -1,267 +1,303 @@
1
- import type { FindResultItem } from "./client.js";
2
-
3
- export function clampScore(value: number | undefined): number {
4
- if (typeof value !== "number" || Number.isNaN(value)) {
5
- return 0;
6
- }
7
- return Math.max(0, Math.min(1, value));
8
- }
9
-
10
- function normalizeDedupeText(text: string): string {
11
- return text.toLowerCase().replace(/\s+/g, " ").trim();
12
- }
13
-
14
- function isEventOrCaseMemory(item: FindResultItem): boolean {
15
- const category = (item.category ?? "").toLowerCase();
16
- const uri = item.uri.toLowerCase();
17
- return (
18
- category === "events" ||
19
- category === "cases" ||
20
- uri.includes("/events/") ||
21
- uri.includes("/cases/")
22
- );
23
- }
24
-
25
- function getMemoryDedupeKey(item: FindResultItem): string {
26
- const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");
27
- const category = (item.category ?? "").toLowerCase() || "unknown";
28
- if (abstract && !isEventOrCaseMemory(item)) {
29
- return `abstract:${category}:${abstract}`;
30
- }
31
- return `uri:${item.uri}`;
32
- }
33
-
34
- export function postProcessMemories(
35
- items: FindResultItem[],
36
- options: {
37
- limit: number;
38
- scoreThreshold: number;
39
- leafOnly?: boolean;
40
- },
41
- ): FindResultItem[] {
42
- const deduped: FindResultItem[] = [];
43
- const seen = new Set<string>();
44
- const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));
45
- for (const item of sorted) {
46
- if (options.leafOnly && item.level !== 2) {
47
- continue;
48
- }
49
- if (clampScore(item.score) < options.scoreThreshold) {
50
- continue;
51
- }
52
- const key = getMemoryDedupeKey(item);
53
- if (seen.has(key)) {
54
- continue;
55
- }
56
- seen.add(key);
57
- deduped.push(item);
58
- if (deduped.length >= options.limit) {
59
- break;
60
- }
61
- }
62
- return deduped;
63
- }
64
-
65
- export function formatMemoryLines(items: FindResultItem[]): string {
66
- return items
67
- .map((item, index) => {
68
- const score = clampScore(item.score);
69
- const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;
70
- const category = item.category ?? "memory";
71
- return `${index + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;
72
- })
73
- .join("\n");
74
- }
75
-
76
- export function trimForLog(value: string, limit = 260): string {
77
- const normalized = value.trim();
78
- if (normalized.length <= limit) {
79
- return normalized;
80
- }
81
- return `${normalized.slice(0, limit)}...`;
82
- }
83
-
84
- export function toJsonLog(value: unknown, maxLen = 6000): string {
85
- try {
86
- const json = JSON.stringify(value);
87
- if (json.length <= maxLen) {
88
- return json;
89
- }
90
- return JSON.stringify({
91
- truncated: true,
92
- length: json.length,
93
- preview: `${json.slice(0, maxLen)}...`,
94
- });
95
- } catch {
96
- return JSON.stringify({ error: "stringify_failed" });
97
- }
98
- }
99
-
100
- export function summarizeInjectionMemories(items: FindResultItem[]): Array<Record<string, unknown>> {
101
- return items.map((item) => ({
102
- uri: item.uri,
103
- category: item.category ?? null,
104
- abstract: trimForLog(item.abstract?.trim() || item.overview?.trim() || item.uri, 180),
105
- score: clampScore(item.score),
106
- is_leaf: item.level === 2,
107
- }));
108
- }
109
-
110
- export function summarizeExtractedMemories(
111
- items: Array<Record<string, unknown>>,
112
- ): Array<Record<string, unknown>> {
113
- return items.slice(0, 10).map((item) => {
114
- const abstractRaw =
115
- typeof item.abstract === "string"
116
- ? item.abstract
117
- : typeof item.overview === "string"
118
- ? item.overview
119
- : typeof item.title === "string"
120
- ? item.title
121
- : "";
122
- return {
123
- uri: typeof item.uri === "string" ? item.uri : null,
124
- category: typeof item.category === "string" ? item.category : null,
125
- abstract: trimForLog(abstractRaw, 180),
126
- is_leaf: item.level === 2,
127
- };
128
- });
129
- }
130
-
131
- function isPreferencesMemory(item: FindResultItem): boolean {
132
- return (
133
- item.category === "preferences" ||
134
- item.uri.includes("/preferences/") ||
135
- item.uri.endsWith("/preferences")
136
- );
137
- }
138
-
139
- function isEventMemory(item: FindResultItem): boolean {
140
- const category = (item.category ?? "").toLowerCase();
141
- return category === "events" || item.uri.includes("/events/");
142
- }
143
-
144
- function isLeafLikeMemory(item: FindResultItem): boolean {
145
- return item.level === 2;
146
- }
147
-
148
- const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
149
- const TEMPORAL_QUERY_RE =
150
- /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天|上周|下周|上个月|下个月|去年|明年/i;
151
- const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;
152
- const QUERY_TOKEN_STOPWORDS = new Set([
153
- "what",
154
- "when",
155
- "where",
156
- "which",
157
- "who",
158
- "whom",
159
- "whose",
160
- "why",
161
- "how",
162
- "did",
163
- "does",
164
- "is",
165
- "are",
166
- "was",
167
- "were",
168
- "the",
169
- "and",
170
- "for",
171
- "with",
172
- "from",
173
- "that",
174
- "this",
175
- "your",
176
- "you",
177
- ]);
178
-
179
- type RecallQueryProfile = {
180
- tokens: string[];
181
- wantsPreference: boolean;
182
- wantsTemporal: boolean;
183
- };
184
-
185
- function buildRecallQueryProfile(query: string): RecallQueryProfile {
186
- const text = query.trim();
187
- const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];
188
- const tokens = allTokens.filter((token) => !QUERY_TOKEN_STOPWORDS.has(token));
189
- return {
190
- tokens,
191
- wantsPreference: PREFERENCE_QUERY_RE.test(text),
192
- wantsTemporal: TEMPORAL_QUERY_RE.test(text),
193
- };
194
- }
195
-
196
- function lexicalOverlapBoost(tokens: string[], text: string): number {
197
- if (tokens.length === 0 || !text) {
198
- return 0;
199
- }
200
- const haystack = ` ${text.toLowerCase()} `;
201
- let matched = 0;
202
- for (const token of tokens.slice(0, 8)) {
203
- if (haystack.includes(` ${token} `) || haystack.includes(token)) {
204
- matched += 1;
205
- }
206
- }
207
- return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
208
- }
209
-
210
- function rankForInjection(item: FindResultItem, query: RecallQueryProfile): number {
211
- // Keep ranking simple and stable: semantic score + light query-aware boosts.
212
- const baseScore = clampScore(item.score);
213
- const abstract = (item.abstract ?? item.overview ?? "").trim();
214
- const leafBoost = isLeafLikeMemory(item) ? 0.12 : 0;
215
- const eventBoost = query.wantsTemporal && isEventMemory(item) ? 0.1 : 0;
216
- const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? 0.08 : 0;
217
- const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);
218
- return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost;
219
- }
220
-
221
- export function pickMemoriesForInjection(
222
- items: FindResultItem[],
223
- limit: number,
224
- queryText: string,
225
- scoreThreshold: number = 0,
226
- ): FindResultItem[] {
227
- if (items.length === 0 || limit <= 0) {
228
- return [];
229
- }
230
-
231
- const query = buildRecallQueryProfile(queryText);
232
- const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));
233
- const deduped: FindResultItem[] = [];
234
- const seen = new Set<string>();
235
- for (const item of sorted) {
236
- const abstractKey = (item.abstract ?? item.overview ?? "").trim().toLowerCase();
237
- const key = abstractKey || item.uri;
238
- if (seen.has(key)) {
239
- continue;
240
- }
241
- seen.add(key);
242
- deduped.push(item);
243
- }
244
- const leaves = deduped.filter((item) => isLeafLikeMemory(item));
245
- if (leaves.length >= limit) {
246
- return leaves.slice(0, limit);
247
- }
248
-
249
- const picked = [...leaves];
250
- const used = new Set(leaves.map((item) => item.uri));
251
- for (const item of deduped) {
252
- if (picked.length >= limit) {
253
- break;
254
- }
255
- if (used.has(item.uri)) {
256
- continue;
257
- }
258
- // Respect score threshold when supplementing leaf memories with
259
- // non-leaf items. Without this check, low-scoring memories bypass
260
- // the threshold configured in recallScoreThreshold (see #1106).
261
- if (clampScore(item.score) < scoreThreshold) {
262
- continue;
263
- }
264
- picked.push(item);
265
- }
266
- return picked;
267
- }
1
+ import type { FindResultItem } from "./client.js";
2
+
3
+ export function clampScore(value: number | undefined): number {
4
+ if (typeof value !== "number" || Number.isNaN(value)) {
5
+ return 0;
6
+ }
7
+ return Math.max(0, Math.min(1, value));
8
+ }
9
+
10
+ function normalizeDedupeText(text: string): string {
11
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
12
+ }
13
+
14
+ function isEventOrCaseMemory(item: FindResultItem): boolean {
15
+ const category = (item.category ?? "").toLowerCase();
16
+ const uri = item.uri.toLowerCase();
17
+ return (
18
+ category === "events" ||
19
+ category === "cases" ||
20
+ uri.includes("/events/") ||
21
+ uri.includes("/cases/")
22
+ );
23
+ }
24
+
25
+ function getMemoryDedupeKey(item: FindResultItem): string {
26
+ const abstract = normalizeDedupeText(item.abstract ?? item.overview ?? "");
27
+ const category = (item.category ?? "").toLowerCase() || "unknown";
28
+ if (abstract && !isEventOrCaseMemory(item)) {
29
+ return `abstract:${category}:${abstract}`;
30
+ }
31
+ return `uri:${item.uri}`;
32
+ }
33
+
34
+ export function postProcessMemories(
35
+ items: FindResultItem[],
36
+ options: {
37
+ limit: number;
38
+ scoreThreshold: number;
39
+ leafOnly?: boolean;
40
+ },
41
+ ): FindResultItem[] {
42
+ const deduped: FindResultItem[] = [];
43
+ const seen = new Set<string>();
44
+ const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));
45
+ for (const item of sorted) {
46
+ if (options.leafOnly && item.level !== 2) {
47
+ continue;
48
+ }
49
+ if (clampScore(item.score) < options.scoreThreshold) {
50
+ continue;
51
+ }
52
+ const key = getMemoryDedupeKey(item);
53
+ if (seen.has(key)) {
54
+ continue;
55
+ }
56
+ seen.add(key);
57
+ deduped.push(item);
58
+ if (deduped.length >= options.limit) {
59
+ break;
60
+ }
61
+ }
62
+ return deduped;
63
+ }
64
+
65
+ export function formatMemoryLines(items: FindResultItem[]): string {
66
+ return items
67
+ .map((item, index) => {
68
+ const score = clampScore(item.score);
69
+ const abstract = item.abstract?.trim() || item.overview?.trim() || item.uri;
70
+ const category = item.category ?? "memory";
71
+ return `${index + 1}. [${category}] ${abstract} (${(score * 100).toFixed(0)}%)`;
72
+ })
73
+ .join("\n");
74
+ }
75
+
76
+ export function trimForLog(value: string, limit = 260): string {
77
+ const normalized = value.trim();
78
+ if (normalized.length <= limit) {
79
+ return normalized;
80
+ }
81
+ return `${normalized.slice(0, limit)}...`;
82
+ }
83
+
84
+ export function toJsonLog(value: unknown, maxLen = 6000): string {
85
+ try {
86
+ const json = JSON.stringify(value);
87
+ if (json.length <= maxLen) {
88
+ return json;
89
+ }
90
+ return JSON.stringify({
91
+ truncated: true,
92
+ length: json.length,
93
+ preview: `${json.slice(0, maxLen)}...`,
94
+ });
95
+ } catch {
96
+ return JSON.stringify({ error: "stringify_failed" });
97
+ }
98
+ }
99
+
100
+ export function summarizeInjectionMemories(items: FindResultItem[]): Array<Record<string, unknown>> {
101
+ return items.map((item) => ({
102
+ uri: item.uri,
103
+ category: item.category ?? null,
104
+ abstract: trimForLog(item.abstract?.trim() || item.overview?.trim() || item.uri, 180),
105
+ score: clampScore(item.score),
106
+ is_leaf: item.level === 2,
107
+ }));
108
+ }
109
+
110
+ export function summarizeExtractedMemories(
111
+ items: Array<Record<string, unknown>>,
112
+ ): Array<Record<string, unknown>> {
113
+ return items.slice(0, 10).map((item) => {
114
+ const abstractRaw =
115
+ typeof item.abstract === "string"
116
+ ? item.abstract
117
+ : typeof item.overview === "string"
118
+ ? item.overview
119
+ : typeof item.title === "string"
120
+ ? item.title
121
+ : "";
122
+ return {
123
+ uri: typeof item.uri === "string" ? item.uri : null,
124
+ category: typeof item.category === "string" ? item.category : null,
125
+ abstract: trimForLog(abstractRaw, 180),
126
+ is_leaf: item.level === 2,
127
+ };
128
+ });
129
+ }
130
+
131
+ function isPreferencesMemory(item: FindResultItem): boolean {
132
+ return (
133
+ item.category === "preferences" ||
134
+ item.uri.includes("/preferences/") ||
135
+ item.uri.endsWith("/preferences")
136
+ );
137
+ }
138
+
139
+ function isEventMemory(item: FindResultItem): boolean {
140
+ const category = (item.category ?? "").toLowerCase();
141
+ return category === "events" || item.uri.includes("/events/");
142
+ }
143
+
144
+ function isLeafLikeMemory(item: FindResultItem): boolean {
145
+ return item.level === 2;
146
+ }
147
+
148
+ const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
149
+ const TEMPORAL_QUERY_RE =
150
+ /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天|上周|下周|上个月|下个月|去年|明年/i;
151
+ const QUERY_TOKEN_RE = /[a-z0-9]{2,}/gi;
152
+ const QUERY_TOKEN_STOPWORDS = new Set([
153
+ "what",
154
+ "when",
155
+ "where",
156
+ "which",
157
+ "who",
158
+ "whom",
159
+ "whose",
160
+ "why",
161
+ "how",
162
+ "did",
163
+ "does",
164
+ "is",
165
+ "are",
166
+ "was",
167
+ "were",
168
+ "the",
169
+ "and",
170
+ "for",
171
+ "with",
172
+ "from",
173
+ "that",
174
+ "this",
175
+ "your",
176
+ "you",
177
+ ]);
178
+
179
+ type RecallQueryProfile = {
180
+ tokens: string[];
181
+ wantsPreference: boolean;
182
+ wantsTemporal: boolean;
183
+ };
184
+
185
+ export type RankingWeights = {
186
+ baseScore?: number;
187
+ leaf?: number;
188
+ event?: number;
189
+ preference?: number;
190
+ lexicalOverlapMax?: number;
191
+ };
192
+
193
+ export type RankingOptions = {
194
+ weights?: RankingWeights;
195
+ categoryWeights?: Record<string, number>;
196
+ resourceTypeWeights?: Record<string, number>;
197
+ };
198
+
199
+ const DEFAULT_RANKING_WEIGHTS = {
200
+ baseScore: 1,
201
+ leaf: 0.12,
202
+ event: 0.1,
203
+ preference: 0.08,
204
+ lexicalOverlapMax: 0.2,
205
+ };
206
+
207
+ function buildRecallQueryProfile(query: string): RecallQueryProfile {
208
+ const text = query.trim();
209
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];
210
+ const tokens = allTokens.filter((token) => !QUERY_TOKEN_STOPWORDS.has(token));
211
+ return {
212
+ tokens,
213
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
214
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
215
+ };
216
+ }
217
+
218
+ function lexicalOverlapBoost(tokens: string[], text: string, maxBoost = DEFAULT_RANKING_WEIGHTS.lexicalOverlapMax): number {
219
+ if (tokens.length === 0 || !text) {
220
+ return 0;
221
+ }
222
+ const haystack = ` ${text.toLowerCase()} `;
223
+ let matched = 0;
224
+ for (const token of tokens.slice(0, 8)) {
225
+ if (haystack.includes(` ${token} `) || haystack.includes(token)) {
226
+ matched += 1;
227
+ }
228
+ }
229
+ return Math.min(maxBoost, (matched / Math.min(tokens.length, 4)) * maxBoost);
230
+ }
231
+
232
+ function inferResourceType(item: FindResultItem): string | undefined {
233
+ if (item.uri.startsWith("viking://resources")) return "resource";
234
+ if (item.uri.startsWith("viking://session/")) return "session";
235
+ if (item.uri.startsWith("viking://user/skills") || item.uri.startsWith("viking://skills")) return "agent";
236
+ if (item.uri.startsWith("viking://user/")) return "user";
237
+ return undefined;
238
+ }
239
+
240
+ function rankForInjection(item: FindResultItem, query: RecallQueryProfile, options?: RankingOptions): number {
241
+ // Keep ranking simple and stable: semantic score + light query-aware boosts.
242
+ const weights = { ...DEFAULT_RANKING_WEIGHTS, ...(options?.weights ?? {}) };
243
+ const baseScore = clampScore(item.score) * weights.baseScore;
244
+ const abstract = (item.abstract ?? item.overview ?? "").trim();
245
+ const leafBoost = isLeafLikeMemory(item) ? weights.leaf : 0;
246
+ const eventBoost = query.wantsTemporal && isEventMemory(item) ? weights.event : 0;
247
+ const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? weights.preference : 0;
248
+ const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`, weights.lexicalOverlapMax);
249
+ const category = (item.category ?? "").toLowerCase();
250
+ const categoryBoost = category ? (options?.categoryWeights?.[category] ?? options?.categoryWeights?.[item.category ?? ""] ?? 0) : 0;
251
+ const resourceType = inferResourceType(item);
252
+ const resourceTypeBoost = resourceType ? (options?.resourceTypeWeights?.[resourceType] ?? 0) : 0;
253
+ return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost + categoryBoost + resourceTypeBoost;
254
+ }
255
+
256
+ export function pickMemoriesForInjection(
257
+ items: FindResultItem[],
258
+ limit: number,
259
+ queryText: string,
260
+ scoreThreshold: number = 0,
261
+ rankingOptions?: RankingOptions,
262
+ ): FindResultItem[] {
263
+ if (items.length === 0 || limit <= 0) {
264
+ return [];
265
+ }
266
+
267
+ const query = buildRecallQueryProfile(queryText);
268
+ const sorted = [...items].sort((a, b) => rankForInjection(b, query, rankingOptions) - rankForInjection(a, query, rankingOptions));
269
+ const deduped: FindResultItem[] = [];
270
+ const seen = new Set<string>();
271
+ for (const item of sorted) {
272
+ const abstractKey = (item.abstract ?? item.overview ?? "").trim().toLowerCase();
273
+ const key = abstractKey || item.uri;
274
+ if (seen.has(key)) {
275
+ continue;
276
+ }
277
+ seen.add(key);
278
+ deduped.push(item);
279
+ }
280
+ const leaves = deduped.filter((item) => isLeafLikeMemory(item));
281
+ if (leaves.length >= limit) {
282
+ return leaves.slice(0, limit);
283
+ }
284
+
285
+ const picked = [...leaves];
286
+ const used = new Set(leaves.map((item) => item.uri));
287
+ for (const item of deduped) {
288
+ if (picked.length >= limit) {
289
+ break;
290
+ }
291
+ if (used.has(item.uri)) {
292
+ continue;
293
+ }
294
+ // Respect score threshold when supplementing leaf memories with
295
+ // non-leaf items. Without this check, low-scoring memories bypass
296
+ // the threshold configured in recallScoreThreshold (see #1106).
297
+ if (clampScore(item.score) < scoreThreshold) {
298
+ continue;
299
+ }
300
+ picked.push(item);
301
+ }
302
+ return picked;
303
+ }