Skip to main content

sqlite_graphrag/commands/
reclassify.rs

1//! Handler for the `reclassify` CLI subcommand (GAP-18).
2//!
3//! Reclassifies one entity (single mode) or a whole group of entities (batch
4//! mode) by updating the `type` column in the `entities` table.
5//!
6//! Single mode: `--name <entity>` changes the type of one entity.
7//! Batch mode: `--from-type <old> --to-type <new> --batch` changes every
8//! entity in the namespace that currently has `<old>` as its type.
9
10use crate::entity_type::EntityType;
11use crate::errors::AppError;
12use crate::i18n::errors_msg;
13use crate::output::{self, OutputFormat};
14use crate::paths::AppPaths;
15use crate::storage::connection::open_rw;
16use crate::storage::entities;
17use rusqlite::params;
18use serde::Serialize;
19
20#[derive(clap::Args)]
21#[command(after_long_help = "EXAMPLES:\n  \
22    # Reclassify a single entity from its current type to 'tool'\n  \
23    sqlite-graphrag reclassify --name tokio-runtime --new-type tool\n\n  \
24    # Reclassify all 'concept' entities to 'tool' in one shot (batch)\n  \
25    sqlite-graphrag reclassify --from-type concept --to-type tool --batch\n\n  \
26    # Reclassify in a specific namespace\n  \
27    sqlite-graphrag reclassify --name alice --new-type person --namespace my-project\n\n\
28NOTE:\n  \
29    Single mode requires --name and --new-type.\n  \
30    Batch mode requires --from-type, --to-type and --batch.\n  \
31    Providing --name together with --batch is an error.\n\n\
32VALID ENTITY TYPES:\n  \
33    project, tool, person, file, concept, incident, decision,\n  \
34    memory, dashboard, issue_tracker, organization, location, date")]
35pub struct ReclassifyArgs {
36    /// Entity name to reclassify (single mode). Mutually exclusive with --from-type + --batch.
37    #[arg(long, conflicts_with_all = ["from_type", "batch"])]
38    pub name: Option<String>,
39    /// New entity type for single mode.
40    #[arg(long, value_enum, value_name = "TYPE")]
41    pub new_type: Option<EntityType>,
42    /// New description for the entity (single mode only). Ignored in batch mode.
43    #[arg(long, value_name = "TEXT")]
44    pub description: Option<String>,
45    /// Current entity type to match in batch mode. Requires --to-type and --batch.
46    #[arg(
47        long,
48        value_enum,
49        value_name = "TYPE",
50        requires = "to_type",
51        requires = "batch"
52    )]
53    pub from_type: Option<EntityType>,
54    /// New entity type to assign in batch mode. Requires --from-type and --batch.
55    #[arg(long, value_enum, value_name = "TYPE", requires = "from_type")]
56    pub to_type: Option<EntityType>,
57    /// Enable batch reclassification (--from-type to --to-type). Requires --from-type and --to-type.
58    #[arg(long, default_value_t = false, requires = "from_type")]
59    pub batch: bool,
60    #[arg(long)]
61    pub namespace: Option<String>,
62    #[arg(long, value_enum, default_value = "json")]
63    pub format: OutputFormat,
64    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
65    pub json: bool,
66    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
67    pub db: Option<String>,
68}
69
70#[derive(Serialize)]
71struct ReclassifyResponse {
72    action: String,
73    count: usize,
74    namespace: String,
75    /// Total execution time in milliseconds from handler start to serialisation.
76    elapsed_ms: u64,
77}
78
79pub fn run(args: ReclassifyArgs) -> Result<(), AppError> {
80    let inicio = std::time::Instant::now();
81    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
82    let paths = AppPaths::resolve(args.db.as_deref())?;
83
84    crate::storage::connection::ensure_db_ready(&paths)?;
85
86    let mut conn = open_rw(&paths.db)?;
87
88    let count = if args.batch {
89        // Batch mode: --from-type + --to-type + --batch
90        let from_type = args.from_type.ok_or_else(|| {
91            AppError::Validation("--from-type is required in batch mode".to_string())
92        })?;
93        let to_type = args.to_type.ok_or_else(|| {
94            AppError::Validation("--to-type is required in batch mode".to_string())
95        })?;
96
97        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
98        let affected = tx.execute(
99            "UPDATE entities SET type = ?1, updated_at = unixepoch()
100             WHERE type = ?2 AND namespace = ?3",
101            params![to_type.as_str(), from_type.as_str(), namespace],
102        )?;
103        tx.commit()?;
104        if affected == 0 {
105            tracing::warn!(
106                from_type = from_type.as_str(),
107                namespace = %namespace,
108                "reclassify batch matched zero entities — verify --from-type value exists"
109            );
110        }
111        affected
112    } else {
113        // Single mode: --name + --new-type
114        let entity_name = args
115            .name
116            .as_deref()
117            .ok_or_else(|| AppError::Validation("--name is required in single mode".to_string()))?;
118        let new_type = args.new_type.ok_or_else(|| {
119            AppError::Validation("--new-type is required in single mode".to_string())
120        })?;
121
122        // Verify entity exists.
123        entities::find_entity_id(&conn, &namespace, entity_name)?.ok_or_else(|| {
124            AppError::NotFound(errors_msg::entity_not_found(entity_name, &namespace))
125        })?;
126
127        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
128        let affected = tx.execute(
129            "UPDATE entities SET type = ?1, updated_at = unixepoch()
130             WHERE name = ?2 AND namespace = ?3",
131            params![new_type.as_str(), entity_name, namespace],
132        )?;
133        if let Some(ref desc) = args.description {
134            tx.execute(
135                "UPDATE entities SET description = ?1, updated_at = unixepoch()
136                 WHERE name = ?2 AND namespace = ?3",
137                params![desc, entity_name, namespace],
138            )?;
139        }
140        tx.commit()?;
141        affected
142    };
143
144    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
145
146    let response = ReclassifyResponse {
147        action: "reclassified".to_string(),
148        count,
149        namespace: namespace.clone(),
150        elapsed_ms: inicio.elapsed().as_millis() as u64,
151    };
152
153    match args.format {
154        OutputFormat::Json => output::emit_json(&response)?,
155        OutputFormat::Text | OutputFormat::Markdown => {
156            output::emit_text(&format!(
157                "reclassified: {} entities [{}]",
158                response.count, response.namespace
159            ));
160        }
161    }
162
163    Ok(())
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn reclassify_response_serializes_all_fields() {
172        let resp = ReclassifyResponse {
173            action: "reclassified".to_string(),
174            count: 5,
175            namespace: "global".to_string(),
176            elapsed_ms: 12,
177        };
178        let json = serde_json::to_value(&resp).expect("serialization failed");
179        assert_eq!(json["action"], "reclassified");
180        assert_eq!(json["count"], 5);
181        assert_eq!(json["namespace"], "global");
182        assert!(json["elapsed_ms"].is_number());
183    }
184
185    #[test]
186    fn reclassify_response_count_zero_is_valid() {
187        let resp = ReclassifyResponse {
188            action: "reclassified".to_string(),
189            count: 0,
190            namespace: "my-project".to_string(),
191            elapsed_ms: 3,
192        };
193        let json = serde_json::to_value(&resp).expect("serialization failed");
194        assert_eq!(json["count"], 0);
195        assert_eq!(json["action"], "reclassified");
196    }
197
198    #[test]
199    fn reclassify_response_action_is_reclassified() {
200        let resp = ReclassifyResponse {
201            action: "reclassified".to_string(),
202            count: 1,
203            namespace: "ns".to_string(),
204            elapsed_ms: 1,
205        };
206        assert_eq!(resp.action, "reclassified");
207    }
208}