Skip to content

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

feat(privacy): add current configuration tree overview (#6337)

MaojiaSheng1c439998838c
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index cb2078f9d..bd0435844 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -1726,6 +1726,13 @@ impl HttpClient {
self.get("/api/v1/privacy-configs", &[]).await
}
+ pub async fn privacy_tree(&self, category: Option<&str>) -> Result<serde_json::Value> {
+ let params = category
+ .map(|value| vec![("category".to_string(), value.to_string())])
+ .unwrap_or_default();
+ self.get("/api/v1/privacy-configs/tree", &params).await
+ }
+
pub async fn privacy_list_targets(&self, category: &str) -> Result<serde_json::Value> {
let path = format!("/api/v1/privacy-configs/{}", category);
self.get(&path, &[]).await
diff --git a/crates/ov_cli/src/commands/privacy.rs b/crates/ov_cli/src/commands/privacy.rs
index 9214cc88b..999ce9443 100644
--- a/crates/ov_cli/src/commands/privacy.rs
+++ b/crates/ov_cli/src/commands/privacy.rs
@@ -1,10 +1,91 @@
use crate::client::HttpClient;
use crate::error::{Error, Result};
use crate::output::{OutputFormat, output_success};
+use crate::theme;
use serde_json::{Map, Value};
use std::collections::{HashMap, HashSet};
use std::io::{self, IsTerminal, Write};
+const TREE_INDENT: &str = " ";
+
+fn render_privacy_tree(result: &Value, references: bool) -> String {
+ let Some(categories) = result
+ .get("categories")
+ .and_then(Value::as_array)
+ .filter(|categories| !categories.is_empty())
+ else {
+ return theme::muted("(empty)").to_string();
+ };
+ let mut lines = vec![theme::heading("viking://~/privacy").to_string()];
+ for category in categories {
+ lines.push(format!(
+ "{TREE_INDENT}{}",
+ theme::heading(category["category"].as_str().unwrap_or_default())
+ ));
+ for target in category
+ .get("targets")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ lines.push(format!(
+ "{}{} {}",
+ TREE_INDENT.repeat(2),
+ theme::sky_value(target["target_key"].as_str().unwrap_or_default()),
+ theme::muted(format!("(v{})", target["version"]))
+ ));
+ for field in target
+ .get("fields")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ let status = if field["configured"].as_bool().unwrap_or(false) {
+ theme::success("configured")
+ } else {
+ theme::warning("unconfigured")
+ };
+ lines.push(format!(
+ "{}{} {}",
+ TREE_INDENT.repeat(3),
+ theme::sky_value(field["field"].as_str().unwrap_or_default()),
+ status
+ ));
+ if references && let Some(reference) = field["reference"].as_str() {
+ lines.push(format!(
+ "{}{}",
+ TREE_INDENT.repeat(4),
+ theme::muted(reference)
+ ));
+ }
+ }
+ }
+ }
+ lines.join("\n")
+}
+
+pub async fn tree(
+ client: &HttpClient,
+ category: Option<&str>,
+ references: bool,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let result = client.privacy_tree(category).await?;
+ if output_format == OutputFormat::Json {
+ output_success(&result, OutputFormat::Json, compact);
+ } else {
+ println!(
+ "{}",
+ crate::output::append_profile_to_rendered(
+ render_privacy_tree(&result, references),
+ &result
+ )
+ );
+ }
+ Ok(())
+}
+
fn parse_field_pairs(pairs: &[String]) -> Result<HashMap<String, String>> {
let mut parsed: HashMap<String, String> = HashMap::new();
for pair in pairs {
@@ -552,6 +633,68 @@ mod tests {
use super::*;
use serde_json::json;
+ fn privacy_tree_result() -> Value {
+ json!({"owner_user_id": "alice", "categories": [{
+ "category": "credential", "targets": [{
+ "target_key": "github", "version": 3, "fields": [
+ {"field": "pat", "configured": true,
+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"},
+ {"field": "region", "configured": false,
+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/region}}"}
+ ]
+ }]
+ }]})
+ }
+
+ #[test]
+ fn privacy_tree_renders_empty() {
+ for references in [false, true] {
+ let rendered = render_privacy_tree(&json!({"categories": []}), references);
+ assert!(rendered.contains("(empty)"));
+ assert!(!rendered.contains("ov_privacy"));
+ }
+ }
+
+ #[test]
+ fn privacy_tree_without_references_shows_hierarchy_and_status() {
+ let rendered = render_privacy_tree(&privacy_tree_result(), false);
+ let lines: Vec<_> = rendered.lines().collect();
+ assert_eq!(lines.len(), 5);
+ assert!(lines[0].contains("viking://~/privacy"));
+ assert!(lines[1].starts_with(" ") && lines[1].contains("credential"));
+ assert!(
+ lines[2].starts_with(" ")
+ && lines[2].contains("github")
+ && lines[2].contains("(v3)")
+ );
+ assert!(
+ lines[3].starts_with(" ")
+ && lines[3].contains("pat")
+ && lines[3].contains("configured")
+ );
+ assert!(!lines[3].contains("unconfigured"));
+ assert!(
+ lines[4].starts_with(" ")
+ && lines[4].contains("region")
+ && lines[4].contains("unconfigured")
+ );
+ assert!(!rendered.contains("ov_privacy:"));
+ }
+
+ #[test]
+ fn privacy_tree_references_are_indented_under_each_field() {
+ let result = privacy_tree_result();
+ let rendered = render_privacy_tree(&result, true);
+ let lines: Vec<_> = rendered.lines().collect();
+ assert_eq!(lines.len(), 7);
+ for (index, field) in [(4, 0), (6, 1)] {
+ let reference = result["categories"][0]["targets"][0]["fields"][field]["reference"]
+ .as_str()
+ .unwrap();
+ assert!(lines[index].starts_with(" ") && lines[index].contains(reference));
+ }
+ }
+
#[test]
fn inferred_field_requires_an_unambiguous_target() {
let one = vec!["pat".to_string()];
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index f589fecb1..ddb17c7e0 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -803,6 +803,19 @@ pub async fn handle_privacy(cmd: PrivacyCommands, ctx: CliContext) -> Result<()>
PrivacyCommands::Categories => {
commands::privacy::categories(&client, ctx.output_format, ctx.compact).await
}
+ PrivacyCommands::Tree {
+ category,
+ references,
+ } => {
+ commands::privacy::tree(
+ &client,
+ category.as_deref(),
+ references,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
+ }
PrivacyCommands::List { category } => {
commands::privacy::list_targets(&client, &category, ctx.output_format, ctx.compact)
.await
diff --git a/crates/ov_cli/src/help_ui.rs b/crates/ov_cli/src/help_ui.rs
index 8479ad116..ddc558f53 100644
--- a/crates/ov_cli/src/help_ui.rs
+++ b/crates/ov_cli/src/help_ui.rs
@@ -774,6 +774,10 @@ const COMMAND_HELP_SPECS: &[CommandHelpSpec] = &[
path: &["privacy"],
purpose: "Manage privacy targets, field references, values, versions, and cleanup.",
examples: &[
+ HelpItem {
+ label: "ov privacy tree [--category <category>] [--references]",
+ description: "List current targets and fields without revealing values.",
+ },
HelpItem {
label: "ov privacy categories",
description: "List privacy categories.",
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 007cd5a81..63c80e9a1 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -1943,6 +1943,15 @@ enum WatchCommands {
enum PrivacyCommands {
/// List privacy config categories
Categories,
+ /// List all privacy targets and fields as a tree (current version, no values)
+ Tree {
+ /// Limit the tree to one category
+ #[arg(long, value_name = "category")]
+ category: Option<String>,
+ /// Append the owner-bound reference for each field
+ #[arg(long)]
+ references: bool,
+ },
/// List targets by category
List {
/// Privacy config category
@@ -2860,6 +2869,7 @@ fn is_privacy_subcommand(token: &str) -> bool {
matches!(
token,
"categories"
+ | "tree"
| "list"
| "get"
| "reference"
@@ -4718,6 +4728,7 @@ mod tests {
&["ov", "session", "add-messages"],
&["ov", "session", "commit"],
&["ov", "privacy", "categories"],
+ &["ov", "privacy", "tree"],
&["ov", "privacy", "list"],
&["ov", "privacy", "get"],
&["ov", "privacy", "reference"],
@@ -6054,6 +6065,38 @@ mod tests {
.expect("CLI parser test thread");
}
+ #[test]
+ fn cli_parses_privacy_tree_options_without_rewriting_to_get() {
+ on_cli_parser_stack(|| {
+ let args = [
+ "ov",
+ "privacy",
+ "tree",
+ "--category",
+ "credential",
+ "--references",
+ "--output",
+ "json",
+ ]
+ .into_iter()
+ .map(OsString::from)
+ .collect();
+ let cli = Cli::parse_from(preprocess_privacy_args(args));
+ let Commands::Privacy { action } = cli.command else {
+ panic!("expected privacy command")
+ };
+ let PrivacyCommands::Tree {
+ category,
+ references,
+ } = *action
+ else {
+ panic!("expected tree command")
+ };
+ assert_eq!(category.as_deref(), Some("credential"));
+ assert!(references);
+ });
+ }
+
#[test]
fn cli_parses_privacy_upsert_with_field_dynamic_flag() {
on_cli_parser_stack(|| {
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index df46fbdd0..498315735 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -521,6 +521,7 @@ This catalog follows the routes actually mounted by the server. Each group headi
| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Add a group member |
| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | Remove a group member |
| GET | `/api/v1/privacy-configs` | List privacy configuration categories |
+| GET | `/api/v1/privacy-configs/tree` | List current targets and field metadata as a tree without values |
| POST | `/api/v1/privacy-configs/scan` | Scan or repair registered values in content |
| GET | `/api/v1/privacy-configs/{category}` | List category targets |
| GET | `/api/v1/privacy-configs/{category}/{target_key}` | Get the active configuration |
diff --git a/docs/en/api/10-privacy.md b/docs/en/api/10-privacy.md
index dc2563fa4..02a6215f3 100644
--- a/docs/en/api/10-privacy.md
+++ b/docs/en/api/10-privacy.md
@@ -4,7 +4,7 @@ Privacy configs manage sensitive values by `category + target_key` (for example,
Changed values create a version snapshot. You can query history and switch the active version. Submitting the same values as the current version does not create a new version.
-These examples use the current user’s API key. In trusted mode, supply the identity headers required by your deployment. Reads and CLI output contain the stored values; `***` below is an example placeholder, not automatic redaction.
+These examples use the current user’s API key. In trusted mode, supply the identity headers required by your deployment. Value-reading endpoints and CLI commands return stored values; tree and field-metadata endpoints omit them. `***` below is an example placeholder, not automatic redaction.
Activating a version changes only the values stored in OpenViking. It does not rotate, revoke, or restore credentials at the external provider.
@@ -13,6 +13,7 @@ Activating a version changes only the values stored in OpenViking. It does not r
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/privacy-configs` | List privacy config categories |
+| GET | `/api/v1/privacy-configs/tree` | List current targets and field metadata as a tree without values |
| POST | `/api/v1/privacy-configs/scan` | Scan or repair registered values in stored content |
| GET | `/api/v1/privacy-configs/{category}` | List targets under a category |
| GET | `/api/v1/privacy-configs/{category}/{target_key}` | Get active config (`meta + current`) |
@@ -143,6 +144,57 @@ curl -X GET http://localhost:1933/api/v1/privacy-configs \
---
+### list_privacy_tree()
+
+List the current user's categories, targets, active version numbers and field metadata
+in one request. Historical versions and stored values are never returned. Targets
+without a current snapshot are skipped.
+
+**HTTP API**
+
+```text
+GET /api/v1/privacy-configs/tree
+```
+
+The optional `category` query parameter limits the tree to one category. An invalid
+identifier returns `INVALID_ARGUMENT`. An empty store returns `categories: []`;
+a missing filtered category returns that category with `targets: []`.
+
+```bash
+curl "http://localhost:1933/api/v1/privacy-configs/tree?category=credential" \
+ -H "X-API-Key: your-key"
+```
+
+**Response**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "owner_user_id": "alice",
+ "categories": [{
+ "category": "credential",
+ "targets": [{
+ "target_key": "github",
+ "version": 3,
+ "fields": [{
+ "field": "pat",
+ "configured": true,
+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"
+ }]
+ }]
+ }]
+ }
+}
+```
+
+`configured` is false for `null` or an empty string; other values, including `false`
+and `0`, are configured. References are bound to the current owner and always
+included in the API response. The CLI shows them in table output only when
+`--references` is set; JSON output preserves all metadata.
+
+---
+
### list_privacy_targets()
List target keys under a category.
@@ -520,6 +572,11 @@ curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-se
ov privacy categories
ov privacy list skill
+# Tree of current targets and fields, without values
+ov privacy tree
+ov privacy tree --category credential --references
+ov privacy tree --output json
+
# Active config (shortcut supported)
ov privacy get skill byted-viking-search-knowledgebase
ov privacy skill byted-viking-search-knowledgebase
diff --git a/docs/en/concepts/13-privacy.md b/docs/en/concepts/13-privacy.md
index de62b3b97..7c0cec6f9 100644
--- a/docs/en/concepts/13-privacy.md
+++ b/docs/en/concepts/13-privacy.md
@@ -136,6 +136,9 @@ Using a GitHub Personal Access Token (PAT) as an example:
# Create or rotate the PAT; credential/github is the target and pat is the field
ov privacy upsert credential github --field-pat 'github_pat_...'
+# Inspect current targets and fields without exposing values
+ov privacy tree --category credential --references
+
# Omit the field when pat is the target's only field
ov privacy reference credential github
ov privacy resolve credential github
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 6aee7b1a7..e32022509 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -516,6 +516,7 @@ JSON 输出 - 错误:
| PUT | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 添加用户组成员 |
| DELETE | `/api/v1/admin/accounts/{account_id}/groups/{group_id}/members/{user_id}` | 移除用户组成员 |
| GET | `/api/v1/privacy-configs` | 列出隐私配置分类 |
+| GET | `/api/v1/privacy-configs/tree` | 树形列出当前目标和字段元数据,不返回值 |
| POST | `/api/v1/privacy-configs/scan` | 扫描或修复正文中的登记值 |
| GET | `/api/v1/privacy-configs/{category}` | 列出分类目标 |
| GET | `/api/v1/privacy-configs/{category}/{target_key}` | 获取生效配置 |
diff --git a/docs/zh/api/10-privacy.md b/docs/zh/api/10-privacy.md
index 057cc74aa..47b55c07e 100644
--- a/docs/zh/api/10-privacy.md
+++ b/docs/zh/api/10-privacy.md
@@ -4,7 +4,7 @@
配置值变化时会生成版本快照,可查询历史版本并切换生效版本。提交与当前版本相同的值不会创建新版本。
-以下示例使用当前用户的 API Key。trusted 模式需补充部署要求的身份头。读取接口和 CLI 会返回保存的实际值;下文的 `***` 仅为示例占位符,不表示接口自动脱敏。
+以下示例使用当前用户的 API Key。trusted 模式需补充部署要求的身份头。读取值的接口和 CLI 命令会返回实际值;树总览和字段元数据接口不返回值。下文的 `***` 仅为示例占位符,不表示接口自动脱敏。
激活版本只改变 OpenViking 保存的配置,不会替外部服务轮换、撤销或恢复密钥。
@@ -22,6 +22,7 @@
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/api/v1/privacy-configs` | 列出隐私配置分类 |
+| GET | `/api/v1/privacy-configs/tree` | 树形列出当前目标和字段元数据,不返回值 |
| POST | `/api/v1/privacy-configs/scan` | 扫描或修复已存储正文中的登记值 |
| GET | `/api/v1/privacy-configs/{category}` | 列出分类下目标 |
| GET | `/api/v1/privacy-configs/{category}/{target_key}` | 获取当前生效配置(meta + current) |
@@ -143,6 +144,54 @@ curl -X GET http://localhost:1933/api/v1/privacy-configs \
---
+### list_privacy_tree()
+
+一次请求列出当前用户的分类、目标、当前生效版本号和字段元数据。
+不返回历史版本或任何保存的值,没有 current 快照的目标会被跳过。
+
+**HTTP API**
+
+```text
+GET /api/v1/privacy-configs/tree
+```
+
+可选查询参数 `category` 将结果限制在一个分类。非法标识符返回 `INVALID_ARGUMENT`。
+空存量返回 `categories: []`;过滤的分类不存在时返回该分类和 `targets: []`。
+
+```bash
+curl "http://localhost:1933/api/v1/privacy-configs/tree?category=credential" \
+ -H "X-API-Key: your-key"
+```
+
+**响应**
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "owner_user_id": "alice",
+ "categories": [{
+ "category": "credential",
+ "targets": [{
+ "target_key": "github",
+ "version": 3,
+ "fields": [{
+ "field": "pat",
+ "configured": true,
+ "reference": "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/pat}}"
+ }]
+ }]
+ }]
+ }
+}
+```
+
+值为 `null` 或空字符串时,`configured` 为 false;其他值(包括 `false` 和 `0`)均为已配置。
+API 始终返回绑定当前 owner 的 reference。CLI 的表格输出仅在设置 `--references`
+时展示引用;JSON 输出保留全部元数据。
+
+---
+
### list_privacy_targets()
列出分类下的 target_key。
@@ -524,6 +573,11 @@ curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-se
ov privacy categories
ov privacy list skill
+# 树形盘点当前目标和字段,不显示值
+ov privacy tree
+ov privacy tree --category credential --references
+ov privacy tree --output json
+
# 当前生效配置(支持快捷形式)
ov privacy get skill byted-viking-search-knowledgebase
ov privacy skill byted-viking-search-knowledgebase
diff --git a/docs/zh/concepts/13-privacy.md b/docs/zh/concepts/13-privacy.md
index c5924ee2c..0b680ba28 100644
--- a/docs/zh/concepts/13-privacy.md
+++ b/docs/zh/concepts/13-privacy.md
@@ -136,6 +136,9 @@ PrivacySanitizer 不根据字段名猜测敏感性。当前 active Privacy 中
# 首次写入或轮换 GitHub PAT;credential/github 是 target,pat 是 field
ov privacy upsert credential github --field-pat 'github_pat_...'
+# 盘点当前目标和字段,不暴露值
+ov privacy tree --category credential --references
+
# target 只有 pat 一个字段时可以省略 field
ov privacy reference credential github
ov privacy resolve credential github
diff --git a/openviking/server/routers/privacy_configs.py b/openviking/server/routers/privacy_configs.py
index 728ac29b3..3aea7a341 100644
--- a/openviking/server/routers/privacy_configs.py
+++ b/openviking/server/routers/privacy_configs.py
@@ -14,7 +14,10 @@ from openviking.privacy.reference import (
)
from openviking.privacy.sanitizer import PrivacySanitizer
from openviking.privacy.scan import PRIVACY_SCAN_MAX_NODES, scan_privacy_content
-from openviking.privacy.validation import validate_privacy_field_name
+from openviking.privacy.validation import (
+ validate_privacy_field_name,
+ validate_privacy_identifier,
+)
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext
@@ -207,6 +210,64 @@ async def delete_privacy_selector(
)
+async def list_privacy_tree(
+ category: Optional[str] = Query(None, description="Limit the tree to one category"),
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """List the caller's active Privacy targets and field metadata without values."""
+ if category is not None:
+ validate_privacy_identifier(category, "category")
+ service = get_service()
+ privacy = service.privacy_configs
+ if privacy is None:
+ return Response(
+ status="ok",
+ result={"owner_user_id": _ctx.user.user_id, "categories": []},
+ )
+
+ if category is not None:
+ categories = [category]
+ else:
+ categories = await privacy.list_categories(_ctx)
+
+ tree = []
+ for name in categories:
+ targets = []
+ for target_key in await privacy.list_targets(_ctx, name):
+ current = await privacy.get_current(_ctx, name, target_key)
+ if current is None:
+ # A Skill update may leave an empty directory behind solely for
+ # its lock; only persisted configuration belongs in the tree.
+ continue
+ fields = [
+ {
+ "field": field,
+ "configured": value is not None and str(value) != "",
+ "reference": build_privacy_field_reference(
+ _ctx.user.user_id,
+ name,
+ target_key,
+ field,
+ ),
+ }
+ for field, value in sorted(current.values.items())
+ ]
+ targets.append(
+ {
+ "target_key": target_key,
+ "version": current.version,
+ "fields": fields,
+ }
+ )
+ tree.append({"category": name, "targets": targets})
+
+ return Response(
+ status="ok",
+ result={"owner_user_id": _ctx.user.user_id, "categories": tree},
+ )
+
+
@router.get("/{category}")
async def list_privacy_targets(
category: str = Path(..., description="Privacy config category"),
diff --git a/tests/server/test_api_privacy_configs.py b/tests/server/test_api_privacy_configs.py
index 664a68651..7427dc37a 100644
--- a/tests/server/test_api_privacy_configs.py
+++ b/tests/server/test_api_privacy_configs.py
@@ -8,6 +8,96 @@ from openviking.server.identity import RequestContext, Role
from openviking_cli.session.user_id import UserIdentifier
+async def test_privacy_tree_lists_current_fields_without_values(client: httpx.AsyncClient, service):
+ created = await client.post(
+ "/api/v1/privacy-configs/credential/github",
+ json={"values": {"pat": "historical-secret-marker", "old_field": "old-value-marker"}},
+ )
+ assert created.status_code == 200, created.text
+ owner = created.json()["result"]["created_by"]
+ for category, target, values in [
+ ("credential", "github", {"pat": "active-secret-marker", "region": "", "unset": None}),
+ ("credential", "flags", {"disabled": False, "retries": 0}),
+ ("skill", "demo", {"api/key": "skill-secret-marker"}),
+ ]:
+ response = await client.post(
+ f"/api/v1/privacy-configs/{category}/{target}", json={"values": values}
+ )
+ assert response.status_code == 200, response.text
+
+ ctx = RequestContext(user=UserIdentifier(service.user.account_id, owner), role=Role.USER)
+ await service.viking_fs.mkdir(f"viking://user/{owner}/privacy/credential/lock-only", ctx=ctx)
+ other_ctx = RequestContext(
+ user=UserIdentifier(service.user.account_id, "other-owner"), role=Role.USER
+ )
+ await service.privacy_configs.upsert(
+ other_ctx, "credential", "other-owner-target", {"token": "other-owner-secret-marker"}
+ )
+ response = await client.get("/api/v1/privacy-configs/tree")
+ assert response.status_code == 200, response.text
+ categories = response.json()["result"]
+ assert categories["owner_user_id"] == owner
+ assert [node["category"] for node in categories["categories"]] == ["credential", "skill"]
+ credential, skill = categories["categories"]
+ assert [node["target_key"] for node in credential["targets"]] == ["flags", "github"]
+ github = credential["targets"][1]
+ assert github == {
+ "target_key": "github",
+ "version": 2,
+ "fields": [
+ {
+ "field": field,
+ "configured": configured,
+ "reference": build_privacy_field_reference(owner, "credential", "github", field),
+ }
+ for field, configured in [("pat", True), ("region", False), ("unset", False)]
+ ],
+ }
+ assert all(field["configured"] for field in credential["targets"][0]["fields"])
+ assert skill["targets"][0]["fields"][0]["reference"] == build_privacy_field_reference(
+ owner, "skill", "demo", "api/key"
+ )
+ for secret in [
+ "historical-secret-marker",
+ "old-value-marker",
+ "active-secret-marker",
+ "skill-secret-marker",
+ "other-owner-secret-marker",
+ "other-owner-target",
+ ]:
+ assert secret not in response.text
+ assert '"values"' not in response.text
+ assert "old_field" not in response.text
+
+ # Activation can select an older version; the tree must follow current, not latest history.
+ activated = await client.post(
+ "/api/v1/privacy-configs/credential/github/activate", json={"version": 1}
+ )
+ assert activated.status_code == 200, activated.text
+ tree = (await client.get("/api/v1/privacy-configs/tree")).json()["result"]
+ assert tree["categories"][0]["targets"][1]["version"] == 1
+
+
+async def test_privacy_tree_category_filter_and_route_not_shadowed(client: httpx.AsyncClient):
+ empty = await client.get("/api/v1/privacy-configs/tree")
+ assert empty.status_code == 200, empty.text
+ assert empty.json()["result"]["categories"] == []
+ for category in ["credential", "skill"]:
+ created = await client.post(
+ f"/api/v1/privacy-configs/{category}/demo", json={"values": {"token": "secret-marker"}}
+ )
+ assert created.status_code == 200, created.text
+ filtered = await client.get("/api/v1/privacy-configs/tree", params={"category": "skill"})
+ assert filtered.status_code == 200, filtered.text
+ assert [node["category"] for node in filtered.json()["result"]["categories"]] == ["skill"]
+ for category in ["", "..", "bad/category"]:
+ invalid = await client.get("/api/v1/privacy-configs/tree", params={"category": category})
+ assert invalid.status_code == 400, invalid.text
+ assert invalid.json()["error"]["code"] == "INVALID_ARGUMENT"
+ missing = await client.get("/api/v1/privacy-configs/tree", params={"category": "missing"})
+ assert missing.json()["result"]["categories"] == [{"category": "missing", "targets": []}]
+
+
async def test_privacy_config_api_roundtrip(client: httpx.AsyncClient):
upsert = await client.post(
"/api/v1/privacy-configs/skill/demo-skill",