-
Notifications
You must be signed in to change notification settings - Fork 543
Expand file tree
/
Copy pathrules.ts
More file actions
326 lines (300 loc) · 9.55 KB
/
rules.ts
File metadata and controls
326 lines (300 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/**
* Rule-Based Classifier (v2 — Weighted Scoring)
*
* Scores a request across 14 weighted dimensions and maps the aggregate
* score to a tier using configurable boundaries. Confidence is calibrated
* via sigmoid — low confidence triggers the fallback classifier.
*
* Handles 70-80% of requests in < 1ms with zero cost.
*/
import type { Tier, ScoringResult, ScoringConfig } from "./types.js";
type DimensionScore = { name: string; score: number; signal: string | null };
// ─── Dimension Scorers ───
// Each returns a score in [-1, 1] and an optional signal string.
function scoreTokenCount(
estimatedTokens: number,
thresholds: { simple: number; complex: number },
): DimensionScore {
if (estimatedTokens < thresholds.simple) {
return { name: "tokenCount", score: -1.0, signal: `short (${estimatedTokens} tokens)` };
}
if (estimatedTokens > thresholds.complex) {
return { name: "tokenCount", score: 1.0, signal: `long (${estimatedTokens} tokens)` };
}
return { name: "tokenCount", score: 0, signal: null };
}
function scoreKeywordMatch(
text: string,
keywords: string[],
name: string,
signalLabel: string,
thresholds: { low: number; high: number },
scores: { none: number; low: number; high: number },
): DimensionScore {
const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));
if (matches.length >= thresholds.high) {
return {
name,
score: scores.high,
signal: `${signalLabel} (${matches.slice(0, 3).join(", ")})`,
};
}
if (matches.length >= thresholds.low) {
return {
name,
score: scores.low,
signal: `${signalLabel} (${matches.slice(0, 3).join(", ")})`,
};
}
return { name, score: scores.none, signal: null };
}
function scoreMultiStep(text: string): DimensionScore {
const patterns = [/first.*then/i, /step \d/i, /\d\.\s/];
const hits = patterns.filter((p) => p.test(text));
if (hits.length > 0) {
return { name: "multiStepPatterns", score: 0.5, signal: "multi-step" };
}
return { name: "multiStepPatterns", score: 0, signal: null };
}
function scoreQuestionComplexity(prompt: string): DimensionScore {
const count = (prompt.match(/\?/g) || []).length;
if (count > 3) {
return { name: "questionComplexity", score: 0.5, signal: `${count} questions` };
}
return { name: "questionComplexity", score: 0, signal: null };
}
/**
* Score agentic task indicators.
* Returns agenticScore (0-1) based on keyword matches:
* - 4+ matches = 1.0 (high agentic)
* - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)
* - 1-2 matches = 0.2 (low agentic)
*
* Thresholds raised because common keywords were pruned from the list.
*/
function scoreAgenticTask(
text: string,
keywords: string[],
): { dimensionScore: DimensionScore; agenticScore: number } {
let matchCount = 0;
const signals: string[] = [];
for (const keyword of keywords) {
if (text.includes(keyword.toLowerCase())) {
matchCount++;
if (signals.length < 3) {
signals.push(keyword);
}
}
}
// Threshold-based scoring (raised thresholds after keyword pruning)
if (matchCount >= 4) {
return {
dimensionScore: {
name: "agenticTask",
score: 1.0,
signal: `agentic (${signals.join(", ")})`,
},
agenticScore: 1.0,
};
} else if (matchCount >= 3) {
return {
dimensionScore: {
name: "agenticTask",
score: 0.6,
signal: `agentic (${signals.join(", ")})`,
},
agenticScore: 0.6,
};
} else if (matchCount >= 1) {
return {
dimensionScore: {
name: "agenticTask",
score: 0.2,
signal: `agentic-light (${signals.join(", ")})`,
},
agenticScore: 0.2,
};
}
return {
dimensionScore: { name: "agenticTask", score: 0, signal: null },
agenticScore: 0,
};
}
// ─── Main Classifier ───
export function classifyByRules(
prompt: string,
systemPrompt: string | undefined,
estimatedTokens: number,
config: ScoringConfig,
): ScoringResult {
// Score against user prompt only — system prompts contain boilerplate keywords
// (tool definitions, skill descriptions, behavioral rules) that dominate scoring
// and make every request score identically. See GitHub issue #50.
const userText = prompt.toLowerCase();
// Score all 14 dimensions against user text only
const dimensions: DimensionScore[] = [
// Token count uses total estimated tokens (system + user) — context size matters for model selection
scoreTokenCount(estimatedTokens, config.tokenCountThresholds),
scoreKeywordMatch(
userText,
config.codeKeywords,
"codePresence",
"code",
{ low: 1, high: 2 },
{ none: 0, low: 0.5, high: 1.0 },
),
scoreKeywordMatch(
userText,
config.reasoningKeywords,
"reasoningMarkers",
"reasoning",
{ low: 1, high: 2 },
{ none: 0, low: 0.7, high: 1.0 },
),
scoreKeywordMatch(
userText,
config.technicalKeywords,
"technicalTerms",
"technical",
{ low: 2, high: 4 },
{ none: 0, low: 0.5, high: 1.0 },
),
scoreKeywordMatch(
userText,
config.creativeKeywords,
"creativeMarkers",
"creative",
{ low: 1, high: 2 },
{ none: 0, low: 0.5, high: 0.7 },
),
scoreKeywordMatch(
userText,
config.simpleKeywords,
"simpleIndicators",
"simple",
{ low: 1, high: 2 },
{ none: 0, low: -1.0, high: -1.0 },
),
scoreMultiStep(userText),
scoreQuestionComplexity(prompt),
// 6 new dimensions
scoreKeywordMatch(
userText,
config.imperativeVerbs,
"imperativeVerbs",
"imperative",
{ low: 1, high: 2 },
{ none: 0, low: 0.3, high: 0.5 },
),
scoreKeywordMatch(
userText,
config.constraintIndicators,
"constraintCount",
"constraints",
{ low: 1, high: 3 },
{ none: 0, low: 0.3, high: 0.7 },
),
scoreKeywordMatch(
userText,
config.outputFormatKeywords,
"outputFormat",
"format",
{ low: 1, high: 2 },
{ none: 0, low: 0.4, high: 0.7 },
),
scoreKeywordMatch(
userText,
config.referenceKeywords,
"referenceComplexity",
"references",
{ low: 1, high: 2 },
{ none: 0, low: 0.3, high: 0.5 },
),
scoreKeywordMatch(
userText,
config.negationKeywords,
"negationComplexity",
"negation",
{ low: 2, high: 3 },
{ none: 0, low: 0.3, high: 0.5 },
),
scoreKeywordMatch(
userText,
config.domainSpecificKeywords,
"domainSpecificity",
"domain-specific",
{ low: 1, high: 2 },
{ none: 0, low: 0.5, high: 0.8 },
),
];
// Score agentic task indicators — user prompt only
// System prompt describes assistant behavior, not user's intent.
// e.g. a coding assistant system prompt with "edit files" / "fix bugs" should NOT
// force every request into agentic mode.
const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);
dimensions.push(agenticResult.dimensionScore);
const agenticScore = agenticResult.agenticScore;
// Collect signals
const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);
// Compute weighted score
const weights = config.dimensionWeights;
let weightedScore = 0;
for (const d of dimensions) {
const w = weights[d.name] ?? 0;
weightedScore += d.score * w;
}
// Count reasoning markers for override — only check USER prompt, not system prompt
// This prevents system prompts with "step by step" from triggering REASONING for simple queries
const reasoningMatches = config.reasoningKeywords.filter((kw) =>
userText.includes(kw.toLowerCase()),
);
// Direct reasoning override: 2+ reasoning markers = high confidence REASONING
if (reasoningMatches.length >= 2) {
const confidence = calibrateConfidence(
Math.max(weightedScore, 0.3), // ensure positive for confidence calc
config.confidenceSteepness,
);
return {
score: weightedScore,
tier: "REASONING",
confidence: Math.max(confidence, 0.85),
signals,
agenticScore,
dimensions,
};
}
// Map weighted score to tier using boundaries
const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;
let tier: Tier;
let distanceFromBoundary: number;
if (weightedScore < simpleMedium) {
tier = "SIMPLE";
distanceFromBoundary = simpleMedium - weightedScore;
} else if (weightedScore < mediumComplex) {
tier = "MEDIUM";
distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);
} else if (weightedScore < complexReasoning) {
tier = "COMPLEX";
distanceFromBoundary = Math.min(
weightedScore - mediumComplex,
complexReasoning - weightedScore,
);
} else {
tier = "REASONING";
distanceFromBoundary = weightedScore - complexReasoning;
}
// Calibrate confidence via sigmoid of distance from nearest boundary
const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);
// If confidence is below threshold → ambiguous
if (confidence < config.confidenceThreshold) {
return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };
}
return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };
}
/**
* Sigmoid confidence calibration.
* Maps distance from tier boundary to [0.5, 1.0] confidence range.
*/
function calibrateConfidence(distance: number, steepness: number): number {
return 1 / (1 + Math.exp(-steepness * distance));
}