interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / goals.rs

457 lines · 15489 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use chrono::Utc;
17use colored::*;
18use serde::{Deserialize, Serialize};
19use serde_json::{json, Value};
20use std::fs;
21use std::path::{Path, PathBuf};
22
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
24pub enum GoalStatus {
25 Active,
26 Completed,
27 Paused,
28}
29
30impl std::fmt::Display for GoalStatus {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 match self {
33 GoalStatus::Active => write!(f, "Active"),
34 GoalStatus::Completed => write!(f, "Completed"),
35 GoalStatus::Paused => write!(f, "Paused"),
36 }
37 }
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct Milestone {
42 pub id: usize,
43 pub description: String,
44 pub completed: bool,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct Goal {
49 pub id: String,
50 pub title: String,
51 pub description: String,
52 pub status: GoalStatus,
53 pub milestones: Vec<Milestone>,
54 pub created_at: String,
55 pub updated_at: String,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, Default)]
59pub struct GoalManifest {
60 pub project_name: String,
61 pub goals: Vec<Goal>,
62}
63
64pub fn get_goals_path() -> PathBuf {
65 let local = Path::new(".goals.json");
66 if local.exists() {
67 return local.to_path_buf();
68 }
69 crate::platform::PlatformContext::detect()
70 .home_dir
71 .join("basecamp/goals.json")
72}
73
74pub fn load_goals() -> GoalManifest {
75 let path = get_goals_path();
76 if path.exists() {
77 if let Ok(content) = fs::read_to_string(&path) {
78 if let Ok(manifest) = serde_json::from_str::<GoalManifest>(&content) {
79 return manifest;
80 }
81 }
82 }
83 GoalManifest {
84 project_name: "Sovereign Workspace".to_string(),
85 goals: Vec::new(),
86 }
87}
88
89pub fn save_goals(manifest: &GoalManifest) -> Result<PathBuf, String> {
90 let path = get_goals_path();
91 let json_str = serde_json::to_string_pretty(manifest).map_err(|e| e.to_string())?;
92 fs::write(&path, json_str).map_err(|e| e.to_string())?;
93 Ok(path)
94}
95
96pub fn add_goal(title: &str, description: &str, milestones_raw: Vec<String>) -> Goal {
97 let mut manifest = load_goals();
98 let id = format!("goal-{}", Utc::now().timestamp());
99
100 let milestones: Vec<Milestone> = milestones_raw
101 .into_iter()
102 .enumerate()
103 .map(|(idx, d)| Milestone {
104 id: idx + 1,
105 description: d,
106 completed: false,
107 })
108 .collect();
109
110 let now_str = Utc::now().to_rfc3339();
111 let goal = Goal {
112 id: id.clone(),
113 title: title.to_string(),
114 description: description.to_string(),
115 status: GoalStatus::Active,
116 milestones,
117 created_at: now_str.clone(),
118 updated_at: now_str,
119 };
120
121 manifest.goals.push(goal.clone());
122 let _ = save_goals(&manifest);
123 goal
124}
125
126pub(crate) fn goal_index(goals: &[Goal], target: &str) -> Option<usize> {
127 goals.iter().position(|goal| goal.id == target).or_else(|| {
128 let title = target.to_lowercase();
129 goals
130 .iter()
131 .position(|goal| goal.title.to_lowercase().contains(&title))
132 })
133}
134
135pub fn complete_goal(target_id: &str) -> Result<String, String> {
136 complete_goal_with(target_id, load_goals(), save_goals)
137}
138
139fn complete_goal_with(
140 target_id: &str,
141 mut manifest: GoalManifest,
142 save: impl FnOnce(&GoalManifest) -> Result<PathBuf, String>,
143) -> Result<String, String> {
144 let index = goal_index(&manifest.goals, target_id)
145 .ok_or_else(|| format!("Goal '{}' not found in manifest.", target_id))?;
146 let goal = &mut manifest.goals[index];
147 goal.status = GoalStatus::Completed;
148 for milestone in &mut goal.milestones {
149 milestone.completed = true;
150 }
151 goal.updated_at = Utc::now().to_rfc3339();
152 save(&manifest)?;
153 Ok(format!(
154 "Goal '{}' ({}) marked as Completed.",
155 manifest.goals[index].title, target_id
156 ))
157}
158
159pub fn complete_milestone(target_id: &str, milestone_id: usize) -> Result<String, String> {
160 complete_milestone_with(target_id, milestone_id, load_goals(), save_goals)
161}
162
163fn complete_milestone_with(
164 target_id: &str,
165 milestone_id: usize,
166 mut manifest: GoalManifest,
167 save: impl FnOnce(&GoalManifest) -> Result<PathBuf, String>,
168) -> Result<String, String> {
169 let missing = || {
170 format!(
171 "Milestone {} for goal '{}' not found.",
172 milestone_id, target_id
173 )
174 };
175 let index = goal_index(&manifest.goals, target_id).ok_or_else(missing)?;
176 let goal = &mut manifest.goals[index];
177 let milestone = goal
178 .milestones
179 .iter_mut()
180 .find(|milestone| milestone.id == milestone_id)
181 .ok_or_else(missing)?;
182 milestone.completed = true;
183 goal.updated_at = Utc::now().to_rfc3339();
184 let all_completed = goal.milestones.iter().all(|milestone| milestone.completed);
185 if all_completed {
186 goal.status = GoalStatus::Completed;
187 }
188 save(&manifest)?;
189 if all_completed {
190 Ok(format!(
191 "Milestone {} completed. All milestones finished! Goal is now Completed.",
192 milestone_id
193 ))
194 } else {
195 Ok(format!("Milestone {} completed.", milestone_id))
196 }
197}
198
199pub fn format_goals_tui() -> String {
200 let manifest = load_goals();
201 let mut out = String::new();
202
203 out.push_str(&format!(
204 "{}\n",
205 format!("=== Project Goals: {} ===", manifest.project_name)
206 .cyan()
207 .bold()
208 ));
209 if manifest.goals.is_empty() {
210 out.push_str(&format!(
211 "{}\n",
212 "No active goals in manifest. Use '/goal new <title>' to create one.".dimmed()
213 ));
214 return out;
215 }
216
217 for (i, g) in manifest.goals.iter().enumerate() {
218 let status_colored = match g.status {
219 GoalStatus::Active => "[ACTIVE]".green().bold(),
220 GoalStatus::Completed => "[DONE]".dimmed(),
221 GoalStatus::Paused => "[PAUSED]".yellow(),
222 };
223
224 out.push_str(&format!(
225 "{}. {} {} ({})\n",
226 i + 1,
227 status_colored,
228 g.title.bold(),
229 g.id.cyan()
230 ));
231 if !g.description.is_empty() {
232 out.push_str(&format!(" {}\n", g.description.dimmed()));
233 }
234
235 for m in &g.milestones {
236 let mark = if m.completed {
237 "✓".green()
238 } else {
239 "○".dimmed()
240 };
241 out.push_str(&format!(" {} {}. {}\n", mark, m.id, m.description));
242 }
243 out.push('\n');
244 }
245
246 out
247}
248
249pub fn goals_dispatch_tool(args: &Value) -> Value {
250 let action = args.get("action").and_then(Value::as_str).unwrap_or("list");
251
252 match action {
253 "milestone_done" | "advance" => {
254 let id = args.get("id").and_then(Value::as_str).unwrap_or("");
255 let m_id = args
256 .get("milestone_id")
257 .and_then(Value::as_u64)
258 .unwrap_or(1) as usize;
259 match complete_milestone(id, m_id) {
260 Ok(msg) => json!({"status": "ok", "message": msg}),
261 Err(e) => json!({"status": "error", "error": e}),
262 }
263 }
264 "new" | "create" => {
265 let title = args
266 .get("title")
267 .and_then(Value::as_str)
268 .unwrap_or("Untitled Goal");
269 let desc = args
270 .get("description")
271 .and_then(Value::as_str)
272 .unwrap_or("");
273 let milestones: Vec<String> = args
274 .get("milestones")
275 .and_then(Value::as_array)
276 .map(|arr| {
277 arr.iter()
278 .filter_map(Value::as_str)
279 .map(|s| s.to_string())
280 .collect()
281 })
282 .unwrap_or_default();
283
284 let g = add_goal(title, desc, milestones);
285 json!({
286 "status": "ok",
287 "goal": g,
288 "message": format!("Goal '{}' initialized successfully.", title)
289 })
290 }
291 "done" | "complete" => {
292 let id = args.get("id").and_then(Value::as_str).unwrap_or("");
293 match complete_goal(id) {
294 Ok(msg) => json!({"status": "ok", "message": msg}),
295 Err(e) => json!({"status": "error", "error": e}),
296 }
297 }
298 "list" => {
299 let manifest = load_goals();
300 json!({
301 "status": "ok",
302 "project": manifest.project_name,
303 "total_goals": manifest.goals.len(),
304 "goals": manifest.goals
305 })
306 }
307 _ => json!({"error": format!("Unknown goal action '{}'", action)}),
308 }
309}
310
311#[cfg(test)]
312mod completion_tests {
313 use super::*;
314 fn manifest() -> GoalManifest {
315 GoalManifest {
316 project_name: "isolated".into(),
317 goals: vec![Goal {
318 id: "active".into(),
319 title: "active".into(),
320 description: "test".into(),
321 status: GoalStatus::Active,
322 created_at: "test".into(),
323 updated_at: "test".into(),
324 milestones: vec![Milestone {
325 id: 7,
326 description: "test".into(),
327 completed: false,
328 }],
329 }],
330 }
331 }
332 #[test]
333 fn round3_milestone_persistence_failure_is_error() {
334 let scratch = tempfile::tempdir().unwrap();
335 let blocked = scratch.path().join("goals.json");
336 std::fs::create_dir(&blocked).unwrap();
337 let result = complete_milestone_with("active", 7, manifest(), |m| {
338 std::fs::write(&blocked, serde_json::to_vec(m).unwrap())
339 .map(|_| blocked.clone())
340 .map_err(|e| format!("write goals: {e}"))
341 });
342 assert!(result.unwrap_err().contains("write goals"));
343 }
344 #[test]
345 fn round3_goal_persistence_failure_is_error() {
346 let result =
347 complete_goal_with("active", manifest(), |_| Err("storage unavailable".into()));
348 assert!(result.unwrap_err().contains("storage unavailable"));
349 }
350 #[test]
351 fn round3_milestone_persistence_success() {
352 let scratch = tempfile::tempdir().unwrap();
353 let path = scratch.path().join("goals.json");
354 complete_milestone_with("active", 7, manifest(), |m| {
355 std::fs::write(&path, serde_json::to_vec(m).unwrap())
356 .map(|_| path.clone())
357 .map_err(|e| e.to_string())
358 })
359 .unwrap();
360 let saved: GoalManifest = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
361 assert!(saved.goals[0].milestones[0].completed);
362 assert_eq!(saved.goals[0].status, GoalStatus::Completed);
363 }
364
365 fn collision_manifest() -> GoalManifest {
366 let mut manifest = manifest();
367 let mut goal_a = manifest.goals.remove(0);
368 goal_a.id = "goal-A".into();
369 goal_a.title = "Support goal-B".into();
370 goal_a.milestones[0].id = 1;
371 let mut goal_b = goal_a.clone();
372 goal_b.id = "goal-B".into();
373 goal_b.title = "Actual task".into();
374 manifest.goals = vec![goal_a, goal_b];
375 manifest
376 }
377
378 #[test]
379 fn round4_exact_goal_resolution_precedes_title() {
380 let manifest = collision_manifest();
381 assert_eq!(goal_index(&manifest.goals, "goal-B"), Some(1));
382 assert_eq!(goal_index(&manifest.goals, "Actual task"), Some(1));
383 assert_eq!(goal_index(&manifest.goals, "ACTUAL"), Some(1));
384 assert_eq!(goal_index(&manifest.goals, "Support"), Some(0));
385 assert_eq!(goal_index(&manifest.goals, "missing"), None);
386 }
387
388 fn persisted_dispatch_collision(test_name: &str, actions: &[&str]) {
389 const CHILD_ACTION: &str = "AIEN_TEST_ROUND4_GOAL_DISPATCH_ACTION";
390 if let Ok(action) = std::env::var(CHILD_ACTION) {
391 assert!(actions.contains(&action.as_str()));
392 let before = load_goals();
393 // This is the same resolver used by autonomous mode. Resolving
394 // the title selects goal-B; its id must stay authoritative when
395 // the real tool dispatcher persists the completion.
396 let selected = goal_index(&before.goals, "Actual task").unwrap();
397 let id = &before.goals[selected].id;
398 assert_eq!(id, "goal-B");
399 let result = goals_dispatch_tool(&json!({
400 "action": action, "id": id, "milestone_id": 1,
401 }));
402 assert_eq!(result["status"], "ok", "{result}");
403 let saved: GoalManifest =
404 serde_json::from_slice(&fs::read(".goals.json").unwrap()).unwrap();
405 assert!(
406 saved.goals[1].milestones[0].completed,
407 "{action}: goal-B not persisted"
408 );
409 assert_eq!(saved.goals[1].status, GoalStatus::Completed);
410 assert_eq!(
411 serde_json::to_value(&saved.goals[0]).unwrap(),
412 serde_json::to_value(&before.goals[0]).unwrap(),
413 "{action}: unrelated goal-A changed",
414 );
415 return;
416 }
417 for action in actions {
418 let scratch = tempfile::tempdir().unwrap();
419 fs::write(
420 scratch.path().join(".goals.json"),
421 serde_json::to_vec(&collision_manifest()).unwrap(),
422 )
423 .unwrap();
424 // Isolate the real path resolver and writer without changing the
425 // unit-test process's cwd or using synthetic dispatch success.
426 let output = std::process::Command::new(std::env::current_exe().unwrap())
427 .current_dir(scratch.path())
428 .env(CHILD_ACTION, action)
429 .args(["--exact", test_name, "--nocapture"])
430 .output()
431 .unwrap();
432 assert!(
433 output.status.success(),
434 "{action}: child failed ({:?})\n{}\n{}",
435 output.status.code(),
436 String::from_utf8_lossy(&output.stdout),
437 String::from_utf8_lossy(&output.stderr),
438 );
439 }
440 }
441
442 #[test]
443 fn round4_milestone_dispatch_persists_exact_goal() {
444 persisted_dispatch_collision(
445 "goals::completion_tests::round4_milestone_dispatch_persists_exact_goal",
446 &["milestone_done", "advance"],
447 );
448 }
449
450 #[test]
451 fn round4_goal_dispatch_persists_exact_goal() {
452 persisted_dispatch_collision(
453 "goals::completion_tests::round4_goal_dispatch_persists_exact_goal",
454 &["done", "complete"],
455 );
456 }
457}