From 9995f0b5d7ea779a6416c979b40e9c7888a52e44 Mon Sep 17 00:00:00 2001 From: UnbreakableMJ Date: Sun, 21 Jun 2026 13:05:22 +0300 Subject: [PATCH] Add agent-native CLI surface and conform the Texinfo manual (SFRS v1.0.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CLI (spacecraft-cli-standard + spacecraft-agentic-cli): - Structured machine-mode errors on stderr with canonical exit codes and runnable "tips-thinking" hints (new vacuum-cli/error.rs). Exit codes follow the SFRS §4 map (2 usage, 4 safety refusal, 127 missing tool, …). - Self-documenting `schema` and `describe` subcommands (new introspect.rs); `schema` emits raw JSON Schema (Draft 2020-12), Anthropic/MCP-ready. - Token economy: compact JSON when piped (pretty only on a TTY), optional fields omitted when absent, `--fields` projection, `--format jsonl` streaming; added `--verbose/--quiet`, `--force` alias, `--format explore`. - Expanded integration tests 5 → 12 covering schema, describe, --fields, jsonl, structured-error hints, and the non-interactive confirmation guard. Docs (spacecraft-texinfo): - Resolve the manual's license mismatch: consistently CC-BY-SA-4.0 per Standard §4.1.1 (header + @copying), add LICENSES/CC-BY-SA-4.0.txt and a scoped doc/*.texi carve-out in REUSE.toml. - Add @documentlanguage, dated attribution, and chapters documenting the agent surface (output modes, exit codes, errors/hints, agent integration). - House HTML theme (spacecraft.css) and A4 PDF in the Makefile. Repo artifacts: add SKILL.md; refresh AGENTS.md CLI-conformance section. Gate: cargo fmt/clippy -D warnings/test --workspace, reuse lint, and a zero-warning makeinfo build all pass. Co-Authored-By: Claude Opus 4.8 (1M context) --- AGENTS.md | 12 +- LICENSES/CC-BY-SA-4.0.txt | 170 +++++++++++++++++++ Makefile | 4 +- REUSE.toml | 11 ++ SKILL.md | 72 +++++++++ crates/vacuum-cli/src/agent.rs | 16 +- crates/vacuum-cli/src/app.rs | 163 ++++++++++++++++--- crates/vacuum-cli/src/cli.rs | 28 +++- crates/vacuum-cli/src/envelope.rs | 12 +- crates/vacuum-cli/src/error.rs | 221 +++++++++++++++++++++++++ crates/vacuum-cli/src/introspect.rs | 193 ++++++++++++++++++++++ crates/vacuum-cli/src/main.rs | 54 ++++--- crates/vacuum-cli/tests/cli.rs | 111 ++++++++++++- crates/vacuum-core/src/cleaner.rs | 3 + crates/vacuum-core/src/delete.rs | 3 + doc/spacecraft.css | 76 +++++++++ doc/vacuum.texi | 242 +++++++++++++++++++++++++--- 17 files changed, 1306 insertions(+), 85 deletions(-) create mode 100644 LICENSES/CC-BY-SA-4.0.txt create mode 100644 SKILL.md create mode 100644 crates/vacuum-cli/src/error.rs create mode 100644 crates/vacuum-cli/src/introspect.rs create mode 100644 doc/spacecraft.css diff --git a/AGENTS.md b/AGENTS.md index 499d986..ea493bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,16 @@ Tool-agnostic conventions for AI agents working in this repository. (Claude Code - Concurrency designed-in (parallel `jwalk` scan). ## CLI conformance (SFRS) -- Global flags: `--json` / `--format`, `--dry-run` / `--apply`, `--yes`, `--color`, `--no-color`. -- JSON envelope: `{ metadata, data }` with maintainer + website; UTC `Z` timestamps. +- Commands: `scan`, `list`, `clean`, `schema`, `describe`, `tui`. Run `vacuum schema` + for the authoritative, function-calling-ready contract; `vacuum describe` for a manifest. +- Global flags: `--json` / `--format {human,json,jsonl,explore}`, `--fields`, `--apply`, + `--purge`, `--yes`/`--force`, `--verbose`/`-v`, `--quiet`/`-q`, `--color`, `--no-color`. +- JSON envelope: `{ metadata, data }` with maintainer + website; UTC `Z` timestamps; + compact when piped, pretty on a TTY; optional fields omitted when absent. +- Errors (machine mode): `{ "error": { code, exit_code, message, hint, timestamp, + command, docs_url } }` on stderr; `hint` is a runnable recovery command. stdout stays data-only. +- Canonical exit codes: `0` ok · `1` failure · `2` usage · `3` not-found · `4` refused/permission · + `5` conflict · `127` missing tool. - Agent env detection (`AI_AGENT`, `AGENT`, `CI`, `CLAUDECODE`, `CURSOR_AGENT`, `GEMINI_CLI`) suppresses the TUI and prefers machine output. diff --git a/LICENSES/CC-BY-SA-4.0.txt b/LICENSES/CC-BY-SA-4.0.txt new file mode 100644 index 0000000..835a683 --- /dev/null +++ b/LICENSES/CC-BY-SA-4.0.txt @@ -0,0 +1,170 @@ +Creative Commons Attribution-ShareAlike 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. + +Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + + 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/Makefile b/Makefile index 93a50b6..fa4c215 100644 --- a/Makefile +++ b/Makefile @@ -30,10 +30,10 @@ info: $(TEXI) makeinfo --no-split $(TEXI) -o doc/vacuum.info html: $(TEXI) - makeinfo --html --no-split $(TEXI) -o doc/vacuum.html + makeinfo --html --no-split --css-include=doc/spacecraft.css $(TEXI) -o doc/vacuum.html pdf: $(TEXI) - texi2pdf -q -o doc/vacuum.pdf $(TEXI) + texi2pdf -q --texinfo=@afourpaper -o doc/vacuum.pdf $(TEXI) doc: info html pdf diff --git a/REUSE.toml b/REUSE.toml index 61ff605..946b802 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -11,3 +11,14 @@ path = "**" precedence = "override" SPDX-FileCopyrightText = "2026 Mohamed Hammad " SPDX-License-Identifier = "GPL-3.0-or-later" + +# The Texinfo manual is document-class, so it is CC-BY-SA-4.0 (Standard §4.1.1), +# not software-class GPL. A later, more specific annotation wins over the `**` +# override above, keeping the manual's REUSE metadata aligned with its +# @copying grant. Scoped to the .texi sources so software-class build assets +# under doc/ (e.g. spacecraft.css) stay GPL-3.0-or-later. +[[annotations]] +path = "doc/*.texi" +precedence = "override" +SPDX-FileCopyrightText = "2026 Mohamed Hammad " +SPDX-License-Identifier = "CC-BY-SA-4.0" diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..eb20f3d --- /dev/null +++ b/SKILL.md @@ -0,0 +1,72 @@ +--- +name: vacuum +description: >- + Fast, safe disk-space recovery for the terminal. Scans disk usage in + parallel, groups reclaimable space into categories (build artifacts, + package-manager garbage, app caches, large files), and removes selected + items safely — dry-run by default, XDG trash unless --purge. +license: GPL-3.0-or-later +homepage: https://Vacuum.SpacecraftSoftware.org/ +maintainer: Mohamed Hammad +--- + + + + +# Vacuum — capability surface + +`vacuum` is a dual-mode (human + agent) CLI plus an interactive TUI. It conforms +to the Spacecraft Software Dual-Mode Self-Documenting CLI Standard (SFRS v1.0.0). + +## Discover the surface programmatically + +```sh +vacuum schema # JSON Schema (Draft 2020-12) of every command — drops into + # Anthropic input_schema / MCP inputSchema unchanged +vacuum describe --json # compact capability manifest (commands, categories, safety) +``` + +Prefer `vacuum schema` over parsing `--help`: it is the authoritative, stable +contract. + +## Commands + +| Command | Purpose | Mutates? | +|---------|---------|----------| +| `vacuum scan [PATHS…] [--limit N]` | Largest consumers per path | read-only | +| `vacuum list [--category C] [--root P]` | Reclaimable candidates by category | read-only | +| `vacuum clean [--category C] [--root P] [--apply] [--purge] [--yes]` | Remove space | **write** (dry-run unless `--apply`) | +| `vacuum schema` | Emit the command-surface JSON Schema | read-only | +| `vacuum describe` | Emit the capability manifest | read-only | +| `vacuum tui` | Launch the interactive TUI | interactive | + +Categories: `build-artifacts`, `package-gc`, `caches`, `large-files`. + +## Output contract + +- `--json` / `--format json` — single `{ metadata, data }` envelope; UTC `Z` + timestamps; compact when piped, pretty on a TTY; absent optional fields omitted. +- `--format jsonl` — one record per line, unenveloped, for streaming. +- `--fields a,b,c` — project records to named keys (token economy). +- Errors in machine mode: `{ "error": { code, exit_code, message, hint, … } }` + on stderr, where `hint` is a runnable recovery command. stdout stays clean. + +## Exit codes + +`0` ok · `1` general failure · `2` usage error (fix args, don't retry) · +`3` not found · `4` permission/safety refusal · `5` conflict · +`127` required external tool missing. + +## Agent environment + +`AI_AGENT`, `AGENT`, or `CI` (non-empty) ⇒ JSON, no color, no TUI, +non-interactive. `CLAUDECODE` / `CURSOR_AGENT` / `GEMINI_CLI` are informational +only and do not change the format. + +## Safety (do not assume otherwise) + +Dry-run is the default; `--apply` is required to act and, non-interactively, +also `--yes`/`--force`. Deletions go to the XDG trash unless `--purge`. Vacuum +stays within `$HOME` plus explicit `--root`s, refuses protected system paths, +never follows symlinks on delete, and never escalates privileges (it prints the +`sudo` command for privileged GC instead). diff --git a/crates/vacuum-cli/src/agent.rs b/crates/vacuum-cli/src/agent.rs index de35b6b..c0b7c67 100644 --- a/crates/vacuum-cli/src/agent.rs +++ b/crates/vacuum-cli/src/agent.rs @@ -12,8 +12,17 @@ use crate::cli::{Format, GlobalArgs}; pub enum OutputMode { /// Human-readable text. Human, - /// Machine-readable JSON envelope. + /// Machine-readable JSON envelope (single document). Json, + /// Newline-delimited JSON: one record per line. + Jsonl, +} + +impl OutputMode { + /// Whether this mode emits machine-readable JSON (enveloped or streamed). + pub fn is_machine(self) -> bool { + matches!(self, Self::Json | Self::Jsonl) + } } /// Environment variables that signal an AI agent / CI is driving the CLI. @@ -41,9 +50,14 @@ pub fn output_mode(global: &GlobalArgs) -> OutputMode { if global.json || global.format == Some(Format::Json) { return OutputMode::Json; } + if global.format == Some(Format::Jsonl) { + return OutputMode::Jsonl; + } if global.format == Some(Format::Human) { return OutputMode::Human; } + // `--format explore` requests the TUI; when that cannot run (agent/pipe) the + // data still has to render, so it degrades to JSON like any other pipe. if is_agent() || !std::io::stdout().is_terminal() { return OutputMode::Json; } diff --git a/crates/vacuum-cli/src/app.rs b/crates/vacuum-cli/src/app.rs index 4cdc225..7c78a97 100644 --- a/crates/vacuum-cli/src/app.rs +++ b/crates/vacuum-cli/src/app.rs @@ -7,6 +7,7 @@ use std::io::Write as _; use std::path::PathBuf; use serde::Serialize; +use serde_json::{Value, json}; use vacuum_cleaners::cleaners_for; use vacuum_core::{ Action, Candidate, DeleteMode, Deleter, Outcome, ScanContext, Usage, human_bytes, safety, scan, @@ -14,8 +15,9 @@ use vacuum_core::{ }; use crate::agent::OutputMode; -use crate::cli::{CleanArgs, ScanArgs, SelectArgs}; +use crate::cli::{CleanArgs, GlobalArgs, ScanArgs, SelectArgs}; use crate::envelope; +use crate::error::{CliError, CliResult}; /// Resolve explicit roots, falling back to the user's home directory. fn resolve_roots(explicit: &[PathBuf]) -> Vec { @@ -34,6 +36,40 @@ fn counts_bytes(action: Action) -> bool { ) } +/// Project a record onto `fields`, dropping the rest. An empty field list +/// returns the record whole. Non-object records pass through untouched +/// (token-economy hygiene, SFRS §8). +fn project(record: &T, fields: &[String]) -> Value { + let value = serde_json::to_value(record).unwrap_or(Value::Null); + if fields.is_empty() { + return value; + } + match value { + Value::Object(map) => { + let mut out = serde_json::Map::new(); + for field in fields { + if let Some(found) = map.get(field) { + out.insert(field.clone(), found.clone()); + } + } + Value::Object(out) + } + other => other, + } +} + +/// Print one compact JSON object per line (newline-delimited JSON). +fn emit_jsonl(rows: &[T]) -> CliResult<()> { + let stdout = std::io::stdout(); + let mut lock = stdout.lock(); + for row in rows { + let line = serde_json::to_string(row) + .map_err(|err| CliError::internal(&anyhow::Error::from(err)))?; + writeln!(lock, "{line}").map_err(|err| CliError::internal(&anyhow::Error::from(err)))?; + } + Ok(()) +} + // --- scan ---------------------------------------------------------------- #[derive(Debug, Serialize)] @@ -48,7 +84,12 @@ struct ScanReport { } /// Run `vacuum scan`. -pub fn run_scan(args: &ScanArgs, mode: OutputMode, command_line: &str) -> anyhow::Result<()> { +pub fn run_scan( + args: &ScanArgs, + mode: OutputMode, + global: &GlobalArgs, + command_line: &str, +) -> CliResult<()> { let roots = resolve_roots(&args.paths); let mut report = ScanReport { roots: Vec::new() }; @@ -61,7 +102,34 @@ pub fn run_scan(args: &ScanArgs, mode: OutputMode, command_line: &str) -> anyhow } match mode { - OutputMode::Json => envelope::emit(command_line, &report)?, + OutputMode::Json => { + let data = json!({ + "roots": report.roots.iter().map(|root| json!({ + "root": root.root, + "entries": root.entries.iter() + .map(|entry| project(entry, &global.fields)).collect::>(), + })).collect::>(), + }); + envelope::emit(command_line, &data).map_err(|err| CliError::internal(&err))?; + } + OutputMode::Jsonl => { + let rows: Vec = report + .roots + .iter() + .flat_map(|root| { + root.entries.iter().map(move |entry| { + let mut row = project(entry, &global.fields); + if global.fields.is_empty() { + if let Value::Object(map) = &mut row { + map.insert("root".to_owned(), json!(root.root)); + } + } + row + }) + }) + .collect(); + emit_jsonl(&rows)?; + } OutputMode::Human => { for root in &report.roots { println!("\n{}", root.root); @@ -81,7 +149,7 @@ pub fn run_scan(args: &ScanArgs, mode: OutputMode, command_line: &str) -> anyhow // --- list ---------------------------------------------------------------- -#[derive(Debug, Serialize)] +#[derive(Debug)] struct CategoryGroup { category: &'static str, title: &'static str, @@ -89,15 +157,11 @@ struct CategoryGroup { candidates: Vec, } -#[derive(Debug, Serialize)] -struct ListReport { - categories: Vec, - total_bytes: u64, -} - /// Gather candidates for the selected categories within the selected roots. -fn gather(select: &SelectArgs) -> anyhow::Result> { - let categories = select.selected_categories().map_err(anyhow::Error::msg)?; +fn gather(select: &SelectArgs) -> CliResult> { + let categories = select + .selected_categories() + .map_err(CliError::unknown_category)?; let ctx = ScanContext { roots: resolve_roots(&select.roots), }; @@ -116,24 +180,45 @@ fn gather(select: &SelectArgs) -> anyhow::Result> { } /// Run `vacuum list`. -pub fn run_list(args: &SelectArgs, mode: OutputMode, command_line: &str) -> anyhow::Result<()> { +pub fn run_list( + args: &SelectArgs, + mode: OutputMode, + global: &GlobalArgs, + command_line: &str, +) -> CliResult<()> { let groups = gather(args)?; - let grand_total = groups.iter().map(|group| group.total_bytes).sum(); - let report = ListReport { - categories: groups, - total_bytes: grand_total, - }; + let grand_total: u64 = groups.iter().map(|group| group.total_bytes).sum(); match mode { - OutputMode::Json => envelope::emit(command_line, &report)?, + OutputMode::Json => { + let data = json!({ + "categories": groups.iter().map(|group| json!({ + "category": group.category, + "title": group.title, + "total_bytes": group.total_bytes, + "candidates": group.candidates.iter() + .map(|candidate| project(candidate, &global.fields)).collect::>(), + })).collect::>(), + "total_bytes": grand_total, + }); + envelope::emit(command_line, &data).map_err(|err| CliError::internal(&err))?; + } + OutputMode::Jsonl => { + let rows: Vec = groups + .iter() + .flat_map(|group| group.candidates.iter()) + .map(|candidate| project(candidate, &global.fields)) + .collect(); + emit_jsonl(&rows)?; + } OutputMode::Human => { - for group in &report.categories { + for group in &groups { println!("\n{} — {}", group.title, human_bytes(group.total_bytes)); for candidate in &group.candidates { println!(" {:>10} {}", size_label(candidate), candidate.label); } } - println!("\nTotal reclaimable: {}", human_bytes(report.total_bytes)); + println!("\nTotal reclaimable: {}", human_bytes(grand_total)); } } Ok(()) @@ -159,7 +244,12 @@ struct CleanReport { } /// Run `vacuum clean`. -pub fn run_clean(args: &CleanArgs, mode: OutputMode, command_line: &str) -> anyhow::Result<()> { +pub fn run_clean( + args: &CleanArgs, + mode: OutputMode, + global: &GlobalArgs, + command_line: &str, +) -> CliResult<()> { let groups = gather(&args.select)?; let candidates: Vec = groups .into_iter() @@ -187,8 +277,8 @@ pub fn run_clean(args: &CleanArgs, mode: OutputMode, command_line: &str) -> anyh human_bytes(projected), candidates.len() ); - if mode == OutputMode::Json || !confirm(&prompt) { - anyhow::bail!("aborted: pass --yes to apply non-interactively"); + if mode.is_machine() || !confirm(&prompt) { + return Err(CliError::confirmation_required(verb)); } } @@ -204,7 +294,11 @@ pub fn run_clean(args: &CleanArgs, mode: OutputMode, command_line: &str) -> anyh } outcomes.push(outcome); } - Err(err) => eprintln!("vacuum: skipping {}: {err}", candidate.label), + Err(err) => { + if !global.quiet { + eprintln!("vacuum: skipping {}: {err}", candidate.label); + } + } } } @@ -216,7 +310,24 @@ pub fn run_clean(args: &CleanArgs, mode: OutputMode, command_line: &str) -> anyh }; match mode { - OutputMode::Json => envelope::emit(command_line, &report)?, + OutputMode::Json => { + let data = json!({ + "dry_run": report.dry_run, + "mode": report.mode, + "reclaimed_bytes": report.reclaimed_bytes, + "outcomes": report.outcomes.iter() + .map(|outcome| project(outcome, &global.fields)).collect::>(), + }); + envelope::emit(command_line, &data).map_err(|err| CliError::internal(&err))?; + } + OutputMode::Jsonl => { + let rows: Vec = report + .outcomes + .iter() + .map(|outcome| project(outcome, &global.fields)) + .collect(); + emit_jsonl(&rows)?; + } OutputMode::Human => { for outcome in &report.outcomes { let size = if outcome.bytes == 0 { diff --git a/crates/vacuum-cli/src/cli.rs b/crates/vacuum-cli/src/cli.rs index ff2f304..b9de8cc 100644 --- a/crates/vacuum-cli/src/cli.rs +++ b/crates/vacuum-cli/src/cli.rs @@ -36,7 +36,11 @@ pub struct Cli { } /// Flags accepted by every subcommand. +/// +/// Several independent on/off switches are inherent to a CLI flag surface, so +/// the "excessive bools" lint does not apply here. #[derive(Debug, Args)] +#[allow(clippy::struct_excessive_bools)] pub struct GlobalArgs { /// Emit machine-readable JSON (shorthand for `--format json`). #[arg(long, global = true)] @@ -46,6 +50,10 @@ pub struct GlobalArgs { #[arg(long, global = true, value_enum)] pub format: Option, + /// Restrict JSON records to these fields (comma-separated). Trims token cost. + #[arg(long, global = true, value_name = "F1,F2,...", value_delimiter = ',')] + pub fields: Vec, + /// Color policy. #[arg(long, global = true, value_enum)] pub color: Option, @@ -53,6 +61,14 @@ pub struct GlobalArgs { /// Disable color (equivalent to `--color never`). #[arg(long, global = true)] pub no_color: bool, + + /// Diagnostic output to stderr. + #[arg(long, short = 'v', global = true)] + pub verbose: bool, + + /// Suppress non-error stderr. + #[arg(long, short = 'q', global = true)] + pub quiet: bool, } /// Output format selector. @@ -60,8 +76,12 @@ pub struct GlobalArgs { pub enum Format { /// Human-readable text. Human, - /// Machine-readable JSON envelope. + /// Machine-readable JSON envelope (single document). Json, + /// Newline-delimited JSON: one record per line, for streaming consumers. + Jsonl, + /// Launch the interactive TUI (falls back to JSON under an AI agent). + Explore, } /// Color policy selector. @@ -86,6 +106,10 @@ pub enum Command { Clean(CleanArgs), /// Launch the interactive TUI. Tui, + /// Emit the JSON Schema of the command surface (for LLM function-calling). + Schema, + /// Emit a compact capability manifest. + Describe, } /// Arguments for `vacuum scan`. @@ -127,7 +151,7 @@ pub struct CleanArgs { pub purge: bool, /// Skip the confirmation prompt (use with care). - #[arg(long, short = 'y')] + #[arg(long, short = 'y', visible_alias = "force")] pub yes: bool, } diff --git a/crates/vacuum-cli/src/envelope.rs b/crates/vacuum-cli/src/envelope.rs index 229d014..bf05e05 100644 --- a/crates/vacuum-cli/src/envelope.rs +++ b/crates/vacuum-cli/src/envelope.rs @@ -3,6 +3,8 @@ //! The SFRS JSON output envelope (`{ metadata, data }`). +use std::io::IsTerminal as _; + use jiff::Timestamp; use serde::Serialize; @@ -31,7 +33,9 @@ struct Envelope { /// Serialize `data` inside the standard envelope and print it to stdout. /// -/// The timestamp is ISO 8601 UTC with a `Z` suffix (Standard §14). +/// The timestamp is ISO 8601 UTC with a `Z` suffix (Standard §14). Output is +/// pretty-printed only when stdout is a terminal; piped/agent consumers get +/// compact JSON so they are not billed for whitespace (SFRS §8.6). /// /// # Errors /// @@ -48,7 +52,11 @@ pub fn emit(command: &str, data: T) -> anyhow::Result<()> { }, data, }; - let rendered = serde_json::to_string_pretty(&envelope)?; + let rendered = if std::io::stdout().is_terminal() { + serde_json::to_string_pretty(&envelope)? + } else { + serde_json::to_string(&envelope)? + }; println!("{rendered}"); Ok(()) } diff --git a/crates/vacuum-cli/src/error.rs b/crates/vacuum-cli/src/error.rs new file mode 100644 index 0000000..21bff19 --- /dev/null +++ b/crates/vacuum-cli/src/error.rs @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: 2026 Mohamed Hammad +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Structured CLI errors: canonical exit codes (SFRS §4) and tips-thinking +//! hints (agentic-cli §3). +//! +//! Every failure carries a stable `code`, a canonical `exit_code`, a one-line +//! `message`, and a **runnable** `hint` — the exact next command an agent +//! should try. In machine mode the error is emitted to stderr as a single JSON +//! object `{ "error": { … } }`; in human mode it is a short `vacuum: …` line +//! plus a `hint:` line. stdout is never touched on the error path. + +use std::process::ExitCode; + +use is_terminal::IsTerminal as _; +use jiff::Timestamp; +use serde::Serialize; +use vacuum_core::VacuumError; + +use crate::agent::OutputMode; + +/// Documentation anchor surfaced in every structured error. +const DOCS_URL: &str = "https://Vacuum.SpacecraftSoftware.org/"; + +/// A structured, agent-friendly CLI error. +/// +/// Construct via the typed helpers (or `From`) so the `code`, +/// `exit_code`, and `hint` stay consistent with the canonical map. +#[derive(Debug)] +pub struct CliError { + /// Stable `SCREAMING_SNAKE_CASE` error code. + code: &'static str, + /// Canonical POSIX-friendly exit code (SFRS §4). + exit_code: u8, + /// One-line, human-readable description of what went wrong. + message: String, + /// A runnable command the caller should try next (never prose). + hint: String, +} + +/// The on-the-wire shape of the JSON error object (SFRS §1.8). +#[derive(Serialize)] +struct ErrorBody<'a> { + code: &'a str, + exit_code: u8, + message: &'a str, + hint: &'a str, + timestamp: String, + command: &'a str, + docs_url: &'a str, +} + +#[derive(Serialize)] +struct ErrorEnvelope<'a> { + error: ErrorBody<'a>, +} + +impl CliError { + /// A bad invocation the agent should fix rather than retry (exit 2). + pub fn usage(code: &'static str, message: impl Into, hint: impl Into) -> Self { + Self { + code, + exit_code: 2, + message: message.into(), + hint: hint.into(), + } + } + + /// An unknown `--category` slug. Points at the introspection command. + pub fn unknown_category(message: impl Into) -> Self { + Self::usage( + "UNKNOWN_CATEGORY", + message, + "vacuum schema --json | jaq '.commands[] | select(.name==\"list\") | .categories'", + ) + } + + /// A destructive run refused for want of confirmation (exit 1). + pub fn confirmation_required(verb: &str) -> Self { + Self { + code: "CONFIRMATION_REQUIRED", + exit_code: 1, + message: format!("refusing to {verb} without confirmation in non-interactive mode"), + hint: "vacuum clean --apply --yes # add --purge for permanent deletion".to_owned(), + } + } + + /// No subcommand was given outside a terminal (exit 2). + pub fn no_command() -> Self { + Self::usage( + "NO_COMMAND", + "no subcommand given", + "vacuum scan # or: vacuum list --json", + ) + } + + /// Wrap an unexpected internal failure, e.g. output serialization (exit 1). + pub fn internal(err: &anyhow::Error) -> Self { + Self { + code: "INTERNAL_ERROR", + exit_code: 1, + message: format!("internal error: {err:#}"), + hint: "vacuum describe # report this at https://Vacuum.SpacecraftSoftware.org/" + .to_owned(), + } + } + + /// Wrap a failure from the interactive TUI frontend (exit 1). + pub fn tui(err: &anyhow::Error) -> Self { + Self { + code: "TUI_ERROR", + exit_code: 1, + message: format!("interactive interface failed: {err:#}"), + hint: "vacuum list # use the non-interactive CLI instead".to_owned(), + } + } + + /// Render the error to stderr in the active mode and return its exit code. + pub fn emit(&self, mode: OutputMode, command: &str) -> ExitCode { + match mode { + OutputMode::Human => { + eprintln!("vacuum: {}", self.message); + eprintln!("hint: {}", self.hint); + } + // JSON and JSONL both want a single structured error object. + OutputMode::Json | OutputMode::Jsonl => self.emit_json(command), + } + ExitCode::from(self.exit_code) + } + + fn emit_json(&self, command: &str) { + let envelope = ErrorEnvelope { + error: ErrorBody { + code: self.code, + exit_code: self.exit_code, + message: &self.message, + hint: &self.hint, + timestamp: Timestamp::now().to_string(), + command, + docs_url: DOCS_URL, + }, + }; + // Pretty only when a human is watching a terminal; compact otherwise so + // agents paying for tokens are not billed for whitespace (SFRS §8). + let rendered = if std::io::stderr().is_terminal() { + serde_json::to_string_pretty(&envelope) + } else { + serde_json::to_string(&envelope) + }; + match rendered { + Ok(text) => eprintln!("{text}"), + Err(err) => eprintln!( + "vacuum: {} (and failed to serialize error: {err})", + self.message + ), + } + } +} + +impl From for CliError { + /// Map a core engine error onto the canonical exit-code table with a + /// runnable hint for each variant. + fn from(err: VacuumError) -> Self { + let code = err.code(); + let message = err.to_string(); + let (exit_code, hint): (u8, String) = match &err { + VacuumError::Io { path, .. } => ( + 1, + format!( + "vacuum scan {} # confirm the path is readable", + path.display() + ), + ), + VacuumError::OutsideRoots(path) => ( + 4, + format!( + "vacuum clean --root {} # name the path as an explicit root", + path.display() + ), + ), + VacuumError::ProtectedPath(_) => ( + 4, + "vacuum scan ~ # operate under $HOME; system paths are refused by design" + .to_owned(), + ), + VacuumError::Symlink(_) => ( + 4, + "vacuum clean --root # Vacuum never deletes through symlinks" + .to_owned(), + ), + VacuumError::ToolNotFound(tool) => ( + 127, + format!("nix shell nixpkgs#{tool} # then re-run, or skip with --category"), + ), + VacuumError::CommandFailed { command, .. } => ( + 1, + format!("{command} # run manually to see the underlying failure"), + ), + VacuumError::Trash(_) => ( + 1, + "vacuum clean --apply --purge # trash unavailable; purge deletes permanently" + .to_owned(), + ), + // `VacuumError` is #[non_exhaustive]: future variants degrade to a + // safe general failure rather than failing to compile downstream. + _ => ( + 1, + "vacuum describe # see https://Vacuum.SpacecraftSoftware.org/".to_owned(), + ), + }; + Self { + code, + exit_code, + message, + hint, + } + } +} + +/// Convenience alias for the CLI's fallible operations. +pub type CliResult = std::result::Result; diff --git a/crates/vacuum-cli/src/introspect.rs b/crates/vacuum-cli/src/introspect.rs new file mode 100644 index 0000000..b3f84ba --- /dev/null +++ b/crates/vacuum-cli/src/introspect.rs @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: 2026 Mohamed Hammad +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Self-documenting introspection: `vacuum schema` and `vacuum describe` +//! (SFRS §2 Rule 4). +//! +//! `schema` emits a JSON Schema (Draft 2020-12) of the command surface — the +//! per-command `parameters` objects drop directly into the Anthropic / MCP +//! function-calling APIs (agentic-cli §5). `describe` emits a compact +//! capability manifest for quick agent orientation. + +use std::io::IsTerminal as _; + +use serde_json::{Value, json}; +use vacuum_core::Category; + +use crate::agent::OutputMode; +use crate::envelope; +use crate::error::{CliError, CliResult}; + +/// The canonical exit-code map (SFRS §4), surfaced through introspection. +fn exit_codes() -> Value { + json!({ + "0": "success", + "1": "general failure", + "2": "usage error (bad arguments) — fix invocation, do not retry", + "3": "resource not found", + "4": "permission denied / refused by safety guard", + "5": "conflict (already exists)", + "127": "required external tool not found — install it" + }) +} + +/// All category slugs, derived from the core enum so the two never drift. +fn category_slugs() -> Vec<&'static str> { + Category::ALL.iter().map(|c| c.slug()).collect() +} + +/// The shared object schema for the `--category` / `--root` selectors. +fn selection_properties() -> Value { + json!({ + "category": { + "type": "array", + "items": { "type": "string", "enum": category_slugs() }, + "description": "Restrict to these categories. Defaults to all." + }, + "root": { + "type": "array", + "items": { "type": "string" }, + "description": "Roots to operate within. Defaults to $HOME." + } + }) +} + +/// Build the full command-surface schema (raw JSON Schema, Anthropic/MCP-ready). +fn command_schema() -> Value { + json!({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "vacuum", + "description": "Fast, safe disk-space recovery for the terminal (CLI + TUI).", + "version": env!("CARGO_PKG_VERSION"), + "categories": category_slugs(), + "exit_codes": exit_codes(), + "commands": [ + { + "name": "scan", + "summary": "Report the largest disk-space consumers under each path (read-only).", + "parameters": { + "type": "object", + "additionalProperties": false, + "properties": { + "paths": { + "type": "array", + "items": { "type": "string" }, + "description": "Paths to scan. Defaults to $HOME." + }, + "limit": { + "type": "integer", + "minimum": 1, + "default": 20, + "description": "Top consumers to show per path." + } + } + }, + "examples": [ + "vacuum scan --json", + "vacuum scan ~/Downloads --limit 10 --json" + ] + }, + { + "name": "list", + "summary": "List reclaimable candidates by category (read-only).", + "parameters": { + "type": "object", + "additionalProperties": false, + "properties": selection_properties() + }, + "examples": [ + "vacuum list --json", + "vacuum list --category build-artifacts --json --fields label,bytes" + ] + }, + { + "name": "clean", + "summary": "Remove reclaimable space. Dry-run unless --apply; trash unless --purge.", + "parameters": { + "type": "object", + "additionalProperties": false, + "properties": { + "category": selection_properties()["category"].clone(), + "root": selection_properties()["root"].clone(), + "apply": { + "type": "boolean", + "default": false, + "description": "Actually act. Without it, the run is a dry run." + }, + "purge": { + "type": "boolean", + "default": false, + "description": "Delete permanently instead of moving to trash." + }, + "yes": { + "type": "boolean", + "default": false, + "description": "Skip confirmation (required for non-interactive --apply)." + } + } + }, + "examples": [ + "vacuum clean --category build-artifacts --json", + "vacuum clean --category caches --apply --yes --json" + ] + }, + { + "name": "schema", + "summary": "Emit this JSON Schema of the command surface.", + "parameters": { "type": "object", "additionalProperties": false, "properties": {} }, + "examples": [ "vacuum schema" ] + }, + { + "name": "describe", + "summary": "Emit a compact capability manifest.", + "parameters": { "type": "object", "additionalProperties": false, "properties": {} }, + "examples": [ "vacuum describe --json" ] + } + ] + }) +} + +/// Run `vacuum schema`: emit the raw JSON Schema to stdout (never enveloped, so +/// it drops straight into a function-calling `input_schema`). +pub fn run_schema() -> CliResult<()> { + let schema = command_schema(); + let rendered = if std::io::stdout().is_terminal() { + serde_json::to_string_pretty(&schema) + } else { + serde_json::to_string(&schema) + } + .map_err(|err| CliError::internal(&anyhow::Error::from(err)))?; + println!("{rendered}"); + Ok(()) +} + +/// Run `vacuum describe`: a capability manifest, enveloped like any data command. +pub fn run_describe(mode: OutputMode, command_line: &str) -> CliResult<()> { + let manifest = json!({ + "tool": "vacuum", + "summary": "Fast, safe disk-space recovery for the terminal.", + "commands": ["scan", "list", "clean", "schema", "describe", "tui"], + "categories": category_slugs(), + "safety": { + "dry_run_default": true, + "trash_default": true, + "purge_flag": "--purge", + "never_follows_symlinks": true, + "never_escalates_privileges": true + } + }); + + match mode { + OutputMode::Json | OutputMode::Jsonl => { + envelope::emit(command_line, &manifest).map_err(|err| CliError::internal(&err))?; + } + OutputMode::Human => { + println!("vacuum — fast, safe disk-space recovery for the terminal."); + println!("\nCommands: scan, list, clean, schema, describe, tui"); + println!("Categories: {}", category_slugs().join(", ")); + println!("\nSafety: dry-run by default, trash unless --purge, never follows symlinks,"); + println!("never escalates privileges. Run `vacuum schema` for the full surface."); + } + } + Ok(()) +} diff --git a/crates/vacuum-cli/src/main.rs b/crates/vacuum-cli/src/main.rs index 2215c20..0861aae 100644 --- a/crates/vacuum-cli/src/main.rs +++ b/crates/vacuum-cli/src/main.rs @@ -11,13 +11,16 @@ mod agent; mod app; mod cli; mod envelope; +mod error; +mod introspect; use std::process::ExitCode; use clap::Parser as _; use mimalloc::MiMalloc; -use crate::cli::{Cli, Command}; +use crate::cli::{Cli, Command, Format}; +use crate::error::{CliError, CliResult}; /// Microsoft Rust Guidelines M-MIMALLOC-APPS: faster allocation on hot paths. #[global_allocator] @@ -26,35 +29,46 @@ static GLOBAL: MiMalloc = MiMalloc; fn main() -> ExitCode { let cli = Cli::parse(); let command_line = std::env::args().collect::>().join(" "); + let mode = agent::output_mode(&cli.global); - match run(&cli, &command_line) { - Ok(code) => code, - Err(err) => { - eprintln!("vacuum: {err:#}"); - ExitCode::FAILURE - } + match run(&cli, mode, &command_line) { + Ok(()) => ExitCode::SUCCESS, + Err(err) => err.emit(mode, &command_line), } } -fn run(cli: &Cli, command_line: &str) -> anyhow::Result { - let mode = agent::output_mode(&cli.global); +/// Launch the interactive TUI, mapping any frontend failure to a [`CliError`]. +fn launch_tui() -> CliResult<()> { + vacuum_tui::run().map_err(|err| CliError::tui(&err)) +} + +fn run(cli: &Cli, mode: agent::OutputMode, command_line: &str) -> CliResult<()> { + // `--format explore` is an interactive request. Honor it for any data + // command — but never trap an agent in a render loop (SFRS §5): under an + // AI agent it degrades to the JSON path below with a warning. + if cli.global.format == Some(Format::Explore) { + if agent::is_agent() { + if !cli.global.quiet { + eprintln!("vacuum: --format explore is interactive; using JSON for agent use"); + } + } else { + return launch_tui(); + } + } match &cli.command { - Some(Command::Scan(args)) => app::run_scan(args, mode, command_line)?, - Some(Command::List(args)) => app::run_list(args, mode, command_line)?, - Some(Command::Clean(args)) => app::run_clean(args, mode, command_line)?, - Some(Command::Tui) => vacuum_tui::run()?, + Some(Command::Scan(args)) => app::run_scan(args, mode, &cli.global, command_line), + Some(Command::List(args)) => app::run_list(args, mode, &cli.global, command_line), + Some(Command::Clean(args)) => app::run_clean(args, mode, &cli.global, command_line), + Some(Command::Schema) => introspect::run_schema(), + Some(Command::Describe) => introspect::run_describe(mode, command_line), + Some(Command::Tui) => launch_tui(), None => { if agent::should_launch_tui(&cli.global) { - vacuum_tui::run()?; + launch_tui() } else { - eprintln!( - "vacuum: no subcommand given. Try `vacuum --help`, `vacuum scan`, or `vacuum list`." - ); - return Ok(ExitCode::from(2)); + Err(CliError::no_command()) } } } - - Ok(ExitCode::SUCCESS) } diff --git a/crates/vacuum-cli/tests/cli.rs b/crates/vacuum-cli/tests/cli.rs index 450c61c..7568c75 100644 --- a/crates/vacuum-cli/tests/cli.rs +++ b/crates/vacuum-cli/tests/cli.rs @@ -36,17 +36,82 @@ fn version_carries_attribution() { #[test] fn list_json_reports_build_artifacts() { let tmp = sample_tree(); + // Piped stdout (non-TTY) yields compact JSON — no space after the colon. Command::cargo_bin("vacuum") .unwrap() .args(["list", "--json", "--category", "build-artifacts", "--root"]) .arg(tmp.path()) .assert() .success() - .stdout(predicate::str::contains("\"tool\": \"vacuum\"")) - .stdout(predicate::str::contains( - "\"category\": \"build-artifacts\"", - )) - .stdout(predicate::str::contains("\"kind\": \"path\"")); + .stdout(predicate::str::contains("\"tool\":\"vacuum\"")) + .stdout(predicate::str::contains("\"category\":\"build-artifacts\"")) + .stdout(predicate::str::contains("\"kind\":\"path\"")); +} + +#[test] +fn list_fields_restricts_payload() { + let tmp = sample_tree(); + Command::cargo_bin("vacuum") + .unwrap() + .args([ + "list", + "--json", + "--fields", + "label,bytes", + "--category", + "build-artifacts", + "--root", + ]) + .arg(tmp.path()) + .assert() + .success() + .stdout(predicate::str::contains("\"label\":")) + // Projected away: risk/regenerable/target must not appear in records. + .stdout(predicate::str::contains("\"regenerable\":").not()) + .stdout(predicate::str::contains("\"risk\":").not()); +} + +#[test] +fn list_jsonl_streams_unenveloped_rows() { + let tmp = sample_tree(); + Command::cargo_bin("vacuum") + .unwrap() + .args([ + "list", + "--format", + "jsonl", + "--category", + "build-artifacts", + "--root", + ]) + .arg(tmp.path()) + .assert() + .success() + // One record per line, no metadata envelope wrapping the stream. + .stdout(predicate::str::contains("\"cleaner_id\":")) + .stdout(predicate::str::contains("\"metadata\"").not()); +} + +#[test] +fn schema_is_valid_json_schema() { + Command::cargo_bin("vacuum") + .unwrap() + .arg("schema") + .assert() + .success() + .stdout(predicate::str::contains("json-schema.org/draft/2020-12")) + .stdout(predicate::str::contains("\"commands\"")) + .stdout(predicate::str::contains("build-artifacts")); +} + +#[test] +fn describe_lists_capabilities() { + Command::cargo_bin("vacuum") + .unwrap() + .args(["describe", "--json"]) + .assert() + .success() + .stdout(predicate::str::contains("\"dry_run_default\":true")); } #[test] @@ -88,11 +153,41 @@ fn clean_apply_purge_removes() { } #[test] -fn unknown_category_fails() { +fn unknown_category_emits_structured_error_with_hint() { + // Usage errors exit 2 and carry a runnable hint (SFRS §4, agentic §3). Command::cargo_bin("vacuum") .unwrap() - .args(["list", "--category", "not-a-category"]) + .args(["list", "--json", "--category", "not-a-category"]) .assert() - .failure() + .code(2) + .stderr(predicate::str::contains("\"code\":\"UNKNOWN_CATEGORY\"")) + .stderr(predicate::str::contains("\"exit_code\":2")) + .stderr(predicate::str::contains("\"hint\":")) .stderr(predicate::str::contains("unknown category")); } + +#[test] +fn clean_apply_without_yes_is_refused_non_interactively() { + let tmp = sample_tree(); + // Non-interactive --apply without --yes must refuse, not act (SFRS §7). + Command::cargo_bin("vacuum") + .unwrap() + .args([ + "clean", + "--json", + "--apply", + "--category", + "build-artifacts", + "--root", + ]) + .arg(tmp.path()) + .assert() + .failure() + .stderr(predicate::str::contains( + "\"code\":\"CONFIRMATION_REQUIRED\"", + )); + assert!( + tmp.path().join("proj/target").exists(), + "a refused clean must not delete anything" + ); +} diff --git a/crates/vacuum-core/src/cleaner.rs b/crates/vacuum-core/src/cleaner.rs index fa247db..a6538fd 100644 --- a/crates/vacuum-core/src/cleaner.rs +++ b/crates/vacuum-core/src/cleaner.rs @@ -127,6 +127,9 @@ pub struct Candidate { /// A short human-readable label (typically the path or tool name). pub label: String, /// Optional extra detail (e.g. why it is safe to remove). + /// + /// Omitted from JSON output when absent (token-economy hygiene, SFRS §8). + #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option, /// Estimated bytes reclaimed; `0` when the amount cannot be measured ahead /// of time (true for some command-based cleaners). diff --git a/crates/vacuum-core/src/delete.rs b/crates/vacuum-core/src/delete.rs index 03cfa35..f65a251 100644 --- a/crates/vacuum-core/src/delete.rs +++ b/crates/vacuum-core/src/delete.rs @@ -57,6 +57,9 @@ pub struct Outcome { /// What was done, or would be done. pub action: Action, /// Optional human-readable detail (e.g. the `sudo` command to run). + /// + /// Omitted from JSON output when absent (token-economy hygiene, SFRS §8). + #[serde(skip_serializing_if = "Option::is_none")] pub note: Option, } diff --git a/doc/spacecraft.css b/doc/spacecraft.css new file mode 100644 index 0000000..516653f --- /dev/null +++ b/doc/spacecraft.css @@ -0,0 +1,76 @@ +/* SPDX-FileCopyrightText: 2026 Mohamed Hammad + SPDX-License-Identifier: GPL-3.0-or-later + + Spacecraft Software HTML theme for texi2any output. + Apply with: texi2any --html --no-split --css-include=spacecraft.css FILE.texi + Palette: Steelbore Standard §10. Typography: §11 (Share Tech Mono / Inconsolata, both OFL). + Fonts load from Google Fonts; system monospace is the offline fallback. */ + +@import url('https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;700&family=Share+Tech+Mono&display=swap'); + +:root { + --void-navy: #000027; /* background / canvas */ + --molten-amber: #D98E32; /* body text / active readout */ + --steel-blue: #4B7EB0; /* H1 / accent / visited link */ + --radium-green: #50FA7B; /* H2 / success */ + --liquid-coolant: #8BE9FD; /* H3 / info / link */ + --red-oxide: #FF5C5C; /* warning / error */ +} + +body { + background-color: var(--void-navy); + color: var(--molten-amber); + font-family: 'Inconsolata', monospace; + font-size: 16px; + line-height: 1.6; + margin: 0 auto; + max-width: 50rem; + padding: 2rem 1.5rem; +} + +h1, h2, h3, h4, h5, h6, +.settitle, .shortcontents-heading, .contents-heading { + font-family: 'Share Tech Mono', monospace; + font-weight: normal; + line-height: 1.25; +} + +h1, .titlefont, .settitle { color: var(--steel-blue); } +h2, .chapter, .unnumbered, .appendix { color: var(--steel-blue); } +h3, .section { color: var(--radium-green); } +h4, h5, h6, .subsection, .subsubsection { color: var(--liquid-coolant); } + +a:link { color: var(--liquid-coolant); } +a:visited { color: var(--steel-blue); } +a:hover { color: var(--radium-green); } + +code, samp, kbd, tt, pre, .verbatim, +.example, .smallexample, .lisp { + font-family: 'Inconsolata', monospace; + color: var(--liquid-coolant); +} + +pre.example, pre.verbatim, pre.smallexample, pre.lisp, pre.display { + background-color: rgba(75, 126, 176, 0.12); /* steel-blue wash */ + border-left: 3px solid var(--steel-blue); + border-radius: 4px; + padding: 0.75rem 1rem; + overflow-x: auto; +} + +blockquote, .quotation { + border-left: 3px solid var(--molten-amber); + margin-left: 0; + padding-left: 1rem; + color: var(--molten-amber); +} + +table { border-collapse: collapse; } +th, td { border: 1px solid var(--steel-blue); padding: 0.35rem 0.6rem; } +th { color: var(--radium-green); font-family: 'Share Tech Mono', monospace; } + +/* Definition commands (@deffn etc.) */ +dt { color: var(--radium-green); } +dfn, var { color: var(--molten-amber); font-style: italic; } + +hr { border: none; border-top: 1px solid var(--steel-blue); } diff --git a/doc/vacuum.texi b/doc/vacuum.texi index 5619a41..7c74840 100644 --- a/doc/vacuum.texi +++ b/doc/vacuum.texi @@ -1,23 +1,31 @@ \input texinfo @c -*-texinfo-*- @c SPDX-FileCopyrightText: 2026 Mohamed Hammad -@c SPDX-License-Identifier: GPL-3.0-or-later +@c SPDX-License-Identifier: CC-BY-SA-4.0 @c %**start of header @setfilename vacuum.info @documentencoding UTF-8 -@settitle Vacuum Manual +@documentlanguage en +@settitle Vacuum Manual 0.1.0 @c %**end of header @set VERSION 0.1.0 +@set UPDATED 2026-06-21 @copying -This manual is for Vacuum (version @value{VERSION}), a fast, safe disk-space -recovery tool for the terminal. +This manual is for Vacuum (version @value{VERSION}, updated @value{UPDATED}), a +fast, safe disk-space recovery tool for the terminal, part of the Spacecraft +Software ecosystem. -Copyright @copyright{} 2026 Mohamed Hammad & Spacecraft Software. +Copyright @copyright{} 2026 Mohamed Hammad and Spacecraft Software. + +Maintained by Mohamed Hammad (Mohamed.Hammad @@ SpacecraftSoftware.org), +@uref{https://Vacuum.SpacecraftSoftware.org/}. @quotation Permission is granted to copy, distribute and/or modify this document under the -terms of the Creative Commons Attribution-ShareAlike 4.0 International License. +terms of the Creative Commons Attribution-ShareAlike 4.0 International License +(CC-BY-SA-4.0). A copy of the license is included in the source distribution +under @file{LICENSES/}. @end quotation @end copying @@ -28,8 +36,10 @@ terms of the Creative Commons Attribution-ShareAlike 4.0 International License. @titlepage @title Vacuum Manual +@subtitle Fast, safe disk-space recovery for the terminal @subtitle For Vacuum version @value{VERSION} @author Mohamed Hammad +@author @email{Mohamed.Hammad@@SpacecraftSoftware.org} @page @vskip 0pt plus 1filll @insertcopying @@ -45,11 +55,15 @@ terms of the Creative Commons Attribution-ShareAlike 4.0 International License. @end ifnottex @menu -* Overview:: What Vacuum does. -* Invocation:: Commands and options. -* Cleaner Categories:: What Vacuum reclaims. -* Safety Model:: How Vacuum avoids data loss. -* Attribution:: Maintainer and license. +* Overview:: What Vacuum does. +* Invocation:: Commands and global options. +* Output Modes:: Human text, JSON envelope, JSONL, and field selection. +* Exit Codes:: The canonical exit-code map. +* Errors and Hints:: Structured errors with runnable next-step hints. +* Cleaner Categories:: What Vacuum reclaims. +* Safety Model:: How Vacuum avoids data loss. +* Agent Integration:: Driving Vacuum from an AI agent or pipeline. +* Attribution:: Maintainer and license. @end menu @node Overview @@ -57,22 +71,37 @@ terms of the Creative Commons Attribution-ShareAlike 4.0 International License. Vacuum scans disk usage in parallel, groups the reclaimable space into clear categories, and lets you delete what you choose. It is a command-line tool with -an interactive terminal user interface (TUI). +an interactive terminal user interface (TUI), built to be equally comfortable +for a human at a prompt and for an AI agent driving it over a pipe. Run with no arguments in a terminal to launch the TUI; otherwise use the -@command{scan}, @command{list}, and @command{clean} subcommands. +@command{scan}, @command{list}, and @command{clean} subcommands. Two further +subcommands, @command{schema} and @command{describe}, let a program discover the +command surface without parsing help text. + +Vacuum is conservative by default: it never removes anything without an explicit +@option{--apply}, it routes deletions to the trash unless you ask to purge, and +it refuses to touch protected system paths. @xref{Safety Model}. @node Invocation @chapter Invocation +@menu +* Subcommands:: scan, list, clean, schema, describe, tui. +* Global Options:: Flags accepted by every subcommand. +@end menu + +@node Subcommands +@section Subcommands + @table @code @item vacuum Launch the interactive TUI (when standard output is a terminal and no AI agent -is detected). +is detected). Equivalent to @command{vacuum tui}. @item vacuum scan [@var{paths}@dots{}] [--limit @var{n}] Report the largest consumers under each path (default: your home directory), -largest first. Equivalent to @samp{du --max-depth=1 | sort -rh}. +largest first. Equivalent in spirit to @samp{du --max-depth=1 | sort -rh}. @item vacuum list [--category @var{cat}@dots{}] [--root @var{path}@dots{}] List reclaimable candidates by category. Read-only. @@ -80,12 +109,153 @@ List reclaimable candidates by category. Read-only. @item vacuum clean [--category @var{cat}@dots{}] [--root @var{path}@dots{}] [--apply] [--purge] [--yes] Remove reclaimable space. Without @option{--apply} this is a dry run. Deletions go to the trash unless @option{--purge} is given. Use @option{--yes} -to skip the confirmation prompt (required for non-interactive use). +(alias @option{--force}) to skip the confirmation prompt; this is required for +non-interactive use. @xref{Safety Model}. + +@item vacuum schema +Emit a JSON Schema (Draft 2020-12) of the whole command surface on standard +output. The per-command @code{parameters} objects drop directly into the +function-calling APIs of the major LLM providers. @xref{Agent Integration}. + +@item vacuum describe +Emit a compact capability manifest: the command list, category slugs, and the +safety defaults. Honors @option{--json}. + +@item vacuum tui +Launch the interactive TUI explicitly. @end table -Global options: @option{--json} (or @option{--format json}) emits a -machine-readable envelope with ISO@tie{}8601 UTC timestamps; @option{--color} -and @option{--no-color} control color. +@node Global Options +@section Global Options + +These flags are accepted by every subcommand. + +@table @option +@item --json +Emit the machine-readable JSON envelope. Shorthand for @option{--format json}. + +@item --format @var{fmt} +Select the output format: @code{human}, @code{json}, @code{jsonl}, or +@code{explore} (the interactive TUI). @xref{Output Modes}. + +@item --fields @var{f1,f2,@dots{}} +Restrict JSON records to the named fields, reducing payload size for +token-billed agents. @xref{Output Modes}. + +@item --color @var{when} +@itemx --no-color +Control ANSI color: @code{auto}, @code{always}, or @code{never}. @option{--no-color} +is equivalent to @option{--color never}. + +@item --verbose +@itemx -v +Emit diagnostic detail to standard error. + +@item --quiet +@itemx -q +Suppress non-error standard-error output, such as per-item skip warnings. +@end table + +Timestamps in JSON output are always ISO@tie{}8601 UTC with a mandatory @code{Z} +suffix (Standard @t{§14}); local-time rendering never appears in machine output. + +@node Output Modes +@chapter Output Modes + +Vacuum renders the same data two ways. It chooses automatically, but you can +force the choice with @option{--format} or @option{--json}. + +@table @asis +@item Detection cascade +An explicit @option{--format}/@option{--json} flag always wins. Otherwise, if an +AI-agent or CI environment variable is set (@pxref{Agent Integration}), or +standard output is not a terminal, Vacuum emits JSON; an interactive terminal +gets human-readable text. + +@item The JSON envelope +Every @option{--json} response is a single document of the form: + +@verbatim +{ + "metadata": { + "tool": "vacuum", + "version": "0.1.0", + "command": "vacuum list --json", + "timestamp": "2026-06-21T14:30:00Z", + "maintainer": "Mohamed Hammad ", + "website": "https://Vacuum.SpacecraftSoftware.org/" + }, + "data": { "categories": [ ... ], "total_bytes": 0 } +} +@end verbatim + +Property names are @code{snake_case}; numbers are JSON numbers; absent optional +fields are omitted rather than emitted as @code{null}. Output is pretty-printed +only when standard output is a terminal; piped consumers receive compact JSON. + +@item JSONL streaming +@option{--format jsonl} emits one JSON record per line with no enclosing +envelope, so a consumer can process records as they arrive. For @command{list} +the rows are candidates; for @command{scan}, usage entries; for @command{clean}, +outcomes. + +@item Field selection +@option{--fields label,bytes} projects each JSON record down to the named keys. +This is the primary lever for trimming token cost when an agent needs only part +of each record. +@end table + +@node Exit Codes +@chapter Exit Codes + +Vacuum follows the Spacecraft Software canonical exit-code map, so a calling +program can branch on the status without parsing output. + +@table @code +@item 0 +Success. +@item 1 +General failure (for example, a deletion or external command failed). +@item 2 +Usage error: bad arguments. Fix the invocation; do not retry verbatim. +@item 3 +Resource not found. +@item 4 +Permission denied, or an action refused by a safety guard (outside the allowed +roots, a protected system path, or a symlink). +@item 5 +Conflict (already exists). +@item 127 +A required external tool is not installed. +@end table + +In any machine-readable mode, a non-zero exit is always accompanied by a +structured error object on standard error. @xref{Errors and Hints}. + +@node Errors and Hints +@chapter Errors and Hints + +In JSON mode, failures are emitted to standard error as a single object so an +agent never has to parse a prose sentence: + +@verbatim +{ + "error": { + "code": "UNKNOWN_CATEGORY", + "exit_code": 2, + "message": "unknown category: not-a-category", + "hint": "vacuum schema --json | jaq '.commands[] | select(.name==\"list\") | .categories'", + "timestamp": "2026-06-21T14:30:00Z", + "command": "vacuum list --category not-a-category", + "docs_url": "https://Vacuum.SpacecraftSoftware.org/" + } +} +@end verbatim + +The @code{hint} field is a @emph{runnable command}, not advice in prose: an agent +can execute it directly to recover. In human mode the same failure renders as a +short @samp{vacuum: @dots{}} line followed by a @samp{hint: @dots{}} line. +Standard output is never written on the error path. @node Cleaner Categories @chapter Cleaner Categories @@ -116,6 +286,8 @@ Vacuum is conservative by design: @itemize @bullet @item Dry run by default; nothing is removed without @option{--apply}. @item Path removals go to the XDG trash unless @option{--purge} is given. +@item A real @option{--apply} run refuses to act non-interactively unless +@option{--yes} (alias @option{--force}) is supplied; interactively it prompts. @item Operation is bounded to your home directory plus any paths you name; protected system locations are refused. @item Symlinks are never followed when deleting, and source files are never @@ -124,14 +296,40 @@ removed. command is reported for you to run. @end itemize +@node Agent Integration +@chapter Agent Integration + +Vacuum is designed to be driven by an AI agent or an automation pipeline as +readily as by a person. + +@table @asis +@item Environment detection +When any of @env{AI_AGENT}, @env{AGENT}, or @env{CI} is set to a non-empty +value, Vacuum suppresses the TUI, defaults to JSON, and disables color. The +informational variables @env{CLAUDECODE}, @env{CURSOR_AGENT}, and +@env{GEMINI_CLI} are recognized but do not by themselves change the output +format. + +@item Function-calling schema +@command{vacuum schema} emits a JSON Schema whose per-command @code{parameters} +objects are valid Anthropic @code{input_schema} / MCP @code{inputSchema} +payloads. An agent can fetch the schema once and call the tool without guessing +flag names. + +@item Token economy +Use @option{--fields} to trim each record to the keys you need, and +@option{--format jsonl} to stream large result sets. Optional fields are omitted +when absent, and piped output is compact. +@end table + @node Attribution @chapter Attribution Maintained by Mohamed Hammad (@email{Mohamed.Hammad@@SpacecraftSoftware.org}). -Copyright @copyright{} 2026 Mohamed Hammad & Spacecraft Software. -License: GPL-3.0-or-later. -@uref{https://Vacuum.SpacecraftSoftware.org/} +Copyright @copyright{} 2026 Mohamed Hammad and Spacecraft Software. +Manual licensed under CC-BY-SA-4.0; the Vacuum software is licensed under +GPL-3.0-or-later. @uref{https://Vacuum.SpacecraftSoftware.org/} @bye