-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtask_fingerprint.rs
More file actions
450 lines (421 loc) · 14.5 KB
/
Copy pathtask_fingerprint.rs
File metadata and controls
450 lines (421 loc) · 14.5 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Semantic coding-task fingerprints (spec §7.3).
//!
//! Replaces tool-only recurrence signatures ([`crate::pattern_log`]) with a
//! richer, stable description of *what kind of coding work* a turn performed.
//! Matching uses set overlap — exact tool sequences are intentionally NOT the
//! primary signal so similar tasks remain recognizable across different
//! agent tool choices.
#![allow(dead_code)]
use serde::{Deserialize, Serialize};
/// Compact semantic fingerprint of a coding task.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct TaskFingerprint {
/// Coarse intent label, e.g. `extend-tool-schema`, `fix-bug`.
#[serde(default)]
pub intent: String,
#[serde(default)]
pub subsystems: Vec<String>,
#[serde(default)]
pub languages: Vec<String>,
#[serde(default)]
pub frameworks: Vec<String>,
#[serde(default)]
pub symbols: Vec<String>,
#[serde(default)]
pub file_categories: Vec<String>,
#[serde(default)]
pub operations: Vec<String>,
#[serde(default)]
pub diagnostic_classes: Vec<String>,
#[serde(default)]
pub validation_classes: Vec<String>,
}
/// Inputs used to build a fingerprint from a completed (or in-progress) turn.
#[derive(Clone, Debug, Default)]
pub struct FingerprintInputs<'a> {
pub user_intent: &'a str,
pub files_read: &'a [String],
pub files_changed: &'a [String],
pub symbols: &'a [String],
pub tools_used: &'a [String],
pub diagnostics: &'a [String],
pub tests_run: &'a [String],
}
/// Build a [`TaskFingerprint`] from turn evidence.
pub fn build_fingerprint(input: &FingerprintInputs<'_>) -> TaskFingerprint {
let mut fp = TaskFingerprint {
intent: infer_intent(input.user_intent, input.tools_used, input.files_changed),
subsystems: infer_subsystems(input.files_read, input.files_changed),
languages: infer_languages(input.files_read, input.files_changed),
frameworks: Vec::new(),
symbols: capped_unique(input.symbols, 24),
file_categories: {
let mut cats: Vec<String> = input
.files_changed
.iter()
.chain(input.files_read.iter())
.map(|p| crate::pattern_log::file_category(p))
.collect();
sort_dedup(&mut cats);
cats.truncate(16);
cats
},
operations: infer_operations(input.tools_used, input.files_changed),
diagnostic_classes: capped_unique(input.diagnostics, 12),
validation_classes: infer_validation(input.tests_run),
};
// Keep frameworks empty unless we later add lightweight detectors; do not
// invent them from path heuristics alone.
let _ = &mut fp.frameworks;
fp
}
/// Cheap heuristic: does this prompt look like a code-change / build / verify
/// task (worth refreshing the codebase index, change coupling, and coverage,
/// and worth surfacing likely-files/companions)? Conversational/strategic
/// prompts return false so the turn skips that I/O and the context pack omits
/// file/companion sections that would only false-match. Conservative — leans
/// toward `true` (refresh), since a stale index is cheap to tolerate and the
/// context pack still reads the existing index for file hints when needed.
pub fn looks_like_code_task(prompt: &str) -> bool {
let p = prompt.to_lowercase();
// A file-path-like token (path separator + extension) is a strong signal.
if p.split_whitespace()
.any(|t| t.contains('/') && t.contains('.'))
{
return true;
}
// Code-edit / build / verify verbs and tool names. Broad on purpose — false
// positives only mean a refresh runs, which is safe.
const CODE_VERBS: &[&str] = &[
"edit",
"fix",
"refactor",
"implement",
"build",
"compile",
"debug",
"wire",
"extend",
"migrate",
"port",
"rewrite",
"patch",
"cargo",
"npm",
"pnpm",
"bun",
"pytest",
"rustc",
"clippy",
"lint",
"test",
"update",
"add",
"remove",
"delete",
"rename",
"create",
"change",
"modify",
];
p.split_whitespace().any(|t| CODE_VERBS.contains(&t))
}
/// Similarity in `0.0..=1.0` using weighted Jaccard over fingerprint fields.
/// Deterministic and independent of tool-choice order.
pub fn fingerprint_similarity(a: &TaskFingerprint, b: &TaskFingerprint) -> f32 {
let mut score = 0.0f32;
let mut weight = 0.0f32;
// Intent: exact match is strong; token overlap otherwise.
weight += 0.25;
score += 0.25 * intent_sim(&a.intent, &b.intent);
weight += 0.20;
score += 0.20 * jaccard(&a.symbols, &b.symbols);
weight += 0.15;
score += 0.15 * jaccard(&a.subsystems, &b.subsystems);
weight += 0.10;
score += 0.10 * jaccard(&a.file_categories, &b.file_categories);
weight += 0.10;
score += 0.10 * jaccard(&a.operations, &b.operations);
weight += 0.08;
score += 0.08 * jaccard(&a.languages, &b.languages);
weight += 0.07;
score += 0.07 * jaccard(&a.diagnostic_classes, &b.diagnostic_classes);
weight += 0.05;
score += 0.05 * jaccard(&a.validation_classes, &b.validation_classes);
if weight <= 0.0 {
0.0
} else {
(score / weight).clamp(0.0, 1.0)
}
}
fn intent_sim(a: &str, b: &str) -> f32 {
if a.is_empty() && b.is_empty() {
return 0.0;
}
if a == b {
return 1.0;
}
let ta = tokenize(a);
let tb = tokenize(b);
jaccard(&ta, &tb)
}
fn jaccard(a: &[String], b: &[String]) -> f32 {
if a.is_empty() && b.is_empty() {
return 0.0;
}
let set_a: std::collections::HashSet<&str> = a.iter().map(|s| s.as_str()).collect();
let set_b: std::collections::HashSet<&str> = b.iter().map(|s| s.as_str()).collect();
let inter = set_a.intersection(&set_b).count() as f32;
let union = set_a.union(&set_b).count() as f32;
if union == 0.0 {
0.0
} else {
inter / union
}
}
fn tokenize(s: &str) -> Vec<String> {
s.split(|c: char| !c.is_alphanumeric() && c != '_' && c != '-')
.filter(|w| w.len() > 1)
.map(|w| w.to_lowercase())
.collect()
}
fn sort_dedup(v: &mut Vec<String>) {
v.sort();
v.dedup();
}
fn capped_unique(items: &[String], cap: usize) -> Vec<String> {
let mut out: Vec<String> = items
.iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
sort_dedup(&mut out);
out.truncate(cap);
out
}
fn infer_intent(prompt: &str, tools: &[String], changed: &[String]) -> String {
let p = prompt.to_lowercase();
let has = |k: &str| p.contains(k);
if has("add provider") || has("new provider") || has("key-auth") {
return "add-provider".into();
}
if has("memory") && (has("action") || has("tool") || has("schema")) {
return "extend-memory-tool".into();
}
if has("tool") && (has("schema") || has("action") || has("dispatch")) {
return "extend-tool-schema".into();
}
if has("skill") {
return "skill-work".into();
}
if has("plugin") {
return "plugin-work".into();
}
if has("test") && (has("fix") || has("fail") || has("flaky")) {
return "fix-test".into();
}
if has("refactor") {
return "refactor".into();
}
if has("fix") || has("bug") || has("error") || has("panic") {
return "fix-bug".into();
}
if has("document") || has("readme") || has("docs") {
return "docs".into();
}
// Fallback from tools/files.
let editish = tools.iter().any(|t| {
matches!(
t.as_str(),
"edit" | "write_file" | "patch" | "bulk_edit" | "bulk_write"
)
});
if editish && changed.iter().any(|f| f.contains("test")) {
return "test-change".into();
}
if editish {
return "code-change".into();
}
if !tools.is_empty() {
return "explore".into();
}
"unknown".into()
}
fn infer_subsystems(read: &[String], changed: &[String]) -> Vec<String> {
let mut out = Vec::new();
for p in read.iter().chain(changed.iter()) {
let lower = p.replace('\\', "/").to_lowercase();
let top = lower
.split('/')
.find(|c| !c.is_empty() && *c != "." && *c != "..");
if let Some(t) = top {
let sub = match t {
"core" => {
if lower.contains("memory") {
"memory"
} else if lower.contains("tool") {
"tools"
} else if lower.contains("provider") || lower.contains("oauth") {
"provider"
} else if lower.contains("plugin") {
"plugins"
} else if lower.contains("subagent") {
"subagent"
} else {
"core"
}
}
"tui" => "tui",
"web" => "web",
"sdk" => "sdk",
"docs" => "docs",
other => other,
};
out.push(sub.to_string());
}
}
sort_dedup(&mut out);
out.truncate(8);
out
}
fn infer_languages(read: &[String], changed: &[String]) -> Vec<String> {
let mut out = Vec::new();
for p in read.iter().chain(changed.iter()) {
if let Some(ext) = std::path::Path::new(p).extension().and_then(|e| e.to_str()) {
let lang = match ext {
"rs" => "rust",
"go" => "go",
"ts" | "tsx" => "typescript",
"js" | "jsx" | "mjs" | "cjs" => "javascript",
"py" => "python",
"md" | "mdx" => "markdown",
"json" => "json",
"toml" => "toml",
"yaml" | "yml" => "yaml",
_ => continue,
};
out.push(lang.to_string());
}
}
sort_dedup(&mut out);
out
}
fn infer_operations(tools: &[String], changed: &[String]) -> Vec<String> {
let mut ops = Vec::new();
for t in tools {
match t.as_str() {
"edit" | "bulk_edit" | "patch" => ops.push("edit".into()),
"write_file" | "bulk_write" => ops.push("create-file".into()),
"bash" => ops.push("shell".into()),
"subagent" | "spawn" => ops.push("delegate".into()),
"todo_write" => ops.push("plan".into()),
_ => {}
}
}
for f in changed {
let lower = f.to_lowercase();
if lower.contains("test") {
ops.push("test-change".into());
}
if lower.ends_with(".rs") && lower.contains("tool") {
ops.push("dispatch-change".into());
ops.push("schema-change".into());
}
}
sort_dedup(&mut ops);
ops.truncate(12);
ops
}
fn infer_validation(tests: &[String]) -> Vec<String> {
let mut out: Vec<String> = tests
.iter()
.map(|t| {
let lower = t.to_lowercase();
if lower.contains("cargo test") {
// Keep a short class: `cargo-test-<filter>` when present.
if let Some(rest) = lower.split("cargo test").nth(1) {
let filter = rest
.split_whitespace()
.find(|w| !w.starts_with('-'))
.unwrap_or("all");
format!("cargo-test-{filter}")
} else {
"cargo-test".into()
}
} else if lower.contains("cargo build") || lower.contains("cargo check") {
"cargo-build".into()
} else if lower.contains("go test") {
"go-test".into()
} else if lower.contains("npm test") || lower.contains("pnpm test") {
"js-test".into()
} else {
truncate(t, 48).to_string()
}
})
.collect();
sort_dedup(&mut out);
out.truncate(12);
out
}
fn truncate(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn similar_tasks_match_despite_different_tools() {
let a = build_fingerprint(&FingerprintInputs {
user_intent: "Extend the memory tool with a new action",
files_read: &["core/src/memory.rs".into(), "core/src/tools.rs".into()],
files_changed: &["core/src/memory.rs".into(), "core/src/tools.rs".into()],
symbols: &["MemoryEntry".into(), "memory_tool".into()],
tools_used: &["read_file".into(), "edit".into(), "bash".into()],
diagnostics: &[],
tests_run: &["cargo test memory".into()],
});
let b = build_fingerprint(&FingerprintInputs {
user_intent: "Add a memory tool action for deprecate",
files_read: &["core/src/tools.rs".into(), "core/src/memory.rs".into()],
files_changed: &["core/src/tools.rs".into()],
symbols: &["memory_tool".into(), "MemoryEntry".into()],
// Different tools chosen by the agent.
tools_used: &["grep".into(), "patch".into(), "subagent".into()],
diagnostics: &[],
tests_run: &["cargo test memory".into()],
});
assert_eq!(a.intent, "extend-memory-tool");
assert_eq!(b.intent, "extend-memory-tool");
let sim = fingerprint_similarity(&a, &b);
assert!(sim >= 0.55, "expected similar fingerprints, got {sim}");
}
#[test]
fn unrelated_tasks_have_low_similarity() {
let a = build_fingerprint(&FingerprintInputs {
user_intent: "Fix TUI rendering glitch",
files_read: &["tui/render.go".into()],
files_changed: &["tui/render.go".into()],
symbols: &["Render".into()],
tools_used: &["edit".into()],
diagnostics: &[],
tests_run: &[],
});
let b = build_fingerprint(&FingerprintInputs {
user_intent: "Add OpenAI provider",
files_read: &["core/src/provider.rs".into()],
files_changed: &["core/src/provider.rs".into()],
symbols: &["ProviderConfig".into()],
tools_used: &["edit".into()],
diagnostics: &[],
tests_run: &[],
});
let sim = fingerprint_similarity(&a, &b);
assert!(
sim < 0.4,
"unrelated tasks should not match strongly: {sim}"
);
}
}