@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.0

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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -0,0 +1,539 @@
1
+ /**
2
+ * @file _locate.mjs - rank a repository's files against bug or task text.
3
+ *
4
+ * Shared by `product-tree.mjs locate` and `product-tree-eval.mjs`, so the arm
5
+ * the evaluation measures is the arm the pipeline runs. Three arms, each a
6
+ * strict superset of the one before:
7
+ *
8
+ * bm25 field-weighted BM25 over each file's name, declared symbols and
9
+ * directory words: what the code graph alone can answer
10
+ * graph bm25 plus four signals that need no screen layer: the query
11
+ * expanded with the keys of the UI strings it quotes, a ranking of
12
+ * the files that reference those keys (a UI-string boost),
13
+ * personalized PageRank seeded from the best files over the import
14
+ * and reference edges, and Turkish-aware normalisation
15
+ * tree graph plus the screen layer: screens ranked by name, route and the
16
+ * strings they show, expanded to the files each screen owns
17
+ *
18
+ * Normalisation folds Turkish and accented letters onto ASCII (identifiers
19
+ * are ASCII, user text often is not) and indexes a suffix-stripped stem beside
20
+ * every word, so "bitkiyi" meets "bitki". Identifier splitting comes from
21
+ * _retrieval.mjs tokens(), the tokenizer the memory stores already use.
22
+ *
23
+ * Deterministic, no embeddings, zero dependencies.
24
+ *
25
+ * @module pipeline/scripts/_locate
26
+ */
27
+
28
+ import { tokens, rrf } from "./_retrieval.mjs";
29
+
30
+ /**
31
+ * Fold Turkish dotless i and every combining accent onto ASCII letters.
32
+ *
33
+ * @param {string} s
34
+ * @returns {string}
35
+ */
36
+ export function foldText(s) {
37
+ return String(s ?? "")
38
+ .replace(/ı/g, "i")
39
+ .normalize("NFD")
40
+ .replace(/\p{M}/gu, "");
41
+ }
42
+
43
+ const TR_SUFFIXES = [
44
+ "larindan",
45
+ "lerinden",
46
+ "larinda",
47
+ "lerinde",
48
+ "larini",
49
+ "lerini",
50
+ "lardan",
51
+ "lerden",
52
+ "larda",
53
+ "lerde",
54
+ "larin",
55
+ "lerin",
56
+ "lari",
57
+ "leri",
58
+ "indan",
59
+ "inden",
60
+ "inda",
61
+ "inde",
62
+ "unda",
63
+ "unde",
64
+ "lar",
65
+ "ler",
66
+ "nda",
67
+ "nde",
68
+ "dan",
69
+ "den",
70
+ "tan",
71
+ "ten",
72
+ "nin",
73
+ "nun",
74
+ "yla",
75
+ "yle",
76
+ "yi",
77
+ "yu",
78
+ "ya",
79
+ "ye",
80
+ "in",
81
+ "un",
82
+ "da",
83
+ "de",
84
+ "ta",
85
+ "te",
86
+ "i",
87
+ "u",
88
+ ];
89
+
90
+ /**
91
+ * Strip one Turkish inflection suffix from a folded, lower-case word.
92
+ *
93
+ * One pass, longest suffix first, and the stem keeps at least four letters, so
94
+ * an English word is rarely touched and never cut to a fragment. The stem is
95
+ * indexed beside the word, never instead of it.
96
+ *
97
+ * @param {string} term
98
+ * @returns {string}
99
+ */
100
+ export function stemTr(term) {
101
+ if (term.length < 5) return term;
102
+ for (const s of TR_SUFFIXES) {
103
+ if (term.endsWith(s) && term.length - s.length >= 4) return term.slice(0, -s.length);
104
+ }
105
+ return term;
106
+ }
107
+
108
+ /**
109
+ * Ranking terms for a piece of text: folded, identifier-split, stop words
110
+ * dropped, each inflected word followed by its stem.
111
+ *
112
+ * @param {string} text
113
+ * @returns {string[]}
114
+ */
115
+ export function termsOf(text) {
116
+ const out = [];
117
+ for (const t of tokens(foldText(text))) {
118
+ out.push(t);
119
+ const s = stemTr(t);
120
+ if (s !== t) out.push(s);
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * BM25 over documents with weighted fields, tokenised once and searched many
127
+ * times. Lucene IDF, so a term in most documents still scores above zero.
128
+ */
129
+ export class TermIndex {
130
+ /**
131
+ * @param {Array<Record<string,string>>} docs
132
+ * @param {Record<string,number>} [fieldWeights] absent fields weigh 1
133
+ * @param {{k1?: number, b?: number}} [opts]
134
+ */
135
+ constructor(docs, fieldWeights = {}, { k1 = 1.2, b = 0.75 } = {}) {
136
+ this.k1 = k1;
137
+ this.b = b;
138
+ this.n = docs.length;
139
+ this.tf = new Array(this.n);
140
+ this.len = new Array(this.n);
141
+ this.df = new Map();
142
+ let total = 0;
143
+ for (let i = 0; i < this.n; i++) {
144
+ const tf = new Map();
145
+ let len = 0;
146
+ const doc = docs[i] || {};
147
+ for (const field of Object.keys(doc)) {
148
+ const w = fieldWeights[field] === undefined ? 1 : fieldWeights[field];
149
+ if (!w) continue;
150
+ for (const t of termsOf(doc[field])) {
151
+ tf.set(t, (tf.get(t) || 0) + w);
152
+ len += w;
153
+ }
154
+ }
155
+ for (const t of tf.keys()) this.df.set(t, (this.df.get(t) || 0) + 1);
156
+ this.tf[i] = tf;
157
+ this.len[i] = len;
158
+ total += len;
159
+ }
160
+ this.avg = total / (this.n || 1) || 1;
161
+ }
162
+
163
+ /**
164
+ * @param {string[]} queryTerms
165
+ * @returns {Array<{index:number, score:number}>} positive scores, best first
166
+ */
167
+ search(queryTerms) {
168
+ const q = [...new Set(queryTerms)].filter((t) => this.df.has(t));
169
+ if (!q.length) return [];
170
+ const idf = new Map(
171
+ q.map((t) => [t, Math.log(1 + (this.n - this.df.get(t) + 0.5) / (this.df.get(t) + 0.5))]),
172
+ );
173
+ const out = [];
174
+ for (let i = 0; i < this.n; i++) {
175
+ const tf = this.tf[i];
176
+ let s = 0;
177
+ for (const t of q) {
178
+ const f = tf.get(t);
179
+ if (!f) continue;
180
+ s +=
181
+ (idf.get(t) * (f * (this.k1 + 1))) /
182
+ (f + this.k1 * (1 - this.b + (this.b * this.len[i]) / this.avg));
183
+ }
184
+ if (s > 0) out.push({ index: i, score: s });
185
+ }
186
+ return out.sort((a, b) => b.score - a.score || a.index - b.index);
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Personalized PageRank by power iteration.
192
+ *
193
+ * The walk restarts at the seeds with probability `restart`, so the score
194
+ * falls with distance from them; a node with no edges sends its mass back to
195
+ * the seeds, which keeps the total at one.
196
+ *
197
+ * @param {Map<string, string[]>} adj node -> neighbours
198
+ * @param {Map<string, number>} seeds node -> positive weight
199
+ * @param {{restart?: number, iterations?: number}} [opts]
200
+ * @returns {Map<string, number>}
201
+ */
202
+ export function personalizedPageRank(adj, seeds, { restart = 0.3, iterations = 30 } = {}) {
203
+ const total = [...seeds.values()].reduce((s, x) => s + (x > 0 ? x : 0), 0);
204
+ if (!(total > 0)) return new Map();
205
+ const p = new Map();
206
+ for (const [id, w] of seeds) if (w > 0) p.set(id, w / total);
207
+ const nodes = new Set([...adj.keys(), ...p.keys()]);
208
+ for (const list of adj.values()) for (const v of list) nodes.add(v);
209
+ let r = new Map(p);
210
+ for (let it = 0; it < iterations; it++) {
211
+ const next = new Map();
212
+ let dangling = 0;
213
+ for (const [u, mass] of r) {
214
+ const out = adj.get(u) || [];
215
+ if (!out.length) {
216
+ dangling += mass;
217
+ continue;
218
+ }
219
+ const share = ((1 - restart) * mass) / out.length;
220
+ for (const v of out) next.set(v, (next.get(v) || 0) + share);
221
+ }
222
+ for (const [id, w] of p) {
223
+ next.set(id, (next.get(id) || 0) + (restart + (1 - restart) * dangling) * w);
224
+ }
225
+ let sum = 0;
226
+ for (const v of next.values()) sum += v;
227
+ const fix = sum > 0 ? 1 / sum : 1;
228
+ r = new Map([...next].map(([k, v]) => [k, v * fix]));
229
+ }
230
+ for (const id of nodes) if (!r.has(id)) r.set(id, 0);
231
+ return r;
232
+ }
233
+
234
+ const baseName = (p) =>
235
+ String(p)
236
+ .split("/")
237
+ .pop()
238
+ .replace(/\.[^.]+$/, "");
239
+ const dirWords = (p) => String(p).split("/").slice(0, -1).join(" ");
240
+
241
+ /**
242
+ * Build everything the arms need from plain data.
243
+ *
244
+ * @param {object} input
245
+ * @param {Array<{path: string, symbols?: string[], isTest?: boolean}>} input.files
246
+ * @param {Array<[string, string]>} [input.edges] file -> file dependencies
247
+ * @param {Array<{key: string, values: Record<string,string>, files?: string[]}>} [input.strings]
248
+ * @param {Array<{id: string, name: string, path: string, routes?: string[], files?: string[], keys?: string[]}>} [input.screens]
249
+ */
250
+ export function buildLocateIndex({ files, edges = [], strings = [], screens = [] }) {
251
+ const candidates = files.filter((f) => !f.isTest).map((f) => f.path);
252
+ const isCandidate = new Set(candidates);
253
+ const symbolsOf = new Map(files.map((f) => [f.path, f.symbols || []]));
254
+ const fileIndex = new TermIndex(
255
+ candidates.map((p) => ({
256
+ name: baseName(p),
257
+ symbols: symbolsOf.get(p).join(" "),
258
+ path: dirWords(p),
259
+ })),
260
+ { name: 3, symbols: 2, path: 1 },
261
+ );
262
+ const adj = new Map();
263
+ const link = (a, b) => {
264
+ if (!adj.has(a)) adj.set(a, []);
265
+ if (!adj.get(a).includes(b)) adj.get(a).push(b);
266
+ };
267
+ for (const [a, b] of edges) {
268
+ if (a === b || !isCandidate.has(a) || !isCandidate.has(b)) continue;
269
+ link(a, b);
270
+ link(b, a);
271
+ }
272
+ const stringIndex = new TermIndex(
273
+ strings.map((s) => ({ value: Object.values(s.values || {}).join(" \n "), key: s.key })),
274
+ { value: 2, key: 1 },
275
+ );
276
+ const valuesByKey = new Map(strings.map((s) => [s.key, s.values || {}]));
277
+ const screenIndex = new TermIndex(
278
+ screens.map((s) => ({
279
+ name: s.name,
280
+ routes: (s.routes || []).join(" "),
281
+ strings: (s.keys || [])
282
+ .map((k) => Object.values(valuesByKey.get(k) || {}).join(" "))
283
+ .join(" \n "),
284
+ path: dirWords(s.path),
285
+ })),
286
+ { name: 3, routes: 2, strings: 1, path: 1 },
287
+ );
288
+ return { candidates, isCandidate, fileIndex, adj, strings, stringIndex, screens, screenIndex };
289
+ }
290
+
291
+ /**
292
+ * Locate inputs from a tree and, when present, the code graph beside it.
293
+ *
294
+ * @param {object} tree
295
+ * @param {object|null} graph
296
+ */
297
+ export function locateInput(tree, graph) {
298
+ const byId = new Map(tree.nodes.map((n) => [n.id, n]));
299
+ const files = new Map();
300
+ const edges = [];
301
+ if (graph) {
302
+ const symPath = new Map();
303
+ for (const n of graph.nodes) {
304
+ if (n.kind === "file")
305
+ files.set(n.path, { path: n.path, symbols: [], isTest: Boolean(n.isTest) });
306
+ if (n.kind === "symbol") symPath.set(n.id, n.path);
307
+ }
308
+ for (const n of graph.nodes) if (n.kind === "symbol") files.get(n.path)?.symbols.push(n.name);
309
+ for (const e of graph.edges) {
310
+ if (e.kind !== "references" && e.kind !== "imports") continue;
311
+ const a = e.from.startsWith("file:") ? e.from.slice(5) : null;
312
+ const b = e.to.startsWith("file:") ? e.to.slice(5) : symPath.get(e.to);
313
+ if (a && b && a !== b) edges.push([a, b]);
314
+ }
315
+ }
316
+ const strings = tree.nodes
317
+ .filter((n) => n.kind === "string")
318
+ .map((n) => ({ key: n.name, values: n.values || {}, files: n.files || [] }));
319
+ const routesOf = new Map();
320
+ const keysOf = new Map();
321
+ for (const e of tree.edges) {
322
+ if (e.kind === "shows") {
323
+ if (!routesOf.has(e.to)) routesOf.set(e.to, []);
324
+ routesOf.get(e.to).push(byId.get(e.from)?.name ?? e.from);
325
+ }
326
+ if (e.kind === "uses-string") {
327
+ if (!keysOf.has(e.from)) keysOf.set(e.from, []);
328
+ keysOf.get(e.from).push(byId.get(e.to)?.name ?? e.to);
329
+ }
330
+ }
331
+ const screens = tree.nodes
332
+ .filter((n) => n.kind === "screen")
333
+ .map((n) => ({
334
+ id: n.id,
335
+ name: n.name,
336
+ path: n.path,
337
+ files: n.files || [n.path],
338
+ routes: routesOf.get(n.id) || [],
339
+ keys: keysOf.get(n.id) || [],
340
+ }));
341
+ for (const s of screens) {
342
+ for (const f of s.files) if (!files.has(f)) files.set(f, { path: f, symbols: [] });
343
+ }
344
+ for (const s of strings) {
345
+ for (const f of s.files) if (!files.has(f)) files.set(f, { path: f, symbols: [] });
346
+ }
347
+ return { files: [...files.values()], edges, strings, screens };
348
+ }
349
+
350
+ const asRanking = (scores) =>
351
+ [...scores]
352
+ .filter(([, s]) => s > 0)
353
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
354
+
355
+ /**
356
+ * Ranking parameters. Chosen on the development half of the mined bugs only
357
+ * (product-tree-eval.mjs --tune); the held-out half is never used to set them.
358
+ *
359
+ * keyCoverage a string matches when at least this share of its words
360
+ * appear in the text, so a lone common word ("error",
361
+ * "save") does not pull in every file that shows it
362
+ * expandKeys how many matched keys extend the query
363
+ * graphWeights RRF weights for [bm25, expanded bm25, UI-string files,
364
+ * personalized PageRank]
365
+ * graphK RRF damping for the same four
366
+ * treeWeights RRF weights for [graph arm, files of matched screens]
367
+ * treeK RRF damping for the same two
368
+ */
369
+ export const DEFAULT_RANK = Object.freeze({
370
+ keyCoverage: 0.5,
371
+ expandKeys: 3,
372
+ graphWeights: [1, 0.3, 0.3, 0.3],
373
+ graphK: [10, 20, 20, 60],
374
+ treeWeights: [1, 1],
375
+ treeK: [10, 30],
376
+ });
377
+
378
+ const GENERIC_SCREEN_WORDS = new Set([
379
+ "screen",
380
+ "scene",
381
+ "view",
382
+ "page",
383
+ "component",
384
+ "modal",
385
+ "dialog",
386
+ "sheet",
387
+ "index",
388
+ "layout",
389
+ "content",
390
+ "route",
391
+ "root",
392
+ "main",
393
+ "app",
394
+ ]);
395
+
396
+ /**
397
+ * Rank files for one piece of text under all three arms.
398
+ *
399
+ * @param {ReturnType<typeof buildLocateIndex>} index
400
+ * @param {string} text
401
+ * @param {{limit?: number, maxKeys?: number, maxScreens?: number, rank?: Partial<typeof DEFAULT_RANK>}} [opts]
402
+ * @returns {{bm25: string[], graph: string[], tree: string[],
403
+ * keys: Array<{key: string, score: number}>,
404
+ * screens: Array<{id: string, name: string, path: string, routes: string[], score: number}>}}
405
+ */
406
+ export function rankArms(
407
+ index,
408
+ text,
409
+ { limit = 100, maxKeys = 10, maxScreens = 8, rank = {} } = {},
410
+ ) {
411
+ const P = { ...DEFAULT_RANK, ...rank };
412
+ const q = termsOf(text);
413
+ const qSet = new Set(q);
414
+ const { candidates } = index;
415
+ const asHits = (hits) => hits.map((h) => ({ id: candidates[h.index], score: h.score }));
416
+ const bm25Hits = asHits(index.fileIndex.search(q));
417
+ const bm25 = bm25Hits.slice(0, limit).map((h) => h.id);
418
+
419
+ const keys = [];
420
+ for (const h of index.stringIndex.search(q)) {
421
+ if (keys.length >= maxKeys) break;
422
+ const s = index.strings[h.index];
423
+ const cover = Math.max(
424
+ 0,
425
+ ...Object.values(s.values || {}).map((v) => {
426
+ const words = new Set(tokens(foldText(v)));
427
+ if (words.size < 2) return 0;
428
+ let hit = 0;
429
+ for (const w of words) if (qSet.has(w) || qSet.has(stemTr(w))) hit++;
430
+ return hit / words.size;
431
+ }),
432
+ );
433
+ if (cover >= P.keyCoverage) keys.push({ key: s.key, score: h.score * cover, at: h.index });
434
+ }
435
+ keys.sort((a, b) => b.score - a.score || a.at - b.at);
436
+
437
+ const expanded = [...q, ...keys.slice(0, P.expandKeys).flatMap((k) => termsOf(k.key))];
438
+ const expHits = keys.length ? asHits(index.fileIndex.search(expanded)) : [];
439
+ const uiScores = new Map();
440
+ for (const k of keys) {
441
+ for (const f of index.strings[k.at].files || []) {
442
+ if (index.isCandidate.has(f)) uiScores.set(f, (uiScores.get(f) || 0) + k.score);
443
+ }
444
+ }
445
+ const ui = asRanking(uiScores).map(([id, score]) => ({ id, score }));
446
+ const seedFuse = fuse([bm25Hits, expHits, ui], {
447
+ k: P.graphK.slice(0, 3),
448
+ weights: P.graphWeights.slice(0, 3),
449
+ });
450
+ const seeds = new Map(seedFuse.slice(0, 5).map((x) => [x.id, x.score]));
451
+ const pr = personalizedPageRank(index.adj, seeds);
452
+ const prRank = asRanking(new Map([...pr].filter(([id]) => index.isCandidate.has(id)))).map(
453
+ ([id, score]) => ({ id, score }),
454
+ );
455
+ const graphFused = fuse([bm25Hits, expHits, ui, prRank], {
456
+ k: P.graphK,
457
+ weights: P.graphWeights,
458
+ });
459
+ const graph = graphFused.slice(0, limit).map((x) => x.id);
460
+
461
+ const keyOfScreen = new Map();
462
+ const nameOfScreen = new Map();
463
+ index.screens.forEach((s, i) => {
464
+ let sc = 0;
465
+ for (const k of keys) if ((s.keys || []).includes(k.key)) sc += k.score;
466
+ if (sc > 0) keyOfScreen.set(String(i), sc);
467
+ const own = new Set(
468
+ termsOf(`${s.name} ${(s.routes || []).join(" ")}`).filter(
469
+ (t) => !GENERIC_SCREEN_WORDS.has(t),
470
+ ),
471
+ );
472
+ let named = 0;
473
+ for (const t of own) if (qSet.has(t)) named++;
474
+ if (named) nameOfScreen.set(String(i), named / own.size);
475
+ });
476
+ const screenFused = fuse(
477
+ [
478
+ asRanking(keyOfScreen).map(([id, score]) => ({ id, score })),
479
+ asRanking(nameOfScreen).map(([id, score]) => ({ id, score })),
480
+ ],
481
+ { k: [5, 5] },
482
+ ).slice(0, maxScreens);
483
+ const screens = screenFused.map((x) => {
484
+ const s = index.screens[Number(x.id)];
485
+ return { id: s.id, name: s.name, path: s.path, routes: s.routes || [], score: x.score };
486
+ });
487
+ const owned = [];
488
+ const seen = new Set();
489
+ for (const x of screenFused) {
490
+ const s = index.screens[Number(x.id)];
491
+ const files = (s.files && s.files.length ? s.files : [s.path]).filter((f) =>
492
+ index.isCandidate.has(f),
493
+ );
494
+ files.forEach((f, j) => {
495
+ if (seen.has(f)) return;
496
+ seen.add(f);
497
+ owned.push({ id: f, score: x.score / (1 + j) });
498
+ });
499
+ }
500
+ const tree = fuse([graphFused, owned], { k: P.treeK, weights: P.treeWeights })
501
+ .slice(0, limit)
502
+ .map((x) => x.id);
503
+ return { bm25, graph, tree, keys: keys.map(({ key, score }) => ({ key, score })), screens };
504
+ }
505
+
506
+ /** RRF over rankings of {id, score}, returning {id, score} best first. */
507
+ function fuse(rankings, opts) {
508
+ const ids = [];
509
+ const at = new Map();
510
+ const asIdx = rankings.map((r) =>
511
+ r.map((x) => {
512
+ if (!at.has(x.id)) {
513
+ at.set(x.id, ids.length);
514
+ ids.push(x.id);
515
+ }
516
+ return { index: at.get(x.id), score: x.score };
517
+ }),
518
+ );
519
+ return rrf(asIdx, opts).map((x) => ({ id: ids[x.index], score: x.score }));
520
+ }
521
+
522
+ /**
523
+ * Whole lines, in order, while they fit in maxChars once joined by newlines.
524
+ *
525
+ * @param {string[]} lines
526
+ * @param {number} maxChars
527
+ * @returns {string[]}
528
+ */
529
+ export function cutToBudget(lines, maxChars) {
530
+ const kept = [];
531
+ let used = 0;
532
+ for (const line of lines) {
533
+ const add = (kept.length ? 1 : 0) + line.length;
534
+ if (used + add > maxChars) break;
535
+ kept.push(line);
536
+ used += add;
537
+ }
538
+ return kept;
539
+ }