diff --git a/crates/context-cli/tests/mcp_notes.rs b/crates/context-cli/tests/mcp_notes.rs index 88ac85ef..ed82fada 100644 --- a/crates/context-cli/tests/mcp_notes.rs +++ b/crates/context-cli/tests/mcp_notes.rs @@ -34,7 +34,6 @@ async fn test_note_list_empty() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -314,7 +313,6 @@ async fn test_note_list_with_data() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -329,6 +327,10 @@ async fn test_note_list_with_data() { }; let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); assert_eq!(response["total"], 1); + assert_eq!( + response["items"][0]["content"], "", + "list results must project to metadata" + ); } #[tokio::test(flavor = "multi_thread")] @@ -361,7 +363,6 @@ async fn test_note_list_search() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -376,6 +377,10 @@ async fn test_note_list_search() { }; let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); assert_eq!(response["total"], 1); + assert_eq!( + response["items"][0]["content"], "", + "search results must project to metadata" + ); } #[tokio::test(flavor = "multi_thread")] @@ -410,7 +415,6 @@ async fn test_note_list_pagination() { note_type: None, limit: Some(1), offset: None, - include_content: None, sort: None, order: None, }; @@ -458,7 +462,6 @@ async fn test_note_list_tag_filter() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -521,7 +524,6 @@ async fn test_note_list_with_project_id_filter() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -584,7 +586,6 @@ async fn test_note_list_with_parent_id_filter() { note_type: None, limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -648,7 +649,6 @@ async fn test_note_list_with_note_type_filter() { note_type: Some("task".to_string()), limit: None, offset: None, - include_content: None, sort: None, order: None, }; @@ -693,7 +693,6 @@ async fn test_note_list_sorting() { note_type: None, limit: None, offset: None, - include_content: None, sort: Some("title".to_string()), order: Some("asc".to_string()), }; diff --git a/crates/context-cli/tests/mcp_skills.rs b/crates/context-cli/tests/mcp_skills.rs index 3ecebe6c..91ed0533 100644 --- a/crates/context-cli/tests/mcp_skills.rs +++ b/crates/context-cli/tests/mcp_skills.rs @@ -682,3 +682,110 @@ async fn test_skill_update_invalidates_cache() { // Cleanup - TempDir removes itself on drop let _ = skills_dir; } + +#[tokio::test(flavor = "multi_thread")] +async fn test_skill_list_omits_content_by_default() { + let db = setup_db().await; + let skill = Skill { + id: "skill001".to_string(), + name: "test-skill".to_string(), + description: "A test skill".to_string(), + content: "---\nname: test-skill\n---\n# Test\n\nTest content".to_string(), + tags: vec!["test".to_string()], + project_ids: vec![], + scripts: vec![], + references: vec![], + assets: vec![], + created_at: Some("2025-01-01 00:00:00".to_string()), + updated_at: Some("2025-01-01 00:00:00".to_string()), + deleted_at: None, + source: None, + source_subpath: None, + }; + db.skills().create(&skill).await.unwrap(); + let db = Arc::new(db); + let tools = SkillTools::new( + db.clone(), + ChangeNotifier::new(), + get_data_dir().join("skills"), + ); + + let params = ListSkillsParams { + query: None, + tags: None, + project_id: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let result = tools.skill_list(Parameters(params)).await; + assert!(result.is_ok()); + + let call_result = result.unwrap(); + let content_text = match &call_result.content[0] { + ContentBlock::Text(text) => text.text.as_str(), + _ => panic!("Expected text content"), + }; + let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); + assert_eq!(response["total"], 1); + assert_eq!( + response["items"][0]["content"], "", + "skill_list without include_content must omit content" + ); + assert_eq!(response["items"][0]["name"], "test-skill"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_skill_list_search_returns_metadata_only() { + let db = setup_db().await; + let skill = Skill { + id: "skill001".to_string(), + name: "test-skill".to_string(), + description: "A test skill".to_string(), + content: "---\nname: test-skill\n---\n# Test\n\nTest content".to_string(), + tags: vec!["test".to_string()], + project_ids: vec![], + scripts: vec![], + references: vec![], + assets: vec![], + created_at: Some("2025-01-01 00:00:00".to_string()), + updated_at: Some("2025-01-01 00:00:00".to_string()), + deleted_at: None, + source: None, + source_subpath: None, + }; + db.skills().create(&skill).await.unwrap(); + let db = Arc::new(db); + let tools = SkillTools::new( + db.clone(), + ChangeNotifier::new(), + get_data_dir().join("skills"), + ); + + let params = ListSkillsParams { + query: Some("Test content".to_string()), + tags: None, + project_id: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let result = tools.skill_list(Parameters(params)).await; + assert!(result.is_ok()); + + let call_result = result.unwrap(); + let content_text = match &call_result.content[0] { + ContentBlock::Text(text) => text.text.as_str(), + _ => panic!("Expected text content"), + }; + let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); + assert_eq!(response["total"], 1); + assert_eq!( + response["items"][0]["content"], "", + "search results must project to metadata" + ); +} diff --git a/crates/context-cli/tests/mcp_task_lists.rs b/crates/context-cli/tests/mcp_task_lists.rs index 07ca200b..21531e38 100644 --- a/crates/context-cli/tests/mcp_task_lists.rs +++ b/crates/context-cli/tests/mcp_task_lists.rs @@ -392,6 +392,127 @@ async fn test_task_list_list_with_data() { assert_eq!(response["total"], 1); } +const LIST_NOTES: &str = "## Context\n\nThis container note block is deliberately longer than one line so that a null response field is easy to distinguish from the stored value.\n\n## Decisions\n\nKeep the notes out of list payloads."; + +fn make_list_with_notes(id: &str, project_id: &str) -> TaskList { + TaskList { + id: id.to_string(), + title: "Notes List".to_string(), + description: Some("Short description".to_string()), + tags: vec![], + external_refs: vec![], + status: TaskListStatus::Active, + notes: Some(LIST_NOTES.to_string()), + repo_ids: vec![], + project_id: project_id.to_string(), + created_at: Some("2025-01-01 00:00:00".to_string()), + updated_at: Some("2025-01-01 00:00:00".to_string()), + archived_at: None, + deleted_at: None, + } +} + +fn tool_json(result: CallToolResult) -> serde_json::Value { + let content_text = match &result.content[0] { + ContentBlock::Text(text) => text.text.as_str(), + _ => panic!("Expected text content"), + }; + serde_json::from_str(content_text).unwrap() +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_task_list_list_omits_notes() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + db.task_lists() + .create(&make_list_with_notes("list0001", &project_id)) + .await + .unwrap(); + let db = Arc::new(db); + let tools = TaskListTools::new(db.clone(), ChangeNotifier::new()); + + let params = ListTaskListsParams { + query: None, + tags: None, + status: None, + project_id: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let response = tool_json(tools.task_list_list(Parameters(params)).await.unwrap()); + + assert_eq!(response["total"], 1); + assert!( + response["items"][0]["notes"].is_null(), + "task_list_list must omit notes, got: {}", + response["items"][0]["notes"] + ); + assert_eq!( + response["items"][0]["description"], "Short description", + "description stays in list responses" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_task_list_list_search_omits_notes() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + let mut list = make_list_with_notes("list0001", &project_id); + list.title = "Rust Container".to_string(); + db.task_lists().create(&list).await.unwrap(); + let db = Arc::new(db); + let tools = TaskListTools::new(db.clone(), ChangeNotifier::new()); + + let params = ListTaskListsParams { + query: Some("rust".to_string()), + tags: None, + status: None, + project_id: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let response = tool_json(tools.task_list_list(Parameters(params)).await.unwrap()); + + assert_eq!(response["total"], 1); + assert!( + response["items"][0]["notes"].is_null(), + "search results must omit notes, got: {}", + response["items"][0]["notes"] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_task_list_get_returns_notes() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + db.task_lists() + .create(&make_list_with_notes("list0001", &project_id)) + .await + .unwrap(); + let db = Arc::new(db); + let tools = TaskListTools::new(db.clone(), ChangeNotifier::new()); + + let response = tool_json( + tools + .task_list_get(Parameters(GetTaskListParams { + id: "list0001".to_string(), + })) + .await + .unwrap(), + ); + + assert_eq!( + response["notes"], LIST_NOTES, + "single-entity get must keep the stored notes" + ); +} + #[tokio::test(flavor = "multi_thread")] async fn test_task_list_list_pagination() { let db = setup_db().await; diff --git a/crates/context-cli/tests/mcp_tasks.rs b/crates/context-cli/tests/mcp_tasks.rs index b1c8515b..6eebb843 100644 --- a/crates/context-cli/tests/mcp_tasks.rs +++ b/crates/context-cli/tests/mcp_tasks.rs @@ -16,7 +16,7 @@ use context_server::mcp::tools::tasks::{ TransitionTaskParams, UpdateTaskParams, }; use rmcp::handler::server::wrapper::Parameters; -use rmcp::model::ContentBlock; +use rmcp::model::{ContentBlock, ErrorCode}; use std::sync::Arc; async fn setup_db() -> SqliteDatabase { @@ -144,6 +144,43 @@ async fn test_task_create_empty_title() { assert!(result.is_err()); } +#[tokio::test(flavor = "multi_thread")] +async fn test_task_create_description_over_limit() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + let list_id = create_test_task_list(&db, &project_id).await; + let db = Arc::new(db); + let tools = TaskTools::new(db.clone(), ChangeNotifier::new()); + + let params = CreateTaskParams { + list_id: list_id.clone(), + title: "Over-limit description".to_string(), + description: Some("x".repeat(context_core::TASK_DESCRIPTION_MAX + 1)), + priority: None, + tags: None, + parent_id: None, + external_refs: None, + }; + + let error = tools + .task_create(Parameters(params)) + .await + .expect_err("task_create should reject an over-limit description"); + + assert_eq!( + error.code, + ErrorCode::INVALID_PARAMS, + "over-limit description should be reported as invalid_params" + ); + assert!( + error.data.as_ref().is_some_and(|data| data["message"] + .as_str() + .is_some_and(|message| message.contains("maximum size"))), + "error data should mention maximum size, got: {:?}", + error.data + ); +} + #[tokio::test(flavor = "multi_thread")] async fn test_task_get() { let db = setup_db().await; @@ -855,3 +892,109 @@ async fn test_task_list_tag_filter() { let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); assert_eq!(response["total"], 1); } + +#[tokio::test(flavor = "multi_thread")] +async fn test_task_list_omits_description_by_default() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + let list_id = create_test_task_list(&db, &project_id).await; + let task = Task { + id: "task0001".to_string(), + list_id: list_id.clone(), + title: "Task with a description".to_string(), + description: Some("A detailed specification that list results omit".to_string()), + status: TaskStatus::Todo, + priority: Some(3), + tags: vec![], + external_refs: vec![], + parent_id: None, + created_at: Some("2025-01-01 00:00:00".to_string()), + updated_at: Some("2025-01-01 00:00:00".to_string()), + deleted_at: None, + }; + db.tasks().create(&task).await.unwrap(); + let db = Arc::new(db); + let tools = TaskTools::new(db.clone(), ChangeNotifier::new()); + + let params = ListTasksParams { + list_id: list_id.clone(), + query: None, + status: None, + tags: None, + parent_id: None, + task_type: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let result = tools.task_list(Parameters(params)).await; + assert!(result.is_ok()); + + let call_result = result.unwrap(); + let content_text = match &call_result.content[0] { + ContentBlock::Text(text) => text.text.as_str(), + _ => panic!("Expected text content"), + }; + let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); + assert_eq!(response["total"], 1); + assert!( + response["items"][0]["description"].is_null(), + "task_list must omit descriptions, got: {}", + response["items"][0]["description"] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_task_list_search_returns_metadata_only() { + let db = setup_db().await; + let project_id = create_test_project(&db).await; + let list_id = create_test_task_list(&db, &project_id).await; + let task = Task { + id: "task0001".to_string(), + list_id: list_id.clone(), + title: "Rust Backend".to_string(), + description: Some("Machine learning research implementation".to_string()), + status: TaskStatus::Todo, + priority: Some(3), + tags: vec![], + external_refs: vec![], + parent_id: None, + created_at: Some("2025-01-01 00:00:00".to_string()), + updated_at: Some("2025-01-01 00:00:00".to_string()), + deleted_at: None, + }; + db.tasks().create(&task).await.unwrap(); + let db = Arc::new(db); + let tools = TaskTools::new(db.clone(), ChangeNotifier::new()); + + let params = ListTasksParams { + list_id: list_id.clone(), + query: Some("machine learning".to_string()), + status: None, + tags: None, + parent_id: None, + task_type: None, + limit: None, + offset: None, + sort: None, + order: None, + }; + + let result = tools.task_list(Parameters(params)).await; + assert!(result.is_ok()); + + let call_result = result.unwrap(); + let content_text = match &call_result.content[0] { + ContentBlock::Text(text) => text.text.as_str(), + _ => panic!("Expected text content"), + }; + let response: serde_json::Value = serde_json::from_str(content_text).unwrap(); + assert_eq!(response["total"], 1); + assert!( + response["items"][0]["description"].is_null(), + "search results must project to metadata, got: {}", + response["items"][0]["description"] + ); +} diff --git a/crates/context-core/src/models.rs b/crates/context-core/src/models.rs index 00118944..6acc14b3 100644 --- a/crates/context-core/src/models.rs +++ b/crates/context-core/src/models.rs @@ -21,6 +21,10 @@ pub const NOTE_SOFT_MAX: usize = 50_000; // ~12,500 tokens /// Notes exceeding this size will be rejected. pub const NOTE_HARD_MAX: usize = 100_000; // ~25,000 tokens +/// Hard maximum for task description size (characters). +/// Task descriptions exceeding this size will be rejected on create and update. +pub const TASK_DESCRIPTION_MAX: usize = 10_000; // ~2,500 tokens + // ============================================================================= // Skill Constants (Agent Skills Specification) // ============================================================================= diff --git a/crates/context-core/src/repository.rs b/crates/context-core/src/repository.rs index ff71e0ee..1dd6ef57 100644 --- a/crates/context-core/src/repository.rs +++ b/crates/context-core/src/repository.rs @@ -111,6 +111,14 @@ pub trait TaskRepository: Send + Sync { &self, query: Option<&TaskQuery>, ) -> impl Future>> + Send; + /// List tasks without their descriptions. + /// + /// Returns the same rows as [`TaskRepository::list`] with `description` + /// set to `None`. + fn list_metadata_only( + &self, + query: Option<&TaskQuery>, + ) -> impl Future>> + Send; fn count(&self) -> impl Future> + Send; fn count_deleted(&self) -> impl Future> + Send; fn search( @@ -206,6 +214,14 @@ pub trait SkillRepository: Send + Sync { &self, query: Option<&crate::SkillQuery>, ) -> impl Future>> + Send; + /// List skills without their `SKILL.md` content. + /// + /// Returns the same rows as [`SkillRepository::list`] with `content` set + /// to an empty string. + fn list_metadata_only( + &self, + query: Option<&crate::SkillQuery>, + ) -> impl Future>> + Send; fn count(&self) -> impl Future> + Send; fn count_deleted(&self) -> impl Future> + Send; fn update(&self, skill: &crate::Skill) -> impl Future> + Send; diff --git a/crates/context-db/src/skill.rs b/crates/context-db/src/skill.rs index 5f7691f1..e92766a1 100644 --- a/crates/context-db/src/skill.rs +++ b/crates/context-db/src/skill.rs @@ -19,6 +19,14 @@ const SKILL_COLS: &str = /// Standard column list for SELECT queries (with 's.' table alias) const SKILL_COLS_ALIASED: &str = "s.id, s.name, s.description, s.content, s.tags, s.created_at, s.updated_at, s.source, s.source_subpath"; +/// Column list for metadata-only SELECT queries (without the content blob) +const SKILL_METADATA_COLS: &str = + "id, name, description, tags, created_at, updated_at, source, source_subpath"; + +/// Column list for metadata-only SELECT queries (with 's.' table alias) +const SKILL_METADATA_COLS_ALIASED: &str = + "s.id, s.name, s.description, s.tags, s.created_at, s.updated_at, s.source, s.source_subpath"; + /// Parse a database row into a Skill struct (without project_ids) fn row_to_skill(row: &sqlx::sqlite::SqliteRow) -> Skill { let tags_json: String = row.get("tags"); @@ -42,6 +50,32 @@ fn row_to_skill(row: &sqlx::sqlite::SqliteRow) -> Skill { } } +/// Parse a metadata-only database row into a Skill struct. +/// +/// The `content` column is not selected by metadata-only queries, so +/// `row_to_skill` cannot be reused. +fn row_to_skill_metadata(row: &sqlx::sqlite::SqliteRow) -> Skill { + let tags_json: String = row.get("tags"); + let tags: Vec = serde_json::from_str(&tags_json).unwrap_or_default(); + + Skill { + id: row.get("id"), + name: row.get("name"), + description: row.get("description"), + content: String::new(), // metadata_only does not select content + tags, + project_ids: vec![], // Loaded separately via join table + scripts: vec![], // Loaded separately via skill_attachment table + references: vec![], // Loaded separately via skill_attachment table + assets: vec![], // Loaded separately via skill_attachment table + created_at: row.get("created_at"), + updated_at: row.get("updated_at"), + deleted_at: None, + source: row.get("source"), + source_subpath: row.get("source_subpath"), + } +} + /// Validates skill for database storage. /// /// Validation rules: @@ -314,6 +348,112 @@ impl<'a> SkillRepository for SqliteSkillRepository<'a> { }) } + async fn list_metadata_only(&self, query: Option<&SkillQuery>) -> DbResult> { + let default_query = SkillQuery::default(); + let query = query.unwrap_or(&default_query); + let allowed_fields = ["name", "created_at", "updated_at"]; + + let needs_json_each = query.tags.as_ref().is_some_and(|t| !t.is_empty()); + let needs_project_join = query.project_id.is_some(); + let mut bind_values: Vec = Vec::new(); + let mut where_conditions: Vec = Vec::new(); + let (select_cols, from_clause, order_field_prefix) = if needs_json_each + || needs_project_join + { + let mut from = "FROM skill s".to_string(); + if needs_project_join { + from.push_str("\nINNER JOIN project_skill ps ON s.id = ps.skill_id"); + where_conditions.push("ps.project_id = ?".to_string()); + bind_values.push(query.project_id.as_ref().unwrap().clone()); + } + if needs_json_each { + from.push_str(", json_each(s.tags)"); + let tags = query.tags.as_ref().unwrap(); + let placeholders: Vec<&str> = tags.iter().map(|_| "?").collect(); + where_conditions.push(format!("json_each.value IN ({})", placeholders.join(", "))); + bind_values.extend(tags.clone()); + } + ( + format!("DISTINCT {}", SKILL_METADATA_COLS_ALIASED), + from, + "s.", + ) + } else { + ( + SKILL_METADATA_COLS.to_string(), + "FROM skill".to_string(), + "", + ) + }; + // Soft-deleted rows are tombstones and must never appear in results. + where_conditions.push(format!("{}deleted_at IS NULL", order_field_prefix)); + let where_clause = if !where_conditions.is_empty() { + format!("WHERE {}", where_conditions.join(" AND ")) + } else { + String::new() + }; + let order_clause = { + let sort_field = query + .page + .sort_by + .as_deref() + .filter(|f| allowed_fields.contains(f)) + .unwrap_or("created_at"); + let sort_order = match query + .page + .sort_order + .unwrap_or(context_core::SortOrder::Asc) + { + context_core::SortOrder::Asc => "ASC", + context_core::SortOrder::Desc => "DESC", + }; + format!( + "ORDER BY {}{} {}", + order_field_prefix, sort_field, sort_order + ) + }; + let limit_clause = build_limit_offset_clause(&query.page); + let sql = format!( + "SELECT {} {} {} {} {}", + select_cols, from_clause, where_clause, order_clause, limit_clause + ); + let count_sql = if needs_json_each || needs_project_join { + format!( + "SELECT COUNT(DISTINCT s.id) {} {}", + from_clause, where_clause + ) + } else { + format!("SELECT COUNT(*) FROM skill {}", where_clause) + }; + let mut query_builder = sqlx::query(sqlx::AssertSqlSafe(sql.as_str())); + for value in &bind_values { + query_builder = query_builder.bind(value); + } + let rows = query_builder + .fetch_all(self.pool) + .await + .map_err(|e| DbError::Database { + message: e.to_string(), + })?; + let items: Vec = rows.iter().map(row_to_skill_metadata).collect(); + let mut count_query = sqlx::query_scalar(sqlx::AssertSqlSafe(count_sql.as_str())); + for value in &bind_values { + count_query = count_query.bind(value); + } + let total: i64 = count_query + .fetch_one(self.pool) + .await + .map_err(|e| DbError::Database { + message: e.to_string(), + })?; + Ok(ListResult { + items, + total: total as usize, + limit: query.page.limit, + offset: query.page.offset.unwrap_or(0), + }) + } + async fn count(&self) -> DbResult { let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM skill WHERE deleted_at IS NULL") .fetch_one(self.pool) diff --git a/crates/context-db/src/task.rs b/crates/context-db/src/task.rs index 29e936f0..551aeb43 100644 --- a/crates/context-db/src/task.rs +++ b/crates/context-db/src/task.rs @@ -9,7 +9,7 @@ use context_core::{ DbError, DbResult, ListResult, Task, TaskQuery, TaskRepository, TaskStats, TaskStatus, TransitionLog, }; -use context_core::{current_timestamp, generate_entity_id}; +use context_core::{TASK_DESCRIPTION_MAX, current_timestamp, generate_entity_id}; /// SQLx-backed task repository. pub struct SqliteTaskRepository<'a> { @@ -60,6 +60,18 @@ fn validate_task(task: &Task) -> DbResult<()> { errors.push(format!("Task priority must be 1-5, got {}", priority)); } + // Validate description size (bytes, matching the note size policy) + if let Some(description) = &task.description + && description.len() > TASK_DESCRIPTION_MAX + { + errors.push(format!( + "Task description exceeds maximum size of {} characters (got {} characters). \ + Reduce the description or move detail to notes.", + TASK_DESCRIPTION_MAX, + description.len() + )); + } + if errors.is_empty() { Ok(()) } else { @@ -358,6 +370,195 @@ impl<'a> TaskRepository for SqliteTaskRepository<'a> { }) } + async fn list_metadata_only(&self, query: Option<&TaskQuery>) -> DbResult> { + let default_query = TaskQuery::default(); + let query = query.unwrap_or(&default_query); + let allowed_fields = ["title", "status", "priority", "created_at", "updated_at"]; + + // Check if we need last_activity_at computed column + // - When sorting by updated_at, compute activity for proper ordering + // - Only relevant for parent tasks (task_type=task or not filtering by parent_id) + let is_sorting_by_updated = query.page.sort_by.as_deref() == Some("updated_at"); + let is_querying_parents = query.task_type.as_deref() == Some("task") + || (query.parent_id.is_none() && query.task_type.is_none()); + let needs_activity_column = is_sorting_by_updated && is_querying_parents; + + let order_clause = build_order_clause(&query.page, &allowed_fields, "created_at"); + let limit_clause = build_limit_offset_clause(&query.page); + + // Build filter conditions + let mut conditions: Vec = Vec::new(); + let mut bind_values: Vec = Vec::new(); + + // Soft-deleted rows are tombstones and must never appear in list results. + conditions.push("deleted_at IS NULL".to_string()); + + if let Some(list_id) = &query.list_id { + conditions.push("list_id = ?".to_string()); + bind_values.push(list_id.clone()); + } + + if let Some(parent_id) = &query.parent_id { + conditions.push("parent_id = ?".to_string()); + bind_values.push(parent_id.clone()); + } + + // Filter by task type: "task" (parent_id IS NULL) or "subtask" (parent_id IS NOT NULL) + if let Some(task_type) = &query.task_type { + match task_type.as_str() { + "task" => conditions.push("parent_id IS NULL".to_string()), + "subtask" => conditions.push("parent_id IS NOT NULL".to_string()), + _ => {} // Ignore invalid values + } + } + + if let Some(status) = &query.status { + // Handle multiple statuses (comma-separated OR logic) + let statuses: Vec<&str> = status.split(',').map(|s| s.trim()).collect(); + if statuses.len() == 1 { + conditions.push("status = ?".to_string()); + bind_values.push(status.clone()); + } else { + let placeholders: Vec<&str> = statuses.iter().map(|_| "?").collect(); + conditions.push(format!("status IN ({})", placeholders.join(", "))); + bind_values.extend(statuses.iter().map(|s| s.to_string())); + } + } + + // Tag filtering requires json_each join + let needs_json_each = query.tags.as_ref().is_some_and(|t| !t.is_empty()); + + if let Some(tags) = &query.tags + && !tags.is_empty() + { + let placeholders: Vec<&str> = tags.iter().map(|_| "?").collect(); + conditions.push(format!("json_each.value IN ({})", placeholders.join(", "))); + bind_values.extend(tags.clone()); + } + + let where_clause = if conditions.is_empty() { + String::new() + } else { + format!("WHERE {}", conditions.join(" AND ")) + }; + + // Build SQL based on whether we need json_each or activity column + let (sql, count_sql) = if needs_json_each { + let select_cols = if needs_activity_column { + "DISTINCT t.id, t.list_id, t.parent_id, t.title, t.status, t.priority, t.tags, t.external_refs, t.created_at, t.updated_at, \ + COALESCE((SELECT MAX(updated_at) FROM task WHERE parent_id = t.id AND deleted_at IS NULL), t.updated_at) AS last_activity_at" + } else { + "DISTINCT t.id, t.list_id, t.parent_id, t.title, t.status, t.priority, t.tags, t.external_refs, t.created_at, t.updated_at" + }; + + // Replace updated_at in ORDER BY with last_activity_at if we computed it + let order_clause_adjusted = if needs_activity_column { + order_clause.replace("updated_at", "last_activity_at") + } else { + order_clause.clone() + }; + + let sql = format!( + "SELECT {} + FROM task t, json_each(t.tags) + {} {} {}", + select_cols, where_clause, order_clause_adjusted, limit_clause + ); + let count_sql = format!( + "SELECT COUNT(DISTINCT t.id) FROM task t, json_each(t.tags) {}", + where_clause + ); + (sql, count_sql) + } else { + let select_cols = if needs_activity_column { + "task.id, task.list_id, task.parent_id, task.title, task.status, task.priority, task.tags, task.external_refs, task.created_at, task.updated_at, \ + COALESCE((SELECT MAX(updated_at) FROM task AS child WHERE child.parent_id = task.id AND child.deleted_at IS NULL), task.updated_at) AS last_activity_at" + } else { + "id, list_id, parent_id, title, status, priority, tags, external_refs, created_at, updated_at" + }; + + // Replace updated_at in ORDER BY with last_activity_at if we computed it + let order_clause_adjusted = if needs_activity_column { + order_clause.replace("updated_at", "last_activity_at") + } else { + order_clause.clone() + }; + + let sql = format!( + "SELECT {} + FROM task + {} {} {}", + select_cols, where_clause, order_clause_adjusted, limit_clause + ); + let count_sql = format!("SELECT COUNT(*) FROM task {}", where_clause); + (sql, count_sql) + }; + + // Get paginated results + let mut query_builder = sqlx::query(sqlx::AssertSqlSafe(sql.as_str())); + for value in &bind_values { + query_builder = query_builder.bind(value); + } + + let rows = query_builder + .fetch_all(self.pool) + .await + .map_err(|e| DbError::Database { + message: e.to_string(), + })?; + + let items: Vec = rows + .iter() + .map(|row| Task { + id: row.get("id"), + list_id: row.get("list_id"), + parent_id: row.get("parent_id"), + title: row.get("title"), + description: None, // metadata_only does not select descriptions + status: { + let status_str: String = row.get("status"); + TaskStatus::from_str(&status_str).unwrap_or_default() + }, + priority: row.get("priority"), + tags: { + let tags_json: Option = row.get("tags"); + tags_json + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() + }, + external_refs: { + let external_refs_json: Option = row.get("external_refs"); + external_refs_json + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() + }, + created_at: row.get("created_at"), + updated_at: row.get("updated_at"), + deleted_at: None, + }) + .collect(); + + // Get total count + let mut count_query = sqlx::query_scalar(sqlx::AssertSqlSafe(count_sql.as_str())); + for value in &bind_values { + count_query = count_query.bind(value); + } + + let total: i64 = count_query + .fetch_one(self.pool) + .await + .map_err(|e| DbError::Database { + message: e.to_string(), + })?; + + Ok(ListResult { + items, + total: total as usize, + limit: query.page.limit, + offset: query.page.offset.unwrap_or(0), + }) + } + async fn search( &self, search_term: &str, diff --git a/crates/context-db/test/skill.rs b/crates/context-db/test/skill.rs index ae29d6d3..ea0903e0 100644 --- a/crates/context-db/test/skill.rs +++ b/crates/context-db/test/skill.rs @@ -2,7 +2,9 @@ use crate::SqliteDatabase; use crate::helpers::{count_rows, read_deleted_at, read_updated_at}; -use context_core::{Database, HasSkills, Skill, SkillAttachment, SkillQuery, SkillRepository}; +use context_core::{ + Database, HasSkills, Skill, SkillAttachment, SkillQuery, SkillRepository, generate_entity_id, +}; async fn setup_db() -> SqliteDatabase { let db = SqliteDatabase::in_memory() @@ -1260,3 +1262,203 @@ async fn skill_update_replaces_source() { "update must replace source_subpath" ); } + +// ============================================================================= +// Metadata-only listing tests +// ============================================================================= + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_returns_empty_content() { + let db = setup_db().await; + let skills = db.skills(); + + let mut skill = make_skill(&generate_entity_id(), "metadata-skill"); + skill.description = "Metadata description".to_string(); + skill.tags = vec!["rust".to_string()]; + skill.source = Some("git+https://github.com/test/skills".to_string()); + skill.source_subpath = Some("skills/metadata".to_string()); + skills.create(&skill).await.expect("Create should succeed"); + + let full = skills.list(None).await.expect("list should succeed"); + assert_eq!(full.items.len(), 1); + assert_eq!( + full.items[0].content, skill.content, + "list must keep the full SKILL.md content" + ); + + let metadata = skills + .list_metadata_only(None) + .await + .expect("list_metadata_only should succeed"); + + assert_eq!(metadata.items.len(), 1); + assert_eq!(metadata.total, 1); + assert_eq!(metadata.offset, 0); + + let item = &metadata.items[0]; + assert_eq!( + item.content, "", + "list_metadata_only must return an empty content field" + ); + assert_eq!(item.id, skill.id); + assert_eq!(item.name, skill.name); + assert_eq!(item.description, skill.description); + assert_eq!(item.tags, skill.tags); + assert_eq!(item.created_at, skill.created_at); + assert_eq!(item.updated_at, skill.updated_at); + assert_eq!(item.source, skill.source); + assert_eq!(item.source_subpath, skill.source_subpath); + assert_eq!(item.deleted_at, None); + assert!(item.project_ids.is_empty()); + assert!(item.scripts.is_empty()); + assert!(item.references.is_empty()); + assert!(item.assets.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_matches_list_with_filters() { + let db = setup_db().await; + let skills = db.skills(); + + let project_id = generate_entity_id(); + sqlx::query( + "INSERT INTO project (id, title, tags, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", + ) + .bind(&project_id) + .bind("Metadata Project") + .bind("[]") + .bind("2025-01-01 00:00:00") + .bind("2025-01-01 00:00:00") + .execute(db.pool()) + .await + .expect("Create project should succeed"); + + let mut rust = make_skill(&generate_entity_id(), "rust-skill"); + rust.tags = vec!["rust".to_string(), "programming".to_string()]; + let rust = skills.create(&rust).await.expect("Create rust skill"); + + let mut linked = make_skill(&generate_entity_id(), "linked-skill"); + linked.tags = vec!["programming".to_string()]; + linked.project_ids = vec![project_id.clone()]; + let linked = skills.create(&linked).await.expect("Create linked skill"); + + let mut plain = make_skill(&generate_entity_id(), "plain-skill"); + plain.tags = vec!["cooking".to_string()]; + let plain = skills.create(&plain).await.expect("Create plain skill"); + + let queries = [ + ("no filters", SkillQuery::default()), + ( + "tags", + SkillQuery { + tags: Some(vec!["rust".to_string()]), + ..Default::default() + }, + ), + ( + "overlapping tags", + SkillQuery { + tags: Some(vec!["rust".to_string(), "programming".to_string()]), + ..Default::default() + }, + ), + ( + "project_id", + SkillQuery { + project_id: Some(project_id.clone()), + ..Default::default() + }, + ), + ( + "project_id and tags", + SkillQuery { + project_id: Some(project_id.clone()), + tags: Some(vec!["programming".to_string()]), + ..Default::default() + }, + ), + ]; + + for (label, query) in &queries { + let full = skills + .list(Some(query)) + .await + .unwrap_or_else(|e| panic!("list with {label} filters failed: {e}")); + let metadata = skills + .list_metadata_only(Some(query)) + .await + .unwrap_or_else(|e| panic!("list_metadata_only with {label} filters failed: {e}")); + + let mut full_ids: Vec = full.items.iter().map(|s| s.id.clone()).collect(); + let mut metadata_ids: Vec = metadata.items.iter().map(|s| s.id.clone()).collect(); + full_ids.sort(); + metadata_ids.sort(); + + assert_eq!( + metadata.total, full.total, + "total mismatch for {label} filters" + ); + assert_eq!( + metadata_ids, full_ids, + "id set mismatch for {label} filters" + ); + assert!( + metadata.items.iter().all(|s| s.content.is_empty()), + "every item must have empty content for {label} filters" + ); + } + + let overlapping = skills + .list_metadata_only(Some(&SkillQuery { + tags: Some(vec!["rust".to_string(), "programming".to_string()]), + ..Default::default() + })) + .await + .expect("list_metadata_only with overlapping tags should succeed"); + assert_eq!( + overlapping.items.len(), + 2, + "a skill tagged with two matching tags must appear once" + ); + assert_eq!(overlapping.total, 2); + + assert_eq!( + skills + .list_metadata_only(None) + .await + .expect("list_metadata_only should succeed") + .total, + 3 + ); + assert!(rust.id != linked.id); + assert!(plain.id != rust.id); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_excludes_soft_deleted_skills() { + let db = setup_db().await; + let skills = db.skills(); + + let live = skills + .create(&make_skill(&generate_entity_id(), "live-skill")) + .await + .expect("Create live skill"); + let deleted = skills + .create(&make_skill(&generate_entity_id(), "deleted-skill")) + .await + .expect("Create deleted skill"); + skills + .delete(&deleted.id) + .await + .expect("Delete should succeed"); + + let result = skills + .list_metadata_only(None) + .await + .expect("list_metadata_only should succeed"); + + assert_eq!(result.total, 1, "soft-deleted skills must not be counted"); + assert_eq!(result.items.len(), 1); + assert_eq!(result.items[0].id, live.id); + assert_eq!(result.items[0].content, ""); +} diff --git a/crates/context-db/test/task.rs b/crates/context-db/test/task.rs index e67e0814..f47a21b6 100644 --- a/crates/context-db/test/task.rs +++ b/crates/context-db/test/task.rs @@ -2,7 +2,7 @@ use crate::SqliteDatabase; use crate::helpers::count_rows; use context_core::{ Database, HasTaskLists, HasTasks, PageSort, SortOrder, Task, TaskList, TaskListRepository, - TaskListStatus, TaskQuery, TaskRepository, TaskStatus, + TaskListStatus, TaskQuery, TaskRepository, TaskStatus, generate_entity_id, }; async fn setup_db() -> SqliteDatabase { @@ -1003,3 +1003,278 @@ async fn test_purge_deleted_preserves_recent_tombstones() { "a tombstone inside the retention period must be kept" ); } + +// ============================================================================= +// Metadata-only listing tests +// ============================================================================= + +async fn setup_metadata_list(db: &SqliteDatabase, list_id: &str) { + db.task_lists() + .create(&make_task_list(list_id, "Metadata List")) + .await + .expect("Create task list should succeed"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_omits_description() { + let db = setup_db().await; + let list_id = generate_entity_id(); + setup_metadata_list(&db, &list_id).await; + + let tasks = db.tasks(); + let mut task = make_task(&generate_entity_id(), &list_id, "Task with description"); + task.description = Some("A description that metadata-only lists omit".to_string()); + task.tags = vec!["rust".to_string()]; + task.external_refs = vec!["owner/repo#1".to_string()]; + tasks + .create(&task) + .await + .expect("Create task should succeed"); + + let query = TaskQuery { + list_id: Some(list_id.clone()), + ..Default::default() + }; + + let full = tasks.list(Some(&query)).await.expect("list should succeed"); + assert_eq!(full.items.len(), 1); + assert_eq!( + full.items[0].description.as_deref(), + Some("A description that metadata-only lists omit") + ); + + let metadata = tasks + .list_metadata_only(Some(&query)) + .await + .expect("list_metadata_only should succeed"); + + assert_eq!(metadata.items.len(), 1); + assert_eq!(metadata.total, 1); + assert_eq!( + metadata.items[0].description, None, + "list_metadata_only must return description = None" + ); + assert_eq!(metadata.items[0].id, task.id); + assert_eq!(metadata.items[0].title, "Task with description"); + assert_eq!(metadata.items[0].tags, vec!["rust".to_string()]); + assert_eq!( + metadata.items[0].external_refs, + vec!["owner/repo#1".to_string()] + ); + assert_eq!(metadata.items[0].deleted_at, None); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_matches_list_with_filters() { + let db = setup_db().await; + let list_id = generate_entity_id(); + setup_metadata_list(&db, &list_id).await; + + let tasks = db.tasks(); + + let mut alpha = make_task(&generate_entity_id(), &list_id, "Alpha"); + alpha.status = TaskStatus::Todo; + alpha.tags = vec!["rust".to_string()]; + alpha.description = Some("alpha description".to_string()); + let alpha = tasks.create(&alpha).await.expect("Create alpha"); + + let mut beta = make_task(&generate_entity_id(), &list_id, "Beta"); + beta.status = TaskStatus::Todo; + beta.tags = vec!["rust".to_string(), "frontend".to_string()]; + beta.description = Some("beta description".to_string()); + tasks.create(&beta).await.expect("Create beta"); + + let mut gamma = make_task(&generate_entity_id(), &list_id, "Gamma"); + gamma.status = TaskStatus::Done; + gamma.tags = vec!["frontend".to_string()]; + gamma.description = None; + tasks.create(&gamma).await.expect("Create gamma"); + + let mut sub = make_task(&generate_entity_id(), &list_id, "Alpha subtask"); + sub.parent_id = Some(alpha.id.clone()); + sub.status = TaskStatus::Todo; + sub.tags = vec!["rust".to_string()]; + sub.description = Some("subtask description".to_string()); + tasks.create(&sub).await.expect("Create subtask"); + + let queries = [ + ( + "list_id", + TaskQuery { + list_id: Some(list_id.clone()), + ..Default::default() + }, + ), + ( + "status", + TaskQuery { + list_id: Some(list_id.clone()), + status: Some("todo".to_string()), + ..Default::default() + }, + ), + ( + "multi-status", + TaskQuery { + list_id: Some(list_id.clone()), + status: Some("todo,done".to_string()), + ..Default::default() + }, + ), + ( + "tags", + TaskQuery { + list_id: Some(list_id.clone()), + tags: Some(vec!["rust".to_string()]), + ..Default::default() + }, + ), + ( + "parent_id", + TaskQuery { + list_id: Some(list_id.clone()), + parent_id: Some(alpha.id.clone()), + ..Default::default() + }, + ), + ( + "task_type task", + TaskQuery { + list_id: Some(list_id.clone()), + task_type: Some("task".to_string()), + ..Default::default() + }, + ), + ( + "task_type subtask", + TaskQuery { + list_id: Some(list_id.clone()), + task_type: Some("subtask".to_string()), + ..Default::default() + }, + ), + ( + "tags and status", + TaskQuery { + list_id: Some(list_id.clone()), + status: Some("todo".to_string()), + tags: Some(vec!["rust".to_string()]), + ..Default::default() + }, + ), + ]; + + for (label, query) in &queries { + let full = tasks + .list(Some(query)) + .await + .unwrap_or_else(|e| panic!("list with {label} filters failed: {e}")); + let metadata = tasks + .list_metadata_only(Some(query)) + .await + .unwrap_or_else(|e| panic!("list_metadata_only with {label} filters failed: {e}")); + + let mut full_ids: Vec = full.items.iter().map(|t| t.id.clone()).collect(); + let mut metadata_ids: Vec = metadata.items.iter().map(|t| t.id.clone()).collect(); + full_ids.sort(); + metadata_ids.sort(); + + assert_eq!( + metadata.total, full.total, + "total mismatch for {label} filters" + ); + assert_eq!( + metadata.items.len(), + full.items.len(), + "item count mismatch for {label} filters" + ); + assert_eq!( + metadata_ids, full_ids, + "id set mismatch for {label} filters" + ); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_orders_by_activity_like_list() { + let db = setup_db().await; + let list_id = generate_entity_id(); + setup_metadata_list(&db, &list_id).await; + + let tasks = db.tasks(); + + let mut parent1 = make_task(&generate_entity_id(), &list_id, "Parent 1"); + parent1.created_at = Some("2026-01-01 10:00:00".to_string()); + parent1.updated_at = Some("2026-01-01 10:00:00".to_string()); + let parent1 = tasks.create(&parent1).await.expect("Create parent1"); + + let mut parent2 = make_task(&generate_entity_id(), &list_id, "Parent 2"); + parent2.created_at = Some("2026-01-01 11:00:00".to_string()); + parent2.updated_at = Some("2026-01-01 11:00:00".to_string()); + let parent2 = tasks.create(&parent2).await.expect("Create parent2"); + + let mut subtask = make_task(&generate_entity_id(), &list_id, "Subtask of Parent 1"); + subtask.parent_id = Some(parent1.id.clone()); + subtask.created_at = Some("2026-01-01 12:00:00".to_string()); + subtask.updated_at = Some("2026-01-01 12:00:00".to_string()); + tasks.create(&subtask).await.expect("Create subtask"); + + let query = TaskQuery { + page: PageSort { + limit: Some(10), + offset: Some(0), + sort_by: Some("updated_at".to_string()), + sort_order: Some(SortOrder::Desc), + }, + list_id: Some(list_id.clone()), + task_type: Some("task".to_string()), + ..Default::default() + }; + + let full = tasks.list(Some(&query)).await.expect("list should succeed"); + let metadata = tasks + .list_metadata_only(Some(&query)) + .await + .expect("list_metadata_only should succeed"); + + let full_ids: Vec = full.items.iter().map(|t| t.id.clone()).collect(); + let metadata_ids: Vec = metadata.items.iter().map(|t| t.id.clone()).collect(); + + assert_eq!(metadata_ids, full_ids, "ordering must match list"); + assert_eq!( + metadata_ids, + vec![parent1.id.clone(), parent2.id.clone()], + "most recent subtask activity first" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_metadata_only_excludes_soft_deleted_tasks() { + let db = setup_db().await; + let list_id = generate_entity_id(); + setup_metadata_list(&db, &list_id).await; + + let tasks = db.tasks(); + let live = tasks + .create(&make_task(&generate_entity_id(), &list_id, "Live task")) + .await + .expect("Create live task"); + let deleted = tasks + .create(&make_task(&generate_entity_id(), &list_id, "Deleted task")) + .await + .expect("Create deleted task"); + tasks + .delete(&deleted.id) + .await + .expect("Delete should succeed"); + + let result = tasks + .list_metadata_only(None) + .await + .expect("list_metadata_only should succeed"); + + assert_eq!(result.total, 1, "soft-deleted tasks must not be counted"); + assert_eq!(result.items.len(), 1); + assert_eq!(result.items[0].id, live.id); + assert_eq!(result.items[0].description, None); +} diff --git a/crates/context-db/test/task_crud.rs b/crates/context-db/test/task_crud.rs index c650395a..981aff76 100644 --- a/crates/context-db/test/task_crud.rs +++ b/crates/context-db/test/task_crud.rs @@ -981,3 +981,170 @@ async fn update_task_with_empty_title_should_fail() { let result = tasks.update(&updated).await; assert!(result.is_err(), "Update should fail with empty title"); } + +// ============================================================================ +// Description size cap +// ============================================================================ + +const OVER_LIMIT_DESCRIPTION: usize = 11_000; + +/// Seeds a task row directly so tests can exercise read paths on a description +/// that the repository create path now rejects. +/// +/// The migrated schema carries a `length(description) <= 10000` CHECK, so a +/// fresh database cannot hold an over-limit row. CHECK enforcement is disabled +/// for this INSERT only, which emulates a row written before that constraint +/// existed; reads, transitions, and restores must still work on it. +async fn seed_over_limit_task( + db: &SqliteDatabase, + id: &str, + list_id: &str, + deleted_at: Option<&str>, +) { + let mut conn = db.pool().acquire().await.expect("Acquire connection"); + + sqlx::query("PRAGMA ignore_check_constraints = ON") + .execute(&mut *conn) + .await + .expect("Disable CHECK enforcement for the seed INSERT"); + + sqlx::query( + "INSERT INTO task (id, list_id, parent_id, title, description, status, priority, tags, external_refs, created_at, updated_at, deleted_at) \ + VALUES (?, ?, NULL, ?, ?, ?, NULL, ?, ?, ?, ?, ?)", + ) + .bind(id) + .bind(list_id) + .bind("Over-limit description") + .bind("x".repeat(OVER_LIMIT_DESCRIPTION)) + .bind("todo") + .bind("[]") + .bind("[]") + .bind("2025-01-01 00:00:00") + .bind("2025-01-01 00:00:00") + .bind(deleted_at) + .execute(&mut *conn) + .await + .expect("Seed task with an over-limit description"); + + sqlx::query("PRAGMA ignore_check_constraints = OFF") + .execute(&mut *conn) + .await + .expect("Re-enable CHECK enforcement"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn create_task_with_description_over_limit_should_fail() { + let db = setup_db().await; + db.task_lists() + .create(&make_task_list("listmax1", "Create Size Cap")) + .await + .expect("Create task list should succeed"); + + let mut task = make_task("tskmax01", "listmax1", "Too long"); + task.description = Some("x".repeat(context_core::TASK_DESCRIPTION_MAX + 1)); + + match db.tasks().create(&task).await { + Err(context_core::DbError::Validation { message }) => { + assert!( + message.contains("maximum size"), + "Error should mention maximum size, got: {}", + message + ); + } + other => panic!("Expected DbError::Validation, got: {:?}", other), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn create_task_with_description_at_limit_should_succeed() { + let db = setup_db().await; + db.task_lists() + .create(&make_task_list("listmax0", "Boundary Size")) + .await + .expect("Create task list should succeed"); + + let mut task = make_task("tskmax00", "listmax0", "At the limit"); + task.description = Some("x".repeat(context_core::TASK_DESCRIPTION_MAX)); + + let created = db + .tasks() + .create(&task) + .await + .expect("Create at the limit should succeed"); + assert_eq!( + created + .description + .expect("description should be stored") + .len(), + context_core::TASK_DESCRIPTION_MAX + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn update_task_with_over_limit_description_should_fail() { + let db = setup_db().await; + db.task_lists() + .create(&make_task_list("listmax2", "Update Size Cap")) + .await + .expect("Create task list should succeed"); + seed_over_limit_task(&db, "tskmax02", "listmax2", None).await; + + let mut task = db + .tasks() + .get("tskmax02") + .await + .expect("Seeded over-limit task should be readable"); + task.title = "Renamed".to_string(); + + match db.tasks().update(&task).await { + Err(context_core::DbError::Validation { message }) => { + assert!( + message.contains("maximum size"), + "Error should mention maximum size, got: {}", + message + ); + } + other => panic!("Expected DbError::Validation, got: {:?}", other), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn transition_task_with_over_limit_description_should_succeed() { + let db = setup_db().await; + db.task_lists() + .create(&make_task_list("listmax3", "Transition Size Cap")) + .await + .expect("Create task list should succeed"); + seed_over_limit_task(&db, "tskmax03", "listmax3", None).await; + + let updated = db + .tasks() + .transition_tasks(&["tskmax03".to_string()], TaskStatus::InProgress) + .await + .expect("Transition should succeed on an over-limit description"); + + assert_eq!(updated.len(), 1); + assert_eq!(updated[0].status, TaskStatus::InProgress); +} + +#[tokio::test(flavor = "multi_thread")] +async fn restore_task_with_over_limit_description_should_succeed() { + let db = setup_db().await; + db.task_lists() + .create(&make_task_list("listmax4", "Restore Size Cap")) + .await + .expect("Create task list should succeed"); + seed_over_limit_task(&db, "tskmax04", "listmax4", Some("2025-01-02 00:00:00")).await; + + db.tasks() + .restore("tskmax04") + .await + .expect("Restore should succeed on an over-limit description"); + + assert!( + read_deleted_at(db.pool(), "task", "tskmax04") + .await + .is_none(), + "restored task should be live" + ); +} diff --git a/crates/context-frontend/src/api/mod.rs b/crates/context-frontend/src/api/mod.rs index c08207e0..41c33531 100644 --- a/crates/context-frontend/src/api/mod.rs +++ b/crates/context-frontend/src/api/mod.rs @@ -312,6 +312,7 @@ pub mod tasks { if let Some(t) = task_type { query_params.push(format!("type={}", t)); } + query_params.push(format!("include_description={}", true)); if !query_params.is_empty() { url = format!("{}?{}", url, query_params.join("&")); diff --git a/crates/context-frontend/src/components/note_components.rs b/crates/context-frontend/src/components/note_components.rs index 7adc7ddf..204f6894 100644 --- a/crates/context-frontend/src/components/note_components.rs +++ b/crates/context-frontend/src/components/note_components.rs @@ -195,6 +195,7 @@ pub fn NoteStackSidebar(parent_note: Note, on_note_select: Callback) -> .offset(0) .param("type", "subnote") .param("parent_id", parent_id) + .param("include_content", "true") .fetch() .await; @@ -218,6 +219,7 @@ pub fn NoteStackSidebar(parent_note: Note, on_note_select: Callback) -> .offset(new_offset) .param("type", "subnote") .param("parent_id", parent_id) + .param("include_content", "true") .fetch() .await; diff --git a/crates/context-frontend/src/pages/note_detail.rs b/crates/context-frontend/src/pages/note_detail.rs index 43627afe..f17a465c 100644 --- a/crates/context-frontend/src/pages/note_detail.rs +++ b/crates/context-frontend/src/pages/note_detail.rs @@ -138,6 +138,7 @@ pub fn NoteDetail() -> impl IntoView { .offset(offset) .param("type", "subnote") .param("parent_id", &id) + .param("include_content", "true") .fetch() .await; match result { diff --git a/crates/context-frontend/src/pages/notes.rs b/crates/context-frontend/src/pages/notes.rs index a6e4db82..9532559e 100644 --- a/crates/context-frontend/src/pages/notes.rs +++ b/crates/context-frontend/src/pages/notes.rs @@ -79,7 +79,8 @@ fn NotesList() -> impl IntoView { .offset(offset) .sort(current_sort) .order(current_order) - .param("type", "note"); + .param("type", "note") + .param("include_content", "true"); if !current_query.trim().is_empty() { builder = builder.search(current_query); diff --git a/crates/context-frontend/src/pages/project_detail.rs b/crates/context-frontend/src/pages/project_detail.rs index 882b19ea..fd5c220b 100644 --- a/crates/context-frontend/src/pages/project_detail.rs +++ b/crates/context-frontend/src/pages/project_detail.rs @@ -268,7 +268,8 @@ pub fn ProjectDetail() -> impl IntoView { .sort(current_sort) .order(current_order) .param("project_id", id) - .param("type", "note"); + .param("type", "note") + .param("include_content", "true"); if let Some(search) = search_query { builder = builder.search(search); diff --git a/crates/context-frontend/src/pages/project_notes.rs b/crates/context-frontend/src/pages/project_notes.rs index 7446d444..d84d0907 100644 --- a/crates/context-frontend/src/pages/project_notes.rs +++ b/crates/context-frontend/src/pages/project_notes.rs @@ -77,7 +77,8 @@ pub fn ProjectNotes() -> impl IntoView { .sort(current_sort) .order(current_order) .param("type", "note") - .param("project_id", &id); + .param("project_id", &id) + .param("include_content", "true"); if !current_query.trim().is_empty() { builder = builder.search(current_query); diff --git a/crates/context-server/src/api/v1/mod.rs b/crates/context-server/src/api/v1/mod.rs index f3a7a1c1..172bb5f5 100644 --- a/crates/context-server/src/api/v1/mod.rs +++ b/crates/context-server/src/api/v1/mod.rs @@ -1,6 +1,9 @@ //! V1 API handlers. mod notes; +#[cfg(test)] +#[path = "../../../test/api/v1/notes.rs"] +mod notes_test; mod projects; mod repos; #[cfg(test)] @@ -15,6 +18,9 @@ mod sync; #[path = "../../../test/api/v1/sync.rs"] mod sync_test; mod task_lists; +#[cfg(test)] +#[path = "../../../test/api/v1/task_lists.rs"] +mod task_lists_test; mod tasks; #[cfg(test)] #[path = "../../../test/api/v1/tasks.rs"] diff --git a/crates/context-server/src/api/v1/notes.rs b/crates/context-server/src/api/v1/notes.rs index 6a962da0..05436a15 100644 --- a/crates/context-server/src/api/v1/notes.rs +++ b/crates/context-server/src/api/v1/notes.rs @@ -197,6 +197,9 @@ pub struct ListNotesQuery { /// Sort order (asc, desc) #[param(example = "desc")] pub order: Option, + /// Include note content in response (default: false for lighter list responses) + #[param(example = false)] + pub include_content: Option, } #[derive(Serialize, ToSchema)] @@ -261,6 +264,7 @@ pub async fn list_notes( }; // Get notes - either search or list all (at database level) + let include_content = query.include_content.unwrap_or(false); let result = if let Some(q) = &query.q { if q.is_empty() { // Empty search returns empty result @@ -278,13 +282,20 @@ pub async fn list_notes( .await .map_err(internal_error)? } - } else { + } else if include_content { state .db() .notes() .list(Some(&db_query)) .await .map_err(internal_error)? + } else { + state + .db() + .notes() + .list_metadata_only(Some(&db_query)) + .await + .map_err(internal_error)? }; let items: Vec = result.items.into_iter().map(NoteResponse::from).collect(); diff --git a/crates/context-server/src/api/v1/skills.rs b/crates/context-server/src/api/v1/skills.rs index 17701e52..f5fa5996 100644 --- a/crates/context-server/src/api/v1/skills.rs +++ b/crates/context-server/src/api/v1/skills.rs @@ -101,6 +101,9 @@ pub struct ListSkillsQuery { /// Sort order (asc, desc) #[param(example = "desc")] pub order: Option, + /// Include skill content in response (default: false for lighter list responses) + #[param(example = false)] + pub include_content: Option, } #[derive(Debug, Deserialize, ToSchema)] @@ -265,15 +268,16 @@ pub async fn list_skills( project_id: api_query.project_id.clone(), }; - // Route to search if query is provided, otherwise list all - let results = if let Some(q) = &api_query.query { - if !q.trim().is_empty() { - repo.search(q, Some(&db_query)).await - } else { - repo.list(Some(&db_query)).await - } - } else { + // Search keeps full content; list rows are metadata-only unless opted in + let include_content = api_query.include_content.unwrap_or(false); + let results = if let Some(q) = &api_query.query + && !q.trim().is_empty() + { + repo.search(q, Some(&db_query)).await + } else if include_content { repo.list(Some(&db_query)).await + } else { + repo.list_metadata_only(Some(&db_query)).await } .map_err(|e| { ( @@ -290,7 +294,7 @@ pub async fn list_skills( .into_iter() .map(|skill| { let mut response = SkillResponse::from(skill); - response.enabled = is_skill_enabled(skills_dir, &response.content); + response.enabled = is_skill_enabled(skills_dir, &response.name); response }) .collect(); @@ -336,7 +340,7 @@ pub async fn get_skill( ), })?; let mut response = SkillResponse::from(skill); - response.enabled = is_skill_enabled(state.skills_dir(), &response.content); + response.enabled = is_skill_enabled(state.skills_dir(), &response.name); Ok(Json(response)) } @@ -960,9 +964,8 @@ pub async fn refresh_skill( )); }; - // The cache directory name comes from the content frontmatter. Content - // without a parseable name is treated as disabled. - let was_enabled = is_skill_enabled(state.skills_dir(), &skill.content); + // The cache directory name comes from the record name. + let was_enabled = is_skill_enabled(state.skills_dir(), &skill.name); // Wipe the cache before importing. Overwriting alone would leave files that // disappeared from the source behind, so the wipe is what guarantees the @@ -1058,10 +1061,7 @@ pub async fn refresh_skill( /// Report whether a skill is enabled, meaning its cache directory exists. /// -/// The cache directory name comes from the `name` field in the skill content -/// frontmatter. Content without a parseable name is reported as disabled. -fn is_skill_enabled(skills_dir: &std::path::Path, content: &str) -> bool { - context_skills::parse_skill_name_from_content(content) - .map(|name| skills_dir.join(name).exists()) - .unwrap_or(false) +/// The cache directory name comes from the skill record name. +fn is_skill_enabled(skills_dir: &std::path::Path, name: &str) -> bool { + skills_dir.join(name).exists() } diff --git a/crates/context-server/src/api/v1/task_lists.rs b/crates/context-server/src/api/v1/task_lists.rs index 6d950f02..a355b0b7 100644 --- a/crates/context-server/src/api/v1/task_lists.rs +++ b/crates/context-server/src/api/v1/task_lists.rs @@ -178,6 +178,9 @@ pub struct ListTaskListsQuery { /// Sort order (asc, desc) #[param(example = "desc")] pub order: Option, + /// Include task list notes in response (default: false for lighter list responses) + #[param(example = false)] + pub include_notes: Option, } #[derive(Serialize, ToSchema)] @@ -289,10 +292,17 @@ pub async fn list_task_lists( ) })?; + let include_notes = query.include_notes.unwrap_or(false); let items: Vec = result .items .into_iter() .map(TaskListResponse::from) + .map(|mut response| { + if !include_notes { + response.notes = None; + } + response + }) .collect(); Ok(Json(PaginatedTaskLists { diff --git a/crates/context-server/src/api/v1/tasks.rs b/crates/context-server/src/api/v1/tasks.rs index 3153d5db..13792ec4 100644 --- a/crates/context-server/src/api/v1/tasks.rs +++ b/crates/context-server/src/api/v1/tasks.rs @@ -251,6 +251,9 @@ pub struct ListTasksQuery { #[param(example = "task")] #[serde(rename = "type")] pub task_type: Option, + /// Include task description in the response (default: false for lighter list responses) + #[param(example = false)] + pub include_description: Option, } #[derive(Serialize, ToSchema)] @@ -303,19 +306,20 @@ pub async fn list_tasks( task_type: query.task_type.clone(), }; - // Use search if query provided, otherwise list - let result = if let Some(ref search_query) = query.q { - if !search_query.trim().is_empty() { - state - .db() - .tasks() - .search(search_query, Some(&db_query)) - .await - } else { - state.db().tasks().list(Some(&db_query)).await - } - } else { + // Use search if query provided, otherwise list; descriptions are opt-in + let include_description = query.include_description.unwrap_or(false); + let result = if let Some(search_query) = &query.q + && !search_query.trim().is_empty() + { + state + .db() + .tasks() + .search(search_query, Some(&db_query)) + .await + } else if include_description { state.db().tasks().list(Some(&db_query)).await + } else { + state.db().tasks().list_metadata_only(Some(&db_query)).await } .map_err(|e| { ( diff --git a/crates/context-server/src/mcp/tools/notes.rs b/crates/context-server/src/mcp/tools/notes.rs index 9473851f..08f1959d 100644 --- a/crates/context-server/src/mcp/tools/notes.rs +++ b/crates/context-server/src/mcp/tools/notes.rs @@ -128,10 +128,6 @@ pub struct ListNotesParams { pub limit: Option, #[schemars(description = "Number of items to skip")] pub offset: Option, - #[schemars( - description = "Include note content in response (default: false for lighter list responses). Set to true to retrieve full content." - )] - pub include_content: Option, #[schemars( description = "Field to sort by (title, created_at, updated_at, last_activity_at). Default: created_at" )] @@ -250,15 +246,12 @@ impl NoteTools { } #[tool( - description = "List notes. Query for FTS search. Default: metadata only (use include_content=true for full). Filter by tags/project_id/parent_id/note_type. Limit: 10 (max 20)." + description = "List notes. Query for FTS search. Default: metadata only. Filter by tags/project_id/parent_id/note_type. Limit: 10 (max 20)." )] pub async fn note_list( &self, params: Parameters, ) -> Result { - // Default to include_content=false for lighter list responses - let include_content = params.0.include_content.unwrap_or(false); - // Build query let query = NoteQuery { page: PageSort { @@ -280,15 +273,18 @@ impl NoteTools { // If query is provided, perform FTS search let result = if let Some(q) = ¶ms.0.query { self.db.notes().search(q, Some(&query)).await - } else if include_content { - self.db.notes().list(Some(&query)).await } else { self.db.notes().list_metadata_only(Some(&query)).await } .map_err(map_db_error)?; + let mut items = result.items; + for note in &mut items { + note.content = String::new(); + } + let response = json!({ - "items": result.items, + "items": items, "total": result.total, "limit": result.limit, "offset": result.offset, diff --git a/crates/context-server/src/mcp/tools/skills.rs b/crates/context-server/src/mcp/tools/skills.rs index 7c8a5fe6..c8059be4 100644 --- a/crates/context-server/src/mcp/tools/skills.rs +++ b/crates/context-server/src/mcp/tools/skills.rs @@ -88,7 +88,7 @@ impl SkillTools { // -- Tools to implement (following notes pattern) #[tool( - description = "List skills with optional full-text search. Provide 'query' parameter to search, omit to list all. Supports filtering, sorting, and pagination." + description = "List skills with optional full-text search. Provide 'query' parameter to search, omit to list all. Default: metadata only. Supports filtering, sorting, and pagination." )] pub async fn skill_list( &self, @@ -109,7 +109,7 @@ impl SkillTools { project_id: params.0.project_id.clone(), }; - // Route to search if query is provided, otherwise list all + // Route to search if query is provided, otherwise list metadata only let result = if let Some(query) = ¶ms.0.query { self.db .skills() @@ -122,16 +122,25 @@ impl SkillTools { ) })? } else { - self.db.skills().list(Some(&db_query)).await.map_err(|e| { - McpError::internal_error( - "database_error", - Some(serde_json::json!({"error": e.to_string()})), - ) - })? + self.db + .skills() + .list_metadata_only(Some(&db_query)) + .await + .map_err(|e| { + McpError::internal_error( + "database_error", + Some(serde_json::json!({"error": e.to_string()})), + ) + })? }; + let mut items = result.items; + for item in &mut items { + item.content = String::new(); + } + let response = json!({ - "items": result.items, + "items": items, "total": result.total, "limit": result.limit, "offset": result.offset, diff --git a/crates/context-server/src/mcp/tools/task_lists.rs b/crates/context-server/src/mcp/tools/task_lists.rs index 4e768812..fb51b40b 100644 --- a/crates/context-server/src/mcp/tools/task_lists.rs +++ b/crates/context-server/src/mcp/tools/task_lists.rs @@ -150,7 +150,7 @@ impl TaskListTools { } #[tool( - description = "List task lists with filtering by project, status, or tags. Use this to find existing lists before creating new ones." + description = "List task lists with filtering by project, status, or tags. Default: metadata only (notes omitted; task_list_get returns full notes). Use this to find existing lists before creating new ones." )] pub async fn task_list_list( &self, @@ -189,8 +189,13 @@ impl TaskListTools { } .map_err(map_db_error)?; + let mut items = result.items; + for list in &mut items { + list.notes = None; + } + let response = json!({ - "items": result.items, + "items": items, "total": result.total, "limit": result.limit.unwrap_or(50), "offset": result.offset, diff --git a/crates/context-server/src/mcp/tools/tasks.rs b/crates/context-server/src/mcp/tools/tasks.rs index f7311f4d..7016b358 100644 --- a/crates/context-server/src/mcp/tools/tasks.rs +++ b/crates/context-server/src/mcp/tools/tasks.rs @@ -182,7 +182,7 @@ impl TaskTools { } #[tool( - description = "List tasks in a task list with optional full-text search. Provide 'query' parameter to search, omit to list all. Filter by status, parent_id (for subtasks), or tags. Sort by title, status, priority, created_at, or updated_at (default: created_at). Use order='asc' or 'desc' (default: asc). Use this to see current work before adding new tasks." + description = "List tasks in a task list with optional full-text search. Provide 'query' parameter to search, omit to list all. Default: metadata only. Filter by status, parent_id (for subtasks), or tags. Sort by title, status, priority, created_at, or updated_at (default: created_at). Use order='asc' or 'desc' (default: asc). Use this to see current work before adding new tasks." )] pub async fn task_list( &self, @@ -214,12 +214,17 @@ impl TaskTools { let result = if let Some(q) = ¶ms.0.query { self.db.tasks().search(q, Some(&query)).await } else { - self.db.tasks().list(Some(&query)).await + self.db.tasks().list_metadata_only(Some(&query)).await } .map_err(map_db_error)?; + let mut items = result.items; + for item in &mut items { + item.description = None; + } + let response = json!({ - "items": result.items, + "items": items, "total": result.total, "limit": result.limit, "offset": result.offset, diff --git a/crates/context-server/test/api/v1/notes.rs b/crates/context-server/test/api/v1/notes.rs new file mode 100644 index 00000000..31f9ea81 --- /dev/null +++ b/crates/context-server/test/api/v1/notes.rs @@ -0,0 +1,168 @@ +//! Co-located tests for note REST handlers. +//! +//! Covers the list payload rule: list and search results are metadata-only; +//! single-entity responses keep the full content. + +use axum::{ + body::Body, + http::{Request, StatusCode}, +}; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use tower::ServiceExt; + +use crate::api::{AppState, routes}; +use context_core::Database; +use context_db::SqliteDatabase; +use context_sync::{MockGitOps, SyncManager}; +use tempfile::TempDir; + +/// Content longer than 100 chars so a blanked placeholder is distinguishable. +const NOTE_CONTENT: &str = "This note body is deliberately longer than one hundred characters so that a blanked response field is easy to tell apart from the stored value."; + +/// Create a test app backed by an in-memory SQLite database. +async fn test_app() -> axum::Router { + let db = SqliteDatabase::in_memory() + .await + .expect("Failed to create in-memory database"); + db.migrate().expect("Migration should succeed"); + + let temp_dir = TempDir::new().unwrap(); + let state = AppState::new( + db, + SyncManager::new(MockGitOps::new()), + crate::api::notifier::ChangeNotifier::new(), + temp_dir.path().join("skills"), + ); + routes::create_router(state, false) +} + +/// Parse a JSON response body. +async fn json_body(response: axum::response::Response) -> Value { + let body = response.into_body().collect().await.unwrap().to_bytes(); + serde_json::from_slice(&body).unwrap() +} + +/// Create a note with the shared content; return its ID. +async fn create_note(app: &axum::Router, title: &str) -> String { + let response = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/notes") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({ + "title": title, + "content": NOTE_CONTENT + })) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::CREATED); + json_body(response).await["id"] + .as_str() + .unwrap() + .to_string() +} + +/// GET the note list with an optional raw query string. +async fn list_notes(app: &axum::Router, query: &str) -> Value { + let uri = if query.is_empty() { + "/api/v1/notes".to_string() + } else { + format!("/api/v1/notes?{query}") + }; + let response = app + .clone() + .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + json_body(response).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_notes_returns_metadata_only() { + let app = test_app().await; + let note_id = create_note(&app, "Listed note").await; + + let body = list_notes(&app, "").await; + + assert_eq!(body["total"], 1); + assert_eq!(body["limit"], 50); + assert_eq!(body["offset"], 0); + assert_eq!(body["items"][0]["id"], json!(note_id)); + assert_eq!( + body["items"][0]["content"], + json!(""), + "list must omit note content" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_notes_include_content_returns_content() { + let app = test_app().await; + create_note(&app, "Listed note").await; + + let body = list_notes(&app, "include_content=true").await; + + assert_eq!(body["total"], 1); + assert_eq!(body["items"][0]["content"], json!(NOTE_CONTENT)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_notes_search_returns_content() { + let app = test_app().await; + create_note(&app, "Rust Note").await; + + let body = list_notes(&app, "q=deliberately").await; + + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["content"], + json!(NOTE_CONTENT), + "search results must keep the stored content" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_notes_empty_query_returns_empty_list() { + let app = test_app().await; + create_note(&app, "Listed note").await; + + let body = list_notes(&app, "q=").await; + + assert_eq!(body["total"], 0); + assert_eq!(body["items"], json!([])); + assert_eq!(body["offset"], 0); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_note_still_returns_content() { + let app = test_app().await; + let note_id = create_note(&app, "Listed note").await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/v1/notes/{note_id}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!( + body["content"], + json!(NOTE_CONTENT), + "single-entity GET must keep the stored content" + ); +} diff --git a/crates/context-server/test/api/v1/skills.rs b/crates/context-server/test/api/v1/skills.rs index 3d0568f8..61fe32ac 100644 --- a/crates/context-server/test/api/v1/skills.rs +++ b/crates/context-server/test/api/v1/skills.rs @@ -87,8 +87,8 @@ async fn create_skill(app: &axum::Router, name: &str) -> String { .to_string() } -/// Create a skill whose content has no parseable frontmatter name. -async fn create_unnamed_skill(app: &axum::Router) -> String { +/// Create a skill with an explicit record name and content; return its ID. +async fn create_skill_with_content(app: &axum::Router, name: &str, content: &str) -> String { let response = app .clone() .oneshot( @@ -98,9 +98,9 @@ async fn create_unnamed_skill(app: &axum::Router) -> String { .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({ - "name": "unnamed", + "name": name, "description": "Test skill", - "content": "---\ndescription: d\n---\n# Body" + "content": content })) .unwrap(), )) @@ -242,18 +242,37 @@ async fn list_skills_includes_enabled_state() { } // ============================================================================= -// Criterion 4: unparseable content reports enabled false +// Criterion 4: enabled derives from the record name // ============================================================================= #[tokio::test(flavor = "multi_thread")] -async fn get_skill_without_parseable_name_reports_disabled() { +async fn get_skill_without_cache_dir_reports_disabled() { let app = test_app().await; - let skill_id = create_unnamed_skill(&app.router).await; + let skill_id = create_skill(&app.router, "no-cache-skill").await; let body = get_skill(&app.router, &skill_id).await; assert!( !body["enabled"].as_bool().expect("enabled must be a bool"), - "unparseable content must report disabled" + "a record whose name has no cache directory must report disabled" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_skill_reports_enabled_from_record_name_not_content() { + let app = test_app().await; + let skill_id = create_skill_with_content( + &app.router, + "record-name", + "---\nname: other-name\ndescription: d\n---\n# Body", + ) + .await; + std::fs::create_dir_all(app.skills_dir.join("record-name")) + .expect("cache directory should be created"); + + let body = get_skill(&app.router, &skill_id).await; + assert!( + body["enabled"].as_bool().expect("enabled must be a bool"), + "enabled must come from the record name's cache directory" ); } @@ -610,3 +629,103 @@ async fn get_skill_reports_source_subpath() { "GET must expose the stored subpath" ); } + +// ============================================================================= +// List payload trimming +// ============================================================================= + +/// GET the skill list; return the parsed body. +async fn list_skills(app: &axum::Router, query: &str) -> Value { + let uri = if query.is_empty() { + "/api/v1/skills".to_string() + } else { + format!("/api/v1/skills?{query}") + }; + let response = app + .clone() + .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + json_body(response).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_skills_omits_content_by_default() { + let app = test_app().await; + let skill_id = create_skill(&app.router, "content-skill").await; + + let body = list_skills(&app.router, "").await; + + assert_eq!(body["total"], 1); + assert_eq!(body["limit"], 50); + assert_eq!(body["offset"], 0); + assert_eq!(body["items"][0]["id"], json!(skill_id)); + assert_eq!( + body["items"][0]["content"], + json!(""), + "list must omit the SKILL.md content" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_skills_include_content_returns_content() { + let app = test_app().await; + create_skill(&app.router, "content-skill").await; + + let body = list_skills(&app.router, "include_content=true").await; + + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["content"], + json!("---\nname: content-skill\ndescription: d\n---\n# Body") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_skills_search_returns_content() { + let app = test_app().await; + create_skill(&app.router, "content-skill").await; + + let body = list_skills(&app.router, "q=Body").await; + + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["content"], + json!("---\nname: content-skill\ndescription: d\n---\n# Body"), + "search results must keep the stored content" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_skills_report_enabled_from_record_name() { + let app = test_app().await; + let skill_id = create_skill(&app.router, "enabled-list-skill").await; + + let response = post_toggle(&app.router, &skill_id, "enable").await; + assert_eq!(response.status(), StatusCode::OK); + + let body = list_skills(&app.router, "").await; + + assert_eq!(body["items"][0]["content"], json!("")); + assert!( + body["items"][0]["enabled"] + .as_bool() + .expect("enabled must be a bool"), + "enabled must come from the record name's cache directory" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_skill_still_returns_content() { + let app = test_app().await; + let skill_id = create_skill(&app.router, "content-skill").await; + + let body = get_skill(&app.router, &skill_id).await; + + assert_eq!( + body["content"], + json!("---\nname: content-skill\ndescription: d\n---\n# Body"), + "single-entity GET must keep the stored content" + ); +} diff --git a/crates/context-server/test/api/v1/task_lists.rs b/crates/context-server/test/api/v1/task_lists.rs new file mode 100644 index 00000000..c20b1bcb --- /dev/null +++ b/crates/context-server/test/api/v1/task_lists.rs @@ -0,0 +1,194 @@ +//! Co-located tests for task-list REST handlers. +//! +//! Covers the list payload rule: container listings omit the freeform notes +//! markdown; single-entity responses keep it. + +use axum::{ + body::Body, + http::{Request, StatusCode}, +}; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use tower::ServiceExt; + +use crate::api::{AppState, routes}; +use context_core::Database; +use context_db::SqliteDatabase; +use context_sync::{MockGitOps, SyncManager}; +use tempfile::TempDir; + +/// Multi-paragraph notes so a null placeholder is distinguishable. +const LIST_NOTES: &str = "## Context\n\nThis container note block is deliberately longer than one line so that a null response field is easy to distinguish from the stored value.\n\n## Decisions\n\nKeep the notes out of list payloads."; + +/// Create a test app backed by an in-memory SQLite database. +async fn test_app() -> axum::Router { + let db = SqliteDatabase::in_memory() + .await + .expect("Failed to create in-memory database"); + db.migrate().expect("Migration should succeed"); + + let temp_dir = TempDir::new().unwrap(); + let state = AppState::new( + db, + SyncManager::new(MockGitOps::new()), + crate::api::notifier::ChangeNotifier::new(), + temp_dir.path().join("skills"), + ); + routes::create_router(state, false) +} + +/// Parse a JSON response body. +async fn json_body(response: axum::response::Response) -> Value { + let body = response.into_body().collect().await.unwrap().to_bytes(); + serde_json::from_slice(&body).unwrap() +} + +/// Create a project and a task list carrying the shared notes; return the list ID. +async fn create_list_with_notes(app: &axum::Router, title: &str) -> String { + let project = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/projects") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({"title": "Notes Project"})).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let project_id = json_body(project).await["id"].as_str().unwrap().to_string(); + + let list = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/task-lists") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({ + "title": title, + "description": "Short description", + "notes": LIST_NOTES, + "project_id": project_id + })) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(list.status(), StatusCode::CREATED); + json_body(list).await["id"].as_str().unwrap().to_string() +} + +/// GET the task-list collection with an optional raw query string. +async fn list_task_lists(app: &axum::Router, query: &str) -> Value { + let uri = if query.is_empty() { + "/api/v1/task-lists".to_string() + } else { + format!("/api/v1/task-lists?{query}") + }; + let response = app + .clone() + .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + json_body(response).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_task_lists_omits_notes() { + let app = test_app().await; + let list_id = create_list_with_notes(&app, "Notes List").await; + + let body = list_task_lists(&app, "").await; + + assert_eq!(body["total"], 1); + assert_eq!(body["limit"], 50); + assert_eq!(body["offset"], 0); + assert_eq!(body["items"][0]["id"], json!(list_id)); + assert!( + body["items"][0]["notes"].is_null(), + "list must omit notes, got: {}", + body["items"][0]["notes"] + ); + assert_eq!( + body["items"][0]["description"], "Short description", + "description stays in list responses" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_task_lists_search_omits_notes() { + let app = test_app().await; + create_list_with_notes(&app, "Rust Container").await; + + let body = list_task_lists(&app, "q=rust").await; + + assert_eq!(body["total"], 1); + assert!( + body["items"][0]["notes"].is_null(), + "search results must omit notes without the flag, got: {}", + body["items"][0]["notes"] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_task_lists_include_notes_returns_notes() { + let app = test_app().await; + create_list_with_notes(&app, "Notes List").await; + + let body = list_task_lists(&app, "include_notes=true").await; + + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["notes"], + json!(LIST_NOTES), + "include_notes=true must return the stored notes" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_task_lists_search_include_notes_returns_notes() { + let app = test_app().await; + create_list_with_notes(&app, "Rust Container").await; + + let body = list_task_lists(&app, "q=rust&include_notes=true").await; + + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["notes"], + json!(LIST_NOTES), + "search with include_notes=true must return the stored notes" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_task_list_still_returns_notes() { + let app = test_app().await; + let list_id = create_list_with_notes(&app, "Notes List").await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/v1/task-lists/{list_id}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!( + body["notes"], + json!(LIST_NOTES), + "single-entity GET must keep the stored notes" + ); +} diff --git a/crates/context-server/test/api/v1/tasks.rs b/crates/context-server/test/api/v1/tasks.rs index 3bef3acf..d5796d1f 100644 --- a/crates/context-server/test/api/v1/tasks.rs +++ b/crates/context-server/test/api/v1/tasks.rs @@ -286,3 +286,203 @@ async fn openapi_doc_includes_transition_endpoint() { // which panics if a referenced schema is not registered. let _app = routes::create_router(state, true); } + +// ============================================================================= +// List payload trimming +// ============================================================================= + +/// Create a project, task list, and task carrying a description. +/// +/// Returns the task list ID and the task ID. +async fn create_described_task( + app: &axum::Router, + title: &str, + description: &str, +) -> (String, String) { + let project = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/projects") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({"title": "Description Project"})).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let project_id = json_body(project).await["id"].as_str().unwrap().to_string(); + + let list = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/task-lists") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({ + "title": "Description List", + "project_id": project_id + })) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let list_id = json_body(list).await["id"].as_str().unwrap().to_string(); + + let task = app + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri(format!("/api/v1/task-lists/{}/tasks", list_id)) + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&json!({ + "title": title, + "description": description + })) + .unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let task_id = json_body(task).await["id"].as_str().unwrap().to_string(); + + (list_id, task_id) +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_tasks_omits_description_by_default() { + let app = test_app().await; + let (list_id, task_id) = create_described_task( + &app, + "Task with a description", + "A detailed specification that list results omit", + ) + .await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/v1/task-lists/{}/tasks", list_id)) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!(body["total"], 1); + assert_eq!(body["limit"], 50); + assert_eq!(body["offset"], 0); + assert_eq!(body["items"][0]["id"], task_id); + assert!( + body["items"][0]["description"].is_null(), + "list must omit descriptions, got: {}", + body["items"][0]["description"] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_tasks_include_description_returns_description() { + let app = test_app().await; + let (list_id, _task_id) = create_described_task( + &app, + "Task with a description", + "A detailed specification that list results omit", + ) + .await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!( + "/api/v1/task-lists/{}/tasks?include_description=true", + list_id + )) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["description"], + "A detailed specification that list results omit" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn list_tasks_search_returns_description() { + let app = test_app().await; + let (list_id, _task_id) = create_described_task( + &app, + "Rust Backend", + "Machine learning research implementation", + ) + .await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!( + "/api/v1/task-lists/{}/tasks?q=machine+learning", + list_id + )) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!(body["total"], 1); + assert_eq!( + body["items"][0]["description"], + "Machine learning research implementation" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_task_still_returns_description() { + let app = test_app().await; + let (_list_id, task_id) = create_described_task( + &app, + "Task with a description", + "A detailed specification that single-entity responses keep", + ) + .await; + + let response = app + .clone() + .oneshot( + Request::builder() + .uri(format!("/api/v1/tasks/{}", task_id)) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + let body = json_body(response).await; + assert_eq!( + body["description"], + "A detailed specification that single-entity responses keep" + ); +}