dsh-capability-trimmer 0.0.0-stage → 1.0.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.
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: capability-trimmer
3
+ name: 'dsh-capability-trimmer'
package/core.mjs ADDED
@@ -0,0 +1,284 @@
1
+ /**
2
+ * capability-audit core — pure overlap scoring, vendored verbatim from the
3
+ * capability-audit project (SCORING_VERSION '2026-12-01.4').
4
+ * Only the pure-scoring section is vendored; the CLI discovery section is
5
+ * not needed by the plugin. Bump together with the source when the formula
6
+ * changes so drift stays detectable.
7
+ */
8
+
9
+ export const SCORING_VERSION = '2026-12-01.4'
10
+
11
+ // Function words plus the generic verbs that appear in almost every tool
12
+ // description. Left in, they form a noise floor that pushes unrelated
13
+ // capabilities above genuinely related ones.
14
+ const STOPWORDS = new Set([
15
+ 'the', 'and', 'for', 'with', 'from', 'this', 'that', 'you', 'your', 'use', 'used',
16
+ 'uses', 'when', 'not', 'are', 'can', 'will', 'has', 'have', 'its', 'to', 'of', 'in',
17
+ 'on', 'or', 'as', 'by', 'at', 'is', 'be', 'do', 'does', 'all', 'any', 'one', 'per',
18
+ 'via', 'into', 'over', 'than', 'then', 'them', 'they', 'his', 'her', 'also',
19
+ 'call', 'calls', 'called', 'run', 'runs', 'running', 'return', 'returns', 'returned',
20
+ 'result', 'results', 'before', 'after', 'each', 'using', 'being', 'make', 'makes',
21
+ 'other', 'same', 'only', 'more', 'most', 'such', 'very', 'well', 'must', 'may',
22
+ 'should', 'would', 'could', 'execute', 'instead', 'without', 'within', 'including',
23
+ 'which', 'where', 'while', 'there', 'these', 'those', 'just', 'like', 'both',
24
+ 'either', 'neither', 'new', 'old', 'first', 'last', 'next', 'own', 'get', 'gets',
25
+ 'set', 'sets', 'added', 'need', 'needs', 'want', 'wants', 'help', 'helps', 'allow',
26
+ 'allows', 'allowed', 'support', 'supports', 'work', 'works', 'working', 'way', 'ways',
27
+ 'case', 'cases', 'thing', 'things', 'part', 'parts', 'value', 'values', 'item',
28
+ 'items', 'name', 'names', 'type', 'types', 'mode', 'modes', 'time', 'times', 'level',
29
+ 'levels', 'number', 'numbers', 'via', 'etc', 'when', 'step', 'steps', 'option',
30
+ 'options', 'shows', 'show', 'shown', 'given', 'give', 'gives', 'whether', 'already',
31
+ 'still', 'even', 'ever', 'never', 'always', 'sometimes', 'usually',
32
+ 'list', 'lists', 'their', 'ids', 'was', 'were', 'reports', 'report', 'complete',
33
+ 'larger', 'smaller', 'saved', 'said', 'take', 'takes', 'put', 'puts', 'iramcli',
34
+ ])
35
+
36
+ /** Drop the harness transport prefix, e.g. `mcp__joytest__db_get_table` -> `db_get_table`. */
37
+ export function shortLabel(label) {
38
+ return String(label ?? '')
39
+ .replace(/^mcp__[A-Za-z0-9_-]{1,32}__/, '')
40
+ .replace(/^iramcli-/, '')
41
+ }
42
+
43
+ const LATIN_WORD = /[a-z][a-z0-9_]*/g
44
+ const CJK_RUN = /[\u3400-\u9fff]+/g
45
+
46
+ /** Keep letters and digits only. */
47
+ export function normalize(text) {
48
+ return String(text ?? '').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '')
49
+ }
50
+
51
+ /**
52
+ * Tokens for similarity: Latin words and word pairs, Chinese character bigrams.
53
+ *
54
+ * Character bigrams are right for Chinese (no segmenter needed) but wrong for
55
+ * English, where "ru", "as" and "th" appear in nearly every sentence and swamp
56
+ * the signal. Latin text is therefore tokenized by word.
57
+ */
58
+ export function tokens(text) {
59
+ const source = String(text ?? '').toLowerCase()
60
+ const out = new Set()
61
+
62
+ const words = (source.match(LATIN_WORD) ?? []).filter((word) => word.length >= 2 && !STOPWORDS.has(word))
63
+ for (const word of words) out.add(`w:${word}`)
64
+ for (let i = 0; i + 1 < words.length; i += 1) out.add(`p:${words[i]}_${words[i + 1]}`)
65
+
66
+ for (const run of source.match(CJK_RUN) ?? []) {
67
+ for (let i = 0; i + 1 < run.length; i += 1) out.add(`c:${run.slice(i, i + 2)}`)
68
+ }
69
+ return out
70
+ }
71
+
72
+ /** Jaccard similarity of two sets. */
73
+ export function jaccard(a, b) {
74
+ if (a.size === 0 || b.size === 0) return 0
75
+ let inter = 0
76
+ for (const item of a) if (b.has(item)) inter += 1
77
+ return inter / (a.size + b.size - inter)
78
+ }
79
+
80
+ /** Distinguishing ASCII tokens: technology and product names. */
81
+ export function entities(text) {
82
+ const out = new Set()
83
+ for (const token of String(text ?? '').toLowerCase().match(/[a-z][a-z0-9_.-]{2,}/g) ?? []) {
84
+ const cleaned = token.replace(/[.-]+$/, '')
85
+ if (cleaned.length < 3 || STOPWORDS.has(cleaned)) continue
86
+ out.add(cleaned)
87
+ }
88
+ return out
89
+ }
90
+
91
+ /** The `触发词:` list, as whole tokens. This is the routing signal. */
92
+ export function triggerTokens(description) {
93
+ const match = String(description ?? '').match(/触发词[::]\s*([^。\n]*)/)
94
+ if (!match) return new Set()
95
+ return new Set(
96
+ match[1]
97
+ .split(/[、,,;;/|]/)
98
+ .map((part) => part.trim().toLowerCase())
99
+ .filter((part) => part.length >= 2),
100
+ )
101
+ }
102
+
103
+ /** Name tokens, split on separators. */
104
+ export function nameTokens(label) {
105
+ return new Set(
106
+ String(label ?? '').toLowerCase().split(/[-_.:/]+/).filter((p) => p.length > 1 && !STOPWORDS.has(p)),
107
+ )
108
+ }
109
+
110
+ /** Name family = everything before the first separator. */
111
+ export function familyOf(label) {
112
+ const head = String(label ?? '').split(/[-_.:/]/)[0]
113
+ return head.length > 1 ? head : ''
114
+ }
115
+
116
+ /**
117
+ * Build corpus statistics once, so pairwise comparison is length-normalized.
118
+ * A record needs `{ label, description, whenToUse?, kind?, source? }`.
119
+ */
120
+ export function buildIndex(records) {
121
+ const docs = records.map((r) => tokens(`${r.description ?? ''} ${r.whenToUse ?? ''}`))
122
+ const df = new Map()
123
+ for (const doc of docs) for (const gram of doc) df.set(gram, (df.get(gram) ?? 0) + 1)
124
+ const total = records.length
125
+ const weightOf = (gram) => Math.log(1 + total / (df.get(gram) ?? 1))
126
+ const norms = docs.map((doc) => {
127
+ let sum = 0
128
+ for (const gram of doc) {
129
+ const w = weightOf(gram)
130
+ sum += w * w
131
+ }
132
+ return Math.sqrt(sum) || 1
133
+ })
134
+ return { docs, weightOf, norms, total }
135
+ }
136
+
137
+ /** TF-IDF weighted cosine: down-weights corpus-wide boilerplate, normalizes length. */
138
+ export function cosine(index, i, j) {
139
+ const a = index.docs[i]
140
+ const b = index.docs[j]
141
+ let dot = 0
142
+ for (const gram of a) {
143
+ if (!b.has(gram)) continue
144
+ const w = index.weightOf(gram)
145
+ dot += w * w
146
+ }
147
+ return dot / (index.norms[i] * index.norms[j])
148
+ }
149
+
150
+ /**
151
+ * Thresholds are deliberately not exposed as a label: on Chinese skill corpora
152
+ * raw scores stay far below the English-tuned bands, so any fixed wording would
153
+ * call everything "mild". The ranked order and the component breakdown are the
154
+ * signal; the absolute number is only a sort key.
155
+ */
156
+
157
+ /**
158
+ * Score every pair and group name families.
159
+ * @param {Array<object>} records - capabilities to compare.
160
+ * @param {object} [options] - `{ minScore?, top = 10 }`; omit minScore to auto-calibrate.
161
+ */
162
+ export function audit(records, options = {}) {
163
+ const minScore = options.minScore
164
+ const top = options.top ?? 10
165
+
166
+ if (records.length < 2) {
167
+ return {
168
+ scoringVersion: SCORING_VERSION,
169
+ counts: { compared: records.length },
170
+ threshold: minScore,
171
+ pairs: [],
172
+ clusters: [],
173
+ note: 'fewer than two capabilities; nothing to compare',
174
+ }
175
+ }
176
+
177
+ const index = buildIndex(records)
178
+ const shortOf = new Map(records.map((r) => [r.label, shortLabel(r.label)]))
179
+ const trigrams = records.map((r) => triggerTokens(r.description))
180
+
181
+ // Raw TF-IDF cosine lands in a narrow band that depends on the corpus, so the
182
+ // 0.5 weight quietly lost its meaning and name similarity started deciding
183
+ // every pair. Rescale monotonically against the corpus's own 90th percentile:
184
+ // ordering is preserved and each component spans roughly [0, 1] again.
185
+ const size = records.length
186
+ const rawDesc = new Float64Array(size * size)
187
+ const sample = []
188
+ for (let i = 0; i < size; i += 1) {
189
+ for (let j = i + 1; j < size; j += 1) {
190
+ const value = cosine(index, i, j)
191
+ rawDesc[i * size + j] = value
192
+ sample.push(value)
193
+ }
194
+ }
195
+ const peak = Math.max(...sample, 1e-6)
196
+
197
+ const pairs = []
198
+ for (let i = 0; i < size; i += 1) {
199
+ for (let j = i + 1; j < size; j += 1) {
200
+ const left = records[i]
201
+ const right = records[j]
202
+
203
+ const descSim = rawDesc[i * size + j] / peak
204
+ const triggerSim = jaccard(trigrams[i], trigrams[j])
205
+ const nameSim = jaccard(nameTokens(shortOf.get(left.label)), nameTokens(shortOf.get(right.label)))
206
+ const sharedTerms = [...entities(`${left.label} ${left.description}`)]
207
+ .filter((term) => entities(`${right.label} ${right.description}`).has(term))
208
+
209
+ const score = 0.5 * descSim
210
+ + 0.25 * triggerSim
211
+ + 0.15 * nameSim
212
+ + 0.1 * Math.min(sharedTerms.length / 3, 1)
213
+
214
+ const reasons = []
215
+ if (descSim >= 0.5) reasons.push(`descriptions overlap ${descSim.toFixed(2)}`)
216
+ if (triggerSim >= 0.2) reasons.push(`shared trigger words ${triggerSim.toFixed(2)}`)
217
+ if (nameSim >= 0.34) reasons.push(`similar names ${nameSim.toFixed(2)}`)
218
+ if (sharedTerms.length >= 2) reasons.push(`shared terms: ${sharedTerms.slice(0, 6).join(', ')}`)
219
+
220
+ pairs.push({
221
+ left: left.label,
222
+ right: right.label,
223
+ leftKind: left.kind ?? 'unknown',
224
+ rightKind: right.kind ?? 'unknown',
225
+ leftSource: left.source ?? '',
226
+ rightSource: right.source ?? '',
227
+ score: Math.round(score * 1000) / 1000,
228
+ // Same family AND same kind is structural: a skill that documents a tool is
229
+ // not duplication, it is packaging. Cross-kind pairs stay in the ranking.
230
+ sameFamily: left.kind === right.kind
231
+ && familyOf(shortOf.get(left.label)) === familyOf(shortOf.get(right.label))
232
+ && familyOf(shortOf.get(left.label)) !== '',
233
+ sharedTerms: sharedTerms.slice(0, 8),
234
+ reasons,
235
+ })
236
+ }
237
+ }
238
+ pairs.sort((a, b) => b.score - a.score)
239
+
240
+ // Absolute thresholds do not travel: Chinese skill corpora share far fewer
241
+ // bigrams than English prose, so a fixed 0.45 reports nothing at all. When no
242
+ // threshold is given, the cut adapts to the Nth best pair, so the report is
243
+ // always a ranking rather than an empty page.
244
+ // Same-family pairs are structural, not actionable: the cluster view already
245
+ // covers them. Keeping them out of the pair list is what makes it worth reading.
246
+ const pool = options.includeIntraFamily ? pairs : pairs.filter((pair) => !pair.sameFamily)
247
+ const cut = Number.isFinite(minScore) ? minScore : (pool[top - 1]?.score ?? 0)
248
+ const kept = pool.filter((pair) => pair.score >= cut)
249
+
250
+ const buckets = new Map()
251
+ for (const record of records) {
252
+ const family = familyOf(shortOf.get(record.label))
253
+ if (!family) continue
254
+ const list = buckets.get(family) ?? []
255
+ list.push(record.label)
256
+ buckets.set(family, list)
257
+ }
258
+ const clusters = [...buckets.entries()]
259
+ .filter(([, members]) => members.length >= 3)
260
+ .map(([prefix, members]) => {
261
+ const inside = pairs.filter((p) => familyOf(shortOf.get(p.left)) === prefix && familyOf(shortOf.get(p.right)) === prefix)
262
+ const worst = inside.length ? inside.reduce((a, b) => (b.score > a.score ? b : a)) : null
263
+ return {
264
+ prefix,
265
+ count: members.length,
266
+ maxIntraScore: worst ? worst.score : 0,
267
+ worstPair: worst ? `${worst.left} x ${worst.right}` : '',
268
+ members: members.sort(),
269
+ }
270
+ })
271
+ .sort((a, b) => b.count - a.count)
272
+
273
+ return {
274
+ scoringVersion: SCORING_VERSION,
275
+ counts: { compared: records.length },
276
+ threshold: Math.round(cut * 1000) / 1000,
277
+ adaptive: !Number.isFinite(minScore),
278
+ pairs: kept.slice(0, top),
279
+ clusters: clusters.slice(0, 5),
280
+ note: kept.length > top
281
+ ? `${kept.length} pairs at or above ${Math.round(cut * 1000) / 1000}; showing ${top}.`
282
+ : `${kept.length} pairs at or above ${Math.round(cut * 1000) / 1000}.`,
283
+ }
284
+ }
package/icon.svg ADDED
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Capability manager">
2
+ <rect x="6" y="10" width="52" height="10" rx="5" fill="#3b6fe0"/>
3
+ <rect x="6" y="27" width="34" height="10" rx="5" fill="#8fb1f5"/>
4
+ <rect x="6" y="44" width="22" height="10" rx="5" fill="#c9d6ef"/>
5
+ <circle cx="49" cy="32" r="9" fill="none" stroke="#3b6fe0" stroke-width="3"/>
6
+ <path d="M45.5 32.5l2.6 2.6 4.6-5.2" fill="none" stroke="#3b6fe0" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
7
+ <circle cx="49" cy="49" r="9" fill="none" stroke="#c9d6ef" stroke-width="3"/>
8
+ </svg>