From 124ae28dadf68420bd603eae3736849d6a524847 Mon Sep 17 00:00:00 2001 From: RealZST Date: Sun, 29 Nov 2026 18:43:43 +0800 Subject: [PATCH] fix(cli): honour audit filters and --no-scan, and fix piped and coloured output - hk audit --kind and --severity were parsed and ignored; they now filter. - hk audit scanned twice and --no-scan skipped only the second scan; it now scans once, and not at all with --no-scan. - Printing into a closed pipe (hk list --json | head -1) panicked on Unix. - Coloured cells counted their ANSI codes as width, misaligning tables. - hk list agents --json returned an error; it now prints JSON. - An unknown --kind value is rejected instead of ignored, and the help lists cli. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 72 ++++++++++ crates/hk-cli/Cargo.toml | 5 +- crates/hk-cli/src/main.rs | 129 ++++++++++++------ crates/hk-core/src/models.rs | 13 ++ .../src/content/docs/docs/reference/cli.mdx | 14 +- .../content/docs/zh/docs/reference/cli.mdx | 14 +- 6 files changed, 195 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7ce48a6a..be50a151 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,6 +59,25 @@ dependencies = [ "libc", ] +[[package]] +name = "ansi-str" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "060de1453b69f46304b28274f382132f4e72c55637cf362920926a70d090890d" +dependencies = [ + "ansitok", +] + +[[package]] +name = "ansitok" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a8acea8c2f1c60f0a92a8cd26bf96ca97db56f10bbcab238bbe0cceba659ee" +dependencies = [ + "nom", + "vte", +] + [[package]] name = "anstream" version = "1.0.0" @@ -124,6 +143,12 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -658,6 +683,8 @@ version = "7.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47" dependencies = [ + "ansi-str", + "console", "crossterm", "unicode-segmentation", "unicode-width", @@ -672,6 +699,18 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "console" +version = "0.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + [[package]] name = "convert_case" version = "0.4.0" @@ -1172,6 +1211,12 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -1932,6 +1977,7 @@ dependencies = [ "dirs", "hk-core", "hk-web", + "libc", "rand 0.9.4", "serde", "serde_json", @@ -2786,6 +2832,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "minisign-verify" version = "0.2.5" @@ -2923,6 +2975,16 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "notify" version = "7.0.0" @@ -5911,6 +5973,16 @@ dependencies = [ "libc", ] +[[package]] +name = "vte" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "walkdir" version = "2.5.0" diff --git a/crates/hk-cli/Cargo.toml b/crates/hk-cli/Cargo.toml index b413f316..b6b5cd7c 100644 --- a/crates/hk-cli/Cargo.toml +++ b/crates/hk-cli/Cargo.toml @@ -13,12 +13,15 @@ serde.workspace = true serde_json.workspace = true anyhow.workspace = true clap = { version = "4", features = ["derive"] } -comfy-table = "7" +comfy-table = { version = "7", features = ["custom_styling"] } colored = "3" dirs = "6" hk-web = { path = "../hk-web" } tokio = { version = "1", features = ["full"] } rand = "0.9" +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] tempfile = "3" diff --git a/crates/hk-cli/src/main.rs b/crates/hk-cli/src/main.rs index 29679163..9a8aa1cc 100644 --- a/crates/hk-cli/src/main.rs +++ b/crates/hk-cli/src/main.rs @@ -27,9 +27,9 @@ enum Commands { Status, /// List extensions List { - /// Filter by kind: skill, mcp, plugin, hook + /// Filter by kind: skill, mcp, plugin, hook, cli #[arg(long)] - kind: Option, + kind: Option, /// Filter by agent name #[arg(long)] agent: Option, @@ -57,13 +57,13 @@ enum Commands { Audit { /// Audit a specific extension by name name: Option, - /// Filter by kind + /// Filter by kind: skill, mcp, plugin, hook, cli #[arg(long)] - kind: Option, - /// Filter by minimum severity + kind: Option, + /// Only findings at or above this severity: low, medium, high, critical #[arg(long)] - severity: Option, - /// Skip the initial scan and sync (use existing DB state) + severity: Option, + /// Skip the scan and sync (use existing DB state) #[arg(long)] no_scan: bool, }, @@ -142,14 +142,24 @@ fn main() -> Result<()> { return Ok(()); } + // Rust ignores SIGPIPE, so printing into a pipe whose reader has gone + // (`hk list | head -1`) panics. The one-shot commands below end quietly + // instead; `serve` has returned above and keeps ignoring the signal. + #[cfg(unix)] + unsafe { + libc::signal(libc::SIGPIPE, libc::SIG_DFL); + } + let data_dir = hk_data_dir(); std::fs::create_dir_all(&data_dir)?; let store = Store::open(&data_dir.join("metadata.db"))?; let adapters = adapter::all_adapters(); // Sync: scan all agents and upsert into store - let projects = store.list_project_tuples(); - store.sync_scan(&scanner::scan_all(&adapters, &projects))?; + if !matches!(cli.command, Commands::Audit { no_scan: true, .. }) { + let projects = store.list_project_tuples(); + store.sync_scan(&scanner::scan_all(&adapters, &projects))?; + } // Read back from DB so we get backfilled fields (e.g. pack from install_url) let extensions = store.list_extensions(None, None)?; @@ -165,11 +175,10 @@ fn main() -> Result<()> { if sub.as_deref() == Some("agents") { cmd_list_agents(&adapters, json) } else { - let kind_filter = kind.as_deref().and_then(|k| k.parse().ok()); cmd_list( &store, &adapters, - kind_filter, + kind, agent.as_deref(), pack.as_deref(), &extensions, @@ -184,15 +193,8 @@ fn main() -> Result<()> { name, kind, severity, - no_scan, - } => cmd_audit( - &store, - &adapters, - name.as_deref(), - kind.as_deref(), - severity.as_deref(), - no_scan, - ), + .. + } => cmd_audit(&store, &adapters, name.as_deref(), kind, severity), Commands::Enable { name, pack, scope } => cmd_toggle( &store, &extensions, @@ -616,11 +618,43 @@ fn print_list_table(rows: &[ListRow<'_>]) { println!("{table}"); } +#[derive(Serialize)] +struct ListAgentsJsonOutput<'a> { + schema_version: u8, + command: &'static str, + count: usize, + rows: Vec>, +} + +#[derive(Serialize)] +struct ListAgentsJsonRow<'a> { + name: &'a str, + detected: bool, +} + +fn build_list_agents_json_output( + adapters: &[Box], +) -> ListAgentsJsonOutput<'_> { + let rows: Vec<_> = adapters + .iter() + .map(|adapter| ListAgentsJsonRow { + name: adapter.name(), + detected: adapter.detect(), + }) + .collect(); + ListAgentsJsonOutput { + schema_version: 1, + command: "list agents", + count: rows.len(), + rows, + } +} + fn cmd_list_agents(adapters: &[Box], json: bool) -> Result<()> { if json { - return Err(anyhow::anyhow!( - "--json is only supported for extension list output, not list agents" - )); + let output = build_list_agents_json_output(adapters); + println!("{}", serde_json::to_string_pretty(&output)?); + return Ok(()); } let mut table = Table::new(); @@ -788,16 +822,9 @@ fn cmd_audit( store: &Store, adapters: &[Box], name: Option<&str>, - _kind: Option<&str>, - _severity: Option<&str>, - no_scan: bool, + kind: Option, + min_severity: Option, ) -> Result<()> { - // When --no-scan is set, skip the scan_and_sync that main() already did - if !no_scan { - let projects = store.list_project_tuples(); - store.sync_scan(&scanner::scan_all(adapters, &projects))?; - } - let results = service::run_full_audit(store, adapters)?; let extensions = store.list_extensions(None, None)?; @@ -827,7 +854,9 @@ fn cmd_audit( Some(i) => *i, None => continue, }; - if !groups[idx].has_enabled_agent(&enabled_agents) { + if !groups[idx].has_enabled_agent(&enabled_agents) + || kind.is_some_and(|kind| groups[idx].first().kind != kind) + { continue; } let group = merged.entry(idx).or_insert_with(|| GroupedAudit { @@ -863,6 +892,12 @@ fn cmd_audit( if let Some(n) = name { sorted.retain(|g| g.name == n); } + if let Some(min) = min_severity { + for group in &mut sorted { + group.findings.retain(|f| f.severity >= min); + } + sorted.retain(|g| !g.findings.is_empty()); + } // Summary let total = sorted.len(); @@ -1148,13 +1183,29 @@ mod cli_json_tests { } #[test] - fn list_agents_json_returns_unsupported_error() { - let err = cmd_list_agents(&[], true).unwrap_err(); + fn audit_rejects_a_kind_or_severity_it_does_not_know() { + let parsed = Cli::try_parse_from(["hk", "audit", "--kind", "mcp", "--severity", "HIGH"]); + assert!(matches!( + parsed.map(|cli| cli.command), + Ok(Commands::Audit { + kind: Some(ExtensionKind::Mcp), + severity: Some(Severity::High), + .. + }) + )); + assert!(Cli::try_parse_from(["hk", "audit", "--kind", "bogus"]).is_err()); + assert!(Cli::try_parse_from(["hk", "audit", "--severity", "bogus"]).is_err()); + } - assert_eq!( - err.to_string(), - "--json is only supported for extension list output, not list agents" - ); + #[test] + fn list_agents_json_names_each_agent_and_whether_it_is_detected() { + let adapters = adapter::all_adapters(); + let output = serde_json::to_value(build_list_agents_json_output(&adapters)).unwrap(); + + assert_eq!(output["command"], "list agents"); + assert_eq!(output["count"], adapters.len()); + assert_eq!(output["rows"][0]["name"], adapters[0].name()); + assert!(output["rows"][0]["detected"].is_boolean()); } #[test] diff --git a/crates/hk-core/src/models.rs b/crates/hk-core/src/models.rs index 1afc0911..7fe9e0e8 100644 --- a/crates/hk-core/src/models.rs +++ b/crates/hk-core/src/models.rs @@ -322,6 +322,19 @@ impl Severity { } } +impl FromStr for Severity { + type Err = anyhow::Error; + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "low" => Ok(Self::Low), + "medium" => Ok(Self::Medium), + "high" => Ok(Self::High), + "critical" => Ok(Self::Critical), + _ => Err(anyhow::anyhow!("unknown severity: {s}")), + } + } +} + // --- Trust Tier --- #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 006844bb..1305ef79 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -61,7 +61,7 @@ Lists extensions as a table with the columns Name, Kind, Scope, Agent, Source, S | Option | Meaning | |--------|---------| -| `--kind ` | Only this kind: `skill`, `mcp`, `plugin`, `hook` or `cli`. An unrecognized value is ignored and every kind is listed. | +| `--kind ` | Only this kind: `skill`, `mcp`, `plugin`, `hook` or `cli`. | | `--agent ` | Only extensions on this agent, by id. | | `--pack ` | Only extensions from this source repository. | | `--json` | Print JSON instead of a table. | @@ -71,10 +71,10 @@ The JSON output has `schema_version`, `command`, `semantics` (`"grouped"`), `fil ## hk list agents ```bash -hk list agents +hk list agents [--json] ``` -Lists every supported agent and whether it is detected on this machine. It has no `--json` output. +Lists every supported agent and whether it is detected on this machine. With `--json`, the output has `schema_version`, `command`, `count` and `rows`, and each row has `name` and `detected`. ## hk info @@ -92,7 +92,7 @@ Shows one copy of an extension: name, kind, agents, scope, whether it is enabled ## hk audit ```bash -hk audit [NAME] [--no-scan] +hk audit [NAME] [--kind ] [--severity ] [--no-scan] ``` Runs the [security audit](/docs/guides/audit/) over every extension, then prints a summary line with the number of extensions scanned and how many are Safe, Low Risk and Needs Review. Each extension follows, worst score first, with its trust score and its findings. Each finding shows its severity, a message, and where it was found: a file and line, a file or folder, or the name of an MCP server, hook or CLI. @@ -102,7 +102,9 @@ An extension installed on several agents is printed once, with the lowest score | Option | Meaning | |--------|---------| | `NAME` | Print only this extension. The audit still runs over everything. A hook needs its full name, `event:matcher:command`. A name that matches nothing prints `0 extensions scanned` and exits with code 0. | -| `--no-scan` | Skip the second scan that `audit` runs right before auditing. The scan every command runs at startup still happens. | +| `--kind ` | Print only extensions of this kind: `skill`, `mcp`, `plugin`, `hook` or `cli`. | +| `--severity ` | Print only findings at or above this severity: `low`, `medium`, `high` or `critical`. | +| `--no-scan` | Skip the scan that every command runs at startup, and audit the extensions HarnessKit already has on record. | ## hk enable and hk disable @@ -189,7 +191,7 @@ $ hk list --pack owner/repo --json # one source, as JSON } ``` -`hk list` groups extensions the way the desktop Extensions table does, so a skill installed on two agents is one row that names both. `hk list agents` has no JSON output. +`hk list` groups extensions the way the desktop Extensions table does, so a skill installed on two agents is one row that names both. A hook's `name` in the JSON is its full name, `event:matcher:command`. Pass that name to `hk info`, `hk enable` or `hk disable`, in quotes, since a command often has spaces: diff --git a/website/src/content/docs/zh/docs/reference/cli.mdx b/website/src/content/docs/zh/docs/reference/cli.mdx index 994f8953..4eeb3caa 100644 --- a/website/src/content/docs/zh/docs/reference/cli.mdx +++ b/website/src/content/docs/zh/docs/reference/cli.mdx @@ -63,7 +63,7 @@ hk list [--kind ] [--agent ] [--pack ] [--json] | 选项 | 含义 | |--------|---------| -| `--kind ` | 只列出这一类:`skill`、`mcp`、`plugin`、`hook` 或 `cli`。值无法识别时忽略此选项,照常列出所有类型。 | +| `--kind ` | 只列出这一类:`skill`、`mcp`、`plugin`、`hook` 或 `cli`。 | | `--agent ` | 只列出该 agent 上的扩展,用 id 指定。 | | `--pack ` | 只列出来自该源仓库的扩展。 | | `--json` | 输出 JSON,而不是表格。 | @@ -73,10 +73,10 @@ JSON 输出包含 `schema_version`、`command`、`semantics`(`"grouped"`)、 ## hk list agents ```bash -hk list agents +hk list agents [--json] ``` -列出所有支持的 agent,以及这台机器上是否检测到它们。此命令没有 `--json` 输出。 +列出所有支持的 agent,以及这台机器上是否检测到它们。加上 `--json` 时,输出包含 `schema_version`、`command`、`count` 和 `rows`,每一行有 `name` 和 `detected`。 ## hk info @@ -94,7 +94,7 @@ hk info [--scope ] [--json] ## hk audit ```bash -hk audit [NAME] [--no-scan] +hk audit [NAME] [--kind ] [--severity ] [--no-scan] ``` 对所有扩展运行[安全审计](/zh/docs/guides/audit/),然后打印一行汇总:扫描了多少个扩展,其中安全、低风险、需复核的各有多少。接着按分数从低到高逐个列出扩展,并附上信任评分和问题。每个问题显示严重程度、一条说明,以及问题所在的位置:文件和行号、文件或文件夹,或者 MCP server、hook、CLI 的名称。 @@ -104,7 +104,9 @@ hk audit [NAME] [--no-scan] | 选项 | 含义 | |--------|---------| | `NAME` | 只打印该扩展。审计仍会对全部扩展执行。hook 需要使用全名 `event:matcher:command`。若没有任何名称匹配,打印 `0 extensions scanned`,退出码为 0。 | -| `--no-scan` | 跳过 `audit` 在审计前紧接着执行的第二次扫描。每个命令启动时都会执行的那次扫描不受影响。 | +| `--kind ` | 只打印这一类扩展:`skill`、`mcp`、`plugin`、`hook` 或 `cli`。 | +| `--severity ` | 只打印严重程度不低于此值的问题:`low`、`medium`、`high` 或 `critical`。 | +| `--no-scan` | 跳过每个命令启动时执行的扫描,直接审计 HarnessKit 已记录的扩展。 | ## hk enable 和 hk disable @@ -191,7 +193,7 @@ $ hk list --pack owner/repo --json # 某个来源的扩展,输出 JSON } ``` -`hk list` 与桌面应用的**扩展**表格一样合并扩展:一个 skill 安装在两个 agent 上,也只占一行,两个 agent 都列在这一行中。`hk list agents` 没有 JSON 输出。 +`hk list` 与桌面应用的**扩展**表格一样合并扩展:一个 skill 安装在两个 agent 上,也只占一行,两个 agent 都列在这一行中。 hook 在 JSON 中的 `name` 是全名 `event:matcher:command`。把这个名称传给 `hk info`、`hk enable` 或 `hk disable` 时,需要加引号,因为命令中常有空格: