@astryxdesign/cli 0.7.3-canary.ca48bb7 → 0.7.3-canary.cac3d8d

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 (53) hide show
  1. package/api/build/_adapter.mjs +37 -25
  2. package/api/build/blocks/blocks.d.mts +68 -20
  3. package/api/build/blocks/blocks.mjs +472 -196
  4. package/api/build/blocks/blocks.test.mjs +185 -168
  5. package/api/build/blocks/blocks.weights.json +1 -1
  6. package/api/build/build.type.mjs +1 -1
  7. package/api/build/kit/answer.d.mts +4 -1
  8. package/api/build/kit/answer.mjs +11 -3
  9. package/api/build/kit/signals.d.mts +11 -0
  10. package/api/build/kit/signals.mjs +8 -7
  11. package/api/build/kit/weights.d.mts +8 -22
  12. package/api/build/kit/weights.mjs +87 -8
  13. package/api/build/kit/weights.test.mjs +96 -0
  14. package/api/build/tree.mjs +2 -1
  15. package/api/build/tree.test.mjs +27 -27
  16. package/api/component/_adapter.mjs +39 -5
  17. package/api/discover/_adapter.d.mts +1 -2
  18. package/api/discover/_adapter.mjs +6 -8
  19. package/api/discover/discover.mjs +0 -1
  20. package/api/docs/_adapter.mjs +4 -0
  21. package/api/doctor/_adapter.d.mts +33 -13
  22. package/api/doctor/_adapter.mjs +55 -25
  23. package/api/doctor/doctor.d.mts +23 -5
  24. package/api/doctor/doctor.mjs +81 -16
  25. package/api/doctor/doctor.test.mjs +58 -0
  26. package/api/search/_gather-templates.d.mts +0 -1
  27. package/api/search/_gather-templates.mjs +25 -0
  28. package/api/search/search.integration-block.test.mjs +100 -0
  29. package/api/template/template.mjs +5 -1
  30. package/assets/docs/tree/ci-and-containers.doc.mjs +13 -0
  31. package/clients/cli/commands/doctor.doc.mjs +1 -1
  32. package/clients/cli/commands/outside-project.test.mjs +99 -0
  33. package/clients/cli/commands/setup-nudge.test.mjs +17 -0
  34. package/clients/cli/index.mjs +25 -8
  35. package/foundation/agent-docs/agent-doc-state.d.mts +12 -0
  36. package/foundation/agent-docs/agent-doc-state.mjs +24 -2
  37. package/foundation/agent-docs/agent-docs.mjs +5 -5
  38. package/foundation/agent-docs/computer-agent-text.d.mts +39 -2
  39. package/foundation/agent-docs/computer-agent-text.mjs +135 -8
  40. package/foundation/agent-docs/computer-agent-text.test.mjs +99 -2
  41. package/foundation/integrations/public-imports.mjs +1 -1
  42. package/foundation/release/cache.test.mjs +24 -21
  43. package/foundation/release/global-state.d.mts +8 -4
  44. package/foundation/release/global-state.mjs +4 -2
  45. package/foundation/release/notices.d.mts +62 -8
  46. package/foundation/release/notices.mjs +136 -25
  47. package/foundation/release/notices.test.mjs +21 -0
  48. package/foundation/text/string-utils.d.mts +2 -1
  49. package/foundation/text/string-utils.mjs +16 -5
  50. package/foundation/text/suggest-order.d.mts +72 -0
  51. package/foundation/text/suggest-order.mjs +363 -0
  52. package/foundation/text/suggest-order.test.mjs +259 -0
  53. package/package.json +9 -9
@@ -1,147 +1,91 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
3
  /**
4
- * @file build's block picker: re-ranks the blocks build would name for a
5
- * request with checked-in word weights, and keeps build's own count.
4
+ * @file build's block picker: ranks every block in the catalog for a request
5
+ * by meaning, from each block's own docs, and keeps build's own count.
6
6
  *
7
7
  * @input The request, build's signals for it (`kitSignals`: the blocks the kit
8
- * names, search's block results with their scores and coverage), the block
9
- * ids the project can scaffold, and the picker weights (`blocks.weights.json`
10
- * beside this file, read by the adapter): a vocabulary of words and word
11
- * pairs with their weight (x1024), the block ids it scores, a bias per block
12
- * and a sparse row of weights per word (x64), and five combiner numbers.
13
- * @output `pickBlocks(...)`: block ids, best first, as many as build's own list.
8
+ * names, search's block results with their scores and coverage, the block
9
+ * catalog and the components), and the picker weights
10
+ * (`blocks.weights.json` beside this file, read by the adapter): a
11
+ * vocabulary of stemmed words and word pairs with their idf (x1024), two
12
+ * signed byte matrices that map request words and doc words into one space, the
13
+ * lexical weight, the blocks the matrices were fitted with, and the ranking
14
+ * coefficients.
15
+ * @output `pickBlocks(...)`: block names, best first, as many as build's own
16
+ * list, and an entry (real score and reason) for each listed block search
17
+ * did not return.
14
18
  * @position api/build/blocks; tree.mjs's main searcher calls it between
15
- * kitSignals (kit/signals.mjs) and kitAnswer (kit/answer.mjs). Pure: no file, network, or environment access.
19
+ * kitSignals (kit/signals.mjs) and kitAnswer (kit/answer.mjs). Pure: no file,
20
+ * network, or environment access.
16
21
  *
17
- * How it scores. The request's words and adjacent word pairs, each weighted
18
- * (1 + ln count) x its vocabulary weight and scaled to unit length, give every
19
- * block a linear score (its bias plus the weighted words' rows). The
20
- * candidates are build's own blocks and search's first 100 block results
21
- * (each a block search returned, with its real score and reason); a block
22
- * build does not name joins only if it shares a content word (the same word
23
- * up to plural and stem form, as search's sameWord reads it) with the
24
- * request (its display name and description against the request's words).
25
- * Each candidate's final score combines five numbers: search's score / 100,
26
- * the share of the request search matched, whether build names it, 1 / (1 +
27
- * its place in build's list, then search's), and the block's log-share of the
28
- * linear scores. Ties keep that order. A block the request names (its name,
29
- * or the component its name starts with, written out, joined, or plural), a
30
- * block the weights do not know, and a block whose package is not Core's keep
31
- * the slot build gave them; the picker's best fill the other slots, so the
32
- * kit never lists more blocks than build's own.
33
- */
34
-
35
- import {pluralOf, STOPWORDS} from '../../search/_query.mjs';
36
- import {sameWord, wordsOf} from '../../search/_words.mjs';
22
+ * How it scores. A block is described by its own docs only: its name, display
23
+ * name and description, and its component's name and keywords. The request
24
+ * and each block's docs become weighted word vectors (stemmed content words
25
+ * and adjacent pairs, (1 + ln count) x idf, unit length). Their match is the
26
+ * request's vector through the request matrix, against the docs' vector
27
+ * through the doc matrix, plus the lexical weight times their plain overlap
28
+ * (cosine), so a block the weights were never fitted with, such as a new one,
29
+ * is scored from its docs the same way. The candidates are the best matches,
30
+ * build's own blocks, search's first results, and the best plain overlaps.
31
+ * Each candidate's final score adds the ranking coefficients times: its match
32
+ * relative to the best, its place among the matches, its lead over the
33
+ * second-best match, whether the weights know it, its plain overlap,
34
+ * search's score and share of the request matched and place, whether build
35
+ * names it and where, how strongly the request names its component, and
36
+ * whether it is its component's general example. A block the request writes
37
+ * out by its exact name, and a block whose package is not Core's, keep the
38
+ * slot build gave them; the best of the others fill the remaining slots.
39
+ */
40
+
41
+ import {STOPWORDS} from '../../search/_query.mjs';
37
42
 
38
43
  /**
39
44
  * @typedef {object} BlockPickerWeights
40
- * @property {Record<string, number>} vocab word or word pair -> weight x1024
41
- * @property {string[]} classes the block ids the words score
42
- * @property {number[]} bias one per class, x64
43
- * @property {Record<string, number[]>} words word -> [class index, weight x64, ...]
44
- * @property {number[]} theta the five combiner numbers
45
+ * @property {string[]} vocab stemmed words and `a_b` word pairs
46
+ * @property {number[]} idf one per vocab entry, x1024
47
+ * @property {number} dims the width of the shared space
48
+ * @property {string} request base64 bytes, vocab.length x dims, row-major, each a signed weight offset by 128
49
+ * @property {number} requestScale
50
+ * @property {string} doc base64 bytes, vocab.length x dims, row-major, each a signed weight offset by 128
51
+ * @property {number} docScale
52
+ * @property {number} lexical the weight of the plain overlap
53
+ * @property {string[]} known the blocks the matrices were fitted with
54
+ * @property {Record<string, number>} theta the ranking coefficients
45
55
  *
46
56
  * @typedef {import('../kit/signals.mjs').BlockScore} BlockScore
57
+ * @typedef {{name: string, package?: string, displayName?: string, description?: string, command?: string}} CatalogBlock
58
+ * @typedef {{name: string, keywords?: string[]}} CatalogComponent
59
+ * @typedef {import('../../search/search.type.mjs').SearchResultEntry} SearchResultEntry
47
60
  */
48
61
 
49
- /** The linear score of a block the words do not score. */
50
- const UNSCORED = -30;
51
-
52
- /**
53
- * The words and adjacent word pairs of a request, with their weights, in the
54
- * order they first appear; only those in the vocabulary.
55
- * @param {string} request
56
- * @param {BlockPickerWeights} weights
57
- * @returns {Map<string, number>}
58
- */
59
- function features(request, weights) {
60
- const tokens =
61
- String(request ?? '')
62
- .toLowerCase()
63
- .match(/[a-z0-9]{2,}/g) ?? [];
64
- const all = [...tokens];
65
- for (let i = 0; i + 1 < tokens.length; i++)
66
- all.push(`${tokens[i]} ${tokens[i + 1]}`);
67
- /** @type {Map<string, number>} */
68
- const counts = new Map();
69
- for (const f of all) {
70
- if (Object.hasOwn(weights.vocab, f))
71
- counts.set(f, (counts.get(f) ?? 0) + 1);
72
- }
73
- /** @type {Map<string, number>} */
74
- const x = new Map();
75
- for (const [f, c] of counts)
76
- x.set(f, ((1 + Math.log(c)) * weights.vocab[f]) / 1024);
77
- return x;
78
- }
79
-
80
62
  /**
81
- * Every class's linear score for a request, and the log of the normalizer.
82
- * @param {string} request
83
- * @param {BlockPickerWeights} weights
84
- * @returns {{z: number[], lse: number}}
85
- */
86
- function linearScores(request, weights) {
87
- const x = features(request, weights);
88
- let sq = 0;
89
- for (const v of x.values()) sq += v * v;
90
- const norm = Math.sqrt(sq);
91
- const z = weights.bias.slice();
92
- if (norm > 0) {
93
- for (const [f, v] of x) {
94
- const row = Object.hasOwn(weights.words, f) ? weights.words[f] : null;
95
- if (!row) continue;
96
- for (let k = 0; k < row.length; k += 2)
97
- z[row[k]] += (v / norm) * row[k + 1];
98
- }
99
- }
100
- for (let c = 0; c < z.length; c++) z[c] /= 64;
101
- let max = -Infinity;
102
- for (const v of z) if (v > max) max = v;
103
- let sum = 0;
104
- for (const v of z) sum += Math.exp(v - max);
105
- return {z, lse: max + Math.log(sum)};
106
- }
107
-
108
- /** How many of search's block results are candidates. */
109
- const SEARCH_POOL = 100;
110
-
111
- /**
112
- * Generic English function words (pronouns, relative pronouns, determiners,
113
- * quantifiers, auxiliaries, conjunctions, prepositions): never a reason to tie
114
- * a block to a request.
115
- */
116
- const FUNCTION_WORDS = (
117
- 'about above across after again against all along already also although ' +
118
- 'always am among amongst an and another any anyone anything anywhere are ' +
119
- 'around as at be because been before behind being below beneath beside ' +
120
- 'besides between beyond both but by can could despite did do does doing ' +
121
- 'down during each either else enough even ever every everyone everything ' +
122
- 'everywhere except few following for from further had has have having he ' +
123
- 'her here hers herself him himself his how however if in inside instead ' +
124
- 'into is it its itself just least less little lot lots many may maybe me ' +
125
- 'might more most much must my myself near neither never no nobody none ' +
126
- 'nor not nothing now nowhere of off often on once one ones only onto or ' +
127
- 'other others ought our ours ourselves out outside over own past per ' +
128
- 'perhaps quite rather same several shall she should since so some someone ' +
129
- 'something sometimes somewhat somewhere still such than that the their ' +
130
- 'theirs them themselves then there these they this those though through ' +
131
- 'throughout thus till to together too toward towards under underneath ' +
132
- 'unless unlike until up upon usually very via was we were what whatever ' +
133
- 'when whenever where whereas whether which whichever while who whoever ' +
134
- 'whom whomever whose why will with within without would yet you your ' +
135
- 'yours yourself yourselves'
136
- ).split(' ');
137
-
138
- /**
139
- * Words too common to tie a block to a request: search's own stopwords, the
140
- * function words, and words every build request or block shares.
63
+ * Generic English function words, search's stopwords, and words every build
64
+ * request or block shares: never a reason to tie a block to a request.
141
65
  */
142
66
  const STOP = new Set([
143
67
  ...STOPWORDS,
144
- ...FUNCTION_WORDS,
68
+ ...(
69
+ 'about above across after again against all along already also although ' +
70
+ 'always am among amongst an and another any anyone anything anywhere are ' +
71
+ 'around as at be because been before behind being below beneath beside ' +
72
+ 'besides between beyond both but by can could despite did do does doing ' +
73
+ 'down during each either else enough even ever every everyone everything ' +
74
+ 'everywhere except few following for from further had has have having he ' +
75
+ 'her here hers herself him himself his how however if in inside instead ' +
76
+ 'into is it its itself just least less little lot lots many may maybe me ' +
77
+ 'might more most much must my myself near neither never no nobody none ' +
78
+ 'nor not nothing now nowhere of off often on once one ones only onto or ' +
79
+ 'other others ought our ours ourselves out outside over own past per ' +
80
+ 'perhaps quite rather same several shall she should since so some someone ' +
81
+ 'something sometimes somewhat somewhere still such than that the their ' +
82
+ 'theirs them themselves then there these they this those though through ' +
83
+ 'throughout thus till to together too toward towards under underneath ' +
84
+ 'unless unlike until up upon usually very via was we were what whatever ' +
85
+ 'when whenever where whereas whether which whichever while who whoever ' +
86
+ 'whom whomever whose why will with within without would yet you your ' +
87
+ 'yours yourself yourselves'
88
+ ).split(' '),
145
89
  ...(
146
90
  'a an the and or of for to in on with by at from as is are be this that ' +
147
91
  'it its my our your their me we you i into via per each all any some page ' +
@@ -152,101 +96,433 @@ const STOP = new Set([
152
96
  ]);
153
97
 
154
98
  /**
155
- * The content words of a text: its lowercase words of three or more letters
156
- * that are not in {@link STOP}.
99
+ * Words after which the rest of a request is where the new piece goes, not
100
+ * the piece itself ("a filter bar ABOVE the table").
101
+ */
102
+ const CONTEXT = new Set(
103
+ (
104
+ 'in on inside within into above below under beneath next beside to for ' +
105
+ 'with and from of near over across along around after before at'
106
+ ).split(' '),
107
+ );
108
+
109
+ /** How many of each kind of candidate the picker weighs. */
110
+ const POOL = {matches: 60, searched: 60, overlaps: 20};
111
+
112
+ /** How many matches carry a place; the rest share the last one's match. */
113
+ const TOP = 80;
114
+
115
+ /**
116
+ * A word with a plural or verb ending removed (words over four letters):
117
+ * "-ies" becomes "-y"; "-es" goes only after s, x, z, ch, or sh; otherwise a
118
+ * final "s" goes, but never after another "s"; then "-ing" or "-ed".
119
+ * @param {string} w
120
+ * @returns {string}
121
+ */
122
+ export function stemOf(w) {
123
+ if (w.length <= 4) return w;
124
+ if (w.endsWith('ies')) return `${w.slice(0, -3)}y`;
125
+ if (/(?:s|x|z|ch|sh)es$/.test(w)) return w.slice(0, -2);
126
+ if (w.endsWith('s') && !w.endsWith('ss')) return w.slice(0, -1);
127
+ if (w.endsWith('ing')) return w.slice(0, -3);
128
+ if (w.endsWith('ed')) return w.slice(0, -2);
129
+ return w;
130
+ }
131
+
132
+ /**
133
+ * An identifier's words, lowercase: "SideNavNestedItems" -> side, nav,
134
+ * nested, items.
135
+ * @param {string} text
136
+ * @returns {string[]}
137
+ */
138
+ export function wordsOf(text) {
139
+ return String(text)
140
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
141
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
142
+ .toLowerCase()
143
+ .split(/[^a-z0-9]+/)
144
+ .filter(Boolean);
145
+ }
146
+
147
+ /**
148
+ * A text's stemmed content words, then its adjacent pairs as `a_b`.
157
149
  * @param {string} text
158
150
  * @returns {string[]}
159
151
  */
160
- function contentWords(text) {
161
- const words =
152
+ export function termsOf(text) {
153
+ const words = (
162
154
  String(text)
163
155
  .toLowerCase()
164
- .match(/[a-z0-9]{3,}/g) ?? [];
165
- return [...new Set(words.filter(w => !STOP.has(w)))];
156
+ .match(/[a-z0-9]{2,}/g) ?? []
157
+ )
158
+ .filter(w => !STOP.has(w))
159
+ .map(stemOf);
160
+ const out = [...words];
161
+ for (let i = 0; i + 1 < words.length; i++)
162
+ out.push(`${words[i]}_${words[i + 1]}`);
163
+ return out;
166
164
  }
167
165
 
168
166
  /**
169
- * Whether a request names a block: a run of one to three adjacent words of
170
- * the request, joined, is the block's name, the start of its name that names
171
- * its component (at least four letters, whole words), or the plural of either.
172
- * @param {string[]} words the request's lowercase words
173
- * @param {string} block
174
- * @returns {boolean}
175
- */
176
- function names(words, block) {
177
- const parts = wordsOf(block);
178
- /** @type {Set<string>} */
179
- const forms = new Set();
180
- for (let n = 1; n <= parts.length; n++) {
181
- const form = parts.slice(0, n).join('');
182
- if (form.length >= 4) forms.add(form);
167
+ * The weights, decoded once per weights object.
168
+ * @type {WeakMap<BlockPickerWeights, {index: Map<string, number>, idf: Float64Array, request: Int8Array, doc: Int8Array}>}
169
+ */
170
+ const decoded = new WeakMap();
171
+
172
+ /** @param {BlockPickerWeights} weights */
173
+ function decode(weights) {
174
+ let d = decoded.get(weights);
175
+ if (!d) {
176
+ // Each byte is a signed weight stored offset by 128.
177
+ const bytes = (/** @type {string} */ s) =>
178
+ Int8Array.from(Buffer.from(s, 'base64'), b => b - 128);
179
+ d = {
180
+ index: new Map(weights.vocab.map((w, i) => [w, i])),
181
+ idf: Float64Array.from(weights.idf, x => x / 1024),
182
+ request: bytes(weights.request),
183
+ doc: bytes(weights.doc),
184
+ };
185
+ decoded.set(weights, d);
186
+ }
187
+ return d;
188
+ }
189
+
190
+ /**
191
+ * A text's sparse unit vector over the vocabulary: (1 + ln count) x idf.
192
+ * @param {string[]} terms
193
+ * @param {ReturnType<typeof decode>} d
194
+ * @returns {Map<number, number>}
195
+ */
196
+ function vectorOf(terms, d) {
197
+ /** @type {Map<number, number>} */
198
+ const counts = new Map();
199
+ for (const t of terms) {
200
+ const i = d.index.get(t);
201
+ if (i !== undefined) counts.set(i, (counts.get(i) ?? 0) + 1);
202
+ }
203
+ /** @type {Map<number, number>} */
204
+ const v = new Map();
205
+ let sq = 0;
206
+ for (const [i, c] of counts) {
207
+ const x = (1 + Math.log(c)) * d.idf[i];
208
+ v.set(i, x);
209
+ sq += x * x;
210
+ }
211
+ const norm = Math.sqrt(sq) || 1;
212
+ for (const [i, x] of v) v.set(i, x / norm);
213
+ return v;
214
+ }
215
+
216
+ /**
217
+ * A sparse vector through a signed byte matrix.
218
+ * @param {Map<number, number>} v
219
+ * @param {Int8Array} m
220
+ * @param {number} scale
221
+ * @param {number} dims
222
+ */
223
+ function project(v, m, scale, dims) {
224
+ const out = new Float64Array(dims);
225
+ for (const [i, x] of v) {
226
+ const row = i * dims;
227
+ for (let k = 0; k < dims; k++) out[k] += x * m[row + k];
228
+ }
229
+ for (let k = 0; k < dims; k++) out[k] *= scale;
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * Each block's component: the longest component name its name starts with,
235
+ * else the display name's part before " — ", without spaces.
236
+ * @param {CatalogBlock} block
237
+ * @param {string[]} componentNames longest first
238
+ */
239
+ function componentOf(block, componentNames) {
240
+ for (const c of componentNames) if (block.name.startsWith(c)) return c;
241
+ const display = block.displayName ?? block.name;
242
+ return display.split(' — ')[0].replace(/ /g, '');
243
+ }
244
+
245
+ /**
246
+ * The catalog, read once per weights and catalog contents: each block's
247
+ * component, docs vector and projection, and each component's name phrases.
248
+ * @type {WeakMap<BlockPickerWeights, {key: string, blocks: Map<string, {component: string, vector: Map<number, number>, projected: Float64Array}>, phrases: Map<string, [string[], number][]>}>}
249
+ */
250
+ const catalogs = new WeakMap();
251
+
252
+ /**
253
+ * @param {CatalogBlock[]} catalog
254
+ * @param {CatalogComponent[]} components
255
+ * @param {BlockPickerWeights} weights
256
+ */
257
+ function readCatalog(catalog, components, weights) {
258
+ const key = JSON.stringify([
259
+ catalog.map(b => [b.name, b.displayName, b.description]),
260
+ components.map(c => [c.name, c.keywords]),
261
+ ]);
262
+ const cached = catalogs.get(weights);
263
+ if (cached && cached.key === key) return cached;
264
+ const d = decode(weights);
265
+ const names = components.map(c => c.name).sort((a, b) => b.length - a.length);
266
+ const keywords = new Map(components.map(c => [c.name, c.keywords ?? []]));
267
+ /** @type {Map<string, {component: string, vector: Map<number, number>, projected: Float64Array}>} */
268
+ const blocks = new Map();
269
+ for (const b of catalog) {
270
+ if (blocks.has(b.name)) continue;
271
+ const component = componentOf(b, names);
272
+ const text = [
273
+ wordsOf(b.name).join(' '),
274
+ b.displayName ?? '',
275
+ b.description ?? '',
276
+ wordsOf(component).join(' '),
277
+ (keywords.get(component) ?? []).join(' '),
278
+ ].join(' ');
279
+ const vector = vectorOf(termsOf(text), d);
280
+ blocks.set(b.name, {
281
+ component,
282
+ vector,
283
+ projected: project(vector, d.doc, weights.docScale, weights.dims),
284
+ });
285
+ }
286
+ // A component is named by its own words, or by a keyword at most three
287
+ // components share (weighted by how few share it).
288
+ /** @type {Map<string, number>} */
289
+ const shared = new Map();
290
+ for (const c of components)
291
+ for (const k of new Set((c.keywords ?? []).map(k => k.replace(/-/g, ' '))))
292
+ shared.set(k, (shared.get(k) ?? 0) + 1);
293
+ const phrase = (/** @type {string} */ s) =>
294
+ s.toLowerCase().split(/\s+/).filter(Boolean).map(stemOf);
295
+ /** @type {Map<string, [string[], number][]>} */
296
+ const phrases = new Map();
297
+ const withBlocks = new Set([...blocks.values()].map(b => b.component));
298
+ for (const c of withBlocks) {
299
+ /** @type {[string[], number][]} */
300
+ const list = [[phrase(wordsOf(c).join(' ')), 3]];
301
+ for (const k of (keywords.get(c) ?? []).map(k => k.replace(/-/g, ' ')))
302
+ if ((shared.get(k) ?? 0) <= 3)
303
+ list.push([phrase(k), 1 / (shared.get(k) ?? 1)]);
304
+ phrases.set(c, list);
305
+ }
306
+ const read = {key, blocks, phrases};
307
+ catalogs.set(weights, read);
308
+ return read;
309
+ }
310
+
311
+ /**
312
+ * How strongly the request names each component: its best phrase, longer
313
+ * phrases and earlier ones stronger, and half as strong once the request has
314
+ * moved on to where the piece goes.
315
+ * @param {string} request
316
+ * @param {Map<string, [string[], number][]>} phrases
317
+ * @returns {Map<string, number>}
318
+ */
319
+ function namedComponents(request, phrases) {
320
+ const raw =
321
+ String(request)
322
+ .toLowerCase()
323
+ .match(/[a-z0-9]+/g) ?? [];
324
+ const stems = raw.map(stemOf);
325
+ let context = raw.findIndex((w, k) => k > 0 && CONTEXT.has(w));
326
+ if (context < 0) context = raw.length;
327
+ /** @type {Map<string, number>} */
328
+ const out = new Map();
329
+ for (const [c, list] of phrases) {
330
+ let best = 0;
331
+ for (const [p, w] of list) {
332
+ if (p.length === 0) continue;
333
+ let at = -1;
334
+ for (let i = 0; i + p.length <= stems.length && at < 0; i++)
335
+ if (p.every((x, k) => stems[i + k] === x)) at = i;
336
+ if (at < 0) continue;
337
+ const s =
338
+ w *
339
+ (1 + 0.3 * (p.length - 1)) *
340
+ (at < context ? 1 : 0.5) *
341
+ (1 - 0.01 * at);
342
+ if (s > best) best = s;
343
+ }
344
+ if (best) out.set(c, best);
183
345
  }
346
+ return out;
347
+ }
348
+
349
+ /**
350
+ * Whether the request writes out the block's exact name (its words joined).
351
+ * @param {string[]} words the request's identifier words
352
+ * @param {string} block
353
+ */
354
+ function writesName(words, block) {
355
+ const name = block.toLowerCase();
356
+ const length = wordsOf(block).length;
184
357
  for (let i = 0; i < words.length; i++) {
185
358
  let run = '';
186
- for (let n = 0; n < 3 && i + n < words.length; n++) {
359
+ for (let n = 0; n < length && i + n < words.length; n++) {
187
360
  run += words[i + n];
188
- for (const form of forms)
189
- if (run === form || pluralOf(run, form)) return true;
361
+ if (run === name) return true;
190
362
  }
191
363
  }
192
364
  return false;
193
365
  }
194
366
 
195
367
  /**
196
- * The blocks build names for a request, re-ranked by the picker.
368
+ * The blocks build names for a request, ranked by the picker.
197
369
  * @param {string} request
198
- * @param {{kitBlocks: string[], searched: BlockScore[], foreign: string[], blockText: Map<string, string>}} signals
199
- * build's signals: the kit's blocks, search's block results [id, score,
200
- * matched, total] in order, the blocks whose package is not Core's, and
201
- * each searched block's display name and description
370
+ * @param {{kitBlocks: string[], searched: BlockScore[], foreign: string[], catalog: CatalogBlock[], components: CatalogComponent[]}} signals
202
371
  * @param {BlockPickerWeights} weights
203
- * @returns {string[]} as many blocks as build's own list: a block the request
204
- * names, one the weights do not know, or one an integration ships keeps its
205
- * slot; the picker's best, from build's blocks and search's, fill the others
372
+ * @returns {{names: string[], entries: Map<string, SearchResultEntry>}} as
373
+ * many names as build's own list, best first; an entry for each listed
374
+ * block search did not return
206
375
  */
207
376
  export function pickBlocks(request, signals, weights) {
208
377
  const own = signals.kitBlocks;
209
- if (own.length === 0) return [];
210
- const {z, lse} = linearScores(request, weights);
211
- const classIndex = new Map(weights.classes.map((c, i) => [c, i]));
212
- /** @type {Map<string, BlockScore>} */
378
+ /** @type {Map<string, SearchResultEntry>} */
379
+ const entries = new Map();
380
+ if (own.length === 0) return {names: [], entries};
381
+ const d = decode(weights);
382
+ const cat = readCatalog(signals.catalog, signals.components, weights);
383
+ const q = vectorOf(termsOf(request), d);
384
+ const eq = project(q, d.request, weights.requestScale, weights.dims);
385
+ const dot = (/** @type {Map<number, number>} */ v) => {
386
+ let s = 0;
387
+ for (const [i, x] of q) {
388
+ const y = v.get(i);
389
+ if (y !== undefined) s += x * y;
390
+ }
391
+ return s;
392
+ };
393
+ /** @type {Map<string, {match: number, overlap: number}>} */
394
+ const scored = new Map();
395
+ for (const [name, b] of cat.blocks) {
396
+ let s = 0;
397
+ for (let k = 0; k < weights.dims; k++) s += eq[k] * b.projected[k];
398
+ const overlap = dot(b.vector);
399
+ scored.set(name, {match: s + weights.lexical * overlap, overlap});
400
+ }
401
+ const get = (/** @type {string} */ b) =>
402
+ scored.get(b) ?? {match: -Infinity, overlap: 0};
403
+ const ranked = [...scored.keys()].sort((a, b) => get(b).match - get(a).match);
404
+ const top = ranked.slice(0, TOP);
405
+ const best = top.length ? get(top[0]).match : 0;
406
+ const second = top.length > 1 ? get(top[1]).match : 0;
407
+ const floor = top.length ? get(top[top.length - 1]).match : 0;
408
+ const place = new Map(top.map((b, k) => [b, k]));
409
+ /** @type {Map<string, [BlockScore, number]>} */
213
410
  const found = new Map();
214
- for (const s of signals.searched) if (!found.has(s[0])) found.set(s[0], s);
411
+ signals.searched.forEach((s, k) => {
412
+ if (!found.has(s[0])) found.set(s[0], [s, k]);
413
+ });
414
+ const overlaps = [...scored.keys()]
415
+ .filter(b => get(b).overlap > 0)
416
+ .sort((a, b) => get(b).overlap - get(a).overlap || (a < b ? -1 : 1));
417
+ const pool = [
418
+ ...new Set([
419
+ ...own,
420
+ ...top.slice(0, POOL.matches),
421
+ ...signals.searched.slice(0, POOL.searched).map(s => s[0]),
422
+ ...overlaps.slice(0, POOL.overlaps),
423
+ ]),
424
+ ].filter(b => scored.has(b) || found.has(b));
425
+ const known = new Set(weights.known);
426
+ const named = namedComponents(request, cat.phrases);
427
+ const t = weights.theta;
428
+ const final = pool.map((b, pos) => {
429
+ const m = place.has(b) ? get(b).match : floor;
430
+ const f = found.get(b);
431
+ const s = f?.[0];
432
+ const component = cat.blocks.get(b)?.component;
433
+ const score =
434
+ t.g * (m - best) +
435
+ t.grank * (place.get(b) ?? 99) +
436
+ t.gmargin * (m - second) +
437
+ t.seen * (known.has(b) ? 1 : 0) +
438
+ t.lex * get(b).overlap +
439
+ t.sscore * (s ? s[1] / 100 : 0) +
440
+ t.scov * (s ? (s[2] ?? 0) / Math.max(s[3] ?? 0, 1) : 0) +
441
+ t.srank * (f ? f[1] : 300) +
442
+ t.inkit * (own.includes(b) ? 1 : 0) +
443
+ t.kitpos * (own.includes(b) ? own.indexOf(b) : 9) +
444
+ t.mention * (component ? (named.get(component) ?? 0) : 0) +
445
+ t.show * (/Showcase|Basic/.test(b) ? 1 : 0);
446
+ return {b, pos, score};
447
+ });
448
+ final.sort((a, b) => b.score - a.score || a.pos - b.pos);
215
449
  const foreign = new Set(signals.foreign);
216
450
  const words = wordsOf(request);
217
- const keeps = own.map(
218
- b => !classIndex.has(b) || foreign.has(b) || names(words, b),
219
- );
220
- /** @type {Map<string, number>} */
221
- const place = new Map();
222
- for (const b of [...own, ...signals.searched.map(s => s[0])])
223
- if (!place.has(b)) place.set(b, place.size);
224
- const requestWords = contentWords(request);
225
- // The same word, up to plural and stem form, as search reads it.
226
- const shares = (/** @type {string} */ b) =>
227
- contentWords(
228
- `${wordsOf(b).join(' ')} ${signals.blockText.get(b) ?? ''}`,
229
- ).some(v => requestWords.some(w => sameWord(w, v)));
230
- const pool = own.filter((_, k) => !keeps[k]);
231
- for (const [b] of signals.searched.slice(0, SEARCH_POOL)) {
232
- if (own.includes(b) || pool.includes(b)) continue;
233
- if (!classIndex.has(b) || foreign.has(b) || !shares(b)) continue;
234
- pool.push(b);
235
- }
236
- const [t0, t1, t2, t3, t4] = weights.theta;
237
- const scored = pool
238
- .map((b, pos) => {
239
- const s = found.get(b);
240
- const c = classIndex.get(b);
241
- const at = place.get(b);
242
- const f0 = s ? s[1] / 100 : 0;
243
- const f1 = s ? (s[2] ?? 0) / Math.max(s[3] ?? 0, 1) : 0;
244
- const f2 = own.includes(b) ? 1 : 0;
245
- const f3 = at === undefined ? 0 : 1 / (1 + at);
246
- const f4 = (c === undefined ? UNSCORED : z[c]) - lse;
247
- return {b, pos, s: t0 * f0 + t1 * f1 + t2 * f2 + t3 * f3 + t4 * f4};
248
- })
249
- .sort((a, b) => b.s - a.s || a.pos - b.pos);
451
+ const keeps = own.map(b => foreign.has(b) || writesName(words, b));
452
+ const kept = new Set(own.filter((_, k) => keeps[k]));
453
+ const order = [
454
+ ...final.map(x => x.b).filter(b => !kept.has(b) && !foreign.has(b)),
455
+ ...own.filter(b => !kept.has(b)),
456
+ ];
457
+ /** @type {string[]} */
458
+ const out = [];
250
459
  let next = 0;
251
- return own.map((b, k) => (keeps[k] ? b : scored[next++].b));
460
+ for (let k = 0; k < own.length; k++) {
461
+ if (keeps[k]) {
462
+ out.push(own[k]);
463
+ continue;
464
+ }
465
+ while (out.includes(order[next])) next++;
466
+ out.push(order[next++]);
467
+ }
468
+ // A listed block search did not return gets the picker's own entry: its
469
+ // score (100 for the best candidate, less by how far it trails, never
470
+ // below 1) and the request words that tie it to its docs.
471
+ const max = Math.max(...final.map(x => x.score));
472
+ const byName = new Map(signals.catalog.map(b => [b.name, b]));
473
+ for (const name of out) {
474
+ if (found.has(name) || own.includes(name)) continue;
475
+ const block = byName.get(name);
476
+ const x = final.find(f => f.b === name);
477
+ if (!block || !x) continue;
478
+ entries.set(name, {
479
+ domain: 'template',
480
+ name,
481
+ package: block.package ?? '',
482
+ score: Math.max(1, Math.round(100 * Math.exp(x.score - max))),
483
+ reason: reasonFor(request, cat.blocks.get(name), d, weights),
484
+ description: block.description ?? '',
485
+ displayName: block.displayName,
486
+ kind: 'block',
487
+ command: block.command ?? '',
488
+ });
489
+ }
490
+ return {names: out, entries};
491
+ }
492
+
493
+ /**
494
+ * Why a block fits: the request words that tie it to its docs most.
495
+ * @param {string} request
496
+ * @param {{vector: Map<number, number>, projected: Float64Array} | undefined} block
497
+ * @param {ReturnType<typeof decode>} d
498
+ * @param {BlockPickerWeights} weights
499
+ */
500
+ function reasonFor(request, block, d, weights) {
501
+ if (!block) return 'fits by meaning';
502
+ const raw =
503
+ String(request)
504
+ .toLowerCase()
505
+ .match(/[a-z0-9]{2,}/g) ?? [];
506
+ /** @type {Map<string, string>} */
507
+ const wordOf = new Map();
508
+ for (const w of raw)
509
+ if (!STOP.has(w) && !wordOf.has(stemOf(w))) wordOf.set(stemOf(w), w);
510
+ const q = vectorOf(termsOf(request), d);
511
+ /** @type {[string, number][]} */
512
+ const parts = [];
513
+ for (const [i, x] of q) {
514
+ const term = weights.vocab[i];
515
+ if (term.includes('_')) continue;
516
+ let s = 0;
517
+ const row = i * weights.dims;
518
+ for (let k = 0; k < weights.dims; k++)
519
+ s += d.request[row + k] * block.projected[k];
520
+ s =
521
+ x * s * weights.requestScale +
522
+ weights.lexical * x * (block.vector.get(i) ?? 0);
523
+ if (s > 0) parts.push([wordOf.get(term) ?? term, s]);
524
+ }
525
+ parts.sort((a, b) => b[1] - a[1]);
526
+ const top = parts.slice(0, 3).map(p => p[0]);
527
+ return top.length ? `fits by meaning: ${top.join(', ')}` : 'fits by meaning';
252
528
  }