Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(snapshot): support path-filtered commit history (#3271)

Haoyu Zhangef4d97ebe302
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index d79dfc26d..143585acb 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1610,11 +1610,21 @@ impl HttpClient {
self.post("/api/v1/snapshot/restore", req).await
}
- pub async fn snapshot_log(&self, branch: &str, limit: u32) -> Result<Value> {
- let params = vec![
+ pub async fn snapshot_log(
+ &self,
+ branch: &str,
+ limit: u32,
+ paths: Option<&[String]>,
+ ) -> Result<Value> {
+ let mut params = vec![
("branch".to_string(), branch.to_string()),
("limit".to_string(), limit.to_string()),
];
+ if let Some(paths) = paths {
+ for path in paths {
+ params.push(("paths".to_string(), path.to_string()));
+ }
+ }
self.get("/api/v1/snapshot/log", &params).await
}
diff --git a/crates/ov_cli/src/commands/snapshot.rs b/crates/ov_cli/src/commands/snapshot.rs
index cc60d9d0a..3d119f281 100644
--- a/crates/ov_cli/src/commands/snapshot.rs
+++ b/crates/ov_cli/src/commands/snapshot.rs
@@ -63,8 +63,12 @@ pub async fn dispatch(
let result = client.snapshot_show(&target_ref, path.as_deref()).await?;
handle_show(result, out_path, output_format, compact)
}
- SnapshotCmd::Log { branch, limit } => {
- let value = client.snapshot_log(&branch, limit).await?;
+ SnapshotCmd::Log {
+ branch,
+ limit,
+ paths,
+ } => {
+ let value = client.snapshot_log(&branch, limit, paths.as_deref()).await?;
print_log(&value, output_format, compact);
Ok(())
}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 91e227e86..01345281a 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -1131,6 +1131,9 @@ pub(crate) enum SnapshotCmd {
branch: String,
#[arg(long, default_value_t = 20)]
limit: u32,
+ /// Show only commits touching any of these viking:// URIs (comma-separated); accepts files and directories.
+ #[arg(long, value_delimiter = ',')]
+ paths: Option<Vec<String>>,
},
/// Get the account .ovgitignore content
IgnoreGet,
diff --git a/crates/ragfs-python/src/git.rs b/crates/ragfs-python/src/git.rs
index b84095403..da77eef13 100644
--- a/crates/ragfs-python/src/git.rs
+++ b/crates/ragfs-python/src/git.rs
@@ -159,44 +159,74 @@ fn build_s3_service(
Ok((object_store, ref_store, index_store))
}
-/// Map a `GitError` to the appropriate Python exception.
-///
-/// Loads exception classes from the `openviking.pyagfs` module. When the
-/// module is not importable (e.g. during unit tests), falls back to
-/// `PyRuntimeError` with the same message.
-pub fn map_git_error(py: Python<'_>, e: ragfs::git::GitError) -> PyErr {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum GitErrorMapping {
+ PythonException(&'static str),
+ RestoreWritebackPartial,
+ RuntimeFallback,
+}
+
+fn classify_git_error(e: &ragfs::git::GitError) -> GitErrorMapping {
use ragfs::git::{GitError, ObjectStoreError, RefStoreError};
- let msg = e.to_string();
+
match e {
- GitError::FeatureDisabled => new_py_err_pub(py, "AGFSNotSupportedError", msg),
- GitError::ConcurrentCommit { .. } => new_py_err_pub(py, "GitConcurrentCommitError", msg),
- GitError::PathNotFound(_) => new_py_err_pub(py, "AGFSNotFoundError", msg),
- GitError::PathIsDirectory(_) => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::SubtreeNotFoundInCommit { .. } => new_py_err_pub(py, "AGFSNotFoundError", msg),
- GitError::InvalidAccountId(_) => new_py_err_pub(py, "AGFSInvalidPathError", msg),
- GitError::InvalidProjectDir(_) => new_py_err_pub(py, "AGFSInvalidPathError", msg),
- GitError::InvalidPath(_) => new_py_err_pub(py, "AGFSInvalidPathError", msg),
- GitError::BlobTooLarge { .. } => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::TooManyFiles { .. } => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::IgnoreFileTooLarge { .. } => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::InvalidIgnoreFile { .. } => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::CorruptedObject(_) => new_py_err_pub(py, "AGFSInternalError", msg),
- GitError::RefStore(RefStoreError::NotFound(_)) => {
- new_py_err_pub(py, "AGFSNotFoundError", msg)
+ GitError::FeatureDisabled => GitErrorMapping::PythonException("AGFSNotSupportedError"),
+ GitError::ConcurrentCommit { .. } => {
+ GitErrorMapping::PythonException("GitConcurrentCommitError")
}
- GitError::RefStore(RefStoreError::Conflict { .. }) => {
- new_py_err_pub(py, "GitConcurrentCommitError", msg)
+ GitError::PathNotFound(_) => GitErrorMapping::PythonException("AGFSNotFoundError"),
+ GitError::PathIsDirectory(_) => {
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ }
+ GitError::SubtreeNotFoundInCommit { .. } => {
+ GitErrorMapping::PythonException("AGFSNotFoundError")
}
- GitError::OidPrefixNotFound { .. } => new_py_err_pub(py, "AGFSNotFoundError", msg),
- GitError::AmbiguousOid { .. } => new_py_err_pub(py, "AGFSInvalidOperationError", msg),
- GitError::ObjectStore(ObjectStoreError::NotFound(_)) => {
- new_py_err_pub(py, "AGFSNotFoundError", msg)
+ GitError::InvalidAccountId(_)
+ | GitError::InvalidProjectDir(_)
+ | GitError::InvalidPath(_) => GitErrorMapping::PythonException("AGFSInvalidPathError"),
+ GitError::BlobTooLarge { .. }
+ | GitError::TooManyFiles { .. }
+ | GitError::TooManyLogPaths { .. }
+ | GitError::LogPathTooDeep { .. }
+ | GitError::LogScanLimitExceeded { .. }
+ | GitError::IgnoreFileTooLarge { .. }
+ | GitError::InvalidIgnoreFile { .. }
+ | GitError::AmbiguousOid { .. } => {
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
}
- GitError::RestoreWritebackPartial(p) => writeback_partial_to_pyerr(py, *p, msg),
+ GitError::CorruptedObject(_) => GitErrorMapping::PythonException("AGFSInternalError"),
+ GitError::RefStore(RefStoreError::NotFound(_))
+ | GitError::OidPrefixNotFound { .. }
+ | GitError::ObjectStore(ObjectStoreError::NotFound(_)) => {
+ GitErrorMapping::PythonException("AGFSNotFoundError")
+ }
+ GitError::RefStore(RefStoreError::Conflict { .. }) => {
+ GitErrorMapping::PythonException("GitConcurrentCommitError")
+ }
+ GitError::RestoreWritebackPartial(_) => GitErrorMapping::RestoreWritebackPartial,
GitError::ObjectStore(_)
| GitError::RefStore(_)
| GitError::Vfs(_)
- | GitError::Other(_) => PyRuntimeError::new_err(msg),
+ | GitError::Other(_) => GitErrorMapping::RuntimeFallback,
+ }
+}
+
+/// Map a `GitError` to the appropriate Python exception.
+///
+/// Loads exception classes from the `openviking.pyagfs` module. When the
+/// module is not importable (e.g. during unit tests), falls back to
+/// `PyRuntimeError` with the same message.
+pub fn map_git_error(py: Python<'_>, e: ragfs::git::GitError) -> PyErr {
+ let msg = e.to_string();
+ match classify_git_error(&e) {
+ GitErrorMapping::PythonException(class_name) => new_py_err_pub(py, class_name, msg),
+ GitErrorMapping::RestoreWritebackPartial => {
+ let ragfs::git::GitError::RestoreWritebackPartial(payload) = e else {
+ unreachable!("restore classification must carry a restore payload")
+ };
+ writeback_partial_to_pyerr(py, *payload, msg)
+ }
+ GitErrorMapping::RuntimeFallback => PyRuntimeError::new_err(msg),
}
}
@@ -263,8 +293,8 @@ pub fn new_py_err_pub(py: Python<'_>, name: &str, msg: String) -> PyErr {
use pyo3::types::{PyBytes, PyDict, PyList};
use ragfs::git::{
- Actor, CommitRequest, CommitResponse, RestoreDiff, RestoreRequest, RestoreResponse,
- RestoreWritebackPartial, ShowRequest, ShowResponse,
+ Actor, CommitRequest, CommitResponse, LogEntry, LogRequest, RestoreDiff, RestoreRequest,
+ RestoreResponse, RestoreWritebackPartial, ShowRequest, ShowResponse,
};
// ---------- request parsers ----------
@@ -296,6 +326,15 @@ fn optional_bool(kwargs: &Bound<PyDict>, key: &str, default: bool) -> PyResult<b
}
}
+fn optional_usize(kwargs: &Bound<PyDict>, key: &str, default: usize) -> PyResult<usize> {
+ match kwargs.get_item(key)? {
+ Some(v) if !v.is_none() => v
+ .extract::<usize>()
+ .map_err(|_| PyValueError::new_err(format!("kwarg {} must be a non-negative integer", key))),
+ _ => Ok(default),
+ }
+}
+
fn optional_string_list(kwargs: &Bound<PyDict>, key: &str) -> PyResult<Option<Vec<String>>> {
match kwargs.get_item(key)? {
Some(v) if !v.is_none() => v
@@ -338,6 +377,15 @@ pub fn parse_show_request(kwargs: &Bound<PyDict>) -> PyResult<ShowRequest> {
})
}
+pub fn parse_log_request(kwargs: &Bound<PyDict>) -> PyResult<LogRequest> {
+ Ok(LogRequest {
+ account: require_str(kwargs, "account")?,
+ branch: require_str(kwargs, "branch")?,
+ limit: optional_usize(kwargs, "limit", 20)?,
+ paths: optional_string_list(kwargs, "paths")?,
+ })
+}
+
// ---------- response converters ----------
fn oid_hex(oid: &gix_hash::ObjectId) -> String {
@@ -462,6 +510,25 @@ pub fn show_response_to_pydict(py: Python<'_>, resp: ShowResponse) -> PyResult<P
Ok(d.into_any().unbind())
}
+pub fn log_entries_to_pylist(py: Python<'_>, entries: Vec<LogEntry>) -> PyResult<Py<PyAny>> {
+ let list = PyList::empty(py);
+ for entry in entries {
+ let d = PyDict::new(py);
+ d.set_item("oid", oid_hex(&entry.oid))?;
+ d.set_item("tree", oid_hex(&entry.tree))?;
+ let parents = PyList::empty(py);
+ for parent in &entry.parents {
+ parents.append(oid_hex(parent))?;
+ }
+ d.set_item("parents", parents)?;
+ d.set_item("author", actor_to_dict(py, &entry.author)?)?;
+ d.set_item("committer", actor_to_dict(py, &entry.committer)?)?;
+ d.set_item("message", entry.message)?;
+ list.append(d)?;
+ }
+ Ok(list.into_any().unbind())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -630,6 +697,75 @@ mod tests {
});
}
+ #[test]
+ fn map_git_error_log_budgets_preserve_messages() {
+ pyo3::prepare_freethreaded_python();
+ Python::attach(|py| {
+ let cases = [
+ GitError::TooManyLogPaths {
+ count: 33,
+ limit: 32,
+ },
+ GitError::LogPathTooDeep {
+ path: "resources/deep".into(),
+ depth: 65,
+ limit: 64,
+ },
+ GitError::LogScanLimitExceeded {
+ scanned: 1_000,
+ max_scanned: 1_000,
+ matched: 0,
+ requested: 1,
+ },
+ ];
+
+ for case in cases {
+ let expected = case.to_string();
+ let mapped = map_git_error(py, case);
+ assert!(mapped.to_string().contains(&expected));
+ }
+ });
+ }
+
+ #[test]
+ fn map_git_error_log_too_many_paths_classification() {
+ let error = GitError::TooManyLogPaths {
+ count: 33,
+ limit: 32,
+ };
+ assert_eq!(
+ classify_git_error(&error),
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ );
+ }
+
+ #[test]
+ fn map_git_error_log_path_too_deep_classification() {
+ let error = GitError::LogPathTooDeep {
+ path: "resources/docs/deep.md".into(),
+ depth: 65,
+ limit: 64,
+ };
+ assert_eq!(
+ classify_git_error(&error),
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ );
+ }
+
+ #[test]
+ fn map_git_error_log_scan_limit_exceeded_classification() {
+ let error = GitError::LogScanLimitExceeded {
+ scanned: 1_000,
+ max_scanned: 1_000,
+ matched: 3,
+ requested: 10,
+ };
+ assert_eq!(
+ classify_git_error(&error),
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ );
+ }
+
use pyo3::types::PyDict;
#[test]
@@ -754,6 +890,28 @@ mod tests {
});
}
+ #[test]
+ fn parse_log_request_with_paths() {
+ pyo3::prepare_freethreaded_python();
+ Python::attach(|py| {
+ let kwargs = PyDict::new(py);
+ kwargs.set_item("account", "a").unwrap();
+ kwargs.set_item("branch", "main").unwrap();
+ kwargs.set_item("limit", 10).unwrap();
+ kwargs
+ .set_item("paths", vec!["resources/a.md", "resources/docs"])
+ .unwrap();
+ let req = parse_log_request(&kwargs).expect("parses");
+ assert_eq!(req.account, "a");
+ assert_eq!(req.branch, "main");
+ assert_eq!(req.limit, 10);
+ assert_eq!(
+ req.paths.as_ref().unwrap(),
+ &vec!["resources/a.md".to_string(), "resources/docs".to_string()]
+ );
+ });
+ }
+
#[test]
fn commit_response_created_to_dict() {
pyo3::prepare_freethreaded_python();
@@ -790,6 +948,43 @@ mod tests {
});
}
+ #[test]
+ fn log_entries_to_pylist_includes_commit_metadata() {
+ pyo3::prepare_freethreaded_python();
+ Python::attach(|py| {
+ let oid = gix_hash::ObjectId::null(gix_hash::Kind::Sha1);
+ let actor = ragfs::git::Actor {
+ name: "alice".to_string(),
+ email: "[email protected]".to_string(),
+ time_seconds: 1,
+ tz_offset_seconds: 0,
+ };
+ let entries = vec![ragfs::git::LogEntry {
+ oid,
+ tree: oid,
+ parents: vec![oid],
+ author: actor.clone(),
+ committer: actor,
+ message: "subject\n\nbody".to_string(),
+ }];
+ let obj = log_entries_to_pylist(py, entries).expect("converts");
+ let list = obj.bind(py).downcast::<PyList>().unwrap();
+ assert_eq!(list.len(), 1);
+ let first = list.get_item(0).unwrap();
+ let d = first.downcast::<PyDict>().unwrap();
+ assert_eq!(
+ d.get_item("oid").unwrap().unwrap().extract::<String>().unwrap(),
+ oid.to_hex().to_string()
+ );
+ assert_eq!(
+ d.get_item("message").unwrap().unwrap().extract::<String>().unwrap(),
+ "subject\n\nbody"
+ );
+ let parents = d.get_item("parents").unwrap().unwrap();
+ assert_eq!(parents.downcast::<PyList>().unwrap().len(), 1);
+ });
+ }
+
#[test]
fn show_response_blob_to_dict_carries_bytes() {
pyo3::prepare_freethreaded_python();
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index f0363764d..f5d7458ba 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -1060,6 +1060,24 @@ impl RAGFSBindingClient {
git::show_response_to_pydict(py, resp)
}
+ /// Walk snapshot history, optionally filtered to commits touching paths.
+ #[pyo3(signature = (**kwargs))]
+ fn git_log(
+ &self,
+ py: Python<'_>,
+ kwargs: Option<&Bound<'_, PyDict>>,
+ ) -> PyResult<Py<PyAny>> {
+ let svc = self.git_service.clone().ok_or_else(|| {
+ git::new_py_err_pub(py, "AGFSNotSupportedError", "git feature disabled".into())
+ })?;
+ let empty = PyDict::new(py);
+ let kw = kwargs.unwrap_or(&empty);
+ let req = git::parse_log_request(kw)?;
+ let resp = py_detach_blocking(py, move || self.rt.block_on(svc.log(req)))
+ .map_err(|e| git::map_git_error(py, e))?;
+ git::log_entries_to_pylist(py, resp)
+ }
+
/// Get client capabilities.
fn get_capabilities(&self) -> PyResult<HashMap<String, Py<PyAny>>> {
Python::attach(|py| {
diff --git a/crates/ragfs/src/git/error.rs b/crates/ragfs/src/git/error.rs
index a8895e472..80bd612eb 100644
--- a/crates/ragfs/src/git/error.rs
+++ b/crates/ragfs/src/git/error.rs
@@ -134,6 +134,29 @@ pub enum GitError {
#[error("too many files: {count} exceeds limit {limit}")]
TooManyFiles { count: usize, limit: usize },
+ /// Too many unique paths in a filtered log request.
+ #[error("too many log filter paths: {count} exceeds limit {limit}")]
+ TooManyLogPaths { count: usize, limit: usize },
+
+ /// A filtered log path has too many tree components.
+ #[error("log filter path {path:?} has depth {depth}, exceeds limit {limit}")]
+ LogPathTooDeep {
+ path: String,
+ depth: usize,
+ limit: usize,
+ },
+
+ /// Filtered history still has uninspected commits after its scan budget.
+ #[error(
+ "snapshot log scan limit exceeded: scanned {scanned}/{max_scanned} commits, matched {matched}/{requested}"
+ )]
+ LogScanLimitExceeded {
+ scanned: usize,
+ max_scanned: usize,
+ matched: usize,
+ requested: usize,
+ },
+
/// `.ovgitignore` exceeds the configured size limit.
#[error("ignore file too large: {path} is {size} bytes, limit {max} bytes")]
IgnoreFileTooLarge {
diff --git a/crates/ragfs/src/git/mod.rs b/crates/ragfs/src/git/mod.rs
index cabbbe771..ff9db954f 100644
--- a/crates/ragfs/src/git/mod.rs
+++ b/crates/ragfs/src/git/mod.rs
@@ -49,8 +49,8 @@ pub use ref_store::RefStore;
pub use service::GitService;
pub use tree_builder::{flatten, lookup, TreeEditor};
pub use types::{
- Actor, CommitRequest, CommitResponse, IndexEntry, RestoreDiff, RestoreRequest,
- RestoreResponse, RestoreWritebackPartial, ShowRequest, ShowResponse,
+ Actor, CommitRequest, CommitResponse, IndexEntry, LogEntry, LogRequest, RestoreDiff,
+ RestoreRequest, RestoreResponse, RestoreWritebackPartial, ShowRequest, ShowResponse,
};
// Re-exports from backends
diff --git a/crates/ragfs/src/git/service.rs b/crates/ragfs/src/git/service.rs
index 49c516c41..818050dad 100644
--- a/crates/ragfs/src/git/service.rs
+++ b/crates/ragfs/src/git/service.rs
@@ -29,11 +29,15 @@ use crate::git::{
object_store::ObjectStore,
ref_store::RefStore,
types::{
- CommitRequest, CommitResponse, IndexEntry, RestoreRequest, RestoreResponse, ShowRequest,
- ShowResponse,
+ CommitRequest, CommitResponse, IndexEntry, LogEntry, LogRequest, RestoreRequest,
+ RestoreResponse, ShowRequest, ShowResponse,
},
};
+const MAX_LOG_COMMITS_SCANNED: usize = 1_000;
+const MAX_LOG_FILTER_PATHS: usize = 32;
+const MAX_LOG_PATH_DEPTH: usize = 64;
+
/// `GitService` orchestrates the full commit pipeline against a `FileSystem`
/// (the working tree), an `ObjectStore`, and a `RefStore`. An optional
/// `IndexStore` enables Fast Path 1 — the persistent stat cache that lets
@@ -821,6 +825,99 @@ impl GitService {
}
}
+ /// Walk commit history newest-first, optionally returning only commits
+ /// that changed at least one requested path relative to their first parent.
+ ///
+ /// `limit` counts returned commits, not commits inspected. With `paths`
+ /// set, traversal continues through unrelated commits until `limit`
+ /// matching commits are collected or history ends. Filtered traversal
+ /// returns `GitError::LogScanLimitExceeded` when history remains after
+ /// 1,000 candidate commits.
+ pub async fn log(&self, mut req: LogRequest) -> Result<Vec<LogEntry>, GitError> {
+ validate_account_id(&req.account)?;
+ req.paths = normalize_log_paths(req.paths)?;
+ if req.limit == 0 {
+ return Ok(Vec::new());
+ }
+
+ self.log_with_scan_limit(req, MAX_LOG_COMMITS_SCANNED).await
+ }
+
+ async fn log_with_scan_limit(
+ &self,
+ req: LogRequest,
+ max_commits_scanned: usize,
+ ) -> Result<Vec<LogEntry>, GitError> {
+ debug_assert!(max_commits_scanned > 0);
+
+ let mut next_oid = Some(
+ resolve_ref(
+ self.ref_store.as_ref(),
+ self.object_store.as_ref(),
+ &req.account,
+ &req.branch,
+ )
+ .await?,
+ );
+ let filtered_paths = req.paths.as_deref();
+ let mut next_meta: Option<CommitMeta> = None;
+ let mut scanned = 0usize;
+ let mut out = Vec::new();
+
+ while let Some(commit_oid) = next_oid {
+ let meta = match next_meta.take() {
+ Some(meta) => meta,
+ None => {
+ load_commit_meta(self.object_store.as_ref(), &req.account, &commit_oid).await?
+ }
+ };
+ let parent_oid = meta.parents.first().copied();
+
+ let parent_meta = match (filtered_paths, parent_oid) {
+ (Some(_), Some(parent_oid)) => Some(
+ load_commit_meta(self.object_store.as_ref(), &req.account, &parent_oid).await?,
+ ),
+ _ => None,
+ };
+
+ let include = match filtered_paths {
+ None => true,
+ Some(paths) => {
+ scanned += 1;
+ commit_touches_any_path(
+ self.object_store.as_ref(),
+ &req.account,
+ meta.tree,
+ parent_meta.as_ref().map(|parent| parent.tree),
+ paths,
+ )
+ .await?
+ }
+ };
+
+ next_oid = parent_oid;
+ next_meta = parent_meta;
+
+ if include {
+ out.push(log_entry_from_meta(commit_oid, meta));
+ if out.len() >= req.limit {
+ return Ok(out);
+ }
+ }
+
+ if filtered_paths.is_some() && scanned >= max_commits_scanned && next_oid.is_some() {
+ return Err(GitError::LogScanLimitExceeded {
+ scanned,
+ max_scanned: max_commits_scanned,
+ matched: out.len(),
+ requested: req.limit,
+ });
+ }
+ }
+
+ Ok(out)
+ }
+
/// Restore a subtree at `project_dir` to the state it had in `source_commit`,
/// producing a new commit whose parent is the **current HEAD** (not
/// `source_commit`). HEAD always moves forward.
@@ -1307,6 +1404,89 @@ async fn load_commit_meta(
})
}
+fn log_entry_from_meta(oid: ObjectId, meta: CommitMeta) -> LogEntry {
+ LogEntry {
+ oid,
+ tree: meta.tree,
+ parents: meta.parents,
+ author: meta.author,
+ committer: meta.committer,
+ message: meta.message,
+ }
+}
+
+fn normalize_log_paths(paths: Option<Vec<String>>) -> Result<Option<Vec<String>>, GitError> {
+ let Some(mut paths) = paths else {
+ return Ok(None);
+ };
+
+ for path in &paths {
+ validate_relative_path(path)?;
+ }
+
+ let mut seen = HashSet::new();
+ paths.retain(|path| seen.insert(path.clone()));
+
+ if paths.len() > MAX_LOG_FILTER_PATHS {
+ return Err(GitError::TooManyLogPaths {
+ count: paths.len(),
+ limit: MAX_LOG_FILTER_PATHS,
+ });
+ }
+
+ for path in &paths {
+ let depth = path.split('/').count();
+ if depth > MAX_LOG_PATH_DEPTH {
+ return Err(GitError::LogPathTooDeep {
+ path: path.clone(),
+ depth,
+ limit: MAX_LOG_PATH_DEPTH,
+ });
+ }
+ }
+
+ Ok((!paths.is_empty()).then_some(paths))
+}
+
+async fn commit_touches_any_path(
+ store: &dyn ObjectStore,
+ account: &str,
+ current_tree: ObjectId,
+ parent_tree: Option<ObjectId>,
+ paths: &[String],
+) -> Result<bool, GitError> {
+ let mut current_cache = crate::git::tree_builder::TreeLookupCache::new();
+ let mut parent_cache = crate::git::tree_builder::TreeLookupCache::new();
+
+ for path in paths {
+ let current = crate::git::tree_builder::lookup_cached(
+ store,
+ account,
+ current_tree,
+ path,
+ &mut current_cache,
+ )
+ .await?;
+ let parent = match parent_tree {
+ Some(tree) => {
+ crate::git::tree_builder::lookup_cached(
+ store,
+ account,
+ tree,
+ path,
+ &mut parent_cache,
+ )
+ .await?
+ }
+ None => None,
+ };
+ if current != parent {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
/// Resolve an abbreviated commit OID (4–39 hex chars) by walking the parent
/// chains from every ref tip in the account. The traversal is bounded by
/// `MAX_OID_RESOLVE_VISITED` to keep degenerate histories from running away.
@@ -2986,7 +3166,217 @@ mod tests {
}
}
- // ── 9: show ────────────────────────────────────────────────────────
+ // ── 9: log path filtering ─────────────────────────────────────────
+ #[test]
+ fn test_normalize_log_paths_rejects_more_than_32_unique_paths() {
+ let paths = (0..=MAX_LOG_FILTER_PATHS)
+ .map(|index| format!("resources/docs/{index}.md"))
+ .collect();
+
+ let err = normalize_log_paths(Some(paths)).unwrap_err();
+ assert!(matches!(
+ err,
+ GitError::TooManyLogPaths {
+ count: 33,
+ limit: MAX_LOG_FILTER_PATHS,
+ }
+ ));
+ }
+
+ #[test]
+ fn test_normalize_log_paths_deduplicates_before_counting() {
+ let paths = vec!["resources/docs/a.md".to_string(); MAX_LOG_FILTER_PATHS + 1];
+
+ let normalized = normalize_log_paths(Some(paths)).unwrap().unwrap();
+ assert_eq!(normalized, vec!["resources/docs/a.md"]);
+ }
+
+ #[test]
+ fn test_normalize_log_paths_enforces_64_component_depth() {
+ let accepted = std::iter::repeat_n("segment", MAX_LOG_PATH_DEPTH)
+ .collect::<Vec<_>>()
+ .join("/");
+ let rejected = std::iter::repeat_n("segment", MAX_LOG_PATH_DEPTH + 1)
+ .collect::<Vec<_>>()
+ .join("/");
+
+ assert_eq!(
+ normalize_log_paths(Some(vec![accepted.clone()]))
+ .unwrap()
+ .unwrap(),
+ vec![accepted]
+ );
+
+ let err = normalize_log_paths(Some(vec![rejected.clone()])).unwrap_err();
+ assert!(matches!(
+ err,
+ GitError::LogPathTooDeep {
+ path,
+ depth: 65,
+ limit: MAX_LOG_PATH_DEPTH,
+ } if path == rejected
+ ));
+ }
+
+ #[test]
+ fn test_normalize_log_paths_preserves_unfiltered_semantics() {
+ assert!(normalize_log_paths(None).unwrap().is_none());
+ assert!(normalize_log_paths(Some(Vec::new())).unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn test_log_with_paths_returns_matching_commits_up_to_limit() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct");
+ vfs.put("resources/target.md", b"v1");
+ vfs.put("resources/other.md", b"other-v1");
+ let c1 = make_commit(&svc, "acct", "main", "target root").await;
+
+ vfs.put("resources/other.md", b"other-v2");
+ let _c2 = make_commit(&svc, "acct", "main", "unrelated").await;
+
+ vfs.put("resources/target.md", b"v2");
+ let c3 = make_commit(&svc, "acct", "main", "target edit").await;
+
+ vfs.put("resources/docs/readme.md", b"docs");
+ let c4 = make_commit(&svc, "acct", "main", "docs edit").await;
+
+ let log = svc
+ .log(crate::git::types::LogRequest {
+ account: "acct".to_string(),
+ branch: "main".to_string(),
+ limit: 2,
+ paths: Some(vec![
+ "resources/target.md".to_string(),
+ "resources/docs".to_string(),
+ ]),
+ })
+ .await
+ .unwrap();
+
+ let oids: Vec<ObjectId> = log.into_iter().map(|entry| entry.oid).collect();
+ assert_eq!(oids, vec![c4, c3], "limit counts matching commits only");
+
+ let log = svc
+ .log(crate::git::types::LogRequest {
+ account: "acct".to_string(),
+ branch: "main".to_string(),
+ limit: 10,
+ paths: Some(vec!["resources/target.md".to_string()]),
+ })
+ .await
+ .unwrap();
+ let oids: Vec<ObjectId> = log.into_iter().map(|entry| entry.oid).collect();
+ assert_eq!(oids, vec![c3, c1]);
+ }
+
+ #[tokio::test]
+ async fn test_log_with_empty_paths_is_unfiltered() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct");
+ vfs.put("resources/first.md", b"v1");
+ let c1 = make_commit(&svc, "acct", "main", "first").await;
+ vfs.put("resources/second.md", b"v2");
+ let c2 = make_commit(&svc, "acct", "main", "second").await;
+
+ let log = svc
+ .log(crate::git::types::LogRequest {
+ account: "acct".to_string(),
+ branch: "main".to_string(),
+ limit: 10,
+ paths: Some(Vec::new()),
+ })
+ .await
+ .unwrap();
+
+ let oids: Vec<ObjectId> = log.into_iter().map(|entry| entry.oid).collect();
+ assert_eq!(oids, vec![c2, c1]);
+ }
+
+ #[tokio::test]
+ async fn test_filtered_log_errors_when_uninspected_history_remains() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct_log_budget");
+ vfs.put("resources/target.md", b"target");
+ make_commit(&svc, "acct_log_budget", "main", "target root").await;
+ vfs.put("resources/other.md", b"v1");
+ make_commit(&svc, "acct_log_budget", "main", "unrelated one").await;
+ vfs.put("resources/other.md", b"v2");
+ make_commit(&svc, "acct_log_budget", "main", "unrelated two").await;
+
+ let err = svc
+ .log_with_scan_limit(
+ LogRequest {
+ account: "acct_log_budget".into(),
+ branch: "main".into(),
+ limit: 1,
+ paths: Some(vec!["resources/target.md".into()]),
+ },
+ 2,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ GitError::LogScanLimitExceeded {
+ scanned: 2,
+ max_scanned: 2,
+ matched: 0,
+ requested: 1,
+ }
+ ));
+ }
+
+ #[tokio::test]
+ async fn test_filtered_log_accepts_match_on_scan_boundary() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct_log_match");
+ vfs.put("resources/seed.md", b"seed");
+ make_commit(&svc, "acct_log_match", "main", "seed").await;
+ vfs.put("resources/target.md", b"target");
+ let target_commit = make_commit(&svc, "acct_log_match", "main", "target").await;
+ vfs.put("resources/other.md", b"other");
+ make_commit(&svc, "acct_log_match", "main", "unrelated").await;
+
+ let log = svc
+ .log_with_scan_limit(
+ LogRequest {
+ account: "acct_log_match".into(),
+ branch: "main".into(),
+ limit: 1,
+ paths: Some(vec!["resources/target.md".into()]),
+ },
+ 2,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(log.len(), 1);
+ assert_eq!(log[0].oid, target_commit);
+ }
+
+ #[tokio::test]
+ async fn test_filtered_log_returns_complete_empty_history_at_scan_boundary() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct_log_complete");
+ vfs.put("resources/other.md", b"v1");
+ make_commit(&svc, "acct_log_complete", "main", "one").await;
+ vfs.put("resources/other.md", b"v2");
+ make_commit(&svc, "acct_log_complete", "main", "two").await;
+
+ let log = svc
+ .log_with_scan_limit(
+ LogRequest {
+ account: "acct_log_complete".into(),
+ branch: "main".into(),
+ limit: 1,
+ paths: Some(vec!["resources/never-created.md".into()]),
+ },
+ 2,
+ )
+ .await
+ .unwrap();
+
+ assert!(log.is_empty());
+ }
+
+ // ── 10: show ───────────────────────────────────────────────────────
#[tokio::test]
async fn test_show_commit_meta_by_oid() {
let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct");
@@ -4994,6 +5384,55 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_filtered_log_reads_each_commit_object_at_most_once() {
+ let dir = tempfile::tempdir().unwrap();
+ let object_store = Arc::new(GetSpyObjectStore {
+ inner: LocalObjectStore::new(dir.path()),
+ gets: std::sync::Mutex::new(Vec::new()),
+ });
+ let ref_store = Arc::new(LocalRefStore::new(dir.path()));
+ let vfs = MockVfs::new("acct_log_reads");
+ let svc = GitService::new(
+ vfs.clone() as Arc<dyn FileSystem>,
+ object_store.clone() as Arc<dyn ObjectStore>,
+ ref_store as Arc<dyn RefStore>,
+ );
+
+ let mut commits = Vec::new();
+ for version in 1..=4 {
+ let content = format!("v{version}");
+ vfs.put("resources/other.md", content.as_bytes());
+ commits.push(
+ make_commit(&svc, "acct_log_reads", "main", &format!("commit {version}")).await,
+ );
+ }
+ object_store.reset();
+
+ let err = svc
+ .log_with_scan_limit(
+ LogRequest {
+ account: "acct_log_reads".into(),
+ branch: "main".into(),
+ limit: 1,
+ paths: Some(vec!["resources/never-created.md".into()]),
+ },
+ 3,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ GitError::LogScanLimitExceeded { scanned: 3, .. }
+ ));
+
+ let commit_gets: usize = commits.iter().map(|oid| object_store.count_gets(oid)).sum();
+ assert_eq!(commit_gets, 4, "three candidates plus one parent lookahead");
+ for oid in commits {
+ assert_eq!(object_store.count_gets(&oid), 1, "commit {oid} was re-read");
+ }
+ }
+
#[tokio::test]
async fn test_commit_prev_tree_lookup_cache_amortises_ancestors() {
// Build a prev tree where many candidates share the same depth-3
diff --git a/crates/ragfs/src/git/types.rs b/crates/ragfs/src/git/types.rs
index 9e572469c..534698b48 100644
--- a/crates/ragfs/src/git/types.rs
+++ b/crates/ragfs/src/git/types.rs
@@ -53,6 +53,37 @@ pub struct ShowRequest {
pub path: Option<String>,
}
+/// Input for walking commit history, optionally restricted to paths.
+#[derive(Debug, Clone)]
+pub struct LogRequest {
+ /// Account whose branch history should be read.
+ pub account: String,
+ /// Branch or ref to start from, usually "main".
+ pub branch: String,
+ /// Maximum number of matching commits to return.
+ pub limit: usize,
+ /// Optional account-relative paths. File paths match exactly; directory
+ /// paths match commits whose subtree changed.
+ pub paths: Option<Vec<String>>,
+}
+
+/// One commit returned by `GitService::log`.
+#[derive(Debug, Clone)]
+pub struct LogEntry {
+ /// Commit object id.
+ pub oid: ObjectId,
+ /// Root tree object id.
+ pub tree: ObjectId,
+ /// Parent commit ids.
+ pub parents: Vec<ObjectId>,
+ /// Commit author.
+ pub author: Actor,
+ /// Commit committer.
+ pub committer: Actor,
+ /// Full commit message.
+ pub message: String,
+}
+
#[derive(Debug, Clone)]
pub enum ShowResponse {
Commit {
diff --git a/docs/en/api/11-snapshot.md b/docs/en/api/11-snapshot.md
index e69442cab..e7bf6d874 100644
--- a/docs/en/api/11-snapshot.md
+++ b/docs/en/api/11-snapshot.md
@@ -123,12 +123,20 @@ Starting from a branch's HEAD, walk history along the first parent (`parents[0]`
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| branch | str | No | `main` | Branch to walk |
-| limit | int | No | 20 | Max commits to return. The HTTP endpoint clamps this to 1–500 |
+| limit | int | No | 20 | Max commits to return. The HTTP endpoint accepts values from 1 to 500 |
+| paths | List[str] | No | null | Return only commits that changed any specified `viking://` URI; files and directories are supported. At most 32 paths are accepted, and each account-relative path may contain at most 64 components. Pass multiple URIs to HTTP as repeated `paths` query parameters |
+
+Filtering happens before the result limit is applied, so `limit=10` with `paths=[X]` returns up to 10 commits related to X rather than filtering only the 10 newest commits.
+
+To bound storage work, a filtered request inspects at most 1,000 commits. If the requested number of matches has not been collected and older uninspected history remains, the request returns an `INVALID_ARGUMENT` error instead of a partial history list. Unfiltered history is not subject to this scan budget because every inspected commit advances the result limit.
**Python SDK (Embedded / HTTP)**
```python
-history = client.snapshot.log(limit=10)
+history = client.snapshot.log(
+ limit=10,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+)
for commit in history:
print(commit["oid"], commit["message"])
```
@@ -136,24 +144,35 @@ for commit in history:
**TypeScript SDK**
```typescript
-console.log(await client.gitLog("main", 20));
+console.log(
+ await client.gitLog("main", 20, [
+ "viking://resources/a.md",
+ "viking://resources/docs",
+ ]),
+);
```
**HTTP API**
```
-GET /api/v1/snapshot/log?branch={branch}&limit={limit}
+GET /api/v1/snapshot/log?branch={branch}&limit={limit}&paths={uri1}&paths={uri2}
```
```bash
-curl -X GET "http://localhost:1933/api/v1/snapshot/log?branch=main&limit=10" \
+curl --get "http://localhost:1933/api/v1/snapshot/log" \
+ --data-urlencode "branch=main" \
+ --data-urlencode "limit=10" \
+ --data-urlencode "paths=viking://resources/a.md" \
+ --data-urlencode "paths=viking://resources/docs" \
-H "X-API-Key: your-key"
```
**CLI**
```bash
-ov snapshot log --limit 10 -o json
+ov snapshot log --limit 10 \
+ --paths viking://resources/a.md,viking://resources/docs \
+ -o json
```
**Response**
diff --git a/docs/zh/api/11-snapshot.md b/docs/zh/api/11-snapshot.md
index f15675d11..ff8a63c2b 100644
--- a/docs/zh/api/11-snapshot.md
+++ b/docs/zh/api/11-snapshot.md
@@ -124,11 +124,19 @@ ov snapshot commit -m "v1 initial import" --paths viking://resources/my_md.md -o
|------|------|------|--------|------|
| branch | str | 否 | `main` | 要回溯的分支 |
| limit | int | 否 | 20 | 最多返回的提交数量。HTTP 接口限制范围为 1–500 |
+| paths | List[str] | 否 | null | 只返回修改了任一指定 `viking://` URI 的提交;支持文件和目录。最多接受 32 条路径,每条 account-relative 路径最多包含 64 个层级。HTTP 接口通过重复 `paths` 查询参数传入多个 URI |
+
+过滤发生在限制返回数量之前,因此 `limit=10` 和 `paths=[X]` 表示最多返回 10 条与 X 有关的提交,而不是先取最近 10 条提交再过滤。
+
+为限制存储开销,过滤请求最多检查 1,000 条提交。如果尚未收集到请求数量的匹配结果,并且仍存在未检查的更早历史,接口将返回 `INVALID_ARGUMENT` 错误,而不是返回不完整的历史列表。非过滤请求不受该扫描预算限制,因为每检查一条提交都会推进返回数量限制。
**Python SDK (Embedded / HTTP)**
```python
-history = client.snapshot.log(limit=10)
+history = client.snapshot.log(
+ limit=10,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+)
for commit in history:
print(commit["oid"], commit["message"])
```
@@ -136,24 +144,35 @@ for commit in history:
**TypeScript SDK**
```typescript
-console.log(await client.gitLog("main", 20));
+console.log(
+ await client.gitLog("main", 20, [
+ "viking://resources/a.md",
+ "viking://resources/docs",
+ ]),
+);
```
**HTTP API**
```
-GET /api/v1/snapshot/log?branch={branch}&limit={limit}
+GET /api/v1/snapshot/log?branch={branch}&limit={limit}&paths={uri1}&paths={uri2}
```
```bash
-curl -X GET "http://localhost:1933/api/v1/snapshot/log?branch=main&limit=10" \
+curl --get "http://localhost:1933/api/v1/snapshot/log" \
+ --data-urlencode "branch=main" \
+ --data-urlencode "limit=10" \
+ --data-urlencode "paths=viking://resources/a.md" \
+ --data-urlencode "paths=viking://resources/docs" \
-H "X-API-Key: your-key"
```
**CLI**
```bash
-ov snapshot log --limit 10 -o json
+ov snapshot log --limit 10 \
+ --paths viking://resources/a.md,viking://resources/docs \
+ -o json
```
**响应**
diff --git a/openviking/client/local.py b/openviking/client/local.py
index 610ccb0f8..deb531314 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -1179,9 +1179,10 @@ class LocalClient(BaseClient):
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Walk back along parents[0] up to limit commits."""
- return await self._service.fs.log(branch=branch, limit=limit, ctx=self._ctx)
+ return await self._service.fs.log(branch=branch, limit=limit, paths=paths, ctx=self._ctx)
async def git_get_ignore(self) -> str:
"""Return the account .ovgitignore content (empty string if absent)."""
diff --git a/openviking/server/routers/snapshot.py b/openviking/server/routers/snapshot.py
index f7ba48900..6c83ea56e 100644
--- a/openviking/server/routers/snapshot.py
+++ b/openviking/server/routers/snapshot.py
@@ -26,6 +26,8 @@ from openviking_cli.exceptions import InternalError, NotFoundError, OpenVikingEr
router = APIRouter(prefix="/api/v1/snapshot", tags=["snapshot"])
+MAX_LOG_FILTER_PATHS = 32
+
class CommitRequest(BaseModel):
"""Request body for ``POST /api/v1/snapshot/commit``."""
@@ -55,7 +57,7 @@ async def commit(
author_email=request.author_email,
ctx=_ctx,
)
- except AGFSClientError as e:
+ except (AGFSClientError, ValueError) as e:
mapped = map_exception(e)
if mapped is not None:
raise mapped from e
@@ -67,15 +69,23 @@ async def commit(
async def log(
branch: str = Query("main", description="Branch ref name"),
limit: int = Query(20, ge=1, le=500, description="Max commits to return"),
+ paths: Optional[List[str]] = Query(
+ None,
+ max_length=MAX_LOG_FILTER_PATHS,
+ description=(
+ "Optional viking:// paths; repeat up to 32 values to filter history "
+ "to commits touching any path"
+ ),
+ ),
_ctx: RequestContext = Depends(get_request_context),
):
"""Walk commit history newest-first along parents[0]."""
service = get_service()
try:
- result = await service.fs.log(branch=branch, limit=limit, ctx=_ctx)
+ result = await service.fs.log(branch=branch, limit=limit, paths=paths, ctx=_ctx)
except AGFSNotFoundError:
raise NotFoundError(branch, "git_ref")
- except AGFSClientError as e:
+ except (AGFSClientError, ValueError) as e:
mapped = map_exception(e)
if mapped is not None:
raise mapped from e
@@ -127,7 +137,7 @@ async def restore(
code="RESTORE_WRITEBACK_PARTIAL",
details=exc.to_dict(),
) from exc
- except AGFSClientError as e:
+ except (AGFSClientError, ValueError) as e:
mapped = map_exception(e)
if mapped is not None:
raise mapped from e
@@ -161,7 +171,7 @@ async def show(
except AGFSNotFoundError as e:
resource = path if path is not None else target_ref
raise NotFoundError(resource, "git_blob" if path is not None else "git_ref") from e
- except AGFSClientError as e:
+ except (AGFSClientError, ValueError) as e:
mapped = map_exception(e)
if mapped is not None:
raise mapped from e
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 3573eaa77..b6c254e99 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -668,10 +668,15 @@ class FSService:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Forward to VikingFS.log. Walks parents[0] up to limit commits."""
viking_fs = self._ensure_initialized()
- return await viking_fs.log(branch=branch, limit=limit, ctx=ctx)
+ if paths is not None:
+ paths = [validate_viking_uri(path, field_name="paths") for path in paths]
+ if not paths:
+ paths = None
+ return await viking_fs.log(branch=branch, limit=limit, paths=paths, ctx=ctx)
async def get_gitignore(self, *, ctx: RequestContext) -> str:
"""Forward to VikingFS.get_gitignore. Returns the account .ovgitignore
diff --git a/openviking/snapshot_namespace.py b/openviking/snapshot_namespace.py
index 3196f42a4..4c7f181a8 100644
--- a/openviking/snapshot_namespace.py
+++ b/openviking/snapshot_namespace.py
@@ -81,9 +81,10 @@ class AsyncSnapshotNamespace:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
await self._client._ensure_initialized()
- return await self._client._client.git_log(branch=branch, limit=limit)
+ return await self._client._client.git_log(branch=branch, limit=limit, paths=paths)
async def get_gitignore(self) -> str:
"""Return the account .ovgitignore content (empty string if absent)."""
@@ -169,8 +170,9 @@ class SyncSnapshotNamespace:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
- return run_async(self._ns().log(branch=branch, limit=limit))
+ return run_async(self._ns().log(branch=branch, limit=limit, paths=paths))
def get_gitignore(self) -> str:
return run_async(self._ns().get_gitignore())
diff --git a/openviking/storage/viking_fs.py b/openviking/storage/viking_fs.py
index 662dae765..cbc1a1938 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -4042,6 +4042,7 @@ class VikingFS:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
ctx: Optional[RequestContext] = None,
) -> List[Dict[str, Any]]:
"""Walk back from ``branch``'s HEAD along ``parents[0]`` up to ``limit`` commits.
@@ -4052,25 +4053,18 @@ class VikingFS:
return []
real_ctx = self._ctx_or_default(ctx)
account = real_ctx.account_id
- head = await self._async_agfs.run(
- "git_show",
+ tree_paths = (
+ None
+ if not paths
+ else [self._uri_to_tree_path(path, ctx=real_ctx) for path in paths]
+ )
+ return await self._async_agfs.run(
+ "git_log",
account=account,
- target_ref=branch,
- path=None,
+ branch=branch,
+ limit=limit,
+ paths=tree_paths,
)
- results: List[Dict[str, Any]] = [head]
- parents = head.get("parents") or []
- while parents and len(results) < limit:
- parent_oid = parents[0]
- commit = await self._async_agfs.run(
- "git_show",
- account=account,
- target_ref=parent_oid,
- path=None,
- )
- results.append(commit)
- parents = commit.get("parents") or []
- return results
def _collect_restore_vector_tasks(
self,
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 08d375b17..8d3792eb3 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -589,6 +589,7 @@ class BaseClient(ABC):
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Walk back along parents[0] up to limit commits."""
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 1b848cdf2..aef8efe4d 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -1580,12 +1580,16 @@ class AsyncHTTPClient:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Walk commit history newest-first."""
+ params: Dict[str, Any] = {"branch": branch, "limit": limit}
+ if paths:
+ params["paths"] = paths
response = await self._request(
"GET",
"/api/v1/snapshot/log",
- params={"branch": branch, "limit": limit},
+ params=params,
)
return self._handle_response(response)
@@ -2360,8 +2364,9 @@ class AsyncHTTPSnapshotNamespace:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
- return await self._client.git_log(branch=branch, limit=limit)
+ return await self._client.git_log(branch=branch, limit=limit, paths=paths)
async def get_gitignore(self) -> str:
return await self._client.git_get_ignore()
@@ -2437,8 +2442,9 @@ class SyncHTTPSnapshotNamespace:
*,
branch: str = "main",
limit: int = 20,
+ paths: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
- return run_async(self._ns().log(branch=branch, limit=limit))
+ return run_async(self._ns().log(branch=branch, limit=limit, paths=paths))
def get_gitignore(self) -> str:
return run_async(self._ns().get_gitignore())
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index 447744162..22fb98ef5 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -858,9 +858,9 @@ export class OpenVikingClient {
);
}
/** Return snapshot history from newest to oldest. */
- gitLog(branch = "main", limit = 20): Promise<JsonObject[]> {
+ gitLog(branch = "main", limit = 20, paths?: string[]): Promise<JsonObject[]> {
return this.request("GET", "/api/v1/snapshot/log", {
- query: { branch, limit },
+ query: { branch, limit, paths },
});
}
/** Return the account `.ovgitignore` content. */
diff --git a/sdk/typescript/src/transport.ts b/sdk/typescript/src/transport.ts
index eb51cb2c4..2848cd8e0 100644
--- a/sdk/typescript/src/transport.ts
+++ b/sdk/typescript/src/transport.ts
@@ -71,8 +71,14 @@ export class OpenVikingTransport {
`${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`,
);
for (const [key, value] of Object.entries(options.query ?? {})) {
- if (value !== undefined && value !== null && value !== "")
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (item !== undefined && item !== null && item !== "")
+ url.searchParams.append(key, String(item));
+ }
+ } else if (value !== undefined && value !== null && value !== "") {
url.searchParams.set(key, String(value));
+ }
}
if (this.profile) url.searchParams.set("profile", "1");
const headers = new Headers(this.headers);
diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts
index 395aa268b..58acadc9b 100644
--- a/sdk/typescript/tests/client.test.ts
+++ b/sdk/typescript/tests/client.test.ts
@@ -554,6 +554,7 @@ describe("OpenVikingClient", () => {
}),
)
.mockResolvedValueOnce(ok([{ oid: "commit-1" }]))
+ .mockResolvedValueOnce(ok([{ oid: "commit-1" }]))
.mockResolvedValueOnce(ok("*.tmp\n"))
.mockResolvedValueOnce(ok(null))
.mockResolvedValueOnce(ok(null));
@@ -570,7 +571,15 @@ describe("OpenVikingClient", () => {
size: 2,
bytes: new Uint8Array([4, 5]),
});
- await expect(client.gitLog()).resolves.toEqual([{ oid: "commit-1" }]);
+ await expect(
+ client.gitLog("main", 20, [
+ "viking://resources/a",
+ "viking://resources/docs",
+ ]),
+ ).resolves.toEqual([{ oid: "commit-1" }]);
+ await expect(client.gitLog("main", 20, [])).resolves.toEqual([
+ { oid: "commit-1" },
+ ]);
await expect(client.gitGetIgnore()).resolves.toBe("*.tmp\n");
await client.gitSetIgnore("*.log\n");
await client.gitDeleteIgnore();
@@ -583,7 +592,16 @@ describe("OpenVikingClient", () => {
expect(
new URL(String(fetcher.mock.calls[1]![0])).searchParams.get("path"),
).toBe("viking://resources/a");
- expect(JSON.parse(String(fetcher.mock.calls[4]![1]?.body))).toEqual({
+ const logUrl = new URL(String(fetcher.mock.calls[2]![0]));
+ expect(logUrl.searchParams.get("limit")).toBe("20");
+ expect(logUrl.searchParams.getAll("paths")).toEqual([
+ "viking://resources/a",
+ "viking://resources/docs",
+ ]);
+ const unfilteredLogUrl = new URL(String(fetcher.mock.calls[3]![0]));
+ expect(unfilteredLogUrl.searchParams.get("limit")).toBe("20");
+ expect(unfilteredLogUrl.searchParams.getAll("paths")).toEqual([]);
+ expect(JSON.parse(String(fetcher.mock.calls[5]![1]?.body))).toEqual({
content: "*.log\n",
});
});
diff --git a/tests/agfs/test_viking_fs_git.py b/tests/agfs/test_viking_fs_git.py
index c1307713e..c7609c00b 100644
--- a/tests/agfs/test_viking_fs_git.py
+++ b/tests/agfs/test_viking_fs_git.py
@@ -218,6 +218,60 @@ class TestCommitShowLog:
limited = await vfs.log(limit=2, ctx=ctx)
assert [h["oid"] for h in limited] == [c3["commit_oid"], c2["commit_oid"]]
+ async def test_log_filters_files_directories_and_deletions(self, vfs):
+ ctx = _make_ctx(account="acct_log_paths")
+ target = "viking://resources/proj/a.md"
+ project = "viking://resources/proj"
+
+ await vfs.write_file(target, b"v1", ctx=ctx)
+ added = await vfs.commit(message="add target", paths=[target], ctx=ctx)
+
+ unrelated_path = "viking://resources/other.md"
+ await vfs.write_file(unrelated_path, b"other", ctx=ctx)
+ await vfs.commit(
+ message="unrelated",
+ paths=[unrelated_path],
+ ctx=ctx,
+ )
+
+ sibling = "viking://resources/proj/nested/b.md"
+ await vfs.write_file(sibling, b"sibling", ctx=ctx)
+ directory_changed = await vfs.commit(
+ message="change project directory",
+ paths=[sibling],
+ ctx=ctx,
+ )
+
+ await vfs.rm(target, ctx=ctx)
+ deleted = await vfs.commit(message="delete target", paths=[target], ctx=ctx)
+
+ file_history = await vfs.log(paths=[target], limit=2, ctx=ctx)
+ assert [entry["oid"] for entry in file_history] == [
+ deleted["commit_oid"],
+ added["commit_oid"],
+ ]
+
+ directory_history = await vfs.log(paths=[project], limit=10, ctx=ctx)
+ assert [entry["oid"] for entry in directory_history] == [
+ deleted["commit_oid"],
+ directory_changed["commit_oid"],
+ added["commit_oid"],
+ ]
+
+ async def test_log_rejects_too_many_unique_paths(self, vfs):
+ ctx = _make_ctx(account="acct_log_path_budget")
+ paths = [f"viking://resources/path-{index}.md" for index in range(33)]
+
+ with pytest.raises(AGFSInvalidOperationError, match="too many log filter paths"):
+ await vfs.log(paths=paths, limit=1, ctx=ctx)
+
+ async def test_log_rejects_path_deeper_than_64_components(self, vfs):
+ ctx = _make_ctx(account="acct_log_depth_budget")
+ path = "viking://" + "/".join(["resources", *(["nested"] * 64)])
+
+ with pytest.raises(AGFSInvalidOperationError, match="has depth 65"):
+ await vfs.log(paths=[path], limit=1, ctx=ctx)
+
async def test_show_missing_branch_raises(self, vfs):
ctx = _make_ctx(account="acct_missing")
with pytest.raises(AGFSNotFoundError):
diff --git a/tests/cli/test_cli_snapshot.py b/tests/cli/test_cli_snapshot.py
index 3024d766f..8dced310a 100644
--- a/tests/cli/test_cli_snapshot.py
+++ b/tests/cli/test_cli_snapshot.py
@@ -12,14 +12,27 @@ from conftest import ov
pytestmark = pytest.mark.cli_remote
-def _commit(message: str):
+def _create_file(uri: str, content: str):
+ """Create a file without waiting for unrelated semantic processing."""
+ return ov(
+ ["write", uri, "--content", content, "--mode", "create", "-o", "json"],
+ timeout=60,
+ )
+
+
+def _commit(message: str, paths=None):
"""Helper: take a snapshot, return the full envelope dict.
Retries briefly on transient server busy errors.
"""
+ args = ["snapshot", "commit", "-m", message]
+ if paths:
+ args.extend(["--paths", ",".join(paths)])
+ args.extend(["-o", "json"])
+
r = None
for _attempt in range(5):
- r = ov(["snapshot", "commit", "-m", message, "-o", "json"], timeout=120)
+ r = ov(args, timeout=120)
if r["exit_code"] == 0:
break
if "busy" in r["stderr"].lower() or "internal" in r["stderr"].lower():
@@ -39,14 +52,18 @@ class TestSnapshotCommit:
assert "commit_oid" in result, f"expected commit_oid in result, got {result}"
assert isinstance(result["commit_oid"], str) and len(result["commit_oid"]) >= 12
- def test_commit_human_prints_short_oid(self, test_pack_uri):
+ def test_commit_human_prints_result_table(self, test_pack_uri):
msg = f"cli-test human {uuid.uuid4().hex[:6]}"
r = ov(["snapshot", "commit", "-m", msg], timeout=120)
assert r["exit_code"] == 0, f"snapshot commit failed: {r['stderr'][:300]}"
out = r["stdout"]
- assert re.match(
- r"^(Created [0-9a-f]{12}|No changes)", out
- ), f"unexpected commit stdout: {out[:200]}"
+ assert re.search(r"(?m)^result\s+(created|noop)$", out), (
+ f"expected result row in commit output: {out[:200]}"
+ )
+ oid_match = re.search(r"(?m)^commit_oid\s+([0-9a-f]+)$", out)
+ assert oid_match and len(oid_match.group(1)) >= 12, (
+ f"expected commit_oid row in commit output: {out[:200]}"
+ )
class TestSnapshotLog:
@@ -87,6 +104,48 @@ class TestSnapshotLog:
first = result[0]
assert "oid" in first and "message" in first
+ def test_log_filters_paths(self):
+ suffix = uuid.uuid4().hex[:8]
+ base_uri = f"viking://resources/cli_log_paths_{suffix}"
+ target_uri = f"{base_uri}/a.md"
+ directory_uri = f"{base_uri}/docs"
+ child_uri = f"{directory_uri}/guide.md"
+ unrelated_uri = f"viking://resources/cli_log_paths_other_{suffix}.md"
+
+ write = _create_file(target_uri, "target")
+ assert write["exit_code"] == 0, f"target write failed: {write['stderr'][:300]}"
+ target_commit = _commit("cli log paths: add target", paths=[target_uri])
+
+ write = _create_file(unrelated_uri, "unrelated")
+ assert write["exit_code"] == 0, f"unrelated write failed: {write['stderr'][:300]}"
+ _commit("cli log paths: add unrelated", paths=[unrelated_uri])
+
+ write = _create_file(child_uri, "guide")
+ assert write["exit_code"] == 0, f"directory child write failed: {write['stderr'][:300]}"
+ directory_commit = _commit("cli log paths: add directory child", paths=[child_uri])
+
+ result = ov(
+ [
+ "snapshot",
+ "log",
+ "--limit",
+ "2",
+ "--paths",
+ f"{target_uri},{directory_uri}",
+ "-o",
+ "json",
+ ],
+ timeout=60,
+ )
+
+ assert result["exit_code"] == 0, f"snapshot log failed: {result['stderr'][:300]}"
+ assert result["json"] is not None and result["json"].get("ok") is True
+ history = result["json"]["result"]
+ assert [item["oid"] for item in history] == [
+ directory_commit["commit_oid"],
+ target_commit["commit_oid"],
+ ]
+
class TestSnapshotShow:
def test_show_metadata(self, test_pack_uri):
diff --git a/tests/client/test_git_versioning.py b/tests/client/test_git_versioning.py
index bc638dcab..4fc8e43c3 100644
--- a/tests/client/test_git_versioning.py
+++ b/tests/client/test_git_versioning.py
@@ -219,6 +219,41 @@ async def test_log_walks_parents(git_harness):
]
+async def test_log_filters_multiple_paths_end_to_end(git_harness):
+ target_uri = "viking://resources/log_paths/a.md"
+ directory_uri = "viking://resources/log_paths/docs"
+ child_uri = f"{directory_uri}/guide.md"
+ unrelated_uri = "viking://resources/log_paths_other.md"
+
+ await git_harness.vfs.write_file(target_uri, b"target", ctx=git_harness.ctx)
+ target_commit = git_harness.client.snapshot.commit(
+ message="add target",
+ paths=[target_uri],
+ )
+
+ await git_harness.vfs.write_file(unrelated_uri, b"unrelated", ctx=git_harness.ctx)
+ git_harness.client.snapshot.commit(
+ message="add unrelated",
+ paths=[unrelated_uri],
+ )
+
+ await git_harness.vfs.write_file(child_uri, b"guide", ctx=git_harness.ctx)
+ directory_commit = git_harness.client.snapshot.commit(
+ message="add directory child",
+ paths=[child_uri],
+ )
+
+ history = git_harness.client.snapshot.log(
+ limit=2,
+ paths=[target_uri, directory_uri],
+ )
+
+ assert [item["oid"] for item in history] == [
+ directory_commit["commit_oid"],
+ target_commit["commit_oid"],
+ ]
+
+
async def test_restore_reverts_file_and_advances_head(git_harness):
await git_harness.vfs.write_file(
"viking://resources/proj/a.md",
diff --git a/tests/client/test_git_versioning_http.py b/tests/client/test_git_versioning_http.py
index ccc11b475..3323645f7 100644
--- a/tests/client/test_git_versioning_http.py
+++ b/tests/client/test_git_versioning_http.py
@@ -182,6 +182,51 @@ async def test_http_commit_and_log_roundtrip(http_git_client, http_service):
assert "oid" in log[0] and "message" in log[0]
+async def test_http_log_filters_repeated_paths_end_to_end(http_app, http_service):
+ target_uri = "viking://resources/http_log_paths/a.md"
+ directory_uri = "viking://resources/http_log_paths/docs"
+ child_uri = f"{directory_uri}/guide.md"
+ unrelated_uri = "viking://resources/http_log_paths_other.md"
+
+ transport = httpx.ASGITransport(app=http_app)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ headers=_AUTH_HEADERS,
+ timeout=30.0,
+ ) as client:
+ async def commit(uri: str, body: bytes, message: str) -> dict:
+ await _write_blob(http_service, uri, body)
+ response = await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": message, "paths": [uri]},
+ )
+ assert response.status_code == 200
+ return response.json()["result"]
+
+ target_commit = await commit(target_uri, b"target", "add target")
+ await commit(unrelated_uri, b"unrelated", "add unrelated")
+ directory_commit = await commit(child_uri, b"guide", "add directory child")
+
+ response = await client.get(
+ "/api/v1/snapshot/log",
+ params=[
+ ("branch", "main"),
+ ("limit", "2"),
+ ("paths", target_uri),
+ ("paths", directory_uri),
+ ],
+ )
+
+ assert response.status_code == 200
+ assert response.request.url.params.get_list("paths") == [target_uri, directory_uri]
+ history = response.json()["result"]
+ assert [item["oid"] for item in history] == [
+ directory_commit["commit_oid"],
+ target_commit["commit_oid"],
+ ]
+
+
async def test_http_show_blob_byte_exact_roundtrip(http_git_client, http_service):
client = http_git_client
blob_uri = "viking://resources/http_show_blob.txt"
diff --git a/tests/client/test_http_client_snapshot.py b/tests/client/test_http_client_snapshot.py
index 94c576940..8c004ed88 100644
--- a/tests/client/test_http_client_snapshot.py
+++ b/tests/client/test_http_client_snapshot.py
@@ -205,9 +205,30 @@ async def test_git_log_gets_with_params():
client._handle_response = lambda resp: [{"oid": "d" * 40, "message": "x"}]
fake.next_response = object()
- result = await client.git_log(branch="main", limit=5)
+ result = await client.git_log(
+ branch="main",
+ limit=5,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+ )
assert result == [{"oid": "d" * 40, "message": "x"}]
+ call = fake.calls[-1]
+ assert call["method"] == "GET"
+ assert call["path"] == "/api/v1/snapshot/log"
+ assert call["params"] == {
+ "branch": "main",
+ "limit": 5,
+ "paths": ["viking://resources/a.md", "viking://resources/docs"],
+ }
+
+
+async def test_git_log_empty_paths_is_unfiltered():
+ client, fake = _client_with_fake()
+ client._handle_response = lambda resp: [{"oid": "d" * 40, "message": "x"}]
+ fake.next_response = object()
+
+ await client.git_log(branch="main", limit=5, paths=[])
+
call = fake.calls[-1]
assert call["method"] == "GET"
assert call["path"] == "/api/v1/snapshot/log"
diff --git a/tests/server/test_api_snapshot.py b/tests/server/test_api_snapshot.py
index a83defd49..f51ea2dc3 100644
--- a/tests/server/test_api_snapshot.py
+++ b/tests/server/test_api_snapshot.py
@@ -2,10 +2,19 @@
# SPDX-License-Identifier: AGPL-3.0
"""End-to-end tests for /api/v1/snapshot/*."""
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import httpx
import pytest
import pytest_asyncio
-import httpx
+from openviking.server.auth import get_request_context
+from openviking.server.app import create_app
+from openviking.server.config import ServerConfig
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.exceptions import InvalidArgumentError, InvalidURIError
+from openviking_cli.session.user_id import UserIdentifier
pytestmark = pytest.mark.asyncio
@@ -23,6 +32,24 @@ async def client_with_no_repo(app):
yield c
+@pytest_asyncio.fixture(scope="function")
+async def snapshot_router_client():
+ """Production app without running its service-initializing lifespan."""
+ app = create_app(
+ config=ServerConfig(),
+ service=SimpleNamespace(sessions=None),
+ )
+
+ async def request_context_override():
+ return RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ app.dependency_overrides[get_request_context] = request_context_override
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ yield client
+
+
async def test_commit_creates_snapshot(client_with_resource):
client, _root_uri = client_with_resource
resp = await client.post(
@@ -58,6 +85,84 @@ async def test_log_empty_repo_returns_404(client_with_no_repo):
assert resp.json()["status"] == "error"
+async def test_log_value_error_is_mapped(monkeypatch):
+ from openviking.server.routers import snapshot
+
+ fake_service = SimpleNamespace(
+ fs=SimpleNamespace(
+ log=AsyncMock(
+ side_effect=ValueError("git tree path cannot be the account root: 'viking://'")
+ )
+ )
+ )
+ monkeypatch.setattr(snapshot, "get_service", lambda: fake_service)
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ with pytest.raises((InvalidArgumentError, InvalidURIError)):
+ await snapshot.log(branch="main", limit=5, paths=["viking://"], _ctx=ctx)
+
+
+async def test_log_rejects_more_than_32_raw_path_parameters(snapshot_router_client, monkeypatch):
+ from openviking.server.routers import snapshot
+
+ log_mock = AsyncMock(return_value=[])
+ monkeypatch.setattr(
+ snapshot,
+ "get_service",
+ lambda: SimpleNamespace(fs=SimpleNamespace(log=log_mock)),
+ )
+ params = [("paths", "viking://resources/a.md")] * 33
+
+ response = await snapshot_router_client.get("/api/v1/snapshot/log", params=params)
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+ log_mock.assert_not_awaited()
+
+
+async def test_log_accepts_32_raw_path_parameters(snapshot_router_client, monkeypatch):
+ from openviking.server.routers import snapshot
+
+ log_mock = AsyncMock(return_value=[])
+ monkeypatch.setattr(
+ snapshot,
+ "get_service",
+ lambda: SimpleNamespace(fs=SimpleNamespace(log=log_mock)),
+ )
+ params = [("paths", f"viking://resources/{index}.md") for index in range(32)]
+
+ response = await snapshot_router_client.get("/api/v1/snapshot/log", params=params)
+
+ assert response.status_code == 200
+ forwarded_paths = log_mock.await_args.kwargs["paths"]
+ assert len(forwarded_paths) == 32
+
+
+async def test_log_scan_limit_error_maps_to_invalid_argument(monkeypatch):
+ from openviking.pyagfs.exceptions import AGFSInvalidOperationError
+ from openviking.server.routers import snapshot
+
+ fake_service = SimpleNamespace(
+ fs=SimpleNamespace(
+ log=AsyncMock(
+ side_effect=AGFSInvalidOperationError(
+ "snapshot log scan limit exceeded: scanned 1000/1000 commits"
+ )
+ )
+ )
+ )
+ monkeypatch.setattr(snapshot, "get_service", lambda: fake_service)
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ with pytest.raises(InvalidArgumentError, match="scan limit exceeded"):
+ await snapshot.log(
+ branch="main",
+ limit=1,
+ paths=["viking://resources/missing.md"],
+ _ctx=ctx,
+ )
+
+
@pytest_asyncio.fixture(scope="function")
async def client_with_resource_and_blob(client_with_resource, service):
"""client_with_resource + a known blob written via VikingFS.write_file, then committed."""
diff --git a/tests/unit/test_fs_service_git_forwarders.py b/tests/unit/test_fs_service_git_forwarders.py
index 06afc2023..42903ded4 100644
--- a/tests/unit/test_fs_service_git_forwarders.py
+++ b/tests/unit/test_fs_service_git_forwarders.py
@@ -119,15 +119,37 @@ async def test_show_with_path_validated(svc, viking_fs_mock):
async def test_log_defaults(svc, viking_fs_mock):
ctx = _ctx()
out = await svc.log(ctx=ctx)
- viking_fs_mock.log.assert_awaited_once_with(branch="main", limit=20, ctx=ctx)
+ viking_fs_mock.log.assert_awaited_once_with(branch="main", limit=20, paths=None, ctx=ctx)
assert len(out) == 1
@pytest.mark.asyncio
async def test_log_with_overrides(svc, viking_fs_mock):
ctx = _ctx()
- await svc.log(ctx=ctx, branch="dev", limit=5)
- viking_fs_mock.log.assert_awaited_once_with(branch="dev", limit=5, ctx=ctx)
+ await svc.log(
+ ctx=ctx,
+ branch="dev",
+ limit=5,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+ )
+ viking_fs_mock.log.assert_awaited_once_with(
+ branch="dev",
+ limit=5,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+ ctx=ctx,
+ )
+
+
+async def test_log_empty_paths_is_unfiltered(svc, viking_fs_mock):
+ ctx = _ctx()
+ await svc.log(ctx=ctx, branch="dev", limit=5, paths=[])
+ viking_fs_mock.log.assert_awaited_once_with(
+ branch="dev",
+ limit=5,
+ paths=None,
+ ctx=ctx,
+ )
@pytest.mark.asyncio
diff --git a/tests/unit/test_local_client_git.py b/tests/unit/test_local_client_git.py
index d4105f560..33ffc02c3 100644
--- a/tests/unit/test_local_client_git.py
+++ b/tests/unit/test_local_client_git.py
@@ -123,11 +123,22 @@ async def test_show_with_path(local_client, mock_fs):
@pytest.mark.asyncio
async def test_log_defaults(local_client, mock_fs):
out = await local_client.git_log()
- mock_fs.log.assert_awaited_once_with(branch="main", limit=20, ctx=local_client._ctx)
+ mock_fs.log.assert_awaited_once_with(
+ branch="main", limit=20, paths=None, ctx=local_client._ctx
+ )
assert len(out) == 1
@pytest.mark.asyncio
async def test_log_overrides(local_client, mock_fs):
- await local_client.git_log(branch="dev", limit=5)
- mock_fs.log.assert_awaited_once_with(branch="dev", limit=5, ctx=local_client._ctx)
+ await local_client.git_log(
+ branch="dev",
+ limit=5,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+ )
+ mock_fs.log.assert_awaited_once_with(
+ branch="dev",
+ limit=5,
+ paths=["viking://resources/a.md", "viking://resources/docs"],
+ ctx=local_client._ctx,
+ )
diff --git a/tests/unit/test_snapshot_namespace.py b/tests/unit/test_snapshot_namespace.py
index e24c648e0..e16560198 100644
--- a/tests/unit/test_snapshot_namespace.py
+++ b/tests/unit/test_snapshot_namespace.py
@@ -105,14 +105,18 @@ async def test_async_show_with_path(async_ns, fake_async_client):
@pytest.mark.asyncio
async def test_async_log_defaults(async_ns, fake_async_client):
out = await async_ns.log()
- fake_async_client._client.git_log.assert_awaited_once_with(branch="main", limit=20)
+ fake_async_client._client.git_log.assert_awaited_once_with(
+ branch="main", limit=20, paths=None
+ )
assert len(out) == 1
@pytest.mark.asyncio
async def test_async_log_overrides(async_ns, fake_async_client):
- await async_ns.log(branch="dev", limit=5)
- fake_async_client._client.git_log.assert_awaited_once_with(branch="dev", limit=5)
+ await async_ns.log(branch="dev", limit=5, paths=["viking://resources/a.md"])
+ fake_async_client._client.git_log.assert_awaited_once_with(
+ branch="dev", limit=5, paths=["viking://resources/a.md"]
+ )
@pytest.mark.asyncio
@@ -150,7 +154,7 @@ def test_sync_namespace_delegates_through_async(monkeypatch):
inner_async_ns.show.assert_awaited_once_with("main", path="viking://x/a")
sync_ns.log(branch="dev", limit=3)
- inner_async_ns.log.assert_awaited_once_with(branch="dev", limit=3)
+ inner_async_ns.log.assert_awaited_once_with(branch="dev", limit=3, paths=None)
def test_async_client_snapshot_property_is_lazy_and_cached():
diff --git a/uv.lock b/uv.lock
index 7ba4c6efa..59f9d02c4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3633,7 +3633,6 @@ dependencies = [
{ name = "opentelemetry-exporter-otlp-proto-http" },
{ name = "opentelemetry-instrumentation-asyncio" },
{ name = "opentelemetry-sdk" },
- { name = "openviking-sdk" },
{ name = "pathspec" },
{ name = "pdfminer-six" },
{ name = "pdfplumber" },
@@ -3843,7 +3842,6 @@ requires-dist = [
{ name = "opentelemetry-exporter-otlp-proto-http", specifier = ">=1.14" },
{ name = "opentelemetry-instrumentation-asyncio", specifier = ">=0.61b0" },
{ name = "opentelemetry-sdk", specifier = ">=1.14" },
- { name = "openviking-sdk", specifier = ">=0.1.1" },
{ name = "pandas", marker = "extra == 'benchmark'", specifier = ">=2.0.0" },
{ name = "pandas", marker = "extra == 'eval'", specifier = ">=2.0.0" },
{ name = "pandas", marker = "extra == 'test'", specifier = ">=2.0.0" },
@@ -3917,18 +3915,6 @@ provides-extras = ["test", "opengauss", "dev", "doc", "eval", "gemini", "gemini-
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=9.0.2" }]
-[[package]]
-name = "openviking-sdk"
-version = "0.1.2"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "httpx" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/b0/d2/1638f2d9592a87e2350a5d663db46b2bab8fff57b79f688a3ed63da069a1/openviking_sdk-0.1.2.tar.gz", hash = "sha256:673370c7df89fa7f7c6708e05251450e1cb736c5b94d1ba87ff18cd40d51eff8", size = 26700, upload-time = "2026-06-22T06:12:06.241Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/2d/c7/f21f7899a8902bbc9b2f8bfc6f60eb0b64addf44fc71b76f0c72241183f6/openviking_sdk-0.1.2-py3-none-any.whl", hash = "sha256:9e4c719d0f3f84dd686ffce45b80e8730c815ce6e4da94b94416307c679caa5f", size = 16904, upload-time = "2026-06-22T06:12:04.866Z" },
-]
-
[[package]]
name = "orjson"
version = "3.11.7"