-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext_pack.rs
More file actions
787 lines (746 loc) · 25.8 KB
/
Copy pathcontext_pack.rs
File metadata and controls
787 lines (746 loc) · 25.8 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Task-specific context pack (spec §14) — compact, bounded, scope-labeled.
//!
//! Assembles retrieval from memories (hybrid ranker), preferences, episodes,
//! rejected approaches, change coupling, and the codebase index.
//! Deterministic. Fail-open.
#![allow(dead_code)]
use std::path::Path;
use crate::change_coupling;
use crate::codebase_index;
use crate::coverage_ledger;
use crate::episodes;
use crate::failure_atlas;
use crate::learning_activations::{self, RetrievalStage};
use crate::learning_retrieval;
use crate::learning_store;
use crate::memory::{self, MemoryStatus, Scope};
use crate::preferences::{self, PreferenceRecord};
use crate::project_identity::{self, ProjectIdentity};
use crate::rejected_approaches;
use crate::task_fingerprint::{self, FingerprintInputs, TaskFingerprint};
/// Default character budget for the pack (spec §14.3).
pub const CONTEXT_PACK_MAX_CHARS: usize = 10_000;
const MAX_PROJECT_MEMORIES: usize = 5;
const MAX_GLOBAL_PREFS: usize = 3;
const MAX_EPISODES: usize = 3;
const MAX_REJECTED: usize = 3;
const MAX_FILES: usize = 6;
const MAX_COMPANIONS: usize = 6;
/// Role for multi-agent context packs (spec §20).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContextRole {
Full,
Scout,
Planner,
Worker,
Reviewer,
}
impl ContextRole {
pub fn parse(s: &str) -> Self {
match s.trim().to_lowercase().as_str() {
"scout" => Self::Scout,
"planner" => Self::Planner,
"worker" => Self::Worker,
"reviewer" => Self::Reviewer,
_ => Self::Full,
}
}
}
/// Build a compact `[TASK CONTEXT]` pack for `prompt` (full role).
pub fn build_context_pack(workspace: &Path, prompt: &str) -> String {
build_context_pack_for(workspace, prompt, ContextRole::Full)
}
/// Role-filtered context pack for subagents.
pub fn build_context_pack_for(workspace: &Path, prompt: &str, role: ContextRole) -> String {
build_context_pack_with_inputs(
workspace,
prompt,
role,
&FingerprintInputs {
user_intent: prompt,
files_read: &[],
files_changed: &[],
symbols: &[],
tools_used: &[],
diagnostics: &[],
tests_run: &[],
},
)
}
/// Context pack with live turn fingerprint inputs (paths/tools from this turn).
pub fn build_context_pack_with_inputs(
workspace: &Path,
prompt: &str,
role: ContextRole,
inputs: &FingerprintInputs<'_>,
) -> String {
let identity = project_identity::resolve_project_identity(workspace);
let mut inputs = FingerprintInputs {
user_intent: if inputs.user_intent.is_empty() {
prompt
} else {
inputs.user_intent
},
files_read: inputs.files_read,
files_changed: inputs.files_changed,
symbols: inputs.symbols,
tools_used: inputs.tools_used,
diagnostics: inputs.diagnostics,
tests_run: inputs.tests_run,
};
// Ensure user_intent is set for fingerprinting.
if inputs.user_intent.is_empty() {
inputs.user_intent = prompt;
}
let fp = task_fingerprint::build_fingerprint(&inputs);
let mut out = String::from("[TASK CONTEXT]\n\n");
out.push_str(&format!("Task interpretation:\n- intent: {}\n", fp.intent));
if !fp.subsystems.is_empty() {
out.push_str(&format!("- subsystems: {}\n", fp.subsystems.join(", ")));
}
out.push('\n');
out.push_str(&format!(
"Project identity:\n- [PROJECT] {}{}\n\n",
identity.id,
identity
.remote
.as_ref()
.map(|r| format!(" ({r})"))
.unwrap_or_default()
));
let include_prefs = matches!(
role,
ContextRole::Full | ContextRole::Planner | ContextRole::Worker
);
let include_rejected = matches!(
role,
ContextRole::Full | ContextRole::Planner | ContextRole::Reviewer
);
let include_episodes = matches!(
role,
ContextRole::Full | ContextRole::Scout | ContextRole::Planner
);
let include_files = matches!(
role,
ContextRole::Full | ContextRole::Scout | ContextRole::Worker
);
let include_companions = matches!(
role,
ContextRole::Full | ContextRole::Planner | ContextRole::Worker
);
let include_validation = matches!(
role,
ContextRole::Full | ContextRole::Reviewer | ContextRole::Worker
);
if include_prefs {
let prefs = preferences::load_global_preferences();
append_preferences(&mut out, &prefs);
}
if include_rejected {
append_rejected(&mut out, &identity, &fp);
}
// Error-recovery: surface matching diagnostic signatures (spec §14.4).
if looks_like_error_prompt(prompt) {
append_diagnostics(&mut out, &identity.id, prompt);
}
if include_episodes {
append_episodes(&mut out, &identity, &fp);
}
// File/companion surfacing needs the code index and only helps for
// code-change tasks; for conversational prompts it false-matches paths and
// wastes tokens. Gate on a cheap code-task heuristic.
let code_task = task_fingerprint::looks_like_code_task(prompt);
if include_files && code_task {
append_repo_map(&mut out, &identity);
append_likely_files(&mut out, &identity, prompt);
}
if include_companions && code_task {
append_companions(&mut out, &identity, prompt);
append_symbol_companions(&mut out, &identity, prompt);
}
if include_validation {
append_validation_hints(&mut out, &identity, &fp);
append_coverage_and_patterns(&mut out, &identity, &fp);
} else if matches!(role, ContextRole::Scout | ContextRole::Planner) {
// Scout/planner still benefit from coverage hotspots without full validation block.
append_coverage_and_patterns(&mut out, &identity, &fp);
}
// Collections RAG (opt-in indexed docs) — surface top hits when any collection exists.
if matches!(
role,
ContextRole::Full | ContextRole::Scout | ContextRole::Planner | ContextRole::Worker
) {
append_collections_hits(&mut out, &identity.id, prompt);
}
// Ranked memories (was defined but never called — subagents rely on pack
// alone and never saw the main-turn [RELEVANT MEMORIES] tail) (CORE_REVIEW C13).
let include_memories = matches!(
role,
ContextRole::Full | ContextRole::Planner | ContextRole::Worker | ContextRole::Scout
);
if include_memories {
append_ranked_memories(&mut out, workspace, prompt, &fp, true, true);
}
// Activation telemetry (fail-open).
learning_activations::record_pack_activations(
&identity.id,
RetrievalStage::PrePlan,
None,
&[("context_pack", "task-context", 0, 1.0, out.len() / 4)],
);
if out.len() > CONTEXT_PACK_MAX_CHARS {
out.truncate(CONTEXT_PACK_MAX_CHARS);
out.push_str("\n…[context pack truncated]\n");
}
out
}
fn append_ranked_memories(
out: &mut String,
workspace: &Path,
prompt: &str,
fp: &TaskFingerprint,
project: bool,
global: bool,
) {
let memories = memory::scan_all_memories(workspace);
let pid = project_identity::resolve_project_identity(workspace).id;
let ranked = learning_retrieval::rank_memories_in_project(&memories, prompt, fp, 12, &pid);
let mut project_n = 0usize;
let mut global_n = 0usize;
let mut project_section = String::new();
let mut global_section = String::new();
for (score, m, _reasons) in ranked {
if score < 0.05 {
continue;
}
let status = match m.status {
MemoryStatus::Verified => "[VERIFIED]",
MemoryStatus::Candidate => "[CANDIDATE]",
MemoryStatus::NeedsVerification | MemoryStatus::Stale => "[STALE]",
_ => continue,
};
let blurb = if m.description.is_empty() {
m.content.lines().next().unwrap_or("").to_string()
} else {
m.description.clone()
};
match m.scope {
Scope::Workspace if project && project_n < MAX_PROJECT_MEMORIES => {
project_section.push_str(&format!(
"- [PROJECT] {status} {} — {}\n",
m.name,
truncate(&blurb, 120)
));
project_n += 1;
}
Scope::Global if global && global_n < MAX_GLOBAL_PREFS => {
global_section.push_str(&format!(
"- [GLOBAL] {status} {} — {}\n",
m.name,
truncate(&blurb, 120)
));
global_n += 1;
}
_ => {}
}
}
if !project_section.is_empty() {
out.push_str("Project architecture and conventions:\n");
out.push_str(&project_section);
out.push('\n');
}
if !global_section.is_empty() {
out.push_str("Global developer preferences:\n");
out.push_str(&global_section);
out.push('\n');
}
}
fn append_preferences(out: &mut String, prefs: &[PreferenceRecord]) {
if prefs.is_empty() {
return;
}
out.push_str("Structured preferences:\n");
for p in prefs.iter().take(MAX_GLOBAL_PREFS) {
out.push_str(&format!(
"- [GLOBAL] [VERIFIED] ({}) {}\n",
p.category,
truncate(&p.statement, 120)
));
}
out.push('\n');
}
fn append_rejected(out: &mut String, identity: &ProjectIdentity, fp: &TaskFingerprint) {
let mut hits = rejected_approaches::match_rejected(fp, Some(&identity.id), 0.2, MAX_REJECTED);
let global = rejected_approaches::match_rejected(fp, None, 0.4, MAX_REJECTED);
hits.extend(global);
hits.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
hits.truncate(MAX_REJECTED);
if hits.is_empty() {
return;
}
out.push_str("Known rejected approaches and failure modes:\n");
for (sim, r) in hits {
let scope = if r.scope == "global" {
"[GLOBAL]"
} else {
"[PROJECT]"
};
out.push_str(&format!(
"- {scope} [REJECTED APPROACH] (sim={sim:.2}) {} — {}{}\n",
truncate(&r.approach, 80),
truncate(&r.rejection_reason, 100),
r.preferred_alternative
.as_ref()
.map(|a| format!(" → prefer: {}", truncate(a, 60)))
.unwrap_or_default()
));
}
out.push('\n');
}
fn append_episodes(out: &mut String, identity: &ProjectIdentity, fp: &TaskFingerprint) {
let similar = episodes::similar_episodes(&identity.id, fp, 0.35, MAX_EPISODES);
if similar.is_empty() {
return;
}
out.push_str("Similar previous coding episodes:\n");
for (sim, ep) in similar {
out.push_str(&format!(
"- [PROJECT] {} (sim={sim:.2}, outcome={}) — {}\n",
ep.id,
ep.outcome.as_str(),
truncate(&ep.user_intent, 100)
));
}
out.push('\n');
}
fn append_likely_files(out: &mut String, identity: &ProjectIdentity, prompt: &str) {
if prompt.trim().is_empty() {
return;
}
let hits = codebase_index::search_index(&identity.id, prompt, MAX_FILES);
if hits.is_empty() {
return;
}
out.push_str("Likely files and symbols:\n");
for h in hits {
match h.line {
Some(line) => out.push_str(&format!(
"- [PROJECT] {} — {}:{} (score={})\n",
h.name, h.path, line, h.score
)),
None => out.push_str(&format!(
"- [PROJECT] {} — {} (score={})\n",
h.name, h.path, h.score
)),
}
}
out.push('\n');
}
fn append_repo_map(out: &mut String, identity: &ProjectIdentity) {
let digest = codebase_index::load_digest(&identity.id);
if !digest.is_empty() {
let excerpt: String = digest.lines().take(28).collect::<Vec<_>>().join("\n");
out.push_str("Repo map (from /index digest):\n");
out.push_str(&excerpt);
if !excerpt.ends_with('\n') {
out.push('\n');
}
out.push('\n');
return;
}
let files = codebase_index::list_files(&identity.id);
if files.is_empty() {
return;
}
let mut dirs: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut entries: Vec<&codebase_index::FileRecord> = Vec::new();
for f in &files {
if f.binary || f.ignored || f.generated {
continue;
}
let top = f.path.split('/').next().unwrap_or(f.path.as_str());
*dirs.entry(top.to_string()).or_insert(0) += 1;
let name = f.path.rsplit('/').next().unwrap_or(f.path.as_str());
if matches!(
name,
"main.rs"
| "lib.rs"
| "mod.rs"
| "Cargo.toml"
| "package.json"
| "go.mod"
| "pyproject.toml"
| "tsconfig.json"
) {
entries.push(f);
}
}
if dirs.is_empty() {
return;
}
out.push_str("Repo map (from index):\n");
for (dir, n) in dirs.iter().take(10) {
out.push_str(&format!("- {dir}/ ({n} files)\n"));
}
if !entries.is_empty() {
out.push_str("Entry files:\n");
for f in entries.into_iter().take(8) {
out.push_str(&format!("- [PROJECT] {}\n", f.path));
}
}
out.push_str(
"Recon: `knowledge` context/search/symbol, then `lsp` definition/references, then ranged `read_file`.\n\n",
);
}
fn append_companions(out: &mut String, identity: &ProjectIdentity, prompt: &str) {
let files = codebase_index::list_files(&identity.id);
let prompt_l = prompt.to_lowercase();
let triggers: Vec<&str> = files
.iter()
.filter(|f| {
let p = f.path.to_lowercase();
prompt_l
.split_whitespace()
.any(|t| t.len() > 3 && p.contains(t))
})
.map(|f| f.path.as_str())
.take(3)
.collect();
let mut lines = Vec::new();
for t in triggers {
for edge in change_coupling::companions_for(&identity.id, t, 3) {
lines.push(format!(
"- [PROJECT] {} → {} (conf={:.2}, n={})",
edge.trigger, edge.companion, edge.confidence, edge.supporting_commits
));
if lines.len() >= MAX_COMPANIONS {
break;
}
}
if lines.len() >= MAX_COMPANIONS {
break;
}
}
if lines.is_empty() {
return;
}
out.push_str("Likely companion changes:\n");
for l in lines {
out.push_str(&l);
out.push('\n');
}
out.push('\n');
}
fn append_validation_hints(out: &mut String, identity: &ProjectIdentity, fp: &TaskFingerprint) {
let eps = episodes::similar_episodes(&identity.id, fp, 0.4, 5);
let mut cmds: Vec<String> = Vec::new();
for (_, ep) in eps {
for t in ep.tests_run {
if t.ok {
let c = t.command.clone();
if !cmds.iter().any(|x| x == &c) {
cmds.push(c);
}
}
}
}
for v in &fp.validation_classes {
let guess = if v.starts_with("cargo-test-") {
format!("cargo test {}", v.trim_start_matches("cargo-test-"))
} else if v == "cargo-build" {
"cargo build".into()
} else {
continue;
};
if !cmds.iter().any(|x| x == &guess) {
cmds.push(guess);
}
}
cmds.truncate(5);
if cmds.is_empty() {
return;
}
out.push_str("Recommended validation:\n");
for c in cmds {
out.push_str(&format!("- [PROJECT] {c}\n"));
}
out.push('\n');
}
fn looks_like_error_prompt(prompt: &str) -> bool {
let p = prompt.to_lowercase();
p.contains("error[")
|| p.contains("failed")
|| p.contains("panic")
|| p.contains("does not compile")
|| p.contains("test failed")
}
fn append_diagnostics(out: &mut String, project_id: &str, prompt: &str) {
let hits = failure_atlas::match_diagnostics(project_id, prompt, 3);
if hits.is_empty() {
// Also try a coarse class token.
let hits = failure_atlas::match_diagnostics(project_id, "cargo", 3);
if hits.is_empty() {
return;
}
out.push_str("Prior matching failures:\n");
for d in hits {
out.push_str(&format!(
"- [PROJECT] [{}] x{} {}\n",
d.class,
d.count,
truncate(&d.signature, 100)
));
}
out.push('\n');
return;
}
out.push_str("Prior matching failures:\n");
for d in hits {
out.push_str(&format!(
"- [PROJECT] [{}] x{} {}\n",
d.class,
d.count,
truncate(&d.signature, 100)
));
}
out.push('\n');
}
fn append_symbol_companions(out: &mut String, identity: &ProjectIdentity, prompt: &str) {
let mut syms: Vec<String> = Vec::new();
for tok in prompt.split(|c: char| !c.is_alphanumeric() && c != '_' && c != '-') {
if tok.len() >= 4
&& tok.len() <= 64
&& tok.chars().any(|c| c.is_ascii_uppercase() || c == '_')
&& !syms.iter().any(|s| s == tok)
{
syms.push(tok.to_string());
}
if syms.len() >= 4 {
break;
}
}
let mut lines = Vec::new();
for s in &syms {
for edge in change_coupling::symbol_companions_for(&identity.id, s, 3) {
lines.push(format!(
"- [PROJECT] symbol {} → {} ({} → {}, conf={:.2})",
edge.trigger_symbol,
edge.companion_symbol,
edge.trigger_path,
edge.companion_path,
edge.confidence
));
if lines.len() >= MAX_COMPANIONS {
break;
}
}
if lines.len() >= MAX_COMPANIONS {
break;
}
}
if lines.is_empty() {
return;
}
out.push_str("Likely symbol companions:\n");
for l in lines {
out.push_str(&l);
out.push('\n');
}
out.push('\n');
}
fn append_coverage_and_patterns(
out: &mut String,
identity: &ProjectIdentity,
fp: &TaskFingerprint,
) {
let poor = coverage_ledger::poorly_covered(&identity.id, 4);
if !poor.is_empty() {
out.push_str("Poorly covered areas (coverage ledger):\n");
for a in &poor {
out.push_str(&format!(
"- [PROJECT] {}: confidence {:.2}, files {}, symbols {}\n",
a.area, a.confidence, a.indexed_files, a.indexed_symbols
));
}
out.push('\n');
}
let patterns = learning_store::task_patterns::load_task_patterns(&identity.id);
if !patterns.is_empty() {
let mut scored: Vec<(f32, &learning_store::task_patterns::TaskPattern)> = patterns
.iter()
.map(|p| {
let sim = task_fingerprint::fingerprint_similarity(fp, &p.fingerprint);
(sim, p)
})
.filter(|(s, _)| *s >= 0.25)
.collect();
scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
scored.truncate(3);
if !scored.is_empty() {
out.push_str("Similar prior task patterns:\n");
for (sim, pat) in scored {
out.push_str(&format!(
"- [PROJECT] (sim={:.2}, ok={}, fail={}) {} — {}\n",
sim,
pat.success_count,
pat.failure_count,
truncate(&pat.fingerprint.intent, 60),
truncate(&pat.sample_approach, 100)
));
}
out.push('\n');
}
}
}
fn truncate(s: &str, n: usize) -> String {
match s.char_indices().nth(n) {
Some((i, _)) => format!("{}…", &s[..i]),
None => s.to_string(),
}
}
fn append_collections_hits(out: &mut String, project_id: &str, prompt: &str) {
let cols = crate::collections::list(project_id);
if cols.is_empty() {
return;
}
let mut any = false;
let mut block = String::from("Document collections (RAG hits):\n");
for meta in cols.iter().take(3) {
match crate::collections::search(project_id, &meta.name, prompt, 2) {
Ok(hits) if !hits.is_empty() => {
any = true;
for h in hits {
block.push_str(&format!(
"- [{}] (score={:.2}) {}\n",
meta.name,
h.score,
truncate(h.text.trim(), 120)
));
}
}
_ => {}
}
}
if any {
out.push_str(&block);
out.push('\n');
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::learning_store::override_learning_root;
use crate::memory::override_memory_root;
use crate::preferences::LearningStatus;
use crate::project_identity::override_registry_path;
use crate::rejected_approaches::{append_rejected, RejectedApproach};
fn tmp_home(label: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!(
"{}-{}-{}",
label,
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn pack_is_bounded_and_labeled() {
let home = tmp_home("ctx-pack");
let _serial = crate::memory::memory_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _lserial = crate::learning_store::learning_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _mr = override_memory_root(home.join("memory"));
let _lr = override_learning_root(home.join("learning"));
let _rserial = crate::project_identity::registry_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _rr = override_registry_path(home.join("registry.json"));
let ws = home.join("ws");
std::fs::create_dir_all(&ws).unwrap();
std::fs::write(ws.join("main.rs"), "fn main() {}").unwrap();
let _ = codebase_index::ensure_index(&ws);
let pack = build_context_pack(&ws, "extend the memory tool schema");
assert!(pack.contains("[TASK CONTEXT]"));
assert!(pack.contains("Project identity"));
assert!(
pack.contains("Repo map") || pack.contains("Recon:"),
"code-task pack should include repo map: {pack}"
);
assert!(pack.len() <= CONTEXT_PACK_MAX_CHARS + 40);
}
#[test]
fn rejected_approaches_surface_as_warnings() {
let home = tmp_home("ctx-rej");
let _serial = crate::memory::memory_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _lserial = crate::learning_store::learning_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _mr = override_memory_root(home.join("memory"));
let _lr = override_learning_root(home.join("learning"));
let _rserial = crate::project_identity::registry_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _rr = override_registry_path(home.join("registry.json"));
let ws = home.join("ws");
std::fs::create_dir_all(&ws).unwrap();
let id = project_identity::resolve_project_identity(&ws);
let mut fp = TaskFingerprint::default();
fp.intent = "extend-memory-tool".into();
fp.subsystems = vec!["memory".into(), "tools".into()];
append_rejected(
Some(&id.id),
&RejectedApproach {
id: "rej-1".into(),
scope: "project".into(),
task_fingerprint: fp.clone(),
approach: "add tool action without schema".into(),
rejection_reason: "dispatch/schema drift".into(),
preferred_alternative: Some("update schema + dispatch together".into()),
evidence: vec!["ep-1".into()],
confidence: 0.9,
status: LearningStatus::Verified,
},
);
let matched = rejected_approaches::match_rejected(&fp, Some(&id.id), 0.2, 3);
assert!(
!matched.is_empty(),
"stored rejection must match fingerprint"
);
let pack = build_context_pack(&ws, "Extend the memory tool with a new action");
assert!(
pack.contains("[REJECTED APPROACH]"),
"pack should warn about rejected approaches: {pack}"
);
}
#[test]
fn scout_role_omits_rejected_section() {
let home = tmp_home("ctx-role");
let _serial = crate::memory::memory_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _lserial = crate::learning_store::learning_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _mr = override_memory_root(home.join("memory"));
let _lr = override_learning_root(home.join("learning"));
let _rserial = crate::project_identity::registry_test_serial()
.lock()
.unwrap_or_else(|e| e.into_inner());
let _rr = override_registry_path(home.join("registry.json"));
let ws = home.join("ws");
std::fs::create_dir_all(&ws).unwrap();
let scout = build_context_pack_for(&ws, "find memory modules", ContextRole::Scout);
assert!(!scout.contains("[REJECTED APPROACH]"));
assert!(scout.contains("[TASK CONTEXT]"));
}
}