docs: tambah doc comment, logging, dan inline comments di semua 255 file

Meliputi:
- File-level //! doc comment: tujuan file, alur kerja, komponen utama
- Function-level /// doc comment: apa, parameter, return, flow, edge cases
- Struct/enum/trait /// doc comment: peran, field docs
- Tracing logging (tracing::info!/debug!/trace!/warn!/error!) di setiap fungsi
- Inline comments untuk variable dan branching logic penting
- Seluruh 8 crates di workspace: zesdex-backend, zesdex-cms, zesdex-entities,
  zesdex-iam, zesdex-infra, zesdex-ipc, zesdex-middleware, zesdex-utils
- Build: 0 errors, 242/242 tests passed
This commit is contained in:
asepharyana
2026-07-19 17:05:47 +07:00
parent 6680795ce7
commit 5aaedbf787
255 changed files with 5666 additions and 743 deletions
@@ -1,5 +1,16 @@
#![allow(dead_code)]
//! Hardcoded built-in subagent definitions (coder, reviewer, researcher, planner).
//!
//! These agents are always available regardless of user or session config.
//! They provide the default set of roles shipped with the application.
//!
//! ## Available agents
//! | Agent | Purpose | Key tools |
//! |-------|---------|-----------|
//! | coder | Write/edit code | read, write, edit, bash, lsp_* |
//! | reviewer | Review code for correctness/safety | read, grep, lsp_diagnostics |
//! | researcher | Search and summarise | read, grep, bash, search_web |
//! | planner | Break down tasks into steps | read, write, edit, bash, todo_* |
use crate::app::subagent::spawn::AgentDefinition;
/// Build the fixed list of built-in agent definitions shipped with zesdex.
@@ -34,6 +45,7 @@ pub fn builtin_agents() -> Vec<AgentDefinition> {
"lsp_completion".to_string(),
"lsp_disconnect".to_string(),
])
// Unlimited steps — the coder runs until the task is done.
.with_max_steps(usize::MAX),
AgentDefinition::new("reviewer".to_string(), "reviewer".to_string())
.with_system_prompt(
@@ -17,22 +17,32 @@ use crate::app::subagent::spawn::AgentDefinition;
pub fn load_global_agents() -> Vec<AgentDefinition> {
let store = crate::model::store::Store::new();
let agents_dir = store.base_dir.join("agents");
tracing::debug!(dir = %agents_dir.display(), "load_global_agents");
if !agents_dir.exists() {
tracing::debug!("load_global_agents — agents dir does not exist");
return Vec::new();
}
let mut agents = Vec::new();
if let Ok(entries) = std::fs::read_dir(&agents_dir) {
for entry in entries.flatten() {
let path = entry.path();
// Only process `.json` files; skip subdirectories, hidden files, etc.
if path.extension().is_some_and(|e| e == "json") {
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(def) = serde_json::from_str::<AgentDefinition>(&content) {
tracing::debug!(agent = %def.name, "load_global_agents — loaded");
agents.push(def);
} else {
tracing::warn!(file = %path.display(), "load_global_agents — failed to parse JSON");
}
} else {
tracing::warn!(file = %path.display(), "load_global_agents — failed to read file");
}
}
}
}
tracing::info!(count = agents.len(), "load_global_agents — done");
agents
}
@@ -56,13 +66,17 @@ pub fn save_global_agent(def: &AgentDefinition) -> anyhow::Result<()> {
let path = agents_dir.join(format!("{}.json", def.name));
let tmp = agents_dir.join(format!("{}.json.tmp", def.name));
let content = serde_json::to_string_pretty(def)?;
// Write to temp file first, then fsync + rename for crash-safe atomic write.
tracing::debug!(agent = %def.name, "save_global_agent — writing");
std::fs::write(&tmp, content)?;
let f = std::fs::File::open(&tmp)?;
f.sync_all()?;
std::fs::rename(&tmp, path)?;
// Sync parent directory so the rename is durable on filesystems like ext4.
if let Some(parent) = agents_dir.parent() {
let _ = std::fs::File::open(parent).and_then(|d| d.sync_all());
}
tracing::info!(agent = %def.name, "save_global_agent — saved");
Ok(())
}
@@ -76,9 +90,19 @@ pub fn save_global_agent(def: &AgentDefinition) -> anyhow::Result<()> {
pub fn remove_global_agent(name: &str) -> anyhow::Result<bool> {
let store = crate::model::store::Store::new();
let path = store.base_dir.join("agents").join(format!("{name}.json"));
tracing::debug!(%name, path = %path.display(), "remove_global_agent");
match std::fs::remove_file(&path) {
Ok(_) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
Ok(_) => {
tracing::info!(%name, "remove_global_agent — removed");
Ok(true)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!(%name, "remove_global_agent — not found");
Ok(false)
}
Err(e) => {
tracing::error!(%name, error = %e, "remove_global_agent — failed");
Err(e.into())
}
}
}
@@ -1,5 +1,15 @@
//! Agent definition sources: built-in defaults, global (user-wide), and
//! per-session overrides.
//!
//! Agent definitions control the system prompt, tool set, and configuration
//! for each agent. The resolution order (lowest to highest priority) is:
//!
//! 1. `builtin` — hardcoded default agent shipped with the application.
//! 2. `global` — user-wide overrides stored in the config directory.
//! 3. `session` — per-session overrides stored in the session directory.
//!
//! This layered approach lets users customise agents globally and then
//! fine-tune per-session without modifying the built-in defaults.
pub mod builtin;
pub mod global;
pub mod session;
@@ -1,6 +1,10 @@
#![allow(dead_code)]
//! Load, save, add, and remove agent definitions scoped to a single
//! session (`<session_dir>/agents.json`).
//!
//! Session-scoped agents override global and built-in agents of the same
//! name, letting users define custom personalities for specific tasks
//! without affecting other sessions.
use crate::app::subagent::spawn::AgentDefinition;
use std::path::Path;
@@ -17,15 +21,25 @@ use std::path::Path;
/// exist or the file is malformed.
pub fn load_session_agents(session_dir: &Path) -> Vec<AgentDefinition> {
let agents_file = session_dir.join("agents.json");
tracing::debug!(file = %agents_file.display(), "load_session_agents");
if !agents_file.exists() {
tracing::debug!("load_session_agents — file does not exist");
return Vec::new();
}
match std::fs::read_to_string(&agents_file) {
Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
tracing::warn!("[session] failed to parse agents.json: {}", e);
Ok(content) => {
let agents: Vec<AgentDefinition> = serde_json::from_str(&content).unwrap_or_else(|e| {
tracing::warn!("load_session_agents — failed to parse agents.json: {}", e);
Vec::new()
});
tracing::debug!(count = agents.len(), "load_session_agents — loaded");
agents
}
Err(e) => {
tracing::warn!(error = %e, "load_session_agents — failed to read");
Vec::new()
}),
Err(_) => Vec::new(),
}
}
}
@@ -41,11 +55,16 @@ pub fn save_session_agents(session_dir: &Path, agents: &[AgentDefinition]) -> an
let agents_file = session_dir.join("agents.json");
let tmp = session_dir.join("agents.json.tmp");
let content = serde_json::to_string_pretty(agents)?;
tracing::debug!(count = agents.len(), "save_session_agents — writing");
// Atomic write: temp file → fsync → rename → fsync parent dir
std::fs::write(&tmp, content)?;
let f = std::fs::File::open(&tmp)?;
f.sync_all()?;
std::fs::rename(&tmp, agents_file)?;
let _ = std::fs::File::open(session_dir).and_then(|d| d.sync_all());
tracing::info!(count = agents.len(), "save_session_agents — saved");
Ok(())
}
@@ -58,7 +77,9 @@ pub fn save_session_agents(session_dir: &Path, agents: &[AgentDefinition]) -> an
///
/// Return: `Ok(())` on success, propagating any load/save error.
pub fn add_session_agent(session_dir: &Path, def: &AgentDefinition) -> anyhow::Result<()> {
tracing::debug!(agent = %def.name, "add_session_agent");
let mut agents = load_session_agents(session_dir);
// Remove existing definition with the same name (upsert semantics)
agents.retain(|a| a.name != def.name);
agents.push(def.clone());
save_session_agents(session_dir, &agents)
@@ -71,12 +92,15 @@ pub fn add_session_agent(session_dir: &Path, def: &AgentDefinition) -> anyhow::R
/// Return: `Ok(true)` if removed, `Ok(false)` if not found, `Err` on
/// load/save failure.
pub fn remove_session_agent(session_dir: &Path, name: &str) -> anyhow::Result<bool> {
tracing::debug!(%name, "remove_session_agent");
let mut agents = load_session_agents(session_dir);
let before = agents.len();
agents.retain(|a| a.name != name);
if agents.len() == before {
tracing::debug!(%name, "remove_session_agent — not found");
return Ok(false);
}
save_session_agents(session_dir, &agents)?;
tracing::info!(%name, "remove_session_agent — removed");
Ok(true)
}
+13 -3
View File
@@ -1,10 +1,20 @@
//! Re-exports from `zesdex-entities` crate under the original module paths,
//! plus local sub-modules (agent_def, msglog) that weren't extracted.
//! Data-model layer for the zesdex backend.
//!
//! This module re-exports types from the `zesdex-entities` workspace crate
//! under their original `crate::model::*` paths for backward compatibility,
//! and defines two local sub-modules that haven't been extracted:
//!
//! - `agent_def` — agent definition model (built-in, global, session scopes)
//! - `msglog` — SQLite-backed message-log persistence (schema, insert, blobs)
//!
//! ## Re-exports
//! | Path | Source |
//! |------|--------|
//! | `crate::model::store::*` | `zesdex_entities::domain::common::store` |
// Module re-exports matching original `crate::model::*` paths
pub mod store {
pub use zesdex_entities::domain::common::store::*;
}
pub mod agent_def;
/// Local modules not extracted to workspace crates
pub mod msglog;
@@ -8,6 +8,9 @@ use rusqlite::{params, Connection};
/// Flow: compute current timestamp -> `INSERT OR REPLACE` into `blobs`
/// keyed on `(session_id, blob_key)`.
///
/// `INSERT OR REPLACE` is used so re-uploading the same key overwrites
/// the previous blob rather than failing on the UNIQUE constraint.
///
/// Return: `Ok(())` on success, or the underlying `SQLite` error.
pub fn store_blob(
conn: &Connection,
@@ -17,10 +20,12 @@ pub fn store_blob(
mime_type: Option<&str>,
) -> Result<()> {
let created_at = chrono::Utc::now().timestamp_millis();
tracing::debug!(%session_id, %blob_key, size = data.len(), "store_blob");
conn.execute(
"INSERT OR REPLACE INTO blobs (session_id, blob_key, data, mime_type, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",
params![session_id, blob_key, data, mime_type, created_at],
)?;
tracing::info!(%session_id, %blob_key, "store_blob — stored");
Ok(())
}
@@ -33,15 +38,25 @@ pub fn retrieve_blob(
session_id: &str,
blob_key: &str,
) -> Result<Option<Vec<u8>>> {
tracing::debug!(%session_id, %blob_key, "retrieve_blob");
let result = conn.query_row(
"SELECT data FROM blobs WHERE session_id = ?1 AND blob_key = ?2",
params![session_id, blob_key],
|row| row.get(0),
|row| row.get::<_, Vec<u8>>(0),
);
match result {
Ok(data) => Ok(Some(data)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.into()),
Ok(data) => {
tracing::debug!(%session_id, %blob_key, size = data.len(), "retrieve_blob — found");
Ok(Some(data))
}
Err(rusqlite::Error::QueryReturnedNoRows) => {
tracing::debug!(%session_id, %blob_key, "retrieve_blob — not found");
Ok(None)
}
Err(e) => {
tracing::error!(%session_id, %blob_key, error = %e, "retrieve_blob — query failed");
Err(e.into())
}
}
}
@@ -50,6 +65,7 @@ pub fn retrieve_blob(
/// Return: `Ok(Vec<String>)` of keys ordered by `created_at`, or the
/// underlying `SQLite` error.
pub fn list_blob_keys(conn: &Connection, session_id: &str) -> Result<Vec<String>> {
tracing::debug!(%session_id, "list_blob_keys");
let mut stmt =
conn.prepare("SELECT blob_key FROM blobs WHERE session_id = ?1 ORDER BY created_at ASC")?;
let rows = stmt.query_map(params![session_id], |row| row.get::<_, String>(0))?;
@@ -57,5 +73,6 @@ pub fn list_blob_keys(conn: &Connection, session_id: &str) -> Result<Vec<String>
for row in rows {
keys.push(row?);
}
tracing::debug!(%session_id, count = keys.len(), "list_blob_keys — done");
Ok(keys)
}
@@ -25,9 +25,13 @@ pub fn insert_message(conn: &Connection, session_id: &str, msg: &ChatMessage) ->
Role::System => "system",
Role::Tool => "tool",
};
tracing::debug!(%session_id, %role_str, content_len = content.map_or(0, str::len), "insert_message");
conn.execute(
"INSERT INTO messages (session_id, role, content, tool_call_id, tool_name, tool_arguments, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![session_id, role_str, content, tool_call_id, tool_name, tool_arguments, created_at],
)?;
Ok(conn.last_insert_rowid())
let rowid = conn.last_insert_rowid();
tracing::info!(%session_id, %role_str, rowid, "insert_message — inserted");
Ok(rowid)
}
@@ -1,5 +1,14 @@
//! SQLite-backed message log: per-session `messages.sqlite` storing chat
//! messages, blobs, and archive/summary metadata.
//!
//! ## Tables
//! | Table | Purpose |
//! |-------|---------|
//! | `messages` | Individual chat messages (role, content, tool calls) |
//! | `archives` | Session archive metadata (title, model, summary) |
//! | `blobs` | Binary attachments keyed by `(session_id, blob_key)` |
//!
//! All writes use WAL mode for concurrent reads without blocking.
pub mod blobs;
pub mod insert;
pub mod schema;
@@ -17,12 +26,16 @@ pub use insert::insert_message;
/// fails.
pub fn open_or_create(session_dir: &std::path::Path) -> anyhow::Result<rusqlite::Connection> {
let path = session_dir.join("messages.sqlite");
tracing::debug!(?path, "open_or_create");
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let conn = rusqlite::Connection::open(&path)?;
// WAL journal allows concurrent reads without blocking on writes.
conn.execute_batch("PRAGMA journal_mode = WAL;")?;
conn.execute_batch("PRAGMA busy_timeout = 5000;")?;
schema::init_schema(&conn)?;
tracing::info!("open_or_create — database ready");
Ok(conn)
}
@@ -1,4 +1,17 @@
//! `SQLite` schema definition for the message log database.
//!
//! ## Schema overview
//!
//! ```text
//! archives (1) ──── (N) messages
//! │
//! └── (N) blobs
//! ```
//!
//! `messages` has a `FOREIGN KEY` on `archives(session_id)`, but the
//! relationship is soft — the archive row may not exist yet when the first
//! messages are inserted (messages are inserted incrementally during a
//! turn, while the archive is created only on session close).
use anyhow::Result;
use rusqlite::Connection;
@@ -10,6 +23,7 @@ use rusqlite::Connection;
///
/// Return: `Ok(())` on success, or the underlying `SQLite` error.
pub fn init_schema(conn: &Connection) -> Result<()> {
tracing::debug!("init_schema — creating tables if not exists");
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
conn.execute_batch(
"
@@ -52,5 +66,6 @@ pub fn init_schema(conn: &Connection) -> Result<()> {
);
",
)?;
tracing::info!("init_schema — schema ready");
Ok(())
}