g8_conflict/lib.rs
1//! `g8-conflict` — cross-project intent/capability overlap detection.
2//!
3//! Provides [`ConflictDetector`] with two entry points:
4//!
5//! - [`ConflictDetector::compare_spaces`] — compare two stores (local + remote-attached) and
6//! return all conflicts between them, ordered by descending severity.
7//! - [`ConflictDetector::detect_intra_space`] — single-store variant: detect conflicts within
8//! one space (duplicate intents, contradictory decisions, governance violations).
9//!
10//! # Design notes
11//!
12//! This crate is purely computational — no I/O, no async. It reads data from the store via the
13//! [`ConflictStore`] trait and produces `Vec<Conflict>` using typed [`Evidence`] variants (per
14//! A1 decision #3 — `Vec<Evidence>` not stringified evidence).
15//!
16//! Cross-project capability identity is `<project>::<name>` (used only as lookup keys per A1
17//! decision #2; annotations never carry the prefix).
18//!
19//! ## Four conflict kinds
20//!
21//! | Kind | Trigger | Severity |
22//! |---|---|---|
23//! | `DuplicateIntent` | Same `kind + scope_path` in both spaces, different `description` | `Warn` |
24//! | `CapabilityNameCollision` | Same kebab-case `name` in both spaces, no alias resolves them | `Error` |
25//! | `CapabilityNameCollision` | Same name AND alias resolves them | `Info` |
26//! | `ContradictoryDecisions` | Same `title`, both `accepted`, different `body` | `Error` |
27//! | `GovernanceViolation` | Plan substrate forbidden by a `Boundary` intent in the other space | `Error` |
28
29pub mod store_adapter;
30pub mod store_trait;
31
32use std::path::PathBuf;
33
34use g8_core::{Conflict, ConflictKind, Evidence, IntentKind, Severity, SpaceId};
35use tracing::instrument;
36
37pub use store_adapter::ConflictAdapter;
38pub use store_trait::ConflictStore;
39
40// ── Error type ───────────────────────────────────────────────────────────────
41
42/// Errors produced by [`ConflictDetector`] operations.
43///
44/// The only current variant is a transparent delegation to the store error type.
45/// Downstream crates should match `ConflictError::Store` to inspect the root cause.
46#[derive(Debug, thiserror::Error)]
47pub enum ConflictError {
48 /// A store operation failed during conflict detection.
49 #[error("store error during conflict detection: {0}")]
50 Store(String),
51}
52
53// ── ConflictDetector ─────────────────────────────────────────────────────────
54
55/// Entry point for all conflict-detection operations.
56///
57/// All methods are associated functions (no instance state); the detector is
58/// stateless — store references are passed per-call.
59pub struct ConflictDetector;
60
61impl ConflictDetector {
62 /// Compare two stores and return all conflicts between them.
63 ///
64 /// Both stores must have fully-loaded scan data (capabilities, intents, decisions, plans).
65 /// The returned `Vec<Conflict>` is sorted by descending severity (`Error` first, then `Warn`,
66 /// then `Info`).
67 ///
68 /// # Arguments
69 ///
70 /// * `local` — the local store (read-only access required)
71 /// * `local_space` — space ID to query in the local store
72 /// * `remote` — the remote store (typically ATTACHed or opened separately)
73 /// * `remote_space` — space ID to query in the remote store
74 ///
75 /// # Examples
76 ///
77 /// ```
78 /// use g8_conflict::{ConflictDetector, ConflictStore};
79 /// use g8_conflict::store_trait::MemoryStore;
80 /// use g8_core::SpaceId;
81 ///
82 /// let local = MemoryStore::default();
83 /// let remote = MemoryStore::default();
84 /// let local_space = SpaceId::derive(&["docs", "local"]);
85 /// let remote_space = SpaceId::derive(&["docs", "remote"]);
86 ///
87 /// let conflicts = ConflictDetector::compare_spaces(
88 /// &local, &local_space,
89 /// &remote, &remote_space,
90 /// ).unwrap();
91 /// assert!(conflicts.is_empty(), "empty stores produce no conflicts");
92 /// ```
93 #[instrument(skip(local, remote), fields(local_space = %local_space, remote_space = %remote_space, conflicts_found))]
94 pub fn compare_spaces(
95 local: &dyn ConflictStore,
96 local_space: &SpaceId,
97 remote: &dyn ConflictStore,
98 remote_space: &SpaceId,
99 ) -> Result<Vec<Conflict>, ConflictError> {
100 let mut conflicts = Vec::new();
101
102 // ── 1. DuplicateIntent ───────────────────────────────────────────────
103 let duplicate_intent_conflicts =
104 detect_duplicate_intents(local, local_space, remote, remote_space)?;
105 conflicts.extend(duplicate_intent_conflicts);
106
107 // ── 2. CapabilityNameCollision ────────────────────────────────────────
108 let capability_collisions =
109 detect_capability_collisions(local, local_space, remote, remote_space)?;
110 conflicts.extend(capability_collisions);
111
112 // ── 3. ContradictoryDecisions ────────────────────────────────────────
113 let decision_conflicts =
114 detect_contradictory_decisions(local, local_space, remote, remote_space)?;
115 conflicts.extend(decision_conflicts);
116
117 // ── 4. GovernanceViolation ────────────────────────────────────────────
118 // Check plans in local against boundary intents in remote, AND
119 // plans in remote against boundary intents in local.
120 let gov_violations =
121 detect_governance_violations(local, local_space, remote, remote_space)?;
122 conflicts.extend(gov_violations);
123
124 // Sort by descending severity (Error > Warn > Info).
125 conflicts.sort_by_key(|c| std::cmp::Reverse(c.severity));
126
127 tracing::Span::current().record("conflicts_found", conflicts.len());
128
129 Ok(conflicts)
130 }
131
132 /// Detect conflicts within a single space (no cross-store comparison).
133 ///
134 /// Used by `g8 status --intra-conflicts` to surface issues in one workspace. Detects
135 /// duplicate intents and contradictory decisions within the same space.
136 ///
137 /// # Examples
138 ///
139 /// ```
140 /// use g8_conflict::{ConflictDetector, ConflictStore};
141 /// use g8_conflict::store_trait::MemoryStore;
142 /// use g8_core::SpaceId;
143 ///
144 /// let store = MemoryStore::default();
145 /// let space = SpaceId::derive(&["docs", "space"]);
146 ///
147 /// let conflicts = ConflictDetector::detect_intra_space(&store, &space).unwrap();
148 /// assert!(conflicts.is_empty());
149 /// ```
150 #[instrument(skip(store), fields(space = %space))]
151 pub fn detect_intra_space(
152 store: &dyn ConflictStore,
153 space: &SpaceId,
154 ) -> Result<Vec<Conflict>, ConflictError> {
155 let mut conflicts = Vec::new();
156
157 // Duplicate intents within the same space: compare the space against itself
158 // looking for same kind+scope_path with different descriptions (e.g. from
159 // different projects in the same space contributing conflicting section bodies).
160 let intents = store
161 .list_intents(space)
162 .map_err(|e| ConflictError::Store(e.to_string()))?;
163
164 // Group by (kind, scope_path) — if multiple intents share the key with
165 // different descriptions that is an intra-space duplicate.
166 let mut seen: std::collections::HashMap<(String, PathBuf), Vec<&store_trait::IntentRow>> =
167 std::collections::HashMap::new();
168 for intent in &intents {
169 let key = (format!("{:?}", intent.kind), intent.scope_path.clone());
170 seen.entry(key).or_default().push(intent);
171 }
172
173 for group in seen.values() {
174 if group.len() < 2 {
175 continue;
176 }
177 // Check if any pair has different descriptions.
178 let first = &group[0];
179 for other in group.iter().skip(1) {
180 if other.description != first.description {
181 let evidence = vec![
182 Evidence::IntentRef {
183 intent_id: first.id.clone(),
184 heading: first.heading.clone(),
185 path: first.scope_path.clone(),
186 },
187 Evidence::IntentRef {
188 intent_id: other.id.clone(),
189 heading: other.heading.clone(),
190 path: other.scope_path.clone(),
191 },
192 Evidence::Note {
193 text: format!(
194 "Intra-space duplicate: same kind={:?} scope_path={} with different description",
195 first.kind,
196 first.scope_path.display()
197 ),
198 },
199 ];
200 conflicts.push(Conflict {
201 kind: ConflictKind::DuplicateIntent,
202 severity: Severity::Warn,
203 evidence,
204 });
205 }
206 }
207 }
208
209 // Contradictory decisions within the same space.
210 let decisions = store
211 .list_decisions(space)
212 .map_err(|e| ConflictError::Store(e.to_string()))?;
213
214 let mut decision_map: std::collections::HashMap<String, Vec<&store_trait::DecisionRow>> =
215 std::collections::HashMap::new();
216 for d in &decisions {
217 decision_map.entry(d.title.clone()).or_default().push(d);
218 }
219
220 for (title, group) in &decision_map {
221 let accepted: Vec<&&store_trait::DecisionRow> =
222 group.iter().filter(|d| d.status_accepted).collect();
223 if accepted.len() < 2 {
224 continue;
225 }
226 let first = accepted[0];
227 for other in accepted.iter().skip(1) {
228 if other.body != first.body {
229 let evidence = vec![
230 Evidence::DecisionRef {
231 decision_id: first.id.clone(),
232 title: title.clone(),
233 },
234 Evidence::DecisionRef {
235 decision_id: other.id.clone(),
236 title: title.clone(),
237 },
238 Evidence::Note {
239 text: format!(
240 "Intra-space contradictory accepted decisions for title='{title}'"
241 ),
242 },
243 ];
244 conflicts.push(Conflict {
245 kind: ConflictKind::ContradictoryDecisions,
246 severity: Severity::Error,
247 evidence,
248 });
249 }
250 }
251 }
252
253 conflicts.sort_by_key(|c| std::cmp::Reverse(c.severity));
254 Ok(conflicts)
255 }
256}
257
258// ── Detection helpers (private) ──────────────────────────────────────────────
259
260/// Detect `DuplicateIntent` conflicts: same `kind + scope_path`, different `description`.
261///
262/// Severity: `Warn` (per ARCH §3.5 detection table).
263fn detect_duplicate_intents(
264 local: &dyn ConflictStore,
265 local_space: &SpaceId,
266 remote: &dyn ConflictStore,
267 remote_space: &SpaceId,
268) -> Result<Vec<Conflict>, ConflictError> {
269 let local_intents = local
270 .list_intents(local_space)
271 .map_err(|e| ConflictError::Store(e.to_string()))?;
272 let remote_intents = remote
273 .list_intents(remote_space)
274 .map_err(|e| ConflictError::Store(e.to_string()))?;
275
276 let mut conflicts = Vec::new();
277
278 for li in &local_intents {
279 for ri in &remote_intents {
280 let same_kind = li.kind == ri.kind;
281 let same_scope = li.scope_path == ri.scope_path;
282 let different_description = li.description != ri.description;
283
284 if same_kind && same_scope && different_description {
285 conflicts.push(Conflict {
286 kind: ConflictKind::DuplicateIntent,
287 severity: Severity::Warn,
288 evidence: vec![
289 Evidence::IntentRef {
290 intent_id: li.id.clone(),
291 heading: li.heading.clone(),
292 path: li.scope_path.clone(),
293 },
294 Evidence::IntentRef {
295 intent_id: ri.id.clone(),
296 heading: ri.heading.clone(),
297 path: ri.scope_path.clone(),
298 },
299 Evidence::Note {
300 text: format!(
301 "Both spaces declare intent kind={:?} at '{}' with different descriptions",
302 li.kind,
303 li.scope_path.display()
304 ),
305 },
306 ],
307 });
308 }
309 }
310 }
311
312 Ok(conflicts)
313}
314
315/// Detect `CapabilityNameCollision` conflicts.
316///
317/// - Same kebab-case `name` in both spaces AND no alias resolves them → `Error`
318/// - Same kebab-case `name` AND alias resolves them → `Info` (acknowledgment)
319///
320/// Cross-project capability identity key is `<project_name>::<capability_name>` per A1 decision #2.
321/// The project name is used only in lookup keys — annotations never carry the prefix.
322fn detect_capability_collisions(
323 local: &dyn ConflictStore,
324 local_space: &SpaceId,
325 remote: &dyn ConflictStore,
326 remote_space: &SpaceId,
327) -> Result<Vec<Conflict>, ConflictError> {
328 let local_caps = local
329 .list_capabilities(local_space)
330 .map_err(|e| ConflictError::Store(e.to_string()))?;
331 let remote_caps = remote
332 .list_capabilities(remote_space)
333 .map_err(|e| ConflictError::Store(e.to_string()))?;
334
335 // Build a map from canonical name → capability for the remote side.
336 // canonical key form: <project_name>::<capability_name>
337 let remote_by_name: std::collections::HashMap<&str, &store_trait::CapabilityRow> =
338 remote_caps.iter().map(|c| (c.name.as_str(), c)).collect();
339
340 let mut conflicts = Vec::new();
341
342 for lc in &local_caps {
343 if let Some(rc) = remote_by_name.get(lc.name.as_str()) {
344 // Same capability name exists in both spaces.
345 // Check if an alias resolves them — i.e. both are known by the same canonical name.
346 let local_key = format!("{}::{}", lc.project_name, lc.name);
347 let remote_key = format!("{}::{}", rc.project_name, rc.name);
348
349 let alias_resolves = local
350 .resolve_canonical(&local_key)
351 .and_then(|lk| remote.resolve_canonical(&remote_key).map(|rk| lk == rk))
352 .unwrap_or(false);
353
354 let (severity, note) = if alias_resolves {
355 (
356 Severity::Info,
357 format!(
358 "Capability '{}' exists in both spaces but alias resolves them to the same canonical identity",
359 lc.name
360 ),
361 )
362 } else {
363 (
364 Severity::Error,
365 format!(
366 "Capability '{}' exists in both spaces with no alias: cross-project name collision",
367 lc.name
368 ),
369 )
370 };
371
372 conflicts.push(Conflict {
373 kind: ConflictKind::CapabilityNameCollision,
374 severity,
375 evidence: vec![
376 Evidence::CapabilityRef {
377 capability_id: lc.id.clone(),
378 name: lc.name.clone(),
379 project: lc.project_name.clone(),
380 },
381 Evidence::CapabilityRef {
382 capability_id: rc.id.clone(),
383 name: rc.name.clone(),
384 project: rc.project_name.clone(),
385 },
386 Evidence::Note { text: note },
387 ],
388 });
389 }
390 }
391
392 Ok(conflicts)
393}
394
395/// Detect `ContradictoryDecisions` conflicts.
396///
397/// Rule: same `title` in both spaces, both with `status = accepted`, `body` differs.
398/// Severity: `Error`.
399fn detect_contradictory_decisions(
400 local: &dyn ConflictStore,
401 local_space: &SpaceId,
402 remote: &dyn ConflictStore,
403 remote_space: &SpaceId,
404) -> Result<Vec<Conflict>, ConflictError> {
405 let local_decisions = local
406 .list_decisions(local_space)
407 .map_err(|e| ConflictError::Store(e.to_string()))?;
408 let remote_decisions = remote
409 .list_decisions(remote_space)
410 .map_err(|e| ConflictError::Store(e.to_string()))?;
411
412 // Index remote accepted decisions by title.
413 let remote_accepted: std::collections::HashMap<&str, &store_trait::DecisionRow> =
414 remote_decisions
415 .iter()
416 .filter(|d| d.status_accepted)
417 .map(|d| (d.title.as_str(), d))
418 .collect();
419
420 let mut conflicts = Vec::new();
421
422 for ld in &local_decisions {
423 if !ld.status_accepted {
424 continue;
425 }
426 if let Some(rd) = remote_accepted.get(ld.title.as_str()) {
427 if ld.body != rd.body {
428 conflicts.push(Conflict {
429 kind: ConflictKind::ContradictoryDecisions,
430 severity: Severity::Error,
431 evidence: vec![
432 Evidence::DecisionRef {
433 decision_id: ld.id.clone(),
434 title: ld.title.clone(),
435 },
436 Evidence::DecisionRef {
437 decision_id: rd.id.clone(),
438 title: rd.title.clone(),
439 },
440 Evidence::Note {
441 text: format!(
442 "Both spaces have accepted decision '{}' but the body text differs",
443 ld.title
444 ),
445 },
446 ],
447 });
448 }
449 }
450 }
451
452 Ok(conflicts)
453}
454
455/// Detect `GovernanceViolation` conflicts.
456///
457/// Rule: A Plan in space A has `substrate = X`; space B has a `Boundary` intent at any ancestor
458/// path saying "never modify X" (the intent `description` or `heading` contains `substrate` name).
459///
460/// We check both directions: local plans vs remote boundaries, and remote plans vs local boundaries.
461/// Severity: `Error`.
462fn detect_governance_violations(
463 local: &dyn ConflictStore,
464 local_space: &SpaceId,
465 remote: &dyn ConflictStore,
466 remote_space: &SpaceId,
467) -> Result<Vec<Conflict>, ConflictError> {
468 let local_plans = local
469 .list_plans(local_space)
470 .map_err(|e| ConflictError::Store(e.to_string()))?;
471 let remote_plans = remote
472 .list_plans(remote_space)
473 .map_err(|e| ConflictError::Store(e.to_string()))?;
474
475 let remote_boundary_intents: Vec<store_trait::IntentRow> = remote
476 .list_intents(remote_space)
477 .map_err(|e| ConflictError::Store(e.to_string()))?
478 .into_iter()
479 .filter(|i| i.kind == IntentKind::Boundary)
480 .collect();
481
482 let local_boundary_intents: Vec<store_trait::IntentRow> = local
483 .list_intents(local_space)
484 .map_err(|e| ConflictError::Store(e.to_string()))?
485 .into_iter()
486 .filter(|i| i.kind == IntentKind::Boundary)
487 .collect();
488
489 let mut conflicts = Vec::new();
490
491 // Check local plans against remote boundary intents.
492 for plan in &local_plans {
493 if let Some(ref substrate) = plan.substrate {
494 for boundary in &remote_boundary_intents {
495 if boundary_forbids(boundary, substrate) {
496 conflicts.push(Conflict {
497 kind: ConflictKind::GovernanceViolation,
498 severity: Severity::Error,
499 evidence: vec![
500 Evidence::PlanRef {
501 plan_id: plan.id.clone(),
502 title: plan.title.clone(),
503 space: local_space.as_str().to_string(),
504 },
505 Evidence::IntentRef {
506 intent_id: boundary.id.clone(),
507 heading: boundary.heading.clone(),
508 path: boundary.scope_path.clone(),
509 },
510 Evidence::Note {
511 text: format!(
512 "Plan '{}' uses substrate '{substrate}' which is forbidden by boundary intent '{}' in the remote space",
513 plan.title, boundary.heading
514 ),
515 },
516 ],
517 });
518 }
519 }
520 }
521 }
522
523 // Check remote plans against local boundary intents.
524 for plan in &remote_plans {
525 if let Some(ref substrate) = plan.substrate {
526 for boundary in &local_boundary_intents {
527 if boundary_forbids(boundary, substrate) {
528 conflicts.push(Conflict {
529 kind: ConflictKind::GovernanceViolation,
530 severity: Severity::Error,
531 evidence: vec![
532 Evidence::PlanRef {
533 plan_id: plan.id.clone(),
534 title: plan.title.clone(),
535 space: remote_space.as_str().to_string(),
536 },
537 Evidence::IntentRef {
538 intent_id: boundary.id.clone(),
539 heading: boundary.heading.clone(),
540 path: boundary.scope_path.clone(),
541 },
542 Evidence::Note {
543 text: format!(
544 "Remote plan '{}' uses substrate '{substrate}' which is forbidden by boundary intent '{}' in the local space",
545 plan.title, boundary.heading
546 ),
547 },
548 ],
549 });
550 }
551 }
552 }
553 }
554
555 Ok(conflicts)
556}
557
558/// Returns `true` if the boundary intent description or heading contains a reference that
559/// forbids the given substrate.
560///
561/// The detection heuristic: the intent description contains the substring "never modify",
562/// "never use", "do not use", or "forbidden" followed (within 80 chars) by the substrate name,
563/// OR the heading or description contains the exact substrate name (case-insensitive).
564///
565/// This is intentionally simple for v0.1. Richer NL parsing is v0.2 scope.
566fn boundary_forbids(boundary: &store_trait::IntentRow, substrate: &str) -> bool {
567 let lower_desc = boundary.description.to_lowercase();
568 let lower_heading = boundary.heading.to_lowercase();
569 let lower_substrate = substrate.to_lowercase();
570
571 // Direct mention of the substrate in the heading or description.
572 let mentions_substrate =
573 lower_desc.contains(&lower_substrate) || lower_heading.contains(&lower_substrate);
574
575 if !mentions_substrate {
576 return false;
577 }
578
579 // Must also contain a prohibition keyword to count as a governance constraint.
580 lower_desc.contains("never modify")
581 || lower_desc.contains("never use")
582 || lower_desc.contains("do not use")
583 || lower_desc.contains("forbidden")
584 || lower_desc.contains("prohibited")
585 || lower_desc.contains("must not")
586 || lower_heading.contains("never modify")
587 || lower_heading.contains("never use")
588 || lower_heading.contains("forbidden")
589 || lower_heading.contains("must not")
590}