Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions atomic-cli/src/commands/vault/intent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//! list List intents
//! show Show an intent's content
//! update Update an intent's fields
//! delete Delete an unstarted backlog intent
//! link Link a goal to an intent
//! ```
//!
Expand All @@ -37,6 +38,10 @@
//! # Update intent status
//! atomic vault intent update PIMO-1 --status in-progress
//!
//! # Delete an accidental draft intent
//! atomic vault intent delete PIMO-1
//! atomic vault intent delete PIMO-1 --force
//!
//! # Link a goal to an intent
//! atomic vault intent link PIMO-1 --goal swift-meadow-a3f2
//! ```
Expand Down Expand Up @@ -119,6 +124,20 @@ pub enum IntentCommands {
/// ```
Update(IntentUpdate),

/// Delete an unstarted backlog intent.
///
/// Removes an accidental draft intent from the vault. Only backlog
/// intents with no linked goals can be deleted. Use --force to skip the
/// confirmation prompt.
///
/// # Examples
///
/// ```text
/// atomic vault intent delete PIMO-1
/// atomic vault intent delete PIMO-1 --force
/// ```
Delete(IntentDelete),

/// Link a goal to an intent.
///
/// Associates a goal with an intent so that the work done in the goal
Expand Down Expand Up @@ -152,6 +171,7 @@ impl Command for Intent {
IntentCommands::List(cmd) => cmd.run(),
IntentCommands::Show(cmd) => cmd.run(),
IntentCommands::Update(cmd) => cmd.run(),
IntentCommands::Delete(cmd) => cmd.run(),
IntentCommands::Link(cmd) => cmd.run(),
}
}
Expand Down Expand Up @@ -380,6 +400,69 @@ impl Command for IntentUpdate {
}
}

// Delete Subcommand

/// Delete an unstarted backlog intent.
///
/// Removes an intent that has not left backlog and has no linked goals. Use this
/// for accidental drafts only; started work should be closed or superseded
/// instead of deleted. Without `--force`, prompts for confirmation.
#[derive(Parser, Debug)]
#[command(name = "delete")]
pub struct IntentDelete {
/// Intent ID.
pub id: String,

/// Skip the confirmation prompt.
#[arg(long, short = 'f')]
pub force: bool,

/// Output as JSON.
#[arg(long)]
pub json: bool,
}

impl Command for IntentDelete {
fn run(&self) -> CliResult<()> {
let root = find_repository_root()?;
let repo = Repository::open(&root).map_err(CliError::Repository)?;

if !self.force {
let prompt = format!(
"Discard intent '{}'? This removes the unstarted draft from the vault.",
self.id
);
let confirmed = dialoguer::Confirm::new()
.with_prompt(&prompt)
.default(false)
.interact()
.map_err(|e| CliError::Internal(anyhow::anyhow!("Prompt failed: {}", e)))?;

if !confirmed {
return Err(CliError::Cancelled);
}
}

let result = repo
.vault_intent_delete(&self.id)
.map_err(CliError::Repository)?;

if self.json {
let json = serde_json::json!({
"id": result.id,
"intent_file": result.intent_file,
"deleted": true,
});
println!("{}", serde_json::to_string_pretty(&json).unwrap());
} else {
println!("Deleted intent: {}", result.id);
println!(" file: .vault/{}", result.intent_file);
}

Ok(())
}
}

// Link Subcommand

/// Link a goal to an intent.
Expand Down
4 changes: 3 additions & 1 deletion atomic-repository/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ pub use repository::{
};

// Vault intent exports
pub use repository::{IntentCreateOptions, IntentCreateResult, IntentInfo, IntentUpdateOptions};
pub use repository::{
IntentCreateOptions, IntentCreateResult, IntentDeleteResult, IntentInfo, IntentUpdateOptions,
};

// Vault embedding exports
pub use repository::{hash_embed, EmbedConfig, TextChunk};
Expand Down
4 changes: 3 additions & 1 deletion atomic-repository/src/repository/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ pub use vault_goal::{
GoalInfo, GoalStartOptions, GoalStartResult, GoalStopOptions, GoalStopResult,
};
pub use vault_identity::VaultIdentity;
pub use vault_intent::{IntentCreateOptions, IntentCreateResult, IntentInfo, IntentUpdateOptions};
pub use vault_intent::{
IntentCreateOptions, IntentCreateResult, IntentDeleteResult, IntentInfo, IntentUpdateOptions,
};
pub use vault_kg_enrich::KgEnrichStats;
pub use vault_names::{derive_intent_prefix, generate_goal_name};

Expand Down
220 changes: 220 additions & 0 deletions atomic-repository/src/repository/vault_intent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const INTENT_TEMPLATE: &str = include_str!("../../vault/templates/intent.md");
use super::*;
use atomic_core::pristine::vault::{IntentSummary, VaultEntry, VaultEntryType, VaultManifest};
use atomic_core::pristine::{VaultMutTxnT, VaultTxnT};
use std::fs;

/// Options for creating a new intent.
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -49,6 +50,15 @@ pub struct IntentCreateResult {
pub view_name: String,
}

/// Result of deleting an intent.
#[derive(Debug, Clone)]
pub struct IntentDeleteResult {
/// The normalized intent ID that was deleted.
pub id: String,
/// Vault-relative path to the removed intent.md file.
pub intent_file: String,
}

/// Options for updating an intent.
#[derive(Debug, Clone, Default)]
pub struct IntentUpdateOptions {
Expand Down Expand Up @@ -302,6 +312,99 @@ impl Repository {
})
}

/// Delete an unstarted backlog intent.
///
/// This is intentionally conservative: only backlog intents with no linked
/// goals can be deleted. Started work should be closed or superseded
/// instead of removed from the vault.
pub fn vault_intent_delete(
&self,
intent_id: &str,
) -> Result<IntentDeleteResult, RepositoryError> {
let full_id = self.normalize_intent_id(intent_id)?;
let intent_file =
self.find_intent_path(&full_id)?
.ok_or_else(|| RepositoryError::InvalidOperation {
message: format!("Intent '{}' not found", full_id),
})?;

let manifest = self.vault_manifest()?;
let summary =
manifest
.intents
.get(&full_id)
.ok_or_else(|| RepositoryError::InvalidOperation {
message: format!("Intent '{}' not found", full_id),
})?;

if summary.status != "backlog" {
return Err(RepositoryError::InvalidOperation {
message: format!(
"Intent '{}' has status '{}'; only backlog intents can be deleted",
full_id, summary.status
),
});
}

let referenced_goals = manifest
.goals
.values()
.filter(|goal| {
goal.intent
.as_deref()
.is_some_and(|id| id.eq_ignore_ascii_case(&full_id))
})
.count() as u32;
let linked_goals = summary.goals.max(referenced_goals);

if linked_goals > 0 {
return Err(RepositoryError::InvalidOperation {
message: format!(
"Intent '{}' is linked to {} goal(s); unlink or close the work instead",
full_id, linked_goals
),
});
}

let deleted = self.vault_delete(&intent_file)?;
if !deleted {
return Err(RepositoryError::InvalidOperation {
message: format!("Intent '{}' not found", full_id),
});
}

{
let mut txn = self
.pristine
.write_txn()
.map_err(|e| RepositoryError::Database(e.to_string()))?;
let mut manifest = txn
.get_vault_manifest()
.map_err(|e| RepositoryError::Database(e.to_string()))?;
manifest.intents.remove(&full_id);
txn.put_vault_manifest(&manifest)
.map_err(|e| RepositoryError::Database(e.to_string()))?;
txn.commit()
.map_err(|e| RepositoryError::Database(e.to_string()))?;
}

let materialized = self.vault_dir().join(&intent_file);
match fs::remove_file(&materialized) {
Ok(()) => {
if let Some(parent) = materialized.parent() {
let _ = remove_empty_dirs_up_to(parent, &self.vault_dir().join("intents"));
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(RepositoryError::Io(e)),
}

Ok(IntentDeleteResult {
id: full_id,
intent_file,
})
}

/// Update an intent's fields.
pub fn vault_intent_update(
&self,
Expand Down Expand Up @@ -576,6 +679,33 @@ impl Repository {
}
}

fn remove_empty_dirs_up_to(
mut dir: &std::path::Path,
stop_at: &std::path::Path,
) -> Result<(), std::io::Error> {
while dir.starts_with(stop_at) && dir != stop_at {
match fs::remove_dir(dir) {
Ok(()) => {
if let Some(parent) = dir.parent() {
dir = parent;
} else {
break;
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
if let Some(parent) = dir.parent() {
dir = parent;
} else {
break;
}
}
Err(e) if e.kind() == std::io::ErrorKind::DirectoryNotEmpty => break,
Err(e) => return Err(e),
}
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -774,6 +904,96 @@ mod tests {
assert_eq!(manifest.intents[&result.id].status, "in-progress");
}

#[test]
fn test_intent_delete_backlog_removes_manifest_entry_and_file() {
let dir = tempdir().unwrap();
let repo = init_repo_with_vault(dir.path());

let result = repo.vault_intent_create(create_opts("Delete me")).unwrap();
let materialized = repo.vault_dir().join(&result.intent_file);
assert!(materialized.exists());

let deleted = repo.vault_intent_delete(&result.id).unwrap();
assert_eq!(deleted.id, result.id);
assert_eq!(deleted.intent_file, result.intent_file);

let manifest = repo.vault_manifest().unwrap();
assert!(!manifest.intents.contains_key(&result.id));
assert!(repo.vault_retrieve(&result.intent_file).unwrap().is_none());
assert!(!materialized.exists());
}

#[test]
fn test_intent_delete_rejects_non_backlog_intent() {
let dir = tempdir().unwrap();
let repo = init_repo_with_vault(dir.path());

let result = repo.vault_intent_create(create_opts("Started")).unwrap();
repo.vault_intent_update(
&result.id,
IntentUpdateOptions {
status: Some("in-progress".to_string()),
..Default::default()
},
)
.unwrap();

let err = repo.vault_intent_delete(&result.id).unwrap_err();
assert!(err
.to_string()
.contains("only backlog intents can be deleted"));
assert!(repo.vault_retrieve(&result.intent_file).unwrap().is_some());
}

#[test]
fn test_intent_delete_rejects_linked_goal() {
let dir = tempdir().unwrap();
let repo = init_repo_with_vault(dir.path());

let intent = repo.vault_intent_create(create_opts("Linked")).unwrap();
repo.vault_store(
"goals/test-goal/_goal.md",
VaultEntryType::Session,
b"# Goal".to_vec(),
r#"{"goal_id":"test-goal","status":"active"}"#.to_string(),
)
.unwrap();
repo.vault_intent_link(&intent.id, "test-goal").unwrap();

let err = repo.vault_intent_delete(&intent.id).unwrap_err();
assert!(err.to_string().contains("linked to 1 goal"));
assert!(repo.vault_retrieve(&intent.intent_file).unwrap().is_some());
}

#[test]
fn test_intent_delete_rejects_goal_started_with_intent() {
let dir = tempdir().unwrap();
let repo = init_repo_with_vault(dir.path());

let intent = repo
.vault_intent_create(create_opts("Started from goal"))
.unwrap();
repo.vault_goal_start(GoalStartOptions {
name: Some("test-goal".to_string()),
intent: Some(intent.id.clone()),
..Default::default()
})
.unwrap();

// Goal start stores the canonical relationship on the goal summary.
// Deletion must not rely only on the intent's cached goal count.
let manifest = repo.vault_manifest().unwrap();
assert_eq!(manifest.intents[&intent.id].goals, 0);
assert_eq!(
manifest.goals["test-goal"].intent.as_deref(),
Some(intent.id.as_str())
);

let err = repo.vault_intent_delete(&intent.id).unwrap_err();
assert!(err.to_string().contains("linked to 1 goal"));
assert!(repo.vault_retrieve(&intent.intent_file).unwrap().is_some());
}

#[test]
fn test_intent_link_goal() {
let dir = tempdir().unwrap();
Expand Down