octomind 0.25.0

Session-based AI development assistant with conversational codebase interaction, multimodal vision support, built-in MCP tools, and multi-provider AI integration
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
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Schedule storage: entries, store operations, and time parsing.

use anyhow::{bail, Result};
use chrono::{DateTime, Duration, Local, NaiveTime};
use uuid::Uuid;

/// A single scheduled task.
#[derive(Debug, Clone)]
pub struct ScheduleEntry {
	/// Short unique ID (first 8 chars of UUID).
	pub id: String,
	/// Human-readable description of what this task is about.
	pub description: String,
	/// Exact text that will be injected verbatim as a user message when triggered.
	pub message: String,
	/// When to fire this entry.
	pub trigger_at: DateTime<Local>,
	/// When this entry was created.
	pub created_at: DateTime<Local>,
}

impl ScheduleEntry {
	pub fn new(description: String, message: String, trigger_at: DateTime<Local>) -> Self {
		let id = Uuid::new_v4().to_string()[..8].to_string();
		Self {
			id,
			description,
			message,
			trigger_at,
			created_at: Local::now(),
		}
	}

	/// Human-friendly countdown string, e.g. "in 1h 23m" or "in 45s".
	pub fn countdown(&self) -> String {
		let now = Local::now();
		let diff = self.trigger_at.signed_duration_since(now);
		if diff.num_seconds() <= 0 {
			return "now".to_string();
		}
		let total_secs = diff.num_seconds();
		let hours = total_secs / 3600;
		let mins = (total_secs % 3600) / 60;
		let secs = total_secs % 60;
		if hours > 0 {
			format!("in {}h {}m", hours, mins)
		} else if mins > 0 {
			format!("in {}m {}s", mins, secs)
		} else {
			format!("in {}s", secs)
		}
	}
}

/// In-memory store for scheduled entries. Sorted by trigger_at ascending.
#[derive(Default)]
pub struct ScheduleStore {
	entries: Vec<ScheduleEntry>,
}

impl ScheduleStore {
	pub fn new() -> Self {
		Self::default()
	}

	/// Add a new entry. Returns the entry ID.
	pub fn add(&mut self, entry: ScheduleEntry) -> String {
		let id = entry.id.clone();
		self.entries.push(entry);
		// Keep sorted by trigger time so pop_due and next_due are O(1).
		self.entries.sort_by_key(|e| e.trigger_at);
		id
	}

	/// Remove an entry by ID. Returns true if found and removed.
	pub fn remove(&mut self, id: &str) -> bool {
		let before = self.entries.len();
		self.entries.retain(|e| e.id != id);
		self.entries.len() < before
	}

	/// Edit an existing entry. Only provided fields are updated.
	pub fn edit(
		&mut self,
		id: &str,
		description: Option<String>,
		message: Option<String>,
		trigger_at: Option<DateTime<Local>>,
	) -> bool {
		let entry = self.entries.iter_mut().find(|e| e.id == id);
		match entry {
			None => false,
			Some(e) => {
				if let Some(d) = description {
					e.description = d;
				}
				if let Some(m) = message {
					e.message = m;
				}
				if let Some(t) = trigger_at {
					e.trigger_at = t;
				}
				// Re-sort after potential time change.
				self.entries.sort_by_key(|e| e.trigger_at);
				true
			}
		}
	}

	/// Pop the earliest entry that is due (trigger_at <= now). Returns None if nothing is due.
	pub fn pop_due(&mut self) -> Option<ScheduleEntry> {
		let now = Local::now();
		if self
			.entries
			.first()
			.map(|e| e.trigger_at <= now)
			.unwrap_or(false)
		{
			Some(self.entries.remove(0))
		} else {
			None
		}
	}

	/// Duration until the next entry fires. Returns None if the store is empty.
	pub fn next_due_duration(&self) -> Option<std::time::Duration> {
		let now = Local::now();
		self.entries.first().map(|e| {
			let diff = e.trigger_at.signed_duration_since(now);
			if diff.num_milliseconds() <= 0 {
				std::time::Duration::ZERO
			} else {
				std::time::Duration::from_millis(diff.num_milliseconds() as u64)
			}
		})
	}

	pub fn is_empty(&self) -> bool {
		self.entries.is_empty()
	}

	pub fn entries(&self) -> &[ScheduleEntry] {
		&self.entries
	}
}

// ---------------------------------------------------------------------------
// Time parsing
// ---------------------------------------------------------------------------

/// Parse a human-readable time expression into an absolute `DateTime<Local>`.
///
/// Supported formats:
/// - Relative: `"in 5m"`, `"in 2h"`, `"in 1h30m"`, `"in 90s"`, `"in 2h 30m 10s"`
/// - Absolute time today: `"15:30"`, `"3:30pm"`, `"9am"` (if past, schedules for tomorrow)
/// - Absolute datetime: `"2026-03-22 15:30"`, `"2026-03-22 15:30:00"`
pub fn parse_when(input: &str) -> Result<DateTime<Local>> {
	let s = input.trim().to_lowercase();

	if let Some(stripped) = s.strip_prefix("in ") {
		return parse_relative(stripped);
	}

	// Try absolute datetime first (contains a space between date and time parts with dashes).
	if s.contains('-') && s.contains(' ') {
		return parse_absolute_datetime(&s);
	}

	// Try absolute time-of-day.
	parse_time_of_day(&s)
}

/// Parse relative duration like `"5m"`, `"2h"`, `"1h30m"`, `"2h 30m 10s"`.
fn parse_relative(s: &str) -> Result<DateTime<Local>> {
	let total_secs = parse_duration_secs(s)?;
	if total_secs == 0 {
		bail!("duration must be greater than zero");
	}
	Ok(Local::now() + Duration::seconds(total_secs))
}

/// Parse a duration string into total seconds.
/// Accepts: `"5m"`, `"2h"`, `"90s"`, `"1h30m"`, `"2h 30m 10s"` (spaces optional).
fn parse_duration_secs(s: &str) -> Result<i64> {
	// Remove spaces so "1h 30m" and "1h30m" both work.
	let s = s.replace(' ', "");
	if s.is_empty() {
		bail!("empty duration");
	}

	let mut total: i64 = 0;
	let mut num_buf = String::new();

	for ch in s.chars() {
		if ch.is_ascii_digit() {
			num_buf.push(ch);
		} else {
			let n: i64 = if num_buf.is_empty() {
				bail!("expected number before '{}'", ch)
			} else {
				num_buf.parse()?
			};
			num_buf.clear();
			match ch {
				'h' => total += n * 3600,
				'm' => total += n * 60,
				's' => total += n,
				_ => bail!("unknown unit '{}' — use h, m, or s", ch),
			}
		}
	}

	if !num_buf.is_empty() {
		bail!(
			"trailing number '{}' without unit (use h, m, or s)",
			num_buf
		);
	}

	Ok(total)
}

/// Parse `"15:30"`, `"3:30pm"`, `"9am"` into today's date at that time.
/// If the time is already past, schedules for tomorrow.
fn parse_time_of_day(s: &str) -> Result<DateTime<Local>> {
	let naive_time = parse_naive_time(s)?;
	let now = Local::now();
	let today = now.date_naive();
	let candidate = today
		.and_time(naive_time)
		.and_local_timezone(Local)
		.single()
		.ok_or_else(|| anyhow::anyhow!("ambiguous local time"))?;

	// If already past, schedule for tomorrow.
	if candidate <= now {
		let tomorrow = today
			.succ_opt()
			.ok_or_else(|| anyhow::anyhow!("date overflow"))?;
		let next = tomorrow
			.and_time(naive_time)
			.and_local_timezone(Local)
			.single()
			.ok_or_else(|| anyhow::anyhow!("ambiguous local time"))?;
		Ok(next)
	} else {
		Ok(candidate)
	}
}

/// Parse time strings: `"15:30"`, `"15:30:00"`, `"3:30pm"`, `"9am"`.
fn parse_naive_time(s: &str) -> Result<NaiveTime> {
	// Strip am/pm suffix.
	let (s, pm) = if let Some(stripped) = s.strip_suffix("pm") {
		(stripped, true)
	} else if let Some(stripped) = s.strip_suffix("am") {
		(stripped, false)
	} else {
		(s, false)
	};

	let parts: Vec<&str> = s.split(':').collect();
	let mut hour: u32 = parts
		.first()
		.ok_or_else(|| anyhow::anyhow!("invalid time"))?
		.parse()?;
	let minute: u32 = parts.get(1).unwrap_or(&"0").parse()?;
	let second: u32 = parts.get(2).unwrap_or(&"0").parse()?;

	if pm && hour != 12 {
		hour += 12;
	} else if !pm && hour == 12 {
		// 12am = midnight
		hour = 0;
	}

	NaiveTime::from_hms_opt(hour, minute, second)
		.ok_or_else(|| anyhow::anyhow!("invalid time {}:{}:{}", hour, minute, second))
}

/// Parse `"2026-03-22 15:30"` or `"2026-03-22 15:30:00"`.
fn parse_absolute_datetime(s: &str) -> Result<DateTime<Local>> {
	// Try with seconds first, then without.
	if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
		return dt
			.and_local_timezone(Local)
			.single()
			.ok_or_else(|| anyhow::anyhow!("ambiguous local datetime"));
	}
	if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M") {
		return dt
			.and_local_timezone(Local)
			.single()
			.ok_or_else(|| anyhow::anyhow!("ambiguous local datetime"));
	}
	bail!(
		"could not parse datetime '{}' — expected format: YYYY-MM-DD HH:MM",
		s
	)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
	use super::*;
	use chrono::{Datelike, Timelike};

	#[test]
	fn test_parse_relative_minutes() {
		let t = parse_when("in 5m").unwrap();
		let diff = t.signed_duration_since(Local::now()).num_seconds();
		assert!((295..=305).contains(&diff), "expected ~300s, got {}", diff);
	}

	#[test]
	fn test_parse_relative_hours() {
		let t = parse_when("in 2h").unwrap();
		let diff = t.signed_duration_since(Local::now()).num_seconds();
		assert!(
			(7195..=7205).contains(&diff),
			"expected ~7200s, got {}",
			diff
		);
	}

	#[test]
	fn test_parse_relative_combined() {
		let t = parse_when("in 1h30m").unwrap();
		let diff = t.signed_duration_since(Local::now()).num_seconds();
		assert!(
			(5395..=5405).contains(&diff),
			"expected ~5400s, got {}",
			diff
		);
	}

	#[test]
	fn test_parse_relative_with_spaces() {
		let t = parse_when("in 1h 30m 10s").unwrap();
		let diff = t.signed_duration_since(Local::now()).num_seconds();
		assert!(
			(5405..=5415).contains(&diff),
			"expected ~5410s, got {}",
			diff
		);
	}

	#[test]
	fn test_parse_relative_seconds() {
		let t = parse_when("in 90s").unwrap();
		let diff = t.signed_duration_since(Local::now()).num_seconds();
		assert!((88..=92).contains(&diff), "expected ~90s, got {}", diff);
	}

	#[test]
	fn test_parse_absolute_datetime() {
		let t = parse_when("2099-12-31 23:59").unwrap();
		assert_eq!(t.year(), 2099);
		assert_eq!(t.month(), 12);
		assert_eq!(t.day(), 31);
		assert_eq!(t.hour(), 23);
		assert_eq!(t.minute(), 59);
	}

	#[test]
	fn test_parse_invalid_relative() {
		assert!(parse_when("in 5x").is_err());
		assert!(parse_when("in ").is_err());
		assert!(parse_when("in 0m").is_err());
	}

	#[test]
	fn test_store_pop_due() {
		let mut store = ScheduleStore::new();
		let past = Local::now() - Duration::seconds(1);
		let entry = ScheduleEntry {
			id: "test0001".to_string(),
			description: "test".to_string(),
			message: "hello".to_string(),
			trigger_at: past,
			created_at: Local::now(),
		};
		store.add(entry);
		assert!(store.pop_due().is_some());
		assert!(store.is_empty());
	}

	#[test]
	fn test_store_not_due_yet() {
		let mut store = ScheduleStore::new();
		let future = Local::now() + Duration::seconds(3600);
		let entry = ScheduleEntry {
			id: "test0002".to_string(),
			description: "test".to_string(),
			message: "hello".to_string(),
			trigger_at: future,
			created_at: Local::now(),
		};
		store.add(entry);
		assert!(store.pop_due().is_none());
		assert!(!store.is_empty());
	}

	#[test]
	fn test_store_sorted_by_trigger() {
		let mut store = ScheduleStore::new();
		let later = Local::now() + Duration::seconds(7200);
		let sooner = Local::now() + Duration::seconds(3600);
		store.add(ScheduleEntry {
			id: "late0001".to_string(),
			description: "later".to_string(),
			message: "b".to_string(),
			trigger_at: later,
			created_at: Local::now(),
		});
		store.add(ScheduleEntry {
			id: "soon0001".to_string(),
			description: "sooner".to_string(),
			message: "a".to_string(),
			trigger_at: sooner,
			created_at: Local::now(),
		});
		// First entry should be the sooner one.
		assert_eq!(store.entries()[0].id, "soon0001");
	}
}