Skip to content

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

feat(snapshot): add path diff API, SDK, and CLI (#3451)

agent27debfe7a8c2
diff --git a/Cargo.lock b/Cargo.lock
index ed90581e7..8be5cb555 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3937,6 +3937,7 @@ dependencies = [
"ragfs-cache-redis",
"serde",
"serde_json",
+ "similar",
"tokio",
"toml",
]
@@ -4686,6 +4687,15 @@ dependencies = [
"quote",
]
+[[package]]
+name = "similar"
+version = "3.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6505efef05804732ed8a3f2d4f279429eb485bd69d5b0cc6b19cc02005cda16"
+dependencies = [
+ "bstr",
+]
+
[[package]]
name = "slab"
version = "0.4.12"
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index 45427d9aa..e2bd1ebb5 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1592,6 +1592,22 @@ impl HttpClient {
self.get("/api/v1/snapshot/log", &params).await
}
+ pub async fn snapshot_diff(
+ &self,
+ path: &str,
+ from_ref: Option<&str>,
+ to_ref: &str,
+ ) -> Result<Value> {
+ let mut params = vec![
+ ("path".to_string(), path.to_string()),
+ ("to".to_string(), to_ref.to_string()),
+ ];
+ if let Some(from_ref) = from_ref {
+ params.push(("from".to_string(), from_ref.to_string()));
+ }
+ self.get("/api/v1/snapshot/diff", &params).await
+ }
+
pub async fn snapshot_ignore_get(&self) -> Result<Value> {
self.get("/api/v1/snapshot/ignore", &[]).await
}
@@ -1925,6 +1941,23 @@ mod tests {
assert_gateway_token_retry(&requests);
}
+ #[tokio::test]
+ async fn snapshot_diff_sends_path_and_refs() {
+ let (base_url, request_rx) = spawn_request_capture_server().await;
+ let client = HttpClient::new(base_url, None, None, None, None, 5.0, false, None);
+
+ client
+ .snapshot_diff("viking://resources/a.md", Some("old"), "new")
+ .await
+ .expect("snapshot diff should succeed");
+
+ let request = request_rx.await.expect("request should be captured");
+ assert!(request.starts_with("GET /api/v1/snapshot/diff?"));
+ assert!(request.contains("path=viking%3A%2F%2Fresources%2Fa.md"));
+ assert!(request.contains("from=old"));
+ assert!(request.contains("to=new"));
+ }
+
fn assert_gateway_token_retry(requests: &[String]) {
assert_eq!(requests.len(), 2);
assert!(!requests[0].to_ascii_lowercase().contains("x-gateway-token"));
diff --git a/crates/ov_cli/src/commands/snapshot.rs b/crates/ov_cli/src/commands/snapshot.rs
index 3d119f281..4f8f32d16 100644
--- a/crates/ov_cli/src/commands/snapshot.rs
+++ b/crates/ov_cli/src/commands/snapshot.rs
@@ -68,10 +68,23 @@ pub async fn dispatch(
limit,
paths,
} => {
- let value = client.snapshot_log(&branch, limit, paths.as_deref()).await?;
+ let value = client
+ .snapshot_log(&branch, limit, paths.as_deref())
+ .await?;
print_log(&value, output_format, compact);
Ok(())
}
+ SnapshotCmd::Diff {
+ path,
+ from_ref,
+ to_ref,
+ } => {
+ let value = client
+ .snapshot_diff(&path, from_ref.as_deref(), &to_ref)
+ .await?;
+ print_diff(&value, output_format, compact);
+ Ok(())
+ }
SnapshotCmd::IgnoreGet => {
let value = client.snapshot_ignore_get().await?;
print_ignore_get(&value, output_format, compact);
@@ -91,6 +104,17 @@ pub async fn dispatch(
}
}
+fn print_diff(value: &Value, output_format: OutputFormat, compact: bool) {
+ if matches!(output_format, OutputFormat::Json) {
+ output_success(value, output_format, compact);
+ return;
+ }
+ let diff = value.get("diff_text").and_then(Value::as_str).unwrap_or("");
+ let mut stdout = std::io::stdout();
+ let _ = stdout.write_all(diff.as_bytes());
+ let _ = stdout.flush();
+}
+
/// Resolve `.ovgitignore` content: `--file` takes precedence over `--content`;
/// if neither is given, the content is left empty (clears the rules).
fn resolve_ignore_content(content: Option<&str>, file: Option<&std::path::Path>) -> Result<String> {
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index e075af8eb..ef05f1937 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -527,7 +527,7 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
},
CommandHelpSpec {
path: &["snapshot"],
- purpose: "Manage workspace snapshots: commit, restore, show, and walk history.",
+ purpose: "Manage workspace snapshots: commit, restore, show, diff, and walk history.",
examples: &[
HelpItem {
label: "ov snapshot commit -m \"checkpoint before refactor\"",
@@ -537,6 +537,10 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
label: "ov snapshot log --branch main",
description: "Walk commit history, newest first.",
},
+ HelpItem {
+ label: "ov snapshot diff viking://docs/spec.md --from <old> --to <new>",
+ description: "Compare one file between two snapshots.",
+ },
HelpItem {
label: "ov snapshot restore viking://projects/acme <commit> --dry-run",
description: "Preview restoring a directory to a past snapshot.",
@@ -625,6 +629,24 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
description: "Inspect a commit from the log.",
}],
},
+ CommandHelpSpec {
+ path: &["snapshot", "diff"],
+ purpose: "Compare one file between two snapshots as a unified diff.",
+ examples: &[
+ HelpItem {
+ label: "ov snapshot diff viking://docs/spec.md --from <old> --to <new>",
+ description: "Compare the file contents at two commits.",
+ },
+ HelpItem {
+ label: "ov snapshot diff viking://docs/spec.md --to <commit>",
+ description: "Compare an empty file with the file at a commit.",
+ },
+ ],
+ next_steps: &[HelpItem {
+ label: "ov snapshot log --paths viking://docs/spec.md",
+ description: "Find commits that changed this file.",
+ }],
+ },
CommandHelpSpec {
path: &["snapshot", "ignore-get"],
purpose: "Show the account-level .ovgitignore content.",
@@ -1865,11 +1887,12 @@ fn localized_command_purpose(spec: &CommandHelpSpec, language: Language) -> &str
["health"] => "快速检查服务器是否可连接。",
["status"] => "查看 OpenViking 服务器诊断状态。",
["language"] => "选择 OpenViking CLI 显示语言。",
- ["snapshot"] => "管理工作区快照:提交、恢复、查看,以及遍历历史。",
+ ["snapshot"] => "管理工作区快照:提交、恢复、查看、对比,以及遍历历史。",
["snapshot", "commit"] => "将当前工作区状态提交为新的快照。",
["snapshot", "restore"] => "通过一次前向提交,将项目目录恢复到历史快照。",
["snapshot", "show"] => "查看某次提交的元数据,或指定路径下的单个文件内容。",
["snapshot", "log"] => "按分支遍历提交历史,最新的在前。",
+ ["snapshot", "diff"] => "对比指定文件在两个快照中的内容差异。",
_ => spec.purpose,
}
}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 021b7c502..7178d4801 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -953,7 +953,7 @@ enum Commands {
#[command(subcommand)]
action: TaskCommands,
},
- /// [Version] Manage workspace snapshots (commit, restore, show, log)
+ /// [Version] Manage workspace snapshots (commit, restore, show, diff, log)
Snapshot {
#[command(subcommand)]
cmd: SnapshotCmd,
@@ -1134,6 +1134,17 @@ pub(crate) enum SnapshotCmd {
#[arg(long, value_delimiter = ',')]
paths: Option<Vec<String>>,
},
+ /// Compare one file between two snapshots
+ Diff {
+ /// viking:// URI of the file to compare
+ path: String,
+ /// Older commit oid, branch, or tag; omit to compare an empty file
+ #[arg(long = "from")]
+ from_ref: Option<String>,
+ /// Newer commit oid, branch, or tag
+ #[arg(long = "to")]
+ to_ref: String,
+ },
/// Get the account .ovgitignore content
IgnoreGet,
/// Set the account .ovgitignore content
@@ -3261,11 +3272,11 @@ async fn main() {
mod tests {
use super::{
Cli, CliContext, Commands, ConfigAddTarget, ConfigCommands, LanguageGateAction,
- PrivacyCommands, SkillCommands, UploadCliOptions, find_command_index, first_command_token,
- is_language_command_request, language_command_can_run_picker, language_gate_action,
- language_required_message, legacy_upload_option_error, plain_help_misuse,
- pre_parse_output_options, pre_parse_requires_cli_config_file, preprocess_cli_args,
- preprocess_privacy_args,
+ PrivacyCommands, SkillCommands, SnapshotCmd, UploadCliOptions, find_command_index,
+ first_command_token, is_language_command_request, language_command_can_run_picker,
+ language_gate_action, language_required_message, legacy_upload_option_error,
+ plain_help_misuse, pre_parse_output_options, pre_parse_requires_cli_config_file,
+ preprocess_cli_args, preprocess_privacy_args,
};
use crate::config::{Config, DEFAULT_CUSTOM_URL};
use crate::output::OutputFormat;
@@ -3296,6 +3307,37 @@ mod tests {
assert_eq!(cli.actor_peer_id.as_deref(), Some("peer-a"));
}
+ #[test]
+ fn cli_parses_snapshot_diff_refs() {
+ let cli = Cli::try_parse_from([
+ "ov",
+ "snapshot",
+ "diff",
+ "viking://resources/a.md",
+ "--from",
+ "old",
+ "--to",
+ "new",
+ ])
+ .expect("snapshot diff should parse");
+
+ match cli.command {
+ Commands::Snapshot {
+ cmd:
+ SnapshotCmd::Diff {
+ path,
+ from_ref,
+ to_ref,
+ },
+ } => {
+ assert_eq!(path, "viking://resources/a.md");
+ assert_eq!(from_ref.as_deref(), Some("old"));
+ assert_eq!(to_ref, "new");
+ }
+ _ => panic!("expected snapshot diff"),
+ }
+ }
+
#[test]
fn pre_parse_output_options_preserve_json_config_errors() {
for args in [
diff --git a/crates/ragfs-python-native/Cargo.toml b/crates/ragfs-python-native/Cargo.toml
index 853c00f15..6f0702cc1 100644
--- a/crates/ragfs-python-native/Cargo.toml
+++ b/crates/ragfs-python-native/Cargo.toml
@@ -36,3 +36,7 @@ ragfs-cache-mooncake = { path = "../ragfs-cache-mooncake", optional = true }
pyo3 = { version = "0.27", features = ["abi3", "abi3-py310"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1.0"
+serde = { version = "1", features = ["derive"] }
+toml = "0.8"
+gix-hash = "0.14"
+similar = "3.1"
diff --git a/crates/ragfs-python/Cargo.toml b/crates/ragfs-python/Cargo.toml
index 65b0c801a..d466c5a11 100644
--- a/crates/ragfs-python/Cargo.toml
+++ b/crates/ragfs-python/Cargo.toml
@@ -28,6 +28,7 @@ serde = { version = "1", features = ["derive"] }
toml = "0.8"
gix-hash = "0.14"
bytes = "1.5"
+similar = "3.1"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("yuanrong-native", "mooncake-native"))'] }
diff --git a/crates/ragfs-python/src/git.rs b/crates/ragfs-python/src/git.rs
index da77eef13..57a666ef8 100644
--- a/crates/ragfs-python/src/git.rs
+++ b/crates/ragfs-python/src/git.rs
@@ -10,10 +10,13 @@
//!
//! The free functions are invoked from thin `#[pymethods]` wrappers in `lib.rs`.
+use std::io::{self, Write};
use std::sync::Arc;
+use std::time::Duration;
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::prelude::*;
+use similar::{Algorithm, TextDiff};
use ragfs::core::FileSystem;
use ragfs::git::{
@@ -174,7 +177,7 @@ fn classify_git_error(e: &ragfs::git::GitError) -> GitErrorMapping {
GitError::ConcurrentCommit { .. } => {
GitErrorMapping::PythonException("GitConcurrentCommitError")
}
- GitError::PathNotFound(_) => GitErrorMapping::PythonException("AGFSNotFoundError"),
+ GitError::PathNotFound(_) => GitErrorMapping::PythonException("AGFSPathNotFoundError"),
GitError::PathIsDirectory(_) => {
GitErrorMapping::PythonException("AGFSInvalidOperationError")
}
@@ -184,8 +187,10 @@ fn classify_git_error(e: &ragfs::git::GitError) -> GitErrorMapping {
GitError::InvalidAccountId(_)
| GitError::InvalidProjectDir(_)
| GitError::InvalidPath(_) => GitErrorMapping::PythonException("AGFSInvalidPathError"),
- GitError::BlobTooLarge { .. }
- | GitError::TooManyFiles { .. }
+ GitError::BlobTooLarge { .. } => {
+ GitErrorMapping::PythonException("AGFSResourceExhaustedError")
+ }
+ GitError::TooManyFiles { .. }
| GitError::TooManyLogPaths { .. }
| GitError::LogPathTooDeep { .. }
| GitError::LogScanLimitExceeded { .. }
@@ -203,6 +208,9 @@ fn classify_git_error(e: &ragfs::git::GitError) -> GitErrorMapping {
GitError::RefStore(RefStoreError::Conflict { .. }) => {
GitErrorMapping::PythonException("GitConcurrentCommitError")
}
+ GitError::RefStore(RefStoreError::InvalidName(_)) => {
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ }
GitError::RestoreWritebackPartial(_) => GitErrorMapping::RestoreWritebackPartial,
GitError::ObjectStore(_)
| GitError::RefStore(_)
@@ -297,6 +305,71 @@ use ragfs::git::{
RestoreResponse, RestoreWritebackPartial, ShowRequest, ShowResponse,
};
+#[derive(Debug, PartialEq, Eq)]
+pub enum BoundedDiffError {
+ OutputTooLarge { limit: usize },
+ Render(String),
+}
+
+struct LimitedWriter {
+ bytes: Vec<u8>,
+ limit: usize,
+ exceeded: bool,
+}
+
+impl LimitedWriter {
+ fn new(limit: usize) -> Self {
+ Self {
+ bytes: Vec::new(),
+ limit,
+ exceeded: false,
+ }
+ }
+}
+
+impl Write for LimitedWriter {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ if buf.len() > self.limit.saturating_sub(self.bytes.len()) {
+ self.exceeded = true;
+ return Err(io::Error::other("snapshot diff output size limit exceeded"));
+ }
+ self.bytes.extend_from_slice(buf);
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+pub fn build_bounded_unified_diff(
+ before: &str,
+ after: &str,
+ fromfile: &str,
+ tofile: &str,
+ timeout_ms: u64,
+ max_output_bytes: usize,
+) -> Result<String, BoundedDiffError> {
+ let mut config = TextDiff::configure();
+ config
+ .algorithm(Algorithm::Myers)
+ .timeout(Duration::from_millis(timeout_ms));
+ let diff = config.diff_lines(before, after);
+ let mut writer = LimitedWriter::new(max_output_bytes);
+ let result = diff
+ .unified_diff()
+ .header(fromfile, tofile)
+ .to_writer(&mut writer);
+
+ if writer.exceeded {
+ return Err(BoundedDiffError::OutputTooLarge {
+ limit: max_output_bytes,
+ });
+ }
+ result.map_err(|err| BoundedDiffError::Render(err.to_string()))?;
+ String::from_utf8(writer.bytes).map_err(|err| BoundedDiffError::Render(err.to_string()))
+}
+
// ---------- request parsers ----------
fn require_str(kwargs: &Bound<PyDict>, key: &str) -> PyResult<String> {
@@ -345,6 +418,26 @@ fn optional_string_list(kwargs: &Bound<PyDict>, key: &str) -> PyResult<Option<Ve
}
}
+pub struct DiffTextRequest {
+ pub before: String,
+ pub after: String,
+ pub fromfile: String,
+ pub tofile: String,
+ pub timeout_ms: u64,
+ pub max_output_bytes: usize,
+}
+
+pub fn parse_diff_text_request(kwargs: &Bound<PyDict>) -> PyResult<DiffTextRequest> {
+ Ok(DiffTextRequest {
+ before: require_str(kwargs, "before")?,
+ after: require_str(kwargs, "after")?,
+ fromfile: require_str(kwargs, "fromfile")?,
+ tofile: require_str(kwargs, "tofile")?,
+ timeout_ms: optional_usize(kwargs, "timeout_ms", 500)? as u64,
+ max_output_bytes: optional_usize(kwargs, "max_output_bytes", 20 * 1024 * 1024)?,
+ })
+}
+
pub fn parse_commit_request(kwargs: &Bound<PyDict>) -> PyResult<CommitRequest> {
Ok(CommitRequest {
account: require_str(kwargs, "account")?,
@@ -377,6 +470,15 @@ pub fn parse_show_request(kwargs: &Bound<PyDict>) -> PyResult<ShowRequest> {
})
}
+pub fn parse_show_max_blob_bytes(kwargs: &Bound<PyDict>) -> PyResult<Option<u64>> {
+ match kwargs.get_item("max_blob_bytes")? {
+ Some(value) if !value.is_none() => value.extract::<u64>().map(Some).map_err(|_| {
+ PyValueError::new_err("kwarg max_blob_bytes must be a non-negative integer")
+ }),
+ _ => Ok(None),
+ }
+}
+
pub fn parse_log_request(kwargs: &Bound<PyDict>) -> PyResult<LogRequest> {
Ok(LogRequest {
account: require_str(kwargs, "account")?,
@@ -533,7 +635,7 @@ pub fn log_entries_to_pylist(py: Python<'_>, entries: Vec<LogEntry>) -> PyResult
mod tests {
use super::*;
use ragfs::core::MountableFS;
- use ragfs::git::GitError;
+ use ragfs::git::{GitError, RefStoreError};
use std::sync::Arc;
fn local_cfg(base_dir: &str) -> ragfs::git::GitConfig {
@@ -673,6 +775,71 @@ mod tests {
});
}
+ #[test]
+ fn path_and_object_not_found_have_distinct_python_mappings() {
+ let oid = gix_hash::ObjectId::null(gix_hash::Kind::Sha1);
+ assert_eq!(
+ classify_git_error(&GitError::PathNotFound("foo/bar".into())),
+ GitErrorMapping::PythonException("AGFSPathNotFoundError")
+ );
+ assert_eq!(
+ classify_git_error(&GitError::ObjectStore(
+ ragfs::git::ObjectStoreError::NotFound(oid),
+ )),
+ GitErrorMapping::PythonException("AGFSNotFoundError")
+ );
+ }
+
+ #[test]
+ fn bounded_unified_diff_returns_valid_output_for_adversarial_input() {
+ let before = (0..20_000)
+ .map(|i| format!("before-{i}\n"))
+ .collect::<String>();
+ let after = (0..20_000)
+ .map(|i| format!("after-{i}\n"))
+ .collect::<String>();
+
+ let output = build_bounded_unified_diff(
+ &before,
+ &after,
+ "file@old",
+ "file@new",
+ 5,
+ 2 * 1024 * 1024,
+ )
+ .expect("deadline should produce an approximate diff");
+
+ assert!(output.starts_with("--- file@old\n+++ file@new\n"));
+ assert!(output.contains("-before-0\n"));
+ assert!(output.contains("+after-0\n"));
+ }
+
+ #[test]
+ fn bounded_unified_diff_enforces_output_limit() {
+ assert_eq!(
+ build_bounded_unified_diff("old\n", "new\n", "old", "new", 500, 8),
+ Err(BoundedDiffError::OutputTooLarge { limit: 8 })
+ );
+ }
+
+ #[test]
+ fn bounded_unified_diff_marks_missing_final_newline() {
+ let output = build_bounded_unified_diff(
+ "old without newline",
+ "new without newline",
+ "old",
+ "new",
+ 500,
+ 1024,
+ )
+ .expect("small text diff should succeed");
+
+ assert_eq!(
+ output.matches("\\ No newline at end of file").count(),
+ 2
+ );
+ }
+
#[test]
fn map_git_error_invalid_account() {
pyo3::prepare_freethreaded_python();
@@ -697,6 +864,18 @@ mod tests {
});
}
+ #[test]
+ fn blob_too_large_maps_to_resource_exhausted() {
+ let error = GitError::BlobTooLarge {
+ size: 200,
+ limit: 100,
+ };
+ assert_eq!(
+ classify_git_error(&error),
+ GitErrorMapping::PythonException("AGFSResourceExhaustedError")
+ );
+ }
+
#[test]
fn map_git_error_log_budgets_preserve_messages() {
pyo3::prepare_freethreaded_python();
@@ -766,6 +945,15 @@ mod tests {
);
}
+ #[test]
+ fn map_git_error_invalid_ref_name_classification() {
+ let error = GitError::RefStore(RefStoreError::InvalidName("bad ref".into()));
+ assert_eq!(
+ classify_git_error(&error),
+ GitErrorMapping::PythonException("AGFSInvalidOperationError")
+ );
+ }
+
use pyo3::types::PyDict;
#[test]
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index f5d7458ba..d10db441c 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -1055,11 +1055,46 @@ impl RAGFSBindingClient {
let empty = PyDict::new(py);
let kw = kwargs.unwrap_or(&empty);
let req = git::parse_show_request(kw)?;
- let resp = py_detach_blocking(py, move || self.rt.block_on(svc.show(req)))
+ let max_blob_bytes = git::parse_show_max_blob_bytes(kw)?;
+ let resp = py_detach_blocking(py, move || {
+ self.rt.block_on(svc.show_with_limit(req, max_blob_bytes))
+ })
.map_err(|e| git::map_git_error(py, e))?;
git::show_response_to_pydict(py, resp)
}
+ /// Build a bounded unified text diff outside the Python interpreter.
+ #[pyo3(signature = (**kwargs))]
+ fn git_diff_text(
+ &self,
+ py: Python<'_>,
+ kwargs: Option<&Bound<'_, PyDict>>,
+ ) -> PyResult<String> {
+ let empty = PyDict::new(py);
+ let kw = kwargs.unwrap_or(&empty);
+ let req = git::parse_diff_text_request(kw)?;
+ let result = py_detach_blocking(py, move || {
+ git::build_bounded_unified_diff(
+ &req.before,
+ &req.after,
+ &req.fromfile,
+ &req.tofile,
+ req.timeout_ms,
+ req.max_output_bytes,
+ )
+ });
+ result.map_err(|err| match err {
+ git::BoundedDiffError::OutputTooLarge { limit } => git::new_py_err_pub(
+ py,
+ "AGFSResourceExhaustedError",
+ format!("snapshot diff output size limit exceeded ({limit} bytes)"),
+ ),
+ git::BoundedDiffError::Render(message) => {
+ git::new_py_err_pub(py, "AGFSInternalError", message)
+ }
+ })
+ }
+
/// Walk snapshot history, optionally filtered to commits touching paths.
#[pyo3(signature = (**kwargs))]
fn git_log(
diff --git a/crates/ragfs/src/git/backends/local.rs b/crates/ragfs/src/git/backends/local.rs
index 3aeb7dbc0..bb82e254c 100644
--- a/crates/ragfs/src/git/backends/local.rs
+++ b/crates/ragfs/src/git/backends/local.rs
@@ -104,6 +104,38 @@ impl ObjectStore for LocalObjectStore {
}
}
+ async fn get_limited(
+ &self,
+ account: &str,
+ oid: &ObjectId,
+ max_bytes: u64,
+ ) -> Result<Bytes, ObjectStoreError> {
+ let path = self.object_path(account, oid);
+ let size = match tokio::fs::metadata(&path).await {
+ Ok(metadata) => metadata.len(),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ return Err(ObjectStoreError::NotFound(*oid));
+ }
+ Err(e) => return Err(e.into()),
+ };
+ if size > max_bytes {
+ return Err(ObjectStoreError::ReadLimitExceeded {
+ size,
+ limit: max_bytes,
+ });
+ }
+
+ let bytes = tokio::fs::read(&path).await?;
+ let size = bytes.len() as u64;
+ if size > max_bytes {
+ return Err(ObjectStoreError::ReadLimitExceeded {
+ size,
+ limit: max_bytes,
+ });
+ }
+ Ok(Bytes::from(bytes))
+ }
+
async fn exists(&self, account: &str, oid: &ObjectId) -> Result<bool, ObjectStoreError> {
let path = self.object_path(account, oid);
tokio::fs::try_exists(&path)
diff --git a/crates/ragfs/src/git/backends/s3.rs b/crates/ragfs/src/git/backends/s3.rs
index 62d78f62b..e088106e0 100644
--- a/crates/ragfs/src/git/backends/s3.rs
+++ b/crates/ragfs/src/git/backends/s3.rs
@@ -8,6 +8,7 @@ use aws_sdk_s3::config::Credentials;
use aws_sdk_s3::config::Region;
use bytes::Bytes;
use gix_hash::ObjectId;
+use tokio::io::AsyncReadExt;
use crate::git::error::{ObjectStoreError, RefStoreError};
use crate::git::index_store::{
@@ -187,6 +188,65 @@ impl ObjectStore for S3ObjectStore {
}
}
+ async fn get_limited(
+ &self,
+ account: &str,
+ oid: &ObjectId,
+ max_bytes: u64,
+ ) -> Result<Bytes, ObjectStoreError> {
+ let key = self.object_key(account, oid);
+ let resp = match self
+ .client
+ .get_object()
+ .bucket(&self.bucket)
+ .key(&key)
+ .send()
+ .await
+ {
+ Ok(resp) => resp,
+ Err(err) => {
+ let err_str = format!("{:?}", err);
+ if err_str.to_lowercase().contains("no_such_key")
+ || err_str.to_lowercase().contains("404")
+ {
+ return Err(ObjectStoreError::NotFound(*oid));
+ }
+ return Err(ObjectStoreError::Backend(format!("S3 get error: {:?}", err)));
+ }
+ };
+
+ let content_length = resp.content_length();
+ if let Some(size) = content_length.filter(|size| *size >= 0) {
+ let size = size as u64;
+ if size > max_bytes {
+ return Err(ObjectStoreError::ReadLimitExceeded {
+ size,
+ limit: max_bytes,
+ });
+ }
+ }
+
+ let mut reader = resp.body.into_async_read().take(max_bytes.saturating_add(1));
+ let mut bytes = Vec::with_capacity(
+ content_length
+ .and_then(|size| usize::try_from(size).ok())
+ .unwrap_or(0)
+ .min(usize::try_from(max_bytes).unwrap_or(usize::MAX)),
+ );
+ reader
+ .read_to_end(&mut bytes)
+ .await
+ .map_err(|e| ObjectStoreError::Backend(format!("S3 read body error: {:?}", e)))?;
+ let size = bytes.len() as u64;
+ if size > max_bytes {
+ return Err(ObjectStoreError::ReadLimitExceeded {
+ size,
+ limit: max_bytes,
+ });
+ }
+ Ok(Bytes::from(bytes))
+ }
+
async fn exists(&self, account: &str, oid: &ObjectId) -> Result<bool, ObjectStoreError> {
let key = self.object_key(account, oid);
diff --git a/crates/ragfs/src/git/error.rs b/crates/ragfs/src/git/error.rs
index 80bd612eb..47ae45384 100644
--- a/crates/ragfs/src/git/error.rs
+++ b/crates/ragfs/src/git/error.rs
@@ -27,6 +27,15 @@ pub enum ObjectStoreError {
/// Backend-specific error
#[error("backend error: {0}")]
Backend(String),
+
+ /// Object retrieval exceeded the caller-provided byte budget.
+ #[error("object read limit exceeded: {size} bytes exceeds limit {limit} bytes")]
+ ReadLimitExceeded {
+ /// Number of bytes observed or declared by the object.
+ size: u64,
+ /// Maximum number of bytes permitted by the caller.
+ limit: u64,
+ },
}
/// Errors from RefStore operations
diff --git a/crates/ragfs/src/git/object_store.rs b/crates/ragfs/src/git/object_store.rs
index abdbfddc3..2977de2b5 100644
--- a/crates/ragfs/src/git/object_store.rs
+++ b/crates/ragfs/src/git/object_store.rs
@@ -31,11 +31,34 @@ pub trait ObjectStore: Send + Sync + 'static {
zlib_body: Bytes,
) -> Result<(), ObjectStoreError>;
- /// Read and decompress an object.
+ /// Read a compressed loose object.
///
- /// Returns the full uncompressed bytes (including Git header: "type size\0content").
+ /// Returns the zlib-compressed bytes written by [`ObjectStore::put`].
async fn get(&self, account: &str, oid: &ObjectId) -> Result<Bytes, ObjectStoreError>;
+ /// Read a compressed loose object without exceeding `max_bytes`.
+ ///
+ /// Production backends should override this method so the limit is checked
+ /// before the complete object is materialized. The default preserves
+ /// compatibility for custom stores while still enforcing the contract
+ /// before returning to the caller.
+ async fn get_limited(
+ &self,
+ account: &str,
+ oid: &ObjectId,
+ max_bytes: u64,
+ ) -> Result<Bytes, ObjectStoreError> {
+ let bytes = self.get(account, oid).await?;
+ let size = bytes.len() as u64;
+ if size > max_bytes {
+ return Err(ObjectStoreError::ReadLimitExceeded {
+ size,
+ limit: max_bytes,
+ });
+ }
+ Ok(bytes)
+ }
+
/// Check if an object exists without reading its content.
///
/// This is an optimization path - implementations should use the cheapest
diff --git a/crates/ragfs/src/git/service.rs b/crates/ragfs/src/git/service.rs
index 818050dad..c83488fec 100644
--- a/crates/ragfs/src/git/service.rs
+++ b/crates/ragfs/src/git/service.rs
@@ -762,6 +762,15 @@ impl GitService {
/// Missing ref → `GitError::RefStore(RefStoreError::NotFound)`.
/// Missing commit object → `GitError::ObjectStore(ObjectStoreError::NotFound)`.
pub async fn show(&self, req: ShowRequest) -> Result<ShowResponse, GitError> {
+ self.show_with_limit(req, None).await
+ }
+
+ /// Same as [`GitService::show`], with an optional maximum blob payload size.
+ pub async fn show_with_limit(
+ &self,
+ req: ShowRequest,
+ max_blob_bytes: Option<u64>,
+ ) -> Result<ShowResponse, GitError> {
let ShowRequest {
account,
target_ref,
@@ -804,15 +813,41 @@ impl GitService {
if mode.is_tree() {
return Err(GitError::PathIsDirectory(p));
}
- let raw =
- crate::git::util::read_object(self.object_store.as_ref(), &account, &blob_oid)
- .await?;
+ let raw = match max_blob_bytes {
+ Some(limit) => crate::git::util::read_object_limited(
+ self.object_store.as_ref(),
+ &account,
+ &blob_oid,
+ limit,
+ )
+ .await
+ .map_err(|err| match err {
+ ObjectStoreError::ReadLimitExceeded { size, .. } => {
+ GitError::BlobTooLarge { size, limit }
+ }
+ other => GitError::ObjectStore(other),
+ })?,
+ None => crate::git::util::read_object(
+ self.object_store.as_ref(),
+ &account,
+ &blob_oid,
+ )
+ .await?,
+ };
let (kind, payload_size, hdr) = crate::git::util::parse_object_header(&raw)?;
if kind != gix_object::Kind::Blob {
return Err(GitError::CorruptedObject(format!(
"expected blob at {p}, got {kind:?}"
)));
}
+ if let Some(limit) = max_blob_bytes {
+ if payload_size > limit {
+ return Err(GitError::BlobTooLarge {
+ size: payload_size,
+ limit,
+ });
+ }
+ }
// `raw` is already a `Bytes`; `slice` is O(1) and shares the
// backing buffer instead of allocating a fresh payload copy.
let bytes = raw.slice(hdr..);
@@ -3541,6 +3576,55 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_show_blob_limit_rejects_before_returning_payload() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct");
+ vfs.put("resources/a.md", b"payload exceeds limit");
+ let _ = make_commit(&svc, "acct", "main", "first").await;
+
+ let err = svc
+ .show_with_limit(
+ ShowRequest {
+ account: "acct".into(),
+ target_ref: "main".into(),
+ path: Some("resources/a.md".into()),
+ },
+ Some(4),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, GitError::BlobTooLarge { size: 21, limit: 4 }));
+ }
+
+ #[tokio::test]
+ async fn test_show_blob_limit_allows_payload_at_limit() {
+ let (_dir, vfs, _object_store, _ref_store, svc) = make_service("acct");
+ vfs.put("resources/a.md", b"payload");
+ let _ = make_commit(&svc, "acct", "main", "first").await;
+
+ let response = svc
+ .show_with_limit(
+ ShowRequest {
+ account: "acct".into(),
+ target_ref: "main".into(),
+ path: Some("resources/a.md".into()),
+ },
+ Some(7),
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ response,
+ ShowResponse::Blob {
+ bytes,
+ size: 7,
+ ..
+ } if bytes.as_ref() == b"payload"
+ ));
+ }
+
// ── 12 ─────────────────────────────────────────────────────────────
#[tokio::test]
async fn test_show_blob_path_not_found() {
diff --git a/crates/ragfs/src/git/util.rs b/crates/ragfs/src/git/util.rs
index cee57cd94..a393c178e 100644
--- a/crates/ragfs/src/git/util.rs
+++ b/crates/ragfs/src/git/util.rs
@@ -87,6 +87,73 @@ pub async fn read_object(
Ok(Bytes::from(decompressed))
}
+/// Read and decompress a loose object while bounding both compressed and
+/// decompressed materialization. `max_payload_bytes` excludes the Git header.
+pub async fn read_object_limited(
+ store: &dyn crate::git::object_store::ObjectStore,
+ account: &str,
+ oid: &gix_hash::ObjectId,
+ max_payload_bytes: u64,
+) -> Result<Bytes, crate::git::error::ObjectStoreError> {
+ const MAX_LOOSE_HEADER_BYTES: u64 = 64;
+ let max_loose_bytes = max_payload_bytes.saturating_add(MAX_LOOSE_HEADER_BYTES);
+ let compressed_limit = zlib_compress_bound(max_loose_bytes);
+ let compressed = store.get_limited(account, oid, compressed_limit).await?;
+
+ let mut decoder = flate2::read::ZlibDecoder::new(compressed.as_ref());
+ let mut header = Vec::with_capacity(MAX_LOOSE_HEADER_BYTES as usize);
+ loop {
+ if header.len() >= MAX_LOOSE_HEADER_BYTES as usize {
+ return Err(crate::git::error::ObjectStoreError::Backend(
+ "invalid object header: exceeds 64 bytes".to_string(),
+ ));
+ }
+ let mut byte = [0u8; 1];
+ let read = decoder.read(&mut byte)?;
+ if read == 0 {
+ return Err(crate::git::error::ObjectStoreError::Backend(
+ "invalid object header: missing terminator".to_string(),
+ ));
+ }
+ header.push(byte[0]);
+ if byte[0] == 0 {
+ break;
+ }
+ }
+
+ let (_, payload_size, _) = parse_object_header(&header)?;
+ if payload_size > max_payload_bytes {
+ return Err(crate::git::error::ObjectStoreError::ReadLimitExceeded {
+ size: payload_size,
+ limit: max_payload_bytes,
+ });
+ }
+
+ let payload_limit = payload_size.saturating_add(1);
+ let mut payload = Vec::with_capacity(usize::try_from(payload_size).unwrap_or(usize::MAX));
+ decoder
+ .take(payload_limit)
+ .read_to_end(&mut payload)
+ .map_err(|e| crate::git::error::ObjectStoreError::Zlib(e.to_string()))?;
+ if payload.len() as u64 != payload_size {
+ return Err(crate::git::error::ObjectStoreError::Backend(format!(
+ "invalid object payload: header declares {payload_size} bytes, decoded {}",
+ payload.len()
+ )));
+ }
+
+ header.extend_from_slice(&payload);
+ Ok(Bytes::from(header))
+}
+
+fn zlib_compress_bound(source_len: u64) -> u64 {
+ source_len
+ .saturating_add(source_len >> 12)
+ .saturating_add(source_len >> 14)
+ .saturating_add(source_len >> 25)
+ .saturating_add(13)
+}
+
/// Serialize, compress, and write a Git object to ObjectStore.
/// Returns the object's ObjectId.
pub async fn write_object(
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index a12d4c9b7..a2f230b87 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -470,6 +470,7 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m
| POST | `/api/v1/snapshot/commit` | Save the current workspace state as a new snapshot |
| GET | `/api/v1/snapshot/log` | Walk commit history newest-first |
| GET | `/api/v1/snapshot/show` | View commit metadata, or read a file from a commit |
+| GET | `/api/v1/snapshot/diff` | Compare one file between two snapshots |
| POST | `/api/v1/snapshot/restore` | Restore a directory or the whole account tree to a past snapshot (forward commit) |
### Content
@@ -606,7 +607,7 @@ Subsequent API documentation is organized by functional module as follows:
| [Resources](02-resources.md) - Resource management API | Adding, importing, exporting resources and skills |
| [Retrieval](06-retrieval.md) - Search API | Search, relations, context acquisition |
| [File System](03-filesystem.md) - File system operations | Directory operations, content reading and writing |
-| [Snapshots](11-snapshot.md) - Multi-version management | Snapshot commit, history walk, version restore |
+| [Snapshots](11-snapshot.md) - Multi-version management | Snapshot commit, history walk, single-file diff, version restore |
| [Sessions](05-sessions.md) - Session management | Session creation, message management, memory extraction |
| [Skills](04-skills.md) - Skill management API | Skill management |
| [System](07-system.md) - System and monitoring API | System status, monitoring, debug API |
diff --git a/docs/en/api/11-snapshot.md b/docs/en/api/11-snapshot.md
index e7bf6d874..3b98f6b26 100644
--- a/docs/en/api/11-snapshot.md
+++ b/docs/en/api/11-snapshot.md
@@ -4,13 +4,14 @@ On top of VikingFS, OpenViking provides Git-based multi-version management, call
Snapshots are powered by [gitoxide](https://github.com/Byron/gitoxide) embedded in the Rust RAGFS layer, maintaining one logical Git repository per `account_id`. This is fully transparent to callers — you never touch a `.ovgit` directory, the object store, or ref internals.
-The four core commands:
+The five core commands:
| Command | Purpose |
|---------|---------|
| `commit` | Save the current workspace state as a new snapshot |
| `log` | Walk commit history starting from the newest |
| `show` | View a commit's metadata, or read a file's content from that commit |
+| `diff` | Compare one file between two snapshots as a unified diff |
| `restore` | Restore a directory (or the whole account tree) to a past snapshot |
In addition, account-level `.ovgitignore` exclusion rules can be managed (`get`/`set`/`delete`) to exclude matching files from `commit`. See [Ignore management](#ignore-management).
@@ -26,7 +27,7 @@ In addition, account-level `.ovgitignore` exclusion rules can be managed (`get`/
- HTTP routes: [snapshot.py](https://github.com/volcengine/OpenViking/blob/main/openviking/server/routers/snapshot.py), prefix `/api/v1/snapshot`.
- SDK namespace: [snapshot_namespace.py](https://github.com/volcengine/OpenViking/blob/main/openviking/snapshot_namespace.py), exposed as `client.snapshot.*`.
-- Underlying semantics: `commit` / `restore` / `show` / `log` in [viking_fs.py](https://github.com/volcengine/OpenViking/blob/main/openviking/storage/viking_fs.py).
+- Underlying semantics: `commit` / `restore` / `show` / `log` / `diff` in [viking_fs.py](https://github.com/volcengine/OpenViking/blob/main/openviking/storage/viking_fs.py).
- CLI: the `SnapshotCmd` in [main.rs](https://github.com/volcengine/OpenViking/blob/main/crates/ov_cli/src/main.rs), subcommands in [snapshot.rs](https://github.com/volcengine/OpenViking/blob/main/crates/ov_cli/src/commands/snapshot.rs).
## API Reference
@@ -298,6 +299,58 @@ ov snapshot show 3f2a1b9c --path viking://resources/my_project/guide.md --out-fi
---
+### diff()
+
+Compare one UTF-8 file between two snapshot refs and return a unified diff. `to_ref` is required. When `from_ref` is omitted, the older side is treated as an empty file, which is useful for displaying the initial version.
+
+**Python SDK (Embedded / HTTP)**
+
+```python
+result = client.snapshot.diff(
+ "viking://resources/my_project/guide.md",
+ from_ref="3f2a1b9c",
+ to_ref="9a0b1c2d",
+)
+print(result["diff_text"])
+```
+
+**TypeScript SDK**
+
+```typescript
+const result = await client.gitDiff(
+ "viking://resources/my_project/guide.md",
+ "9a0b1c2d",
+ "3f2a1b9c",
+);
+console.log(result.diff_text);
+```
+
+**HTTP API**
+
+```
+GET /api/v1/snapshot/diff?path={uri}&from={old_ref}&to={new_ref}
+```
+
+```bash
+curl --get "http://localhost:1933/api/v1/snapshot/diff" \
+ --data-urlencode "path=viking://resources/my_project/guide.md" \
+ --data-urlencode "from=3f2a1b9c" \
+ --data-urlencode "to=9a0b1c2d" \
+ -H "X-API-Key: your-key"
+```
+
+**CLI**
+
+```bash
+ov snapshot diff viking://resources/my_project/guide.md \
+ --from 3f2a1b9c \
+ --to 9a0b1c2d
+```
+
+The response contains `path`, resolved `from_commit` and `to_commit`, `change_type` (`added`, `deleted`, `modified`, or `unchanged`), and `diff_text`. Each side is limited to 10 MiB and 100,000 lines, and the generated diff is limited to 20 MiB; larger requests return `RESOURCE_EXHAUSTED` rather than a truncated diff.
+
+---
+
### restore()
Restore a directory (or the whole account tree) to its state at `source_commit`.
diff --git a/docs/scripts/check-api-reference.mjs b/docs/scripts/check-api-reference.mjs
index 573046e6d..30d8947bf 100644
--- a/docs/scripts/check-api-reference.mjs
+++ b/docs/scripts/check-api-reference.mjs
@@ -66,6 +66,7 @@ function splitTopLevel(source) {
}
const routes = new Map()
+const middlewareQueryParameters = new Set(['profile'])
for (const file of fs.readdirSync(routerDir).filter((name) => name.endsWith('.py'))) {
const source = fs.readFileSync(path.join(routerDir, file), 'utf8')
const prefix = source.match(/router\s*=\s*APIRouter\([^)]*prefix=["']([^"']+)/s)?.[1] ?? ''
@@ -82,7 +83,8 @@ for (const file of fs.readdirSync(routerDir).filter((name) => name.endsWith('.py
for (const parameter of splitTopLevel(signature)) {
const queryMatch = parameter.match(/^([A-Za-z_]\w*)\s*:[\s\S]*?=\s*Query\(([\s\S]*)\)$/)
if (queryMatch) {
- query.set(queryMatch[1], /^\s*\.\.\.(?:\s*,|\s*$)/.test(queryMatch[2]))
+ const alias = queryMatch[2].match(/\balias\s*=\s*["']([^"']+)["']/)?.[1]
+ query.set(alias ?? queryMatch[1], /^\s*\.\.\.(?:\s*,|\s*$)/.test(queryMatch[2]))
continue
}
@@ -121,15 +123,42 @@ const errors = []
let httpExamples = 0
let typescriptCalls = 0
const curlUrlPattern = String.raw`["']?https?:\/\/[^/\s"']+(\/[A-Za-z0-9_{}<>?=&./:-]+)`
-const explicitCurlPattern = new RegExp(
- String.raw`\bcurl\b[^\n]*?(?:-X|--request)\s+(GET|POST|PUT|PATCH|DELETE)\s+` +
- curlUrlPattern,
- 'g'
-)
-const implicitGetCurlPattern = new RegExp(
- String.raw`\bcurl\b(?![^\n]*(?:-X|--request))[^\n]*?` + curlUrlPattern,
- 'g'
-)
+
+function curlReferences(source) {
+ const references = []
+ for (const match of source.matchAll(/\bcurl\b[^\n]*(?:\r?\n[ \t]+(?:--|-H\b)[^\n]*)*/g)) {
+ const command = match[0]
+ const url = command.match(new RegExp(curlUrlPattern))
+ if (!url) continue
+
+ const explicitMethod = command.match(
+ /(?:-X|--request)\s+(GET|POST|PUT|PATCH|DELETE)\b/
+ )?.[1]
+ const method = explicitMethod ?? 'GET'
+ let documentedPath = url[1]
+ const queryNames = Array.from(
+ command.matchAll(/--data-urlencode\s+["']?([A-Za-z_]\w*)=/g),
+ (item) => item[1]
+ )
+ if (queryNames.length) {
+ const existingNames = new Set(
+ (documentedPath.split('?')[1] ?? '')
+ .split('&')
+ .filter(Boolean)
+ .map((item) => item.split('=')[0])
+ )
+ const missing = queryNames.filter((name) => !existingNames.has(name))
+ if (missing.length) {
+ documentedPath += `${documentedPath.includes('?') ? '&' : '?'}${missing
+ .map((name) => `${name}={}`)
+ .join('&')}`
+ }
+ }
+ references.push([method, documentedPath])
+ }
+ return references
+}
+
for (const file of apiDocs) {
const source = fs.readFileSync(file, 'utf8')
const relative = path.relative(repoRoot, file)
@@ -138,14 +167,7 @@ for (const file of apiDocs) {
source.matchAll(/^\s*(GET|POST|PUT|PATCH|DELETE)\s+(\/[A-Za-z0-9_{}?=&./:-]+)/gm),
(match) => [match[1], match[2]]
),
- ...Array.from(
- source.matchAll(explicitCurlPattern),
- (match) => [match[1], match[2]]
- ),
- ...Array.from(
- source.matchAll(implicitGetCurlPattern),
- (match) => ['GET', match[1]]
- )
+ ...curlReferences(source)
]
for (const [method, documentedPath] of httpReferences) {
const normalizedPath = normalizePath(documentedPath)
@@ -191,7 +213,7 @@ for (const file of apiDocs) {
.map((item) => item.split('=')[0])
)
for (const name of queryNames) {
- if (!contract.query.has(name)) {
+ if (!contract.query.has(name) && !middlewareQueryParameters.has(name)) {
errors.push(`${relative}: ${route} has unknown query parameter ${name}`)
}
}
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 8936e5081..4c2c195c2 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -465,6 +465,7 @@ JSON 输出 - 错误:
| POST | `/api/v1/snapshot/commit` | 把当前工作区状态保存成新快照 |
| GET | `/api/v1/snapshot/log` | 从最新提交开始回溯历史 |
| GET | `/api/v1/snapshot/show` | 查看提交元数据,或读取提交中某个文件 |
+| GET | `/api/v1/snapshot/diff` | 对比某个文件在两个快照中的内容 |
| POST | `/api/v1/snapshot/restore` | 恢复目录或整棵账号树到某个历史快照(正向提交) |
### 内容端点
@@ -600,7 +601,7 @@ VikingBot API 需要服务器启动时指定 `--with-bot` 选项:
|------|------|
| [资源管理](02-resources.md) | 资源和技能的添加、导入、导出 |
| [文件系统](03-filesystem.md) | 目录操作、内容读写 |
-| [多版本管理](11-snapshot.md) | 快照提交、历史回溯、版本恢复 |
+| [多版本管理](11-snapshot.md) | 快照提交、历史回溯、单文件差异、版本恢复 |
| [技能](04-skills.md) | 技能管理 API |
| [会话管理](05-sessions.md) | 会话创建、消息管理、记忆提取 |
| [检索](06-retrieval.md) | 搜索、关联、上下文获取 |
diff --git a/docs/zh/api/11-snapshot.md b/docs/zh/api/11-snapshot.md
index ff8a63c2b..a005389f8 100644
--- a/docs/zh/api/11-snapshot.md
+++ b/docs/zh/api/11-snapshot.md
@@ -4,13 +4,14 @@ OpenViking 在 VikingFS 之上提供了一套基于 Git 的多版本管理能力
快照能力底层由内嵌在 Rust RAGFS 层的 [gitoxide](https://github.com/Byron/gitoxide) 驱动,按 `account_id` 维护一个逻辑 Git 仓库(每个账号一个仓库),对调用方完全透明——你无需关心 `.ovgit` 目录、对象库或引用细节。
-四个核心命令:
+五个核心命令:
| 命令 | 作用 |
|------|------|
| `commit` | 把当前工作区状态保存成一个新快照 |
| `log` | 从最新提交开始回溯历史 |
| `show` | 查看某个提交的元数据,或读取该提交中某个文件的内容 |
+| `diff` | 以 unified diff 格式对比某个文件在两个快照中的内容 |
| `restore` | 把目录(或整棵账号树)恢复到某个历史快照的状态 |
此外还提供账号级 `.ovgitignore` 排除规则的管理命令(`get`/`set`/`delete`),用于在 `commit` 时按规则排除匹配的文件。详见 [ignore 管理](#ignore-管理)。
@@ -26,7 +27,7 @@ OpenViking 在 VikingFS 之上提供了一套基于 Git 的多版本管理能力
- HTTP 路由:[snapshot.py](https://github.com/volcengine/OpenViking/blob/main/openviking/server/routers/snapshot.py),前缀 `/api/v1/snapshot`。
- 命名空间(SDK):[snapshot_namespace.py](https://github.com/volcengine/OpenViking/blob/main/openviking/snapshot_namespace.py),暴露为 `client.snapshot.*`。
-- 底层语义实现:[viking_fs.py](https://github.com/volcengine/OpenViking/blob/main/openviking/storage/viking_fs.py) 的 `commit` / `restore` / `show` / `log`。
+- 底层语义实现:[viking_fs.py](https://github.com/volcengine/OpenViking/blob/main/openviking/storage/viking_fs.py) 的 `commit` / `restore` / `show` / `log` / `diff`。
- CLI 命令:[main.rs](https://github.com/volcengine/OpenViking/blob/main/crates/ov_cli/src/main.rs) 的 `SnapshotCmd`,子命令 [snapshot.rs](https://github.com/volcengine/OpenViking/blob/main/crates/ov_cli/src/commands/snapshot.rs)。
## API 参考
@@ -298,6 +299,58 @@ ov snapshot show 3f2a1b9c --path viking://resources/my_project/guide.md --out-fi
---
+### diff()
+
+对比一个 UTF-8 文件在两个快照引用中的内容,并返回 unified diff。`to_ref` 必填;省略 `from_ref` 时,旧版本按空文件处理,可用于展示文件的初始版本。
+
+**Python SDK (Embedded / HTTP)**
+
+```python
+result = client.snapshot.diff(
+ "viking://resources/my_project/guide.md",
+ from_ref="3f2a1b9c",
+ to_ref="9a0b1c2d",
+)
+print(result["diff_text"])
+```
+
+**TypeScript SDK**
+
+```typescript
+const result = await client.gitDiff(
+ "viking://resources/my_project/guide.md",
+ "9a0b1c2d",
+ "3f2a1b9c",
+);
+console.log(result.diff_text);
+```
+
+**HTTP API**
+
+```
+GET /api/v1/snapshot/diff?path={uri}&from={old_ref}&to={new_ref}
+```
+
+```bash
+curl --get "http://localhost:1933/api/v1/snapshot/diff" \
+ --data-urlencode "path=viking://resources/my_project/guide.md" \
+ --data-urlencode "from=3f2a1b9c" \
+ --data-urlencode "to=9a0b1c2d" \
+ -H "X-API-Key: your-key"
+```
+
+**CLI**
+
+```bash
+ov snapshot diff viking://resources/my_project/guide.md \
+ --from 3f2a1b9c \
+ --to 9a0b1c2d
+```
+
+响应包含 `path`、解析后的 `from_commit` 和 `to_commit`、`change_type`(`added`、`deleted`、`modified` 或 `unchanged`)以及 `diff_text`。参与对比的单侧文件上限为 10 MiB 和 100,000 行,生成的 diff 上限为 20 MiB;超限时返回 `RESOURCE_EXHAUSTED`,不会返回被截断的 diff。
+
+---
+
### restore()
把某个目录(或整棵账号树)恢复到 `source_commit` 时的状态。
diff --git a/openviking/client/local.py b/openviking/client/local.py
index bcccbed61..aecce6b78 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -1185,6 +1185,21 @@ class LocalClient(BaseClient):
"""Walk back along parents[0] up to limit commits."""
return await self._service.fs.log(branch=branch, limit=limit, paths=paths, ctx=self._ctx)
+ async def git_diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ return await self._service.fs.diff(
+ path=path,
+ from_ref=from_ref,
+ to_ref=to_ref,
+ ctx=self._ctx,
+ )
+
async def git_get_ignore(self) -> str:
"""Return the account .ovgitignore content (empty string if absent)."""
return await self._service.fs.get_gitignore(ctx=self._ctx)
diff --git a/openviking/pyagfs/__init__.py b/openviking/pyagfs/__init__.py
index 42cb721f2..bf99e99b5 100644
--- a/openviking/pyagfs/__init__.py
+++ b/openviking/pyagfs/__init__.py
@@ -30,8 +30,10 @@ from .exceptions import (
AGFSNotADirectoryError,
AGFSNotFoundError,
AGFSNotSupportedError,
+ AGFSPathNotFoundError,
AGFSPermissionDeniedError,
AGFSPluginError,
+ AGFSResourceExhaustedError,
AGFSSerializationError,
AGFSTimeoutError,
GitConcurrentCommitError,
@@ -166,6 +168,7 @@ __all__ = [
"AGFSHTTPError",
"AGFSNotSupportedError",
"AGFSNotFoundError",
+ "AGFSPathNotFoundError",
"AGFSAlreadyExistsError",
"AGFSFileExistsError",
"AGFSPermissionDeniedError",
@@ -174,6 +177,7 @@ __all__ = [
"AGFSIsADirectoryError",
"AGFSDirectoryNotEmptyError",
"AGFSInvalidOperationError",
+ "AGFSResourceExhaustedError",
"AGFSIoError",
"AGFSConfigError",
"AGFSMountPointNotFoundError",
diff --git a/openviking/pyagfs/exceptions.py b/openviking/pyagfs/exceptions.py
index 36ec261f2..1087b4001 100644
--- a/openviking/pyagfs/exceptions.py
+++ b/openviking/pyagfs/exceptions.py
@@ -39,6 +39,12 @@ class AGFSNotFoundError(AGFSClientError):
pass
+class AGFSPathNotFoundError(AGFSNotFoundError):
+ """Path not found inside a snapshot tree"""
+
+ pass
+
+
class AGFSAlreadyExistsError(AGFSClientError):
"""File or directory already exists"""
@@ -87,6 +93,12 @@ class AGFSInvalidOperationError(AGFSClientError):
pass
+class AGFSResourceExhaustedError(AGFSClientError):
+ """Operation exceeded a configured resource limit"""
+
+ pass
+
+
class AGFSIoError(AGFSClientError):
"""I/O error"""
diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.py
index 6c10b1370..dcfa11256 100644
--- a/openviking/server/error_mapping.py
+++ b/openviking/server/error_mapping.py
@@ -24,6 +24,7 @@ from openviking.pyagfs.exceptions import (
AGFSNotSupportedError,
AGFSPermissionDeniedError,
AGFSPluginError,
+ AGFSResourceExhaustedError,
AGFSSerializationError,
AGFSTimeoutError,
GitConcurrentCommitError,
@@ -38,6 +39,7 @@ from openviking_cli.exceptions import (
NotFoundError,
OpenVikingError,
PermissionDeniedError,
+ ResourceExhaustedError,
UnavailableError,
UnimplementedError,
)
@@ -515,6 +517,8 @@ def map_exception(
return InvalidArgumentError(str(exc), details=_file_directory_details(resource))
if isinstance(exc, AGFSDirectoryNotEmptyError):
return FailedPreconditionError(str(exc), details=_resource_details(resource))
+ if isinstance(exc, AGFSResourceExhaustedError):
+ return ResourceExhaustedError(str(exc), details=_resource_details(resource))
if isinstance(exc, AGFSInvalidOperationError):
return InvalidArgumentError(str(exc), details=_resource_details(resource))
if isinstance(
diff --git a/openviking/server/routers/snapshot.py b/openviking/server/routers/snapshot.py
index 6c83ea56e..af6d10f83 100644
--- a/openviking/server/routers/snapshot.py
+++ b/openviking/server/routers/snapshot.py
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""HTTP routes for git-style version control (snapshots).
-Mirrors VikingFS.commit / VikingFS.restore / VikingFS.show / VikingFS.log,
+Mirrors VikingFS.commit / VikingFS.restore / VikingFS.show / VikingFS.diff / VikingFS.log,
which already implement the underlying semantics.
"""
@@ -187,6 +187,34 @@ async def show(
)
+async def diff(
+ path: str = Query(..., description="Viking URI of the file to compare"),
+ from_ref: Optional[str] = Query(
+ None,
+ alias="from",
+ description="Base commit oid, branch, or tag; omit to compare against an empty file",
+ ),
+ to_ref: str = Query(..., alias="to", description="Target commit oid, branch, or tag"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Return a unified text diff for one path between two snapshots."""
+ service = get_service()
+ try:
+ result = await service.fs.diff(
+ path=path,
+ from_ref=from_ref,
+ to_ref=to_ref,
+ ctx=_ctx,
+ )
+ except (AGFSClientError, ValueError) as exc:
+ mapped = map_exception(exc)
+ if mapped is not None:
+ raise mapped from exc
+ raise
+ return Response(status="ok", result=result)
+
+
@router.get("/ignore")
async def get_ignore(
_ctx: RequestContext = Depends(get_request_context),
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index b6c254e99..1ed9782be 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -662,6 +662,19 @@ class FSService:
path = validate_viking_uri(path, field_name="path")
return await viking_fs.show_blob_raw(target_ref, path=path, ctx=ctx)
+ async def diff(
+ self,
+ *,
+ path: str,
+ from_ref: Optional[str],
+ to_ref: str,
+ ctx: RequestContext,
+ ) -> Dict[str, Any]:
+ """Return a unified text diff for one path between two snapshots."""
+ viking_fs = self._ensure_initialized()
+ path = validate_viking_uri(path, field_name="path")
+ return await viking_fs.diff(path=path, from_ref=from_ref, to_ref=to_ref, ctx=ctx)
+
async def log(
self,
ctx: RequestContext,
diff --git a/openviking/snapshot_namespace.py b/openviking/snapshot_namespace.py
index 4c7f181a8..7198d2f7b 100644
--- a/openviking/snapshot_namespace.py
+++ b/openviking/snapshot_namespace.py
@@ -9,7 +9,7 @@ underneath.
"""
from __future__ import annotations
-from typing import Any, Dict, List, Optional, TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
from openviking_cli.utils import run_async
@@ -86,6 +86,21 @@ class AsyncSnapshotNamespace:
await self._client._ensure_initialized()
return await self._client._client.git_log(branch=branch, limit=limit, paths=paths)
+ async def diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ await self._client._ensure_initialized()
+ return await self._client._client.git_diff(
+ path,
+ from_ref=from_ref,
+ to_ref=to_ref,
+ )
+
async def get_gitignore(self) -> str:
"""Return the account .ovgitignore content (empty string if absent)."""
await self._client._ensure_initialized()
@@ -174,6 +189,18 @@ class SyncSnapshotNamespace:
) -> List[Dict[str, Any]]:
return run_async(self._ns().log(branch=branch, limit=limit, paths=paths))
+ def diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ return run_async(
+ self._ns().diff(path, from_ref=from_ref, to_ref=to_ref)
+ )
+
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 939695624..1e1676073 100644
--- a/openviking/storage/viking_fs.py
+++ b/openviking/storage/viking_fs.py
@@ -40,7 +40,10 @@ from openviking.pyagfs.exceptions import (
AGFSDirectoryNotEmptyError,
AGFSHTTPError,
AGFSInvalidOperationError,
+ AGFSNotFoundError,
AGFSNotSupportedError,
+ AGFSPathNotFoundError,
+ AGFSResourceExhaustedError,
)
from openviking.resource.watch_storage import is_watch_task_control_uri
from openviking.server.error_mapping import is_not_found_error, map_exception
@@ -58,6 +61,7 @@ from openviking_cli.exceptions import (
InvalidArgumentError,
NotFoundError,
PermissionDeniedError,
+ ResourceExhaustedError,
)
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.config.grep_config import GrepEngine
@@ -79,9 +83,66 @@ logger = get_logger(__name__)
# materializes its first 1000 subdirectories. Pass this explicitly at those
# call sites.
LS_ALL_NODES = 2**31 - 1
+SNAPSHOT_DIFF_MAX_FILE_BYTES = 10 * 1024 * 1024
+SNAPSHOT_DIFF_MAX_OUTPUT_BYTES = 20 * 1024 * 1024
+SNAPSHOT_DIFF_MAX_LINES = 100_000
+SNAPSHOT_DIFF_TIMEOUT_MS = 500
_T = TypeVar("_T")
+def _snapshot_line_count(text: str) -> int:
+ if not text:
+ return 0
+ line_breaks = (
+ "\n",
+ "\r",
+ "\v",
+ "\f",
+ "\x1c",
+ "\x1d",
+ "\x1e",
+ "\x85",
+ "\u2028",
+ "\u2029",
+ )
+ count = sum(text.count(separator) for separator in line_breaks)
+ count -= text.count("\r\n")
+ return count if text.endswith(line_breaks) else count + 1
+
+
+def _prepare_snapshot_diff(
+ *,
+ path: str,
+ before_bytes: Optional[bytes],
+ after_bytes: Optional[bytes],
+ max_lines: int,
+) -> tuple[str, str, str]:
+ try:
+ before = before_bytes.decode("utf-8") if before_bytes is not None else ""
+ after = after_bytes.decode("utf-8") if after_bytes is not None else ""
+ except UnicodeDecodeError as exc:
+ raise InvalidArgumentError("snapshot diff only supports UTF-8 text files") from exc
+
+ for text in (before, after):
+ line_count = _snapshot_line_count(text)
+ if line_count > max_lines:
+ raise ResourceExhaustedError(
+ f"snapshot diff line count limit exceeded ({max_lines} lines per file)",
+ details={"limit_lines": max_lines, "path": path},
+ )
+
+ if before_bytes is None:
+ change_type = "added"
+ elif after_bytes is None:
+ change_type = "deleted"
+ elif before_bytes == after_bytes:
+ change_type = "unchanged"
+ else:
+ change_type = "modified"
+
+ return change_type, before, after
+
+
def _ensure_non_empty_search_query(query: str, image_url: Optional[str] = None) -> None:
if not query.strip() and not image_url:
raise InvalidArgumentError("Search query or image_url must not be empty.")
@@ -3996,6 +4057,7 @@ class VikingFS:
target_ref: str,
*,
path: Optional[str] = None,
+ max_blob_bytes: Optional[int] = None,
ctx: Optional[RequestContext] = None,
) -> Union[Dict[str, Any], bytes]:
"""Read a commit's metadata or a single blob.
@@ -4007,12 +4069,14 @@ class VikingFS:
real_ctx = self._ctx_or_default(ctx)
account = real_ctx.account_id
tree_path = self._uri_to_tree_path(path, ctx=real_ctx) if path else None
- resp = await self._async_agfs.run(
- "git_show",
- account=account,
- target_ref=target_ref,
- path=tree_path,
- )
+ kwargs: Dict[str, Any] = {
+ "account": account,
+ "target_ref": target_ref,
+ "path": tree_path,
+ }
+ if max_blob_bytes is not None:
+ kwargs["max_blob_bytes"] = max_blob_bytes
+ resp = await self._async_agfs.run("git_show", **kwargs)
if path is not None and isinstance(resp, dict) and "bytes" in resp:
return resp["bytes"]
return resp
@@ -4045,6 +4109,96 @@ class VikingFS:
)
return resp
+ async def diff(
+ self,
+ *,
+ path: str,
+ from_ref: Optional[str],
+ to_ref: str,
+ ctx: Optional[RequestContext] = None,
+ ) -> Dict[str, Any]:
+ """Return a unified text diff for one path between two snapshots."""
+ real_ctx = self._ctx_or_default(ctx)
+ path = canonicalize_uri(path, ctx=real_ctx)
+ self._ensure_access(path, real_ctx)
+
+ from_meta: Optional[Dict[str, Any]] = None
+ if from_ref:
+ try:
+ from_meta = await self.show(from_ref, ctx=real_ctx)
+ except AGFSNotFoundError as exc:
+ raise NotFoundError(from_ref, "git_ref") from exc
+ try:
+ to_meta = await self.show(to_ref, ctx=real_ctx)
+ except AGFSNotFoundError as exc:
+ raise NotFoundError(to_ref, "git_ref") from exc
+
+ from_oid = str(from_meta.get("oid", from_ref)) if isinstance(from_meta, dict) else ""
+ to_oid = str(to_meta.get("oid", to_ref)) if isinstance(to_meta, dict) else to_ref
+
+ async def read_optional(ref: str) -> Optional[bytes]:
+ try:
+ value = await self.show(
+ ref,
+ path=path,
+ max_blob_bytes=SNAPSHOT_DIFF_MAX_FILE_BYTES,
+ ctx=real_ctx,
+ )
+ except AGFSPathNotFoundError:
+ return None
+ except AGFSResourceExhaustedError as exc:
+ raise ResourceExhaustedError(
+ f"snapshot diff file size limit exceeded "
+ f"({SNAPSHOT_DIFF_MAX_FILE_BYTES} bytes)",
+ details={"limit_bytes": SNAPSHOT_DIFF_MAX_FILE_BYTES, "path": path},
+ ) from exc
+ if not isinstance(value, bytes):
+ raise TypeError(f"git_show returned unexpected blob type: {type(value).__name__}")
+ return value
+
+ before_bytes = await read_optional(from_oid) if from_ref else None
+ after_bytes = await read_optional(to_oid)
+ if before_bytes is None and after_bytes is None:
+ raise NotFoundError(path, "git_blob")
+
+ for value in (before_bytes, after_bytes):
+ if value is not None and len(value) > SNAPSHOT_DIFF_MAX_FILE_BYTES:
+ raise ResourceExhaustedError(
+ f"snapshot diff file size limit exceeded ({SNAPSHOT_DIFF_MAX_FILE_BYTES} bytes)",
+ details={"limit_bytes": SNAPSHOT_DIFF_MAX_FILE_BYTES, "path": path},
+ )
+
+ change_type, before, after = await asyncio.to_thread(
+ _prepare_snapshot_diff,
+ path=path,
+ before_bytes=before_bytes,
+ after_bytes=after_bytes,
+ max_lines=SNAPSHOT_DIFF_MAX_LINES,
+ )
+ try:
+ diff_text = await self._async_agfs.run(
+ "git_diff_text",
+ before=before,
+ after=after,
+ fromfile=f"{path}@{from_oid}",
+ tofile=f"{path}@{to_oid}",
+ timeout_ms=SNAPSHOT_DIFF_TIMEOUT_MS,
+ max_output_bytes=SNAPSHOT_DIFF_MAX_OUTPUT_BYTES,
+ )
+ except AGFSResourceExhaustedError as exc:
+ raise ResourceExhaustedError(
+ f"snapshot diff output size limit exceeded "
+ f"({SNAPSHOT_DIFF_MAX_OUTPUT_BYTES} bytes)",
+ details={"limit_bytes": SNAPSHOT_DIFF_MAX_OUTPUT_BYTES, "path": path},
+ ) from exc
+ return {
+ "path": path,
+ "from_commit": from_oid,
+ "to_commit": to_oid,
+ "change_type": change_type,
+ "diff_text": diff_text,
+ }
+
async def log(
self,
*,
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 8d3792eb3..9db81a80c 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -593,6 +593,20 @@ class BaseClient(ABC):
) -> List[Dict[str, Any]]:
"""Walk back along parents[0] up to limit commits."""
+ async def git_diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs.
+
+ The default keeps third-party subclasses written against older
+ OpenViking releases instantiable while making unsupported use explicit.
+ """
+ raise NotImplementedError("snapshot diff is not supported by this client")
+
@abstractmethod
async def git_get_ignore(self) -> str:
"""Return the account .ovgitignore content (empty string if absent)."""
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 405ce6b42..87ae76dcc 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -1598,6 +1598,24 @@ class AsyncHTTPClient:
)
return self._handle_response(response)
+ async def git_diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ params: Dict[str, Any] = {"path": path, "to": to_ref}
+ if from_ref is not None:
+ params["from"] = from_ref
+ response = await self._request(
+ "GET",
+ "/api/v1/snapshot/diff",
+ params=params,
+ )
+ return self._handle_response(response)
+
async def git_get_ignore(self) -> str:
"""Return the account ``.ovgitignore`` content (empty string if absent)."""
response = await self._request("GET", "/api/v1/snapshot/ignore")
@@ -2373,6 +2391,20 @@ class AsyncHTTPSnapshotNamespace:
) -> List[Dict[str, Any]]:
return await self._client.git_log(branch=branch, limit=limit, paths=paths)
+ async def diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ return await self._client.git_diff(
+ path,
+ from_ref=from_ref,
+ to_ref=to_ref,
+ )
+
async def get_gitignore(self) -> str:
return await self._client.git_get_ignore()
@@ -2451,6 +2483,18 @@ class SyncHTTPSnapshotNamespace:
) -> List[Dict[str, Any]]:
return run_async(self._ns().log(branch=branch, limit=limit, paths=paths))
+ def diff(
+ self,
+ path: str,
+ *,
+ to_ref: str,
+ from_ref: Optional[str] = None,
+ ) -> Dict[str, Any]:
+ """Compare one file between two snapshot refs."""
+ return run_async(
+ self._ns().diff(path, from_ref=from_ref, to_ref=to_ref)
+ )
+
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 22fb98ef5..58d727424 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -863,6 +863,16 @@ export class OpenVikingClient {
query: { branch, limit, paths },
});
}
+ /** Compare one file between two snapshot refs. */
+ gitDiff(path: string, toRef: string, fromRef?: string): Promise<JsonObject> {
+ return this.request("GET", "/api/v1/snapshot/diff", {
+ query: {
+ path: normalizeURI(path),
+ from: fromRef,
+ to: toRef,
+ },
+ });
+ }
/** Return the account `.ovgitignore` content. */
async gitGetIgnore(): Promise<string> {
const result = await this.request<unknown>(
diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts
index f68b94c47..e79268d60 100644
--- a/sdk/typescript/tests/client.test.ts
+++ b/sdk/typescript/tests/client.test.ts
@@ -597,7 +597,7 @@ describe("OpenVikingClient", () => {
});
});
- it("supports snapshot restore, binary show, log and ignore operations", async () => {
+ it("supports snapshot restore, binary show, log, diff and ignore operations", async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(ok({ oid: "restored" }))
@@ -612,6 +612,15 @@ describe("OpenVikingClient", () => {
)
.mockResolvedValueOnce(ok([{ oid: "commit-1" }]))
.mockResolvedValueOnce(ok([{ oid: "commit-1" }]))
+ .mockResolvedValueOnce(
+ ok({
+ path: "viking://resources/a",
+ from_commit: "old",
+ to_commit: "new",
+ change_type: "modified",
+ diff_text: "@@ -1 +1 @@\n-old\n+new\n",
+ }),
+ )
.mockResolvedValueOnce(ok("*.tmp\n"))
.mockResolvedValueOnce(ok(null))
.mockResolvedValueOnce(ok(null));
@@ -637,6 +646,9 @@ describe("OpenVikingClient", () => {
await expect(client.gitLog("main", 20, [])).resolves.toEqual([
{ oid: "commit-1" },
]);
+ await expect(
+ client.gitDiff("viking://resources/a", "new", "old"),
+ ).resolves.toMatchObject({ change_type: "modified" });
await expect(client.gitGetIgnore()).resolves.toBe("*.tmp\n");
await client.gitSetIgnore("*.log\n");
await client.gitDeleteIgnore();
@@ -658,7 +670,12 @@ describe("OpenVikingClient", () => {
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({
+ const diffUrl = new URL(String(fetcher.mock.calls[4]![0]));
+ expect(diffUrl.pathname).toBe("/api/v1/snapshot/diff");
+ expect(diffUrl.searchParams.get("path")).toBe("viking://resources/a");
+ expect(diffUrl.searchParams.get("from")).toBe("old");
+ expect(diffUrl.searchParams.get("to")).toBe("new");
+ expect(JSON.parse(String(fetcher.mock.calls[6]![1]?.body))).toEqual({
content: "*.log\n",
});
});
diff --git a/tests/client/test_base_client_compatibility.py b/tests/client/test_base_client_compatibility.py
new file mode 100644
index 000000000..687d42e3e
--- /dev/null
+++ b/tests/client/test_base_client_compatibility.py
@@ -0,0 +1,11 @@
+from openviking_cli.client.base import BaseClient
+
+
+def test_legacy_base_client_subclass_without_git_diff_remains_instantiable():
+ async def noop(self, *args, **kwargs):
+ return None
+
+ implementations = {name: noop for name in BaseClient.__abstractmethods__ if name != "git_diff"}
+ legacy_client_type = type("LegacyClient", (BaseClient,), implementations)
+
+ legacy_client_type()
diff --git a/tests/client/test_http_client_snapshot.py b/tests/client/test_http_client_snapshot.py
index 8c004ed88..74274789c 100644
--- a/tests/client/test_http_client_snapshot.py
+++ b/tests/client/test_http_client_snapshot.py
@@ -1,6 +1,6 @@
"""Unit tests for AsyncHTTPClient git_* methods that drive /api/v1/snapshot/*."""
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List
import pytest
@@ -233,3 +233,63 @@ async def test_git_log_empty_paths_is_unfiltered():
assert call["method"] == "GET"
assert call["path"] == "/api/v1/snapshot/log"
assert call["params"] == {"branch": "main", "limit": 5}
+
+
+async def test_git_diff_gets_with_refs_and_path():
+ client, fake = _client_with_fake()
+ client._handle_response = lambda resp: {
+ "path": "viking://resources/a.md",
+ "from_commit": "old",
+ "to_commit": "new",
+ "change_type": "modified",
+ "diff_text": "@@ -1 +1 @@\n-old\n+new\n",
+ }
+ fake.next_response = object()
+
+ result = await client.git_diff(
+ "viking://resources/a.md",
+ from_ref="old",
+ to_ref="new",
+ )
+
+ assert result["change_type"] == "modified"
+ call = fake.calls[-1]
+ assert call == {
+ "method": "GET",
+ "path": "/api/v1/snapshot/diff",
+ "params": {
+ "path": "viking://resources/a.md",
+ "from": "old",
+ "to": "new",
+ },
+ "headers": None,
+ }
+
+
+async def test_git_diff_omits_optional_from_ref():
+ client, fake = _client_with_fake()
+ fake.next_response = object()
+
+ await client.git_diff("viking://resources/a.md", to_ref="new")
+
+ assert fake.calls[-1]["params"] == {
+ "path": "viking://resources/a.md",
+ "to": "new",
+ }
+
+
+async def test_snapshot_namespace_exposes_diff():
+ client, fake = _client_with_fake()
+ client._handle_response = lambda resp: {"change_type": "added", "diff_text": "+new\n"}
+ fake.next_response = object()
+
+ result = await client.snapshot.diff(
+ "viking://resources/a.md",
+ to_ref="new",
+ )
+
+ assert result["change_type"] == "added"
+ assert fake.calls[-1]["params"] == {
+ "path": "viking://resources/a.md",
+ "to": "new",
+ }
diff --git a/tests/server/test_api_snapshot.py b/tests/server/test_api_snapshot.py
index f51ea2dc3..e06fcc12d 100644
--- a/tests/server/test_api_snapshot.py
+++ b/tests/server/test_api_snapshot.py
@@ -247,6 +247,167 @@ async def test_show_path_not_found_returns_404(client_with_resource):
assert resp.json()["status"] == "error"
+async def test_diff_returns_unified_diff_for_path(client_with_resource, service):
+ client, _ = client_with_resource
+ path = "viking://resources/snapshot_diff_fixture.md"
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ await service.viking_fs.write_file(path, b"# Title\n\nold line\n", ctx=ctx)
+ from_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff v1", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ await service.viking_fs.write_file(path, b"# Title\n\nnew line\n", ctx=ctx)
+ to_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff v2", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ response = await client.get(
+ "/api/v1/snapshot/diff",
+ params={"path": path, "from": from_commit, "to": to_commit},
+ )
+
+ assert response.status_code == 200, response.text
+ result = response.json()["result"]
+ assert result["path"] == path
+ assert result["from_commit"] == from_commit
+ assert result["to_commit"] == to_commit
+ assert result["change_type"] == "modified"
+ assert "-old line" in result["diff_text"]
+ assert "+new line" in result["diff_text"]
+
+
+async def test_diff_supports_first_version_without_from_commit(client_with_resource, service):
+ client, _ = client_with_resource
+ path = "viking://resources/snapshot_diff_added_fixture.md"
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ await service.viking_fs.write_file(path, b"first version\n", ctx=ctx)
+ to_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff added", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ response = await client.get(
+ "/api/v1/snapshot/diff",
+ params={"path": path, "to": to_commit},
+ )
+
+ assert response.status_code == 200, response.text
+ result = response.json()["result"]
+ assert result["from_commit"] == ""
+ assert result["to_commit"] == to_commit
+ assert result["change_type"] == "added"
+ assert "+first version" in result["diff_text"]
+
+
+async def test_diff_reports_missing_final_newline(client_with_resource, service):
+ client, _ = client_with_resource
+ path = "viking://resources/snapshot_diff_newline_fixture.md"
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ await service.viking_fs.write_file(path, b"same line\n", ctx=ctx)
+ from_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff newline v1", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ await service.viking_fs.write_file(path, b"same line", ctx=ctx)
+ to_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff newline v2", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ response = await client.get(
+ "/api/v1/snapshot/diff",
+ params={"path": path, "from": from_commit, "to": to_commit},
+ )
+
+ assert response.status_code == 200, response.text
+ result = response.json()["result"]
+ assert result["change_type"] == "modified"
+ assert "-same line" in result["diff_text"]
+ assert "+same line" in result["diff_text"]
+ assert "\\ No newline at end of file" in result["diff_text"]
+
+
+async def test_diff_reports_deleted_path(client_with_resource, service):
+ client, _ = client_with_resource
+ path = "viking://resources/snapshot_diff_deleted_fixture.md"
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ await service.viking_fs.write_file(path, b"deleted content\n", ctx=ctx)
+ from_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff deleted v1", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ await service.viking_fs.rm(path, ctx=ctx)
+ to_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff deleted v2", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ response = await client.get(
+ "/api/v1/snapshot/diff",
+ params={"path": path, "from": from_commit, "to": to_commit},
+ )
+
+ assert response.status_code == 200, response.text
+ result = response.json()["result"]
+ assert result["change_type"] == "deleted"
+ assert "-deleted content" in result["diff_text"]
+
+
+async def test_diff_reports_unchanged_path(client_with_resource, service):
+ client, _ = client_with_resource
+ path = "viking://resources/snapshot_diff_unchanged_fixture.md"
+ other_path = "viking://resources/snapshot_diff_other_fixture.md"
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+ await service.viking_fs.write_file(path, b"unchanged content\n", ctx=ctx)
+ from_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff unchanged v1", "paths": [path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ await service.viking_fs.write_file(other_path, b"advance snapshot\n", ctx=ctx)
+ to_commit = (
+ await client.post(
+ "/api/v1/snapshot/commit",
+ json={"message": "snapshot diff unchanged v2", "paths": [other_path]},
+ )
+ ).json()["result"]["commit_oid"]
+
+ response = await client.get(
+ "/api/v1/snapshot/diff",
+ params={"path": path, "from": from_commit, "to": to_commit},
+ )
+
+ assert response.status_code == 200, response.text
+ result = response.json()["result"]
+ assert result["change_type"] == "unchanged"
+ assert result["diff_text"] == ""
+
+
# ---------------------------------------------------------------------------
# restore (apply) — forward-commit chain + reindex hook + concurrent-commit 409
# ---------------------------------------------------------------------------
diff --git a/tests/server/test_error_mapping.py b/tests/server/test_error_mapping.py
index 840f18158..34dab57d2 100644
--- a/tests/server/test_error_mapping.py
+++ b/tests/server/test_error_mapping.py
@@ -8,6 +8,7 @@ from openviking.pyagfs.exceptions import (
AGFSHTTPError,
AGFSIsADirectoryError,
AGFSNotSupportedError,
+ AGFSResourceExhaustedError,
GitConcurrentCommitError,
)
from openviking.server.error_mapping import map_exception
@@ -18,6 +19,7 @@ from openviking_cli.exceptions import (
InvalidArgumentError,
InvalidURIError,
NotFoundError,
+ ResourceExhaustedError,
)
@@ -96,6 +98,16 @@ def test_agfs_not_supported_maps_to_unimplemented():
assert mapped.code == "UNIMPLEMENTED"
+def test_agfs_resource_limit_maps_to_resource_exhausted():
+ mapped = map_exception(
+ AGFSResourceExhaustedError("blob exceeds configured limit"),
+ resource="viking://user/test/memories/experiences/example.md",
+ )
+
+ assert isinstance(mapped, ResourceExhaustedError)
+ assert mapped.code == "RESOURCE_EXHAUSTED"
+
+
def test_value_error_invalid_uri_maps_to_invalid_uri():
mapped = map_exception(ValueError("invalid viking URI: missing path"), resource="viking://")
diff --git a/tests/storage/test_viking_fs_git.py b/tests/storage/test_viking_fs_git.py
index 81ed5674a..69a421d1b 100644
--- a/tests/storage/test_viking_fs_git.py
+++ b/tests/storage/test_viking_fs_git.py
@@ -1,9 +1,51 @@
# tests/storage/test_viking_fs_git.py
import pytest
+from openviking.pyagfs.exceptions import AGFSNotFoundError, AGFSPathNotFoundError
+from openviking.server.identity import RequestContext, Role
+from openviking.storage import viking_fs as viking_fs_module
+from openviking.storage.viking_fs import VikingFS
+from openviking_cli.exceptions import PermissionDeniedError, ResourceExhaustedError
+from openviking_cli.session.user_id import UserIdentifier
+
pytestmark = pytest.mark.asyncio
+async def test_show_without_limit_preserves_existing_binding_call():
+ class RecordingAGFS:
+ def __init__(self):
+ self.calls = []
+
+ async def run(self, operation, **kwargs):
+ self.calls.append((operation, kwargs))
+ return {"oid": "a" * 40}
+
+ class ShowVikingFS:
+ def __init__(self):
+ self._async_agfs = RecordingAGFS()
+
+ def _ctx_or_default(self, ctx):
+ return ctx
+
+ def _uri_to_tree_path(self, path, *, ctx):
+ return path
+
+ vfs = ShowVikingFS()
+
+ await VikingFS.show(vfs, "main", ctx=_request_context())
+
+ assert vfs._async_agfs.calls == [
+ (
+ "git_show",
+ {
+ "account": "account",
+ "target_ref": "main",
+ "path": None,
+ },
+ )
+ ]
+
+
@pytest.mark.skip(reason="needs git-enabled VikingFS fixture")
async def test_show_blob_raw_returns_envelope(viking_fs_with_two_commits):
"""show_blob_raw must return the full {oid, size, bytes} dict, not strip it."""
@@ -15,3 +57,273 @@ async def test_show_blob_raw_returns_envelope(viking_fs_with_two_commits):
assert raw["bytes"] == sample_bytes
assert raw["size"] == len(sample_bytes)
assert isinstance(raw["oid"], str) and len(raw["oid"]) == 40
+
+
+async def test_diff_reads_blobs_from_resolved_commit_oids():
+ from_oid = "a" * 40
+ to_oid = "b" * 40
+
+ class MovingRefVikingFS:
+ def __init__(self):
+ self._async_agfs = _RecordingDiffAGFS()
+ self.blob_refs = []
+
+ def _ctx_or_default(self, ctx):
+ return ctx
+
+ def _ensure_access(self, uri, ctx):
+ return None
+
+ async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):
+ if path is None:
+ return {"oid": from_oid if target_ref == "base" else to_oid}
+
+ self.blob_refs.append(target_ref)
+ contents = {
+ from_oid: b"old content\n",
+ to_oid: b"new content\n",
+ "base": b"moved base content\n",
+ "main": b"moved main content\n",
+ }
+ return contents[target_ref]
+
+ vfs = MovingRefVikingFS()
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="account", user_id="user"),
+ role=Role.ROOT,
+ )
+
+ result = await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="base",
+ to_ref="main",
+ ctx=ctx,
+ )
+
+ assert vfs.blob_refs == [from_oid, to_oid]
+ assert result["from_commit"] == from_oid
+ assert result["to_commit"] == to_oid
+ assert "-old content" in result["diff_text"]
+ assert "+new content" in result["diff_text"]
+
+
+class _DiffVikingFS:
+ def __init__(self, before: bytes, after: bytes):
+ self._before = before
+ self._after = after
+ self._async_agfs = _RecordingDiffAGFS()
+ self.blob_read_limits = []
+ self.access_checks = []
+
+ def _ctx_or_default(self, ctx):
+ return ctx
+
+ def _ensure_access(self, uri, ctx):
+ self.access_checks.append((uri, ctx))
+
+ async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):
+ if path is None:
+ return {"oid": target_ref}
+ self.blob_read_limits.append(max_blob_bytes)
+ return self._before if target_ref == "from" else self._after
+
+
+class _RecordingDiffAGFS:
+ def __init__(self):
+ self.calls = []
+
+ async def run(self, operation, **kwargs):
+ self.calls.append((operation, kwargs))
+ assert operation == "git_diff_text"
+ before = kwargs["before"]
+ after = kwargs["after"]
+ output = (
+ f"--- {kwargs['fromfile']}\n"
+ f"+++ {kwargs['tofile']}\n"
+ "@@ -1 +1 @@\n"
+ f"-{before.rstrip()}\n"
+ f"+{after.rstrip()}\n"
+ )
+ if len(output.encode("utf-8")) > kwargs["max_output_bytes"]:
+ from openviking.pyagfs.exceptions import AGFSResourceExhaustedError
+
+ raise AGFSResourceExhaustedError("snapshot diff output size limit exceeded")
+ return output
+
+
+def _request_context() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier(account_id="account", user_id="user"),
+ role=Role.ROOT,
+ )
+
+
+async def test_diff_rejects_files_over_size_limit(monkeypatch):
+ monkeypatch.setattr(viking_fs_module, "SNAPSHOT_DIFF_MAX_FILE_BYTES", 3)
+ vfs = _DiffVikingFS(b"old\n", b"new\n")
+
+ with pytest.raises(ResourceExhaustedError, match="file size limit"):
+ await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+
+async def test_diff_passes_file_size_limit_to_blob_reads(monkeypatch):
+ monkeypatch.setattr(viking_fs_module, "SNAPSHOT_DIFF_MAX_FILE_BYTES", 123)
+ vfs = _DiffVikingFS(b"old\n", b"new\n")
+
+ await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+ assert vfs.blob_read_limits == [123, 123]
+
+
+async def test_diff_checks_access_before_reading_snapshot_content():
+ path = "viking://user/other-user/memories/private.md"
+ ctx = RequestContext(
+ user=UserIdentifier(account_id="account", user_id="user"),
+ role=Role.USER,
+ )
+ vfs = object.__new__(VikingFS)
+ show_calls = []
+
+ async def show(*args, **kwargs):
+ show_calls.append((args, kwargs))
+ return {"oid": "a" * 40}
+
+ vfs.show = show
+
+ with pytest.raises(PermissionDeniedError):
+ await VikingFS.diff(
+ vfs,
+ path=path,
+ from_ref="from",
+ to_ref="to",
+ ctx=ctx,
+ )
+
+ assert show_calls == []
+
+
+async def test_diff_rejects_excessive_line_count_before_building_diff(monkeypatch):
+ monkeypatch.setattr(viking_fs_module, "SNAPSHOT_DIFF_MAX_LINES", 2, raising=False)
+ vfs = _DiffVikingFS(b"a\nb\nc\n", b"a\nb\nd\n")
+
+ with pytest.raises(ResourceExhaustedError, match="line count limit"):
+ await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+
+ "text",
+ [
+ "",
+ "one line",
+ "one line\n",
+ "one\r\ntwo\r\n",
+ "one\rtwo",
+ "one\u2028two\u2029",
+ "\n\n",
+ ],
+)
+async def test_snapshot_line_count_matches_splitlines(text):
+ assert viking_fs_module._snapshot_line_count(text) == len(text.splitlines())
+
+
+async def test_diff_rejects_output_over_size_limit(monkeypatch):
+ monkeypatch.setattr(viking_fs_module, "SNAPSHOT_DIFF_MAX_FILE_BYTES", 1024)
+ monkeypatch.setattr(viking_fs_module, "SNAPSHOT_DIFF_MAX_OUTPUT_BYTES", 16)
+ vfs = _DiffVikingFS(b"old\n", b"new\n")
+
+ with pytest.raises(ResourceExhaustedError, match="output size limit"):
+ await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+
+async def test_diff_uses_bounded_native_diff_builder():
+ vfs = _DiffVikingFS(b"old\n", b"new\n")
+
+ result = await VikingFS.diff(
+ vfs,
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+ assert vfs._async_agfs.calls == [
+ (
+ "git_diff_text",
+ {
+ "before": "old\n",
+ "after": "new\n",
+ "fromfile": (
+ "viking://user/user/memories/experiences/example.md@from"
+ ),
+ "tofile": "viking://user/user/memories/experiences/example.md@to",
+ "timeout_ms": viking_fs_module.SNAPSHOT_DIFF_TIMEOUT_MS,
+ "max_output_bytes": viking_fs_module.SNAPSHOT_DIFF_MAX_OUTPUT_BYTES,
+ },
+ )
+ ]
+ assert "-old" in result["diff_text"]
+ assert "+new" in result["diff_text"]
+
+
+async def test_diff_treats_only_missing_tree_path_as_absent():
+ class MissingPathVikingFS(_DiffVikingFS):
+ async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):
+ if path is None:
+ return {"oid": target_ref}
+ if target_ref == "to":
+ raise AGFSPathNotFoundError("path not found in tree")
+ return self._before
+
+ result = await VikingFS.diff(
+ MissingPathVikingFS(b"old\n", b""),
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
+
+ assert result["change_type"] == "deleted"
+
+
+async def test_diff_does_not_treat_missing_storage_object_as_absent():
+ class MissingObjectVikingFS(_DiffVikingFS):
+ async def show(self, target_ref, *, path=None, ctx=None, max_blob_bytes=None):
+ if path is None:
+ return {"oid": target_ref}
+ if target_ref == "to":
+ raise AGFSNotFoundError("object not found: deadbeef")
+ return self._before
+
+ with pytest.raises(AGFSNotFoundError, match="object not found"):
+ await VikingFS.diff(
+ MissingObjectVikingFS(b"old\n", b""),
+ path="viking://user/user/memories/experiences/example.md",
+ from_ref="from",
+ to_ref="to",
+ ctx=_request_context(),
+ )
diff --git a/tests/unit/test_fs_service_git_forwarders.py b/tests/unit/test_fs_service_git_forwarders.py
index 42903ded4..650359b38 100644
--- a/tests/unit/test_fs_service_git_forwarders.py
+++ b/tests/unit/test_fs_service_git_forwarders.py
@@ -1,6 +1,6 @@
"""Tests for FSService git forwarder methods.
-These tests verify FSService.{commit, restore, show, log} pass the right
+These tests verify FSService.{commit, restore, show, diff, log} pass the right
args to VikingFS. They don't exercise real git — that's covered by
tests/agfs/test_viking_fs_git.py.
"""
@@ -27,6 +27,15 @@ def viking_fs_mock():
m.commit = AsyncMock(return_value={"result": "created", "commit_oid": "a" * 40, "changed": 1})
m.restore = AsyncMock(return_value={"result": "applied", "commit_oid": "b" * 40})
m.show = AsyncMock(return_value={"oid": "c" * 40, "message": "m", "parents": []})
+ m.diff = AsyncMock(
+ return_value={
+ "path": "viking://resources/a.md",
+ "from_commit": "",
+ "to_commit": "c" * 40,
+ "change_type": "added",
+ "diff_text": "+hello\n",
+ }
+ )
m.log = AsyncMock(return_value=[{"oid": "c" * 40, "message": "m"}])
return m
@@ -115,6 +124,24 @@ async def test_show_with_path_validated(svc, viking_fs_mock):
assert out == b"hello"
+async def test_diff_forwards_validated_path_and_refs(svc, viking_fs_mock):
+ ctx = _ctx()
+ out = await svc.diff(
+ path="viking://resources/a.md",
+ from_ref=None,
+ to_ref="main",
+ ctx=ctx,
+ )
+ viking_fs_mock.diff.assert_awaited_once_with(
+ path="viking://resources/a.md",
+ from_ref=None,
+ to_ref="main",
+ ctx=ctx,
+ )
+ assert out["change_type"] == "added"
+
+
@pytest.mark.asyncio
async def test_log_defaults(svc, viking_fs_mock):
ctx = _ctx()
@@ -162,5 +189,9 @@ async def test_methods_raise_when_not_initialized():
await svc.restore(project_dir="viking://x", source_commit="a", ctx=ctx)
with pytest.raises(NotInitializedError):
await svc.show("main", ctx=ctx)
+ with pytest.raises(NotInitializedError):
+ await svc.diff(
+ path="viking://resources/a.md", from_ref=None, to_ref="main", ctx=ctx
+ )
with pytest.raises(NotInitializedError):
await svc.log(ctx=ctx)
diff --git a/tests/unit/test_local_client_git.py b/tests/unit/test_local_client_git.py
index 33ffc02c3..d5817552f 100644
--- a/tests/unit/test_local_client_git.py
+++ b/tests/unit/test_local_client_git.py
@@ -1,7 +1,6 @@
"""Tests for LocalClient git version control methods.
-Verifies that LocalClient.{git_commit, git_restore, git_show, git_log}
-forward the right kwargs to FSService.{commit, restore, show, log}.
+Verifies that LocalClient git methods forward the right kwargs to FSService.
"""
from unittest.mock import AsyncMock, MagicMock
@@ -19,6 +18,7 @@ def mock_fs():
m.restore = AsyncMock(return_value={"result": "applied", "commit_oid": "b" * 40})
m.show = AsyncMock(return_value={"oid": "c" * 40, "message": "m", "parents": []})
m.log = AsyncMock(return_value=[{"oid": "c" * 40, "message": "m"}])
+ m.diff = AsyncMock(return_value={"change_type": "modified"})
return m
@@ -142,3 +142,19 @@ async def test_log_overrides(local_client, mock_fs):
paths=["viking://resources/a.md", "viking://resources/docs"],
ctx=local_client._ctx,
)
+
+
+async def test_diff_forwards_kwargs(local_client, mock_fs):
+ out = await local_client.git_diff(
+ "viking://resources/a.md",
+ from_ref="old",
+ to_ref="new",
+ )
+ mock_fs.diff.assert_awaited_once_with(
+ path="viking://resources/a.md",
+ from_ref="old",
+ to_ref="new",
+ ctx=local_client._ctx,
+ )
+ assert out["change_type"] == "modified"
diff --git a/tests/unit/test_snapshot_namespace.py b/tests/unit/test_snapshot_namespace.py
index e16560198..72c265b1a 100644
--- a/tests/unit/test_snapshot_namespace.py
+++ b/tests/unit/test_snapshot_namespace.py
@@ -20,6 +20,15 @@ def fake_async_client():
parent._client.git_restore = AsyncMock(return_value={"result": "applied", "commit_oid": "b" * 40})
parent._client.git_show = AsyncMock(return_value={"oid": "c" * 40, "parents": []})
parent._client.git_log = AsyncMock(return_value=[{"oid": "c" * 40}])
+ parent._client.git_diff = AsyncMock(
+ return_value={
+ "path": "viking://resources/a.md",
+ "from_commit": "a" * 40,
+ "to_commit": "b" * 40,
+ "change_type": "modified",
+ "diff_text": "@@ -1 +1 @@\n-old\n+new\n",
+ }
+ )
return parent
@@ -119,6 +128,21 @@ async def test_async_log_overrides(async_ns, fake_async_client):
)
+async def test_async_diff_forwards(async_ns, fake_async_client):
+ out = await async_ns.diff(
+ "viking://resources/a.md",
+ from_ref="a" * 40,
+ to_ref="b" * 40,
+ )
+ fake_async_client._client.git_diff.assert_awaited_once_with(
+ "viking://resources/a.md",
+ from_ref="a" * 40,
+ to_ref="b" * 40,
+ )
+ assert out["change_type"] == "modified"
+
+
@pytest.mark.asyncio
async def test_async_ensures_initialized_before_every_call(async_ns, fake_async_client):
await async_ns.commit(message="m")
@@ -139,6 +163,7 @@ def test_sync_namespace_delegates_through_async(monkeypatch):
inner_async_ns.restore = AsyncMock(return_value={"result": "applied"})
inner_async_ns.show = AsyncMock(return_value=b"blob")
inner_async_ns.log = AsyncMock(return_value=[])
+ inner_async_ns.diff = AsyncMock(return_value={"change_type": "modified"})
sync_parent._async_client.snapshot = inner_async_ns
sync_ns = SyncSnapshotNamespace(sync_parent)
@@ -156,6 +181,11 @@ def test_sync_namespace_delegates_through_async(monkeypatch):
sync_ns.log(branch="dev", limit=3)
inner_async_ns.log.assert_awaited_once_with(branch="dev", limit=3, paths=None)
+ sync_ns.diff("viking://x/a", from_ref="old", to_ref="new")
+ inner_async_ns.diff.assert_awaited_once_with(
+ "viking://x/a", from_ref="old", to_ref="new"
+ )
+
def test_async_client_snapshot_property_is_lazy_and_cached():
"""Accessing .snapshot twice returns the same instance and doesn't construct early."""