agentstatedeveloper-core 1.4.8

Core types, traits, and ASG-backed implementations for AgentStateDeveloper
Documentation
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! ASG state repair — scan for corruption and apply safe auto-corrections.
//!
//! Three entry points:
//!   - [`scan_asg`]: read-only; returns every detected ASG-side issue.
//!   - [`scan_sidecar`]: read-only; flags files/dirs in `.asd/conclusions/`
//!     that violate the Plan K sidecar inclusion rule (Plan K t-010).
//!   - [`repair_asg`]: calls `scan_asg`, then optionally applies auto-fixable
//!     corrections and re-scans to show what remains.
//!
//! ## Detected issue kinds
//!
//! | kind | severity | auto-fixable |
//! |---|---|---|
//! | `orphaned_effect` | warn | yes — deleted, unless it holds runtime or trace evidence |
//! | `effect_id_mismatch` | error | no — ambiguous, needs manual resolution |
//! | `malformed_effect` | error | no — unknown cause |
//! | `orphaned_callee_ref` | warn | yes — ref removed from callees list |
//! | `orphaned_caller_ref` | warn | yes — ref removed from callers list |
//! | `orphaned_ledger` | warn | no — preserve audit trail |
//! | `ledger_duplicate` | error | yes — keeps the copy under a live symbol (else the latest revision), removes the rest |
//! | `empty_ledger_node` | warn | yes — removed |
//! | `sidecar_unknown_file` | warn | no — manual review (might be intentional) |
//! | `sidecar_unknown_dir` | warn | no — manual review |
//! | `sidecar_wrong_extension` | warn | no — manual review |

use std::collections::HashSet;

use agentstategraph::{CommitOptions, Repository};
use agentstategraph_core::IntentCategory;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::error::Result;
use crate::paths;
use crate::schema::{EffectDecl, LedgerEntry, ScratchEntry, ScratchStatus};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Severity level for a [`RepairIssue`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum IssueSeverity {
    /// Degraded quality but not blocking (e.g., stale ref).
    Warn,
    /// Data inconsistency that may cause incorrect query results (e.g., mismatched IDs).
    Error,
}

/// A single integrity issue detected in the ASG.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepairIssue {
    /// Machine-readable issue type (see module docs).
    pub kind: String,
    pub severity: IssueSeverity,
    /// ASG path that carries the corrupt/orphaned data.
    pub path: String,
    /// Human-readable description.
    pub detail: String,
    /// Whether `repair_asg(dry_run: false)` will correct this automatically.
    pub auto_fixable: bool,
}

/// Result returned by [`repair_asg`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepairReport {
    /// Total issues detected before any fixes.
    pub issues_found: usize,
    /// Number of individual corrections applied (0 when `dry_run` is true).
    pub fixes_applied: usize,
    /// True when the caller passed `dry_run: true` — no writes were made.
    pub dry_run: bool,
    /// Issues remaining *after* fixes (same as initial list when `dry_run`).
    pub issues: Vec<RepairIssue>,
}

// ---------------------------------------------------------------------------
// Core scan
// ---------------------------------------------------------------------------

/// Read-only integrity scan.  Returns every detected [`RepairIssue`] without
/// modifying any ASG state.
pub fn scan_asg(repo: &Repository, ref_name: &str) -> Result<Vec<RepairIssue>> {
    let mut issues = Vec::new();

    let live_symbol_ids = build_live_symbol_ids(repo, ref_name);

    check_effects(repo, ref_name, &live_symbol_ids, &mut issues);
    check_callee_refs(repo, ref_name, &live_symbol_ids, &mut issues);
    check_caller_refs(repo, ref_name, &live_symbol_ids, &mut issues);
    check_ledger(repo, ref_name, &live_symbol_ids, &mut issues);
    check_ledger_duplicates(repo, ref_name, &live_symbol_ids, &mut issues);
    check_scratch(repo, ref_name, &live_symbol_ids, &mut issues);

    Ok(issues)
}

// ---------------------------------------------------------------------------
// Repair (scan + optionally fix)
// ---------------------------------------------------------------------------

/// Scan the ASG for integrity issues and, when `dry_run` is false, apply all
/// auto-fixable corrections.
///
/// When `dry_run` is true the function behaves identically to [`scan_asg`]
/// (no writes, `fixes_applied` is 0).
pub fn repair_asg(
    repo: &Repository,
    ref_name: &str,
    agent_id: &str,
    dry_run: bool,
) -> Result<RepairReport> {
    repair_asg_with_cache(repo, None, ref_name, agent_id, dry_run)
}

/// [`repair_asg`], also pointing the ledger cache at the copy kept of each
/// duplicated entry — the cache answers `list_entries`, and a row left on a
/// removed copy would hide the entry from its symbol.
pub fn repair_asg_with_cache(
    repo: &Repository,
    fts: Option<&crate::search_fts::SearchFtsDb>,
    ref_name: &str,
    agent_id: &str,
    dry_run: bool,
) -> Result<RepairReport> {
    let issues = scan_asg(repo, ref_name)?;
    let issues_found = issues.len();

    if dry_run {
        return Ok(RepairReport {
            issues_found,
            fixes_applied: 0,
            dry_run: true,
            issues,
        });
    }

    // Every fix lands in one commit. A commit per dropped effect or rewritten
    // edge list stored a fresh copy of the enclosing map each time — on a
    // store with 54,685 orphaned effects, roughly 100 GB. The
    // subtrees are cleaned in memory on top of the state the speculation
    // forked from and written once each.
    let (spec, fork) = crate::subtree::speculate_at_head(repo, ref_name, "asd-repair")?;
    let staged = (|| -> Result<(usize, usize, usize, LedgerCleanup)> {
        let live = build_live_symbol_ids(repo, &fork);

        // Fix 1: orphaned effect records → delete, keeping evidence.
        let effects_root = format!("{}/effects", paths::ASD_ROOT);
        let mut effects = crate::subtree::read_seed(repo, &fork, &effects_root)?;
        let before = effects.len();
        effects
            .retain(|id, value| live.contains(id) || crate::effects::value_carries_evidence(value));
        let effects_dropped = before - effects.len();
        if effects_dropped > 0 {
            repo.spec_set_json(spec, &effects_root, &serde_json::Value::Object(effects))
                .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
        }

        // Fixes 2 and 3: orphaned callee and caller refs.
        let callees = stage_edge_lists(repo, spec, &fork, &live, "callees")?;
        let callers = stage_edge_lists(repo, spec, &fork, &live, "callers")?;

        // Fix 4: an entry filed under several symbols keeps one copy; a
        // symbol node with no entries left goes.
        let ledger = stage_ledger_cleanup(repo, spec, &fork, &live)?;
        Ok((effects_dropped, callees, callers, ledger))
    })();
    let fixes_applied = match staged {
        Ok((0, 0, 0, ledger)) if ledger.kept.is_empty() && ledger.empty_nodes == 0 => {
            let _ = repo.discard_speculation(spec);
            0
        }
        Ok((effects, callees, callers, ledger)) => {
            let LedgerCleanup { kept, empty_nodes } = ledger;
            let opts = CommitOptions::new(
                agent_id,
                IntentCategory::Refine,
                format!(
                    "repair: drop {effects} orphaned effect(s), {callees} orphaned callee ref(s), \
                     {callers} orphaned caller ref(s), {} duplicated ledger entr{}, \
                     {empty_nodes} empty ledger node(s)",
                    kept.len(),
                    if kept.len() == 1 { "y" } else { "ies" }
                ),
            );
            repo.commit_speculation(spec, opts)
                .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
            if let Some(fts) = fts {
                for entry in &kept {
                    fts.upsert_ledger_entry(entry, ref_name)
                        .map_err(|e| crate::error::AsdError::Other(format!("ledger cache: {e}")))?;
                }
            }
            effects + callees + callers + kept.len() + empty_nodes
        }
        Err(e) => {
            let _ = repo.discard_speculation(spec);
            return Err(e);
        }
    };

    // Re-scan: show what remains after fixes.
    let remaining = scan_asg(repo, ref_name)?;

    Ok(RepairReport {
        issues_found,
        fixes_applied,
        dry_run: false,
        issues: remaining,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn build_live_symbol_ids(repo: &Repository, ref_name: &str) -> HashSet<String> {
    let prefix = format!("{}/index/by-qname", paths::ASD_ROOT);
    match repo.get_tree(ref_name, &prefix) {
        Ok(serde_json::Value::Object(map)) => map
            .values()
            .filter_map(|v| v.get("symbol_id")?.as_str().map(|s| s.to_string()))
            .collect(),
        _ => HashSet::new(),
    }
}

fn check_effects(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let prefix = format!("{}/effects", paths::ASD_ROOT);
    let map = match repo.get_tree(ref_name, &prefix) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    for (key, value) in &map {
        match serde_json::from_value::<EffectDecl>(value.clone()) {
            Err(e) => {
                issues.push(RepairIssue {
                    kind: "malformed_effect".to_string(),
                    severity: IssueSeverity::Error,
                    path: paths::effects_path(key),
                    detail: format!("blob for '{}' fails to deserialize: {}", key, e),
                    auto_fixable: false,
                });
            }
            Ok(decl) => {
                if decl.symbol_id != *key {
                    issues.push(RepairIssue {
                        kind: "effect_id_mismatch".to_string(),
                        severity: IssueSeverity::Error,
                        path: paths::effects_path(key),
                        detail: format!(
                            "key='{}' but internal symbol_id='{}' — likely bad merge conflict resolution",
                            key, decl.symbol_id
                        ),
                        auto_fixable: false,
                    });
                }
                if !live.contains(key) {
                    let evidence = crate::effects::carries_evidence(&decl);
                    issues.push(RepairIssue {
                        kind: "orphaned_effect".to_string(),
                        severity: IssueSeverity::Warn,
                        path: paths::effects_path(key),
                        detail: if evidence {
                            format!(
                                "symbol '{key}' not found in index; effect record is orphaned \
                                 but holds runtime or trace evidence, so it is kept"
                            )
                        } else {
                            format!("symbol '{key}' not found in index; effect record is orphaned")
                        },
                        auto_fixable: !evidence,
                    });
                }
            }
        }
    }
}

fn check_callee_refs(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let prefix = format!("{}/index/callees", paths::ASD_ROOT);
    let map = match repo.get_tree(ref_name, &prefix) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    for (caller_id, value) in &map {
        let callees = extract_str_array(value, "callees");
        for callee_id in callees {
            if !live.contains(&callee_id) {
                issues.push(RepairIssue {
                    kind: "orphaned_callee_ref".to_string(),
                    severity: IssueSeverity::Warn,
                    path: paths::callees_path(caller_id),
                    detail: format!(
                        "callee '{}' referenced by '{}' no longer exists in the index",
                        callee_id, caller_id
                    ),
                    auto_fixable: true,
                });
            }
        }
    }
}

fn check_caller_refs(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let prefix = format!("{}/index/callers", paths::ASD_ROOT);
    let map = match repo.get_tree(ref_name, &prefix) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    for (callee_id, value) in &map {
        let callers = extract_str_array(value, "callers");
        for caller_id in callers {
            if !live.contains(&caller_id) {
                issues.push(RepairIssue {
                    kind: "orphaned_caller_ref".to_string(),
                    severity: IssueSeverity::Warn,
                    path: paths::callers_path(callee_id),
                    detail: format!(
                        "caller '{}' in call list for '{}' no longer exists in the index",
                        caller_id, callee_id
                    ),
                    auto_fixable: true,
                });
            }
        }
    }
}

fn check_ledger(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let prefix = format!("{}/ledger", paths::ASD_ROOT);
    let map = match repo.get_tree(ref_name, &prefix) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    for (symbol_id, entries) in &map {
        if entries.as_object().is_some_and(|m| m.is_empty()) {
            issues.push(RepairIssue {
                kind: "empty_ledger_node".to_string(),
                severity: IssueSeverity::Warn,
                path: paths::ledger_symbol_path(symbol_id),
                detail: format!(
                    "no ledger entries left under '{symbol_id}' — a node an earlier \
                     `asd hydrate` emptied while replaying a rebind"
                ),
                auto_fixable: true,
            });
        } else if !live.contains(symbol_id) {
            issues.push(RepairIssue {
                kind: "orphaned_ledger".to_string(),
                severity: IssueSeverity::Warn,
                path: paths::ledger_symbol_path(symbol_id),
                detail: format!(
                    "ledger entries for '{}' whose symbol is no longer in the index \
                     (preserved for audit trail — run `asd ledger find` to inspect)",
                    symbol_id
                ),
                auto_fixable: false,
            });
        }
    }
}

fn check_ledger_duplicates(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let ledger = match repo.get_tree(ref_name, &paths::ledger_root()) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    let index = match repo.get_tree(ref_name, &paths::ledger_index_root()) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => Default::default(),
    };
    for (entry_id, symbols) in crate::ledger_dupes::locations(&ledger) {
        if symbols.len() < 2 {
            continue;
        }
        let keep = keeper(&entry_id, &symbols, &ledger, &index, live);
        issues.push(RepairIssue {
            kind: "ledger_duplicate".to_string(),
            severity: IssueSeverity::Error,
            path: paths::ledger_entry_index_path(&entry_id),
            detail: format!(
                "entry '{entry_id}' is filed under {} symbols ({}); the ledger cache shows it \
                 under one of them only. --fix keeps the copy under '{keep}' and removes the rest",
                symbols.len(),
                symbols.join(", ")
            ),
            auto_fixable: true,
        });
    }
}

/// Which of the symbols an entry is filed under keeps it: see
/// [`crate::ledger_dupes::claim`]; then the symbol the entry index names;
/// then the smallest id, so the choice never depends on map order.
fn keeper(
    entry_id: &str,
    symbols: &[String],
    ledger: &serde_json::Map<String, serde_json::Value>,
    index: &serde_json::Map<String, serde_json::Value>,
    live: &HashSet<String>,
) -> String {
    let indexed_at = index.get(entry_id).and_then(|v| v.as_str());
    symbols
        .iter()
        .filter_map(|sym| {
            let entry: LedgerEntry =
                serde_json::from_value(ledger.get(sym)?.get(entry_id)?.clone()).ok()?;
            let (is_live, revised) = crate::ledger_dupes::claim(sym, &entry, live);
            Some(((is_live, revised, indexed_at == Some(sym.as_str())), sym))
        })
        .max_by(|(a, sa), (b, sb)| a.cmp(b).then_with(|| sb.cmp(sa)))
        .map(|(_, sym)| sym.clone())
        .unwrap_or_else(|| symbols[0].clone())
}

/// What [`stage_ledger_cleanup`] changed.
struct LedgerCleanup {
    /// The copy kept of each duplicated entry — for the ledger cache.
    kept: Vec<LedgerEntry>,
    /// Symbol nodes removed for holding no entries.
    empty_nodes: usize,
}

/// Keep one copy of every entry filed under several symbols, and drop symbol
/// nodes left with no entries, in the ledger and entry-index subtrees as the
/// speculation forked them, written once.
fn stage_ledger_cleanup(
    repo: &Repository,
    spec: agentstategraph::SpecHandle,
    fork: &str,
    live: &HashSet<String>,
) -> Result<LedgerCleanup> {
    let mut ledger = crate::subtree::read_seed(repo, fork, &paths::ledger_root())?;
    let dupes: Vec<(String, Vec<String>)> = crate::ledger_dupes::locations(&ledger)
        .into_iter()
        .filter(|(_, symbols)| symbols.len() > 1)
        .collect();
    let before = ledger.len();
    ledger.retain(|_, entries| entries.as_object().is_none_or(|m| !m.is_empty()));
    let empty_nodes = before - ledger.len();
    if dupes.is_empty() {
        if empty_nodes > 0 {
            repo.spec_set_json(
                spec,
                &paths::ledger_root(),
                &serde_json::Value::Object(ledger),
            )
            .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
        }
        return Ok(LedgerCleanup {
            kept: Vec::new(),
            empty_nodes,
        });
    }
    let mut index = crate::subtree::read_seed(repo, fork, &paths::ledger_index_root())?;
    let mut kept = Vec::with_capacity(dupes.len());
    for (entry_id, symbols) in dupes {
        let keep = keeper(&entry_id, &symbols, &ledger, &index, live);
        for sym in symbols.iter().filter(|s| **s != keep) {
            let emptied = match ledger.get_mut(sym) {
                Some(serde_json::Value::Object(entries)) => {
                    entries.remove(&entry_id);
                    entries.is_empty()
                }
                _ => false,
            };
            if emptied {
                ledger.remove(sym);
            }
        }
        if let Some(entry) = ledger
            .get(&keep)
            .and_then(|m| m.get(&entry_id))
            .and_then(|v| serde_json::from_value::<LedgerEntry>(v.clone()).ok())
        {
            kept.push(entry);
        }
        index.insert(entry_id, serde_json::Value::String(keep));
    }
    for (path, map) in [
        (paths::ledger_root(), ledger),
        (paths::ledger_index_root(), index),
    ] {
        repo.spec_set_json(spec, &path, &serde_json::Value::Object(map))
            .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
    }
    Ok(LedgerCleanup { kept, empty_nodes })
}

/// Remove ids that are no longer live from every list in the `field` edge
/// subtree (`callees` or `callers`) as the speculation forked it, and write
/// the subtree once if anything changed. Returns the number of refs dropped.
fn stage_edge_lists(
    repo: &Repository,
    spec: agentstategraph::SpecHandle,
    fork: &str,
    live: &HashSet<String>,
    field: &str,
) -> Result<usize> {
    let prefix = format!("{}/index/{field}", paths::ASD_ROOT);
    let mut map = crate::subtree::read_seed(repo, fork, &prefix)?;
    let mut total_dropped = 0usize;
    for value in map.values_mut() {
        let all = extract_str_array(value, field);
        let clean: Vec<&String> = all.iter().filter(|id| live.contains(*id)).collect();
        let dropped = all.len() - clean.len();
        if dropped > 0 {
            *value = json!({ field: clean });
            total_dropped += dropped;
        }
    }
    if total_dropped > 0 {
        repo.spec_set_json(spec, &prefix, &serde_json::Value::Object(map))
            .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
    }
    Ok(total_dropped)
}

/// Drop orphaned callee and caller refs whose target symbol_id no longer
/// exists in the live index, in one commit.  Returns the total number of
/// individual refs dropped.  Called by [`hydrate_from_dir`] after a hydrate
/// pass to clean up any stale edges the sidecar may have carried.
pub fn drop_orphaned_edge_refs(repo: &Repository, ref_name: &str, agent_id: &str) -> Result<usize> {
    let (spec, fork) = crate::subtree::speculate_at_head(repo, ref_name, "asd-drop-edge-refs")?;
    let staged = (|| -> Result<usize> {
        let live = build_live_symbol_ids(repo, &fork);
        Ok(stage_edge_lists(repo, spec, &fork, &live, "callees")?
            + stage_edge_lists(repo, spec, &fork, &live, "callers")?)
    })();
    match staged {
        Ok(0) => {
            let _ = repo.discard_speculation(spec);
            Ok(0)
        }
        Ok(dropped) => {
            let opts = CommitOptions::new(
                agent_id,
                IntentCategory::Refine,
                format!("repair: drop {dropped} orphaned edge ref(s)"),
            );
            repo.commit_speculation(spec, opts)
                .map_err(|e| crate::error::AsdError::Other(e.to_string()))?;
            Ok(dropped)
        }
        Err(e) => {
            let _ = repo.discard_speculation(spec);
            Err(e)
        }
    }
}

/// Informational check: find draft scratch entries whose `symbol_id` is no
/// longer in the live index. Does not auto-delete; the agent may still need
/// the note. Emits a `Warn`-level, non-auto-fixable issue per orphan.
fn check_scratch(
    repo: &Repository,
    ref_name: &str,
    live: &HashSet<String>,
    issues: &mut Vec<RepairIssue>,
) {
    let prefix = paths::scratch_root();
    let map = match repo.get_tree(ref_name, prefix) {
        Ok(serde_json::Value::Object(m)) => m,
        _ => return,
    };
    for (scratch_id, value) in &map {
        let entry = match serde_json::from_value::<ScratchEntry>(value.clone()) {
            Ok(e) => e,
            Err(e) => {
                issues.push(RepairIssue {
                    kind: "malformed_scratch".to_string(),
                    severity: IssueSeverity::Error,
                    path: paths::scratch_entry_path(scratch_id),
                    detail: format!("scratch entry '{scratch_id}' fails to deserialize: {e}"),
                    auto_fixable: false,
                });
                continue;
            }
        };
        // Only warn about Draft entries — Promoted/Discarded may legitimately
        // outlive their symbol after cleanup cycles.
        if entry.status != ScratchStatus::Draft {
            continue;
        }
        if let Some(ref sym_id) = entry.symbol_id {
            if !live.contains(sym_id) {
                issues.push(RepairIssue {
                    kind: "orphaned_scratch".to_string(),
                    severity: IssueSeverity::Warn,
                    path: paths::scratch_entry_path(scratch_id),
                    detail: format!(
                        "scratch entry '{scratch_id}' references symbol '{sym_id}' \
                         which is no longer in the index (session: {}, workflow: {})",
                        entry.session,
                        entry.workflow.as_deref().unwrap_or("—"),
                    ),
                    auto_fixable: false,
                });
            }
        }
    }
}

fn extract_str_array(v: &serde_json::Value, field: &str) -> Vec<String> {
    v.get(field)
        .and_then(|f| f.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|x| x.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default()
}

// ---------------------------------------------------------------------------
// Plan K t-010: sidecar inclusion-rule lint
// ---------------------------------------------------------------------------

/// Scan `.asd/conclusions/` for files and directories that don't match
/// the Plan K sidecar inclusion rule:
///
/// > The committed sidecar carries **judgment** — anything an agent
/// > or human had to decide, classify, hypothesize, approve, or
/// > otherwise commit mental effort to. Anything mechanically
/// > derivable from source stays in the regenerable SQLite cache and
/// > is gitignored.
///
/// Concretely, `.asd/conclusions/` should ONLY contain:
///   - `<stem>.jsonl` for the default Class layout, where `<stem>`
///     is one of the 7 `ConclusionClass::filename_stem()` values
///   - `<stem>/<anything>.jsonl` for per-package layout (Plan K t-007)
///
/// Anything else — `.md` notes, `.json` dumps, `effects.jsonl`
/// (regenerable!), random subdirs — is leakage. We warn so a
/// contributor or `pre-commit` hook can review before the noise
/// lands in git.
///
/// Read-only; never deletes. Returns an empty list when the directory
/// doesn't exist (fresh project — nothing to lint yet).
pub fn scan_sidecar(conclusions_dir: &std::path::Path) -> Vec<RepairIssue> {
    use crate::schema::ConclusionClass;
    let mut issues = Vec::new();
    if !conclusions_dir.is_dir() {
        return issues;
    }
    let known_stems: std::collections::HashSet<&'static str> = ConclusionClass::all()
        .iter()
        .map(|c| c.filename_stem())
        .collect();

    let entries = match std::fs::read_dir(conclusions_dir) {
        Ok(e) => e,
        Err(_) => return issues,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let rel = path
            .strip_prefix(conclusions_dir)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();

        if path.is_dir() {
            // Per-package layout subdirectory — name must match a
            // known ConclusionClass stem.
            if !known_stems.contains(name.as_str()) {
                issues.push(RepairIssue {
                    kind: "sidecar_unknown_dir".into(),
                    severity: IssueSeverity::Warn,
                    path: format!(".asd/conclusions/{rel}"),
                    detail: format!(
                        "subdirectory `{name}` is not a known ConclusionClass; \
                         expected one of: {known_list}. If you intended a \
                         per-package layout (Plan K t-007), the subdir name \
                         must match a class stem.",
                        known_list = sorted_known_stems_list(&known_stems),
                    ),
                    auto_fixable: false,
                });
                continue;
            }
            // Inside a valid class subdir, every file must be *.jsonl.
            if let Ok(inner) = std::fs::read_dir(&path) {
                for sub in inner.flatten() {
                    let sub_path = sub.path();
                    let sub_rel = sub_path
                        .strip_prefix(conclusions_dir)
                        .unwrap_or(&sub_path)
                        .to_string_lossy()
                        .replace('\\', "/");
                    if sub_path.is_file()
                        && sub_path.extension().and_then(|s| s.to_str()) != Some("jsonl")
                    {
                        issues.push(RepairIssue {
                            kind: "sidecar_wrong_extension".into(),
                            severity: IssueSeverity::Warn,
                            path: format!(".asd/conclusions/{sub_rel}"),
                            detail: format!(
                                "file is not `.jsonl`; per-package shards must have \
                                 the `.jsonl` extension to be picked up by import."
                            ),
                            auto_fixable: false,
                        });
                    }
                }
            }
        } else if path.is_file() {
            // Top-level file — must be `<known-stem>.jsonl`.
            let stem = path
                .file_stem()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_default();
            let ext = path.extension().and_then(|s| s.to_str());
            if ext != Some("jsonl") {
                issues.push(RepairIssue {
                    kind: "sidecar_wrong_extension".into(),
                    severity: IssueSeverity::Warn,
                    path: format!(".asd/conclusions/{rel}"),
                    detail: format!(
                        "file is not `.jsonl`; the committed sidecar should \
                         carry only JSONL ledger projections. Move other \
                         artifacts out of `.asd/conclusions/` — derived caches \
                         belong in `.asd/cache/` (gitignored)."
                    ),
                    auto_fixable: false,
                });
            } else if !known_stems.contains(stem.as_str()) {
                issues.push(RepairIssue {
                    kind: "sidecar_unknown_file".into(),
                    severity: IssueSeverity::Warn,
                    path: format!(".asd/conclusions/{rel}"),
                    detail: format!(
                        "file `{name}` doesn't match a known ConclusionClass \
                         (one of: {known_list}). If a new judgment class \
                         shipped, add the ConclusionClass variant. If this is \
                         a regenerable artifact (e.g. effects, FTS), move it \
                         to `.asd/cache/` (gitignored).",
                        known_list = sorted_known_stems_list(&known_stems),
                    ),
                    auto_fixable: false,
                });
            }
        }
    }
    issues
}

fn sorted_known_stems_list(stems: &std::collections::HashSet<&str>) -> String {
    let mut v: Vec<&str> = stems.iter().copied().collect();
    v.sort();
    v.join(", ")
}

#[cfg(test)]
mod sidecar_lint_tests {
    use super::*;
    use tempfile::tempdir;

    fn touch(p: &std::path::Path) {
        std::fs::write(p, b"").unwrap();
    }

    #[test]
    fn empty_or_missing_dir_returns_no_issues() {
        let tmp = tempdir().unwrap();
        let missing = tmp.path().join("nope");
        assert!(scan_sidecar(&missing).is_empty());

        let empty = tmp.path().join("empty");
        std::fs::create_dir(&empty).unwrap();
        assert!(scan_sidecar(&empty).is_empty());
    }

    #[test]
    fn known_class_files_pass_clean() {
        let tmp = tempdir().unwrap();
        for stem in [
            "decisions",
            "classifications",
            "mappings",
            "hazards",
            "recipes",
            "followups",
            "thinking",
        ] {
            touch(&tmp.path().join(format!("{stem}.jsonl")));
        }
        let issues = scan_sidecar(tmp.path());
        assert!(
            issues.is_empty(),
            "all-known-stem files must lint clean; got: {issues:?}"
        );
    }

    #[test]
    fn flags_unknown_top_level_file() {
        let tmp = tempdir().unwrap();
        touch(&tmp.path().join("effects.jsonl")); // not a ConclusionClass
        let issues = scan_sidecar(tmp.path());
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].kind, "sidecar_unknown_file");
        assert!(issues[0].path.contains("effects.jsonl"));
    }

    #[test]
    fn flags_wrong_extension_at_top_level() {
        let tmp = tempdir().unwrap();
        touch(&tmp.path().join("notes.md"));
        let issues = scan_sidecar(tmp.path());
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].kind, "sidecar_wrong_extension");
    }

    #[test]
    fn flags_unknown_subdir_name() {
        let tmp = tempdir().unwrap();
        std::fs::create_dir(tmp.path().join("backups")).unwrap();
        let issues = scan_sidecar(tmp.path());
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].kind, "sidecar_unknown_dir");
    }

    #[test]
    fn accepts_known_class_subdir_with_jsonl_shards() {
        // Per-package layout: `.asd/conclusions/decisions/crates--core.jsonl`
        let tmp = tempdir().unwrap();
        let class_dir = tmp.path().join("decisions");
        std::fs::create_dir(&class_dir).unwrap();
        touch(&class_dir.join("crates--core.jsonl"));
        touch(&class_dir.join("crates--cli.jsonl"));
        let issues = scan_sidecar(tmp.path());
        assert!(
            issues.is_empty(),
            "known class subdir with .jsonl shards must lint clean; got: {issues:?}"
        );
    }

    #[test]
    fn flags_wrong_extension_inside_class_subdir() {
        let tmp = tempdir().unwrap();
        let class_dir = tmp.path().join("decisions");
        std::fs::create_dir(&class_dir).unwrap();
        touch(&class_dir.join("crates--core.json")); // wrong ext
        let issues = scan_sidecar(tmp.path());
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].kind, "sidecar_wrong_extension");
        assert!(issues[0].path.contains("decisions/"));
    }
}