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
//! `asd annotate-commit [sha] [--write]` — derive ledger annotations from a commit.
//!
//! Reads a git commit's changed files and commit message, resolves the symbols
//! in those files, and derives candidate ledger entries (decisions, invariants,
//! hazards, proofs, validation scenarios).
//!
//! By default this is a dry-run: it prints the suggested entries as JSON.
//! Pass `--write` to actually append them to the ASD ledger.
//!
//! Annotation syntax recognised in commit message body:
//! invariant: <text> → LedgerKind::Invariant
//! hazard: <text> → LedgerKind::Hazard
//! proof: <text> → LedgerKind::Proof
//! validation_scenario: <text> → LedgerKind::ValidationScenario
//! known_bug: <text> → LedgerKind::KnownBug
//! decision: <text> → LedgerKind::Decision (explicit)
//! (any other body line) → LedgerKind::Decision (implicit, from subject)
//!
//! The subject line always produces a Decision entry for every touched symbol
//! that doesn't already have that exact summary recorded.
//!
//! Integrates with CTX task closure via `--task-description`:
//! asd annotate-commit --write --task-description "$(ctx task show t-042)"
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::Command;
use anyhow::{Context, Result};
use clap::Args;
use serde_json::{Value, json};
use agentstatedeveloper_core::{
AsgIndexStore, AsgLedgerStore, Engine, LedgerKind, LedgerStore, Symbol, kind_str,
schema::{Author, AuthorKind, LedgerEntry},
};
/// Per-file change detail for a commit, used to split symbols into
/// "directly edited" (their line span overlaps a changed hunk) vs
/// "nearby/touched" (in a renamed/moved file, or a changed file but outside
/// the edited lines) — so ledger annotations don't treat a file move the same
/// as a real edit.
#[derive(Default)]
struct FileChange {
/// True when the file was renamed/moved in this commit.
renamed: bool,
/// 1-based inclusive line ranges on the NEW side that actually changed.
/// Empty for a pure rename (100% similarity, no content delta).
hunks: Vec<(u32, u32)>,
}
impl FileChange {
/// Does `[start, end]` (1-based inclusive) overlap any changed hunk?
fn overlaps(&self, start: u32, end: u32) -> bool {
self.hunks.iter().any(|(a, b)| start <= *b && end >= *a)
}
}
/// Parse `git diff-tree -p -M --unified=0` for a commit into new-path →
/// FileChange. Tracks renames (`rename to`) and new-side hunk ranges (`@@ …
/// +c,d @@`).
fn commit_file_changes(commit: &str) -> std::collections::HashMap<String, FileChange> {
use std::collections::HashMap;
let mut map: HashMap<String, FileChange> = HashMap::new();
let out = Command::new("git")
.args([
"diff-tree",
"--no-commit-id",
"-r",
"-M",
"-p",
"--unified=0",
commit,
])
.output();
let text = match out {
Ok(o) => String::from_utf8_lossy(&o.stdout).into_owned(),
Err(_) => return map,
};
let mut cur: Option<String> = None;
let mut renamed = false;
for line in text.lines() {
if line.starts_with("diff --git ") {
// New file section; resolve the path from later +++/rename lines.
cur = None;
renamed = false;
} else if let Some(p) = line.strip_prefix("rename to ") {
renamed = true;
let path = p.trim().to_string();
map.entry(path.clone()).or_default().renamed = true;
cur = Some(path);
} else if let Some(p) = line.strip_prefix("+++ b/") {
if p != "/dev/null" {
let path = p.trim().to_string();
let e = map.entry(path.clone()).or_default();
e.renamed = e.renamed || renamed;
cur = Some(path);
}
} else if line.starts_with("@@ ") {
// @@ -a,b +c,d @@ ; new range is [c, c+max(d,1)-1]; d==0 → deletion at c.
if let Some(rest) = line.split(" +").nth(1)
&& let Some(spec) = rest.split(' ').next()
{
let mut it = spec.split(',');
let c: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(0);
let d: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1);
let start = c.max(1);
let end = if d == 0 { start } else { start + d - 1 };
if let Some(ref path) = cur {
map.entry(path.clone())
.or_default()
.hunks
.push((start, end));
}
}
}
}
map
}
fn is_doc_file(path: &str) -> bool {
let lower = path.to_lowercase();
let p = Path::new(&lower);
let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
matches!(
ext,
"md" | "txt" | "rst" | "adoc" | "asciidoc" | "tex" | "org"
) || name.starts_with("readme")
|| name.starts_with("changelog")
|| name.starts_with("license")
|| name.starts_with("authors")
|| name.starts_with("contributing")
|| lower.contains("/docs/")
|| lower.starts_with("docs/")
|| lower.contains("/doc/")
|| lower.starts_with("doc/")
}
use crate::config::Config;
#[derive(Debug, Args)]
pub struct AnnotateCommitArgs {
/// Git commit SHA to annotate (default: HEAD).
pub sha: Option<String>,
/// Write derived entries to the ASD ledger.
/// Without this flag the command is a dry-run and only prints suggestions.
#[arg(long, default_value_t = false)]
pub write: bool,
/// Author id written into ledger entries (default: git user.name).
#[arg(long)]
pub author: Option<String>,
/// Additional context from the active CTX task (its title or description).
/// Appended to the commit message body when deriving annotations.
#[arg(long)]
pub task_description: Option<String>,
/// CTX task ID — written as a `ctx:task:<id>` provenance tag on every entry.
/// Also accepts CTXONE_TASK env var.
#[arg(long)]
pub ctx_task: Option<String>,
/// CTX plan ID — written as a `ctx:plan:<id>` provenance tag.
/// Also accepts CTXONE_PLAN env var.
#[arg(long)]
pub ctx_plan: Option<String>,
/// Suppress informational stderr output.
#[arg(long)]
pub quiet: bool,
/// Print per-doc cluster selection reasoning: terms extracted, top-5 candidates
/// with kind bonus and match score, and why the winner was selected.
/// Only active for docs-only commits.
#[arg(long)]
pub debug_clusters: bool,
}
pub fn run(cfg: &Config, args: AnnotateCommitArgs) -> Result<()> {
let sha = args.sha.clone().unwrap_or_else(|| "HEAD".to_string());
// ---- Commit metadata ------------------------------------------------
let log_out = Command::new("git")
.args(["log", "-1", "--format=%H%n%s%n%b", &sha])
.output()
.context("git log failed")?;
let log_str = String::from_utf8_lossy(&log_out.stdout);
let mut log_lines = log_str.lines();
let commit_hash = log_lines.next().unwrap_or("").trim().to_string();
let subject = log_lines.next().unwrap_or("").trim().to_string();
let body: String = log_lines.collect::<Vec<_>>().join("\n");
if commit_hash.is_empty() {
anyhow::bail!("could not resolve commit: {}", sha);
}
// Append optional task description to body for annotation extraction.
let full_body = if let Some(ref td) = args.task_description {
format!("{body}\n{td}")
} else {
body
};
// ---- Changed files ---------------------------------------------------
let diff_out = Command::new("git")
.args([
"diff-tree",
"--no-commit-id",
"-r",
"--name-only",
&commit_hash,
])
.output()
.context("git diff-tree failed")?;
let changed_files: Vec<String> = String::from_utf8_lossy(&diff_out.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
if changed_files.is_empty() {
println!(
"{}",
json!({ "commit": commit_hash, "subject": subject, "note": "no changed files detected", "suggested_entries": [] })
);
return Ok(());
}
// ---- Resolve symbols for changed files --------------------------------
let engine = Engine::open_sqlite(&cfg.db_path)?;
let index_store = AsgIndexStore::from_engine(&engine);
let ledger_store = AsgLedgerStore::from_engine(&engine);
// Load all indexed symbols via the SQLite cache (avoids a full git tree walk).
let all_syms: Vec<Symbol> = index_store.build_id_map(&engine).into_values().collect();
let mut touched_symbols: Vec<Symbol> = Vec::new();
let mut seen_ids: HashSet<String> = HashSet::new();
// Borrow (not move) so all_syms stays available for the docs-only candidate scan below.
for sym in &all_syms {
if changed_files
.iter()
.any(|f| sym.file.ends_with(f.as_str()) || sym.file == *f)
{
if seen_ids.insert(sym.symbol_id.clone()) {
touched_symbols.push(sym.clone());
}
}
}
// Limit to 20 most relevant symbols to keep output manageable.
touched_symbols.truncate(20);
// cluster_meta: symbol_id → (per-cluster concept summary, confidence 0-1).
// Populated by the docs-only path; used in the emit loop to attach
// file-specific concept annotations only to their matched symbol.
let mut cluster_meta: HashMap<String, (String, f64)> = HashMap::new();
// cluster_debug: per-doc selection trace (populated when --debug-clusters is set).
let mut cluster_debug: Vec<Value> = Vec::new();
// ---- Docs-only path: find nearest domain symbol when all changed files
// are documentation (*.md, docs/ dirs, etc.) and no symbols were found.
let all_docs = !changed_files.is_empty() && changed_files.iter().all(|f| is_doc_file(f));
if all_docs && touched_symbols.is_empty() {
let extract_terms = |path: &str| -> Vec<String> {
let stem = Path::new(path)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_lowercase();
stem.replace(['-', '_', '.'], " ")
.split_whitespace()
.filter(|w| {
w.len() >= 3
&& !matches!(
*w,
"the"
| "and"
| "for"
| "doc"
| "docs"
| "readme"
| "design"
| "notes"
| "plan"
| "spec"
| "guide"
| "api"
| "todo"
| "fixme"
| "draft"
| "wip"
| "change"
| "changes"
)
})
.map(|w| w.to_string())
.collect()
};
// Filter non-doc candidate symbols from the already-loaded all_syms
// (no second git tree walk needed).
let candidate_syms: Vec<&Symbol> =
all_syms.iter().filter(|s| !is_doc_file(&s.file)).collect();
// Per-file pass: find the best-matching symbol for each changed doc file
// independently. This produces one concept cluster per doc domain rather
// than collapsing all files into a single nearest-neighbour lookup.
// Prefers type/module/class/struct symbols over methods to anchor concepts
// at the right granularity.
let mut any_term_match = false;
for doc_file in &changed_files {
let file_terms = extract_terms(doc_file);
if file_terms.is_empty() {
continue;
}
// combined_score is isize so test-file symbols can receive a negative bonus.
let mut ranked: Vec<(isize, usize, &Symbol)> = candidate_syms
.iter()
.copied()
.map(|s| {
let haystack = format!("{} {}", s.qname.to_lowercase(), s.file.to_lowercase());
let term_score = file_terms
.iter()
.filter(|t| haystack.contains(t.as_str()))
.count();
let fl = s.file.to_lowercase();
let is_test_file = fl.contains("/test")
|| fl.contains("/tests/")
|| fl.contains("/spec")
|| fl.ends_with("tests.swift");
let kind_bonus: isize = if is_test_file {
-2 // loses to any non-test class with equal term match
} else {
match kind_str(&s.kind) {
"module" | "class" | "struct" | "enum" | "trait" | "type"
| "interface" | "protocol" | "namespace" => 2,
_ => 0,
}
};
// dir_seg_bonus: +1 per distinct doc-term that appears in a *parent-
// directory* component of the symbol's file path (not the filename).
// Rewards symbols in a dedicated namespace dir (SongPlayers/SIDPlayer/)
// over symbols that merely match a term in their class name.
let dir_seg_bonus: isize = {
let p = Path::new(&s.file);
let dirs: Vec<String> = p
.parent()
.map(|parent| {
parent
.components()
.filter_map(|c| c.as_os_str().to_str())
.map(|seg| seg.to_lowercase())
.collect()
})
.unwrap_or_default();
file_terms
.iter()
.filter(|t| dirs.iter().any(|d| d.contains(t.as_str())))
.count() as isize
};
(
(term_score as isize) * 2 + kind_bonus + dir_seg_bonus,
term_score,
s,
)
})
.filter(|(_, ts, _)| *ts >= 1)
.collect();
ranked.sort_by(|a, b| b.0.cmp(&a.0));
let best = ranked.first().copied();
if args.debug_clusters {
let top5: Vec<Value> = ranked
.iter()
.take(5)
.map(|(combined, ts, s)| {
let k = kind_str(&s.kind);
let fl = s.file.to_lowercase();
let is_test = fl.contains("/test")
|| fl.contains("/tests/")
|| fl.contains("/spec")
|| fl.ends_with("tests.swift");
let kb: isize = if is_test {
-2
} else {
match k {
"module" | "class" | "struct" | "enum" | "trait" | "type"
| "interface" | "protocol" | "namespace" => 2,
_ => 0,
}
};
let dsb: isize = {
let p = Path::new(&s.file);
let dirs: Vec<String> = p
.parent()
.map(|parent| {
parent
.components()
.filter_map(|c| c.as_os_str().to_str())
.map(|seg| seg.to_lowercase())
.collect()
})
.unwrap_or_default();
file_terms
.iter()
.filter(|t| dirs.iter().any(|d| d.contains(t.as_str())))
.count() as isize
};
json!({
"qname": s.qname,
"file": s.file,
"kind": k,
"kind_bonus": kb,
"dir_seg_bonus": dsb,
"term_score": ts,
"combined_score": combined,
})
})
.collect();
let winner_info: Value = if let Some((_, ts, sym)) = best {
let confidence = ts as f64 / file_terms.len().max(1) as f64;
json!({
"qname": sym.qname,
"term_score": ts,
"confidence": confidence,
"reason": format!(
"highest combined score (term_score×2 + kind_bonus + dir_seg_bonus); matched {}/{} terms",
ts, file_terms.len()
),
})
} else {
json!({"reason": "no candidates matched any term"})
};
cluster_debug.push(json!({
"doc_file": doc_file,
"terms_extracted": file_terms,
"top_5_candidates": top5,
"winner_selected": winner_info,
}));
}
if let Some((_, term_score, sym)) = best {
any_term_match = true;
let confidence = term_score as f64 / file_terms.len().max(1) as f64;
let doc_name = Path::new(doc_file)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(doc_file);
let concept = format!("documentation: {}", doc_name.replace(['-', '_'], " "));
cluster_meta.insert(sym.symbol_id.clone(), (concept, confidence));
if seen_ids.insert(sym.symbol_id.clone()) {
touched_symbols.push(sym.clone());
}
}
}
// Fallback: no term matches found — use directory heuristics across all docs combined.
if !any_term_match {
let doc_dirs: Vec<&str> = changed_files
.iter()
.filter_map(|f| Path::new(f).parent()?.to_str())
.collect();
let mut dir_scored: Vec<(usize, &Symbol)> = candidate_syms
.iter()
.copied()
.map(|s| {
let score = doc_dirs
.iter()
.filter(|d| !d.is_empty() && **d != "." && s.file.contains(**d))
.count();
(score, s)
})
.collect();
dir_scored.sort_by(|a, b| b.0.cmp(&a.0));
for (_, sym) in dir_scored.into_iter().take(5) {
if seen_ids.insert(sym.symbol_id.clone()) {
touched_symbols.push((*sym).clone());
}
}
}
if !args.quiet {
eprintln!(
"asd: docs-only commit — {} domain cluster(s) identified across {} doc file(s)",
touched_symbols.len(),
changed_files.len()
);
}
}
// ---- Parse commit message for structured annotations -----------------
#[derive(Debug)]
struct Annotation {
kind: LedgerKind,
summary: String,
}
let mut annotations: Vec<Annotation> = Vec::new();
// Docs-only commits: subject becomes a Concept entry (documentation, not code decision).
// Code commits: subject becomes a Decision.
if !subject.is_empty() {
let subject_kind = if all_docs {
LedgerKind::Concept
} else {
LedgerKind::Decision
};
annotations.push(Annotation {
kind: subject_kind,
summary: subject.clone(),
});
}
// Note: for docs-only commits, per-cluster concept annotations are stored in
// `cluster_meta` (built in the docs-only path above) rather than the global
// annotations list, so they attach only to their matched cluster symbol.
// No global file-stem concepts are injected here.
// Parse body lines for structured annotations.
for line in full_body.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let (kind, text) = if let Some(rest) = line.strip_prefix("invariant:") {
(LedgerKind::Invariant, rest.trim())
} else if let Some(rest) = line.strip_prefix("hazard:") {
(LedgerKind::Hazard, rest.trim())
} else if let Some(rest) = line.strip_prefix("proof:") {
(LedgerKind::Proof, rest.trim())
} else if let Some(rest) = line.strip_prefix("validation_scenario:") {
(LedgerKind::ValidationScenario, rest.trim())
} else if let Some(rest) = line.strip_prefix("known_bug:") {
(LedgerKind::KnownBug, rest.trim())
} else if let Some(rest) = line.strip_prefix("concept:") {
(LedgerKind::Concept, rest.trim())
} else if let Some(rest) = line.strip_prefix("decision:") {
(LedgerKind::Decision, rest.trim())
} else {
continue; // unstructured body lines are skipped
};
if !text.is_empty() {
annotations.push(Annotation {
kind,
summary: text.to_string(),
});
}
}
// ---- CTX provenance tags (t-001) -------------------------------------
let ctx_plan = args
.ctx_plan
.clone()
.or_else(|| std::env::var("CTXONE_PLAN").ok())
.unwrap_or_default();
let ctx_task = args
.ctx_task
.clone()
.or_else(|| std::env::var("CTXONE_TASK").ok())
.unwrap_or_default();
let mut ctx_tags: Vec<String> = Vec::new();
if !ctx_plan.is_empty() {
ctx_tags.push(format!("ctx:plan:{}", ctx_plan));
}
if !ctx_task.is_empty() {
ctx_tags.push(format!("ctx:task:{}", ctx_task));
}
ctx_tags.push(format!(
"commit:{}",
&commit_hash[..8.min(commit_hash.len())]
));
// ---- Determine author ------------------------------------------------
let author_id = args.author.clone().unwrap_or_else(|| {
let out = Command::new("git")
.args(["config", "user.name"])
.output()
.ok();
out.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default()
.trim()
.to_string()
});
let author = Author {
kind: AuthorKind::Human,
id: author_id,
};
// ---- Build suggested entries -----------------------------------------
let mut suggested: Vec<Value> = Vec::new();
let mut written: Vec<Value> = Vec::new();
for sym in &touched_symbols {
// For docs-only commits, inject the per-cluster concept annotation
// before the global annotations so the concept is recorded first.
let cluster_anns: Vec<Annotation> = if all_docs {
cluster_meta
.get(&sym.symbol_id)
.map(|(concept, _)| {
vec![Annotation {
kind: LedgerKind::Concept,
summary: concept.clone(),
}]
})
.unwrap_or_default()
} else {
vec![]
};
// When this symbol has a cluster-specific concept, suppress any generic
// Concept entries from the global annotations list (the subject line) so
// we don't emit both "documentation: X" and "Define X scope" for the same symbol.
let has_cluster = !cluster_anns.is_empty();
let all_anns: Vec<&Annotation> = cluster_anns
.iter()
.chain(
annotations
.iter()
.filter(|a| !(has_cluster && a.kind == LedgerKind::Concept)),
)
.collect();
let cluster_confidence = cluster_meta.get(&sym.symbol_id).map(|(_, c)| *c);
for ann in all_anns {
// Check for duplicate: skip if same summary + kind already recorded.
let existing = ledger_store
.list_entries(&engine.ref_name, &sym.symbol_id)
.unwrap_or_default();
let already_exists = existing.iter().any(|e| {
e.kind == ann.kind && e.summary.to_lowercase() == ann.summary.to_lowercase()
});
if already_exists {
continue;
}
let entry_val = json!({
"symbol": sym.qname,
"file": sym.file,
"kind": format!("{:?}", ann.kind).to_lowercase(),
"summary": ann.summary,
"cluster_confidence": cluster_confidence,
});
if args.write {
let mut entry = LedgerEntry::new(
sym.symbol_id.clone(),
ann.kind,
ann.summary.clone(),
author.clone(),
);
entry.tags.extend(ctx_tags.iter().cloned());
match ledger_store.append_entry(&engine.ref_name, &entry, &author.id) {
Ok(()) => written.push(entry_val),
Err(e) => eprintln!("warn: could not write entry for {}: {e}", sym.qname),
}
} else {
suggested.push(entry_val);
}
}
}
// Split touched symbols into those whose own line span was actually edited
// vs those merely carried along by a file move / an unrelated same-file
// change — computed here, after all mutations to `touched_symbols`.
let file_changes = commit_file_changes(&commit_hash);
let symbol_directly_edited = |sym: &Symbol| -> bool {
file_changes
.iter()
.find(|(p, _)| sym.file.ends_with(p.as_str()) || &sym.file == *p)
.map(|(_, c)| c.overlaps(sym.start.line, sym.end.line))
.unwrap_or(false)
};
let directly_edited: Vec<String> = touched_symbols
.iter()
.filter(|s| symbol_directly_edited(s))
.map(|s| s.qname.clone())
.collect();
let nearby_touched: Vec<String> = touched_symbols
.iter()
.filter(|s| !symbol_directly_edited(s))
.map(|s| s.qname.clone())
.collect();
let out = if args.write {
json!({
"commit": commit_hash,
"subject": subject,
"changed_files": changed_files,
"touched_symbols": touched_symbols.len(),
"directly_edited": directly_edited,
"nearby_touched": nearby_touched,
"written_entries": written,
})
} else {
json!({
"commit": commit_hash,
"subject": subject,
"changed_files": changed_files,
"touched_symbols": touched_symbols.iter().map(|s| &s.qname).collect::<Vec<_>>(),
// The signal split: symbols whose own lines changed vs those merely
// carried along by a move / unrelated same-file edit.
"directly_edited": directly_edited,
"nearby_touched": nearby_touched,
"suggested_entries": suggested,
"note": "dry-run — pass --write to record these entries",
"cluster_debug": if args.debug_clusters { json!(cluster_debug) } else { Value::Null },
})
};
println!("{}", serde_json::to_string_pretty(&out)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn overlaps_detects_span_hunk_intersection() {
let fc = FileChange {
renamed: false,
hunks: vec![(10, 12), (40, 40)],
};
// Symbol [8,15] straddles hunk (10,12) → directly edited.
assert!(fc.overlaps(8, 15));
// Symbol exactly on a single-line hunk.
assert!(fc.overlaps(40, 45));
// Symbol [20,30] between hunks → not edited (nearby/touched).
assert!(!fc.overlaps(20, 30));
// Symbol entirely before the first hunk.
assert!(!fc.overlaps(1, 9));
}
#[test]
fn pure_rename_has_no_hunks_so_never_directly_edited() {
let fc = FileChange {
renamed: true,
hunks: vec![],
};
assert!(!fc.overlaps(1, 10_000));
}
}