coding-agent-search 0.7.0

Unified TUI search over local coding agent histories
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
//! Project a likely root-cause family from observed evidence signals.
//!
//! Bead: coding_agent_session_search-cass-fleet-resilience-20260608-uojcg.9.2
//! ("Project likely root-cause family in status doctor and fleet outputs").
//!
//! Bead `9.1` defines the attribution *contract* ([`RootCauseAttribution`],
//! [`RootCauseFamily`], [`EvidenceRef`], [`AttributionConfidence`]). This module
//! is the pure **classifier** that fills it: it maps a read-only
//! [`ProjectionSignals`] snapshot (the structured facts status/doctor/fleet and
//! incident mining already observe) to the single most likely family, with a
//! confidence that reflects how dominant and unambiguous the evidence is, the
//! supporting [`EvidenceRef`]s, and the cheap next probe.
//!
//! It deliberately honors each family's documented false-positive guidance:
//! lexical fail-open returning results is *designed degradation*, not a search
//! fault; a cold/never-indexed data dir is *not* derived-state corruption;
//! abundant free space rules out disk pressure. Signals that only describe
//! graceful behavior never, on their own, drive an attribution.

use crate::root_cause_taxonomy::{
    AttributionConfidence, EvidenceRef, RootCauseAttribution, RootCauseFamily,
};

/// Read-only evidence snapshot. Every field is a fact a diagnostic already
/// gathered; presence (not prose) drives attribution. Defaults are "no signal".
#[derive(Debug, Clone, Default)]
pub struct ProjectionSignals {
    // --- frankensqlite / storage ---
    /// A structured fsqlite error code was observed (direct evidence).
    pub fsqlite_error_code: Option<String>,
    /// An OpenRead / FTS read failure occurred.
    pub open_read_failure: bool,

    // --- frankensearch / search stack ---
    /// A search-stack error (fusion panic, tantivy segment corruption).
    pub frankensearch_error: bool,
    /// Lexical fail-open returned results (designed degradation — NOT a fault
    /// by itself; never drives an attribution alone).
    pub lexical_fail_open: bool,

    // --- cass derived state ---
    /// Two CASS-owned facts disagree (e.g. index count vs. truth table). A cold
    /// or empty data dir is NOT this; only a real mismatch counts.
    pub derived_truth_table_mismatch: bool,

    // --- asupersync runtime ---
    /// Work stalled with no underlying I/O progress, or cancellation failed.
    pub runtime_task_stall: bool,

    // --- remote transport / auth ---
    /// Remote authentication failed (publickey/permission denied).
    pub transport_auth_failure: bool,
    /// Remote ssh/transport non-zero exit, when known.
    pub transport_ssh_exit_code: Option<i32>,
    /// Remote connect timed out.
    pub transport_connect_timeout: bool,

    // --- semantic assets ---
    /// Semantic mode was requested/enabled but its assets are missing/partial
    /// (disabled-by-config is NOT a fault).
    pub semantic_requested_but_missing: bool,

    // --- workspace provenance ---
    /// Configured provenance disagrees with on-disk reality (moved/stale data
    /// dir, misclassified source).
    pub workspace_provenance_mismatch: bool,

    // --- host disk pressure ---
    /// Free-space percentage, when measured. Below ~5% is pressure.
    pub host_disk_free_pct: Option<f64>,

    // --- host OOM / load ---
    /// An OOM kill was recorded.
    pub host_oom_kill: bool,
    /// Load average vs. core count, when measured (ratio > ~4 is pressure).
    pub host_load_ratio: Option<f64>,

    // --- old binary / contract skew ---
    /// The running binary's contract/api version is behind on-disk/fleet need.
    pub binary_behind_contract: bool,
}

const DISK_PRESSURE_PCT: f64 = 5.0;
const LOAD_PRESSURE_RATIO: f64 = 4.0;

/// One scored family hit, with the evidence backing it.
struct FamilyHit {
    family: RootCauseFamily,
    /// 2 = direct/unambiguous, 1 = circumstantial.
    score: u32,
    evidence: Vec<EvidenceRef>,
    /// Direct evidence makes a single-family attribution `Confirmed`.
    direct: bool,
}

/// Collect the families implicated by the signals, each with score + evidence.
fn collect_hits(s: &ProjectionSignals) -> Vec<FamilyHit> {
    let mut hits: Vec<FamilyHit> = Vec::new();

    // frankensqlite storage — direct on an explicit error code / OpenRead.
    {
        let mut ev = Vec::new();
        let mut direct = false;
        if let Some(code) = &s.fsqlite_error_code {
            ev.push(EvidenceRef::new("fsqlite.error_code", "diag").with_detail(code.clone()));
            direct = true;
        }
        if s.open_read_failure {
            ev.push(EvidenceRef::new("fsqlite.open_read_failure", "diag"));
            direct = true;
        }
        if !ev.is_empty() {
            hits.push(FamilyHit {
                family: RootCauseFamily::FrankensqliteStorage,
                score: if direct { 2 } else { 1 },
                evidence: ev,
                direct,
            });
        }
    }

    // frankensearch — only on a real error; lexical fail-open alone is NOT a fault.
    if s.frankensearch_error {
        hits.push(FamilyHit {
            family: RootCauseFamily::FrankensearchSearch,
            score: 2,
            evidence: vec![EvidenceRef::new("frankensearch.fusion_error", "search")],
            direct: true,
        });
    }

    // cass derived state — only on a concrete mismatch.
    if s.derived_truth_table_mismatch {
        hits.push(FamilyHit {
            family: RootCauseFamily::CassDerivedState,
            score: 2,
            evidence: vec![EvidenceRef::new(
                "cass.derived_asset.truth_table_mismatch",
                "doctor",
            )],
            direct: true,
        });
    }

    // asupersync runtime.
    if s.runtime_task_stall {
        hits.push(FamilyHit {
            family: RootCauseFamily::AsupersyncRuntime,
            score: 1,
            evidence: vec![EvidenceRef::new("asupersync.task_stall_ms", "status")],
            direct: false,
        });
    }

    // remote transport / auth.
    {
        let mut ev = Vec::new();
        let mut direct = false;
        if s.transport_auth_failure {
            ev.push(EvidenceRef::new("transport.auth_failure", "sources"));
            direct = true;
        }
        if let Some(code) = s.transport_ssh_exit_code {
            ev.push(
                EvidenceRef::new("transport.ssh_exit_code", "sources")
                    .with_detail(code.to_string()),
            );
        }
        if s.transport_connect_timeout {
            ev.push(EvidenceRef::new("transport.connect_timeout_ms", "sources"));
        }
        if !ev.is_empty() {
            hits.push(FamilyHit {
                family: RootCauseFamily::RemoteTransportAuth,
                score: if direct { 2 } else { 1 },
                evidence: ev,
                direct,
            });
        }
    }

    // semantic assets — requested-but-missing only.
    if s.semantic_requested_but_missing {
        hits.push(FamilyHit {
            family: RootCauseFamily::SemanticAssets,
            score: 1,
            evidence: vec![
                EvidenceRef::new("semantic.vector_index_built", "diag")
                    .with_detail("false".to_string()),
            ],
            direct: false,
        });
    }

    // workspace provenance.
    if s.workspace_provenance_mismatch {
        hits.push(FamilyHit {
            family: RootCauseFamily::WorkspaceProvenance,
            score: 1,
            evidence: vec![EvidenceRef::new("config.data_dir", "status")],
            direct: false,
        });
    }

    // host disk pressure — only below threshold (abundant free space rules out).
    if let Some(pct) = s.host_disk_free_pct
        && pct < DISK_PRESSURE_PCT
    {
        hits.push(FamilyHit {
            family: RootCauseFamily::HostDiskPressure,
            score: 2,
            evidence: vec![
                EvidenceRef::new("host.disk_free_pct", "host").with_detail(format!("{pct:.1}")),
            ],
            direct: true,
        });
    }

    // host OOM / load.
    {
        let mut ev = Vec::new();
        let mut direct = false;
        if s.host_oom_kill {
            ev.push(EvidenceRef::new("host.oom_kill_count", "host").with_detail("1+".to_string()));
            direct = true;
        }
        if let Some(ratio) = s.host_load_ratio
            && ratio > LOAD_PRESSURE_RATIO
        {
            ev.push(
                EvidenceRef::new("host.load_avg_1m", "host").with_detail(format!("{ratio:.1}x")),
            );
        }
        if !ev.is_empty() {
            hits.push(FamilyHit {
                family: RootCauseFamily::HostOomLoad,
                score: if direct { 2 } else { 1 },
                evidence: ev,
                direct,
            });
        }
    }

    // old binary / contract skew.
    if s.binary_behind_contract {
        hits.push(FamilyHit {
            family: RootCauseFamily::OldBinarySkew,
            score: 2,
            evidence: vec![EvidenceRef::new("binary.contract_version", "api-version")],
            direct: true,
        });
    }

    hits
}

/// Project the most likely root-cause attribution from the evidence. Pure; no
/// I/O or mutation. With no signals, returns the explicit unattributed record.
///
/// Confidence:
/// - `Confirmed`: exactly one family implicated, by direct evidence.
/// - `Probable`: one family clearly dominates (strictly higher score).
/// - `Possible`: the top family ties with another (mixed evidence).
/// - `Unknown`: no signals.
pub fn project_root_cause(signals: &ProjectionSignals) -> RootCauseAttribution {
    let mut hits = collect_hits(signals);
    if hits.is_empty() {
        return RootCauseAttribution::unattributed(
            "no evidence signals pointed at any root-cause family".to_string(),
        );
    }

    // Highest score wins; ties broken by the stable family label for determinism.
    hits.sort_by(|a, b| {
        b.score
            .cmp(&a.score)
            .then_with(|| a.family.as_str().cmp(b.family.as_str()))
    });

    let top_score = hits[0].score;
    let contenders = hits.iter().filter(|h| h.score == top_score).count();
    let only_one_family = hits.len() == 1;

    let confidence = if only_one_family && hits[0].direct {
        AttributionConfidence::Confirmed
    } else if contenders == 1 {
        AttributionConfidence::Probable
    } else {
        AttributionConfidence::Possible
    };

    let chosen = &hits[0];
    let competing: Vec<&str> = hits
        .iter()
        .skip(1)
        .filter(|h| h.score == top_score)
        .map(|h| h.family.as_str())
        .collect();
    let summary = if competing.is_empty() {
        format!(
            "evidence points at {}; confirm with the family's bounded probe",
            chosen.family.as_str()
        )
    } else {
        format!(
            "evidence favors {} but {} is not excluded; gather more before acting",
            chosen.family.as_str(),
            competing.join(", ")
        )
    };

    RootCauseAttribution::new(chosen.family, confidence, summary)
        .with_evidence(chosen.evidence.clone())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::root_cause_taxonomy::FaultLocus;

    #[test]
    fn storage_dominated_corpus_attributes_frankensqlite() {
        // csd-like: storage-dominated.
        let s = ProjectionSignals {
            fsqlite_error_code: Some("SQLITE_BUSY".to_string()),
            open_read_failure: true,
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::FrankensqliteStorage);
        assert_eq!(a.locus, FaultLocus::Dependency);
        assert_eq!(a.confidence, AttributionConfidence::Confirmed);
        assert!(
            a.evidence_refs
                .iter()
                .any(|e| e.kind == "fsqlite.error_code")
        );
        assert!(a.recommended_next_probe.is_some());
    }

    #[test]
    fn dependency_search_corpus_attributes_frankensearch() {
        // css-like: dependency/search-dominated (a real search-stack error).
        let s = ProjectionSignals {
            frankensearch_error: true,
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::FrankensearchSearch);
        assert_eq!(a.locus, FaultLocus::Dependency);
        assert_eq!(a.confidence, AttributionConfidence::Confirmed);
    }

    #[test]
    fn lexical_fail_open_alone_is_not_a_search_fault() {
        // Designed graceful degradation must NOT attribute a fault.
        let s = ProjectionSignals {
            lexical_fail_open: true,
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::Unknown);
        assert_eq!(a.confidence, AttributionConfidence::Unknown);
    }

    #[test]
    fn stale_derived_state_without_host_pressure_attributes_cass_not_host() {
        let s = ProjectionSignals {
            derived_truth_table_mismatch: true,
            // No disk/oom signals at all.
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::CassDerivedState);
        assert_eq!(a.locus, FaultLocus::Cass);
        assert_ne!(a.family, RootCauseFamily::HostDiskPressure);
        assert_ne!(a.family, RootCauseFamily::HostOomLoad);
    }

    #[test]
    fn auth_failure_attributes_remote_transport() {
        let s = ProjectionSignals {
            transport_auth_failure: true,
            transport_ssh_exit_code: Some(255),
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::RemoteTransportAuth);
        assert_eq!(a.confidence, AttributionConfidence::Confirmed);
        assert!(
            a.evidence_refs
                .iter()
                .any(|e| e.kind == "transport.auth_failure")
        );
    }

    #[test]
    fn disk_pressure_only_below_threshold() {
        // Abundant free space rules it out.
        let plenty = ProjectionSignals {
            host_disk_free_pct: Some(60.0),
            ..Default::default()
        };
        assert_eq!(project_root_cause(&plenty).family, RootCauseFamily::Unknown);
        // Below threshold attributes host disk pressure.
        let tight = ProjectionSignals {
            host_disk_free_pct: Some(2.0),
            ..Default::default()
        };
        let a = project_root_cause(&tight);
        assert_eq!(a.family, RootCauseFamily::HostDiskPressure);
        assert_eq!(a.locus, FaultLocus::Host);
    }

    #[test]
    fn mixed_evidence_picks_dominant_with_possible_confidence() {
        // Two direct families implicated => top is Possible, competitor named.
        let s = ProjectionSignals {
            open_read_failure: true,            // FrankensqliteStorage (direct, score 2)
            derived_truth_table_mismatch: true, // CassDerivedState (direct, score 2)
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.confidence, AttributionConfidence::Possible);
        // Deterministic tie-break by taxonomy rank; both must be representable.
        assert!(matches!(
            a.family,
            RootCauseFamily::FrankensqliteStorage | RootCauseFamily::CassDerivedState
        ));
        assert!(a.summary.contains("not excluded"));
    }

    #[test]
    fn dominant_direct_over_circumstantial_is_probable() {
        // One direct (score 2) + one circumstantial (score 1) => Probable, no tie.
        let s = ProjectionSignals {
            binary_behind_contract: true,        // OldBinarySkew, direct, score 2
            workspace_provenance_mismatch: true, // WorkspaceProvenance, score 1
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::OldBinarySkew);
        assert_eq!(a.confidence, AttributionConfidence::Probable);
    }

    #[test]
    fn no_signals_is_explicit_unknown() {
        let a = project_root_cause(&ProjectionSignals::default());
        assert_eq!(a.family, RootCauseFamily::Unknown);
        assert_eq!(a.confidence, AttributionConfidence::Unknown);
        assert!(a.evidence_refs.is_empty());
    }

    #[test]
    fn attribution_json_contract_round_trips() {
        let s = ProjectionSignals {
            host_oom_kill: true,
            ..Default::default()
        };
        let a = project_root_cause(&s);
        assert_eq!(a.family, RootCauseFamily::HostOomLoad);
        let value = serde_json::to_value(&a).unwrap();
        assert_eq!(value["family"], "host-oom-load");
        assert_eq!(value["confidence"], "confirmed");
        let back: RootCauseAttribution = serde_json::from_value(value).unwrap();
        assert_eq!(back, a);
    }
}