1use agent_doc_element_backlog::backlog::{self, PendingItem, PendingListMarker, PendingState};
4use serde::Serialize;
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6use std::path::Path;
7use tsift_memory::{MemoryEvent, MemoryEventKind, MemoryInsertResult};
8
9const TRACKED_WORK_IMPORT_SOURCE: &str = "agent-doc:tracked-work";
10const EXCHANGE_IMPORT_SOURCE: &str = "agent-doc:exchange";
11const MAX_RESPONSE_BODY_CHARS: usize = 2_000;
12
13#[derive(Debug, Clone, Serialize)]
14pub struct MemorySearchResult {
15 pub score: f64,
16 pub id: String,
17 pub kind: String,
18 pub source_ref: String,
19 #[serde(skip_serializing_if = "Option::is_none")]
20 pub component: Option<String>,
21 #[serde(skip_serializing_if = "Option::is_none")]
22 pub item_id: Option<String>,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub state: Option<String>,
25 pub text: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct CompletionCandidate {
30 pub source: String,
31 pub source_ref: String,
32 pub item_id: Option<String>,
33 pub text: String,
34 pub queue_index: Option<usize>,
35 pub exclude_from_queue_strike: bool,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize)]
39pub struct SemanticCompletionMatch {
40 pub score: f64,
41 pub candidate_source: String,
42 pub candidate_ref: String,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 pub candidate_id: Option<String>,
45 pub candidate_text: String,
46 pub matched_done_ref: String,
47 #[serde(skip_serializing_if = "Option::is_none")]
48 pub matched_done_id: Option<String>,
49 pub matched_done_text: String,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
54#[serde(rename_all = "snake_case")]
55pub enum QueueStrikeMatchKind {
56 Done,
57 Backlog,
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize)]
61pub struct QueueStrikeMatch {
62 pub score: f64,
63 pub matched_kind: QueueStrikeMatchKind,
64 pub candidate_index: usize,
65 pub candidate_text: String,
66 pub matched_ref: String,
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub matched_id: Option<String>,
69 pub matched_text: String,
70}
71
72pub const QUEUE_STRIKE_THRESHOLD: f64 = 1.6;
74
75pub fn queue_prompt_target_id(text: &str) -> Option<String> {
76 let marker = text.find('#')?;
77 let tail = &text[marker + 1..];
78 let id = tail
79 .chars()
80 .take_while(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_'))
81 .collect::<String>();
82 if id.is_empty() {
83 None
84 } else {
85 Some(id.to_ascii_lowercase())
86 }
87}
88
89pub fn format_semantic_completion_warning(candidate: &SemanticCompletionMatch) -> String {
90 let candidate_id = candidate
91 .candidate_id
92 .as_deref()
93 .map(|id| format!(" #{id}"))
94 .unwrap_or_default();
95 let done_id = candidate
96 .matched_done_id
97 .as_deref()
98 .map(|id| format!(" #{id}"))
99 .unwrap_or_else(|| " completed work".to_string());
100 format!(
101 "semantic completion candidate: {}{} may already be resolved by{} ({:.3}) at {}; candidate={:?}; match={:?}",
102 candidate.candidate_source,
103 candidate_id,
104 done_id,
105 candidate.score,
106 candidate.matched_done_ref,
107 candidate.candidate_text,
108 candidate.matched_done_text
109 )
110}
111
112pub fn semantic_completion_matches(
113 candidates: &[CompletionCandidate],
114 events: &[MemoryEvent],
115 limit: usize,
116) -> Vec<SemanticCompletionMatch> {
117 if candidates.is_empty() {
118 return Vec::new();
119 }
120
121 let done_events = events
122 .iter()
123 .filter(|event| is_done_tracked_work_event(event))
124 .cloned()
125 .collect::<Vec<_>>();
126 if done_events.is_empty() {
127 return Vec::new();
128 }
129
130 let mut seen = BTreeSet::new();
131 let mut matches = Vec::new();
132 for candidate in candidates {
133 let ranked = rank_events(&candidate.text, &done_events);
134 for result in ranked {
135 if result.score < 0.8 {
136 break;
137 }
138 if candidate.item_id.is_some() && candidate.item_id == result.item_id {
139 continue;
140 }
141 let key = (
142 candidate.source_ref.clone(),
143 result.source_ref.clone(),
144 result.item_id.clone(),
145 );
146 if !seen.insert(key) {
147 continue;
148 }
149 matches.push(SemanticCompletionMatch {
150 score: result.score,
151 candidate_source: candidate.source.clone(),
152 candidate_ref: candidate.source_ref.clone(),
153 candidate_id: candidate.item_id.clone(),
154 candidate_text: trim_chars(&candidate.text, 320),
155 matched_done_ref: result.source_ref,
156 matched_done_id: result.item_id,
157 matched_done_text: result.text,
158 });
159 break;
160 }
161 }
162
163 matches.sort_by(|a, b| {
164 b.score
165 .partial_cmp(&a.score)
166 .unwrap_or(std::cmp::Ordering::Equal)
167 .then_with(|| a.candidate_ref.cmp(&b.candidate_ref))
168 .then_with(|| a.matched_done_ref.cmp(&b.matched_done_ref))
169 });
170 matches.truncate(limit.max(1));
171 matches
172}
173
174pub fn semantic_queue_strike_matches(
175 candidates: &[CompletionCandidate],
176 events: &[MemoryEvent],
177 threshold: f64,
178 limit: usize,
179) -> Vec<QueueStrikeMatch> {
180 if candidates.is_empty() {
181 return Vec::new();
182 }
183
184 let done_events = events
185 .iter()
186 .filter(|event| is_done_tracked_work_event(event))
187 .cloned()
188 .collect::<Vec<_>>();
189 let backlog_events = events
190 .iter()
191 .filter(|event| is_active_backlog_work_event(event))
192 .cloned()
193 .collect::<Vec<_>>();
194 if done_events.is_empty() && backlog_events.is_empty() {
195 return Vec::new();
196 }
197
198 let mut matches = Vec::new();
199 for candidate in candidates {
200 if candidate.source != "queue" || candidate.item_id.is_some() {
201 continue;
202 }
203 let Some(candidate_index) = candidate.queue_index else {
204 continue;
205 };
206 if candidate.exclude_from_queue_strike {
207 continue;
208 }
209
210 let best_done = rank_events(&candidate.text, &done_events)
211 .into_iter()
212 .next();
213 let best_backlog = rank_events(&candidate.text, &backlog_events)
214 .into_iter()
215 .next();
216 let chosen = match (best_done, best_backlog) {
217 (Some(d), Some(b)) => {
218 if d.score >= b.score {
219 Some((QueueStrikeMatchKind::Done, d))
220 } else {
221 Some((QueueStrikeMatchKind::Backlog, b))
222 }
223 }
224 (Some(d), None) => Some((QueueStrikeMatchKind::Done, d)),
225 (None, Some(b)) => Some((QueueStrikeMatchKind::Backlog, b)),
226 (None, None) => None,
227 };
228 let Some((matched_kind, result)) = chosen else {
229 continue;
230 };
231 if result.score < threshold {
232 continue;
233 }
234 matches.push(QueueStrikeMatch {
235 score: result.score,
236 matched_kind,
237 candidate_index,
238 candidate_text: candidate.text.clone(),
239 matched_ref: result.source_ref,
240 matched_id: result.item_id,
241 matched_text: result.text,
242 });
243 }
244
245 matches.sort_by(|a, b| {
246 b.score
247 .partial_cmp(&a.score)
248 .unwrap_or(std::cmp::Ordering::Equal)
249 .then_with(|| a.candidate_index.cmp(&b.candidate_index))
250 });
251 matches.truncate(limit.max(1));
252 matches
253}
254
255pub fn is_done_tracked_work_event(event: &MemoryEvent) -> bool {
256 event
257 .metadata
258 .get("agent_doc_surface")
259 .is_some_and(|surface| surface == "tracked_work")
260 && event
261 .metadata
262 .get("state")
263 .is_some_and(|state| state == "done")
264}
265
266pub fn is_active_backlog_work_event(event: &MemoryEvent) -> bool {
270 event
271 .metadata
272 .get("agent_doc_surface")
273 .is_some_and(|surface| surface == "tracked_work")
274 && event
275 .metadata
276 .get("state")
277 .is_none_or(|state| state != "done")
278 && event.metadata.get("component").is_some_and(|component| {
279 backlog::component_matches_tracked_surface(component, "backlog")
280 })
281}
282
283pub fn count_insert_results(results: &[MemoryInsertResult]) -> (usize, usize) {
284 let inserted = results.iter().filter(|result| result.inserted).count();
285 (inserted, results.len().saturating_sub(inserted))
286}
287
288pub fn bump_component_count(counts: &mut BTreeMap<String, usize>, component: &str, amount: usize) {
289 if amount > 0 {
290 *counts.entry(component.to_string()).or_insert(0) += amount;
291 }
292}
293
294pub fn display_path(path: &Path) -> String {
295 path.display().to_string()
296}
297
298pub fn rank_events(query: &str, events: &[MemoryEvent]) -> Vec<MemorySearchResult> {
299 let query_tokens = tokenize(query);
300 let query_lower = query.trim().to_ascii_lowercase();
301 let mut ranked = events
302 .iter()
303 .filter_map(|event| {
304 let score = score_event(&query_tokens, &query_lower, event);
305 (score > 0.0).then(|| search_result(score, event))
306 })
307 .collect::<Vec<_>>();
308
309 ranked.sort_by(|a, b| {
310 b.score
311 .partial_cmp(&a.score)
312 .unwrap_or(std::cmp::Ordering::Equal)
313 .then_with(|| a.source_ref.cmp(&b.source_ref))
314 .then_with(|| a.text.cmp(&b.text))
315 });
316 ranked
317}
318
319pub fn dedupe_events(events: Vec<MemoryEvent>) -> Vec<MemoryEvent> {
320 let mut by_key = HashMap::new();
321 for event in events {
322 let key = (
323 event.source_ref.clone(),
324 event.text.clone(),
325 event.metadata.get("item_id").cloned(),
326 );
327 by_key.entry(key).or_insert(event);
328 }
329 by_key.into_values().collect()
330}
331
332pub fn trim_chars(text: &str, max_chars: usize) -> String {
333 let mut out = String::new();
334 for (idx, ch) in text.chars().enumerate() {
335 if idx >= max_chars {
336 out.push_str("...");
337 break;
338 }
339 out.push(ch);
340 }
341 out
342}
343
344pub fn tracked_work_events(
345 session_ref: &str,
346 doc_hash: &str,
347 component: &str,
348 items: impl IntoIterator<Item = PendingItem>,
349 state_override: Option<PendingState>,
350) -> Vec<MemoryEvent> {
351 items
352 .into_iter()
353 .filter(|item| !item.id.is_empty() || !item.text.trim().is_empty())
354 .map(|item| tracked_work_event(session_ref, doc_hash, component, item, state_override))
355 .collect()
356}
357
358pub fn tracked_work_event(
359 session_ref: &str,
360 doc_hash: &str,
361 component: &str,
362 item: PendingItem,
363 state_override: Option<PendingState>,
364) -> MemoryEvent {
365 let state = state_override.unwrap_or(item.state);
366 let state_str = pending_state_str(state);
367 let mut text = format!("#{} {}", item.id, item.text.trim());
368 if !item.continuation.trim().is_empty() {
369 text.push('\n');
370 text.push_str(item.continuation.trim());
371 }
372 let item_id = if item.id.is_empty() {
373 format!("anon:{}", agent_doc_hash::content_hash(&text))
374 } else {
375 item.id.clone()
376 };
377 let text_hash = agent_doc_hash::content_hash(&text);
378 let source_ref = format!("{session_ref}#{component}:{item_id}");
379 MemoryEvent::new(MemoryEventKind::ImportedObservation, source_ref, text)
380 .with_session_id(session_ref.to_string())
381 .with_metadata("agent_doc_surface", "tracked_work")
382 .with_metadata("component", component)
383 .with_metadata("item_id", item_id.clone())
384 .with_metadata("state", state_str)
385 .with_import(
386 TRACKED_WORK_IMPORT_SOURCE,
387 format!("{doc_hash}:{component}:{item_id}:{text_hash}"),
388 )
389}
390
391pub fn response_summary_events(session_ref: &str, doc_hash: &str, body: &str) -> Vec<MemoryEvent> {
392 response_sections(body)
393 .into_iter()
394 .map(|(index, heading, text)| {
395 let event_text = trim_chars(&format!("{heading}\n{text}"), MAX_RESPONSE_BODY_CHARS);
396 let text_hash = agent_doc_hash::content_hash(&event_text);
397 MemoryEvent::new(
398 MemoryEventKind::ResponseSummary,
399 format!("{session_ref}#exchange:{index}"),
400 event_text,
401 )
402 .with_session_id(session_ref.to_string())
403 .with_metadata("agent_doc_surface", "exchange")
404 .with_metadata("component", "exchange")
405 .with_metadata("heading", heading)
406 .with_import(
407 EXCHANGE_IMPORT_SOURCE,
408 format!("{doc_hash}:exchange:{index}:{text_hash}"),
409 )
410 })
411 .collect()
412}
413
414pub fn response_sections(body: &str) -> Vec<(usize, String, String)> {
415 let mut sections = Vec::new();
416 let mut current_heading: Option<String> = None;
417 let mut current_body = String::new();
418
419 for line in body.lines() {
420 if line.starts_with("### Re:") {
421 if let Some(heading) = current_heading.take() {
422 let index = sections.len() + 1;
423 sections.push((index, heading, current_body.trim().to_string()));
424 current_body.clear();
425 }
426 current_heading = Some(line.trim_start_matches('#').trim().to_string());
427 } else if current_heading.is_some() && !line.starts_with("<!-- agent:boundary:") {
428 current_body.push_str(line);
429 current_body.push('\n');
430 }
431 }
432 if let Some(heading) = current_heading {
433 let index = sections.len() + 1;
434 sections.push((index, heading, current_body.trim().to_string()));
435 }
436 sections
437}
438
439pub fn parse_done_archive_items(body: &str) -> Vec<PendingItem> {
440 let mut items = Vec::new();
441 let mut current: Option<PendingItem> = None;
442
443 for line in body.lines() {
444 if let Some((date, id, text)) = parse_done_archive_line(line) {
445 if let Some(item) = current.take() {
446 items.push(item);
447 }
448 current = Some(PendingItem {
449 marker: PendingListMarker::Bullet,
450 id,
451 state: PendingState::Done,
452 gate_type: None,
453 in_progress: false,
454 text: format!("{date} {text}"),
455 continuation: String::new(),
456 });
457 } else if let Some(item) = current.as_mut()
458 && (line.starts_with(' ') || line.starts_with('\t'))
459 {
460 item.continuation.push_str(line);
461 item.continuation.push('\n');
462 }
463 }
464
465 if let Some(item) = current {
466 items.push(item);
467 }
468 items
469}
470
471pub fn parse_done_archive_line(line: &str) -> Option<(String, String, String)> {
472 let rest = line.strip_prefix("- ")?;
473 if !looks_like_iso_date_prefix(rest) {
474 return None;
475 }
476 let date = rest[..10].to_string();
477 let after_date = &rest[11..];
478 let after_id = after_date.strip_prefix("[#")?;
479 let end = after_id.find(']')?;
480 let id = after_id[..end].trim();
481 if id.is_empty() {
482 return None;
483 }
484 let text = after_id[end + 1..].trim_start();
485 Some((date, id.to_string(), text.to_string()))
486}
487
488pub fn looks_like_iso_date_prefix(text: &str) -> bool {
489 let bytes = text.as_bytes();
490 bytes.len() > 11
491 && bytes[4] == b'-'
492 && bytes[7] == b'-'
493 && bytes[10] == b' '
494 && bytes[..4].iter().all(u8::is_ascii_digit)
495 && bytes[5..7].iter().all(u8::is_ascii_digit)
496 && bytes[8..10].iter().all(u8::is_ascii_digit)
497}
498
499pub fn pending_state_str(state: PendingState) -> &'static str {
500 match state {
501 PendingState::Open => "open",
502 PendingState::Gated => "gated",
503 PendingState::Done => "done",
504 }
505}
506
507fn score_event(query_tokens: &BTreeSet<String>, query_lower: &str, event: &MemoryEvent) -> f64 {
508 let event_text = format!(
509 "{} {} {}",
510 event.source_ref,
511 event.text,
512 event
513 .metadata
514 .values()
515 .cloned()
516 .collect::<Vec<_>>()
517 .join(" ")
518 );
519 let event_lower = event_text.to_ascii_lowercase();
520 let event_tokens = tokenize(&event_text);
521 let overlap = query_tokens.intersection(&event_tokens).count();
522 let mut score = if query_tokens.is_empty() {
523 0.0
524 } else {
525 overlap as f64 / query_tokens.len() as f64
526 };
527
528 if !query_lower.is_empty() && event_lower.contains(query_lower) {
529 score += 1.0;
530 }
531 if let Some(item_id) = event.metadata.get("item_id")
532 && query_tokens.contains(&item_id.to_ascii_lowercase())
533 {
534 score += 1.5;
535 }
536 if event
537 .metadata
538 .get("agent_doc_surface")
539 .is_some_and(|surface| surface == "tracked_work")
540 {
541 score += 0.05;
542 }
543 score
544}
545
546fn search_result(score: f64, event: &MemoryEvent) -> MemorySearchResult {
547 MemorySearchResult {
548 score,
549 id: event.stable_id(),
550 kind: event.kind.as_str().to_string(),
551 source_ref: event.source_ref.clone(),
552 component: event.metadata.get("component").cloned(),
553 item_id: event.metadata.get("item_id").cloned(),
554 state: event.metadata.get("state").cloned(),
555 text: trim_chars(&event.text, 320),
556 }
557}
558
559fn tokenize(text: &str) -> BTreeSet<String> {
560 let mut tokens = BTreeSet::new();
561 let mut current = String::new();
562 for ch in text.chars() {
563 if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
564 current.push(ch.to_ascii_lowercase());
565 } else {
566 push_token(&mut tokens, &mut current);
567 }
568 }
569 push_token(&mut tokens, &mut current);
570 tokens
571}
572
573fn push_token(tokens: &mut BTreeSet<String>, current: &mut String) {
574 if current.len() >= 2 {
575 tokens.insert(std::mem::take(current));
576 } else {
577 current.clear();
578 }
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584 use tsift_memory::MemoryEventKind;
585
586 fn tracked_event_with_state(
587 source_ref: &str,
588 item_id: &str,
589 component: &str,
590 state: &str,
591 text: &str,
592 ) -> MemoryEvent {
593 MemoryEvent::new(
594 MemoryEventKind::ImportedObservation,
595 source_ref.to_string(),
596 text.to_string(),
597 )
598 .with_metadata("agent_doc_surface", "tracked_work")
599 .with_metadata("component", component)
600 .with_metadata("item_id", item_id)
601 .with_metadata("state", state)
602 }
603
604 fn tracked_event(source_ref: &str, item_id: &str, text: &str) -> MemoryEvent {
605 tracked_event_with_state(source_ref, item_id, "backlog", "open", text)
606 }
607
608 fn done_event(source_ref: &str, item_id: &str, text: &str) -> MemoryEvent {
609 tracked_event_with_state(source_ref, item_id, "done", "done", text)
610 }
611
612 fn completion_candidate(
613 source: &str,
614 source_ref: &str,
615 item_id: Option<&str>,
616 text: &str,
617 ) -> CompletionCandidate {
618 CompletionCandidate {
619 source: source.to_string(),
620 source_ref: source_ref.to_string(),
621 item_id: item_id.map(str::to_string),
622 text: text.to_string(),
623 queue_index: None,
624 exclude_from_queue_strike: false,
625 }
626 }
627
628 fn queue_candidate(index: usize, text: &str, exclude: bool) -> CompletionCandidate {
629 CompletionCandidate {
630 source: "queue".to_string(),
631 source_ref: format!("doc#queue:{index}"),
632 item_id: None,
633 text: text.to_string(),
634 queue_index: Some(index),
635 exclude_from_queue_strike: exclude,
636 }
637 }
638
639 #[test]
640 fn ranks_by_overlap_substring_and_item_id() {
641 let events = vec![
642 tracked_event(
643 "doc#backlog:routes",
644 "routes",
645 "#routes Fix tmux route timeout",
646 ),
647 tracked_event(
648 "doc#backlog:memrag",
649 "memrag",
650 "#memrag Add semantic retrieval over backlog history",
651 ),
652 ];
653
654 let ranked = rank_events("semantic backlog retrieval", &events);
655
656 assert_eq!(
657 ranked.first().and_then(|result| result.item_id.as_deref()),
658 Some("memrag")
659 );
660 assert!(ranked[0].score > ranked[1].score);
661 }
662
663 #[test]
664 fn trims_by_character_boundary() {
665 assert_eq!(trim_chars("abcd", 3), "abc...");
666 assert_eq!(trim_chars("åßcd", 2), "åß...");
667 assert_eq!(trim_chars("abcd", 4), "abcd");
668 }
669
670 #[test]
671 fn dedupes_by_source_text_and_item_id() {
672 let first = tracked_event("doc#backlog:memrag", "memrag", "Add semantic retrieval");
673 let duplicate = tracked_event("doc#backlog:memrag", "memrag", "Add semantic retrieval");
674 let other = tracked_event("doc#backlog:routes", "routes", "Fix route timeout");
675
676 let deduped = dedupe_events(vec![first, duplicate, other]);
677
678 assert_eq!(deduped.len(), 2);
679 }
680
681 #[test]
682 fn bump_component_count_skips_zero_and_accumulates_positive_counts() {
683 let mut counts = BTreeMap::new();
684
685 bump_component_count(&mut counts, "backlog", 0);
686 bump_component_count(&mut counts, "backlog", 2);
687 bump_component_count(&mut counts, "backlog", 3);
688
689 assert_eq!(counts.len(), 1);
690 assert_eq!(counts.get("backlog"), Some(&5));
691 }
692
693 #[test]
694 fn display_path_uses_standard_path_display() {
695 assert_eq!(
696 display_path(Path::new("tasks/session.md")),
697 "tasks/session.md"
698 );
699 }
700
701 #[test]
702 fn semantic_completion_matches_done_events_and_skips_same_item_id() {
703 let candidates = vec![
704 completion_candidate(
705 "backlog",
706 "doc#backlog:cachefix",
707 Some("cachefix"),
708 "Repair cache duplication on save",
709 ),
710 queue_candidate(0, "Repair cache duplication on save", false),
711 ];
712 let events = vec![done_event(
713 "doc#done:cachefix",
714 "cachefix",
715 "#cachefix Repair cache duplication on save",
716 )];
717
718 let matches = semantic_completion_matches(&candidates, &events, 5);
719
720 assert_eq!(matches.len(), 1);
721 assert_eq!(matches[0].candidate_source, "queue");
722 assert_eq!(matches[0].matched_done_id.as_deref(), Some("cachefix"));
723 }
724
725 #[test]
726 fn semantic_queue_strike_prefers_done_over_equal_backlog_match() {
727 let candidates = vec![queue_candidate(
728 3,
729 "Repair cache duplication on save",
730 false,
731 )];
732 let events = vec![
733 done_event(
734 "doc#done:cachefix",
735 "cachefix",
736 "#cachefix Repair cache duplication on save",
737 ),
738 tracked_event(
739 "doc#backlog:cachefix",
740 "cachefix",
741 "#cachefix Repair cache duplication on save",
742 ),
743 ];
744
745 let matches =
746 semantic_queue_strike_matches(&candidates, &events, QUEUE_STRIKE_THRESHOLD, 5);
747
748 assert_eq!(matches.len(), 1);
749 assert_eq!(matches[0].matched_kind, QueueStrikeMatchKind::Done);
750 assert_eq!(matches[0].candidate_index, 3);
751 assert_eq!(matches[0].matched_id.as_deref(), Some("cachefix"));
752 }
753
754 #[test]
755 fn semantic_queue_strike_skips_excluded_candidate() {
756 let candidates = vec![queue_candidate(0, "Repair cache duplication on save", true)];
757 let events = vec![done_event(
758 "doc#done:cachefix",
759 "cachefix",
760 "#cachefix Repair cache duplication on save",
761 )];
762
763 let matches =
764 semantic_queue_strike_matches(&candidates, &events, QUEUE_STRIKE_THRESHOLD, 5);
765
766 assert!(matches.is_empty());
767 }
768
769 #[test]
770 fn semantic_event_classifiers_distinguish_done_and_active_backlog() {
771 let done = done_event("doc#done:cachefix", "cachefix", "Repair cache duplication");
772 let active_pending = tracked_event_with_state(
773 "doc#pending:cachefix",
774 "cachefix",
775 "pending",
776 "open",
777 "Repair cache duplication",
778 );
779 let review = tracked_event_with_state(
780 "doc#review:cachefix",
781 "cachefix",
782 "review",
783 "open",
784 "Repair cache duplication",
785 );
786
787 assert!(is_done_tracked_work_event(&done));
788 assert!(!is_active_backlog_work_event(&done));
789 assert!(is_active_backlog_work_event(&active_pending));
790 assert!(!is_active_backlog_work_event(&review));
791 }
792
793 #[test]
794 fn queue_prompt_target_id_parses_bracketed_id_like_prose() {
795 assert_eq!(
796 queue_prompt_target_id("[ ] #Cache-Fix_7 repair duplicate cache writes").as_deref(),
797 Some("cache-fix_7")
798 );
799 }
800
801 #[test]
802 fn queue_prompt_target_id_returns_none_when_missing_id() {
803 assert_eq!(
804 queue_prompt_target_id("repair duplicate cache writes"),
805 None
806 );
807 }
808
809 #[test]
810 fn queue_prompt_target_id_returns_none_for_empty_hash() {
811 assert_eq!(
812 queue_prompt_target_id("# repair duplicate cache writes"),
813 None
814 );
815 }
816
817 #[test]
818 fn queue_prompt_target_id_normalizes_to_lowercase() {
819 assert_eq!(
820 queue_prompt_target_id("#ABC_Def-12").as_deref(),
821 Some("abc_def-12")
822 );
823 }
824
825 #[test]
826 fn parse_done_archive_items_reads_archive_lines_and_continuations() {
827 let items = parse_done_archive_items(
828 "- 2026-06-07 [#cachefix] Repair cache duplication\n proof: shipped\n",
829 );
830
831 assert_eq!(items.len(), 1);
832 assert_eq!(items[0].id, "cachefix");
833 assert_eq!(items[0].state, PendingState::Done);
834 assert_eq!(items[0].text, "2026-06-07 Repair cache duplication");
835 assert_eq!(items[0].continuation, " proof: shipped\n");
836 }
837
838 #[test]
839 fn tracked_work_event_shapes_stable_import_metadata() {
840 let event = tracked_work_event(
841 "tasks/doc.md",
842 "doc-hash",
843 "backlog",
844 PendingItem {
845 marker: PendingListMarker::Bullet,
846 id: "cachefix".to_string(),
847 state: PendingState::Gated,
848 gate_type: None,
849 in_progress: false,
850 text: "Repair cache duplication".to_string(),
851 continuation: " proof: pending\n".to_string(),
852 },
853 None,
854 );
855
856 assert_eq!(event.kind, MemoryEventKind::ImportedObservation);
857 assert_eq!(event.source_ref, "tasks/doc.md#backlog:cachefix");
858 assert_eq!(
859 event.metadata.get("state").map(String::as_str),
860 Some("gated")
861 );
862 assert_eq!(
863 event.metadata.get("component").map(String::as_str),
864 Some("backlog")
865 );
866 assert!(event.text.contains("proof: pending"));
867 }
868
869 #[test]
870 fn response_summary_events_split_replies_and_skip_boundaries() {
871 let events = response_summary_events(
872 "tasks/doc.md",
873 "doc-hash",
874 "### Re: first\nbody\n<!-- agent:boundary:x -->\n### Re: second\nnext\n",
875 );
876
877 assert_eq!(events.len(), 2);
878 assert_eq!(events[0].kind, MemoryEventKind::ResponseSummary);
879 assert_eq!(events[0].source_ref, "tasks/doc.md#exchange:1");
880 assert_eq!(
881 events[0].metadata.get("heading").map(String::as_str),
882 Some("Re: first")
883 );
884 assert_eq!(events[0].text, "Re: first\nbody");
885 assert_eq!(events[1].source_ref, "tasks/doc.md#exchange:2");
886 }
887
888 #[test]
889 fn formats_semantic_completion_warning() {
890 let warning = format_semantic_completion_warning(&SemanticCompletionMatch {
891 score: 1.75,
892 candidate_source: "queue".to_string(),
893 candidate_ref: "doc#queue:0".to_string(),
894 candidate_id: None,
895 candidate_text: "Repair cache duplication".to_string(),
896 matched_done_ref: "doc#done:cachefix".to_string(),
897 matched_done_id: Some("cachefix".to_string()),
898 matched_done_text: "#cachefix Repair cache duplication".to_string(),
899 });
900
901 assert!(warning.contains("semantic completion candidate"));
902 assert!(warning.contains("#cachefix"));
903 assert!(warning.contains("1.750"));
904 }
905}