1use std::collections::HashMap;
4
5use rusqlite::{Connection, params};
6
7use crate::error::{KernelError, Result};
8
9use super::types::GraphStats;
10
11pub fn touch_node(conn: &Connection, id: &str) {
15 let now = now_iso();
16 let _ = conn.execute(
17 "UPDATE nodes SET access_count = access_count + 1, accessed_at = ?1 WHERE id = ?2",
18 params![now, id],
19 );
20}
21
22pub fn touch_nodes(conn: &Connection, ids: &[String]) {
24 if ids.is_empty() {
25 return;
26 }
27 let _ = conn.execute_batch("SAVEPOINT touch_batch");
28 for id in ids {
29 touch_node(conn, id);
30 }
31 let _ = conn.execute_batch("RELEASE touch_batch");
32}
33
34pub fn decay_importance(conn: &Connection, days: u64, factor: f64, floor: f64) -> Result<u64> {
44 let cutoff = compute_cutoff_timestamp(days);
45 let changed = conn
46 .execute(
47 "UPDATE nodes SET importance = MAX(?3, importance * ?2)
48 WHERE (accessed_at < ?1 OR accessed_at = '')
49 AND updated < ?1
50 AND importance > ?3
51 AND ',' || tags || ',' NOT LIKE '%,pinned,%'",
52 params![cutoff, factor, floor],
53 )
54 .map_err(|e| KernelError::Store(e.to_string()))?;
55 Ok(changed as u64)
56}
57
58pub fn tag_stale_nodes(conn: &Connection, days: u64) -> Result<u64> {
60 let cutoff = compute_cutoff_timestamp(days);
61 let changed = conn
62 .execute(
63 "UPDATE nodes SET tags = CASE
64 WHEN tags = '' THEN 'stale'
65 WHEN ',' || tags || ',' NOT LIKE '%,stale,%' THEN tags || ',stale'
66 ELSE tags
67 END
68 WHERE updated < ?1
69 AND ',' || tags || ',' NOT LIKE '%,stale,%'",
70 params![cutoff],
71 )
72 .map_err(|e| KernelError::Store(e.to_string()))?;
73 Ok(changed as u64)
74}
75
76pub fn compute_stats(conn: &Connection) -> Result<GraphStats> {
80 let total_nodes: i64 = conn
81 .query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))
82 .unwrap_or(0);
83 let total_edges: i64 = conn
84 .query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))
85 .unwrap_or(0);
86 let avg_importance: f64 = conn
87 .query_row("SELECT AVG(importance) FROM nodes", [], |r| r.get(0))
88 .unwrap_or(0.0);
89
90 let mut stmt = conn
91 .prepare("SELECT type, COUNT(*) FROM nodes GROUP BY type")
92 .map_err(|e| KernelError::Store(e.to_string()))?;
93 let by_type: HashMap<String, i64> = stmt
94 .query_map([], |row| {
95 let t: String = row.get(0)?;
96 let c: i64 = row.get(1)?;
97 Ok((t, c))
98 })
99 .map(|rows| rows.flatten().collect())
100 .unwrap_or_default();
101
102 Ok(GraphStats {
103 total_nodes,
104 total_edges,
105 avg_importance: (avg_importance * 100.0).round() / 100.0,
106 by_type,
107 })
108}
109
110fn compute_cutoff_timestamp(days: u64) -> String {
113 let secs = std::time::SystemTime::now()
114 .duration_since(std::time::SystemTime::UNIX_EPOCH)
115 .unwrap_or_default()
116 .as_secs()
117 .saturating_sub(days * 86400);
118 let (y, m, d) = days_to_ymd(secs / 86400);
119 let hh = (secs / 3600) % 24;
120 let mm = (secs / 60) % 60;
121 let ss = secs % 60;
122 format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
123}
124
125pub(crate) fn days_to_ymd(mut days: u64) -> (u64, u64, u64) {
126 let mut year = 1970u64;
127 loop {
128 let leap = is_leap(year);
129 let days_in_year = if leap { 366 } else { 365 };
130 if days < days_in_year {
131 break;
132 }
133 days -= days_in_year;
134 year += 1;
135 }
136 let leap = is_leap(year);
137 let month_days = [
138 31u64,
139 if leap { 29 } else { 28 },
140 31,
141 30,
142 31,
143 30,
144 31,
145 31,
146 30,
147 31,
148 30,
149 31,
150 ];
151 let mut month = 1u64;
152 for md in &month_days {
153 if days < *md {
154 break;
155 }
156 days -= md;
157 month += 1;
158 }
159 (year, month, days + 1)
160}
161
162fn is_leap(y: u64) -> bool {
163 (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400)
164}
165
166pub(crate) fn now_iso() -> String {
167 let secs = std::time::SystemTime::now()
168 .duration_since(std::time::SystemTime::UNIX_EPOCH)
169 .unwrap_or_default()
170 .as_secs();
171 let (y, m, d) = days_to_ymd(secs / 86400);
172 let hh = (secs / 3600) % 24;
173 let mm = (secs / 60) % 60;
174 let ss = secs % 60;
175 format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
176}
177
178pub(crate) fn parse_iso_to_secs(ts: &str) -> u64 {
180 if ts.len() < 19 {
181 return 0;
182 }
183 let year: u64 = ts[0..4].parse().unwrap_or(0);
184 let month: u64 = ts[5..7].parse().unwrap_or(1);
185 let day: u64 = ts[8..10].parse().unwrap_or(1);
186 let hour: u64 = ts[11..13].parse().unwrap_or(0);
187 let min: u64 = ts[14..16].parse().unwrap_or(0);
188 let sec: u64 = ts[17..19].parse().unwrap_or(0);
189
190 let total_days = days_since_epoch(year, month, day);
191 total_days * 86400 + hour * 3600 + min * 60 + sec
192}
193
194fn days_since_epoch(year: u64, month: u64, day: u64) -> u64 {
195 let y = year as i64 - 1;
196 let base = 1969i64;
197 let leaps = (y / 4 - y / 100 + y / 400) - (base / 4 - base / 100 + base / 400);
198 let days_from_years = (year as i64 - 1970) * 365 + leaps;
199
200 const MONTH_DAYS: [u64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
201 let leap = (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400);
202 let mut days_from_months: u64 = 0;
203 let prior_months = (month.saturating_sub(1) as usize).min(12);
204 for (m, &md) in MONTH_DAYS.iter().enumerate().take(prior_months) {
205 days_from_months += md;
206 if m == 1 && leap {
207 days_from_months += 1;
208 }
209 }
210 (days_from_years as u64) + days_from_months + day.saturating_sub(1)
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use crate::graph::schema::init_graph_schema;
217 use crate::graph::store::upsert_node;
218 use crate::graph::types::GraphNode;
219 use rusqlite::Connection;
220
221 fn mem_db() -> Connection {
222 let conn = Connection::open_in_memory().unwrap();
223 init_graph_schema(&conn).unwrap();
224 conn
225 }
226
227 fn test_node(id: &str, importance: f64, tags: Vec<&str>) -> GraphNode {
228 GraphNode {
229 id: id.to_string(),
230 node_type: "concept".to_string(),
231 title: format!("Node {id}"),
232 body: String::new(),
233 tags: tags.into_iter().map(|s| s.to_string()).collect(),
234 projects: vec![],
235 agents: vec![],
236 created: "2026-01-01T00:00:00Z".to_string(),
237 updated: "2026-01-01T00:00:00Z".to_string(),
238 importance,
239 access_count: 0,
240 accessed_at: String::new(),
241 }
242 }
243
244 #[test]
245 fn touch_node_increments_count() {
246 let conn = mem_db();
247 upsert_node(&conn, &test_node("n1", 0.7, vec![])).unwrap();
248 touch_node(&conn, "n1");
249 touch_node(&conn, "n1");
250 let node = crate::graph::store::read_node(&conn, "n1")
251 .unwrap()
252 .unwrap();
253 assert_eq!(node.access_count, 2);
254 assert!(!node.accessed_at.is_empty());
255 }
256
257 #[test]
258 fn decay_reduces_importance() {
259 let conn = mem_db();
260 upsert_node(&conn, &test_node("n1", 0.8, vec![])).unwrap();
262 let changed = decay_importance(&conn, 30, 0.9, 0.05).unwrap();
263 assert!(changed > 0);
264 let node = crate::graph::store::read_node(&conn, "n1")
265 .unwrap()
266 .unwrap();
267 assert!(node.importance < 0.8);
268 }
269
270 #[test]
271 fn decay_skips_pinned() {
272 let conn = mem_db();
273 upsert_node(&conn, &test_node("n1", 0.9, vec!["pinned"])).unwrap();
274 let changed = decay_importance(&conn, 30, 0.9, 0.05).unwrap();
275 assert_eq!(changed, 0);
276 }
277
278 #[test]
279 fn tag_stale_marks_old_nodes() {
280 let conn = mem_db();
281 upsert_node(&conn, &test_node("n1", 0.5, vec![])).unwrap();
282 let changed = tag_stale_nodes(&conn, 30).unwrap();
283 assert!(changed > 0);
284 let node = crate::graph::store::read_node(&conn, "n1")
285 .unwrap()
286 .unwrap();
287 assert!(node.tags.contains(&"stale".to_string()));
288 }
289
290 #[test]
291 fn compute_stats_returns_counts() {
292 let conn = mem_db();
293 let mut n1 = test_node("n1", 0.7, vec![]);
294 n1.node_type = "decision".to_string();
295 upsert_node(&conn, &n1).unwrap();
296 upsert_node(&conn, &test_node("n2", 0.5, vec![])).unwrap();
297
298 let stats = compute_stats(&conn).unwrap();
299 assert_eq!(stats.total_nodes, 2);
300 assert_eq!(stats.total_edges, 0);
301 assert!(stats.by_type.contains_key("decision"));
302 }
303
304 #[test]
305 fn parse_iso_roundtrip() {
306 let secs = parse_iso_to_secs("2026-01-15T12:30:45Z");
307 assert!(secs > 0);
308 }
309}